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