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