Whamcloud - gitweb
LU-11881 utils: silence error message
[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         int ver = conn->ibc_version;
870         int rc;
871         int done;
872
873         LASSERT(tx->tx_queued);
874         /* We rely on this for QP sizing */
875         LASSERT(tx->tx_nwrq > 0 && tx->tx_nsge >= 0);
876         LASSERT(tx->tx_nwrq <= 1 + conn->ibc_max_frags);
877
878         LASSERT(credit == 0 || credit == 1);
879         LASSERT(conn->ibc_outstanding_credits >= 0);
880         LASSERT(conn->ibc_outstanding_credits <= conn->ibc_queue_depth);
881         LASSERT(conn->ibc_credits >= 0);
882         LASSERT(conn->ibc_credits <= conn->ibc_queue_depth);
883
884         if (conn->ibc_nsends_posted ==
885             conn->ibc_queue_depth) {
886                 /* tx completions outstanding... */
887                 CDEBUG(D_NET, "%s: posted enough\n",
888                        libcfs_nid2str(peer_ni->ibp_nid));
889                 return -EAGAIN;
890         }
891
892         if (credit != 0 && conn->ibc_credits == 0) {   /* no credits */
893                 CDEBUG(D_NET, "%s: no credits\n",
894                        libcfs_nid2str(peer_ni->ibp_nid));
895                 return -EAGAIN;
896         }
897
898         if (credit != 0 && !IBLND_OOB_CAPABLE(ver) &&
899             conn->ibc_credits == 1 &&   /* last credit reserved */
900             msg->ibm_type != IBLND_MSG_NOOP) {      /* for NOOP */
901                 CDEBUG(D_NET, "%s: not using last credit\n",
902                        libcfs_nid2str(peer_ni->ibp_nid));
903                 return -EAGAIN;
904         }
905
906         /* NB don't drop ibc_lock before bumping tx_sending */
907         list_del(&tx->tx_list);
908         tx->tx_queued = 0;
909
910         if (msg->ibm_type == IBLND_MSG_NOOP &&
911             (!kiblnd_need_noop(conn) ||     /* redundant NOOP */
912              (IBLND_OOB_CAPABLE(ver) && /* posted enough NOOP */
913               conn->ibc_noops_posted == IBLND_OOB_MSGS(ver)))) {
914                 /* OK to drop when posted enough NOOPs, since
915                  * kiblnd_check_sends_locked will queue NOOP again when
916                  * posted NOOPs complete */
917                 spin_unlock(&conn->ibc_lock);
918                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
919                 kiblnd_tx_done(tx);
920                 spin_lock(&conn->ibc_lock);
921                 CDEBUG(D_NET, "%s(%d): redundant or enough NOOP\n",
922                        libcfs_nid2str(peer_ni->ibp_nid),
923                        conn->ibc_noops_posted);
924                 return 0;
925         }
926
927         kiblnd_pack_msg(peer_ni->ibp_ni, msg, ver, conn->ibc_outstanding_credits,
928                         peer_ni->ibp_nid, conn->ibc_incarnation);
929
930         conn->ibc_credits -= credit;
931         conn->ibc_outstanding_credits = 0;
932         conn->ibc_nsends_posted++;
933         if (msg->ibm_type == IBLND_MSG_NOOP)
934                 conn->ibc_noops_posted++;
935
936         /* CAVEAT EMPTOR!  This tx could be the PUT_DONE of an RDMA
937          * PUT.  If so, it was first queued here as a PUT_REQ, sent and
938          * stashed on ibc_active_txs, matched by an incoming PUT_ACK,
939          * and then re-queued here.  It's (just) possible that
940          * tx_sending is non-zero if we've not done the tx_complete()
941          * from the first send; hence the ++ rather than = below. */
942         tx->tx_sending++;
943         list_add(&tx->tx_list, &conn->ibc_active_txs);
944
945         /* I'm still holding ibc_lock! */
946         if (conn->ibc_state != IBLND_CONN_ESTABLISHED) {
947                 rc = -ECONNABORTED;
948         } else if (tx->tx_pool->tpo_pool.po_failed ||
949                  conn->ibc_hdev != tx->tx_pool->tpo_hdev) {
950                 /* close_conn will launch failover */
951                 rc = -ENETDOWN;
952         } else {
953                 struct kib_fast_reg_descriptor *frd = tx->tx_fmr.fmr_frd;
954                 struct ib_send_wr *bad = &tx->tx_wrq[tx->tx_nwrq - 1].wr;
955                 struct ib_send_wr *wr  = &tx->tx_wrq[0].wr;
956
957                 if (frd != NULL) {
958                         if (!frd->frd_valid) {
959                                 wr = &frd->frd_inv_wr.wr;
960                                 wr->next = &frd->frd_fastreg_wr.wr;
961                         } else {
962                                 wr = &frd->frd_fastreg_wr.wr;
963                         }
964                         frd->frd_fastreg_wr.wr.next = &tx->tx_wrq[0].wr;
965                 }
966
967                 LASSERTF(bad->wr_id == kiblnd_ptr2wreqid(tx, IBLND_WID_TX),
968                          "bad wr_id %#llx, opc %d, flags %d, peer_ni: %s\n",
969                          bad->wr_id, bad->opcode, bad->send_flags,
970                          libcfs_nid2str(conn->ibc_peer->ibp_nid));
971
972                 bad = NULL;
973                 if (lnet_send_error_simulation(tx->tx_lntmsg[0], &tx->tx_hstatus))
974                         rc = -EINVAL;
975                 else
976                         rc = ib_post_send(conn->ibc_cmid->qp, wr, &bad);
977         }
978
979         conn->ibc_last_send = ktime_get();
980
981         if (rc == 0)
982                 return 0;
983
984         /* NB credits are transferred in the actual
985          * message, which can only be the last work item */
986         conn->ibc_credits += credit;
987         conn->ibc_outstanding_credits += msg->ibm_credits;
988         conn->ibc_nsends_posted--;
989         if (msg->ibm_type == IBLND_MSG_NOOP)
990                 conn->ibc_noops_posted--;
991
992         tx->tx_status = rc;
993         tx->tx_waiting = 0;
994         tx->tx_sending--;
995
996         done = (tx->tx_sending == 0);
997         if (done)
998                 list_del(&tx->tx_list);
999
1000         spin_unlock(&conn->ibc_lock);
1001
1002         if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1003                 CERROR("Error %d posting transmit to %s\n",
1004                        rc, libcfs_nid2str(peer_ni->ibp_nid));
1005         else
1006                 CDEBUG(D_NET, "Error %d posting transmit to %s\n",
1007                        rc, libcfs_nid2str(peer_ni->ibp_nid));
1008
1009         kiblnd_close_conn(conn, rc);
1010
1011         if (done)
1012                 kiblnd_tx_done(tx);
1013
1014         spin_lock(&conn->ibc_lock);
1015
1016         return -EIO;
1017 }
1018
1019 static void
1020 kiblnd_check_sends_locked(struct kib_conn *conn)
1021 {
1022         int ver = conn->ibc_version;
1023         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
1024         struct kib_tx *tx;
1025
1026         /* Don't send anything until after the connection is established */
1027         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
1028                 CDEBUG(D_NET, "%s too soon\n",
1029                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
1030                 return;
1031         }
1032
1033         LASSERT(conn->ibc_nsends_posted <=
1034                 conn->ibc_queue_depth);
1035         LASSERT (!IBLND_OOB_CAPABLE(ver) ||
1036                  conn->ibc_noops_posted <= IBLND_OOB_MSGS(ver));
1037         LASSERT (conn->ibc_reserved_credits >= 0);
1038
1039         while (conn->ibc_reserved_credits > 0 &&
1040                !list_empty(&conn->ibc_tx_queue_rsrvd)) {
1041                 tx = list_entry(conn->ibc_tx_queue_rsrvd.next,
1042                                 struct kib_tx, tx_list);
1043                 list_del(&tx->tx_list);
1044                 list_add_tail(&tx->tx_list, &conn->ibc_tx_queue);
1045                 conn->ibc_reserved_credits--;
1046         }
1047
1048         if (kiblnd_need_noop(conn)) {
1049                 spin_unlock(&conn->ibc_lock);
1050
1051                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1052                 if (tx != NULL)
1053                         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_NOOP, 0);
1054
1055                 spin_lock(&conn->ibc_lock);
1056                 if (tx != NULL)
1057                         kiblnd_queue_tx_locked(tx, conn);
1058         }
1059
1060         for (;;) {
1061                 int credit;
1062
1063                 if (!list_empty(&conn->ibc_tx_queue_nocred)) {
1064                         credit = 0;
1065                         tx = list_entry(conn->ibc_tx_queue_nocred.next,
1066                                         struct kib_tx, tx_list);
1067                 } else if (!list_empty(&conn->ibc_tx_noops)) {
1068                         LASSERT (!IBLND_OOB_CAPABLE(ver));
1069                         credit = 1;
1070                         tx = list_entry(conn->ibc_tx_noops.next,
1071                                         struct kib_tx, tx_list);
1072                 } else if (!list_empty(&conn->ibc_tx_queue)) {
1073                         credit = 1;
1074                         tx = list_entry(conn->ibc_tx_queue.next,
1075                                         struct kib_tx, tx_list);
1076                 } else
1077                         break;
1078
1079                 if (kiblnd_post_tx_locked(conn, tx, credit) != 0)
1080                         break;
1081         }
1082 }
1083
1084 static void
1085 kiblnd_tx_complete(struct kib_tx *tx, int status)
1086 {
1087         int           failed = (status != IB_WC_SUCCESS);
1088         struct kib_conn   *conn = tx->tx_conn;
1089         int           idle;
1090
1091         LASSERT (tx->tx_sending > 0);
1092
1093         if (failed) {
1094                 if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1095                         CNETERR("Tx -> %s cookie %#llx"
1096                                 " sending %d waiting %d: failed %d\n",
1097                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
1098                                 tx->tx_cookie, tx->tx_sending, tx->tx_waiting,
1099                                 status);
1100
1101                 kiblnd_close_conn(conn, -EIO);
1102         } else {
1103                 kiblnd_peer_alive(conn->ibc_peer);
1104         }
1105
1106         spin_lock(&conn->ibc_lock);
1107
1108         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
1109          * gets to free it, which also drops its ref on 'conn'. */
1110
1111         tx->tx_sending--;
1112         conn->ibc_nsends_posted--;
1113         if (tx->tx_msg->ibm_type == IBLND_MSG_NOOP)
1114                 conn->ibc_noops_posted--;
1115
1116         if (failed) {
1117                 tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
1118                 tx->tx_waiting = 0;             /* don't wait for peer_ni */
1119                 tx->tx_status = -EIO;
1120         }
1121
1122         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
1123                !tx->tx_waiting &&               /* Not waiting for peer_ni */
1124                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
1125         if (idle)
1126                 list_del(&tx->tx_list);
1127
1128         kiblnd_check_sends_locked(conn);
1129         spin_unlock(&conn->ibc_lock);
1130
1131         if (idle)
1132                 kiblnd_tx_done(tx);
1133 }
1134
1135 static void
1136 kiblnd_init_tx_msg(struct lnet_ni *ni, struct kib_tx *tx, int type,
1137                    int body_nob)
1138 {
1139         struct kib_hca_dev *hdev = tx->tx_pool->tpo_hdev;
1140         struct ib_sge *sge = &tx->tx_msgsge;
1141         struct ib_rdma_wr *wrq;
1142         int nob = offsetof(struct kib_msg, ibm_u) + body_nob;
1143 #ifdef HAVE_IB_GET_DMA_MR
1144         struct ib_mr *mr = hdev->ibh_mrs;
1145 #endif
1146
1147         LASSERT(tx->tx_nwrq >= 0);
1148         LASSERT(tx->tx_nwrq < IBLND_MAX_RDMA_FRAGS + 1);
1149         LASSERT(nob <= IBLND_MSG_SIZE);
1150 #ifdef HAVE_IB_GET_DMA_MR
1151         LASSERT(mr != NULL);
1152 #endif
1153
1154         kiblnd_init_msg(tx->tx_msg, type, body_nob);
1155
1156 #ifdef HAVE_IB_GET_DMA_MR
1157         sge->lkey   = mr->lkey;
1158 #else
1159         sge->lkey   = hdev->ibh_pd->local_dma_lkey;
1160 #endif
1161         sge->addr   = tx->tx_msgaddr;
1162         sge->length = nob;
1163
1164         wrq = &tx->tx_wrq[tx->tx_nwrq];
1165         memset(wrq, 0, sizeof(*wrq));
1166
1167         wrq->wr.next            = NULL;
1168         wrq->wr.wr_id           = kiblnd_ptr2wreqid(tx, IBLND_WID_TX);
1169         wrq->wr.sg_list         = sge;
1170         wrq->wr.num_sge         = 1;
1171         wrq->wr.opcode          = IB_WR_SEND;
1172         wrq->wr.send_flags      = IB_SEND_SIGNALED;
1173
1174         tx->tx_nwrq++;
1175 }
1176
1177 static int
1178 kiblnd_init_rdma(struct kib_conn *conn, struct kib_tx *tx, int type,
1179                  int resid, struct kib_rdma_desc *dstrd, u64 dstcookie)
1180 {
1181         struct kib_msg *ibmsg = tx->tx_msg;
1182         struct kib_rdma_desc *srcrd = tx->tx_rd;
1183         struct ib_rdma_wr *wrq = NULL;
1184         struct ib_sge     *sge;
1185         int                rc  = resid;
1186         int                srcidx;
1187         int                dstidx;
1188         int                sge_nob;
1189         int                wrq_sge;
1190
1191         LASSERT(!in_interrupt());
1192         LASSERT(tx->tx_nwrq == 0 && tx->tx_nsge == 0);
1193         LASSERT(type == IBLND_MSG_GET_DONE || type == IBLND_MSG_PUT_DONE);
1194
1195         for (srcidx = dstidx = wrq_sge = sge_nob = 0;
1196              resid > 0; resid -= sge_nob) {
1197                 int     prev = dstidx;
1198
1199                 if (srcidx >= srcrd->rd_nfrags) {
1200                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1201                         rc = -EPROTO;
1202                         break;
1203                 }
1204
1205                 if (dstidx >= dstrd->rd_nfrags) {
1206                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1207                         rc = -EPROTO;
1208                         break;
1209                 }
1210
1211                 if (tx->tx_nwrq >= conn->ibc_max_frags) {
1212                         CERROR("RDMA has too many fragments for peer_ni %s (%d), "
1213                                "src idx/frags: %d/%d dst idx/frags: %d/%d\n",
1214                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
1215                                conn->ibc_max_frags,
1216                                srcidx, srcrd->rd_nfrags,
1217                                dstidx, dstrd->rd_nfrags);
1218                         rc = -EMSGSIZE;
1219                         break;
1220                 }
1221
1222                 sge_nob = MIN(MIN(kiblnd_rd_frag_size(srcrd, srcidx),
1223                                   kiblnd_rd_frag_size(dstrd, dstidx)), resid);
1224
1225                 sge = &tx->tx_sge[tx->tx_nsge];
1226                 sge->addr   = kiblnd_rd_frag_addr(srcrd, srcidx);
1227                 sge->lkey   = kiblnd_rd_frag_key(srcrd, srcidx);
1228                 sge->length = sge_nob;
1229
1230                 if (wrq_sge == 0) {
1231                         wrq = &tx->tx_wrq[tx->tx_nwrq];
1232
1233                         wrq->wr.next    = &(wrq + 1)->wr;
1234                         wrq->wr.wr_id   = kiblnd_ptr2wreqid(tx, IBLND_WID_RDMA);
1235                         wrq->wr.sg_list = sge;
1236                         wrq->wr.opcode  = IB_WR_RDMA_WRITE;
1237                         wrq->wr.send_flags = 0;
1238
1239 #ifdef HAVE_IB_RDMA_WR
1240                         wrq->remote_addr        = kiblnd_rd_frag_addr(dstrd,
1241                                                                       dstidx);
1242                         wrq->rkey               = kiblnd_rd_frag_key(dstrd,
1243                                                                      dstidx);
1244 #else
1245                         wrq->wr.wr.rdma.remote_addr = kiblnd_rd_frag_addr(dstrd,
1246                                                                         dstidx);
1247                         wrq->wr.wr.rdma.rkey    = kiblnd_rd_frag_key(dstrd,
1248                                                                      dstidx);
1249 #endif
1250                 }
1251
1252                 srcidx = kiblnd_rd_consume_frag(srcrd, srcidx, sge_nob);
1253                 dstidx = kiblnd_rd_consume_frag(dstrd, dstidx, sge_nob);
1254
1255                 wrq_sge++;
1256                 if (wrq_sge == *kiblnd_tunables.kib_wrq_sge || dstidx != prev) {
1257                         tx->tx_nwrq++;
1258                         wrq->wr.num_sge = wrq_sge;
1259                         wrq_sge = 0;
1260                 }
1261                 tx->tx_nsge++;
1262         }
1263
1264         if (rc < 0)     /* no RDMA if completing with failure */
1265                 tx->tx_nwrq = tx->tx_nsge = 0;
1266
1267         ibmsg->ibm_u.completion.ibcm_status = rc;
1268         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1269         kiblnd_init_tx_msg(conn->ibc_peer->ibp_ni, tx,
1270                            type, sizeof(struct kib_completion_msg));
1271
1272         return rc;
1273 }
1274
1275 static void
1276 kiblnd_queue_tx_locked(struct kib_tx *tx, struct kib_conn *conn)
1277 {
1278         struct list_head *q;
1279         s64 timeout_ns;
1280
1281         LASSERT(tx->tx_nwrq > 0);       /* work items set up */
1282         LASSERT(!tx->tx_queued);        /* not queued for sending already */
1283         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1284
1285         timeout_ns = lnet_get_lnd_timeout() * NSEC_PER_SEC;
1286         tx->tx_queued = 1;
1287         tx->tx_deadline = ktime_add_ns(ktime_get(), timeout_ns);
1288
1289         if (tx->tx_conn == NULL) {
1290                 kiblnd_conn_addref(conn);
1291                 tx->tx_conn = conn;
1292                 LASSERT (tx->tx_msg->ibm_type != IBLND_MSG_PUT_DONE);
1293         } else {
1294                 /* PUT_DONE first attached to conn as a PUT_REQ */
1295                 LASSERT (tx->tx_conn == conn);
1296                 LASSERT (tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1297         }
1298
1299         switch (tx->tx_msg->ibm_type) {
1300         default:
1301                 LBUG();
1302
1303         case IBLND_MSG_PUT_REQ:
1304         case IBLND_MSG_GET_REQ:
1305                 q = &conn->ibc_tx_queue_rsrvd;
1306                 break;
1307
1308         case IBLND_MSG_PUT_NAK:
1309         case IBLND_MSG_PUT_ACK:
1310         case IBLND_MSG_PUT_DONE:
1311         case IBLND_MSG_GET_DONE:
1312                 q = &conn->ibc_tx_queue_nocred;
1313                 break;
1314
1315         case IBLND_MSG_NOOP:
1316                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
1317                         q = &conn->ibc_tx_queue_nocred;
1318                 else
1319                         q = &conn->ibc_tx_noops;
1320                 break;
1321
1322         case IBLND_MSG_IMMEDIATE:
1323                 q = &conn->ibc_tx_queue;
1324                 break;
1325         }
1326
1327         list_add_tail(&tx->tx_list, q);
1328 }
1329
1330 static void
1331 kiblnd_queue_tx(struct kib_tx *tx, struct kib_conn *conn)
1332 {
1333         spin_lock(&conn->ibc_lock);
1334         kiblnd_queue_tx_locked(tx, conn);
1335         kiblnd_check_sends_locked(conn);
1336         spin_unlock(&conn->ibc_lock);
1337 }
1338
1339 static int kiblnd_resolve_addr(struct rdma_cm_id *cmid,
1340                                struct sockaddr_in *srcaddr,
1341                                struct sockaddr_in *dstaddr,
1342                                int timeout_ms)
1343 {
1344         unsigned short port;
1345         int rc;
1346
1347         /* allow the port to be reused */
1348         rc = rdma_set_reuseaddr(cmid, 1);
1349         if (rc != 0) {
1350                 CERROR("Unable to set reuse on cmid: %d\n", rc);
1351                 return rc;
1352         }
1353
1354         /* look for a free privileged port */
1355         for (port = PROT_SOCK-1; port > 0; port--) {
1356                 srcaddr->sin_port = htons(port);
1357                 rc = rdma_resolve_addr(cmid,
1358                                        (struct sockaddr *)srcaddr,
1359                                        (struct sockaddr *)dstaddr,
1360                                        timeout_ms);
1361                 if (rc == 0) {
1362                         CDEBUG(D_NET, "bound to port %hu\n", port);
1363                         return 0;
1364                 } else if (rc == -EADDRINUSE || rc == -EADDRNOTAVAIL) {
1365                         CDEBUG(D_NET, "bind to port %hu failed: %d\n",
1366                                port, rc);
1367                 } else {
1368                         return rc;
1369                 }
1370         }
1371
1372         CERROR("Failed to bind to a free privileged port\n");
1373         return rc;
1374 }
1375
1376 static void
1377 kiblnd_connect_peer(struct kib_peer_ni *peer_ni)
1378 {
1379         struct rdma_cm_id *cmid;
1380         struct kib_dev *dev;
1381         struct kib_net *net = peer_ni->ibp_ni->ni_data;
1382         struct sockaddr_in srcaddr;
1383         struct sockaddr_in dstaddr;
1384         int rc;
1385
1386         LASSERT (net != NULL);
1387         LASSERT (peer_ni->ibp_connecting > 0);
1388
1389         cmid = kiblnd_rdma_create_id(kiblnd_cm_callback, peer_ni, RDMA_PS_TCP,
1390                                      IB_QPT_RC);
1391
1392         if (IS_ERR(cmid)) {
1393                 CERROR("Can't create CMID for %s: %ld\n",
1394                        libcfs_nid2str(peer_ni->ibp_nid), PTR_ERR(cmid));
1395                 rc = PTR_ERR(cmid);
1396                 goto failed;
1397         }
1398
1399         dev = net->ibn_dev;
1400         memset(&srcaddr, 0, sizeof(srcaddr));
1401         srcaddr.sin_family = AF_INET;
1402         srcaddr.sin_addr.s_addr = htonl(dev->ibd_ifip);
1403
1404         memset(&dstaddr, 0, sizeof(dstaddr));
1405         dstaddr.sin_family = AF_INET;
1406         dstaddr.sin_port = htons(*kiblnd_tunables.kib_service);
1407         dstaddr.sin_addr.s_addr = htonl(LNET_NIDADDR(peer_ni->ibp_nid));
1408
1409         kiblnd_peer_addref(peer_ni);               /* cmid's ref */
1410
1411         if (*kiblnd_tunables.kib_use_priv_port) {
1412                 rc = kiblnd_resolve_addr(cmid, &srcaddr, &dstaddr,
1413                                          lnet_get_lnd_timeout() * 1000);
1414         } else {
1415                 rc = rdma_resolve_addr(cmid,
1416                                        (struct sockaddr *)&srcaddr,
1417                                        (struct sockaddr *)&dstaddr,
1418                                        lnet_get_lnd_timeout() * 1000);
1419         }
1420         if (rc != 0) {
1421                 /* Can't initiate address resolution:  */
1422                 CERROR("Can't resolve addr for %s: %d\n",
1423                        libcfs_nid2str(peer_ni->ibp_nid), rc);
1424                 goto failed2;
1425         }
1426
1427         return;
1428
1429  failed2:
1430         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1431         kiblnd_peer_decref(peer_ni);               /* cmid's ref */
1432         rdma_destroy_id(cmid);
1433         return;
1434  failed:
1435         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1436 }
1437
1438 bool
1439 kiblnd_reconnect_peer(struct kib_peer_ni *peer_ni)
1440 {
1441         rwlock_t         *glock = &kiblnd_data.kib_global_lock;
1442         char             *reason = NULL;
1443         struct list_head  txs;
1444         unsigned long     flags;
1445
1446         INIT_LIST_HEAD(&txs);
1447
1448         write_lock_irqsave(glock, flags);
1449         if (peer_ni->ibp_reconnecting == 0) {
1450                 if (peer_ni->ibp_accepting)
1451                         reason = "accepting";
1452                 else if (peer_ni->ibp_connecting)
1453                         reason = "connecting";
1454                 else if (!list_empty(&peer_ni->ibp_conns))
1455                         reason = "connected";
1456                 else /* connected then closed */
1457                         reason = "closed";
1458
1459                 goto no_reconnect;
1460         }
1461
1462         if (peer_ni->ibp_accepting)
1463                 CNETERR("Detecting race between accepting and reconnecting\n");
1464         peer_ni->ibp_reconnecting--;
1465
1466         if (!kiblnd_peer_active(peer_ni)) {
1467                 list_splice_init(&peer_ni->ibp_tx_queue, &txs);
1468                 reason = "unlinked";
1469                 goto no_reconnect;
1470         }
1471
1472         peer_ni->ibp_connecting++;
1473         peer_ni->ibp_reconnected++;
1474
1475         write_unlock_irqrestore(glock, flags);
1476
1477         kiblnd_connect_peer(peer_ni);
1478         return true;
1479
1480  no_reconnect:
1481         write_unlock_irqrestore(glock, flags);
1482
1483         CWARN("Abort reconnection of %s: %s\n",
1484               libcfs_nid2str(peer_ni->ibp_nid), reason);
1485         kiblnd_txlist_done(&txs, -ECONNABORTED,
1486                            LNET_MSG_STATUS_LOCAL_ABORTED);
1487         return false;
1488 }
1489
1490 void
1491 kiblnd_launch_tx(struct lnet_ni *ni, struct kib_tx *tx, lnet_nid_t nid)
1492 {
1493         struct kib_peer_ni *peer_ni;
1494         struct kib_peer_ni *peer2;
1495         struct kib_conn *conn;
1496         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
1497         unsigned long      flags;
1498         int                rc;
1499         int                i;
1500         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
1501
1502         /* If I get here, I've committed to send, so I complete the tx with
1503          * failure on any problems */
1504
1505         LASSERT (tx == NULL || tx->tx_conn == NULL); /* only set when assigned a conn */
1506         LASSERT (tx == NULL || tx->tx_nwrq > 0);     /* work items have been set up */
1507
1508         /* First time, just use a read lock since I expect to find my peer_ni
1509          * connected */
1510         read_lock_irqsave(g_lock, flags);
1511
1512         peer_ni = kiblnd_find_peer_locked(ni, nid);
1513         if (peer_ni != NULL && !list_empty(&peer_ni->ibp_conns)) {
1514                 /* Found a peer_ni with an established connection */
1515                 conn = kiblnd_get_conn_locked(peer_ni);
1516                 kiblnd_conn_addref(conn); /* 1 ref for me... */
1517
1518                 read_unlock_irqrestore(g_lock, flags);
1519
1520                 if (tx != NULL)
1521                         kiblnd_queue_tx(tx, conn);
1522                 kiblnd_conn_decref(conn); /* ...to here */
1523                 return;
1524         }
1525
1526         read_unlock(g_lock);
1527         /* Re-try with a write lock */
1528         write_lock(g_lock);
1529
1530         peer_ni = kiblnd_find_peer_locked(ni, nid);
1531         if (peer_ni != NULL) {
1532                 if (list_empty(&peer_ni->ibp_conns)) {
1533                         /* found a peer_ni, but it's still connecting... */
1534                         LASSERT(kiblnd_peer_connecting(peer_ni));
1535                         if (tx != NULL)
1536                                 list_add_tail(&tx->tx_list,
1537                                                   &peer_ni->ibp_tx_queue);
1538                         write_unlock_irqrestore(g_lock, flags);
1539                 } else {
1540                         conn = kiblnd_get_conn_locked(peer_ni);
1541                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1542
1543                         write_unlock_irqrestore(g_lock, flags);
1544
1545                         if (tx != NULL)
1546                                 kiblnd_queue_tx(tx, conn);
1547                         kiblnd_conn_decref(conn); /* ...to here */
1548                 }
1549                 return;
1550         }
1551
1552         write_unlock_irqrestore(g_lock, flags);
1553
1554         /* Allocate a peer_ni ready to add to the peer_ni table and retry */
1555         rc = kiblnd_create_peer(ni, &peer_ni, nid);
1556         if (rc != 0) {
1557                 CERROR("Can't create peer_ni %s\n", libcfs_nid2str(nid));
1558                 if (tx != NULL) {
1559                         tx->tx_status = -EHOSTUNREACH;
1560                         tx->tx_waiting = 0;
1561                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1562                         kiblnd_tx_done(tx);
1563                 }
1564                 return;
1565         }
1566
1567         write_lock_irqsave(g_lock, flags);
1568
1569         peer2 = kiblnd_find_peer_locked(ni, nid);
1570         if (peer2 != NULL) {
1571                 if (list_empty(&peer2->ibp_conns)) {
1572                         /* found a peer_ni, but it's still connecting... */
1573                         LASSERT(kiblnd_peer_connecting(peer2));
1574                         if (tx != NULL)
1575                                 list_add_tail(&tx->tx_list,
1576                                                   &peer2->ibp_tx_queue);
1577                         write_unlock_irqrestore(g_lock, flags);
1578                 } else {
1579                         conn = kiblnd_get_conn_locked(peer2);
1580                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1581
1582                         write_unlock_irqrestore(g_lock, flags);
1583
1584                         if (tx != NULL)
1585                                 kiblnd_queue_tx(tx, conn);
1586                         kiblnd_conn_decref(conn); /* ...to here */
1587                 }
1588
1589                 kiblnd_peer_decref(peer_ni);
1590                 return;
1591         }
1592
1593         /* Brand new peer_ni */
1594         LASSERT(peer_ni->ibp_connecting == 0);
1595         tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
1596         peer_ni->ibp_connecting = tunables->lnd_conns_per_peer;
1597
1598         /* always called with a ref on ni, which prevents ni being shutdown */
1599         LASSERT(((struct kib_net *)ni->ni_data)->ibn_shutdown == 0);
1600
1601         if (tx != NULL)
1602                 list_add_tail(&tx->tx_list, &peer_ni->ibp_tx_queue);
1603
1604         kiblnd_peer_addref(peer_ni);
1605         list_add_tail(&peer_ni->ibp_list, kiblnd_nid2peerlist(nid));
1606
1607         write_unlock_irqrestore(g_lock, flags);
1608
1609         for (i = 0; i < tunables->lnd_conns_per_peer; i++)
1610                 kiblnd_connect_peer(peer_ni);
1611         kiblnd_peer_decref(peer_ni);
1612 }
1613
1614 int
1615 kiblnd_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg)
1616 {
1617         struct lnet_hdr *hdr = &lntmsg->msg_hdr;
1618         int               type = lntmsg->msg_type;
1619         struct lnet_process_id target = lntmsg->msg_target;
1620         int               target_is_router = lntmsg->msg_target_is_router;
1621         int               routing = lntmsg->msg_routing;
1622         unsigned int      payload_niov = lntmsg->msg_niov;
1623         struct kvec      *payload_iov = lntmsg->msg_iov;
1624         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
1625         unsigned int      payload_offset = lntmsg->msg_offset;
1626         unsigned int      payload_nob = lntmsg->msg_len;
1627         struct kib_msg *ibmsg;
1628         struct kib_rdma_desc *rd;
1629         struct kib_tx *tx;
1630         int               nob;
1631         int               rc;
1632
1633         /* NB 'private' is different depending on what we're sending.... */
1634
1635         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1636                payload_nob, payload_niov, libcfs_id2str(target));
1637
1638         LASSERT (payload_nob == 0 || payload_niov > 0);
1639         LASSERT (payload_niov <= LNET_MAX_IOV);
1640
1641         /* Thread context */
1642         LASSERT (!in_interrupt());
1643         /* payload is either all vaddrs or all pages */
1644         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1645
1646         switch (type) {
1647         default:
1648                 LBUG();
1649                 return (-EIO);
1650
1651         case LNET_MSG_ACK:
1652                 LASSERT (payload_nob == 0);
1653                 break;
1654
1655         case LNET_MSG_GET:
1656                 if (routing || target_is_router)
1657                         break;                  /* send IMMEDIATE */
1658
1659                 /* is the REPLY message too small for RDMA? */
1660                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1661                 if (nob <= IBLND_MSG_SIZE)
1662                         break;                  /* send IMMEDIATE */
1663
1664                 tx = kiblnd_get_idle_tx(ni, target.nid);
1665                 if (tx == NULL) {
1666                         CERROR("Can't allocate txd for GET to %s\n",
1667                                libcfs_nid2str(target.nid));
1668                         return -ENOMEM;
1669                 }
1670
1671                 ibmsg = tx->tx_msg;
1672                 rd = &ibmsg->ibm_u.get.ibgm_rd;
1673                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0)
1674                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1675                                                  lntmsg->msg_md->md_niov,
1676                                                  lntmsg->msg_md->md_iov.iov,
1677                                                  0, lntmsg->msg_md->md_length);
1678                 else
1679                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1680                                                   lntmsg->msg_md->md_niov,
1681                                                   lntmsg->msg_md->md_iov.kiov,
1682                                                   0, lntmsg->msg_md->md_length);
1683                 if (rc != 0) {
1684                         CERROR("Can't setup GET sink for %s: %d\n",
1685                                libcfs_nid2str(target.nid), rc);
1686                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1687                         kiblnd_tx_done(tx);
1688                         return -EIO;
1689                 }
1690
1691                 nob = offsetof(struct kib_get_msg, ibgm_rd.rd_frags[rd->rd_nfrags]);
1692                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1693                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1694
1695                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1696
1697                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1698                 if (tx->tx_lntmsg[1] == NULL) {
1699                         CERROR("Can't create reply for GET -> %s\n",
1700                                libcfs_nid2str(target.nid));
1701                         kiblnd_tx_done(tx);
1702                         return -EIO;
1703                 }
1704
1705                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1706                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1707                 kiblnd_launch_tx(ni, tx, target.nid);
1708                 return 0;
1709
1710         case LNET_MSG_REPLY:
1711         case LNET_MSG_PUT:
1712                 /* Is the payload small enough not to need RDMA? */
1713                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob]);
1714                 if (nob <= IBLND_MSG_SIZE)
1715                         break;                  /* send IMMEDIATE */
1716
1717                 tx = kiblnd_get_idle_tx(ni, target.nid);
1718                 if (tx == NULL) {
1719                         CERROR("Can't allocate %s txd for %s\n",
1720                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1721                                libcfs_nid2str(target.nid));
1722                         return -ENOMEM;
1723                 }
1724
1725                 if (payload_kiov == NULL)
1726                         rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1727                                                  payload_niov, payload_iov,
1728                                                  payload_offset, payload_nob);
1729                 else
1730                         rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1731                                                   payload_niov, payload_kiov,
1732                                                   payload_offset, payload_nob);
1733                 if (rc != 0) {
1734                         CERROR("Can't setup PUT src for %s: %d\n",
1735                                libcfs_nid2str(target.nid), rc);
1736                         kiblnd_tx_done(tx);
1737                         return -EIO;
1738                 }
1739
1740                 ibmsg = tx->tx_msg;
1741                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1742                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1743                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ,
1744                                    sizeof(struct kib_putreq_msg));
1745
1746                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1747                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1748                 kiblnd_launch_tx(ni, tx, target.nid);
1749                 return 0;
1750         }
1751
1752         /* send IMMEDIATE */
1753         LASSERT(offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob])
1754                 <= IBLND_MSG_SIZE);
1755
1756         tx = kiblnd_get_idle_tx(ni, target.nid);
1757         if (tx == NULL) {
1758                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1759                         type, libcfs_nid2str(target.nid));
1760                 return -ENOMEM;
1761         }
1762
1763         ibmsg = tx->tx_msg;
1764         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1765
1766         if (payload_kiov != NULL)
1767                 lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1768                                     offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1769                                     payload_niov, payload_kiov,
1770                                     payload_offset, payload_nob);
1771         else
1772                 lnet_copy_iov2flat(IBLND_MSG_SIZE, ibmsg,
1773                                    offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1774                                    payload_niov, payload_iov,
1775                                    payload_offset, payload_nob);
1776
1777         nob = offsetof(struct kib_immediate_msg, ibim_payload[payload_nob]);
1778         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1779
1780         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1781         kiblnd_launch_tx(ni, tx, target.nid);
1782         return 0;
1783 }
1784
1785 static void
1786 kiblnd_reply(struct lnet_ni *ni, struct kib_rx *rx, struct lnet_msg *lntmsg)
1787 {
1788         struct lnet_process_id target = lntmsg->msg_target;
1789         unsigned int      niov = lntmsg->msg_niov;
1790         struct kvec      *iov = lntmsg->msg_iov;
1791         lnet_kiov_t      *kiov = lntmsg->msg_kiov;
1792         unsigned int      offset = lntmsg->msg_offset;
1793         unsigned int      nob = lntmsg->msg_len;
1794         struct kib_tx *tx;
1795         int               rc;
1796
1797         tx = kiblnd_get_idle_tx(ni, rx->rx_conn->ibc_peer->ibp_nid);
1798         if (tx == NULL) {
1799                 CERROR("Can't get tx for REPLY to %s\n",
1800                        libcfs_nid2str(target.nid));
1801                 goto failed_0;
1802         }
1803
1804         if (nob == 0)
1805                 rc = 0;
1806         else if (kiov == NULL)
1807                 rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1808                                          niov, iov, offset, nob);
1809         else
1810                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1811                                           niov, kiov, offset, nob);
1812
1813         if (rc != 0) {
1814                 CERROR("Can't setup GET src for %s: %d\n",
1815                        libcfs_nid2str(target.nid), rc);
1816                 goto failed_1;
1817         }
1818
1819         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1820                               IBLND_MSG_GET_DONE, nob,
1821                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1822                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1823         if (rc < 0) {
1824                 CERROR("Can't setup rdma for GET from %s: %d\n",
1825                        libcfs_nid2str(target.nid), rc);
1826                 goto failed_1;
1827         }
1828
1829         if (nob == 0) {
1830                 /* No RDMA: local completion may happen now! */
1831                 lnet_finalize(lntmsg, 0);
1832         } else {
1833                 /* RDMA: lnet_finalize(lntmsg) when it
1834                  * completes */
1835                 tx->tx_lntmsg[0] = lntmsg;
1836         }
1837
1838         kiblnd_queue_tx(tx, rx->rx_conn);
1839         return;
1840
1841
1842 failed_1:
1843         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1844         kiblnd_tx_done(tx);
1845 failed_0:
1846         lnet_finalize(lntmsg, -EIO);
1847 }
1848
1849 int
1850 kiblnd_recv(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg,
1851             int delayed, unsigned int niov, struct kvec *iov, lnet_kiov_t *kiov,
1852             unsigned int offset, unsigned int mlen, unsigned int rlen)
1853 {
1854         struct kib_rx *rx = private;
1855         struct kib_msg *rxmsg = rx->rx_msg;
1856         struct kib_conn *conn = rx->rx_conn;
1857         struct kib_tx *tx;
1858         __u64        ibprm_cookie;
1859         int          nob;
1860         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1861         int          rc = 0;
1862
1863         LASSERT (mlen <= rlen);
1864         LASSERT (!in_interrupt());
1865         /* Either all pages or all vaddrs */
1866         LASSERT (!(kiov != NULL && iov != NULL));
1867
1868         switch (rxmsg->ibm_type) {
1869         default:
1870                 LBUG();
1871
1872         case IBLND_MSG_IMMEDIATE:
1873                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[rlen]);
1874                 if (nob > rx->rx_nob) {
1875                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1876                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1877                                 nob, rx->rx_nob);
1878                         rc = -EPROTO;
1879                         break;
1880                 }
1881
1882                 if (kiov != NULL)
1883                         lnet_copy_flat2kiov(niov, kiov, offset,
1884                                             IBLND_MSG_SIZE, rxmsg,
1885                                             offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1886                                             mlen);
1887                 else
1888                         lnet_copy_flat2iov(niov, iov, offset,
1889                                            IBLND_MSG_SIZE, rxmsg,
1890                                            offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1891                                            mlen);
1892                 lnet_finalize(lntmsg, 0);
1893                 break;
1894
1895         case IBLND_MSG_PUT_REQ: {
1896                 struct kib_msg  *txmsg;
1897                 struct kib_rdma_desc *rd;
1898                 ibprm_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1899
1900                 if (mlen == 0) {
1901                         lnet_finalize(lntmsg, 0);
1902                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1903                                                0, ibprm_cookie);
1904                         break;
1905                 }
1906
1907                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1908                 if (tx == NULL) {
1909                         CERROR("Can't allocate tx for %s\n",
1910                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1911                         /* Not replying will break the connection */
1912                         rc = -ENOMEM;
1913                         break;
1914                 }
1915
1916                 txmsg = tx->tx_msg;
1917                 rd = &txmsg->ibm_u.putack.ibpam_rd;
1918                 if (kiov == NULL)
1919                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1920                                                  niov, iov, offset, mlen);
1921                 else
1922                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1923                                                   niov, kiov, offset, mlen);
1924                 if (rc != 0) {
1925                         CERROR("Can't setup PUT sink for %s: %d\n",
1926                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1927                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1928                         kiblnd_tx_done(tx);
1929                         /* tell peer_ni it's over */
1930                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1931                                                rc, ibprm_cookie);
1932                         break;
1933                 }
1934
1935                 nob = offsetof(struct kib_putack_msg, ibpam_rd.rd_frags[rd->rd_nfrags]);
1936                 txmsg->ibm_u.putack.ibpam_src_cookie = ibprm_cookie;
1937                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1938
1939                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1940
1941                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1942                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1943                 kiblnd_queue_tx(tx, conn);
1944
1945                 /* reposted buffer reserved for PUT_DONE */
1946                 post_credit = IBLND_POSTRX_NO_CREDIT;
1947                 break;
1948                 }
1949
1950         case IBLND_MSG_GET_REQ:
1951                 if (lntmsg != NULL) {
1952                         /* Optimized GET; RDMA lntmsg's payload */
1953                         kiblnd_reply(ni, rx, lntmsg);
1954                 } else {
1955                         /* GET didn't match anything */
1956                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1957                                                -ENODATA,
1958                                                rxmsg->ibm_u.get.ibgm_cookie);
1959                 }
1960                 break;
1961         }
1962
1963         kiblnd_post_rx(rx, post_credit);
1964         return rc;
1965 }
1966
1967 int
1968 kiblnd_thread_start(int (*fn)(void *arg), void *arg, char *name)
1969 {
1970         struct task_struct *task = kthread_run(fn, arg, name);
1971
1972         if (IS_ERR(task))
1973                 return PTR_ERR(task);
1974
1975         atomic_inc(&kiblnd_data.kib_nthreads);
1976         return 0;
1977 }
1978
1979 static void
1980 kiblnd_thread_fini (void)
1981 {
1982         atomic_dec (&kiblnd_data.kib_nthreads);
1983 }
1984
1985 static void
1986 kiblnd_peer_alive(struct kib_peer_ni *peer_ni)
1987 {
1988         /* This is racy, but everyone's only writing ktime_get_seconds() */
1989         peer_ni->ibp_last_alive = ktime_get_seconds();
1990         smp_mb();
1991 }
1992
1993 static void
1994 kiblnd_peer_notify(struct kib_peer_ni *peer_ni)
1995 {
1996         int           error = 0;
1997         time64_t last_alive = 0;
1998         unsigned long flags;
1999
2000         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2001
2002         if (kiblnd_peer_idle(peer_ni) && peer_ni->ibp_error != 0) {
2003                 error = peer_ni->ibp_error;
2004                 peer_ni->ibp_error = 0;
2005
2006                 last_alive = peer_ni->ibp_last_alive;
2007         }
2008
2009         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2010
2011         if (error != 0)
2012                 lnet_notify(peer_ni->ibp_ni,
2013                             peer_ni->ibp_nid, 0, last_alive);
2014 }
2015
2016 void
2017 kiblnd_close_conn_locked(struct kib_conn *conn, int error)
2018 {
2019         /* This just does the immediate housekeeping.  'error' is zero for a
2020          * normal shutdown which can happen only after the connection has been
2021          * established.  If the connection is established, schedule the
2022          * connection to be finished off by the connd.  Otherwise the connd is
2023          * already dealing with it (either to set it up or tear it down).
2024          * Caller holds kib_global_lock exclusively in irq context */
2025         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2026         struct kib_dev *dev;
2027         unsigned long flags;
2028
2029         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2030
2031         if (error != 0 && conn->ibc_comms_error == 0)
2032                 conn->ibc_comms_error = error;
2033
2034         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
2035                 return; /* already being handled  */
2036
2037         if (error == 0 &&
2038             list_empty(&conn->ibc_tx_noops) &&
2039             list_empty(&conn->ibc_tx_queue) &&
2040             list_empty(&conn->ibc_tx_queue_rsrvd) &&
2041             list_empty(&conn->ibc_tx_queue_nocred) &&
2042             list_empty(&conn->ibc_active_txs)) {
2043                 CDEBUG(D_NET, "closing conn to %s\n", 
2044                        libcfs_nid2str(peer_ni->ibp_nid));
2045         } else {
2046                 CNETERR("Closing conn to %s: error %d%s%s%s%s%s\n",
2047                        libcfs_nid2str(peer_ni->ibp_nid), error,
2048                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
2049                        list_empty(&conn->ibc_tx_noops) ? "" : "(sending_noops)",
2050                        list_empty(&conn->ibc_tx_queue_rsrvd) ?
2051                                                 "" : "(sending_rsrvd)",
2052                        list_empty(&conn->ibc_tx_queue_nocred) ?
2053                                                  "" : "(sending_nocred)",
2054                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
2055         }
2056
2057         dev = ((struct kib_net *)peer_ni->ibp_ni->ni_data)->ibn_dev;
2058         if (peer_ni->ibp_next_conn == conn)
2059                 /* clear next_conn so it won't be used */
2060                 peer_ni->ibp_next_conn = NULL;
2061         list_del(&conn->ibc_list);
2062         /* connd (see below) takes over ibc_list's ref */
2063
2064         if (list_empty(&peer_ni->ibp_conns) &&    /* no more conns */
2065             kiblnd_peer_active(peer_ni)) {         /* still in peer_ni table */
2066                 kiblnd_unlink_peer_locked(peer_ni);
2067
2068                 /* set/clear error on last conn */
2069                 peer_ni->ibp_error = conn->ibc_comms_error;
2070         }
2071
2072         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
2073
2074         if (error != 0 &&
2075             kiblnd_dev_can_failover(dev)) {
2076                 list_add_tail(&dev->ibd_fail_list,
2077                               &kiblnd_data.kib_failed_devs);
2078                 wake_up(&kiblnd_data.kib_failover_waitq);
2079         }
2080
2081         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2082
2083         list_add_tail(&conn->ibc_list, &kiblnd_data.kib_connd_conns);
2084         wake_up(&kiblnd_data.kib_connd_waitq);
2085
2086         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
2087 }
2088
2089 void
2090 kiblnd_close_conn(struct kib_conn *conn, int error)
2091 {
2092         unsigned long flags;
2093
2094         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2095
2096         kiblnd_close_conn_locked(conn, error);
2097
2098         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2099 }
2100
2101 static void
2102 kiblnd_handle_early_rxs(struct kib_conn *conn)
2103 {
2104         unsigned long flags;
2105         struct kib_rx *rx;
2106
2107         LASSERT(!in_interrupt());
2108         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2109
2110         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2111         while (!list_empty(&conn->ibc_early_rxs)) {
2112                 rx = list_entry(conn->ibc_early_rxs.next,
2113                                 struct kib_rx, rx_list);
2114                 list_del(&rx->rx_list);
2115                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2116
2117                 kiblnd_handle_rx(rx);
2118
2119                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2120         }
2121         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2122 }
2123
2124 static void
2125 kiblnd_abort_txs(struct kib_conn *conn, struct list_head *txs)
2126 {
2127         struct list_head         zombies = LIST_HEAD_INIT(zombies);
2128         struct list_head        *tmp;
2129         struct list_head        *nxt;
2130         struct kib_tx *tx;
2131
2132         spin_lock(&conn->ibc_lock);
2133
2134         list_for_each_safe(tmp, nxt, txs) {
2135                 tx = list_entry(tmp, struct kib_tx, tx_list);
2136
2137                 if (txs == &conn->ibc_active_txs) {
2138                         LASSERT(!tx->tx_queued);
2139                         LASSERT(tx->tx_waiting ||
2140                                 tx->tx_sending != 0);
2141                         if (conn->ibc_comms_error == -ETIMEDOUT) {
2142                                 if (tx->tx_waiting && !tx->tx_sending)
2143                                         tx->tx_hstatus =
2144                                           LNET_MSG_STATUS_REMOTE_TIMEOUT;
2145                                 else if (tx->tx_sending)
2146                                         tx->tx_hstatus =
2147                                           LNET_MSG_STATUS_NETWORK_TIMEOUT;
2148                         }
2149                 } else {
2150                         LASSERT(tx->tx_queued);
2151                         if (conn->ibc_comms_error == -ETIMEDOUT)
2152                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2153                         else
2154                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
2155                 }
2156
2157                 tx->tx_status = -ECONNABORTED;
2158                 tx->tx_waiting = 0;
2159
2160                 /*
2161                  * TODO: This makes an assumption that
2162                  * kiblnd_tx_complete() will be called for each tx. If
2163                  * that event is dropped we could end up with stale
2164                  * connections floating around. We'd like to deal with
2165                  * that in a better way.
2166                  *
2167                  * Also that means we can exceed the timeout by many
2168                  * seconds.
2169                  */
2170                 if (tx->tx_sending == 0) {
2171                         tx->tx_queued = 0;
2172                         list_del(&tx->tx_list);
2173                         list_add(&tx->tx_list, &zombies);
2174                 }
2175         }
2176
2177         spin_unlock(&conn->ibc_lock);
2178
2179         /*
2180          * aborting transmits occurs when finalizing the connection.
2181          * The connection is finalized on error.
2182          * Passing LNET_MSG_STATUS_OK to txlist_done() will not
2183          * override the value already set in tx->tx_hstatus above.
2184          */
2185         kiblnd_txlist_done(&zombies, -ECONNABORTED, LNET_MSG_STATUS_OK);
2186 }
2187
2188 static void
2189 kiblnd_finalise_conn(struct kib_conn *conn)
2190 {
2191         LASSERT (!in_interrupt());
2192         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
2193
2194         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
2195
2196         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
2197          * for connections that didn't get as far as being connected, because
2198          * rdma_disconnect() does this for free. */
2199         kiblnd_abort_receives(conn);
2200
2201         /* Complete all tx descs not waiting for sends to complete.
2202          * NB we should be safe from RDMA now that the QP has changed state */
2203
2204         kiblnd_abort_txs(conn, &conn->ibc_tx_noops);
2205         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
2206         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
2207         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
2208         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
2209
2210         kiblnd_handle_early_rxs(conn);
2211 }
2212
2213 static void
2214 kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
2215                            int error)
2216 {
2217         struct list_head zombies = LIST_HEAD_INIT(zombies);
2218         unsigned long   flags;
2219
2220         LASSERT (error != 0);
2221         LASSERT (!in_interrupt());
2222
2223         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2224
2225         if (active) {
2226                 LASSERT(peer_ni->ibp_connecting > 0);
2227                 peer_ni->ibp_connecting--;
2228         } else {
2229                 LASSERT (peer_ni->ibp_accepting > 0);
2230                 peer_ni->ibp_accepting--;
2231         }
2232
2233         if (kiblnd_peer_connecting(peer_ni)) {
2234                 /* another connection attempt under way... */
2235                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2236                                         flags);
2237                 return;
2238         }
2239
2240         peer_ni->ibp_reconnected = 0;
2241         if (list_empty(&peer_ni->ibp_conns)) {
2242                 /* Take peer_ni's blocked transmits to complete with error */
2243                 list_splice_init(&peer_ni->ibp_tx_queue, &zombies);
2244
2245                 if (kiblnd_peer_active(peer_ni))
2246                         kiblnd_unlink_peer_locked(peer_ni);
2247
2248                 peer_ni->ibp_error = error;
2249         } else {
2250                 /* Can't have blocked transmits if there are connections */
2251                 LASSERT(list_empty(&peer_ni->ibp_tx_queue));
2252         }
2253
2254         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2255
2256         kiblnd_peer_notify(peer_ni);
2257
2258         if (list_empty(&zombies))
2259                 return;
2260
2261         CNETERR("Deleting messages for %s: connection failed\n",
2262                 libcfs_nid2str(peer_ni->ibp_nid));
2263
2264         kiblnd_txlist_done(&zombies, error,
2265                            LNET_MSG_STATUS_LOCAL_DROPPED);
2266 }
2267
2268 static void
2269 kiblnd_connreq_done(struct kib_conn *conn, int status)
2270 {
2271         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2272         struct kib_tx *tx;
2273         struct list_head txs;
2274         unsigned long    flags;
2275         int              active;
2276
2277         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2278
2279         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
2280                libcfs_nid2str(peer_ni->ibp_nid), active,
2281                conn->ibc_version, status);
2282
2283         LASSERT (!in_interrupt());
2284         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2285                   peer_ni->ibp_connecting > 0) ||
2286                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2287                   peer_ni->ibp_accepting > 0));
2288
2289         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2290         conn->ibc_connvars = NULL;
2291
2292         if (status != 0) {
2293                 /* failed to establish connection */
2294                 kiblnd_peer_connect_failed(peer_ni, active, status);
2295                 kiblnd_finalise_conn(conn);
2296                 return;
2297         }
2298
2299         /* connection established */
2300         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2301
2302         conn->ibc_last_send = ktime_get();
2303         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2304         kiblnd_peer_alive(peer_ni);
2305
2306         /* Add conn to peer_ni's list and nuke any dangling conns from a different
2307          * peer_ni instance... */
2308         kiblnd_conn_addref(conn);       /* +1 ref for ibc_list */
2309         list_add(&conn->ibc_list, &peer_ni->ibp_conns);
2310         peer_ni->ibp_reconnected = 0;
2311         if (active)
2312                 peer_ni->ibp_connecting--;
2313         else
2314                 peer_ni->ibp_accepting--;
2315
2316         if (peer_ni->ibp_version == 0) {
2317                 peer_ni->ibp_version     = conn->ibc_version;
2318                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2319         }
2320
2321         if (peer_ni->ibp_version     != conn->ibc_version ||
2322             peer_ni->ibp_incarnation != conn->ibc_incarnation) {
2323                 kiblnd_close_stale_conns_locked(peer_ni, conn->ibc_version,
2324                                                 conn->ibc_incarnation);
2325                 peer_ni->ibp_version     = conn->ibc_version;
2326                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2327         }
2328
2329         /* grab pending txs while I have the lock */
2330         INIT_LIST_HEAD(&txs);
2331         list_splice_init(&peer_ni->ibp_tx_queue, &txs);
2332
2333         if (!kiblnd_peer_active(peer_ni) ||        /* peer_ni has been deleted */
2334             conn->ibc_comms_error != 0) {       /* error has happened already */
2335
2336                 /* start to shut down connection */
2337                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2338                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2339
2340                 kiblnd_txlist_done(&txs, -ECONNABORTED,
2341                                    LNET_MSG_STATUS_LOCAL_ERROR);
2342
2343                 return;
2344         }
2345
2346         /* +1 ref for myself, this connection is visible to other threads
2347          * now, refcount of peer:ibp_conns can be released by connection
2348          * close from either a different thread, or the calling of
2349          * kiblnd_check_sends_locked() below. See bz21911 for details.
2350          */
2351         kiblnd_conn_addref(conn);
2352         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2353
2354         /* Schedule blocked txs
2355          * Note: if we are running with conns_per_peer > 1, these blocked
2356          * txs will all get scheduled to the first connection which gets
2357          * scheduled.  We won't be using round robin on this first batch.
2358          */
2359         spin_lock(&conn->ibc_lock);
2360         while (!list_empty(&txs)) {
2361                 tx = list_entry(txs.next, struct kib_tx, tx_list);
2362                 list_del(&tx->tx_list);
2363
2364                 kiblnd_queue_tx_locked(tx, conn);
2365         }
2366         kiblnd_check_sends_locked(conn);
2367         spin_unlock(&conn->ibc_lock);
2368
2369         /* schedule blocked rxs */
2370         kiblnd_handle_early_rxs(conn);
2371         kiblnd_conn_decref(conn);
2372 }
2373
2374 static void
2375 kiblnd_reject(struct rdma_cm_id *cmid, struct kib_rej *rej)
2376 {
2377         int          rc;
2378
2379         rc = rdma_reject(cmid, rej, sizeof(*rej));
2380
2381         if (rc != 0)
2382                 CWARN("Error %d sending reject\n", rc);
2383 }
2384
2385 static int
2386 kiblnd_passive_connect(struct rdma_cm_id *cmid, void *priv, int priv_nob)
2387 {
2388         rwlock_t                *g_lock = &kiblnd_data.kib_global_lock;
2389         struct kib_msg *reqmsg = priv;
2390         struct kib_msg *ackmsg;
2391         struct kib_dev *ibdev;
2392         struct kib_peer_ni *peer_ni;
2393         struct kib_peer_ni *peer2;
2394         struct kib_conn *conn;
2395         struct lnet_ni *ni = NULL;
2396         struct kib_net *net = NULL;
2397         lnet_nid_t             nid;
2398         struct rdma_conn_param cp;
2399         struct kib_rej rej;
2400         int                    version = IBLND_MSG_VERSION;
2401         unsigned long          flags;
2402         int                    rc;
2403         struct sockaddr_in    *peer_addr;
2404         LASSERT (!in_interrupt());
2405
2406         /* cmid inherits 'context' from the corresponding listener id */
2407         ibdev = cmid->context;
2408         LASSERT(ibdev);
2409
2410         memset(&rej, 0, sizeof(rej));
2411         rej.ibr_magic                = IBLND_MSG_MAGIC;
2412         rej.ibr_why                  = IBLND_REJECT_FATAL;
2413         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2414
2415         peer_addr = (struct sockaddr_in *)&(cmid->route.addr.dst_addr);
2416         if (*kiblnd_tunables.kib_require_priv_port &&
2417             ntohs(peer_addr->sin_port) >= PROT_SOCK) {
2418                 __u32 ip = ntohl(peer_addr->sin_addr.s_addr);
2419                 CERROR("peer_ni's port (%pI4h:%hu) is not privileged\n",
2420                        &ip, ntohs(peer_addr->sin_port));
2421                 goto failed;
2422         }
2423
2424         if (priv_nob < offsetof(struct kib_msg, ibm_type)) {
2425                 CERROR("Short connection request\n");
2426                 goto failed;
2427         }
2428
2429         /* Future protocol version compatibility support!  If the
2430          * o2iblnd-specific protocol changes, or when LNET unifies
2431          * protocols over all LNDs, the initial connection will
2432          * negotiate a protocol version.  I trap this here to avoid
2433          * console errors; the reject tells the peer_ni which protocol I
2434          * speak. */
2435         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2436             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2437                 goto failed;
2438         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2439             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2440             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2441                 goto failed;
2442         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2443             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2444             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2445                 goto failed;
2446
2447         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2448         if (rc != 0) {
2449                 CERROR("Can't parse connection request: %d\n", rc);
2450                 goto failed;
2451         }
2452
2453         nid = reqmsg->ibm_srcnid;
2454         ni  = lnet_nid2ni_addref(reqmsg->ibm_dstnid);
2455
2456         if (ni != NULL) {
2457                 net = (struct kib_net *)ni->ni_data;
2458                 rej.ibr_incarnation = net->ibn_incarnation;
2459         }
2460
2461         if (ni == NULL ||                         /* no matching net */
2462             ni->ni_nid != reqmsg->ibm_dstnid ||   /* right NET, wrong NID! */
2463             net->ibn_dev != ibdev) {              /* wrong device */
2464                 CERROR("Can't accept conn from %s on %s (%s:%d:%pI4h): "
2465                        "bad dst nid %s\n", libcfs_nid2str(nid),
2466                        ni == NULL ? "NA" : libcfs_nid2str(ni->ni_nid),
2467                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2468                         &ibdev->ibd_ifip,
2469                        libcfs_nid2str(reqmsg->ibm_dstnid));
2470
2471                 goto failed;
2472         }
2473
2474        /* check time stamp as soon as possible */
2475         if (reqmsg->ibm_dststamp != 0 &&
2476             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2477                 CWARN("Stale connection request\n");
2478                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2479                 goto failed;
2480         }
2481
2482         /* I can accept peer_ni's version */
2483         version = reqmsg->ibm_version;
2484
2485         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2486                 CERROR("Unexpected connreq msg type: %x from %s\n",
2487                        reqmsg->ibm_type, libcfs_nid2str(nid));
2488                 goto failed;
2489         }
2490
2491         if (reqmsg->ibm_u.connparams.ibcp_queue_depth >
2492             kiblnd_msg_queue_size(version, ni)) {
2493                 CERROR("Can't accept conn from %s, queue depth too large: "
2494                        " %d (<=%d wanted)\n",
2495                        libcfs_nid2str(nid),
2496                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2497                        kiblnd_msg_queue_size(version, ni));
2498
2499                 if (version == IBLND_MSG_VERSION)
2500                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2501
2502                 goto failed;
2503         }
2504
2505         if (reqmsg->ibm_u.connparams.ibcp_max_frags >
2506             IBLND_MAX_RDMA_FRAGS) {
2507                 CWARN("Can't accept conn from %s (version %x): "
2508                       "max_frags %d too large (%d wanted)\n",
2509                       libcfs_nid2str(nid), version,
2510                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2511                       IBLND_MAX_RDMA_FRAGS);
2512
2513                 if (version >= IBLND_MSG_VERSION)
2514                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2515
2516                 goto failed;
2517         } else if (reqmsg->ibm_u.connparams.ibcp_max_frags <
2518                    IBLND_MAX_RDMA_FRAGS &&
2519                    net->ibn_fmr_ps == NULL) {
2520                 CWARN("Can't accept conn from %s (version %x): "
2521                       "max_frags %d incompatible without FMR pool "
2522                       "(%d wanted)\n",
2523                       libcfs_nid2str(nid), version,
2524                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2525                       IBLND_MAX_RDMA_FRAGS);
2526
2527                 if (version == IBLND_MSG_VERSION)
2528                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2529
2530                 goto failed;
2531         }
2532
2533         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2534                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2535                        libcfs_nid2str(nid),
2536                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2537                        IBLND_MSG_SIZE);
2538                 goto failed;
2539         }
2540
2541         /* assume 'nid' is a new peer_ni; create  */
2542         rc = kiblnd_create_peer(ni, &peer_ni, nid);
2543         if (rc != 0) {
2544                 CERROR("Can't create peer_ni for %s\n", libcfs_nid2str(nid));
2545                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2546                 goto failed;
2547         }
2548
2549         /* We have validated the peer's parameters so use those */
2550         peer_ni->ibp_max_frags = reqmsg->ibm_u.connparams.ibcp_max_frags;
2551         peer_ni->ibp_queue_depth = reqmsg->ibm_u.connparams.ibcp_queue_depth;
2552
2553         write_lock_irqsave(g_lock, flags);
2554
2555         peer2 = kiblnd_find_peer_locked(ni, nid);
2556         if (peer2 != NULL) {
2557                 if (peer2->ibp_version == 0) {
2558                         peer2->ibp_version     = version;
2559                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2560                 }
2561
2562                 /* not the guy I've talked with */
2563                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2564                     peer2->ibp_version     != version) {
2565                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2566
2567                         if (kiblnd_peer_active(peer2)) {
2568                                 peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2569                                 peer2->ibp_version = version;
2570                         }
2571                         write_unlock_irqrestore(g_lock, flags);
2572
2573                         CWARN("Conn stale %s version %x/%x incarnation %llu/%llu\n",
2574                               libcfs_nid2str(nid), peer2->ibp_version, version,
2575                               peer2->ibp_incarnation, reqmsg->ibm_srcstamp);
2576
2577                         kiblnd_peer_decref(peer_ni);
2578                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2579                         goto failed;
2580                 }
2581
2582                 /* Tie-break connection race in favour of the higher NID.
2583                  * If we keep running into a race condition multiple times,
2584                  * we have to assume that the connection attempt with the
2585                  * higher NID is stuck in a connecting state and will never
2586                  * recover.  As such, we pass through this if-block and let
2587                  * the lower NID connection win so we can move forward.
2588                  */
2589                 if (peer2->ibp_connecting != 0 &&
2590                     nid < ni->ni_nid && peer2->ibp_races <
2591                     MAX_CONN_RACES_BEFORE_ABORT) {
2592                         peer2->ibp_races++;
2593                         write_unlock_irqrestore(g_lock, flags);
2594
2595                         CDEBUG(D_NET, "Conn race %s\n",
2596                                libcfs_nid2str(peer2->ibp_nid));
2597
2598                         kiblnd_peer_decref(peer_ni);
2599                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2600                         goto failed;
2601                 }
2602                 if (peer2->ibp_races >= MAX_CONN_RACES_BEFORE_ABORT)
2603                         CNETERR("Conn race %s: unresolved after %d attempts, letting lower NID win\n",
2604                                 libcfs_nid2str(peer2->ibp_nid),
2605                                 MAX_CONN_RACES_BEFORE_ABORT);
2606                 /*
2607                  * passive connection is allowed even this peer_ni is waiting for
2608                  * reconnection.
2609                  */
2610                 peer2->ibp_reconnecting = 0;
2611                 peer2->ibp_races = 0;
2612                 peer2->ibp_accepting++;
2613                 kiblnd_peer_addref(peer2);
2614
2615                 /* Race with kiblnd_launch_tx (active connect) to create peer_ni
2616                  * so copy validated parameters since we now know what the
2617                  * peer_ni's limits are */
2618                 peer2->ibp_max_frags = peer_ni->ibp_max_frags;
2619                 peer2->ibp_queue_depth = peer_ni->ibp_queue_depth;
2620
2621                 write_unlock_irqrestore(g_lock, flags);
2622                 kiblnd_peer_decref(peer_ni);
2623                 peer_ni = peer2;
2624         } else {
2625                 /* Brand new peer_ni */
2626                 LASSERT (peer_ni->ibp_accepting == 0);
2627                 LASSERT (peer_ni->ibp_version == 0 &&
2628                          peer_ni->ibp_incarnation == 0);
2629
2630                 peer_ni->ibp_accepting   = 1;
2631                 peer_ni->ibp_version     = version;
2632                 peer_ni->ibp_incarnation = reqmsg->ibm_srcstamp;
2633
2634                 /* I have a ref on ni that prevents it being shutdown */
2635                 LASSERT (net->ibn_shutdown == 0);
2636
2637                 kiblnd_peer_addref(peer_ni);
2638                 list_add_tail(&peer_ni->ibp_list, kiblnd_nid2peerlist(nid));
2639
2640                 write_unlock_irqrestore(g_lock, flags);
2641         }
2642
2643         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_PASSIVE_WAIT, version);
2644         if (conn == NULL) {
2645                 kiblnd_peer_connect_failed(peer_ni, 0, -ENOMEM);
2646                 kiblnd_peer_decref(peer_ni);
2647                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2648                 goto failed;
2649         }
2650
2651         /* conn now "owns" cmid, so I return success from here on to ensure the
2652          * CM callback doesn't destroy cmid. */
2653         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2654         conn->ibc_credits          = conn->ibc_queue_depth;
2655         conn->ibc_reserved_credits = conn->ibc_queue_depth;
2656         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2657                 IBLND_OOB_MSGS(version) <= IBLND_RX_MSGS(conn));
2658
2659         ackmsg = &conn->ibc_connvars->cv_msg;
2660         memset(ackmsg, 0, sizeof(*ackmsg));
2661
2662         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2663                         sizeof(ackmsg->ibm_u.connparams));
2664         ackmsg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2665         ackmsg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2666         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2667
2668         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2669
2670         memset(&cp, 0, sizeof(cp));
2671         cp.private_data        = ackmsg;
2672         cp.private_data_len    = ackmsg->ibm_nob;
2673         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2674         cp.initiator_depth     = 0;
2675         cp.flow_control        = 1;
2676         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2677         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2678
2679         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2680
2681         rc = rdma_accept(cmid, &cp);
2682         if (rc != 0) {
2683                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2684                 rej.ibr_version = version;
2685                 rej.ibr_why     = IBLND_REJECT_FATAL;
2686
2687                 kiblnd_reject(cmid, &rej);
2688                 kiblnd_connreq_done(conn, rc);
2689                 kiblnd_conn_decref(conn);
2690         }
2691
2692         lnet_ni_decref(ni);
2693         return 0;
2694
2695  failed:
2696         if (ni != NULL) {
2697                 rej.ibr_cp.ibcp_queue_depth =
2698                         kiblnd_msg_queue_size(version, ni);
2699                 rej.ibr_cp.ibcp_max_frags   = IBLND_MAX_RDMA_FRAGS;
2700                 lnet_ni_decref(ni);
2701         }
2702
2703         rej.ibr_version = version;
2704         kiblnd_reject(cmid, &rej);
2705
2706         return -ECONNREFUSED;
2707 }
2708
2709 static void
2710 kiblnd_check_reconnect(struct kib_conn *conn, int version,
2711                        u64 incarnation, int why, struct kib_connparams *cp)
2712 {
2713         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
2714         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2715         char            *reason;
2716         int              msg_size = IBLND_MSG_SIZE;
2717         int              frag_num = -1;
2718         int              queue_dep = -1;
2719         bool             reconnect;
2720         unsigned long    flags;
2721
2722         LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2723         LASSERT(peer_ni->ibp_connecting > 0);   /* 'conn' at least */
2724
2725         if (cp) {
2726                 msg_size        = cp->ibcp_max_msg_size;
2727                 frag_num        = cp->ibcp_max_frags;
2728                 queue_dep       = cp->ibcp_queue_depth;
2729         }
2730
2731         write_lock_irqsave(glock, flags);
2732         /* retry connection if it's still needed and no other connection
2733          * attempts (active or passive) are in progress
2734          * NB: reconnect is still needed even when ibp_tx_queue is
2735          * empty if ibp_version != version because reconnect may be
2736          * initiated by kiblnd_query() */
2737         reconnect = (!list_empty(&peer_ni->ibp_tx_queue) ||
2738                      peer_ni->ibp_version != version) &&
2739                     peer_ni->ibp_connecting &&
2740                     peer_ni->ibp_accepting == 0;
2741         if (!reconnect) {
2742                 reason = "no need";
2743                 goto out;
2744         }
2745
2746         switch (why) {
2747         default:
2748                 reason = "Unknown";
2749                 break;
2750
2751         case IBLND_REJECT_RDMA_FRAGS: {
2752                 struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2753
2754                 if (!cp) {
2755                         reason = "can't negotiate max frags";
2756                         goto out;
2757                 }
2758                 tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2759 #ifdef HAVE_IB_GET_DMA_MR
2760                 /*
2761                  * This check only makes sense if the kernel supports global
2762                  * memory registration. Otherwise, map_on_demand will never == 0
2763                  */
2764                 if (!tunables->lnd_map_on_demand) {
2765                         reason = "map_on_demand must be enabled";
2766                         goto out;
2767                 }
2768 #endif
2769                 if (conn->ibc_max_frags <= frag_num) {
2770                         reason = "unsupported max frags";
2771                         goto out;
2772                 }
2773
2774                 peer_ni->ibp_max_frags = frag_num;
2775                 reason = "rdma fragments";
2776                 break;
2777         }
2778         case IBLND_REJECT_MSG_QUEUE_SIZE:
2779                 if (!cp) {
2780                         reason = "can't negotiate queue depth";
2781                         goto out;
2782                 }
2783                 if (conn->ibc_queue_depth <= queue_dep) {
2784                         reason = "unsupported queue depth";
2785                         goto out;
2786                 }
2787
2788                 peer_ni->ibp_queue_depth = queue_dep;
2789                 reason = "queue depth";
2790                 break;
2791
2792         case IBLND_REJECT_CONN_STALE:
2793                 reason = "stale";
2794                 break;
2795
2796         case IBLND_REJECT_CONN_RACE:
2797                 reason = "conn race";
2798                 break;
2799
2800         case IBLND_REJECT_CONN_UNCOMPAT:
2801                 reason = "version negotiation";
2802                 break;
2803
2804         case IBLND_REJECT_INVALID_SRV_ID:
2805                 reason = "invalid service id";
2806                 break;
2807         }
2808
2809         conn->ibc_reconnect = 1;
2810         peer_ni->ibp_reconnecting++;
2811         peer_ni->ibp_version = version;
2812         if (incarnation != 0)
2813                 peer_ni->ibp_incarnation = incarnation;
2814  out:
2815         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2816
2817         CNETERR("%s: %s (%s), %x, %x, msg_size: %d, queue_depth: %d/%d, max_frags: %d/%d\n",
2818                 libcfs_nid2str(peer_ni->ibp_nid),
2819                 reconnect ? "reconnect" : "don't reconnect",
2820                 reason, IBLND_MSG_VERSION, version, msg_size,
2821                 conn->ibc_queue_depth, queue_dep,
2822                 conn->ibc_max_frags, frag_num);
2823         /*
2824          * if conn::ibc_reconnect is TRUE, connd will reconnect to the peer_ni
2825          * while destroying the zombie
2826          */
2827 }
2828
2829 static void
2830 kiblnd_rejected(struct kib_conn *conn, int reason, void *priv, int priv_nob)
2831 {
2832         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2833
2834         LASSERT (!in_interrupt());
2835         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2836
2837         switch (reason) {
2838         case IB_CM_REJ_STALE_CONN:
2839                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2840                                        IBLND_REJECT_CONN_STALE, NULL);
2841                 break;
2842
2843         case IB_CM_REJ_INVALID_SERVICE_ID:
2844                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2845                                        IBLND_REJECT_INVALID_SRV_ID, NULL);
2846                 CNETERR("%s rejected: no listener at %d\n",
2847                         libcfs_nid2str(peer_ni->ibp_nid),
2848                         *kiblnd_tunables.kib_service);
2849                 break;
2850
2851         case IB_CM_REJ_CONSUMER_DEFINED:
2852                 if (priv_nob >= offsetof(struct kib_rej, ibr_padding)) {
2853                         struct kib_rej *rej = priv;
2854                         struct kib_connparams *cp = NULL;
2855                         int               flip        = 0;
2856                         __u64             incarnation = -1;
2857
2858                         /* NB. default incarnation is -1 because:
2859                          * a) V1 will ignore dst incarnation in connreq.
2860                          * b) V2 will provide incarnation while rejecting me,
2861                          *    -1 will be overwrote.
2862                          *
2863                          * if I try to connect to a V1 peer_ni with V2 protocol,
2864                          * it rejected me then upgrade to V2, I have no idea
2865                          * about the upgrading and try to reconnect with V1,
2866                          * in this case upgraded V2 can find out I'm trying to
2867                          * talk to the old guy and reject me(incarnation is -1). 
2868                          */
2869
2870                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2871                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2872                                 __swab32s(&rej->ibr_magic);
2873                                 __swab16s(&rej->ibr_version);
2874                                 flip = 1;
2875                         }
2876
2877                         if (priv_nob >= sizeof(struct kib_rej) &&
2878                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2879                                 /* priv_nob is always 148 in current version
2880                                  * of OFED, so we still need to check version.
2881                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE) */
2882                                 cp = &rej->ibr_cp;
2883
2884                                 if (flip) {
2885                                         __swab64s(&rej->ibr_incarnation);
2886                                         __swab16s(&cp->ibcp_queue_depth);
2887                                         __swab16s(&cp->ibcp_max_frags);
2888                                         __swab32s(&cp->ibcp_max_msg_size);
2889                                 }
2890
2891                                 incarnation = rej->ibr_incarnation;
2892                         }
2893
2894                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2895                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2896                                 CERROR("%s rejected: consumer defined fatal error\n",
2897                                        libcfs_nid2str(peer_ni->ibp_nid));
2898                                 break;
2899                         }
2900
2901                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2902                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2903                                 CERROR("%s rejected: o2iblnd version %x error\n",
2904                                        libcfs_nid2str(peer_ni->ibp_nid),
2905                                        rej->ibr_version);
2906                                 break;
2907                         }
2908
2909                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2910                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2911                                 CDEBUG(D_NET, "rejected by old version peer_ni %s: %x\n",
2912                                        libcfs_nid2str(peer_ni->ibp_nid), rej->ibr_version);
2913
2914                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2915                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2916                         }
2917
2918                         switch (rej->ibr_why) {
2919                         case IBLND_REJECT_CONN_RACE:
2920                         case IBLND_REJECT_CONN_STALE:
2921                         case IBLND_REJECT_CONN_UNCOMPAT:
2922                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2923                         case IBLND_REJECT_RDMA_FRAGS:
2924                                 kiblnd_check_reconnect(conn, rej->ibr_version,
2925                                                 incarnation, rej->ibr_why, cp);
2926                                 break;
2927
2928                         case IBLND_REJECT_NO_RESOURCES:
2929                                 CERROR("%s rejected: o2iblnd no resources\n",
2930                                        libcfs_nid2str(peer_ni->ibp_nid));
2931                                 break;
2932
2933                         case IBLND_REJECT_FATAL:
2934                                 CERROR("%s rejected: o2iblnd fatal error\n",
2935                                        libcfs_nid2str(peer_ni->ibp_nid));
2936                                 break;
2937
2938                         default:
2939                                 CERROR("%s rejected: o2iblnd reason %d\n",
2940                                        libcfs_nid2str(peer_ni->ibp_nid),
2941                                        rej->ibr_why);
2942                                 break;
2943                         }
2944                         break;
2945                 }
2946                 /* fall through */
2947         default:
2948                 CNETERR("%s rejected: reason %d, size %d\n",
2949                         libcfs_nid2str(peer_ni->ibp_nid), reason, priv_nob);
2950                 break;
2951         }
2952
2953         kiblnd_connreq_done(conn, -ECONNREFUSED);
2954 }
2955
2956 static void
2957 kiblnd_check_connreply(struct kib_conn *conn, void *priv, int priv_nob)
2958 {
2959         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2960         struct lnet_ni *ni = peer_ni->ibp_ni;
2961         struct kib_net *net = ni->ni_data;
2962         struct kib_msg *msg = priv;
2963         int            ver  = conn->ibc_version;
2964         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
2965         unsigned long  flags;
2966
2967         LASSERT (net != NULL);
2968
2969         if (rc != 0) {
2970                 CERROR("Can't unpack connack from %s: %d\n",
2971                        libcfs_nid2str(peer_ni->ibp_nid), rc);
2972                 goto failed;
2973         }
2974
2975         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2976                 CERROR("Unexpected message %d from %s\n",
2977                        msg->ibm_type, libcfs_nid2str(peer_ni->ibp_nid));
2978                 rc = -EPROTO;
2979                 goto failed;
2980         }
2981
2982         if (ver != msg->ibm_version) {
2983                 CERROR("%s replied version %x is different with "
2984                        "requested version %x\n",
2985                        libcfs_nid2str(peer_ni->ibp_nid), msg->ibm_version, ver);
2986                 rc = -EPROTO;
2987                 goto failed;
2988         }
2989
2990         if (msg->ibm_u.connparams.ibcp_queue_depth >
2991             conn->ibc_queue_depth) {
2992                 CERROR("%s has incompatible queue depth %d (<=%d wanted)\n",
2993                        libcfs_nid2str(peer_ni->ibp_nid),
2994                        msg->ibm_u.connparams.ibcp_queue_depth,
2995                        conn->ibc_queue_depth);
2996                 rc = -EPROTO;
2997                 goto failed;
2998         }
2999
3000         if (msg->ibm_u.connparams.ibcp_max_frags >
3001             conn->ibc_max_frags) {
3002                 CERROR("%s has incompatible max_frags %d (<=%d wanted)\n",
3003                        libcfs_nid2str(peer_ni->ibp_nid),
3004                        msg->ibm_u.connparams.ibcp_max_frags,
3005                        conn->ibc_max_frags);
3006                 rc = -EPROTO;
3007                 goto failed;
3008         }
3009
3010         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
3011                 CERROR("%s max message size %d too big (%d max)\n",
3012                        libcfs_nid2str(peer_ni->ibp_nid),
3013                        msg->ibm_u.connparams.ibcp_max_msg_size,
3014                        IBLND_MSG_SIZE);
3015                 rc = -EPROTO;
3016                 goto failed;
3017         }
3018
3019         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3020         if (msg->ibm_dstnid == ni->ni_nid &&
3021             msg->ibm_dststamp == net->ibn_incarnation)
3022                 rc = 0;
3023         else
3024                 rc = -ESTALE;
3025         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3026
3027         if (rc != 0) {
3028                 CERROR("Bad connection reply from %s, rc = %d, "
3029                        "version: %x max_frags: %d\n",
3030                        libcfs_nid2str(peer_ni->ibp_nid), rc,
3031                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
3032                 goto failed;
3033         }
3034
3035         conn->ibc_incarnation      = msg->ibm_srcstamp;
3036         conn->ibc_credits          = msg->ibm_u.connparams.ibcp_queue_depth;
3037         conn->ibc_reserved_credits = msg->ibm_u.connparams.ibcp_queue_depth;
3038         conn->ibc_queue_depth      = msg->ibm_u.connparams.ibcp_queue_depth;
3039         conn->ibc_max_frags        = msg->ibm_u.connparams.ibcp_max_frags;
3040         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
3041                 IBLND_OOB_MSGS(ver) <= IBLND_RX_MSGS(conn));
3042
3043         kiblnd_connreq_done(conn, 0);
3044         return;
3045
3046  failed:
3047         /* NB My QP has already established itself, so I handle anything going
3048          * wrong here by setting ibc_comms_error.
3049          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
3050          * immediately tears it down. */
3051
3052         LASSERT (rc != 0);
3053         conn->ibc_comms_error = rc;
3054         kiblnd_connreq_done(conn, 0);
3055 }
3056
3057 static int
3058 kiblnd_active_connect(struct rdma_cm_id *cmid)
3059 {
3060         struct kib_peer_ni *peer_ni = cmid->context;
3061         struct kib_conn *conn;
3062         struct kib_msg *msg;
3063         struct rdma_conn_param cp;
3064         int                      version;
3065         __u64                    incarnation;
3066         unsigned long            flags;
3067         int                      rc;
3068
3069         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3070
3071         incarnation = peer_ni->ibp_incarnation;
3072         version     = (peer_ni->ibp_version == 0) ? IBLND_MSG_VERSION :
3073                                                  peer_ni->ibp_version;
3074
3075         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3076
3077         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_ACTIVE_CONNECT,
3078                                   version);
3079         if (conn == NULL) {
3080                 kiblnd_peer_connect_failed(peer_ni, 1, -ENOMEM);
3081                 kiblnd_peer_decref(peer_ni); /* lose cmid's ref */
3082                 return -ENOMEM;
3083         }
3084
3085         /* conn "owns" cmid now, so I return success from here on to ensure the
3086          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
3087          * on peer_ni */
3088
3089         msg = &conn->ibc_connvars->cv_msg;
3090
3091         memset(msg, 0, sizeof(*msg));
3092         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
3093         msg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
3094         msg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
3095         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
3096
3097         kiblnd_pack_msg(peer_ni->ibp_ni, msg, version,
3098                         0, peer_ni->ibp_nid, incarnation);
3099
3100         memset(&cp, 0, sizeof(cp));
3101         cp.private_data        = msg;
3102         cp.private_data_len    = msg->ibm_nob;
3103         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
3104         cp.initiator_depth     = 0;
3105         cp.flow_control        = 1;
3106         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
3107         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
3108
3109         LASSERT(cmid->context == (void *)conn);
3110         LASSERT(conn->ibc_cmid == cmid);
3111
3112         rc = rdma_connect(cmid, &cp);
3113         if (rc != 0) {
3114                 CERROR("Can't connect to %s: %d\n",
3115                        libcfs_nid2str(peer_ni->ibp_nid), rc);
3116                 kiblnd_connreq_done(conn, rc);
3117                 kiblnd_conn_decref(conn);
3118         }
3119
3120         return 0;
3121 }
3122
3123 int
3124 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
3125 {
3126         struct kib_peer_ni *peer_ni;
3127         struct kib_conn *conn;
3128         int rc;
3129
3130         switch (event->event) {
3131         default:
3132                 CERROR("Unexpected event: %d, status: %d\n",
3133                        event->event, event->status);
3134                 LBUG();
3135
3136         case RDMA_CM_EVENT_CONNECT_REQUEST:
3137                 /* destroy cmid on failure */
3138                 rc = kiblnd_passive_connect(cmid,
3139                                             (void *)KIBLND_CONN_PARAM(event),
3140                                             KIBLND_CONN_PARAM_LEN(event));
3141                 CDEBUG(D_NET, "connreq: %d\n", rc);
3142                 return rc;
3143
3144         case RDMA_CM_EVENT_ADDR_ERROR:
3145                 peer_ni = cmid->context;
3146                 CNETERR("%s: ADDR ERROR %d\n",
3147                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3148                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3149                 kiblnd_peer_decref(peer_ni);
3150                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
3151
3152         case RDMA_CM_EVENT_ADDR_RESOLVED:
3153                 peer_ni = cmid->context;
3154
3155                 CDEBUG(D_NET,"%s Addr resolved: %d\n",
3156                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3157
3158                 if (event->status != 0) {
3159                         CNETERR("Can't resolve address for %s: %d\n",
3160                                 libcfs_nid2str(peer_ni->ibp_nid), event->status);
3161                         rc = event->status;
3162                 } else {
3163                         rc = rdma_resolve_route(
3164                                 cmid, lnet_get_lnd_timeout() * 1000);
3165                         if (rc == 0) {
3166                                 struct kib_net *net = peer_ni->ibp_ni->ni_data;
3167                                 struct kib_dev *dev = net->ibn_dev;
3168
3169                                 CDEBUG(D_NET, "%s: connection bound to "\
3170                                        "%s:%pI4h:%s\n",
3171                                        libcfs_nid2str(peer_ni->ibp_nid),
3172                                        dev->ibd_ifname,
3173                                        &dev->ibd_ifip, cmid->device->name);
3174
3175                                 return 0;
3176                         }
3177
3178                         /* Can't initiate route resolution */
3179                         CERROR("Can't resolve route for %s: %d\n",
3180                                libcfs_nid2str(peer_ni->ibp_nid), rc);
3181                 }
3182                 kiblnd_peer_connect_failed(peer_ni, 1, rc);
3183                 kiblnd_peer_decref(peer_ni);
3184                 return rc;                      /* rc != 0 destroys cmid */
3185
3186         case RDMA_CM_EVENT_ROUTE_ERROR:
3187                 peer_ni = cmid->context;
3188                 CNETERR("%s: ROUTE ERROR %d\n",
3189                         libcfs_nid2str(peer_ni->ibp_nid), event->status);
3190                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3191                 kiblnd_peer_decref(peer_ni);
3192                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
3193
3194         case RDMA_CM_EVENT_ROUTE_RESOLVED:
3195                 peer_ni = cmid->context;
3196                 CDEBUG(D_NET,"%s Route resolved: %d\n",
3197                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3198
3199                 if (event->status == 0)
3200                         return kiblnd_active_connect(cmid);
3201
3202                 CNETERR("Can't resolve route for %s: %d\n",
3203                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3204                 kiblnd_peer_connect_failed(peer_ni, 1, event->status);
3205                 kiblnd_peer_decref(peer_ni);
3206                 return event->status;           /* rc != 0 destroys cmid */
3207
3208         case RDMA_CM_EVENT_UNREACHABLE:
3209                 conn = cmid->context;
3210                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3211                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3212                 CNETERR("%s: UNREACHABLE %d\n",
3213                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3214                 kiblnd_connreq_done(conn, -ENETDOWN);
3215                 kiblnd_conn_decref(conn);
3216                 return 0;
3217
3218         case RDMA_CM_EVENT_CONNECT_ERROR:
3219                 conn = cmid->context;
3220                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3221                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3222                 CNETERR("%s: CONNECT ERROR %d\n",
3223                         libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3224                 kiblnd_connreq_done(conn, -ENOTCONN);
3225                 kiblnd_conn_decref(conn);
3226                 return 0;
3227
3228         case RDMA_CM_EVENT_REJECTED:
3229                 conn = cmid->context;
3230                 switch (conn->ibc_state) {
3231                 default:
3232                         LBUG();
3233
3234                 case IBLND_CONN_PASSIVE_WAIT:
3235                         CERROR ("%s: REJECTED %d\n",
3236                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
3237                                 event->status);
3238                         kiblnd_connreq_done(conn, -ECONNRESET);
3239                         break;
3240
3241                 case IBLND_CONN_ACTIVE_CONNECT:
3242                         kiblnd_rejected(conn, event->status,
3243                                         (void *)KIBLND_CONN_PARAM(event),
3244                                         KIBLND_CONN_PARAM_LEN(event));
3245                         break;
3246                 }
3247                 kiblnd_conn_decref(conn);
3248                 return 0;
3249
3250         case RDMA_CM_EVENT_ESTABLISHED:
3251                 conn = cmid->context;
3252                 switch (conn->ibc_state) {
3253                 default:
3254                         LBUG();
3255
3256                 case IBLND_CONN_PASSIVE_WAIT:
3257                         CDEBUG(D_NET, "ESTABLISHED (passive): %s\n",
3258                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3259                         kiblnd_connreq_done(conn, 0);
3260                         break;
3261
3262                 case IBLND_CONN_ACTIVE_CONNECT:
3263                         CDEBUG(D_NET, "ESTABLISHED(active): %s\n",
3264                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3265                         kiblnd_check_connreply(conn,
3266                                                (void *)KIBLND_CONN_PARAM(event),
3267                                                KIBLND_CONN_PARAM_LEN(event));
3268                         break;
3269                 }
3270                 /* net keeps its ref on conn! */
3271                 return 0;
3272
3273         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
3274                 CDEBUG(D_NET, "Ignore TIMEWAIT_EXIT event\n");
3275                 return 0;
3276
3277         case RDMA_CM_EVENT_DISCONNECTED:
3278                 conn = cmid->context;
3279                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
3280                         CERROR("%s DISCONNECTED\n",
3281                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3282                         kiblnd_connreq_done(conn, -ECONNRESET);
3283                 } else {
3284                         kiblnd_close_conn(conn, 0);
3285                 }
3286                 kiblnd_conn_decref(conn);
3287                 cmid->context = NULL;
3288                 return 0;
3289
3290         case RDMA_CM_EVENT_DEVICE_REMOVAL:
3291                 LCONSOLE_ERROR_MSG(0x131,
3292                                    "Received notification of device removal\n"
3293                                    "Please shutdown LNET to allow this to proceed\n");
3294                 /* Can't remove network from underneath LNET for now, so I have
3295                  * to ignore this */
3296                 return 0;
3297
3298         case RDMA_CM_EVENT_ADDR_CHANGE:
3299                 LCONSOLE_INFO("Physical link changed (eg hca/port)\n");
3300                 return 0;
3301         }
3302 }
3303
3304 static int
3305 kiblnd_check_txs_locked(struct kib_conn *conn, struct list_head *txs)
3306 {
3307         struct kib_tx *tx;
3308         struct list_head *ttmp;
3309
3310         list_for_each(ttmp, txs) {
3311                 tx = list_entry(ttmp, struct kib_tx, tx_list);
3312
3313                 if (txs != &conn->ibc_active_txs) {
3314                         LASSERT(tx->tx_queued);
3315                 } else {
3316                         LASSERT(!tx->tx_queued);
3317                         LASSERT(tx->tx_waiting || tx->tx_sending != 0);
3318                 }
3319
3320                 if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3321                         CERROR("Timed out tx: %s, %lld seconds\n",
3322                                kiblnd_queue2str(conn, txs),
3323                                ktime_ms_delta(ktime_get(),
3324                                               tx->tx_deadline) / MSEC_PER_SEC);
3325                         return 1;
3326                 }
3327         }
3328
3329         return 0;
3330 }
3331
3332 static int
3333 kiblnd_conn_timed_out_locked(struct kib_conn *conn)
3334 {
3335         return  kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue) ||
3336                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_noops) ||
3337                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_rsrvd) ||
3338                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_nocred) ||
3339                 kiblnd_check_txs_locked(conn, &conn->ibc_active_txs);
3340 }
3341
3342 static void
3343 kiblnd_check_conns (int idx)
3344 {
3345         struct list_head  closes = LIST_HEAD_INIT(closes);
3346         struct list_head  checksends = LIST_HEAD_INIT(checksends);
3347         struct list_head  timedout_txs = LIST_HEAD_INIT(timedout_txs);
3348         struct list_head *peers = &kiblnd_data.kib_peers[idx];
3349         struct list_head *ptmp;
3350         struct kib_peer_ni *peer_ni;
3351         struct kib_conn *conn;
3352         struct kib_tx *tx, *tx_tmp;
3353         struct list_head *ctmp;
3354         unsigned long     flags;
3355
3356         /* NB. We expect to have a look at all the peers and not find any
3357          * RDMAs to time out, so we just use a shared lock while we
3358          * take a look... */
3359         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3360
3361         list_for_each(ptmp, peers) {
3362                 peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
3363
3364                 /* Check tx_deadline */
3365                 list_for_each_entry_safe(tx, tx_tmp, &peer_ni->ibp_tx_queue, tx_list) {
3366                         if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3367                                 CWARN("Timed out tx for %s: %lld seconds\n",
3368                                       libcfs_nid2str(peer_ni->ibp_nid),
3369                                       ktime_ms_delta(ktime_get(),
3370                                                      tx->tx_deadline) / MSEC_PER_SEC);
3371                                 list_move(&tx->tx_list, &timedout_txs);
3372                         }
3373                 }
3374
3375                 list_for_each(ctmp, &peer_ni->ibp_conns) {
3376                         int timedout;
3377                         int sendnoop;
3378
3379                         conn = list_entry(ctmp, struct kib_conn, ibc_list);
3380
3381                         LASSERT(conn->ibc_state == IBLND_CONN_ESTABLISHED);
3382
3383                         spin_lock(&conn->ibc_lock);
3384
3385                         sendnoop = kiblnd_need_noop(conn);
3386                         timedout = kiblnd_conn_timed_out_locked(conn);
3387                         if (!sendnoop && !timedout) {
3388                                 spin_unlock(&conn->ibc_lock);
3389                                 continue;
3390                         }
3391
3392                         if (timedout) {
3393                                 CERROR("Timed out RDMA with %s (%lld): "
3394                                        "c: %u, oc: %u, rc: %u\n",
3395                                        libcfs_nid2str(peer_ni->ibp_nid),
3396                                        ktime_get_seconds() - peer_ni->ibp_last_alive,
3397                                        conn->ibc_credits,
3398                                        conn->ibc_outstanding_credits,
3399                                        conn->ibc_reserved_credits);
3400                                 list_add(&conn->ibc_connd_list, &closes);
3401                         } else {
3402                                 list_add(&conn->ibc_connd_list, &checksends);
3403                         }
3404                         /* +ref for 'closes' or 'checksends' */
3405                         kiblnd_conn_addref(conn);
3406
3407                         spin_unlock(&conn->ibc_lock);
3408                 }
3409         }
3410
3411         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3412
3413         if (!list_empty(&timedout_txs))
3414                 kiblnd_txlist_done(&timedout_txs, -ETIMEDOUT,
3415                                    LNET_MSG_STATUS_LOCAL_TIMEOUT);
3416
3417         /* Handle timeout by closing the whole
3418          * connection. We can only be sure RDMA activity
3419          * has ceased once the QP has been modified. */
3420         while (!list_empty(&closes)) {
3421                 conn = list_entry(closes.next,
3422                                   struct kib_conn, ibc_connd_list);
3423                 list_del(&conn->ibc_connd_list);
3424                 kiblnd_close_conn(conn, -ETIMEDOUT);
3425                 kiblnd_conn_decref(conn);
3426         }
3427
3428         /* In case we have enough credits to return via a
3429          * NOOP, but there were no non-blocking tx descs
3430          * free to do it last time... */
3431         while (!list_empty(&checksends)) {
3432                 conn = list_entry(checksends.next,
3433                                   struct kib_conn, ibc_connd_list);
3434                 list_del(&conn->ibc_connd_list);
3435
3436                 spin_lock(&conn->ibc_lock);
3437                 kiblnd_check_sends_locked(conn);
3438                 spin_unlock(&conn->ibc_lock);
3439
3440                 kiblnd_conn_decref(conn);
3441         }
3442 }
3443
3444 static void
3445 kiblnd_disconnect_conn(struct kib_conn *conn)
3446 {
3447         LASSERT (!in_interrupt());
3448         LASSERT (current == kiblnd_data.kib_connd);
3449         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
3450
3451         rdma_disconnect(conn->ibc_cmid);
3452         kiblnd_finalise_conn(conn);
3453
3454         kiblnd_peer_notify(conn->ibc_peer);
3455 }
3456
3457 /*
3458  * High-water for reconnection to the same peer_ni, reconnection attempt should
3459  * be delayed after trying more than KIB_RECONN_HIGH_RACE.
3460  */
3461 #define KIB_RECONN_HIGH_RACE    10
3462 /*
3463  * Allow connd to take a break and handle other things after consecutive
3464  * reconnection attemps.
3465  */
3466 #define KIB_RECONN_BREAK        100
3467
3468 int
3469 kiblnd_connd (void *arg)
3470 {
3471         spinlock_t        *lock= &kiblnd_data.kib_connd_lock;
3472         wait_queue_entry_t wait;
3473         unsigned long      flags;
3474         struct kib_conn *conn;
3475         int                timeout;
3476         int                i;
3477         int                dropped_lock;
3478         int                peer_index = 0;
3479         unsigned long      deadline = jiffies;
3480
3481         cfs_block_allsigs();
3482
3483         init_waitqueue_entry(&wait, current);
3484         kiblnd_data.kib_connd = current;
3485
3486         spin_lock_irqsave(lock, flags);
3487
3488         while (!kiblnd_data.kib_shutdown) {
3489                 int reconn = 0;
3490
3491                 dropped_lock = 0;
3492
3493                 if (!list_empty(&kiblnd_data.kib_connd_zombies)) {
3494                         struct kib_peer_ni *peer_ni = NULL;
3495
3496                         conn = list_entry(kiblnd_data.kib_connd_zombies.next,
3497                                           struct kib_conn, ibc_list);
3498                         list_del(&conn->ibc_list);
3499                         if (conn->ibc_reconnect) {
3500                                 peer_ni = conn->ibc_peer;
3501                                 kiblnd_peer_addref(peer_ni);
3502                         }
3503
3504                         spin_unlock_irqrestore(lock, flags);
3505                         dropped_lock = 1;
3506
3507                         kiblnd_destroy_conn(conn);
3508
3509                         spin_lock_irqsave(lock, flags);
3510                         if (!peer_ni) {
3511                                 LIBCFS_FREE(conn, sizeof(*conn));
3512                                 continue;
3513                         }
3514
3515                         conn->ibc_peer = peer_ni;
3516                         if (peer_ni->ibp_reconnected < KIB_RECONN_HIGH_RACE)
3517                                 list_add_tail(&conn->ibc_list,
3518                                               &kiblnd_data.kib_reconn_list);
3519                         else
3520                                 list_add_tail(&conn->ibc_list,
3521                                               &kiblnd_data.kib_reconn_wait);
3522                 }
3523
3524                 if (!list_empty(&kiblnd_data.kib_connd_conns)) {
3525                         conn = list_entry(kiblnd_data.kib_connd_conns.next,
3526                                           struct kib_conn, ibc_list);
3527                         list_del(&conn->ibc_list);
3528
3529                         spin_unlock_irqrestore(lock, flags);
3530                         dropped_lock = 1;
3531
3532                         kiblnd_disconnect_conn(conn);
3533                         kiblnd_conn_decref(conn);
3534
3535                         spin_lock_irqsave(lock, flags);
3536                 }
3537
3538                 while (reconn < KIB_RECONN_BREAK) {
3539                         if (kiblnd_data.kib_reconn_sec !=
3540                             ktime_get_real_seconds()) {
3541                                 kiblnd_data.kib_reconn_sec = ktime_get_real_seconds();
3542                                 list_splice_init(&kiblnd_data.kib_reconn_wait,
3543                                                  &kiblnd_data.kib_reconn_list);
3544                         }
3545
3546                         if (list_empty(&kiblnd_data.kib_reconn_list))
3547                                 break;
3548
3549                         conn = list_entry(kiblnd_data.kib_reconn_list.next,
3550                                           struct kib_conn, ibc_list);
3551                         list_del(&conn->ibc_list);
3552
3553                         spin_unlock_irqrestore(lock, flags);
3554                         dropped_lock = 1;
3555
3556                         reconn += kiblnd_reconnect_peer(conn->ibc_peer);
3557                         kiblnd_peer_decref(conn->ibc_peer);
3558                         LIBCFS_FREE(conn, sizeof(*conn));
3559
3560                         spin_lock_irqsave(lock, flags);
3561                 }
3562
3563                 /* careful with the jiffy wrap... */
3564                 timeout = (int)(deadline - jiffies);
3565                 if (timeout <= 0) {
3566                         const int n = 4;
3567                         const int p = 1;
3568                         int       chunk = kiblnd_data.kib_peer_hash_size;
3569                         unsigned int lnd_timeout;
3570
3571                         spin_unlock_irqrestore(lock, flags);
3572                         dropped_lock = 1;
3573
3574                         /* Time to check for RDMA timeouts on a few more
3575                          * peers: I do checks every 'p' seconds on a
3576                          * proportion of the peer_ni table and I need to check
3577                          * every connection 'n' times within a timeout
3578                          * interval, to ensure I detect a timeout on any
3579                          * connection within (n+1)/n times the timeout
3580                          * interval. */
3581
3582                         lnd_timeout = lnet_get_lnd_timeout();
3583                         if (lnd_timeout > n * p)
3584                                 chunk = (chunk * n * p) / lnd_timeout;
3585                         if (chunk == 0)
3586                                 chunk = 1;
3587
3588                         for (i = 0; i < chunk; i++) {
3589                                 kiblnd_check_conns(peer_index);
3590                                 peer_index = (peer_index + 1) %
3591                                              kiblnd_data.kib_peer_hash_size;
3592                         }
3593
3594                         deadline += msecs_to_jiffies(p * MSEC_PER_SEC);
3595                         spin_lock_irqsave(lock, flags);
3596                 }
3597
3598                 if (dropped_lock)
3599                         continue;
3600
3601                 /* Nothing to do for 'timeout'  */
3602                 set_current_state(TASK_INTERRUPTIBLE);
3603                 add_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3604                 spin_unlock_irqrestore(lock, flags);
3605
3606                 schedule_timeout(timeout);
3607
3608                 set_current_state(TASK_RUNNING);
3609                 remove_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3610                 spin_lock_irqsave(lock, flags);
3611         }
3612
3613         spin_unlock_irqrestore(lock, flags);
3614
3615         kiblnd_thread_fini();
3616         return 0;
3617 }
3618
3619 void
3620 kiblnd_qp_event(struct ib_event *event, void *arg)
3621 {
3622         struct kib_conn *conn = arg;
3623
3624         switch (event->event) {
3625         case IB_EVENT_COMM_EST:
3626                 CDEBUG(D_NET, "%s established\n",
3627                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
3628                 /* We received a packet but connection isn't established
3629                  * probably handshake packet was lost, so free to
3630                  * force make connection established */
3631                 rdma_notify(conn->ibc_cmid, IB_EVENT_COMM_EST);
3632                 return;
3633
3634         case IB_EVENT_PORT_ERR:
3635         case IB_EVENT_DEVICE_FATAL:
3636                 CERROR("Fatal device error for NI %s\n",
3637                        libcfs_nid2str(conn->ibc_peer->ibp_ni->ni_nid));
3638                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 1);
3639                 return;
3640
3641         case IB_EVENT_PORT_ACTIVE:
3642                 CERROR("Port reactivated for NI %s\n",
3643                        libcfs_nid2str(conn->ibc_peer->ibp_ni->ni_nid));
3644                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 0);
3645                 return;
3646
3647         default:
3648                 CERROR("%s: Async QP event type %d\n",
3649                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3650                 return;
3651         }
3652 }
3653
3654 static void
3655 kiblnd_complete (struct ib_wc *wc)
3656 {
3657         switch (kiblnd_wreqid2type(wc->wr_id)) {
3658         default:
3659                 LBUG();
3660
3661         case IBLND_WID_MR:
3662                 if (wc->status != IB_WC_SUCCESS &&
3663                     wc->status != IB_WC_WR_FLUSH_ERR)
3664                         CNETERR("FastReg failed: %d\n", wc->status);
3665                 return;
3666
3667         case IBLND_WID_RDMA:
3668                 /* We only get RDMA completion notification if it fails.  All
3669                  * subsequent work items, including the final SEND will fail
3670                  * too.  However we can't print out any more info about the
3671                  * failing RDMA because 'tx' might be back on the idle list or
3672                  * even reused already if we didn't manage to post all our work
3673                  * items */
3674                 CNETERR("RDMA (tx: %p) failed: %d\n",
3675                         kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3676                 return;
3677
3678         case IBLND_WID_TX:
3679                 kiblnd_tx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3680                 return;
3681
3682         case IBLND_WID_RX:
3683                 kiblnd_rx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status,
3684                                    wc->byte_len);
3685                 return;
3686         }
3687 }
3688
3689 void
3690 kiblnd_cq_completion(struct ib_cq *cq, void *arg)
3691 {
3692         /* NB I'm not allowed to schedule this conn once its refcount has
3693          * reached 0.  Since fundamentally I'm racing with scheduler threads
3694          * consuming my CQ I could be called after all completions have
3695          * occurred.  But in this case, ibc_nrx == 0 && ibc_nsends_posted == 0
3696          * and this CQ is about to be destroyed so I NOOP. */
3697         struct kib_conn *conn = arg;
3698         struct kib_sched_info *sched = conn->ibc_sched;
3699         unsigned long flags;
3700
3701         LASSERT(cq == conn->ibc_cq);
3702
3703         spin_lock_irqsave(&sched->ibs_lock, flags);
3704
3705         conn->ibc_ready = 1;
3706
3707         if (!conn->ibc_scheduled &&
3708             (conn->ibc_nrx > 0 ||
3709              conn->ibc_nsends_posted > 0)) {
3710                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3711                 conn->ibc_scheduled = 1;
3712                 list_add_tail(&conn->ibc_sched_list, &sched->ibs_conns);
3713
3714                 if (waitqueue_active(&sched->ibs_waitq))
3715                         wake_up(&sched->ibs_waitq);
3716         }
3717
3718         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3719 }
3720
3721 void
3722 kiblnd_cq_event(struct ib_event *event, void *arg)
3723 {
3724         struct kib_conn *conn = arg;
3725
3726         CERROR("%s: async CQ event type %d\n",
3727                libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3728 }
3729
3730 int
3731 kiblnd_scheduler(void *arg)
3732 {
3733         long                    id = (long)arg;
3734         struct kib_sched_info   *sched;
3735         struct kib_conn *conn;
3736         wait_queue_entry_t      wait;
3737         unsigned long           flags;
3738         struct ib_wc            wc;
3739         int                     did_something;
3740         int                     busy_loops = 0;
3741         int                     rc;
3742
3743         cfs_block_allsigs();
3744
3745         init_waitqueue_entry(&wait, current);
3746
3747         sched = kiblnd_data.kib_scheds[KIB_THREAD_CPT(id)];
3748
3749         rc = cfs_cpt_bind(lnet_cpt_table(), sched->ibs_cpt);
3750         if (rc != 0) {
3751                 CWARN("Unable to bind on CPU partition %d, please verify "
3752                       "whether all CPUs are healthy and reload modules if "
3753                       "necessary, otherwise your system might under risk of "
3754                       "low performance\n", sched->ibs_cpt);
3755         }
3756
3757         spin_lock_irqsave(&sched->ibs_lock, flags);
3758
3759         while (!kiblnd_data.kib_shutdown) {
3760                 if (busy_loops++ >= IBLND_RESCHED) {
3761                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3762
3763                         cond_resched();
3764                         busy_loops = 0;
3765
3766                         spin_lock_irqsave(&sched->ibs_lock, flags);
3767                 }
3768
3769                 did_something = 0;
3770
3771                 if (!list_empty(&sched->ibs_conns)) {
3772                         conn = list_entry(sched->ibs_conns.next,
3773                                           struct kib_conn, ibc_sched_list);
3774                         /* take over kib_sched_conns' ref on conn... */
3775                         LASSERT(conn->ibc_scheduled);
3776                         list_del(&conn->ibc_sched_list);
3777                         conn->ibc_ready = 0;
3778
3779                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3780
3781                         wc.wr_id = IBLND_WID_INVAL;
3782
3783                         rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3784                         if (rc == 0) {
3785                                 rc = ib_req_notify_cq(conn->ibc_cq,
3786                                                       IB_CQ_NEXT_COMP);
3787                                 if (rc < 0) {
3788                                         CWARN("%s: ib_req_notify_cq failed: %d, "
3789                                               "closing connection\n",
3790                                               libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
3791                                         kiblnd_close_conn(conn, -EIO);
3792                                         kiblnd_conn_decref(conn);
3793                                         spin_lock_irqsave(&sched->ibs_lock,
3794                                                               flags);
3795                                         continue;
3796                                 }
3797
3798                                 rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3799                         }
3800
3801                         if (unlikely(rc > 0 && wc.wr_id == IBLND_WID_INVAL)) {
3802                                 LCONSOLE_ERROR(
3803                                         "ib_poll_cq (rc: %d) returned invalid "
3804                                         "wr_id, opcode %d, status: %d, "
3805                                         "vendor_err: %d, conn: %s status: %d\n"
3806                                         "please upgrade firmware and OFED or "
3807                                         "contact vendor.\n", rc,
3808                                         wc.opcode, wc.status, wc.vendor_err,
3809                                         libcfs_nid2str(conn->ibc_peer->ibp_nid),
3810                                         conn->ibc_state);
3811                                 rc = -EINVAL;
3812                         }
3813
3814                         if (rc < 0) {
3815                                 CWARN("%s: ib_poll_cq failed: %d, "
3816                                       "closing connection\n",
3817                                       libcfs_nid2str(conn->ibc_peer->ibp_nid),
3818                                       rc);
3819                                 kiblnd_close_conn(conn, -EIO);
3820                                 kiblnd_conn_decref(conn);
3821                                 spin_lock_irqsave(&sched->ibs_lock, flags);
3822                                 continue;
3823                         }
3824
3825                         spin_lock_irqsave(&sched->ibs_lock, flags);
3826
3827                         if (rc != 0 || conn->ibc_ready) {
3828                                 /* There may be another completion waiting; get
3829                                  * another scheduler to check while I handle
3830                                  * this one... */
3831                                 /* +1 ref for sched_conns */
3832                                 kiblnd_conn_addref(conn);
3833                                 list_add_tail(&conn->ibc_sched_list,
3834                                                   &sched->ibs_conns);
3835                                 if (waitqueue_active(&sched->ibs_waitq))
3836                                         wake_up(&sched->ibs_waitq);
3837                         } else {
3838                                 conn->ibc_scheduled = 0;
3839                         }
3840
3841                         if (rc != 0) {
3842                                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
3843                                 kiblnd_complete(&wc);
3844
3845                                 spin_lock_irqsave(&sched->ibs_lock, flags);
3846                         }
3847
3848                         kiblnd_conn_decref(conn); /* ...drop my ref from above */
3849                         did_something = 1;
3850                 }
3851
3852                 if (did_something)
3853                         continue;
3854
3855                 set_current_state(TASK_INTERRUPTIBLE);
3856                 add_wait_queue_exclusive(&sched->ibs_waitq, &wait);
3857                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
3858
3859                 schedule();
3860                 busy_loops = 0;
3861
3862                 remove_wait_queue(&sched->ibs_waitq, &wait);
3863                 set_current_state(TASK_RUNNING);
3864                 spin_lock_irqsave(&sched->ibs_lock, flags);
3865         }
3866
3867         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3868
3869         kiblnd_thread_fini();
3870         return 0;
3871 }
3872
3873 int
3874 kiblnd_failover_thread(void *arg)
3875 {
3876         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
3877         struct kib_dev *dev;
3878         wait_queue_entry_t wait;
3879         unsigned long    flags;
3880         int              rc;
3881
3882         LASSERT(*kiblnd_tunables.kib_dev_failover != 0);
3883
3884         cfs_block_allsigs();
3885
3886         init_waitqueue_entry(&wait, current);
3887         write_lock_irqsave(glock, flags);
3888
3889         while (!kiblnd_data.kib_shutdown) {
3890                 int     do_failover = 0;
3891                 int     long_sleep;
3892
3893                 list_for_each_entry(dev, &kiblnd_data.kib_failed_devs,
3894                                     ibd_fail_list) {
3895                         if (ktime_get_seconds() < dev->ibd_next_failover)
3896                                 continue;
3897                         do_failover = 1;
3898                         break;
3899                 }
3900
3901                 if (do_failover) {
3902                         list_del_init(&dev->ibd_fail_list);
3903                         dev->ibd_failover = 1;
3904                         write_unlock_irqrestore(glock, flags);
3905
3906                         rc = kiblnd_dev_failover(dev);
3907
3908                         write_lock_irqsave(glock, flags);
3909
3910                         LASSERT (dev->ibd_failover);
3911                         dev->ibd_failover = 0;
3912                         if (rc >= 0) { /* Device is OK or failover succeed */
3913                                 dev->ibd_next_failover = ktime_get_seconds() + 3;
3914                                 continue;
3915                         }
3916
3917                         /* failed to failover, retry later */
3918                         dev->ibd_next_failover = ktime_get_seconds() +
3919                                                  min(dev->ibd_failed_failover, 10);
3920                         if (kiblnd_dev_can_failover(dev)) {
3921                                 list_add_tail(&dev->ibd_fail_list,
3922                                               &kiblnd_data.kib_failed_devs);
3923                         }
3924
3925                         continue;
3926                 }
3927
3928                 /* long sleep if no more pending failover */
3929                 long_sleep = list_empty(&kiblnd_data.kib_failed_devs);
3930
3931                 set_current_state(TASK_INTERRUPTIBLE);
3932                 add_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
3933                 write_unlock_irqrestore(glock, flags);
3934
3935                 rc = schedule_timeout(long_sleep ? cfs_time_seconds(10) :
3936                                                    cfs_time_seconds(1));
3937                 set_current_state(TASK_RUNNING);
3938                 remove_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
3939                 write_lock_irqsave(glock, flags);
3940
3941                 if (!long_sleep || rc != 0)
3942                         continue;
3943
3944                 /* have a long sleep, routine check all active devices,
3945                  * we need checking like this because if there is not active
3946                  * connection on the dev and no SEND from local, we may listen
3947                  * on wrong HCA for ever while there is a bonding failover */
3948                 list_for_each_entry(dev, &kiblnd_data.kib_devs, ibd_list) {
3949                         if (kiblnd_dev_can_failover(dev)) {
3950                                 list_add_tail(&dev->ibd_fail_list,
3951                                               &kiblnd_data.kib_failed_devs);
3952                         }
3953                 }
3954         }
3955
3956         write_unlock_irqrestore(glock, flags);
3957
3958         kiblnd_thread_fini();
3959         return 0;
3960 }