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