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