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