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