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