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