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