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