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