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