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