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