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