Whamcloud - gitweb
LU-10391 lnet: separate lnet_hdr in msg from that in lnd.
[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         struct lnet_hdr hdr;
336
337         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
338
339         CDEBUG (D_NET, "Received %x[%d] from %s\n",
340                 msg->ibm_type, credits,
341                 libcfs_nid2str(conn->ibc_peer->ibp_nid));
342
343         if (credits != 0) {
344                 /* Have I received credits that will let me send? */
345                 spin_lock(&conn->ibc_lock);
346
347                 if (conn->ibc_credits + credits >
348                     conn->ibc_queue_depth) {
349                         rc2 = conn->ibc_credits;
350                         spin_unlock(&conn->ibc_lock);
351
352                         CERROR("Bad credits from %s: %d + %d > %d\n",
353                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
354                                rc2, credits,
355                                conn->ibc_queue_depth);
356
357                         kiblnd_close_conn(conn, -EPROTO);
358                         kiblnd_post_rx(rx, IBLND_POSTRX_NO_CREDIT);
359                         return;
360                 }
361
362                 conn->ibc_credits += credits;
363
364                 /* This ensures the credit taken by NOOP can be returned */
365                 if (msg->ibm_type == IBLND_MSG_NOOP &&
366                     !IBLND_OOB_CAPABLE(conn->ibc_version)) /* v1 only */
367                         conn->ibc_outstanding_credits++;
368
369                 kiblnd_check_sends_locked(conn);
370                 spin_unlock(&conn->ibc_lock);
371         }
372
373         switch (msg->ibm_type) {
374         default:
375                 CERROR("Bad IBLND message type %x from %s\n",
376                        msg->ibm_type, libcfs_nid2str(conn->ibc_peer->ibp_nid));
377                 post_credit = IBLND_POSTRX_NO_CREDIT;
378                 rc = -EPROTO;
379                 break;
380
381         case IBLND_MSG_NOOP:
382                 if (IBLND_OOB_CAPABLE(conn->ibc_version)) {
383                         post_credit = IBLND_POSTRX_NO_CREDIT;
384                         break;
385                 }
386
387                 if (credits != 0) /* credit already posted */
388                         post_credit = IBLND_POSTRX_NO_CREDIT;
389                 else              /* a keepalive NOOP */
390                         post_credit = IBLND_POSTRX_PEER_CREDIT;
391                 break;
392
393         case IBLND_MSG_IMMEDIATE:
394                 post_credit = IBLND_POSTRX_DONT_POST;
395                 lnet_hdr_from_nid4(&hdr, &msg->ibm_u.immediate.ibim_hdr);
396                 rc = lnet_parse(ni, &hdr, msg->ibm_srcnid, rx, 0);
397                 if (rc < 0)                     /* repost on error */
398                         post_credit = IBLND_POSTRX_PEER_CREDIT;
399                 break;
400
401         case IBLND_MSG_PUT_REQ:
402                 post_credit = IBLND_POSTRX_DONT_POST;
403                 lnet_hdr_from_nid4(&hdr, &msg->ibm_u.putreq.ibprm_hdr);
404                 rc = lnet_parse(ni, &hdr, msg->ibm_srcnid, rx, 1);
405                 if (rc < 0)                     /* repost on error */
406                         post_credit = IBLND_POSTRX_PEER_CREDIT;
407                 break;
408
409         case IBLND_MSG_PUT_NAK:
410                 CWARN ("PUT_NACK from %s\n",
411                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
412                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
413                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_REQ,
414                                          msg->ibm_u.completion.ibcm_status,
415                                          msg->ibm_u.completion.ibcm_cookie);
416                 break;
417
418         case IBLND_MSG_PUT_ACK:
419                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
420
421                 spin_lock(&conn->ibc_lock);
422                 tx = kiblnd_find_waiting_tx_locked(conn, IBLND_MSG_PUT_REQ,
423                                         msg->ibm_u.putack.ibpam_src_cookie);
424                 if (tx != NULL)
425                         list_del(&tx->tx_list);
426                 spin_unlock(&conn->ibc_lock);
427
428                 if (tx == NULL) {
429                         CERROR("Unmatched PUT_ACK from %s\n",
430                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
431                         rc = -EPROTO;
432                         break;
433                 }
434
435                 LASSERT (tx->tx_waiting);
436                 /* CAVEAT EMPTOR: I could be racing with tx_complete, but...
437                  * (a) I can overwrite tx_msg since my peer_ni has received it!
438                  * (b) tx_waiting set tells tx_complete() it's not done. */
439
440                 tx->tx_nwrq = tx->tx_nsge = 0;  /* overwrite PUT_REQ */
441
442                 rc2 = kiblnd_init_rdma(conn, tx, IBLND_MSG_PUT_DONE,
443                                        kiblnd_rd_size(&msg->ibm_u.putack.ibpam_rd),
444                                        &msg->ibm_u.putack.ibpam_rd,
445                                        msg->ibm_u.putack.ibpam_dst_cookie);
446                 if (rc2 < 0)
447                         CERROR("Can't setup rdma for PUT to %s: %d\n",
448                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc2);
449
450                 spin_lock(&conn->ibc_lock);
451                 tx->tx_waiting = 0;     /* clear waiting and queue atomically */
452                 kiblnd_queue_tx_locked(tx, conn);
453                 spin_unlock(&conn->ibc_lock);
454                 break;
455
456         case IBLND_MSG_PUT_DONE:
457                 post_credit = IBLND_POSTRX_PEER_CREDIT;
458                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_ACK,
459                                          msg->ibm_u.completion.ibcm_status,
460                                          msg->ibm_u.completion.ibcm_cookie);
461                 break;
462
463         case IBLND_MSG_GET_REQ:
464                 post_credit = IBLND_POSTRX_DONT_POST;
465                 lnet_hdr_from_nid4(&hdr, &msg->ibm_u.get.ibgm_hdr);
466                 rc = lnet_parse(ni, &hdr, msg->ibm_srcnid, rx, 1);
467                 if (rc < 0)                     /* repost on error */
468                         post_credit = IBLND_POSTRX_PEER_CREDIT;
469                 break;
470
471         case IBLND_MSG_GET_DONE:
472                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
473                 kiblnd_handle_completion(conn, IBLND_MSG_GET_REQ,
474                                          msg->ibm_u.completion.ibcm_status,
475                                          msg->ibm_u.completion.ibcm_cookie);
476                 break;
477         }
478
479         if (rc < 0)                             /* protocol error */
480                 kiblnd_close_conn(conn, rc);
481
482         if (post_credit != IBLND_POSTRX_DONT_POST)
483                 kiblnd_post_rx(rx, post_credit);
484 }
485
486 static void
487 kiblnd_rx_complete(struct kib_rx *rx, int status, int nob)
488 {
489         struct kib_msg *msg = rx->rx_msg;
490         struct kib_conn   *conn = rx->rx_conn;
491         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
492         struct kib_net *net = ni->ni_data;
493         int rc;
494         int err = -EIO;
495
496         LASSERT(net);
497         LASSERT(rx->rx_nob < 0);        /* was posted */
498         rx->rx_nob = 0;                 /* isn't now */
499
500         if (conn->ibc_state > IBLND_CONN_ESTABLISHED)
501                 goto ignore;
502
503         if (status != IB_WC_SUCCESS) {
504                 CNETERR("Rx from %s failed: %d\n",
505                         libcfs_nid2str(conn->ibc_peer->ibp_nid), status);
506                 goto failed;
507         }
508
509         LASSERT(nob >= 0);
510         rx->rx_nob = nob;
511
512         rc = kiblnd_unpack_msg(msg, rx->rx_nob);
513         if (rc != 0) {
514                 CERROR("Error %d unpacking rx from %s\n",
515                        rc, libcfs_nid2str(conn->ibc_peer->ibp_nid));
516                 goto failed;
517         }
518
519         if (msg->ibm_srcnid != conn->ibc_peer->ibp_nid ||
520             msg->ibm_dstnid != lnet_nid_to_nid4(&ni->ni_nid) ||
521             msg->ibm_srcstamp != conn->ibc_incarnation ||
522             msg->ibm_dststamp != net->ibn_incarnation) {
523                 CERROR("Stale rx from %s\n",
524                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
525                 err = -ESTALE;
526                 goto failed;
527         }
528
529         /* set time last known alive */
530         kiblnd_peer_alive(conn->ibc_peer);
531
532         /* racing with connection establishment/teardown! */
533
534         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
535                 rwlock_t  *g_lock = &kiblnd_data.kib_global_lock;
536                 unsigned long  flags;
537
538                 write_lock_irqsave(g_lock, flags);
539                 /* must check holding global lock to eliminate race */
540                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
541                         list_add_tail(&rx->rx_list, &conn->ibc_early_rxs);
542                         write_unlock_irqrestore(g_lock, flags);
543                         return;
544                 }
545                 write_unlock_irqrestore(g_lock, flags);
546         }
547         kiblnd_handle_rx(rx);
548         return;
549
550 failed:
551         CDEBUG(D_NET, "rx %p conn %p\n", rx, conn);
552         kiblnd_close_conn(conn, err);
553 ignore:
554         kiblnd_drop_rx(rx);                     /* Don't re-post rx. */
555 }
556
557 static int
558 kiblnd_fmr_map_tx(struct kib_net *net, struct kib_tx *tx,
559                   struct kib_rdma_desc *rd, u32 nob)
560 {
561         struct kib_hca_dev *hdev;
562         struct kib_dev *dev;
563         struct kib_fmr_poolset *fps;
564         int                     cpt;
565         int                     rc;
566         int i;
567
568         LASSERT(tx->tx_pool != NULL);
569         LASSERT(tx->tx_pool->tpo_pool.po_owner != NULL);
570
571         dev = net->ibn_dev;
572         hdev = tx->tx_pool->tpo_hdev;
573         cpt = tx->tx_pool->tpo_pool.po_owner->ps_cpt;
574
575         /*
576          * If we're dealing with FastReg, but the device doesn't
577          * support GAPS and the tx has GAPS, then there is no real point
578          * in trying to map the memory, because it'll just fail. So
579          * preemptively fail with an appropriate message
580          */
581         if ((dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED) &&
582             !(dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT) &&
583             tx->tx_gaps) {
584                 CERROR("Using FastReg with no GAPS support, but tx has gaps. "
585                        "Try setting use_fastreg_gaps to 1\n");
586                 return -EPROTONOSUPPORT;
587         }
588
589 #ifdef HAVE_FMR_POOL_API
590         /*
591          * FMR does not support gaps but the tx has gaps then
592          * we should make sure that the number of fragments we'll be sending
593          * over fits within the number of fragments negotiated on the
594          * connection, otherwise, we won't be able to RDMA the data.
595          * We need to maintain the number of fragments negotiation on the
596          * connection for backwards compatibility.
597          */
598         if (tx->tx_gaps && (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)) {
599                 if (tx->tx_conn &&
600                     tx->tx_conn->ibc_max_frags <= rd->rd_nfrags) {
601                         CERROR("TX number of frags (%d) is <= than connection"
602                                " number of frags (%d). Consider setting peer's"
603                                " map_on_demand to 256\n", tx->tx_nfrags,
604                                tx->tx_conn->ibc_max_frags);
605                         return -EFBIG;
606                 }
607         }
608 #endif
609
610         fps = net->ibn_fmr_ps[cpt];
611         rc = kiblnd_fmr_pool_map(fps, tx, rd, nob, 0, &tx->tx_fmr);
612         if (rc != 0) {
613                 CERROR("Can't map %u bytes (%u/%u)s: %d\n", nob,
614                        tx->tx_nfrags, rd->rd_nfrags, rc);
615                 return rc;
616         }
617
618         /*
619          * If rd is not tx_rd, it's going to get sent to a peer_ni, who will
620          * need the rkey
621          */
622         rd->rd_key = tx->tx_fmr.fmr_key;
623         /*
624          * for FastReg or FMR with no gaps we can accumulate all
625          * the fragments in one FastReg or FMR fragment.
626          */
627         if (
628 #ifdef HAVE_FMR_POOL_API
629             ((dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)
630              && !tx->tx_gaps) ||
631 #endif
632             (dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED)) {
633                 /* FMR requires zero based address */
634 #ifdef HAVE_FMR_POOL_API
635                 if (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)
636                         rd->rd_frags[0].rf_addr &= ~hdev->ibh_page_mask;
637 #endif
638                 rd->rd_frags[0].rf_nob = nob;
639                 rd->rd_nfrags = 1;
640         } else {
641                 /*
642                  * We're transmitting with gaps using FMR.
643                  * We'll need to use multiple fragments and identify the
644                  * zero based address of each fragment.
645                  */
646                 for (i = 0; i < rd->rd_nfrags; i++) {
647                         rd->rd_frags[i].rf_addr &= ~hdev->ibh_page_mask;
648                         rd->rd_frags[i].rf_addr += i << hdev->ibh_page_shift;
649                 }
650         }
651
652         return 0;
653 }
654
655 static void
656 kiblnd_unmap_tx(struct kib_tx *tx)
657 {
658         if (
659 #ifdef HAVE_FMR_POOL_API
660                 tx->tx_fmr.fmr_pfmr ||
661 #endif
662                 tx->tx_fmr.fmr_frd)
663                 kiblnd_fmr_pool_unmap(&tx->tx_fmr, tx->tx_status);
664
665         if (tx->tx_nfrags != 0) {
666                 kiblnd_dma_unmap_sg(tx->tx_pool->tpo_hdev,
667                                     tx->tx_frags, tx->tx_nfrags, tx->tx_dmadir);
668                 tx->tx_nfrags = 0;
669         }
670 }
671
672 #ifdef HAVE_IB_GET_DMA_MR
673 static struct ib_mr *
674 kiblnd_find_rd_dma_mr(struct lnet_ni *ni, struct kib_rdma_desc *rd)
675 {
676         struct kib_net *net = ni->ni_data;
677         struct kib_hca_dev *hdev = net->ibn_dev->ibd_hdev;
678         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
679
680         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
681
682         /*
683          * if map-on-demand is turned on and the device supports
684          * either FMR or FastReg then use that. Otherwise use global
685          * memory regions. If that's not available either, then you're
686          * dead in the water and fail the operation.
687          */
688         if (tunables->lnd_map_on_demand &&
689             (net->ibn_dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED
690 #ifdef HAVE_FMR_POOL_API
691              || net->ibn_dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED
692 #endif
693         ))
694                 return NULL;
695
696         /*
697          * hdev->ibh_mrs can be NULL. This case is dealt with gracefully
698          * in the call chain. The mapping will fail with appropriate error
699          * message.
700          */
701         return hdev->ibh_mrs;
702 }
703 #endif
704
705 static int kiblnd_map_tx(struct lnet_ni *ni, struct kib_tx *tx,
706                          struct kib_rdma_desc *rd, int nfrags)
707 {
708         struct kib_net *net = ni->ni_data;
709         struct kib_hca_dev *hdev = net->ibn_dev->ibd_hdev;
710 #ifdef HAVE_IB_GET_DMA_MR
711         struct ib_mr *mr = NULL;
712 #endif
713         __u32 nob;
714         int i;
715
716         /* If rd is not tx_rd, it's going to get sent to a peer_ni and I'm the
717          * RDMA sink */
718         tx->tx_dmadir = (rd != tx->tx_rd) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
719         tx->tx_nfrags = nfrags;
720
721         rd->rd_nfrags = kiblnd_dma_map_sg(hdev, tx->tx_frags,
722                                           tx->tx_nfrags, tx->tx_dmadir);
723
724         for (i = 0, nob = 0; i < rd->rd_nfrags; i++) {
725                 rd->rd_frags[i].rf_nob  = kiblnd_sg_dma_len(
726                         hdev->ibh_ibdev, &tx->tx_frags[i]);
727                 rd->rd_frags[i].rf_addr = kiblnd_sg_dma_address(
728                         hdev->ibh_ibdev, &tx->tx_frags[i]);
729                 nob += rd->rd_frags[i].rf_nob;
730         }
731
732 #ifdef HAVE_IB_GET_DMA_MR
733         mr = kiblnd_find_rd_dma_mr(ni, rd);
734         if (mr != NULL) {
735                 /* found pre-mapping MR */
736                 rd->rd_key = (rd != tx->tx_rd) ? mr->rkey : mr->lkey;
737                 return 0;
738         }
739 #endif
740
741         if (net->ibn_fmr_ps != NULL)
742                 return kiblnd_fmr_map_tx(net, tx, rd, nob);
743
744         return -EINVAL;
745 }
746
747 static int kiblnd_setup_rd_kiov(struct lnet_ni *ni, struct kib_tx *tx,
748                                 struct kib_rdma_desc *rd, int nkiov,
749                                 struct bio_vec *kiov, int offset, int nob)
750 {
751         struct kib_net *net = ni->ni_data;
752         struct scatterlist *sg;
753         int fragnob;
754         int max_nkiov;
755         int sg_count = 0;
756
757         CDEBUG(D_NET, "niov %d offset %d nob %d\n", nkiov, offset, nob);
758
759         LASSERT(nob > 0);
760         LASSERT(nkiov > 0);
761         LASSERT(net != NULL);
762
763         while (offset >= kiov->bv_len) {
764                 offset -= kiov->bv_len;
765                 nkiov--;
766                 kiov++;
767                 LASSERT(nkiov > 0);
768         }
769
770         max_nkiov = nkiov;
771
772         sg = tx->tx_frags;
773         do {
774                 LASSERT(nkiov > 0);
775
776                 if (!sg) {
777                         CERROR("lacking enough sg entries to map tx\n");
778                         return -EFAULT;
779                 }
780                 sg_count++;
781
782                 fragnob = min((int)(kiov->bv_len - offset), nob);
783
784                 /*
785                  * We're allowed to start at a non-aligned page offset in
786                  * the first fragment and end at a non-aligned page offset
787                  * in the last fragment.
788                  */
789                 if ((fragnob < (int)(kiov->bv_len - offset)) &&
790                     nkiov < max_nkiov && nob > fragnob) {
791                         CDEBUG(D_NET, "fragnob %d < available page %d: with"
792                                       " remaining %d kiovs with %d nob left\n",
793                                fragnob, (int)(kiov->bv_len - offset),
794                                nkiov, nob);
795                         tx->tx_gaps = true;
796                 }
797
798                 sg_set_page(sg, kiov->bv_page, fragnob,
799                             kiov->bv_offset + offset);
800                 sg = sg_next(sg);
801
802                 offset = 0;
803                 kiov++;
804                 nkiov--;
805                 nob -= fragnob;
806         } while (nob > 0);
807
808         return kiblnd_map_tx(ni, tx, rd, sg_count);
809 }
810
811 static int
812 kiblnd_post_tx_locked(struct kib_conn *conn, struct kib_tx *tx, int credit)
813 __must_hold(&conn->ibc_lock)
814 {
815         struct kib_msg *msg = tx->tx_msg;
816         struct kib_peer_ni *peer_ni = conn->ibc_peer;
817         struct lnet_ni *ni = peer_ni->ibp_ni;
818         struct kib_fast_reg_descriptor *frd = tx->tx_fmr.fmr_frd;
819         int ver = conn->ibc_version;
820         int rc;
821         int done;
822
823         LASSERT(tx->tx_queued);
824         /* We rely on this for QP sizing */
825         LASSERT(tx->tx_nwrq > 0 && tx->tx_nsge >= 0);
826         LASSERT(tx->tx_nwrq <= 1 + conn->ibc_max_frags);
827
828         LASSERT(credit == 0 || credit == 1);
829         LASSERT(conn->ibc_outstanding_credits >= 0);
830         LASSERT(conn->ibc_outstanding_credits <= conn->ibc_queue_depth);
831         LASSERT(conn->ibc_credits >= 0);
832         LASSERT(conn->ibc_credits <= conn->ibc_queue_depth);
833
834         if (conn->ibc_nsends_posted ==
835             kiblnd_concurrent_sends(ver, ni)) {
836                 /* tx completions outstanding... */
837                 CDEBUG(D_NET, "%s: posted enough\n",
838                        libcfs_nid2str(peer_ni->ibp_nid));
839                 return -EAGAIN;
840         }
841
842         if (credit != 0 && conn->ibc_credits == 0) {   /* no credits */
843                 CDEBUG(D_NET, "%s: no credits\n",
844                        libcfs_nid2str(peer_ni->ibp_nid));
845                 return -EAGAIN;
846         }
847
848         if (credit != 0 && !IBLND_OOB_CAPABLE(ver) &&
849             conn->ibc_credits == 1 &&   /* last credit reserved */
850             msg->ibm_type != IBLND_MSG_NOOP) {      /* for NOOP */
851                 CDEBUG(D_NET, "%s: not using last credit\n",
852                        libcfs_nid2str(peer_ni->ibp_nid));
853                 return -EAGAIN;
854         }
855
856         /* NB don't drop ibc_lock before bumping tx_sending */
857         list_del(&tx->tx_list);
858         tx->tx_queued = 0;
859
860         if (msg->ibm_type == IBLND_MSG_NOOP &&
861             (!kiblnd_need_noop(conn) ||     /* redundant NOOP */
862              (IBLND_OOB_CAPABLE(ver) && /* posted enough NOOP */
863               conn->ibc_noops_posted == IBLND_OOB_MSGS(ver)))) {
864                 /* OK to drop when posted enough NOOPs, since
865                  * kiblnd_check_sends_locked will queue NOOP again when
866                  * posted NOOPs complete */
867                 spin_unlock(&conn->ibc_lock);
868                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
869                 kiblnd_tx_done(tx);
870                 spin_lock(&conn->ibc_lock);
871                 CDEBUG(D_NET, "%s(%d): redundant or enough NOOP\n",
872                        libcfs_nid2str(peer_ni->ibp_nid),
873                        conn->ibc_noops_posted);
874                 return 0;
875         }
876
877         kiblnd_pack_msg(peer_ni->ibp_ni, msg, ver, conn->ibc_outstanding_credits,
878                         peer_ni->ibp_nid, conn->ibc_incarnation);
879
880         conn->ibc_credits -= credit;
881         conn->ibc_outstanding_credits = 0;
882         conn->ibc_nsends_posted++;
883         if (msg->ibm_type == IBLND_MSG_NOOP)
884                 conn->ibc_noops_posted++;
885
886         /* CAVEAT EMPTOR!  This tx could be the PUT_DONE of an RDMA
887          * PUT.  If so, it was first queued here as a PUT_REQ, sent and
888          * stashed on ibc_active_txs, matched by an incoming PUT_ACK,
889          * and then re-queued here.  It's (just) possible that
890          * tx_sending is non-zero if we've not done the tx_complete()
891          * from the first send; hence the ++ rather than = below. */
892         tx->tx_sending++;
893         list_add(&tx->tx_list, &conn->ibc_active_txs);
894
895         /* I'm still holding ibc_lock! */
896         if (conn->ibc_state != IBLND_CONN_ESTABLISHED) {
897                 rc = -ECONNABORTED;
898         } else if (tx->tx_pool->tpo_pool.po_failed ||
899                  conn->ibc_hdev != tx->tx_pool->tpo_hdev) {
900                 /* close_conn will launch failover */
901                 rc = -ENETDOWN;
902         } else {
903                 struct ib_send_wr *bad = &tx->tx_wrq[tx->tx_nwrq - 1].wr;
904                 struct ib_send_wr *wr  = &tx->tx_wrq[0].wr;
905
906                 if (frd != NULL && !frd->frd_posted) {
907                         if (!frd->frd_valid) {
908                                 wr = &frd->frd_inv_wr.wr;
909                                 wr->next = &frd->frd_fastreg_wr.wr;
910                         } else {
911                                 wr = &frd->frd_fastreg_wr.wr;
912                         }
913                         frd->frd_fastreg_wr.wr.next = &tx->tx_wrq[0].wr;
914                 }
915
916                 LASSERTF(bad->wr_id == kiblnd_ptr2wreqid(tx, IBLND_WID_TX),
917                          "bad wr_id %#llx, opc %d, flags %d, peer_ni: %s\n",
918                          bad->wr_id, bad->opcode, bad->send_flags,
919                          libcfs_nid2str(conn->ibc_peer->ibp_nid));
920
921                 bad = NULL;
922                 if (lnet_send_error_simulation(tx->tx_lntmsg[0], &tx->tx_hstatus))
923                         rc = -EINVAL;
924                 else
925 #ifdef HAVE_IB_POST_SEND_RECV_CONST
926                         rc = ib_post_send(conn->ibc_cmid->qp, wr,
927                                           (const struct ib_send_wr **)&bad);
928 #else
929                         rc = ib_post_send(conn->ibc_cmid->qp, wr, &bad);
930 #endif
931         }
932
933         conn->ibc_last_send = ktime_get();
934
935         if (rc == 0) {
936                 if (frd != NULL)
937                         frd->frd_posted = true;
938                 return 0;
939         }
940
941         /* NB credits are transferred in the actual
942          * message, which can only be the last work item */
943         conn->ibc_credits += credit;
944         conn->ibc_outstanding_credits += msg->ibm_credits;
945         conn->ibc_nsends_posted--;
946         if (msg->ibm_type == IBLND_MSG_NOOP)
947                 conn->ibc_noops_posted--;
948
949         tx->tx_status = rc;
950         tx->tx_waiting = 0;
951         tx->tx_sending--;
952
953         done = (tx->tx_sending == 0);
954         if (done)
955                 list_del(&tx->tx_list);
956
957         spin_unlock(&conn->ibc_lock);
958
959         if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
960                 CERROR("Error %d posting transmit to %s\n",
961                        rc, libcfs_nid2str(peer_ni->ibp_nid));
962         else
963                 CDEBUG(D_NET, "Error %d posting transmit to %s\n",
964                        rc, libcfs_nid2str(peer_ni->ibp_nid));
965
966         kiblnd_close_conn(conn, rc);
967
968         if (done)
969                 kiblnd_tx_done(tx);
970
971         spin_lock(&conn->ibc_lock);
972
973         return -EIO;
974 }
975
976 static void
977 kiblnd_check_sends_locked(struct kib_conn *conn)
978 {
979         int ver = conn->ibc_version;
980         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
981         struct kib_tx *tx;
982
983         /* Don't send anything until after the connection is established */
984         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
985                 CDEBUG(D_NET, "%s too soon\n",
986                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
987                 return;
988         }
989
990         LASSERT(conn->ibc_nsends_posted <=
991                 kiblnd_concurrent_sends(ver, ni));
992         LASSERT (!IBLND_OOB_CAPABLE(ver) ||
993                  conn->ibc_noops_posted <= IBLND_OOB_MSGS(ver));
994         LASSERT (conn->ibc_reserved_credits >= 0);
995
996         while (conn->ibc_reserved_credits > 0 &&
997                (tx = list_first_entry_or_null(&conn->ibc_tx_queue_rsrvd,
998                                               struct kib_tx, tx_list)) != NULL) {
999                 list_move_tail(&tx->tx_list, &conn->ibc_tx_queue);
1000                 conn->ibc_reserved_credits--;
1001         }
1002
1003         if (kiblnd_need_noop(conn)) {
1004                 spin_unlock(&conn->ibc_lock);
1005
1006                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1007                 if (tx != NULL)
1008                         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_NOOP, 0);
1009
1010                 spin_lock(&conn->ibc_lock);
1011                 if (tx != NULL)
1012                         kiblnd_queue_tx_locked(tx, conn);
1013         }
1014
1015         for (;;) {
1016                 int credit;
1017
1018                 if (!list_empty(&conn->ibc_tx_queue_nocred)) {
1019                         credit = 0;
1020                         tx = list_first_entry(&conn->ibc_tx_queue_nocred,
1021                                               struct kib_tx, tx_list);
1022                 } else if (!list_empty(&conn->ibc_tx_noops)) {
1023                         LASSERT (!IBLND_OOB_CAPABLE(ver));
1024                         credit = 1;
1025                         tx = list_first_entry(&conn->ibc_tx_noops,
1026                                               struct kib_tx, tx_list);
1027                 } else if (!list_empty(&conn->ibc_tx_queue)) {
1028                         credit = 1;
1029                         tx = list_first_entry(&conn->ibc_tx_queue,
1030                                               struct kib_tx, tx_list);
1031                 } else
1032                         break;
1033
1034                 if (kiblnd_post_tx_locked(conn, tx, credit) != 0)
1035                         break;
1036         }
1037 }
1038
1039 static void
1040 kiblnd_tx_complete(struct kib_tx *tx, int status)
1041 {
1042         int           failed = (status != IB_WC_SUCCESS);
1043         struct kib_conn   *conn = tx->tx_conn;
1044         int           idle;
1045
1046         if (tx->tx_sending <= 0) {
1047                 CERROR("Received an event on a freed tx: %p status %d\n",
1048                        tx, tx->tx_status);
1049                 return;
1050         }
1051
1052         if (failed) {
1053                 if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1054                         CNETERR("Tx -> %s cookie %#llx"
1055                                 " sending %d waiting %d: failed %d\n",
1056                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
1057                                 tx->tx_cookie, tx->tx_sending, tx->tx_waiting,
1058                                 status);
1059
1060                 kiblnd_close_conn(conn, -EIO);
1061         } else {
1062                 kiblnd_peer_alive(conn->ibc_peer);
1063         }
1064
1065         spin_lock(&conn->ibc_lock);
1066
1067         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
1068          * gets to free it, which also drops its ref on 'conn'. */
1069
1070         tx->tx_sending--;
1071         conn->ibc_nsends_posted--;
1072         if (tx->tx_msg->ibm_type == IBLND_MSG_NOOP)
1073                 conn->ibc_noops_posted--;
1074
1075         if (failed) {
1076                 tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
1077                 tx->tx_waiting = 0;             /* don't wait for peer_ni */
1078                 tx->tx_status = -EIO;
1079         }
1080
1081         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
1082                !tx->tx_waiting &&               /* Not waiting for peer_ni */
1083                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
1084         if (idle)
1085                 list_del(&tx->tx_list);
1086
1087         kiblnd_check_sends_locked(conn);
1088         spin_unlock(&conn->ibc_lock);
1089
1090         if (idle)
1091                 kiblnd_tx_done(tx);
1092 }
1093
1094
1095 static void
1096 kiblnd_init_tx_sge(struct kib_tx *tx, u64 addr, unsigned int len)
1097 {
1098         struct ib_sge *sge = &tx->tx_sge[tx->tx_nsge];
1099         struct kib_hca_dev *hdev = tx->tx_pool->tpo_hdev;
1100 #ifdef HAVE_IB_GET_DMA_MR
1101         struct ib_mr *mr = hdev->ibh_mrs;
1102 #endif
1103
1104         *sge = (struct ib_sge) {
1105 #ifdef HAVE_IB_GET_DMA_MR
1106                 .lkey   = mr->lkey,
1107 #else
1108                 .lkey   = hdev->ibh_pd->local_dma_lkey,
1109 #endif
1110                 .addr   = addr,
1111                 .length = len,
1112         };
1113
1114         tx->tx_nsge++;
1115 }
1116
1117 static void
1118 kiblnd_init_tx_msg(struct lnet_ni *ni, struct kib_tx *tx, int type,
1119                    int body_nob)
1120 {
1121         struct ib_rdma_wr *wrq;
1122         int nob = offsetof(struct kib_msg, ibm_u) + body_nob;
1123
1124         LASSERT(tx->tx_nwrq >= 0);
1125         LASSERT(tx->tx_nwrq < IBLND_MAX_RDMA_FRAGS + 1);
1126         LASSERT(nob <= IBLND_MSG_SIZE);
1127
1128         kiblnd_init_msg(tx->tx_msg, type, body_nob);
1129
1130         wrq = &tx->tx_wrq[tx->tx_nwrq];
1131
1132         *wrq = (struct ib_rdma_wr) {
1133                 .wr = {
1134                         .wr_id          = kiblnd_ptr2wreqid(tx, IBLND_WID_TX),
1135                         .num_sge        = 1,
1136                         .sg_list        = &tx->tx_sge[tx->tx_nsge],
1137                         .opcode         = IB_WR_SEND,
1138                         .send_flags     = IB_SEND_SIGNALED,
1139                 },
1140         };
1141
1142         kiblnd_init_tx_sge(tx, tx->tx_msgaddr, nob);
1143
1144         tx->tx_nwrq++;
1145 }
1146
1147 static int
1148 kiblnd_init_rdma(struct kib_conn *conn, struct kib_tx *tx, int type,
1149                  int resid, struct kib_rdma_desc *dstrd, u64 dstcookie)
1150 {
1151         struct kib_msg *ibmsg = tx->tx_msg;
1152         struct kib_rdma_desc *srcrd = tx->tx_rd;
1153         struct ib_rdma_wr *wrq = NULL;
1154         struct ib_sge     *sge;
1155         int                rc  = resid;
1156         int                srcidx;
1157         int                dstidx;
1158         int                sge_nob;
1159         int                wrq_sge;
1160
1161         LASSERT(!in_interrupt());
1162         LASSERT(tx->tx_nwrq == 0 && tx->tx_nsge == 0);
1163         LASSERT(type == IBLND_MSG_GET_DONE || type == IBLND_MSG_PUT_DONE);
1164
1165         for (srcidx = dstidx = wrq_sge = sge_nob = 0;
1166              resid > 0; resid -= sge_nob) {
1167                 int     prev = dstidx;
1168
1169                 if (srcidx >= srcrd->rd_nfrags) {
1170                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1171                         rc = -EPROTO;
1172                         break;
1173                 }
1174
1175                 if (dstidx >= dstrd->rd_nfrags) {
1176                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1177                         rc = -EPROTO;
1178                         break;
1179                 }
1180
1181                 if (tx->tx_nwrq >= conn->ibc_max_frags) {
1182                         CERROR("RDMA has too many fragments for peer_ni %s (%d), "
1183                                "src idx/frags: %d/%d dst idx/frags: %d/%d\n",
1184                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
1185                                conn->ibc_max_frags,
1186                                srcidx, srcrd->rd_nfrags,
1187                                dstidx, dstrd->rd_nfrags);
1188                         rc = -EMSGSIZE;
1189                         break;
1190                 }
1191
1192                 sge_nob = min3(kiblnd_rd_frag_size(srcrd, srcidx),
1193                                kiblnd_rd_frag_size(dstrd, dstidx),
1194                                resid);
1195
1196                 sge = &tx->tx_sge[tx->tx_nsge];
1197                 sge->addr   = kiblnd_rd_frag_addr(srcrd, srcidx);
1198                 sge->lkey   = kiblnd_rd_frag_key(srcrd, srcidx);
1199                 sge->length = sge_nob;
1200
1201                 if (wrq_sge == 0) {
1202                         wrq = &tx->tx_wrq[tx->tx_nwrq];
1203
1204                         wrq->wr.next    = &(wrq + 1)->wr;
1205                         wrq->wr.wr_id   = kiblnd_ptr2wreqid(tx, IBLND_WID_RDMA);
1206                         wrq->wr.sg_list = sge;
1207                         wrq->wr.opcode  = IB_WR_RDMA_WRITE;
1208                         wrq->wr.send_flags = 0;
1209
1210 #ifdef HAVE_IB_RDMA_WR
1211                         wrq->remote_addr        = kiblnd_rd_frag_addr(dstrd,
1212                                                                       dstidx);
1213                         wrq->rkey               = kiblnd_rd_frag_key(dstrd,
1214                                                                      dstidx);
1215 #else
1216                         wrq->wr.wr.rdma.remote_addr = kiblnd_rd_frag_addr(dstrd,
1217                                                                         dstidx);
1218                         wrq->wr.wr.rdma.rkey    = kiblnd_rd_frag_key(dstrd,
1219                                                                      dstidx);
1220 #endif
1221                 }
1222
1223                 srcidx = kiblnd_rd_consume_frag(srcrd, srcidx, sge_nob);
1224                 dstidx = kiblnd_rd_consume_frag(dstrd, dstidx, sge_nob);
1225
1226                 wrq_sge++;
1227                 if (wrq_sge == *kiblnd_tunables.kib_wrq_sge || dstidx != prev) {
1228                         tx->tx_nwrq++;
1229                         wrq->wr.num_sge = wrq_sge;
1230                         wrq_sge = 0;
1231                 }
1232                 tx->tx_nsge++;
1233         }
1234
1235         if (rc < 0)     /* no RDMA if completing with failure */
1236                 tx->tx_nwrq = tx->tx_nsge = 0;
1237
1238         ibmsg->ibm_u.completion.ibcm_status = rc;
1239         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1240         kiblnd_init_tx_msg(conn->ibc_peer->ibp_ni, tx,
1241                            type, sizeof(struct kib_completion_msg));
1242
1243         return rc;
1244 }
1245
1246 static void
1247 kiblnd_queue_tx_locked(struct kib_tx *tx, struct kib_conn *conn)
1248 {
1249         struct list_head *q;
1250         s64 timeout_ns;
1251
1252         LASSERT(tx->tx_nwrq > 0);       /* work items set up */
1253         LASSERT(!tx->tx_queued);        /* not queued for sending already */
1254         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1255
1256         if (conn->ibc_state >= IBLND_CONN_DISCONNECTED) {
1257                 tx->tx_status = -ECONNABORTED;
1258                 tx->tx_waiting = 0;
1259                 if (tx->tx_conn != NULL) {
1260                         /* PUT_DONE first attached to conn as a PUT_REQ */
1261                         LASSERT(tx->tx_conn == conn);
1262                         LASSERT(tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1263                         tx->tx_conn = NULL;
1264                         kiblnd_conn_decref(conn);
1265                 }
1266                 list_add(&tx->tx_list, &conn->ibc_zombie_txs);
1267
1268                 return;
1269         }
1270
1271         timeout_ns = kiblnd_timeout() * NSEC_PER_SEC;
1272         tx->tx_queued = 1;
1273         tx->tx_deadline = ktime_add_ns(ktime_get(), timeout_ns);
1274
1275         if (tx->tx_conn == NULL) {
1276                 kiblnd_conn_addref(conn);
1277                 tx->tx_conn = conn;
1278                 LASSERT (tx->tx_msg->ibm_type != IBLND_MSG_PUT_DONE);
1279         } else {
1280                 /* PUT_DONE first attached to conn as a PUT_REQ */
1281                 LASSERT (tx->tx_conn == conn);
1282                 LASSERT (tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1283         }
1284
1285         switch (tx->tx_msg->ibm_type) {
1286         default:
1287                 LBUG();
1288
1289         case IBLND_MSG_PUT_REQ:
1290         case IBLND_MSG_GET_REQ:
1291                 q = &conn->ibc_tx_queue_rsrvd;
1292                 break;
1293
1294         case IBLND_MSG_PUT_NAK:
1295         case IBLND_MSG_PUT_ACK:
1296         case IBLND_MSG_PUT_DONE:
1297         case IBLND_MSG_GET_DONE:
1298                 q = &conn->ibc_tx_queue_nocred;
1299                 break;
1300
1301         case IBLND_MSG_NOOP:
1302                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
1303                         q = &conn->ibc_tx_queue_nocred;
1304                 else
1305                         q = &conn->ibc_tx_noops;
1306                 break;
1307
1308         case IBLND_MSG_IMMEDIATE:
1309                 q = &conn->ibc_tx_queue;
1310                 break;
1311         }
1312
1313         list_add_tail(&tx->tx_list, q);
1314 }
1315
1316 static void
1317 kiblnd_queue_tx(struct kib_tx *tx, struct kib_conn *conn)
1318 {
1319         spin_lock(&conn->ibc_lock);
1320         kiblnd_queue_tx_locked(tx, conn);
1321         kiblnd_check_sends_locked(conn);
1322         spin_unlock(&conn->ibc_lock);
1323 }
1324
1325 static int
1326 kiblnd_resolve_addr_cap(struct rdma_cm_id *cmid,
1327                         struct sockaddr_in *srcaddr,
1328                         struct sockaddr_in *dstaddr,
1329                         int timeout_ms)
1330 {
1331         unsigned short port;
1332         int rc;
1333
1334         /* allow the port to be reused */
1335         rc = rdma_set_reuseaddr(cmid, 1);
1336         if (rc != 0) {
1337                 CERROR("Unable to set reuse on cmid: %d\n", rc);
1338                 return rc;
1339         }
1340
1341         /* look for a free privileged port */
1342         for (port = PROT_SOCK-1; port > 0; port--) {
1343                 srcaddr->sin_port = htons(port);
1344                 rc = rdma_resolve_addr(cmid,
1345                                        (struct sockaddr *)srcaddr,
1346                                        (struct sockaddr *)dstaddr,
1347                                        timeout_ms);
1348                 if (rc == 0) {
1349                         CDEBUG(D_NET, "bound to port %hu\n", port);
1350                         return 0;
1351                 } else if (rc == -EADDRINUSE || rc == -EADDRNOTAVAIL) {
1352                         CDEBUG(D_NET, "bind to port %hu failed: %d\n",
1353                                port, rc);
1354                 } else {
1355                         return rc;
1356                 }
1357         }
1358
1359         CERROR("cannot bind to a free privileged port: rc = %d\n", rc);
1360
1361         return rc;
1362 }
1363
1364 static int
1365 kiblnd_resolve_addr(struct rdma_cm_id *cmid,
1366                     struct sockaddr_in *srcaddr,
1367                     struct sockaddr_in *dstaddr,
1368                     int timeout_ms)
1369 {
1370         const struct cred *old_creds = NULL;
1371         struct cred *new_creds;
1372         int rc;
1373
1374         if (!capable(CAP_NET_BIND_SERVICE)) {
1375                 new_creds = prepare_kernel_cred(NULL);
1376                 if (!new_creds)
1377                         return -ENOMEM;
1378
1379                 cap_raise(new_creds->cap_effective, CAP_NET_BIND_SERVICE);
1380                 old_creds = override_creds(new_creds);
1381         }
1382
1383         rc = kiblnd_resolve_addr_cap(cmid, srcaddr, dstaddr, timeout_ms);
1384
1385         if (old_creds)
1386                 revert_creds(old_creds);
1387
1388         return rc;
1389 }
1390
1391 static void
1392 kiblnd_connect_peer(struct kib_peer_ni *peer_ni)
1393 {
1394         struct rdma_cm_id *cmid;
1395         struct kib_dev *dev;
1396         struct kib_net *net = peer_ni->ibp_ni->ni_data;
1397         struct sockaddr_in srcaddr;
1398         struct sockaddr_in dstaddr;
1399         int rc;
1400
1401         LASSERT (net != NULL);
1402         LASSERT (peer_ni->ibp_connecting > 0);
1403
1404         cmid = kiblnd_rdma_create_id(peer_ni->ibp_ni->ni_net_ns,
1405                                      kiblnd_cm_callback, peer_ni,
1406                                      RDMA_PS_TCP, IB_QPT_RC);
1407
1408         if (IS_ERR(cmid)) {
1409                 CERROR("Can't create CMID for %s: %ld\n",
1410                        libcfs_nid2str(peer_ni->ibp_nid), PTR_ERR(cmid));
1411                 rc = PTR_ERR(cmid);
1412                 goto failed;
1413         }
1414
1415         dev = net->ibn_dev;
1416         memset(&srcaddr, 0, sizeof(srcaddr));
1417         srcaddr.sin_family = AF_INET;
1418         srcaddr.sin_addr.s_addr = htonl(dev->ibd_ifip);
1419
1420         memset(&dstaddr, 0, sizeof(dstaddr));
1421         dstaddr.sin_family = AF_INET;
1422         dstaddr.sin_port = htons(*kiblnd_tunables.kib_service);
1423         dstaddr.sin_addr.s_addr = htonl(LNET_NIDADDR(peer_ni->ibp_nid));
1424
1425         kiblnd_peer_addref(peer_ni);               /* cmid's ref */
1426
1427         if (*kiblnd_tunables.kib_use_priv_port) {
1428                 rc = kiblnd_resolve_addr(cmid, &srcaddr, &dstaddr,
1429                                          kiblnd_timeout() * 1000);
1430         } else {
1431                 rc = rdma_resolve_addr(cmid,
1432                                        (struct sockaddr *)&srcaddr,
1433                                        (struct sockaddr *)&dstaddr,
1434                                        kiblnd_timeout() * 1000);
1435         }
1436         if (rc != 0) {
1437                 /* Can't initiate address resolution:  */
1438                 CERROR("Can't resolve addr for %s: %d\n",
1439                        libcfs_nid2str(peer_ni->ibp_nid), rc);
1440                 goto failed2;
1441         }
1442
1443         return;
1444
1445  failed2:
1446         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1447         kiblnd_peer_decref(peer_ni);               /* cmid's ref */
1448         rdma_destroy_id(cmid);
1449         return;
1450  failed:
1451         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1452 }
1453
1454 bool
1455 kiblnd_reconnect_peer(struct kib_peer_ni *peer_ni)
1456 {
1457         rwlock_t *glock = &kiblnd_data.kib_global_lock;
1458         char *reason = NULL;
1459         LIST_HEAD(txs);
1460         unsigned long flags;
1461
1462         write_lock_irqsave(glock, flags);
1463         if (peer_ni->ibp_reconnecting == 0) {
1464                 if (peer_ni->ibp_accepting)
1465                         reason = "accepting";
1466                 else if (peer_ni->ibp_connecting)
1467                         reason = "connecting";
1468                 else if (!list_empty(&peer_ni->ibp_conns))
1469                         reason = "connected";
1470                 else /* connected then closed */
1471                         reason = "closed";
1472
1473                 goto no_reconnect;
1474         }
1475
1476         if (peer_ni->ibp_accepting)
1477                 CNETERR("Detecting race between accepting and reconnecting\n");
1478         peer_ni->ibp_reconnecting--;
1479
1480         if (!kiblnd_peer_active(peer_ni)) {
1481                 list_splice_init(&peer_ni->ibp_tx_queue, &txs);
1482                 reason = "unlinked";
1483                 goto no_reconnect;
1484         }
1485
1486         peer_ni->ibp_connecting++;
1487         peer_ni->ibp_reconnected++;
1488
1489         write_unlock_irqrestore(glock, flags);
1490
1491         kiblnd_connect_peer(peer_ni);
1492         return true;
1493
1494  no_reconnect:
1495         write_unlock_irqrestore(glock, flags);
1496
1497         CWARN("Abort reconnection of %s: %s\n",
1498               libcfs_nid2str(peer_ni->ibp_nid), reason);
1499         kiblnd_txlist_done(&txs, -ECONNABORTED,
1500                            LNET_MSG_STATUS_LOCAL_ABORTED);
1501         return false;
1502 }
1503
1504 void
1505 kiblnd_launch_tx(struct lnet_ni *ni, struct kib_tx *tx, lnet_nid_t nid)
1506 {
1507         struct kib_peer_ni *peer_ni;
1508         struct kib_peer_ni *peer2;
1509         struct kib_conn *conn;
1510         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
1511         unsigned long flags;
1512         int rc;
1513         int i;
1514         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
1515
1516         /* If I get here, I've committed to send, so I complete the tx with
1517          * failure on any problems
1518          */
1519
1520         LASSERT(!tx || !tx->tx_conn);     /* only set when assigned a conn */
1521         LASSERT(!tx || tx->tx_nwrq > 0);  /* work items have been set up */
1522
1523         /* First time, just use a read lock since I expect to find my peer_ni
1524          * connected
1525          */
1526         read_lock_irqsave(g_lock, flags);
1527
1528         peer_ni = kiblnd_find_peer_locked(ni, nid);
1529         if (peer_ni != NULL && !list_empty(&peer_ni->ibp_conns)) {
1530                 /* Found a peer_ni with an established connection */
1531                 conn = kiblnd_get_conn_locked(peer_ni);
1532                 kiblnd_conn_addref(conn); /* 1 ref for me... */
1533
1534                 read_unlock_irqrestore(g_lock, flags);
1535
1536                 if (tx != NULL)
1537                         kiblnd_queue_tx(tx, conn);
1538                 kiblnd_conn_decref(conn); /* ...to here */
1539                 return;
1540         }
1541
1542         read_unlock(g_lock);
1543         /* Re-try with a write lock */
1544         write_lock(g_lock);
1545
1546         peer_ni = kiblnd_find_peer_locked(ni, nid);
1547         if (peer_ni != NULL) {
1548                 if (list_empty(&peer_ni->ibp_conns)) {
1549                         /* found a peer_ni, but it's still connecting... */
1550                         LASSERT(kiblnd_peer_connecting(peer_ni));
1551                         if (tx != NULL)
1552                                 list_add_tail(&tx->tx_list,
1553                                               &peer_ni->ibp_tx_queue);
1554                         write_unlock_irqrestore(g_lock, flags);
1555                 } else {
1556                         conn = kiblnd_get_conn_locked(peer_ni);
1557                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1558
1559                         write_unlock_irqrestore(g_lock, flags);
1560
1561                         if (tx != NULL)
1562                                 kiblnd_queue_tx(tx, conn);
1563                         kiblnd_conn_decref(conn); /* ...to here */
1564                 }
1565                 return;
1566         }
1567
1568         write_unlock_irqrestore(g_lock, flags);
1569
1570         /* Allocate a peer_ni ready to add to the peer_ni table and retry */
1571         rc = kiblnd_create_peer(ni, &peer_ni, nid);
1572         if (rc != 0) {
1573                 CERROR("Can't create peer_ni %s\n", libcfs_nid2str(nid));
1574                 if (tx != NULL) {
1575                         tx->tx_status = -EHOSTUNREACH;
1576                         tx->tx_waiting = 0;
1577                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1578                         kiblnd_tx_done(tx);
1579                 }
1580                 return;
1581         }
1582
1583         write_lock_irqsave(g_lock, flags);
1584
1585         peer2 = kiblnd_find_peer_locked(ni, nid);
1586         if (peer2 != NULL) {
1587                 if (list_empty(&peer2->ibp_conns)) {
1588                         /* found a peer_ni, but it's still connecting... */
1589                         LASSERT(kiblnd_peer_connecting(peer2));
1590                         if (tx != NULL)
1591                                 list_add_tail(&tx->tx_list,
1592                                               &peer2->ibp_tx_queue);
1593                         write_unlock_irqrestore(g_lock, flags);
1594                 } else {
1595                         conn = kiblnd_get_conn_locked(peer2);
1596                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1597
1598                         write_unlock_irqrestore(g_lock, flags);
1599
1600                         if (tx != NULL)
1601                                 kiblnd_queue_tx(tx, conn);
1602                         kiblnd_conn_decref(conn); /* ...to here */
1603                 }
1604
1605                 kiblnd_peer_decref(peer_ni);
1606                 return;
1607         }
1608
1609         /* Brand new peer_ni */
1610         LASSERT(peer_ni->ibp_connecting == 0);
1611         tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
1612         peer_ni->ibp_connecting = tunables->lnd_conns_per_peer;
1613
1614         /* always called with a ref on ni, which prevents ni being shutdown */
1615         LASSERT(((struct kib_net *)ni->ni_data)->ibn_shutdown == 0);
1616
1617         if (tx != NULL)
1618                 list_add_tail(&tx->tx_list, &peer_ni->ibp_tx_queue);
1619
1620         kiblnd_peer_addref(peer_ni);
1621         hash_add(kiblnd_data.kib_peers, &peer_ni->ibp_list, nid);
1622
1623         write_unlock_irqrestore(g_lock, flags);
1624
1625         for (i = 0; i < tunables->lnd_conns_per_peer; i++)
1626                 kiblnd_connect_peer(peer_ni);
1627         kiblnd_peer_decref(peer_ni);
1628 }
1629
1630 int
1631 kiblnd_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg)
1632 {
1633         struct lnet_hdr *hdr = &lntmsg->msg_hdr;
1634         int               type = lntmsg->msg_type;
1635         struct lnet_processid *target = &lntmsg->msg_target;
1636         int               target_is_router = lntmsg->msg_target_is_router;
1637         int               routing = lntmsg->msg_routing;
1638         unsigned int      payload_niov = lntmsg->msg_niov;
1639         struct bio_vec   *payload_kiov = lntmsg->msg_kiov;
1640         unsigned int      payload_offset = lntmsg->msg_offset;
1641         unsigned int      payload_nob = lntmsg->msg_len;
1642         struct kib_msg *ibmsg;
1643         struct kib_rdma_desc *rd;
1644         struct kib_tx *tx;
1645         int               nob;
1646         int               rc;
1647
1648         /* NB 'private' is different depending on what we're sending.... */
1649
1650         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1651                payload_nob, payload_niov, libcfs_idstr(target));
1652
1653         LASSERT (payload_nob == 0 || payload_niov > 0);
1654         LASSERT (payload_niov <= LNET_MAX_IOV);
1655
1656         /* Thread context */
1657         LASSERT (!in_interrupt());
1658
1659         tx = kiblnd_get_idle_tx(ni, lnet_nid_to_nid4(&target->nid));
1660         if (tx == NULL) {
1661                 CERROR("Can't allocate %s txd for %s\n",
1662                         lnet_msgtyp2str(type),
1663                         libcfs_nidstr(&target->nid));
1664                 return -ENOMEM;
1665         }
1666         ibmsg = tx->tx_msg;
1667
1668         switch (type) {
1669         default:
1670                 LBUG();
1671                 return (-EIO);
1672
1673         case LNET_MSG_ACK:
1674                 LASSERT (payload_nob == 0);
1675                 break;
1676
1677         case LNET_MSG_GET:
1678                 if (routing || target_is_router)
1679                         break;                  /* send IMMEDIATE */
1680
1681                 /* is the REPLY message too small for RDMA? */
1682                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1683                 if (nob <= IBLND_MSG_SIZE && !lntmsg->msg_rdma_force)
1684                         break;                  /* send IMMEDIATE */
1685
1686                 rd = &ibmsg->ibm_u.get.ibgm_rd;
1687                 rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1688                                           lntmsg->msg_md->md_niov,
1689                                           lntmsg->msg_md->md_kiov,
1690                                           0, lntmsg->msg_md->md_length);
1691                 if (rc != 0) {
1692                         CERROR("Can't setup GET sink for %s: %d\n",
1693                                libcfs_nidstr(&target->nid), rc);
1694                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1695                         kiblnd_tx_done(tx);
1696                         return -EIO;
1697                 }
1698
1699                 nob = offsetof(struct kib_get_msg, ibgm_rd.rd_frags[rd->rd_nfrags]);
1700                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1701                 lnet_hdr_to_nid4(hdr, &ibmsg->ibm_u.get.ibgm_hdr);
1702
1703                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1704
1705                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1706                 if (tx->tx_lntmsg[1] == NULL) {
1707                         CERROR("Can't create reply for GET -> %s\n",
1708                                libcfs_nidstr(&target->nid));
1709                         kiblnd_tx_done(tx);
1710                         return -EIO;
1711                 }
1712
1713                 /* finalise lntmsg[0,1] on completion */
1714                 tx->tx_lntmsg[0] = lntmsg;
1715                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1716                 kiblnd_launch_tx(ni, tx, lnet_nid_to_nid4(&target->nid));
1717                 return 0;
1718
1719         case LNET_MSG_REPLY:
1720         case LNET_MSG_PUT:
1721                 /* Is the payload small enough not to need RDMA? */
1722                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob]);
1723                 if (nob <= IBLND_MSG_SIZE && !lntmsg->msg_rdma_force)
1724                         break;                  /* send IMMEDIATE */
1725
1726                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1727                                           payload_niov, payload_kiov,
1728                                           payload_offset, payload_nob);
1729                 if (rc != 0) {
1730                         CERROR("Can't setup PUT src for %s: %d\n",
1731                                libcfs_nidstr(&target->nid), rc);
1732                         kiblnd_tx_done(tx);
1733                         return -EIO;
1734                 }
1735
1736                 lnet_hdr_to_nid4(hdr, &ibmsg->ibm_u.putreq.ibprm_hdr);
1737                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1738                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ,
1739                                    sizeof(struct kib_putreq_msg));
1740
1741                 /* finalise lntmsg[0,1] on completion */
1742                 tx->tx_lntmsg[0] = lntmsg;
1743                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1744                 kiblnd_launch_tx(ni, tx, lnet_nid_to_nid4(&target->nid));
1745                 return 0;
1746         }
1747
1748         /* send IMMEDIATE */
1749         LASSERT(offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob])
1750                 <= IBLND_MSG_SIZE);
1751
1752         ibmsg = tx->tx_msg;
1753         lnet_hdr_to_nid4(hdr, &ibmsg->ibm_u.immediate.ibim_hdr);
1754
1755         lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1756                             offsetof(struct kib_msg,
1757                                      ibm_u.immediate.ibim_payload),
1758                             payload_niov, payload_kiov,
1759                             payload_offset, payload_nob);
1760
1761         nob = offsetof(struct kib_immediate_msg, ibim_payload[payload_nob]);
1762
1763         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1764
1765         /* finalise lntmsg on completion */
1766         tx->tx_lntmsg[0] = lntmsg;
1767
1768         kiblnd_launch_tx(ni, tx, lnet_nid_to_nid4(&target->nid));
1769         return 0;
1770 }
1771
1772 static void
1773 kiblnd_reply(struct lnet_ni *ni, struct kib_rx *rx, struct lnet_msg *lntmsg)
1774 {
1775         struct lnet_processid *target = &lntmsg->msg_target;
1776         unsigned int niov = lntmsg->msg_niov;
1777         struct bio_vec *kiov = lntmsg->msg_kiov;
1778         unsigned int offset = lntmsg->msg_offset;
1779         unsigned int nob = lntmsg->msg_len;
1780         struct kib_tx *tx;
1781         int rc;
1782
1783         tx = kiblnd_get_idle_tx(ni, rx->rx_conn->ibc_peer->ibp_nid);
1784         if (tx == NULL) {
1785                 CERROR("Can't get tx for REPLY to %s\n",
1786                        libcfs_nidstr(&target->nid));
1787                 goto failed_0;
1788         }
1789
1790         if (nob == 0)
1791                 rc = 0;
1792         else
1793                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1794                                           niov, kiov, offset, nob);
1795
1796         if (rc != 0) {
1797                 CERROR("Can't setup GET src for %s: %d\n",
1798                        libcfs_nidstr(&target->nid), rc);
1799                 goto failed_1;
1800         }
1801
1802         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1803                               IBLND_MSG_GET_DONE, nob,
1804                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1805                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1806         if (rc < 0) {
1807                 CERROR("Can't setup rdma for GET from %s: %d\n",
1808                        libcfs_nidstr(&target->nid), rc);
1809                 goto failed_1;
1810         }
1811
1812         if (nob == 0) {
1813                 /* No RDMA: local completion may happen now! */
1814                 lnet_finalize(lntmsg, 0);
1815         } else {
1816                 /* RDMA: lnet_finalize(lntmsg) when it
1817                  * completes */
1818                 tx->tx_lntmsg[0] = lntmsg;
1819         }
1820
1821         kiblnd_queue_tx(tx, rx->rx_conn);
1822         return;
1823
1824
1825 failed_1:
1826         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1827         kiblnd_tx_done(tx);
1828 failed_0:
1829         lnet_finalize(lntmsg, -EIO);
1830 }
1831
1832 unsigned int
1833 kiblnd_get_dev_prio(struct lnet_ni *ni, unsigned int dev_idx)
1834 {
1835         struct kib_net *net = ni->ni_data;
1836         struct device *dev = NULL;
1837
1838         if (net)
1839                 dev = net->ibn_dev->ibd_hdev->ibh_ibdev->dma_device;
1840
1841         return lnet_get_dev_prio(dev, dev_idx);
1842
1843 }
1844
1845 int
1846 kiblnd_recv(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg,
1847             int delayed, unsigned int niov, struct bio_vec *kiov,
1848             unsigned int offset, unsigned int mlen, unsigned int rlen)
1849 {
1850         struct kib_rx *rx = private;
1851         struct kib_msg *rxmsg = rx->rx_msg;
1852         struct kib_conn *conn = rx->rx_conn;
1853         struct kib_tx *tx;
1854         __u64        ibprm_cookie;
1855         int          nob;
1856         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1857         int          rc = 0;
1858
1859         LASSERT (mlen <= rlen);
1860         LASSERT (!in_interrupt());
1861
1862         switch (rxmsg->ibm_type) {
1863         default:
1864                 LBUG();
1865                 /* fallthrough */
1866         case IBLND_MSG_IMMEDIATE:
1867                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[rlen]);
1868                 if (nob > rx->rx_nob) {
1869                         CERROR("Immediate message from %s too big: %d(%d)\n",
1870                                libcfs_nid2str(lntmsg->msg_hdr.src_nid),
1871                                nob, rx->rx_nob);
1872                         rc = -EPROTO;
1873                         break;
1874                 }
1875
1876                 lnet_copy_flat2kiov(niov, kiov, offset,
1877                                     IBLND_MSG_SIZE, rxmsg,
1878                                     offsetof(struct kib_msg,
1879                                              ibm_u.immediate.ibim_payload),
1880                                     mlen);
1881                 lnet_finalize(lntmsg, 0);
1882                 break;
1883
1884         case IBLND_MSG_PUT_REQ: {
1885                 struct kib_msg  *txmsg;
1886                 struct kib_rdma_desc *rd;
1887                 ibprm_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1888
1889                 if (mlen == 0) {
1890                         lnet_finalize(lntmsg, 0);
1891                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1892                                                0, ibprm_cookie);
1893                         break;
1894                 }
1895
1896                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1897                 if (tx == NULL) {
1898                         CERROR("Can't allocate tx for %s\n",
1899                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1900                         /* Not replying will break the connection */
1901                         rc = -ENOMEM;
1902                         break;
1903                 }
1904
1905                 txmsg = tx->tx_msg;
1906                 rd = &txmsg->ibm_u.putack.ibpam_rd;
1907                 rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1908                                           niov, kiov, offset, mlen);
1909                 if (rc != 0) {
1910                         CERROR("Can't setup PUT sink for %s: %d\n",
1911                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1912                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1913                         kiblnd_tx_done(tx);
1914                         /* tell peer_ni it's over */
1915                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1916                                                rc, ibprm_cookie);
1917                         break;
1918                 }
1919
1920                 nob = offsetof(struct kib_putack_msg, ibpam_rd.rd_frags[rd->rd_nfrags]);
1921                 txmsg->ibm_u.putack.ibpam_src_cookie = ibprm_cookie;
1922                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1923
1924                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1925
1926                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1927                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1928                 kiblnd_queue_tx(tx, conn);
1929
1930                 /* reposted buffer reserved for PUT_DONE */
1931                 post_credit = IBLND_POSTRX_NO_CREDIT;
1932                 break;
1933                 }
1934
1935         case IBLND_MSG_GET_REQ:
1936                 if (lntmsg != NULL) {
1937                         /* Optimized GET; RDMA lntmsg's payload */
1938                         kiblnd_reply(ni, rx, lntmsg);
1939                 } else {
1940                         /* GET didn't match anything */
1941                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1942                                                -ENODATA,
1943                                                rxmsg->ibm_u.get.ibgm_cookie);
1944                 }
1945                 break;
1946         }
1947
1948         kiblnd_post_rx(rx, post_credit);
1949         return rc;
1950 }
1951
1952 static void
1953 kiblnd_thread_fini (void)
1954 {
1955         atomic_dec (&kiblnd_data.kib_nthreads);
1956 }
1957
1958 static void
1959 kiblnd_peer_alive(struct kib_peer_ni *peer_ni)
1960 {
1961         /* This is racy, but everyone's only writing ktime_get_seconds() */
1962         peer_ni->ibp_last_alive = ktime_get_seconds();
1963         smp_mb();
1964 }
1965
1966 static void
1967 kiblnd_peer_notify(struct kib_peer_ni *peer_ni)
1968 {
1969         int           error = 0;
1970         time64_t last_alive = 0;
1971         unsigned long flags;
1972
1973         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1974
1975         if (kiblnd_peer_idle(peer_ni) && peer_ni->ibp_error != 0) {
1976                 error = peer_ni->ibp_error;
1977                 peer_ni->ibp_error = 0;
1978
1979                 last_alive = peer_ni->ibp_last_alive;
1980         }
1981
1982         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1983
1984         if (error != 0)
1985                 lnet_notify(peer_ni->ibp_ni,
1986                             peer_ni->ibp_nid, false, false, last_alive);
1987 }
1988
1989 void
1990 kiblnd_close_conn_locked(struct kib_conn *conn, int error)
1991 {
1992         /* This just does the immediate housekeeping.  'error' is zero for a
1993          * normal shutdown which can happen only after the connection has been
1994          * established.  If the connection is established, schedule the
1995          * connection to be finished off by the connd.  Otherwise the connd is
1996          * already dealing with it (either to set it up or tear it down).
1997          * Caller holds kib_global_lock exclusively in irq context */
1998         struct kib_peer_ni *peer_ni = conn->ibc_peer;
1999         struct kib_dev *dev;
2000         unsigned long flags;
2001
2002         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2003
2004         if (error != 0 && conn->ibc_comms_error == 0)
2005                 conn->ibc_comms_error = error;
2006
2007         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
2008                 return; /* already being handled  */
2009
2010         if (error == 0 &&
2011             list_empty(&conn->ibc_tx_noops) &&
2012             list_empty(&conn->ibc_tx_queue) &&
2013             list_empty(&conn->ibc_tx_queue_rsrvd) &&
2014             list_empty(&conn->ibc_tx_queue_nocred) &&
2015             list_empty(&conn->ibc_active_txs)) {
2016                 CDEBUG(D_NET, "closing conn to %s\n", 
2017                        libcfs_nid2str(peer_ni->ibp_nid));
2018         } else {
2019                 CNETERR("Closing conn to %s: error %d%s%s%s%s%s\n",
2020                        libcfs_nid2str(peer_ni->ibp_nid), error,
2021                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
2022                        list_empty(&conn->ibc_tx_noops) ? "" : "(sending_noops)",
2023                        list_empty(&conn->ibc_tx_queue_rsrvd) ?
2024                                                 "" : "(sending_rsrvd)",
2025                        list_empty(&conn->ibc_tx_queue_nocred) ?
2026                                                  "" : "(sending_nocred)",
2027                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
2028         }
2029
2030         dev = ((struct kib_net *)peer_ni->ibp_ni->ni_data)->ibn_dev;
2031         if (peer_ni->ibp_next_conn == conn)
2032                 /* clear next_conn so it won't be used */
2033                 peer_ni->ibp_next_conn = NULL;
2034         list_del(&conn->ibc_list);
2035         /* connd (see below) takes over ibc_list's ref */
2036
2037         if (list_empty(&peer_ni->ibp_conns) &&    /* no more conns */
2038             kiblnd_peer_active(peer_ni)) {         /* still in peer_ni table */
2039                 kiblnd_unlink_peer_locked(peer_ni);
2040
2041                 /* set/clear error on last conn */
2042                 peer_ni->ibp_error = conn->ibc_comms_error;
2043         }
2044
2045         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
2046
2047         if (error != 0 &&
2048             kiblnd_dev_can_failover(dev)) {
2049                 list_add_tail(&dev->ibd_fail_list,
2050                               &kiblnd_data.kib_failed_devs);
2051                 wake_up(&kiblnd_data.kib_failover_waitq);
2052         }
2053
2054         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2055
2056         list_add_tail(&conn->ibc_list, &kiblnd_data.kib_connd_conns);
2057         wake_up(&kiblnd_data.kib_connd_waitq);
2058
2059         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
2060 }
2061
2062 void
2063 kiblnd_close_conn(struct kib_conn *conn, int error)
2064 {
2065         unsigned long flags;
2066
2067         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2068
2069         kiblnd_close_conn_locked(conn, error);
2070
2071         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2072 }
2073
2074 static void
2075 kiblnd_handle_early_rxs(struct kib_conn *conn)
2076 {
2077         unsigned long flags;
2078         struct kib_rx *rx;
2079
2080         LASSERT(!in_interrupt());
2081         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2082
2083         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2084         while ((rx = list_first_entry_or_null(&conn->ibc_early_rxs,
2085                                               struct kib_rx,
2086                                               rx_list)) != NULL) {
2087                 list_del(&rx->rx_list);
2088                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2089
2090                 kiblnd_handle_rx(rx);
2091
2092                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2093         }
2094         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2095 }
2096
2097 void
2098 kiblnd_abort_txs(struct kib_conn *conn, struct list_head *txs)
2099 {
2100         LIST_HEAD(zombies);
2101         struct kib_tx *nxt;
2102         struct kib_tx *tx;
2103
2104         spin_lock(&conn->ibc_lock);
2105
2106         list_for_each_entry_safe(tx, nxt, txs, tx_list) {
2107                 if (txs == &conn->ibc_active_txs) {
2108                         LASSERT(!tx->tx_queued);
2109                         LASSERT(tx->tx_waiting ||
2110                                 tx->tx_sending != 0);
2111                         if (conn->ibc_comms_error == -ETIMEDOUT) {
2112                                 if (tx->tx_waiting && !tx->tx_sending)
2113                                         tx->tx_hstatus =
2114                                           LNET_MSG_STATUS_REMOTE_TIMEOUT;
2115                                 else if (tx->tx_sending)
2116                                         tx->tx_hstatus =
2117                                           LNET_MSG_STATUS_NETWORK_TIMEOUT;
2118                         }
2119                 } else {
2120                         LASSERT(tx->tx_queued);
2121                         if (conn->ibc_comms_error == -ETIMEDOUT)
2122                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2123                         else
2124                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
2125                 }
2126
2127                 tx->tx_status = -ECONNABORTED;
2128                 tx->tx_waiting = 0;
2129
2130                 /*
2131                  * TODO: This makes an assumption that
2132                  * kiblnd_tx_complete() will be called for each tx. If
2133                  * that event is dropped we could end up with stale
2134                  * connections floating around. We'd like to deal with
2135                  * that in a better way.
2136                  *
2137                  * Also that means we can exceed the timeout by many
2138                  * seconds.
2139                  */
2140                 if (tx->tx_sending == 0) {
2141                         tx->tx_queued = 0;
2142                         list_move(&tx->tx_list, &zombies);
2143                 } else {
2144                         /* keep tx until cq destroy */
2145                         list_move(&tx->tx_list, &conn->ibc_zombie_txs);
2146                         conn->ibc_waits ++;
2147                 }
2148         }
2149
2150         spin_unlock(&conn->ibc_lock);
2151
2152         /*
2153          * aborting transmits occurs when finalizing the connection.
2154          * The connection is finalized on error.
2155          * Passing LNET_MSG_STATUS_OK to txlist_done() will not
2156          * override the value already set in tx->tx_hstatus above.
2157          */
2158         kiblnd_txlist_done(&zombies, -ECONNABORTED, LNET_MSG_STATUS_OK);
2159 }
2160
2161 static bool
2162 kiblnd_tx_may_discard(struct kib_conn *conn)
2163 {
2164         bool rc = false;
2165         struct kib_tx *nxt;
2166         struct kib_tx *tx;
2167
2168         spin_lock(&conn->ibc_lock);
2169
2170         list_for_each_entry_safe(tx, nxt, &conn->ibc_zombie_txs, tx_list) {
2171                 if (tx->tx_sending > 0 && tx->tx_lntmsg[0] &&
2172                     lnet_md_discarded(tx->tx_lntmsg[0]->msg_md)) {
2173                         tx->tx_sending --;
2174                         if (tx->tx_sending == 0) {
2175                                 kiblnd_conn_decref(tx->tx_conn);
2176                                 tx->tx_conn = NULL;
2177                                 rc = true;
2178                         }
2179                 }
2180         }
2181
2182         spin_unlock(&conn->ibc_lock);
2183         return rc;
2184 }
2185
2186 static void
2187 kiblnd_finalise_conn(struct kib_conn *conn)
2188 {
2189         LASSERT (!in_interrupt());
2190         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
2191
2192         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
2193          * for connections that didn't get as far as being connected, because
2194          * rdma_disconnect() does this for free. */
2195         kiblnd_abort_receives(conn);
2196
2197         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
2198
2199         /* Complete all tx descs not waiting for sends to complete.
2200          * NB we should be safe from RDMA now that the QP has changed state */
2201
2202         kiblnd_abort_txs(conn, &conn->ibc_tx_noops);
2203         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
2204         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
2205         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
2206         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
2207
2208         kiblnd_handle_early_rxs(conn);
2209 }
2210
2211 static void
2212 kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
2213                            int error)
2214 {
2215         LIST_HEAD(zombies);
2216         unsigned long flags;
2217         enum lnet_msg_hstatus hstatus;
2218
2219         LASSERT(error != 0);
2220         LASSERT(!in_interrupt());
2221
2222         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2223
2224         if (active) {
2225                 LASSERT(peer_ni->ibp_connecting > 0);
2226                 peer_ni->ibp_connecting--;
2227         } else {
2228                 LASSERT (peer_ni->ibp_accepting > 0);
2229                 peer_ni->ibp_accepting--;
2230         }
2231
2232         if (kiblnd_peer_connecting(peer_ni)) {
2233                 /* another connection attempt under way... */
2234                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2235                                         flags);
2236                 return;
2237         }
2238
2239         peer_ni->ibp_reconnected = 0;
2240         if (list_empty(&peer_ni->ibp_conns)) {
2241                 /* Take peer_ni's blocked transmits to complete with error */
2242                 list_splice_init(&peer_ni->ibp_tx_queue, &zombies);
2243
2244                 if (kiblnd_peer_active(peer_ni))
2245                         kiblnd_unlink_peer_locked(peer_ni);
2246
2247                 peer_ni->ibp_error = error;
2248         } else {
2249                 /* Can't have blocked transmits if there are connections */
2250                 LASSERT(list_empty(&peer_ni->ibp_tx_queue));
2251         }
2252
2253         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2254
2255         kiblnd_peer_notify(peer_ni);
2256
2257         if (list_empty(&zombies))
2258                 return;
2259
2260         CNETERR("Deleting messages for %s: connection failed\n",
2261                 libcfs_nid2str(peer_ni->ibp_nid));
2262
2263         switch (error) {
2264         case -EHOSTUNREACH:
2265         case -ETIMEDOUT:
2266                 hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
2267                 break;
2268         case -ECONNREFUSED:
2269                 hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
2270                 break;
2271         default:
2272                 hstatus = LNET_MSG_STATUS_LOCAL_DROPPED;
2273                 break;
2274         }
2275
2276         kiblnd_txlist_done(&zombies, error, hstatus);
2277 }
2278
2279 static void
2280 kiblnd_connreq_done(struct kib_conn *conn, int status)
2281 {
2282         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2283         struct kib_tx *tx;
2284         LIST_HEAD(txs);
2285         unsigned long    flags;
2286         int              active;
2287
2288         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2289
2290         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
2291                libcfs_nid2str(peer_ni->ibp_nid), active,
2292                conn->ibc_version, status);
2293
2294         LASSERT (!in_interrupt());
2295         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2296                   peer_ni->ibp_connecting > 0) ||
2297                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2298                   peer_ni->ibp_accepting > 0));
2299
2300         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2301         conn->ibc_connvars = NULL;
2302
2303         if (status != 0) {
2304                 /* failed to establish connection */
2305                 kiblnd_peer_connect_failed(peer_ni, active, status);
2306                 kiblnd_finalise_conn(conn);
2307                 return;
2308         }
2309
2310         /* connection established */
2311         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2312
2313         conn->ibc_last_send = ktime_get();
2314         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2315         kiblnd_peer_alive(peer_ni);
2316
2317         /* Add conn to peer_ni's list and nuke any dangling conns from a different
2318          * peer_ni instance... */
2319         kiblnd_conn_addref(conn);       /* +1 ref for ibc_list */
2320         list_add(&conn->ibc_list, &peer_ni->ibp_conns);
2321         peer_ni->ibp_reconnected = 0;
2322         if (active)
2323                 peer_ni->ibp_connecting--;
2324         else
2325                 peer_ni->ibp_accepting--;
2326
2327         if (peer_ni->ibp_version == 0) {
2328                 peer_ni->ibp_version     = conn->ibc_version;
2329                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2330         }
2331
2332         if (peer_ni->ibp_version     != conn->ibc_version ||
2333             peer_ni->ibp_incarnation != conn->ibc_incarnation) {
2334                 kiblnd_close_stale_conns_locked(peer_ni, conn->ibc_version,
2335                                                 conn->ibc_incarnation);
2336                 peer_ni->ibp_version     = conn->ibc_version;
2337                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2338         }
2339
2340         /* grab pending txs while I have the lock */
2341         list_splice_init(&peer_ni->ibp_tx_queue, &txs);
2342
2343         if (!kiblnd_peer_active(peer_ni) ||        /* peer_ni has been deleted */
2344             conn->ibc_comms_error != 0) {       /* error has happened already */
2345
2346                 /* start to shut down connection */
2347                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2348                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2349
2350                 kiblnd_txlist_done(&txs, -ECONNABORTED,
2351                                    LNET_MSG_STATUS_LOCAL_ERROR);
2352
2353                 return;
2354         }
2355
2356         /* +1 ref for myself, this connection is visible to other threads
2357          * now, refcount of peer:ibp_conns can be released by connection
2358          * close from either a different thread, or the calling of
2359          * kiblnd_check_sends_locked() below. See bz21911 for details.
2360          */
2361         kiblnd_conn_addref(conn);
2362         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2363
2364         /* Schedule blocked txs
2365          * Note: if we are running with conns_per_peer > 1, these blocked
2366          * txs will all get scheduled to the first connection which gets
2367          * scheduled.  We won't be using round robin on this first batch.
2368          */
2369         spin_lock(&conn->ibc_lock);
2370         while ((tx = list_first_entry_or_null(&txs, struct kib_tx,
2371                                               tx_list)) != NULL) {
2372                 list_del(&tx->tx_list);
2373
2374                 kiblnd_queue_tx_locked(tx, conn);
2375         }
2376         kiblnd_check_sends_locked(conn);
2377         spin_unlock(&conn->ibc_lock);
2378
2379         /* schedule blocked rxs */
2380         kiblnd_handle_early_rxs(conn);
2381         kiblnd_conn_decref(conn);
2382 }
2383
2384 static void
2385 kiblnd_reject(struct rdma_cm_id *cmid, struct kib_rej *rej)
2386 {
2387         int          rc;
2388
2389 #ifdef HAVE_RDMA_REJECT_4ARGS
2390         rc = rdma_reject(cmid, rej, sizeof(*rej), IB_CM_REJ_CONSUMER_DEFINED);
2391 #else
2392         rc = rdma_reject(cmid, rej, sizeof(*rej));
2393 #endif
2394
2395         if (rc != 0)
2396                 CWARN("Error %d sending reject\n", rc);
2397 }
2398
2399 static int
2400 kiblnd_passive_connect(struct rdma_cm_id *cmid, void *priv, int priv_nob)
2401 {
2402         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
2403         struct kib_msg *reqmsg = priv;
2404         struct kib_msg *ackmsg;
2405         struct kib_dev *ibdev;
2406         struct kib_peer_ni *peer_ni;
2407         struct kib_peer_ni *peer2;
2408         struct kib_conn *conn;
2409         struct lnet_ni *ni = NULL;
2410         struct kib_net *net = NULL;
2411         lnet_nid_t nid;
2412         struct rdma_conn_param cp;
2413         struct kib_rej rej;
2414         int version = IBLND_MSG_VERSION;
2415         unsigned long flags;
2416         int rc;
2417         struct sockaddr_in *peer_addr;
2418
2419         LASSERT(!in_interrupt());
2420         /* cmid inherits 'context' from the corresponding listener id */
2421         ibdev = cmid->context;
2422         LASSERT(ibdev);
2423
2424         memset(&rej, 0, sizeof(rej));
2425         rej.ibr_magic                = IBLND_MSG_MAGIC;
2426         rej.ibr_why                  = IBLND_REJECT_FATAL;
2427         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2428
2429         peer_addr = (struct sockaddr_in *)&(cmid->route.addr.dst_addr);
2430         if (*kiblnd_tunables.kib_require_priv_port &&
2431             ntohs(peer_addr->sin_port) >= PROT_SOCK) {
2432                 __u32 ip = ntohl(peer_addr->sin_addr.s_addr);
2433                 CERROR("peer_ni's port (%pI4h:%hu) is not privileged\n",
2434                        &ip, ntohs(peer_addr->sin_port));
2435                 goto failed;
2436         }
2437
2438         if (priv_nob < offsetof(struct kib_msg, ibm_type)) {
2439                 CERROR("Short connection request\n");
2440                 goto failed;
2441         }
2442
2443         /* Future protocol version compatibility support!  If the
2444          * o2iblnd-specific protocol changes, or when LNET unifies
2445          * protocols over all LNDs, the initial connection will
2446          * negotiate a protocol version.  I trap this here to avoid
2447          * console errors; the reject tells the peer_ni which protocol I
2448          * speak. */
2449         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2450             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2451                 goto failed;
2452         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2453             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2454             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2455                 goto failed;
2456         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2457             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2458             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2459                 goto failed;
2460
2461         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2462         if (rc != 0) {
2463                 CERROR("Can't parse connection request: %d\n", rc);
2464                 goto failed;
2465         }
2466
2467         nid = reqmsg->ibm_srcnid;
2468         ni  = lnet_nid2ni_addref(reqmsg->ibm_dstnid);
2469
2470         if (ni != NULL) {
2471                 net = (struct kib_net *)ni->ni_data;
2472                 rej.ibr_incarnation = net->ibn_incarnation;
2473         }
2474
2475         if (ni == NULL ||                       /* no matching net */
2476             lnet_nid_to_nid4(&ni->ni_nid) !=
2477             reqmsg->ibm_dstnid ||               /* right NET, wrong NID! */
2478             net->ibn_dev != ibdev) {            /* wrong device */
2479                 CERROR("Can't accept conn from %s on %s (%s:%d:%pI4h): bad dst nid %s\n", libcfs_nid2str(nid),
2480                        ni ? libcfs_nidstr(&ni->ni_nid) : "NA",
2481                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2482                        &ibdev->ibd_ifip,
2483                        libcfs_nid2str(reqmsg->ibm_dstnid));
2484
2485                 goto failed;
2486         }
2487
2488         /* check time stamp as soon as possible */
2489         if (reqmsg->ibm_dststamp != 0 &&
2490             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2491                 CWARN("Stale connection request\n");
2492                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2493                 goto failed;
2494         }
2495
2496         /* I can accept peer_ni's version */
2497         version = reqmsg->ibm_version;
2498
2499         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2500                 CERROR("Unexpected connreq msg type: %x from %s\n",
2501                        reqmsg->ibm_type, libcfs_nid2str(nid));
2502                 goto failed;
2503         }
2504
2505         if (reqmsg->ibm_u.connparams.ibcp_queue_depth >
2506             kiblnd_msg_queue_size(version, ni)) {
2507                 CERROR("Can't accept conn from %s, queue depth too large:  %d (<=%d wanted)\n",
2508                        libcfs_nid2str(nid),
2509                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2510                        kiblnd_msg_queue_size(version, ni));
2511
2512                 if (version == IBLND_MSG_VERSION)
2513                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2514
2515                 goto failed;
2516         }
2517
2518         if (reqmsg->ibm_u.connparams.ibcp_max_frags >
2519             IBLND_MAX_RDMA_FRAGS) {
2520                 CWARN("Can't accept conn from %s (version %x): max_frags %d too large (%d wanted)\n",
2521                       libcfs_nid2str(nid), version,
2522                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2523                       IBLND_MAX_RDMA_FRAGS);
2524
2525                 if (version >= IBLND_MSG_VERSION)
2526                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2527
2528                 goto failed;
2529         } else if (reqmsg->ibm_u.connparams.ibcp_max_frags <
2530                    IBLND_MAX_RDMA_FRAGS &&
2531                    net->ibn_fmr_ps == NULL) {
2532                 CWARN("Can't accept conn from %s (version %x): max_frags %d incompatible without FMR pool (%d wanted)\n",
2533                       libcfs_nid2str(nid), version,
2534                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2535                       IBLND_MAX_RDMA_FRAGS);
2536
2537                 if (version == IBLND_MSG_VERSION)
2538                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2539
2540                 goto failed;
2541         }
2542
2543         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2544                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2545                        libcfs_nid2str(nid),
2546                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2547                        IBLND_MSG_SIZE);
2548                 goto failed;
2549         }
2550
2551         /* assume 'nid' is a new peer_ni; create  */
2552         rc = kiblnd_create_peer(ni, &peer_ni, nid);
2553         if (rc != 0) {
2554                 CERROR("Can't create peer_ni for %s\n", libcfs_nid2str(nid));
2555                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2556                 goto failed;
2557         }
2558
2559         /* We have validated the peer's parameters so use those */
2560         peer_ni->ibp_max_frags = reqmsg->ibm_u.connparams.ibcp_max_frags;
2561         peer_ni->ibp_queue_depth = reqmsg->ibm_u.connparams.ibcp_queue_depth;
2562
2563         write_lock_irqsave(g_lock, flags);
2564
2565         peer2 = kiblnd_find_peer_locked(ni, nid);
2566         if (peer2 != NULL) {
2567                 if (peer2->ibp_version == 0) {
2568                         peer2->ibp_version     = version;
2569                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2570                 }
2571
2572                 /* not the guy I've talked with */
2573                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2574                     peer2->ibp_version     != version) {
2575                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2576
2577                         if (kiblnd_peer_active(peer2)) {
2578                                 peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2579                                 peer2->ibp_version = version;
2580                         }
2581                         write_unlock_irqrestore(g_lock, flags);
2582
2583                         CWARN("Conn stale %s version %x/%x incarnation %llu/%llu\n",
2584                               libcfs_nid2str(nid), peer2->ibp_version, version,
2585                               peer2->ibp_incarnation, reqmsg->ibm_srcstamp);
2586
2587                         kiblnd_peer_decref(peer_ni);
2588                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2589                         goto failed;
2590                 }
2591
2592                 /* Tie-break connection race in favour of the higher NID.
2593                  * If we keep running into a race condition multiple times,
2594                  * we have to assume that the connection attempt with the
2595                  * higher NID is stuck in a connecting state and will never
2596                  * recover.  As such, we pass through this if-block and let
2597                  * the lower NID connection win so we can move forward.
2598                  */
2599                 if (peer2->ibp_connecting != 0 &&
2600                     nid < lnet_nid_to_nid4(&ni->ni_nid) &&
2601                     peer2->ibp_races < MAX_CONN_RACES_BEFORE_ABORT) {
2602                         peer2->ibp_races++;
2603                         write_unlock_irqrestore(g_lock, flags);
2604
2605                         CDEBUG(D_NET, "Conn race %s\n",
2606                                libcfs_nid2str(peer2->ibp_nid));
2607
2608                         kiblnd_peer_decref(peer_ni);
2609                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2610                         goto failed;
2611                 }
2612                 if (peer2->ibp_races >= MAX_CONN_RACES_BEFORE_ABORT)
2613                         CNETERR("Conn race %s: unresolved after %d attempts, letting lower NID win\n",
2614                                 libcfs_nid2str(peer2->ibp_nid),
2615                                 MAX_CONN_RACES_BEFORE_ABORT);
2616                 /*
2617                  * passive connection is allowed even this peer_ni is waiting for
2618                  * reconnection.
2619                  */
2620                 peer2->ibp_reconnecting = 0;
2621                 peer2->ibp_races = 0;
2622                 peer2->ibp_accepting++;
2623                 kiblnd_peer_addref(peer2);
2624
2625                 /* Race with kiblnd_launch_tx (active connect) to create peer_ni
2626                  * so copy validated parameters since we now know what the
2627                  * peer_ni's limits are */
2628                 peer2->ibp_max_frags = peer_ni->ibp_max_frags;
2629                 peer2->ibp_queue_depth = peer_ni->ibp_queue_depth;
2630
2631                 write_unlock_irqrestore(g_lock, flags);
2632                 kiblnd_peer_decref(peer_ni);
2633                 peer_ni = peer2;
2634         } else {
2635                 /* Brand new peer_ni */
2636                 LASSERT(peer_ni->ibp_accepting == 0);
2637                 LASSERT(peer_ni->ibp_version == 0 &&
2638                         peer_ni->ibp_incarnation == 0);
2639
2640                 peer_ni->ibp_accepting   = 1;
2641                 peer_ni->ibp_version     = version;
2642                 peer_ni->ibp_incarnation = reqmsg->ibm_srcstamp;
2643
2644                 /* I have a ref on ni that prevents it being shutdown */
2645                 LASSERT(net->ibn_shutdown == 0);
2646
2647                 kiblnd_peer_addref(peer_ni);
2648                 hash_add(kiblnd_data.kib_peers, &peer_ni->ibp_list, nid);
2649
2650                 write_unlock_irqrestore(g_lock, flags);
2651         }
2652
2653         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_PASSIVE_WAIT,
2654                                   version);
2655         if (!conn) {
2656                 kiblnd_peer_connect_failed(peer_ni, 0, -ENOMEM);
2657                 kiblnd_peer_decref(peer_ni);
2658                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2659                 goto failed;
2660         }
2661
2662         /* conn now "owns" cmid, so I return success from here on to ensure the
2663          * CM callback doesn't destroy cmid.
2664          */
2665         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2666         conn->ibc_credits          = conn->ibc_queue_depth;
2667         conn->ibc_reserved_credits = conn->ibc_queue_depth;
2668         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2669                 IBLND_OOB_MSGS(version) <= IBLND_RX_MSGS(conn));
2670
2671         ackmsg = &conn->ibc_connvars->cv_msg;
2672         memset(ackmsg, 0, sizeof(*ackmsg));
2673
2674         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2675                         sizeof(ackmsg->ibm_u.connparams));
2676         ackmsg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2677         ackmsg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2678         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2679
2680         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2681
2682         memset(&cp, 0, sizeof(cp));
2683         cp.private_data        = ackmsg;
2684         cp.private_data_len    = ackmsg->ibm_nob;
2685         cp.responder_resources = 0;            /* No atomic ops or RDMA reads */
2686         cp.initiator_depth     = 0;
2687         cp.flow_control        = 1;
2688         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2689         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2690
2691         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2692
2693         rc = rdma_accept(cmid, &cp);
2694         if (rc != 0) {
2695                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2696                 rej.ibr_version = version;
2697                 rej.ibr_why     = IBLND_REJECT_FATAL;
2698
2699                 kiblnd_reject(cmid, &rej);
2700                 kiblnd_connreq_done(conn, rc);
2701                 kiblnd_conn_decref(conn);
2702         }
2703
2704         lnet_ni_decref(ni);
2705         return 0;
2706
2707  failed:
2708         if (ni != NULL) {
2709                 rej.ibr_cp.ibcp_queue_depth =
2710                         kiblnd_msg_queue_size(version, ni);
2711                 rej.ibr_cp.ibcp_max_frags   = IBLND_MAX_RDMA_FRAGS;
2712                 lnet_ni_decref(ni);
2713         }
2714
2715         rej.ibr_version = version;
2716         kiblnd_reject(cmid, &rej);
2717
2718         return -ECONNREFUSED;
2719 }
2720
2721 static void
2722 kiblnd_check_reconnect(struct kib_conn *conn, int version,
2723                        u64 incarnation, int why, struct kib_connparams *cp)
2724 {
2725         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
2726         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2727         char            *reason;
2728         int              msg_size = IBLND_MSG_SIZE;
2729         int              frag_num = -1;
2730         int              queue_dep = -1;
2731         bool             reconnect;
2732         unsigned long    flags;
2733
2734         LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2735         LASSERT(peer_ni->ibp_connecting > 0);   /* 'conn' at least */
2736
2737         if (cp) {
2738                 msg_size        = cp->ibcp_max_msg_size;
2739                 frag_num        = cp->ibcp_max_frags;
2740                 queue_dep       = cp->ibcp_queue_depth;
2741         }
2742
2743         write_lock_irqsave(glock, flags);
2744         /* retry connection if it's still needed and no other connection
2745          * attempts (active or passive) are in progress
2746          * NB: reconnect is still needed even when ibp_tx_queue is
2747          * empty if ibp_version != version because reconnect may be
2748          * initiated.
2749          */
2750         reconnect = (!list_empty(&peer_ni->ibp_tx_queue) ||
2751                      peer_ni->ibp_version != version) &&
2752                     peer_ni->ibp_connecting &&
2753                     peer_ni->ibp_accepting == 0;
2754         if (!reconnect) {
2755                 reason = "no need";
2756                 goto out;
2757         }
2758
2759         switch (why) {
2760         default:
2761                 reason = "Unknown";
2762                 break;
2763
2764         case IBLND_REJECT_RDMA_FRAGS: {
2765                 if (!cp) {
2766                         reason = "can't negotiate max frags";
2767                         goto out;
2768                 }
2769
2770                 if (conn->ibc_max_frags <= frag_num) {
2771                         reason = "unsupported max frags";
2772                         goto out;
2773                 }
2774
2775                 peer_ni->ibp_max_frags = frag_num;
2776                 reason = "rdma fragments";
2777                 break;
2778         }
2779         case IBLND_REJECT_MSG_QUEUE_SIZE:
2780                 if (!cp) {
2781                         reason = "can't negotiate queue depth";
2782                         goto out;
2783                 }
2784                 if (conn->ibc_queue_depth <= queue_dep) {
2785                         reason = "unsupported queue depth";
2786                         goto out;
2787                 }
2788
2789                 peer_ni->ibp_queue_depth = queue_dep;
2790                 reason = "queue depth";
2791                 break;
2792
2793         case IBLND_REJECT_CONN_STALE:
2794                 reason = "stale";
2795                 break;
2796
2797         case IBLND_REJECT_CONN_RACE:
2798                 reason = "conn race";
2799                 break;
2800
2801         case IBLND_REJECT_CONN_UNCOMPAT:
2802                 reason = "version negotiation";
2803                 break;
2804         }
2805
2806         conn->ibc_reconnect = 1;
2807         peer_ni->ibp_reconnecting++;
2808         peer_ni->ibp_version = version;
2809         if (incarnation != 0)
2810                 peer_ni->ibp_incarnation = incarnation;
2811  out:
2812         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2813
2814         CNETERR("%s: %s (%s), %x, %x, msg_size: %d, queue_depth: %d/%d, max_frags: %d/%d\n",
2815                 libcfs_nid2str(peer_ni->ibp_nid),
2816                 reconnect ? "reconnect" : "don't reconnect",
2817                 reason, IBLND_MSG_VERSION, version, msg_size,
2818                 conn->ibc_queue_depth, queue_dep,
2819                 conn->ibc_max_frags, frag_num);
2820         /*
2821          * if conn::ibc_reconnect is TRUE, connd will reconnect to the peer_ni
2822          * while destroying the zombie
2823          */
2824 }
2825
2826 static void
2827 kiblnd_rejected(struct kib_conn *conn, int reason, void *priv, int priv_nob)
2828 {
2829         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2830         int status = -ECONNREFUSED;
2831
2832         LASSERT (!in_interrupt());
2833         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2834
2835         switch (reason) {
2836         case IB_CM_REJ_STALE_CONN:
2837                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2838                                        IBLND_REJECT_CONN_STALE, NULL);
2839                 break;
2840
2841         case IB_CM_REJ_INVALID_SERVICE_ID:
2842                 status = -EHOSTUNREACH;
2843                 CNETERR("%s rejected: no listener at %d\n",
2844                         libcfs_nid2str(peer_ni->ibp_nid),
2845                         *kiblnd_tunables.kib_service);
2846                 break;
2847
2848         case IB_CM_REJ_CONSUMER_DEFINED:
2849                 if (priv_nob >= offsetof(struct kib_rej, ibr_padding)) {
2850                         struct kib_rej *rej = priv;
2851                         struct kib_connparams *cp = NULL;
2852                         bool flip = false;
2853                         __u64 incarnation = -1;
2854
2855                         /* NB. default incarnation is -1 because:
2856                          * a) V1 will ignore dst incarnation in connreq.
2857                          * b) V2 will provide incarnation while rejecting me,
2858                          *    -1 will be overwrote.
2859                          *
2860                          * if I try to connect to a V1 peer_ni with V2 protocol,
2861                          * it rejected me then upgrade to V2, I have no idea
2862                          * about the upgrading and try to reconnect with V1,
2863                          * in this case upgraded V2 can find out I'm trying to
2864                          * talk to the old guy and reject me(incarnation is -1).
2865                          */
2866
2867                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2868                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2869                                 __swab32s(&rej->ibr_magic);
2870                                 __swab16s(&rej->ibr_version);
2871                                 flip = true;
2872                         }
2873
2874                         if (priv_nob >= sizeof(struct kib_rej) &&
2875                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2876                                 /* priv_nob is always 148 in current version
2877                                  * of OFED, so we still need to check version.
2878                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE)
2879                                  */
2880                                 cp = &rej->ibr_cp;
2881
2882                                 if (flip) {
2883                                         __swab64s(&rej->ibr_incarnation);
2884                                         __swab16s(&cp->ibcp_queue_depth);
2885                                         __swab16s(&cp->ibcp_max_frags);
2886                                         __swab32s(&cp->ibcp_max_msg_size);
2887                                 }
2888
2889                                 incarnation = rej->ibr_incarnation;
2890                         }
2891
2892                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2893                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2894                                 CERROR("%s rejected: consumer defined fatal error\n",
2895                                        libcfs_nid2str(peer_ni->ibp_nid));
2896                                 break;
2897                         }
2898
2899                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2900                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2901                                 CERROR("%s rejected: o2iblnd version %x error\n",
2902                                        libcfs_nid2str(peer_ni->ibp_nid),
2903                                        rej->ibr_version);
2904                                 break;
2905                         }
2906
2907                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2908                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2909                                 CDEBUG(D_NET, "rejected by old version peer_ni %s: %x\n",
2910                                        libcfs_nid2str(peer_ni->ibp_nid),
2911                                        rej->ibr_version);
2912
2913                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2914                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2915                         }
2916
2917                         switch (rej->ibr_why) {
2918                         case IBLND_REJECT_CONN_RACE:
2919                         case IBLND_REJECT_CONN_STALE:
2920                         case IBLND_REJECT_CONN_UNCOMPAT:
2921                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2922                         case IBLND_REJECT_RDMA_FRAGS:
2923                                 kiblnd_check_reconnect(conn, rej->ibr_version,
2924                                                        incarnation,
2925                                                        rej->ibr_why, cp);
2926                                 break;
2927
2928                         case IBLND_REJECT_NO_RESOURCES:
2929                                 CERROR("%s rejected: o2iblnd no resources\n",
2930                                        libcfs_nid2str(peer_ni->ibp_nid));
2931                                 break;
2932
2933                         case IBLND_REJECT_FATAL:
2934                                 CERROR("%s rejected: o2iblnd fatal error\n",
2935                                        libcfs_nid2str(peer_ni->ibp_nid));
2936                                 break;
2937
2938                         default:
2939                                 CERROR("%s rejected: o2iblnd reason %d\n",
2940                                        libcfs_nid2str(peer_ni->ibp_nid),
2941                                        rej->ibr_why);
2942                                 break;
2943                         }
2944                         break;
2945                 }
2946                 /* fall through */
2947         default:
2948                 CNETERR("%s rejected: reason %d, size %d\n",
2949                         libcfs_nid2str(peer_ni->ibp_nid), reason, priv_nob);
2950                 break;
2951         }
2952
2953         kiblnd_connreq_done(conn, status);
2954 }
2955
2956 static void
2957 kiblnd_check_connreply(struct kib_conn *conn, void *priv, int priv_nob)
2958 {
2959         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2960         struct lnet_ni *ni = peer_ni->ibp_ni;
2961         struct kib_net *net = ni->ni_data;
2962         struct kib_msg *msg = priv;
2963         int            ver  = conn->ibc_version;
2964         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
2965         unsigned long  flags;
2966
2967         LASSERT (net != NULL);
2968
2969         if (rc != 0) {
2970                 CERROR("Can't unpack connack from %s: %d\n",
2971                        libcfs_nid2str(peer_ni->ibp_nid), rc);
2972                 goto failed;
2973         }
2974
2975         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2976                 CERROR("Unexpected message %d from %s\n",
2977                        msg->ibm_type, libcfs_nid2str(peer_ni->ibp_nid));
2978                 rc = -EPROTO;
2979                 goto failed;
2980         }
2981
2982         if (ver != msg->ibm_version) {
2983                 CERROR("%s replied version %x is different with "
2984                        "requested version %x\n",
2985                        libcfs_nid2str(peer_ni->ibp_nid), msg->ibm_version, ver);
2986                 rc = -EPROTO;
2987                 goto failed;
2988         }
2989
2990         if (msg->ibm_u.connparams.ibcp_queue_depth >
2991             conn->ibc_queue_depth) {
2992                 CERROR("%s has incompatible queue depth %d (<=%d wanted)\n",
2993                        libcfs_nid2str(peer_ni->ibp_nid),
2994                        msg->ibm_u.connparams.ibcp_queue_depth,
2995                        conn->ibc_queue_depth);
2996                 rc = -EPROTO;
2997                 goto failed;
2998         }
2999
3000         if (msg->ibm_u.connparams.ibcp_max_frags >
3001             conn->ibc_max_frags) {
3002                 CERROR("%s has incompatible max_frags %d (<=%d wanted)\n",
3003                        libcfs_nid2str(peer_ni->ibp_nid),
3004                        msg->ibm_u.connparams.ibcp_max_frags,
3005                        conn->ibc_max_frags);
3006                 rc = -EPROTO;
3007                 goto failed;
3008         }
3009
3010         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
3011                 CERROR("%s max message size %d too big (%d max)\n",
3012                        libcfs_nid2str(peer_ni->ibp_nid),
3013                        msg->ibm_u.connparams.ibcp_max_msg_size,
3014                        IBLND_MSG_SIZE);
3015                 rc = -EPROTO;
3016                 goto failed;
3017         }
3018
3019         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3020         if (msg->ibm_dstnid == lnet_nid_to_nid4(&ni->ni_nid) &&
3021             msg->ibm_dststamp == net->ibn_incarnation)
3022                 rc = 0;
3023         else
3024                 rc = -ESTALE;
3025         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3026
3027         if (rc != 0) {
3028                 CERROR("Bad connection reply from %s, rc = %d, "
3029                        "version: %x max_frags: %d\n",
3030                        libcfs_nid2str(peer_ni->ibp_nid), rc,
3031                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
3032                 goto failed;
3033         }
3034
3035         conn->ibc_incarnation      = msg->ibm_srcstamp;
3036         conn->ibc_credits          = msg->ibm_u.connparams.ibcp_queue_depth;
3037         conn->ibc_reserved_credits = msg->ibm_u.connparams.ibcp_queue_depth;
3038         conn->ibc_queue_depth      = msg->ibm_u.connparams.ibcp_queue_depth;
3039         conn->ibc_max_frags        = msg->ibm_u.connparams.ibcp_max_frags;
3040         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
3041                 IBLND_OOB_MSGS(ver) <= IBLND_RX_MSGS(conn));
3042
3043         kiblnd_connreq_done(conn, 0);
3044         return;
3045
3046  failed:
3047         /* NB My QP has already established itself, so I handle anything going
3048          * wrong here by setting ibc_comms_error.
3049          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
3050          * immediately tears it down. */
3051
3052         LASSERT (rc != 0);
3053         conn->ibc_comms_error = rc;
3054         kiblnd_connreq_done(conn, 0);
3055 }
3056
3057 static int
3058 kiblnd_active_connect(struct rdma_cm_id *cmid)
3059 {
3060         struct kib_peer_ni *peer_ni = cmid->context;
3061         struct kib_conn *conn;
3062         struct kib_msg *msg;
3063         struct rdma_conn_param cp;
3064         int                      version;
3065         __u64                    incarnation;
3066         unsigned long            flags;
3067         int                      rc;
3068
3069         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3070
3071         incarnation = peer_ni->ibp_incarnation;
3072         version     = (peer_ni->ibp_version == 0) ? IBLND_MSG_VERSION :
3073                                                  peer_ni->ibp_version;
3074
3075         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3076
3077         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_ACTIVE_CONNECT,
3078                                   version);
3079         if (conn == NULL) {
3080                 kiblnd_peer_connect_failed(peer_ni, 1, -ENOMEM);
3081                 kiblnd_peer_decref(peer_ni); /* lose cmid's ref */
3082                 return -ENOMEM;
3083         }
3084
3085         /* conn "owns" cmid now, so I return success from here on to ensure the
3086          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
3087          * on peer_ni */
3088
3089         msg = &conn->ibc_connvars->cv_msg;
3090
3091         memset(msg, 0, sizeof(*msg));
3092         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
3093         msg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
3094         msg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
3095         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
3096
3097         kiblnd_pack_msg(peer_ni->ibp_ni, msg, version,
3098                         0, peer_ni->ibp_nid, incarnation);
3099
3100         memset(&cp, 0, sizeof(cp));
3101         cp.private_data        = msg;
3102         cp.private_data_len    = msg->ibm_nob;
3103         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
3104         cp.initiator_depth     = 0;
3105         cp.flow_control        = 1;
3106         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
3107         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
3108
3109         LASSERT(cmid->context == (void *)conn);
3110         LASSERT(conn->ibc_cmid == cmid);
3111         rc = rdma_connect_locked(cmid, &cp);
3112         if (rc != 0) {
3113                 CERROR("Can't connect to %s: %d\n",
3114                        libcfs_nid2str(peer_ni->ibp_nid), rc);
3115                 kiblnd_connreq_done(conn, rc);
3116                 kiblnd_conn_decref(conn);
3117         }
3118
3119         return 0;
3120 }
3121
3122 int
3123 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
3124 {
3125         struct kib_peer_ni *peer_ni;
3126         struct kib_conn *conn;
3127         int rc;
3128
3129         switch (event->event) {
3130         default:
3131                 CERROR("Unexpected event: %d, status: %d\n",
3132                        event->event, event->status);
3133                 LBUG();
3134
3135         case RDMA_CM_EVENT_CONNECT_REQUEST:
3136                 /* destroy cmid on failure */
3137                 rc = kiblnd_passive_connect(cmid,
3138                                             (void *)KIBLND_CONN_PARAM(event),
3139                                             KIBLND_CONN_PARAM_LEN(event));
3140                 CDEBUG(D_NET, "connreq: %d\n", rc);
3141                 return rc;
3142
3143         case RDMA_CM_EVENT_ADDR_ERROR:
3144                 peer_ni = cmid->context;
3145                 CNETERR("%s: ADDR ERROR %d\n",
3146                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3147                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3148                 kiblnd_peer_decref(peer_ni);
3149                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
3150
3151         case RDMA_CM_EVENT_ADDR_RESOLVED:
3152                 peer_ni = cmid->context;
3153
3154                 CDEBUG(D_NET,"%s Addr resolved: %d\n",
3155                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3156
3157                 if (event->status != 0) {
3158                         CNETERR("Can't resolve address for %s: %d\n",
3159                                 libcfs_nid2str(peer_ni->ibp_nid), event->status);
3160                         rc = event->status;
3161                 } else {
3162                         rc = rdma_resolve_route(
3163                                 cmid, kiblnd_timeout() * 1000);
3164                         if (rc == 0) {
3165                                 struct kib_net *net = peer_ni->ibp_ni->ni_data;
3166                                 struct kib_dev *dev = net->ibn_dev;
3167
3168                                 CDEBUG(D_NET, "%s: connection bound to "\
3169                                        "%s:%pI4h:%s\n",
3170                                        libcfs_nid2str(peer_ni->ibp_nid),
3171                                        dev->ibd_ifname,
3172                                        &dev->ibd_ifip, cmid->device->name);
3173
3174                                 return 0;
3175                         }
3176
3177                         /* Can't initiate route resolution */
3178                         CERROR("Can't resolve route for %s: %d\n",
3179                                libcfs_nid2str(peer_ni->ibp_nid), rc);
3180                 }
3181                 kiblnd_peer_connect_failed(peer_ni, 1, rc);
3182                 kiblnd_peer_decref(peer_ni);
3183                 return rc;                      /* rc != 0 destroys cmid */
3184
3185         case RDMA_CM_EVENT_ROUTE_ERROR:
3186                 peer_ni = cmid->context;
3187                 CNETERR("%s: ROUTE ERROR %d\n",
3188                         libcfs_nid2str(peer_ni->ibp_nid), event->status);
3189                 kiblnd_peer_connect_failed(peer_ni, 1, -EHOSTUNREACH);
3190                 kiblnd_peer_decref(peer_ni);
3191                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
3192
3193         case RDMA_CM_EVENT_ROUTE_RESOLVED:
3194                 peer_ni = cmid->context;
3195                 CDEBUG(D_NET,"%s Route resolved: %d\n",
3196                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3197
3198                 if (event->status == 0)
3199                         return kiblnd_active_connect(cmid);
3200
3201                 CNETERR("Can't resolve route for %s: %d\n",
3202                        libcfs_nid2str(peer_ni->ibp_nid), event->status);
3203                 kiblnd_peer_connect_failed(peer_ni, 1, event->status);
3204                 kiblnd_peer_decref(peer_ni);
3205                 return event->status;           /* rc != 0 destroys cmid */
3206
3207         case RDMA_CM_EVENT_UNREACHABLE:
3208                 conn = cmid->context;
3209                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3210                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3211                 CNETERR("%s: UNREACHABLE %d\n",
3212                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3213                 kiblnd_connreq_done(conn, -ENETDOWN);
3214                 kiblnd_conn_decref(conn);
3215                 return 0;
3216
3217         case RDMA_CM_EVENT_CONNECT_ERROR:
3218                 conn = cmid->context;
3219                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3220                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3221                 CNETERR("%s: CONNECT ERROR %d\n",
3222                         libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3223                 kiblnd_connreq_done(conn, -ENOTCONN);
3224                 kiblnd_conn_decref(conn);
3225                 return 0;
3226
3227         case RDMA_CM_EVENT_REJECTED:
3228                 conn = cmid->context;
3229                 switch (conn->ibc_state) {
3230                 default:
3231                         LBUG();
3232
3233                 case IBLND_CONN_PASSIVE_WAIT:
3234                         CERROR ("%s: REJECTED %d\n",
3235                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
3236                                 event->status);
3237                         kiblnd_connreq_done(conn, -ECONNRESET);
3238                         break;
3239
3240                 case IBLND_CONN_ACTIVE_CONNECT:
3241                         kiblnd_rejected(conn, event->status,
3242                                         (void *)KIBLND_CONN_PARAM(event),
3243                                         KIBLND_CONN_PARAM_LEN(event));
3244                         break;
3245                 }
3246                 kiblnd_conn_decref(conn);
3247                 return 0;
3248
3249         case RDMA_CM_EVENT_ESTABLISHED:
3250                 conn = cmid->context;
3251                 switch (conn->ibc_state) {
3252                 default:
3253                         LBUG();
3254
3255                 case IBLND_CONN_PASSIVE_WAIT:
3256                         CDEBUG(D_NET, "ESTABLISHED (passive): %s\n",
3257                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3258                         kiblnd_connreq_done(conn, 0);
3259                         break;
3260
3261                 case IBLND_CONN_ACTIVE_CONNECT:
3262                         CDEBUG(D_NET, "ESTABLISHED(active): %s\n",
3263                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3264                         kiblnd_check_connreply(conn,
3265                                                (void *)KIBLND_CONN_PARAM(event),
3266                                                KIBLND_CONN_PARAM_LEN(event));
3267                         break;
3268                 }
3269                 /* net keeps its ref on conn! */
3270                 return 0;
3271
3272         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
3273                 CDEBUG(D_NET, "Ignore TIMEWAIT_EXIT event\n");
3274                 return 0;
3275
3276         case RDMA_CM_EVENT_DISCONNECTED:
3277                 conn = cmid->context;
3278                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
3279                         CERROR("%s DISCONNECTED\n",
3280                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3281                         kiblnd_connreq_done(conn, -ECONNRESET);
3282                 } else {
3283                         kiblnd_close_conn(conn, 0);
3284                 }
3285                 kiblnd_conn_decref(conn);
3286                 cmid->context = NULL;
3287                 return 0;
3288
3289         case RDMA_CM_EVENT_DEVICE_REMOVAL:
3290                 LCONSOLE_ERROR_MSG(0x131,
3291                                    "Received notification of device removal\n"
3292                                    "Please shutdown LNET to allow this to proceed\n");
3293                 /* Can't remove network from underneath LNET for now, so I have
3294                  * to ignore this */
3295                 return 0;
3296
3297         case RDMA_CM_EVENT_ADDR_CHANGE:
3298                 LCONSOLE_INFO("Physical link changed (eg hca/port)\n");
3299                 return 0;
3300         }
3301 }
3302
3303 static int
3304 kiblnd_check_txs_locked(struct kib_conn *conn, struct list_head *txs)
3305 {
3306         struct kib_tx *tx;
3307
3308         list_for_each_entry(tx, txs, tx_list) {
3309                 if (txs != &conn->ibc_active_txs) {
3310                         LASSERT(tx->tx_queued);
3311                 } else {
3312                         LASSERT(!tx->tx_queued);
3313                         LASSERT(tx->tx_waiting || tx->tx_sending != 0);
3314                 }
3315
3316                 if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3317                         CERROR("Timed out tx: %s(WSQ:%d%d%d), %lld seconds\n",
3318                                kiblnd_queue2str(conn, txs),
3319                                tx->tx_waiting, tx->tx_sending, tx->tx_queued,
3320                                kiblnd_timeout() +
3321                                ktime_ms_delta(ktime_get(),
3322                                               tx->tx_deadline) / MSEC_PER_SEC);
3323                         return 1;
3324                 }
3325         }
3326
3327         return 0;
3328 }
3329
3330 static int
3331 kiblnd_conn_timed_out_locked(struct kib_conn *conn)
3332 {
3333         return  kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue) ||
3334                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_noops) ||
3335                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_rsrvd) ||
3336                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_nocred) ||
3337                 kiblnd_check_txs_locked(conn, &conn->ibc_active_txs);
3338 }
3339
3340 static void
3341 kiblnd_check_conns (int idx)
3342 {
3343         LIST_HEAD(closes);
3344         LIST_HEAD(checksends);
3345         LIST_HEAD(timedout_txs);
3346         struct hlist_head *peers = &kiblnd_data.kib_peers[idx];
3347         struct kib_peer_ni *peer_ni;
3348         struct kib_conn *conn;
3349         struct kib_tx *tx, *tx_tmp;
3350         unsigned long flags;
3351
3352         /* NB. We expect to have a look at all the peers and not find any
3353          * RDMAs to time out, so we just use a shared lock while we
3354          * take a look...
3355          */
3356         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3357
3358         hlist_for_each_entry(peer_ni, peers, ibp_list) {
3359                 /* Check tx_deadline */
3360                 list_for_each_entry_safe(tx, tx_tmp, &peer_ni->ibp_tx_queue, tx_list) {
3361                         if (ktime_compare(ktime_get(), tx->tx_deadline) >= 0) {
3362                                 CWARN("Timed out tx for %s: %lld seconds\n",
3363                                       libcfs_nid2str(peer_ni->ibp_nid),
3364                                       ktime_ms_delta(ktime_get(),
3365                                                      tx->tx_deadline) / MSEC_PER_SEC);
3366                                 list_move(&tx->tx_list, &timedout_txs);
3367                         }
3368                 }
3369
3370                 list_for_each_entry(conn, &peer_ni->ibp_conns, ibc_list) {
3371                         int timedout;
3372                         int sendnoop;
3373
3374                         LASSERT(conn->ibc_state == IBLND_CONN_ESTABLISHED);
3375
3376                         spin_lock(&conn->ibc_lock);
3377
3378                         sendnoop = kiblnd_need_noop(conn);
3379                         timedout = kiblnd_conn_timed_out_locked(conn);
3380                         if (!sendnoop && !timedout) {
3381                                 spin_unlock(&conn->ibc_lock);
3382                                 continue;
3383                         }
3384
3385                         if (timedout) {
3386                                 CERROR("Timed out RDMA with %s (%lld): c: %u, oc: %u, rc: %u\n",
3387                                        libcfs_nid2str(peer_ni->ibp_nid),
3388                                        ktime_get_seconds()
3389                                        - peer_ni->ibp_last_alive,
3390                                        conn->ibc_credits,
3391                                        conn->ibc_outstanding_credits,
3392                                        conn->ibc_reserved_credits);
3393                                 list_add(&conn->ibc_connd_list, &closes);
3394                         } else {
3395                                 list_add(&conn->ibc_connd_list, &checksends);
3396                         }
3397                         /* +ref for 'closes' or 'checksends' */
3398                         kiblnd_conn_addref(conn);
3399
3400                         spin_unlock(&conn->ibc_lock);
3401                 }
3402         }
3403
3404         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3405
3406         if (!list_empty(&timedout_txs))
3407                 kiblnd_txlist_done(&timedout_txs, -ETIMEDOUT,
3408                                    LNET_MSG_STATUS_NETWORK_TIMEOUT);
3409
3410         /* Handle timeout by closing the whole
3411          * connection. We can only be sure RDMA activity
3412          * has ceased once the QP has been modified.
3413          */
3414         while ((conn = list_first_entry_or_null(&closes,
3415                                                 struct kib_conn,
3416                                                 ibc_connd_list)) != NULL) {
3417                 list_del(&conn->ibc_connd_list);
3418                 kiblnd_close_conn(conn, -ETIMEDOUT);
3419                 kiblnd_conn_decref(conn);
3420         }
3421
3422         /* In case we have enough credits to return via a
3423          * NOOP, but there were no non-blocking tx descs
3424          * free to do it last time...
3425          */
3426         while ((conn = list_first_entry_or_null(&checksends,
3427                                                 struct kib_conn,
3428                                                 ibc_connd_list)) != NULL) {
3429                 list_del(&conn->ibc_connd_list);
3430
3431                 spin_lock(&conn->ibc_lock);
3432                 kiblnd_check_sends_locked(conn);
3433                 spin_unlock(&conn->ibc_lock);
3434
3435                 kiblnd_conn_decref(conn);
3436         }
3437 }
3438
3439 static void
3440 kiblnd_disconnect_conn(struct kib_conn *conn)
3441 {
3442         LASSERT (!in_interrupt());
3443         LASSERT (current == kiblnd_data.kib_connd);
3444         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
3445
3446         rdma_disconnect(conn->ibc_cmid);
3447         kiblnd_finalise_conn(conn);
3448
3449         kiblnd_peer_notify(conn->ibc_peer);
3450 }
3451
3452 /*
3453  * High-water for reconnection to the same peer_ni, reconnection attempt should
3454  * be delayed after trying more than KIB_RECONN_HIGH_RACE.
3455  */
3456 #define KIB_RECONN_HIGH_RACE    10
3457 /*
3458  * Allow connd to take a break and handle other things after consecutive
3459  * reconnection attemps.
3460  */
3461 #define KIB_RECONN_BREAK        100
3462
3463 int
3464 kiblnd_connd (void *arg)
3465 {
3466         spinlock_t *lock = &kiblnd_data.kib_connd_lock;
3467         wait_queue_entry_t wait;
3468         unsigned long flags;
3469         struct kib_conn *conn;
3470         int timeout;
3471         int i;
3472         bool dropped_lock;
3473         int peer_index = 0;
3474         unsigned long deadline = jiffies;
3475
3476         init_wait(&wait);
3477         kiblnd_data.kib_connd = current;
3478
3479         spin_lock_irqsave(lock, flags);
3480
3481         while (!kiblnd_data.kib_shutdown) {
3482                 int reconn = 0;
3483
3484                 dropped_lock = false;
3485
3486                 conn = list_first_entry_or_null(&kiblnd_data.kib_connd_zombies,
3487                                                 struct kib_conn, ibc_list);
3488                 if (conn) {
3489                         struct kib_peer_ni *peer_ni = NULL;
3490
3491                         list_del(&conn->ibc_list);
3492                         if (conn->ibc_reconnect) {
3493                                 peer_ni = conn->ibc_peer;
3494                                 kiblnd_peer_addref(peer_ni);
3495                         }
3496
3497                         spin_unlock_irqrestore(lock, flags);
3498                         dropped_lock = true;
3499
3500                         kiblnd_destroy_conn(conn);
3501
3502                         spin_lock_irqsave(lock, flags);
3503                         if (!peer_ni) {
3504                                 LIBCFS_FREE(conn, sizeof(*conn));
3505                                 continue;
3506                         }
3507
3508                         conn->ibc_peer = peer_ni;
3509                         if (peer_ni->ibp_reconnected < KIB_RECONN_HIGH_RACE)
3510                                 list_add_tail(&conn->ibc_list,
3511                                               &kiblnd_data.kib_reconn_list);
3512                         else
3513                                 list_add_tail(&conn->ibc_list,
3514                                               &kiblnd_data.kib_reconn_wait);
3515                 }
3516
3517                 conn = list_first_entry_or_null(&kiblnd_data.kib_connd_conns,
3518                                                 struct kib_conn, ibc_list);
3519                 if (conn) {
3520                         int wait;
3521
3522                         list_del(&conn->ibc_list);
3523
3524                         spin_unlock_irqrestore(lock, flags);
3525                         dropped_lock = true;
3526
3527                         kiblnd_disconnect_conn(conn);
3528                         wait = conn->ibc_waits;
3529                         if (wait == 0) /* keep ref for connd_wait, see below */
3530                                 kiblnd_conn_decref(conn);
3531
3532                         spin_lock_irqsave(lock, flags);
3533
3534                         if (wait)
3535                                 list_add_tail(&conn->ibc_list,
3536                                               &kiblnd_data.kib_connd_waits);
3537                 }
3538
3539                 while (reconn < KIB_RECONN_BREAK) {
3540                         if (kiblnd_data.kib_reconn_sec !=
3541                             ktime_get_real_seconds()) {
3542                                 kiblnd_data.kib_reconn_sec = ktime_get_real_seconds();
3543                                 list_splice_init(&kiblnd_data.kib_reconn_wait,
3544                                                  &kiblnd_data.kib_reconn_list);
3545                         }
3546
3547                         conn = list_first_entry_or_null(&kiblnd_data.kib_reconn_list,
3548                                                         struct kib_conn, ibc_list);
3549                         if (!conn)
3550                                 break;
3551
3552                         list_del(&conn->ibc_list);
3553
3554                         spin_unlock_irqrestore(lock, flags);
3555                         dropped_lock = true;
3556
3557                         reconn += kiblnd_reconnect_peer(conn->ibc_peer);
3558                         kiblnd_peer_decref(conn->ibc_peer);
3559                         LIBCFS_FREE(conn, sizeof(*conn));
3560
3561                         spin_lock_irqsave(lock, flags);
3562                 }
3563
3564                 conn = list_first_entry_or_null(&kiblnd_data.kib_connd_waits,
3565                                                 struct kib_conn, ibc_list);
3566                 if (conn) {
3567                         list_del(&conn->ibc_list);
3568                         spin_unlock_irqrestore(lock, flags);
3569
3570                         dropped_lock = kiblnd_tx_may_discard(conn);
3571                         if (dropped_lock)
3572                                 kiblnd_conn_decref(conn);
3573
3574                         spin_lock_irqsave(lock, flags);
3575                         if (!dropped_lock)
3576                                 list_add_tail(&conn->ibc_list,
3577                                               &kiblnd_data.kib_connd_waits);
3578                 }
3579
3580                 /* careful with the jiffy wrap... */
3581                 timeout = (int)(deadline - jiffies);
3582                 if (timeout <= 0) {
3583                         const int n = 4;
3584                         const int p = 1;
3585                         int chunk = HASH_SIZE(kiblnd_data.kib_peers);
3586                         unsigned int lnd_timeout;
3587
3588                         spin_unlock_irqrestore(lock, flags);
3589                         dropped_lock = true;
3590
3591                         /* Time to check for RDMA timeouts on a few more
3592                          * peers: I do checks every 'p' seconds on a
3593                          * proportion of the peer_ni table and I need to check
3594                          * every connection 'n' times within a timeout
3595                          * interval, to ensure I detect a timeout on any
3596                          * connection within (n+1)/n times the timeout
3597                          * interval.
3598                          */
3599
3600                         lnd_timeout = kiblnd_timeout();
3601                         if (lnd_timeout > n * p)
3602                                 chunk = (chunk * n * p) / lnd_timeout;
3603                         if (chunk == 0)
3604                                 chunk = 1;
3605
3606                         for (i = 0; i < chunk; i++) {
3607                                 kiblnd_check_conns(peer_index);
3608                                 peer_index = (peer_index + 1) %
3609                                         HASH_SIZE(kiblnd_data.kib_peers);
3610                         }
3611
3612                         deadline += cfs_time_seconds(p);
3613                         spin_lock_irqsave(lock, flags);
3614                 }
3615
3616                 if (dropped_lock)
3617                         continue;
3618
3619                 /* Nothing to do for 'timeout'  */
3620                 set_current_state(TASK_INTERRUPTIBLE);
3621                 add_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3622                 spin_unlock_irqrestore(lock, flags);
3623
3624                 schedule_timeout(timeout);
3625
3626                 remove_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3627                 spin_lock_irqsave(lock, flags);
3628         }
3629
3630         spin_unlock_irqrestore(lock, flags);
3631
3632         kiblnd_thread_fini();
3633         return 0;
3634 }
3635
3636 void
3637 kiblnd_qp_event(struct ib_event *event, void *arg)
3638 {
3639         struct kib_conn *conn = arg;
3640
3641         switch (event->event) {
3642         case IB_EVENT_COMM_EST:
3643                 CDEBUG(D_NET, "%s established\n",
3644                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
3645                 /* We received a packet but connection isn't established
3646                  * probably handshake packet was lost, so free to
3647                  * force make connection established */
3648                 rdma_notify(conn->ibc_cmid, IB_EVENT_COMM_EST);
3649                 return;
3650
3651         case IB_EVENT_PORT_ERR:
3652         case IB_EVENT_DEVICE_FATAL:
3653                 CERROR("Fatal device error for NI %s\n",
3654                        libcfs_nidstr(&conn->ibc_peer->ibp_ni->ni_nid));
3655                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 1);
3656                 return;
3657
3658         case IB_EVENT_PORT_ACTIVE:
3659                 CERROR("Port reactivated for NI %s\n",
3660                        libcfs_nidstr(&conn->ibc_peer->ibp_ni->ni_nid));
3661                 atomic_set(&conn->ibc_peer->ibp_ni->ni_fatal_error_on, 0);
3662                 return;
3663
3664         default:
3665                 CERROR("%s: Async QP event type %d\n",
3666                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3667                 return;
3668         }
3669 }
3670
3671 static void
3672 kiblnd_complete (struct ib_wc *wc)
3673 {
3674         switch (kiblnd_wreqid2type(wc->wr_id)) {
3675         default:
3676                 LBUG();
3677
3678         case IBLND_WID_MR:
3679                 if (wc->status != IB_WC_SUCCESS &&
3680                     wc->status != IB_WC_WR_FLUSH_ERR)
3681                         CNETERR("FastReg failed: %d\n", wc->status);
3682                 return;
3683
3684         case IBLND_WID_RDMA:
3685                 /* We only get RDMA completion notification if it fails.  All
3686                  * subsequent work items, including the final SEND will fail
3687                  * too.  However we can't print out any more info about the
3688                  * failing RDMA because 'tx' might be back on the idle list or
3689                  * even reused already if we didn't manage to post all our work
3690                  * items */
3691                 CNETERR("RDMA (tx: %p) failed: %d\n",
3692                         kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3693                 return;
3694
3695         case IBLND_WID_TX:
3696                 kiblnd_tx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3697                 return;
3698
3699         case IBLND_WID_RX:
3700                 kiblnd_rx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status,
3701                                    wc->byte_len);
3702                 return;
3703         }
3704 }
3705
3706 void
3707 kiblnd_cq_completion(struct ib_cq *cq, void *arg)
3708 {
3709         /* NB I'm not allowed to schedule this conn once its refcount has
3710          * reached 0.  Since fundamentally I'm racing with scheduler threads
3711          * consuming my CQ I could be called after all completions have
3712          * occurred.  But in this case, ibc_nrx == 0 && ibc_nsends_posted == 0
3713          * and this CQ is about to be destroyed so I NOOP. */
3714         struct kib_conn *conn = arg;
3715         struct kib_sched_info *sched = conn->ibc_sched;
3716         unsigned long flags;
3717
3718         LASSERT(cq == conn->ibc_cq);
3719
3720         spin_lock_irqsave(&sched->ibs_lock, flags);
3721
3722         conn->ibc_ready = 1;
3723
3724         if (!conn->ibc_scheduled &&
3725             (conn->ibc_nrx > 0 ||
3726              conn->ibc_nsends_posted > 0)) {
3727                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3728                 conn->ibc_scheduled = 1;
3729                 list_add_tail(&conn->ibc_sched_list, &sched->ibs_conns);
3730
3731                 if (waitqueue_active(&sched->ibs_waitq))
3732                         wake_up(&sched->ibs_waitq);
3733         }
3734
3735         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3736 }
3737
3738 void
3739 kiblnd_cq_event(struct ib_event *event, void *arg)
3740 {
3741         struct kib_conn *conn = arg;
3742
3743         CERROR("%s: async CQ event type %d\n",
3744                libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3745 }
3746
3747 int
3748 kiblnd_scheduler(void *arg)
3749 {
3750         long id = (long)arg;
3751         struct kib_sched_info *sched;
3752         struct kib_conn *conn;
3753         wait_queue_entry_t wait;
3754         unsigned long flags;
3755         struct ib_wc wc;
3756         bool did_something;
3757         int rc;
3758
3759         init_wait(&wait);
3760
3761         sched = kiblnd_data.kib_scheds[KIB_THREAD_CPT(id)];
3762
3763         rc = cfs_cpt_bind(lnet_cpt_table(), sched->ibs_cpt);
3764         if (rc != 0) {
3765                 CWARN("Unable to bind on CPU partition %d, please verify whether all CPUs are healthy and reload modules if necessary, otherwise your system might under risk of low performance\n", sched->ibs_cpt);
3766         }
3767
3768         spin_lock_irqsave(&sched->ibs_lock, flags);
3769
3770         while (!kiblnd_data.kib_shutdown) {
3771                 if (need_resched()) {
3772                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3773
3774                         cond_resched();
3775
3776                         spin_lock_irqsave(&sched->ibs_lock, flags);
3777                 }
3778
3779                 did_something = false;
3780
3781                 conn = list_first_entry_or_null(&sched->ibs_conns,
3782                                                 struct kib_conn,
3783                                                 ibc_sched_list);
3784                 if (conn) {
3785                         /* take over kib_sched_conns' ref on conn... */
3786                         LASSERT(conn->ibc_scheduled);
3787                         list_del(&conn->ibc_sched_list);
3788                         conn->ibc_ready = 0;
3789
3790                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3791
3792                         wc.wr_id = IBLND_WID_INVAL;
3793
3794                         rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3795                         if (rc == 0) {
3796                                 rc = ib_req_notify_cq(conn->ibc_cq,
3797                                                       IB_CQ_NEXT_COMP);
3798                                 if (rc < 0) {
3799                                         CWARN("%s: ib_req_notify_cq failed: %d, closing connection\n",
3800                                               libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
3801                                         kiblnd_close_conn(conn, -EIO);
3802                                         kiblnd_conn_decref(conn);
3803                                         spin_lock_irqsave(&sched->ibs_lock,
3804                                                           flags);
3805                                         continue;
3806                                 }
3807
3808                                 rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3809                         }
3810
3811                         if (unlikely(rc > 0 && wc.wr_id == IBLND_WID_INVAL)) {
3812                                 LCONSOLE_ERROR(
3813                                         "ib_poll_cq (rc: %d) returned invalid "
3814                                         "wr_id, opcode %d, status: %d, "
3815                                         "vendor_err: %d, conn: %s status: %d\n"
3816                                         "please upgrade firmware and OFED or "
3817                                         "contact vendor.\n", rc,
3818                                         wc.opcode, wc.status, wc.vendor_err,
3819                                         libcfs_nid2str(conn->ibc_peer->ibp_nid),
3820                                         conn->ibc_state);
3821                                 rc = -EINVAL;
3822                         }
3823
3824                         if (rc < 0) {
3825                                 CWARN("%s: ib_poll_cq failed: %d, closing connection\n",
3826                                       libcfs_nid2str(conn->ibc_peer->ibp_nid),
3827                                       rc);
3828                                 kiblnd_close_conn(conn, -EIO);
3829                                 kiblnd_conn_decref(conn);
3830                                 spin_lock_irqsave(&sched->ibs_lock, flags);
3831                                 continue;
3832                         }
3833
3834                         spin_lock_irqsave(&sched->ibs_lock, flags);
3835
3836                         if (rc != 0 || conn->ibc_ready) {
3837                                 /* There may be another completion waiting; get
3838                                  * another scheduler to check while I handle
3839                                  * this one... */
3840                                 /* +1 ref for sched_conns */
3841                                 kiblnd_conn_addref(conn);
3842                                 list_add_tail(&conn->ibc_sched_list,
3843                                               &sched->ibs_conns);
3844                                 if (waitqueue_active(&sched->ibs_waitq))
3845                                         wake_up(&sched->ibs_waitq);
3846                         } else {
3847                                 conn->ibc_scheduled = 0;
3848                         }
3849
3850                         if (rc != 0) {
3851                                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
3852                                 kiblnd_complete(&wc);
3853
3854                                 spin_lock_irqsave(&sched->ibs_lock, flags);
3855                         }
3856
3857                         kiblnd_conn_decref(conn); /* ..drop my ref from above */
3858                         did_something = true;
3859                 }
3860
3861                 if (did_something)
3862                         continue;
3863
3864                 set_current_state(TASK_INTERRUPTIBLE);
3865                 add_wait_queue_exclusive(&sched->ibs_waitq, &wait);
3866                 spin_unlock_irqrestore(&sched->ibs_lock, flags);
3867
3868                 schedule();
3869
3870                 remove_wait_queue(&sched->ibs_waitq, &wait);
3871                 set_current_state(TASK_RUNNING);
3872                 spin_lock_irqsave(&sched->ibs_lock, flags);
3873         }
3874
3875         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3876
3877         kiblnd_thread_fini();
3878         return 0;
3879 }
3880
3881 int
3882 kiblnd_failover_thread(void *arg)
3883 {
3884         rwlock_t *glock = &kiblnd_data.kib_global_lock;
3885         struct kib_dev *dev;
3886         struct net *ns = arg;
3887         wait_queue_entry_t wait;
3888         unsigned long flags;
3889         int rc;
3890
3891         LASSERT(*kiblnd_tunables.kib_dev_failover != 0);
3892
3893         init_wait(&wait);
3894         write_lock_irqsave(glock, flags);
3895
3896         while (!kiblnd_data.kib_shutdown) {
3897                 bool do_failover = false;
3898                 int long_sleep;
3899
3900                 list_for_each_entry(dev, &kiblnd_data.kib_failed_devs,
3901                                     ibd_fail_list) {
3902                         if (ktime_get_seconds() < dev->ibd_next_failover)
3903                                 continue;
3904                         do_failover = true;
3905                         break;
3906                 }
3907
3908                 if (do_failover) {
3909                         list_del_init(&dev->ibd_fail_list);
3910                         dev->ibd_failover = 1;
3911                         write_unlock_irqrestore(glock, flags);
3912
3913                         rc = kiblnd_dev_failover(dev, ns);
3914
3915                         write_lock_irqsave(glock, flags);
3916
3917                         LASSERT(dev->ibd_failover);
3918                         dev->ibd_failover = 0;
3919                         if (rc >= 0) { /* Device is OK or failover succeed */
3920                                 dev->ibd_next_failover = ktime_get_seconds() + 3;
3921                                 continue;
3922                         }
3923
3924                         /* failed to failover, retry later */
3925                         dev->ibd_next_failover = ktime_get_seconds() +
3926                                 min(dev->ibd_failed_failover, 10);
3927                         if (kiblnd_dev_can_failover(dev)) {
3928                                 list_add_tail(&dev->ibd_fail_list,
3929                                               &kiblnd_data.kib_failed_devs);
3930                         }
3931
3932                         continue;
3933                 }
3934
3935                 /* long sleep if no more pending failover */
3936                 long_sleep = list_empty(&kiblnd_data.kib_failed_devs);
3937
3938                 set_current_state(TASK_INTERRUPTIBLE);
3939                 add_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
3940                 write_unlock_irqrestore(glock, flags);
3941
3942                 rc = schedule_timeout(long_sleep ? cfs_time_seconds(10) :
3943                                       cfs_time_seconds(1));
3944                 set_current_state(TASK_RUNNING);
3945                 remove_wait_queue(&kiblnd_data.kib_failover_waitq, &wait);
3946                 write_lock_irqsave(glock, flags);
3947
3948                 if (!long_sleep || rc != 0)
3949                         continue;
3950
3951                 /* have a long sleep, routine check all active devices,
3952                  * we need checking like this because if there is not active
3953                  * connection on the dev and no SEND from local, we may listen
3954                  * on wrong HCA for ever while there is a bonding failover
3955                  */
3956                 list_for_each_entry(dev, &kiblnd_data.kib_devs, ibd_list) {
3957                         if (kiblnd_dev_can_failover(dev)) {
3958                                 list_add_tail(&dev->ibd_fail_list,
3959                                               &kiblnd_data.kib_failed_devs);
3960                         }
3961                 }
3962         }
3963
3964         write_unlock_irqrestore(glock, flags);
3965
3966         kiblnd_thread_fini();
3967         return 0;
3968 }