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