Whamcloud - gitweb
LU-17325 o2iblnd: CM_EVENT_UNREACHABLE on established conn
[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_OFED_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_OFED_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_OFED_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_OFED_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_OFED_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_OFED_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_OFED_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_OFED_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_OFED_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_OFED_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_OFED_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_OFED_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_OFED_IB_GET_DMA_MR
1135         struct ib_mr *mr = hdev->ibh_mrs;
1136 #endif
1137
1138         *sge = (struct ib_sge) {
1139 #ifdef HAVE_OFED_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_OFED_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_OFED_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 (%s:%d:%pI4h): net for nid %s not added yet\n",
2579                                 libcfs_nid2str(nid),
2580                                 ibdev->ibd_ifname, ibdev->ibd_nnets,
2581                                 &ibdev->ibd_ifip,
2582                                 libcfs_nid2str(reqmsg->ibm_dstnid));
2583                         goto failed;
2584                 }
2585                 list_for_each_entry(net, &ibdev->ibd_nets, ibn_list) {
2586                         if ((net->ibn_dev == ibdev) &&
2587                             (net->ibn_ni != NULL) &&
2588                             (net->ibn_ni->ni_state != LNET_NI_STATE_ACTIVE)) {
2589                                 rej.ibr_why = IBLND_REJECT_EARLY;
2590                                 CNETERR("Can't accept conn from %s on %s (%s:%d:%pI4h): nid %s not ready\n",
2591                                        libcfs_nid2str(nid),
2592                                        libcfs_nidstr(&net->ibn_ni->ni_nid),
2593                                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2594                                        &ibdev->ibd_ifip,
2595                                        libcfs_nid2str(reqmsg->ibm_dstnid));
2596                                 goto failed;
2597                         }
2598                 }
2599         }
2600
2601         if (ni == NULL ||                       /* no matching net */
2602             !nid_same(&ni->ni_nid, &destnid) || /* right NET, wrong NID! */
2603             net->ibn_dev != ibdev) {            /* wrong device */
2604                 CERROR("Can't accept conn from %s on %s (%s:%d:%pI4h): bad dst nid %s\n",
2605                        libcfs_nid2str(nid),
2606                        ni ? libcfs_nidstr(&ni->ni_nid) : "NA",
2607                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2608                        &ibdev->ibd_ifip,
2609                        libcfs_nid2str(reqmsg->ibm_dstnid));
2610
2611                 goto failed;
2612         }
2613
2614         /* check time stamp as soon as possible */
2615         if (reqmsg->ibm_dststamp != 0 &&
2616             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2617                 CWARN("Stale connection request\n");
2618                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2619                 goto failed;
2620         }
2621
2622         /* I can accept peer_ni's version */
2623         version = reqmsg->ibm_version;
2624
2625         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2626                 CERROR("Unexpected connreq msg type: %x from %s\n",
2627                        reqmsg->ibm_type, libcfs_nid2str(nid));
2628                 goto failed;
2629         }
2630
2631         if (reqmsg->ibm_u.connparams.ibcp_queue_depth >
2632             kiblnd_msg_queue_size(version, ni)) {
2633                 CERROR("Can't accept conn from %s, queue depth too large:  %d (<=%d wanted)\n",
2634                        libcfs_nid2str(nid),
2635                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2636                        kiblnd_msg_queue_size(version, ni));
2637
2638                 if (version == IBLND_MSG_VERSION)
2639                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2640
2641                 goto failed;
2642         }
2643
2644         if (reqmsg->ibm_u.connparams.ibcp_max_frags >
2645             IBLND_MAX_RDMA_FRAGS) {
2646                 CWARN("Can't accept conn from %s (version %x): max_frags %d too large (%d wanted)\n",
2647                       libcfs_nid2str(nid), version,
2648                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2649                       IBLND_MAX_RDMA_FRAGS);
2650
2651                 if (version >= IBLND_MSG_VERSION)
2652                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2653
2654                 goto failed;
2655         } else if (reqmsg->ibm_u.connparams.ibcp_max_frags <
2656                    IBLND_MAX_RDMA_FRAGS &&
2657                    net->ibn_fmr_ps == NULL) {
2658                 CWARN("Can't accept conn from %s (version %x): max_frags %d incompatible without FMR pool (%d wanted)\n",
2659                       libcfs_nid2str(nid), version,
2660                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2661                       IBLND_MAX_RDMA_FRAGS);
2662
2663                 if (version == IBLND_MSG_VERSION)
2664                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2665
2666                 goto failed;
2667         }
2668
2669         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2670                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2671                        libcfs_nid2str(nid),
2672                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2673                        IBLND_MSG_SIZE);
2674                 goto failed;
2675         }
2676
2677         /* assume 'nid' is a new peer_ni; create  */
2678         rc = kiblnd_create_peer(ni, &peer_ni, nid);
2679         if (rc != 0) {
2680                 CERROR("Can't create peer_ni for %s\n", libcfs_nid2str(nid));
2681                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2682                 goto failed;
2683         }
2684
2685         /* We have validated the peer's parameters so use those */
2686         peer_ni->ibp_max_frags = reqmsg->ibm_u.connparams.ibcp_max_frags;
2687         peer_ni->ibp_queue_depth = reqmsg->ibm_u.connparams.ibcp_queue_depth;
2688
2689         write_lock_irqsave(g_lock, flags);
2690
2691         peer2 = kiblnd_find_peer_locked(ni, nid);
2692         if (peer2 != NULL) {
2693                 if (peer2->ibp_version == 0) {
2694                         peer2->ibp_version     = version;
2695                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2696                 }
2697
2698                 /* not the guy I've talked with */
2699                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2700                     peer2->ibp_version     != version) {
2701                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2702
2703                         if (kiblnd_peer_active(peer2)) {
2704                                 peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2705                                 peer2->ibp_version = version;
2706                         }
2707                         write_unlock_irqrestore(g_lock, flags);
2708
2709                         CWARN("Conn stale %s version %x/%x incarnation %llu/%llu\n",
2710                               libcfs_nid2str(nid), peer2->ibp_version, version,
2711                               peer2->ibp_incarnation, reqmsg->ibm_srcstamp);
2712
2713                         kiblnd_peer_decref(peer_ni);
2714                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2715                         goto failed;
2716                 }
2717
2718                 /* Tie-break connection race in favour of the higher NID.
2719                  * If we keep running into a race condition multiple times,
2720                  * we have to assume that the connection attempt with the
2721                  * higher NID is stuck in a connecting state and will never
2722                  * recover.  As such, we pass through this if-block and let
2723                  * the lower NID connection win so we can move forward.
2724                  */
2725                 if (peer2->ibp_connecting != 0 &&
2726                     nid < lnet_nid_to_nid4(&ni->ni_nid) &&
2727                     peer2->ibp_races < MAX_CONN_RACES_BEFORE_ABORT) {
2728                         peer2->ibp_races++;
2729                         write_unlock_irqrestore(g_lock, flags);
2730
2731                         CDEBUG(D_NET, "Conn race %s\n",
2732                                libcfs_nid2str(peer2->ibp_nid));
2733
2734                         kiblnd_peer_decref(peer_ni);
2735                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2736                         goto failed;
2737                 }
2738                 if (peer2->ibp_races >= MAX_CONN_RACES_BEFORE_ABORT)
2739                         CNETERR("Conn race %s: unresolved after %d attempts, letting lower NID win\n",
2740                                 libcfs_nid2str(peer2->ibp_nid),
2741                                 MAX_CONN_RACES_BEFORE_ABORT);
2742                 /*
2743                  * passive connection is allowed even this peer_ni is waiting for
2744                  * reconnection.
2745                  */
2746                 peer2->ibp_reconnecting = 0;
2747                 peer2->ibp_races = 0;
2748                 peer2->ibp_accepting++;
2749                 kiblnd_peer_addref(peer2);
2750
2751                 /* Race with kiblnd_launch_tx (active connect) to create peer_ni
2752                  * so copy validated parameters since we now know what the
2753                  * peer_ni's limits are */
2754                 peer2->ibp_max_frags = peer_ni->ibp_max_frags;
2755                 peer2->ibp_queue_depth = peer_ni->ibp_queue_depth;
2756
2757                 write_unlock_irqrestore(g_lock, flags);
2758                 kiblnd_peer_decref(peer_ni);
2759                 peer_ni = peer2;
2760         } else {
2761                 /* Brand new peer_ni */
2762                 LASSERT(peer_ni->ibp_accepting == 0);
2763                 LASSERT(peer_ni->ibp_version == 0 &&
2764                         peer_ni->ibp_incarnation == 0);
2765
2766                 peer_ni->ibp_accepting   = 1;
2767                 peer_ni->ibp_version     = version;
2768                 peer_ni->ibp_incarnation = reqmsg->ibm_srcstamp;
2769
2770                 /* I have a ref on ni that prevents it being shutdown */
2771                 LASSERT(net->ibn_shutdown == 0);
2772
2773                 kiblnd_peer_addref(peer_ni);
2774                 hash_add(kiblnd_data.kib_peers, &peer_ni->ibp_list, nid);
2775
2776                 write_unlock_irqrestore(g_lock, flags);
2777         }
2778
2779         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_PASSIVE_WAIT,
2780                                   version);
2781         if (!conn) {
2782                 kiblnd_peer_connect_failed(peer_ni, 0, -ENOMEM);
2783                 kiblnd_peer_decref(peer_ni);
2784                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2785                 goto failed;
2786         }
2787
2788         /* conn now "owns" cmid, so I return success from here on to ensure the
2789          * CM callback doesn't destroy cmid.
2790          */
2791         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2792         conn->ibc_credits          = conn->ibc_queue_depth;
2793         conn->ibc_reserved_credits = conn->ibc_queue_depth;
2794         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2795                 IBLND_OOB_MSGS(version) <= IBLND_RX_MSGS(conn));
2796
2797         ackmsg = &conn->ibc_connvars->cv_msg;
2798         memset(ackmsg, 0, sizeof(*ackmsg));
2799
2800         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2801                         sizeof(ackmsg->ibm_u.connparams));
2802         ackmsg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2803         ackmsg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2804         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2805
2806         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2807
2808         memset(&cp, 0, sizeof(cp));
2809         cp.private_data        = ackmsg;
2810         cp.private_data_len    = ackmsg->ibm_nob;
2811         cp.responder_resources = 0;            /* No atomic ops or RDMA reads */
2812         cp.initiator_depth     = 0;
2813         cp.flow_control        = 1;
2814         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2815         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2816
2817         CDEBUG(D_NET, "Accept %s conn %p\n", libcfs_nid2str(nid), conn);
2818
2819         rc = rdma_accept(cmid, &cp);
2820         if (rc != 0) {
2821                 CNETERR("Can't accept %s: %d cm_id %p\n", libcfs_nid2str(nid), rc, cmid);
2822                 rej.ibr_version = version;
2823                 rej.ibr_why     = IBLND_REJECT_FATAL;
2824
2825                 kiblnd_reject(cmid, &rej);
2826                 kiblnd_connreq_done(conn, rc);
2827                 kiblnd_conn_decref(conn);
2828         }
2829
2830         lnet_ni_decref(ni);
2831         return 0;
2832
2833  failed:
2834         if (ni != NULL) {
2835                 rej.ibr_cp.ibcp_queue_depth =
2836                         kiblnd_msg_queue_size(version, ni);
2837                 rej.ibr_cp.ibcp_max_frags   = IBLND_MAX_RDMA_FRAGS;
2838                 lnet_ni_decref(ni);
2839         }
2840
2841         rej.ibr_version = version;
2842         kiblnd_reject(cmid, &rej);
2843
2844         return -ECONNREFUSED;
2845 }
2846
2847 static void
2848 kiblnd_check_reconnect(struct kib_conn *conn, int version,
2849                        u64 incarnation, int why, struct kib_connparams *cp)
2850 {
2851         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
2852         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2853         char            *reason;
2854         int              msg_size = IBLND_MSG_SIZE;
2855         int              frag_num = -1;
2856         int              queue_dep = -1;
2857         bool             reconnect;
2858         unsigned long    flags;
2859
2860         LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2861         LASSERT(peer_ni->ibp_connecting > 0);   /* 'conn' at least */
2862
2863         if (cp) {
2864                 msg_size        = cp->ibcp_max_msg_size;
2865                 frag_num        = cp->ibcp_max_frags;
2866                 queue_dep       = cp->ibcp_queue_depth;
2867         }
2868
2869         write_lock_irqsave(glock, flags);
2870         /* retry connection if it's still needed and no other connection
2871          * attempts (active or passive) are in progress
2872          * NB: reconnect is still needed even when ibp_tx_queue is
2873          * empty if ibp_version != version because reconnect may be
2874          * initiated.
2875          */
2876         reconnect = (!list_empty(&peer_ni->ibp_tx_queue) ||
2877                      peer_ni->ibp_version != version) &&
2878                     peer_ni->ibp_connecting &&
2879                     peer_ni->ibp_accepting == 0;
2880         if (!reconnect) {
2881                 reason = "no need";
2882                 goto out;
2883         }
2884
2885         switch (why) {
2886         default:
2887                 reason = "Unknown";
2888                 break;
2889
2890         case IBLND_REJECT_RDMA_FRAGS: {
2891                 if (!cp) {
2892                         reason = "can't negotiate max frags";
2893                         goto out;
2894                 }
2895
2896                 if (conn->ibc_max_frags <= frag_num) {
2897                         reason = "unsupported max frags";
2898                         goto out;
2899                 }
2900
2901                 peer_ni->ibp_max_frags = frag_num;
2902                 reason = "rdma fragments";
2903                 break;
2904         }
2905         case IBLND_REJECT_MSG_QUEUE_SIZE:
2906                 if (!cp) {
2907                         reason = "can't negotiate queue depth";
2908                         goto out;
2909                 }
2910                 if (conn->ibc_queue_depth <= queue_dep) {
2911                         reason = "unsupported queue depth";
2912                         goto out;
2913                 }
2914
2915                 peer_ni->ibp_queue_depth = queue_dep;
2916                 reason = "queue depth";
2917                 break;
2918
2919         case IBLND_REJECT_CONN_STALE:
2920                 reason = "stale";
2921                 break;
2922
2923         case IBLND_REJECT_CONN_RACE:
2924                 reason = "conn race";
2925                 break;
2926
2927         case IBLND_REJECT_CONN_UNCOMPAT:
2928                 reason = "version negotiation";
2929                 break;
2930         }
2931
2932         conn->ibc_reconnect = 1;
2933         peer_ni->ibp_reconnecting++;
2934         peer_ni->ibp_version = version;
2935         if (incarnation != 0)
2936                 peer_ni->ibp_incarnation = incarnation;
2937  out:
2938         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2939
2940         CNETERR("%s: %s (%s), %x, %x, msg_size: %d, queue_depth: %d/%d, max_frags: %d/%d\n",
2941                 libcfs_nid2str(peer_ni->ibp_nid),
2942                 reconnect ? "reconnect" : "don't reconnect",
2943                 reason, IBLND_MSG_VERSION, version, msg_size,
2944                 conn->ibc_queue_depth, queue_dep,
2945                 conn->ibc_max_frags, frag_num);
2946         /*
2947          * if conn::ibc_reconnect is TRUE, connd will reconnect to the peer_ni
2948          * while destroying the zombie
2949          */
2950 }
2951
2952 static void
2953 kiblnd_rejected(struct kib_conn *conn, int reason, void *priv, int priv_nob)
2954 {
2955         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2956         int status = -ECONNREFUSED;
2957
2958         LASSERT (!in_interrupt());
2959         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2960
2961         switch (reason) {
2962         case IB_CM_REJ_STALE_CONN:
2963                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2964                                        IBLND_REJECT_CONN_STALE, NULL);
2965                 break;
2966
2967         case IB_CM_REJ_INVALID_SERVICE_ID:
2968                 status = -EHOSTUNREACH;
2969                 CNETERR("%s rejected: no listener at %d\n",
2970                         libcfs_nid2str(peer_ni->ibp_nid),
2971                         *kiblnd_tunables.kib_service);
2972                 break;
2973
2974         case IB_CM_REJ_CONSUMER_DEFINED:
2975                 if (priv_nob >= offsetof(struct kib_rej, ibr_padding)) {
2976                         struct kib_rej *rej = priv;
2977                         struct kib_connparams *cp = NULL;
2978                         bool flip = false;
2979                         __u64 incarnation = -1;
2980
2981                         /* NB. default incarnation is -1 because:
2982                          * a) V1 will ignore dst incarnation in connreq.
2983                          * b) V2 will provide incarnation while rejecting me,
2984                          *    -1 will be overwrote.
2985                          *
2986                          * if I try to connect to a V1 peer_ni with V2 protocol,
2987                          * it rejected me then upgrade to V2, I have no idea
2988                          * about the upgrading and try to reconnect with V1,
2989                          * in this case upgraded V2 can find out I'm trying to
2990                          * talk to the old guy and reject me(incarnation is -1).
2991                          */
2992
2993                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2994                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2995                                 __swab32s(&rej->ibr_magic);
2996                                 __swab16s(&rej->ibr_version);
2997                                 flip = true;
2998                         }
2999
3000                         if (priv_nob >= sizeof(struct kib_rej) &&
3001                             rej->ibr_version > IBLND_MSG_VERSION_1) {
3002                                 /* priv_nob is always 148 in current version
3003                                  * of OFED, so we still need to check version.
3004                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE)
3005                                  */
3006                                 cp = &rej->ibr_cp;
3007
3008                                 if (flip) {
3009                                         __swab64s(&rej->ibr_incarnation);
3010                                         __swab16s(&cp->ibcp_queue_depth);
3011                                         __swab16s(&cp->ibcp_max_frags);
3012                                         __swab32s(&cp->ibcp_max_msg_size);
3013                                 }
3014
3015                                 incarnation = rej->ibr_incarnation;
3016                         }
3017
3018                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
3019                             rej->ibr_magic != LNET_PROTO_MAGIC) {
3020                                 CERROR("%s rejected: consumer defined fatal error\n",
3021                                        libcfs_nid2str(peer_ni->ibp_nid));
3022                                 break;
3023                         }
3024
3025                         if (rej->ibr_version != IBLND_MSG_VERSION &&
3026                             rej->ibr_version != IBLND_MSG_VERSION_1) {
3027                                 CERROR("%s rejected: o2iblnd version %x error\n",
3028                                        libcfs_nid2str(peer_ni->ibp_nid),
3029                                        rej->ibr_version);
3030                                 break;
3031                         }
3032
3033                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
3034                             rej->ibr_version == IBLND_MSG_VERSION_1) {
3035                                 CDEBUG(D_NET, "rejected by old version peer_ni %s: %x\n",
3036                                        libcfs_nid2str(peer_ni->ibp_nid),
3037                                        rej->ibr_version);
3038
3039                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
3040                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
3041                         }
3042
3043                         switch (rej->ibr_why) {
3044                         case IBLND_REJECT_CONN_RACE:
3045                         case IBLND_REJECT_CONN_STALE:
3046                         case IBLND_REJECT_CONN_UNCOMPAT:
3047                         case IBLND_REJECT_MSG_QUEUE_SIZE:
3048                         case IBLND_REJECT_RDMA_FRAGS:
3049                                 kiblnd_check_reconnect(conn, rej->ibr_version,
3050                                                        incarnation,
3051                                                        rej->ibr_why, cp);
3052                                 break;
3053
3054                         case IBLND_REJECT_NO_RESOURCES:
3055                                 CERROR("%s rejected: o2iblnd no resources\n",
3056                                        libcfs_nid2str(peer_ni->ibp_nid));
3057                                 break;
3058
3059                         case IBLND_REJECT_FATAL:
3060                                 CERROR("%s rejected: o2iblnd fatal error\n",
3061                                        libcfs_nid2str(peer_ni->ibp_nid));
3062                                 break;
3063
3064                         case IBLND_REJECT_EARLY:
3065                                 CNETERR("%s rejected: tried too early\n",
3066                                        libcfs_nid2str(peer_ni->ibp_nid));
3067                                 break;
3068
3069                         default:
3070                                 CERROR("%s rejected: o2iblnd reason %d\n",
3071                                        libcfs_nid2str(peer_ni->ibp_nid),
3072                                        rej->ibr_why);
3073                                 break;
3074                         }
3075                         break;
3076                 }
3077                 fallthrough;
3078         default:
3079                 CNETERR("%s rejected: reason %d, size %d\n",
3080                         libcfs_nid2str(peer_ni->ibp_nid), reason, priv_nob);
3081                 break;
3082         }
3083
3084         kiblnd_connreq_done(conn, status);
3085 }
3086
3087 static void
3088 kiblnd_check_connreply(struct kib_conn *conn, void *priv, int priv_nob)
3089 {
3090         struct kib_peer_ni *peer_ni = conn->ibc_peer;
3091         struct lnet_ni *ni = peer_ni->ibp_ni;
3092         struct kib_net *net = ni->ni_data;
3093         struct kib_msg *msg = priv;
3094         int            ver  = conn->ibc_version;
3095         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
3096         unsigned long  flags;
3097
3098         LASSERT (net != NULL);
3099
3100         if (rc != 0) {
3101                 CERROR("Can't unpack connack from %s: %d\n",
3102                        libcfs_nid2str(peer_ni->ibp_nid), rc);
3103                 goto failed;
3104         }
3105
3106         if (msg->ibm_type != IBLND_MSG_CONNACK) {
3107                 CERROR("Unexpected message %d from %s\n",
3108                        msg->ibm_type, libcfs_nid2str(peer_ni->ibp_nid));
3109                 rc = -EPROTO;
3110                 goto failed;
3111         }
3112
3113         if (ver != msg->ibm_version) {
3114                 CERROR("%s replied version %x is different with "
3115                        "requested version %x\n",
3116                        libcfs_nid2str(peer_ni->ibp_nid), msg->ibm_version, ver);
3117                 rc = -EPROTO;
3118                 goto failed;
3119         }
3120
3121         if (msg->ibm_u.connparams.ibcp_queue_depth >
3122             conn->ibc_queue_depth) {
3123                 CERROR("%s has incompatible queue depth %d (<=%d wanted)\n",
3124                        libcfs_nid2str(peer_ni->ibp_nid),
3125                        msg->ibm_u.connparams.ibcp_queue_depth,
3126                        conn->ibc_queue_depth);
3127                 rc = -EPROTO;
3128                 goto failed;
3129         }
3130
3131         if (msg->ibm_u.connparams.ibcp_max_frags >
3132             conn->ibc_max_frags) {
3133                 CERROR("%s has incompatible max_frags %d (<=%d wanted)\n",
3134                        libcfs_nid2str(peer_ni->ibp_nid),
3135                        msg->ibm_u.connparams.ibcp_max_frags,
3136                        conn->ibc_max_frags);
3137                 rc = -EPROTO;
3138                 goto failed;
3139         }
3140
3141         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
3142                 CERROR("%s max message size %d too big (%d max)\n",
3143                        libcfs_nid2str(peer_ni->ibp_nid),
3144                        msg->ibm_u.connparams.ibcp_max_msg_size,
3145                        IBLND_MSG_SIZE);
3146                 rc = -EPROTO;
3147                 goto failed;
3148         }
3149
3150         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3151         if (msg->ibm_dstnid == lnet_nid_to_nid4(&ni->ni_nid) &&
3152             msg->ibm_dststamp == net->ibn_incarnation)
3153                 rc = 0;
3154         else
3155                 rc = -ESTALE;
3156         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3157
3158         if (rc != 0) {
3159                 CERROR("Bad connection reply from %s, rc = %d, "
3160                        "version: %x max_frags: %d\n",
3161                        libcfs_nid2str(peer_ni->ibp_nid), rc,
3162                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
3163                 goto failed;
3164         }
3165
3166         conn->ibc_incarnation      = msg->ibm_srcstamp;
3167         conn->ibc_credits          = msg->ibm_u.connparams.ibcp_queue_depth;
3168         conn->ibc_reserved_credits = msg->ibm_u.connparams.ibcp_queue_depth;
3169         conn->ibc_queue_depth      = msg->ibm_u.connparams.ibcp_queue_depth;
3170         conn->ibc_max_frags        = msg->ibm_u.connparams.ibcp_max_frags;
3171         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
3172                 IBLND_OOB_MSGS(ver) <= IBLND_RX_MSGS(conn));
3173
3174         kiblnd_connreq_done(conn, 0);
3175         return;
3176
3177  failed:
3178         /* NB My QP has already established itself, so I handle anything going
3179          * wrong here by setting ibc_comms_error.
3180          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
3181          * immediately tears it down. */
3182
3183         LASSERT (rc != 0);
3184         conn->ibc_comms_error = rc;
3185         kiblnd_connreq_done(conn, 0);
3186 }
3187
3188 static int
3189 kiblnd_active_connect(struct rdma_cm_id *cmid)
3190 {
3191         struct kib_peer_ni *peer_ni = cmid->context;
3192         struct kib_conn *conn;
3193         struct kib_msg *msg;
3194         struct rdma_conn_param cp;
3195         int                      version;
3196         __u64                    incarnation;
3197         unsigned long            flags;
3198         int                      rc;
3199
3200         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3201
3202         incarnation = peer_ni->ibp_incarnation;
3203         version     = (peer_ni->ibp_version == 0) ? IBLND_MSG_VERSION :
3204                                                  peer_ni->ibp_version;
3205
3206         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3207
3208         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_ACTIVE_CONNECT,
3209                                   version);
3210         if (conn == NULL) {
3211                 kiblnd_peer_connect_failed(peer_ni, 1, -ENOMEM);
3212                 kiblnd_peer_decref(peer_ni); /* lose cmid's ref */
3213                 return -ENOMEM;
3214         }
3215
3216         /* conn "owns" cmid now, so I return success from here on to ensure the
3217          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
3218          * on peer_ni */
3219
3220         msg = &conn->ibc_connvars->cv_msg;
3221
3222         memset(msg, 0, sizeof(*msg));
3223         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
3224         msg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
3225         msg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
3226         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
3227
3228         kiblnd_pack_msg(peer_ni->ibp_ni, msg, version,
3229                         0, peer_ni->ibp_nid, incarnation);
3230
3231         memset(&cp, 0, sizeof(cp));
3232         cp.private_data        = msg;
3233         cp.private_data_len    = msg->ibm_nob;
3234         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
3235         cp.initiator_depth     = 0;
3236         cp.flow_control        = 1;
3237         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
3238         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
3239
3240         LASSERT(cmid->context == (void *)conn);
3241         LASSERT(conn->ibc_cmid == cmid);
3242         rc = rdma_connect_locked(cmid, &cp);
3243         if (rc != 0) {
3244                 CNETERR("Can't connect to %s: %d cm_id %p\n",
3245                         libcfs_nid2str(peer_ni->ibp_nid), rc, cmid);
3246                 kiblnd_connreq_done(conn, rc);
3247                 kiblnd_conn_decref(conn);
3248         } else {
3249                 CDEBUG(D_NET, "Connected to %s: cm_id %p\n",
3250                         libcfs_nid2str(peer_ni->ibp_nid), cmid);
3251         }
3252
3253         return 0;
3254 }
3255
3256 int
3257 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
3258 {
3259         struct kib_peer_ni *peer_ni;
3260         struct kib_conn *conn;
3261         int rc;
3262
3263         switch (event->event) {
3264         default:
3265                 CERROR("Unexpected event: %d, status: %d\n",
3266                        event->event, event->status);
3267                 LBUG();
3268
3269         case RDMA_CM_EVENT_CONNECT_REQUEST:
3270                 /* destroy cmid on failure */
3271                 rc = kiblnd_passive_connect(cmid,
3272                                             (void *)KIBLND_CONN_PARAM(event),
3273                                             KIBLND_CONN_PARAM_LEN(event));
3274                 CDEBUG(D_NET, "connreq: %d cm_id %p\n", rc, cmid);
3275                 return rc;
3276
3277         case RDMA_CM_EVENT_ADDR_ERROR:
3278                 peer_ni = cmid->context;
3279                 CNETERR("%s: ADDR ERROR %d cm_id %p\n",
3280                         libcfs_nid2str(peer_ni->ibp_nid), event->status, cmid);
3281                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3282                 kiblnd_peer_decref(peer_ni);
3283                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
3284
3285         case RDMA_CM_EVENT_ADDR_RESOLVED:
3286                 peer_ni = cmid->context;
3287
3288                 CDEBUG(D_NET, "%s Addr resolved: %d cm_id %p\n",
3289                         libcfs_nid2str(peer_ni->ibp_nid), event->status, cmid);
3290
3291                 if (event->status != 0) {
3292                         CNETERR("Can't resolve address for %s: %d cm_id %p\n",
3293                                 libcfs_nid2str(peer_ni->ibp_nid),
3294                                 event->status, cmid);
3295                         rc = event->status;
3296                 } else {
3297                         rc = rdma_resolve_route(
3298                                 cmid, kiblnd_timeout() * 1000);
3299                         if (rc == 0) {
3300                                 struct kib_net *net = peer_ni->ibp_ni->ni_data;
3301                                 struct kib_dev *dev = net->ibn_dev;
3302
3303                                 CDEBUG(D_NET, "%s: connection bound to "\
3304                                        "%s:%pI4h:%s\n",
3305                                        libcfs_nid2str(peer_ni->ibp_nid),
3306                                        dev->ibd_ifname,
3307                                        &dev->ibd_ifip, cmid->device->name);
3308
3309                                 return 0;
3310                         }
3311
3312                         /* Can't initiate route resolution */
3313                         CNETERR("Can't resolve route for %s: %d cm_id %p\n",
3314                                 libcfs_nid2str(peer_ni->ibp_nid), rc, cmid);
3315                 }
3316                 kiblnd_peer_connect_failed(peer_ni, 1, rc);
3317                 kiblnd_peer_decref(peer_ni);
3318                 return rc;                      /* rc != 0 destroys cmid */
3319
3320         case RDMA_CM_EVENT_ROUTE_ERROR:
3321                 peer_ni = cmid->context;
3322                 CNETERR("%s: ROUTE ERROR %d cm_id %p\n",
3323                         libcfs_nid2str(peer_ni->ibp_nid), event->status, cmid);
3324                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3325                 kiblnd_peer_decref(peer_ni);
3326                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
3327
3328         case RDMA_CM_EVENT_ROUTE_RESOLVED:
3329                 peer_ni = cmid->context;
3330                 CDEBUG(D_NET,"%s Route resolved: %d\n",
3331                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3332
3333                 if (event->status == 0)
3334                         return kiblnd_active_connect(cmid);
3335
3336                 CNETERR("Can't resolve route for %s: %d cm_id %p\n",
3337                         libcfs_nid2str(peer_ni->ibp_nid), event->status, cmid);
3338                 kiblnd_peer_connect_failed(peer_ni, 1, event->status);
3339                 kiblnd_peer_decref(peer_ni);
3340                 return event->status;           /* rc != 0 destroys cmid */
3341
3342         case RDMA_CM_EVENT_UNREACHABLE:
3343                 conn = cmid->context;
3344                 CNETERR("%s: UNREACHABLE %d cm_id %p conn %p ibc_state: %d\n",
3345                         libcfs_nid2str(conn->ibc_peer->ibp_nid),
3346                         event->status, cmid, conn, conn->ibc_state);
3347                 LASSERT(conn->ibc_state != IBLND_CONN_INIT);
3348                 if (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3349                     conn->ibc_state == IBLND_CONN_PASSIVE_WAIT) {
3350                         kiblnd_connreq_done(conn, -ENETDOWN);
3351                         kiblnd_conn_decref(conn);
3352                 }
3353                 return 0;
3354
3355         case RDMA_CM_EVENT_CONNECT_ERROR:
3356                 conn = cmid->context;
3357                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3358                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3359                 CNETERR("%s: CONNECT ERROR %d cm_id %p conn %p\n",
3360                         libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status, cmid, conn);
3361                 kiblnd_connreq_done(conn, -ENOTCONN);
3362                 kiblnd_conn_decref(conn);
3363                 return 0;
3364
3365         case RDMA_CM_EVENT_REJECTED:
3366                 conn = cmid->context;
3367                 switch (conn->ibc_state) {
3368                 default:
3369                         LBUG();
3370
3371                 case IBLND_CONN_PASSIVE_WAIT:
3372                         CERROR("%s: REJECTED %d cm_id %p\n",
3373                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
3374                                 event->status, cmid);
3375                         kiblnd_connreq_done(conn, -ECONNRESET);
3376                         break;
3377
3378                 case IBLND_CONN_ACTIVE_CONNECT:
3379                         kiblnd_rejected(conn, event->status,
3380                                         (void *)KIBLND_CONN_PARAM(event),
3381                                         KIBLND_CONN_PARAM_LEN(event));
3382                         break;
3383                 }
3384                 kiblnd_conn_decref(conn);
3385                 return 0;
3386
3387         case RDMA_CM_EVENT_ESTABLISHED:
3388                 conn = cmid->context;
3389                 switch (conn->ibc_state) {
3390                 default:
3391                         LBUG();
3392
3393                 case IBLND_CONN_PASSIVE_WAIT:
3394                         CDEBUG(D_NET, "ESTABLISHED (passive): %s cm_id %p conn %p\n",
3395                                 libcfs_nid2str(conn->ibc_peer->ibp_nid), cmid, conn);
3396                         kiblnd_connreq_done(conn, 0);
3397                         break;
3398
3399                 case IBLND_CONN_ACTIVE_CONNECT:
3400                         CDEBUG(D_NET, "ESTABLISHED(active): %s cm_id %p conn %p\n",
3401                                 libcfs_nid2str(conn->ibc_peer->ibp_nid), cmid, conn);
3402                         kiblnd_check_connreply(conn,
3403                                                (void *)KIBLND_CONN_PARAM(event),
3404                                                KIBLND_CONN_PARAM_LEN(event));
3405                         break;
3406                 }
3407                 /* net keeps its ref on conn! */
3408                 return 0;
3409
3410         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
3411                 CDEBUG(D_NET, "Ignore TIMEWAIT_EXIT event\n");
3412                 return 0;
3413
3414         case RDMA_CM_EVENT_DISCONNECTED:
3415                 conn = cmid->context;
3416                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
3417                         CERROR("%s DISCONNECTED cm_id %p conn %p\n",
3418                                 libcfs_nid2str(conn->ibc_peer->ibp_nid), cmid, conn);
3419                         kiblnd_connreq_done(conn, -ECONNRESET);
3420                 } else {
3421                         kiblnd_close_conn(conn, 0);
3422                 }
3423                 kiblnd_conn_decref(conn);
3424                 cmid->context = NULL;
3425                 return 0;
3426
3427         case RDMA_CM_EVENT_DEVICE_REMOVAL:
3428                 LCONSOLE_ERROR_MSG(0x131,
3429                                    "Received notification of device removal\n"
3430                                    "Please shutdown LNET to allow this to proceed\n");
3431                 /* Can't remove network from underneath LNET for now, so I have
3432                  * to ignore this */
3433                 return 0;
3434
3435         case RDMA_CM_EVENT_ADDR_CHANGE:
3436                 LCONSOLE_INFO("Physical link changed (eg hca/port)\n");
3437                 return 0;
3438         }
3439 }
3440
3441 static int
3442 kiblnd_check_txs_locked(struct kib_conn *conn, struct list_head *txs)
3443 {
3444         struct kib_tx *tx;
3445
3446         list_for_each_entry(tx, txs, tx_list) {
3447                 if (txs != &conn->ibc_active_txs) {
3448                         LASSERT(tx->tx_queued);
3449                 } else {
3450                         LASSERT(!tx->tx_queued);
3451                         LASSERT(tx->tx_waiting || tx->tx_sending != 0);
3452                 }
3453
3454                 if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3455                         CERROR("Timed out tx: %s(WSQ:%d%d%d), %lld seconds\n",
3456                                kiblnd_queue2str(conn, txs),
3457                                tx->tx_waiting, tx->tx_sending, tx->tx_queued,
3458                                kiblnd_timeout() +
3459                                ktime_ms_delta(ktime_get(),
3460                                               tx->tx_deadline) / MSEC_PER_SEC);
3461                         return 1;
3462                 }
3463         }
3464
3465         return 0;
3466 }
3467
3468 static int
3469 kiblnd_conn_timed_out_locked(struct kib_conn *conn)
3470 {
3471         return  kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue) ||
3472                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_noops) ||
3473                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_rsrvd) ||
3474                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_nocred) ||
3475                 kiblnd_check_txs_locked(conn, &conn->ibc_active_txs);
3476 }
3477
3478 static void
3479 kiblnd_check_conns (int idx)
3480 {
3481         LIST_HEAD(closes);
3482         LIST_HEAD(checksends);
3483         LIST_HEAD(timedout_txs);
3484         struct hlist_head *peers = &kiblnd_data.kib_peers[idx];
3485         struct kib_peer_ni *peer_ni;
3486         struct kib_conn *conn;
3487         struct kib_tx *tx, *tx_tmp;
3488         unsigned long flags;
3489
3490         /* NB. We expect to have a look at all the peers and not find any
3491          * RDMAs to time out, so we just use a shared lock while we
3492          * take a look...
3493          */
3494         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3495
3496         hlist_for_each_entry(peer_ni, peers, ibp_list) {
3497                 /* Check tx_deadline */
3498                 list_for_each_entry_safe(tx, tx_tmp, &peer_ni->ibp_tx_queue, tx_list) {
3499                         if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3500                                 CWARN("Timed out tx for %s: %lld seconds\n",
3501                                       libcfs_nid2str(peer_ni->ibp_nid),
3502                                       ktime_ms_delta(ktime_get(),
3503                                                      tx->tx_deadline) / MSEC_PER_SEC);
3504                                 list_move(&tx->tx_list, &timedout_txs);
3505                         }
3506                 }
3507
3508                 list_for_each_entry(conn, &peer_ni->ibp_conns, ibc_list) {
3509                         int timedout;
3510                         int sendnoop;
3511
3512                         LASSERT(conn->ibc_state == IBLND_CONN_ESTABLISHED);
3513
3514                         spin_lock(&conn->ibc_lock);
3515
3516                         sendnoop = kiblnd_need_noop(conn);
3517                         timedout = kiblnd_conn_timed_out_locked(conn);
3518                         if (!sendnoop && !timedout) {
3519                                 spin_unlock(&conn->ibc_lock);
3520                                 continue;
3521                         }
3522
3523                         if (timedout) {
3524                                 CERROR("Timed out RDMA with %s (%lld): c: %u, oc: %u, rc: %u\n",
3525                                        libcfs_nid2str(peer_ni->ibp_nid),
3526                                        ktime_get_seconds()
3527                                        - peer_ni->ibp_last_alive,
3528                                        conn->ibc_credits,
3529                                        conn->ibc_outstanding_credits,
3530                                        conn->ibc_reserved_credits);
3531 #ifdef O2IBLND_CONN_STATE_DEBUG
3532                                 kiblnd_dump_conn_dbg(conn);
3533 #endif
3534                                 list_add(&conn->ibc_connd_list, &closes);
3535                         } else {
3536                                 list_add(&conn->ibc_connd_list, &checksends);
3537                         }
3538                         /* +ref for 'closes' or 'checksends' */
3539                         kiblnd_conn_addref(conn);
3540
3541                         spin_unlock(&conn->ibc_lock);
3542                 }
3543         }
3544
3545         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3546
3547         if (!list_empty(&timedout_txs))
3548                 kiblnd_txlist_done(&timedout_txs, -ETIMEDOUT,
3549                                    LNET_MSG_STATUS_NETWORK_TIMEOUT);
3550
3551         /* Handle timeout by closing the whole
3552          * connection. We can only be sure RDMA activity
3553          * has ceased once the QP has been modified.
3554          */
3555         while ((conn = list_first_entry_or_null(&closes,
3556                                                 struct kib_conn,
3557                                                 ibc_connd_list)) != NULL) {
3558                 list_del(&conn->ibc_connd_list);
3559                 kiblnd_close_conn(conn, -ETIMEDOUT);
3560                 kiblnd_conn_decref(conn);
3561         }
3562
3563         /* In case we have enough credits to return via a
3564          * NOOP, but there were no non-blocking tx descs
3565          * free to do it last time...
3566          */
3567         while ((conn = list_first_entry_or_null(&checksends,
3568                                                 struct kib_conn,
3569                                                 ibc_connd_list)) != NULL) {
3570                 list_del(&conn->ibc_connd_list);
3571
3572                 spin_lock(&conn->ibc_lock);
3573                 kiblnd_check_sends_locked(conn);
3574                 spin_unlock(&conn->ibc_lock);
3575
3576                 kiblnd_conn_decref(conn);
3577         }
3578 }
3579
3580 static void
3581 kiblnd_disconnect_conn(struct kib_conn *conn)
3582 {
3583         LASSERT (!in_interrupt());
3584         LASSERT (current == kiblnd_data.kib_connd);
3585         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
3586 #ifdef O2IBLND_CONN_STATE_DEBUG
3587         kiblnd_dump_conn_dbg(conn);
3588 #endif
3589         rdma_disconnect(conn->ibc_cmid);
3590         kiblnd_finalise_conn(conn);
3591
3592         kiblnd_peer_notify(conn->ibc_peer);
3593 }
3594
3595 /*
3596  * High-water for reconnection to the same peer_ni, reconnection attempt should
3597  * be delayed after trying more than KIB_RECONN_HIGH_RACE.
3598  */
3599 #define KIB_RECONN_HIGH_RACE    10
3600 /*
3601  * Allow connd to take a break and handle other things after consecutive
3602  * reconnection attemps.
3603  */
3604 #define KIB_RECONN_BREAK        100
3605
3606 int
3607 kiblnd_connd (void *arg)
3608 {
3609         spinlock_t *lock = &kiblnd_data.kib_connd_lock;
3610         wait_queue_entry_t wait;
3611         unsigned long flags;
3612         struct kib_conn *conn;
3613         int timeout;
3614         int i;
3615         bool dropped_lock;
3616         int peer_index = 0;
3617         unsigned long deadline = jiffies;
3618
3619         init_wait(&wait);
3620         kiblnd_data.kib_connd = current;
3621
3622         spin_lock_irqsave(lock, flags);
3623
3624         while (!kiblnd_data.kib_shutdown) {
3625                 int reconn = 0;
3626
3627                 dropped_lock = false;
3628
3629                 conn = list_first_entry_or_null(&kiblnd_data.kib_connd_zombies,
3630                                                 struct kib_conn, ibc_list);
3631                 if (conn) {
3632                         struct kib_peer_ni *peer_ni = NULL;
3633
3634                         list_del(&conn->ibc_list);
3635                         if (conn->ibc_reconnect) {
3636                                 peer_ni = conn->ibc_peer;
3637                                 kiblnd_peer_addref(peer_ni);
3638                         }
3639
3640                         spin_unlock_irqrestore(lock, flags);
3641                         dropped_lock = true;
3642
3643                         kiblnd_destroy_conn(conn);
3644
3645                         spin_lock_irqsave(lock, flags);
3646                         if (!peer_ni) {
3647                                 LIBCFS_FREE(conn, sizeof(*conn));
3648                                 continue;
3649                         }
3650
3651                         conn->ibc_peer = peer_ni;
3652                         if (peer_ni->ibp_reconnected < KIB_RECONN_HIGH_RACE)
3653                                 list_add_tail(&conn->ibc_list,
3654                                               &kiblnd_data.kib_reconn_list);
3655                         else
3656                                 list_add_tail(&conn->ibc_list,
3657                                               &kiblnd_data.kib_reconn_wait);
3658                 }
3659
3660                 conn = list_first_entry_or_null(&kiblnd_data.kib_connd_conns,
3661                                                 struct kib_conn, ibc_list);
3662                 if (conn) {
3663                         int wait;
3664
3665                         list_del(&conn->ibc_list);
3666
3667                         spin_unlock_irqrestore(lock, flags);
3668                         dropped_lock = true;
3669
3670                         kiblnd_disconnect_conn(conn);
3671                         wait = conn->ibc_waits;
3672                         if (wait == 0) /* keep ref for connd_wait, see below */
3673                                 kiblnd_conn_decref(conn);
3674
3675                         spin_lock_irqsave(lock, flags);
3676
3677                         if (wait)
3678                                 list_add_tail(&conn->ibc_list,
3679                                               &kiblnd_data.kib_connd_waits);
3680                 }
3681
3682                 while (reconn < KIB_RECONN_BREAK) {
3683                         if (kiblnd_data.kib_reconn_sec !=
3684                             ktime_get_real_seconds()) {
3685                                 kiblnd_data.kib_reconn_sec = ktime_get_real_seconds();
3686                                 list_splice_init(&kiblnd_data.kib_reconn_wait,
3687                                                  &kiblnd_data.kib_reconn_list);
3688                         }
3689
3690                         conn = list_first_entry_or_null(&kiblnd_data.kib_reconn_list,
3691                                                         struct kib_conn, ibc_list);
3692                         if (!conn)
3693                                 break;
3694
3695                         list_del(&conn->ibc_list);
3696
3697                         spin_unlock_irqrestore(lock, flags);
3698                         dropped_lock = true;
3699
3700                         reconn += kiblnd_reconnect_peer(conn->ibc_peer);
3701                         kiblnd_peer_decref(conn->ibc_peer);
3702                         LIBCFS_FREE(conn, sizeof(*conn));
3703
3704                         spin_lock_irqsave(lock, flags);
3705                 }
3706
3707                 conn = list_first_entry_or_null(&kiblnd_data.kib_connd_waits,
3708                                                 struct kib_conn, ibc_list);
3709                 if (conn) {
3710                         list_del(&conn->ibc_list);
3711                         spin_unlock_irqrestore(lock, flags);
3712
3713                         dropped_lock = kiblnd_tx_may_discard(conn);
3714                         if (dropped_lock)
3715                                 kiblnd_conn_decref(conn);
3716
3717                         spin_lock_irqsave(lock, flags);
3718                         if (!dropped_lock)
3719                                 list_add_tail(&conn->ibc_list,
3720                                               &kiblnd_data.kib_connd_waits);
3721                 }
3722
3723                 /* careful with the jiffy wrap... */
3724                 timeout = (int)(deadline - jiffies);
3725                 if (timeout <= 0) {
3726                         const int n = 4;
3727                         const int p = 1;
3728                         int chunk = HASH_SIZE(kiblnd_data.kib_peers);
3729                         unsigned int lnd_timeout;
3730
3731                         spin_unlock_irqrestore(lock, flags);
3732                         dropped_lock = true;
3733
3734                         /* Time to check for RDMA timeouts on a few more
3735                          * peers: I do checks every 'p' seconds on a
3736                          * proportion of the peer_ni table and I need to check
3737                          * every connection 'n' times within a timeout
3738                          * interval, to ensure I detect a timeout on any
3739                          * connection within (n+1)/n times the timeout
3740                          * interval.
3741                          */
3742
3743                         lnd_timeout = kiblnd_timeout();
3744                         if (lnd_timeout > n * p)
3745                                 chunk = (chunk * n * p) / lnd_timeout;
3746                         if (chunk == 0)
3747                                 chunk = 1;
3748
3749                         for (i = 0; i < chunk; i++) {
3750                                 kiblnd_check_conns(peer_index);
3751                                 peer_index = (peer_index + 1) %
3752                                         HASH_SIZE(kiblnd_data.kib_peers);
3753                         }
3754
3755                         deadline += cfs_time_seconds(p);
3756                         spin_lock_irqsave(lock, flags);
3757                 }
3758
3759                 if (dropped_lock)
3760                         continue;
3761
3762                 /* Nothing to do for 'timeout'  */
3763                 set_current_state(TASK_INTERRUPTIBLE);
3764                 add_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3765                 spin_unlock_irqrestore(lock, flags);
3766
3767                 schedule_timeout(timeout);
3768
3769                 remove_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3770                 spin_lock_irqsave(lock, flags);
3771         }
3772
3773         spin_unlock_irqrestore(lock, flags);
3774
3775         kiblnd_thread_fini();
3776         return 0;
3777 }
3778
3779 void
3780 kiblnd_qp_event(struct ib_event *event, void *arg)
3781 {
3782         struct kib_conn *conn = arg;
3783
3784         switch (event->event) {
3785         case IB_EVENT_COMM_EST:
3786                 CDEBUG(D_NET, "%s established\n",
3787                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
3788                 /* We received a packet but connection isn't established
3789                  * probably handshake packet was lost, so free to
3790                  * force make connection established */
3791                 rdma_notify(conn->ibc_cmid, IB_EVENT_COMM_EST);
3792                 return;
3793
3794         case IB_EVENT_PORT_ERR:
3795         case IB_EVENT_DEVICE_FATAL:
3796                 CERROR("Fatal device error for NI %s\n",
3797                        libcfs_nidstr(&conn->ibc_peer->ibp_ni->ni_nid));
3798                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 1);
3799                 return;
3800
3801         case IB_EVENT_PORT_ACTIVE:
3802                 CERROR("Port reactivated for NI %s\n",
3803                        libcfs_nidstr(&conn->ibc_peer->ibp_ni->ni_nid));
3804                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 0);
3805                 return;
3806
3807         default:
3808                 CERROR("%s: Async QP event type %d\n",
3809                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3810                 return;
3811         }
3812 }
3813
3814 static void
3815 kiblnd_complete (struct ib_wc *wc)
3816 {
3817         switch (kiblnd_wreqid2type(wc->wr_id)) {
3818         default:
3819                 LBUG();
3820
3821         case IBLND_WID_MR:
3822                 if (wc->status != IB_WC_SUCCESS &&
3823                     wc->status != IB_WC_WR_FLUSH_ERR)
3824                         CNETERR("FastReg failed: %d\n", wc->status);
3825                 return;
3826
3827         case IBLND_WID_RDMA:
3828                 /* We only get RDMA completion notification if it fails.  All
3829                  * subsequent work items, including the final SEND will fail
3830                  * too.  However we can't print out any more info about the
3831                  * failing RDMA because 'tx' might be back on the idle list or
3832                  * even reused already if we didn't manage to post all our work
3833                  * items */
3834                 CNETERR("RDMA (tx: %p) failed: %d\n",
3835                         kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3836                 return;
3837
3838         case IBLND_WID_TX:
3839                 kiblnd_tx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3840                 return;
3841
3842         case IBLND_WID_RX:
3843                 kiblnd_rx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status,
3844                                    wc->byte_len);
3845                 return;
3846         }
3847 }
3848
3849 void
3850 kiblnd_cq_completion(struct ib_cq *cq, void *arg)
3851 {
3852         /* NB I'm not allowed to schedule this conn once its refcount has
3853          * reached 0.  Since fundamentally I'm racing with scheduler threads
3854          * consuming my CQ I could be called after all completions have
3855          * occurred.  But in this case, ibc_nrx == 0 && ibc_nsends_posted == 0
3856          * and this CQ is about to be destroyed so I NOOP. */
3857         struct kib_conn *conn = arg;
3858         struct kib_sched_info *sched = conn->ibc_sched;
3859         unsigned long flags;
3860
3861         LASSERT(cq == conn->ibc_cq);
3862
3863         spin_lock_irqsave(&sched->ibs_lock, flags);
3864
3865         conn->ibc_ready = 1;
3866
3867         if (!conn->ibc_scheduled &&
3868             (conn->ibc_nrx > 0 ||
3869              conn->ibc_nsends_posted > 0)) {
3870                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3871                 kiblnd_dump_conn_dbg(conn);
3872                 conn->ibc_scheduled = 1;
3873                 list_add_tail(&conn->ibc_sched_list, &sched->ibs_conns);
3874
3875                 if (waitqueue_active(&sched->ibs_waitq))
3876                         wake_up(&sched->ibs_waitq);
3877         }
3878
3879         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3880 }
3881
3882 void
3883 kiblnd_cq_event(struct ib_event *event, void *arg)
3884 {
3885         struct kib_conn *conn = arg;
3886
3887         CERROR("%s: async CQ event type %d\n",
3888                libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3889 }
3890
3891 int
3892 kiblnd_scheduler(void *arg)
3893 {
3894         long id = (long)arg;
3895         struct kib_sched_info *sched;
3896         struct kib_conn *conn;
3897         wait_queue_entry_t wait;
3898         unsigned long flags;
3899         struct ib_wc wc;
3900         bool did_something;
3901         int rc;
3902
3903         init_wait(&wait);
3904
3905         sched = kiblnd_data.kib_scheds[KIB_THREAD_CPT(id)];
3906
3907         rc = cfs_cpt_bind(lnet_cpt_table(), sched->ibs_cpt);
3908         if (rc != 0) {
3909                 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);
3910         }
3911
3912         spin_lock_irqsave(&sched->ibs_lock, flags);
3913
3914         while (!kiblnd_data.kib_shutdown) {
3915                 if (need_resched()) {
3916                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3917
3918                         cond_resched();
3919
3920                         spin_lock_irqsave(&sched->ibs_lock, flags);
3921                 }
3922
3923                 did_something = false;
3924
3925                 conn = list_first_entry_or_null(&sched->ibs_conns,
3926                                                 struct kib_conn,
3927                                                 ibc_sched_list);
3928                 if (conn) {
3929                         /* take over kib_sched_conns' ref on conn... */
3930                         LASSERT(conn->ibc_scheduled);
3931                         list_del(&conn->ibc_sched_list);
3932                         conn->ibc_ready = 0;
3933
3934                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3935
3936                         wc.wr_id = IBLND_WID_INVAL;
3937
3938                         rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3939                         if (rc == 0) {
3940                                 rc = ib_req_notify_cq(conn->ibc_cq,
3941                                                       IB_CQ_NEXT_COMP);
3942                                 if (rc < 0) {
3943                                         CWARN("%s: ib_req_notify_cq failed: %d, closing connection %p\n",
3944                                               libcfs_nid2str(conn->ibc_peer->ibp_nid),
3945                                               rc, conn);
3946                                         kiblnd_close_conn(conn, -EIO);
3947                                         kiblnd_conn_decref(conn);
3948                                         spin_lock_irqsave(&sched->ibs_lock,
3949                                                           flags);
3950                                         continue;
3951                                 }
3952
3953                                 rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3954                         }
3955
3956                         if (unlikely(rc > 0 && wc.wr_id == IBLND_WID_INVAL)) {
3957                                 LCONSOLE_ERROR(
3958                                         "ib_poll_cq (rc: %d) returned invalid "
3959                                         "wr_id, opcode %d, status: %d, "
3960                                         "vendor_err: %d, conn: %s status: %d\n"
3961                                         "please upgrade firmware and OFED or "
3962                                         "contact vendor.\n", rc,
3963                                         wc.opcode, wc.status, wc.vendor_err,
3964                                         libcfs_nid2str(conn->ibc_peer->ibp_nid),
3965                                         conn->ibc_state);
3966                                 rc = -EINVAL;
3967                         }
3968
3969                         if (rc < 0) {
3970                                 CWARN("%s: ib_poll_cq failed: %d, closing connection %p\n",
3971                                       libcfs_nid2str(conn->ibc_peer->ibp_nid),
3972                                       rc, conn);
3973                                 kiblnd_close_conn(conn, -EIO);
3974                                 kiblnd_conn_decref(conn);
3975                                 spin_lock_irqsave(&sched->ibs_lock, flags);
3976                                 continue;
3977                         }
3978
3979                         spin_lock_irqsave(&sched->ibs_lock, flags);
3980
3981                         if (rc != 0 || conn->ibc_ready) {
3982                                 /* There may be another completion waiting; get
3983                                  * another scheduler to check while I handle
3984                                  * this one... */
3985                                 /* +1 ref for sched_conns */
3986                                 kiblnd_conn_addref(conn);
3987                                 list_add_tail(&conn->ibc_sched_list,
3988                                               &sched->ibs_conns);
3989                                 if (waitqueue_active(&sched->ibs_waitq))
3990                                         wake_up(&sched->ibs_waitq);
3991                         } else {
3992                                 conn->ibc_scheduled = 0;
3993                         }
3994
3995                         if (rc != 0) {
3996                                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
3997                                 kiblnd_complete(&wc);
3998
3999                                 spin_lock_irqsave(&sched->ibs_lock, flags);
4000                         }
4001
4002                         kiblnd_conn_decref(conn); /* ..drop my ref from above */
4003                         did_something = true;
4004                 }
4005
4006                 if (did_something)
4007                         continue;
4008
4009                 set_current_state(TASK_INTERRUPTIBLE);
4010                 add_wait_queue_exclusive(&sched->ibs_waitq, &wait);
4011                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
4012
4013                 schedule();
4014
4015                 remove_wait_queue(&sched->ibs_waitq, &wait);
4016                 set_current_state(TASK_RUNNING);
4017                 spin_lock_irqsave(&sched->ibs_lock, flags);
4018         }
4019
4020         spin_unlock_irqrestore(&sched->ibs_lock, flags);
4021
4022         kiblnd_thread_fini();
4023         return 0;
4024 }
4025
4026 int
4027 kiblnd_failover_thread(void *arg)
4028 {
4029         rwlock_t *glock = &kiblnd_data.kib_global_lock;
4030         struct kib_dev *dev;
4031         struct net *ns = arg;
4032         wait_queue_entry_t wait;
4033         unsigned long flags;
4034         int rc;
4035
4036         LASSERT(*kiblnd_tunables.kib_dev_failover != 0);
4037
4038         init_wait(&wait);
4039         write_lock_irqsave(glock, flags);
4040
4041         while (!kiblnd_data.kib_shutdown) {
4042                 bool do_failover = false;
4043                 int long_sleep;
4044
4045                 list_for_each_entry(dev, &kiblnd_data.kib_failed_devs,
4046                                     ibd_fail_list) {
4047                         if (ktime_get_seconds() < dev->ibd_next_failover)
4048                                 continue;
4049                         do_failover = true;
4050                         break;
4051                 }
4052
4053                 if (do_failover) {
4054                         list_del_init(&dev->ibd_fail_list);
4055                         dev->ibd_failover = 1;
4056                         write_unlock_irqrestore(glock, flags);
4057
4058                         rc = kiblnd_dev_failover(dev, ns);
4059
4060                         write_lock_irqsave(glock, flags);
4061
4062                         LASSERT(dev->ibd_failover);
4063                         dev->ibd_failover = 0;
4064                         if (rc >= 0) { /* Device is OK or failover succeed */
4065                                 dev->ibd_next_failover = ktime_get_seconds() + 3;
4066                                 continue;
4067                         }
4068
4069                         /* failed to failover, retry later */
4070                         dev->ibd_next_failover = ktime_get_seconds() +
4071                                 min(dev->ibd_failed_failover, 10);
4072                         if (kiblnd_dev_can_failover(dev)) {
4073                                 list_add_tail(&dev->ibd_fail_list,
4074                                               &kiblnd_data.kib_failed_devs);
4075                         }
4076
4077                         continue;
4078                 }
4079
4080                 /* long sleep if no more pending failover */
4081                 long_sleep = list_empty(&kiblnd_data.kib_failed_devs);
4082
4083                 set_current_state(TASK_INTERRUPTIBLE);
4084                 add_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
4085                 write_unlock_irqrestore(glock, flags);
4086
4087                 rc = schedule_timeout(long_sleep ? cfs_time_seconds(10) :
4088                                       cfs_time_seconds(1));
4089                 set_current_state(TASK_RUNNING);
4090                 remove_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
4091                 write_lock_irqsave(glock, flags);
4092
4093                 if (!long_sleep || rc != 0)
4094                         continue;
4095
4096                 /* have a long sleep, routine check all active devices,
4097                  * we need checking like this because if there is not active
4098                  * connection on the dev and no SEND from local, we may listen
4099                  * on wrong HCA for ever while there is a bonding failover
4100                  */
4101                 list_for_each_entry(dev, &kiblnd_data.kib_devs, ibd_list) {
4102                         if (kiblnd_dev_can_failover(dev)) {
4103                                 list_add_tail(&dev->ibd_fail_list,
4104                                               &kiblnd_data.kib_failed_devs);
4105                         }
4106                 }
4107         }
4108
4109         write_unlock_irqrestore(glock, flags);
4110
4111         kiblnd_thread_fini();
4112         return 0;
4113 }