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