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