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