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