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