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