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