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