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