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