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