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