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