Whamcloud - gitweb
LU-11300 lnet: remove lnd_query interface.
[fs/lustre-release.git] / lnet / klnds / o2iblnd / o2iblnd_cb.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lnet/klnds/o2iblnd/o2iblnd_cb.c
33  *
34  * Author: Eric Barton <eric@bartonsoftware.com>
35  */
36
37 #include "o2iblnd.h"
38
39 #define MAX_CONN_RACES_BEFORE_ABORT 20
40
41 static void kiblnd_peer_alive(struct kib_peer_ni *peer_ni);
42 static void kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
43                                        int error);
44 static void kiblnd_init_tx_msg(struct lnet_ni *ni, struct kib_tx *tx,
45                                int type, int body_nob);
46 static int kiblnd_init_rdma(struct kib_conn *conn, struct kib_tx *tx, int type,
47                             int resid, struct kib_rdma_desc *dstrd, u64 dstcookie);
48 static void kiblnd_queue_tx_locked(struct kib_tx *tx, struct kib_conn *conn);
49 static void kiblnd_queue_tx(struct kib_tx *tx, struct kib_conn *conn);
50
51 static void kiblnd_unmap_tx(struct kib_tx *tx);
52 static void kiblnd_check_sends_locked(struct kib_conn *conn);
53
54 void
55 kiblnd_tx_done(struct kib_tx *tx)
56 {
57         struct lnet_msg *lntmsg[2];
58         int         rc;
59         int         i;
60
61         LASSERT (!in_interrupt());
62         LASSERT (!tx->tx_queued);               /* mustn't be queued for sending */
63         LASSERT (tx->tx_sending == 0);          /* mustn't be awaiting sent callback */
64         LASSERT (!tx->tx_waiting);              /* mustn't be awaiting peer_ni response */
65         LASSERT (tx->tx_pool != NULL);
66
67         kiblnd_unmap_tx(tx);
68
69         /* tx may have up to 2 lnet msgs to finalise */
70         lntmsg[0] = tx->tx_lntmsg[0]; tx->tx_lntmsg[0] = NULL;
71         lntmsg[1] = tx->tx_lntmsg[1]; tx->tx_lntmsg[1] = NULL;
72         rc = tx->tx_status;
73
74         if (tx->tx_conn != NULL) {
75                 kiblnd_conn_decref(tx->tx_conn);
76                 tx->tx_conn = NULL;
77         }
78
79         tx->tx_nwrq = tx->tx_nsge = 0;
80         tx->tx_status = 0;
81
82         kiblnd_pool_free_node(&tx->tx_pool->tpo_pool, &tx->tx_list);
83
84         /* delay finalize until my descs have been freed */
85         for (i = 0; i < 2; i++) {
86                 if (lntmsg[i] == NULL)
87                         continue;
88
89                 /* propagate health status to LNet for requests */
90                 if (i == 0 && lntmsg[i])
91                         lntmsg[i]->msg_health_status = tx->tx_hstatus;
92
93                 lnet_finalize(lntmsg[i], rc);
94         }
95 }
96
97 void
98 kiblnd_txlist_done(struct list_head *txlist, int status,
99                    enum lnet_msg_hstatus hstatus)
100 {
101         struct kib_tx *tx;
102
103         while (!list_empty(txlist)) {
104                 tx = list_entry(txlist->next, struct kib_tx, tx_list);
105
106                 list_del(&tx->tx_list);
107                 /* complete now */
108                 tx->tx_waiting = 0;
109                 tx->tx_status = status;
110                 if (hstatus != LNET_MSG_STATUS_OK)
111                         tx->tx_hstatus = hstatus;
112                 kiblnd_tx_done(tx);
113         }
114 }
115
116 static struct kib_tx *
117 kiblnd_get_idle_tx(struct lnet_ni *ni, lnet_nid_t target)
118 {
119         struct kib_net *net = ni->ni_data;
120         struct list_head *node;
121         struct kib_tx *tx;
122         struct kib_tx_poolset *tps;
123
124         tps = net->ibn_tx_ps[lnet_cpt_of_nid(target, ni)];
125         node = kiblnd_pool_alloc_node(&tps->tps_poolset);
126         if (node == NULL)
127                 return NULL;
128         tx = container_of(node, struct kib_tx, tx_list);
129
130         LASSERT (tx->tx_nwrq == 0);
131         LASSERT (!tx->tx_queued);
132         LASSERT (tx->tx_sending == 0);
133         LASSERT (!tx->tx_waiting);
134         LASSERT (tx->tx_status == 0);
135         LASSERT (tx->tx_conn == NULL);
136         LASSERT (tx->tx_lntmsg[0] == NULL);
137         LASSERT (tx->tx_lntmsg[1] == NULL);
138         LASSERT (tx->tx_nfrags == 0);
139
140         tx->tx_gaps = false;
141         tx->tx_hstatus = LNET_MSG_STATUS_OK;
142
143         return tx;
144 }
145
146 static void
147 kiblnd_drop_rx(struct kib_rx *rx)
148 {
149         struct kib_conn *conn = rx->rx_conn;
150         struct kib_sched_info *sched = conn->ibc_sched;
151         unsigned long flags;
152
153         spin_lock_irqsave(&sched->ibs_lock, flags);
154         LASSERT(conn->ibc_nrx > 0);
155         conn->ibc_nrx--;
156         spin_unlock_irqrestore(&sched->ibs_lock, flags);
157
158         kiblnd_conn_decref(conn);
159 }
160
161 int
162 kiblnd_post_rx(struct kib_rx *rx, int credit)
163 {
164         struct kib_conn *conn = rx->rx_conn;
165         struct kib_net *net = conn->ibc_peer->ibp_ni->ni_data;
166         struct ib_recv_wr *bad_wrq = NULL;
167 #ifdef HAVE_IB_GET_DMA_MR
168         struct ib_mr *mr = conn->ibc_hdev->ibh_mrs;
169 #endif
170         int rc;
171
172         LASSERT (net != NULL);
173         LASSERT (!in_interrupt());
174         LASSERT (credit == IBLND_POSTRX_NO_CREDIT ||
175                  credit == IBLND_POSTRX_PEER_CREDIT ||
176                  credit == IBLND_POSTRX_RSRVD_CREDIT);
177 #ifdef HAVE_IB_GET_DMA_MR
178         LASSERT(mr != NULL);
179
180         rx->rx_sge.lkey   = mr->lkey;
181 #else
182         rx->rx_sge.lkey   = conn->ibc_hdev->ibh_pd->local_dma_lkey;
183 #endif
184         rx->rx_sge.addr   = rx->rx_msgaddr;
185         rx->rx_sge.length = IBLND_MSG_SIZE;
186
187         rx->rx_wrq.next = NULL;
188         rx->rx_wrq.sg_list = &rx->rx_sge;
189         rx->rx_wrq.num_sge = 1;
190         rx->rx_wrq.wr_id = kiblnd_ptr2wreqid(rx, IBLND_WID_RX);
191
192         LASSERT (conn->ibc_state >= IBLND_CONN_INIT);
193         LASSERT (rx->rx_nob >= 0);              /* not posted */
194
195         if (conn->ibc_state > IBLND_CONN_ESTABLISHED) {
196                 kiblnd_drop_rx(rx);             /* No more posts for this rx */
197                 return 0;
198         }
199
200         rx->rx_nob = -1;                        /* flag posted */
201
202         /* NB: need an extra reference after ib_post_recv because we don't
203          * own this rx (and rx::rx_conn) anymore, LU-5678.
204          */
205         kiblnd_conn_addref(conn);
206 #ifdef HAVE_IB_POST_SEND_RECV_CONST
207         rc = ib_post_recv(conn->ibc_cmid->qp, &rx->rx_wrq,
208                           (const struct ib_recv_wr **)&bad_wrq);
209 #else
210         rc = ib_post_recv(conn->ibc_cmid->qp, &rx->rx_wrq, &bad_wrq);
211 #endif
212         if (unlikely(rc != 0)) {
213                 CERROR("Can't post rx for %s: %d, bad_wrq: %p\n",
214                        libcfs_nid2str(conn->ibc_peer->ibp_nid), rc, bad_wrq);
215                 rx->rx_nob = 0;
216         }
217
218         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) /* Initial post */
219                 goto out;
220
221         if (unlikely(rc != 0)) {
222                 kiblnd_close_conn(conn, rc);
223                 kiblnd_drop_rx(rx);     /* No more posts for this rx */
224                 goto out;
225         }
226
227         if (credit == IBLND_POSTRX_NO_CREDIT)
228                 goto out;
229
230         spin_lock(&conn->ibc_lock);
231         if (credit == IBLND_POSTRX_PEER_CREDIT)
232                 conn->ibc_outstanding_credits++;
233         else
234                 conn->ibc_reserved_credits++;
235         kiblnd_check_sends_locked(conn);
236         spin_unlock(&conn->ibc_lock);
237
238 out:
239         kiblnd_conn_decref(conn);
240         return rc;
241 }
242
243 static struct kib_tx *
244 kiblnd_find_waiting_tx_locked(struct kib_conn *conn, int txtype, u64 cookie)
245 {
246         struct list_head *tmp;
247
248         list_for_each(tmp, &conn->ibc_active_txs) {
249                 struct kib_tx *tx = list_entry(tmp, struct kib_tx, tx_list);
250
251                 LASSERT(!tx->tx_queued);
252                 LASSERT(tx->tx_sending != 0 || tx->tx_waiting);
253
254                 if (tx->tx_cookie != cookie)
255                         continue;
256
257                 if (tx->tx_waiting &&
258                     tx->tx_msg->ibm_type == txtype)
259                         return tx;
260
261                 CWARN("Bad completion: %swaiting, type %x (wanted %x)\n",
262                       tx->tx_waiting ? "" : "NOT ",
263                       tx->tx_msg->ibm_type, txtype);
264         }
265         return NULL;
266 }
267
268 static void
269 kiblnd_handle_completion(struct kib_conn *conn, int txtype, int status, u64 cookie)
270 {
271         struct kib_tx *tx;
272         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
273         int idle;
274
275         spin_lock(&conn->ibc_lock);
276
277         tx = kiblnd_find_waiting_tx_locked(conn, txtype, cookie);
278         if (tx == NULL) {
279                 spin_unlock(&conn->ibc_lock);
280
281                 CWARN("Unmatched completion type %x cookie %#llx from %s\n",
282                       txtype, cookie, libcfs_nid2str(conn->ibc_peer->ibp_nid));
283                 kiblnd_close_conn(conn, -EPROTO);
284                 return;
285         }
286
287         if (tx->tx_status == 0) {               /* success so far */
288                 if (status < 0) {               /* failed? */
289                         tx->tx_status = status;
290                         tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
291                 } else if (txtype == IBLND_MSG_GET_REQ) {
292                         lnet_set_reply_msg_len(ni, tx->tx_lntmsg[1], status);
293                 }
294         }
295
296         tx->tx_waiting = 0;
297
298         idle = !tx->tx_queued && (tx->tx_sending == 0);
299         if (idle)
300                 list_del(&tx->tx_list);
301
302         spin_unlock(&conn->ibc_lock);
303
304         if (idle)
305                 kiblnd_tx_done(tx);
306 }
307
308 static void
309 kiblnd_send_completion(struct kib_conn *conn, int type, int status, u64 cookie)
310 {
311         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
312         struct kib_tx *tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
313
314         if (tx == NULL) {
315                 CERROR("Can't get tx for completion %x for %s\n",
316                        type, libcfs_nid2str(conn->ibc_peer->ibp_nid));
317                 return;
318         }
319
320         tx->tx_msg->ibm_u.completion.ibcm_status = status;
321         tx->tx_msg->ibm_u.completion.ibcm_cookie = cookie;
322         kiblnd_init_tx_msg(ni, tx, type, sizeof(struct kib_completion_msg));
323
324         kiblnd_queue_tx(tx, conn);
325 }
326
327 static void
328 kiblnd_handle_rx(struct kib_rx *rx)
329 {
330         struct kib_msg *msg = rx->rx_msg;
331         struct kib_conn   *conn = rx->rx_conn;
332         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
333         int           credits = msg->ibm_credits;
334         struct kib_tx *tx;
335         int           rc = 0;
336         int           rc2;
337         int           post_credit;
338
339         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
340
341         CDEBUG (D_NET, "Received %x[%d] from %s\n",
342                 msg->ibm_type, credits,
343                 libcfs_nid2str(conn->ibc_peer->ibp_nid));
344
345         if (credits != 0) {
346                 /* Have I received credits that will let me send? */
347                 spin_lock(&conn->ibc_lock);
348
349                 if (conn->ibc_credits + credits >
350                     conn->ibc_queue_depth) {
351                         rc2 = conn->ibc_credits;
352                         spin_unlock(&conn->ibc_lock);
353
354                         CERROR("Bad credits from %s: %d + %d > %d\n",
355                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
356                                rc2, credits,
357                                conn->ibc_queue_depth);
358
359                         kiblnd_close_conn(conn, -EPROTO);
360                         kiblnd_post_rx(rx, IBLND_POSTRX_NO_CREDIT);
361                         return;
362                 }
363
364                 conn->ibc_credits += credits;
365
366                 /* This ensures the credit taken by NOOP can be returned */
367                 if (msg->ibm_type == IBLND_MSG_NOOP &&
368                     !IBLND_OOB_CAPABLE(conn->ibc_version)) /* v1 only */
369                         conn->ibc_outstanding_credits++;
370
371                 kiblnd_check_sends_locked(conn);
372                 spin_unlock(&conn->ibc_lock);
373         }
374
375         switch (msg->ibm_type) {
376         default:
377                 CERROR("Bad IBLND message type %x from %s\n",
378                        msg->ibm_type, libcfs_nid2str(conn->ibc_peer->ibp_nid));
379                 post_credit = IBLND_POSTRX_NO_CREDIT;
380                 rc = -EPROTO;
381                 break;
382
383         case IBLND_MSG_NOOP:
384                 if (IBLND_OOB_CAPABLE(conn->ibc_version)) {
385                         post_credit = IBLND_POSTRX_NO_CREDIT;
386                         break;
387                 }
388
389                 if (credits != 0) /* credit already posted */
390                         post_credit = IBLND_POSTRX_NO_CREDIT;
391                 else              /* a keepalive NOOP */
392                         post_credit = IBLND_POSTRX_PEER_CREDIT;
393                 break;
394
395         case IBLND_MSG_IMMEDIATE:
396                 post_credit = IBLND_POSTRX_DONT_POST;
397                 rc = lnet_parse(ni, &msg->ibm_u.immediate.ibim_hdr,
398                                 msg->ibm_srcnid, rx, 0);
399                 if (rc < 0)                     /* repost on error */
400                         post_credit = IBLND_POSTRX_PEER_CREDIT;
401                 break;
402
403         case IBLND_MSG_PUT_REQ:
404                 post_credit = IBLND_POSTRX_DONT_POST;
405                 rc = lnet_parse(ni, &msg->ibm_u.putreq.ibprm_hdr,
406                                 msg->ibm_srcnid, rx, 1);
407                 if (rc < 0)                     /* repost on error */
408                         post_credit = IBLND_POSTRX_PEER_CREDIT;
409                 break;
410
411         case IBLND_MSG_PUT_NAK:
412                 CWARN ("PUT_NACK from %s\n",
413                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
414                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
415                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_REQ,
416                                          msg->ibm_u.completion.ibcm_status,
417                                          msg->ibm_u.completion.ibcm_cookie);
418                 break;
419
420         case IBLND_MSG_PUT_ACK:
421                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
422
423                 spin_lock(&conn->ibc_lock);
424                 tx = kiblnd_find_waiting_tx_locked(conn, IBLND_MSG_PUT_REQ,
425                                         msg->ibm_u.putack.ibpam_src_cookie);
426                 if (tx != NULL)
427                         list_del(&tx->tx_list);
428                 spin_unlock(&conn->ibc_lock);
429
430                 if (tx == NULL) {
431                         CERROR("Unmatched PUT_ACK from %s\n",
432                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
433                         rc = -EPROTO;
434                         break;
435                 }
436
437                 LASSERT (tx->tx_waiting);
438                 /* CAVEAT EMPTOR: I could be racing with tx_complete, but...
439                  * (a) I can overwrite tx_msg since my peer_ni has received it!
440                  * (b) tx_waiting set tells tx_complete() it's not done. */
441
442                 tx->tx_nwrq = tx->tx_nsge = 0;  /* overwrite PUT_REQ */
443
444                 rc2 = kiblnd_init_rdma(conn, tx, IBLND_MSG_PUT_DONE,
445                                        kiblnd_rd_size(&msg->ibm_u.putack.ibpam_rd),
446                                        &msg->ibm_u.putack.ibpam_rd,
447                                        msg->ibm_u.putack.ibpam_dst_cookie);
448                 if (rc2 < 0)
449                         CERROR("Can't setup rdma for PUT to %s: %d\n",
450                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc2);
451
452                 spin_lock(&conn->ibc_lock);
453                 tx->tx_waiting = 0;     /* clear waiting and queue atomically */
454                 kiblnd_queue_tx_locked(tx, conn);
455                 spin_unlock(&conn->ibc_lock);
456                 break;
457
458         case IBLND_MSG_PUT_DONE:
459                 post_credit = IBLND_POSTRX_PEER_CREDIT;
460                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_ACK,
461                                          msg->ibm_u.completion.ibcm_status,
462                                          msg->ibm_u.completion.ibcm_cookie);
463                 break;
464
465         case IBLND_MSG_GET_REQ:
466                 post_credit = IBLND_POSTRX_DONT_POST;
467                 rc = lnet_parse(ni, &msg->ibm_u.get.ibgm_hdr,
468                                 msg->ibm_srcnid, rx, 1);
469                 if (rc < 0)                     /* repost on error */
470                         post_credit = IBLND_POSTRX_PEER_CREDIT;
471                 break;
472
473         case IBLND_MSG_GET_DONE:
474                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
475                 kiblnd_handle_completion(conn, IBLND_MSG_GET_REQ,
476                                          msg->ibm_u.completion.ibcm_status,
477                                          msg->ibm_u.completion.ibcm_cookie);
478                 break;
479         }
480
481         if (rc < 0)                             /* protocol error */
482                 kiblnd_close_conn(conn, rc);
483
484         if (post_credit != IBLND_POSTRX_DONT_POST)
485                 kiblnd_post_rx(rx, post_credit);
486 }
487
488 static void
489 kiblnd_rx_complete(struct kib_rx *rx, int status, int nob)
490 {
491         struct kib_msg *msg = rx->rx_msg;
492         struct kib_conn   *conn = rx->rx_conn;
493         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
494         struct kib_net *net = ni->ni_data;
495         int rc;
496         int err = -EIO;
497
498         LASSERT (net != NULL);
499         LASSERT (rx->rx_nob < 0);               /* was posted */
500         rx->rx_nob = 0;                         /* isn't now */
501
502         if (conn->ibc_state > IBLND_CONN_ESTABLISHED)
503                 goto ignore;
504
505         if (status != IB_WC_SUCCESS) {
506                 CNETERR("Rx from %s failed: %d\n",
507                         libcfs_nid2str(conn->ibc_peer->ibp_nid), status);
508                 goto failed;
509         }
510
511         LASSERT (nob >= 0);
512         rx->rx_nob = nob;
513
514         rc = kiblnd_unpack_msg(msg, rx->rx_nob);
515         if (rc != 0) {
516                 CERROR ("Error %d unpacking rx from %s\n",
517                         rc, libcfs_nid2str(conn->ibc_peer->ibp_nid));
518                 goto failed;
519         }
520
521         if (msg->ibm_srcnid != conn->ibc_peer->ibp_nid ||
522             msg->ibm_dstnid != ni->ni_nid ||
523             msg->ibm_srcstamp != conn->ibc_incarnation ||
524             msg->ibm_dststamp != net->ibn_incarnation) {
525                 CERROR ("Stale rx from %s\n",
526                         libcfs_nid2str(conn->ibc_peer->ibp_nid));
527                 err = -ESTALE;
528                 goto failed;
529         }
530
531         /* set time last known alive */
532         kiblnd_peer_alive(conn->ibc_peer);
533
534         /* racing with connection establishment/teardown! */
535
536         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
537                 rwlock_t  *g_lock = &kiblnd_data.kib_global_lock;
538                 unsigned long  flags;
539
540                 write_lock_irqsave(g_lock, flags);
541                 /* must check holding global lock to eliminate race */
542                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
543                         list_add_tail(&rx->rx_list, &conn->ibc_early_rxs);
544                         write_unlock_irqrestore(g_lock, flags);
545                         return;
546                 }
547                 write_unlock_irqrestore(g_lock, flags);
548         }
549         kiblnd_handle_rx(rx);
550         return;
551
552  failed:
553         CDEBUG(D_NET, "rx %p conn %p\n", rx, conn);
554         kiblnd_close_conn(conn, err);
555  ignore:
556         kiblnd_drop_rx(rx);                     /* Don't re-post rx. */
557 }
558
559 static int
560 kiblnd_fmr_map_tx(struct kib_net *net, struct kib_tx *tx,
561                   struct kib_rdma_desc *rd, u32 nob)
562 {
563         struct kib_hca_dev *hdev;
564         struct kib_dev *dev;
565         struct kib_fmr_poolset *fps;
566         int                     cpt;
567         int                     rc;
568         int i;
569
570         LASSERT(tx->tx_pool != NULL);
571         LASSERT(tx->tx_pool->tpo_pool.po_owner != NULL);
572
573         dev = net->ibn_dev;
574         hdev = tx->tx_pool->tpo_hdev;
575         cpt = tx->tx_pool->tpo_pool.po_owner->ps_cpt;
576
577         /*
578          * If we're dealing with FastReg, but the device doesn't
579          * support GAPS and the tx has GAPS, then there is no real point
580          * in trying to map the memory, because it'll just fail. So
581          * preemptively fail with an appropriate message
582          */
583         if ((dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED) &&
584             !(dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT) &&
585             tx->tx_gaps) {
586                 CERROR("Using FastReg with no GAPS support, but tx has gaps. "
587                        "Try setting use_fastreg_gaps to 1\n");
588                 return -EPROTONOSUPPORT;
589         }
590
591         /*
592          * FMR does not support gaps but the tx has gaps then
593          * we should make sure that the number of fragments we'll be sending
594          * over fits within the number of fragments negotiated on the
595          * connection, otherwise, we won't be able to RDMA the data.
596          * We need to maintain the number of fragments negotiation on the
597          * connection for backwards compatibility.
598          */
599         if (tx->tx_gaps && (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)) {
600                 if (tx->tx_conn &&
601                     tx->tx_conn->ibc_max_frags <= rd->rd_nfrags) {
602                         CERROR("TX number of frags (%d) is <= than connection"
603                                " number of frags (%d). Consider setting peer's"
604                                " map_on_demand to 256\n", tx->tx_nfrags,
605                                tx->tx_conn->ibc_max_frags);
606                         return -EFBIG;
607                 }
608         }
609
610         fps = net->ibn_fmr_ps[cpt];
611         rc = kiblnd_fmr_pool_map(fps, tx, rd, nob, 0, &tx->tx_fmr);
612         if (rc != 0) {
613                 CERROR("Can't map %u pages: %d\n", nob, rc);
614                 return rc;
615         }
616
617         /*
618          * If rd is not tx_rd, it's going to get sent to a peer_ni, who will
619          * need the rkey
620          */
621         rd->rd_key = tx->tx_fmr.fmr_key;
622         /*
623          * for FastReg or FMR with no gaps we can accumulate all
624          * the fragments in one FastReg or FMR fragment.
625          */
626         if (((dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED) && !tx->tx_gaps) ||
627             (dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED)) {
628                 /* FMR requires zero based address */
629                 if (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)
630                         rd->rd_frags[0].rf_addr &= ~hdev->ibh_page_mask;
631                 rd->rd_frags[0].rf_nob = nob;
632                 rd->rd_nfrags = 1;
633         } else {
634                 /*
635                  * We're transmitting with gaps using FMR.
636                  * We'll need to use multiple fragments and identify the
637                  * zero based address of each fragment.
638                  */
639                 for (i = 0; i < rd->rd_nfrags; i++) {
640                         rd->rd_frags[i].rf_addr &= ~hdev->ibh_page_mask;
641                         rd->rd_frags[i].rf_addr += i << hdev->ibh_page_shift;
642                 }
643         }
644
645         return 0;
646 }
647
648 static void
649 kiblnd_unmap_tx(struct kib_tx *tx)
650 {
651         if (tx->tx_fmr.fmr_pfmr || tx->tx_fmr.fmr_frd)
652                 kiblnd_fmr_pool_unmap(&tx->tx_fmr, tx->tx_status);
653
654         if (tx->tx_nfrags != 0) {
655                 kiblnd_dma_unmap_sg(tx->tx_pool->tpo_hdev->ibh_ibdev,
656                                     tx->tx_frags, tx->tx_nfrags, tx->tx_dmadir);
657                 tx->tx_nfrags = 0;
658         }
659 }
660
661 #ifdef HAVE_IB_GET_DMA_MR
662 static struct ib_mr *
663 kiblnd_find_rd_dma_mr(struct lnet_ni *ni, struct kib_rdma_desc *rd)
664 {
665         struct kib_net *net = ni->ni_data;
666         struct kib_hca_dev *hdev = net->ibn_dev->ibd_hdev;
667         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
668
669         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
670
671         /*
672          * if map-on-demand is turned on and the device supports
673          * either FMR or FastReg then use that. Otherwise use global
674          * memory regions. If that's not available either, then you're
675          * dead in the water and fail the operation.
676          */
677         if (tunables->lnd_map_on_demand &&
678             (net->ibn_dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED ||
679              net->ibn_dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED))
680                 return NULL;
681
682         /*
683          * hdev->ibh_mrs can be NULL. This case is dealt with gracefully
684          * in the call chain. The mapping will fail with appropriate error
685          * message.
686          */
687         return hdev->ibh_mrs;
688 }
689 #endif
690
691 static int kiblnd_map_tx(struct lnet_ni *ni, struct kib_tx *tx,
692                          struct kib_rdma_desc *rd, int nfrags)
693 {
694         struct kib_net *net = ni->ni_data;
695         struct kib_hca_dev *hdev = net->ibn_dev->ibd_hdev;
696 #ifdef HAVE_IB_GET_DMA_MR
697         struct ib_mr *mr = NULL;
698 #endif
699         __u32 nob;
700         int i;
701
702         /* If rd is not tx_rd, it's going to get sent to a peer_ni and I'm the
703          * RDMA sink */
704         tx->tx_dmadir = (rd != tx->tx_rd) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
705         tx->tx_nfrags = nfrags;
706
707         rd->rd_nfrags = kiblnd_dma_map_sg(hdev->ibh_ibdev, tx->tx_frags,
708                                           tx->tx_nfrags, tx->tx_dmadir);
709
710         for (i = 0, nob = 0; i < rd->rd_nfrags; i++) {
711                 rd->rd_frags[i].rf_nob  = kiblnd_sg_dma_len(
712                         hdev->ibh_ibdev, &tx->tx_frags[i]);
713                 rd->rd_frags[i].rf_addr = kiblnd_sg_dma_address(
714                         hdev->ibh_ibdev, &tx->tx_frags[i]);
715                 nob += rd->rd_frags[i].rf_nob;
716         }
717
718 #ifdef HAVE_IB_GET_DMA_MR
719         mr = kiblnd_find_rd_dma_mr(ni, rd);
720         if (mr != NULL) {
721                 /* found pre-mapping MR */
722                 rd->rd_key = (rd != tx->tx_rd) ? mr->rkey : mr->lkey;
723                 return 0;
724         }
725 #endif
726
727         if (net->ibn_fmr_ps != NULL)
728                 return kiblnd_fmr_map_tx(net, tx, rd, nob);
729
730         return -EINVAL;
731 }
732
733 static int kiblnd_setup_rd_iov(struct lnet_ni *ni, struct kib_tx *tx,
734                                struct kib_rdma_desc *rd, unsigned int niov,
735                                struct kvec *iov, int offset, int nob)
736 {
737         struct kib_net *net = ni->ni_data;
738         struct page *page;
739         struct scatterlist *sg;
740         unsigned long       vaddr;
741         int                 fragnob;
742         int                 page_offset;
743         unsigned int        max_niov;
744
745         LASSERT (nob > 0);
746         LASSERT (niov > 0);
747         LASSERT (net != NULL);
748
749         while (offset >= iov->iov_len) {
750                 offset -= iov->iov_len;
751                 niov--;
752                 iov++;
753                 LASSERT (niov > 0);
754         }
755
756         max_niov = niov;
757
758         sg = tx->tx_frags;
759         do {
760                 LASSERT(niov > 0);
761
762                 vaddr = ((unsigned long)iov->iov_base) + offset;
763                 page_offset = vaddr & (PAGE_SIZE - 1);
764                 page = lnet_kvaddr_to_page(vaddr);
765                 if (page == NULL) {
766                         CERROR("Can't find page\n");
767                         return -EFAULT;
768                 }
769
770                 fragnob = min((int)(iov->iov_len - offset), nob);
771                 fragnob = min(fragnob, (int)PAGE_SIZE - page_offset);
772
773                 /*
774                  * We're allowed to start at a non-aligned page offset in
775                  * the first fragment and end at a non-aligned page offset
776                  * in the last fragment.
777                  */
778                 if ((fragnob < (int)PAGE_SIZE - page_offset) &&
779                     (niov < max_niov) && nob > fragnob) {
780                         CDEBUG(D_NET, "fragnob %d < available page %d: with"
781                                       " remaining %d iovs with %d nob left\n",
782                                fragnob, (int)PAGE_SIZE - page_offset, niov,
783                                nob);
784                         tx->tx_gaps = true;
785                 }
786
787                 sg_set_page(sg, page, fragnob, page_offset);
788                 sg = sg_next(sg);
789                 if (!sg) {
790                         CERROR("lacking enough sg entries to map tx\n");
791                         return -EFAULT;
792                 }
793
794                 if (offset + fragnob < iov->iov_len) {
795                         offset += fragnob;
796                 } else {
797                         offset = 0;
798                         iov++;
799                         niov--;
800                 }
801                 nob -= fragnob;
802         } while (nob > 0);
803
804         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
805 }
806
807 static int kiblnd_setup_rd_kiov(struct lnet_ni *ni, struct kib_tx *tx,
808                                 struct kib_rdma_desc *rd, int nkiov,
809                                 lnet_kiov_t *kiov, int offset, int nob)
810 {
811         struct kib_net *net = ni->ni_data;
812         struct scatterlist *sg;
813         int                 fragnob;
814         int                 max_nkiov;
815
816         CDEBUG(D_NET, "niov %d offset %d nob %d\n", nkiov, offset, nob);
817
818         LASSERT(nob > 0);
819         LASSERT(nkiov > 0);
820         LASSERT(net != NULL);
821
822         while (offset >= kiov->kiov_len) {
823                 offset -= kiov->kiov_len;
824                 nkiov--;
825                 kiov++;
826                 LASSERT(nkiov > 0);
827         }
828
829         max_nkiov = nkiov;
830
831         sg = tx->tx_frags;
832         do {
833                 LASSERT(nkiov > 0);
834
835                 fragnob = min((int)(kiov->kiov_len - offset), nob);
836
837                 /*
838                  * We're allowed to start at a non-aligned page offset in
839                  * the first fragment and end at a non-aligned page offset
840                  * in the last fragment.
841                  */
842                 if ((fragnob < (int)(kiov->kiov_len - offset)) &&
843                     nkiov < max_nkiov && nob > fragnob) {
844                         CDEBUG(D_NET, "fragnob %d < available page %d: with"
845                                       " remaining %d kiovs with %d nob left\n",
846                                fragnob, (int)(kiov->kiov_len - offset),
847                                nkiov, nob);
848                         tx->tx_gaps = true;
849                 }
850
851                 sg_set_page(sg, kiov->kiov_page, fragnob,
852                             kiov->kiov_offset + offset);
853                 sg = sg_next(sg);
854                 if (!sg) {
855                         CERROR("lacking enough sg entries to map tx\n");
856                         return -EFAULT;
857                 }
858
859                 offset = 0;
860                 kiov++;
861                 nkiov--;
862                 nob -= fragnob;
863         } while (nob > 0);
864
865         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
866 }
867
868 static int
869 kiblnd_post_tx_locked(struct kib_conn *conn, struct kib_tx *tx, int credit)
870 __must_hold(&conn->ibc_lock)
871 {
872         struct kib_msg *msg = tx->tx_msg;
873         struct kib_peer_ni *peer_ni = conn->ibc_peer;
874         struct lnet_ni *ni = peer_ni->ibp_ni;
875         int ver = conn->ibc_version;
876         int rc;
877         int done;
878
879         LASSERT(tx->tx_queued);
880         /* We rely on this for QP sizing */
881         LASSERT(tx->tx_nwrq > 0 && tx->tx_nsge >= 0);
882         LASSERT(tx->tx_nwrq <= 1 + conn->ibc_max_frags);
883
884         LASSERT(credit == 0 || credit == 1);
885         LASSERT(conn->ibc_outstanding_credits >= 0);
886         LASSERT(conn->ibc_outstanding_credits <= conn->ibc_queue_depth);
887         LASSERT(conn->ibc_credits >= 0);
888         LASSERT(conn->ibc_credits <= conn->ibc_queue_depth);
889
890         if (conn->ibc_nsends_posted ==
891             kiblnd_concurrent_sends(ver, ni)) {
892                 /* tx completions outstanding... */
893                 CDEBUG(D_NET, "%s: posted enough\n",
894                        libcfs_nid2str(peer_ni->ibp_nid));
895                 return -EAGAIN;
896         }
897
898         if (credit != 0 && conn->ibc_credits == 0) {   /* no credits */
899                 CDEBUG(D_NET, "%s: no credits\n",
900                        libcfs_nid2str(peer_ni->ibp_nid));
901                 return -EAGAIN;
902         }
903
904         if (credit != 0 && !IBLND_OOB_CAPABLE(ver) &&
905             conn->ibc_credits == 1 &&   /* last credit reserved */
906             msg->ibm_type != IBLND_MSG_NOOP) {      /* for NOOP */
907                 CDEBUG(D_NET, "%s: not using last credit\n",
908                        libcfs_nid2str(peer_ni->ibp_nid));
909                 return -EAGAIN;
910         }
911
912         /* NB don't drop ibc_lock before bumping tx_sending */
913         list_del(&tx->tx_list);
914         tx->tx_queued = 0;
915
916         if (msg->ibm_type == IBLND_MSG_NOOP &&
917             (!kiblnd_need_noop(conn) ||     /* redundant NOOP */
918              (IBLND_OOB_CAPABLE(ver) && /* posted enough NOOP */
919               conn->ibc_noops_posted == IBLND_OOB_MSGS(ver)))) {
920                 /* OK to drop when posted enough NOOPs, since
921                  * kiblnd_check_sends_locked will queue NOOP again when
922                  * posted NOOPs complete */
923                 spin_unlock(&conn->ibc_lock);
924                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
925                 kiblnd_tx_done(tx);
926                 spin_lock(&conn->ibc_lock);
927                 CDEBUG(D_NET, "%s(%d): redundant or enough NOOP\n",
928                        libcfs_nid2str(peer_ni->ibp_nid),
929                        conn->ibc_noops_posted);
930                 return 0;
931         }
932
933         kiblnd_pack_msg(peer_ni->ibp_ni, msg, ver, conn->ibc_outstanding_credits,
934                         peer_ni->ibp_nid, conn->ibc_incarnation);
935
936         conn->ibc_credits -= credit;
937         conn->ibc_outstanding_credits = 0;
938         conn->ibc_nsends_posted++;
939         if (msg->ibm_type == IBLND_MSG_NOOP)
940                 conn->ibc_noops_posted++;
941
942         /* CAVEAT EMPTOR!  This tx could be the PUT_DONE of an RDMA
943          * PUT.  If so, it was first queued here as a PUT_REQ, sent and
944          * stashed on ibc_active_txs, matched by an incoming PUT_ACK,
945          * and then re-queued here.  It's (just) possible that
946          * tx_sending is non-zero if we've not done the tx_complete()
947          * from the first send; hence the ++ rather than = below. */
948         tx->tx_sending++;
949         list_add(&tx->tx_list, &conn->ibc_active_txs);
950
951         /* I'm still holding ibc_lock! */
952         if (conn->ibc_state != IBLND_CONN_ESTABLISHED) {
953                 rc = -ECONNABORTED;
954         } else if (tx->tx_pool->tpo_pool.po_failed ||
955                  conn->ibc_hdev != tx->tx_pool->tpo_hdev) {
956                 /* close_conn will launch failover */
957                 rc = -ENETDOWN;
958         } else {
959                 struct kib_fast_reg_descriptor *frd = tx->tx_fmr.fmr_frd;
960                 struct ib_send_wr *bad = &tx->tx_wrq[tx->tx_nwrq - 1].wr;
961                 struct ib_send_wr *wr  = &tx->tx_wrq[0].wr;
962
963                 if (frd != NULL) {
964                         if (!frd->frd_valid) {
965                                 wr = &frd->frd_inv_wr.wr;
966                                 wr->next = &frd->frd_fastreg_wr.wr;
967                         } else {
968                                 wr = &frd->frd_fastreg_wr.wr;
969                         }
970                         frd->frd_fastreg_wr.wr.next = &tx->tx_wrq[0].wr;
971                 }
972
973                 LASSERTF(bad->wr_id == kiblnd_ptr2wreqid(tx, IBLND_WID_TX),
974                          "bad wr_id %#llx, opc %d, flags %d, peer_ni: %s\n",
975                          bad->wr_id, bad->opcode, bad->send_flags,
976                          libcfs_nid2str(conn->ibc_peer->ibp_nid));
977
978                 bad = NULL;
979                 if (lnet_send_error_simulation(tx->tx_lntmsg[0], &tx->tx_hstatus))
980                         rc = -EINVAL;
981                 else
982 #ifdef HAVE_IB_POST_SEND_RECV_CONST
983                         rc = ib_post_send(conn->ibc_cmid->qp, wr,
984                                           (const struct ib_send_wr **)&bad);
985 #else
986                         rc = ib_post_send(conn->ibc_cmid->qp, wr, &bad);
987 #endif
988         }
989
990         conn->ibc_last_send = ktime_get();
991
992         if (rc == 0)
993                 return 0;
994
995         /* NB credits are transferred in the actual
996          * message, which can only be the last work item */
997         conn->ibc_credits += credit;
998         conn->ibc_outstanding_credits += msg->ibm_credits;
999         conn->ibc_nsends_posted--;
1000         if (msg->ibm_type == IBLND_MSG_NOOP)
1001                 conn->ibc_noops_posted--;
1002
1003         tx->tx_status = rc;
1004         tx->tx_waiting = 0;
1005         tx->tx_sending--;
1006
1007         done = (tx->tx_sending == 0);
1008         if (done)
1009                 list_del(&tx->tx_list);
1010
1011         spin_unlock(&conn->ibc_lock);
1012
1013         if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1014                 CERROR("Error %d posting transmit to %s\n",
1015                        rc, libcfs_nid2str(peer_ni->ibp_nid));
1016         else
1017                 CDEBUG(D_NET, "Error %d posting transmit to %s\n",
1018                        rc, libcfs_nid2str(peer_ni->ibp_nid));
1019
1020         kiblnd_close_conn(conn, rc);
1021
1022         if (done)
1023                 kiblnd_tx_done(tx);
1024
1025         spin_lock(&conn->ibc_lock);
1026
1027         return -EIO;
1028 }
1029
1030 static void
1031 kiblnd_check_sends_locked(struct kib_conn *conn)
1032 {
1033         int ver = conn->ibc_version;
1034         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
1035         struct kib_tx *tx;
1036
1037         /* Don't send anything until after the connection is established */
1038         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
1039                 CDEBUG(D_NET, "%s too soon\n",
1040                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
1041                 return;
1042         }
1043
1044         LASSERT(conn->ibc_nsends_posted <=
1045                 kiblnd_concurrent_sends(ver, ni));
1046         LASSERT (!IBLND_OOB_CAPABLE(ver) ||
1047                  conn->ibc_noops_posted <= IBLND_OOB_MSGS(ver));
1048         LASSERT (conn->ibc_reserved_credits >= 0);
1049
1050         while (conn->ibc_reserved_credits > 0 &&
1051                !list_empty(&conn->ibc_tx_queue_rsrvd)) {
1052                 tx = list_entry(conn->ibc_tx_queue_rsrvd.next,
1053                                 struct kib_tx, tx_list);
1054                 list_move_tail(&tx->tx_list, &conn->ibc_tx_queue);
1055                 conn->ibc_reserved_credits--;
1056         }
1057
1058         if (kiblnd_need_noop(conn)) {
1059                 spin_unlock(&conn->ibc_lock);
1060
1061                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1062                 if (tx != NULL)
1063                         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_NOOP, 0);
1064
1065                 spin_lock(&conn->ibc_lock);
1066                 if (tx != NULL)
1067                         kiblnd_queue_tx_locked(tx, conn);
1068         }
1069
1070         for (;;) {
1071                 int credit;
1072
1073                 if (!list_empty(&conn->ibc_tx_queue_nocred)) {
1074                         credit = 0;
1075                         tx = list_entry(conn->ibc_tx_queue_nocred.next,
1076                                         struct kib_tx, tx_list);
1077                 } else if (!list_empty(&conn->ibc_tx_noops)) {
1078                         LASSERT (!IBLND_OOB_CAPABLE(ver));
1079                         credit = 1;
1080                         tx = list_entry(conn->ibc_tx_noops.next,
1081                                         struct kib_tx, tx_list);
1082                 } else if (!list_empty(&conn->ibc_tx_queue)) {
1083                         credit = 1;
1084                         tx = list_entry(conn->ibc_tx_queue.next,
1085                                         struct kib_tx, tx_list);
1086                 } else
1087                         break;
1088
1089                 if (kiblnd_post_tx_locked(conn, tx, credit) != 0)
1090                         break;
1091         }
1092 }
1093
1094 static void
1095 kiblnd_tx_complete(struct kib_tx *tx, int status)
1096 {
1097         int           failed = (status != IB_WC_SUCCESS);
1098         struct kib_conn   *conn = tx->tx_conn;
1099         int           idle;
1100
1101         LASSERT (tx->tx_sending > 0);
1102
1103         if (failed) {
1104                 if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1105                         CNETERR("Tx -> %s cookie %#llx"
1106                                 " sending %d waiting %d: failed %d\n",
1107                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
1108                                 tx->tx_cookie, tx->tx_sending, tx->tx_waiting,
1109                                 status);
1110
1111                 kiblnd_close_conn(conn, -EIO);
1112         } else {
1113                 kiblnd_peer_alive(conn->ibc_peer);
1114         }
1115
1116         spin_lock(&conn->ibc_lock);
1117
1118         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
1119          * gets to free it, which also drops its ref on 'conn'. */
1120
1121         tx->tx_sending--;
1122         conn->ibc_nsends_posted--;
1123         if (tx->tx_msg->ibm_type == IBLND_MSG_NOOP)
1124                 conn->ibc_noops_posted--;
1125
1126         if (failed) {
1127                 tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
1128                 tx->tx_waiting = 0;             /* don't wait for peer_ni */
1129                 tx->tx_status = -EIO;
1130         }
1131
1132         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
1133                !tx->tx_waiting &&               /* Not waiting for peer_ni */
1134                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
1135         if (idle)
1136                 list_del(&tx->tx_list);
1137
1138         kiblnd_check_sends_locked(conn);
1139         spin_unlock(&conn->ibc_lock);
1140
1141         if (idle)
1142                 kiblnd_tx_done(tx);
1143 }
1144
1145 static void
1146 kiblnd_init_tx_msg(struct lnet_ni *ni, struct kib_tx *tx, int type,
1147                    int body_nob)
1148 {
1149         struct kib_hca_dev *hdev = tx->tx_pool->tpo_hdev;
1150         struct ib_sge *sge = &tx->tx_msgsge;
1151         struct ib_rdma_wr *wrq;
1152         int nob = offsetof(struct kib_msg, ibm_u) + body_nob;
1153 #ifdef HAVE_IB_GET_DMA_MR
1154         struct ib_mr *mr = hdev->ibh_mrs;
1155 #endif
1156
1157         LASSERT(tx->tx_nwrq >= 0);
1158         LASSERT(tx->tx_nwrq < IBLND_MAX_RDMA_FRAGS + 1);
1159         LASSERT(nob <= IBLND_MSG_SIZE);
1160 #ifdef HAVE_IB_GET_DMA_MR
1161         LASSERT(mr != NULL);
1162 #endif
1163
1164         kiblnd_init_msg(tx->tx_msg, type, body_nob);
1165
1166 #ifdef HAVE_IB_GET_DMA_MR
1167         sge->lkey   = mr->lkey;
1168 #else
1169         sge->lkey   = hdev->ibh_pd->local_dma_lkey;
1170 #endif
1171         sge->addr   = tx->tx_msgaddr;
1172         sge->length = nob;
1173
1174         wrq = &tx->tx_wrq[tx->tx_nwrq];
1175         memset(wrq, 0, sizeof(*wrq));
1176
1177         wrq->wr.next            = NULL;
1178         wrq->wr.wr_id           = kiblnd_ptr2wreqid(tx, IBLND_WID_TX);
1179         wrq->wr.sg_list         = sge;
1180         wrq->wr.num_sge         = 1;
1181         wrq->wr.opcode          = IB_WR_SEND;
1182         wrq->wr.send_flags      = IB_SEND_SIGNALED;
1183
1184         tx->tx_nwrq++;
1185 }
1186
1187 static int
1188 kiblnd_init_rdma(struct kib_conn *conn, struct kib_tx *tx, int type,
1189                  int resid, struct kib_rdma_desc *dstrd, u64 dstcookie)
1190 {
1191         struct kib_msg *ibmsg = tx->tx_msg;
1192         struct kib_rdma_desc *srcrd = tx->tx_rd;
1193         struct ib_rdma_wr *wrq = NULL;
1194         struct ib_sge     *sge;
1195         int                rc  = resid;
1196         int                srcidx;
1197         int                dstidx;
1198         int                sge_nob;
1199         int                wrq_sge;
1200
1201         LASSERT(!in_interrupt());
1202         LASSERT(tx->tx_nwrq == 0 && tx->tx_nsge == 0);
1203         LASSERT(type == IBLND_MSG_GET_DONE || type == IBLND_MSG_PUT_DONE);
1204
1205         for (srcidx = dstidx = wrq_sge = sge_nob = 0;
1206              resid > 0; resid -= sge_nob) {
1207                 int     prev = dstidx;
1208
1209                 if (srcidx >= srcrd->rd_nfrags) {
1210                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1211                         rc = -EPROTO;
1212                         break;
1213                 }
1214
1215                 if (dstidx >= dstrd->rd_nfrags) {
1216                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1217                         rc = -EPROTO;
1218                         break;
1219                 }
1220
1221                 if (tx->tx_nwrq >= conn->ibc_max_frags) {
1222                         CERROR("RDMA has too many fragments for peer_ni %s (%d), "
1223                                "src idx/frags: %d/%d dst idx/frags: %d/%d\n",
1224                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
1225                                conn->ibc_max_frags,
1226                                srcidx, srcrd->rd_nfrags,
1227                                dstidx, dstrd->rd_nfrags);
1228                         rc = -EMSGSIZE;
1229                         break;
1230                 }
1231
1232                 sge_nob = MIN(MIN(kiblnd_rd_frag_size(srcrd, srcidx),
1233                                   kiblnd_rd_frag_size(dstrd, dstidx)), resid);
1234
1235                 sge = &tx->tx_sge[tx->tx_nsge];
1236                 sge->addr   = kiblnd_rd_frag_addr(srcrd, srcidx);
1237                 sge->lkey   = kiblnd_rd_frag_key(srcrd, srcidx);
1238                 sge->length = sge_nob;
1239
1240                 if (wrq_sge == 0) {
1241                         wrq = &tx->tx_wrq[tx->tx_nwrq];
1242
1243                         wrq->wr.next    = &(wrq + 1)->wr;
1244                         wrq->wr.wr_id   = kiblnd_ptr2wreqid(tx, IBLND_WID_RDMA);
1245                         wrq->wr.sg_list = sge;
1246                         wrq->wr.opcode  = IB_WR_RDMA_WRITE;
1247                         wrq->wr.send_flags = 0;
1248
1249 #ifdef HAVE_IB_RDMA_WR
1250                         wrq->remote_addr        = kiblnd_rd_frag_addr(dstrd,
1251                                                                       dstidx);
1252                         wrq->rkey               = kiblnd_rd_frag_key(dstrd,
1253                                                                      dstidx);
1254 #else
1255                         wrq->wr.wr.rdma.remote_addr = kiblnd_rd_frag_addr(dstrd,
1256                                                                         dstidx);
1257                         wrq->wr.wr.rdma.rkey    = kiblnd_rd_frag_key(dstrd,
1258                                                                      dstidx);
1259 #endif
1260                 }
1261
1262                 srcidx = kiblnd_rd_consume_frag(srcrd, srcidx, sge_nob);
1263                 dstidx = kiblnd_rd_consume_frag(dstrd, dstidx, sge_nob);
1264
1265                 wrq_sge++;
1266                 if (wrq_sge == *kiblnd_tunables.kib_wrq_sge || dstidx != prev) {
1267                         tx->tx_nwrq++;
1268                         wrq->wr.num_sge = wrq_sge;
1269                         wrq_sge = 0;
1270                 }
1271                 tx->tx_nsge++;
1272         }
1273
1274         if (rc < 0)     /* no RDMA if completing with failure */
1275                 tx->tx_nwrq = tx->tx_nsge = 0;
1276
1277         ibmsg->ibm_u.completion.ibcm_status = rc;
1278         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1279         kiblnd_init_tx_msg(conn->ibc_peer->ibp_ni, tx,
1280                            type, sizeof(struct kib_completion_msg));
1281
1282         return rc;
1283 }
1284
1285 static void
1286 kiblnd_queue_tx_locked(struct kib_tx *tx, struct kib_conn *conn)
1287 {
1288         struct list_head *q;
1289         s64 timeout_ns;
1290
1291         LASSERT(tx->tx_nwrq > 0);       /* work items set up */
1292         LASSERT(!tx->tx_queued);        /* not queued for sending already */
1293         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1294
1295         if (conn->ibc_state >= IBLND_CONN_DISCONNECTED) {
1296                 tx->tx_status = -ECONNABORTED;
1297                 tx->tx_waiting = 0;
1298                 if (tx->tx_conn != NULL) {
1299                         /* PUT_DONE first attached to conn as a PUT_REQ */
1300                         LASSERT(tx->tx_conn == conn);
1301                         LASSERT(tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1302                         tx->tx_conn = NULL;
1303                         kiblnd_conn_decref(conn);
1304                 }
1305                 list_add(&tx->tx_list, &conn->ibc_zombie_txs);
1306
1307                 return;
1308         }
1309
1310         timeout_ns = lnet_get_lnd_timeout() * NSEC_PER_SEC;
1311         tx->tx_queued = 1;
1312         tx->tx_deadline = ktime_add_ns(ktime_get(), timeout_ns);
1313
1314         if (tx->tx_conn == NULL) {
1315                 kiblnd_conn_addref(conn);
1316                 tx->tx_conn = conn;
1317                 LASSERT (tx->tx_msg->ibm_type != IBLND_MSG_PUT_DONE);
1318         } else {
1319                 /* PUT_DONE first attached to conn as a PUT_REQ */
1320                 LASSERT (tx->tx_conn == conn);
1321                 LASSERT (tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1322         }
1323
1324         switch (tx->tx_msg->ibm_type) {
1325         default:
1326                 LBUG();
1327
1328         case IBLND_MSG_PUT_REQ:
1329         case IBLND_MSG_GET_REQ:
1330                 q = &conn->ibc_tx_queue_rsrvd;
1331                 break;
1332
1333         case IBLND_MSG_PUT_NAK:
1334         case IBLND_MSG_PUT_ACK:
1335         case IBLND_MSG_PUT_DONE:
1336         case IBLND_MSG_GET_DONE:
1337                 q = &conn->ibc_tx_queue_nocred;
1338                 break;
1339
1340         case IBLND_MSG_NOOP:
1341                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
1342                         q = &conn->ibc_tx_queue_nocred;
1343                 else
1344                         q = &conn->ibc_tx_noops;
1345                 break;
1346
1347         case IBLND_MSG_IMMEDIATE:
1348                 q = &conn->ibc_tx_queue;
1349                 break;
1350         }
1351
1352         list_add_tail(&tx->tx_list, q);
1353 }
1354
1355 static void
1356 kiblnd_queue_tx(struct kib_tx *tx, struct kib_conn *conn)
1357 {
1358         spin_lock(&conn->ibc_lock);
1359         kiblnd_queue_tx_locked(tx, conn);
1360         kiblnd_check_sends_locked(conn);
1361         spin_unlock(&conn->ibc_lock);
1362 }
1363
1364 static int kiblnd_resolve_addr(struct rdma_cm_id *cmid,
1365                                struct sockaddr_in *srcaddr,
1366                                struct sockaddr_in *dstaddr,
1367                                int timeout_ms)
1368 {
1369         unsigned short port;
1370         int rc;
1371
1372         /* allow the port to be reused */
1373         rc = rdma_set_reuseaddr(cmid, 1);
1374         if (rc != 0) {
1375                 CERROR("Unable to set reuse on cmid: %d\n", rc);
1376                 return rc;
1377         }
1378
1379         /* look for a free privileged port */
1380         for (port = PROT_SOCK-1; port > 0; port--) {
1381                 srcaddr->sin_port = htons(port);
1382                 rc = rdma_resolve_addr(cmid,
1383                                        (struct sockaddr *)srcaddr,
1384                                        (struct sockaddr *)dstaddr,
1385                                        timeout_ms);
1386                 if (rc == 0) {
1387                         CDEBUG(D_NET, "bound to port %hu\n", port);
1388                         return 0;
1389                 } else if (rc == -EADDRINUSE || rc == -EADDRNOTAVAIL) {
1390                         CDEBUG(D_NET, "bind to port %hu failed: %d\n",
1391                                port, rc);
1392                 } else {
1393                         return rc;
1394                 }
1395         }
1396
1397         CERROR("Failed to bind to a free privileged port\n");
1398         return rc;
1399 }
1400
1401 static void
1402 kiblnd_connect_peer(struct kib_peer_ni *peer_ni)
1403 {
1404         struct rdma_cm_id *cmid;
1405         struct kib_dev *dev;
1406         struct kib_net *net = peer_ni->ibp_ni->ni_data;
1407         struct sockaddr_in srcaddr;
1408         struct sockaddr_in dstaddr;
1409         int rc;
1410
1411         LASSERT (net != NULL);
1412         LASSERT (peer_ni->ibp_connecting > 0);
1413
1414         cmid = kiblnd_rdma_create_id(peer_ni->ibp_ni->ni_net_ns,
1415                                      kiblnd_cm_callback, peer_ni,
1416                                      RDMA_PS_TCP, IB_QPT_RC);
1417
1418         if (IS_ERR(cmid)) {
1419                 CERROR("Can't create CMID for %s: %ld\n",
1420                        libcfs_nid2str(peer_ni->ibp_nid), PTR_ERR(cmid));
1421                 rc = PTR_ERR(cmid);
1422                 goto failed;
1423         }
1424
1425         dev = net->ibn_dev;
1426         memset(&srcaddr, 0, sizeof(srcaddr));
1427         srcaddr.sin_family = AF_INET;
1428         srcaddr.sin_addr.s_addr = htonl(dev->ibd_ifip);
1429
1430         memset(&dstaddr, 0, sizeof(dstaddr));
1431         dstaddr.sin_family = AF_INET;
1432         dstaddr.sin_port = htons(*kiblnd_tunables.kib_service);
1433         dstaddr.sin_addr.s_addr = htonl(LNET_NIDADDR(peer_ni->ibp_nid));
1434
1435         kiblnd_peer_addref(peer_ni);               /* cmid's ref */
1436
1437         if (*kiblnd_tunables.kib_use_priv_port) {
1438                 rc = kiblnd_resolve_addr(cmid, &srcaddr, &dstaddr,
1439                                          lnet_get_lnd_timeout() * 1000);
1440         } else {
1441                 rc = rdma_resolve_addr(cmid,
1442                                        (struct sockaddr *)&srcaddr,
1443                                        (struct sockaddr *)&dstaddr,
1444                                        lnet_get_lnd_timeout() * 1000);
1445         }
1446         if (rc != 0) {
1447                 /* Can't initiate address resolution:  */
1448                 CERROR("Can't resolve addr for %s: %d\n",
1449                        libcfs_nid2str(peer_ni->ibp_nid), rc);
1450                 goto failed2;
1451         }
1452
1453         return;
1454
1455  failed2:
1456         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1457         kiblnd_peer_decref(peer_ni);               /* cmid's ref */
1458         rdma_destroy_id(cmid);
1459         return;
1460  failed:
1461         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1462 }
1463
1464 bool
1465 kiblnd_reconnect_peer(struct kib_peer_ni *peer_ni)
1466 {
1467         rwlock_t *glock = &kiblnd_data.kib_global_lock;
1468         char *reason = NULL;
1469         LIST_HEAD(txs);
1470         unsigned long flags;
1471
1472         write_lock_irqsave(glock, flags);
1473         if (peer_ni->ibp_reconnecting == 0) {
1474                 if (peer_ni->ibp_accepting)
1475                         reason = "accepting";
1476                 else if (peer_ni->ibp_connecting)
1477                         reason = "connecting";
1478                 else if (!list_empty(&peer_ni->ibp_conns))
1479                         reason = "connected";
1480                 else /* connected then closed */
1481                         reason = "closed";
1482
1483                 goto no_reconnect;
1484         }
1485
1486         if (peer_ni->ibp_accepting)
1487                 CNETERR("Detecting race between accepting and reconnecting\n");
1488         peer_ni->ibp_reconnecting--;
1489
1490         if (!kiblnd_peer_active(peer_ni)) {
1491                 list_splice_init(&peer_ni->ibp_tx_queue, &txs);
1492                 reason = "unlinked";
1493                 goto no_reconnect;
1494         }
1495
1496         peer_ni->ibp_connecting++;
1497         peer_ni->ibp_reconnected++;
1498
1499         write_unlock_irqrestore(glock, flags);
1500
1501         kiblnd_connect_peer(peer_ni);
1502         return true;
1503
1504  no_reconnect:
1505         write_unlock_irqrestore(glock, flags);
1506
1507         CWARN("Abort reconnection of %s: %s\n",
1508               libcfs_nid2str(peer_ni->ibp_nid), reason);
1509         kiblnd_txlist_done(&txs, -ECONNABORTED,
1510                            LNET_MSG_STATUS_LOCAL_ABORTED);
1511         return false;
1512 }
1513
1514 void
1515 kiblnd_launch_tx(struct lnet_ni *ni, struct kib_tx *tx, lnet_nid_t nid)
1516 {
1517         struct kib_peer_ni *peer_ni;
1518         struct kib_peer_ni *peer2;
1519         struct kib_conn *conn;
1520         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
1521         unsigned long      flags;
1522         int                rc;
1523         int                i;
1524         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
1525
1526         /* If I get here, I've committed to send, so I complete the tx with
1527          * failure on any problems */
1528
1529         LASSERT (tx == NULL || tx->tx_conn == NULL); /* only set when assigned a conn */
1530         LASSERT (tx == NULL || tx->tx_nwrq > 0);     /* work items have been set up */
1531
1532         /* First time, just use a read lock since I expect to find my peer_ni
1533          * connected */
1534         read_lock_irqsave(g_lock, flags);
1535
1536         peer_ni = kiblnd_find_peer_locked(ni, nid);
1537         if (peer_ni != NULL && !list_empty(&peer_ni->ibp_conns)) {
1538                 /* Found a peer_ni with an established connection */
1539                 conn = kiblnd_get_conn_locked(peer_ni);
1540                 kiblnd_conn_addref(conn); /* 1 ref for me... */
1541
1542                 read_unlock_irqrestore(g_lock, flags);
1543
1544                 if (tx != NULL)
1545                         kiblnd_queue_tx(tx, conn);
1546                 kiblnd_conn_decref(conn); /* ...to here */
1547                 return;
1548         }
1549
1550         read_unlock(g_lock);
1551         /* Re-try with a write lock */
1552         write_lock(g_lock);
1553
1554         peer_ni = kiblnd_find_peer_locked(ni, nid);
1555         if (peer_ni != NULL) {
1556                 if (list_empty(&peer_ni->ibp_conns)) {
1557                         /* found a peer_ni, but it's still connecting... */
1558                         LASSERT(kiblnd_peer_connecting(peer_ni));
1559                         if (tx != NULL)
1560                                 list_add_tail(&tx->tx_list,
1561                                                   &peer_ni->ibp_tx_queue);
1562                         write_unlock_irqrestore(g_lock, flags);
1563                 } else {
1564                         conn = kiblnd_get_conn_locked(peer_ni);
1565                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1566
1567                         write_unlock_irqrestore(g_lock, flags);
1568
1569                         if (tx != NULL)
1570                                 kiblnd_queue_tx(tx, conn);
1571                         kiblnd_conn_decref(conn); /* ...to here */
1572                 }
1573                 return;
1574         }
1575
1576         write_unlock_irqrestore(g_lock, flags);
1577
1578         /* Allocate a peer_ni ready to add to the peer_ni table and retry */
1579         rc = kiblnd_create_peer(ni, &peer_ni, nid);
1580         if (rc != 0) {
1581                 CERROR("Can't create peer_ni %s\n", libcfs_nid2str(nid));
1582                 if (tx != NULL) {
1583                         tx->tx_status = -EHOSTUNREACH;
1584                         tx->tx_waiting = 0;
1585                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1586                         kiblnd_tx_done(tx);
1587                 }
1588                 return;
1589         }
1590
1591         write_lock_irqsave(g_lock, flags);
1592
1593         peer2 = kiblnd_find_peer_locked(ni, nid);
1594         if (peer2 != NULL) {
1595                 if (list_empty(&peer2->ibp_conns)) {
1596                         /* found a peer_ni, but it's still connecting... */
1597                         LASSERT(kiblnd_peer_connecting(peer2));
1598                         if (tx != NULL)
1599                                 list_add_tail(&tx->tx_list,
1600                                                   &peer2->ibp_tx_queue);
1601                         write_unlock_irqrestore(g_lock, flags);
1602                 } else {
1603                         conn = kiblnd_get_conn_locked(peer2);
1604                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1605
1606                         write_unlock_irqrestore(g_lock, flags);
1607
1608                         if (tx != NULL)
1609                                 kiblnd_queue_tx(tx, conn);
1610                         kiblnd_conn_decref(conn); /* ...to here */
1611                 }
1612
1613                 kiblnd_peer_decref(peer_ni);
1614                 return;
1615         }
1616
1617         /* Brand new peer_ni */
1618         LASSERT(peer_ni->ibp_connecting == 0);
1619         tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
1620         peer_ni->ibp_connecting = tunables->lnd_conns_per_peer;
1621
1622         /* always called with a ref on ni, which prevents ni being shutdown */
1623         LASSERT(((struct kib_net *)ni->ni_data)->ibn_shutdown == 0);
1624
1625         if (tx != NULL)
1626                 list_add_tail(&tx->tx_list, &peer_ni->ibp_tx_queue);
1627
1628         kiblnd_peer_addref(peer_ni);
1629         list_add_tail(&peer_ni->ibp_list, kiblnd_nid2peerlist(nid));
1630
1631         write_unlock_irqrestore(g_lock, flags);
1632
1633         for (i = 0; i < tunables->lnd_conns_per_peer; i++)
1634                 kiblnd_connect_peer(peer_ni);
1635         kiblnd_peer_decref(peer_ni);
1636 }
1637
1638 int
1639 kiblnd_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg)
1640 {
1641         struct lnet_hdr *hdr = &lntmsg->msg_hdr;
1642         int               type = lntmsg->msg_type;
1643         struct lnet_process_id target = lntmsg->msg_target;
1644         int               target_is_router = lntmsg->msg_target_is_router;
1645         int               routing = lntmsg->msg_routing;
1646         unsigned int      payload_niov = lntmsg->msg_niov;
1647         struct kvec      *payload_iov = lntmsg->msg_iov;
1648         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
1649         unsigned int      payload_offset = lntmsg->msg_offset;
1650         unsigned int      payload_nob = lntmsg->msg_len;
1651         struct kib_msg *ibmsg;
1652         struct kib_rdma_desc *rd;
1653         struct kib_tx *tx;
1654         int               nob;
1655         int               rc;
1656
1657         /* NB 'private' is different depending on what we're sending.... */
1658
1659         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1660                payload_nob, payload_niov, libcfs_id2str(target));
1661
1662         LASSERT (payload_nob == 0 || payload_niov > 0);
1663         LASSERT (payload_niov <= LNET_MAX_IOV);
1664
1665         /* Thread context */
1666         LASSERT (!in_interrupt());
1667         /* payload is either all vaddrs or all pages */
1668         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1669
1670         switch (type) {
1671         default:
1672                 LBUG();
1673                 return (-EIO);
1674
1675         case LNET_MSG_ACK:
1676                 LASSERT (payload_nob == 0);
1677                 break;
1678
1679         case LNET_MSG_GET:
1680                 if (routing || target_is_router)
1681                         break;                  /* send IMMEDIATE */
1682
1683                 /* is the REPLY message too small for RDMA? */
1684                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1685                 if (nob <= IBLND_MSG_SIZE)
1686                         break;                  /* send IMMEDIATE */
1687
1688                 tx = kiblnd_get_idle_tx(ni, target.nid);
1689                 if (tx == NULL) {
1690                         CERROR("Can't allocate txd for GET to %s\n",
1691                                libcfs_nid2str(target.nid));
1692                         return -ENOMEM;
1693                 }
1694
1695                 ibmsg = tx->tx_msg;
1696                 rd = &ibmsg->ibm_u.get.ibgm_rd;
1697                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0)
1698                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1699                                                  lntmsg->msg_md->md_niov,
1700                                                  lntmsg->msg_md->md_iov.iov,
1701                                                  0, lntmsg->msg_md->md_length);
1702                 else
1703                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1704                                                   lntmsg->msg_md->md_niov,
1705                                                   lntmsg->msg_md->md_iov.kiov,
1706                                                   0, lntmsg->msg_md->md_length);
1707                 if (rc != 0) {
1708                         CERROR("Can't setup GET sink for %s: %d\n",
1709                                libcfs_nid2str(target.nid), rc);
1710                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1711                         kiblnd_tx_done(tx);
1712                         return -EIO;
1713                 }
1714
1715                 nob = offsetof(struct kib_get_msg, ibgm_rd.rd_frags[rd->rd_nfrags]);
1716                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1717                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1718
1719                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1720
1721                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1722                 if (tx->tx_lntmsg[1] == NULL) {
1723                         CERROR("Can't create reply for GET -> %s\n",
1724                                libcfs_nid2str(target.nid));
1725                         kiblnd_tx_done(tx);
1726                         return -EIO;
1727                 }
1728
1729                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1730                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1731                 kiblnd_launch_tx(ni, tx, target.nid);
1732                 return 0;
1733
1734         case LNET_MSG_REPLY:
1735         case LNET_MSG_PUT:
1736                 /* Is the payload small enough not to need RDMA? */
1737                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob]);
1738                 if (nob <= IBLND_MSG_SIZE)
1739                         break;                  /* send IMMEDIATE */
1740
1741                 tx = kiblnd_get_idle_tx(ni, target.nid);
1742                 if (tx == NULL) {
1743                         CERROR("Can't allocate %s txd for %s\n",
1744                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1745                                libcfs_nid2str(target.nid));
1746                         return -ENOMEM;
1747                 }
1748
1749                 if (payload_kiov == NULL)
1750                         rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1751                                                  payload_niov, payload_iov,
1752                                                  payload_offset, payload_nob);
1753                 else
1754                         rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1755                                                   payload_niov, payload_kiov,
1756                                                   payload_offset, payload_nob);
1757                 if (rc != 0) {
1758                         CERROR("Can't setup PUT src for %s: %d\n",
1759                                libcfs_nid2str(target.nid), rc);
1760                         kiblnd_tx_done(tx);
1761                         return -EIO;
1762                 }
1763
1764                 ibmsg = tx->tx_msg;
1765                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1766                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1767                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ,
1768                                    sizeof(struct kib_putreq_msg));
1769
1770                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1771                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1772                 kiblnd_launch_tx(ni, tx, target.nid);
1773                 return 0;
1774         }
1775
1776         /* send IMMEDIATE */
1777         LASSERT(offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob])
1778                 <= IBLND_MSG_SIZE);
1779
1780         tx = kiblnd_get_idle_tx(ni, target.nid);
1781         if (tx == NULL) {
1782                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1783                         type, libcfs_nid2str(target.nid));
1784                 return -ENOMEM;
1785         }
1786
1787         ibmsg = tx->tx_msg;
1788         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1789
1790         if (payload_kiov != NULL)
1791                 lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1792                                     offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1793                                     payload_niov, payload_kiov,
1794                                     payload_offset, payload_nob);
1795         else
1796                 lnet_copy_iov2flat(IBLND_MSG_SIZE, ibmsg,
1797                                    offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1798                                    payload_niov, payload_iov,
1799                                    payload_offset, payload_nob);
1800
1801         nob = offsetof(struct kib_immediate_msg, ibim_payload[payload_nob]);
1802         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1803
1804         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1805         kiblnd_launch_tx(ni, tx, target.nid);
1806         return 0;
1807 }
1808
1809 static void
1810 kiblnd_reply(struct lnet_ni *ni, struct kib_rx *rx, struct lnet_msg *lntmsg)
1811 {
1812         struct lnet_process_id target = lntmsg->msg_target;
1813         unsigned int      niov = lntmsg->msg_niov;
1814         struct kvec      *iov = lntmsg->msg_iov;
1815         lnet_kiov_t      *kiov = lntmsg->msg_kiov;
1816         unsigned int      offset = lntmsg->msg_offset;
1817         unsigned int      nob = lntmsg->msg_len;
1818         struct kib_tx *tx;
1819         int               rc;
1820
1821         tx = kiblnd_get_idle_tx(ni, rx->rx_conn->ibc_peer->ibp_nid);
1822         if (tx == NULL) {
1823                 CERROR("Can't get tx for REPLY to %s\n",
1824                        libcfs_nid2str(target.nid));
1825                 goto failed_0;
1826         }
1827
1828         if (nob == 0)
1829                 rc = 0;
1830         else if (kiov == NULL)
1831                 rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1832                                          niov, iov, offset, nob);
1833         else
1834                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1835                                           niov, kiov, offset, nob);
1836
1837         if (rc != 0) {
1838                 CERROR("Can't setup GET src for %s: %d\n",
1839                        libcfs_nid2str(target.nid), rc);
1840                 goto failed_1;
1841         }
1842
1843         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1844                               IBLND_MSG_GET_DONE, nob,
1845                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1846                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1847         if (rc < 0) {
1848                 CERROR("Can't setup rdma for GET from %s: %d\n",
1849                        libcfs_nid2str(target.nid), rc);
1850                 goto failed_1;
1851         }
1852
1853         if (nob == 0) {
1854                 /* No RDMA: local completion may happen now! */
1855                 lnet_finalize(lntmsg, 0);
1856         } else {
1857                 /* RDMA: lnet_finalize(lntmsg) when it
1858                  * completes */
1859                 tx->tx_lntmsg[0] = lntmsg;
1860         }
1861
1862         kiblnd_queue_tx(tx, rx->rx_conn);
1863         return;
1864
1865
1866 failed_1:
1867         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1868         kiblnd_tx_done(tx);
1869 failed_0:
1870         lnet_finalize(lntmsg, -EIO);
1871 }
1872
1873 int
1874 kiblnd_recv(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg,
1875             int delayed, unsigned int niov, struct kvec *iov, lnet_kiov_t *kiov,
1876             unsigned int offset, unsigned int mlen, unsigned int rlen)
1877 {
1878         struct kib_rx *rx = private;
1879         struct kib_msg *rxmsg = rx->rx_msg;
1880         struct kib_conn *conn = rx->rx_conn;
1881         struct kib_tx *tx;
1882         __u64        ibprm_cookie;
1883         int          nob;
1884         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1885         int          rc = 0;
1886
1887         LASSERT (mlen <= rlen);
1888         LASSERT (!in_interrupt());
1889         /* Either all pages or all vaddrs */
1890         LASSERT (!(kiov != NULL && iov != NULL));
1891
1892         switch (rxmsg->ibm_type) {
1893         default:
1894                 LBUG();
1895
1896         case IBLND_MSG_IMMEDIATE:
1897                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[rlen]);
1898                 if (nob > rx->rx_nob) {
1899                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1900                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1901                                 nob, rx->rx_nob);
1902                         rc = -EPROTO;
1903                         break;
1904                 }
1905
1906                 if (kiov != NULL)
1907                         lnet_copy_flat2kiov(niov, kiov, offset,
1908                                             IBLND_MSG_SIZE, rxmsg,
1909                                             offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1910                                             mlen);
1911                 else
1912                         lnet_copy_flat2iov(niov, iov, offset,
1913                                            IBLND_MSG_SIZE, rxmsg,
1914                                            offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1915                                            mlen);
1916                 lnet_finalize(lntmsg, 0);
1917                 break;
1918
1919         case IBLND_MSG_PUT_REQ: {
1920                 struct kib_msg  *txmsg;
1921                 struct kib_rdma_desc *rd;
1922                 ibprm_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1923
1924                 if (mlen == 0) {
1925                         lnet_finalize(lntmsg, 0);
1926                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1927                                                0, ibprm_cookie);
1928                         break;
1929                 }
1930
1931                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1932                 if (tx == NULL) {
1933                         CERROR("Can't allocate tx for %s\n",
1934                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1935                         /* Not replying will break the connection */
1936                         rc = -ENOMEM;
1937                         break;
1938                 }
1939
1940                 txmsg = tx->tx_msg;
1941                 rd = &txmsg->ibm_u.putack.ibpam_rd;
1942                 if (kiov == NULL)
1943                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1944                                                  niov, iov, offset, mlen);
1945                 else
1946                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1947                                                   niov, kiov, offset, mlen);
1948                 if (rc != 0) {
1949                         CERROR("Can't setup PUT sink for %s: %d\n",
1950                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1951                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1952                         kiblnd_tx_done(tx);
1953                         /* tell peer_ni it's over */
1954                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1955                                                rc, ibprm_cookie);
1956                         break;
1957                 }
1958
1959                 nob = offsetof(struct kib_putack_msg, ibpam_rd.rd_frags[rd->rd_nfrags]);
1960                 txmsg->ibm_u.putack.ibpam_src_cookie = ibprm_cookie;
1961                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1962
1963                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1964
1965                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1966                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1967                 kiblnd_queue_tx(tx, conn);
1968
1969                 /* reposted buffer reserved for PUT_DONE */
1970                 post_credit = IBLND_POSTRX_NO_CREDIT;
1971                 break;
1972                 }
1973
1974         case IBLND_MSG_GET_REQ:
1975                 if (lntmsg != NULL) {
1976                         /* Optimized GET; RDMA lntmsg's payload */
1977                         kiblnd_reply(ni, rx, lntmsg);
1978                 } else {
1979                         /* GET didn't match anything */
1980                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1981                                                -ENODATA,
1982                                                rxmsg->ibm_u.get.ibgm_cookie);
1983                 }
1984                 break;
1985         }
1986
1987         kiblnd_post_rx(rx, post_credit);
1988         return rc;
1989 }
1990
1991 int
1992 kiblnd_thread_start(int (*fn)(void *arg), void *arg, char *name)
1993 {
1994         struct task_struct *task = kthread_run(fn, arg, name);
1995
1996         if (IS_ERR(task))
1997                 return PTR_ERR(task);
1998
1999         atomic_inc(&kiblnd_data.kib_nthreads);
2000         return 0;
2001 }
2002
2003 static void
2004 kiblnd_thread_fini (void)
2005 {
2006         atomic_dec (&kiblnd_data.kib_nthreads);
2007 }
2008
2009 static void
2010 kiblnd_peer_alive(struct kib_peer_ni *peer_ni)
2011 {
2012         /* This is racy, but everyone's only writing ktime_get_seconds() */
2013         peer_ni->ibp_last_alive = ktime_get_seconds();
2014         smp_mb();
2015 }
2016
2017 static void
2018 kiblnd_peer_notify(struct kib_peer_ni *peer_ni)
2019 {
2020         int           error = 0;
2021         time64_t last_alive = 0;
2022         unsigned long flags;
2023
2024         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2025
2026         if (kiblnd_peer_idle(peer_ni) && peer_ni->ibp_error != 0) {
2027                 error = peer_ni->ibp_error;
2028                 peer_ni->ibp_error = 0;
2029
2030                 last_alive = peer_ni->ibp_last_alive;
2031         }
2032
2033         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2034
2035         if (error != 0)
2036                 lnet_notify(peer_ni->ibp_ni,
2037                             peer_ni->ibp_nid, false, false, last_alive);
2038 }
2039
2040 void
2041 kiblnd_close_conn_locked(struct kib_conn *conn, int error)
2042 {
2043         /* This just does the immediate housekeeping.  'error' is zero for a
2044          * normal shutdown which can happen only after the connection has been
2045          * established.  If the connection is established, schedule the
2046          * connection to be finished off by the connd.  Otherwise the connd is
2047          * already dealing with it (either to set it up or tear it down).
2048          * Caller holds kib_global_lock exclusively in irq context */
2049         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2050         struct kib_dev *dev;
2051         unsigned long flags;
2052
2053         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2054
2055         if (error != 0 && conn->ibc_comms_error == 0)
2056                 conn->ibc_comms_error = error;
2057
2058         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
2059                 return; /* already being handled  */
2060
2061         if (error == 0 &&
2062             list_empty(&conn->ibc_tx_noops) &&
2063             list_empty(&conn->ibc_tx_queue) &&
2064             list_empty(&conn->ibc_tx_queue_rsrvd) &&
2065             list_empty(&conn->ibc_tx_queue_nocred) &&
2066             list_empty(&conn->ibc_active_txs)) {
2067                 CDEBUG(D_NET, "closing conn to %s\n", 
2068                        libcfs_nid2str(peer_ni->ibp_nid));
2069         } else {
2070                 CNETERR("Closing conn to %s: error %d%s%s%s%s%s\n",
2071                        libcfs_nid2str(peer_ni->ibp_nid), error,
2072                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
2073                        list_empty(&conn->ibc_tx_noops) ? "" : "(sending_noops)",
2074                        list_empty(&conn->ibc_tx_queue_rsrvd) ?
2075                                                 "" : "(sending_rsrvd)",
2076                        list_empty(&conn->ibc_tx_queue_nocred) ?
2077                                                  "" : "(sending_nocred)",
2078                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
2079         }
2080
2081         dev = ((struct kib_net *)peer_ni->ibp_ni->ni_data)->ibn_dev;
2082         if (peer_ni->ibp_next_conn == conn)
2083                 /* clear next_conn so it won't be used */
2084                 peer_ni->ibp_next_conn = NULL;
2085         list_del(&conn->ibc_list);
2086         /* connd (see below) takes over ibc_list's ref */
2087
2088         if (list_empty(&peer_ni->ibp_conns) &&    /* no more conns */
2089             kiblnd_peer_active(peer_ni)) {         /* still in peer_ni table */
2090                 kiblnd_unlink_peer_locked(peer_ni);
2091
2092                 /* set/clear error on last conn */
2093                 peer_ni->ibp_error = conn->ibc_comms_error;
2094         }
2095
2096         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
2097
2098         if (error != 0 &&
2099             kiblnd_dev_can_failover(dev)) {
2100                 list_add_tail(&dev->ibd_fail_list,
2101                               &kiblnd_data.kib_failed_devs);
2102                 wake_up(&kiblnd_data.kib_failover_waitq);
2103         }
2104
2105         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2106
2107         list_add_tail(&conn->ibc_list, &kiblnd_data.kib_connd_conns);
2108         wake_up(&kiblnd_data.kib_connd_waitq);
2109
2110         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
2111 }
2112
2113 void
2114 kiblnd_close_conn(struct kib_conn *conn, int error)
2115 {
2116         unsigned long flags;
2117
2118         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2119
2120         kiblnd_close_conn_locked(conn, error);
2121
2122         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2123 }
2124
2125 static void
2126 kiblnd_handle_early_rxs(struct kib_conn *conn)
2127 {
2128         unsigned long flags;
2129         struct kib_rx *rx;
2130
2131         LASSERT(!in_interrupt());
2132         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2133
2134         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2135         while (!list_empty(&conn->ibc_early_rxs)) {
2136                 rx = list_entry(conn->ibc_early_rxs.next,
2137                                 struct kib_rx, rx_list);
2138                 list_del(&rx->rx_list);
2139                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2140
2141                 kiblnd_handle_rx(rx);
2142
2143                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2144         }
2145         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2146 }
2147
2148 void
2149 kiblnd_abort_txs(struct kib_conn *conn, struct list_head *txs)
2150 {
2151         LIST_HEAD(zombies);
2152         struct list_head        *tmp;
2153         struct list_head        *nxt;
2154         struct kib_tx *tx;
2155
2156         spin_lock(&conn->ibc_lock);
2157
2158         list_for_each_safe(tmp, nxt, txs) {
2159                 tx = list_entry(tmp, struct kib_tx, tx_list);
2160
2161                 if (txs == &conn->ibc_active_txs) {
2162                         LASSERT(!tx->tx_queued);
2163                         LASSERT(tx->tx_waiting ||
2164                                 tx->tx_sending != 0);
2165                         if (conn->ibc_comms_error == -ETIMEDOUT) {
2166                                 if (tx->tx_waiting && !tx->tx_sending)
2167                                         tx->tx_hstatus =
2168                                           LNET_MSG_STATUS_REMOTE_TIMEOUT;
2169                                 else if (tx->tx_sending)
2170                                         tx->tx_hstatus =
2171                                           LNET_MSG_STATUS_NETWORK_TIMEOUT;
2172                         }
2173                 } else {
2174                         LASSERT(tx->tx_queued);
2175                         if (conn->ibc_comms_error == -ETIMEDOUT)
2176                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2177                         else
2178                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
2179                 }
2180
2181                 tx->tx_status = -ECONNABORTED;
2182                 tx->tx_waiting = 0;
2183
2184                 /*
2185                  * TODO: This makes an assumption that
2186                  * kiblnd_tx_complete() will be called for each tx. If
2187                  * that event is dropped we could end up with stale
2188                  * connections floating around. We'd like to deal with
2189                  * that in a better way.
2190                  *
2191                  * Also that means we can exceed the timeout by many
2192                  * seconds.
2193                  */
2194                 if (tx->tx_sending == 0) {
2195                         tx->tx_queued = 0;
2196                         list_move(&tx->tx_list, &zombies);
2197                 }
2198         }
2199
2200         spin_unlock(&conn->ibc_lock);
2201
2202         /*
2203          * aborting transmits occurs when finalizing the connection.
2204          * The connection is finalized on error.
2205          * Passing LNET_MSG_STATUS_OK to txlist_done() will not
2206          * override the value already set in tx->tx_hstatus above.
2207          */
2208         kiblnd_txlist_done(&zombies, -ECONNABORTED, LNET_MSG_STATUS_OK);
2209 }
2210
2211 static void
2212 kiblnd_finalise_conn(struct kib_conn *conn)
2213 {
2214         LASSERT (!in_interrupt());
2215         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
2216
2217         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
2218          * for connections that didn't get as far as being connected, because
2219          * rdma_disconnect() does this for free. */
2220         kiblnd_abort_receives(conn);
2221
2222         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
2223
2224         /* Complete all tx descs not waiting for sends to complete.
2225          * NB we should be safe from RDMA now that the QP has changed state */
2226
2227         kiblnd_abort_txs(conn, &conn->ibc_tx_noops);
2228         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
2229         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
2230         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
2231         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
2232
2233         kiblnd_handle_early_rxs(conn);
2234 }
2235
2236 static void
2237 kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
2238                            int error)
2239 {
2240         LIST_HEAD(zombies);
2241         unsigned long   flags;
2242
2243         LASSERT (error != 0);
2244         LASSERT (!in_interrupt());
2245
2246         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2247
2248         if (active) {
2249                 LASSERT(peer_ni->ibp_connecting > 0);
2250                 peer_ni->ibp_connecting--;
2251         } else {
2252                 LASSERT (peer_ni->ibp_accepting > 0);
2253                 peer_ni->ibp_accepting--;
2254         }
2255
2256         if (kiblnd_peer_connecting(peer_ni)) {
2257                 /* another connection attempt under way... */
2258                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2259                                         flags);
2260                 return;
2261         }
2262
2263         peer_ni->ibp_reconnected = 0;
2264         if (list_empty(&peer_ni->ibp_conns)) {
2265                 /* Take peer_ni's blocked transmits to complete with error */
2266                 list_splice_init(&peer_ni->ibp_tx_queue, &zombies);
2267
2268                 if (kiblnd_peer_active(peer_ni))
2269                         kiblnd_unlink_peer_locked(peer_ni);
2270
2271                 peer_ni->ibp_error = error;
2272         } else {
2273                 /* Can't have blocked transmits if there are connections */
2274                 LASSERT(list_empty(&peer_ni->ibp_tx_queue));
2275         }
2276
2277         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2278
2279         kiblnd_peer_notify(peer_ni);
2280
2281         if (list_empty(&zombies))
2282                 return;
2283
2284         CNETERR("Deleting messages for %s: connection failed\n",
2285                 libcfs_nid2str(peer_ni->ibp_nid));
2286
2287         kiblnd_txlist_done(&zombies, error,
2288                            LNET_MSG_STATUS_LOCAL_DROPPED);
2289 }
2290
2291 static void
2292 kiblnd_connreq_done(struct kib_conn *conn, int status)
2293 {
2294         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2295         struct kib_tx *tx;
2296         LIST_HEAD(txs);
2297         unsigned long    flags;
2298         int              active;
2299
2300         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2301
2302         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
2303                libcfs_nid2str(peer_ni->ibp_nid), active,
2304                conn->ibc_version, status);
2305
2306         LASSERT (!in_interrupt());
2307         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2308                   peer_ni->ibp_connecting > 0) ||
2309                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2310                   peer_ni->ibp_accepting > 0));
2311
2312         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2313         conn->ibc_connvars = NULL;
2314
2315         if (status != 0) {
2316                 /* failed to establish connection */
2317                 kiblnd_peer_connect_failed(peer_ni, active, status);
2318                 kiblnd_finalise_conn(conn);
2319                 return;
2320         }
2321
2322         /* connection established */
2323         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2324
2325         conn->ibc_last_send = ktime_get();
2326         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2327         kiblnd_peer_alive(peer_ni);
2328
2329         /* Add conn to peer_ni's list and nuke any dangling conns from a different
2330          * peer_ni instance... */
2331         kiblnd_conn_addref(conn);       /* +1 ref for ibc_list */
2332         list_add(&conn->ibc_list, &peer_ni->ibp_conns);
2333         peer_ni->ibp_reconnected = 0;
2334         if (active)
2335                 peer_ni->ibp_connecting--;
2336         else
2337                 peer_ni->ibp_accepting--;
2338
2339         if (peer_ni->ibp_version == 0) {
2340                 peer_ni->ibp_version     = conn->ibc_version;
2341                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2342         }
2343
2344         if (peer_ni->ibp_version     != conn->ibc_version ||
2345             peer_ni->ibp_incarnation != conn->ibc_incarnation) {
2346                 kiblnd_close_stale_conns_locked(peer_ni, conn->ibc_version,
2347                                                 conn->ibc_incarnation);
2348                 peer_ni->ibp_version     = conn->ibc_version;
2349                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2350         }
2351
2352         /* grab pending txs while I have the lock */
2353         list_splice_init(&peer_ni->ibp_tx_queue, &txs);
2354
2355         if (!kiblnd_peer_active(peer_ni) ||        /* peer_ni has been deleted */
2356             conn->ibc_comms_error != 0) {       /* error has happened already */
2357
2358                 /* start to shut down connection */
2359                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2360                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2361
2362                 kiblnd_txlist_done(&txs, -ECONNABORTED,
2363                                    LNET_MSG_STATUS_LOCAL_ERROR);
2364
2365                 return;
2366         }
2367
2368         /* +1 ref for myself, this connection is visible to other threads
2369          * now, refcount of peer:ibp_conns can be released by connection
2370          * close from either a different thread, or the calling of
2371          * kiblnd_check_sends_locked() below. See bz21911 for details.
2372          */
2373         kiblnd_conn_addref(conn);
2374         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2375
2376         /* Schedule blocked txs
2377          * Note: if we are running with conns_per_peer > 1, these blocked
2378          * txs will all get scheduled to the first connection which gets
2379          * scheduled.  We won't be using round robin on this first batch.
2380          */
2381         spin_lock(&conn->ibc_lock);
2382         while (!list_empty(&txs)) {
2383                 tx = list_entry(txs.next, struct kib_tx, tx_list);
2384                 list_del(&tx->tx_list);
2385
2386                 kiblnd_queue_tx_locked(tx, conn);
2387         }
2388         kiblnd_check_sends_locked(conn);
2389         spin_unlock(&conn->ibc_lock);
2390
2391         /* schedule blocked rxs */
2392         kiblnd_handle_early_rxs(conn);
2393         kiblnd_conn_decref(conn);
2394 }
2395
2396 static void
2397 kiblnd_reject(struct rdma_cm_id *cmid, struct kib_rej *rej)
2398 {
2399         int          rc;
2400
2401         rc = rdma_reject(cmid, rej, sizeof(*rej));
2402
2403         if (rc != 0)
2404                 CWARN("Error %d sending reject\n", rc);
2405 }
2406
2407 static int
2408 kiblnd_passive_connect(struct rdma_cm_id *cmid, void *priv, int priv_nob)
2409 {
2410         rwlock_t                *g_lock = &kiblnd_data.kib_global_lock;
2411         struct kib_msg *reqmsg = priv;
2412         struct kib_msg *ackmsg;
2413         struct kib_dev *ibdev;
2414         struct kib_peer_ni *peer_ni;
2415         struct kib_peer_ni *peer2;
2416         struct kib_conn *conn;
2417         struct lnet_ni *ni = NULL;
2418         struct kib_net *net = NULL;
2419         lnet_nid_t             nid;
2420         struct rdma_conn_param cp;
2421         struct kib_rej rej;
2422         int                    version = IBLND_MSG_VERSION;
2423         unsigned long          flags;
2424         int                    rc;
2425         struct sockaddr_in    *peer_addr;
2426         LASSERT (!in_interrupt());
2427
2428         /* cmid inherits 'context' from the corresponding listener id */
2429         ibdev = cmid->context;
2430         LASSERT(ibdev);
2431
2432         memset(&rej, 0, sizeof(rej));
2433         rej.ibr_magic                = IBLND_MSG_MAGIC;
2434         rej.ibr_why                  = IBLND_REJECT_FATAL;
2435         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2436
2437         peer_addr = (struct sockaddr_in *)&(cmid->route.addr.dst_addr);
2438         if (*kiblnd_tunables.kib_require_priv_port &&
2439             ntohs(peer_addr->sin_port) >= PROT_SOCK) {
2440                 __u32 ip = ntohl(peer_addr->sin_addr.s_addr);
2441                 CERROR("peer_ni's port (%pI4h:%hu) is not privileged\n",
2442                        &ip, ntohs(peer_addr->sin_port));
2443                 goto failed;
2444         }
2445
2446         if (priv_nob < offsetof(struct kib_msg, ibm_type)) {
2447                 CERROR("Short connection request\n");
2448                 goto failed;
2449         }
2450
2451         /* Future protocol version compatibility support!  If the
2452          * o2iblnd-specific protocol changes, or when LNET unifies
2453          * protocols over all LNDs, the initial connection will
2454          * negotiate a protocol version.  I trap this here to avoid
2455          * console errors; the reject tells the peer_ni which protocol I
2456          * speak. */
2457         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2458             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2459                 goto failed;
2460         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2461             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2462             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2463                 goto failed;
2464         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2465             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2466             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2467                 goto failed;
2468
2469         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2470         if (rc != 0) {
2471                 CERROR("Can't parse connection request: %d\n", rc);
2472                 goto failed;
2473         }
2474
2475         nid = reqmsg->ibm_srcnid;
2476         ni  = lnet_nid2ni_addref(reqmsg->ibm_dstnid);
2477
2478         if (ni != NULL) {
2479                 net = (struct kib_net *)ni->ni_data;
2480                 rej.ibr_incarnation = net->ibn_incarnation;
2481         }
2482
2483         if (ni == NULL ||                         /* no matching net */
2484             ni->ni_nid != reqmsg->ibm_dstnid ||   /* right NET, wrong NID! */
2485             net->ibn_dev != ibdev) {              /* wrong device */
2486                 CERROR("Can't accept conn from %s on %s (%s:%d:%pI4h): "
2487                        "bad dst nid %s\n", libcfs_nid2str(nid),
2488                        ni == NULL ? "NA" : libcfs_nid2str(ni->ni_nid),
2489                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2490                         &ibdev->ibd_ifip,
2491                        libcfs_nid2str(reqmsg->ibm_dstnid));
2492
2493                 goto failed;
2494         }
2495
2496        /* check time stamp as soon as possible */
2497         if (reqmsg->ibm_dststamp != 0 &&
2498             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2499                 CWARN("Stale connection request\n");
2500                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2501                 goto failed;
2502         }
2503
2504         /* I can accept peer_ni's version */
2505         version = reqmsg->ibm_version;
2506
2507         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2508                 CERROR("Unexpected connreq msg type: %x from %s\n",
2509                        reqmsg->ibm_type, libcfs_nid2str(nid));
2510                 goto failed;
2511         }
2512
2513         if (reqmsg->ibm_u.connparams.ibcp_queue_depth >
2514             kiblnd_msg_queue_size(version, ni)) {
2515                 CERROR("Can't accept conn from %s, queue depth too large: "
2516                        " %d (<=%d wanted)\n",
2517                        libcfs_nid2str(nid),
2518                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2519                        kiblnd_msg_queue_size(version, ni));
2520
2521                 if (version == IBLND_MSG_VERSION)
2522                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2523
2524                 goto failed;
2525         }
2526
2527         if (reqmsg->ibm_u.connparams.ibcp_max_frags >
2528             IBLND_MAX_RDMA_FRAGS) {
2529                 CWARN("Can't accept conn from %s (version %x): "
2530                       "max_frags %d too large (%d wanted)\n",
2531                       libcfs_nid2str(nid), version,
2532                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2533                       IBLND_MAX_RDMA_FRAGS);
2534
2535                 if (version >= IBLND_MSG_VERSION)
2536                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2537
2538                 goto failed;
2539         } else if (reqmsg->ibm_u.connparams.ibcp_max_frags <
2540                    IBLND_MAX_RDMA_FRAGS &&
2541                    net->ibn_fmr_ps == NULL) {
2542                 CWARN("Can't accept conn from %s (version %x): "
2543                       "max_frags %d incompatible without FMR pool "
2544                       "(%d wanted)\n",
2545                       libcfs_nid2str(nid), version,
2546                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2547                       IBLND_MAX_RDMA_FRAGS);
2548
2549                 if (version == IBLND_MSG_VERSION)
2550                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2551
2552                 goto failed;
2553         }
2554
2555         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2556                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2557                        libcfs_nid2str(nid),
2558                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2559                        IBLND_MSG_SIZE);
2560                 goto failed;
2561         }
2562
2563         /* assume 'nid' is a new peer_ni; create  */
2564         rc = kiblnd_create_peer(ni, &peer_ni, nid);
2565         if (rc != 0) {
2566                 CERROR("Can't create peer_ni for %s\n", libcfs_nid2str(nid));
2567                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2568                 goto failed;
2569         }
2570
2571         /* We have validated the peer's parameters so use those */
2572         peer_ni->ibp_max_frags = reqmsg->ibm_u.connparams.ibcp_max_frags;
2573         peer_ni->ibp_queue_depth = reqmsg->ibm_u.connparams.ibcp_queue_depth;
2574
2575         write_lock_irqsave(g_lock, flags);
2576
2577         peer2 = kiblnd_find_peer_locked(ni, nid);
2578         if (peer2 != NULL) {
2579                 if (peer2->ibp_version == 0) {
2580                         peer2->ibp_version     = version;
2581                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2582                 }
2583
2584                 /* not the guy I've talked with */
2585                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2586                     peer2->ibp_version     != version) {
2587                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2588
2589                         if (kiblnd_peer_active(peer2)) {
2590                                 peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2591                                 peer2->ibp_version = version;
2592                         }
2593                         write_unlock_irqrestore(g_lock, flags);
2594
2595                         CWARN("Conn stale %s version %x/%x incarnation %llu/%llu\n",
2596                               libcfs_nid2str(nid), peer2->ibp_version, version,
2597                               peer2->ibp_incarnation, reqmsg->ibm_srcstamp);
2598
2599                         kiblnd_peer_decref(peer_ni);
2600                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2601                         goto failed;
2602                 }
2603
2604                 /* Tie-break connection race in favour of the higher NID.
2605                  * If we keep running into a race condition multiple times,
2606                  * we have to assume that the connection attempt with the
2607                  * higher NID is stuck in a connecting state and will never
2608                  * recover.  As such, we pass through this if-block and let
2609                  * the lower NID connection win so we can move forward.
2610                  */
2611                 if (peer2->ibp_connecting != 0 &&
2612                     nid < ni->ni_nid && peer2->ibp_races <
2613                     MAX_CONN_RACES_BEFORE_ABORT) {
2614                         peer2->ibp_races++;
2615                         write_unlock_irqrestore(g_lock, flags);
2616
2617                         CDEBUG(D_NET, "Conn race %s\n",
2618                                libcfs_nid2str(peer2->ibp_nid));
2619
2620                         kiblnd_peer_decref(peer_ni);
2621                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2622                         goto failed;
2623                 }
2624                 if (peer2->ibp_races >= MAX_CONN_RACES_BEFORE_ABORT)
2625                         CNETERR("Conn race %s: unresolved after %d attempts, letting lower NID win\n",
2626                                 libcfs_nid2str(peer2->ibp_nid),
2627                                 MAX_CONN_RACES_BEFORE_ABORT);
2628                 /*
2629                  * passive connection is allowed even this peer_ni is waiting for
2630                  * reconnection.
2631                  */
2632                 peer2->ibp_reconnecting = 0;
2633                 peer2->ibp_races = 0;
2634                 peer2->ibp_accepting++;
2635                 kiblnd_peer_addref(peer2);
2636
2637                 /* Race with kiblnd_launch_tx (active connect) to create peer_ni
2638                  * so copy validated parameters since we now know what the
2639                  * peer_ni's limits are */
2640                 peer2->ibp_max_frags = peer_ni->ibp_max_frags;
2641                 peer2->ibp_queue_depth = peer_ni->ibp_queue_depth;
2642
2643                 write_unlock_irqrestore(g_lock, flags);
2644                 kiblnd_peer_decref(peer_ni);
2645                 peer_ni = peer2;
2646         } else {
2647                 /* Brand new peer_ni */
2648                 LASSERT (peer_ni->ibp_accepting == 0);
2649                 LASSERT (peer_ni->ibp_version == 0 &&
2650                          peer_ni->ibp_incarnation == 0);
2651
2652                 peer_ni->ibp_accepting   = 1;
2653                 peer_ni->ibp_version     = version;
2654                 peer_ni->ibp_incarnation = reqmsg->ibm_srcstamp;
2655
2656                 /* I have a ref on ni that prevents it being shutdown */
2657                 LASSERT (net->ibn_shutdown == 0);
2658
2659                 kiblnd_peer_addref(peer_ni);
2660                 list_add_tail(&peer_ni->ibp_list, kiblnd_nid2peerlist(nid));
2661
2662                 write_unlock_irqrestore(g_lock, flags);
2663         }
2664
2665         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_PASSIVE_WAIT, version);
2666         if (conn == NULL) {
2667                 kiblnd_peer_connect_failed(peer_ni, 0, -ENOMEM);
2668                 kiblnd_peer_decref(peer_ni);
2669                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2670                 goto failed;
2671         }
2672
2673         /* conn now "owns" cmid, so I return success from here on to ensure the
2674          * CM callback doesn't destroy cmid. */
2675         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2676         conn->ibc_credits          = conn->ibc_queue_depth;
2677         conn->ibc_reserved_credits = conn->ibc_queue_depth;
2678         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2679                 IBLND_OOB_MSGS(version) <= IBLND_RX_MSGS(conn));
2680
2681         ackmsg = &conn->ibc_connvars->cv_msg;
2682         memset(ackmsg, 0, sizeof(*ackmsg));
2683
2684         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2685                         sizeof(ackmsg->ibm_u.connparams));
2686         ackmsg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2687         ackmsg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2688         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2689
2690         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2691
2692         memset(&cp, 0, sizeof(cp));
2693         cp.private_data        = ackmsg;
2694         cp.private_data_len    = ackmsg->ibm_nob;
2695         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2696         cp.initiator_depth     = 0;
2697         cp.flow_control        = 1;
2698         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2699         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2700
2701         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2702
2703         rc = rdma_accept(cmid, &cp);
2704         if (rc != 0) {
2705                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2706                 rej.ibr_version = version;
2707                 rej.ibr_why     = IBLND_REJECT_FATAL;
2708
2709                 kiblnd_reject(cmid, &rej);
2710                 kiblnd_connreq_done(conn, rc);
2711                 kiblnd_conn_decref(conn);
2712         }
2713
2714         lnet_ni_decref(ni);
2715         return 0;
2716
2717  failed:
2718         if (ni != NULL) {
2719                 rej.ibr_cp.ibcp_queue_depth =
2720                         kiblnd_msg_queue_size(version, ni);
2721                 rej.ibr_cp.ibcp_max_frags   = IBLND_MAX_RDMA_FRAGS;
2722                 lnet_ni_decref(ni);
2723         }
2724
2725         rej.ibr_version = version;
2726         kiblnd_reject(cmid, &rej);
2727
2728         return -ECONNREFUSED;
2729 }
2730
2731 static void
2732 kiblnd_check_reconnect(struct kib_conn *conn, int version,
2733                        u64 incarnation, int why, struct kib_connparams *cp)
2734 {
2735         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
2736         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2737         char            *reason;
2738         int              msg_size = IBLND_MSG_SIZE;
2739         int              frag_num = -1;
2740         int              queue_dep = -1;
2741         bool             reconnect;
2742         unsigned long    flags;
2743
2744         LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2745         LASSERT(peer_ni->ibp_connecting > 0);   /* 'conn' at least */
2746
2747         if (cp) {
2748                 msg_size        = cp->ibcp_max_msg_size;
2749                 frag_num        = cp->ibcp_max_frags;
2750                 queue_dep       = cp->ibcp_queue_depth;
2751         }
2752
2753         write_lock_irqsave(glock, flags);
2754         /* retry connection if it's still needed and no other connection
2755          * attempts (active or passive) are in progress
2756          * NB: reconnect is still needed even when ibp_tx_queue is
2757          * empty if ibp_version != version because reconnect may be
2758          * initiated.
2759          */
2760         reconnect = (!list_empty(&peer_ni->ibp_tx_queue) ||
2761                      peer_ni->ibp_version != version) &&
2762                     peer_ni->ibp_connecting &&
2763                     peer_ni->ibp_accepting == 0;
2764         if (!reconnect) {
2765                 reason = "no need";
2766                 goto out;
2767         }
2768
2769         switch (why) {
2770         default:
2771                 reason = "Unknown";
2772                 break;
2773
2774         case IBLND_REJECT_RDMA_FRAGS: {
2775                 struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2776
2777                 if (!cp) {
2778                         reason = "can't negotiate max frags";
2779                         goto out;
2780                 }
2781                 tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2782 #ifdef HAVE_IB_GET_DMA_MR
2783                 /*
2784                  * This check only makes sense if the kernel supports global
2785                  * memory registration. Otherwise, map_on_demand will never == 0
2786                  */
2787                 if (!tunables->lnd_map_on_demand) {
2788                         reason = "map_on_demand must be enabled";
2789                         goto out;
2790                 }
2791 #endif
2792                 if (conn->ibc_max_frags <= frag_num) {
2793                         reason = "unsupported max frags";
2794                         goto out;
2795                 }
2796
2797                 peer_ni->ibp_max_frags = frag_num;
2798                 reason = "rdma fragments";
2799                 break;
2800         }
2801         case IBLND_REJECT_MSG_QUEUE_SIZE:
2802                 if (!cp) {
2803                         reason = "can't negotiate queue depth";
2804                         goto out;
2805                 }
2806                 if (conn->ibc_queue_depth <= queue_dep) {
2807                         reason = "unsupported queue depth";
2808                         goto out;
2809                 }
2810
2811                 peer_ni->ibp_queue_depth = queue_dep;
2812                 reason = "queue depth";
2813                 break;
2814
2815         case IBLND_REJECT_CONN_STALE:
2816                 reason = "stale";
2817                 break;
2818
2819         case IBLND_REJECT_CONN_RACE:
2820                 reason = "conn race";
2821                 break;
2822
2823         case IBLND_REJECT_CONN_UNCOMPAT:
2824                 reason = "version negotiation";
2825                 break;
2826
2827         case IBLND_REJECT_INVALID_SRV_ID:
2828                 reason = "invalid service id";
2829                 break;
2830         }
2831
2832         conn->ibc_reconnect = 1;
2833         peer_ni->ibp_reconnecting++;
2834         peer_ni->ibp_version = version;
2835         if (incarnation != 0)
2836                 peer_ni->ibp_incarnation = incarnation;
2837  out:
2838         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2839
2840         CNETERR("%s: %s (%s), %x, %x, msg_size: %d, queue_depth: %d/%d, max_frags: %d/%d\n",
2841                 libcfs_nid2str(peer_ni->ibp_nid),
2842                 reconnect ? "reconnect" : "don't reconnect",
2843                 reason, IBLND_MSG_VERSION, version, msg_size,
2844                 conn->ibc_queue_depth, queue_dep,
2845                 conn->ibc_max_frags, frag_num);
2846         /*
2847          * if conn::ibc_reconnect is TRUE, connd will reconnect to the peer_ni
2848          * while destroying the zombie
2849          */
2850 }
2851
2852 static void
2853 kiblnd_rejected(struct kib_conn *conn, int reason, void *priv, int priv_nob)
2854 {
2855         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2856
2857         LASSERT (!in_interrupt());
2858         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2859
2860         switch (reason) {
2861         case IB_CM_REJ_STALE_CONN:
2862                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2863                                        IBLND_REJECT_CONN_STALE, NULL);
2864                 break;
2865
2866         case IB_CM_REJ_INVALID_SERVICE_ID:
2867                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2868                                        IBLND_REJECT_INVALID_SRV_ID, NULL);
2869                 CNETERR("%s rejected: no listener at %d\n",
2870                         libcfs_nid2str(peer_ni->ibp_nid),
2871                         *kiblnd_tunables.kib_service);
2872                 break;
2873
2874         case IB_CM_REJ_CONSUMER_DEFINED:
2875                 if (priv_nob >= offsetof(struct kib_rej, ibr_padding)) {
2876                         struct kib_rej *rej = priv;
2877                         struct kib_connparams *cp = NULL;
2878                         int               flip        = 0;
2879                         __u64             incarnation = -1;
2880
2881                         /* NB. default incarnation is -1 because:
2882                          * a) V1 will ignore dst incarnation in connreq.
2883                          * b) V2 will provide incarnation while rejecting me,
2884                          *    -1 will be overwrote.
2885                          *
2886                          * if I try to connect to a V1 peer_ni with V2 protocol,
2887                          * it rejected me then upgrade to V2, I have no idea
2888                          * about the upgrading and try to reconnect with V1,
2889                          * in this case upgraded V2 can find out I'm trying to
2890                          * talk to the old guy and reject me(incarnation is -1). 
2891                          */
2892
2893                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2894                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2895                                 __swab32s(&rej->ibr_magic);
2896                                 __swab16s(&rej->ibr_version);
2897                                 flip = 1;
2898                         }
2899
2900                         if (priv_nob >= sizeof(struct kib_rej) &&
2901                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2902                                 /* priv_nob is always 148 in current version
2903                                  * of OFED, so we still need to check version.
2904                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE) */
2905                                 cp = &rej->ibr_cp;
2906
2907                                 if (flip) {
2908                                         __swab64s(&rej->ibr_incarnation);
2909                                         __swab16s(&cp->ibcp_queue_depth);
2910                                         __swab16s(&cp->ibcp_max_frags);
2911                                         __swab32s(&cp->ibcp_max_msg_size);
2912                                 }
2913
2914                                 incarnation = rej->ibr_incarnation;
2915                         }
2916
2917                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2918                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2919                                 CERROR("%s rejected: consumer defined fatal error\n",
2920                                        libcfs_nid2str(peer_ni->ibp_nid));
2921                                 break;
2922                         }
2923
2924                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2925                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2926                                 CERROR("%s rejected: o2iblnd version %x error\n",
2927                                        libcfs_nid2str(peer_ni->ibp_nid),
2928                                        rej->ibr_version);
2929                                 break;
2930                         }
2931
2932                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2933                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2934                                 CDEBUG(D_NET, "rejected by old version peer_ni %s: %x\n",
2935                                        libcfs_nid2str(peer_ni->ibp_nid), rej->ibr_version);
2936
2937                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2938                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2939                         }
2940
2941                         switch (rej->ibr_why) {
2942                         case IBLND_REJECT_CONN_RACE:
2943                         case IBLND_REJECT_CONN_STALE:
2944                         case IBLND_REJECT_CONN_UNCOMPAT:
2945                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2946                         case IBLND_REJECT_RDMA_FRAGS:
2947                                 kiblnd_check_reconnect(conn, rej->ibr_version,
2948                                                 incarnation, rej->ibr_why, cp);
2949                                 break;
2950
2951                         case IBLND_REJECT_NO_RESOURCES:
2952                                 CERROR("%s rejected: o2iblnd no resources\n",
2953                                        libcfs_nid2str(peer_ni->ibp_nid));
2954                                 break;
2955
2956                         case IBLND_REJECT_FATAL:
2957                                 CERROR("%s rejected: o2iblnd fatal error\n",
2958                                        libcfs_nid2str(peer_ni->ibp_nid));
2959                                 break;
2960
2961                         default:
2962                                 CERROR("%s rejected: o2iblnd reason %d\n",
2963                                        libcfs_nid2str(peer_ni->ibp_nid),
2964                                        rej->ibr_why);
2965                                 break;
2966                         }
2967                         break;
2968                 }
2969                 /* fall through */
2970         default:
2971                 CNETERR("%s rejected: reason %d, size %d\n",
2972                         libcfs_nid2str(peer_ni->ibp_nid), reason, priv_nob);
2973                 break;
2974         }
2975
2976         kiblnd_connreq_done(conn, -ECONNREFUSED);
2977 }
2978
2979 static void
2980 kiblnd_check_connreply(struct kib_conn *conn, void *priv, int priv_nob)
2981 {
2982         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2983         struct lnet_ni *ni = peer_ni->ibp_ni;
2984         struct kib_net *net = ni->ni_data;
2985         struct kib_msg *msg = priv;
2986         int            ver  = conn->ibc_version;
2987         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
2988         unsigned long  flags;
2989
2990         LASSERT (net != NULL);
2991
2992         if (rc != 0) {
2993                 CERROR("Can't unpack connack from %s: %d\n",
2994                        libcfs_nid2str(peer_ni->ibp_nid), rc);
2995                 goto failed;
2996         }
2997
2998         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2999                 CERROR("Unexpected message %d from %s\n",
3000                        msg->ibm_type, libcfs_nid2str(peer_ni->ibp_nid));
3001                 rc = -EPROTO;
3002                 goto failed;
3003         }
3004
3005         if (ver != msg->ibm_version) {
3006                 CERROR("%s replied version %x is different with "
3007                        "requested version %x\n",
3008                        libcfs_nid2str(peer_ni->ibp_nid), msg->ibm_version, ver);
3009                 rc = -EPROTO;
3010                 goto failed;
3011         }
3012
3013         if (msg->ibm_u.connparams.ibcp_queue_depth >
3014             conn->ibc_queue_depth) {
3015                 CERROR("%s has incompatible queue depth %d (<=%d wanted)\n",
3016                        libcfs_nid2str(peer_ni->ibp_nid),
3017                        msg->ibm_u.connparams.ibcp_queue_depth,
3018                        conn->ibc_queue_depth);
3019                 rc = -EPROTO;
3020                 goto failed;
3021         }
3022
3023         if (msg->ibm_u.connparams.ibcp_max_frags >
3024             conn->ibc_max_frags) {
3025                 CERROR("%s has incompatible max_frags %d (<=%d wanted)\n",
3026                        libcfs_nid2str(peer_ni->ibp_nid),
3027                        msg->ibm_u.connparams.ibcp_max_frags,
3028                        conn->ibc_max_frags);
3029                 rc = -EPROTO;
3030                 goto failed;
3031         }
3032
3033         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
3034                 CERROR("%s max message size %d too big (%d max)\n",
3035                        libcfs_nid2str(peer_ni->ibp_nid),
3036                        msg->ibm_u.connparams.ibcp_max_msg_size,
3037                        IBLND_MSG_SIZE);
3038                 rc = -EPROTO;
3039                 goto failed;
3040         }
3041
3042         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3043         if (msg->ibm_dstnid == ni->ni_nid &&
3044             msg->ibm_dststamp == net->ibn_incarnation)
3045                 rc = 0;
3046         else
3047                 rc = -ESTALE;
3048         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3049
3050         if (rc != 0) {
3051                 CERROR("Bad connection reply from %s, rc = %d, "
3052                        "version: %x max_frags: %d\n",
3053                        libcfs_nid2str(peer_ni->ibp_nid), rc,
3054                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
3055                 goto failed;
3056         }
3057
3058         conn->ibc_incarnation      = msg->ibm_srcstamp;
3059         conn->ibc_credits          = msg->ibm_u.connparams.ibcp_queue_depth;
3060         conn->ibc_reserved_credits = msg->ibm_u.connparams.ibcp_queue_depth;
3061         conn->ibc_queue_depth      = msg->ibm_u.connparams.ibcp_queue_depth;
3062         conn->ibc_max_frags        = msg->ibm_u.connparams.ibcp_max_frags;
3063         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
3064                 IBLND_OOB_MSGS(ver) <= IBLND_RX_MSGS(conn));
3065
3066         kiblnd_connreq_done(conn, 0);
3067         return;
3068
3069  failed:
3070         /* NB My QP has already established itself, so I handle anything going
3071          * wrong here by setting ibc_comms_error.
3072          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
3073          * immediately tears it down. */
3074
3075         LASSERT (rc != 0);
3076         conn->ibc_comms_error = rc;
3077         kiblnd_connreq_done(conn, 0);
3078 }
3079
3080 static int
3081 kiblnd_active_connect(struct rdma_cm_id *cmid)
3082 {
3083         struct kib_peer_ni *peer_ni = cmid->context;
3084         struct kib_conn *conn;
3085         struct kib_msg *msg;
3086         struct rdma_conn_param cp;
3087         int                      version;
3088         __u64                    incarnation;
3089         unsigned long            flags;
3090         int             &n