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