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