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