ctdb-transport: Replace ctdb_logging.h with common/logging.h
[obnox/samba/samba-obnox.git] / ctdb / ib / ibwrapper.c
1 /*
2  * Unix SMB/CIFS implementation.
3  * Wrap Infiniband calls.
4  *
5  * Copyright (C) Sven Oehme <oehmes@de.ibm.com> 2006
6  *
7  * Major code contributions by Peter Somogyi <psomogyi@gamax.hu>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, see <http://www.gnu.org/licenses/>.
21  */
22
23 #include "replace.h"
24 #include "system/network.h"
25
26 #include <assert.h>
27 #include <talloc.h>
28 #include <tevent.h>
29
30 #include "lib/util/dlinklist.h"
31 #include "lib/util/debug.h"
32
33 #include "common/logging.h"
34
35 #include <infiniband/kern-abi.h>
36 #include <rdma/rdma_cma_abi.h>
37 #include <rdma/rdma_cma.h>
38
39 #include "ibwrapper.h"
40 #include "ibwrapper_internal.h"
41
42 #define IBW_LASTERR_BUFSIZE 512
43 static char ibw_lasterr[IBW_LASTERR_BUFSIZE];
44
45 #define IBW_MAX_SEND_WR 256
46 #define IBW_MAX_RECV_WR 1024
47 #define IBW_RECV_BUFSIZE 256
48 #define IBW_RECV_THRESHOLD (1 * 1024 * 1024)
49
50 static void ibw_event_handler_verbs(struct tevent_context *ev,
51         struct tevent_fd *fde, uint16_t flags, void *private_data);
52 static int ibw_fill_cq(struct ibw_conn *conn);
53 static int ibw_wc_recv(struct ibw_conn *conn, struct ibv_wc *wc);
54 static int ibw_wc_send(struct ibw_conn *conn, struct ibv_wc *wc);
55 static int ibw_send_packet(struct ibw_conn *conn, void *buf, struct ibw_wr *p, uint32_t len);
56
57 static void *ibw_alloc_mr(struct ibw_ctx_priv *pctx, struct ibw_conn_priv *pconn,
58         uint32_t n, struct ibv_mr **ppmr)
59 {
60         void *buf;
61
62         DEBUG(DEBUG_DEBUG, ("ibw_alloc_mr(cmid=%p, n=%u)\n", pconn->cm_id, n));
63         buf = memalign(pctx->pagesize, n);
64         if (!buf) {
65                 sprintf(ibw_lasterr, "couldn't allocate memory\n");
66                 return NULL;
67         }
68
69         *ppmr = ibv_reg_mr(pconn->pd, buf, n, IBV_ACCESS_LOCAL_WRITE);
70         if (!*ppmr) {
71                 sprintf(ibw_lasterr, "couldn't allocate mr\n");
72                 free(buf);
73                 return NULL;
74         }
75
76         return buf;
77 }
78
79 static void ibw_free_mr(char **ppbuf, struct ibv_mr **ppmr)
80 {
81         DEBUG(DEBUG_DEBUG, ("ibw_free_mr(%p %p)\n", *ppbuf, *ppmr));
82         if (*ppmr!=NULL) {
83                 ibv_dereg_mr(*ppmr);
84                 *ppmr = NULL;
85         }
86         if (*ppbuf) {
87                 free(*ppbuf);
88                 *ppbuf = NULL;
89         }
90 }
91
92 static int ibw_init_memory(struct ibw_conn *conn)
93 {
94         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
95         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
96         struct ibw_opts *opts = &pctx->opts;
97         int     i;
98         struct ibw_wr   *p;
99
100         DEBUG(DEBUG_DEBUG, ("ibw_init_memory(cmid: %p)\n", pconn->cm_id));
101         pconn->buf_send = ibw_alloc_mr(pctx, pconn,
102                 opts->max_send_wr * opts->recv_bufsize, &pconn->mr_send);
103         if (!pconn->buf_send) {
104                 sprintf(ibw_lasterr, "couldn't allocate work send buf\n");
105                 return -1;
106         }
107
108         pconn->buf_recv = ibw_alloc_mr(pctx, pconn,
109                 opts->max_recv_wr * opts->recv_bufsize, &pconn->mr_recv);
110         if (!pconn->buf_recv) {
111                 sprintf(ibw_lasterr, "couldn't allocate work recv buf\n");
112                 return -1;
113         }
114
115         pconn->wr_index = talloc_size(pconn, opts->max_send_wr * sizeof(struct ibw_wr *));
116         assert(pconn->wr_index!=NULL);
117
118         for(i=0; i<opts->max_send_wr; i++) {
119                 p = pconn->wr_index[i] = talloc_zero(pconn, struct ibw_wr);
120                 p->buf = pconn->buf_send + (i * opts->recv_bufsize);
121                 p->wr_id = i;
122
123                 DLIST_ADD(pconn->wr_list_avail, p);
124         }
125
126         return 0;
127 }
128
129 static int ibw_ctx_priv_destruct(struct ibw_ctx_priv *pctx)
130 {
131         DEBUG(DEBUG_DEBUG, ("ibw_ctx_priv_destruct(%p)\n", pctx));
132
133         /*
134          * tevent_fd must be removed before the fd is closed
135          */
136         TALLOC_FREE(pctx->cm_channel_event);
137
138         /* destroy cm */
139         if (pctx->cm_channel) {
140                 rdma_destroy_event_channel(pctx->cm_channel);
141                 pctx->cm_channel = NULL;
142         }
143         if (pctx->cm_id) {
144                 rdma_destroy_id(pctx->cm_id);
145                 pctx->cm_id = NULL;
146         }
147
148         return 0;
149 }
150
151 static int ibw_ctx_destruct(struct ibw_ctx *ctx)
152 {
153         DEBUG(DEBUG_DEBUG, ("ibw_ctx_destruct(%p)\n", ctx));
154         return 0;
155 }
156
157 static int ibw_conn_priv_destruct(struct ibw_conn_priv *pconn)
158 {
159         DEBUG(DEBUG_DEBUG, ("ibw_conn_priv_destruct(%p, cmid: %p)\n",
160                 pconn, pconn->cm_id));
161
162         /* pconn->wr_index is freed by talloc */
163         /* pconn->wr_index[i] are freed by talloc */
164
165         /*
166          * tevent_fd must be removed before the fd is closed
167          */
168         TALLOC_FREE(pconn->verbs_channel_event);
169
170         /* destroy verbs */
171         if (pconn->cm_id!=NULL && pconn->cm_id->qp!=NULL) {
172                 rdma_destroy_qp(pconn->cm_id);
173                 pconn->cm_id->qp = NULL;
174         }
175
176         if (pconn->cq!=NULL) {
177                 ibv_destroy_cq(pconn->cq);
178                 pconn->cq = NULL;
179         }
180
181         if (pconn->verbs_channel!=NULL) {
182                 ibv_destroy_comp_channel(pconn->verbs_channel);
183                 pconn->verbs_channel = NULL;
184         }
185
186         /* free memory regions */
187         ibw_free_mr(&pconn->buf_send, &pconn->mr_send);
188         ibw_free_mr(&pconn->buf_recv, &pconn->mr_recv);
189
190         if (pconn->pd) {
191                 ibv_dealloc_pd(pconn->pd);
192                 pconn->pd = NULL;
193                 DEBUG(DEBUG_DEBUG, ("pconn=%p pd deallocated\n", pconn));
194         }
195
196         if (pconn->cm_id) {
197                 rdma_destroy_id(pconn->cm_id);
198                 pconn->cm_id = NULL;
199                 DEBUG(DEBUG_DEBUG, ("pconn=%p cm_id destroyed\n", pconn));
200         }
201
202         return 0;
203 }
204
205 static int ibw_wr_destruct(struct ibw_wr *wr)
206 {
207         if (wr->buf_large!=NULL)
208                 ibw_free_mr(&wr->buf_large, &wr->mr_large);
209         return 0;
210 }
211
212 static int ibw_conn_destruct(struct ibw_conn *conn)
213 {
214         DEBUG(DEBUG_DEBUG, ("ibw_conn_destruct(%p)\n", conn));
215         
216         /* important here: ctx is a talloc _parent_ */
217         DLIST_REMOVE(conn->ctx->conn_list, conn);
218         return 0;
219 }
220
221 struct ibw_conn *ibw_conn_new(struct ibw_ctx *ctx, TALLOC_CTX *mem_ctx)
222 {
223         struct ibw_conn *conn;
224         struct ibw_conn_priv *pconn;
225
226         assert(ctx!=NULL);
227
228         conn = talloc_zero(mem_ctx, struct ibw_conn);
229         assert(conn!=NULL);
230         talloc_set_destructor(conn, ibw_conn_destruct);
231
232         pconn = talloc_zero(conn, struct ibw_conn_priv);
233         assert(pconn!=NULL);
234         talloc_set_destructor(pconn, ibw_conn_priv_destruct);
235
236         conn->ctx = ctx;
237         conn->internal = (void *)pconn;
238
239         DLIST_ADD(ctx->conn_list, conn);
240
241         return conn;
242 }
243
244 static int ibw_setup_cq_qp(struct ibw_conn *conn)
245 {
246         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
247         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
248         struct ibv_qp_init_attr init_attr;
249         struct ibv_qp_attr attr;
250         int rc;
251
252         DEBUG(DEBUG_DEBUG, ("ibw_setup_cq_qp(cmid: %p)\n", pconn->cm_id));
253
254         /* init verbs */
255         pconn->verbs_channel = ibv_create_comp_channel(pconn->cm_id->verbs);
256         if (!pconn->verbs_channel) {
257                 sprintf(ibw_lasterr, "ibv_create_comp_channel failed %d\n", errno);
258                 return -1;
259         }
260         DEBUG(DEBUG_DEBUG, ("created channel %p\n", pconn->verbs_channel));
261
262         pconn->verbs_channel_event = tevent_add_fd(pctx->ectx, NULL, /* not pconn or conn */
263                 pconn->verbs_channel->fd, TEVENT_FD_READ, ibw_event_handler_verbs, conn);
264
265         pconn->pd = ibv_alloc_pd(pconn->cm_id->verbs);
266         if (!pconn->pd) {
267                 sprintf(ibw_lasterr, "ibv_alloc_pd failed %d\n", errno);
268                 return -1;
269         }
270         DEBUG(DEBUG_DEBUG, ("created pd %p\n", pconn->pd));
271
272         /* init mr */
273         if (ibw_init_memory(conn))
274                 return -1;
275
276         /* init cq */
277         pconn->cq = ibv_create_cq(pconn->cm_id->verbs,
278                 pctx->opts.max_recv_wr + pctx->opts.max_send_wr,
279                 conn, pconn->verbs_channel, 0);
280         if (pconn->cq==NULL) {
281                 sprintf(ibw_lasterr, "ibv_create_cq failed\n");
282                 return -1;
283         }
284
285         rc = ibv_req_notify_cq(pconn->cq, 0);
286         if (rc) {
287                 sprintf(ibw_lasterr, "ibv_req_notify_cq failed with %d\n", rc);
288                 return rc;
289         }
290
291         /* init qp */
292         memset(&init_attr, 0, sizeof(init_attr));
293         init_attr.cap.max_send_wr = pctx->opts.max_send_wr;
294         init_attr.cap.max_recv_wr = pctx->opts.max_recv_wr;
295         init_attr.cap.max_recv_sge = 1;
296         init_attr.cap.max_send_sge = 1;
297         init_attr.qp_type = IBV_QPT_RC;
298         init_attr.send_cq = pconn->cq;
299         init_attr.recv_cq = pconn->cq;
300
301         rc = rdma_create_qp(pconn->cm_id, pconn->pd, &init_attr);
302         if (rc) {
303                 sprintf(ibw_lasterr, "rdma_create_qp failed with %d\n", rc);
304                 return rc;
305         }
306         /* elase result is in pconn->cm_id->qp */
307
308         rc = ibv_query_qp(pconn->cm_id->qp, &attr, IBV_QP_PATH_MTU, &init_attr);
309         if (rc) {
310                 sprintf(ibw_lasterr, "ibv_query_qp failed with %d\n", rc);
311                 return rc;
312         }
313
314         return ibw_fill_cq(conn);
315 }
316
317 static int ibw_refill_cq_recv(struct ibw_conn *conn)
318 {
319         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
320         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
321         int     rc;
322         struct ibv_sge list = {
323                 .addr   = (uintptr_t) NULL, /* filled below */
324                 .length = pctx->opts.recv_bufsize,
325                 .lkey   = pconn->mr_recv->lkey /* always the same */
326         };
327         struct ibv_recv_wr wr = {
328                 .wr_id      = 0, /* filled below */
329                 .sg_list    = &list,
330                 .num_sge    = 1,
331         };
332         struct ibv_recv_wr *bad_wr;
333
334         DEBUG(DEBUG_DEBUG, ("ibw_refill_cq_recv(cmid: %p)\n", pconn->cm_id));
335
336         list.addr = (uintptr_t) pconn->buf_recv + pctx->opts.recv_bufsize * pconn->recv_index;
337         wr.wr_id = pconn->recv_index;
338         pconn->recv_index = (pconn->recv_index + 1) % pctx->opts.max_recv_wr;
339
340         rc = ibv_post_recv(pconn->cm_id->qp, &wr, &bad_wr);
341         if (rc) {
342                 sprintf(ibw_lasterr, "refill/ibv_post_recv failed with %d\n", rc);
343                 DEBUG(DEBUG_ERR, (ibw_lasterr));
344                 return -2;
345         }
346
347         return 0;
348 }
349
350 static int ibw_fill_cq(struct ibw_conn *conn)
351 {
352         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
353         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
354         int     i, rc;
355         struct ibv_sge list = {
356                 .addr   = (uintptr_t) NULL, /* filled below */
357                 .length = pctx->opts.recv_bufsize,
358                 .lkey   = pconn->mr_recv->lkey /* always the same */
359         };
360         struct ibv_recv_wr wr = {
361                 .wr_id      = 0, /* filled below */
362                 .sg_list    = &list,
363                 .num_sge    = 1,
364         };
365         struct ibv_recv_wr *bad_wr;
366
367         DEBUG(DEBUG_DEBUG, ("ibw_fill_cq(cmid: %p)\n", pconn->cm_id));
368
369         for(i = pctx->opts.max_recv_wr; i!=0; i--) {
370                 list.addr = (uintptr_t) pconn->buf_recv + pctx->opts.recv_bufsize * pconn->recv_index;
371                 wr.wr_id = pconn->recv_index;
372                 pconn->recv_index = (pconn->recv_index + 1) % pctx->opts.max_recv_wr;
373
374                 rc = ibv_post_recv(pconn->cm_id->qp, &wr, &bad_wr);
375                 if (rc) {
376                         sprintf(ibw_lasterr, "fill/ibv_post_recv failed with %d\n", rc);
377                         DEBUG(DEBUG_ERR, (ibw_lasterr));
378                         return -2;
379                 }
380         }
381
382         return 0;
383 }
384
385 static int ibw_manage_connect(struct ibw_conn *conn)
386 {
387         struct rdma_conn_param conn_param;
388         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
389         int     rc;
390
391         DEBUG(DEBUG_DEBUG, ("ibw_manage_connect(cmid: %p)\n", pconn->cm_id));
392
393         if (ibw_setup_cq_qp(conn))
394                 return -1;
395
396         /* cm connect */
397         memset(&conn_param, 0, sizeof conn_param);
398         conn_param.responder_resources = 1;
399         conn_param.initiator_depth = 1;
400         conn_param.retry_count = 10;
401
402         rc = rdma_connect(pconn->cm_id, &conn_param);
403         if (rc)
404                 sprintf(ibw_lasterr, "rdma_connect error %d\n", rc);
405
406         return rc;
407 }
408
409 static void ibw_event_handler_cm(struct tevent_context *ev,
410         struct tevent_fd *fde, uint16_t flags, void *private_data)
411 {
412         int     rc;
413         struct ibw_ctx  *ctx = talloc_get_type(private_data, struct ibw_ctx);
414         struct ibw_ctx_priv *pctx = talloc_get_type(ctx->internal, struct ibw_ctx_priv);
415         struct ibw_conn *conn = NULL;
416         struct ibw_conn_priv *pconn = NULL;
417         struct rdma_cm_id *cma_id = NULL;
418         struct rdma_cm_event *event = NULL;
419
420         assert(ctx!=NULL);
421
422         rc = rdma_get_cm_event(pctx->cm_channel, &event);
423         if (rc) {
424                 ctx->state = IBWS_ERROR;
425                 event = NULL;
426                 sprintf(ibw_lasterr, "rdma_get_cm_event error %d\n", rc);
427                 goto error;
428         }
429         cma_id = event->id;
430
431         DEBUG(DEBUG_DEBUG, ("cma_event type %d cma_id %p (%s)\n", event->event, cma_id,
432                   (cma_id == pctx->cm_id) ? "parent" : "child"));
433
434         switch (event->event) {
435         case RDMA_CM_EVENT_ADDR_RESOLVED:
436                 DEBUG(DEBUG_DEBUG, ("RDMA_CM_EVENT_ADDR_RESOLVED\n"));
437                 /* continuing from ibw_connect ... */
438                 rc = rdma_resolve_route(cma_id, 2000);
439                 if (rc) {
440                         sprintf(ibw_lasterr, "rdma_resolve_route error %d\n", rc);
441                         goto error;
442                 }
443                 /* continued at RDMA_CM_EVENT_ROUTE_RESOLVED */
444                 break;
445
446         case RDMA_CM_EVENT_ROUTE_RESOLVED:
447                 DEBUG(DEBUG_DEBUG, ("RDMA_CM_EVENT_ROUTE_RESOLVED\n"));
448                 /* after RDMA_CM_EVENT_ADDR_RESOLVED: */
449                 assert(cma_id->context!=NULL);
450                 conn = talloc_get_type(cma_id->context, struct ibw_conn);
451
452                 rc = ibw_manage_connect(conn);
453                 if (rc)
454                         goto error;
455
456                 break;
457
458         case RDMA_CM_EVENT_CONNECT_REQUEST:
459                 DEBUG(DEBUG_DEBUG, ("RDMA_CM_EVENT_CONNECT_REQUEST\n"));
460                 ctx->state = IBWS_CONNECT_REQUEST;
461                 conn = ibw_conn_new(ctx, ctx);
462                 pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
463                 pconn->cm_id = cma_id; /* !!! event will be freed but id not */
464                 cma_id->context = (void *)conn;
465                 DEBUG(DEBUG_DEBUG, ("pconn->cm_id %p\n", pconn->cm_id));
466
467                 if (ibw_setup_cq_qp(conn))
468                         goto error;
469
470                 conn->state = IBWC_INIT;
471                 pctx->connstate_func(ctx, conn);
472
473                 /* continued at ibw_accept when invoked by the func above */
474                 if (!pconn->is_accepted) {
475                         rc = rdma_reject(cma_id, NULL, 0);
476                         if (rc)
477                                 DEBUG(DEBUG_ERR, ("rdma_reject failed with rc=%d\n", rc));
478                         talloc_free(conn);
479                         DEBUG(DEBUG_DEBUG, ("pconn->cm_id %p wasn't accepted\n", pconn->cm_id));
480                 }
481
482                 /* TODO: clarify whether if it's needed by upper layer: */
483                 ctx->state = IBWS_READY;
484                 pctx->connstate_func(ctx, NULL);
485
486                 /* NOTE: more requests can arrive until RDMA_CM_EVENT_ESTABLISHED ! */
487                 break;
488
489         case RDMA_CM_EVENT_ESTABLISHED:
490                 /* expected after ibw_accept and ibw_connect[not directly] */
491                 DEBUG(DEBUG_INFO, ("ESTABLISHED (conn: %p)\n", cma_id->context));
492                 conn = talloc_get_type(cma_id->context, struct ibw_conn);
493                 assert(conn!=NULL); /* important assumption */
494
495                 DEBUG(DEBUG_DEBUG, ("ibw_setup_cq_qp succeeded (cmid=%p)\n", cma_id));
496
497                 /* client conn is up */
498                 conn->state = IBWC_CONNECTED;
499
500                 /* both ctx and conn have changed */
501                 pctx->connstate_func(ctx, conn);
502                 break;
503
504         case RDMA_CM_EVENT_ADDR_ERROR:
505                 sprintf(ibw_lasterr, "RDMA_CM_EVENT_ADDR_ERROR, error %d\n", event->status);
506         case RDMA_CM_EVENT_ROUTE_ERROR:
507                 sprintf(ibw_lasterr, "RDMA_CM_EVENT_ROUTE_ERROR, error %d\n", event->status);
508         case RDMA_CM_EVENT_CONNECT_ERROR:
509                 sprintf(ibw_lasterr, "RDMA_CM_EVENT_CONNECT_ERROR, error %d\n", event->status);
510         case RDMA_CM_EVENT_UNREACHABLE:
511                 sprintf(ibw_lasterr, "RDMA_CM_EVENT_UNREACHABLE, error %d\n", event->status);
512                 goto error;
513         case RDMA_CM_EVENT_REJECTED:
514                 sprintf(ibw_lasterr, "RDMA_CM_EVENT_REJECTED, error %d\n", event->status);
515                 DEBUG(DEBUG_INFO, ("cm event handler: %s", ibw_lasterr));
516                 conn = talloc_get_type(cma_id->context, struct ibw_conn);
517                 if (conn) {
518                         /* must be done BEFORE connstate */
519                         if ((rc=rdma_ack_cm_event(event)))
520                                 DEBUG(DEBUG_ERR, ("reject/rdma_ack_cm_event failed with %d\n", rc));
521                         event = NULL; /* not to touch cma_id or conn */
522                         conn->state = IBWC_ERROR;
523                         /* it should free the conn */
524                         pctx->connstate_func(NULL, conn);
525                 }
526                 break; /* this is not strictly an error */
527
528         case RDMA_CM_EVENT_DISCONNECTED:
529                 DEBUG(DEBUG_DEBUG, ("RDMA_CM_EVENT_DISCONNECTED\n"));
530                 if ((rc=rdma_ack_cm_event(event)))
531                         DEBUG(DEBUG_ERR, ("disc/rdma_ack_cm_event failed with %d\n", rc));
532                 event = NULL; /* don't ack more */
533
534                 if (cma_id!=pctx->cm_id) {
535                         DEBUG(DEBUG_ERR, ("client DISCONNECT event cm_id=%p\n", cma_id));
536                         conn = talloc_get_type(cma_id->context, struct ibw_conn);
537                         conn->state = IBWC_DISCONNECTED;
538                         pctx->connstate_func(NULL, conn);
539                 }
540                 break;
541
542         case RDMA_CM_EVENT_DEVICE_REMOVAL:
543                 sprintf(ibw_lasterr, "cma detected device removal!\n");
544                 goto error;
545
546         default:
547                 sprintf(ibw_lasterr, "unknown event %d\n", event->event);
548                 goto error;
549         }
550
551         if (event!=NULL && (rc=rdma_ack_cm_event(event))) {
552                 sprintf(ibw_lasterr, "rdma_ack_cm_event failed with %d\n", rc);
553                 goto error;
554         }
555
556         return;
557 error:
558         DEBUG(DEBUG_ERR, ("cm event handler: %s", ibw_lasterr));
559
560         if (event!=NULL) {
561                 if (cma_id!=NULL && cma_id!=pctx->cm_id) {
562                         conn = talloc_get_type(cma_id->context, struct ibw_conn);
563                         if (conn) {
564                                 conn->state = IBWC_ERROR;
565                                 pctx->connstate_func(NULL, conn);
566                         }
567                 } else {
568                         ctx->state = IBWS_ERROR;
569                         pctx->connstate_func(ctx, NULL);
570                 }
571
572                 if ((rc=rdma_ack_cm_event(event))!=0) {
573                         DEBUG(DEBUG_ERR, ("rdma_ack_cm_event failed with %d\n", rc));
574                 }
575         }
576
577         return;
578 }
579
580 static void ibw_event_handler_verbs(struct tevent_context *ev,
581         struct tevent_fd *fde, uint16_t flags, void *private_data)
582 {
583         struct ibw_conn *conn = talloc_get_type(private_data, struct ibw_conn);
584         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
585         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
586
587         struct ibv_wc wc;
588         int rc;
589         struct ibv_cq *ev_cq;
590         void          *ev_ctx;
591
592         DEBUG(DEBUG_DEBUG, ("ibw_event_handler_verbs(%u)\n", (uint32_t)flags));
593
594         /* TODO: check whether if it's good to have more channels here... */
595         rc = ibv_get_cq_event(pconn->verbs_channel, &ev_cq, &ev_ctx);
596         if (rc) {
597                 sprintf(ibw_lasterr, "Failed to get cq_event with %d\n", rc);
598                 goto error;
599         }
600         if (ev_cq != pconn->cq) {
601                 sprintf(ibw_lasterr, "ev_cq(%p) != pconn->cq(%p)\n", ev_cq, pconn->cq);
602                 goto error;
603         }
604         rc = ibv_req_notify_cq(pconn->cq, 0);
605         if (rc) {
606                 sprintf(ibw_lasterr, "Couldn't request CQ notification (%d)\n", rc);
607                 goto error;
608         }
609
610         while((rc=ibv_poll_cq(pconn->cq, 1, &wc))==1) {
611                 if (wc.status) {
612                         sprintf(ibw_lasterr, "cq completion failed status=%d, opcode=%d, rc=%d\n",
613                                 wc.status, wc.opcode, rc);
614                         goto error;
615                 }
616
617                 switch(wc.opcode) {
618                 case IBV_WC_SEND:
619                         DEBUG(DEBUG_DEBUG, ("send completion\n"));
620                         if (ibw_wc_send(conn, &wc))
621                                 goto error;
622                         break;
623
624                 case IBV_WC_RDMA_WRITE:
625                         DEBUG(DEBUG_DEBUG, ("rdma write completion\n"));
626                         break;
627         
628                 case IBV_WC_RDMA_READ:
629                         DEBUG(DEBUG_DEBUG, ("rdma read completion\n"));
630                         break;
631
632                 case IBV_WC_RECV:
633                         DEBUG(DEBUG_DEBUG, ("recv completion\n"));
634                         if (ibw_wc_recv(conn, &wc))
635                                 goto error;
636                         break;
637
638                 default:
639                         sprintf(ibw_lasterr, "unknown completion %d\n", wc.opcode);
640                         goto error;
641                 }
642         }
643         if (rc!=0) {
644                 sprintf(ibw_lasterr, "ibv_poll_cq error %d\n", rc);
645                 goto error;
646         }
647
648         ibv_ack_cq_events(pconn->cq, 1);
649
650         return;
651 error:
652         ibv_ack_cq_events(pconn->cq, 1);
653
654         DEBUG(DEBUG_ERR, (ibw_lasterr));
655         
656         if (conn->state!=IBWC_ERROR) {
657                 conn->state = IBWC_ERROR;
658                 pctx->connstate_func(NULL, conn);
659         }
660 }
661
662 static int ibw_process_queue(struct ibw_conn *conn)
663 {
664         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
665         struct ibw_ctx_priv *pctx;
666         struct ibw_wr   *p;
667         int     rc;
668         uint32_t        msg_size;
669
670         if (pconn->queue==NULL)
671                 return 0; /* NOP */
672
673         p = pconn->queue;
674
675         /* we must have at least 1 fragment to send */
676         assert(p->queued_ref_cnt>0);
677         p->queued_ref_cnt--;
678
679         pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
680         msg_size = (p->queued_ref_cnt) ? pctx->opts.recv_bufsize : p->queued_rlen;
681
682         assert(p->queued_msg!=NULL);
683         assert(msg_size!=0);
684
685         DEBUG(DEBUG_DEBUG, ("ibw_process_queue refcnt=%d msgsize=%u\n",
686                 p->queued_ref_cnt, msg_size));
687
688         rc = ibw_send_packet(conn, p->queued_msg, p, msg_size);
689
690         /* was this the last fragment? */
691         if (p->queued_ref_cnt) {
692                 p->queued_msg += pctx->opts.recv_bufsize;
693         } else {
694                 DLIST_REMOVE2(pconn->queue, p, qprev, qnext);
695                 p->queued_msg = NULL;
696         }
697
698         return rc;
699 }
700
701 static int ibw_wc_send(struct ibw_conn *conn, struct ibv_wc *wc)
702 {
703         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
704         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
705         struct ibw_wr   *p;
706         int     send_index;
707
708         DEBUG(DEBUG_DEBUG, ("ibw_wc_send(cmid: %p, wr_id: %u, bl: %u)\n",
709                 pconn->cm_id, (uint32_t)wc->wr_id, (uint32_t)wc->byte_len));
710
711         assert(pconn->cm_id->qp->qp_num==wc->qp_num);
712         assert(wc->wr_id >= pctx->opts.max_recv_wr);
713         send_index = wc->wr_id - pctx->opts.max_recv_wr;
714         pconn->wr_sent--;
715
716         if (send_index < pctx->opts.max_send_wr) {
717                 DEBUG(DEBUG_DEBUG, ("ibw_wc_send#1 %u\n", (int)wc->wr_id));
718                 p = pconn->wr_index[send_index];
719                 if (p->buf_large!=NULL) {
720                         if (p->ref_cnt) {
721                                 /* awaiting more of it... */
722                                 p->ref_cnt--;
723                         } else {
724                                 ibw_free_mr(&p->buf_large, &p->mr_large);
725                                 DLIST_REMOVE(pconn->wr_list_used, p);
726                                 DLIST_ADD(pconn->wr_list_avail, p);
727                         }
728                 } else { /* nasty - but necessary */
729                         DLIST_REMOVE(pconn->wr_list_used, p);
730                         DLIST_ADD(pconn->wr_list_avail, p);
731                 }
732         } else { /* "extra" request - not optimized */
733                 DEBUG(DEBUG_DEBUG, ("ibw_wc_send#2 %u\n", (int)wc->wr_id));
734                 for(p=pconn->extra_sent; p!=NULL; p=p->next)
735                         if ((p->wr_id + pctx->opts.max_recv_wr)==(int)wc->wr_id)
736                                 break;
737                 if (p==NULL) {
738                         sprintf(ibw_lasterr, "failed to find wr_id %d\n", (int)wc->wr_id);
739                                 return -1;
740                 }
741                 if (p->ref_cnt) {
742                         p->ref_cnt--;
743                 } else {
744                         ibw_free_mr(&p->buf_large, &p->mr_large);
745                         DLIST_REMOVE(pconn->extra_sent, p);
746                         DLIST_ADD(pconn->extra_avail, p);
747                 }
748         }
749
750         return ibw_process_queue(conn);
751 }
752
753 static int ibw_append_to_part(struct ibw_conn_priv *pconn,
754         struct ibw_part *part, char **pp, uint32_t add_len, int info)
755 {
756         DEBUG(DEBUG_DEBUG, ("ibw_append_to_part: cmid=%p, (bs=%u, len=%u, tr=%u), al=%u, i=%u\n",
757                 pconn->cm_id, part->bufsize, part->len, part->to_read, add_len, info));
758
759         /* allocate more if necessary - it's an "evergrowing" buffer... */
760         if (part->len + add_len > part->bufsize) {
761                 if (part->buf==NULL) {
762                         assert(part->len==0);
763                         part->buf = talloc_size(pconn, add_len);
764                         if (part->buf==NULL) {
765                                 sprintf(ibw_lasterr, "recv talloc_size error (%u) #%d\n",
766                                         add_len, info);
767                                 return -1;
768                         }
769                         part->bufsize = add_len;
770                 } else {
771                         part->buf = talloc_realloc_size(pconn,
772                                 part->buf, part->len + add_len);
773                         if (part->buf==NULL) {
774                                 sprintf(ibw_lasterr, "recv realloc error (%u + %u) #%d\n",
775                                         part->len, add_len, info);
776                                 return -1;
777                         }
778                 }
779                 part->bufsize = part->len + add_len;
780         }
781
782         /* consume pp */
783         memcpy(part->buf + part->len, *pp, add_len);
784         *pp += add_len;
785         part->len += add_len;
786         part->to_read -= add_len;
787
788         return 0;
789 }
790
791 static int ibw_wc_mem_threshold(struct ibw_conn_priv *pconn,
792         struct ibw_part *part, uint32_t threshold)
793 {
794         DEBUG(DEBUG_DEBUG, ("ibw_wc_mem_threshold: cmid=%p, (bs=%u, len=%u, tr=%u), thr=%u\n",
795                 pconn->cm_id, part->bufsize, part->len, part->to_read, threshold));
796
797         if (part->bufsize > threshold) {
798                 DEBUG(DEBUG_DEBUG, ("ibw_wc_mem_threshold: cmid=%p, %u > %u\n",
799                         pconn->cm_id, part->bufsize, threshold));
800                 talloc_free(part->buf);
801                 part->buf = talloc_size(pconn, threshold);
802                 if (part->buf==NULL) {
803                         sprintf(ibw_lasterr, "talloc_size failed\n");
804                         return -1;
805                 }
806                 part->bufsize = threshold;
807         }
808         return 0;
809 }
810
811 static int ibw_wc_recv(struct ibw_conn *conn, struct ibv_wc *wc)
812 {
813         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
814         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
815         struct ibw_part *part = &pconn->part;
816         char    *p;
817         uint32_t        remain = wc->byte_len;
818
819         DEBUG(DEBUG_DEBUG, ("ibw_wc_recv: cmid=%p, wr_id: %u, bl: %u\n",
820                 pconn->cm_id, (uint32_t)wc->wr_id, remain));
821
822         assert(pconn->cm_id->qp->qp_num==wc->qp_num);
823         assert((int)wc->wr_id < pctx->opts.max_recv_wr);
824         assert(wc->byte_len <= pctx->opts.recv_bufsize);
825
826         p = pconn->buf_recv + ((int)wc->wr_id * pctx->opts.recv_bufsize);
827
828         while(remain) {
829                 /* here always true: (part->len!=0 && part->to_read!=0) ||
830                         (part->len==0 && part->to_read==0) */
831                 if (part->len) { /* is there a partial msg to be continued? */
832                         int read_len = (part->to_read<=remain) ? part->to_read : remain;
833                         if (ibw_append_to_part(pconn, part, &p, read_len, 421))
834                                 goto error;
835                         remain -= read_len;
836
837                         if (part->len<=sizeof(uint32_t) && part->to_read==0) {
838                                 assert(part->len==sizeof(uint32_t));
839                                 /* set it again now... */
840                                 part->to_read = *((uint32_t *)(part->buf)); /* TODO: ntohl */
841                                 if (part->to_read<sizeof(uint32_t)) {
842                                         sprintf(ibw_lasterr, "got msglen=%u #2\n", part->to_read);
843                                         goto error;
844                                 }
845                                 part->to_read -= sizeof(uint32_t); /* it's already read */
846                         }
847
848                         if (part->to_read==0) {
849                                 if (pctx->receive_func(conn, part->buf, part->len) != 0) {
850                                         goto error;
851                                 }
852                                 part->len = 0; /* tells not having partial data (any more) */
853                                 if (ibw_wc_mem_threshold(pconn, part, pctx->opts.recv_threshold))
854                                         goto error;
855                         }
856                 } else {
857                         if (remain>=sizeof(uint32_t)) {
858                                 uint32_t msglen = *(uint32_t *)p; /* TODO: ntohl */
859                                 if (msglen<sizeof(uint32_t)) {
860                                         sprintf(ibw_lasterr, "got msglen=%u\n", msglen);
861                                         goto error;
862                                 }
863
864                                 /* mostly awaited case: */
865                                 if (msglen<=remain) {
866                                         if (pctx->receive_func(conn, p, msglen) != 0) {
867                                                 goto error;
868                                         }
869                                         p += msglen;
870                                         remain -= msglen;
871                                 } else {
872                                         part->to_read = msglen;
873                                         /* part->len is already 0 */
874                                         if (ibw_append_to_part(pconn, part, &p, remain, 422))
875                                                 goto error;
876                                         remain = 0; /* to be continued ... */
877                                         /* part->to_read > 0 here */
878                                 }
879                         } else { /* edge case: */
880                                 part->to_read = sizeof(uint32_t);
881                                 /* part->len is already 0 */
882                                 if (ibw_append_to_part(pconn, part, &p, remain, 423))
883                                         goto error;
884                                 remain = 0;
885                                 /* part->to_read > 0 here */
886                         }
887                 }
888         } /* <remain> is always decreased at least by 1 */
889
890         if (ibw_refill_cq_recv(conn))
891                 goto error;
892
893         return 0;
894
895 error:
896         DEBUG(DEBUG_ERR, ("ibw_wc_recv error: %s", ibw_lasterr));
897         return -1;
898 }
899
900 static int ibw_process_init_attrs(struct ibw_initattr *attr, int nattr, struct ibw_opts *opts)
901 {
902         int     i;
903         const char *name, *value;
904
905         DEBUG(DEBUG_DEBUG, ("ibw_process_init_attrs: nattr: %d\n", nattr));
906
907         opts->max_send_wr = IBW_MAX_SEND_WR;
908         opts->max_recv_wr = IBW_MAX_RECV_WR;
909         opts->recv_bufsize = IBW_RECV_BUFSIZE;
910         opts->recv_threshold = IBW_RECV_THRESHOLD;
911
912         for(i=0; i<nattr; i++) {
913                 name = attr[i].name;
914                 value = attr[i].value;
915
916                 assert(name!=NULL && value!=NULL);
917                 if (strcmp(name, "max_send_wr")==0)
918                         opts->max_send_wr = atoi(value);
919                 else if (strcmp(name, "max_recv_wr")==0)
920                         opts->max_recv_wr = atoi(value);
921                 else if (strcmp(name, "recv_bufsize")==0)
922                         opts->recv_bufsize = atoi(value);
923                 else if (strcmp(name, "recv_threshold")==0)
924                         opts->recv_threshold = atoi(value);
925                 else {
926                         sprintf(ibw_lasterr, "ibw_init: unknown name %s\n", name);
927                         return -1;
928                 }
929         }
930         return 0;
931 }
932
933 struct ibw_ctx *ibw_init(struct ibw_initattr *attr, int nattr,
934         void *ctx_userdata,
935         ibw_connstate_fn_t ibw_connstate,
936         ibw_receive_fn_t ibw_receive,
937         struct tevent_context *ectx)
938 {
939         struct ibw_ctx *ctx = talloc_zero(NULL, struct ibw_ctx);
940         struct ibw_ctx_priv *pctx;
941         int     rc;
942
943         DEBUG(DEBUG_DEBUG, ("ibw_init(ctx_userdata: %p, ectx: %p)\n", ctx_userdata, ectx));
944
945         /* initialize basic data structures */
946         memset(ibw_lasterr, 0, IBW_LASTERR_BUFSIZE);
947
948         assert(ctx!=NULL);
949         ibw_lasterr[0] = '\0';
950         talloc_set_destructor(ctx, ibw_ctx_destruct);
951         ctx->ctx_userdata = ctx_userdata;
952
953         pctx = talloc_zero(ctx, struct ibw_ctx_priv);
954         talloc_set_destructor(pctx, ibw_ctx_priv_destruct);
955         ctx->internal = (void *)pctx;
956         assert(pctx!=NULL);
957
958         pctx->connstate_func = ibw_connstate;
959         pctx->receive_func = ibw_receive;
960
961         pctx->ectx = ectx;
962
963         /* process attributes */
964         if (ibw_process_init_attrs(attr, nattr, &pctx->opts))
965                 goto cleanup;
966
967         /* init cm */
968         pctx->cm_channel = rdma_create_event_channel();
969         if (!pctx->cm_channel) {
970                 sprintf(ibw_lasterr, "rdma_create_event_channel error %d\n", errno);
971                 goto cleanup;
972         }
973
974         pctx->cm_channel_event = tevent_add_fd(pctx->ectx, pctx,
975                 pctx->cm_channel->fd, TEVENT_FD_READ, ibw_event_handler_cm, ctx);
976
977 #if RDMA_USER_CM_MAX_ABI_VERSION >= 2
978         rc = rdma_create_id(pctx->cm_channel, &pctx->cm_id, ctx, RDMA_PS_TCP);
979 #else
980         rc = rdma_create_id(pctx->cm_channel, &pctx->cm_id, ctx);
981 #endif
982         if (rc) {
983                 rc = errno;
984                 sprintf(ibw_lasterr, "rdma_create_id error %d\n", rc);
985                 goto cleanup;
986         }
987         DEBUG(DEBUG_DEBUG, ("created cm_id %p\n", pctx->cm_id));
988
989         pctx->pagesize = sysconf(_SC_PAGESIZE);
990
991         return ctx;
992         /* don't put code here */
993 cleanup:
994         DEBUG(DEBUG_ERR, (ibw_lasterr));
995
996         if (ctx)
997                 talloc_free(ctx);
998
999         return NULL;
1000 }
1001
1002 int ibw_stop(struct ibw_ctx *ctx)
1003 {
1004         struct ibw_ctx_priv *pctx = (struct ibw_ctx_priv *)ctx->internal;
1005         struct ibw_conn *p;
1006
1007         DEBUG(DEBUG_DEBUG, ("ibw_stop\n"));
1008
1009         for(p=ctx->conn_list; p!=NULL; p=p->next) {
1010                 if (p->state==IBWC_ERROR || p->state==IBWC_CONNECTED) {
1011                         if (ibw_disconnect(p))
1012                                 return -1;
1013                 }
1014         }
1015
1016         ctx->state = IBWS_STOPPED;
1017         pctx->connstate_func(ctx, NULL);
1018
1019         return 0;
1020 }
1021
1022 int ibw_bind(struct ibw_ctx *ctx, struct sockaddr_in *my_addr)
1023 {
1024         struct ibw_ctx_priv *pctx = (struct ibw_ctx_priv *)ctx->internal;
1025         int     rc;
1026
1027         DEBUG(DEBUG_DEBUG, ("ibw_bind: addr=%s, port=%u\n",
1028                 inet_ntoa(my_addr->sin_addr), ntohs(my_addr->sin_port)));
1029         rc = rdma_bind_addr(pctx->cm_id, (struct sockaddr *) my_addr);
1030         if (rc) {
1031                 sprintf(ibw_lasterr, "rdma_bind_addr error %d\n", rc);
1032                 DEBUG(DEBUG_ERR, (ibw_lasterr));
1033                 return rc;
1034         }
1035         DEBUG(DEBUG_DEBUG, ("rdma_bind_addr successful\n"));
1036
1037         return 0;
1038 }
1039
1040 int ibw_listen(struct ibw_ctx *ctx, int backlog)
1041 {
1042         struct ibw_ctx_priv *pctx = talloc_get_type(ctx->internal, struct ibw_ctx_priv);
1043         int     rc;
1044
1045         DEBUG(DEBUG_DEBUG, ("ibw_listen\n"));
1046         rc = rdma_listen(pctx->cm_id, backlog);
1047         if (rc) {
1048                 sprintf(ibw_lasterr, "rdma_listen failed: %d\n", rc);
1049                 DEBUG(DEBUG_ERR, (ibw_lasterr));
1050                 return rc;
1051         }
1052
1053         return 0;
1054 }
1055
1056 int ibw_accept(struct ibw_ctx *ctx, struct ibw_conn *conn, void *conn_userdata)
1057 {
1058         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
1059         struct rdma_conn_param  conn_param;
1060         int     rc;
1061
1062         DEBUG(DEBUG_DEBUG, ("ibw_accept: cmid=%p\n", pconn->cm_id));
1063         conn->conn_userdata = conn_userdata;
1064
1065         memset(&conn_param, 0, sizeof(struct rdma_conn_param));
1066         conn_param.responder_resources = 1;
1067         conn_param.initiator_depth = 1;
1068         rc = rdma_accept(pconn->cm_id, &conn_param);
1069         if (rc) {
1070                 sprintf(ibw_lasterr, "rdma_accept failed %d\n", rc);
1071                 DEBUG(DEBUG_ERR, (ibw_lasterr));
1072                 return -1;;
1073         }
1074
1075         pconn->is_accepted = 1;
1076
1077         /* continued at RDMA_CM_EVENT_ESTABLISHED */
1078
1079         return 0;
1080 }
1081
1082 int ibw_connect(struct ibw_conn *conn, struct sockaddr_in *serv_addr, void *conn_userdata)
1083 {
1084         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
1085         struct ibw_conn_priv *pconn = NULL;
1086         int     rc;
1087
1088         assert(conn!=NULL);
1089
1090         conn->conn_userdata = conn_userdata;
1091         pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
1092         DEBUG(DEBUG_DEBUG, ("ibw_connect: addr=%s, port=%u\n", inet_ntoa(serv_addr->sin_addr),
1093                 ntohs(serv_addr->sin_port)));
1094
1095         /* clean previous - probably half - initialization */
1096         if (ibw_conn_priv_destruct(pconn)) {
1097                 DEBUG(DEBUG_ERR, ("ibw_connect/ibw_pconn_destruct failed for cm_id=%p\n", pconn->cm_id));
1098                 return -1;
1099         }
1100
1101         /* init cm */
1102 #if RDMA_USER_CM_MAX_ABI_VERSION >= 2
1103         rc = rdma_create_id(pctx->cm_channel, &pconn->cm_id, conn, RDMA_PS_TCP);
1104 #else
1105         rc = rdma_create_id(pctx->cm_channel, &pconn->cm_id, conn);
1106 #endif
1107         if (rc) {
1108                 rc = errno;
1109                 sprintf(ibw_lasterr, "ibw_connect/rdma_create_id error %d\n", rc);
1110                 talloc_free(conn);
1111                 return -1;
1112         }
1113         DEBUG(DEBUG_DEBUG, ("ibw_connect: rdma_create_id succeeded, cm_id=%p\n", pconn->cm_id));
1114
1115         rc = rdma_resolve_addr(pconn->cm_id, NULL, (struct sockaddr *) serv_addr, 2000);
1116         if (rc) {
1117                 sprintf(ibw_lasterr, "rdma_resolve_addr error %d\n", rc);
1118                 DEBUG(DEBUG_ERR, (ibw_lasterr));
1119                 talloc_free(conn);
1120                 return -1;
1121         }
1122
1123         /* continued at RDMA_CM_EVENT_ADDR_RESOLVED */
1124
1125         return 0;
1126 }
1127
1128 int ibw_disconnect(struct ibw_conn *conn)
1129 {
1130         int     rc;
1131         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
1132
1133         DEBUG(DEBUG_DEBUG, ("ibw_disconnect: cmid=%p\n", pconn->cm_id));
1134
1135         assert(pconn!=NULL);
1136
1137         switch(conn->state) {
1138         case IBWC_ERROR:
1139                 ibw_conn_priv_destruct(pconn); /* do this here right now */
1140                 break;
1141         case IBWC_CONNECTED:
1142                 rc = rdma_disconnect(pconn->cm_id);
1143                 if (rc) {
1144                         sprintf(ibw_lasterr, "ibw_disconnect failed with %d\n", rc);
1145                         DEBUG(DEBUG_ERR, (ibw_lasterr));
1146                         return rc;
1147                 }
1148                 break;
1149         default:
1150                 DEBUG(DEBUG_DEBUG, ("invalid state for disconnect: %d\n", conn->state));
1151                 break;
1152         }
1153
1154         return 0;
1155 }
1156
1157 int ibw_alloc_send_buf(struct ibw_conn *conn, void **buf, void **key, uint32_t len)
1158 {
1159         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
1160         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
1161         struct ibw_wr *p = pconn->wr_list_avail;
1162
1163         if (p!=NULL) {
1164                 DEBUG(DEBUG_DEBUG, ("ibw_alloc_send_buf#1: cmid=%p, len=%d\n", pconn->cm_id, len));
1165
1166                 DLIST_REMOVE(pconn->wr_list_avail, p);
1167                 DLIST_ADD(pconn->wr_list_used, p);
1168
1169                 if (len <= pctx->opts.recv_bufsize) {
1170                         *buf = (void *)p->buf;
1171                 } else {
1172                         p->buf_large = ibw_alloc_mr(pctx, pconn, len, &p->mr_large);
1173                         if (p->buf_large==NULL) {
1174                                 sprintf(ibw_lasterr, "ibw_alloc_mr#1 failed\n");
1175                                 goto error;
1176                         }
1177                         *buf = (void *)p->buf_large;
1178                 }
1179                 /* p->wr_id is already filled in ibw_init_memory */
1180         } else {
1181                 DEBUG(DEBUG_DEBUG, ("ibw_alloc_send_buf#2: cmid=%p, len=%d\n", pconn->cm_id, len));
1182                 /* not optimized */
1183                 p = pconn->extra_avail;
1184                 if (!p) {
1185                         p = pconn->extra_avail = talloc_zero(pconn, struct ibw_wr);
1186                         talloc_set_destructor(p, ibw_wr_destruct);
1187                         if (p==NULL) {
1188                                 sprintf(ibw_lasterr, "talloc_zero failed (emax: %u)\n", pconn->extra_max);
1189                                 goto error;
1190                         }
1191                         p->wr_id = pctx->opts.max_send_wr + pconn->extra_max;
1192                         pconn->extra_max++;
1193                         switch(pconn->extra_max) {
1194                                 case 1: DEBUG(DEBUG_INFO, ("warning: queue performed\n")); break;
1195                                 case 10: DEBUG(DEBUG_INFO, ("warning: queue reached 10\n")); break;
1196                                 case 100: DEBUG(DEBUG_INFO, ("warning: queue reached 100\n")); break;
1197                                 case 1000: DEBUG(DEBUG_INFO, ("warning: queue reached 1000\n")); break;
1198                                 default: break;
1199                         }
1200                 }
1201
1202                 p->buf_large = ibw_alloc_mr(pctx, pconn, len, &p->mr_large);
1203                 if (p->buf_large==NULL) {
1204                         sprintf(ibw_lasterr, "ibw_alloc_mr#2 failed\n");
1205                         goto error;
1206                 }
1207                 *buf = (void *)p->buf_large;
1208
1209                 DLIST_REMOVE(pconn->extra_avail, p);
1210                 /* we don't have prepared index for this, so that
1211                  * we will have to find this by wr_id later on */
1212                 DLIST_ADD(pconn->extra_sent, p);
1213         }
1214
1215         *key = (void *)p;
1216
1217         return 0;
1218 error:
1219         DEBUG(DEBUG_ERR, ("ibw_alloc_send_buf error: %s", ibw_lasterr));
1220         return -1;
1221 }
1222
1223
1224 static int ibw_send_packet(struct ibw_conn *conn, void *buf, struct ibw_wr *p, uint32_t len)
1225 {
1226         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
1227         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
1228         int     rc;
1229
1230         /* can we send it right now? */
1231         if (pconn->wr_sent<pctx->opts.max_send_wr) {
1232                 struct ibv_send_wr *bad_wr;
1233                 struct ibv_sge list = {
1234                         .addr   = (uintptr_t)buf,
1235                         .length = len,
1236                         .lkey   = pconn->mr_send->lkey
1237                 };
1238                 struct ibv_send_wr wr = {
1239                         .wr_id      = p->wr_id + pctx->opts.max_recv_wr,
1240                         .sg_list    = &list,
1241                         .num_sge    = 1,
1242                         .opcode     = IBV_WR_SEND,
1243                         .send_flags = IBV_SEND_SIGNALED,
1244                 };
1245
1246                 if (p->buf_large==NULL) {
1247                         DEBUG(DEBUG_DEBUG, ("ibw_send#normal(cmid: %p, wrid: %u, n: %d)\n",
1248                                 pconn->cm_id, (uint32_t)wr.wr_id, len));
1249                 } else {
1250                         DEBUG(DEBUG_DEBUG, ("ibw_send#large(cmid: %p, wrid: %u, n: %d)\n",
1251                                 pconn->cm_id, (uint32_t)wr.wr_id, len));
1252                         list.lkey = p->mr_large->lkey;
1253                 }
1254
1255                 rc = ibv_post_send(pconn->cm_id->qp, &wr, &bad_wr);
1256                 if (rc) {
1257                         sprintf(ibw_lasterr, "ibv_post_send error %d (%d)\n",
1258                                 rc, pconn->wr_sent);
1259                         goto error;
1260                 }
1261
1262                 pconn->wr_sent++;
1263
1264                 return rc;
1265         } /* else put the request into our own queue: */
1266
1267         DEBUG(DEBUG_DEBUG, ("ibw_send#queued(cmid: %p, len: %u)\n", pconn->cm_id, len));
1268
1269         /* TODO: clarify how to continue when state==IBWC_STOPPED */
1270
1271         /* to be sent by ibw_wc_send */
1272         /* regardless "normal" or [a part of] "large" packet */
1273         if (!p->queued_ref_cnt) {
1274                 DLIST_ADD_END2(pconn->queue, p, struct ibw_wr *,
1275                         qprev, qnext); /* TODO: optimize */
1276                 p->queued_msg = buf;
1277         }
1278         p->queued_ref_cnt++;
1279         p->queued_rlen = len; /* last wins; see ibw_wc_send */
1280
1281         return 0;
1282 error:
1283         DEBUG(DEBUG_ERR, (ibw_lasterr));
1284         return -1;
1285 }
1286
1287 int ibw_send(struct ibw_conn *conn, void *buf, void *key, uint32_t len)
1288 {
1289         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
1290         struct ibw_wr *p = talloc_get_type(key, struct ibw_wr);
1291         int     rc;
1292
1293         assert(len>=sizeof(uint32_t));
1294         assert((*((uint32_t *)buf)==len)); /* TODO: htonl */
1295
1296         if (len > pctx->opts.recv_bufsize) {
1297                 struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
1298                 int     rlen = len;
1299                 char    *packet = (char *)buf;
1300                 uint32_t        recv_bufsize = pctx->opts.recv_bufsize;
1301
1302                 DEBUG(DEBUG_DEBUG, ("ibw_send#frag(cmid: %p, buf: %p, len: %u)\n",
1303                         pconn->cm_id, buf, len));
1304
1305                 /* single threaded => no race here: */
1306                 assert(p->ref_cnt==0);
1307                 while(rlen > recv_bufsize) {
1308                         rc = ibw_send_packet(conn, packet, p, recv_bufsize);
1309                         if (rc)
1310                                 return rc;
1311                         packet += recv_bufsize;
1312                         rlen -= recv_bufsize;
1313                         p->ref_cnt++; /* not good to have it in ibw_send_packet */
1314                 }
1315                 if (rlen) {
1316                         rc = ibw_send_packet(conn, packet, p, rlen);
1317                         p->ref_cnt++; /* not good to have it in ibw_send_packet */
1318                 }
1319                 p->ref_cnt--; /* for the same handling */
1320         } else {
1321                 assert(p->ref_cnt==0);
1322                 assert(p->queued_ref_cnt==0);
1323
1324                 rc = ibw_send_packet(conn, buf, p, len);
1325         }
1326         return rc;
1327 }
1328
1329 int ibw_cancel_send_buf(struct ibw_conn *conn, void *buf, void *key)
1330 {
1331         struct ibw_ctx_priv *pctx = talloc_get_type(conn->ctx->internal, struct ibw_ctx_priv);
1332         struct ibw_conn_priv *pconn = talloc_get_type(conn->internal, struct ibw_conn_priv);
1333         struct ibw_wr *p = talloc_get_type(key, struct ibw_wr);
1334
1335         assert(p!=NULL);
1336         assert(buf!=NULL);
1337         assert(conn!=NULL);
1338
1339         if (p->buf_large!=NULL)
1340                 ibw_free_mr(&p->buf_large, &p->mr_large);
1341
1342         /* parallel case */
1343         if (p->wr_id < pctx->opts.max_send_wr) {
1344                 DEBUG(DEBUG_DEBUG, ("ibw_cancel_send_buf#1 %u", (int)p->wr_id));
1345                 DLIST_REMOVE(pconn->wr_list_used, p);
1346                 DLIST_ADD(pconn->wr_list_avail, p);
1347         } else { /* "extra" packet */
1348                 DEBUG(DEBUG_DEBUG, ("ibw_cancel_send_buf#2 %u", (int)p->wr_id));
1349                 DLIST_REMOVE(pconn->extra_sent, p);
1350                 DLIST_ADD(pconn->extra_avail, p);
1351         }
1352
1353         return 0;
1354 }
1355
1356 const char *ibw_getLastError(void)
1357 {
1358         return ibw_lasterr;
1359 }