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