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