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