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