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