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