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