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