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