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