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