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