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