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