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