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