Whamcloud - gitweb
LU-13181 o2ib: fix page mapping error
[fs/lustre-release.git] / lnet / klnds / o2iblnd / o2iblnd_cb.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lnet/klnds/o2iblnd/o2iblnd_cb.c
33  *
34  * Author: Eric Barton <eric@bartonsoftware.com>
35  */
36
37 #include "o2iblnd.h"
38
39 #define MAX_CONN_RACES_BEFORE_ABORT 20
40
41 static void kiblnd_peer_alive(struct kib_peer_ni *peer_ni);
42 static void kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
43                                        int error);
44 static void kiblnd_init_tx_msg(struct lnet_ni *ni, struct kib_tx *tx,
45                                int type, int body_nob);
46 static int kiblnd_init_rdma(struct kib_conn *conn, struct kib_tx *tx, int type,
47                             int resid, struct kib_rdma_desc *dstrd, u64 dstcookie);
48 static void kiblnd_queue_tx_locked(struct kib_tx *tx, struct kib_conn *conn);
49 static void kiblnd_queue_tx(struct kib_tx *tx, struct kib_conn *conn);
50
51 static void kiblnd_unmap_tx(struct kib_tx *tx);
52 static void kiblnd_check_sends_locked(struct kib_conn *conn);
53
54 void
55 kiblnd_tx_done(struct kib_tx *tx)
56 {
57         struct lnet_msg *lntmsg[2];
58         int         rc;
59         int         i;
60
61         LASSERT (!in_interrupt());
62         LASSERT (!tx->tx_queued);               /* mustn't be queued for sending */
63         LASSERT (tx->tx_sending == 0);          /* mustn't be awaiting sent callback */
64         LASSERT (!tx->tx_waiting);              /* mustn't be awaiting peer_ni response */
65         LASSERT (tx->tx_pool != NULL);
66
67         kiblnd_unmap_tx(tx);
68
69         /* tx may have up to 2 lnet msgs to finalise */
70         lntmsg[0] = tx->tx_lntmsg[0]; tx->tx_lntmsg[0] = NULL;
71         lntmsg[1] = tx->tx_lntmsg[1]; tx->tx_lntmsg[1] = NULL;
72         rc = tx->tx_status;
73
74         if (tx->tx_conn != NULL) {
75                 kiblnd_conn_decref(tx->tx_conn);
76                 tx->tx_conn = NULL;
77         }
78
79         tx->tx_nwrq = tx->tx_nsge = 0;
80         tx->tx_status = 0;
81
82         kiblnd_pool_free_node(&tx->tx_pool->tpo_pool, &tx->tx_list);
83
84         /* delay finalize until my descs have been freed */
85         for (i = 0; i < 2; i++) {
86                 if (lntmsg[i] == NULL)
87                         continue;
88
89                 /* propagate health status to LNet for requests */
90                 if (i == 0 && lntmsg[i])
91                         lntmsg[i]->msg_health_status = tx->tx_hstatus;
92
93                 lnet_finalize(lntmsg[i], rc);
94         }
95 }
96
97 void
98 kiblnd_txlist_done(struct list_head *txlist, int status,
99                    enum lnet_msg_hstatus hstatus)
100 {
101         struct kib_tx *tx;
102
103         while (!list_empty(txlist)) {
104                 tx = list_entry(txlist->next, struct kib_tx, tx_list);
105
106                 list_del(&tx->tx_list);
107                 /* complete now */
108                 tx->tx_waiting = 0;
109                 tx->tx_status = status;
110                 if (hstatus != LNET_MSG_STATUS_OK)
111                         tx->tx_hstatus = hstatus;
112                 kiblnd_tx_done(tx);
113         }
114 }
115
116 static struct kib_tx *
117 kiblnd_get_idle_tx(struct lnet_ni *ni, lnet_nid_t target)
118 {
119         struct kib_net *net = ni->ni_data;
120         struct list_head *node;
121         struct kib_tx *tx;
122         struct kib_tx_poolset *tps;
123
124         tps = net->ibn_tx_ps[lnet_cpt_of_nid(target, ni)];
125         node = kiblnd_pool_alloc_node(&tps->tps_poolset);
126         if (node == NULL)
127                 return NULL;
128         tx = container_of(node, struct kib_tx, tx_list);
129
130         LASSERT (tx->tx_nwrq == 0);
131         LASSERT (!tx->tx_queued);
132         LASSERT (tx->tx_sending == 0);
133         LASSERT (!tx->tx_waiting);
134         LASSERT (tx->tx_status == 0);
135         LASSERT (tx->tx_conn == NULL);
136         LASSERT (tx->tx_lntmsg[0] == NULL);
137         LASSERT (tx->tx_lntmsg[1] == NULL);
138         LASSERT (tx->tx_nfrags == 0);
139
140         tx->tx_gaps = false;
141         tx->tx_hstatus = LNET_MSG_STATUS_OK;
142
143         return tx;
144 }
145
146 static void
147 kiblnd_drop_rx(struct kib_rx *rx)
148 {
149         struct kib_conn *conn = rx->rx_conn;
150         struct kib_sched_info *sched = conn->ibc_sched;
151         unsigned long flags;
152
153         spin_lock_irqsave(&sched->ibs_lock, flags);
154         LASSERT(conn->ibc_nrx > 0);
155         conn->ibc_nrx--;
156         spin_unlock_irqrestore(&sched->ibs_lock, flags);
157
158         kiblnd_conn_decref(conn);
159 }
160
161 int
162 kiblnd_post_rx(struct kib_rx *rx, int credit)
163 {
164         struct kib_conn *conn = rx->rx_conn;
165         struct kib_net *net = conn->ibc_peer->ibp_ni->ni_data;
166         struct ib_recv_wr *bad_wrq = NULL;
167 #ifdef HAVE_IB_GET_DMA_MR
168         struct ib_mr *mr = conn->ibc_hdev->ibh_mrs;
169 #endif
170         int rc;
171
172         LASSERT (net != NULL);
173         LASSERT (!in_interrupt());
174         LASSERT (credit == IBLND_POSTRX_NO_CREDIT ||
175                  credit == IBLND_POSTRX_PEER_CREDIT ||
176                  credit == IBLND_POSTRX_RSRVD_CREDIT);
177 #ifdef HAVE_IB_GET_DMA_MR
178         LASSERT(mr != NULL);
179
180         rx->rx_sge.lkey   = mr->lkey;
181 #else
182         rx->rx_sge.lkey   = conn->ibc_hdev->ibh_pd->local_dma_lkey;
183 #endif
184         rx->rx_sge.addr   = rx->rx_msgaddr;
185         rx->rx_sge.length = IBLND_MSG_SIZE;
186
187         rx->rx_wrq.next = NULL;
188         rx->rx_wrq.sg_list = &rx->rx_sge;
189         rx->rx_wrq.num_sge = 1;
190         rx->rx_wrq.wr_id = kiblnd_ptr2wreqid(rx, IBLND_WID_RX);
191
192         LASSERT (conn->ibc_state >= IBLND_CONN_INIT);
193         LASSERT (rx->rx_nob >= 0);              /* not posted */
194
195         if (conn->ibc_state > IBLND_CONN_ESTABLISHED) {
196                 kiblnd_drop_rx(rx);             /* No more posts for this rx */
197                 return 0;
198         }
199
200         rx->rx_nob = -1;                        /* flag posted */
201
202         /* NB: need an extra reference after ib_post_recv because we don't
203          * own this rx (and rx::rx_conn) anymore, LU-5678.
204          */
205         kiblnd_conn_addref(conn);
206 #ifdef HAVE_IB_POST_SEND_RECV_CONST
207         rc = ib_post_recv(conn->ibc_cmid->qp, &rx->rx_wrq,
208                           (const struct ib_recv_wr **)&bad_wrq);
209 #else
210         rc = ib_post_recv(conn->ibc_cmid->qp, &rx->rx_wrq, &bad_wrq);
211 #endif
212         if (unlikely(rc != 0)) {
213                 CERROR("Can't post rx for %s: %d, bad_wrq: %p\n",
214                        libcfs_nid2str(conn->ibc_peer->ibp_nid), rc, bad_wrq);
215                 rx->rx_nob = 0;
216         }
217
218         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) /* Initial post */
219                 goto out;
220
221         if (unlikely(rc != 0)) {
222                 kiblnd_close_conn(conn, rc);
223                 kiblnd_drop_rx(rx);     /* No more posts for this rx */
224                 goto out;
225         }
226
227         if (credit == IBLND_POSTRX_NO_CREDIT)
228                 goto out;
229
230         spin_lock(&conn->ibc_lock);
231         if (credit == IBLND_POSTRX_PEER_CREDIT)
232                 conn->ibc_outstanding_credits++;
233         else
234                 conn->ibc_reserved_credits++;
235         kiblnd_check_sends_locked(conn);
236         spin_unlock(&conn->ibc_lock);
237
238 out:
239         kiblnd_conn_decref(conn);
240         return rc;
241 }
242
243 static struct kib_tx *
244 kiblnd_find_waiting_tx_locked(struct kib_conn *conn, int txtype, u64 cookie)
245 {
246         struct list_head *tmp;
247
248         list_for_each(tmp, &conn->ibc_active_txs) {
249                 struct kib_tx *tx = list_entry(tmp, struct kib_tx, tx_list);
250
251                 LASSERT(!tx->tx_queued);
252                 LASSERT(tx->tx_sending != 0 || tx->tx_waiting);
253
254                 if (tx->tx_cookie != cookie)
255                         continue;
256
257                 if (tx->tx_waiting &&
258                     tx->tx_msg->ibm_type == txtype)
259                         return tx;
260
261                 CWARN("Bad completion: %swaiting, type %x (wanted %x)\n",
262                       tx->tx_waiting ? "" : "NOT ",
263                       tx->tx_msg->ibm_type, txtype);
264         }
265         return NULL;
266 }
267
268 static void
269 kiblnd_handle_completion(struct kib_conn *conn, int txtype, int status, u64 cookie)
270 {
271         struct kib_tx *tx;
272         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
273         int idle;
274
275         spin_lock(&conn->ibc_lock);
276
277         tx = kiblnd_find_waiting_tx_locked(conn, txtype, cookie);
278         if (tx == NULL) {
279                 spin_unlock(&conn->ibc_lock);
280
281                 CWARN("Unmatched completion type %x cookie %#llx from %s\n",
282                       txtype, cookie, libcfs_nid2str(conn->ibc_peer->ibp_nid));
283                 kiblnd_close_conn(conn, -EPROTO);
284                 return;
285         }
286
287         if (tx->tx_status == 0) {               /* success so far */
288                 if (status < 0) {               /* failed? */
289                         tx->tx_status = status;
290                         tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
291                 } else if (txtype == IBLND_MSG_GET_REQ) {
292                         lnet_set_reply_msg_len(ni, tx->tx_lntmsg[1], status);
293                 }
294         }
295
296         tx->tx_waiting = 0;
297
298         idle = !tx->tx_queued && (tx->tx_sending == 0);
299         if (idle)
300                 list_del(&tx->tx_list);
301
302         spin_unlock(&conn->ibc_lock);
303
304         if (idle)
305                 kiblnd_tx_done(tx);
306 }
307
308 static void
309 kiblnd_send_completion(struct kib_conn *conn, int type, int status, u64 cookie)
310 {
311         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
312         struct kib_tx *tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
313
314         if (tx == NULL) {
315                 CERROR("Can't get tx for completion %x for %s\n",
316                        type, libcfs_nid2str(conn->ibc_peer->ibp_nid));
317                 return;
318         }
319
320         tx->tx_msg->ibm_u.completion.ibcm_status = status;
321         tx->tx_msg->ibm_u.completion.ibcm_cookie = cookie;
322         kiblnd_init_tx_msg(ni, tx, type, sizeof(struct kib_completion_msg));
323
324         kiblnd_queue_tx(tx, conn);
325 }
326
327 static void
328 kiblnd_handle_rx(struct kib_rx *rx)
329 {
330         struct kib_msg *msg = rx->rx_msg;
331         struct kib_conn   *conn = rx->rx_conn;
332         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
333         int           credits = msg->ibm_credits;
334         struct kib_tx *tx;
335         int           rc = 0;
336         int           rc2;
337         int           post_credit;
338
339         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
340
341         CDEBUG (D_NET, "Received %x[%d] from %s\n",
342                 msg->ibm_type, credits,
343                 libcfs_nid2str(conn->ibc_peer->ibp_nid));
344
345         if (credits != 0) {
346                 /* Have I received credits that will let me send? */
347                 spin_lock(&conn->ibc_lock);
348
349                 if (conn->ibc_credits + credits >
350                     conn->ibc_queue_depth) {
351                         rc2 = conn->ibc_credits;
352                         spin_unlock(&conn->ibc_lock);
353
354                         CERROR("Bad credits from %s: %d + %d > %d\n",
355                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
356                                rc2, credits,
357                                conn->ibc_queue_depth);
358
359                         kiblnd_close_conn(conn, -EPROTO);
360                         kiblnd_post_rx(rx, IBLND_POSTRX_NO_CREDIT);
361                         return;
362                 }
363
364                 conn->ibc_credits += credits;
365
366                 /* This ensures the credit taken by NOOP can be returned */
367                 if (msg->ibm_type == IBLND_MSG_NOOP &&
368                     !IBLND_OOB_CAPABLE(conn->ibc_version)) /* v1 only */
369                         conn->ibc_outstanding_credits++;
370
371                 kiblnd_check_sends_locked(conn);
372                 spin_unlock(&conn->ibc_lock);
373         }
374
375         switch (msg->ibm_type) {
376         default:
377                 CERROR("Bad IBLND message type %x from %s\n",
378                        msg->ibm_type, libcfs_nid2str(conn->ibc_peer->ibp_nid));
379                 post_credit = IBLND_POSTRX_NO_CREDIT;
380                 rc = -EPROTO;
381                 break;
382
383         case IBLND_MSG_NOOP:
384                 if (IBLND_OOB_CAPABLE(conn->ibc_version)) {
385                         post_credit = IBLND_POSTRX_NO_CREDIT;
386                         break;
387                 }
388
389                 if (credits != 0) /* credit already posted */
390                         post_credit = IBLND_POSTRX_NO_CREDIT;
391                 else              /* a keepalive NOOP */
392                         post_credit = IBLND_POSTRX_PEER_CREDIT;
393                 break;
394
395         case IBLND_MSG_IMMEDIATE:
396                 post_credit = IBLND_POSTRX_DONT_POST;
397                 rc = lnet_parse(ni, &msg->ibm_u.immediate.ibim_hdr,
398                                 msg->ibm_srcnid, rx, 0);
399                 if (rc < 0)                     /* repost on error */
400                         post_credit = IBLND_POSTRX_PEER_CREDIT;
401                 break;
402
403         case IBLND_MSG_PUT_REQ:
404                 post_credit = IBLND_POSTRX_DONT_POST;
405                 rc = lnet_parse(ni, &msg->ibm_u.putreq.ibprm_hdr,
406                                 msg->ibm_srcnid, rx, 1);
407                 if (rc < 0)                     /* repost on error */
408                         post_credit = IBLND_POSTRX_PEER_CREDIT;
409                 break;
410
411         case IBLND_MSG_PUT_NAK:
412                 CWARN ("PUT_NACK from %s\n",
413                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
414                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
415                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_REQ,
416                                          msg->ibm_u.completion.ibcm_status,
417                                          msg->ibm_u.completion.ibcm_cookie);
418                 break;
419
420         case IBLND_MSG_PUT_ACK:
421                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
422
423                 spin_lock(&conn->ibc_lock);
424                 tx = kiblnd_find_waiting_tx_locked(conn, IBLND_MSG_PUT_REQ,
425                                         msg->ibm_u.putack.ibpam_src_cookie);
426                 if (tx != NULL)
427                         list_del(&tx->tx_list);
428                 spin_unlock(&conn->ibc_lock);
429
430                 if (tx == NULL) {
431                         CERROR("Unmatched PUT_ACK from %s\n",
432                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
433                         rc = -EPROTO;
434                         break;
435                 }
436
437                 LASSERT (tx->tx_waiting);
438                 /* CAVEAT EMPTOR: I could be racing with tx_complete, but...
439                  * (a) I can overwrite tx_msg since my peer_ni has received it!
440                  * (b) tx_waiting set tells tx_complete() it's not done. */
441
442                 tx->tx_nwrq = tx->tx_nsge = 0;  /* overwrite PUT_REQ */
443
444                 rc2 = kiblnd_init_rdma(conn, tx, IBLND_MSG_PUT_DONE,
445                                        kiblnd_rd_size(&msg->ibm_u.putack.ibpam_rd),
446                                        &msg->ibm_u.putack.ibpam_rd,
447                                        msg->ibm_u.putack.ibpam_dst_cookie);
448                 if (rc2 < 0)
449                         CERROR("Can't setup rdma for PUT to %s: %d\n",
450                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc2);
451
452                 spin_lock(&conn->ibc_lock);
453                 tx->tx_waiting = 0;     /* clear waiting and queue atomically */
454                 kiblnd_queue_tx_locked(tx, conn);
455                 spin_unlock(&conn->ibc_lock);
456                 break;
457
458         case IBLND_MSG_PUT_DONE:
459                 post_credit = IBLND_POSTRX_PEER_CREDIT;
460                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_ACK,
461                                          msg->ibm_u.completion.ibcm_status,
462                                          msg->ibm_u.completion.ibcm_cookie);
463                 break;
464
465         case IBLND_MSG_GET_REQ:
466                 post_credit = IBLND_POSTRX_DONT_POST;
467                 rc = lnet_parse(ni, &msg->ibm_u.get.ibgm_hdr,
468                                 msg->ibm_srcnid, rx, 1);
469                 if (rc < 0)                     /* repost on error */
470                         post_credit = IBLND_POSTRX_PEER_CREDIT;
471                 break;
472
473         case IBLND_MSG_GET_DONE:
474                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
475                 kiblnd_handle_completion(conn, IBLND_MSG_GET_REQ,
476                                          msg->ibm_u.completion.ibcm_status,
477                                          msg->ibm_u.completion.ibcm_cookie);
478                 break;
479         }
480
481         if (rc < 0)                             /* protocol error */
482                 kiblnd_close_conn(conn, rc);
483
484         if (post_credit != IBLND_POSTRX_DONT_POST)
485                 kiblnd_post_rx(rx, post_credit);
486 }
487
488 static void
489 kiblnd_rx_complete(struct kib_rx *rx, int status, int nob)
490 {
491         struct kib_msg *msg = rx->rx_msg;
492         struct kib_conn   *conn = rx->rx_conn;
493         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
494         struct kib_net *net = ni->ni_data;
495         int rc;
496         int err = -EIO;
497
498         LASSERT (net != NULL);
499         LASSERT (rx->rx_nob < 0);               /* was posted */
500         rx->rx_nob = 0;                         /* isn't now */
501
502         if (conn->ibc_state > IBLND_CONN_ESTABLISHED)
503                 goto ignore;
504
505         if (status != IB_WC_SUCCESS) {
506                 CNETERR("Rx from %s failed: %d\n",
507                         libcfs_nid2str(conn->ibc_peer->ibp_nid), status);
508                 goto failed;
509         }
510
511         LASSERT (nob >= 0);
512         rx->rx_nob = nob;
513
514         rc = kiblnd_unpack_msg(msg, rx->rx_nob);
515         if (rc != 0) {
516                 CERROR ("Error %d unpacking rx from %s\n",
517                         rc, libcfs_nid2str(conn->ibc_peer->ibp_nid));
518                 goto failed;
519         }
520
521         if (msg->ibm_srcnid != conn->ibc_peer->ibp_nid ||
522             msg->ibm_dstnid != ni->ni_nid ||
523             msg->ibm_srcstamp != conn->ibc_incarnation ||
524             msg->ibm_dststamp != net->ibn_incarnation) {
525                 CERROR ("Stale rx from %s\n",
526                         libcfs_nid2str(conn->ibc_peer->ibp_nid));
527                 err = -ESTALE;
528                 goto failed;
529         }
530
531         /* set time last known alive */
532         kiblnd_peer_alive(conn->ibc_peer);
533
534         /* racing with connection establishment/teardown! */
535
536         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
537                 rwlock_t  *g_lock = &kiblnd_data.kib_global_lock;
538                 unsigned long  flags;
539
540                 write_lock_irqsave(g_lock, flags);
541                 /* must check holding global lock to eliminate race */
542                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
543                         list_add_tail(&rx->rx_list, &conn->ibc_early_rxs);
544                         write_unlock_irqrestore(g_lock, flags);
545                         return;
546                 }
547                 write_unlock_irqrestore(g_lock, flags);
548         }
549         kiblnd_handle_rx(rx);
550         return;
551
552  failed:
553         CDEBUG(D_NET, "rx %p conn %p\n", rx, conn);
554         kiblnd_close_conn(conn, err);
555  ignore:
556         kiblnd_drop_rx(rx);                     /* Don't re-post rx. */
557 }
558
559 static int
560 kiblnd_fmr_map_tx(struct kib_net *net, struct kib_tx *tx,
561                   struct kib_rdma_desc *rd, u32 nob)
562 {
563         struct kib_hca_dev *hdev;
564         struct kib_dev *dev;
565         struct kib_fmr_poolset *fps;
566         int                     cpt;
567         int                     rc;
568         int i;
569
570         LASSERT(tx->tx_pool != NULL);
571         LASSERT(tx->tx_pool->tpo_pool.po_owner != NULL);
572
573         dev = net->ibn_dev;
574         hdev = tx->tx_pool->tpo_hdev;
575         cpt = tx->tx_pool->tpo_pool.po_owner->ps_cpt;
576
577         /*
578          * If we're dealing with FastReg, but the device doesn't
579          * support GAPS and the tx has GAPS, then there is no real point
580          * in trying to map the memory, because it'll just fail. So
581          * preemptively fail with an appropriate message
582          */
583         if ((dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED) &&
584             !(dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT) &&
585             tx->tx_gaps) {
586                 CERROR("Using FastReg with no GAPS support, but tx has gaps. "
587                        "Try setting use_fastreg_gaps to 1\n");
588                 return -EPROTONOSUPPORT;
589         }
590
591 #ifdef HAVE_FMR_POOL_API
592         /*
593          * FMR does not support gaps but the tx has gaps then
594          * we should make sure that the number of fragments we'll be sending
595          * over fits within the number of fragments negotiated on the
596          * connection, otherwise, we won't be able to RDMA the data.
597          * We need to maintain the number of fragments negotiation on the
598          * connection for backwards compatibility.
599          */
600         if (tx->tx_gaps && (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)) {
601                 if (tx->tx_conn &&
602                     tx->tx_conn->ibc_max_frags <= rd->rd_nfrags) {
603                         CERROR("TX number of frags (%d) is <= than connection"
604                                " number of frags (%d). Consider setting peer's"
605                                " map_on_demand to 256\n", tx->tx_nfrags,
606                                tx->tx_conn->ibc_max_frags);
607                         return -EFBIG;
608                 }
609         }
610 #endif
611
612         fps = net->ibn_fmr_ps[cpt];
613         rc = kiblnd_fmr_pool_map(fps, tx, rd, nob, 0, &tx->tx_fmr);
614         if (rc != 0) {
615                 CERROR("Can't map %u bytes (%u/%u)s: %d\n", nob,
616                        tx->tx_nfrags, rd->rd_nfrags, rc);
617                 return rc;
618         }
619
620         /*
621          * If rd is not tx_rd, it's going to get sent to a peer_ni, who will
622          * need the rkey
623          */
624         rd->rd_key = tx->tx_fmr.fmr_key;
625         /*
626          * for FastReg or FMR with no gaps we can accumulate all
627          * the fragments in one FastReg or FMR fragment.
628          */
629         if (
630 #ifdef HAVE_FMR_POOL_API
631             ((dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)
632              && !tx->tx_gaps) ||
633 #endif
634             (dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED)) {
635                 /* FMR requires zero based address */
636 #ifdef HAVE_FMR_POOL_API
637                 if (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)
638                         rd->rd_frags[0].rf_addr &= ~hdev->ibh_page_mask;
639 #endif
640                 rd->rd_frags[0].rf_nob = nob;
641                 rd->rd_nfrags = 1;
642         } else {
643                 /*
644                  * We're transmitting with gaps using FMR.
645                  * We'll need to use multiple fragments and identify the
646                  * zero based address of each fragment.
647                  */
648                 for (i = 0; i < rd->rd_nfrags; i++) {
649                         rd->rd_frags[i].rf_addr &= ~hdev->ibh_page_mask;
650                         rd->rd_frags[i].rf_addr += i << hdev->ibh_page_shift;
651                 }
652         }
653
654         return 0;
655 }
656
657 static void
658 kiblnd_unmap_tx(struct kib_tx *tx)
659 {
660         if (
661 #ifdef HAVE_FMR_POOL_API
662                 tx->tx_fmr.fmr_pfmr ||
663 #endif
664                 tx->tx_fmr.fmr_frd)
665                 kiblnd_fmr_pool_unmap(&tx->tx_fmr, tx->tx_status);
666
667         if (tx->tx_nfrags != 0) {
668                 kiblnd_dma_unmap_sg(tx->tx_pool->tpo_hdev->ibh_ibdev,
669                                     tx->tx_frags, tx->tx_nfrags, tx->tx_dmadir);
670                 tx->tx_nfrags = 0;
671         }
672 }
673
674 #ifdef HAVE_IB_GET_DMA_MR
675 static struct ib_mr *
676 kiblnd_find_rd_dma_mr(struct lnet_ni *ni, struct kib_rdma_desc *rd)
677 {
678         struct kib_net *net = ni->ni_data;
679         struct kib_hca_dev *hdev = net->ibn_dev->ibd_hdev;
680         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
681
682         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
683
684         /*
685          * if map-on-demand is turned on and the device supports
686          * either FMR or FastReg then use that. Otherwise use global
687          * memory regions. If that's not available either, then you're
688          * dead in the water and fail the operation.
689          */
690         if (tunables->lnd_map_on_demand &&
691             (net->ibn_dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED
692 #ifdef HAVE_FMR_POOL_API
693              || net->ibn_dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED
694 #endif
695         ))
696                 return NULL;
697
698         /*
699          * hdev->ibh_mrs can be NULL. This case is dealt with gracefully
700          * in the call chain. The mapping will fail with appropriate error
701          * message.
702          */
703         return hdev->ibh_mrs;
704 }
705 #endif
706
707 static int kiblnd_map_tx(struct lnet_ni *ni, struct kib_tx *tx,
708                          struct kib_rdma_desc *rd, int nfrags)
709 {
710         struct kib_net *net = ni->ni_data;
711         struct kib_hca_dev *hdev = net->ibn_dev->ibd_hdev;
712 #ifdef HAVE_IB_GET_DMA_MR
713         struct ib_mr *mr = NULL;
714 #endif
715         __u32 nob;
716         int i;
717
718         /* If rd is not tx_rd, it's going to get sent to a peer_ni and I'm the
719          * RDMA sink */
720         tx->tx_dmadir = (rd != tx->tx_rd) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
721         tx->tx_nfrags = nfrags;
722
723         rd->rd_nfrags = kiblnd_dma_map_sg(hdev->ibh_ibdev, tx->tx_frags,
724                                           tx->tx_nfrags, tx->tx_dmadir);
725
726         for (i = 0, nob = 0; i < rd->rd_nfrags; i++) {
727                 rd->rd_frags[i].rf_nob  = kiblnd_sg_dma_len(
728                         hdev->ibh_ibdev, &tx->tx_frags[i]);
729                 rd->rd_frags[i].rf_addr = kiblnd_sg_dma_address(
730                         hdev->ibh_ibdev, &tx->tx_frags[i]);
731                 nob += rd->rd_frags[i].rf_nob;
732         }
733
734 #ifdef HAVE_IB_GET_DMA_MR
735         mr = kiblnd_find_rd_dma_mr(ni, rd);
736         if (mr != NULL) {
737                 /* found pre-mapping MR */
738                 rd->rd_key = (rd != tx->tx_rd) ? mr->rkey : mr->lkey;
739                 return 0;
740         }
741 #endif
742
743         if (net->ibn_fmr_ps != NULL)
744                 return kiblnd_fmr_map_tx(net, tx, rd, nob);
745
746         return -EINVAL;
747 }
748
749 static int kiblnd_setup_rd_iov(struct lnet_ni *ni, struct kib_tx *tx,
750                                struct kib_rdma_desc *rd, unsigned int niov,
751                                struct kvec *iov, int offset, int nob)
752 {
753         struct kib_net *net = ni->ni_data;
754         struct page *page;
755         struct scatterlist *sg;
756         unsigned long       vaddr;
757         int                 fragnob;
758         int                 page_offset;
759         unsigned int        max_niov;
760
761         LASSERT (nob > 0);
762         LASSERT (niov > 0);
763         LASSERT (net != NULL);
764
765         while (offset >= iov->iov_len) {
766                 offset -= iov->iov_len;
767                 niov--;
768                 iov++;
769                 LASSERT (niov > 0);
770         }
771
772         max_niov = niov;
773
774         sg = tx->tx_frags;
775         do {
776                 LASSERT(niov > 0);
777
778                 vaddr = ((unsigned long)iov->iov_base) + offset;
779                 page_offset = vaddr & (PAGE_SIZE - 1);
780                 page = lnet_kvaddr_to_page(vaddr);
781                 if (page == NULL) {
782                         CERROR("Can't find page\n");
783                         return -EFAULT;
784                 }
785
786                 fragnob = min((int)(iov->iov_len - offset), nob);
787                 fragnob = min(fragnob, (int)PAGE_SIZE - page_offset);
788
789                 /*
790                  * We're allowed to start at a non-aligned page offset in
791                  * the first fragment and end at a non-aligned page offset
792                  * in the last fragment.
793                  */
794                 if ((fragnob < (int)PAGE_SIZE - page_offset) &&
795                     (niov < max_niov) && nob > fragnob) {
796                         CDEBUG(D_NET, "fragnob %d < available page %d: with"
797                                       " remaining %d iovs with %d nob left\n",
798                                fragnob, (int)PAGE_SIZE - page_offset, niov,
799                                nob);
800                         tx->tx_gaps = true;
801                 }
802
803                 sg_set_page(sg, page, fragnob, page_offset);
804                 sg = sg_next(sg);
805                 if (!sg) {
806                         CERROR("lacking enough sg entries to map tx\n");
807                         return -EFAULT;
808                 }
809
810                 if (offset + fragnob < iov->iov_len) {
811                         offset += fragnob;
812                 } else {
813                         offset = 0;
814                         iov++;
815                         niov--;
816                 }
817                 nob -= fragnob;
818         } while (nob > 0);
819
820         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
821 }
822
823 static int kiblnd_setup_rd_kiov(struct lnet_ni *ni, struct kib_tx *tx,
824                                 struct kib_rdma_desc *rd, int nkiov,
825                                 lnet_kiov_t *kiov, int offset, int nob)
826 {
827         struct kib_net *net = ni->ni_data;
828         struct scatterlist *sg;
829         int                 fragnob;
830         int                 max_nkiov;
831
832         CDEBUG(D_NET, "niov %d offset %d nob %d\n", nkiov, offset, nob);
833
834         LASSERT(nob > 0);
835         LASSERT(nkiov > 0);
836         LASSERT(net != NULL);
837
838         while (offset >= kiov->kiov_len) {
839                 offset -= kiov->kiov_len;
840                 nkiov--;
841                 kiov++;
842                 LASSERT(nkiov > 0);
843         }
844
845         max_nkiov = nkiov;
846
847         sg = tx->tx_frags;
848         do {
849                 LASSERT(nkiov > 0);
850
851                 fragnob = min((int)(kiov->kiov_len - offset), nob);
852
853                 /*
854                  * We're allowed to start at a non-aligned page offset in
855                  * the first fragment and end at a non-aligned page offset
856                  * in the last fragment.
857                  */
858                 if ((fragnob < (int)(kiov->kiov_len - offset)) &&
859                     nkiov < max_nkiov && nob > fragnob) {
860                         CDEBUG(D_NET, "fragnob %d < available page %d: with"
861                                       " remaining %d kiovs with %d nob left\n",
862                                fragnob, (int)(kiov->kiov_len - offset),
863                                nkiov, nob);
864                         tx->tx_gaps = true;
865                 }
866
867                 sg_set_page(sg, kiov->kiov_page, fragnob,
868                             kiov->kiov_offset + offset);
869                 sg = sg_next(sg);
870                 if (!sg) {
871                         CERROR("lacking enough sg entries to map tx\n");
872                         return -EFAULT;
873                 }
874
875                 offset = 0;
876                 kiov++;
877                 nkiov--;
878                 nob -= fragnob;
879         } while (nob > 0);
880
881         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
882 }
883
884 static int
885 kiblnd_post_tx_locked(struct kib_conn *conn, struct kib_tx *tx, int credit)
886 __must_hold(&conn->ibc_lock)
887 {
888         struct kib_msg *msg = tx->tx_msg;
889         struct kib_peer_ni *peer_ni = conn->ibc_peer;
890         struct lnet_ni *ni = peer_ni->ibp_ni;
891         int ver = conn->ibc_version;
892         int rc;
893         int done;
894
895         LASSERT(tx->tx_queued);
896         /* We rely on this for QP sizing */
897         LASSERT(tx->tx_nwrq > 0 && tx->tx_nsge >= 0);
898         LASSERT(tx->tx_nwrq <= 1 + conn->ibc_max_frags);
899
900         LASSERT(credit == 0 || credit == 1);
901         LASSERT(conn->ibc_outstanding_credits >= 0);
902         LASSERT(conn->ibc_outstanding_credits <= conn->ibc_queue_depth);
903         LASSERT(conn->ibc_credits >= 0);
904         LASSERT(conn->ibc_credits <= conn->ibc_queue_depth);
905
906         if (conn->ibc_nsends_posted ==
907             kiblnd_concurrent_sends(ver, ni)) {
908                 /* tx completions outstanding... */
909                 CDEBUG(D_NET, "%s: posted enough\n",
910                        libcfs_nid2str(peer_ni->ibp_nid));
911                 return -EAGAIN;
912         }
913
914         if (credit != 0 && conn->ibc_credits == 0) {   /* no credits */
915                 CDEBUG(D_NET, "%s: no credits\n",
916                        libcfs_nid2str(peer_ni->ibp_nid));
917                 return -EAGAIN;
918         }
919
920         if (credit != 0 && !IBLND_OOB_CAPABLE(ver) &&
921             conn->ibc_credits == 1 &&   /* last credit reserved */
922             msg->ibm_type != IBLND_MSG_NOOP) {      /* for NOOP */
923                 CDEBUG(D_NET, "%s: not using last credit\n",
924                        libcfs_nid2str(peer_ni->ibp_nid));
925                 return -EAGAIN;
926         }
927
928         /* NB don't drop ibc_lock before bumping tx_sending */
929         list_del(&tx->tx_list);
930         tx->tx_queued = 0;
931
932         if (msg->ibm_type == IBLND_MSG_NOOP &&
933             (!kiblnd_need_noop(conn) ||     /* redundant NOOP */
934              (IBLND_OOB_CAPABLE(ver) && /* posted enough NOOP */
935               conn->ibc_noops_posted == IBLND_OOB_MSGS(ver)))) {
936                 /* OK to drop when posted enough NOOPs, since
937                  * kiblnd_check_sends_locked will queue NOOP again when
938                  * posted NOOPs complete */
939                 spin_unlock(&conn->ibc_lock);
940                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
941                 kiblnd_tx_done(tx);
942                 spin_lock(&conn->ibc_lock);
943                 CDEBUG(D_NET, "%s(%d): redundant or enough NOOP\n",
944                        libcfs_nid2str(peer_ni->ibp_nid),
945                        conn->ibc_noops_posted);
946                 return 0;
947         }
948
949         kiblnd_pack_msg(peer_ni->ibp_ni, msg, ver, conn->ibc_outstanding_credits,
950                         peer_ni->ibp_nid, conn->ibc_incarnation);
951
952         conn->ibc_credits -= credit;
953         conn->ibc_outstanding_credits = 0;
954         conn->ibc_nsends_posted++;
955         if (msg->ibm_type == IBLND_MSG_NOOP)
956                 conn->ibc_noops_posted++;
957
958         /* CAVEAT EMPTOR!  This tx could be the PUT_DONE of an RDMA
959          * PUT.  If so, it was first queued here as a PUT_REQ, sent and
960          * stashed on ibc_active_txs, matched by an incoming PUT_ACK,
961          * and then re-queued here.  It's (just) possible that
962          * tx_sending is non-zero if we've not done the tx_complete()
963          * from the first send; hence the ++ rather than = below. */
964         tx->tx_sending++;
965         list_add(&tx->tx_list, &conn->ibc_active_txs);
966
967         /* I'm still holding ibc_lock! */
968         if (conn->ibc_state != IBLND_CONN_ESTABLISHED) {
969                 rc = -ECONNABORTED;
970         } else if (tx->tx_pool->tpo_pool.po_failed ||
971                  conn->ibc_hdev != tx->tx_pool->tpo_hdev) {
972                 /* close_conn will launch failover */
973                 rc = -ENETDOWN;
974         } else {
975                 struct kib_fast_reg_descriptor *frd = tx->tx_fmr.fmr_frd;
976                 struct ib_send_wr *bad = &tx->tx_wrq[tx->tx_nwrq - 1].wr;
977                 struct ib_send_wr *wr  = &tx->tx_wrq[0].wr;
978
979                 if (frd != NULL) {
980                         if (!frd->frd_valid) {
981                                 wr = &frd->frd_inv_wr.wr;
982                                 wr->next = &frd->frd_fastreg_wr.wr;
983                         } else {
984                                 wr = &frd->frd_fastreg_wr.wr;
985                         }
986                         frd->frd_fastreg_wr.wr.next = &tx->tx_wrq[0].wr;
987                 }
988
989                 LASSERTF(bad->wr_id == kiblnd_ptr2wreqid(tx, IBLND_WID_TX),
990                          "bad wr_id %#llx, opc %d, flags %d, peer_ni: %s\n",
991                          bad->wr_id, bad->opcode, bad->send_flags,
992                          libcfs_nid2str(conn->ibc_peer->ibp_nid));
993
994                 bad = NULL;
995                 if (lnet_send_error_simulation(tx->tx_lntmsg[0], &tx->tx_hstatus))
996                         rc = -EINVAL;
997                 else
998 #ifdef HAVE_IB_POST_SEND_RECV_CONST
999                         rc = ib_post_send(conn->ibc_cmid->qp, wr,
1000                                           (const struct ib_send_wr **)&bad);
1001 #else
1002                         rc = ib_post_send(conn->ibc_cmid->qp, wr, &bad);
1003 #endif
1004         }
1005
1006         conn->ibc_last_send = ktime_get();
1007
1008         if (rc == 0)
1009                 return 0;
1010
1011         /* NB credits are transferred in the actual
1012          * message, which can only be the last work item */
1013         conn->ibc_credits += credit;
1014         conn->ibc_outstanding_credits += msg->ibm_credits;
1015         conn->ibc_nsends_posted--;
1016         if (msg->ibm_type == IBLND_MSG_NOOP)
1017                 conn->ibc_noops_posted--;
1018
1019         tx->tx_status = rc;
1020         tx->tx_waiting = 0;
1021         tx->tx_sending--;
1022
1023         done = (tx->tx_sending == 0);
1024         if (done)
1025                 list_del(&tx->tx_list);
1026
1027         spin_unlock(&conn->ibc_lock);
1028
1029         if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1030                 CERROR("Error %d posting transmit to %s\n",
1031                        rc, libcfs_nid2str(peer_ni->ibp_nid));
1032         else
1033                 CDEBUG(D_NET, "Error %d posting transmit to %s\n",
1034                        rc, libcfs_nid2str(peer_ni->ibp_nid));
1035
1036         kiblnd_close_conn(conn, rc);
1037
1038         if (done)
1039                 kiblnd_tx_done(tx);
1040
1041         spin_lock(&conn->ibc_lock);
1042
1043         return -EIO;
1044 }
1045
1046 static void
1047 kiblnd_check_sends_locked(struct kib_conn *conn)
1048 {
1049         int ver = conn->ibc_version;
1050         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
1051         struct kib_tx *tx;
1052
1053         /* Don't send anything until after the connection is established */
1054         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
1055                 CDEBUG(D_NET, "%s too soon\n",
1056                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
1057                 return;
1058         }
1059
1060         LASSERT(conn->ibc_nsends_posted <=
1061                 kiblnd_concurrent_sends(ver, ni));
1062         LASSERT (!IBLND_OOB_CAPABLE(ver) ||
1063                  conn->ibc_noops_posted <= IBLND_OOB_MSGS(ver));
1064         LASSERT (conn->ibc_reserved_credits >= 0);
1065
1066         while (conn->ibc_reserved_credits > 0 &&
1067                !list_empty(&conn->ibc_tx_queue_rsrvd)) {
1068                 tx = list_entry(conn->ibc_tx_queue_rsrvd.next,
1069                                 struct kib_tx, tx_list);
1070                 list_del(&tx->tx_list);
1071                 list_add_tail(&tx->tx_list, &conn->ibc_tx_queue);
1072                 conn->ibc_reserved_credits--;
1073         }
1074
1075         if (kiblnd_need_noop(conn)) {
1076                 spin_unlock(&conn->ibc_lock);
1077
1078                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1079                 if (tx != NULL)
1080                         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_NOOP, 0);
1081
1082                 spin_lock(&conn->ibc_lock);
1083                 if (tx != NULL)
1084                         kiblnd_queue_tx_locked(tx, conn);
1085         }
1086
1087         for (;;) {
1088                 int credit;
1089
1090                 if (!list_empty(&conn->ibc_tx_queue_nocred)) {
1091                         credit = 0;
1092                         tx = list_entry(conn->ibc_tx_queue_nocred.next,
1093                                         struct kib_tx, tx_list);
1094                 } else if (!list_empty(&conn->ibc_tx_noops)) {
1095                         LASSERT (!IBLND_OOB_CAPABLE(ver));
1096                         credit = 1;
1097                         tx = list_entry(conn->ibc_tx_noops.next,
1098                                         struct kib_tx, tx_list);
1099                 } else if (!list_empty(&conn->ibc_tx_queue)) {
1100                         credit = 1;
1101                         tx = list_entry(conn->ibc_tx_queue.next,
1102                                         struct kib_tx, tx_list);
1103                 } else
1104                         break;
1105
1106                 if (kiblnd_post_tx_locked(conn, tx, credit) != 0)
1107                         break;
1108         }
1109 }
1110
1111 static void
1112 kiblnd_tx_complete(struct kib_tx *tx, int status)
1113 {
1114         int           failed = (status != IB_WC_SUCCESS);
1115         struct kib_conn   *conn = tx->tx_conn;
1116         int           idle;
1117
1118         if (tx->tx_sending <= 0) {
1119                 CERROR("Received an event on a freed tx: %p status %d\n",
1120                        tx, tx->tx_status);
1121                 return;
1122         }
1123
1124         if (failed) {
1125                 if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1126                         CNETERR("Tx -> %s cookie %#llx"
1127                                 " sending %d waiting %d: failed %d\n",
1128                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
1129                                 tx->tx_cookie, tx->tx_sending, tx->tx_waiting,
1130                                 status);
1131
1132                 kiblnd_close_conn(conn, -EIO);
1133         } else {
1134                 kiblnd_peer_alive(conn->ibc_peer);
1135         }
1136
1137         spin_lock(&conn->ibc_lock);
1138
1139         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
1140          * gets to free it, which also drops its ref on 'conn'. */
1141
1142         tx->tx_sending--;
1143         conn->ibc_nsends_posted--;
1144         if (tx->tx_msg->ibm_type == IBLND_MSG_NOOP)
1145                 conn->ibc_noops_posted--;
1146
1147         if (failed) {
1148                 tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
1149                 tx->tx_waiting = 0;             /* don't wait for peer_ni */
1150                 tx->tx_status = -EIO;
1151         }
1152
1153         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
1154                !tx->tx_waiting &&               /* Not waiting for peer_ni */
1155                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
1156         if (idle)
1157                 list_del(&tx->tx_list);
1158
1159         kiblnd_check_sends_locked(conn);
1160         spin_unlock(&conn->ibc_lock);
1161
1162         if (idle)
1163                 kiblnd_tx_done(tx);
1164 }
1165
1166 static void
1167 kiblnd_init_tx_msg(struct lnet_ni *ni, struct kib_tx *tx, int type,
1168                    int body_nob)
1169 {
1170         struct kib_hca_dev *hdev = tx->tx_pool->tpo_hdev;
1171         struct ib_sge *sge = &tx->tx_msgsge;
1172         struct ib_rdma_wr *wrq;
1173         int nob = offsetof(struct kib_msg, ibm_u) + body_nob;
1174 #ifdef HAVE_IB_GET_DMA_MR
1175         struct ib_mr *mr = hdev->ibh_mrs;
1176 #endif
1177
1178         LASSERT(tx->tx_nwrq >= 0);
1179         LASSERT(tx->tx_nwrq < IBLND_MAX_RDMA_FRAGS + 1);
1180         LASSERT(nob <= IBLND_MSG_SIZE);
1181 #ifdef HAVE_IB_GET_DMA_MR
1182         LASSERT(mr != NULL);
1183 #endif
1184
1185         kiblnd_init_msg(tx->tx_msg, type, body_nob);
1186
1187 #ifdef HAVE_IB_GET_DMA_MR
1188         sge->lkey   = mr->lkey;
1189 #else
1190         sge->lkey   = hdev->ibh_pd->local_dma_lkey;
1191 #endif
1192         sge->addr   = tx->tx_msgaddr;
1193         sge->length = nob;
1194
1195         wrq = &tx->tx_wrq[tx->tx_nwrq];
1196         memset(wrq, 0, sizeof(*wrq));
1197
1198         wrq->wr.next            = NULL;
1199         wrq->wr.wr_id           = kiblnd_ptr2wreqid(tx, IBLND_WID_TX);
1200         wrq->wr.sg_list         = sge;
1201         wrq->wr.num_sge         = 1;
1202         wrq->wr.opcode          = IB_WR_SEND;
1203         wrq->wr.send_flags      = IB_SEND_SIGNALED;
1204
1205         tx->tx_nwrq++;
1206 }
1207
1208 static int
1209 kiblnd_init_rdma(struct kib_conn *conn, struct kib_tx *tx, int type,
1210                  int resid, struct kib_rdma_desc *dstrd, u64 dstcookie)
1211 {
1212         struct kib_msg *ibmsg = tx->tx_msg;
1213         struct kib_rdma_desc *srcrd = tx->tx_rd;
1214         struct ib_rdma_wr *wrq = NULL;
1215         struct ib_sge     *sge;
1216         int                rc  = resid;
1217         int                srcidx;
1218         int                dstidx;
1219         int                sge_nob;
1220         int                wrq_sge;
1221
1222         LASSERT(!in_interrupt());
1223         LASSERT(tx->tx_nwrq == 0 && tx->tx_nsge == 0);
1224         LASSERT(type == IBLND_MSG_GET_DONE || type == IBLND_MSG_PUT_DONE);
1225
1226         for (srcidx = dstidx = wrq_sge = sge_nob = 0;
1227              resid > 0; resid -= sge_nob) {
1228                 int     prev = dstidx;
1229
1230                 if (srcidx >= srcrd->rd_nfrags) {
1231                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1232                         rc = -EPROTO;
1233                         break;
1234                 }
1235
1236                 if (dstidx >= dstrd->rd_nfrags) {
1237                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1238                         rc = -EPROTO;
1239                         break;
1240                 }
1241
1242                 if (tx->tx_nwrq >= conn->ibc_max_frags) {
1243                         CERROR("RDMA has too many fragments for peer_ni %s (%d), "
1244                                "src idx/frags: %d/%d dst idx/frags: %d/%d\n",
1245                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
1246                                conn->ibc_max_frags,
1247                                srcidx, srcrd->rd_nfrags,
1248                                dstidx, dstrd->rd_nfrags);
1249                         rc = -EMSGSIZE;
1250                         break;
1251                 }
1252
1253                 sge_nob = MIN(MIN(kiblnd_rd_frag_size(srcrd, srcidx),
1254                                   kiblnd_rd_frag_size(dstrd, dstidx)), resid);
1255
1256                 sge = &tx->tx_sge[tx->tx_nsge];
1257                 sge->addr   = kiblnd_rd_frag_addr(srcrd, srcidx);
1258                 sge->lkey   = kiblnd_rd_frag_key(srcrd, srcidx);
1259                 sge->length = sge_nob;
1260
1261                 if (wrq_sge == 0) {
1262                         wrq = &tx->tx_wrq[tx->tx_nwrq];
1263
1264                         wrq->wr.next    = &(wrq + 1)->wr;
1265                         wrq->wr.wr_id   = kiblnd_ptr2wreqid(tx, IBLND_WID_RDMA);
1266                         wrq->wr.sg_list = sge;
1267                         wrq->wr.opcode  = IB_WR_RDMA_WRITE;
1268                         wrq->wr.send_flags = 0;
1269
1270 #ifdef HAVE_IB_RDMA_WR
1271                         wrq->remote_addr        = kiblnd_rd_frag_addr(dstrd,
1272                                                                       dstidx);
1273                         wrq->rkey               = kiblnd_rd_frag_key(dstrd,
1274                                                                      dstidx);
1275 #else
1276                         wrq->wr.wr.rdma.remote_addr = kiblnd_rd_frag_addr(dstrd,
1277                                                                         dstidx);
1278                         wrq->wr.wr.rdma.rkey    = kiblnd_rd_frag_key(dstrd,
1279                                                                      dstidx);
1280 #endif
1281                 }
1282
1283                 srcidx = kiblnd_rd_consume_frag(srcrd, srcidx, sge_nob);
1284                 dstidx = kiblnd_rd_consume_frag(dstrd, dstidx, sge_nob);
1285
1286                 wrq_sge++;
1287                 if (wrq_sge == *kiblnd_tunables.kib_wrq_sge || dstidx != prev) {
1288                         tx->tx_nwrq++;
1289                         wrq->wr.num_sge = wrq_sge;
1290                         wrq_sge = 0;
1291                 }
1292                 tx->tx_nsge++;
1293         }
1294
1295         if (rc < 0)     /* no RDMA if completing with failure */
1296                 tx->tx_nwrq = tx->tx_nsge = 0;
1297
1298         ibmsg->ibm_u.completion.ibcm_status = rc;
1299         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1300         kiblnd_init_tx_msg(conn->ibc_peer->ibp_ni, tx,
1301                            type, sizeof(struct kib_completion_msg));
1302
1303         return rc;
1304 }
1305
1306 static void
1307 kiblnd_queue_tx_locked(struct kib_tx *tx, struct kib_conn *conn)
1308 {
1309         struct list_head *q;
1310         s64 timeout_ns;
1311
1312         LASSERT(tx->tx_nwrq > 0);       /* work items set up */
1313         LASSERT(!tx->tx_queued);        /* not queued for sending already */
1314         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1315
1316         if (conn->ibc_state >= IBLND_CONN_DISCONNECTED) {
1317                 tx->tx_status = -ECONNABORTED;
1318                 tx->tx_waiting = 0;
1319                 if (tx->tx_conn != NULL) {
1320                         /* PUT_DONE first attached to conn as a PUT_REQ */
1321                         LASSERT(tx->tx_conn == conn);
1322                         LASSERT(tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1323                         tx->tx_conn = NULL;
1324                         kiblnd_conn_decref(conn);
1325                 }
1326                 list_add(&tx->tx_list, &conn->ibc_zombie_txs);
1327
1328                 return;
1329         }
1330
1331         timeout_ns = lnet_get_lnd_timeout() * NSEC_PER_SEC;
1332         tx->tx_queued = 1;
1333         tx->tx_deadline = ktime_add_ns(ktime_get(), timeout_ns);
1334
1335         if (tx->tx_conn == NULL) {
1336                 kiblnd_conn_addref(conn);
1337                 tx->tx_conn = conn;
1338                 LASSERT (tx->tx_msg->ibm_type != IBLND_MSG_PUT_DONE);
1339         } else {
1340                 /* PUT_DONE first attached to conn as a PUT_REQ */
1341                 LASSERT (tx->tx_conn == conn);
1342                 LASSERT (tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1343         }
1344
1345         switch (tx->tx_msg->ibm_type) {
1346         default:
1347                 LBUG();
1348
1349         case IBLND_MSG_PUT_REQ:
1350         case IBLND_MSG_GET_REQ:
1351                 q = &conn->ibc_tx_queue_rsrvd;
1352                 break;
1353
1354         case IBLND_MSG_PUT_NAK:
1355         case IBLND_MSG_PUT_ACK:
1356         case IBLND_MSG_PUT_DONE:
1357         case IBLND_MSG_GET_DONE:
1358                 q = &conn->ibc_tx_queue_nocred;
1359                 break;
1360
1361         case IBLND_MSG_NOOP:
1362                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
1363                         q = &conn->ibc_tx_queue_nocred;
1364                 else
1365                         q = &conn->ibc_tx_noops;
1366                 break;
1367
1368         case IBLND_MSG_IMMEDIATE:
1369                 q = &conn->ibc_tx_queue;
1370                 break;
1371         }
1372
1373         list_add_tail(&tx->tx_list, q);
1374 }
1375
1376 static void
1377 kiblnd_queue_tx(struct kib_tx *tx, struct kib_conn *conn)
1378 {
1379         spin_lock(&conn->ibc_lock);
1380         kiblnd_queue_tx_locked(tx, conn);
1381         kiblnd_check_sends_locked(conn);
1382         spin_unlock(&conn->ibc_lock);
1383 }
1384
1385 static int kiblnd_resolve_addr(struct rdma_cm_id *cmid,
1386                                struct sockaddr_in *srcaddr,
1387                                struct sockaddr_in *dstaddr,
1388                                int timeout_ms)
1389 {
1390         unsigned short port;
1391         int rc;
1392
1393         /* allow the port to be reused */
1394         rc = rdma_set_reuseaddr(cmid, 1);
1395         if (rc != 0) {
1396                 CERROR("Unable to set reuse on cmid: %d\n", rc);
1397                 return rc;
1398         }
1399
1400         /* look for a free privileged port */
1401         for (port = PROT_SOCK-1; port > 0; port--) {
1402                 srcaddr->sin_port = htons(port);
1403                 rc = rdma_resolve_addr(cmid,
1404                                        (struct sockaddr *)srcaddr,
1405                                        (struct sockaddr *)dstaddr,
1406                                        timeout_ms);
1407                 if (rc == 0) {
1408                         CDEBUG(D_NET, "bound to port %hu\n", port);
1409                         return 0;
1410                 } else if (rc == -EADDRINUSE || rc == -EADDRNOTAVAIL) {
1411                         CDEBUG(D_NET, "bind to port %hu failed: %d\n",
1412                                port, rc);
1413                 } else {
1414                         return rc;
1415                 }
1416         }
1417
1418         CERROR("Failed to bind to a free privileged port\n");
1419         return rc;
1420 }
1421
1422 static void
1423 kiblnd_connect_peer(struct kib_peer_ni *peer_ni)
1424 {
1425         struct rdma_cm_id *cmid;
1426         struct kib_dev *dev;
1427         struct kib_net *net = peer_ni->ibp_ni->ni_data;
1428         struct sockaddr_in srcaddr;
1429         struct sockaddr_in dstaddr;
1430         int rc;
1431
1432         LASSERT (net != NULL);
1433         LASSERT (peer_ni->ibp_connecting > 0);
1434
1435         cmid = kiblnd_rdma_create_id(peer_ni->ibp_ni->ni_net_ns,
1436                                      kiblnd_cm_callback, peer_ni,
1437                                      RDMA_PS_TCP, IB_QPT_RC);
1438
1439         if (IS_ERR(cmid)) {
1440                 CERROR("Can't create CMID for %s: %ld\n",
1441                        libcfs_nid2str(peer_ni->ibp_nid), PTR_ERR(cmid));
1442                 rc = PTR_ERR(cmid);
1443                 goto failed;
1444         }
1445
1446         dev = net->ibn_dev;
1447         memset(&srcaddr, 0, sizeof(srcaddr));
1448         srcaddr.sin_family = AF_INET;
1449         srcaddr.sin_addr.s_addr = htonl(dev->ibd_ifip);
1450
1451         memset(&dstaddr, 0, sizeof(dstaddr));
1452         dstaddr.sin_family = AF_INET;
1453         dstaddr.sin_port = htons(*kiblnd_tunables.kib_service);
1454         dstaddr.sin_addr.s_addr = htonl(LNET_NIDADDR(peer_ni->ibp_nid));
1455
1456         kiblnd_peer_addref(peer_ni);               /* cmid's ref */
1457
1458         if (*kiblnd_tunables.kib_use_priv_port) {
1459                 rc = kiblnd_resolve_addr(cmid, &srcaddr, &dstaddr,
1460                                          lnet_get_lnd_timeout() * 1000);
1461         } else {
1462                 rc = rdma_resolve_addr(cmid,
1463                                        (struct sockaddr *)&srcaddr,
1464                                        (struct sockaddr *)&dstaddr,
1465                                        lnet_get_lnd_timeout() * 1000);
1466         }
1467         if (rc != 0) {
1468                 /* Can't initiate address resolution:  */
1469                 CERROR("Can't resolve addr for %s: %d\n",
1470                        libcfs_nid2str(peer_ni->ibp_nid), rc);
1471                 goto failed2;
1472         }
1473
1474         return;
1475
1476  failed2:
1477         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1478         kiblnd_peer_decref(peer_ni);               /* cmid's ref */
1479         rdma_destroy_id(cmid);
1480         return;
1481  failed:
1482         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1483 }
1484
1485 bool
1486 kiblnd_reconnect_peer(struct kib_peer_ni *peer_ni)
1487 {
1488         rwlock_t         *glock = &kiblnd_data.kib_global_lock;
1489         char             *reason = NULL;
1490         struct list_head  txs;
1491         unsigned long     flags;
1492
1493         INIT_LIST_HEAD(&txs);
1494
1495         write_lock_irqsave(glock, flags);
1496         if (peer_ni->ibp_reconnecting == 0) {
1497                 if (peer_ni->ibp_accepting)
1498                         reason = "accepting";
1499                 else if (peer_ni->ibp_connecting)
1500                         reason = "connecting";
1501                 else if (!list_empty(&peer_ni->ibp_conns))
1502                         reason = "connected";
1503                 else /* connected then closed */
1504                         reason = "closed";
1505
1506                 goto no_reconnect;
1507         }
1508
1509         if (peer_ni->ibp_accepting)
1510                 CNETERR("Detecting race between accepting and reconnecting\n");
1511         peer_ni->ibp_reconnecting--;
1512
1513         if (!kiblnd_peer_active(peer_ni)) {
1514                 list_splice_init(&peer_ni->ibp_tx_queue, &txs);
1515                 reason = "unlinked";
1516                 goto no_reconnect;
1517         }
1518
1519         peer_ni->ibp_connecting++;
1520         peer_ni->ibp_reconnected++;
1521
1522         write_unlock_irqrestore(glock, flags);
1523
1524         kiblnd_connect_peer(peer_ni);
1525         return true;
1526
1527  no_reconnect:
1528         write_unlock_irqrestore(glock, flags);
1529
1530         CWARN("Abort reconnection of %s: %s\n",
1531               libcfs_nid2str(peer_ni->ibp_nid), reason);
1532         kiblnd_txlist_done(&txs, -ECONNABORTED,
1533                            LNET_MSG_STATUS_LOCAL_ABORTED);
1534         return false;
1535 }
1536
1537 void
1538 kiblnd_launch_tx(struct lnet_ni *ni, struct kib_tx *tx, lnet_nid_t nid)
1539 {
1540         struct kib_peer_ni *peer_ni;
1541         struct kib_peer_ni *peer2;
1542         struct kib_conn *conn;
1543         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
1544         unsigned long      flags;
1545         int                rc;
1546         int                i;
1547         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
1548
1549         /* If I get here, I've committed to send, so I complete the tx with
1550          * failure on any problems */
1551
1552         LASSERT (tx == NULL || tx->tx_conn == NULL); /* only set when assigned a conn */
1553         LASSERT (tx == NULL || tx->tx_nwrq > 0);     /* work items have been set up */
1554
1555         /* First time, just use a read lock since I expect to find my peer_ni
1556          * connected */
1557         read_lock_irqsave(g_lock, flags);
1558
1559         peer_ni = kiblnd_find_peer_locked(ni, nid);
1560         if (peer_ni != NULL && !list_empty(&peer_ni->ibp_conns)) {
1561                 /* Found a peer_ni with an established connection */
1562                 conn = kiblnd_get_conn_locked(peer_ni);
1563                 kiblnd_conn_addref(conn); /* 1 ref for me... */
1564
1565                 read_unlock_irqrestore(g_lock, flags);
1566
1567                 if (tx != NULL)
1568                         kiblnd_queue_tx(tx, conn);
1569                 kiblnd_conn_decref(conn); /* ...to here */
1570                 return;
1571         }
1572
1573         read_unlock(g_lock);
1574         /* Re-try with a write lock */
1575         write_lock(g_lock);
1576
1577         peer_ni = kiblnd_find_peer_locked(ni, nid);
1578         if (peer_ni != NULL) {
1579                 if (list_empty(&peer_ni->ibp_conns)) {
1580                         /* found a peer_ni, but it's still connecting... */
1581                         LASSERT(kiblnd_peer_connecting(peer_ni));
1582                         if (tx != NULL)
1583                                 list_add_tail(&tx->tx_list,
1584                                                   &peer_ni->ibp_tx_queue);
1585                         write_unlock_irqrestore(g_lock, flags);
1586                 } else {
1587                         conn = kiblnd_get_conn_locked(peer_ni);
1588                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1589
1590                         write_unlock_irqrestore(g_lock, flags);
1591
1592                         if (tx != NULL)
1593                                 kiblnd_queue_tx(tx, conn);
1594                         kiblnd_conn_decref(conn); /* ...to here */
1595                 }
1596                 return;
1597         }
1598
1599         write_unlock_irqrestore(g_lock, flags);
1600
1601         /* Allocate a peer_ni ready to add to the peer_ni table and retry */
1602         rc = kiblnd_create_peer(ni, &peer_ni, nid);
1603         if (rc != 0) {
1604                 CERROR("Can't create peer_ni %s\n", libcfs_nid2str(nid));
1605                 if (tx != NULL) {
1606                         tx->tx_status = -EHOSTUNREACH;
1607                         tx->tx_waiting = 0;
1608                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1609                         kiblnd_tx_done(tx);
1610                 }
1611                 return;
1612         }
1613
1614         write_lock_irqsave(g_lock, flags);
1615
1616         peer2 = kiblnd_find_peer_locked(ni, nid);
1617         if (peer2 != NULL) {
1618                 if (list_empty(&peer2->ibp_conns)) {
1619                         /* found a peer_ni, but it's still connecting... */
1620                         LASSERT(kiblnd_peer_connecting(peer2));
1621                         if (tx != NULL)
1622                                 list_add_tail(&tx->tx_list,
1623                                                   &peer2->ibp_tx_queue);
1624                         write_unlock_irqrestore(g_lock, flags);
1625                 } else {
1626                         conn = kiblnd_get_conn_locked(peer2);
1627                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1628
1629                         write_unlock_irqrestore(g_lock, flags);
1630
1631                         if (tx != NULL)
1632                                 kiblnd_queue_tx(tx, conn);
1633                         kiblnd_conn_decref(conn); /* ...to here */
1634                 }
1635
1636                 kiblnd_peer_decref(peer_ni);
1637                 return;
1638         }
1639
1640         /* Brand new peer_ni */
1641         LASSERT(peer_ni->ibp_connecting == 0);
1642         tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
1643         peer_ni->ibp_connecting = tunables->lnd_conns_per_peer;
1644
1645         /* always called with a ref on ni, which prevents ni being shutdown */
1646         LASSERT(((struct kib_net *)ni->ni_data)->ibn_shutdown == 0);
1647
1648         if (tx != NULL)
1649                 list_add_tail(&tx->tx_list, &peer_ni->ibp_tx_queue);
1650
1651         kiblnd_peer_addref(peer_ni);
1652         list_add_tail(&peer_ni->ibp_list, kiblnd_nid2peerlist(nid));
1653
1654         write_unlock_irqrestore(g_lock, flags);
1655
1656         for (i = 0; i < tunables->lnd_conns_per_peer; i++)
1657                 kiblnd_connect_peer(peer_ni);
1658         kiblnd_peer_decref(peer_ni);
1659 }
1660
1661 int
1662 kiblnd_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg)
1663 {
1664         struct lnet_hdr *hdr = &lntmsg->msg_hdr;
1665         int               type = lntmsg->msg_type;
1666         struct lnet_process_id target = lntmsg->msg_target;
1667         int               target_is_router = lntmsg->msg_target_is_router;
1668         int               routing = lntmsg->msg_routing;
1669         unsigned int      payload_niov = lntmsg->msg_niov;
1670         struct kvec      *payload_iov = lntmsg->msg_iov;
1671         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
1672         unsigned int      payload_offset = lntmsg->msg_offset;
1673         unsigned int      payload_nob = lntmsg->msg_len;
1674         struct kib_msg *ibmsg;
1675         struct kib_rdma_desc *rd;
1676         struct kib_tx *tx;
1677         int               nob;
1678         int               rc;
1679
1680         /* NB 'private' is different depending on what we're sending.... */
1681
1682         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1683                payload_nob, payload_niov, libcfs_id2str(target));
1684
1685         LASSERT (payload_nob == 0 || payload_niov > 0);
1686         LASSERT (payload_niov <= LNET_MAX_IOV);
1687
1688         /* Thread context */
1689         LASSERT (!in_interrupt());
1690         /* payload is either all vaddrs or all pages */
1691         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1692
1693         switch (type) {
1694         default:
1695                 LBUG();
1696                 return (-EIO);
1697
1698         case LNET_MSG_ACK:
1699                 LASSERT (payload_nob == 0);
1700                 break;
1701
1702         case LNET_MSG_GET:
1703                 if (routing || target_is_router)
1704                         break;                  /* send IMMEDIATE */
1705
1706                 /* is the REPLY message too small for RDMA? */
1707                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1708                 if (nob <= IBLND_MSG_SIZE)
1709                         break;                  /* send IMMEDIATE */
1710
1711                 tx = kiblnd_get_idle_tx(ni, target.nid);
1712                 if (tx == NULL) {
1713                         CERROR("Can't allocate txd for GET to %s\n",
1714                                libcfs_nid2str(target.nid));
1715                         return -ENOMEM;
1716                 }
1717
1718                 ibmsg = tx->tx_msg;
1719                 rd = &ibmsg->ibm_u.get.ibgm_rd;
1720                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0)
1721                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1722                                                  lntmsg->msg_md->md_niov,
1723                                                  lntmsg->msg_md->md_iov.iov,
1724                                                  0, lntmsg->msg_md->md_length);
1725                 else
1726                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1727                                                   lntmsg->msg_md->md_niov,
1728                                                   lntmsg->msg_md->md_iov.kiov,
1729                                                   0, lntmsg->msg_md->md_length);
1730                 if (rc != 0) {
1731                         CERROR("Can't setup GET sink for %s: %d\n",
1732                                libcfs_nid2str(target.nid), rc);
1733                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1734                         kiblnd_tx_done(tx);
1735                         return -EIO;
1736                 }
1737
1738                 nob = offsetof(struct kib_get_msg, ibgm_rd.rd_frags[rd->rd_nfrags]);
1739                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1740                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1741
1742                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1743
1744                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1745                 if (tx->tx_lntmsg[1] == NULL) {
1746                         CERROR("Can't create reply for GET -> %s\n",
1747                                libcfs_nid2str(target.nid));
1748                         kiblnd_tx_done(tx);
1749                         return -EIO;
1750                 }
1751
1752                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1753                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1754                 kiblnd_launch_tx(ni, tx, target.nid);
1755                 return 0;
1756
1757         case LNET_MSG_REPLY:
1758         case LNET_MSG_PUT:
1759                 /* Is the payload small enough not to need RDMA? */
1760                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob]);
1761                 if (nob <= IBLND_MSG_SIZE)
1762                         break;                  /* send IMMEDIATE */
1763
1764                 tx = kiblnd_get_idle_tx(ni, target.nid);
1765                 if (tx == NULL) {
1766                         CERROR("Can't allocate %s txd for %s\n",
1767                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1768                                libcfs_nid2str(target.nid));
1769                         return -ENOMEM;
1770                 }
1771
1772                 if (payload_kiov == NULL)
1773                         rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1774                                                  payload_niov, payload_iov,
1775                                                  payload_offset, payload_nob);
1776                 else
1777                         rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1778                                                   payload_niov, payload_kiov,
1779                                                   payload_offset, payload_nob);
1780                 if (rc != 0) {
1781                         CERROR("Can't setup PUT src for %s: %d\n",
1782                                libcfs_nid2str(target.nid), rc);
1783                         kiblnd_tx_done(tx);
1784                         return -EIO;
1785                 }
1786
1787                 ibmsg = tx->tx_msg;
1788                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1789                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1790                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ,
1791                                    sizeof(struct kib_putreq_msg));
1792
1793                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1794                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1795                 kiblnd_launch_tx(ni, tx, target.nid);
1796                 return 0;
1797         }
1798
1799         /* send IMMEDIATE */
1800         LASSERT(offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob])
1801                 <= IBLND_MSG_SIZE);
1802
1803         tx = kiblnd_get_idle_tx(ni, target.nid);
1804         if (tx == NULL) {
1805                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1806                         type, libcfs_nid2str(target.nid));
1807                 return -ENOMEM;
1808         }
1809
1810         ibmsg = tx->tx_msg;
1811         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1812
1813         if (payload_kiov != NULL)
1814                 lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1815                                     offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1816                                     payload_niov, payload_kiov,
1817                                     payload_offset, payload_nob);
1818         else
1819                 lnet_copy_iov2flat(IBLND_MSG_SIZE, ibmsg,
1820                                    offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1821                                    payload_niov, payload_iov,
1822                                    payload_offset, payload_nob);
1823
1824         nob = offsetof(struct kib_immediate_msg, ibim_payload[payload_nob]);
1825         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1826
1827         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1828         kiblnd_launch_tx(ni, tx, target.nid);
1829         return 0;
1830 }
1831
1832 static void
1833 kiblnd_reply(struct lnet_ni *ni, struct kib_rx *rx, struct lnet_msg *lntmsg)
1834 {
1835         struct lnet_process_id target = lntmsg->msg_target;
1836         unsigned int      niov = lntmsg->msg_niov;
1837         struct kvec      *iov = lntmsg->msg_iov;
1838         lnet_kiov_t      *kiov = lntmsg->msg_kiov;
1839         unsigned int      offset = lntmsg->msg_offset;
1840         unsigned int      nob = lntmsg->msg_len;
1841         struct kib_tx *tx;
1842         int               rc;
1843
1844         tx = kiblnd_get_idle_tx(ni, rx->rx_conn->ibc_peer->ibp_nid);
1845         if (tx == NULL) {
1846                 CERROR("Can't get tx for REPLY to %s\n",
1847                        libcfs_nid2str(target.nid));
1848                 goto failed_0;
1849         }
1850
1851         if (nob == 0)
1852                 rc = 0;
1853         else if (kiov == NULL)
1854                 rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1855                                          niov, iov, offset, nob);
1856         else
1857                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1858                                           niov, kiov, offset, nob);
1859
1860         if (rc != 0) {
1861                 CERROR("Can't setup GET src for %s: %d\n",
1862                        libcfs_nid2str(target.nid), rc);
1863                 goto failed_1;
1864         }
1865
1866         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1867                               IBLND_MSG_GET_DONE, nob,
1868                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1869                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1870         if (rc < 0) {
1871                 CERROR("Can't setup rdma for GET from %s: %d\n",
1872                        libcfs_nid2str(target.nid), rc);
1873                 goto failed_1;
1874         }
1875
1876         if (nob == 0) {
1877                 /* No RDMA: local completion may happen now! */
1878                 lnet_finalize(lntmsg, 0);
1879         } else {
1880                 /* RDMA: lnet_finalize(lntmsg) when it
1881                  * completes */
1882                 tx->tx_lntmsg[0] = lntmsg;
1883         }
1884
1885         kiblnd_queue_tx(tx, rx->rx_conn);
1886         return;
1887
1888
1889 failed_1:
1890         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1891         kiblnd_tx_done(tx);
1892 failed_0:
1893         lnet_finalize(lntmsg, -EIO);
1894 }
1895
1896 int
1897 kiblnd_recv(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg,
1898             int delayed, unsigned int niov, struct kvec *iov, lnet_kiov_t *kiov,
1899             unsigned int offset, unsigned int mlen, unsigned int rlen)
1900 {
1901         struct kib_rx *rx = private;
1902         struct kib_msg *rxmsg = rx->rx_msg;
1903         struct kib_conn *conn = rx->rx_conn;
1904         struct kib_tx *tx;
1905         __u64        ibprm_cookie;
1906         int          nob;
1907         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1908         int          rc = 0;
1909
1910         LASSERT (mlen <= rlen);
1911         LASSERT (!in_interrupt());
1912         /* Either all pages or all vaddrs */
1913         LASSERT (!(kiov != NULL && iov != NULL));
1914
1915         switch (rxmsg->ibm_type) {
1916         default:
1917                 LBUG();
1918
1919         case IBLND_MSG_IMMEDIATE:
1920                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[rlen]);
1921                 if (nob > rx->rx_nob) {
1922                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1923                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1924                                 nob, rx->rx_nob);
1925                         rc = -EPROTO;
1926                         break;
1927                 }
1928
1929                 if (kiov != NULL)
1930                         lnet_copy_flat2kiov(niov, kiov, offset,
1931                                             IBLND_MSG_SIZE, rxmsg,
1932                                             offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1933                                             mlen);
1934                 else
1935                         lnet_copy_flat2iov(niov, iov, offset,
1936                                            IBLND_MSG_SIZE, rxmsg,
1937                                            offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1938                                            mlen);
1939                 lnet_finalize(lntmsg, 0);
1940                 break;
1941
1942         case IBLND_MSG_PUT_REQ: {
1943                 struct kib_msg  *txmsg;
1944                 struct kib_rdma_desc *rd;
1945                 ibprm_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1946
1947                 if (mlen == 0) {
1948                         lnet_finalize(lntmsg, 0);
1949                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1950                                                0, ibprm_cookie);
1951                         break;
1952                 }
1953
1954                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1955                 if (tx == NULL) {
1956                         CERROR("Can't allocate tx for %s\n",
1957                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1958                         /* Not replying will break the connection */
1959                         rc = -ENOMEM;
1960                         break;
1961                 }
1962
1963                 txmsg = tx->tx_msg;
1964                 rd = &txmsg->ibm_u.putack.ibpam_rd;
1965                 if (kiov == NULL)
1966                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1967                                                  niov, iov, offset, mlen);
1968                 else
1969                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1970                                                   niov, kiov, offset, mlen);
1971                 if (rc != 0) {
1972                         CERROR("Can't setup PUT sink for %s: %d\n",
1973                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1974                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1975                         kiblnd_tx_done(tx);
1976                         /* tell peer_ni it's over */
1977                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1978                                                rc, ibprm_cookie);
1979                         break;
1980                 }
1981
1982                 nob = offsetof(struct kib_putack_msg, ibpam_rd.rd_frags[rd->rd_nfrags]);
1983                 txmsg->ibm_u.putack.ibpam_src_cookie = ibprm_cookie;
1984                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1985
1986                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1987
1988                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1989                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1990                 kiblnd_queue_tx(tx, conn);
1991
1992                 /* reposted buffer reserved for PUT_DONE */
1993                 post_credit = IBLND_POSTRX_NO_CREDIT;
1994                 break;
1995                 }
1996
1997         case IBLND_MSG_GET_REQ:
1998                 if (lntmsg != NULL) {
1999                         /* Optimized GET; RDMA lntmsg's payload */
2000                         kiblnd_reply(ni, rx, lntmsg);
2001                 } else {
2002                         /* GET didn't match anything */
2003                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
2004                                                -ENODATA,
2005                                                rxmsg->ibm_u.get.ibgm_cookie);
2006                 }
2007                 break;
2008         }
2009
2010         kiblnd_post_rx(rx, post_credit);
2011         return rc;
2012 }
2013
2014 int
2015 kiblnd_thread_start(int (*fn)(void *arg), void *arg, char *name)
2016 {
2017         struct task_struct *task = kthread_run(fn, arg, name);
2018
2019         if (IS_ERR(task))
2020                 return PTR_ERR(task);
2021
2022         atomic_inc(&kiblnd_data.kib_nthreads);
2023         return 0;
2024 }
2025
2026 static void
2027 kiblnd_thread_fini (void)
2028 {
2029         atomic_dec (&kiblnd_data.kib_nthreads);
2030 }
2031
2032 static void
2033 kiblnd_peer_alive(struct kib_peer_ni *peer_ni)
2034 {
2035         /* This is racy, but everyone's only writing ktime_get_seconds() */
2036         peer_ni->ibp_last_alive = ktime_get_seconds();
2037         smp_mb();
2038 }
2039
2040 static void
2041 kiblnd_peer_notify(struct kib_peer_ni *peer_ni)
2042 {
2043         int           error = 0;
2044         time64_t last_alive = 0;
2045         unsigned long flags;
2046
2047         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2048
2049         if (kiblnd_peer_idle(peer_ni) && peer_ni->ibp_error != 0) {
2050                 error = peer_ni->ibp_error;
2051                 peer_ni->ibp_error = 0;
2052
2053                 last_alive = peer_ni->ibp_last_alive;
2054         }
2055
2056         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2057
2058         if (error != 0)
2059                 lnet_notify(peer_ni->ibp_ni,
2060                             peer_ni->ibp_nid, 0, last_alive);
2061 }
2062
2063 void
2064 kiblnd_close_conn_locked(struct kib_conn *conn, int error)
2065 {
2066         /* This just does the immediate housekeeping.  'error' is zero for a
2067          * normal shutdown which can happen only after the connection has been
2068          * established.  If the connection is established, schedule the
2069          * connection to be finished off by the connd.  Otherwise the connd is
2070          * already dealing with it (either to set it up or tear it down).
2071          * Caller holds kib_global_lock exclusively in irq context */
2072         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2073         struct kib_dev *dev;
2074         unsigned long flags;
2075
2076         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2077
2078         if (error != 0 && conn->ibc_comms_error == 0)
2079                 conn->ibc_comms_error = error;
2080
2081         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
2082                 return; /* already being handled  */
2083
2084         if (error == 0 &&
2085             list_empty(&conn->ibc_tx_noops) &&
2086             list_empty(&conn->ibc_tx_queue) &&
2087             list_empty(&conn->ibc_tx_queue_rsrvd) &&
2088             list_empty(&conn->ibc_tx_queue_nocred) &&
2089             list_empty(&conn->ibc_active_txs)) {
2090                 CDEBUG(D_NET, "closing conn to %s\n", 
2091                        libcfs_nid2str(peer_ni->ibp_nid));
2092         } else {
2093                 CNETERR("Closing conn to %s: error %d%s%s%s%s%s\n",
2094                        libcfs_nid2str(peer_ni->ibp_nid), error,
2095                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
2096                        list_empty(&conn->ibc_tx_noops) ? "" : "(sending_noops)",
2097                        list_empty(&conn->ibc_tx_queue_rsrvd) ?
2098                                                 "" : "(sending_rsrvd)",
2099                        list_empty(&conn->ibc_tx_queue_nocred) ?
2100                                                  "" : "(sending_nocred)",
2101                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
2102         }
2103
2104         dev = ((struct kib_net *)peer_ni->ibp_ni->ni_data)->ibn_dev;
2105         if (peer_ni->ibp_next_conn == conn)
2106                 /* clear next_conn so it won't be used */
2107                 peer_ni->ibp_next_conn = NULL;
2108         list_del(&conn->ibc_list);
2109         /* connd (see below) takes over ibc_list's ref */
2110
2111         if (list_empty(&peer_ni->ibp_conns) &&    /* no more conns */
2112             kiblnd_peer_active(peer_ni)) {         /* still in peer_ni table */
2113                 kiblnd_unlink_peer_locked(peer_ni);
2114
2115                 /* set/clear error on last conn */
2116                 peer_ni->ibp_error = conn->ibc_comms_error;
2117         }
2118
2119         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
2120
2121         if (error != 0 &&
2122             kiblnd_dev_can_failover(dev)) {
2123                 list_add_tail(&dev->ibd_fail_list,
2124                               &kiblnd_data.kib_failed_devs);
2125                 wake_up(&kiblnd_data.kib_failover_waitq);
2126         }
2127
2128         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2129
2130         list_add_tail(&conn->ibc_list, &kiblnd_data.kib_connd_conns);
2131         wake_up(&kiblnd_data.kib_connd_waitq);
2132
2133         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
2134 }
2135
2136 void
2137 kiblnd_close_conn(struct kib_conn *conn, int error)
2138 {
2139         unsigned long flags;
2140
2141         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2142
2143         kiblnd_close_conn_locked(conn, error);
2144
2145         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2146 }
2147
2148 static void
2149 kiblnd_handle_early_rxs(struct kib_conn *conn)
2150 {
2151         unsigned long flags;
2152         struct kib_rx *rx;
2153
2154         LASSERT(!in_interrupt());
2155         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2156
2157         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2158         while (!list_empty(&conn->ibc_early_rxs)) {
2159                 rx = list_entry(conn->ibc_early_rxs.next,
2160                                 struct kib_rx, rx_list);
2161                 list_del(&rx->rx_list);
2162                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2163
2164                 kiblnd_handle_rx(rx);
2165
2166                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2167         }
2168         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2169 }
2170
2171 void
2172 kiblnd_abort_txs(struct kib_conn *conn, struct list_head *txs)
2173 {
2174         struct list_head         zombies = LIST_HEAD_INIT(zombies);
2175         struct list_head        *tmp;
2176         struct list_head        *nxt;
2177         struct kib_tx *tx;
2178
2179         spin_lock(&conn->ibc_lock);
2180
2181         list_for_each_safe(tmp, nxt, txs) {
2182                 tx = list_entry(tmp, struct kib_tx, tx_list);
2183
2184                 if (txs == &conn->ibc_active_txs) {
2185                         LASSERT(!tx->tx_queued);
2186                         LASSERT(tx->tx_waiting ||
2187                                 tx->tx_sending != 0);
2188                         if (conn->ibc_comms_error == -ETIMEDOUT) {
2189                                 if (tx->tx_waiting && !tx->tx_sending)
2190                                         tx->tx_hstatus =
2191                                           LNET_MSG_STATUS_REMOTE_TIMEOUT;
2192                                 else if (tx->tx_sending)
2193                                         tx->tx_hstatus =
2194                                           LNET_MSG_STATUS_NETWORK_TIMEOUT;
2195                         }
2196                 } else {
2197                         LASSERT(tx->tx_queued);
2198                         if (conn->ibc_comms_error == -ETIMEDOUT)
2199                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2200                         else
2201                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
2202                 }
2203
2204                 tx->tx_status = -ECONNABORTED;
2205                 tx->tx_waiting = 0;
2206
2207                 /*
2208                  * TODO: This makes an assumption that
2209                  * kiblnd_tx_complete() will be called for each tx. If
2210                  * that event is dropped we could end up with stale
2211                  * connections floating around. We'd like to deal with
2212                  * that in a better way.
2213                  *
2214                  * Also that means we can exceed the timeout by many
2215                  * seconds.
2216                  */
2217                 if (tx->tx_sending == 0) {
2218                         tx->tx_queued = 0;
2219                         list_del(&tx->tx_list);
2220                         list_add(&tx->tx_list, &zombies);
2221                 }
2222         }
2223
2224         spin_unlock(&conn->ibc_lock);
2225
2226         /*
2227          * aborting transmits occurs when finalizing the connection.
2228          * The connection is finalized on error.
2229          * Passing LNET_MSG_STATUS_OK to txlist_done() will not
2230          * override the value already set in tx->tx_hstatus above.
2231          */
2232         kiblnd_txlist_done(&zombies, -ECONNABORTED, LNET_MSG_STATUS_OK);
2233 }
2234
2235 static void
2236 kiblnd_finalise_conn(struct kib_conn *conn)
2237 {
2238         LASSERT (!in_interrupt());
2239         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
2240
2241         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
2242          * for connections that didn't get as far as being connected, because
2243          * rdma_disconnect() does this for free. */
2244         kiblnd_abort_receives(conn);
2245
2246         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
2247
2248         /* Complete all tx descs not waiting for sends to complete.
2249          * NB we should be safe from RDMA now that the QP has changed state */
2250
2251         kiblnd_abort_txs(conn, &conn->ibc_tx_noops);
2252         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
2253         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
2254         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
2255         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
2256
2257         kiblnd_handle_early_rxs(conn);
2258 }
2259
2260 static void
2261 kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
2262                            int error)
2263 {
2264         struct list_head zombies = LIST_HEAD_INIT(zombies);
2265         unsigned long   flags;
2266
2267         LASSERT (error != 0);
2268         LASSERT (!in_interrupt());
2269
2270         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2271
2272         if (active) {
2273                 LASSERT(peer_ni->ibp_connecting > 0);
2274                 peer_ni->ibp_connecting--;
2275         } else {
2276                 LASSERT (peer_ni->ibp_accepting > 0);
2277                 peer_ni->ibp_accepting--;
2278         }
2279
2280         if (kiblnd_peer_connecting(peer_ni)) {
2281                 /* another connection attempt under way... */
2282                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2283                                         flags);
2284                 return;
2285         }
2286
2287         peer_ni->ibp_reconnected = 0;
2288         if (list_empty(&peer_ni->ibp_conns)) {
2289                 /* Take peer_ni's blocked transmits to complete with error */
2290                 list_splice_init(&peer_ni->ibp_tx_queue, &zombies);
2291
2292                 if (kiblnd_peer_active(peer_ni))
2293                         kiblnd_unlink_peer_locked(peer_ni);
2294
2295                 peer_ni->ibp_error = error;
2296         } else {
2297                 /* Can't have blocked transmits if there are connections */
2298                 LASSERT(list_empty(&peer_ni->ibp_tx_queue));
2299         }
2300
2301         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2302
2303         kiblnd_peer_notify(peer_ni);
2304
2305         if (list_empty(&zombies))
2306                 return;
2307
2308         CNETERR("Deleting messages for %s: connection failed\n",
2309                 libcfs_nid2str(peer_ni->ibp_nid));
2310
2311         kiblnd_txlist_done(&zombies, error,
2312                            LNET_MSG_STATUS_LOCAL_DROPPED);
2313 }
2314
2315 static void
2316 kiblnd_connreq_done(struct kib_conn *conn, int status)
2317 {
2318         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2319         struct kib_tx *tx;
2320         struct list_head txs;
2321         unsigned long    flags;
2322         int              active;
2323
2324         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2325
2326         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
2327                libcfs_nid2str(peer_ni->ibp_nid), active,
2328                conn->ibc_version, status);
2329
2330         LASSERT (!in_interrupt());
2331         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2332                   peer_ni->ibp_connecting > 0) ||
2333                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2334                   peer_ni->ibp_accepting > 0));
2335
2336         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2337         conn->ibc_connvars = NULL;
2338
2339         if (status != 0) {
2340                 /* failed to establish connection */
2341                 kiblnd_peer_connect_failed(peer_ni, active, status);
2342                 kiblnd_finalise_conn(conn);
2343                 return;
2344         }
2345
2346         /* connection established */
2347         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2348
2349         conn->ibc_last_send = ktime_get();
2350         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2351         kiblnd_peer_alive(peer_ni);
2352
2353         /* Add conn to peer_ni's list and nuke any dangling conns from a different
2354          * peer_ni instance... */
2355         kiblnd_conn_addref(conn);       /* +1 ref for ibc_list */
2356         list_add(&conn->ibc_list, &peer_ni->ibp_conns);
2357         peer_ni->ibp_reconnected = 0;
2358         if (active)
2359                 peer_ni->ibp_connecting--;
2360         else
2361                 peer_ni->ibp_accepting--;
2362
2363         if (peer_ni->ibp_version == 0) {
2364                 peer_ni->ibp_version     = conn->ibc_version;
2365                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2366         }
2367
2368         if (peer_ni->ibp_version     != conn->ibc_version ||
2369             peer_ni->ibp_incarnation != conn->ibc_incarnation) {
2370                 kiblnd_close_stale_conns_locked(peer_ni, conn->ibc_version,
2371                                                 conn->ibc_incarnation);
2372                 peer_ni->ibp_version     = conn->ibc_version;
2373                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2374         }
2375
2376         /* grab pending txs while I have the lock */
2377         INIT_LIST_HEAD(&txs);
2378         list_splice_init(&peer_ni->ibp_tx_queue, &txs);
2379
2380         if (!kiblnd_peer_active(peer_ni) ||        /* peer_ni has been deleted */
2381             conn->ibc_comms_error != 0) {       /* error has happened already */
2382
2383                 /* start to shut down connection */
2384                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2385                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2386
2387                 kiblnd_txlist_done(&txs, -ECONNABORTED,
2388                                    LNET_MSG_STATUS_LOCAL_ERROR);
2389
2390                 return;
2391         }
2392
2393         /* +1 ref for myself, this connection is visible to other threads
2394          * now, refcount of peer:ibp_conns can be released by connection
2395          * close from either a different thread, or the calling of
2396          * kiblnd_check_sends_locked() below. See bz21911 for details.
2397          */
2398         kiblnd_conn_addref(conn);
2399         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2400
2401         /* Schedule blocked txs
2402          * Note: if we are running with conns_per_peer > 1, these blocked
2403          * txs will all get scheduled to the first connection which gets
2404          * scheduled.  We won't be using round robin on this first batch.
2405          */
2406         spin_lock(&conn->ibc_lock);
2407         while (!list_empty(&txs)) {
2408                 tx = list_entry(txs.next, struct kib_tx, tx_list);
2409                 list_del(&tx->tx_list);
2410
2411                 kiblnd_queue_tx_locked(tx, conn);
2412         }
2413         kiblnd_check_sends_locked(conn);
2414         spin_unlock(&conn->ibc_lock);
2415
2416         /* schedule blocked rxs */
2417         kiblnd_handle_early_rxs(conn);
2418         kiblnd_conn_decref(conn);
2419 }
2420
2421 static void
2422 kiblnd_reject(struct rdma_cm_id *cmid, struct kib_rej *rej)
2423 {
2424         int          rc;
2425
2426 #ifdef HAVE_RDMA_REJECT_4ARGS
2427         rc = rdma_reject(cmid, rej, sizeof(*rej), IB_CM_REJ_CONSUMER_DEFINED);
2428 #else
2429         rc = rdma_reject(cmid, rej, sizeof(*rej));
2430 #endif
2431
2432         if (rc != 0)
2433                 CWARN("Error %d sending reject\n", rc);
2434 }
2435
2436 static int
2437 kiblnd_passive_connect(struct rdma_cm_id *cmid, void *priv, int priv_nob)
2438 {
2439         rwlock_t                *g_lock = &kiblnd_data.kib_global_lock;
2440         struct kib_msg *reqmsg = priv;
2441         struct kib_msg *ackmsg;
2442         struct kib_dev *ibdev;
2443         struct kib_peer_ni *peer_ni;
2444         struct kib_peer_ni *peer2;
2445         struct kib_conn *conn;
2446         struct lnet_ni *ni = NULL;
2447         struct kib_net *net = NULL;
2448         lnet_nid_t             nid;
2449         struct rdma_conn_param cp;
2450         struct kib_rej rej;
2451         int                    version = IBLND_MSG_VERSION;
2452         unsigned long          flags;
2453         int                    rc;
2454         struct sockaddr_in    *peer_addr;
2455         LASSERT (!in_interrupt());
2456
2457         /* cmid inherits 'context' from the corresponding listener id */
2458         ibdev = cmid->context;
2459         LASSERT(ibdev);
2460
2461         memset(&rej, 0, sizeof(rej));
2462         rej.ibr_magic                = IBLND_MSG_MAGIC;
2463         rej.ibr_why                  = IBLND_REJECT_FATAL;
2464         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2465
2466         peer_addr = (struct sockaddr_in *)&(cmid->route.addr.dst_addr);
2467         if (*kiblnd_tunables.kib_require_priv_port &&
2468             ntohs(peer_addr->sin_port) >= PROT_SOCK) {
2469                 __u32 ip = ntohl(peer_addr->sin_addr.s_addr);
2470                 CERROR("peer_ni's port (%pI4h:%hu) is not privileged\n",
2471                        &ip, ntohs(peer_addr->sin_port));
2472                 goto failed;
2473         }
2474
2475         if (priv_nob < offsetof(struct kib_msg, ibm_type)) {
2476                 CERROR("Short connection request\n");
2477                 goto failed;
2478         }
2479
2480         /* Future protocol version compatibility support!  If the
2481          * o2iblnd-specific protocol changes, or when LNET unifies
2482          * protocols over all LNDs, the initial connection will
2483          * negotiate a protocol version.  I trap this here to avoid
2484          * console errors; the reject tells the peer_ni which protocol I
2485          * speak. */
2486         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2487             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2488                 goto failed;
2489         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2490             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2491             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2492                 goto failed;
2493         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2494             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2495             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2496                 goto failed;
2497
2498         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2499         if (rc != 0) {
2500                 CERROR("Can't parse connection request: %d\n", rc);
2501                 goto failed;
2502         }
2503
2504         nid = reqmsg->ibm_srcnid;
2505         ni  = lnet_nid2ni_addref(reqmsg->ibm_dstnid);
2506
2507         if (ni != NULL) {
2508                 net = (struct kib_net *)ni->ni_data;
2509                 rej.ibr_incarnation = net->ibn_incarnation;
2510         }
2511
2512         if (ni == NULL ||                         /* no matching net */
2513             ni->ni_nid != reqmsg->ibm_dstnid ||   /* right NET, wrong NID! */
2514             net->ibn_dev != ibdev) {              /* wrong device */
2515                 CERROR("Can't accept conn from %s on %s (%s:%d:%pI4h): "
2516                        "bad dst nid %s\n", libcfs_nid2str(nid),
2517                        ni == NULL ? "NA" : libcfs_nid2str(ni->ni_nid),
2518                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2519                         &ibdev->ibd_ifip,
2520                        libcfs_nid2str(reqmsg->ibm_dstnid));
2521
2522                 goto failed;
2523         }
2524
2525        /* check time stamp as soon as possible */
2526         if (reqmsg->ibm_dststamp != 0 &&
2527             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2528                 CWARN("Stale connection request\n");
2529                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2530                 goto failed;
2531         }
2532
2533         /* I can accept peer_ni's version */
2534         version = reqmsg->ibm_version;
2535
2536         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2537                 CERROR("Unexpected connreq msg type: %x from %s\n",
2538                        reqmsg->ibm_type, libcfs_nid2str(nid));
2539                 goto failed;
2540         }
2541
2542         if (reqmsg->ibm_u.connparams.ibcp_queue_depth >
2543             kiblnd_msg_queue_size(version, ni)) {
2544                 CERROR("Can't accept conn from %s, queue depth too large: "
2545                        " %d (<=%d wanted)\n",
2546                        libcfs_nid2str(nid),
2547                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2548                        kiblnd_msg_queue_size(version, ni));
2549
2550                 if (version == IBLND_MSG_VERSION)
2551                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2552
2553                 goto failed;
2554         }
2555
2556         if (reqmsg->ibm_u.connparams.ibcp_max_frags >
2557             IBLND_MAX_RDMA_FRAGS) {
2558                 CWARN("Can't accept conn from %s (version %x): "
2559                       "max_frags %d too large (%d wanted)\n",
2560                       libcfs_nid2str(nid), version,
2561                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2562                       IBLND_MAX_RDMA_FRAGS);
2563
2564                 if (version >= IBLND_MSG_VERSION)
2565                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2566
2567                 goto failed;
2568         } else if (reqmsg->ibm_u.connparams.ibcp_max_frags <
2569                    IBLND_MAX_RDMA_FRAGS &&
2570                    net->ibn_fmr_ps == NULL) {
2571                 CWARN("Can't accept conn from %s (version %x): "
2572                       "max_frags %d incompatible without FMR pool "
2573                       "(%d wanted)\n",
2574                       libcfs_nid2str(nid), version,
2575                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2576                       IBLND_MAX_RDMA_FRAGS);
2577
2578                 if (version == IBLND_MSG_VERSION)
2579                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2580
2581                 goto failed;
2582         }
2583
2584         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2585                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2586                        libcfs_nid2str(nid),
2587                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2588                        IBLND_MSG_SIZE);
2589                 goto failed;
2590         }
2591
2592         /* assume 'nid' is a new peer_ni; create  */
2593         rc = kiblnd_create_peer(ni, &peer_ni, nid);
2594         if (rc != 0) {
2595                 CERROR("Can't create peer_ni for %s\n", libcfs_nid2str(nid));
2596                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2597                 goto failed;
2598         }
2599
2600         /* We have validated the peer's parameters so use those */
2601         peer_ni->ibp_max_frags = reqmsg->ibm_u.connparams.ibcp_max_frags;
2602         peer_ni->ibp_queue_depth = reqmsg->ibm_u.connparams.ibcp_queue_depth;
2603
2604         write_lock_irqsave(g_lock, flags);
2605
2606         peer2 = kiblnd_find_peer_locked(ni, nid);
2607         if (peer2 != NULL) {
2608                 if (peer2->ibp_version == 0) {
2609                         peer2->ibp_version     = version;
2610                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2611                 }
2612
2613                 /* not the guy I've talked with */
2614                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2615                     peer2->ibp_version     != version) {
2616                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2617
2618                         if (kiblnd_peer_active(peer2)) {
2619                                 peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2620                                 peer2->ibp_version = version;
2621                         }
2622                         write_unlock_irqrestore(g_lock, flags);
2623
2624                         CWARN("Conn stale %s version %x/%x incarnation %llu/%llu\n",
2625                               libcfs_nid2str(nid), peer2->ibp_version, version,
2626                               peer2->ibp_incarnation, reqmsg->ibm_srcstamp);
2627
2628                         kiblnd_peer_decref(peer_ni);
2629                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2630                         goto failed;
2631                 }
2632
2633                 /* Tie-break connection race in favour of the higher NID.
2634                  * If we keep running into a race condition multiple times,
2635                  * we have to assume that the connection attempt with the
2636                  * higher NID is stuck in a connecting state and will never
2637                  * recover.  As such, we pass through this if-block and let
2638                  * the lower NID connection win so we can move forward.
2639                  */
2640                 if (peer2->ibp_connecting != 0 &&
2641                     nid < ni->ni_nid && peer2->ibp_races <
2642                     MAX_CONN_RACES_BEFORE_ABORT) {
2643                         peer2->ibp_races++;
2644                         write_unlock_irqrestore(g_lock, flags);
2645
2646                         CDEBUG(D_NET, "Conn race %s\n",
2647                                libcfs_nid2str(peer2->ibp_nid));
2648
2649                         kiblnd_peer_decref(peer_ni);
2650                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2651                         goto failed;
2652                 }
2653                 if (peer2->ibp_races >= MAX_CONN_RACES_BEFORE_ABORT)
2654                         CNETERR("Conn race %s: unresolved after %d attempts, letting lower NID win\n",
2655                                 libcfs_nid2str(peer2->ibp_nid),
2656                                 MAX_CONN_RACES_BEFORE_ABORT);
2657                 /*
2658                  * passive connection is allowed even this peer_ni is waiting for
2659                  * reconnection.
2660                  */
2661                 peer2->ibp_reconnecting = 0;
2662                 peer2->ibp_races = 0;
2663                 peer2->ibp_accepting++;
2664                 kiblnd_peer_addref(peer2);
2665
2666                 /* Race with kiblnd_launch_tx (active connect) to create peer_ni
2667                  * so copy validated parameters since we now know what the
2668                  * peer_ni's limits are */
2669                 peer2->ibp_max_frags = peer_ni->ibp_max_frags;
2670                 peer2->ibp_queue_depth = peer_ni->ibp_queue_depth;
2671
2672                 write_unlock_irqrestore(g_lock, flags);
2673                 kiblnd_peer_decref(peer_ni);
2674                 peer_ni = peer2;
2675         } else {
2676                 /* Brand new peer_ni */
2677                 LASSERT (peer_ni->ibp_accepting == 0);
2678                 LASSERT (peer_ni->ibp_version == 0 &&
2679                          peer_ni->ibp_incarnation == 0);
2680
2681                 peer_ni->ibp_accepting   = 1;
2682                 peer_ni->ibp_version     = version;
2683                 peer_ni->ibp_incarnation = reqmsg->ibm_srcstamp;
2684
2685                 /* I have a ref on ni that prevents it being shutdown */
2686                 LASSERT (net->ibn_shutdown == 0);
2687
2688                 kiblnd_peer_addref(peer_ni);
2689                 list_add_tail(&peer_ni->ibp_list, kiblnd_nid2peerlist(nid));
2690
2691                 write_unlock_irqrestore(g_lock, flags);
2692         }
2693
2694         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_PASSIVE_WAIT, version);
2695         if (conn == NULL) {
2696                 kiblnd_peer_connect_failed(peer_ni, 0, -ENOMEM);
2697                 kiblnd_peer_decref(peer_ni);
2698                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2699                 goto failed;
2700         }
2701
2702         /* conn now "owns" cmid, so I return success from here on to ensure the
2703          * CM callback doesn't destroy cmid. */
2704         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2705         conn->ibc_credits          = conn->ibc_queue_depth;
2706         conn->ibc_reserved_credits = conn->ibc_queue_depth;
2707         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2708                 IBLND_OOB_MSGS(version) <= IBLND_RX_MSGS(conn));
2709
2710         ackmsg = &conn->ibc_connvars->cv_msg;
2711         memset(ackmsg, 0, sizeof(*ackmsg));
2712
2713         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2714                         sizeof(ackmsg->ibm_u.connparams));
2715         ackmsg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2716         ackmsg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2717         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2718
2719         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2720
2721         memset(&cp, 0, sizeof(cp));
2722         cp.private_data        = ackmsg;
2723         cp.private_data_len    = ackmsg->ibm_nob;
2724         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2725         cp.initiator_depth     = 0;
2726         cp.flow_control        = 1;
2727         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2728         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2729
2730         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2731
2732         rc = rdma_accept(cmid, &cp);
2733         if (rc != 0) {
2734                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2735                 rej.ibr_version = version;
2736                 rej.ibr_why     = IBLND_REJECT_FATAL;
2737
2738                 kiblnd_reject(cmid, &rej);
2739                 kiblnd_connreq_done(conn, rc);
2740                 kiblnd_conn_decref(conn);
2741         }
2742
2743         lnet_ni_decref(ni);
2744         return 0;
2745
2746  failed:
2747         if (ni != NULL) {
2748                 rej.ibr_cp.ibcp_queue_depth =
2749                         kiblnd_msg_queue_size(version, ni);
2750                 rej.ibr_cp.ibcp_max_frags   = IBLND_MAX_RDMA_FRAGS;
2751                 lnet_ni_decref(ni);
2752         }
2753
2754         rej.ibr_version = version;
2755         kiblnd_reject(cmid, &rej);
2756
2757         return -ECONNREFUSED;
2758 }
2759
2760 static void
2761 kiblnd_check_reconnect(struct kib_conn *conn, int version,
2762                        u64 incarnation, int why, struct kib_connparams *cp)
2763 {
2764         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
2765         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2766         char            *reason;
2767         int              msg_size = IBLND_MSG_SIZE;
2768         int              frag_num = -1;
2769         int              queue_dep = -1;
2770         bool             reconnect;
2771         unsigned long    flags;
2772
2773         LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2774         LASSERT(peer_ni->ibp_connecting > 0);   /* 'conn' at least */
2775
2776         if (cp) {
2777                 msg_size        = cp->ibcp_max_msg_size;
2778                 frag_num        = cp->ibcp_max_frags;
2779                 queue_dep       = cp->ibcp_queue_depth;
2780         }
2781
2782         write_lock_irqsave(glock, flags);
2783         /* retry connection if it's still needed and no other connection
2784          * attempts (active or passive) are in progress
2785          * NB: reconnect is still needed even when ibp_tx_queue is
2786          * empty if ibp_version != version because reconnect may be
2787          * initiated by kiblnd_query() */
2788         reconnect = (!list_empty(&peer_ni->ibp_tx_queue) ||
2789                      peer_ni->ibp_version != version) &&
2790                     peer_ni->ibp_connecting &&
2791                     peer_ni->ibp_accepting == 0;
2792         if (!reconnect) {
2793                 reason = "no need";
2794                 goto out;
2795         }
2796
2797         switch (why) {
2798         default:
2799                 reason = "Unknown";
2800                 break;
2801
2802         case IBLND_REJECT_RDMA_FRAGS: {
2803                 struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2804
2805                 if (!cp) {
2806                         reason = "can't negotiate max frags";
2807                         goto out;
2808                 }
2809                 tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2810 #ifdef HAVE_IB_GET_DMA_MR
2811                 /*
2812                  * This check only makes sense if the kernel supports global
2813                  * memory registration. Otherwise, map_on_demand will never == 0
2814                  */
2815                 if (!tunables->lnd_map_on_demand) {
2816                         reason = "map_on_demand must be enabled";
2817                         goto out;
2818                 }
2819 #endif
2820                 if (conn->ibc_max_frags <= frag_num) {
2821                         reason = "unsupported max frags";
2822                         goto out;
2823                 }
2824
2825                 peer_ni->ibp_max_frags = frag_num;
2826                 reason = "rdma fragments";
2827                 break;
2828         }
2829         case IBLND_REJECT_MSG_QUEUE_SIZE:
2830                 if (!cp) {
2831                         reason = "can't negotiate queue depth";
2832                         goto out;
2833                 }
2834                 if (conn->ibc_queue_depth <= queue_dep) {
2835                         reason = "unsupported queue depth";
2836                         goto out;
2837                 }
2838
2839                 peer_ni->ibp_queue_depth = queue_dep;
2840                 reason = "queue depth";
2841                 break;
2842
2843         case IBLND_REJECT_CONN_STALE:
2844                 reason = "stale";
2845                 break;
2846
2847         case IBLND_REJECT_CONN_RACE:
2848                 reason = "conn race";
2849                 break;
2850
2851         case IBLND_REJECT_CONN_UNCOMPAT:
2852                 reason = "version negotiation";
2853                 break;
2854
2855         case IBLND_REJECT_INVALID_SRV_ID:
2856                 reason = "invalid service id";
2857                 break;
2858         }
2859
2860         conn->ibc_reconnect = 1;
2861         peer_ni->ibp_reconnecting++;
2862         peer_ni->ibp_version = version;
2863         if (incarnation != 0)
2864                 peer_ni->ibp_incarnation = incarnation;
2865  out:
2866         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2867
2868         CNETERR("%s: %s (%s), %x, %x, msg_size: %d, queue_depth: %d/%d, max_frags: %d/%d\n",
2869                 libcfs_nid2str(peer_ni->ibp_nid),
2870                 reconnect ? "reconnect" : "don't reconnect",
2871                 reason, IBLND_MSG_VERSION, version, msg_size,
2872                 conn->ibc_queue_depth, queue_dep,
2873                 conn->ibc_max_frags, frag_num);
2874         /*
2875          * if conn::ibc_reconnect is TRUE, connd will reconnect to the peer_ni
2876          * while destroying the zombie
2877          */
2878 }
2879
2880 static void
2881 kiblnd_rejected(struct kib_conn *conn, int reason, void *priv, int priv_nob)
2882 {
2883         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2884
2885         LASSERT (!in_interrupt());
2886         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2887
2888         switch (reason) {
2889         case IB_CM_REJ_STALE_CONN:
2890                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2891                                        IBLND_REJECT_CONN_STALE, NULL);
2892                 break;
2893
2894         case IB_CM_REJ_INVALID_SERVICE_ID:
2895                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2896                                        IBLND_REJECT_INVALID_SRV_ID, NULL);
2897                 CNETERR("%s rejected: no listener at %d\n",
2898                         libcfs_nid2str(peer_ni->ibp_nid),
2899                         *kiblnd_tunables.kib_service);
2900                 break;
2901
2902         case IB_CM_REJ_CONSUMER_DEFINED:
2903                 if (priv_nob >= offsetof(struct kib_rej, ibr_padding)) {
2904                         struct kib_rej *rej = priv;
2905                         struct kib_connparams *cp = NULL;
2906                         int               flip        = 0;
2907                         __u64             incarnation = -1;
2908
2909                         /* NB. default incarnation is -1 because:
2910                          * a) V1 will ignore dst incarnation in connreq.
2911                          * b) V2 will provide incarnation while rejecting me,
2912                          *    -1 will be overwrote.
2913                          *
2914                          * if I try to connect to a V1 peer_ni with V2 protocol,
2915                          * it rejected me then upgrade to V2, I have no idea
2916                          * about the upgrading and try to reconnect with V1,
2917                          * in this case upgraded V2 can find out I'm trying to
2918                          * talk to the old guy and reject me(incarnation is -1). 
2919                          */
2920
2921                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2922                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2923                                 __swab32s(&rej->ibr_magic);
2924                                 __swab16s(&rej->ibr_version);
2925                                 flip = 1;
2926                         }
2927
2928                         if (priv_nob >= sizeof(struct kib_rej) &&
2929                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2930                                 /* priv_nob is always 148 in current version
2931                                  * of OFED, so we still need to check version.
2932                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE) */
2933                                 cp = &rej->ibr_cp;
2934
2935                                 if (flip) {
2936                                         __swab64s(&rej->ibr_incarnation);
2937                                         __swab16s(&cp->ibcp_queue_depth);
2938                                         __swab16s(&cp->ibcp_max_frags);
2939                                         __swab32s(&cp->ibcp_max_msg_size);
2940                                 }
2941
2942                                 incarnation = rej->ibr_incarnation;
2943                         }
2944
2945                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2946                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2947                                 CERROR("%s rejected: consumer defined fatal error\n",
2948                                        libcfs_nid2str(peer_ni->ibp_nid));
2949                                 break;
2950                         }
2951
2952                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2953                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2954                                 CERROR("%s rejected: o2iblnd version %x error\n",
2955                                        libcfs_nid2str(peer_ni->ibp_nid),
2956                                        rej->ibr_version);
2957                                 break;
2958                         }
2959
2960                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2961                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2962                                 CDEBUG(D_NET, "rejected by old version peer_ni %s: %x\n",
2963                                        libcfs_nid2str(peer_ni->ibp_nid), rej->ibr_version);
2964
2965                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2966                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2967                         }
2968
2969                         switch (rej->ibr_why) {
2970                         case IBLND_REJECT_CONN_RACE:
2971                         case IBLND_REJECT_CONN_STALE:
2972                         case IBLND_REJECT_CONN_UNCOMPAT:
2973                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2974                         case IBLND_REJECT_RDMA_FRAGS:
2975                                 kiblnd_check_reconnect(conn, rej->ibr_version,
2976                                                 incarnation, rej->ibr_why, cp);
2977                                 break;
2978
2979                         case IBLND_REJECT_NO_RESOURCES:
2980                                 CERROR("%s rejected: o2iblnd no resources\n",
2981                                        libcfs_nid2str(peer_ni->ibp_nid));
2982                                 break;
2983
2984                         case IBLND_REJECT_FATAL:
2985                                 CERROR("%s rejected: o2iblnd fatal error\n",
2986                                        libcfs_nid2str(peer_ni->ibp_nid));
2987                                 break;
2988
2989                         default:
2990                                 CERROR("%s rejected: o2iblnd reason %d\n",
2991                                        libcfs_nid2str(peer_ni->ibp_nid),
2992                                        rej->ibr_why);
2993                                 break;
2994                         }
2995                         break;
2996                 }
2997                 /* fall through */
2998         default:
2999                 CNETERR("%s rejected: reason %d, size %d\n",
3000                         libcfs_nid2str(peer_ni->ibp_nid), reason, priv_nob);
3001                 break;
3002         }
3003
3004         kiblnd_connreq_done(conn, -ECONNREFUSED);
3005 }
3006
3007 static void
3008 kiblnd_check_connreply(struct kib_conn *conn, void *priv, int priv_nob)
3009 {
3010         struct kib_peer_ni *peer_ni = conn->ibc_peer;
3011         struct lnet_ni *ni = peer_ni->ibp_ni;
3012         struct kib_net *net = ni->ni_data;
3013         struct kib_msg *msg = priv;
3014         int            ver  = conn->ibc_version;
3015         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
3016         unsigned long  flags;
3017
3018         LASSERT (net != NULL);
3019
3020         if (rc != 0) {
3021                 CERROR("Can't unpack connack from %s: %d\n",
3022                        libcfs_nid2str(peer_ni->ibp_nid), rc);
3023                 goto failed;
3024         }
3025
3026         if (msg->ibm_type != IBLND_MSG_CONNACK) {
3027                 CERROR("Unexpected message %d from %s\n",
3028                        msg->ibm_type, libcfs_nid2str(peer_ni->ibp_nid));
3029                 rc = -EPROTO;
3030                 goto failed;
3031         }
3032
3033         if (ver != msg->ibm_version) {
3034                 CERROR("%s replied version %x is different with "
3035                        "requested version %x\n",
3036                        libcfs_nid2str(peer_ni->ibp_nid), msg->ibm_version, ver);
3037                 rc = -EPROTO;
3038                 goto failed;
3039         }
3040
3041         if (msg->ibm_u.connparams.ibcp_queue_depth >
3042             conn->ibc_queue_depth) {
3043                 CERROR("%s has incompatible queue depth %d (<=%d wanted)\n",
3044                        libcfs_nid2str(peer_ni->ibp_nid),
3045                        msg->ibm_u.connparams.ibcp_queue_depth,
3046                        conn->ibc_queue_depth);
3047                 rc = -EPROTO;
3048                 goto failed;
3049         }
3050
3051         if (msg->ibm_u.connparams.ibcp_max_frags >
3052             conn->ibc_max_frags) {
3053                 CERROR("%s has incompatible max_frags %d (<=%d wanted)\n",
3054                        libcfs_nid2str(peer_ni->ibp_nid),
3055                        msg->ibm_u.connparams.ibcp_max_frags,
3056                        conn->ibc_max_frags);
3057                 rc = -EPROTO;
3058                 goto failed;
3059         }
3060
3061         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
3062                 CERROR("%s max message size %d too big (%d max)\n",
3063                        libcfs_nid2str(peer_ni->ibp_nid),
3064                        msg->ibm_u.connparams.ibcp_max_msg_size,
3065                        IBLND_MSG_SIZE);
3066                 rc = -EPROTO;
3067                 goto failed;
3068         }
3069
3070         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3071         if (msg->ibm_dstnid == ni->ni_nid &&
3072             msg->ibm_dststamp == net->ibn_incarnation)
3073                 rc = 0;
3074         else
3075                 rc = -ESTALE;
3076         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3077
3078         if (rc != 0) {
3079                 CERROR("Bad connection reply from %s, rc = %d, "
3080                        "version: %x max_frags: %d\n",
3081                        libcfs_nid2str(peer_ni->ibp_nid), rc,
3082                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
3083                 goto failed;
3084         }
3085
3086         conn->ibc_incarnation      = msg->ibm_srcstamp;
3087         conn->ibc_credits          = msg->ibm_u.connparams.ibcp_queue_depth;
3088         conn->ibc_reserved_credits = msg->ibm_u.connparams.ibcp_queue_depth;
3089         conn->ibc_queue_depth      = msg->ibm_u.connparams.ibcp_queue_depth;
3090         conn->ibc_max_frags        = msg->ibm_u.connparams.ibcp_max_frags;
3091         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
3092                 IBLND_OOB_MSGS(ver) <= IBLND_RX_MSGS(conn));
3093
3094         kiblnd_connreq_done(conn, 0);
3095         return;
3096
3097  failed:
3098         /* NB My QP has already established itself, so I handle anything going
3099          * wrong here by setting ibc_comms_error.
3100          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
3101          * immediately tears it down. */
3102
3103         LASSERT (rc != 0);
3104         conn->ibc_comms_error = rc;
3105         kiblnd_connreq_done(conn, 0);
3106 }
3107
3108 static int
3109 kiblnd_active_connect(struct rdma_cm_id *cmid)
3110 {
3111         struct kib_peer_ni *peer_ni = cmid->context;
3112         struct kib_conn *conn;
3113         struct kib_msg *msg;
3114         struct rdma_conn_param cp;
3115         int                      version;
3116         __u64                    incarnation;
3117         unsigned long            flags;
3118         int                      rc;
3119
3120         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3121
3122         incarnation = peer_ni->ibp_incarnation;
3123         version     = (peer_ni->ibp_version == 0) ? IBLND_MSG_VERSION :
3124                                                  peer_ni->ibp_version;
3125
3126         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3127
3128         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_ACTIVE_CONNECT,
3129                                   version);
3130         if (conn == NULL) {
3131                 kiblnd_peer_connect_failed(peer_ni, 1, -ENOMEM);
3132                 kiblnd_peer_decref(peer_ni); /* lose cmid's ref */
3133                 return -ENOMEM;
3134         }
3135
3136         /* conn "owns" cmid now, so I return success from here on to ensure the
3137          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
3138          * on peer_ni */
3139
3140         msg = &conn->ibc_connvars->cv_msg;
3141
3142         memset(msg, 0, sizeof(*msg));
3143         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
3144         msg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
3145         msg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
3146         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
3147
3148         kiblnd_pack_msg(peer_ni->ibp_ni, msg, version,
3149                         0, peer_ni->ibp_nid, incarnation);
3150
3151         memset(&cp, 0, sizeof(cp));
3152         cp.private_data        = msg;
3153         cp.private_data_len    = msg->ibm_nob;
3154         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
3155         cp.initiator_depth     = 0;
3156         cp.flow_control        = 1;
3157         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
3158         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
3159
3160         LASSERT(cmid->context == (void *)conn);
3161         LASSERT(conn->ibc_cmid == cmid);
3162
3163         rc = rdma_connect(cmid, &cp);
3164         if (rc != 0) {
3165                 CERROR("Can't connect to %s: %d\n",
3166                        libcfs_nid2str(peer_ni->ibp_nid), rc);
3167                 kiblnd_connreq_done(conn, rc);
3168                 kiblnd_conn_decref(conn);
3169         }
3170
3171         return 0;
3172 }
3173
3174 int
3175 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
3176 {
3177         struct kib_peer_ni *peer_ni;
3178         struct kib_conn *conn;
3179         int rc;
3180
3181         switch (event->event) {
3182         default:
3183                 CERROR("Unexpected event: %d, status: %d\n",
3184                        event->event, event->status);
3185                 LBUG();
3186
3187         case RDMA_CM_EVENT_CONNECT_REQUEST:
3188                 /* destroy cmid on failure */
3189                 rc = kiblnd_passive_connect(cmid,
3190                                             (void *)KIBLND_CONN_PARAM(event),
3191                                             KIBLND_CONN_PARAM_LEN(event));
3192                 CDEBUG(D_NET, "connreq: %d\n", rc);
3193                 return rc;
3194
3195         case RDMA_CM_EVENT_ADDR_ERROR:
3196                 peer_ni = cmid->context;
3197                 CNETERR("%s: ADDR ERROR %d\n",
3198                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3199                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3200                 kiblnd_peer_decref(peer_ni);
3201                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
3202
3203         case RDMA_CM_EVENT_ADDR_RESOLVED:
3204                 peer_ni = cmid->context;
3205
3206                 CDEBUG(D_NET,"%s Addr resolved: %d\n",
3207                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3208
3209                 if (event->status != 0) {
3210                         CNETERR("Can't resolve address for %s: %d\n",
3211                                 libcfs_nid2str(peer_ni->ibp_nid), event->status);
3212                         rc = event->status;
3213                 } else {
3214                         rc = rdma_resolve_route(
3215                                 cmid, lnet_get_lnd_timeout() * 1000);
3216                         if (rc == 0) {
3217                                 struct kib_net *net = peer_ni->ibp_ni->ni_data;
3218                                 struct kib_dev *dev = net->ibn_dev;
3219
3220                                 CDEBUG(D_NET, "%s: connection bound to "\
3221                                        "%s:%pI4h:%s\n",
3222                                        libcfs_nid2str(peer_ni->ibp_nid),
3223                                        dev->ibd_ifname,
3224                                        &dev->ibd_ifip, cmid->device->name);
3225
3226                                 return 0;
3227                         }
3228
3229                         /* Can't initiate route resolution */
3230                         CERROR("Can't resolve route for %s: %d\n",
3231                                libcfs_nid2str(peer_ni->ibp_nid), rc);
3232                 }
3233                 kiblnd_peer_connect_failed(peer_ni, 1, rc);
3234                 kiblnd_peer_decref(peer_ni);
3235                 return rc;                      /* rc != 0 destroys cmid */
3236
3237         case RDMA_CM_EVENT_ROUTE_ERROR:
3238                 peer_ni = cmid->context;
3239                 CNETERR("%s: ROUTE ERROR %d\n",
3240                         libcfs_nid2str(peer_ni->ibp_nid), event->status);
3241                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3242                 kiblnd_peer_decref(peer_ni);
3243                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
3244
3245         case RDMA_CM_EVENT_ROUTE_RESOLVED:
3246                 peer_ni = cmid->context;
3247                 CDEBUG(D_NET,"%s Route resolved: %d\n",
3248                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3249
3250                 if (event->status == 0)
3251                         return kiblnd_active_connect(cmid);
3252
3253                 CNETERR("Can't resolve route for %s: %d\n",
3254                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3255                 kiblnd_peer_connect_failed(peer_ni, 1, event->status);
3256                 kiblnd_peer_decref(peer_ni);
3257                 return event->status;           /* rc != 0 destroys cmid */
3258
3259         case RDMA_CM_EVENT_UNREACHABLE:
3260                 conn = cmid->context;
3261                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3262                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3263                 CNETERR("%s: UNREACHABLE %d\n",
3264                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3265                 kiblnd_connreq_done(conn, -ENETDOWN);
3266                 kiblnd_conn_decref(conn);
3267                 return 0;
3268
3269         case RDMA_CM_EVENT_CONNECT_ERROR:
3270                 conn = cmid->context;
3271                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3272                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3273                 CNETERR("%s: CONNECT ERROR %d\n",
3274                         libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3275                 kiblnd_connreq_done(conn, -ENOTCONN);
3276                 kiblnd_conn_decref(conn);
3277                 return 0;
3278
3279         case RDMA_CM_EVENT_REJECTED:
3280                 conn = cmid->context;
3281                 switch (conn->ibc_state) {
3282                 default:
3283                         LBUG();
3284
3285                 case IBLND_CONN_PASSIVE_WAIT:
3286                         CERROR ("%s: REJECTED %d\n",
3287                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
3288                                 event->status);
3289                         kiblnd_connreq_done(conn, -ECONNRESET);
3290                         break;
3291
3292                 case IBLND_CONN_ACTIVE_CONNECT:
3293                         kiblnd_rejected(conn, event->status,
3294                                         (void *)KIBLND_CONN_PARAM(event),
3295                                         KIBLND_CONN_PARAM_LEN(event));
3296                         break;
3297                 }
3298                 kiblnd_conn_decref(conn);
3299                 return 0;
3300
3301         case RDMA_CM_EVENT_ESTABLISHED:
3302                 conn = cmid->context;
3303                 switch (conn->ibc_state) {
3304                 default:
3305                         LBUG();
3306
3307                 case IBLND_CONN_PASSIVE_WAIT:
3308                         CDEBUG(D_NET, "ESTABLISHED (passive): %s\n",
3309                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3310                         kiblnd_connreq_done(conn, 0);
3311                         break;
3312
3313                 case IBLND_CONN_ACTIVE_CONNECT:
3314                         CDEBUG(D_NET, "ESTABLISHED(active): %s\n",
3315                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3316                         kiblnd_check_connreply(conn,
3317                                                (void *)KIBLND_CONN_PARAM(event),
3318                                                KIBLND_CONN_PARAM_LEN(event));
3319                         break;
3320                 }
3321                 /* net keeps its ref on conn! */
3322                 return 0;
3323
3324         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
3325                 CDEBUG(D_NET, "Ignore TIMEWAIT_EXIT event\n");
3326                 return 0;
3327
3328         case RDMA_CM_EVENT_DISCONNECTED:
3329                 conn = cmid->context;
3330                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
3331                         CERROR("%s DISCONNECTED\n",
3332                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3333                         kiblnd_connreq_done(conn, -ECONNRESET);
3334                 } else {
3335                         kiblnd_close_conn(conn, 0);
3336                 }
3337                 kiblnd_conn_decref(conn);
3338                 cmid->context = NULL;
3339                 return 0;
3340
3341         case RDMA_CM_EVENT_DEVICE_REMOVAL:
3342                 LCONSOLE_ERROR_MSG(0x131,
3343                                    "Received notification of device removal\n"
3344                                    "Please shutdown LNET to allow this to proceed\n");
3345                 /* Can't remove network from underneath LNET for now, so I have
3346                  * to ignore this */
3347                 return 0;
3348
3349         case RDMA_CM_EVENT_ADDR_CHANGE:
3350                 LCONSOLE_INFO("Physical link changed (eg hca/port)\n");
3351                 return 0;
3352         }
3353 }
3354
3355 static int
3356 kiblnd_check_txs_locked(struct kib_conn *conn, struct list_head *txs)
3357 {
3358         struct kib_tx *tx;
3359         struct list_head *ttmp;
3360
3361         list_for_each(ttmp, txs) {
3362                 tx = list_entry(ttmp, struct kib_tx, tx_list);
3363
3364                 if (txs != &conn->ibc_active_txs) {
3365                         LASSERT(tx->tx_queued);
3366                 } else {
3367                         LASSERT(!tx->tx_queued);
3368                         LASSERT(tx->tx_waiting || tx->tx_sending != 0);
3369                 }
3370
3371                 if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3372                         CERROR("Timed out tx: %s, %lld seconds\n",
3373                                kiblnd_queue2str(conn, txs),
3374                                ktime_ms_delta(ktime_get(),
3375                                               tx->tx_deadline) / MSEC_PER_SEC);
3376                         return 1;
3377                 }
3378         }
3379
3380         return 0;
3381 }
3382
3383 static int
3384 kiblnd_conn_timed_out_locked(struct kib_conn *conn)
3385 {
3386         return  kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue) ||
3387                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_noops) ||
3388                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_rsrvd) ||
3389                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_nocred) ||
3390                 kiblnd_check_txs_locked(conn, &conn->ibc_active_txs);
3391 }
3392
3393 static void
3394 kiblnd_check_conns (int idx)
3395 {
3396         struct list_head  closes = LIST_HEAD_INIT(closes);
3397         struct list_head  checksends = LIST_HEAD_INIT(checksends);
3398         struct list_head  timedout_txs = LIST_HEAD_INIT(timedout_txs);
3399         struct list_head *peers = &kiblnd_data.kib_peers[idx];
3400         struct list_head *ptmp;
3401         struct kib_peer_ni *peer_ni;
3402         struct kib_conn *conn;
3403         struct kib_tx *tx, *tx_tmp;
3404         struct list_head *ctmp;
3405         unsigned long     flags;
3406
3407         /* NB. We expect to have a look at all the peers and not find any
3408          * RDMAs to time out, so we just use a shared lock while we
3409          * take a look... */
3410         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3411
3412         list_for_each(ptmp, peers) {
3413                 peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
3414
3415                 /* Check tx_deadline */
3416                 list_for_each_entry_safe(tx, tx_tmp, &peer_ni->ibp_tx_queue, tx_list) {
3417                         if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3418                                 CWARN("Timed out tx for %s: %lld seconds\n",
3419                                       libcfs_nid2str(peer_ni->ibp_nid),
3420                                       ktime_ms_delta(ktime_get(),
3421                                                      tx->tx_deadline) / MSEC_PER_SEC);
3422                                 list_move(&tx->tx_list, &timedout_txs);
3423                         }
3424                 }
3425
3426                 list_for_each(ctmp, &peer_ni->ibp_conns) {
3427                         int timedout;
3428                         int sendnoop;
3429
3430                         conn = list_entry(ctmp, struct kib_conn, ibc_list);
3431
3432                         LASSERT(conn->ibc_state == IBLND_CONN_ESTABLISHED);
3433
3434                         spin_lock(&conn->ibc_lock);
3435
3436                         sendnoop = kiblnd_need_noop(conn);
3437                         timedout = kiblnd_conn_timed_out_locked(conn);
3438                         if (!sendnoop && !timedout) {
3439                                 spin_unlock(&conn->ibc_lock);
3440                                 continue;
3441                         }
3442
3443                         if (timedout) {
3444                                 CERROR("Timed out RDMA with %s (%lld): "
3445                                        "c: %u, oc: %u, rc: %u\n",
3446                                        libcfs_nid2str(peer_ni->ibp_nid),
3447                                        ktime_get_seconds() - peer_ni->ibp_last_alive,
3448                                        conn->ibc_credits,
3449                                        conn->ibc_outstanding_credits,
3450                                        conn->ibc_reserved_credits);
3451                                 list_add(&conn->ibc_connd_list, &closes);
3452                         } else {
3453                                 list_add(&conn->ibc_connd_list, &checksends);
3454                         }
3455                         /* +ref for 'closes' or 'checksends' */
3456                         kiblnd_conn_addref(conn);
3457
3458                         spin_unlock(&conn->ibc_lock);
3459                 }
3460         }
3461
3462         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3463
3464         if (!list_empty(&timedout_txs))
3465                 kiblnd_txlist_done(&timedout_txs, -ETIMEDOUT,
3466                                    LNET_MSG_STATUS_LOCAL_TIMEOUT);
3467
3468         /* Handle timeout by closing the whole
3469          * connection. We can only be sure RDMA activity
3470          * has ceased once the QP has been modified. */
3471         while (!list_empty(&closes)) {
3472                 conn = list_entry(closes.next,
3473                                   struct kib_conn, ibc_connd_list);
3474                 list_del(&conn->ibc_connd_list);
3475                 kiblnd_close_conn(conn, -ETIMEDOUT);
3476                 kiblnd_conn_decref(conn);
3477         }
3478
3479         /* In case we have enough credits to return via a
3480          * NOOP, but there were no non-blocking tx descs
3481          * free to do it last time... */
3482         while (!list_empty(&checksends)) {
3483                 conn = list_entry(checksends.next,
3484                                   struct kib_conn, ibc_connd_list);
3485                 list_del(&conn->ibc_connd_list);
3486
3487                 spin_lock(&conn->ibc_lock);
3488                 kiblnd_check_sends_locked(conn);
3489                 spin_unlock(&conn->ibc_lock);
3490
3491                 kiblnd_conn_decref(conn);
3492         }
3493 }
3494
3495 static void
3496 kiblnd_disconnect_conn(struct kib_conn *conn)
3497 {
3498         LASSERT (!in_interrupt());
3499         LASSERT (current == kiblnd_data.kib_connd);
3500         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
3501
3502         rdma_disconnect(conn->ibc_cmid);
3503         kiblnd_finalise_conn(conn);
3504
3505         kiblnd_peer_notify(conn->ibc_peer);
3506 }
3507
3508 /*
3509  * High-water for reconnection to the same peer_ni, reconnection attempt should
3510  * be delayed after trying more than KIB_RECONN_HIGH_RACE.
3511  */
3512 #define KIB_RECONN_HIGH_RACE    10
3513 /*
3514  * Allow connd to take a break and handle other things after consecutive
3515  * reconnection attemps.
3516  */
3517 #define KIB_RECONN_BREAK        100
3518
3519 int
3520 kiblnd_connd (void *arg)
3521 {
3522         spinlock_t        *lock= &kiblnd_data.kib_connd_lock;
3523         wait_queue_entry_t wait;
3524         unsigned long      flags;
3525         struct kib_conn *conn;
3526         int                timeout;
3527         int                i;
3528         int                dropped_lock;
3529         int                peer_index = 0;
3530         unsigned long      deadline = jiffies;
3531
3532         cfs_block_allsigs();
3533
3534         init_waitqueue_entry(&wait, current);
3535         kiblnd_data.kib_connd = current;
3536
3537         spin_lock_irqsave(lock, flags);
3538
3539         while (!kiblnd_data.kib_shutdown) {
3540                 int reconn = 0;
3541
3542                 dropped_lock = 0;
3543
3544                 if (!list_empty(&kiblnd_data.kib_connd_zombies)) {
3545                         struct kib_peer_ni *peer_ni = NULL;
3546
3547                         conn = list_entry(kiblnd_data.kib_connd_zombies.next,
3548                                           struct kib_conn, ibc_list);
3549                         list_del(&conn->ibc_list);
3550                         if (conn->ibc_reconnect) {
3551                                 peer_ni = conn->ibc_peer;
3552                                 kiblnd_peer_addref(peer_ni);
3553                         }
3554
3555                         spin_unlock_irqrestore(lock, flags);
3556                         dropped_lock = 1;
3557
3558                         kiblnd_destroy_conn(conn);
3559
3560                         spin_lock_irqsave(lock, flags);
3561                         if (!peer_ni) {
3562                                 LIBCFS_FREE(conn, sizeof(*conn));
3563                                 continue;
3564                         }
3565
3566                         conn->ibc_peer = peer_ni;
3567                         if (peer_ni->ibp_reconnected < KIB_RECONN_HIGH_RACE)
3568                                 list_add_tail(&conn->ibc_list,
3569                                               &kiblnd_data.kib_reconn_list);
3570                         else
3571                                 list_add_tail(&conn->ibc_list,
3572                                               &kiblnd_data.kib_reconn_wait);
3573                 }
3574
3575                 if (!list_empty(&kiblnd_data.kib_connd_conns)) {
3576                         conn = list_entry(kiblnd_data.kib_connd_conns.next,
3577                                           struct kib_conn, ibc_list);
3578                         list_del(&conn->ibc_list);
3579
3580                         spin_unlock_irqrestore(lock, flags);
3581                         dropped_lock = 1;
3582
3583                         kiblnd_disconnect_conn(conn);
3584                         kiblnd_conn_decref(conn);
3585
3586                         spin_lock_irqsave(lock, flags);
3587                 }
3588
3589                 while (reconn < KIB_RECONN_BREAK) {
3590                         if (kiblnd_data.kib_reconn_sec !=
3591                             ktime_get_real_seconds()) {
3592                                 kiblnd_data.kib_reconn_sec = ktime_get_real_seconds();
3593                                 list_splice_init(&kiblnd_data.kib_reconn_wait,
3594                                                  &kiblnd_data.kib_reconn_list);
3595                         }
3596
3597                         if (list_empty(&kiblnd_data.kib_reconn_list))
3598                                 break;
3599
3600                         conn = list_entry(kiblnd_data.kib_reconn_list.next,
3601                                           struct kib_conn, ibc_list);
3602                         list_del(&conn->ibc_list);
3603
3604                         spin_unlock_irqrestore(lock, flags);
3605                         dropped_lock = 1;
3606
3607                         reconn += kiblnd_reconnect_peer(conn->ibc_peer);
3608                         kiblnd_peer_decref(conn->ibc_peer);
3609                         LIBCFS_FREE(conn, sizeof(*conn));
3610
3611                         spin_lock_irqsave(lock, flags);
3612                 }
3613
3614                 /* careful with the jiffy wrap... */
3615                 timeout = (int)(deadline - jiffies);
3616                 if (timeout <= 0) {
3617                         const int n = 4;
3618                         const int p = 1;
3619                         int       chunk = kiblnd_data.kib_peer_hash_size;
3620                         unsigned int lnd_timeout;
3621
3622                         spin_unlock_irqrestore(lock, flags);
3623                         dropped_lock = 1;
3624
3625                         /* Time to check for RDMA timeouts on a few more
3626                          * peers: I do checks every 'p' seconds on a
3627                          * proportion of the peer_ni table and I need to check
3628                          * every connection 'n' times within a timeout
3629                          * interval, to ensure I detect a timeout on any
3630                          * connection within (n+1)/n times the timeout
3631                          * interval. */
3632
3633                         lnd_timeout = lnet_get_lnd_timeout();
3634                         if (lnd_timeout > n * p)
3635                                 chunk = (chunk * n * p) / lnd_timeout;
3636                         if (chunk == 0)
3637                                 chunk = 1;
3638
3639                         for (i = 0; i < chunk; i++) {
3640                                 kiblnd_check_conns(peer_index);
3641                                 peer_index = (peer_index + 1) %
3642                                              kiblnd_data.kib_peer_hash_size;
3643                         }
3644
3645                         deadline += msecs_to_jiffies(p * MSEC_PER_SEC);
3646                         spin_lock_irqsave(lock, flags);
3647                 }
3648
3649                 if (dropped_lock)
3650                         continue;
3651
3652                 /* Nothing to do for 'timeout'  */
3653                 set_current_state(TASK_INTERRUPTIBLE);
3654                 add_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3655                 spin_unlock_irqrestore(lock, flags);
3656
3657                 schedule_timeout(timeout);
3658
3659                 set_current_state(TASK_RUNNING);
3660                 remove_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3661                 spin_lock_irqsave(lock, flags);
3662         }
3663
3664         spin_unlock_irqrestore(lock, flags);
3665
3666         kiblnd_thread_fini();
3667         return 0;
3668 }
3669
3670 void
3671 kiblnd_qp_event(struct ib_event *event, void *arg)
3672 {
3673         struct kib_conn *conn = arg;
3674
3675         switch (event->event) {
3676         case IB_EVENT_COMM_EST:
3677                 CDEBUG(D_NET, "%s established\n",
3678                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
3679                 /* We received a packet but connection isn't established
3680                  * probably handshake packet was lost, so free to
3681                  * force make connection established */
3682                 rdma_notify(conn->ibc_cmid, IB_EVENT_COMM_EST);
3683                 return;
3684
3685         case IB_EVENT_PORT_ERR:
3686         case IB_EVENT_DEVICE_FATAL:
3687                 CERROR("Fatal device error for NI %s\n",
3688                        libcfs_nid2str(conn->ibc_peer->ibp_ni->ni_nid));
3689                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 1);
3690                 return;
3691
3692         case IB_EVENT_PORT_ACTIVE:
3693                 CERROR("Port reactivated for NI %s\n",
3694                        libcfs_nid2str(conn->ibc_peer->ibp_ni->ni_nid));
3695                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 0);
3696                 return;
3697
3698         default:
3699                 CERROR("%s: Async QP event type %d\n",
3700                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3701                 return;
3702         }
3703 }
3704
3705 static void
3706 kiblnd_complete (struct ib_wc *wc)
3707 {
3708         switch (kiblnd_wreqid2type(wc->wr_id)) {
3709         default:
3710                 LBUG();
3711
3712         case IBLND_WID_MR:
3713                 if (wc->status != IB_WC_SUCCESS &&
3714                     wc->status != IB_WC_WR_FLUSH_ERR)
3715                         CNETERR("FastReg failed: %d\n", wc->status);
3716                 return;
3717
3718         case IBLND_WID_RDMA:
3719                 /* We only get RDMA completion notification if it fails.  All
3720                  * subsequent work items, including the final SEND will fail
3721                  * too.  However we can't print out any more info about the
3722                  * failing RDMA because 'tx' might be back on the idle list or
3723                  * even reused already if we didn't manage to post all our work
3724                  * items */
3725                 CNETERR("RDMA (tx: %p) failed: %d\n",
3726                         kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3727                 return;
3728
3729         case IBLND_WID_TX:
3730                 kiblnd_tx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3731                 return;
3732
3733         case IBLND_WID_RX:
3734                 kiblnd_rx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status,
3735                                    wc->byte_len);
3736                 return;
3737         }
3738 }
3739
3740 void
3741 kiblnd_cq_completion(struct ib_cq *cq, void *arg)
3742 {
3743         /* NB I'm not allowed to schedule this conn once its refcount has
3744          * reached 0.  Since fundamentally I'm racing with scheduler threads
3745          * consuming my CQ I could be called after all completions have
3746          * occurred.  But in this case, ibc_nrx == 0 && ibc_nsends_posted == 0
3747          * and this CQ is about to be destroyed so I NOOP. */
3748         struct kib_conn *conn = arg;
3749         struct kib_sched_info *sched = conn->ibc_sched;
3750         unsigned long flags;
3751
3752         LASSERT(cq == conn->ibc_cq);
3753
3754         spin_lock_irqsave(&sched->ibs_lock, flags);
3755
3756         conn->ibc_ready = 1;
3757
3758         if (!conn->ibc_scheduled &&
3759             (conn->ibc_nrx > 0 ||
3760              conn->ibc_nsends_posted > 0)) {
3761                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3762                 conn->ibc_scheduled = 1;
3763                 list_add_tail(&conn->ibc_sched_list, &sched->ibs_conns);
3764
3765                 if (waitqueue_active(&sched->ibs_waitq))
3766                         wake_up(&sched->ibs_waitq);
3767         }
3768
3769         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3770 }
3771
3772 void
3773 kiblnd_cq_event(struct ib_event *event, void *arg)
3774 {
3775         struct kib_conn *conn = arg;
3776
3777         CERROR("%s: async CQ event type %d\n",
3778                libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3779 }
3780
3781 int
3782 kiblnd_scheduler(void *arg)
3783 {
3784         long                    id = (long)arg;
3785         struct kib_sched_info   *sched;
3786         struct kib_conn *conn;
3787         wait_queue_entry_t      wait;
3788         unsigned long           flags;
3789         struct ib_wc            wc;
3790         int                     did_something;
3791         int                     busy_loops = 0;
3792         int                     rc;
3793
3794         cfs_block_allsigs();
3795
3796         init_waitqueue_entry(&wait, current);
3797
3798         sched = kiblnd_data.kib_scheds[KIB_THREAD_CPT(id)];
3799
3800         rc = cfs_cpt_bind(lnet_cpt_table(), sched->ibs_cpt);
3801         if (rc != 0) {
3802                 CWARN("Unable to bind on CPU partition %d, please verify "
3803                       "whether all CPUs are healthy and reload modules if "
3804                       "necessary, otherwise your system might under risk of "
3805                       "low performance\n", sched->ibs_cpt);
3806         }
3807
3808         spin_lock_irqsave(&sched->ibs_lock, flags);
3809
3810         while (!kiblnd_data.kib_shutdown) {
3811                 if (busy_loops++ >= IBLND_RESCHED) {
3812                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3813
3814                         cond_resched();
3815                         busy_loops = 0;
3816
3817                         spin_lock_irqsave(&sched->ibs_lock, flags);
3818                 }
3819
3820                 did_something = 0;
3821
3822                 if (!list_empty(&sched->ibs_conns)) {
3823                         conn = list_entry(sched->ibs_conns.next,
3824                                           struct kib_conn, ibc_sched_list);
3825                         /* take over kib_sched_conns' ref on conn... */
3826                         LASSERT(conn->ibc_scheduled);
3827                         list_del(&conn->ibc_sched_list);
3828                         conn->ibc_ready = 0;
3829
3830                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3831
3832                         wc.wr_id = IBLND_WID_INVAL;
3833
3834                         rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3835                         if (rc == 0) {
3836                                 rc = ib_req_notify_cq(conn->ibc_cq,
3837                                                       IB_CQ_NEXT_COMP);
3838                                 if (rc < 0) {
3839                                         CWARN("%s: ib_req_notify_cq failed: %d, "
3840                                               "closing connection\n",
3841                                               libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
3842                                         kiblnd_close_conn(conn, -EIO);
3843                                         kiblnd_conn_decref(conn);
3844                                         spin_lock_irqsave(&sched->ibs_lock,
3845                                                               flags);
3846                                         continue;
3847                                 }
3848
3849                                 rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3850                         }
3851
3852                         if (unlikely(rc > 0 && wc.wr_id == IBLND_WID_INVAL)) {
3853                                 LCONSOLE_ERROR(
3854                                         "ib_poll_cq (rc: %d) returned invalid "
3855                                         "wr_id, opcode %d, status: %d, "
3856                                         "vendor_err: %d, conn: %s status: %d\n"
3857                                         "please upgrade firmware and OFED or "
3858                                         "contact vendor.\n", rc,
3859                                         wc.opcode, wc.status, wc.vendor_err,
3860                                         libcfs_nid2str(conn->ibc_peer->ibp_nid),
3861                                         conn->ibc_state);
3862                                 rc = -EINVAL;
3863                         }
3864
3865                         if (rc < 0) {
3866                                 CWARN("%s: ib_poll_cq failed: %d, "
3867                                       "closing connection\n",
3868                                       libcfs_nid2str(conn->ibc_peer->ibp_nid),
3869                                       rc);
3870                                 kiblnd_close_conn(conn, -EIO);
3871                                 kiblnd_conn_decref(conn);
3872                                 spin_lock_irqsave(&sched->ibs_lock, flags);
3873                                 continue;
3874                         }
3875
3876                         spin_lock_irqsave(&sched->ibs_lock, flags);
3877
3878                         if (rc != 0 || conn->ibc_ready) {
3879                                 /* There may be another completion waiting; get
3880                                  * another scheduler to check while I handle
3881                                  * this one... */
3882                                 /* +1 ref for sched_conns */
3883                                 kiblnd_conn_addref(conn);
3884                                 list_add_tail(&conn->ibc_sched_list,
3885                                                   &sched->ibs_conns);
3886                                 if (waitqueue_active(&sched->ibs_waitq))
3887                                         wake_up(&sched->ibs_waitq);
3888                         } else {
3889                                 conn->ibc_scheduled = 0;
3890                         }
3891
3892                         if (rc != 0) {
3893                                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
3894                                 kiblnd_complete(&wc);
3895
3896                                 spin_lock_irqsave(&sched->ibs_lock, flags);
3897                         }
3898
3899                         kiblnd_conn_decref(conn); /* ...drop my ref from above */
3900                         did_something = 1;
3901                 }
3902
3903                 if (did_something)
3904                         continue;
3905
3906                 set_current_state(TASK_INTERRUPTIBLE);
3907                 add_wait_queue_exclusive(&sched->ibs_waitq, &wait);
3908                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
3909
3910                 schedule();
3911                 busy_loops = 0;
3912
3913                 remove_wait_queue(&sched->ibs_waitq, &wait);
3914                 set_current_state(TASK_RUNNING);
3915                 spin_lock_irqsave(&sched->ibs_lock, flags);
3916         }
3917
3918         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3919
3920         kiblnd_thread_fini();
3921         return 0;
3922 }
3923
3924 int
3925 kiblnd_failover_thread(void *arg)
3926 {
3927         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
3928         struct kib_dev *dev;
3929         struct net *ns = arg;
3930         wait_queue_entry_t wait;
3931         unsigned long    flags;
3932         int              rc;
3933
3934         LASSERT(*kiblnd_tunables.kib_dev_failover != 0);
3935
3936         cfs_block_allsigs();
3937
3938         init_waitqueue_entry(&wait, current);
3939         write_lock_irqsave(glock, flags);
3940
3941         while (!kiblnd_data.kib_shutdown) {
3942                 int     do_failover = 0;
3943                 int     long_sleep;
3944
3945                 list_for_each_entry(dev, &kiblnd_data.kib_failed_devs,
3946                                     ibd_fail_list) {
3947                         if (ktime_get_seconds() < dev->ibd_next_failover)
3948                                 continue;
3949                         do_failover = 1;
3950                         break;
3951                 }
3952
3953                 if (do_failover) {
3954                         list_del_init(&dev->ibd_fail_list);
3955                         dev->ibd_failover = 1;
3956                         write_unlock_irqrestore(glock, flags);
3957
3958                         rc = kiblnd_dev_failover(dev, ns);
3959
3960                         write_lock_irqsave(glock, flags);
3961
3962                         LASSERT (dev->ibd_failover);
3963                         dev->ibd_failover = 0;
3964                         if (rc >= 0) { /* Device is OK or failover succeed */
3965                                 dev->ibd_next_failover = ktime_get_seconds() + 3;
3966                                 continue;
3967                         }
3968
3969                         /* failed to failover, retry later */
3970                         dev->ibd_next_failover = ktime_get_seconds() +
3971                                                  min(dev->ibd_failed_failover, 10);
3972                         if (kiblnd_dev_can_failover(dev)) {
3973                                 list_add_tail(&dev->ibd_fail_list,
3974                                               &kiblnd_data.kib_failed_devs);
3975                         }
3976
3977                         continue;
3978                 }
3979
3980                 /* long sleep if no more pending failover */
3981                 long_sleep = list_empty(&kiblnd_data.kib_failed_devs);
3982
3983                 set_current_state(TASK_INTERRUPTIBLE);
3984                 add_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
3985                 write_unlock_irqrestore(glock, flags);
3986
3987                 rc = schedule_timeout(long_sleep ? cfs_time_seconds(10) :
3988                                                    cfs_time_seconds(1));
3989                 set_current_state(TASK_RUNNING);
3990                 remove_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
3991                 write_lock_irqsave(glock, flags);
3992
3993                 if (!long_sleep || rc != 0)
3994                         continue;
3995
3996                 /* have a long sleep, routine check all active devices,
3997                  * we need checking like this because if there is not active
3998                  * connection on the dev and no SEND from local, we may listen
3999                  * on wrong HCA for ever while there is a bonding failover */
4000                 list_for_each_entry(dev, &kiblnd_data.kib_devs, ibd_list) {
4001                         if (kiblnd_dev_can_failover(dev)) {
4002                                 list_add_tail(&dev->ibd_fail_list,
4003                                               &kiblnd_data.kib_failed_devs);
4004                         }
4005                 }
4006         }
4007
4008         write_unlock_irqrestore(glock, flags);
4009
4010         kiblnd_thread_fini();
4011         return 0;
4012 }