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