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