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