ib.c 60.7 KB
Newer Older
Dries Kimpe's avatar
Dries Kimpe committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
/*
 * InfiniBand BMI method.
 *
 * Copyright (C) 2003-6 Pete Wyckoff <pw@osc.edu>
 * Copyright (C) 2006 Kyle Schochenmaier <kschoche@scl.ameslab.gov>
 *
 * See COPYING in top-level directory.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <arpa/inet.h>   /* inet_ntoa */
#include <netdb.h>       /* gethostbyname */
#include <sys/poll.h>
#define __PINT_REQPROTO_ENCODE_FUNCS_C  /* include definitions */
#include <src/common/id-generator/id-generator.h>
#include <src/io/bmi/bmi-method-support.h>   /* bmi_method_ops ... */
#include <src/io/bmi/bmi-method-callback.h>  /* bmi_method_addr_reg_callback */
#include <src/common/gen-locks/gen-locks.h>  /* gen_mutex_t ... */
#include <src/common/misc/pvfs2-internal.h>
#include "pint-hint.h"

#ifdef HAVE_VALGRIND_H
#include <memcheck.h>
#else
#define VALGRIND_MAKE_MEM_DEFINED(addr,len)
#endif

#include "ib.h"

static gen_mutex_t interface_mutex = GEN_MUTEX_INITIALIZER;

/*
 * Handle given by upper layer, which must be handed back to create
 * method_addrs.
 */
static int bmi_ib_method_id;

/* alloc space for the single device structure pointer; one for
 * vapi and one for openib */
ib_device_t *ib_device __hidden = NULL;

/* these all vector through the ib_device */
#define new_connection ib_device->func.new_connection
#define close_connection ib_device->func.close_connection
#define drain_qp ib_device->func.drain_qp
#define ib_initialize ib_device->func.ib_initialize
#define ib_finalize ib_device->func.ib_finalize
#define post_sr ib_device->func.post_sr
#define post_sr_rdmaw ib_device->func.post_sr_rdmaw
#define check_cq ib_device->func.check_cq
#define prepare_cq_block ib_device->func.prepare_cq_block
#define ack_cq_completion_event ib_device->func.ack_cq_completion_event
#define wc_status_string ib_device->func.wc_status_string
#define mem_register ib_device->func.mem_register
#define mem_deregister ib_device->func.mem_deregister
#define check_async_events ib_device->func.check_async_events

#if MEMCACHE_EARLY_REG
#if MEMCACHE_BOUNCEBUF
#error Not sensible to use bouncebuf with early reg.  First use of bouncebuf \
  will register it, thus no effect whether early reg or not.
#endif
#endif

#if MEMCACHE_BOUNCEBUF
static ib_buflist_t reg_send_buflist = { .num = 0 };
static ib_buflist_t reg_recv_buflist = { .num = 0 };
static void *reg_send_buflist_buf;
static void *reg_recv_buflist_buf;
static const bmi_size_t reg_send_buflist_len = 256 * 1024;
static const bmi_size_t reg_recv_buflist_len = 256 * 1024;
#endif

static void encourage_send_incoming_cts(struct buf_head *bh, u_int32_t byte_len);
static void encourage_recv_incoming(struct buf_head *bh, msg_type_t type,
                                    u_int32_t byte_len);
static void encourage_rts_done_waiting_buffer(struct ib_work *sq);
static int send_cts(struct ib_work *rq);
static void ib_close_connection(ib_connection_t *c);
static int ib_tcp_client_connect(ib_method_addr_t *ibmap,
                                 struct bmi_method_addr *remote_map);
static int ib_tcp_server_check_new_connections(void);
static int ib_block_for_activity(int timeout_ms);

/*
 * Return string form of work completion opcode field.
 */
static const char *wc_opcode_string(int opcode)
{
    if (opcode == BMI_IB_OP_SEND)
	return "SEND";
    else if (opcode == BMI_IB_OP_RECV)
	return "RECV";
    else if (opcode == BMI_IB_OP_RDMA_WRITE)
	return "RDMA WRITE";
    else
	return "(UNKNOWN)";
}

/*
 * Wander through single completion queue, pulling off messages and
 * sticking them on the proper connection queues.  Later you can
 * walk the incomingq looking for things to do to them.  Returns
 * number of new things that arrived.
 */
static int ib_check_cq(void)
{
    int ret = 0;

    for (;;) {
	struct bmi_ib_wc wc;
	int vret;

	vret = check_cq(&wc);
	if (vret == 0)
	    break;  /* empty */

	debug(4, "%s: found something", __func__);
	++ret;
	if (wc.status != 0) {
	    /* opcode is not necessarily valid; only wr_id, status, qp_num,
	     * and vendor_err can be relied upon */
	    if (wc.opcode == BMI_IB_OP_SEND) {
		debug(0, "%s: entry id 0x%llx SEND error %s", __func__,
		  llu(wc.id), wc_status_string(wc.status));
		if (wc.id) {
		    ib_connection_t *c = ptr_from_int64(wc.id);
		    if (c->cancelled) {
			debug(0,
			  "%s: ignoring send error on cancelled conn to %s",
			  __func__, c->peername);
		    }
		}
	    } else {
		error("%s: entry id 0x%llx opcode %s error %s", __func__,
		  llu(wc.id), wc_opcode_string(wc.opcode),
		  wc_status_string(wc.status));
	    }
	}

	if (wc.opcode == BMI_IB_OP_RECV) {
	    /*
	     * Remote side did a send to us.
	     */
	    msg_header_common_t mh_common;
	    struct buf_head *bh = ptr_from_int64(wc.id);
	    char *ptr = bh->buf;
	    u_int32_t byte_len = wc.byte_len;

	    VALGRIND_MAKE_MEM_DEFINED(ptr, byte_len);
	    decode_msg_header_common_t(&ptr, &mh_common);
	    bh->c->send_credit += mh_common.credit;

	    debug(2, "%s: recv from %s len %d type %s credit %d",
		  __func__, bh->c->peername, byte_len,
		  msg_type_name(mh_common.type), mh_common.credit);
	    if (mh_common.type == MSG_CTS) {
		/* incoming CTS messages go to the send engine */
		encourage_send_incoming_cts(bh, byte_len);
	    } else {
		/* something for the recv side, no known rq yet */
		encourage_recv_incoming(bh, mh_common.type, byte_len);
	    }

	} else if (wc.opcode == BMI_IB_OP_RDMA_WRITE) {

	    /* completion event for the rdma write we initiated, used
	     * to signal memory unpin etc. */
	    struct ib_work *sq = ptr_from_int64(wc.id);

	    debug(3, "%s: sq %p %s", __func__, sq,
	          sq_state_name(sq->state.send));

	    bmi_ib_assert(sq->state.send == SQ_WAITING_DATA_SEND_COMPLETION,
			  "%s: wrong send state %s", __func__,
			  sq_state_name(sq->state.send));

	    sq->state.send = SQ_WAITING_RTS_DONE_BUFFER;

#if !MEMCACHE_BOUNCEBUF
	    memcache_deregister(ib_device->memcache, &sq->buflist);
#endif
	    debug(2, "%s: sq %p RDMA write done, now %s", __func__, sq,
	          sq_state_name(sq->state.send));

	    encourage_rts_done_waiting_buffer(sq);

	} else if (wc.opcode == BMI_IB_OP_SEND) {

	    struct buf_head *bh = ptr_from_int64(wc.id);
	    struct ib_work *sq = bh->sq;

	    if (sq == NULL) {
		/* MSG_BYE or MSG_CREDIT */
		debug(2, "%s: MSG_BYE or MSG_CREDIT completed locally",
		      __func__);
	    } else if (sq->type == BMI_SEND) {
		sq_state_t state = sq->state.send;

		if (state == SQ_WAITING_EAGER_SEND_COMPLETION)
		    sq->state.send = SQ_WAITING_USER_TEST;
		else if (state == SQ_WAITING_RTS_SEND_COMPLETION)
		    sq->state.send = SQ_WAITING_CTS;
		else if (state == SQ_WAITING_RTS_SEND_COMPLETION_GOT_CTS)
		    sq->state.send = SQ_WAITING_DATA_SEND_COMPLETION;
		else if (state == SQ_WAITING_RTS_DONE_SEND_COMPLETION)
		    sq->state.send = SQ_WAITING_USER_TEST;
		else if (state == SQ_CANCELLED)
		    ;
		else
		    bmi_ib_assert(0, "%s: unknown send state %s (%d) of sq %p",
				  __func__, sq_state_name(sq->state.send),
				  sq->state.send, sq);
		debug(2, "%s: send to %s completed locally: sq %p -> %s",
		      __func__, bh->c->peername, sq,
		      sq_state_name(sq->state.send));

	    } else {
		struct ib_work *rq = sq;  /* rename */
		rq_state_t state = rq->state.recv;
		
227 228
		if (state & RQ_RTS_WAITING_CTS_SEND_COMPLETION)
		    rq->state.recv &= ~RQ_RTS_WAITING_CTS_SEND_COMPLETION;
Dries Kimpe's avatar
Dries Kimpe committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
		else if (state == RQ_CANCELLED)
		    ;
		else
		    bmi_ib_assert(0, "%s: unknown recv state %s of rq %p",
				  __func__, rq_state_name(rq->state.recv), rq);
		debug(2, "%s: send to %s completed locally: rq %p -> %s",
		      __func__, bh->c->peername, rq,
		      rq_state_name(rq->state.recv));
	    }

	    qlist_add_tail(&bh->list, &bh->c->eager_send_buf_free);

	} else {
	    error("%s: cq entry id 0x%llx opcode %d unexpected", __func__,
	      llu(wc.id), wc.opcode);
	}
    }
    return ret;
}

/*
 * Initialize common header of all messages.
 */
static void msg_header_init(msg_header_common_t *mh_common,
                            ib_connection_t *c, msg_type_t type)
{
    mh_common->type = type;
    mh_common->credit = c->return_credit;
    c->return_credit = 0;
}

/*
 * Grab an empty buf head, if available.
 */
static struct buf_head *get_eager_buf(ib_connection_t *c)
{
    struct buf_head *bh = NULL;

    if (c->send_credit > 0) {
	--c->send_credit;
	bh = qlist_try_del_head(&c->eager_send_buf_free);
	bmi_ib_assert(bh, "%s: empty eager_send_buf_free list, peer %s",
		      __func__, c->peername);
    }
    return bh;
}

/*
 * Re-post a receive buffer, possibly returning credit to the peer.
 */
static void post_rr(ib_connection_t *c, struct buf_head *bh)
{
    ib_device->func.post_rr(c, bh);
    ++c->return_credit;

    /* if credits are building up, explicitly send them over */
    if (c->return_credit > ib_device->eager_buf_num - 4) {
	msg_header_common_t mh_common;
	char *ptr;

	/* one credit saved back for just this situation, do not check */
	--c->send_credit;
	bh = qlist_try_del_head(&c->eager_send_buf_free);
	bmi_ib_assert(bh, "%s: empty eager_send_buf_free list", __func__);
	bh->sq = NULL;
	debug(2, "%s: return %d credits to %s", __func__, c->return_credit,
	      c->peername);
	msg_header_init(&mh_common, c, MSG_CREDIT);
	ptr = bh->buf;
	encode_msg_header_common_t(&ptr, &mh_common);
	post_sr(bh, sizeof(mh_common));
    }
}

/*
 * Push a send message along its next step.  Called internally only.
 */
static void encourage_send_waiting_buffer(struct ib_work *sq)
{
    struct buf_head *bh;
    ib_connection_t *c = sq->c;

    debug(3, "%s: sq %p", __func__, sq);
    bmi_ib_assert(sq->state.send == SQ_WAITING_BUFFER,
		  "%s: wrong send state %s", __func__,
		  sq_state_name(sq->state.send));

    bh = get_eager_buf(c);
    if (!bh) {
	debug(2, "%s: sq %p no free send buffers to %s", __func__,
	      sq, c->peername);
	return;
    }
    sq->bh = bh;
    bh->sq = sq;  /* uplink for completion */

    if (sq->buflist.tot_len <= ib_device->eager_buf_payload) {
	/*
	 * Eager send.
	 */
	msg_header_eager_t mh_eager;
	char *ptr = bh->buf;

	msg_header_init(&mh_eager.c, c, sq->is_unexpected
	                ? MSG_EAGER_SENDUNEXPECTED : MSG_EAGER_SEND);
	mh_eager.bmi_tag = sq->bmi_tag;
        mh_eager.class = 0;
        if(sq->is_unexpected)
            mh_eager.class += sq->class;
	encode_msg_header_eager_t(&ptr, &mh_eager);

	memcpy_from_buflist(&sq->buflist,
	                    (msg_header_eager_t *) bh->buf + 1);

	/* send the message */
	post_sr(bh, (u_int32_t) (sizeof(mh_eager) + sq->buflist.tot_len));

	/* wait for ack saying remote has received and recycled his buf */
	sq->state.send = SQ_WAITING_EAGER_SEND_COMPLETION;
	debug(2, "%s: sq %p sent EAGER len %lld", __func__, sq,
	      lld(sq->buflist.tot_len));

    } else {
	/*
	 * Request to send, rendez-vous.  Include the mop id in the message
	 * which will be returned to us in the CTS so we can look it up.
	 */
	msg_header_rts_t mh_rts;
	char *ptr = bh->buf;

	msg_header_init(&mh_rts.c, c, MSG_RTS);
	mh_rts.bmi_tag = sq->bmi_tag;
	mh_rts.mop_id = sq->mop->op_id;
	mh_rts.tot_len = sq->buflist.tot_len;

	encode_msg_header_rts_t(&ptr, &mh_rts);

	post_sr(bh, sizeof(mh_rts));

#if MEMCACHE_EARLY_REG
	/* XXX: need to lock against receiver thread?  Could poll return
	 * the CTS and start the data send before this completes? */
	memcache_register(ib_device->memcache, &sq->buflist);
#endif

	sq->state.send = SQ_WAITING_RTS_SEND_COMPLETION;
	debug(2, "%s: sq %p sent RTS mopid %llx len %lld", __func__, sq,
	      llu(sq->mop->op_id), lld(sq->buflist.tot_len));
    }
}

/*
 * Look at the incoming message which is a response to an earlier RTS
 * from us, and start the real data send.
 */
static void
encourage_send_incoming_cts(struct buf_head *bh, u_int32_t byte_len)
{
    msg_header_cts_t mh_cts;
    struct ib_work *sq, *sqt;
    u_int32_t want;
    char *ptr = bh->buf;

    decode_msg_header_cts_t(&ptr, &mh_cts);

    /*
     * Look through this CTS message to determine the owning sq.  Works
     * using the mop_id which was sent during the RTS, now returned to us.
     */
    sq = 0;
    qlist_for_each_entry(sqt, &ib_device->sendq, list) {
	debug(8, "%s: looking for op_id 0x%llx, consider 0x%llx", __func__,
	  llu(mh_cts.rts_mop_id), llu(sqt->mop->op_id));
	if (sqt->c == bh->c
	    && sqt->mop->op_id == (bmi_op_id_t) mh_cts.rts_mop_id) {
	    sq = sqt;
	    break;
	}
    }
    if (!sq)
	error("%s: mop_id %llx in CTS message not found", __func__,
	  llu(mh_cts.rts_mop_id));

    debug(2, "%s: sq %p %s mopid %llx len %u", __func__, sq,
          sq_state_name(sq->state.send), llu(mh_cts.rts_mop_id), byte_len);
    bmi_ib_assert(sq->state.send == SQ_WAITING_CTS ||
		  sq->state.send == SQ_WAITING_RTS_SEND_COMPLETION,
		  "%s: wrong send state %s", __func__,
		  sq_state_name(sq->state.send));

    /* message; cts content; list of buffers, lengths, and keys */
    want = sizeof(mh_cts)
         + mh_cts.buflist_num * MSG_HEADER_CTS_BUFLIST_ENTRY_SIZE;
    if (bmi_ib_unlikely(byte_len != want))
	error("%s: wrong message size for CTS, got %u, want %u", __func__,
              byte_len, want);

    /* start the big tranfser */
    post_sr_rdmaw(sq, &mh_cts, (msg_header_cts_t *) bh->buf + 1);

    /* re-post our recv buf now that we have all the information from CTS */
    post_rr(sq->c, bh);

    if (sq->state.send == SQ_WAITING_CTS)
	sq->state.send = SQ_WAITING_DATA_SEND_COMPLETION;
    else
	sq->state.send = SQ_WAITING_RTS_SEND_COMPLETION_GOT_CTS;
    debug(3, "%s: sq %p now %s", __func__, sq, sq_state_name(sq->state.send));
}


/*
 * See if anything was preposted that matches this.
 */
static struct ib_work *
find_matching_recv(rq_state_t statemask, const ib_connection_t *c,
  bmi_msg_tag_t bmi_tag)
{
    struct ib_work *rq;

    qlist_for_each_entry(rq, &ib_device->recvq, list) {
	if ((rq->state.recv & statemask) && rq->c == c
	    && rq->bmi_tag == bmi_tag)
	    return rq;
    }
    return NULL;
}

/*
 * Init a new recvq entry from something that arrived on the wire.
 */
static struct ib_work *
alloc_new_recv(ib_connection_t *c, struct buf_head *bh)
{
    struct ib_work *rq = bmi_ib_malloc(sizeof(*rq));
    rq->type = BMI_RECV;
    rq->c = c;
    ++rq->c->refcnt;
    rq->bh = bh;
    rq->mop = 0;  /* until user posts for it */
    rq->rts_mop_id = 0;
    qlist_add_tail(&rq->list, &ib_device->recvq);
    return rq;
}

/*
 * Called from incoming message processing, except for the case
 * of ack to a CTS, for which we know the rq (see below).
 *
 * Unexpected receive, either no post or explicit sendunexpected.
 */
static void
encourage_recv_incoming(struct buf_head *bh, msg_type_t type, u_int32_t byte_len)
{
    ib_connection_t *c = bh->c;
    struct ib_work *rq;
    char *ptr = bh->buf;

    debug(4, "%s: incoming msg type %s", __func__, msg_type_name(type));

    if (type == MSG_EAGER_SEND) {

	msg_header_eager_t mh_eager;

	ptr = bh->buf;
	decode_msg_header_eager_t(&ptr, &mh_eager);

	debug(2, "%s: recv eager len %u", __func__, byte_len);

	rq = find_matching_recv(RQ_WAITING_INCOMING, c, mh_eager.bmi_tag);
	if (rq) {
	    bmi_size_t len = byte_len - sizeof(mh_eager);
	    if (len > rq->buflist.tot_len)
		error("%s: EAGER received %lld too small for buffer %lld",
		  __func__, lld(len), lld(rq->buflist.tot_len));

	    memcpy_to_buflist(&rq->buflist,
	                      (msg_header_eager_t *) bh->buf + 1,
			      len);

	    /* re-post */
	    post_rr(c, bh);

	    rq->state.recv = RQ_EAGER_WAITING_USER_TEST;
	    debug(2, "%s: matched rq %p now %s", __func__, rq,
	      rq_state_name(rq->state.recv));
#if MEMCACHE_EARLY_REG
	    /* if a big receive was posted but only a small message came
	     * through, unregister it now */
	    if (rq->buflist.tot_len > ib_device->eager_buf_payload) {
		debug(2, "%s: early registration not needed, dereg after eager",
		  __func__);
		memcache_deregister(ib_device->memcache, &rq->buflist);
	    }
#endif

	} else {
	    rq = alloc_new_recv(c, bh);
	    /* return value for when user does post_recv for this one */
	    rq->bmi_tag = mh_eager.bmi_tag;
	    rq->state.recv = RQ_EAGER_WAITING_USER_POST;
	    /* do not repost or ack, keeping bh until user test */
	    debug(2, "%s: new rq %p now %s", __func__, rq,
	      rq_state_name(rq->state.recv));
	}
	rq->actual_len = byte_len - sizeof(mh_eager);

    } else if (type == MSG_EAGER_SENDUNEXPECTED) {

	msg_header_eager_t mh_eager;

	ptr = bh->buf;
	decode_msg_header_eager_t(&ptr, &mh_eager);

	debug(2, "%s: recv eager unexpected len %u", __func__, byte_len);

	rq = alloc_new_recv(c, bh);
	/* return values for when user does testunexpected for this one */
	rq->bmi_tag = mh_eager.bmi_tag;
	rq->state.recv = RQ_EAGER_WAITING_USER_TESTUNEXPECTED;
	rq->actual_len = byte_len - sizeof(mh_eager);
	/* do not repost, keeping bh until user test */
	debug(2, "%s: new rq %p now %s", __func__, rq,
	  rq_state_name(rq->state.recv));

    } else if (type == MSG_RTS) {
	/*
	 * Sender wants to send a big message, initiates rts/cts protocol.
	 * Has the user posted a matching receive for it yet?
	 */
	msg_header_rts_t mh_rts;

	ptr = bh->buf;
	decode_msg_header_rts_t(&ptr, &mh_rts);

	debug(2, "%s: recv RTS len %lld mopid %llx", __func__,
	      lld(mh_rts.tot_len), llu(mh_rts.mop_id));

	rq = find_matching_recv(RQ_WAITING_INCOMING, c, mh_rts.bmi_tag);
	if (rq) {
	    if ((int)mh_rts.tot_len > rq->buflist.tot_len) {
		error("%s: RTS received %llu too small for buffer %llu",
		  __func__, llu(mh_rts.tot_len), llu(rq->buflist.tot_len));
	    }
	    rq->state.recv = RQ_RTS_WAITING_CTS_BUFFER;
	    debug(2, "%s: matched rq %p MSG_RTS now %s", __func__, rq,
	      rq_state_name(rq->state.recv));
	} else {
	    rq = alloc_new_recv(c, bh);
	    /* return value for when user does post_recv for this one */
	    rq->bmi_tag = mh_rts.bmi_tag;
	    rq->state.recv = RQ_RTS_WAITING_USER_POST;
	    debug(2, "%s: new rq %p MSG_RTS now %s", __func__, rq,
	      rq_state_name(rq->state.recv));
	}
	rq->actual_len = mh_rts.tot_len;
	rq->rts_mop_id = mh_rts.mop_id;

	post_rr(c, bh);

	if (rq->state.recv == RQ_RTS_WAITING_CTS_BUFFER) {
	    int ret;
	    ret = send_cts(rq);
592 593 594 595 596
	    if (ret == 0) {
		rq->state.recv = RQ_RTS_WAITING_RTS_DONE |
                    RQ_RTS_WAITING_CTS_SEND_COMPLETION |
                    RQ_RTS_WAITING_USER_TEST;
            }
Dries Kimpe's avatar
Dries Kimpe committed
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
	    /* else keep waiting until we can send that cts */
	}

    } else if (type == MSG_RTS_DONE) {

	msg_header_rts_done_t mh_rts_done;
	struct ib_work *rqt;

	ptr = bh->buf;
	decode_msg_header_rts_done_t(&ptr, &mh_rts_done);

	debug(2, "%s: recv RTS_DONE mop_id %llx", __func__,
	      llu(mh_rts_done.mop_id));

	rq = NULL;
	qlist_for_each_entry(rqt, &ib_device->recvq, list) {
	    if (rqt->c == c && rqt->rts_mop_id == mh_rts_done.mop_id &&
614
		rqt->state.recv & RQ_RTS_WAITING_RTS_DONE) {
Dries Kimpe's avatar
Dries Kimpe committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
		rq = rqt;
		break;
	    }
	}

	bmi_ib_assert(rq, "%s: mop_id %llx in RTS_DONE message not found",
		      __func__, llu(mh_rts_done.mop_id));

#if MEMCACHE_BOUNCEBUF
	memcpy_to_buflist(&rq->buflist, reg_recv_buflist_buf,
	                  rq->buflist.tot_len);
#else
	memcache_deregister(ib_device->memcache, &rq->buflist);
#endif

	post_rr(c, bh);

632
        rq->state.recv &= ~RQ_RTS_WAITING_RTS_DONE;
Dries Kimpe's avatar
Dries Kimpe committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

    } else if (type == MSG_BYE) {
	/*
	 * Other side requests connection close.  Do it.
	 */
	debug(2, "%s: recv BYE", __func__);
	post_rr(c, bh);
	ib_close_connection(c);

    } else if (type == MSG_CREDIT) {

	/* already added the credit in check_cq */
	debug(2, "%s: recv CREDIT", __func__);
	post_rr(c, bh);

    } else {
	error("%s: unknown message header type %d len %u", __func__,
	      type, byte_len);
    }
}

/*
 * We finished the RDMA write.  Send him a done message.
 */
static void encourage_rts_done_waiting_buffer(struct ib_work *sq)
{
    ib_connection_t *c = sq->c;
    struct buf_head *bh;
    char *ptr;
    msg_header_rts_done_t mh_rts_done;

    bh = get_eager_buf(c);
    if (!bh) {
	debug(2, "%s: sq %p no free send buffers to %s",
	      __func__, sq, c->peername);
	return;
    }
    sq->bh = bh;
    bh->sq = sq;
    ptr = bh->buf;

    msg_header_init(&mh_rts_done.c, c, MSG_RTS_DONE);
    mh_rts_done.mop_id = sq->mop->op_id;

    debug(2, "%s: sq %p sent RTS_DONE mopid %llx", __func__,
          sq, llu(sq->mop->op_id));

    encode_msg_header_rts_done_t(&ptr, &mh_rts_done);

    post_sr(bh, sizeof(mh_rts_done));
    sq->state.send = SQ_WAITING_RTS_DONE_SEND_COMPLETION;
}

static void send_bye(ib_connection_t *c)
{
    msg_header_common_t mh_common;
    struct buf_head *bh;
    char *ptr;

    debug(2, "%s: sending bye", __func__);
    bh = get_eager_buf(c);
    if (!bh) {
	debug(2, "%s: no free send buffers to %s", __func__, c->peername);
	/* if no messages available, let garbage collection on server deal */
	return;
    }
    bh->sq = NULL;
    ptr = bh->buf;
    msg_header_init(&mh_common, c, MSG_BYE);
    encode_msg_header_common_t(&ptr, &mh_common);

    post_sr(bh, sizeof(mh_common));
}

/*
 * Two places need to send a CTS in response to an RTS.  They both
 * call this.  This handles pinning the memory, too.  Don't forget
 * to unpin when done.
 */
static int
send_cts(struct ib_work *rq)
{
    ib_connection_t *c = rq->c;
    struct buf_head *bh;
    msg_header_cts_t mh_cts;
    u_int64_t *bufp;
    u_int32_t *lenp;
    u_int32_t *keyp;
    u_int32_t post_len;
    char *ptr;
    int i;

    debug(2, "%s: rq %p from %s mopid %llx len %lld", __func__,
          rq, rq->c->peername, llu(rq->rts_mop_id),
          lld(rq->buflist.tot_len));

    bh = get_eager_buf(c);
    if (!bh) {
	debug(2, "%s: rq %p no free send buffers to %s",
	      __func__, rq, c->peername);
	return 1;
    }
    rq->bh = bh;
    bh->sq = (struct ib_work *) rq;  /* uplink for completion */

#if MEMCACHE_BOUNCEBUF
    if (reg_recv_buflist.num == 0) {
	reg_recv_buflist.num = 1;
	reg_recv_buflist.buf.recv = &reg_recv_buflist_buf;
	reg_recv_buflist.len = &reg_recv_buflist_len;
	reg_recv_buflist.tot_len = reg_recv_buflist_len;
	reg_recv_buflist_buf = bmi_ib_malloc(reg_recv_buflist_len);
	memcache_register(ib_device->memcache, &reg_recv_buflist);
    }
    if (rq->buflist.tot_len > reg_recv_buflist_len)
	error("%s: recv prereg buflist too small, need %lld", __func__,
	  lld(rq->buflist.tot_len));

    ib_buflist_t save_buflist = rq->buflist;
    rq->buflist = reg_recv_buflist;
#else
#  if !MEMCACHE_EARLY_REG
    memcache_register(ib_device->memcache, &rq->buflist);
#  endif
#endif

    msg_header_init(&mh_cts.c, c, MSG_CTS);
    mh_cts.rts_mop_id = rq->rts_mop_id;
    mh_cts.buflist_tot_len = rq->buflist.tot_len;
    mh_cts.buflist_num = rq->buflist.num;

    ptr = bh->buf;
    encode_msg_header_cts_t(&ptr, &mh_cts);

    /* encode all the buflist entries */
    bufp = (u_int64_t *)((msg_header_cts_t *) bh->buf + 1);
    lenp = (u_int32_t *)(bufp + rq->buflist.num);
    keyp = (u_int32_t *)(lenp + rq->buflist.num);
    post_len = (char *)(keyp + rq->buflist.num) - (char *)bh->buf;
    if (post_len > ib_device->eager_buf_size)
	error("%s: too many (%d) recv buflist entries for buf", __func__,
	  rq->buflist.num);
    for (i=0; i<rq->buflist.num; i++) {
	bufp[i] = htobmi64(int64_from_ptr(rq->buflist.buf.recv[i]));
	lenp[i] = htobmi32(rq->buflist.len[i]);
	keyp[i] = htobmi32(rq->buflist.memcache[i]->memkeys.rkey);
    }

    /* send the cts */
    post_sr(bh, post_len);

#if MEMCACHE_BOUNCEBUF
    rq->buflist = save_buflist;
#endif

    return 0;
}

/*
 * Bring up the connection before posting a send or receive on it.
 */
static int
ensure_connected(struct bmi_method_addr *remote_map)
{
    int ret = 0;
    ib_method_addr_t *ibmap = remote_map->method_data;

    if (!ibmap->c && ibmap->reconnect_flag)
	ret = ib_tcp_client_connect(ibmap, remote_map);
    else if(!ibmap->c && !ibmap->reconnect_flag)
	ret = 1; /* cannot actively connect */
    else
        ret = 0;

    return ret;
}

/*
 * Generic interface for both send and sendunexpected, list and non-list send.
 */
static int
post_send(bmi_op_id_t *id, struct bmi_method_addr *remote_map,
          int numbufs, const void *const *buffers, const bmi_size_t *sizes,
          bmi_size_t total_size, bmi_msg_tag_t tag, void *user_ptr,
          bmi_context_id context_id, int is_unexpected, uint8_t class)
{
    struct ib_work *sq;
    struct method_op *mop;
    ib_method_addr_t *ibmap;
    int i;
    int ret = 0;

    gen_mutex_lock(&interface_mutex);
    ret = ensure_connected(remote_map);
    if (ret)
    	goto out;
    ibmap = remote_map->method_data;

    /* alloc and build new sendq structure */
    sq = bmi_ib_malloc(sizeof(*sq));
    sq->type = BMI_SEND;
    sq->state.send = SQ_WAITING_BUFFER;
    sq->class = class;

    debug(2, "%s: sq %p len %lld peer %s", __func__, sq, (long long) total_size,
          ibmap->c->peername);

    /*
     * For a single buffer, store it inside the sq directly, else save
     * the pointer to the list the user built when calling a _list
     * function.  This case is indicated by the non-_list functions by
     * a zero in numbufs.
     */
    if (numbufs == 0) {
	sq->buflist_one_buf.send = *buffers;
	sq->buflist_one_len = *sizes;
	sq->buflist.num = 1;
	sq->buflist.buf.send = &sq->buflist_one_buf.send;
	sq->buflist.len = &sq->buflist_one_len;
    } else {
	sq->buflist.num = numbufs;
	sq->buflist.buf.send = buffers;
	sq->buflist.len = sizes;
    }
    sq->buflist.tot_len = 0;
    for (i=0; i<sq->buflist.num; i++)
	sq->buflist.tot_len += sizes[i];

    /*
     * This passed-in total length field does not make much sense
     * to me, but I'll at least check it for accuracy.
     */
    if (sq->buflist.tot_len != total_size)
	error("%s: user-provided tot len %lld"
	  " does not match buffer list tot len %lld",
	  __func__, lld(total_size), lld(sq->buflist.tot_len));

    /* unexpected messages must fit inside an eager message */
    if (is_unexpected && sq->buflist.tot_len > ib_device->eager_buf_payload) {
	free(sq);
	ret = -EINVAL;
	goto out;
    }

    sq->bmi_tag = tag;
    sq->c = ibmap->c;
    ++sq->c->refcnt;
    sq->is_unexpected = is_unexpected;
    qlist_add_tail(&sq->list, &ib_device->sendq);

    /* generate identifier used by caller to test for message later */
    mop = bmi_ib_malloc(sizeof(*mop));
    id_gen_fast_register(&mop->op_id, mop);
    mop->addr = remote_map;  /* set of function pointers, essentially */
    mop->method_data = sq;
    mop->user_ptr = user_ptr;
    mop->context_id = context_id;
    *id = mop->op_id;
    sq->mop = mop;
    debug(3, "%s: new sq %p", __func__, sq);

    /* and start sending it if possible */
    encourage_send_waiting_buffer(sq);
  out:
    gen_mutex_unlock(&interface_mutex);
    return ret;
}

static int
BMI_ib_post_send_list(bmi_op_id_t *id, struct bmi_method_addr *remote_map,
  const void *const *buffers, const bmi_size_t *sizes, int list_count,
  bmi_size_t total_size, enum bmi_buffer_type buffer_flag __unused,
  bmi_msg_tag_t tag, void *user_ptr, bmi_context_id context_id, PVFS_hint
  hints __unused)
{
    return post_send(id, remote_map, list_count, buffers, sizes,
                     total_size, tag, user_ptr, context_id, 0, 0);
}

static int
BMI_ib_post_sendunexpected_list(bmi_op_id_t *id, struct bmi_method_addr *remote_map,
                                const void *const *buffers,
				const bmi_size_t *sizes, int list_count,
                                bmi_size_t total_size,
				enum bmi_buffer_type buffer_flag __unused,
                                bmi_msg_tag_t tag, 
                                uint8_t class,
                                void *user_ptr,
				bmi_context_id context_id, 
                                PVFS_hint hints __unused)
{
    return post_send(id, remote_map, list_count, buffers, sizes,
                     total_size, tag, user_ptr, context_id, 1, class);
}

/*
 * Used by both recv and recv_list.
 */
static int
post_recv(bmi_op_id_t *id, struct bmi_method_addr *remote_map,
          int numbufs, void *const *buffers, const bmi_size_t *sizes,
          bmi_size_t tot_expected_len, bmi_msg_tag_t tag,
          void *user_ptr, bmi_context_id context_id)
{
    struct ib_work *rq;
    struct method_op *mop;
    ib_method_addr_t *ibmap;
    ib_connection_t *c;
    int i;
    int ret = 0;
    
    gen_mutex_lock(&interface_mutex);
    ret = ensure_connected(remote_map);
    if (ret)
    	goto out;
    ibmap = remote_map->method_data;
    c = ibmap->c;

    /* poll interface first to save a few steps below */
    ib_check_cq();

    /* check to see if matching recv is in the queue */
    rq = find_matching_recv(
      RQ_EAGER_WAITING_USER_POST | RQ_RTS_WAITING_USER_POST, c, tag);
    if (rq) {
	debug(2, "%s: rq %p matches %s", __func__, rq,
	  rq_state_name(rq->state.recv));
    } else {
	/* alloc and build new recvq structure */
	rq = alloc_new_recv(c, NULL);
	rq->state.recv = RQ_WAITING_INCOMING;
	rq->bmi_tag = tag;
	debug(2, "%s: new rq %p", __func__, rq);
    }

    if (numbufs == 0) {
	rq->buflist_one_buf.recv = *buffers;
	rq->buflist_one_len = *sizes;
	rq->buflist.num = 1;
	rq->buflist.buf.recv = &rq->buflist_one_buf.recv;
	rq->buflist.len = &rq->buflist_one_len;
    } else {
	rq->buflist.num = numbufs;
	rq->buflist.buf.recv = buffers;
	rq->buflist.len = sizes;
    }
    rq->buflist.tot_len = 0;
    for (i=0; i<rq->buflist.num; i++)
	rq->buflist.tot_len += sizes[i];

    /*
     * This passed-in total length field does not make much sense
     * to me, but I'll at least check it for accuracy.
     */
    if (rq->buflist.tot_len != tot_expected_len)
	error("%s: user-provided tot len %lld"
	  " does not match buffer list tot len %lld",
	  __func__, lld(tot_expected_len), lld(rq->buflist.tot_len));

    /* generate identifier used by caller to test for message later */
    mop = bmi_ib_malloc(sizeof(*mop));
    id_gen_fast_register(&mop->op_id, mop);
    mop->addr = remote_map;  /* set of function pointers, essentially */
    mop->method_data = rq;
    mop->user_ptr = user_ptr;
    mop->context_id = context_id;
    *id = mop->op_id;
    rq->mop = mop;

    /* handle the two "waiting for a local user post" states */
    if (rq->state.recv == RQ_EAGER_WAITING_USER_POST) {

	msg_header_eager_t mh_eager;
	char *ptr = rq->bh->buf;

	decode_msg_header_eager_t(&ptr, &mh_eager);

	debug(2, "%s: rq %p state %s finish eager directly", __func__,
	  rq, rq_state_name(rq->state.recv));
	if (rq->actual_len > tot_expected_len) {
	    error("%s: received %lld matches too-small buffer %lld",
	      __func__, lld(rq->actual_len), lld(rq->buflist.tot_len));
	}

	memcpy_to_buflist(&rq->buflist,
	                  (msg_header_eager_t *) rq->bh->buf + 1,
	                  rq->actual_len);

	/* re-post */
	post_rr(rq->c, rq->bh);

	/* now just wait for user to test, never do "immediate completion" */
	rq->state.recv = RQ_EAGER_WAITING_USER_TEST;
	goto out;

    } else if (rq->state.recv == RQ_RTS_WAITING_USER_POST) {
	int sret;
	debug(2, "%s: rq %p %s send cts", __func__, rq,
	  rq_state_name(rq->state.recv));
	/* try to send, or wait for send buffer space */
	rq->state.recv = RQ_RTS_WAITING_CTS_BUFFER;
#if MEMCACHE_EARLY_REG
	memcache_register(ib_device->memcache, &rq->buflist);
#endif
	sret = send_cts(rq);
1038 1039 1040 1041 1042
	if (sret == 0) {
            rq->state.recv = RQ_RTS_WAITING_RTS_DONE |
                RQ_RTS_WAITING_CTS_SEND_COMPLETION |
                RQ_RTS_WAITING_USER_TEST;
        }
Dries Kimpe's avatar
Dries Kimpe committed
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
	goto out;
    }

#if MEMCACHE_EARLY_REG
    /* but remember that this might not be used if the other side sends
     * less than we posted for receive; that's legal */
    if (rq->buflist.tot_len > ib_device->eager_buf_payload)
	memcache_register(ib_device->memcache, &rq->buflist);
#endif

  out:
    gen_mutex_unlock(&interface_mutex);
    return ret;
}

static int
BMI_ib_post_recv_list(bmi_op_id_t *id, struct bmi_method_addr *remote_map,
  void *const *buffers, const bmi_size_t *sizes, int list_count,
  bmi_size_t tot_expected_len, bmi_size_t *tot_actual_len __unused,
  enum bmi_buffer_type buffer_flag __unused, bmi_msg_tag_t tag, void *user_ptr,
  bmi_context_id context_id, PVFS_hint hints __unused)
{
    return post_recv(id, remote_map, list_count, buffers, sizes,
                     tot_expected_len, tag, user_ptr, context_id);
}

/*
 * Internal shared helper function.  Return 1 if found something
 * completed.
 */
static int
test_sq(struct ib_work *sq, bmi_op_id_t *outid, bmi_error_code_t *err,
  bmi_size_t *size, void **user_ptr, int complete)
{
    ib_connection_t *c;

    debug(9, "%s: sq %p outid %p err %p size %p user_ptr %p complete %d",
      __func__, sq, outid, err, size, user_ptr, complete);

    if (sq->state.send == SQ_WAITING_USER_TEST) {
	if (complete) {
	    debug(2, "%s: sq %p completed %lld to %s", __func__,
	      sq, lld(sq->buflist.tot_len), sq->c->peername);
	    *outid = sq->mop->op_id;
	    *err = 0;
	    *size = sq->buflist.tot_len;
	    if (user_ptr)
		*user_ptr = sq->mop->user_ptr;
	    qlist_del(&sq->list);
	    id_gen_fast_unregister(sq->mop->op_id);
	    c = sq->c;
	    free(sq->mop);
	    free(sq);
	    --c->refcnt;
	    if (c->closed || c->cancelled)
		ib_close_connection(c);
	    return 1;
	}
    /* this state needs help, push it (ideally would be triggered
     * when the resource is freed... XXX */
    } else if (sq->state.send == SQ_WAITING_BUFFER) {
	debug(2, "%s: sq %p %s, encouraging", __func__, sq,
	  sq_state_name(sq->state.send));
	encourage_send_waiting_buffer(sq);
    } else if (sq->state.send == SQ_WAITING_RTS_DONE_BUFFER) {
	debug(2, "%s: sq %p %s, encouraging", __func__, sq,
	  sq_state_name(sq->state.send));
	encourage_rts_done_waiting_buffer(sq);
    } else if (sq->state.send == SQ_CANCELLED && complete) {
	debug(2, "%s: sq %p cancelled", __func__, sq);
	*outid = sq->mop->op_id;
	*err = -PVFS_ETIMEDOUT;
	if (user_ptr)
	    *user_ptr = sq->mop->user_ptr;
	qlist_del(&sq->list);
	id_gen_fast_unregister(sq->mop->op_id);
	c = sq->c;
	free(sq->mop);
	free(sq);
	--c->refcnt;
	if (c->closed || c->cancelled)
	    ib_close_connection(c);
	return 1;
    } else {
	debug(9, "%s: sq %p found, not done, state %s", __func__,
	  sq, sq_state_name(sq->state.send));
    }
    return 0;
}

/*
 * Internal shared helper function.  Return 1 if found something
 * completed.  Note that rq->mop can be null for unexpected
 * messages.
 */
static int
test_rq(struct ib_work *rq, bmi_op_id_t *outid, bmi_error_code_t *err,
  bmi_size_t *size, void **user_ptr, int complete)
{
    ib_connection_t *c;

    debug(9, "%s: rq %p outid %p err %p size %p user_ptr %p complete %d",
      __func__, rq, outid, err, size, user_ptr, complete);

    if (rq->state.recv == RQ_EAGER_WAITING_USER_TEST 
      || rq->state.recv == RQ_RTS_WAITING_USER_TEST) {
	if (complete) {
	    debug(2, "%s: rq %p completed %lld from %s", __func__,
	      rq, lld(rq->actual_len), rq->c->peername);
	    *err = 0;
	    *size = rq->actual_len;
	    if (rq->mop) {
		*outid = rq->mop->op_id;
		if (user_ptr)
		    *user_ptr = rq->mop->user_ptr;
		id_gen_fast_unregister(rq->mop->op_id);
		free(rq->mop);
	    }
	    qlist_del(&rq->list);
	    c = rq->c;
	    free(rq);
	    --c->refcnt;
	    if (c->closed || c->cancelled)
		ib_close_connection(c);
	    return 1;
	}
    /* this state needs help, push it (ideally would be triggered
     * when the resource is freed...) XXX */
    } else if (rq->state.recv == RQ_RTS_WAITING_CTS_BUFFER) {
	int ret;
	debug(2, "%s: rq %p %s, encouraging", __func__, rq,
	  rq_state_name(rq->state.recv));
	ret = send_cts(rq);
1176 1177 1178 1179 1180
	if (ret == 0) {
            rq->state.recv = RQ_RTS_WAITING_RTS_DONE |
                RQ_RTS_WAITING_CTS_SEND_COMPLETION |
                RQ_RTS_WAITING_USER_TEST;
        } /* else keep waiting until we can send that cts */
Dries Kimpe's avatar
Dries Kimpe committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
	debug(2, "%s: rq %p now %s", __func__, rq, rq_state_name(rq->state.recv));
    } else if (rq->state.recv == RQ_CANCELLED && complete) {
	debug(2, "%s: rq %p cancelled", __func__, rq);
	*err = -PVFS_ETIMEDOUT;
	if (rq->mop) {
	    *outid = rq->mop->op_id;
	    if (user_ptr)
		*user_ptr = rq->mop->user_ptr;
	    id_gen_fast_unregister(rq->mop->op_id);
	    free(rq->mop);
	}
	qlist_del(&rq->list);
	c = rq->c;
	free(rq);
	--c->refcnt;
	if (c->closed || c->cancelled)
	    ib_close_connection(c);
	return 1;
    } else {
	debug(9, "%s: rq %p found, not done, state %s", __func__,
	  rq, rq_state_name(rq->state.recv));
    }
    return 0;
}

/*
 * Test one message, send or receive.  Also used to test the send side of
 * messages sent using sendunexpected.
 */
static int
BMI_ib_test(bmi_op_id_t id, int *outcount, bmi_error_code_t *err,
  bmi_size_t *size, void **user_ptr, int max_idle_time __unused,
  bmi_context_id context_id __unused)
{
    struct method_op *mop;
    struct ib_work *sq;
    int n;

    gen_mutex_lock(&interface_mutex);
    ib_check_cq();

    mop = id_gen_fast_lookup(id);
    sq = mop->method_data;
    n = 0;
    if (sq->type == BMI_SEND) {
	if (test_sq(sq, &id, err, size, user_ptr, 1))
	    n = 1;
    } else {
	/* actually a recv */
	struct ib_work *rq = mop->method_data;
	if (test_rq(rq, &id, err, size, user_ptr, 1))
	    n = 1;
    }
    *outcount = n;
    gen_mutex_unlock(&interface_mutex);
    return 0;
}

/*
 * Test just the particular list of op ids, returning the list of indices
 * that completed.
 */
static int BMI_ib_testsome(int incount, bmi_op_id_t *ids, int *outcount,
  int *index_array, bmi_error_code_t *errs, bmi_size_t *sizes, void **user_ptrs,
  int max_idle_time __unused, bmi_context_id context_id __unused)
{
    struct method_op *mop;
    struct ib_work *sq;
    bmi_op_id_t tid;
    int i, n;

    gen_mutex_lock(&interface_mutex);
    ib_check_cq();

    n = 0;
    for (i=0; i<incount; i++) {
	if (!ids[i])
	    continue;
	mop = id_gen_fast_lookup(ids[i]);
	sq = mop->method_data;

	if (sq->type == BMI_SEND) {
	    if (test_sq(sq, &tid, &errs[n], &sizes[n], &user_ptrs[n], 1)) {
		index_array[n] = i;
		++n;
	    }
	} else {
	    /* actually a recv */
	    struct ib_work *rq = mop->method_data;
	    if (test_rq(rq, &tid, &errs[n], &sizes[n], &user_ptrs[n], 1)) {
		index_array[n] = i;
		++n;
	    }
	}
    }

    gen_mutex_unlock(&interface_mutex);

    *outcount = n;
    return 0;
}

/*
 * Test for multiple completions matching a particular user context.
 * Return 0 if okay, >0 if want another poll soon, negative for error.
 */
static int
BMI_ib_testcontext(int incount, bmi_op_id_t *outids, int *outcount,
  bmi_error_code_t *errs, bmi_size_t *sizes, void **user_ptrs,
  int max_idle_time, bmi_context_id context_id)
{
    struct qlist_head *l, *lnext;
    int n = 0, complete, activity = 0;
    void **up = NULL;

    gen_mutex_lock(&interface_mutex);

restart:
    activity += ib_check_cq();

    /*
     * Walk _all_ entries on sq, rq, marking them completed or
     * encouraging them as needed due to resource limitations.
     */
    for (l=ib_device->sendq.next; l != &ib_device->sendq; l=lnext) {
	struct ib_work *sq = qlist_upcast(l);
	lnext = l->next;
	/* test them all, even if can't reap them, just to encourage */
	complete = (sq->mop->context_id == context_id) && (n < incount);
	if (user_ptrs)
	    up = &user_ptrs[n];
	n += test_sq(sq, &outids[n], &errs[n], &sizes[n], up, complete);
    }

    for (l=ib_device->recvq.next; l != &ib_device->recvq; l=lnext) {
	struct ib_work *rq = qlist_upcast(l);
	lnext = l->next;

	/* some receives have no mops:  unexpected */
	complete = rq->mop &&
	  (rq->mop->context_id == context_id) && (n < incount);
	if (user_ptrs)
	    up = &user_ptrs[n];
	n += test_rq(rq, &outids[n], &errs[n], &sizes[n], up, complete);
    }

    /* drop lock before blocking on new connections below */
    gen_mutex_unlock(&interface_mutex);

    if (activity == 0 && n == 0 && max_idle_time > 0) {
	/*
	 * Block if told to from above.
	 */
	debug(8, "%s: last activity too long ago, blocking", __func__);
	activity = ib_block_for_activity(max_idle_time);
	if (activity == 1) {   /* IB action, go do it immediately */
	    gen_mutex_lock(&interface_mutex);
	    goto restart;
	}
    }

    *outcount = n;
    return activity + n;
}

/*
 * Non-blocking test to look for any incoming unexpected messages.
 * This is also where we check for new connections on the TCP socket, since
 * those would show up as unexpected the first time anything is sent.
 * Return 0 for success, or -1 for failure; number of things in *outcount.
 * Return >0 if want another poll soon.
 */
static int
BMI_ib_testunexpected(int incount __unused, int *outcount,
  struct bmi_method_unexpected_info *ui, uint8_t class, int max_idle_time)
{
    struct qlist_head *l;
    int activity = 0, n;

    gen_mutex_lock(&interface_mutex);

    /* Check CQ, then look for the first unexpected message.  */
restart:
    activity += ib_check_cq();

    n = 0;
    qlist_for_each(l, &ib_device->recvq) {
	struct ib_work *rq = qlist_upcast(l);
	if (rq->state.recv == RQ_EAGER_WAITING_USER_TESTUNEXPECTED) {
	    msg_header_eager_t mh_eager;
	    char *ptr = rq->bh->buf;
	    ib_connection_t *c = rq->c;

	    decode_msg_header_eager_t(&ptr, &mh_eager);
            if(mh_eager.class != class)
                continue;

	    debug(2, "%s: found waiting testunexpected", __func__);
	    ui->error_code = 0;
	    ui->addr = c->remote_map;  /* hand back permanent method_addr */
	    ui->buffer = bmi_ib_malloc((unsigned long) rq->actual_len);
	    ui->size = rq->actual_len;
	    memcpy(ui->buffer,
	           (msg_header_eager_t *) rq->bh->buf + 1,
	           (size_t) ui->size);
	    ui->tag = rq->bmi_tag;
	    /* re-post the buffer in which it was sitting, just unexpecteds */
	    post_rr(c, rq->bh);
	    n = 1;
	    qlist_del(&rq->list);
	    free(rq);
	    --c->refcnt;
	    if (c->closed || c->cancelled)
		ib_close_connection(c);
	    goto out;
	}
    }

  out:
    gen_mutex_unlock(&interface_mutex);

    if (activity == 0 && n == 0 && max_idle_time > 0) {
	/*
	 * Block if told to from above, also polls TCP listening socket.
	 */
	debug(8, "%s: last activity too long ago, blocking", __func__);
	activity = ib_block_for_activity(max_idle_time);
	if (activity == 1) {   /* IB action, go do it immediately */
	    gen_mutex_lock(&interface_mutex);
	    goto restart;
	}
    }

    *outcount = n;
    return activity + n;
}

/*
 * No need to track these internally.  Just search the entire queue.
 */
static int
BMI_ib_open_context(bmi_context_id context_id __unused)
{
    return 0;
}

static void
BMI_ib_close_context(bmi_context_id context_id __unused)
{
}

/*
 * Asynchronous call to destroy an in-progress operation.
 * Can't just call test since we don't want to reap the operation,
 * just make sure it's done or not.
 */
static int
BMI_ib_cancel(bmi_op_id_t id, bmi_context_id context_id __unused)
{
    struct method_op *mop;
    struct ib_work *tsq;
    ib_connection_t *c = 0;

    gen_mutex_lock(&interface_mutex);
    ib_check_cq();
    mop = id_gen_fast_lookup(id);
    tsq = mop->method_data;
    if (tsq->type == BMI_SEND) {
	/*
	 * Cancelling completed operations is fine, they will be
	 * tested later.  Any others trigger full shutdown of the
	 * connection.
	 */
	if (tsq->state.send != SQ_WAITING_USER_TEST)
	    c = tsq->c;
    } else {
	/* actually a recv */
	struct ib_work *rq = mop->method_data;
	if (!(rq->state.recv == RQ_EAGER_WAITING_USER_TEST 
	   || rq->state.recv == RQ_RTS_WAITING_USER_TEST))
	    c = rq->c;
    }

    if (c && !c->cancelled) {
	/*
	 * In response to a cancel, forcibly close the connection.  Don't send
	 * a bye message first since it may be the case that the peer is dead
	 * anyway.  Do not close the connection until all the sq/rq on it have
	 * gone away.
	 */
	struct qlist_head *l;

	c->cancelled = 1;
	drain_qp(c);
	qlist_for_each(l, &ib_device->sendq) {
	    struct ib_work *sq = qlist_upcast(l);
	    if (sq->c != c) continue;
#if !MEMCACHE_BOUNCEBUF
	    if (sq->state.send == SQ_WAITING_DATA_SEND_COMPLETION)
		memcache_deregister(ib_device->memcache, &sq->buflist);
#  if MEMCACHE_EARLY_REG
	    /* pin when sending rts, so also must dereg in this state */
	    if (sq->state.send == SQ_WAITING_RTS_SEND_COMPLETION ||
	        sq->state.send == SQ_WAITING_RTS_SEND_COMPLETION_GOT_CTS ||
	        sq->state.send == SQ_WAITING_CTS)
		memcache_deregister(ib_device->memcache, &sq->buflist);
#  endif
#endif
	    if (sq->state.send != SQ_WAITING_USER_TEST)
		sq->state.send = SQ_CANCELLED;
	}
	qlist_for_each(l, &ib_device->recvq) {
	    struct ib_work *rq = qlist_upcast(l);
	    if (rq->c != c) continue;
#if !MEMCACHE_BOUNCEBUF
1496
	    if (rq->state.recv & RQ_RTS_WAITING_RTS_DONE)
Dries Kimpe's avatar
Dries Kimpe committed
1497 1498
		memcache_deregister(ib_device->memcache, &rq->buflist);
#  if MEMCACHE_EARLY_REG
1499
            /* pin on post, dereg all these */
Dries Kimpe's avatar
Dries Kimpe committed
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
	    if (rq->state.recv == RQ_WAITING_INCOMING
	      && rq->buflist.tot_len > ib_device->eager_buf_payload)
		memcache_deregister(ib_device->memcache, &rq->buflist);
#  endif
#endif
	    if (!(rq->state.recv == RQ_EAGER_WAITING_USER_TEST 
	       || rq->state.recv == RQ_RTS_WAITING_USER_TEST))
		rq->state.recv = RQ_CANCELLED;
	}
    }

    gen_mutex_unlock(&interface_mutex);
    return 0;
}

static const char *
BMI_ib_rev_lookup(struct bmi_method_addr *meth)
{
    ib_method_addr_t *ibmap = meth->method_data;
    if (!ibmap->c)
	return "(unconnected)";
    else
	return ibmap->c->peername;
}

/*
 * Build and fill an IB-specific method_addr structure.
 */
static struct bmi_method_addr *ib_alloc_method_addr(ib_connection_t *c,
                                                char *hostname, int port, 
                                                int reconnect_flag)
{
    struct bmi_method_addr *map;
    ib_method_addr_t *ibmap;

    map = bmi_alloc_method_addr(bmi_ib_method_id, (bmi_size_t) sizeof(*ibmap));
    ibmap = map->method_data;
    ibmap->c = c;
    ibmap->hostname = hostname;
    ibmap->port = port;
    ibmap->reconnect_flag = reconnect_flag;

    return map;
}

/*
 * Break up a method string like:
 *   ib://hostname:port/filesystem
 * into its constituent fields, storing them in an opaque
 * type, which is then returned.
 * XXX: I'm assuming that these actually return a _const_ pointer
 * so that I can hand back an existing map.
 */
static struct bmi_method_addr *BMI_ib_method_addr_lookup(const char *id)
{
    char *s, *hostname, *cp, *cq;
    int port;
    struct bmi_method_addr *map = NULL;

    /* parse hostname */
    s = string_key("ib", id);  /* allocs a string */
    if (!s)
	return 0;
    cp = strchr(s, ':');
    if (!cp)
	error("%s: no ':' found", __func__);

    /* copy to permanent storage */
    hostname = bmi_ib_malloc((unsigned long) (cp - s + 1));
    strncpy(hostname, s, (size_t) (cp-s));
    hostname[cp-s] = '\0';

    /* strip /filesystem  */
    ++cp;
    cq = strchr(cp, '/');
    if (cq)
	*cq = 0;
    port = strtoul(cp, &cq, 10);
    if (cq == cp)
	error("%s: invalid port number", __func__);
    if (*cq != '\0')
	error("%s: extra characters after port number", __func__);
    free(s);

    /* lookup in known connections, if there are any */
    gen_mutex_lock(&interface_mutex);
    if (ib_device) {
	struct qlist_head *l;
	qlist_for_each(l, &ib_device->connection) {
	    ib_connection_t *c = qlist_upcast(l);
	    ib_method_addr_t *ibmap = c->remote_map->method_data;
	    if (ibmap->port == port && !strcmp(ibmap->hostname, hostname)) {
	       map = c->remote_map;
	       break;
	    }
	}
    }
    gen_mutex_unlock(&interface_mutex);

    if (map)
	free(hostname);  /* found it */
    else
    {
        /* set reconnect flag on this addr; we will be acting as a client
         * for this connection and will be responsible for making sure that
         * the connection is established
         */
	map = ib_alloc_method_addr(0, hostname, port, 1);  /* alloc new one */
	/* but don't call bmi_method_addr_reg_callback! */
    }

    return map;
}

static ib_connection_t *ib_new_connection(int sock, const char *peername,
                                          int is_server)
{
    ib_connection_t *c;
    int i, ret;

    c = bmi_ib_malloc(sizeof(*c));
    c->peername = strdup(peername);

    /* fill send and recv free lists and buf heads */
    c->eager_send_buf_contig = bmi_ib_malloc(ib_device->eager_buf_num
      * ib_device->eager_buf_size);
    c->eager_recv_buf_contig = bmi_ib_malloc(ib_device->eager_buf_num
      * ib_device->eager_buf_size);
    INIT_QLIST_HEAD(&c->eager_send_buf_free);
    INIT_QLIST_HEAD(&c->eager_recv_buf_free);
    c->eager_send_buf_head_contig = bmi_ib_malloc(ib_device->eager_buf_num
      * sizeof(*c->eager_send_buf_head_contig));
    c->eager_recv_buf_head_contig = bmi_ib_malloc(ib_device->eager_buf_num
      * sizeof(*c->eager_recv_buf_head_contig));
    for (i=0; i<ib_device->eager_buf_num; i++) {
	struct buf_head *ebs = &c->eager_send_buf_head_contig[i];
	struct buf_head *ebr = &c->eager_recv_buf_head_contig[i];
	INIT_QLIST_HEAD(&ebs->list);
	INIT_QLIST_HEAD(&ebr->list);
	ebs->c = c;
	ebr->c = c;
	ebs->num = i;
	ebr->num = i;
	ebs->buf = (char *) c->eager_send_buf_contig
		 + i * ib_device->eager_buf_size;
	ebr->buf = (char *) c->eager_recv_buf_contig
		 + i * ib_device->eager_buf_size;
	qlist_add_tail(&ebs->list, &c->eager_send_buf_free);
	qlist_add_tail(&ebr->list, &c->eager_recv_buf_free);
    }

    /* put it on the list */
    qlist_add(&c->list, &ib_device->connection);

    /* other vars */
    c->remote_map = 0;
    c->cancelled = 0;
    c->refcnt = 0;
    c->closed = 0;

    /* save one credit back for emergency credit refill */
    c->send_credit = ib_device->eager_buf_num - 1;
    c->return_credit = 0;

    ret = new_connection(c, sock, is_server);
    if (ret) {
	ib_close_connection(c);
	c = NULL;
    }

    return c;
}

/*
 * Try to close and free a connection, but only do it if refcnt has
 * gone to zero.
 */
static void ib_close_connection(ib_connection_t *c)
{
    debug(2, "%s: closing connection to %s", __func__, c->peername);
    c->closed = 1;
    if (c->refcnt != 0) {
	debug(1, "%s: refcnt non-zero %d, delaying free", __func__, c->refcnt);
	return;
    }

    close_connection(c);

    free(c->eager_send_buf_contig);
    free(c->eager_recv_buf_contig);
    free(c->eager_send_buf_head_contig);
    free(c->eager_recv_buf_head_contig);
    /* never free the remote map, for the life of the executable, just
     * mark it unconnected since BMI will always have this structure. */
    if (c->remote_map) {
	ib_method_addr_t *ibmap = c->remote_map->method_data;
	ibmap->c = NULL;
    }
    free(c->peername);
    qlist_del(&c->list);
    free(c);
}

/*
 * Blocking connect initiated by a post_sendunexpected{,_list}, or
 * post_recv*
 */
static int ib_tcp_client_connect(ib_method_addr_t *ibmap,
                                 struct bmi_method_addr *remote_map)
{
    int s;
    char peername[2048];
    struct hostent *hp;
    struct sockaddr_in skin;
    
    s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0) {
	warning("%s: create tcp socket: %m", __func__);
	return bmi_errno_to_pvfs(-errno);
    }
    hp = gethostbyname(ibmap->hostname);
    if (!hp) {
	warning("%s: cannot resolve server %s", __func__, ibmap->hostname);
	return -1;
    }
    memset(&skin, 0, sizeof(skin));
    skin.sin_family = hp->h_addrtype;
    memcpy(&skin.sin_addr, hp->h_addr_list[0], (size_t) hp->h_length);
    skin.sin_port = htons(ibmap->port);
    sprintf(peername, "%s:%d", ibmap->hostname, ibmap->port);
  retry:
    if (connect(s, (struct sockaddr *) &skin, sizeof(skin)) < 0) {
	if (errno == EINTR)
	    goto retry;
	else {
	    warning("%s: connect to server %s: %m", __func__, peername);
	    return bmi_errno_to_pvfs(-errno);
	}
    }
    ibmap->c = ib_new_connection(s, peername, 0);
    if (!ibmap->c)
	error("%s: ib_new_connection failed", __func__);
    ibmap->c->remote_map = remote_map;

    if (close(s) < 0) {
	warning("%s: close sock: %m", __func__);
	return bmi_errno_to_pvfs(-errno);
    }
    return 0;
}

/*
 * On a server, initialize a socket for listening for new connections.
 */
static void ib_tcp_server_init_listen_socket(struct bmi_method_addr *addr)
{
    int flags;
    struct sockaddr_in skin;
    ib_method_addr_t *ibc = addr->method_data;

    ib_device->listen_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (ib_device->listen_sock < 0)
	error_errno("%s: create tcp socket", __func__);
    flags = 1;
    if (setsockopt(ib_device->listen_sock, SOL_SOCKET, SO_REUSEADDR, &flags,
      sizeof(flags)) < 0)
	error_errno("%s: setsockopt REUSEADDR", __func__);
    memset(&skin, 0, sizeof(skin));
    skin.sin_family = AF_INET;
    skin.sin_port = htons(ibc->port);
  retry:
    if (bind(ib_device->listen_sock, (struct sockaddr *) &skin, sizeof(skin)) < 0) {
	if (errno == EINTR)
	    goto retry;
	else
	    error_errno("%s: bind tcp socket", __func__);
    }
    if (listen(ib_device->listen_sock, 1024) < 0)
	error_errno("%s: listen tcp socket", __func__);
    flags = fcntl(ib_device->listen_sock, F_GETFL);
    if (flags < 0)
	error_errno("%s: fcntl getfl listen sock", __func__);
    flags |= O_NONBLOCK;
    if (fcntl(ib_device->listen_sock, F_SETFL, flags) < 0)
	error_errno("%s: fcntl setfl nonblock listen sock", __func__);
}

/*
 * Check for new connections.  The listening socket is left nonblocking
 * so this test can be quick; but accept is not really that quick compared
 * to polling an IB interface, for instance.  Returns >0 if an accept worked.
 */
static int ib_tcp_server_check_new_connections(void)
{
    struct sockaddr_in ssin;
    socklen_t len;
    int s, ret = 0;

    len = sizeof(ssin);
    s = accept(ib_device->listen_sock, (struct sockaddr *) &ssin, &len);
    if (s < 0) {
	if (!(errno == EAGAIN))
	    error_errno("%s: accept listen sock", __func__);
    } else {
	char peername[2048];
	ib_connection_t *c;

	char *hostname = strdup(inet_ntoa(ssin.sin_addr));
	int port = ntohs(ssin.sin_port);
	sprintf(peername, "%s:%d", hostname, port);

	gen_mutex_lock(&interface_mutex);

	c = ib_new_connection(s, peername, 1);
	if (!c) {
	    free(hostname);
	    goto out_unlock;
	}

        /* don't set reconnect flag on this addr; we are a server in this
         * case and the peer will be responsible for maintaining the
         * connection
         */
	c->remote_map = ib_alloc_method_addr(c, hostname, port, 0);
	/* register this address with the method control layer */
	c->bmi_addr = bmi_method_addr_reg_callback(c->remote_map);
	if (c->bmi_addr == 0)
	    error_xerrno(ENOMEM, "%s: bmi_method_addr_reg_callback", __func__);

	debug(2, "%s: accepted new connection %s at server", __func__,
	  c->peername);
	ret = 1;

out_unlock:
	gen_mutex_unlock(&interface_mutex);
	if (close(s) < 0)
	    error_errno("%s: close new sock", __func__);
    }
    return ret;
}

/*
 * Ask the device to write to its FD if a CQ event happens, and poll on it
 * as well as the listen_sock for activity, but do not actually respond to
 * anything.  A later ib_check_cq will handle CQ events, and a later call to
 * testunexpected will pick up new connections.  Returns ==1 if IB device is
 * ready, other >0 for some activity, else 0.
 */
static int ib_block_for_activity(int timeout_ms)
{
    struct pollfd pfd[3];  /* cq fd, async fd, accept socket */
    int numfd;
    int ret;

    prepare_cq_block(&pfd[0].fd, &pfd[1].fd);
    pfd[0].events = POLLIN;
    pfd[1].events = POLLIN;
    numfd = 2;
    if (ib_device->listen_sock >= 0