コード例 #1
0
ファイル: psm_ep.c プロジェクト: michich/opa-psm2
psm_error_t
__psm_ep_epid_share_memory(psm_ep_t ep, psm_epid_t epid, int *result_o)
{
	uint32_t num_lids = 0;
	uint16_t *lids = NULL;
	int i;
	uint16_t epid_lid;
	int result = 0;
	psm_error_t err;

	psmi_assert_always(ep != NULL);
	PSMI_ERR_UNLESS_INITIALIZED(ep);

	epid_lid = (uint16_t) psm_epid_nid(epid);
	/* If we're in non-hfi mode, done bother listing lids */
	if (!psmi_ep_device_is_enabled(ep, PTL_DEVID_IPS)) {
		uint64_t mylid = (uint16_t) psm_epid_nid(ep->epid);
		if (mylid == epid_lid)
			result = 1;
	} else {
		err = psmi_ep_devlids(&lids, &num_lids, ep->gid_hi, ep->gid_lo);
		if (err)
			return err;
		for (i = 0; i < num_lids; i++) {
			if (epid_lid == lids[i]) {
				result = 1;
				break;
			}
		}
	}
	*result_o = result;
	return PSM_OK;
}
コード例 #2
0
ファイル: psm_am.c プロジェクト: michich/opa-psm2
psm_error_t
__psm_am_reply_short(psm_am_token_t token, psm_handler_t handler,
		     psm_amarg_t *args, int nargs, void *src, size_t len,
		     int flags, psm_am_completion_fn_t completion_fn,
		     void *completion_ctxt)
{
	psm_error_t err;
	struct psmi_am_token *tok;
	psm_epaddr_t epaddr;
	ptl_ctl_t *ptlc;

	PSMI_ASSERT_INITIALIZED();
	psmi_assert_always(token != NULL);
	psmi_assert(handler >= 0 && handler < psmi_am_parameters.max_handlers);
	psmi_assert(nargs >= 0 && nargs <= psmi_am_parameters.max_nargs);
	psmi_assert(nargs > 0 ? args != NULL : 1);
	psmi_assert(len >= 0 && len <= psmi_am_parameters.max_reply_short);
	psmi_assert(len > 0 ? src != NULL : 1);

	tok = (struct psmi_am_token *)token;
	epaddr = tok->epaddr_from;
	ptlc = epaddr->ptlctl;

	/* No locking here since we are already within handler context and already
	 * locked */

	err = ptlc->am_short_reply(token, handler, args,
				   nargs, src, len, flags, completion_fn,
				   completion_ctxt);
	return err;
}
コード例 #3
0
ファイル: psm_ep.c プロジェクト: michich/opa-psm2
psm_error_t __psm_ep_epid_lookup(psm_epid_t epid, psm_epconn_t *epconn)
{
	psm_error_t err = PSM_OK;
	psm_epaddr_t epaddr;
	psm_ep_t ep;

	PSMI_ERR_UNLESS_INITIALIZED(NULL);

	/* Need to have an opened endpoint before we can resolve epids */
	if (psmi_opened_endpoint == NULL) {
		err = psmi_handle_error(NULL, PSM_EP_WAS_CLOSED,
					"PSM Endpoint is closed or does not exist");
		return err;
	}

	ep = psmi_opened_endpoint;
	while (ep) {
		epaddr = psmi_epid_lookup(ep, epid);
		if (!epaddr) {
			ep = ep->user_ep_next;
			continue;
		}

		/* Found connection for epid. Return info about endpoint to caller. */
		psmi_assert_always(epaddr->ptlctl->ep == ep);
		epconn->addr = epaddr;
		epconn->ep = ep;
		epconn->mq = ep->mq;
		return err;
	}

	err = psmi_handle_error(NULL, PSM_EPID_UNKNOWN,
				"Endpoint connection status unknown");
	return err;
}
コード例 #4
0
ファイル: psm_sysbuf.c プロジェクト: michich/opa-psm2
int psmi_sysbuf_init(void)
{
	int i;
	uint32_t block_sizes[] = { 256, 512, 1024,
		2048, 4096, 8192, (uint32_t) -1 };
	uint32_t replenishing_rate[] = { 128, 64, 32, 16, 8, 4, 0 };

	if (psmi_sysbuf.is_initialized)
		return PSM_OK;

	for (i = 0; i < MM_NUM_OF_POOLS; i++) {
		psmi_sysbuf.handler_index[i].block_size = block_sizes[i];
		psmi_sysbuf.handler_index[i].current_available = 0;
		psmi_sysbuf.handler_index[i].free_list = NULL;
		psmi_sysbuf.handler_index[i].total_alloc = 0;
		psmi_sysbuf.handler_index[i].replenishing_rate =
			replenishing_rate[i];

		if (block_sizes[i] == -1) {
			psmi_assert_always(replenishing_rate[i] == 0);
			psmi_sysbuf.handler_index[i].flags =
				MM_FLAG_TRANSIENT;
		} else {
			psmi_assert_always(replenishing_rate[i] > 0);
			psmi_sysbuf.handler_index[i].flags = MM_FLAG_NONE;
		}
	}

	VALGRIND_CREATE_MEMPOOL(&psmi_sysbuf, PSM_VALGRIND_REDZONE_SZ,
				PSM_VALGRIND_MEM_UNDEFINED);

	/* Hit once on each block size so we have a pool that's allocated */
	for (i = 0; i < MM_NUM_OF_POOLS; i++) {
		void *ptr;
		if (block_sizes[i] == -1)
			continue;
		ptr = psmi_sysbuf_alloc(block_sizes[i]);
		psmi_sysbuf_free(ptr);
	}

	return PSM_OK;
}
コード例 #5
0
ファイル: ips_epstate.c プロジェクト: 01org/opa-psm2
psm2_error_t ips_epstate_del(struct ips_epstate *eps, ips_epstate_idx connidx)
{
	ips_epstate_idx idx;
	/* actual table index */
	idx = (connidx + eps->eps_base_idx) & (IPS_EPSTATE_CONNIDX_MAX-1);
	psmi_assert_always(idx < eps->eps_tabsize);
	_HFI_VDBG("connidx=%d, table_idx=%d\n", connidx, idx);
	eps->eps_tab[idx].ipsaddr = NULL;
	/* We may eventually want to release memory, but probably not */
	eps->eps_tabsizeused--;
	return PSM2_OK;
}
コード例 #6
0
ファイル: ips_proto_am.c プロジェクト: 01org/opa-psm2
psm2_error_t
ips_am_short_request(psm2_epaddr_t epaddr,
		     psm2_handler_t handler, psm2_amarg_t *args, int nargs,
		     void *src, size_t len, int flags,
		     psm2_am_completion_fn_t completion_fn,
		     void *completion_ctxt)
{
	struct ips_proto_am *proto_am = &epaddr->proto->proto_am;
	psm2_error_t err;
	ips_scb_t *scb;
	ips_epaddr_t *ipsaddr;
	int pad_bytes = calculate_pad_bytes(len);
	int payload_sz = (nargs << 3);

	if_pt(!(flags & PSM2_AM_FLAG_ASYNC))
	    payload_sz += len;

	if (payload_sz > (IPS_AM_HDR_NARGS << 3)) {
		/* Payload can't fit in header, allocate buffer to carry data */
		int arg_sz = (nargs > IPS_AM_HDR_NARGS) ?
		    ((nargs - IPS_AM_HDR_NARGS) << 3) : 0;

		/* len + pad_bytes + overflow_args */
		PSMI_BLOCKUNTIL(epaddr->ptlctl->ep,
				err,
				((scb = ips_scbctrl_alloc(
				      &proto_am->scbc_request,
				      1,
				      len + pad_bytes + arg_sz,
				      IPS_SCB_FLAG_ADD_BUFFER)) != NULL));
	} else {
		PSMI_BLOCKUNTIL(epaddr->ptlctl->ep,
				err,
				((scb = ips_scbctrl_alloc_tiny(
				      &proto_am->scbc_request)) != NULL));
	}

	psmi_assert_always(scb != NULL);
	ips_am_scb_init(scb, handler, nargs, pad_bytes,
			completion_fn, completion_ctxt);

	/* Select the next ipsaddr for multi-rail */
	ipsaddr = ((ips_epaddr_t *)epaddr)->msgctl->ipsaddr_next;
	ipsaddr->msgctl->ipsaddr_next = ipsaddr->next;

	return am_short_reqrep(scb, ipsaddr, args,
			       nargs,
			       (flags & PSM2_AM_FLAG_NOREPLY) ?
			       OPCODE_AM_REQUEST_NOREPLY : OPCODE_AM_REQUEST,
			       src, len, flags, pad_bytes);
}
コード例 #7
0
ファイル: ips_epstate.c プロジェクト: 01org/opa-psm2
/*
 * Add ipsaddr with epid to the epstate table, return new index to caller in
 * 'connidx'.
 */
psm2_error_t
ips_epstate_add(struct ips_epstate *eps, struct ips_epaddr *ipsaddr,
		ips_epstate_idx *connidx_o)
{
	int i, j;
	ips_epstate_idx connidx;

	if (++eps->eps_tabsizeused > eps->eps_tabsize) {	/* realloc */
		struct ips_epstate_entry *newtab;
		eps->eps_tabsize += PTL_EPADDR_ALLOC_CHUNK;
		newtab = (struct ips_epstate_entry *)
		    psmi_calloc(eps->context->ep, PER_PEER_ENDPOINT,
				eps->eps_tabsize,
				sizeof(struct ips_epstate_entry));
		if (newtab == NULL)
			return PSM2_NO_MEMORY;
		else if (eps->eps_tab) {	/* NOT first alloc */
			for (i = 0;
			     i < eps->eps_tabsize - PTL_EPADDR_ALLOC_CHUNK; i++)
				newtab[i] = eps->eps_tab[i];	/* deep copy */
			psmi_free(eps->eps_tab);
		}
		eps->eps_tab = newtab;
	}
	/* Find the next free hole.  We can afford to do this since connect is not
	 * in the critical path */
	for (i = 0, j = eps->eps_tab_nextidx; i < eps->eps_tabsize; i++, j++) {
		if (j == eps->eps_tabsize)
			j = 0;
		if (eps->eps_tab[j].ipsaddr == NULL) {
			eps->eps_tab_nextidx = j + 1;
			if (eps->eps_tab_nextidx == eps->eps_tabsize)
				eps->eps_tab_nextidx = 0;
			break;
		}
	}
	psmi_assert_always(i != eps->eps_tabsize);
	connidx = (j - eps->eps_base_idx) & (IPS_EPSTATE_CONNIDX_MAX-1);
	_HFI_VDBG("node %s gets connidx=%d (table idx %d)\n",
		  psmi_epaddr_get_name(((psm2_epaddr_t) ipsaddr)->epid), connidx,
		  j);
	eps->eps_tab[j].ipsaddr = ipsaddr;
	if (j >= IPS_EPSTATE_CONNIDX_MAX) {
		return psmi_handle_error(eps->context->ep,
					 PSM2_TOO_MANY_ENDPOINTS,
					 "Can't connect to more than %d non-local endpoints",
					 IPS_EPSTATE_CONNIDX_MAX);
	}
	*connidx_o = connidx;
	return PSM2_OK;
}
コード例 #8
0
ファイル: ptl.c プロジェクト: 01org/opa-psm2
void
psmi_am_mq_handler(void *toki, psm2_amarg_t *args, int narg, void *buf,
		   size_t len)
{
	amsh_am_token_t *tok = (amsh_am_token_t *) toki;
	psm2_mq_req_t req;
	psm2_mq_tag_t tag;
	int rc;
	uint32_t opcode = args[0].u32w0;
	uint32_t msglen = opcode <= MQ_MSG_SHORT ? len : args[0].u32w1;

	tag.tag[0] = args[1].u32w1;
	tag.tag[1] = args[1].u32w0;
	tag.tag[2] = args[2].u32w1;
	psmi_assert(toki != NULL);
	_HFI_VDBG("mq=%p opcode=%d, len=%d, msglen=%d\n",
		  tok->mq, opcode, (int)len, msglen);

	switch (opcode) {
	case MQ_MSG_TINY:
	case MQ_MSG_SHORT:
	case MQ_MSG_EAGER:
		rc = psmi_mq_handle_envelope(tok->mq, tok->tok.epaddr_incoming,
					     &tag, msglen, 0, buf,
					     (uint32_t) len, 1, opcode, &req);

		/* for eager matching */
		req->ptl_req_ptr = (void *)tok->tok.epaddr_incoming;
		req->msg_seqnum = 0;	/* using seqnum 0 */
		break;
	default:{
			void *sreq = (void *)(uintptr_t) args[3].u64w0;
			uintptr_t sbuf = (uintptr_t) args[4].u64w0;
			psmi_assert(narg == 5);
			psmi_assert_always(opcode == MQ_MSG_LONGRTS);
			rc = psmi_mq_handle_rts(tok->mq, tok->tok.epaddr_incoming,
						&tag, msglen, NULL, 0, 1,
						ptl_handle_rtsmatch, &req);

			req->rts_peer = tok->tok.epaddr_incoming;
			req->ptl_req_ptr = sreq;
			req->rts_sbuf = sbuf;

			if (rc == MQ_RET_MATCH_OK)	/* we are in handler context, issue a reply */
				ptl_handle_rtsmatch_request(req, 1, tok);
			/* else will be called later */
			break;
		}
	}
	return;
}
コード例 #9
0
ファイル: ips_tid.c プロジェクト: 01org/opa-psm2
psm2_error_t
ips_tid_acquire(struct ips_tid *tidc,
		const void *buf, uint32_t *length,
		uint32_t *tid_array, uint32_t *tidcnt)
{
	struct ips_tid_ctrl *ctrl = tidc->tid_ctrl;
	psm2_error_t err = PSM2_OK;
	int rc;

	psmi_assert(((uintptr_t) buf & 0xFFF) == 0);
	psmi_assert(((*length) & 0xFFF) == 0);

	if (tidc->context->tid_ctrl)
		pthread_spin_lock(&ctrl->tid_ctrl_lock);

	if (!ctrl->tid_num_avail) {
		err = PSM2_EP_NO_RESOURCES;
		goto fail;
	}

	/* Clip length if it exceeds worst case tid allocation,
	   where each entry in the tid array can accomodate only
	   1 page. */
	if (*length > 4096*tidc->tid_ctrl->tid_num_max)
	{
		*length = 4096*tidc->tid_ctrl->tid_num_max;
	}

	rc = hfi_update_tid(tidc->context->ctrl,
		    (uint64_t) (uintptr_t) buf, length,
		    (uint64_t) (uintptr_t) tid_array, tidcnt);
	if (rc < 0) {
		/* Unable to pin pages? retry later */
		err = PSM2_EP_DEVICE_FAILURE;
		goto fail;
	}

	psmi_assert_always((*tidcnt) > 0);
	psmi_assert(ctrl->tid_num_avail >= (*tidcnt));
	ctrl->tid_num_avail -= (*tidcnt);
	tidc->tid_num_total += (*tidcnt);
	tidc->tid_num_inuse += (*tidcnt);

fail:
	if (tidc->context->tid_ctrl)
		pthread_spin_unlock(&ctrl->tid_ctrl_lock);

	return err;
}
コード例 #10
0
ファイル: ptl.c プロジェクト: 01org/opa-psm2
void
psmi_am_mq_handler_data(void *toki, psm2_amarg_t *args, int narg, void *buf,
			size_t len)
{
	amsh_am_token_t *tok = (amsh_am_token_t *) toki;

	psmi_assert(toki != NULL);

	psm2_epaddr_t epaddr = (psm2_epaddr_t) tok->tok.epaddr_incoming;
	psm2_mq_req_t req = mq_eager_match(tok->mq, epaddr, 0);	/* using seqnum 0 */
	psmi_assert_always(req != NULL);
	psmi_mq_handle_data(tok->mq, req, args[2].u32w0, buf, len);

	return;
}
コード例 #11
0
ファイル: ptl.c プロジェクト: 01org/opa-psm2
static
psm2_error_t
ptl_handle_rtsmatch_request(psm2_mq_req_t req, int was_posted,
			    amsh_am_token_t *tok)
{
	psm2_amarg_t args[5];
	psm2_epaddr_t epaddr = req->rts_peer;
	ptl_t *ptl = epaddr->ptlctl->ptl;
	int pid = 0;

	PSM2_LOG_MSG("entering.");
	psmi_assert((tok != NULL && was_posted)
		    || (tok == NULL && !was_posted));

	_HFI_VDBG("[shm][rndv][recv] req=%p dest=%p len=%d tok=%p\n",
		  req, req->buf, req->recv_msglen, tok);

	if ((ptl->psmi_kassist_mode & PSMI_KASSIST_GET)
	    && req->recv_msglen > 0
	    && (pid = psmi_epaddr_pid(epaddr))) {
		/* cma can be done in handler context or not. */
		size_t nbytes = cma_get(pid, (void *)req->rts_sbuf,
					req->buf, req->recv_msglen);
		psmi_assert_always(nbytes == req->recv_msglen);
	}

	args[0].u64w0 = (uint64_t) (uintptr_t) req->ptl_req_ptr;
	args[1].u64w0 = (uint64_t) (uintptr_t) req;
	args[2].u64w0 = (uint64_t) (uintptr_t) req->buf;
	args[3].u32w0 = req->recv_msglen;
	args[3].u32w1 = tok != NULL ? 1 : 0;
	args[4].u64w0 = 0;

	if (tok != NULL) {
		psmi_am_reqq_add(AMREQUEST_SHORT, tok->ptl,
				 tok->tok.epaddr_incoming, mq_handler_rtsmatch_hidx,
				 args, 5, NULL, 0, NULL, 0);
	} else
		psmi_amsh_short_request(ptl, epaddr, mq_handler_rtsmatch_hidx,
					args, 5, NULL, 0, 0);

	/* 0-byte completion or we used kassist */
	if (pid || req->recv_msglen == 0)
		psmi_mq_handle_rts_complete(req);
	PSM2_LOG_MSG("leaving.");
	return PSM2_OK;
}
コード例 #12
0
ファイル: ips_proto_am.c プロジェクト: 01org/opa-psm2
psm2_error_t
ips_am_short_reply(psm2_am_token_t tok,
		   psm2_handler_t handler, psm2_amarg_t *args, int nargs,
		   void *src, size_t len, int flags,
		   psm2_am_completion_fn_t completion_fn, void *completion_ctxt)
{
	struct ips_am_token *token = (struct ips_am_token *)tok;
	struct ips_proto_am *proto_am = token->proto_am;
	struct ips_epaddr *ipsaddr = token->epaddr_rail;
	int pad_bytes = calculate_pad_bytes(len);
	int scb_flags = 0;
	ips_scb_t *scb;

	if (!token->tok.can_reply) {
		_HFI_ERROR("Invalid AM reply for request!");
		return PSM2_AM_INVALID_REPLY;
	}

	psmi_assert(ips_scbctrl_avail(&proto_am->scbc_reply));

	if ((nargs << 3) + len <= (IPS_AM_HDR_NARGS << 3)) {
		scb = ips_scbctrl_alloc_tiny(&proto_am->scbc_reply);
	} else {
		int payload_sz = (nargs << 3);

		payload_sz += (flags & PSM2_AM_FLAG_ASYNC) ?
			      0 : (len + pad_bytes);
		scb_flags |= (payload_sz > (IPS_AM_HDR_NARGS << 3)) ?
		    IPS_SCB_FLAG_ADD_BUFFER : 0;

		scb =
		    ips_scbctrl_alloc(&proto_am->scbc_reply, 1, payload_sz,
				      scb_flags);
	}

	psmi_assert_always(scb != NULL);
	ips_am_scb_init(scb, handler, nargs, pad_bytes,
			completion_fn, completion_ctxt);
	am_short_reqrep(scb, ipsaddr, args, nargs, OPCODE_AM_REPLY,
			src, len, flags, pad_bytes);
	return PSM2_OK;
}
コード例 #13
0
ファイル: ptl.c プロジェクト: 01org/opa-psm2
void
psmi_am_mq_handler_rtsmatch(void *toki, psm2_amarg_t *args, int narg, void *buf,
			    size_t len)
{
	amsh_am_token_t *tok = (amsh_am_token_t *) toki;

	psmi_assert(toki != NULL);

	ptl_t *ptl = tok->ptl;
	psm2_mq_req_t sreq = (psm2_mq_req_t) (uintptr_t) args[0].u64w0;
	void *dest = (void *)(uintptr_t) args[2].u64w0;
	uint32_t msglen = args[3].u32w0;
	psm2_amarg_t rarg[1];

	_HFI_VDBG("[rndv][send] req=%p dest_req=%p src=%p dest=%p len=%d\n",
		  sreq, (void *)(uintptr_t) args[1].u64w0, sreq->buf, dest,
		  msglen);

	if (msglen > 0) {
		rarg[0].u64w0 = args[1].u64w0;	/* rreq */
		int kassist_mode = ptl->psmi_kassist_mode;

		if (kassist_mode & PSMI_KASSIST_PUT) {
			int pid = psmi_epaddr_pid(tok->tok.epaddr_incoming);

			size_t nbytes = cma_put(sreq->buf, pid, dest, msglen);
			psmi_assert_always(nbytes == msglen);

			/* Send response that PUT is complete */
			psmi_amsh_short_reply(tok, mq_handler_rtsdone_hidx,
					      rarg, 1, NULL, 0, 0);
		} else if (!(kassist_mode & PSMI_KASSIST_MASK)) {
			/* Only transfer if kassist is off, i.e. neither GET nor PUT. */
			psmi_amsh_long_reply(tok, mq_handler_rtsdone_hidx, rarg,
					     1, sreq->buf, msglen, dest, 0);
		}

	}
	psmi_mq_handle_rts_complete(sreq);
}
コード例 #14
0
ファイル: psm_am.c プロジェクト: 01org/psm
psm_error_t
__psm_am_reply_short(psm_am_token_t token, psm_handler_t handler, 
		     psm_amarg_t *args, int nargs, void *src, size_t len, 
		     int flags, psm_am_completion_fn_t completion_fn,
		     void *completion_ctxt)
{
    psm_error_t err;
    struct psmi_am_token *tok = (struct psmi_am_token *)token;
    psm_epaddr_t epaddr = tok->epaddr_from;
    ptl_ctl_t *ptlc = epaddr->ptlctl;

    psmi_assert_always(token != NULL);

    /* No locking here since we are already within handler context and already
     * locked */

    PSMI_ASSERT_INITIALIZED();

    err =  ptlc->am_short_reply(token, handler, args, 
				nargs, src, len, flags, completion_fn,
				completion_ctxt);
    return err;
}
コード例 #15
0
ファイル: ips_subcontext.c プロジェクト: 01org/opa-psm2
psm2_error_t
ips_subcontext_ureg_get(ptl_t *ptl, uint32_t subcontext_cnt,
			psmi_context_t *context,
			struct ips_subcontext_ureg **uregp)
{
	const struct hfi1_base_info *base_info = &context->ctrl->base_info;
	uintptr_t all_subcontext_uregbase =
	    (uintptr_t) base_info->subctxt_uregbase;
	int i;

	psmi_assert_always(all_subcontext_uregbase != 0);
	for (i = 0; i < HFI1_MAX_SHARED_CTXTS; i++) {
		struct ips_subcontext_ureg *subcontext_ureg =
		    (struct ips_subcontext_ureg *)all_subcontext_uregbase;
		*uregp++ = (i < subcontext_cnt) ? subcontext_ureg : NULL;
		all_subcontext_uregbase += sizeof(struct ips_subcontext_ureg);
	}

	ptl->recvshc->hwcontext_ctrl =
	    (struct ips_hwcontext_ctrl *)all_subcontext_uregbase;
	all_subcontext_uregbase += sizeof(struct ips_hwcontext_ctrl);

	context->spio_ctrl = (void *)all_subcontext_uregbase;
	all_subcontext_uregbase += sizeof(struct ips_spio_ctrl);

	context->tid_ctrl = (void *)all_subcontext_uregbase;
	all_subcontext_uregbase += sizeof(struct ips_tid_ctrl);

	context->tf_ctrl = (void *)all_subcontext_uregbase;
	all_subcontext_uregbase += sizeof(struct ips_tf_ctrl);

	psmi_assert((all_subcontext_uregbase -
		     (uintptr_t) base_info->subctxt_uregbase) <= PSMI_PAGESIZE);

	return PSM2_OK;
}
コード例 #16
0
ファイル: ips_tidcache.c プロジェクト: 01org/opa-psm2
/*
 * Register a new buffer with driver, and cache the tidinfo.
 */
static psm2_error_t
ips_tidcache_register(struct ips_tid *tidc,
		unsigned long start, uint32_t length, uint32_t *firstidx)
{
	cl_qmap_t *p_map = &tidc->tid_cachemap;
	uint32_t tidoff, tidlen;
	uint32_t idx, tidcnt;
	psm2_error_t err;

	/*
	 * make sure we have at least one free tid to
	 * register the new buffer.
	 */
	if (NTID == tidc->tid_cachesize) {
		/* all tids are in active use, error? */
		if (NIDLE == 0)
			return PSM2_OK_NO_PROGRESS;

		/*
		 * free the first tid in idle queue.
		 */
		idx = IPREV(IHEAD);
		tidc->tid_array[0] = p_map->root[idx].payload.tidinfo;
		err = ips_tidcache_remove(tidc, 1);
		if (err)
			return err;
	}
	psmi_assert(NTID < tidc->tid_cachesize);

	/* Clip length if it exceeds worst case tid allocation,
	   where each entry in the tid array can accomodate only
	   1 page. */
	if (length > 4096*tidc->tid_ctrl->tid_num_max)
	{
		length = 4096*tidc->tid_ctrl->tid_num_max;
	}
	/*
	 * register the new buffer.
	 */

retry:
	tidcnt = 0;
	if (hfi_update_tid(tidc->context->ctrl,
			(uint64_t) start, &length,
			(uint64_t) tidc->tid_array, &tidcnt) < 0) {
		/* if driver reaches lockable memory limit */
		if (errno == ENOMEM && NIDLE) {
			uint64_t lengthEvicted = ips_tidcache_evict(tidc,length);

			if (lengthEvicted >= length)
				goto retry;
		}

		/* Unable to pin pages? retry later */
		return PSM2_EP_DEVICE_FAILURE;
	}
	psmi_assert_always(tidcnt > 0);
	psmi_assert((tidcnt+NTID) <= tidc->tid_cachesize);

	/*
	 * backward processing because we want to return
	 * the first RB index in the array.
	 */
	idx = 0;
	tidoff = length;
	while (tidcnt) {
		/*
		 * Driver only returns tidctrl=1 or tidctrl=2.
		 */
		tidcnt--;
		idx = 2*IPS_TIDINFO_GET_TID(tidc->tid_array[tidcnt]) +
			IPS_TIDINFO_GET_TIDCTRL(tidc->tid_array[tidcnt]);
		tidlen = IPS_TIDINFO_GET_LENGTH(tidc->tid_array[tidcnt]);

		/*
		 * sanity check.
		 */
		psmi_assert(idx != 0);
		psmi_assert(idx <= tidc->tid_ctrl->tid_num_max);
		psmi_assert(INVALIDATE(idx) != 0);
		psmi_assert(REFCNT(idx) == 0);

		/*
		 * clear the tid invalidated.
		 */
		INVALIDATE(idx) = 0;

		/*
		 * put the tid into a RB node.
		 */
		tidoff -= tidlen << 12;
		START(idx) = start + tidoff;
		LENGTH(idx) = tidlen;
		p_map->root[idx].payload.tidinfo = tidc->tid_array[tidcnt];

		/*
		 * put the node into RB tree and idle queue head.
		 */
		IDLE_INSERT(idx);
		ips_cl_qmap_insert_item(p_map, &p_map->root[idx]);
	}
	psmi_assert(idx != 0);
	psmi_assert(tidoff == 0);
	*firstidx = idx;

	return PSM2_OK;
}
コード例 #17
0
ファイル: psm_ep_connect.c プロジェクト: 01org/opa-psm2
psm2_error_t
__psm2_ep_connect(psm2_ep_t ep, int num_of_epid, psm2_epid_t const *array_of_epid,
		 int const *array_of_epid_mask,	/* can be NULL */
		 psm2_error_t *array_of_errors, psm2_epaddr_t *array_of_epaddr,
		 int64_t timeout)
{
	psm2_error_t err = PSM2_OK;
	ptl_ctl_t *ptlctl;
	ptl_t *ptl;
	int i, j, dup_idx;
	int num_toconnect = 0;
	int *epid_mask = NULL;
	int *epid_mask_isdupof = NULL;
	char *device;
	uint64_t t_start = get_cycles();
	uint64_t t_left;
	union psmi_envvar_val timeout_intval;

	PSM2_LOG_MSG("entering");
	PSMI_ERR_UNLESS_INITIALIZED(ep);

	PSMI_PLOCK();

	/*
	 * Normally we would lock here, but instead each implemented ptl component
	 * does its own locking.  This is mostly because the ptl components are
	 * ahead of the PSM interface in that they can disconnect their peers.
	 */
	if (ep == NULL || array_of_epaddr == NULL || array_of_epid == NULL ||
	    num_of_epid < 1) {
		err = psmi_handle_error(ep, PSM2_PARAM_ERR,
					"Invalid psm2_ep_connect parameters");
		goto fail;
	}

	/* We need two of these masks to detect duplicates */
	err = PSM2_NO_MEMORY;
	epid_mask =
	    (int *)psmi_malloc(ep, UNDEFINED, sizeof(int) * num_of_epid);
	if (epid_mask == NULL)
		goto fail;
	epid_mask_isdupof =
	    (int *)psmi_malloc(ep, UNDEFINED, sizeof(int) * num_of_epid);
	if (epid_mask_isdupof == NULL)
		goto fail;
	err = PSM2_OK;

	/* Eventually handle timeouts across all connects. */
	for (j = 0; j < num_of_epid; j++) {
		if (array_of_epid_mask != NULL && !array_of_epid_mask[j])
			epid_mask[j] = 0;
		else {
			epid_mask[j] = 1;
			array_of_errors[j] = PSM2_EPID_UNKNOWN;
			array_of_epaddr[j] = NULL;
			num_toconnect++;
		}
		epid_mask_isdupof[j] = -1;
	}

	psmi_getenv("PSM2_CONNECT_TIMEOUT",
		    "End-point connection timeout over-ride. 0 for no time-out.",
		    PSMI_ENVVAR_LEVEL_USER, PSMI_ENVVAR_TYPE_UINT,
		    (union psmi_envvar_val)0, &timeout_intval);

	if (getenv("PSM2_CONNECT_TIMEOUT")) {
		timeout = timeout_intval.e_uint * SEC_ULL;
	} else if (timeout > 0) {
		/* The timeout parameter provides the minimum timeout. A heuristic
		 * is used to scale up the timeout linearly with the number of
		 * endpoints, and we allow one second per 100 endpoints. */
		timeout = max(timeout, (num_toconnect * SEC_ULL) / 100);
	}

	if (timeout > 0 && timeout < PSMI_MIN_EP_CONNECT_TIMEOUT)
		timeout = PSMI_MIN_EP_CONNECT_TIMEOUT;
	_HFI_PRDBG("Connect to %d endpoints with time-out of %.2f secs\n",
		   num_toconnect, (double)timeout / 1e9);

	/* Look for duplicates in input array */
	for (i = 0; i < num_of_epid; i++) {
		for (j = i + 1; j < num_of_epid; j++) {
			if (array_of_epid[i] == array_of_epid[j] &&
			    epid_mask[i] && epid_mask[j]) {
				epid_mask[j] = 0;	/* don't connect more than once */
				epid_mask_isdupof[j] = i;
			}
		}
	}

	for (i = 0; i < PTL_MAX_INIT; i++) {
		if (ep->devid_enabled[i] == -1)
			continue;
		/* Set up the right connect ptrs */
		switch (ep->devid_enabled[i]) {
		case PTL_DEVID_IPS:
			ptlctl = &ep->ptl_ips;
			ptl = ep->ptl_ips.ptl;
			device = "ips";
			break;
		case PTL_DEVID_AMSH:
			ptlctl = &ep->ptl_amsh;
			ptl = ep->ptl_amsh.ptl;
			device = "amsh";
			break;
		case PTL_DEVID_SELF:
			ptlctl = &ep->ptl_self;
			ptl = ep->ptl_self.ptl;
			device = "self";
			break;
		default:
			device = "unknown";
			ptlctl = &ep->ptl_ips;	/*no-unused */
			ptl = ep->ptl_ips.ptl;	/*no-unused */
			device = "ips";	/*no-unused */
			psmi_handle_error(PSMI_EP_NORETURN, PSM2_INTERNAL_ERR,
					  "Unknown/unhandled PTL id %d\n",
					  ep->devid_enabled[i]);
			break;
		}
		t_left = psmi_cycles_left(t_start, timeout);

		_HFI_VDBG("Trying to connect with device %s\n", device);
		if ((err = ptlctl->ep_connect(ptl, num_of_epid, array_of_epid,
					      epid_mask, array_of_errors,
					      array_of_epaddr,
					      cycles_to_nanosecs(t_left)))) {
			_HFI_PRDBG("Connect failure in device %s err=%d\n",
				   device, err);
			goto connect_fail;
		}

		/* Now process what's been connected */
		for (j = 0; j < num_of_epid; j++) {
			dup_idx = epid_mask_isdupof[j];
			if (!epid_mask[j] && dup_idx == -1)
				continue;

			if (dup_idx != -1) {	/* dup */
				array_of_epaddr[j] = array_of_epaddr[dup_idx];
				array_of_errors[j] = array_of_errors[dup_idx];
				epid_mask_isdupof[j] = -1;
			}

			if (array_of_errors[j] == PSM2_OK) {
				epid_mask[j] = 0;	/* don't try on next ptl */
				ep->connections++;
			}
		}
	}

	for (i = 0; i < num_of_epid; i++) {
		ptl_ctl_t *c = NULL;
		if (array_of_epid_mask != NULL && !array_of_epid_mask[i])
			continue;
		/* If we see unreachable here, that means some PTLs were not enabled */
		if (array_of_errors[i] == PSM2_EPID_UNREACHABLE) {
			err = PSM2_EPID_UNREACHABLE;
			break;
		}

		psmi_assert_always(array_of_epaddr[i] != NULL);
		c = array_of_epaddr[i]->ptlctl;
		psmi_assert_always(c != NULL);
		_HFI_VDBG("%-20s DEVICE %s (%p)\n",
			  psmi_epaddr_get_name(array_of_epid[i]),
			  c == &ep->ptl_ips ? "hfi" :
			  (c == &ep->ptl_amsh ? "amsh" : "self"),
			  (void *)array_of_epaddr[i]->ptlctl->ptl);
	}

connect_fail:
	/* If the error is a timeout (at worse) and the client is OPA MPI,
	 * just return timeout to let OPA MPI handle the hostnames that
	 * timed out */
	if (err != PSM2_OK) {
		char errbuf[PSM2_ERRSTRING_MAXLEN];
		size_t len;
		int j = 0;

		if (err == PSM2_EPID_UNREACHABLE) {
			char *deverr = "of an incorrect setting";
			char *eperr = " ";
			char *devname = NULL;
			if (!psmi_ep_device_is_enabled(ep, PTL_DEVID_AMSH)) {
				deverr =
				    "there is no shared memory PSM device (shm)";
				eperr = " shared memory ";
			} else
			    if (!psmi_ep_device_is_enabled(ep, PTL_DEVID_IPS)) {
				deverr =
				    "there is no OPA PSM device (hfi)";
				eperr = " OPA ";
			}

			len = snprintf(errbuf, sizeof(errbuf) - 1,
				       "Some%sendpoints could not be connected because %s "
				       "in the currently enabled PSM_DEVICES (",
				       eperr, deverr);
			for (i = 0; i < PTL_MAX_INIT && len < sizeof(errbuf) - 1;
			     i++) {
				switch (ep->devid_enabled[i]) {
				case PTL_DEVID_IPS:
					devname = "hfi";
					break;
				case PTL_DEVID_AMSH:
					devname = "shm";
					break;
				case PTL_DEVID_SELF:
				default:
					devname = "self";
					break;
				}
				len +=
				    snprintf(errbuf + len,
					     sizeof(errbuf) - len - 1, "%s,",
					     devname);
			}
			if (len < sizeof(errbuf) - 1 && devname != NULL)
				/* parsed something, remove trailing comma */
				errbuf[len - 1] = ')';
		} else
			len = snprintf(errbuf, sizeof(errbuf) - 1,
				       "%s", err == PSM2_TIMEOUT ?
				       "Dectected connection timeout" :
				       psm2_error_get_string(err));

		/* first pass, look for all nodes with the error */
		for (i = 0; i < num_of_epid && len < sizeof(errbuf) - 1; i++) {
			if (array_of_epid_mask != NULL
			    && !array_of_epid_mask[i])
				continue;
			if (array_of_errors[i] == PSM2_OK)
				continue;
			if (array_of_errors[i] == PSM2_EPID_UNREACHABLE &&
			    err != PSM2_EPID_UNREACHABLE)
				continue;
			if (err == array_of_errors[i]) {
				len +=
				    snprintf(errbuf + len,
					     sizeof(errbuf) - len - 1, "%c %s",
					     j == 0 ? ':' : ',',
					     psmi_epaddr_get_hostname
					     (array_of_epid[i]));
				j++;
			}
		}
		errbuf[sizeof(errbuf) - 1] = '\0';
		err = psmi_handle_error(ep, err, errbuf);
	}

fail:
	PSMI_PUNLOCK();

	if (epid_mask != NULL)
		psmi_free(epid_mask);
	if (epid_mask_isdupof != NULL)
		psmi_free(epid_mask_isdupof);

	PSM2_LOG_MSG("leaving");
	return err;
}
コード例 #18
0
ファイル: psm_ep.c プロジェクト: michich/opa-psm2
psm_error_t __psm_ep_close(psm_ep_t ep, int mode, int64_t timeout_in)
{
	psm_error_t err = PSM_OK;
	uint64_t t_start = get_cycles();
	union psmi_envvar_val timeout_intval;
	psm_ep_t tmp, mep;

	PSMI_ERR_UNLESS_INITIALIZED(ep);
	psmi_assert_always(ep->mctxt_master == ep);

	PSMI_PLOCK();

	if (psmi_opened_endpoint == NULL) {
		err = psmi_handle_error(NULL, PSM_EP_WAS_CLOSED,
					"PSM Endpoint is closed or does not exist");
		return err;
	}

	tmp = psmi_opened_endpoint;
	while (tmp && tmp != ep) {
		tmp = tmp->user_ep_next;
	}
	if (!tmp) {
		err = psmi_handle_error(NULL, PSM_EP_WAS_CLOSED,
					"PSM Endpoint is closed or does not exist");
		return err;
	}

	psmi_getenv("PSM_CLOSE_TIMEOUT",
		    "End-point close timeout over-ride.",
		    PSMI_ENVVAR_LEVEL_USER, PSMI_ENVVAR_TYPE_UINT,
		    (union psmi_envvar_val)0, &timeout_intval);

	if (getenv("PSM_CLOSE_TIMEOUT")) {
		timeout_in = timeout_intval.e_uint * SEC_ULL;
	} else if (timeout_in > 0) {
		/* The timeout parameter provides the minimum timeout. A heuristic
		 * is used to scale up the timeout linearly with the number of
		 * endpoints, and we allow one second per 100 endpoints. */
		timeout_in = max(timeout_in, (ep->connections * SEC_ULL) / 100);
	}

	if (timeout_in > 0 && timeout_in < PSMI_MIN_EP_CLOSE_TIMEOUT)
		timeout_in = PSMI_MIN_EP_CLOSE_TIMEOUT;

	/* Infinite and excessive close time-out are limited here to a max.
	 * The "rationale" is that there is no point waiting around forever for
	 * graceful termination. Normal (or forced) process termination should clean
	 * up the context state correctly even if termination is not graceful. */
	if (timeout_in <= 0 || timeout_in < PSMI_MAX_EP_CLOSE_TIMEOUT)
		timeout_in = PSMI_MAX_EP_CLOSE_TIMEOUT;
	_HFI_PRDBG("Closing endpoint %p with force=%s and to=%.2f seconds and "
		   "%d connections\n",
		   ep, mode == PSM_EP_CLOSE_FORCE ? "YES" : "NO",
		   (double)timeout_in / 1e9, (int)ep->connections);

	/* XXX We currently cheat in the sense that we leave each PTL the allowed
	 * timeout.  There's no good way to do this until we change the PTL
	 * interface to allow asynchronous finalization
	 */
	mep = ep;
	tmp = ep->mctxt_prev;
	do {
		ep = tmp;
		tmp = ep->mctxt_prev;
		PSM_MCTXT_REMOVE(ep);
		if (psmi_ep_device_is_enabled(ep, PTL_DEVID_AMSH))
			err =
			    psmi_ptl_amsh.fini(ep->ptl_amsh.ptl, mode,
					       timeout_in);

		if ((err == PSM_OK || err == PSM_TIMEOUT) &&
		    psmi_ep_device_is_enabled(ep, PTL_DEVID_IPS))
			err =
			    psmi_ptl_ips.fini(ep->ptl_ips.ptl, mode,
					      timeout_in);

		/* If there's timeouts in the disconnect requests,
		 * still make sure that we still get to close the
		 *endpoint and mark it closed */
		if (psmi_ep_device_is_enabled(ep, PTL_DEVID_IPS))
			psmi_context_close(&ep->context);

		psmi_free(ep->epaddr);
		psmi_free(ep->context_mylabel);
		/*
		 * Before freeing the master ep itself,
		 * remove it from the global linklist.
		 * We do it here to let atexit handler in ptl_am directory
		 * to search the global linklist and free the shared memory file.
		 */
		if (ep == mep) {
			if (psmi_opened_endpoint == ep) {
				psmi_opened_endpoint = ep->user_ep_next;
			} else {
				tmp = psmi_opened_endpoint;
				while (tmp->user_ep_next != ep) {
					tmp = tmp->user_ep_next;
				}
				tmp->user_ep_next = ep->user_ep_next;
			}
			psmi_opened_endpoint_count--;
		}
		psmi_free(ep);

	} while ((err == PSM_OK || err == PSM_TIMEOUT) && tmp != ep);

	PSMI_PUNLOCK();

	_HFI_PRDBG("Closed endpoint in %.3f secs\n",
		   (double)cycles_to_nanosecs(get_cycles() -
					      t_start) / SEC_ULL);
	return err;
}
コード例 #19
0
ファイル: psm_ep.c プロジェクト: michich/opa-psm2
psm_error_t
__psm_ep_open_internal(psm_uuid_t const unique_job_key, int *devid_enabled,
		       struct psm_ep_open_opts const *opts_i, psm_mq_t mq,
		       psm_ep_t *epo, psm_epid_t *epido)
{
	psm_ep_t ep = NULL;
	uint32_t num_units;
	size_t len;
	psm_error_t err;
	psm_epaddr_t epaddr = NULL;
	char buf[128], *p, *e;
	union psmi_envvar_val envvar_val;
	size_t ptl_sizes;
	struct psm_ep_open_opts opts;
	ptl_t *amsh_ptl, *ips_ptl, *self_ptl;
	int i;

	/* First get the set of default options, we overwrite with the user's
	 * desired values afterwards */
	if ((err = psm_ep_open_opts_get_defaults(&opts)))
		goto fail;

	if (opts_i != NULL) {
		if (opts_i->timeout != -1)
			opts.timeout = opts_i->timeout;
		if (opts_i->unit != -1)
			opts.unit = opts_i->unit;
		if (opts_i->affinity != -1)
			opts.affinity = opts_i->affinity;

		if (opts_i->sendbufs_num != -1)
			opts.sendbufs_num = opts_i->sendbufs_num;

		if (opts_i->network_pkey != HFI_DEFAULT_P_KEY)
			opts.network_pkey = opts_i->network_pkey;

		if (opts_i->port != 0)
			opts.port = opts_i->port;

		if (opts_i->outsl != -1)
			opts.outsl = opts_i->outsl;

		if (opts_i->service_id)
			opts.service_id = (uint64_t) opts_i->service_id;
		if (opts_i->path_res_type != PSM_PATH_RES_NONE)
			opts.path_res_type = opts_i->path_res_type;

		if (opts_i->senddesc_num)
			opts.senddesc_num = opts_i->senddesc_num;
		if (opts_i->imm_size)
			opts.imm_size = opts_i->imm_size;
	}

	/* Get Service ID from environment */
	if (!psmi_getenv("PSM_IB_SERVICE_ID",
			 "HFI Service ID for path resolution",
			 PSMI_ENVVAR_LEVEL_USER,
			 PSMI_ENVVAR_TYPE_ULONG_ULONG,
			 (union psmi_envvar_val)HFI_DEFAULT_SERVICE_ID,
			 &envvar_val)) {
		opts.service_id = (uint64_t) envvar_val.e_ulonglong;
	}

	/* Get Path resolution type from environment Possible choices are:
	 *
	 * NONE : Default same as previous instances. Utilizes static data.
	 * OPP  : Use OFED Plus Plus library to do path record queries.
	 * UMAD : Use raw libibumad interface to form and process path records.
	 */
	if (!psmi_getenv("PSM_PATH_REC",
			 "Mechanism to query HFI path record (default is no path query)",
			 PSMI_ENVVAR_LEVEL_USER, PSMI_ENVVAR_TYPE_STR,
			 (union psmi_envvar_val)"none", &envvar_val)) {
		if (!strcasecmp(envvar_val.e_str, "none"))
			opts.path_res_type = PSM_PATH_RES_NONE;
		else if (!strcasecmp(envvar_val.e_str, "opp"))
			opts.path_res_type = PSM_PATH_RES_OPP;
		else if (!strcasecmp(envvar_val.e_str, "umad"))
			opts.path_res_type = PSM_PATH_RES_UMAD;
		else {
			_HFI_ERROR("Unknown path resolution type %s. "
				   "Disabling use of path record query.\n",
				   envvar_val.e_str);
			opts.path_res_type = PSM_PATH_RES_NONE;
		}
	}

	/* If a specific unit is set in the environment, use that one. */
	if (!psmi_getenv("HFI_UNIT", "Device Unit number (-1 autodetects)",
			 PSMI_ENVVAR_LEVEL_USER, PSMI_ENVVAR_TYPE_LONG,
			 (union psmi_envvar_val)HFI_UNIT_ID_ANY, &envvar_val)) {
		opts.unit = envvar_val.e_long;
	}

	/* Get user specified port number to use. */
	if (!psmi_getenv("HFI_PORT", "IB Port number (0 autodetects)",
			 PSMI_ENVVAR_LEVEL_USER, PSMI_ENVVAR_TYPE_LONG,
			 (union psmi_envvar_val)HFI_PORT_NUM_ANY,
			 &envvar_val)) {
		opts.port = envvar_val.e_long;
	}

	/* Get service level from environment, path-query overrides it */
	if (!psmi_getenv
	    ("HFI_SL", "HFI outging ServiceLevel number (default 0)",
	     PSMI_ENVVAR_LEVEL_USER, PSMI_ENVVAR_TYPE_LONG,
	     (union psmi_envvar_val)PSMI_SL_DEFAULT, &envvar_val)) {
		opts.outsl = envvar_val.e_long;
	}

	/* Get network key from environment. MVAPICH and other vendor MPIs do not
	 * specify it on ep open and we may require it for vFabrics.
	 * path-query will override it.
	 */
	if (!psmi_getenv("PSM_PKEY",
			 "HFI PKey to use for endpoint",
			 PSMI_ENVVAR_LEVEL_USER,
			 PSMI_ENVVAR_TYPE_ULONG,
			 (union psmi_envvar_val)HFI_DEFAULT_P_KEY,
			 &envvar_val)) {
		opts.network_pkey = (uint64_t) envvar_val.e_ulong;
	}

	/* BACKWARDS COMPATIBILITY:  Open MPI likes to choose its own PKEY of
	   0x7FFF.  That's no longer a valid default, so override it if the
	   client was compiled against PSM v1 */
	if (PSMI_VERNO_GET_MAJOR(psmi_verno_client()) < 2 &&
			opts.network_pkey == 0x7FFF) {
		opts.network_pkey = HFI_DEFAULT_P_KEY;
	}

	/* Get number of default send buffers from environment */
	if (!psmi_getenv("PSM_NUM_SEND_BUFFERS",
			 "Number of send buffers to allocate [1024]",
			 PSMI_ENVVAR_LEVEL_USER,
			 PSMI_ENVVAR_TYPE_UINT,
			 (union psmi_envvar_val)1024, &envvar_val)) {
		opts.sendbufs_num = envvar_val.e_uint;
	}

	/* Get immediate data size - transfers less than immediate data size do
	 * not consume a send buffer and require just a send descriptor.
	 */
	if (!psmi_getenv("PSM_SEND_IMMEDIATE_SIZE",
			 "Immediate data send size not requiring a buffer [128]",
			 PSMI_ENVVAR_LEVEL_USER,
			 PSMI_ENVVAR_TYPE_UINT,
			 (union psmi_envvar_val)128, &envvar_val)) {
		opts.imm_size = envvar_val.e_uint;
	}

	/* Get numner of send descriptors - by default this is 4 times the number
	 * of send buffers - mainly used for short/inlined messages.
	 */
	if (!psmi_getenv("PSM_NUM_SEND_DESCRIPTORS",
			 "Number of send descriptors to allocate [4096]",
			 PSMI_ENVVAR_LEVEL_USER,
			 PSMI_ENVVAR_TYPE_UINT,
			 (union psmi_envvar_val)4096, &envvar_val)) {
		opts.senddesc_num = envvar_val.e_uint;
	}

	if (psmi_device_is_enabled(devid_enabled, PTL_DEVID_IPS)) {
		if ((err = psm_ep_num_devunits(&num_units)) != PSM_OK)
			goto fail;
	} else
		num_units = 0;

	/* do some error checking */
	if (opts.timeout < -1) {
		err = psmi_handle_error(NULL, PSM_PARAM_ERR,
					"Invalid timeout value %lld",
					(long long)opts.timeout);
		goto fail;
	} else if (num_units && (opts.unit < -1 || opts.unit >= (int)num_units)) {
		err = psmi_handle_error(NULL, PSM_PARAM_ERR,
					"Invalid Device Unit ID %d (%d units found)",
					opts.unit, num_units);
		goto fail;
	} else if (opts.port < 0 || opts.port > HFI_MAX_PORT) {
		err = psmi_handle_error(NULL, PSM_PARAM_ERR,
					"Invalid Device port number %d",
					opts.port);
		goto fail;
	} else if (opts.affinity < 0
		   || opts.affinity > PSM_EP_OPEN_AFFINITY_FORCE) {
		err =
		    psmi_handle_error(NULL, PSM_PARAM_ERR,
				      "Invalid Affinity option: %d",
				      opts.affinity);
		goto fail;
	} else if (opts.outsl < PSMI_SL_MIN || opts.outsl > PSMI_SL_MAX) {
		err = psmi_handle_error(NULL, PSM_PARAM_ERR,
					"Invalid SL number: %lld",
					(unsigned long long)opts.outsl);
		goto fail;
	}

	/* Set environment variable if PSM is not allowed to set affinity */
	if (opts.affinity == PSM_EP_OPEN_AFFINITY_SKIP)
		setenv("HFI_NO_CPUAFFINITY", "1", 1);

	/* Allocate end point structure storage */
	ptl_sizes =
	    (psmi_device_is_enabled(devid_enabled, PTL_DEVID_SELF) ?
	     psmi_ptl_self.sizeof_ptl() : 0) +
	    (psmi_device_is_enabled(devid_enabled, PTL_DEVID_IPS) ?
	     psmi_ptl_ips.sizeof_ptl() : 0) +
	    (psmi_device_is_enabled(devid_enabled, PTL_DEVID_AMSH) ?
	     psmi_ptl_amsh.sizeof_ptl() : 0);
	if (ptl_sizes == 0)
		return PSM_EP_NO_DEVICE;

	ep = (psm_ep_t) psmi_memalign(PSMI_EP_NONE, UNDEFINED, 64,
				      sizeof(struct psm_ep) + ptl_sizes);
	epaddr = (psm_epaddr_t) psmi_calloc(PSMI_EP_NONE, PER_PEER_ENDPOINT,
					    1, sizeof(struct psm_epaddr));
	if (ep == NULL || epaddr == NULL) {
		err = psmi_handle_error(NULL, PSM_NO_MEMORY,
					"Couldn't allocate memory for %s structure",
					ep == NULL ? "psm_ep" : "psm_epaddr");
		goto fail;
	}

	/* Copy PTL enabled status */
	for (i = 0; i < PTL_MAX_INIT; i++)
		ep->devid_enabled[i] = devid_enabled[i];

	/* Matched Queue initialization.  We do this early because we have to
	 * make sure ep->mq exists and is valid before calling ips_do_work.
	 */
	ep->mq = mq;

	/* Get ready for PTL initialization */
	memcpy(&ep->uuid, (void *)unique_job_key, sizeof(psm_uuid_t));
	ep->epaddr = epaddr;
	ep->memmode = mq->memmode;
	ep->hfi_num_sendbufs = opts.sendbufs_num;
	ep->service_id = opts.service_id;
	ep->path_res_type = opts.path_res_type;
	ep->hfi_num_descriptors = opts.senddesc_num;
	ep->hfi_imm_size = opts.imm_size;
	ep->errh = psmi_errhandler_global;	/* by default use the global one */
	ep->ptl_amsh.ep_poll = psmi_poll_noop;
	ep->ptl_ips.ep_poll = psmi_poll_noop;
	ep->connections = 0;

	/* See how many iterations we want to spin before yielding */
	psmi_getenv("PSM_YIELD_SPIN_COUNT",
		    "Spin poll iterations before yield",
		    PSMI_ENVVAR_LEVEL_HIDDEN,
		    PSMI_ENVVAR_TYPE_UINT,
		    (union psmi_envvar_val)PSMI_BLOCKUNTIL_POLLS_BEFORE_YIELD,
		    &envvar_val);
	ep->yield_spin_cnt = envvar_val.e_uint;

	ptl_sizes = 0;
	amsh_ptl = ips_ptl = self_ptl = NULL;
	if (psmi_ep_device_is_enabled(ep, PTL_DEVID_AMSH)) {
		amsh_ptl = (ptl_t *) (ep->ptl_base_data + ptl_sizes);
		ptl_sizes += psmi_ptl_amsh.sizeof_ptl();
	}
	if (psmi_ep_device_is_enabled(ep, PTL_DEVID_IPS)) {
		ips_ptl = (ptl_t *) (ep->ptl_base_data + ptl_sizes);
		ptl_sizes += psmi_ptl_ips.sizeof_ptl();
	}
	if (psmi_ep_device_is_enabled(ep, PTL_DEVID_SELF)) {
		self_ptl = (ptl_t *) (ep->ptl_base_data + ptl_sizes);
		ptl_sizes += psmi_ptl_self.sizeof_ptl();
	}

	if ((err = psmi_ep_open_device(ep, &opts, unique_job_key,
				       &(ep->context), &ep->epid)))
		goto fail;

	psmi_assert_always(ep->epid != 0);
	ep->epaddr->epid = ep->epid;

	_HFI_VDBG("psmi_ep_open_device() passed\n");

	/* Set our new label as soon as we know what it is */
	strncpy(buf, psmi_gethostname(), sizeof(buf) - 1);
	buf[sizeof(buf) - 1] = '\0';

	p = buf + strlen(buf);

	/* If our rank is set, use it. If not, use context.subcontext notation */
	if (((e = getenv("MPI_RANKID")) != NULL && *e) ||
	    ((e = getenv("PSC_MPI_RANK")) != NULL && *e))
		len = snprintf(p, sizeof(buf) - strlen(buf), ":%d.", atoi(e));
	else
		len = snprintf(p, sizeof(buf) - strlen(buf), ":%d.%d.",
			       (uint32_t) psm_epid_context(ep->epid),
			       (uint32_t) psmi_epid_subcontext(ep->epid));
	*(p + len) = '\0';
	ep->context_mylabel = psmi_strdup(ep, buf);
	if (ep->context_mylabel == NULL) {
		err = PSM_NO_MEMORY;
		goto fail;
	}
	/* hfi_set_mylabel(ep->context_mylabel); */

	if ((err = psmi_epid_set_hostname(psm_epid_nid(ep->epid), buf, 0)))
		goto fail;

	_HFI_VDBG("start ptl device init...\n");
	if (psmi_ep_device_is_enabled(ep, PTL_DEVID_SELF)) {
		if ((err = psmi_ptl_self.init(ep, self_ptl, &ep->ptl_self)))
			goto fail;
	}
	if (psmi_ep_device_is_enabled(ep, PTL_DEVID_IPS)) {
		if ((err = psmi_ptl_ips.init(ep, ips_ptl, &ep->ptl_ips)))
			goto fail;
	}
	/* If we're shm-only, this device is enabled above */
	if (psmi_ep_device_is_enabled(ep, PTL_DEVID_AMSH)) {
		if ((err = psmi_ptl_amsh.init(ep, amsh_ptl, &ep->ptl_amsh)))
			goto fail;
	} else {
		/* We may have pre-attached as part of getting our rank for enabling
		 * shared contexts.  */
	}

	_HFI_VDBG("finish ptl device init...\n");

	/*
	 * Keep only IPS since only IPS support multi-rail, other devices
	 * are only setup once. IPS device can come to this function again.
	 */
	for (i = 0; i < PTL_MAX_INIT; i++) {
		if (devid_enabled[i] != PTL_DEVID_IPS) {
			devid_enabled[i] = -1;
		}
	}

	*epido = ep->epid;
	*epo = ep;

	return PSM_OK;

fail:
	if (ep != NULL) {
		if (ep->context.fd != -1)
			close(ep->context.fd);
		psmi_free(ep);
	}
	if (epaddr != NULL)
		psmi_free(epaddr);
	return err;
}