Whamcloud - gitweb
LU-15092 o2iblnd: Fix logic for unaligned transfer
[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         switch (type) {
1648         default:
1649                 LBUG();
1650                 return (-EIO);
1651
1652         case LNET_MSG_ACK:
1653                 LASSERT (payload_nob == 0);
1654                 break;
1655
1656         case LNET_MSG_GET:
1657                 if (routing || target_is_router)
1658                         break;                  /* send IMMEDIATE */
1659
1660                 /* is the REPLY message too small for RDMA? */
1661                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1662                 if (nob <= IBLND_MSG_SIZE && !lntmsg->msg_rdma_force)
1663                         break;                  /* send IMMEDIATE */
1664
1665                 tx = kiblnd_get_idle_tx(ni, target.nid);
1666                 if (tx == NULL) {
1667                         CERROR("Can't allocate txd for GET to %s\n",
1668                                libcfs_nid2str(target.nid));
1669                         return -ENOMEM;
1670                 }
1671
1672                 ibmsg = tx->tx_msg;
1673                 rd = &ibmsg->ibm_u.get.ibgm_rd;
1674                 rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1675                                           lntmsg->msg_md->md_niov,
1676                                           lntmsg->msg_md->md_kiov,
1677                                           0, lntmsg->msg_md->md_length);
1678                 if (rc != 0) {
1679                         CERROR("Can't setup GET sink for %s: %d\n",
1680                                libcfs_nid2str(target.nid), rc);
1681                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1682                         kiblnd_tx_done(tx);
1683                         return -EIO;
1684                 }
1685
1686                 nob = offsetof(struct kib_get_msg, ibgm_rd.rd_frags[rd->rd_nfrags]);
1687                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1688                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1689
1690                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1691
1692                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1693                 if (tx->tx_lntmsg[1] == NULL) {
1694                         CERROR("Can't create reply for GET -> %s\n",
1695                                libcfs_nid2str(target.nid));
1696                         kiblnd_tx_done(tx);
1697                         return -EIO;
1698                 }
1699
1700                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1701                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1702                 kiblnd_launch_tx(ni, tx, target.nid);
1703                 return 0;
1704
1705         case LNET_MSG_REPLY:
1706         case LNET_MSG_PUT:
1707                 /* Is the payload small enough not to need RDMA? */
1708                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob]);
1709                 if (nob <= IBLND_MSG_SIZE && !lntmsg->msg_rdma_force)
1710                         break;                  /* send IMMEDIATE */
1711
1712                 tx = kiblnd_get_idle_tx(ni, target.nid);
1713                 if (tx == NULL) {
1714                         CERROR("Can't allocate %s txd for %s\n",
1715                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1716                                libcfs_nid2str(target.nid));
1717                         return -ENOMEM;
1718                 }
1719
1720                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1721                                           payload_niov, payload_kiov,
1722                                           payload_offset, payload_nob);
1723                 if (rc != 0) {
1724                         CERROR("Can't setup PUT src for %s: %d\n",
1725                                libcfs_nid2str(target.nid), rc);
1726                         kiblnd_tx_done(tx);
1727                         return -EIO;
1728                 }
1729
1730                 ibmsg = tx->tx_msg;
1731                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1732                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1733                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ,
1734                                    sizeof(struct kib_putreq_msg));
1735
1736                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1737                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1738                 kiblnd_launch_tx(ni, tx, target.nid);
1739                 return 0;
1740         }
1741
1742         /* send IMMEDIATE */
1743         LASSERT(offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob])
1744                 <= IBLND_MSG_SIZE);
1745
1746         tx = kiblnd_get_idle_tx(ni, target.nid);
1747         if (tx == NULL) {
1748                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1749                         type, libcfs_nid2str(target.nid));
1750                 return -ENOMEM;
1751         }
1752
1753         ibmsg = tx->tx_msg;
1754         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1755
1756         lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1757                             offsetof(struct kib_msg,
1758                                      ibm_u.immediate.ibim_payload),
1759                             payload_niov, payload_kiov,
1760                             payload_offset, payload_nob);
1761
1762         nob = offsetof(struct kib_immediate_msg, ibim_payload[payload_nob]);
1763         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1764
1765         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1766         kiblnd_launch_tx(ni, tx, target.nid);
1767         return 0;
1768 }
1769
1770 static void
1771 kiblnd_reply(struct lnet_ni *ni, struct kib_rx *rx, struct lnet_msg *lntmsg)
1772 {
1773         struct lnet_process_id target = lntmsg->msg_target;
1774         unsigned int niov = lntmsg->msg_niov;
1775         struct bio_vec *kiov = lntmsg->msg_kiov;
1776         unsigned int offset = lntmsg->msg_offset;
1777         unsigned int nob = lntmsg->msg_len;
1778         struct kib_tx *tx;
1779         int rc;
1780
1781         tx = kiblnd_get_idle_tx(ni, rx->rx_conn->ibc_peer->ibp_nid);
1782         if (tx == NULL) {
1783                 CERROR("Can't get tx for REPLY to %s\n",
1784                        libcfs_nid2str(target.nid));
1785                 goto failed_0;
1786         }
1787
1788         if (nob == 0)
1789                 rc = 0;
1790         else
1791                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1792                                           niov, kiov, offset, nob);
1793
1794         if (rc != 0) {
1795                 CERROR("Can't setup GET src for %s: %d\n",
1796                        libcfs_nid2str(target.nid), rc);
1797                 goto failed_1;
1798         }
1799
1800         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1801                               IBLND_MSG_GET_DONE, nob,
1802                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1803                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1804         if (rc < 0) {
1805                 CERROR("Can't setup rdma for GET from %s: %d\n",
1806                        libcfs_nid2str(target.nid), rc);
1807                 goto failed_1;
1808         }
1809
1810         if (nob == 0) {
1811                 /* No RDMA: local completion may happen now! */
1812                 lnet_finalize(lntmsg, 0);
1813         } else {
1814                 /* RDMA: lnet_finalize(lntmsg) when it
1815                  * completes */
1816                 tx->tx_lntmsg[0] = lntmsg;
1817         }
1818
1819         kiblnd_queue_tx(tx, rx->rx_conn);
1820         return;
1821
1822
1823 failed_1:
1824         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1825         kiblnd_tx_done(tx);
1826 failed_0:
1827         lnet_finalize(lntmsg, -EIO);
1828 }
1829
1830 unsigned int
1831 kiblnd_get_dev_prio(struct lnet_ni *ni, unsigned int dev_idx)
1832 {
1833         struct kib_net *net = ni->ni_data;
1834         struct device *dev = NULL;
1835
1836         if (net)
1837                 dev = net->ibn_dev->ibd_hdev->ibh_ibdev->dma_device;
1838
1839         return lnet_get_dev_prio(dev, dev_idx);
1840
1841 }
1842
1843 int
1844 kiblnd_recv(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg,
1845             int delayed, unsigned int niov, struct bio_vec *kiov,
1846             unsigned int offset, unsigned int mlen, unsigned int rlen)
1847 {
1848         struct kib_rx *rx = private;
1849         struct kib_msg *rxmsg = rx->rx_msg;
1850         struct kib_conn *conn = rx->rx_conn;
1851         struct kib_tx *tx;
1852         __u64        ibprm_cookie;
1853         int          nob;
1854         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1855         int          rc = 0;
1856
1857         LASSERT (mlen <= rlen);
1858         LASSERT (!in_interrupt());
1859
1860         switch (rxmsg->ibm_type) {
1861         default:
1862                 LBUG();
1863
1864         case IBLND_MSG_IMMEDIATE:
1865                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[rlen]);
1866                 if (nob > rx->rx_nob) {
1867                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1868                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1869                                 nob, rx->rx_nob);
1870                         rc = -EPROTO;
1871                         break;
1872                 }
1873
1874                 lnet_copy_flat2kiov(niov, kiov, offset,
1875                                     IBLND_MSG_SIZE, rxmsg,
1876                                     offsetof(struct kib_msg,
1877                                              ibm_u.immediate.ibim_payload),
1878                                     mlen);
1879                 lnet_finalize(lntmsg, 0);
1880                 break;
1881
1882         case IBLND_MSG_PUT_REQ: {
1883                 struct kib_msg  *txmsg;
1884                 struct kib_rdma_desc *rd;
1885                 ibprm_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1886
1887                 if (mlen == 0) {
1888                         lnet_finalize(lntmsg, 0);
1889                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1890                                                0, ibprm_cookie);
1891                         break;
1892                 }
1893
1894                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1895                 if (tx == NULL) {
1896                         CERROR("Can't allocate tx for %s\n",
1897                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1898                         /* Not replying will break the connection */
1899                         rc = -ENOMEM;
1900                         break;
1901                 }
1902
1903                 txmsg = tx->tx_msg;
1904                 rd = &txmsg->ibm_u.putack.ibpam_rd;
1905                 rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1906                                           niov, kiov, offset, mlen);
1907                 if (rc != 0) {
1908                         CERROR("Can't setup PUT sink for %s: %d\n",
1909                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1910                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1911                         kiblnd_tx_done(tx);
1912                         /* tell peer_ni it's over */
1913                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1914                                                rc, ibprm_cookie);
1915                         break;
1916                 }
1917
1918                 nob = offsetof(struct kib_putack_msg, ibpam_rd.rd_frags[rd->rd_nfrags]);
1919                 txmsg->ibm_u.putack.ibpam_src_cookie = ibprm_cookie;
1920                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1921
1922                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1923
1924                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1925                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1926                 kiblnd_queue_tx(tx, conn);
1927
1928                 /* reposted buffer reserved for PUT_DONE */
1929                 post_credit = IBLND_POSTRX_NO_CREDIT;
1930                 break;
1931                 }
1932
1933         case IBLND_MSG_GET_REQ:
1934                 if (lntmsg != NULL) {
1935                         /* Optimized GET; RDMA lntmsg's payload */
1936                         kiblnd_reply(ni, rx, lntmsg);
1937                 } else {
1938                         /* GET didn't match anything */
1939                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1940                                                -ENODATA,
1941                                                rxmsg->ibm_u.get.ibgm_cookie);
1942                 }
1943                 break;
1944         }
1945
1946         kiblnd_post_rx(rx, post_credit);
1947         return rc;
1948 }
1949
1950 static void
1951 kiblnd_thread_fini (void)
1952 {
1953         atomic_dec (&kiblnd_data.kib_nthreads);
1954 }
1955
1956 static void
1957 kiblnd_peer_alive(struct kib_peer_ni *peer_ni)
1958 {
1959         /* This is racy, but everyone's only writing ktime_get_seconds() */
1960         peer_ni->ibp_last_alive = ktime_get_seconds();
1961         smp_mb();
1962 }
1963
1964 static void
1965 kiblnd_peer_notify(struct kib_peer_ni *peer_ni)
1966 {
1967         int           error = 0;
1968         time64_t last_alive = 0;
1969         unsigned long flags;
1970
1971         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1972
1973         if (kiblnd_peer_idle(peer_ni) && peer_ni->ibp_error != 0) {
1974                 error = peer_ni->ibp_error;
1975                 peer_ni->ibp_error = 0;
1976
1977                 last_alive = peer_ni->ibp_last_alive;
1978         }
1979
1980         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1981
1982         if (error != 0)
1983                 lnet_notify(peer_ni->ibp_ni,
1984                             peer_ni->ibp_nid, false, false, last_alive);
1985 }
1986
1987 void
1988 kiblnd_close_conn_locked(struct kib_conn *conn, int error)
1989 {
1990         /* This just does the immediate housekeeping.  'error' is zero for a
1991          * normal shutdown which can happen only after the connection has been
1992          * established.  If the connection is established, schedule the
1993          * connection to be finished off by the connd.  Otherwise the connd is
1994          * already dealing with it (either to set it up or tear it down).
1995          * Caller holds kib_global_lock exclusively in irq context */
1996         struct kib_peer_ni *peer_ni = conn->ibc_peer;
1997         struct kib_dev *dev;
1998         unsigned long flags;
1999
2000         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2001
2002         if (error != 0 && conn->ibc_comms_error == 0)
2003                 conn->ibc_comms_error = error;
2004
2005         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
2006                 return; /* already being handled  */
2007
2008         if (error == 0 &&
2009             list_empty(&conn->ibc_tx_noops) &&
2010             list_empty(&conn->ibc_tx_queue) &&
2011             list_empty(&conn->ibc_tx_queue_rsrvd) &&
2012             list_empty(&conn->ibc_tx_queue_nocred) &&
2013             list_empty(&conn->ibc_active_txs)) {
2014                 CDEBUG(D_NET, "closing conn to %s\n", 
2015                        libcfs_nid2str(peer_ni->ibp_nid));
2016         } else {
2017                 CNETERR("Closing conn to %s: error %d%s%s%s%s%s\n",
2018                        libcfs_nid2str(peer_ni->ibp_nid), error,
2019                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
2020                        list_empty(&conn->ibc_tx_noops) ? "" : "(sending_noops)",
2021                        list_empty(&conn->ibc_tx_queue_rsrvd) ?
2022                                                 "" : "(sending_rsrvd)",
2023                        list_empty(&conn->ibc_tx_queue_nocred) ?
2024                                                  "" : "(sending_nocred)",
2025                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
2026         }
2027
2028         dev = ((struct kib_net *)peer_ni->ibp_ni->ni_data)->ibn_dev;
2029         if (peer_ni->ibp_next_conn == conn)
2030                 /* clear next_conn so it won't be used */
2031                 peer_ni->ibp_next_conn = NULL;
2032         list_del(&conn->ibc_list);
2033         /* connd (see below) takes over ibc_list's ref */
2034
2035         if (list_empty(&peer_ni->ibp_conns) &&    /* no more conns */
2036             kiblnd_peer_active(peer_ni)) {         /* still in peer_ni table */
2037                 kiblnd_unlink_peer_locked(peer_ni);
2038
2039                 /* set/clear error on last conn */
2040                 peer_ni->ibp_error = conn->ibc_comms_error;
2041         }
2042
2043         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
2044
2045         if (error != 0 &&
2046             kiblnd_dev_can_failover(dev)) {
2047                 list_add_tail(&dev->ibd_fail_list,
2048                               &kiblnd_data.kib_failed_devs);
2049                 wake_up(&kiblnd_data.kib_failover_waitq);
2050         }
2051
2052         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2053
2054         list_add_tail(&conn->ibc_list, &kiblnd_data.kib_connd_conns);
2055         wake_up(&kiblnd_data.kib_connd_waitq);
2056
2057         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
2058 }
2059
2060 void
2061 kiblnd_close_conn(struct kib_conn *conn, int error)
2062 {
2063         unsigned long flags;
2064
2065         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2066
2067         kiblnd_close_conn_locked(conn, error);
2068
2069         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2070 }
2071
2072 static void
2073 kiblnd_handle_early_rxs(struct kib_conn *conn)
2074 {
2075         unsigned long flags;
2076         struct kib_rx *rx;
2077
2078         LASSERT(!in_interrupt());
2079         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2080
2081         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2082         while ((rx = list_first_entry_or_null(&conn->ibc_early_rxs,
2083                                               struct kib_rx,
2084                                               rx_list)) != NULL) {
2085                 list_del(&rx->rx_list);
2086                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2087
2088                 kiblnd_handle_rx(rx);
2089
2090                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2091         }
2092         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2093 }
2094
2095 void
2096 kiblnd_abort_txs(struct kib_conn *conn, struct list_head *txs)
2097 {
2098         LIST_HEAD(zombies);
2099         struct kib_tx *nxt;
2100         struct kib_tx *tx;
2101
2102         spin_lock(&conn->ibc_lock);
2103
2104         list_for_each_entry_safe(tx, nxt, txs, tx_list) {
2105                 if (txs == &conn->ibc_active_txs) {
2106                         LASSERT(!tx->tx_queued);
2107                         LASSERT(tx->tx_waiting ||
2108                                 tx->tx_sending != 0);
2109                         if (conn->ibc_comms_error == -ETIMEDOUT) {
2110                                 if (tx->tx_waiting && !tx->tx_sending)
2111                                         tx->tx_hstatus =
2112                                           LNET_MSG_STATUS_REMOTE_TIMEOUT;
2113                                 else if (tx->tx_sending)
2114                                         tx->tx_hstatus =
2115                                           LNET_MSG_STATUS_NETWORK_TIMEOUT;
2116                         }
2117                 } else {
2118                         LASSERT(tx->tx_queued);
2119                         if (conn->ibc_comms_error == -ETIMEDOUT)
2120                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2121                         else
2122                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
2123                 }
2124
2125                 tx->tx_status = -ECONNABORTED;
2126                 tx->tx_waiting = 0;
2127
2128                 /*
2129                  * TODO: This makes an assumption that
2130                  * kiblnd_tx_complete() will be called for each tx. If
2131                  * that event is dropped we could end up with stale
2132                  * connections floating around. We'd like to deal with
2133                  * that in a better way.
2134                  *
2135                  * Also that means we can exceed the timeout by many
2136                  * seconds.
2137                  */
2138                 if (tx->tx_sending == 0) {
2139                         tx->tx_queued = 0;
2140                         list_move(&tx->tx_list, &zombies);
2141                 } else {
2142                         /* keep tx until cq destroy */
2143                         list_move(&tx->tx_list, &conn->ibc_zombie_txs);
2144                         conn->ibc_waits ++;
2145                 }
2146         }
2147
2148         spin_unlock(&conn->ibc_lock);
2149
2150         /*
2151          * aborting transmits occurs when finalizing the connection.
2152          * The connection is finalized on error.
2153          * Passing LNET_MSG_STATUS_OK to txlist_done() will not
2154          * override the value already set in tx->tx_hstatus above.
2155          */
2156         kiblnd_txlist_done(&zombies, -ECONNABORTED, LNET_MSG_STATUS_OK);
2157 }
2158
2159 static bool
2160 kiblnd_tx_may_discard(struct kib_conn *conn)
2161 {
2162         bool rc = false;
2163         struct kib_tx *nxt;
2164         struct kib_tx *tx;
2165
2166         spin_lock(&conn->ibc_lock);
2167
2168         list_for_each_entry_safe(tx, nxt, &conn->ibc_zombie_txs, tx_list) {
2169                 if (tx->tx_sending > 0 && tx->tx_lntmsg[0] &&
2170                     lnet_md_discarded(tx->tx_lntmsg[0]->msg_md)) {
2171                         tx->tx_sending --;
2172                         if (tx->tx_sending == 0) {
2173                                 kiblnd_conn_decref(tx->tx_conn);
2174                                 tx->tx_conn = NULL;
2175                                 rc = true;
2176                         }
2177                 }
2178         }
2179
2180         spin_unlock(&conn->ibc_lock);
2181         return rc;
2182 }
2183
2184 static void
2185 kiblnd_finalise_conn(struct kib_conn *conn)
2186 {
2187         LASSERT (!in_interrupt());
2188         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
2189
2190         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
2191          * for connections that didn't get as far as being connected, because
2192          * rdma_disconnect() does this for free. */
2193         kiblnd_abort_receives(conn);
2194
2195         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
2196
2197         /* Complete all tx descs not waiting for sends to complete.
2198          * NB we should be safe from RDMA now that the QP has changed state */
2199
2200         kiblnd_abort_txs(conn, &conn->ibc_tx_noops);
2201         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
2202         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
2203         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
2204         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
2205
2206         kiblnd_handle_early_rxs(conn);
2207 }
2208
2209 static void
2210 kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
2211                            int error)
2212 {
2213         LIST_HEAD(zombies);
2214         unsigned long flags;
2215         enum lnet_msg_hstatus hstatus;
2216
2217         LASSERT(error != 0);
2218         LASSERT(!in_interrupt());
2219
2220         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2221
2222         if (active) {
2223                 LASSERT(peer_ni->ibp_connecting > 0);
2224                 peer_ni->ibp_connecting--;
2225         } else {
2226                 LASSERT (peer_ni->ibp_accepting > 0);
2227                 peer_ni->ibp_accepting--;
2228         }
2229
2230         if (kiblnd_peer_connecting(peer_ni)) {
2231                 /* another connection attempt under way... */
2232                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2233                                         flags);
2234                 return;
2235         }
2236
2237         peer_ni->ibp_reconnected = 0;
2238         if (list_empty(&peer_ni->ibp_conns)) {
2239                 /* Take peer_ni's blocked transmits to complete with error */
2240                 list_splice_init(&peer_ni->ibp_tx_queue, &zombies);
2241
2242                 if (kiblnd_peer_active(peer_ni))
2243                         kiblnd_unlink_peer_locked(peer_ni);
2244
2245                 peer_ni->ibp_error = error;
2246         } else {
2247                 /* Can't have blocked transmits if there are connections */
2248                 LASSERT(list_empty(&peer_ni->ibp_tx_queue));
2249         }
2250
2251         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2252
2253         kiblnd_peer_notify(peer_ni);
2254
2255         if (list_empty(&zombies))
2256                 return;
2257
2258         CNETERR("Deleting messages for %s: connection failed\n",
2259                 libcfs_nid2str(peer_ni->ibp_nid));
2260
2261         switch (error) {
2262         case -EHOSTUNREACH:
2263         case -ETIMEDOUT:
2264                 hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
2265                 break;
2266         case -ECONNREFUSED:
2267                 hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
2268                 break;
2269         default:
2270                 hstatus = LNET_MSG_STATUS_LOCAL_DROPPED;
2271                 break;
2272         }
2273
2274         kiblnd_txlist_done(&zombies, error, hstatus);
2275 }
2276
2277 static void
2278 kiblnd_connreq_done(struct kib_conn *conn, int status)
2279 {
2280         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2281         struct kib_tx *tx;
2282         LIST_HEAD(txs);
2283         unsigned long    flags;
2284         int              active;
2285
2286         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2287
2288         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
2289                libcfs_nid2str(peer_ni->ibp_nid), active,
2290                conn->ibc_version, status);
2291
2292         LASSERT (!in_interrupt());
2293         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2294                   peer_ni->ibp_connecting > 0) ||
2295                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2296                   peer_ni->ibp_accepting > 0));
2297
2298         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2299         conn->ibc_connvars = NULL;
2300
2301         if (status != 0) {
2302                 /* failed to establish connection */
2303                 kiblnd_peer_connect_failed(peer_ni, active, status);
2304                 kiblnd_finalise_conn(conn);
2305                 return;
2306         }
2307
2308         /* connection established */
2309         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2310
2311         conn->ibc_last_send = ktime_get();
2312         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2313         kiblnd_peer_alive(peer_ni);
2314
2315         /* Add conn to peer_ni's list and nuke any dangling conns from a different
2316          * peer_ni instance... */
2317         kiblnd_conn_addref(conn);       /* +1 ref for ibc_list */
2318         list_add(&conn->ibc_list, &peer_ni->ibp_conns);
2319         peer_ni->ibp_reconnected = 0;
2320         if (active)
2321                 peer_ni->ibp_connecting--;
2322         else
2323                 peer_ni->ibp_accepting--;
2324
2325         if (peer_ni->ibp_version == 0) {
2326                 peer_ni->ibp_version     = conn->ibc_version;
2327                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2328         }
2329
2330         if (peer_ni->ibp_version     != conn->ibc_version ||
2331             peer_ni->ibp_incarnation != conn->ibc_incarnation) {
2332                 kiblnd_close_stale_conns_locked(peer_ni, conn->ibc_version,
2333                                                 conn->ibc_incarnation);
2334                 peer_ni->ibp_version     = conn->ibc_version;
2335                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2336         }
2337
2338         /* grab pending txs while I have the lock */
2339         list_splice_init(&peer_ni->ibp_tx_queue, &txs);
2340
2341         if (!kiblnd_peer_active(peer_ni) ||        /* peer_ni has been deleted */
2342             conn->ibc_comms_error != 0) {       /* error has happened already */
2343
2344                 /* start to shut down connection */
2345                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2346                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2347
2348                 kiblnd_txlist_done(&txs, -ECONNABORTED,
2349                                    LNET_MSG_STATUS_LOCAL_ERROR);
2350
2351                 return;
2352         }
2353
2354         /* +1 ref for myself, this connection is visible to other threads
2355          * now, refcount of peer:ibp_conns can be released by connection
2356          * close from either a different thread, or the calling of
2357          * kiblnd_check_sends_locked() below. See bz21911 for details.
2358          */
2359         kiblnd_conn_addref(conn);
2360         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2361
2362         /* Schedule blocked txs
2363          * Note: if we are running with conns_per_peer > 1, these blocked
2364          * txs will all get scheduled to the first connection which gets
2365          * scheduled.  We won't be using round robin on this first batch.
2366          */
2367         spin_lock(&conn->ibc_lock);
2368         while ((tx = list_first_entry_or_null(&txs, struct kib_tx,
2369                                               tx_list)) != NULL) {
2370                 list_del(&tx->tx_list);
2371
2372                 kiblnd_queue_tx_locked(tx, conn);
2373         }
2374         kiblnd_check_sends_locked(conn);
2375         spin_unlock(&conn->ibc_lock);
2376
2377         /* schedule blocked rxs */
2378         kiblnd_handle_early_rxs(conn);
2379         kiblnd_conn_decref(conn);
2380 }
2381
2382 static void
2383 kiblnd_reject(struct rdma_cm_id *cmid, struct kib_rej *rej)
2384 {
2385         int          rc;
2386
2387 #ifdef HAVE_RDMA_REJECT_4ARGS
2388         rc = rdma_reject(cmid, rej, sizeof(*rej), IB_CM_REJ_CONSUMER_DEFINED);
2389 #else
2390         rc = rdma_reject(cmid, rej, sizeof(*rej));
2391 #endif
2392
2393         if (rc != 0)
2394                 CWARN("Error %d sending reject\n", rc);
2395 }
2396
2397 static int
2398 kiblnd_passive_connect(struct rdma_cm_id *cmid, void *priv, int priv_nob)
2399 {
2400         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
2401         struct kib_msg *reqmsg = priv;
2402         struct kib_msg *ackmsg;
2403         struct kib_dev *ibdev;
2404         struct kib_peer_ni *peer_ni;
2405         struct kib_peer_ni *peer2;
2406         struct kib_conn *conn;
2407         struct lnet_ni *ni = NULL;
2408         struct kib_net *net = NULL;
2409         lnet_nid_t nid;
2410         struct rdma_conn_param cp;
2411         struct kib_rej rej;
2412         int version = IBLND_MSG_VERSION;
2413         unsigned long flags;
2414         int rc;
2415         struct sockaddr_in *peer_addr;
2416
2417         LASSERT(!in_interrupt());
2418         /* cmid inherits 'context' from the corresponding listener id */
2419         ibdev = cmid->context;
2420         LASSERT(ibdev);
2421
2422         memset(&rej, 0, sizeof(rej));
2423         rej.ibr_magic                = IBLND_MSG_MAGIC;
2424         rej.ibr_why                  = IBLND_REJECT_FATAL;
2425         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2426
2427         peer_addr = (struct sockaddr_in *)&(cmid->route.addr.dst_addr);
2428         if (*kiblnd_tunables.kib_require_priv_port &&
2429             ntohs(peer_addr->sin_port) >= PROT_SOCK) {
2430                 __u32 ip = ntohl(peer_addr->sin_addr.s_addr);
2431                 CERROR("peer_ni's port (%pI4h:%hu) is not privileged\n",
2432                        &ip, ntohs(peer_addr->sin_port));
2433                 goto failed;
2434         }
2435
2436         if (priv_nob < offsetof(struct kib_msg, ibm_type)) {
2437                 CERROR("Short connection request\n");
2438                 goto failed;
2439         }
2440
2441         /* Future protocol version compatibility support!  If the
2442          * o2iblnd-specific protocol changes, or when LNET unifies
2443          * protocols over all LNDs, the initial connection will
2444          * negotiate a protocol version.  I trap this here to avoid
2445          * console errors; the reject tells the peer_ni which protocol I
2446          * speak. */
2447         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2448             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2449                 goto failed;
2450         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2451             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2452             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2453                 goto failed;
2454         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2455             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2456             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2457                 goto failed;
2458
2459         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2460         if (rc != 0) {
2461                 CERROR("Can't parse connection request: %d\n", rc);
2462                 goto failed;
2463         }
2464
2465         nid = reqmsg->ibm_srcnid;
2466         ni  = lnet_nid2ni_addref(reqmsg->ibm_dstnid);
2467
2468         if (ni != NULL) {
2469                 net = (struct kib_net *)ni->ni_data;
2470                 rej.ibr_incarnation = net->ibn_incarnation;
2471         }
2472
2473         if (ni == NULL ||                       /* no matching net */
2474             lnet_nid_to_nid4(&ni->ni_nid) !=
2475             reqmsg->ibm_dstnid ||               /* right NET, wrong NID! */
2476             net->ibn_dev != ibdev) {            /* wrong device */
2477                 CERROR("Can't accept conn from %s on %s (%s:%d:%pI4h): bad dst nid %s\n", libcfs_nid2str(nid),
2478                        ni ? libcfs_nidstr(&ni->ni_nid) : "NA",
2479                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2480                        &ibdev->ibd_ifip,
2481                        libcfs_nid2str(reqmsg->ibm_dstnid));
2482
2483                 goto failed;
2484         }
2485
2486         /* check time stamp as soon as possible */
2487         if (reqmsg->ibm_dststamp != 0 &&
2488             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2489                 CWARN("Stale connection request\n");
2490                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2491                 goto failed;
2492         }
2493
2494         /* I can accept peer_ni's version */
2495         version = reqmsg->ibm_version;
2496
2497         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2498                 CERROR("Unexpected connreq msg type: %x from %s\n",
2499                        reqmsg->ibm_type, libcfs_nid2str(nid));
2500                 goto failed;
2501         }
2502
2503         if (reqmsg->ibm_u.connparams.ibcp_queue_depth >
2504             kiblnd_msg_queue_size(version, ni)) {
2505                 CERROR("Can't accept conn from %s, queue depth too large:  %d (<=%d wanted)\n",
2506                        libcfs_nid2str(nid),
2507                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2508                        kiblnd_msg_queue_size(version, ni));
2509
2510                 if (version == IBLND_MSG_VERSION)
2511                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2512
2513                 goto failed;
2514         }
2515
2516         if (reqmsg->ibm_u.connparams.ibcp_max_frags >
2517             IBLND_MAX_RDMA_FRAGS) {
2518                 CWARN("Can't accept conn from %s (version %x): max_frags %d too large (%d wanted)\n",
2519                       libcfs_nid2str(nid), version,
2520                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2521                       IBLND_MAX_RDMA_FRAGS);
2522
2523                 if (version >= IBLND_MSG_VERSION)
2524                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2525
2526                 goto failed;
2527         } else if (reqmsg->ibm_u.connparams.ibcp_max_frags <
2528                    IBLND_MAX_RDMA_FRAGS &&
2529                    net->ibn_fmr_ps == NULL) {
2530                 CWARN("Can't accept conn from %s (version %x): max_frags %d incompatible without FMR pool (%d wanted)\n",
2531                       libcfs_nid2str(nid), version,
2532                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2533                       IBLND_MAX_RDMA_FRAGS);
2534
2535                 if (version == IBLND_MSG_VERSION)
2536                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2537
2538                 goto failed;
2539         }
2540
2541         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2542                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2543                        libcfs_nid2str(nid),
2544                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2545                        IBLND_MSG_SIZE);
2546                 goto failed;
2547         }
2548
2549         /* assume 'nid' is a new peer_ni; create  */
2550         rc = kiblnd_create_peer(ni, &peer_ni, nid);
2551         if (rc != 0) {
2552                 CERROR("Can't create peer_ni for %s\n", libcfs_nid2str(nid));
2553                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2554                 goto failed;
2555         }
2556
2557         /* We have validated the peer's parameters so use those */
2558         peer_ni->ibp_max_frags = reqmsg->ibm_u.connparams.ibcp_max_frags;
2559         peer_ni->ibp_queue_depth = reqmsg->ibm_u.connparams.ibcp_queue_depth;
2560
2561         write_lock_irqsave(g_lock, flags);
2562
2563         peer2 = kiblnd_find_peer_locked(ni, nid);
2564         if (peer2 != NULL) {
2565                 if (peer2->ibp_version == 0) {
2566                         peer2->ibp_version     = version;
2567                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2568                 }
2569
2570                 /* not the guy I've talked with */
2571                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2572                     peer2->ibp_version     != version) {
2573                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2574
2575                         if (kiblnd_peer_active(peer2)) {
2576                                 peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2577                                 peer2->ibp_version = version;
2578                         }
2579                         write_unlock_irqrestore(g_lock, flags);
2580
2581                         CWARN("Conn stale %s version %x/%x incarnation %llu/%llu\n",
2582                               libcfs_nid2str(nid), peer2->ibp_version, version,
2583                               peer2->ibp_incarnation, reqmsg->ibm_srcstamp);
2584
2585                         kiblnd_peer_decref(peer_ni);
2586                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2587                         goto failed;
2588                 }
2589
2590                 /* Tie-break connection race in favour of the higher NID.
2591                  * If we keep running into a race condition multiple times,
2592                  * we have to assume that the connection attempt with the
2593                  * higher NID is stuck in a connecting state and will never
2594                  * recover.  As such, we pass through this if-block and let
2595                  * the lower NID connection win so we can move forward.
2596                  */
2597                 if (peer2->ibp_connecting != 0 &&
2598                     nid < lnet_nid_to_nid4(&ni->ni_nid) &&
2599                     peer2->ibp_races < MAX_CONN_RACES_BEFORE_ABORT) {
2600                         peer2->ibp_races++;
2601                         write_unlock_irqrestore(g_lock, flags);
2602
2603                         CDEBUG(D_NET, "Conn race %s\n",
2604                                libcfs_nid2str(peer2->ibp_nid));
2605
2606                         kiblnd_peer_decref(peer_ni);
2607                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2608                         goto failed;
2609                 }
2610                 if (peer2->ibp_races >= MAX_CONN_RACES_BEFORE_ABORT)
2611                         CNETERR("Conn race %s: unresolved after %d attempts, letting lower NID win\n",
2612                                 libcfs_nid2str(peer2->ibp_nid),
2613                                 MAX_CONN_RACES_BEFORE_ABORT);
2614                 /*
2615                  * passive connection is allowed even this peer_ni is waiting for
2616                  * reconnection.
2617                  */
2618                 peer2->ibp_reconnecting = 0;
2619                 peer2->ibp_races = 0;
2620                 peer2->ibp_accepting++;
2621                 kiblnd_peer_addref(peer2);
2622
2623                 /* Race with kiblnd_launch_tx (active connect) to create peer_ni
2624                  * so copy validated parameters since we now know what the
2625                  * peer_ni's limits are */
2626                 peer2->ibp_max_frags = peer_ni->ibp_max_frags;
2627                 peer2->ibp_queue_depth = peer_ni->ibp_queue_depth;
2628
2629                 write_unlock_irqrestore(g_lock, flags);
2630                 kiblnd_peer_decref(peer_ni);
2631                 peer_ni = peer2;
2632         } else {
2633                 /* Brand new peer_ni */
2634                 LASSERT(peer_ni->ibp_accepting == 0);
2635                 LASSERT(peer_ni->ibp_version == 0 &&
2636                         peer_ni->ibp_incarnation == 0);
2637
2638                 peer_ni->ibp_accepting   = 1;
2639                 peer_ni->ibp_version     = version;
2640                 peer_ni->ibp_incarnation = reqmsg->ibm_srcstamp;
2641
2642                 /* I have a ref on ni that prevents it being shutdown */
2643                 LASSERT(net->ibn_shutdown == 0);
2644
2645                 kiblnd_peer_addref(peer_ni);
2646                 hash_add(kiblnd_data.kib_peers, &peer_ni->ibp_list, nid);
2647
2648                 write_unlock_irqrestore(g_lock, flags);
2649         }
2650
2651         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_PASSIVE_WAIT,
2652                                   version);
2653         if (!conn) {
2654                 kiblnd_peer_connect_failed(peer_ni, 0, -ENOMEM);
2655                 kiblnd_peer_decref(peer_ni);
2656                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2657                 goto failed;
2658         }
2659
2660         /* conn now "owns" cmid, so I return success from here on to ensure the
2661          * CM callback doesn't destroy cmid.
2662          */
2663         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2664         conn->ibc_credits          = conn->ibc_queue_depth;
2665         conn->ibc_reserved_credits = conn->ibc_queue_depth;
2666         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2667                 IBLND_OOB_MSGS(version) <= IBLND_RX_MSGS(conn));
2668
2669         ackmsg = &conn->ibc_connvars->cv_msg;
2670         memset(ackmsg, 0, sizeof(*ackmsg));
2671
2672         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2673                         sizeof(ackmsg->ibm_u.connparams));
2674         ackmsg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2675         ackmsg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2676         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2677
2678         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2679
2680         memset(&cp, 0, sizeof(cp));
2681         cp.private_data        = ackmsg;
2682         cp.private_data_len    = ackmsg->ibm_nob;
2683         cp.responder_resources = 0;            /* No atomic ops or RDMA reads */
2684         cp.initiator_depth     = 0;
2685         cp.flow_control        = 1;
2686         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2687         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2688
2689         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2690
2691         rc = rdma_accept(cmid, &cp);
2692         if (rc != 0) {
2693                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2694                 rej.ibr_version = version;
2695                 rej.ibr_why     = IBLND_REJECT_FATAL;
2696
2697                 kiblnd_reject(cmid, &rej);
2698                 kiblnd_connreq_done(conn, rc);
2699                 kiblnd_conn_decref(conn);
2700         }
2701
2702         lnet_ni_decref(ni);
2703         return 0;
2704
2705  failed:
2706         if (ni != NULL) {
2707                 rej.ibr_cp.ibcp_queue_depth =
2708                         kiblnd_msg_queue_size(version, ni);
2709                 rej.ibr_cp.ibcp_max_frags   = IBLND_MAX_RDMA_FRAGS;
2710                 lnet_ni_decref(ni);
2711         }
2712
2713         rej.ibr_version = version;
2714         kiblnd_reject(cmid, &rej);
2715
2716         return -ECONNREFUSED;
2717 }
2718
2719 static void
2720 kiblnd_check_reconnect(struct kib_conn *conn, int version,
2721                        u64 incarnation, int why, struct kib_connparams *cp)
2722 {
2723         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
2724         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2725         char            *reason;
2726         int              msg_size = IBLND_MSG_SIZE;
2727         int              frag_num = -1;
2728         int              queue_dep = -1;
2729         bool             reconnect;
2730         unsigned long    flags;
2731
2732         LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2733         LASSERT(peer_ni->ibp_connecting > 0);   /* 'conn' at least */
2734
2735         if (cp) {
2736                 msg_size        = cp->ibcp_max_msg_size;
2737                 frag_num        = cp->ibcp_max_frags;
2738                 queue_dep       = cp->ibcp_queue_depth;
2739         }
2740
2741         write_lock_irqsave(glock, flags);
2742         /* retry connection if it's still needed and no other connection
2743          * attempts (active or passive) are in progress
2744          * NB: reconnect is still needed even when ibp_tx_queue is
2745          * empty if ibp_version != version because reconnect may be
2746          * initiated.
2747          */
2748         reconnect = (!list_empty(&peer_ni->ibp_tx_queue) ||
2749                      peer_ni->ibp_version != version) &&
2750                     peer_ni->ibp_connecting &&
2751                     peer_ni->ibp_accepting == 0;
2752         if (!reconnect) {
2753                 reason = "no need";
2754                 goto out;
2755         }
2756
2757         switch (why) {
2758         default:
2759                 reason = "Unknown";
2760                 break;
2761
2762         case IBLND_REJECT_RDMA_FRAGS: {
2763                 if (!cp) {
2764                         reason = "can't negotiate max frags";
2765                         goto out;
2766                 }
2767
2768                 if (conn->ibc_max_frags <= frag_num) {
2769                         reason = "unsupported max frags";
2770                         goto out;
2771                 }
2772
2773                 peer_ni->ibp_max_frags = frag_num;
2774                 reason = "rdma fragments";
2775                 break;
2776         }
2777         case IBLND_REJECT_MSG_QUEUE_SIZE:
2778                 if (!cp) {
2779                         reason = "can't negotiate queue depth";
2780                         goto out;
2781                 }
2782                 if (conn->ibc_queue_depth <= queue_dep) {
2783                         reason = "unsupported queue depth";
2784                         goto out;
2785                 }
2786
2787                 peer_ni->ibp_queue_depth = queue_dep;
2788                 reason = "queue depth";
2789                 break;
2790
2791         case IBLND_REJECT_CONN_STALE:
2792                 reason = "stale";
2793                 break;
2794
2795         case IBLND_REJECT_CONN_RACE:
2796                 reason = "conn race";
2797                 break;
2798
2799         case IBLND_REJECT_CONN_UNCOMPAT:
2800                 reason = "version negotiation";
2801                 break;
2802         }
2803
2804         conn->ibc_reconnect = 1;
2805         peer_ni->ibp_reconnecting++;
2806         peer_ni->ibp_version = version;
2807         if (incarnation != 0)
2808                 peer_ni->ibp_incarnation = incarnation;
2809  out:
2810         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2811
2812         CNETERR("%s: %s (%s), %x, %x, msg_size: %d, queue_depth: %d/%d, max_frags: %d/%d\n",
2813                 libcfs_nid2str(peer_ni->ibp_nid),
2814                 reconnect ? "reconnect" : "don't reconnect",
2815                 reason, IBLND_MSG_VERSION, version, msg_size,
2816                 conn->ibc_queue_depth, queue_dep,
2817                 conn->ibc_max_frags, frag_num);
2818         /*
2819          * if conn::ibc_reconnect is TRUE, connd will reconnect to the peer_ni
2820          * while destroying the zombie
2821          */
2822 }
2823
2824 static void
2825 kiblnd_rejected(struct kib_conn *conn, int reason, void *priv, int priv_nob)
2826 {
2827         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2828         int status = -ECONNREFUSED;
2829
2830         LASSERT (!in_interrupt());
2831         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2832
2833         switch (reason) {
2834         case IB_CM_REJ_STALE_CONN:
2835                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2836                                        IBLND_REJECT_CONN_STALE, NULL);
2837                 break;
2838
2839         case IB_CM_REJ_INVALID_SERVICE_ID:
2840                 status = -EHOSTUNREACH;
2841                 CNETERR("%s rejected: no listener at %d\n",
2842                         libcfs_nid2str(peer_ni->ibp_nid),
2843                         *kiblnd_tunables.kib_service);
2844                 break;
2845
2846         case IB_CM_REJ_CONSUMER_DEFINED:
2847                 if (priv_nob >= offsetof(struct kib_rej, ibr_padding)) {
2848                         struct kib_rej *rej = priv;
2849                         struct kib_connparams *cp = NULL;
2850                         bool flip = false;
2851                         __u64 incarnation = -1;
2852
2853                         /* NB. default incarnation is -1 because:
2854                          * a) V1 will ignore dst incarnation in connreq.
2855                          * b) V2 will provide incarnation while rejecting me,
2856                          *    -1 will be overwrote.
2857                          *
2858                          * if I try to connect to a V1 peer_ni with V2 protocol,
2859                          * it rejected me then upgrade to V2, I have no idea
2860                          * about the upgrading and try to reconnect with V1,
2861                          * in this case upgraded V2 can find out I'm trying to
2862                          * talk to the old guy and reject me(incarnation is -1).
2863                          */
2864
2865                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2866                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2867                                 __swab32s(&rej->ibr_magic);
2868                                 __swab16s(&rej->ibr_version);
2869                                 flip = true;
2870                         }
2871
2872                         if (priv_nob >= sizeof(struct kib_rej) &&
2873                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2874                                 /* priv_nob is always 148 in current version
2875                                  * of OFED, so we still need to check version.
2876                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE)
2877                                  */
2878                                 cp = &rej->ibr_cp;
2879
2880                                 if (flip) {
2881                                         __swab64s(&rej->ibr_incarnation);
2882                                         __swab16s(&cp->ibcp_queue_depth);
2883                                         __swab16s(&cp->ibcp_max_frags);
2884                                         __swab32s(&cp->ibcp_max_msg_size);
2885                                 }
2886
2887                                 incarnation = rej->ibr_incarnation;
2888                         }
2889
2890                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2891                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2892                                 CERROR("%s rejected: consumer defined fatal error\n",
2893                                        libcfs_nid2str(peer_ni->ibp_nid));
2894                                 break;
2895                         }
2896
2897                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2898                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2899                                 CERROR("%s rejected: o2iblnd version %x error\n",
2900                                        libcfs_nid2str(peer_ni->ibp_nid),
2901                                        rej->ibr_version);
2902                                 break;
2903                         }
2904
2905                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2906                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2907                                 CDEBUG(D_NET, "rejected by old version peer_ni %s: %x\n",
2908                                        libcfs_nid2str(peer_ni->ibp_nid),
2909                                        rej->ibr_version);
2910
2911                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2912                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2913                         }
2914
2915                         switch (rej->ibr_why) {
2916                         case IBLND_REJECT_CONN_RACE:
2917                         case IBLND_REJECT_CONN_STALE:
2918                         case IBLND_REJECT_CONN_UNCOMPAT:
2919                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2920                         case IBLND_REJECT_RDMA_FRAGS:
2921                                 kiblnd_check_reconnect(conn, rej->ibr_version,
2922                                                        incarnation,
2923                                                        rej->ibr_why, cp);
2924                                 break;
2925
2926                         case IBLND_REJECT_NO_RESOURCES:
2927                                 CERROR("%s rejected: o2iblnd no resources\n",
2928                                        libcfs_nid2str(peer_ni->ibp_nid));
2929                                 break;
2930
2931                         case IBLND_REJECT_FATAL:
2932                                 CERROR("%s rejected: o2iblnd fatal error\n",
2933                                        libcfs_nid2str(peer_ni->ibp_nid));
2934                                 break;
2935
2936                         default:
2937                                 CERROR("%s rejected: o2iblnd reason %d\n",
2938                                        libcfs_nid2str(peer_ni->ibp_nid),
2939                                        rej->ibr_why);
2940                                 break;
2941                         }
2942                         break;
2943                 }
2944                 /* fall through */
2945         default:
2946                 CNETERR("%s rejected: reason %d, size %d\n",
2947                         libcfs_nid2str(peer_ni->ibp_nid), reason, priv_nob);
2948                 break;
2949         }
2950
2951         kiblnd_connreq_done(conn, status);
2952 }
2953
2954 static void
2955 kiblnd_check_connreply(struct kib_conn *conn, void *priv, int priv_nob)
2956 {
2957         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2958         struct lnet_ni *ni = peer_ni->ibp_ni;
2959         struct kib_net *net = ni->ni_data;
2960         struct kib_msg *msg = priv;
2961         int            ver  = conn->ibc_version;
2962         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
2963         unsigned long  flags;
2964
2965         LASSERT (net != NULL);
2966
2967         if (rc != 0) {
2968                 CERROR("Can't unpack connack from %s: %d\n",
2969                        libcfs_nid2str(peer_ni->ibp_nid), rc);
2970                 goto failed;
2971         }
2972
2973         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2974                 CERROR("Unexpected message %d from %s\n",
2975                        msg->ibm_type, libcfs_nid2str(peer_ni->ibp_nid));
2976                 rc = -EPROTO;
2977                 goto failed;
2978         }
2979
2980         if (ver != msg->ibm_version) {
2981                 CERROR("%s replied version %x is different with "
2982                        "requested version %x\n",
2983                        libcfs_nid2str(peer_ni->ibp_nid), msg->ibm_version, ver);
2984                 rc = -EPROTO;
2985                 goto failed;
2986         }
2987
2988         if (msg->ibm_u.connparams.ibcp_queue_depth >
2989             conn->ibc_queue_depth) {
2990                 CERROR("%s has incompatible queue depth %d (<=%d wanted)\n",
2991                        libcfs_nid2str(peer_ni->ibp_nid),
2992                        msg->ibm_u.connparams.ibcp_queue_depth,
2993                        conn->ibc_queue_depth);
2994                 rc = -EPROTO;
2995                 goto failed;
2996         }
2997
2998         if (msg->ibm_u.connparams.ibcp_max_frags >
2999             conn->ibc_max_frags) {
3000                 CERROR("%s has incompatible max_frags %d (<=%d wanted)\n",
3001                        libcfs_nid2str(peer_ni->ibp_nid),
3002                        msg->ibm_u.connparams.ibcp_max_frags,
3003                        conn->ibc_max_frags);
3004                 rc = -EPROTO;
3005                 goto failed;
3006         }
3007
3008         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
3009                 CERROR("%s max message size %d too big (%d max)\n",
3010                        libcfs_nid2str(peer_ni->ibp_nid),
3011                        msg->ibm_u.connparams.ibcp_max_msg_size,
3012                        IBLND_MSG_SIZE);
3013                 rc = -EPROTO;
3014                 goto failed;
3015         }
3016
3017         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3018         if (msg->ibm_dstnid == lnet_nid_to_nid4(&ni->ni_nid) &&
3019             msg->ibm_dststamp == net->ibn_incarnation)
3020                 rc = 0;
3021         else
3022                 rc = -ESTALE;
3023         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3024
3025         if (rc != 0) {
3026                 CERROR("Bad connection reply from %s, rc = %d, "
3027                        "version: %x max_frags: %d\n",
3028                        libcfs_nid2str(peer_ni->ibp_nid), rc,
3029                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
3030                 goto failed;
3031         }
3032
3033         conn->ibc_incarnation      = msg->ibm_srcstamp;
3034         conn->ibc_credits          = msg->ibm_u.connparams.ibcp_queue_depth;
3035         conn->ibc_reserved_credits = msg->ibm_u.connparams.ibcp_queue_depth;
3036         conn->ibc_queue_depth      = msg->ibm_u.connparams.ibcp_queue_depth;
3037         conn->ibc_max_frags        = msg->ibm_u.connparams.ibcp_max_frags;
3038         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
3039                 IBLND_OOB_MSGS(ver) <= IBLND_RX_MSGS(conn));
3040
3041         kiblnd_connreq_done(conn, 0);
3042         return;
3043
3044  failed:
3045         /* NB My QP has already established itself, so I handle anything going
3046          * wrong here by setting ibc_comms_error.
3047          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
3048          * immediately tears it down. */
3049
3050         LASSERT (rc != 0);
3051         conn->ibc_comms_error = rc;
3052         kiblnd_connreq_done(conn, 0);
3053 }
3054
3055 static int
3056 kiblnd_active_connect(struct rdma_cm_id *cmid)
3057 {
3058         struct kib_peer_ni *peer_ni = cmid->context;
3059         struct kib_conn *conn;
3060         struct kib_msg *msg;
3061         struct rdma_conn_param cp;
3062         int                      version;
3063         __u64                    incarnation;
3064         unsigned long            flags;
3065         int                      rc;
3066
3067         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3068
3069         incarnation = peer_ni->ibp_incarnation;
3070         version     = (peer_ni->ibp_version == 0) ? IBLND_MSG_VERSION :
3071                                                  peer_ni->ibp_version;
3072
3073         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3074
3075         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_ACTIVE_CONNECT,
3076                                   version);
3077         if (conn == NULL) {
3078                 kiblnd_peer_connect_failed(peer_ni, 1, -ENOMEM);
3079                 kiblnd_peer_decref(peer_ni); /* lose cmid's ref */
3080                 return -ENOMEM;
3081         }
3082
3083         /* conn "owns" cmid now, so I return success from here on to ensure the
3084          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
3085          * on peer_ni */
3086
3087         msg = &conn->ibc_connvars->cv_msg;
3088
3089         memset(msg, 0, sizeof(*msg));
3090         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
3091         msg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
3092         msg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
3093         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
3094
3095         kiblnd_pack_msg(peer_ni->ibp_ni, msg, version,
3096                         0, peer_ni->ibp_nid, incarnation);
3097
3098         memset(&cp, 0, sizeof(cp));
3099         cp.private_data        = msg;
3100         cp.private_data_len    = msg->ibm_nob;
3101         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
3102         cp.initiator_depth     = 0;
3103         cp.flow_control        = 1;
3104         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
3105         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
3106
3107         LASSERT(cmid->context == (void *)conn);
3108         LASSERT(conn->ibc_cmid == cmid);
3109         rc = rdma_connect_locked(cmid, &cp);
3110         if (rc != 0) {
3111                 CERROR("Can't connect to %s: %d\n",
3112                        libcfs_nid2str(peer_ni->ibp_nid), rc);
3113                 kiblnd_connreq_done(conn, rc);