Whamcloud - gitweb
LU-10391 lnet: introduce struct lnet_nid
[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);
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 != lnet_nid_to_nid4(&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,
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, 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         struct kib_fast_reg_descriptor *frd = tx->tx_fmr.fmr_frd;
815         int ver = conn->ibc_version;
816         int rc;
817         int done;
818
819         LASSERT(tx->tx_queued);
820         /* We rely on this for QP sizing */
821         LASSERT(tx->tx_nwrq > 0 && tx->tx_nsge >= 0);
822         LASSERT(tx->tx_nwrq <= 1 + conn->ibc_max_frags);
823
824         LASSERT(credit == 0 || credit == 1);
825         LASSERT(conn->ibc_outstanding_credits >= 0);
826         LASSERT(conn->ibc_outstanding_credits <= conn->ibc_queue_depth);
827         LASSERT(conn->ibc_credits >= 0);
828         LASSERT(conn->ibc_credits <= conn->ibc_queue_depth);
829
830         if (conn->ibc_nsends_posted ==
831             kiblnd_concurrent_sends(ver, ni)) {
832                 /* tx completions outstanding... */
833                 CDEBUG(D_NET, "%s: posted enough\n",
834                        libcfs_nid2str(peer_ni->ibp_nid));
835                 return -EAGAIN;
836         }
837
838         if (credit != 0 && conn->ibc_credits == 0) {   /* no credits */
839                 CDEBUG(D_NET, "%s: no credits\n",
840                        libcfs_nid2str(peer_ni->ibp_nid));
841                 return -EAGAIN;
842         }
843
844         if (credit != 0 && !IBLND_OOB_CAPABLE(ver) &&
845             conn->ibc_credits == 1 &&   /* last credit reserved */
846             msg->ibm_type != IBLND_MSG_NOOP) {      /* for NOOP */
847                 CDEBUG(D_NET, "%s: not using last credit\n",
848                        libcfs_nid2str(peer_ni->ibp_nid));
849                 return -EAGAIN;
850         }
851
852         /* NB don't drop ibc_lock before bumping tx_sending */
853         list_del(&tx->tx_list);
854         tx->tx_queued = 0;
855
856         if (msg->ibm_type == IBLND_MSG_NOOP &&
857             (!kiblnd_need_noop(conn) ||     /* redundant NOOP */
858              (IBLND_OOB_CAPABLE(ver) && /* posted enough NOOP */
859               conn->ibc_noops_posted == IBLND_OOB_MSGS(ver)))) {
860                 /* OK to drop when posted enough NOOPs, since
861                  * kiblnd_check_sends_locked will queue NOOP again when
862                  * posted NOOPs complete */
863                 spin_unlock(&conn->ibc_lock);
864                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
865                 kiblnd_tx_done(tx);
866                 spin_lock(&conn->ibc_lock);
867                 CDEBUG(D_NET, "%s(%d): redundant or enough NOOP\n",
868                        libcfs_nid2str(peer_ni->ibp_nid),
869                        conn->ibc_noops_posted);
870                 return 0;
871         }
872
873         kiblnd_pack_msg(peer_ni->ibp_ni, msg, ver, conn->ibc_outstanding_credits,
874                         peer_ni->ibp_nid, conn->ibc_incarnation);
875
876         conn->ibc_credits -= credit;
877         conn->ibc_outstanding_credits = 0;
878         conn->ibc_nsends_posted++;
879         if (msg->ibm_type == IBLND_MSG_NOOP)
880                 conn->ibc_noops_posted++;
881
882         /* CAVEAT EMPTOR!  This tx could be the PUT_DONE of an RDMA
883          * PUT.  If so, it was first queued here as a PUT_REQ, sent and
884          * stashed on ibc_active_txs, matched by an incoming PUT_ACK,
885          * and then re-queued here.  It's (just) possible that
886          * tx_sending is non-zero if we've not done the tx_complete()
887          * from the first send; hence the ++ rather than = below. */
888         tx->tx_sending++;
889         list_add(&tx->tx_list, &conn->ibc_active_txs);
890
891         /* I'm still holding ibc_lock! */
892         if (conn->ibc_state != IBLND_CONN_ESTABLISHED) {
893                 rc = -ECONNABORTED;
894         } else if (tx->tx_pool->tpo_pool.po_failed ||
895                  conn->ibc_hdev != tx->tx_pool->tpo_hdev) {
896                 /* close_conn will launch failover */
897                 rc = -ENETDOWN;
898         } else {
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 && !frd->frd_posted) {
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                 if (frd != NULL)
933                         frd->frd_posted = true;
934                 return 0;
935         }
936
937         /* NB credits are transferred in the actual
938          * message, which can only be the last work item */
939         conn->ibc_credits += credit;
940         conn->ibc_outstanding_credits += msg->ibm_credits;
941         conn->ibc_nsends_posted--;
942         if (msg->ibm_type == IBLND_MSG_NOOP)
943                 conn->ibc_noops_posted--;
944
945         tx->tx_status = rc;
946         tx->tx_waiting = 0;
947         tx->tx_sending--;
948
949         done = (tx->tx_sending == 0);
950         if (done)
951                 list_del(&tx->tx_list);
952
953         spin_unlock(&conn->ibc_lock);
954
955         if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
956                 CERROR("Error %d posting transmit to %s\n",
957                        rc, libcfs_nid2str(peer_ni->ibp_nid));
958         else
959                 CDEBUG(D_NET, "Error %d posting transmit to %s\n",
960                        rc, libcfs_nid2str(peer_ni->ibp_nid));
961
962         kiblnd_close_conn(conn, rc);
963
964         if (done)
965                 kiblnd_tx_done(tx);
966
967         spin_lock(&conn->ibc_lock);
968
969         return -EIO;
970 }
971
972 static void
973 kiblnd_check_sends_locked(struct kib_conn *conn)
974 {
975         int ver = conn->ibc_version;
976         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
977         struct kib_tx *tx;
978
979         /* Don't send anything until after the connection is established */
980         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
981                 CDEBUG(D_NET, "%s too soon\n",
982                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
983                 return;
984         }
985
986         LASSERT(conn->ibc_nsends_posted <=
987                 kiblnd_concurrent_sends(ver, ni));
988         LASSERT (!IBLND_OOB_CAPABLE(ver) ||
989                  conn->ibc_noops_posted <= IBLND_OOB_MSGS(ver));
990         LASSERT (conn->ibc_reserved_credits >= 0);
991
992         while (conn->ibc_reserved_credits > 0 &&
993                (tx = list_first_entry_or_null(&conn->ibc_tx_queue_rsrvd,
994                                               struct kib_tx, tx_list)) != NULL) {
995                 list_move_tail(&tx->tx_list, &conn->ibc_tx_queue);
996                 conn->ibc_reserved_credits--;
997         }
998
999         if (kiblnd_need_noop(conn)) {
1000                 spin_unlock(&conn->ibc_lock);
1001
1002                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1003                 if (tx != NULL)
1004                         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_NOOP, 0);
1005
1006                 spin_lock(&conn->ibc_lock);
1007                 if (tx != NULL)
1008                         kiblnd_queue_tx_locked(tx, conn);
1009         }
1010
1011         for (;;) {
1012                 int credit;
1013
1014                 if (!list_empty(&conn->ibc_tx_queue_nocred)) {
1015                         credit = 0;
1016                         tx = list_first_entry(&conn->ibc_tx_queue_nocred,
1017                                               struct kib_tx, tx_list);
1018                 } else if (!list_empty(&conn->ibc_tx_noops)) {
1019                         LASSERT (!IBLND_OOB_CAPABLE(ver));
1020                         credit = 1;
1021                         tx = list_first_entry(&conn->ibc_tx_noops,
1022                                               struct kib_tx, tx_list);
1023                 } else if (!list_empty(&conn->ibc_tx_queue)) {
1024                         credit = 1;
1025                         tx = list_first_entry(&conn->ibc_tx_queue,
1026                                               struct kib_tx, tx_list);
1027                 } else
1028                         break;
1029
1030                 if (kiblnd_post_tx_locked(conn, tx, credit) != 0)
1031                         break;
1032         }
1033 }
1034
1035 static void
1036 kiblnd_tx_complete(struct kib_tx *tx, int status)
1037 {
1038         int           failed = (status != IB_WC_SUCCESS);
1039         struct kib_conn   *conn = tx->tx_conn;
1040         int           idle;
1041
1042         if (tx->tx_sending <= 0) {
1043                 CERROR("Received an event on a freed tx: %p status %d\n",
1044                        tx, tx->tx_status);
1045                 return;
1046         }
1047
1048         if (failed) {
1049                 if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1050                         CNETERR("Tx -> %s cookie %#llx"
1051                                 " sending %d waiting %d: failed %d\n",
1052                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
1053                                 tx->tx_cookie, tx->tx_sending, tx->tx_waiting,
1054                                 status);
1055
1056                 kiblnd_close_conn(conn, -EIO);
1057         } else {
1058                 kiblnd_peer_alive(conn->ibc_peer);
1059         }
1060
1061         spin_lock(&conn->ibc_lock);
1062
1063         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
1064          * gets to free it, which also drops its ref on 'conn'. */
1065
1066         tx->tx_sending--;
1067         conn->ibc_nsends_posted--;
1068         if (tx->tx_msg->ibm_type == IBLND_MSG_NOOP)
1069                 conn->ibc_noops_posted--;
1070
1071         if (failed) {
1072                 tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
1073                 tx->tx_waiting = 0;             /* don't wait for peer_ni */
1074                 tx->tx_status = -EIO;
1075         }
1076
1077         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
1078                !tx->tx_waiting &&               /* Not waiting for peer_ni */
1079                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
1080         if (idle)
1081                 list_del(&tx->tx_list);
1082
1083         kiblnd_check_sends_locked(conn);
1084         spin_unlock(&conn->ibc_lock);
1085
1086         if (idle)
1087                 kiblnd_tx_done(tx);
1088 }
1089
1090 static void
1091 kiblnd_init_tx_msg(struct lnet_ni *ni, struct kib_tx *tx, int type,
1092                    int body_nob)
1093 {
1094         struct kib_hca_dev *hdev = tx->tx_pool->tpo_hdev;
1095         struct ib_sge *sge = &tx->tx_msgsge;
1096         struct ib_rdma_wr *wrq;
1097         int nob = offsetof(struct kib_msg, ibm_u) + body_nob;
1098 #ifdef HAVE_IB_GET_DMA_MR
1099         struct ib_mr *mr = hdev->ibh_mrs;
1100 #endif
1101
1102         LASSERT(tx->tx_nwrq >= 0);
1103         LASSERT(tx->tx_nwrq < IBLND_MAX_RDMA_FRAGS + 1);
1104         LASSERT(nob <= IBLND_MSG_SIZE);
1105 #ifdef HAVE_IB_GET_DMA_MR
1106         LASSERT(mr != NULL);
1107 #endif
1108
1109         kiblnd_init_msg(tx->tx_msg, type, body_nob);
1110
1111 #ifdef HAVE_IB_GET_DMA_MR
1112         sge->lkey   = mr->lkey;
1113 #else
1114         sge->lkey   = hdev->ibh_pd->local_dma_lkey;
1115 #endif
1116         sge->addr   = tx->tx_msgaddr;
1117         sge->length = nob;
1118
1119         wrq = &tx->tx_wrq[tx->tx_nwrq];
1120         memset(wrq, 0, sizeof(*wrq));
1121
1122         wrq->wr.next            = NULL;
1123         wrq->wr.wr_id           = kiblnd_ptr2wreqid(tx, IBLND_WID_TX);
1124         wrq->wr.sg_list         = sge;
1125         wrq->wr.num_sge         = 1;
1126         wrq->wr.opcode          = IB_WR_SEND;
1127         wrq->wr.send_flags      = IB_SEND_SIGNALED;
1128
1129         tx->tx_nwrq++;
1130 }
1131
1132 static int
1133 kiblnd_init_rdma(struct kib_conn *conn, struct kib_tx *tx, int type,
1134                  int resid, struct kib_rdma_desc *dstrd, u64 dstcookie)
1135 {
1136         struct kib_msg *ibmsg = tx->tx_msg;
1137         struct kib_rdma_desc *srcrd = tx->tx_rd;
1138         struct ib_rdma_wr *wrq = NULL;
1139         struct ib_sge     *sge;
1140         int                rc  = resid;
1141         int                srcidx;
1142         int                dstidx;
1143         int                sge_nob;
1144         int                wrq_sge;
1145
1146         LASSERT(!in_interrupt());
1147         LASSERT(tx->tx_nwrq == 0 && tx->tx_nsge == 0);
1148         LASSERT(type == IBLND_MSG_GET_DONE || type == IBLND_MSG_PUT_DONE);
1149
1150         for (srcidx = dstidx = wrq_sge = sge_nob = 0;
1151              resid > 0; resid -= sge_nob) {
1152                 int     prev = dstidx;
1153
1154                 if (srcidx >= srcrd->rd_nfrags) {
1155                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1156                         rc = -EPROTO;
1157                         break;
1158                 }
1159
1160                 if (dstidx >= dstrd->rd_nfrags) {
1161                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1162                         rc = -EPROTO;
1163                         break;
1164                 }
1165
1166                 if (tx->tx_nwrq >= conn->ibc_max_frags) {
1167                         CERROR("RDMA has too many fragments for peer_ni %s (%d), "
1168                                "src idx/frags: %d/%d dst idx/frags: %d/%d\n",
1169                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
1170                                conn->ibc_max_frags,
1171                                srcidx, srcrd->rd_nfrags,
1172                                dstidx, dstrd->rd_nfrags);
1173                         rc = -EMSGSIZE;
1174                         break;
1175                 }
1176
1177                 sge_nob = min3(kiblnd_rd_frag_size(srcrd, srcidx),
1178                                kiblnd_rd_frag_size(dstrd, dstidx),
1179                                resid);
1180
1181                 sge = &tx->tx_sge[tx->tx_nsge];
1182                 sge->addr   = kiblnd_rd_frag_addr(srcrd, srcidx);
1183                 sge->lkey   = kiblnd_rd_frag_key(srcrd, srcidx);
1184                 sge->length = sge_nob;
1185
1186                 if (wrq_sge == 0) {
1187                         wrq = &tx->tx_wrq[tx->tx_nwrq];
1188
1189                         wrq->wr.next    = &(wrq + 1)->wr;
1190                         wrq->wr.wr_id   = kiblnd_ptr2wreqid(tx, IBLND_WID_RDMA);
1191                         wrq->wr.sg_list = sge;
1192                         wrq->wr.opcode  = IB_WR_RDMA_WRITE;
1193                         wrq->wr.send_flags = 0;
1194
1195 #ifdef HAVE_IB_RDMA_WR
1196                         wrq->remote_addr        = kiblnd_rd_frag_addr(dstrd,
1197                                                                       dstidx);
1198                         wrq->rkey               = kiblnd_rd_frag_key(dstrd,
1199                                                                      dstidx);
1200 #else
1201                         wrq->wr.wr.rdma.remote_addr = kiblnd_rd_frag_addr(dstrd,
1202                                                                         dstidx);
1203                         wrq->wr.wr.rdma.rkey    = kiblnd_rd_frag_key(dstrd,
1204                                                                      dstidx);
1205 #endif
1206                 }
1207
1208                 srcidx = kiblnd_rd_consume_frag(srcrd, srcidx, sge_nob);
1209                 dstidx = kiblnd_rd_consume_frag(dstrd, dstidx, sge_nob);
1210
1211                 wrq_sge++;
1212                 if (wrq_sge == *kiblnd_tunables.kib_wrq_sge || dstidx != prev) {
1213                         tx->tx_nwrq++;
1214                         wrq->wr.num_sge = wrq_sge;
1215                         wrq_sge = 0;
1216                 }
1217                 tx->tx_nsge++;
1218         }
1219
1220         if (rc < 0)     /* no RDMA if completing with failure */
1221                 tx->tx_nwrq = tx->tx_nsge = 0;
1222
1223         ibmsg->ibm_u.completion.ibcm_status = rc;
1224         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1225         kiblnd_init_tx_msg(conn->ibc_peer->ibp_ni, tx,
1226                            type, sizeof(struct kib_completion_msg));
1227
1228         return rc;
1229 }
1230
1231 static void
1232 kiblnd_queue_tx_locked(struct kib_tx *tx, struct kib_conn *conn)
1233 {
1234         struct list_head *q;
1235         s64 timeout_ns;
1236
1237         LASSERT(tx->tx_nwrq > 0);       /* work items set up */
1238         LASSERT(!tx->tx_queued);        /* not queued for sending already */
1239         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1240
1241         if (conn->ibc_state >= IBLND_CONN_DISCONNECTED) {
1242                 tx->tx_status = -ECONNABORTED;
1243                 tx->tx_waiting = 0;
1244                 if (tx->tx_conn != NULL) {
1245                         /* PUT_DONE first attached to conn as a PUT_REQ */
1246                         LASSERT(tx->tx_conn == conn);
1247                         LASSERT(tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1248                         tx->tx_conn = NULL;
1249                         kiblnd_conn_decref(conn);
1250                 }
1251                 list_add(&tx->tx_list, &conn->ibc_zombie_txs);
1252
1253                 return;
1254         }
1255
1256         timeout_ns = kiblnd_timeout() * NSEC_PER_SEC;
1257         tx->tx_queued = 1;
1258         tx->tx_deadline = ktime_add_ns(ktime_get(), timeout_ns);
1259
1260         if (tx->tx_conn == NULL) {
1261                 kiblnd_conn_addref(conn);
1262                 tx->tx_conn = conn;
1263                 LASSERT (tx->tx_msg->ibm_type != IBLND_MSG_PUT_DONE);
1264         } else {
1265                 /* PUT_DONE first attached to conn as a PUT_REQ */
1266                 LASSERT (tx->tx_conn == conn);
1267                 LASSERT (tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1268         }
1269
1270         switch (tx->tx_msg->ibm_type) {
1271         default:
1272                 LBUG();
1273
1274         case IBLND_MSG_PUT_REQ:
1275         case IBLND_MSG_GET_REQ:
1276                 q = &conn->ibc_tx_queue_rsrvd;
1277                 break;
1278
1279         case IBLND_MSG_PUT_NAK:
1280         case IBLND_MSG_PUT_ACK:
1281         case IBLND_MSG_PUT_DONE:
1282         case IBLND_MSG_GET_DONE:
1283                 q = &conn->ibc_tx_queue_nocred;
1284                 break;
1285
1286         case IBLND_MSG_NOOP:
1287                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
1288                         q = &conn->ibc_tx_queue_nocred;
1289                 else
1290                         q = &conn->ibc_tx_noops;
1291                 break;
1292
1293         case IBLND_MSG_IMMEDIATE:
1294                 q = &conn->ibc_tx_queue;
1295                 break;
1296         }
1297
1298         list_add_tail(&tx->tx_list, q);
1299 }
1300
1301 static void
1302 kiblnd_queue_tx(struct kib_tx *tx, struct kib_conn *conn)
1303 {
1304         spin_lock(&conn->ibc_lock);
1305         kiblnd_queue_tx_locked(tx, conn);
1306         kiblnd_check_sends_locked(conn);
1307         spin_unlock(&conn->ibc_lock);
1308 }
1309
1310 static int
1311 kiblnd_resolve_addr_cap(struct rdma_cm_id *cmid,
1312                         struct sockaddr_in *srcaddr,
1313                         struct sockaddr_in *dstaddr,
1314                         int timeout_ms)
1315 {
1316         unsigned short port;
1317         int rc;
1318
1319         /* allow the port to be reused */
1320         rc = rdma_set_reuseaddr(cmid, 1);
1321         if (rc != 0) {
1322                 CERROR("Unable to set reuse on cmid: %d\n", rc);
1323                 return rc;
1324         }
1325
1326         /* look for a free privileged port */
1327         for (port = PROT_SOCK-1; port > 0; port--) {
1328                 srcaddr->sin_port = htons(port);
1329                 rc = rdma_resolve_addr(cmid,
1330                                        (struct sockaddr *)srcaddr,
1331                                        (struct sockaddr *)dstaddr,
1332                                        timeout_ms);
1333                 if (rc == 0) {
1334                         CDEBUG(D_NET, "bound to port %hu\n", port);
1335                         return 0;
1336                 } else if (rc == -EADDRINUSE || rc == -EADDRNOTAVAIL) {
1337                         CDEBUG(D_NET, "bind to port %hu failed: %d\n",
1338                                port, rc);
1339                 } else {
1340                         return rc;
1341                 }
1342         }
1343
1344         CERROR("cannot bind to a free privileged port: rc = %d\n", rc);
1345
1346         return rc;
1347 }
1348
1349 static int
1350 kiblnd_resolve_addr(struct rdma_cm_id *cmid,
1351                     struct sockaddr_in *srcaddr,
1352                     struct sockaddr_in *dstaddr,
1353                     int timeout_ms)
1354 {
1355         const struct cred *old_creds = NULL;
1356         struct cred *new_creds;
1357         int rc;
1358
1359         if (!capable(CAP_NET_BIND_SERVICE)) {
1360                 new_creds = prepare_kernel_cred(NULL);
1361                 if (!new_creds)
1362                         return -ENOMEM;
1363
1364                 cap_raise(new_creds->cap_effective, CAP_NET_BIND_SERVICE);
1365                 old_creds = override_creds(new_creds);
1366         }
1367
1368         rc = kiblnd_resolve_addr_cap(cmid, srcaddr, dstaddr, timeout_ms);
1369
1370         if (old_creds)
1371                 revert_creds(old_creds);
1372
1373         return rc;
1374 }
1375
1376 static void
1377 kiblnd_connect_peer(struct kib_peer_ni *peer_ni)
1378 {
1379         struct rdma_cm_id *cmid;
1380         struct kib_dev *dev;
1381         struct kib_net *net = peer_ni->ibp_ni->ni_data;
1382         struct sockaddr_in srcaddr;
1383         struct sockaddr_in dstaddr;
1384         int rc;
1385
1386         LASSERT (net != NULL);
1387         LASSERT (peer_ni->ibp_connecting > 0);
1388
1389         cmid = kiblnd_rdma_create_id(peer_ni->ibp_ni->ni_net_ns,
1390                                      kiblnd_cm_callback, peer_ni,
1391                                      RDMA_PS_TCP, IB_QPT_RC);
1392
1393         if (IS_ERR(cmid)) {
1394                 CERROR("Can't create CMID for %s: %ld\n",
1395                        libcfs_nid2str(peer_ni->ibp_nid), PTR_ERR(cmid));
1396                 rc = PTR_ERR(cmid);
1397                 goto failed;
1398         }
1399
1400         dev = net->ibn_dev;
1401         memset(&srcaddr, 0, sizeof(srcaddr));
1402         srcaddr.sin_family = AF_INET;
1403         srcaddr.sin_addr.s_addr = htonl(dev->ibd_ifip);
1404
1405         memset(&dstaddr, 0, sizeof(dstaddr));
1406         dstaddr.sin_family = AF_INET;
1407         dstaddr.sin_port = htons(*kiblnd_tunables.kib_service);
1408         dstaddr.sin_addr.s_addr = htonl(LNET_NIDADDR(peer_ni->ibp_nid));
1409
1410         kiblnd_peer_addref(peer_ni);               /* cmid's ref */
1411
1412         if (*kiblnd_tunables.kib_use_priv_port) {
1413                 rc = kiblnd_resolve_addr(cmid, &srcaddr, &dstaddr,
1414                                          kiblnd_timeout() * 1000);
1415         } else {
1416                 rc = rdma_resolve_addr(cmid,
1417                                        (struct sockaddr *)&srcaddr,
1418                                        (struct sockaddr *)&dstaddr,
1419                                        kiblnd_timeout() * 1000);
1420         }
1421         if (rc != 0) {
1422                 /* Can't initiate address resolution:  */
1423                 CERROR("Can't resolve addr for %s: %d\n",
1424                        libcfs_nid2str(peer_ni->ibp_nid), rc);
1425                 goto failed2;
1426         }
1427
1428         return;
1429
1430  failed2:
1431         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1432         kiblnd_peer_decref(peer_ni);               /* cmid's ref */
1433         rdma_destroy_id(cmid);
1434         return;
1435  failed:
1436         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1437 }
1438
1439 bool
1440 kiblnd_reconnect_peer(struct kib_peer_ni *peer_ni)
1441 {
1442         rwlock_t *glock = &kiblnd_data.kib_global_lock;
1443         char *reason = NULL;
1444         LIST_HEAD(txs);
1445         unsigned long flags;
1446
1447         write_lock_irqsave(glock, flags);
1448         if (peer_ni->ibp_reconnecting == 0) {
1449                 if (peer_ni->ibp_accepting)
1450                         reason = "accepting";
1451                 else if (peer_ni->ibp_connecting)
1452                         reason = "connecting";
1453                 else if (!list_empty(&peer_ni->ibp_conns))
1454                         reason = "connected";
1455                 else /* connected then closed */
1456                         reason = "closed";
1457
1458                 goto no_reconnect;
1459         }
1460
1461         if (peer_ni->ibp_accepting)
1462                 CNETERR("Detecting race between accepting and reconnecting\n");
1463         peer_ni->ibp_reconnecting--;
1464
1465         if (!kiblnd_peer_active(peer_ni)) {
1466                 list_splice_init(&peer_ni->ibp_tx_queue, &txs);
1467                 reason = "unlinked";
1468                 goto no_reconnect;
1469         }
1470
1471         peer_ni->ibp_connecting++;
1472         peer_ni->ibp_reconnected++;
1473
1474         write_unlock_irqrestore(glock, flags);
1475
1476         kiblnd_connect_peer(peer_ni);
1477         return true;
1478
1479  no_reconnect:
1480         write_unlock_irqrestore(glock, flags);
1481
1482         CWARN("Abort reconnection of %s: %s\n",
1483               libcfs_nid2str(peer_ni->ibp_nid), reason);
1484         kiblnd_txlist_done(&txs, -ECONNABORTED,
1485                            LNET_MSG_STATUS_LOCAL_ABORTED);
1486         return false;
1487 }
1488
1489 void
1490 kiblnd_launch_tx(struct lnet_ni *ni, struct kib_tx *tx, lnet_nid_t nid)
1491 {
1492         struct kib_peer_ni *peer_ni;
1493         struct kib_peer_ni *peer2;
1494         struct kib_conn *conn;
1495         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
1496         unsigned long flags;
1497         int rc;
1498         int i;
1499         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
1500
1501         /* If I get here, I've committed to send, so I complete the tx with
1502          * failure on any problems
1503          */
1504
1505         LASSERT(!tx || !tx->tx_conn);     /* only set when assigned a conn */
1506         LASSERT(!tx || tx->tx_nwrq > 0);  /* work items have been set up */
1507
1508         /* First time, just use a read lock since I expect to find my peer_ni
1509          * connected
1510          */
1511         read_lock_irqsave(g_lock, flags);
1512
1513         peer_ni = kiblnd_find_peer_locked(ni, nid);
1514         if (peer_ni != NULL && !list_empty(&peer_ni->ibp_conns)) {
1515                 /* Found a peer_ni with an established connection */
1516                 conn = kiblnd_get_conn_locked(peer_ni);
1517                 kiblnd_conn_addref(conn); /* 1 ref for me... */
1518
1519                 read_unlock_irqrestore(g_lock, flags);
1520
1521                 if (tx != NULL)
1522                         kiblnd_queue_tx(tx, conn);
1523                 kiblnd_conn_decref(conn); /* ...to here */
1524                 return;
1525         }
1526
1527         read_unlock(g_lock);
1528         /* Re-try with a write lock */
1529         write_lock(g_lock);
1530
1531         peer_ni = kiblnd_find_peer_locked(ni, nid);
1532         if (peer_ni != NULL) {
1533                 if (list_empty(&peer_ni->ibp_conns)) {
1534                         /* found a peer_ni, but it's still connecting... */
1535                         LASSERT(kiblnd_peer_connecting(peer_ni));
1536                         if (tx != NULL)
1537                                 list_add_tail(&tx->tx_list,
1538                                               &peer_ni->ibp_tx_queue);
1539                         write_unlock_irqrestore(g_lock, flags);
1540                 } else {
1541                         conn = kiblnd_get_conn_locked(peer_ni);
1542                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1543
1544                         write_unlock_irqrestore(g_lock, flags);
1545
1546                         if (tx != NULL)
1547                                 kiblnd_queue_tx(tx, conn);
1548                         kiblnd_conn_decref(conn); /* ...to here */
1549                 }
1550                 return;
1551         }
1552
1553         write_unlock_irqrestore(g_lock, flags);
1554
1555         /* Allocate a peer_ni ready to add to the peer_ni table and retry */
1556         rc = kiblnd_create_peer(ni, &peer_ni, nid);
1557         if (rc != 0) {
1558                 CERROR("Can't create peer_ni %s\n", libcfs_nid2str(nid));
1559                 if (tx != NULL) {
1560                         tx->tx_status = -EHOSTUNREACH;
1561                         tx->tx_waiting = 0;
1562                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1563                         kiblnd_tx_done(tx);
1564                 }
1565                 return;
1566         }
1567
1568         write_lock_irqsave(g_lock, flags);
1569
1570         peer2 = kiblnd_find_peer_locked(ni, nid);
1571         if (peer2 != NULL) {
1572                 if (list_empty(&peer2->ibp_conns)) {
1573                         /* found a peer_ni, but it's still connecting... */
1574                         LASSERT(kiblnd_peer_connecting(peer2));
1575                         if (tx != NULL)
1576                                 list_add_tail(&tx->tx_list,
1577                                               &peer2->ibp_tx_queue);
1578                         write_unlock_irqrestore(g_lock, flags);
1579                 } else {
1580                         conn = kiblnd_get_conn_locked(peer2);
1581                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1582
1583                         write_unlock_irqrestore(g_lock, flags);
1584
1585                         if (tx != NULL)
1586                                 kiblnd_queue_tx(tx, conn);
1587                         kiblnd_conn_decref(conn); /* ...to here */
1588                 }
1589
1590                 kiblnd_peer_decref(peer_ni);
1591                 return;
1592         }
1593
1594         /* Brand new peer_ni */
1595         LASSERT(peer_ni->ibp_connecting == 0);
1596         tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
1597         peer_ni->ibp_connecting = tunables->lnd_conns_per_peer;
1598
1599         /* always called with a ref on ni, which prevents ni being shutdown */
1600         LASSERT(((struct kib_net *)ni->ni_data)->ibn_shutdown == 0);
1601
1602         if (tx != NULL)
1603                 list_add_tail(&tx->tx_list, &peer_ni->ibp_tx_queue);
1604
1605         kiblnd_peer_addref(peer_ni);
1606         hash_add(kiblnd_data.kib_peers, &peer_ni->ibp_list, nid);
1607
1608         write_unlock_irqrestore(g_lock, flags);
1609
1610         for (i = 0; i < tunables->lnd_conns_per_peer; i++)
1611                 kiblnd_connect_peer(peer_ni);
1612         kiblnd_peer_decref(peer_ni);
1613 }
1614
1615 int
1616 kiblnd_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg)
1617 {
1618         struct lnet_hdr *hdr = &lntmsg->msg_hdr;
1619         int               type = lntmsg->msg_type;
1620         struct lnet_process_id target = lntmsg->msg_target;
1621         int               target_is_router = lntmsg->msg_target_is_router;
1622         int               routing = lntmsg->msg_routing;
1623         unsigned int      payload_niov = lntmsg->msg_niov;
1624         struct bio_vec   *payload_kiov = lntmsg->msg_kiov;
1625         unsigned int      payload_offset = lntmsg->msg_offset;
1626         unsigned int      payload_nob = lntmsg->msg_len;
1627         struct kib_msg *ibmsg;
1628         struct kib_rdma_desc *rd;
1629         struct kib_tx *tx;
1630         int               nob;
1631         int               rc;
1632
1633         /* NB 'private' is different depending on what we're sending.... */
1634
1635         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1636                payload_nob, payload_niov, libcfs_id2str(target));
1637
1638         LASSERT (payload_nob == 0 || payload_niov > 0);
1639         LASSERT (payload_niov <= LNET_MAX_IOV);
1640
1641         /* Thread context */
1642         LASSERT (!in_interrupt());
1643
1644         switch (type) {
1645         default:
1646                 LBUG();
1647                 return (-EIO);
1648
1649         case LNET_MSG_ACK:
1650                 LASSERT (payload_nob == 0);
1651                 break;
1652
1653         case LNET_MSG_GET:
1654                 if (routing || target_is_router)
1655                         break;                  /* send IMMEDIATE */
1656
1657                 /* is the REPLY message too small for RDMA? */
1658                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1659                 if (nob <= IBLND_MSG_SIZE && !lntmsg->msg_rdma_force)
1660                         break;                  /* send IMMEDIATE */
1661
1662                 tx = kiblnd_get_idle_tx(ni, target.nid);
1663                 if (tx == NULL) {
1664                         CERROR("Can't allocate txd for GET to %s\n",
1665                                libcfs_nid2str(target.nid));
1666                         return -ENOMEM;
1667                 }
1668
1669                 ibmsg = tx->tx_msg;
1670                 rd = &ibmsg->ibm_u.get.ibgm_rd;
1671                 rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1672                                           lntmsg->msg_md->md_niov,
1673                                           lntmsg->msg_md->md_kiov,
1674                                           0, lntmsg->msg_md->md_length);
1675                 if (rc != 0) {
1676                         CERROR("Can't setup GET sink for %s: %d\n",
1677                                libcfs_nid2str(target.nid), rc);
1678                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1679                         kiblnd_tx_done(tx);
1680                         return -EIO;
1681                 }
1682
1683                 nob = offsetof(struct kib_get_msg, ibgm_rd.rd_frags[rd->rd_nfrags]);
1684                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1685                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1686
1687                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1688
1689                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1690                 if (tx->tx_lntmsg[1] == NULL) {
1691                         CERROR("Can't create reply for GET -> %s\n",
1692                                libcfs_nid2str(target.nid));
1693                         kiblnd_tx_done(tx);
1694                         return -EIO;
1695                 }
1696
1697                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1698                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1699                 kiblnd_launch_tx(ni, tx, target.nid);
1700                 return 0;
1701
1702         case LNET_MSG_REPLY:
1703         case LNET_MSG_PUT:
1704                 /* Is the payload small enough not to need RDMA? */
1705                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob]);
1706                 if (nob <= IBLND_MSG_SIZE && !lntmsg->msg_rdma_force)
1707                         break;                  /* send IMMEDIATE */
1708
1709                 tx = kiblnd_get_idle_tx(ni, target.nid);
1710                 if (tx == NULL) {
1711                         CERROR("Can't allocate %s txd for %s\n",
1712                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1713                                libcfs_nid2str(target.nid));
1714                         return -ENOMEM;
1715                 }
1716
1717                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1718                                           payload_niov, payload_kiov,
1719                                           payload_offset, payload_nob);
1720                 if (rc != 0) {
1721                         CERROR("Can't setup PUT src for %s: %d\n",
1722                                libcfs_nid2str(target.nid), rc);
1723                         kiblnd_tx_done(tx);
1724                         return -EIO;
1725                 }
1726
1727                 ibmsg = tx->tx_msg;
1728                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1729                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1730                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ,
1731                                    sizeof(struct kib_putreq_msg));
1732
1733                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1734                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1735                 kiblnd_launch_tx(ni, tx, target.nid);
1736                 return 0;
1737         }
1738
1739         /* send IMMEDIATE */
1740         LASSERT(offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob])
1741                 <= IBLND_MSG_SIZE);
1742
1743         tx = kiblnd_get_idle_tx(ni, target.nid);
1744         if (tx == NULL) {
1745                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1746                         type, libcfs_nid2str(target.nid));
1747                 return -ENOMEM;
1748         }
1749
1750         ibmsg = tx->tx_msg;
1751         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1752
1753         lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1754                             offsetof(struct kib_msg,
1755                                      ibm_u.immediate.ibim_payload),
1756                             payload_niov, payload_kiov,
1757                             payload_offset, payload_nob);
1758
1759         nob = offsetof(struct kib_immediate_msg, ibim_payload[payload_nob]);
1760         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1761
1762         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1763         kiblnd_launch_tx(ni, tx, target.nid);
1764         return 0;
1765 }
1766
1767 static void
1768 kiblnd_reply(struct lnet_ni *ni, struct kib_rx *rx, struct lnet_msg *lntmsg)
1769 {
1770         struct lnet_process_id target = lntmsg->msg_target;
1771         unsigned int niov = lntmsg->msg_niov;
1772         struct bio_vec *kiov = lntmsg->msg_kiov;
1773         unsigned int offset = lntmsg->msg_offset;
1774         unsigned int nob = lntmsg->msg_len;
1775         struct kib_tx *tx;
1776         int rc;
1777
1778         tx = kiblnd_get_idle_tx(ni, rx->rx_conn->ibc_peer->ibp_nid);
1779         if (tx == NULL) {
1780                 CERROR("Can't get tx for REPLY to %s\n",
1781                        libcfs_nid2str(target.nid));
1782                 goto failed_0;
1783         }
1784
1785         if (nob == 0)
1786                 rc = 0;
1787         else
1788                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1789                                           niov, kiov, offset, nob);
1790
1791         if (rc != 0) {
1792                 CERROR("Can't setup GET src for %s: %d\n",
1793                        libcfs_nid2str(target.nid), rc);
1794                 goto failed_1;
1795         }
1796
1797         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1798                               IBLND_MSG_GET_DONE, nob,
1799                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1800                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1801         if (rc < 0) {
1802                 CERROR("Can't setup rdma for GET from %s: %d\n",
1803                        libcfs_nid2str(target.nid), rc);
1804                 goto failed_1;
1805         }
1806
1807         if (nob == 0) {
1808                 /* No RDMA: local completion may happen now! */
1809                 lnet_finalize(lntmsg, 0);
1810         } else {
1811                 /* RDMA: lnet_finalize(lntmsg) when it
1812                  * completes */
1813                 tx->tx_lntmsg[0] = lntmsg;
1814         }
1815
1816         kiblnd_queue_tx(tx, rx->rx_conn);
1817         return;
1818
1819
1820 failed_1:
1821         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1822         kiblnd_tx_done(tx);
1823 failed_0:
1824         lnet_finalize(lntmsg, -EIO);
1825 }
1826
1827 unsigned int
1828 kiblnd_get_dev_prio(struct lnet_ni *ni, unsigned int dev_idx)
1829 {
1830         struct kib_net *net = ni->ni_data;
1831         struct device *dev = NULL;
1832
1833         if (net)
1834                 dev = net->ibn_dev->ibd_hdev->ibh_ibdev->dma_device;
1835
1836         return lnet_get_dev_prio(dev, dev_idx);
1837
1838 }
1839
1840 int
1841 kiblnd_recv(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg,
1842             int delayed, unsigned int niov, struct bio_vec *kiov,
1843             unsigned int offset, unsigned int mlen, unsigned int rlen)
1844 {
1845         struct kib_rx *rx = private;
1846         struct kib_msg *rxmsg = rx->rx_msg;
1847         struct kib_conn *conn = rx->rx_conn;
1848         struct kib_tx *tx;
1849         __u64        ibprm_cookie;
1850         int          nob;
1851         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1852         int          rc = 0;
1853
1854         LASSERT (mlen <= rlen);
1855         LASSERT (!in_interrupt());
1856
1857         switch (rxmsg->ibm_type) {
1858         default:
1859                 LBUG();
1860
1861         case IBLND_MSG_IMMEDIATE:
1862                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[rlen]);
1863                 if (nob > rx->rx_nob) {
1864                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1865                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1866                                 nob, rx->rx_nob);
1867                         rc = -EPROTO;
1868                         break;
1869                 }
1870
1871                 lnet_copy_flat2kiov(niov, kiov, offset,
1872                                     IBLND_MSG_SIZE, rxmsg,
1873                                     offsetof(struct kib_msg,
1874                                              ibm_u.immediate.ibim_payload),
1875                                     mlen);
1876                 lnet_finalize(lntmsg, 0);
1877                 break;
1878
1879         case IBLND_MSG_PUT_REQ: {
1880                 struct kib_msg  *txmsg;
1881                 struct kib_rdma_desc *rd;
1882                 ibprm_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1883
1884                 if (mlen == 0) {
1885                         lnet_finalize(lntmsg, 0);
1886                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1887                                                0, ibprm_cookie);
1888                         break;
1889                 }
1890
1891                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1892                 if (tx == NULL) {
1893                         CERROR("Can't allocate tx for %s\n",
1894                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1895                         /* Not replying will break the connection */
1896                         rc = -ENOMEM;
1897                         break;
1898                 }
1899
1900                 txmsg = tx->tx_msg;
1901                 rd = &txmsg->ibm_u.putack.ibpam_rd;
1902                 rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1903                                           niov, kiov, offset, mlen);
1904                 if (rc != 0) {
1905                         CERROR("Can't setup PUT sink for %s: %d\n",
1906                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1907                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1908                         kiblnd_tx_done(tx);
1909                         /* tell peer_ni it's over */
1910                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1911                                                rc, ibprm_cookie);
1912                         break;
1913                 }
1914
1915                 nob = offsetof(struct kib_putack_msg, ibpam_rd.rd_frags[rd->rd_nfrags]);
1916                 txmsg->ibm_u.putack.ibpam_src_cookie = ibprm_cookie;
1917                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1918
1919                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1920
1921                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1922                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1923                 kiblnd_queue_tx(tx, conn);
1924
1925                 /* reposted buffer reserved for PUT_DONE */
1926                 post_credit = IBLND_POSTRX_NO_CREDIT;
1927                 break;
1928                 }
1929
1930         case IBLND_MSG_GET_REQ:
1931                 if (lntmsg != NULL) {
1932                         /* Optimized GET; RDMA lntmsg's payload */
1933                         kiblnd_reply(ni, rx, lntmsg);
1934                 } else {
1935                         /* GET didn't match anything */
1936                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1937                                                -ENODATA,
1938                                                rxmsg->ibm_u.get.ibgm_cookie);
1939                 }
1940                 break;
1941         }
1942
1943         kiblnd_post_rx(rx, post_credit);
1944         return rc;
1945 }
1946
1947 static void
1948 kiblnd_thread_fini (void)
1949 {
1950         atomic_dec (&kiblnd_data.kib_nthreads);
1951 }
1952
1953 static void
1954 kiblnd_peer_alive(struct kib_peer_ni *peer_ni)
1955 {
1956         /* This is racy, but everyone's only writing ktime_get_seconds() */
1957         peer_ni->ibp_last_alive = ktime_get_seconds();
1958         smp_mb();
1959 }
1960
1961 static void
1962 kiblnd_peer_notify(struct kib_peer_ni *peer_ni)
1963 {
1964         int           error = 0;
1965         time64_t last_alive = 0;
1966         unsigned long flags;
1967
1968         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1969
1970         if (kiblnd_peer_idle(peer_ni) && peer_ni->ibp_error != 0) {
1971                 error = peer_ni->ibp_error;
1972                 peer_ni->ibp_error = 0;
1973
1974                 last_alive = peer_ni->ibp_last_alive;
1975         }
1976
1977         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1978
1979         if (error != 0)
1980                 lnet_notify(peer_ni->ibp_ni,
1981                             peer_ni->ibp_nid, false, false, last_alive);
1982 }
1983
1984 void
1985 kiblnd_close_conn_locked(struct kib_conn *conn, int error)
1986 {
1987         /* This just does the immediate housekeeping.  'error' is zero for a
1988          * normal shutdown which can happen only after the connection has been
1989          * established.  If the connection is established, schedule the
1990          * connection to be finished off by the connd.  Otherwise the connd is
1991          * already dealing with it (either to set it up or tear it down).
1992          * Caller holds kib_global_lock exclusively in irq context */
1993         struct kib_peer_ni *peer_ni = conn->ibc_peer;
1994         struct kib_dev *dev;
1995         unsigned long flags;
1996
1997         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1998
1999         if (error != 0 && conn->ibc_comms_error == 0)
2000                 conn->ibc_comms_error = error;
2001
2002         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
2003                 return; /* already being handled  */
2004
2005         if (error == 0 &&
2006             list_empty(&conn->ibc_tx_noops) &&
2007             list_empty(&conn->ibc_tx_queue) &&
2008             list_empty(&conn->ibc_tx_queue_rsrvd) &&
2009             list_empty(&conn->ibc_tx_queue_nocred) &&
2010             list_empty(&conn->ibc_active_txs)) {
2011                 CDEBUG(D_NET, "closing conn to %s\n", 
2012                        libcfs_nid2str(peer_ni->ibp_nid));
2013         } else {
2014                 CNETERR("Closing conn to %s: error %d%s%s%s%s%s\n",
2015                        libcfs_nid2str(peer_ni->ibp_nid), error,
2016                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
2017                        list_empty(&conn->ibc_tx_noops) ? "" : "(sending_noops)",
2018                        list_empty(&conn->ibc_tx_queue_rsrvd) ?
2019                                                 "" : "(sending_rsrvd)",
2020                        list_empty(&conn->ibc_tx_queue_nocred) ?
2021                                                  "" : "(sending_nocred)",
2022                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
2023         }
2024
2025         dev = ((struct kib_net *)peer_ni->ibp_ni->ni_data)->ibn_dev;
2026         if (peer_ni->ibp_next_conn == conn)
2027                 /* clear next_conn so it won't be used */
2028                 peer_ni->ibp_next_conn = NULL;
2029         list_del(&conn->ibc_list);
2030         /* connd (see below) takes over ibc_list's ref */
2031
2032         if (list_empty(&peer_ni->ibp_conns) &&    /* no more conns */
2033             kiblnd_peer_active(peer_ni)) {         /* still in peer_ni table */
2034                 kiblnd_unlink_peer_locked(peer_ni);
2035
2036                 /* set/clear error on last conn */
2037                 peer_ni->ibp_error = conn->ibc_comms_error;
2038         }
2039
2040         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
2041
2042         if (error != 0 &&
2043             kiblnd_dev_can_failover(dev)) {
2044                 list_add_tail(&dev->ibd_fail_list,
2045                               &kiblnd_data.kib_failed_devs);
2046                 wake_up(&kiblnd_data.kib_failover_waitq);
2047         }
2048
2049         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2050
2051         list_add_tail(&conn->ibc_list, &kiblnd_data.kib_connd_conns);
2052         wake_up(&kiblnd_data.kib_connd_waitq);
2053
2054         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
2055 }
2056
2057 void
2058 kiblnd_close_conn(struct kib_conn *conn, int error)
2059 {
2060         unsigned long flags;
2061
2062         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2063
2064         kiblnd_close_conn_locked(conn, error);
2065
2066         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2067 }
2068
2069 static void
2070 kiblnd_handle_early_rxs(struct kib_conn *conn)
2071 {
2072         unsigned long flags;
2073         struct kib_rx *rx;
2074
2075         LASSERT(!in_interrupt());
2076         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2077
2078         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2079         while ((rx = list_first_entry_or_null(&conn->ibc_early_rxs,
2080                                               struct kib_rx,
2081                                               rx_list)) != NULL) {
2082                 list_del(&rx->rx_list);
2083                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2084
2085                 kiblnd_handle_rx(rx);
2086
2087                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2088         }
2089         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2090 }
2091
2092 void
2093 kiblnd_abort_txs(struct kib_conn *conn, struct list_head *txs)
2094 {
2095         LIST_HEAD(zombies);
2096         struct kib_tx *nxt;
2097         struct kib_tx *tx;
2098
2099         spin_lock(&conn->ibc_lock);
2100
2101         list_for_each_entry_safe(tx, nxt, txs, tx_list) {
2102                 if (txs == &conn->ibc_active_txs) {
2103                         LASSERT(!tx->tx_queued);
2104                         LASSERT(tx->tx_waiting ||
2105                                 tx->tx_sending != 0);
2106                         if (conn->ibc_comms_error == -ETIMEDOUT) {
2107                                 if (tx->tx_waiting && !tx->tx_sending)
2108                                         tx->tx_hstatus =
2109                                           LNET_MSG_STATUS_REMOTE_TIMEOUT;
2110                                 else if (tx->tx_sending)
2111                                         tx->tx_hstatus =
2112                                           LNET_MSG_STATUS_NETWORK_TIMEOUT;
2113                         }
2114                 } else {
2115                         LASSERT(tx->tx_queued);
2116                         if (conn->ibc_comms_error == -ETIMEDOUT)
2117                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2118                         else
2119                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
2120                 }
2121
2122                 tx->tx_status = -ECONNABORTED;
2123                 tx->tx_waiting = 0;
2124
2125                 /*
2126                  * TODO: This makes an assumption that
2127                  * kiblnd_tx_complete() will be called for each tx. If
2128                  * that event is dropped we could end up with stale
2129                  * connections floating around. We'd like to deal with
2130                  * that in a better way.
2131                  *
2132                  * Also that means we can exceed the timeout by many
2133                  * seconds.
2134                  */
2135                 if (tx->tx_sending == 0) {
2136                         tx->tx_queued = 0;
2137                         list_move(&tx->tx_list, &zombies);
2138                 } else {
2139                         /* keep tx until cq destroy */
2140                         list_move(&tx->tx_list, &conn->ibc_zombie_txs);
2141                         conn->ibc_waits ++;
2142                 }
2143         }
2144
2145         spin_unlock(&conn->ibc_lock);
2146
2147         /*
2148          * aborting transmits occurs when finalizing the connection.
2149          * The connection is finalized on error.
2150          * Passing LNET_MSG_STATUS_OK to txlist_done() will not
2151          * override the value already set in tx->tx_hstatus above.
2152          */
2153         kiblnd_txlist_done(&zombies, -ECONNABORTED, LNET_MSG_STATUS_OK);
2154 }
2155
2156 static bool
2157 kiblnd_tx_may_discard(struct kib_conn *conn)
2158 {
2159         bool rc = false;
2160         struct kib_tx *nxt;
2161         struct kib_tx *tx;
2162
2163         spin_lock(&conn->ibc_lock);
2164
2165         list_for_each_entry_safe(tx, nxt, &conn->ibc_zombie_txs, tx_list) {
2166                 if (tx->tx_sending > 0 && tx->tx_lntmsg[0] &&
2167                     lnet_md_discarded(tx->tx_lntmsg[0]->msg_md)) {
2168                         tx->tx_sending --;
2169                         if (tx->tx_sending == 0) {
2170                                 kiblnd_conn_decref(tx->tx_conn);
2171                                 tx->tx_conn = NULL;
2172                                 rc = true;
2173                         }
2174                 }
2175         }
2176
2177         spin_unlock(&conn->ibc_lock);
2178         return rc;
2179 }
2180
2181 static void
2182 kiblnd_finalise_conn(struct kib_conn *conn)
2183 {
2184         LASSERT (!in_interrupt());
2185         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
2186
2187         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
2188          * for connections that didn't get as far as being connected, because
2189          * rdma_disconnect() does this for free. */
2190         kiblnd_abort_receives(conn);
2191
2192         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
2193
2194         /* Complete all tx descs not waiting for sends to complete.
2195          * NB we should be safe from RDMA now that the QP has changed state */
2196
2197         kiblnd_abort_txs(conn, &conn->ibc_tx_noops);
2198         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
2199         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
2200         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
2201         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
2202
2203         kiblnd_handle_early_rxs(conn);
2204 }
2205
2206 static void
2207 kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
2208                            int error)
2209 {
2210         LIST_HEAD(zombies);
2211         unsigned long flags;
2212         enum lnet_msg_hstatus hstatus;
2213
2214         LASSERT(error != 0);
2215         LASSERT(!in_interrupt());
2216
2217         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2218
2219         if (active) {
2220                 LASSERT(peer_ni->ibp_connecting > 0);
2221                 peer_ni->ibp_connecting--;
2222         } else {
2223                 LASSERT (peer_ni->ibp_accepting > 0);
2224                 peer_ni->ibp_accepting--;
2225         }
2226
2227         if (kiblnd_peer_connecting(peer_ni)) {
2228                 /* another connection attempt under way... */
2229                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2230                                         flags);
2231                 return;
2232         }
2233
2234         peer_ni->ibp_reconnected = 0;
2235         if (list_empty(&peer_ni->ibp_conns)) {
2236                 /* Take peer_ni's blocked transmits to complete with error */
2237                 list_splice_init(&peer_ni->ibp_tx_queue, &zombies);
2238
2239                 if (kiblnd_peer_active(peer_ni))
2240                         kiblnd_unlink_peer_locked(peer_ni);
2241
2242                 peer_ni->ibp_error = error;
2243         } else {
2244                 /* Can't have blocked transmits if there are connections */
2245                 LASSERT(list_empty(&peer_ni->ibp_tx_queue));
2246         }
2247
2248         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2249
2250         kiblnd_peer_notify(peer_ni);
2251
2252         if (list_empty(&zombies))
2253                 return;
2254
2255         CNETERR("Deleting messages for %s: connection failed\n",
2256                 libcfs_nid2str(peer_ni->ibp_nid));
2257
2258         switch (error) {
2259         case -EHOSTUNREACH:
2260         case -ETIMEDOUT:
2261                 hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
2262                 break;
2263         case -ECONNREFUSED:
2264                 hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
2265                 break;
2266         default:
2267                 hstatus = LNET_MSG_STATUS_LOCAL_DROPPED;
2268                 break;
2269         }
2270
2271         kiblnd_txlist_done(&zombies, error, hstatus);
2272 }
2273
2274 static void
2275 kiblnd_connreq_done(struct kib_conn *conn, int status)
2276 {
2277         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2278         struct kib_tx *tx;
2279         LIST_HEAD(txs);
2280         unsigned long    flags;
2281         int              active;
2282
2283         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2284
2285         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
2286                libcfs_nid2str(peer_ni->ibp_nid), active,
2287                conn->ibc_version, status);
2288
2289         LASSERT (!in_interrupt());
2290         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2291                   peer_ni->ibp_connecting > 0) ||
2292                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2293                   peer_ni->ibp_accepting > 0));
2294
2295         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2296         conn->ibc_connvars = NULL;
2297
2298         if (status != 0) {
2299                 /* failed to establish connection */
2300                 kiblnd_peer_connect_failed(peer_ni, active, status);
2301                 kiblnd_finalise_conn(conn);
2302                 return;
2303         }
2304
2305         /* connection established */
2306         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2307
2308         conn->ibc_last_send = ktime_get();
2309         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2310         kiblnd_peer_alive(peer_ni);
2311
2312         /* Add conn to peer_ni's list and nuke any dangling conns from a different
2313          * peer_ni instance... */
2314         kiblnd_conn_addref(conn);       /* +1 ref for ibc_list */
2315         list_add(&conn->ibc_list, &peer_ni->ibp_conns);
2316         peer_ni->ibp_reconnected = 0;
2317         if (active)
2318                 peer_ni->ibp_connecting--;
2319         else
2320                 peer_ni->ibp_accepting--;
2321
2322         if (peer_ni->ibp_version == 0) {
2323                 peer_ni->ibp_version     = conn->ibc_version;
2324                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2325         }
2326
2327         if (peer_ni->ibp_version     != conn->ibc_version ||
2328             peer_ni->ibp_incarnation != conn->ibc_incarnation) {
2329                 kiblnd_close_stale_conns_locked(peer_ni, conn->ibc_version,
2330                                                 conn->ibc_incarnation);
2331                 peer_ni->ibp_version     = conn->ibc_version;
2332                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2333         }
2334
2335         /* grab pending txs while I have the lock */
2336         list_splice_init(&peer_ni->ibp_tx_queue, &txs);
2337
2338         if (!kiblnd_peer_active(peer_ni) ||        /* peer_ni has been deleted */
2339             conn->ibc_comms_error != 0) {       /* error has happened already */
2340
2341                 /* start to shut down connection */
2342                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2343                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2344
2345                 kiblnd_txlist_done(&txs, -ECONNABORTED,
2346                                    LNET_MSG_STATUS_LOCAL_ERROR);
2347
2348                 return;
2349         }
2350
2351         /* +1 ref for myself, this connection is visible to other threads
2352          * now, refcount of peer:ibp_conns can be released by connection
2353          * close from either a different thread, or the calling of
2354          * kiblnd_check_sends_locked() below. See bz21911 for details.
2355          */
2356         kiblnd_conn_addref(conn);
2357         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2358
2359         /* Schedule blocked txs
2360          * Note: if we are running with conns_per_peer > 1, these blocked
2361          * txs will all get scheduled to the first connection which gets
2362          * scheduled.  We won't be using round robin on this first batch.
2363          */
2364         spin_lock(&conn->ibc_lock);
2365         while ((tx = list_first_entry_or_null(&txs, struct kib_tx,
2366                                               tx_list)) != NULL) {
2367                 list_del(&tx->tx_list);
2368
2369                 kiblnd_queue_tx_locked(tx, conn);
2370         }
2371         kiblnd_check_sends_locked(conn);
2372         spin_unlock(&conn->ibc_lock);
2373
2374         /* schedule blocked rxs */
2375         kiblnd_handle_early_rxs(conn);
2376         kiblnd_conn_decref(conn);
2377 }
2378
2379 static void
2380 kiblnd_reject(struct rdma_cm_id *cmid, struct kib_rej *rej)
2381 {
2382         int          rc;
2383
2384 #ifdef HAVE_RDMA_REJECT_4ARGS
2385         rc = rdma_reject(cmid, rej, sizeof(*rej), IB_CM_REJ_CONSUMER_DEFINED);
2386 #else
2387         rc = rdma_reject(cmid, rej, sizeof(*rej));
2388 #endif
2389
2390         if (rc != 0)
2391                 CWARN("Error %d sending reject\n", rc);
2392 }
2393
2394 static int
2395 kiblnd_passive_connect(struct rdma_cm_id *cmid, void *priv, int priv_nob)
2396 {
2397         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
2398         struct kib_msg *reqmsg = priv;
2399         struct kib_msg *ackmsg;
2400         struct kib_dev *ibdev;
2401         struct kib_peer_ni *peer_ni;
2402         struct kib_peer_ni *peer2;
2403         struct kib_conn *conn;
2404         struct lnet_ni *ni = NULL;
2405         struct kib_net *net = NULL;
2406         lnet_nid_t nid;
2407         struct rdma_conn_param cp;
2408         struct kib_rej rej;
2409         int version = IBLND_MSG_VERSION;
2410         unsigned long flags;
2411         int rc;
2412         struct sockaddr_in *peer_addr;
2413
2414         LASSERT(!in_interrupt());
2415         /* cmid inherits 'context' from the corresponding listener id */
2416         ibdev = cmid->context;
2417         LASSERT(ibdev);
2418
2419         memset(&rej, 0, sizeof(rej));
2420         rej.ibr_magic                = IBLND_MSG_MAGIC;
2421         rej.ibr_why                  = IBLND_REJECT_FATAL;
2422         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2423
2424         peer_addr = (struct sockaddr_in *)&(cmid->route.addr.dst_addr);
2425         if (*kiblnd_tunables.kib_require_priv_port &&
2426             ntohs(peer_addr->sin_port) >= PROT_SOCK) {
2427                 __u32 ip = ntohl(peer_addr->sin_addr.s_addr);
2428                 CERROR("peer_ni's port (%pI4h:%hu) is not privileged\n",
2429                        &ip, ntohs(peer_addr->sin_port));
2430                 goto failed;
2431         }
2432
2433         if (priv_nob < offsetof(struct kib_msg, ibm_type)) {
2434                 CERROR("Short connection request\n");
2435                 goto failed;
2436         }
2437
2438         /* Future protocol version compatibility support!  If the
2439          * o2iblnd-specific protocol changes, or when LNET unifies
2440          * protocols over all LNDs, the initial connection will
2441          * negotiate a protocol version.  I trap this here to avoid
2442          * console errors; the reject tells the peer_ni which protocol I
2443          * speak. */
2444         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2445             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2446                 goto failed;
2447         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2448             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2449             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2450                 goto failed;
2451         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2452             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2453             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2454                 goto failed;
2455
2456         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2457         if (rc != 0) {
2458                 CERROR("Can't parse connection request: %d\n", rc);
2459                 goto failed;
2460         }
2461
2462         nid = reqmsg->ibm_srcnid;
2463         ni  = lnet_nid2ni_addref(reqmsg->ibm_dstnid);
2464
2465         if (ni != NULL) {
2466                 net = (struct kib_net *)ni->ni_data;
2467                 rej.ibr_incarnation = net->ibn_incarnation;
2468         }
2469
2470         if (ni == NULL ||                       /* no matching net */
2471             lnet_nid_to_nid4(&ni->ni_nid) !=
2472             reqmsg->ibm_dstnid ||               /* right NET, wrong NID! */
2473             net->ibn_dev != ibdev) {            /* wrong device */
2474                 CERROR("Can't accept conn from %s on %s (%s:%d:%pI4h): bad dst nid %s\n", libcfs_nid2str(nid),
2475                        ni ? libcfs_nidstr(&ni->ni_nid) : "NA",
2476                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2477                        &ibdev->ibd_ifip,
2478                        libcfs_nid2str(reqmsg->ibm_dstnid));
2479
2480                 goto failed;
2481         }
2482
2483         /* check time stamp as soon as possible */
2484         if (reqmsg->ibm_dststamp != 0 &&
2485             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2486                 CWARN("Stale connection request\n");
2487                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2488                 goto failed;
2489         }
2490
2491         /* I can accept peer_ni's version */
2492         version = reqmsg->ibm_version;
2493
2494         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2495                 CERROR("Unexpected connreq msg type: %x from %s\n",
2496                        reqmsg->ibm_type, libcfs_nid2str(nid));
2497                 goto failed;
2498         }
2499
2500         if (reqmsg->ibm_u.connparams.ibcp_queue_depth >
2501             kiblnd_msg_queue_size(version, ni)) {
2502                 CERROR("Can't accept conn from %s, queue depth too large:  %d (<=%d wanted)\n",
2503                        libcfs_nid2str(nid),
2504                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2505                        kiblnd_msg_queue_size(version, ni));
2506
2507                 if (version == IBLND_MSG_VERSION)
2508                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2509
2510                 goto failed;
2511         }
2512
2513         if (reqmsg->ibm_u.connparams.ibcp_max_frags >
2514             IBLND_MAX_RDMA_FRAGS) {
2515                 CWARN("Can't accept conn from %s (version %x): max_frags %d too large (%d wanted)\n",
2516                       libcfs_nid2str(nid), version,
2517                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2518                       IBLND_MAX_RDMA_FRAGS);
2519
2520                 if (version >= IBLND_MSG_VERSION)
2521                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2522
2523                 goto failed;
2524         } else if (reqmsg->ibm_u.connparams.ibcp_max_frags <
2525                    IBLND_MAX_RDMA_FRAGS &&
2526                    net->ibn_fmr_ps == NULL) {
2527                 CWARN("Can't accept conn from %s (version %x): max_frags %d incompatible without FMR pool (%d wanted)\n",
2528                       libcfs_nid2str(nid), version,
2529                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2530                       IBLND_MAX_RDMA_FRAGS);
2531
2532                 if (version == IBLND_MSG_VERSION)
2533                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2534
2535                 goto failed;
2536         }
2537
2538         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2539                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2540                        libcfs_nid2str(nid),
2541                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2542                        IBLND_MSG_SIZE);
2543                 goto failed;
2544         }
2545
2546         /* assume 'nid' is a new peer_ni; create  */
2547         rc = kiblnd_create_peer(ni, &peer_ni, nid);
2548         if (rc != 0) {
2549                 CERROR("Can't create peer_ni for %s\n", libcfs_nid2str(nid));
2550                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2551                 goto failed;
2552         }
2553
2554         /* We have validated the peer's parameters so use those */
2555         peer_ni->ibp_max_frags = reqmsg->ibm_u.connparams.ibcp_max_frags;
2556         peer_ni->ibp_queue_depth = reqmsg->ibm_u.connparams.ibcp_queue_depth;
2557
2558         write_lock_irqsave(g_lock, flags);
2559
2560         peer2 = kiblnd_find_peer_locked(ni, nid);
2561         if (peer2 != NULL) {
2562                 if (peer2->ibp_version == 0) {
2563                         peer2->ibp_version     = version;
2564                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2565                 }
2566
2567                 /* not the guy I've talked with */
2568                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2569                     peer2->ibp_version     != version) {
2570                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2571
2572                         if (kiblnd_peer_active(peer2)) {
2573                                 peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2574                                 peer2->ibp_version = version;
2575                         }
2576                         write_unlock_irqrestore(g_lock, flags);
2577
2578                         CWARN("Conn stale %s version %x/%x incarnation %llu/%llu\n",
2579                               libcfs_nid2str(nid), peer2->ibp_version, version,
2580                               peer2->ibp_incarnation, reqmsg->ibm_srcstamp);
2581
2582                         kiblnd_peer_decref(peer_ni);
2583                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2584                         goto failed;
2585                 }
2586
2587                 /* Tie-break connection race in favour of the higher NID.
2588                  * If we keep running into a race condition multiple times,
2589                  * we have to assume that the connection attempt with the
2590                  * higher NID is stuck in a connecting state and will never
2591                  * recover.  As such, we pass through this if-block and let
2592                  * the lower NID connection win so we can move forward.
2593                  */
2594                 if (peer2->ibp_connecting != 0 &&
2595                     nid < lnet_nid_to_nid4(&ni->ni_nid) &&
2596                     peer2->ibp_races < MAX_CONN_RACES_BEFORE_ABORT) {
2597                         peer2->ibp_races++;
2598                         write_unlock_irqrestore(g_lock, flags);
2599
2600                         CDEBUG(D_NET, "Conn race %s\n",
2601                                libcfs_nid2str(peer2->ibp_nid));
2602
2603                         kiblnd_peer_decref(peer_ni);
2604                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2605                         goto failed;
2606                 }
2607                 if (peer2->ibp_races >= MAX_CONN_RACES_BEFORE_ABORT)
2608                         CNETERR("Conn race %s: unresolved after %d attempts, letting lower NID win\n",
2609                                 libcfs_nid2str(peer2->ibp_nid),
2610                                 MAX_CONN_RACES_BEFORE_ABORT);
2611                 /*
2612                  * passive connection is allowed even this peer_ni is waiting for
2613                  * reconnection.
2614                  */
2615                 peer2->ibp_reconnecting = 0;
2616                 peer2->ibp_races = 0;
2617                 peer2->ibp_accepting++;
2618                 kiblnd_peer_addref(peer2);
2619
2620                 /* Race with kiblnd_launch_tx (active connect) to create peer_ni
2621                  * so copy validated parameters since we now know what the
2622                  * peer_ni's limits are */
2623                 peer2->ibp_max_frags = peer_ni->ibp_max_frags;
2624                 peer2->ibp_queue_depth = peer_ni->ibp_queue_depth;
2625
2626                 write_unlock_irqrestore(g_lock, flags);
2627                 kiblnd_peer_decref(peer_ni);
2628                 peer_ni = peer2;
2629         } else {
2630                 /* Brand new peer_ni */
2631                 LASSERT(peer_ni->ibp_accepting == 0);
2632                 LASSERT(peer_ni->ibp_version == 0 &&
2633                         peer_ni->ibp_incarnation == 0);
2634
2635                 peer_ni->ibp_accepting   = 1;
2636                 peer_ni->ibp_version     = version;
2637                 peer_ni->ibp_incarnation = reqmsg->ibm_srcstamp;
2638
2639                 /* I have a ref on ni that prevents it being shutdown */
2640                 LASSERT(net->ibn_shutdown == 0);
2641
2642                 kiblnd_peer_addref(peer_ni);
2643                 hash_add(kiblnd_data.kib_peers, &peer_ni->ibp_list, nid);
2644
2645                 write_unlock_irqrestore(g_lock, flags);
2646         }
2647
2648         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_PASSIVE_WAIT,
2649                                   version);
2650         if (!conn) {
2651                 kiblnd_peer_connect_failed(peer_ni, 0, -ENOMEM);
2652                 kiblnd_peer_decref(peer_ni);
2653                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2654                 goto failed;
2655         }
2656
2657         /* conn now "owns" cmid, so I return success from here on to ensure the
2658          * CM callback doesn't destroy cmid.
2659          */
2660         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2661         conn->ibc_credits          = conn->ibc_queue_depth;
2662         conn->ibc_reserved_credits = conn->ibc_queue_depth;
2663         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2664                 IBLND_OOB_MSGS(version) <= IBLND_RX_MSGS(conn));
2665
2666         ackmsg = &conn->ibc_connvars->cv_msg;
2667         memset(ackmsg, 0, sizeof(*ackmsg));
2668
2669         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2670                         sizeof(ackmsg->ibm_u.connparams));
2671         ackmsg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2672         ackmsg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2673         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2674
2675         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2676
2677         memset(&cp, 0, sizeof(cp));
2678         cp.private_data        = ackmsg;
2679         cp.private_data_len    = ackmsg->ibm_nob;
2680         cp.responder_resources = 0;            /* No atomic ops or RDMA reads */
2681         cp.initiator_depth     = 0;
2682         cp.flow_control        = 1;
2683         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2684         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2685
2686         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2687
2688         rc = rdma_accept(cmid, &cp);
2689         if (rc != 0) {
2690                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2691                 rej.ibr_version = version;
2692                 rej.ibr_why     = IBLND_REJECT_FATAL;
2693
2694                 kiblnd_reject(cmid, &rej);
2695                 kiblnd_connreq_done(conn, rc);
2696                 kiblnd_conn_decref(conn);
2697         }
2698
2699         lnet_ni_decref(ni);
2700         return 0;
2701
2702  failed:
2703         if (ni != NULL) {
2704                 rej.ibr_cp.ibcp_queue_depth =
2705                         kiblnd_msg_queue_size(version, ni);
2706                 rej.ibr_cp.ibcp_max_frags   = IBLND_MAX_RDMA_FRAGS;
2707                 lnet_ni_decref(ni);
2708         }
2709
2710         rej.ibr_version = version;
2711         kiblnd_reject(cmid, &rej);
2712
2713         return -ECONNREFUSED;
2714 }
2715
2716 static void
2717 kiblnd_check_reconnect(struct kib_conn *conn, int version,
2718                        u64 incarnation, int why, struct kib_connparams *cp)
2719 {
2720         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
2721         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2722         char            *reason;
2723         int              msg_size = IBLND_MSG_SIZE;
2724         int              frag_num = -1;
2725         int              queue_dep = -1;
2726         bool             reconnect;
2727         unsigned long    flags;
2728
2729         LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2730         LASSERT(peer_ni->ibp_connecting > 0);   /* 'conn' at least */
2731
2732         if (cp) {
2733                 msg_size        = cp->ibcp_max_msg_size;
2734                 frag_num        = cp->ibcp_max_frags;
2735                 queue_dep       = cp->ibcp_queue_depth;
2736         }
2737
2738         write_lock_irqsave(glock, flags);
2739         /* retry connection if it's still needed and no other connection
2740          * attempts (active or passive) are in progress
2741          * NB: reconnect is still needed even when ibp_tx_queue is
2742          * empty if ibp_version != version because reconnect may be
2743          * initiated.
2744          */
2745         reconnect = (!list_empty(&peer_ni->ibp_tx_queue) ||
2746                      peer_ni->ibp_version != version) &&
2747                     peer_ni->ibp_connecting &&
2748                     peer_ni->ibp_accepting == 0;
2749         if (!reconnect) {
2750                 reason = "no need";
2751                 goto out;
2752         }
2753
2754         switch (why) {
2755         default:
2756                 reason = "Unknown";
2757                 break;
2758
2759         case IBLND_REJECT_RDMA_FRAGS: {
2760                 struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2761
2762                 if (!cp) {
2763                         reason = "can't negotiate max frags";
2764                         goto out;
2765                 }
2766                 tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2767 #ifdef HAVE_IB_GET_DMA_MR
2768                 /*
2769                  * This check only makes sense if the kernel supports global
2770                  * memory registration. Otherwise, map_on_demand will never == 0
2771                  */
2772                 if (!tunables->lnd_map_on_demand) {
2773                         reason = "map_on_demand must be enabled";
2774                         goto out;
2775                 }
2776 #endif
2777                 if (conn->ibc_max_frags <= frag_num) {
2778                         reason = "unsupported max frags";
2779                         goto out;
2780                 }
2781
2782                 peer_ni->ibp_max_frags = frag_num;
2783                 reason = "rdma fragments";
2784                 break;
2785         }
2786         case IBLND_REJECT_MSG_QUEUE_SIZE:
2787                 if (!cp) {
2788                         reason = "can't negotiate queue depth";
2789                         goto out;
2790                 }
2791                 if (conn->ibc_queue_depth <= queue_dep) {
2792                         reason = "unsupported queue depth";
2793                         goto out;
2794                 }
2795
2796                 peer_ni->ibp_queue_depth = queue_dep;
2797                 reason = "queue depth";
2798                 break;
2799
2800         case IBLND_REJECT_CONN_STALE:
2801                 reason = "stale";
2802                 break;
2803
2804         case IBLND_REJECT_CONN_RACE:
2805                 reason = "conn race";
2806                 break;
2807
2808         case IBLND_REJECT_CONN_UNCOMPAT:
2809                 reason = "version negotiation";
2810                 break;
2811         }
2812
2813         conn->ibc_reconnect = 1;
2814         peer_ni->ibp_reconnecting++;
2815         peer_ni->ibp_version = version;
2816         if (incarnation != 0)
2817                 peer_ni->ibp_incarnation = incarnation;
2818  out:
2819         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2820
2821         CNETERR("%s: %s (%s), %x, %x, msg_size: %d, queue_depth: %d/%d, max_frags: %d/%d\n",
2822                 libcfs_nid2str(peer_ni->ibp_nid),
2823                 reconnect ? "reconnect" : "don't reconnect",
2824                 reason, IBLND_MSG_VERSION, version, msg_size,
2825                 conn->ibc_queue_depth, queue_dep,
2826                 conn->ibc_max_frags, frag_num);
2827         /*
2828          * if conn::ibc_reconnect is TRUE, connd will reconnect to the peer_ni
2829          * while destroying the zombie
2830          */
2831 }
2832
2833 static void
2834 kiblnd_rejected(struct kib_conn *conn, int reason, void *priv, int priv_nob)
2835 {
2836         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2837         int status = -ECONNREFUSED;
2838
2839         LASSERT (!in_interrupt());
2840         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2841
2842         switch (reason) {
2843         case IB_CM_REJ_STALE_CONN:
2844                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2845                                        IBLND_REJECT_CONN_STALE, NULL);
2846                 break;
2847
2848         case IB_CM_REJ_INVALID_SERVICE_ID:
2849                 status = -EHOSTUNREACH;
2850                 CNETERR("%s rejected: no listener at %d\n",
2851                         libcfs_nid2str(peer_ni->ibp_nid),
2852                         *kiblnd_tunables.kib_service);
2853                 break;
2854
2855         case IB_CM_REJ_CONSUMER_DEFINED:
2856                 if (priv_nob >= offsetof(struct kib_rej, ibr_padding)) {
2857                         struct kib_rej *rej = priv;
2858                         struct kib_connparams *cp = NULL;
2859                         bool flip = false;
2860                         __u64 incarnation = -1;
2861
2862                         /* NB. default incarnation is -1 because:
2863                          * a) V1 will ignore dst incarnation in connreq.
2864                          * b) V2 will provide incarnation while rejecting me,
2865                          *    -1 will be overwrote.
2866                          *
2867                          * if I try to connect to a V1 peer_ni with V2 protocol,
2868                          * it rejected me then upgrade to V2, I have no idea
2869                          * about the upgrading and try to reconnect with V1,
2870                          * in this case upgraded V2 can find out I'm trying to
2871                          * talk to the old guy and reject me(incarnation is -1).
2872                          */
2873
2874                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2875                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2876                                 __swab32s(&rej->ibr_magic);
2877                                 __swab16s(&rej->ibr_version);
2878                                 flip = true;
2879                         }
2880
2881                         if (priv_nob >= sizeof(struct kib_rej) &&
2882                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2883                                 /* priv_nob is always 148 in current version
2884                                  * of OFED, so we still need to check version.
2885                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE)
2886                                  */
2887                                 cp = &rej->ibr_cp;
2888
2889                                 if (flip) {
2890                                         __swab64s(&rej->ibr_incarnation);
2891                                         __swab16s(&cp->ibcp_queue_depth);
2892                                         __swab16s(&cp->ibcp_max_frags);
2893                                         __swab32s(&cp->ibcp_max_msg_size);
2894                                 }
2895
2896                                 incarnation = rej->ibr_incarnation;
2897                         }
2898
2899                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2900                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2901                                 CERROR("%s rejected: consumer defined fatal error\n",
2902                                        libcfs_nid2str(peer_ni->ibp_nid));
2903                                 break;
2904                         }
2905
2906                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2907                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2908                                 CERROR("%s rejected: o2iblnd version %x error\n",
2909                                        libcfs_nid2str(peer_ni->ibp_nid),
2910                                        rej->ibr_version);
2911                                 break;
2912                         }
2913
2914                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2915                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2916                                 CDEBUG(D_NET, "rejected by old version peer_ni %s: %x\n",
2917                                        libcfs_nid2str(peer_ni->ibp_nid),
2918                                        rej->ibr_version);
2919
2920                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2921                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2922                         }
2923
2924                         switch (rej->ibr_why) {
2925                         case IBLND_REJECT_CONN_RACE:
2926                         case IBLND_REJECT_CONN_STALE:
2927                         case IBLND_REJECT_CONN_UNCOMPAT:
2928                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2929                         case IBLND_REJECT_RDMA_FRAGS:
2930                                 kiblnd_check_reconnect(conn, rej->ibr_version,
2931                                                        incarnation,
2932                                                        rej->ibr_why, cp);
2933                                 break;
2934
2935                         case IBLND_REJECT_NO_RESOURCES:
2936                                 CERROR("%s rejected: o2iblnd no resources\n",
2937                                        libcfs_nid2str(peer_ni->ibp_nid));
2938                                 break;
2939
2940                         case IBLND_REJECT_FATAL:
2941                                 CERROR("%s rejected: o2iblnd fatal error\n",
2942                                        libcfs_nid2str(peer_ni->ibp_nid));
2943                                 break;
2944
2945                         default:
2946                                 CERROR("%s rejected: o2iblnd reason %d\n",
2947                                        libcfs_nid2str(peer_ni->ibp_nid),
2948                                        rej->ibr_why);
2949                                 break;
2950                         }
2951                         break;
2952                 }
2953                 /* fall through */
2954         default:
2955                 CNETERR("%s rejected: reason %d, size %d\n",
2956                         libcfs_nid2str(peer_ni->ibp_nid), reason, priv_nob);
2957                 break;
2958         }
2959
2960         kiblnd_connreq_done(conn, status);
2961 }
2962
2963 static void
2964 kiblnd_check_connreply(struct kib_conn *conn, void *priv, int priv_nob)
2965 {
2966         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2967         struct lnet_ni *ni = peer_ni->ibp_ni;
2968         struct kib_net *net = ni->ni_data;
2969         struct kib_msg *msg = priv;
2970         int            ver  = conn->ibc_version;
2971         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
2972         unsigned long  flags;
2973
2974         LASSERT (net != NULL);
2975
2976         if (rc != 0) {
2977                 CERROR("Can't unpack connack from %s: %d\n",
2978                        libcfs_nid2str(peer_ni->ibp_nid), rc);
2979                 goto failed;
2980         }
2981
2982         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2983                 CERROR("Unexpected message %d from %s\n",
2984                        msg->ibm_type, libcfs_nid2str(peer_ni->ibp_nid));
2985                 rc = -EPROTO;
2986                 goto failed;
2987         }
2988
2989         if (ver != msg->ibm_version) {
2990                 CERROR("%s replied version %x is different with "
2991                        "requested version %x\n",
2992                        libcfs_nid2str(peer_ni->ibp_nid), msg->ibm_version, ver);
2993                 rc = -EPROTO;
2994                 goto failed;
2995         }
2996
2997         if (msg->ibm_u.connparams.ibcp_queue_depth >
2998             conn->ibc_queue_depth) {
2999                 CERROR("%s has incompatible queue depth %d (<=%d wanted)\n",
3000                        libcfs_nid2str(peer_ni->ibp_nid),
3001                        msg->ibm_u.connparams.ibcp_queue_depth,
3002                        conn->ibc_queue_depth);
3003                 rc = -EPROTO;
3004                 goto failed;
3005         }
3006
3007         if (msg->ibm_u.connparams.ibcp_max_frags >
3008             conn->ibc_max_frags) {
3009                 CERROR("%s has incompatible max_frags %d (<=%d wanted)\n",
3010                        libcfs_nid2str(peer_ni->ibp_nid),
3011                        msg->ibm_u.connparams.ibcp_max_frags,
3012                        conn->ibc_max_frags);
3013                 rc = -EPROTO;
3014                 goto failed;
3015         }
3016
3017         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
3018                 CERROR("%s max message size %d too big (%d max)\n",
3019                        libcfs_nid2str(peer_ni->ibp_nid),
3020                        msg->ibm_u.connparams.ibcp_max_msg_size,
3021                        IBLND_MSG_SIZE);
3022                 rc = -EPROTO;
3023                 goto failed;
3024         }
3025
3026         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3027         if (msg->ibm_dstnid == lnet_nid_to_nid4(&ni->ni_nid) &&
3028             msg->ibm_dststamp == net->ibn_incarnation)
3029                 rc = 0;
3030         else
3031                 rc = -ESTALE;
3032         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3033
3034         if (rc != 0) {
3035                 CERROR("Bad connection reply from %s, rc = %d, "
3036                        "version: %x max_frags: %d\n",
3037                        libcfs_nid2str(peer_ni->ibp_nid), rc,
3038                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
3039                 goto failed;
3040         }
3041
3042         conn->ibc_incarnation      = msg->ibm_srcstamp;
3043         conn->ibc_credits          = msg->ibm_u.connparams.ibcp_queue_depth;
3044         conn->ibc_reserved_credits = msg->ibm_u.connparams.ibcp_queue_depth;
3045         conn->ibc_queue_depth      = msg->ibm_u.connparams.ibcp_queue_depth;
3046         conn->ibc_max_frags        = msg->ibm_u.connparams.ibcp_max_frags;
3047         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
3048                 IBLND_OOB_MSGS(ver) <= IBLND_RX_MSGS(conn));
3049
3050         kiblnd_connreq_done(conn, 0);
3051         return;
3052
3053  failed:
3054         /* NB My QP has already established itself, so I handle anything going
3055          * wrong here by setting ibc_comms_error.
3056          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
3057          * immediately tears it down. */
3058
3059         LASSERT (rc != 0);
3060         conn->ibc_comms_error = rc;
3061         kiblnd_connreq_done(conn, 0);
3062 }
3063
3064 static int
3065 kiblnd_active_connect(struct rdma_cm_id *cmid)
3066 {
3067         struct kib_peer_ni *peer_ni = cmid->context;
3068         struct kib_conn *conn;
3069         struct kib_msg *msg;
3070         struct rdma_conn_param cp;
3071         int                      version;
3072         __u64                    incarnation;
3073         unsigned long            flags;
3074         int                      rc;
3075
3076         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3077
3078         incarnation = peer_ni->ibp_incarnation;
3079         version     = (peer_ni->ibp_version == 0) ? IBLND_MSG_VERSION :
3080                                                  peer_ni->ibp_version;
3081
3082         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3083
3084         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_ACTIVE_CONNECT,
3085                                   version);
3086         if (conn == NULL) {
3087                 kiblnd_peer_connect_failed(peer_ni, 1, -ENOMEM);
3088                 kiblnd_peer_decref(peer_ni); /* lose cmid's ref */
3089                 return -ENOMEM;
3090         }
3091
3092         /* conn "owns" cmid now, so I return success from here on to ensure the
3093          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
3094          * on peer_ni */
3095
3096         msg = &conn->ibc_connvars->cv_msg;
3097
3098         memset(msg, 0, sizeof(*msg));
3099         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
3100         msg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
3101         msg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
3102         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
3103
3104         kiblnd_pack_msg(peer_ni->ibp_ni, msg, version,
3105                         0, peer_ni->ibp_nid, incarnation);
3106
3107         memset(&cp, 0, sizeof(cp));
3108         cp.private_data        = msg;
3109         cp.private_data_len    = msg->ibm_nob;
3110         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
3111         cp.initiator_depth     = 0;
3112         cp.flow_control        = 1;
3113         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
3114         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
3115
3116         LASSERT(cmid->context == (void *)conn);
3117         LASSERT(conn->ibc_cmid == cmid);
3118         rc = rdma_connect_locked(cmid, &cp);
3119         if (rc != 0) {
3120                 CERROR("Can't connect to %s: %d\n",
3121                        libcfs_nid2str(peer_ni->ibp_nid), rc);
3122                 kiblnd_connreq_done(conn, rc);
3123                 kiblnd_conn_decref(conn);
3124         }
3125
3126         return 0;
3127 }
3128
3129 int
3130 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
3131 {
3132         struct kib_peer_ni *peer_ni;
3133         struct kib_conn *conn;
3134         int rc;
3135
3136         switch (event->event) {
3137         default:
3138                 CERROR("Unexpected event: %d, status: %d\n",
3139                        event->event, event->status);
3140                 LBUG();
3141
3142         case RDMA_CM_EVENT_CONNECT_REQUEST:
3143                 /* destroy cmid on failure */
3144                 rc = kiblnd_passive_connect(cmid,
3145                                             (void *)KIBLND_CONN_PARAM(event),
3146                                             KIBLND_CONN_PARAM_LEN(event));
3147                 CDEBUG(D_NET, "connreq: %d\n", rc);
3148                 return rc;
3149
3150         case RDMA_CM_EVENT_ADDR_ERROR:
3151                 peer_ni = cmid->context;
3152                 CNETERR("%s: ADDR ERROR %d\n",
3153                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3154                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3155                 kiblnd_peer_decref(peer_ni);
3156                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
3157
3158         case RDMA_CM_EVENT_ADDR_RESOLVED:
3159                 peer_ni = cmid->context;
3160
3161                 CDEBUG(D_NET,"%s Addr resolved: %d\n",
3162                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3163
3164                 if (event->status != 0) {
3165                         CNETERR("Can't resolve address for %s: %d\n",
3166                                 libcfs_nid2str(peer_ni->ibp_nid), event->status);
3167                         rc = event->status;
3168                 } else {
3169                         rc = rdma_resolve_route(
3170                                 cmid, kiblnd_timeout() * 1000);
3171                         if (rc == 0) {
3172                                 struct kib_net *net = peer_ni->ibp_ni->ni_data;
3173                                 struct kib_dev *dev = net->ibn_dev;
3174
3175                                 CDEBUG(D_NET, "%s: connection bound to "\
3176                                        "%s:%pI4h:%s\n",
3177                                        libcfs_nid2str(peer_ni->ibp_nid),
3178                                        dev->ibd_ifname,
3179                                        &dev->ibd_ifip, cmid->device->name);
3180
3181                                 return 0;
3182                         }
3183
3184                         /* Can't initiate route resolution */
3185                         CERROR("Can't resolve route for %s: %d\n",
3186                                libcfs_nid2str(peer_ni->ibp_nid), rc);
3187                 }
3188                 kiblnd_peer_connect_failed(peer_ni, 1, rc);
3189                 kiblnd_peer_decref(peer_ni);
3190                 return rc;                      /* rc != 0 destroys cmid */
3191
3192         case RDMA_CM_EVENT_ROUTE_ERROR:
3193                 peer_ni = cmid->context;
3194                 CNETERR("%s: ROUTE ERROR %d\n",
3195                         libcfs_nid2str(peer_ni->ibp_nid), event->status);
3196                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3197                 kiblnd_peer_decref(peer_ni);
3198                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
3199
3200         case RDMA_CM_EVENT_ROUTE_RESOLVED:
3201                 peer_ni = cmid->context;
3202                 CDEBUG(D_NET,"%s Route resolved: %d\n",
3203                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3204
3205                 if (event->status == 0)
3206                         return kiblnd_active_connect(cmid);
3207
3208                 CNETERR("Can't resolve route for %s: %d\n",
3209                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3210                 kiblnd_peer_connect_failed(peer_ni, 1, event->status);
3211                 kiblnd_peer_decref(peer_ni);
3212                 return event->status;           /* rc != 0 destroys cmid */
3213
3214         case RDMA_CM_EVENT_UNREACHABLE:
3215                 conn = cmid->context;
3216                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3217                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3218                 CNETERR("%s: UNREACHABLE %d\n",
3219                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3220                 kiblnd_connreq_done(conn, -ENETDOWN);
3221                 kiblnd_conn_decref(conn);
3222                 return 0;
3223
3224         case RDMA_CM_EVENT_CONNECT_ERROR:
3225                 conn = cmid->context;
3226                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3227                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3228                 CNETERR("%s: CONNECT ERROR %d\n",
3229                         libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3230                 kiblnd_connreq_done(conn, -ENOTCONN);
3231                 kiblnd_conn_decref(conn);
3232                 return 0;
3233
3234         case RDMA_CM_EVENT_REJECTED:
3235                 conn = cmid->context;
3236                 switch (conn->ibc_state) {
3237                 default:
3238                         LBUG();
3239
3240                 case IBLND_CONN_PASSIVE_WAIT:
3241                         CERROR ("%s: REJECTED %d\n",
3242                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
3243                                 event->status);
3244                         kiblnd_connreq_done(conn, -ECONNRESET);
3245                         break;
3246
3247                 case IBLND_CONN_ACTIVE_CONNECT:
3248                         kiblnd_rejected(conn, event->status,
3249                                         (void *)KIBLND_CONN_PARAM(event),
3250                                         KIBLND_CONN_PARAM_LEN(event));
3251                         break;
3252                 }
3253                 kiblnd_conn_decref(conn);
3254                 return 0;
3255
3256         case RDMA_CM_EVENT_ESTABLISHED:
3257                 conn = cmid->context;
3258                 switch (conn->ibc_state) {
3259                 default:
3260                         LBUG();
3261
3262                 case IBLND_CONN_PASSIVE_WAIT:
3263                         CDEBUG(D_NET, "ESTABLISHED (passive): %s\n",
3264                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3265                         kiblnd_connreq_done(conn, 0);
3266                         break;
3267
3268                 case IBLND_CONN_ACTIVE_CONNECT:
3269                         CDEBUG(D_NET, "ESTABLISHED(active): %s\n",
3270                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3271                         kiblnd_check_connreply(conn,
3272                                                (void *)KIBLND_CONN_PARAM(event),
3273                                                KIBLND_CONN_PARAM_LEN(event));
3274                         break;
3275                 }
3276                 /* net keeps its ref on conn! */
3277                 return 0;
3278
3279         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
3280                 CDEBUG(D_NET, "Ignore TIMEWAIT_EXIT event\n");
3281                 return 0;
3282
3283         case RDMA_CM_EVENT_DISCONNECTED:
3284                 conn = cmid->context;
3285                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
3286                         CERROR("%s DISCONNECTED\n",
3287                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3288                         kiblnd_connreq_done(conn, -ECONNRESET);
3289                 } else {
3290                         kiblnd_close_conn(conn, 0);
3291                 }
3292                 kiblnd_conn_decref(conn);
3293                 cmid->context = NULL;
3294                 return 0;
3295
3296         case RDMA_CM_EVENT_DEVICE_REMOVAL:
3297                 LCONSOLE_ERROR_MSG(0x131,
3298                                    "Received notification of device removal\n"
3299                                    "Please shutdown LNET to allow this to proceed\n");
3300                 /* Can't remove network from underneath LNET for now, so I have
3301                  * to ignore this */
3302                 return 0;
3303
3304         case RDMA_CM_EVENT_ADDR_CHANGE:
3305                 LCONSOLE_INFO("Physical link changed (eg hca/port)\n");
3306                 return 0;
3307         }
3308 }
3309
3310 static int
3311 kiblnd_check_txs_locked(struct kib_conn *conn, struct list_head *txs)
3312 {
3313         struct kib_tx *tx;
3314
3315         list_for_each_entry(tx, txs, tx_list) {
3316                 if (txs != &conn->ibc_active_txs) {
3317                         LASSERT(tx->tx_queued);
3318                 } else {
3319                         LASSERT(!tx->tx_queued);
3320                         LASSERT(tx->tx_waiting || tx->tx_sending != 0);
3321                 }
3322
3323                 if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3324                         CERROR("Timed out tx: %s(WSQ:%d%d%d), %lld seconds\n",
3325                                kiblnd_queue2str(conn, txs),
3326                                tx->tx_waiting, tx->tx_sending, tx->tx_queued,
3327                                kiblnd_timeout() +
3328                                ktime_ms_delta(ktime_get(),
3329                                               tx->tx_deadline) / MSEC_PER_SEC);
3330                         return 1;
3331                 }
3332         }
3333
3334         return 0;
3335 }
3336
3337 static int
3338 kiblnd_conn_timed_out_locked(struct kib_conn *conn)
3339 {
3340         return  kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue) ||
3341                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_noops) ||
3342                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_rsrvd) ||
3343                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_nocred) ||
3344                 kiblnd_check_txs_locked(conn, &conn->ibc_active_txs);
3345 }
3346
3347 static void
3348 kiblnd_check_conns (int idx)
3349 {
3350         LIST_HEAD(closes);
3351         LIST_HEAD(checksends);
3352         LIST_HEAD(timedout_txs);
3353         struct hlist_head *peers = &kiblnd_data.kib_peers[idx];
3354         struct kib_peer_ni *peer_ni;
3355         struct kib_conn *conn;
3356         struct kib_tx *tx, *tx_tmp;
3357         unsigned long flags;
3358
3359         /* NB. We expect to have a look at all the peers and not find any
3360          * RDMAs to time out, so we just use a shared lock while we
3361          * take a look...
3362          */
3363         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3364
3365         hlist_for_each_entry(peer_ni, peers, ibp_list) {
3366                 /* Check tx_deadline */
3367                 list_for_each_entry_safe(tx, tx_tmp, &peer_ni->ibp_tx_queue, tx_list) {
3368                         if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3369                                 CWARN("Timed out tx for %s: %lld seconds\n",
3370                                       libcfs_nid2str(peer_ni->ibp_nid),
3371                                       ktime_ms_delta(ktime_get(),
3372                                                      tx->tx_deadline) / MSEC_PER_SEC);
3373                                 list_move(&tx->tx_list, &timedout_txs);
3374                         }
3375                 }
3376
3377                 list_for_each_entry(conn, &peer_ni->ibp_conns, ibc_list) {
3378                         int timedout;
3379                         int sendnoop;
3380
3381                         LASSERT(conn->ibc_state == IBLND_CONN_ESTABLISHED);
3382
3383                         spin_lock(&conn->ibc_lock);
3384
3385                         sendnoop = kiblnd_need_noop(conn);
3386                         timedout = kiblnd_conn_timed_out_locked(conn);
3387                         if (!sendnoop && !timedout) {
3388                                 spin_unlock(&conn->ibc_lock);
3389                                 continue;
3390                         }
3391
3392                         if (timedout) {
3393                                 CERROR("Timed out RDMA with %s (%lld): c: %u, oc: %u, rc: %u\n",
3394                                        libcfs_nid2str(peer_ni->ibp_nid),
3395                                        ktime_get_seconds()
3396                                        - peer_ni->ibp_last_alive,
3397                                        conn->ibc_credits,
3398                                        conn->ibc_outstanding_credits,
3399                                        conn->ibc_reserved_credits);
3400                                 list_add(&conn->ibc_connd_list, &closes);
3401                         } else {
3402                                 list_add(&conn->ibc_connd_list, &checksends);
3403                         }
3404                         /* +ref for 'closes' or 'checksends' */
3405                         kiblnd_conn_addref(conn);
3406
3407                         spin_unlock(&conn->ibc_lock);
3408                 }
3409         }
3410
3411         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3412
3413         if (!list_empty(&timedout_txs))
3414                 kiblnd_txlist_done(&timedout_txs, -ETIMEDOUT,
3415                                    LNET_MSG_STATUS_NETWORK_TIMEOUT);
3416
3417         /* Handle timeout by closing the whole
3418          * connection. We can only be sure RDMA activity
3419          * has ceased once the QP has been modified.
3420          */
3421         while ((conn = list_first_entry_or_null(&closes,
3422                                                 struct kib_conn,
3423                                                 ibc_connd_list)) != NULL) {
3424                 list_del(&conn->ibc_connd_list);
3425                 kiblnd_close_conn(conn, -ETIMEDOUT);
3426                 kiblnd_conn_decref(conn);
3427         }
3428
3429         /* In case we have enough credits to return via a
3430          * NOOP, but there were no non-blocking tx descs
3431          * free to do it last time...
3432          */
3433         while ((conn = list_first_entry_or_null(&checksends,
3434                                                 struct kib_conn,
3435                                                 ibc_connd_list)) != NULL) {
3436                 list_del(&conn->ibc_connd_list);
3437
3438                 spin_lock(&conn->ibc_lock);
3439                 kiblnd_check_sends_locked(conn);
3440                 spin_unlock(&conn->ibc_lock);
3441
3442                 kiblnd_conn_decref(conn);
3443         }
3444 }
3445
3446 static void
3447 kiblnd_disconnect_conn(struct kib_conn *conn)
3448 {
3449         LASSERT (!in_interrupt());
3450         LASSERT (current == kiblnd_data.kib_connd);
3451         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
3452
3453         rdma_disconnect(conn->ibc_cmid);
3454         kiblnd_finalise_conn(conn);
3455
3456         kiblnd_peer_notify(conn->ibc_peer);
3457 }
3458
3459 /*
3460  * High-water for reconnection to the same peer_ni, reconnection attempt should
3461  * be delayed after trying more than KIB_RECONN_HIGH_RACE.
3462  */
3463 #define KIB_RECONN_HIGH_RACE    10
3464 /*
3465  * Allow connd to take a break and handle other things after consecutive
3466  * reconnection attemps.
3467  */
3468 #define KIB_RECONN_BREAK        100
3469
3470 int
3471 kiblnd_connd (void *arg)
3472 {
3473         spinlock_t *lock = &kiblnd_data.kib_connd_lock;
3474         wait_queue_entry_t wait;
3475         unsigned long flags;
3476         struct kib_conn *conn;
3477         int timeout;
3478         int i;
3479         bool dropped_lock;
3480         int peer_index = 0;
3481         unsigned long deadline = jiffies;
3482
3483         init_wait(&wait);
3484         kiblnd_data.kib_connd = current;
3485
3486         spin_lock_irqsave(lock, flags);
3487
3488         while (!kiblnd_data.kib_shutdown) {
3489                 int reconn = 0;
3490
3491                 dropped_lock = false;
3492
3493                 conn = list_first_entry_or_null(&kiblnd_data.kib_connd_zombies,
3494                                                 struct kib_conn, ibc_list);
3495                 if (conn) {
3496                         struct kib_peer_ni *peer_ni = NULL;
3497
3498                         list_del(&conn->ibc_list);
3499                         if (conn->ibc_reconnect) {
3500                                 peer_ni = conn->ibc_peer;
3501                                 kiblnd_peer_addref(peer_ni);
3502                         }
3503
3504                         spin_unlock_irqrestore(lock, flags);
3505                         dropped_lock = true;
3506
3507                         kiblnd_destroy_conn(conn);
3508
3509                         spin_lock_irqsave(lock, flags);
3510                         if (!peer_ni) {
3511                                 LIBCFS_FREE(conn, sizeof(*conn));
3512                                 continue;
3513                         }
3514
3515                         conn->ibc_peer = peer_ni;
3516                         if (peer_ni->ibp_reconnected < KIB_RECONN_HIGH_RACE)
3517                                 list_add_tail(&conn->ibc_list,
3518                                               &kiblnd_data.kib_reconn_list);
3519                         else
3520                                 list_add_tail(&conn->ibc_list,
3521                                               &kiblnd_data.kib_reconn_wait);
3522                 }
3523
3524                 conn = list_first_entry_or_null(&kiblnd_data.kib_connd_conns,
3525                                                 struct kib_conn, ibc_list);
3526                 if (conn) {
3527                         int wait;
3528
3529                         list_del(&conn->ibc_list);
3530
3531                         spin_unlock_irqrestore(lock, flags);
3532                         dropped_lock = true;
3533
3534                         kiblnd_disconnect_conn(conn);
3535                         wait = conn->ibc_waits;
3536                         if (wait == 0) /* keep ref for connd_wait, see below */
3537                                 kiblnd_conn_decref(conn);
3538
3539                         spin_lock_irqsave(lock, flags);
3540
3541                         if (wait)
3542                                 list_add_tail(&conn->ibc_list,
3543                                               &kiblnd_data.kib_connd_waits);
3544                 }
3545
3546                 while (reconn < KIB_RECONN_BREAK) {
3547                         if (kiblnd_data.kib_reconn_sec !=
3548                             ktime_get_real_seconds()) {
3549                                 kiblnd_data.kib_reconn_sec = ktime_get_real_seconds();
3550                                 list_splice_init(&kiblnd_data.kib_reconn_wait,
3551                                                  &kiblnd_data.kib_reconn_list);
3552                         }
3553
3554                         conn = list_first_entry_or_null(&kiblnd_data.kib_reconn_list,
3555                                                         struct kib_conn, ibc_list);
3556                         if (!conn)
3557                                 break;
3558
3559                         list_del(&conn->ibc_list);
3560
3561                         spin_unlock_irqrestore(lock, flags);
3562                         dropped_lock = true;
3563
3564                         reconn += kiblnd_reconnect_peer(conn->ibc_peer);
3565                         kiblnd_peer_decref(conn->ibc_peer);
3566                         LIBCFS_FREE(conn, sizeof(*conn));
3567
3568                         spin_lock_irqsave(lock, flags);
3569                 }
3570
3571                 conn = list_first_entry_or_null(&kiblnd_data.kib_connd_waits,
3572                                                 struct kib_conn,
3573                                                 ibc_sched_list);
3574                 if (conn) {
3575                         list_del(&conn->ibc_list);
3576                         spin_unlock_irqrestore(lock, flags);
3577
3578                         dropped_lock = kiblnd_tx_may_discard(conn);
3579                         if (dropped_lock)
3580                                 kiblnd_conn_decref(conn);
3581
3582                         spin_lock_irqsave(lock, flags);
3583                         if (!dropped_lock)
3584                                 list_add_tail(&conn->ibc_list,
3585                                               &kiblnd_data.kib_connd_waits);
3586                 }
3587
3588                 /* careful with the jiffy wrap... */
3589                 timeout = (int)(deadline - jiffies);
3590                 if (timeout <= 0) {
3591                         const int n = 4;
3592                         const int p = 1;
3593                         int chunk = HASH_SIZE(kiblnd_data.kib_peers);
3594                         unsigned int lnd_timeout;
3595
3596                         spin_unlock_irqrestore(lock, flags);
3597                         dropped_lock = true;
3598
3599                         /* Time to check for RDMA timeouts on a few more
3600                          * peers: I do checks every 'p' seconds on a
3601                          * proportion of the peer_ni table and I need to check
3602                          * every connection 'n' times within a timeout
3603                          * interval, to ensure I detect a timeout on any
3604                          * connection within (n+1)/n times the timeout
3605                          * interval.
3606                          */
3607
3608                         lnd_timeout = kiblnd_timeout();
3609                         if (lnd_timeout > n * p)
3610                                 chunk = (chunk * n * p) / lnd_timeout;
3611                         if (chunk == 0)
3612                                 chunk = 1;
3613
3614                         for (i = 0; i < chunk; i++) {
3615                                 kiblnd_check_conns(peer_index);
3616                                 peer_index = (peer_index + 1) %
3617                                         HASH_SIZE(kiblnd_data.kib_peers);
3618                         }
3619
3620                         deadline += cfs_time_seconds(p);
3621                         spin_lock_irqsave(lock, flags);
3622                 }
3623
3624                 if (dropped_lock)
3625                         continue;
3626
3627                 /* Nothing to do for 'timeout'  */
3628                 set_current_state(TASK_INTERRUPTIBLE);
3629                 add_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3630                 spin_unlock_irqrestore(lock, flags);
3631
3632                 schedule_timeout(timeout);
3633
3634                 remove_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3635                 spin_lock_irqsave(lock, flags);
3636         }
3637
3638         spin_unlock_irqrestore(lock, flags);
3639
3640         kiblnd_thread_fini();
3641         return 0;
3642 }
3643
3644 void
3645 kiblnd_qp_event(struct ib_event *event, void *arg)
3646 {
3647         struct kib_conn *conn = arg;
3648
3649         switch (event->event) {
3650         case IB_EVENT_COMM_EST:
3651                 CDEBUG(D_NET, "%s established\n",
3652                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
3653                 /* We received a packet but connection isn't established
3654                  * probably handshake packet was lost, so free to
3655                  * force make connection established */
3656                 rdma_notify(conn->ibc_cmid, IB_EVENT_COMM_EST);
3657                 return;
3658
3659         case IB_EVENT_PORT_ERR:
3660         case IB_EVENT_DEVICE_FATAL:
3661                 CERROR("Fatal device error for NI %s\n",
3662                        libcfs_nidstr(&conn->ibc_peer->ibp_ni->ni_nid));
3663                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 1);
3664                 return;
3665
3666         case IB_EVENT_PORT_ACTIVE:
3667                 CERROR("Port reactivated for NI %s\n",
3668                        libcfs_nidstr(&conn->ibc_peer->ibp_ni->ni_nid));
3669                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 0);
3670                 return;
3671
3672         default:
3673                 CERROR("%s: Async QP event type %d\n",
3674                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3675                 return;
3676         }
3677 }
3678
3679 static void
3680 kiblnd_complete (struct ib_wc *wc)
3681 {
3682         switch (kiblnd_wreqid2type(wc->wr_id)) {
3683         default:
3684                 LBUG();
3685
3686         case IBLND_WID_MR:
3687                 if (wc->status != IB_WC_SUCCESS &&
3688                     wc->status != IB_WC_WR_FLUSH_ERR)
3689                         CNETERR("FastReg failed: %d\n", wc->status);
3690                 return;
3691
3692         case IBLND_WID_RDMA:
3693                 /* We only get RDMA completion notification if it fails.  All
3694                  * subsequent work items, including the final SEND will fail
3695                  * too.  However we can't print out any more info about the
3696                  * failing RDMA because 'tx' might be back on the idle list or
3697                  * even reused already if we didn't manage to post all our work
3698                  * items */
3699                 CNETERR("RDMA (tx: %p) failed: %d\n",
3700                         kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3701                 return;
3702
3703         case IBLND_WID_TX:
3704                 kiblnd_tx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3705                 return;
3706
3707         case IBLND_WID_RX:
3708                 kiblnd_rx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status,
3709                                    wc->byte_len);
3710                 return;
3711         }
3712 }
3713
3714 void
3715 kiblnd_cq_completion(struct ib_cq *cq, void *arg)
3716 {
3717         /* NB I'm not allowed to schedule this conn once its refcount has
3718          * reached 0.  Since fundamentally I'm racing with scheduler threads
3719          * consuming my CQ I could be called after all completions have
3720          * occurred.  But in this case, ibc_nrx == 0 && ibc_nsends_posted == 0
3721          * and this CQ is about to be destroyed so I NOOP. */
3722         struct kib_conn *conn = arg;
3723         struct kib_sched_info *sched = conn->ibc_sched;
3724         unsigned long flags;
3725
3726         LASSERT(cq == conn->ibc_cq);
3727
3728         spin_lock_irqsave(&sched->ibs_lock, flags);
3729
3730         conn->ibc_ready = 1;
3731
3732         if (!conn->ibc_scheduled &&
3733             (conn->ibc_nrx > 0 ||
3734              conn->ibc_nsends_posted > 0)) {
3735                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3736                 conn->ibc_scheduled = 1;
3737                 list_add_tail(&conn->ibc_sched_list, &sched->ibs_conns);
3738
3739                 if (waitqueue_active(&sched->ibs_waitq))
3740                         wake_up(&sched->ibs_waitq);
3741         }
3742
3743         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3744 }
3745
3746 void
3747 kiblnd_cq_event(struct ib_event *event, void *arg)
3748 {
3749         struct kib_conn *conn = arg;
3750
3751         CERROR("%s: async CQ event type %d\n",
3752                libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3753 }
3754
3755 int
3756 kiblnd_scheduler(void *arg)
3757 {
3758         long id = (long)arg;
3759         struct kib_sched_info *sched;
3760         struct kib_conn *conn;
3761         wait_queue_entry_t wait;
3762         unsigned long flags;
3763         struct ib_wc wc;
3764         bool did_something;
3765         int rc;
3766
3767         init_wait(&wait);
3768
3769         sched = kiblnd_data.kib_scheds[KIB_THREAD_CPT(id)];
3770
3771         rc = cfs_cpt_bind(lnet_cpt_table(), sched->ibs_cpt);
3772         if (rc != 0) {
3773                 CWARN("Unable to bind on CPU partition %d, please verify whether all CPUs are healthy and reload modules if necessary, otherwise your system might under risk of low performance\n", sched->ibs_cpt);
3774         }
3775
3776         spin_lock_irqsave(&sched->ibs_lock, flags);
3777
3778         while (!kiblnd_data.kib_shutdown) {
3779                 if (need_resched()) {
3780                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3781
3782                         cond_resched();
3783
3784                         spin_lock_irqsave(&sched->ibs_lock, flags);
3785                 }
3786
3787                 did_something = false;
3788
3789                 conn = list_first_entry_or_null(&sched->ibs_conns,
3790                                                 struct kib_conn,
3791                                                 ibc_sched_list);
3792                 if (conn) {
3793                         /* take over kib_sched_conns' ref on conn... */
3794                         LASSERT(conn->ibc_scheduled);
3795                         list_del(&conn->ibc_sched_list);
3796                         conn->ibc_ready = 0;
3797
3798                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3799
3800                         wc.wr_id = IBLND_WID_INVAL;
3801
3802                         rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3803                         if (rc == 0) {
3804                                 rc = ib_req_notify_cq(conn->ibc_cq,
3805                                                       IB_CQ_NEXT_COMP);
3806                                 if (rc < 0) {
3807                                         CWARN("%s: ib_req_notify_cq failed: %d, closing connection\n",
3808                                               libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
3809                                         kiblnd_close_conn(conn, -EIO);
3810                                         kiblnd_conn_decref(conn);
3811                                         spin_lock_irqsave(&sched->ibs_lock,
3812                                                           flags);
3813                                         continue;
3814                                 }
3815
3816                                 rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3817                         }
3818
3819                         if (unlikely(rc > 0 && wc.wr_id == IBLND_WID_INVAL)) {
3820                                 LCONSOLE_ERROR(
3821                                         "ib_poll_cq (rc: %d) returned invalid "
3822                                         "wr_id, opcode %d, status: %d, "
3823                                         "vendor_err: %d, conn: %s status: %d\n"
3824                                         "please upgrade firmware and OFED or "
3825                                         "contact vendor.\n", rc,
3826                                         wc.opcode, wc.status, wc.vendor_err,
3827                                         libcfs_nid2str(conn->ibc_peer->ibp_nid),
3828                                         conn->ibc_state);
3829                                 rc = -EINVAL;
3830                         }
3831
3832                         if (rc < 0) {
3833                                 CWARN("%s: ib_poll_cq failed: %d, closing connection\n",
3834                                       libcfs_nid2str(conn->ibc_peer->ibp_nid),
3835                                       rc);
3836                                 kiblnd_close_conn(conn, -EIO);
3837                                 kiblnd_conn_decref(conn);
3838                                 spin_lock_irqsave(&sched->ibs_lock, flags);
3839                                 continue;
3840                         }
3841
3842                         spin_lock_irqsave(&sched->ibs_lock, flags);
3843
3844                         if (rc != 0 || conn->ibc_ready) {
3845                                 /* There may be another completion waiting; get
3846                                  * another scheduler to check while I handle
3847                                  * this one... */
3848                                 /* +1 ref for sched_conns */
3849                                 kiblnd_conn_addref(conn);
3850                                 list_add_tail(&conn->ibc_sched_list,
3851                                               &sched->ibs_conns);
3852                                 if (waitqueue_active(&sched->ibs_waitq))
3853                                         wake_up(&sched->ibs_waitq);
3854                         } else {
3855                                 conn->ibc_scheduled = 0;
3856                         }
3857
3858                         if (rc != 0) {
3859                                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
3860                                 kiblnd_complete(&wc);
3861
3862                                 spin_lock_irqsave(&sched->ibs_lock, flags);
3863                         }
3864
3865                         kiblnd_conn_decref(conn); /* ..drop my ref from above */
3866                         did_something = true;
3867                 }
3868
3869                 if (did_something)
3870                         continue;
3871
3872                 set_current_state(TASK_INTERRUPTIBLE);
3873                 add_wait_queue_exclusive(&sched->ibs_waitq, &wait);
3874                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
3875
3876                 schedule();
3877
3878                 remove_wait_queue(&sched->ibs_waitq, &wait);
3879                 set_current_state(TASK_RUNNING);
3880                 spin_lock_irqsave(&sched->ibs_lock, flags);
3881         }
3882
3883         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3884
3885         kiblnd_thread_fini();
3886         return 0;
3887 }
3888
3889 int
3890 kiblnd_failover_thread(void *arg)
3891 {
3892         rwlock_t *glock = &kiblnd_data.kib_global_lock;
3893         struct kib_dev *dev;
3894         struct net *ns = arg;
3895         wait_queue_entry_t wait;
3896         unsigned long flags;
3897         int rc;
3898
3899         LASSERT(*kiblnd_tunables.kib_dev_failover != 0);
3900
3901         init_wait(&wait);
3902         write_lock_irqsave(glock, flags);
3903
3904         while (!kiblnd_data.kib_shutdown) {
3905                 bool do_failover = false;
3906                 int long_sleep;
3907
3908                 list_for_each_entry(dev, &kiblnd_data.kib_failed_devs,
3909                                     ibd_fail_list) {
3910                         if (ktime_get_seconds() < dev->ibd_next_failover)
3911                                 continue;
3912                         do_failover = true;
3913                         break;
3914                 }
3915
3916                 if (do_failover) {
3917                         list_del_init(&dev->ibd_fail_list);
3918                         dev->ibd_failover = 1;
3919                         write_unlock_irqrestore(glock, flags);
3920
3921                         rc = kiblnd_dev_failover(dev, ns);
3922
3923                         write_lock_irqsave(glock, flags);
3924
3925                         LASSERT(dev->ibd_failover);
3926                         dev->ibd_failover = 0;
3927                         if (rc >= 0) { /* Device is OK or failover succeed */
3928                                 dev->ibd_next_failover = ktime_get_seconds() + 3;
3929                                 continue;
3930                         }
3931
3932                         /* failed to failover, retry later */
3933                         dev->ibd_next_failover = ktime_get_seconds() +
3934                                 min(dev->ibd_failed_failover, 10);
3935                         if (kiblnd_dev_can_failover(dev)) {
3936                                 list_add_tail(&dev->ibd_fail_list,
3937                                               &kiblnd_data.kib_failed_devs);
3938                         }
3939
3940                         continue;
3941                 }
3942
3943                 /* long sleep if no more pending failover */
3944                 long_sleep = list_empty(&kiblnd_data.kib_failed_devs);
3945
3946                 set_current_state(TASK_INTERRUPTIBLE);
3947                 add_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
3948                 write_unlock_irqrestore(glock, flags);
3949
3950                 rc = schedule_timeout(long_sleep ? cfs_time_seconds(10) :
3951                                       cfs_time_seconds(1));
3952                 set_current_state(TASK_RUNNING);
3953                 remove_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
3954                 write_lock_irqsave(glock, flags);
3955
3956                 if (!long_sleep || rc != 0)
3957                         continue;
3958
3959                 /* have a long sleep, routine check all active devices,
3960                  * we need checking like this because if there is not active
3961                  * connection on the dev and no SEND from local, we may listen
3962                  * on wrong HCA for ever while there is a bonding failover
3963                  */
3964                 list_for_each_entry(dev, &kiblnd_data.kib_devs, ibd_list) {
3965                         if (kiblnd_dev_can_failover(dev)) {
3966                                 list_add_tail(&dev->ibd_fail_list,
3967                                               &kiblnd_data.kib_failed_devs);
3968                         }
3969                 }
3970         }
3971
3972         write_unlock_irqrestore(glock, flags);
3973
3974         kiblnd_thread_fini();
3975         return 0;
3976 }