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