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