Whamcloud - gitweb
LU-9679 modules: Use LIST_HEAD for declaring list_heads
[fs/lustre-release.git] / lnet / klnds / o2iblnd / o2iblnd_cb.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lnet/klnds/o2iblnd/o2iblnd_cb.c
33  *
34  * Author: Eric Barton <eric@bartonsoftware.com>
35  */
36
37 #include "o2iblnd.h"
38
39 #define MAX_CONN_RACES_BEFORE_ABORT 20
40
41 static void kiblnd_peer_alive(struct kib_peer_ni *peer_ni);
42 static void kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
43                                        int error);
44 static void kiblnd_init_tx_msg(struct lnet_ni *ni, struct kib_tx *tx,
45                                int type, int body_nob);
46 static int kiblnd_init_rdma(struct kib_conn *conn, struct kib_tx *tx, int type,
47                             int resid, struct kib_rdma_desc *dstrd, u64 dstcookie);
48 static void kiblnd_queue_tx_locked(struct kib_tx *tx, struct kib_conn *conn);
49 static void kiblnd_queue_tx(struct kib_tx *tx, struct kib_conn *conn);
50
51 static void kiblnd_unmap_tx(struct kib_tx *tx);
52 static void kiblnd_check_sends_locked(struct kib_conn *conn);
53
54 void
55 kiblnd_tx_done(struct kib_tx *tx)
56 {
57         struct lnet_msg *lntmsg[2];
58         int         rc;
59         int         i;
60
61         LASSERT (!in_interrupt());
62         LASSERT (!tx->tx_queued);               /* mustn't be queued for sending */
63         LASSERT (tx->tx_sending == 0);          /* mustn't be awaiting sent callback */
64         LASSERT (!tx->tx_waiting);              /* mustn't be awaiting peer_ni response */
65         LASSERT (tx->tx_pool != NULL);
66
67         kiblnd_unmap_tx(tx);
68
69         /* tx may have up to 2 lnet msgs to finalise */
70         lntmsg[0] = tx->tx_lntmsg[0]; tx->tx_lntmsg[0] = NULL;
71         lntmsg[1] = tx->tx_lntmsg[1]; tx->tx_lntmsg[1] = NULL;
72         rc = tx->tx_status;
73
74         if (tx->tx_conn != NULL) {
75                 kiblnd_conn_decref(tx->tx_conn);
76                 tx->tx_conn = NULL;
77         }
78
79         tx->tx_nwrq = tx->tx_nsge = 0;
80         tx->tx_status = 0;
81
82         kiblnd_pool_free_node(&tx->tx_pool->tpo_pool, &tx->tx_list);
83
84         /* delay finalize until my descs have been freed */
85         for (i = 0; i < 2; i++) {
86                 if (lntmsg[i] == NULL)
87                         continue;
88
89                 /* propagate health status to LNet for requests */
90                 if (i == 0 && lntmsg[i])
91                         lntmsg[i]->msg_health_status = tx->tx_hstatus;
92
93                 lnet_finalize(lntmsg[i], rc);
94         }
95 }
96
97 void
98 kiblnd_txlist_done(struct list_head *txlist, int status,
99                    enum lnet_msg_hstatus hstatus)
100 {
101         struct kib_tx *tx;
102
103         while (!list_empty(txlist)) {
104                 tx = list_entry(txlist->next, struct kib_tx, tx_list);
105
106                 list_del(&tx->tx_list);
107                 /* complete now */
108                 tx->tx_waiting = 0;
109                 tx->tx_status = status;
110                 if (hstatus != LNET_MSG_STATUS_OK)
111                         tx->tx_hstatus = hstatus;
112                 kiblnd_tx_done(tx);
113         }
114 }
115
116 static struct kib_tx *
117 kiblnd_get_idle_tx(struct lnet_ni *ni, lnet_nid_t target)
118 {
119         struct kib_net *net = ni->ni_data;
120         struct list_head *node;
121         struct kib_tx *tx;
122         struct kib_tx_poolset *tps;
123
124         tps = net->ibn_tx_ps[lnet_cpt_of_nid(target, ni)];
125         node = kiblnd_pool_alloc_node(&tps->tps_poolset);
126         if (node == NULL)
127                 return NULL;
128         tx = container_of(node, struct kib_tx, tx_list);
129
130         LASSERT (tx->tx_nwrq == 0);
131         LASSERT (!tx->tx_queued);
132         LASSERT (tx->tx_sending == 0);
133         LASSERT (!tx->tx_waiting);
134         LASSERT (tx->tx_status == 0);
135         LASSERT (tx->tx_conn == NULL);
136         LASSERT (tx->tx_lntmsg[0] == NULL);
137         LASSERT (tx->tx_lntmsg[1] == NULL);
138         LASSERT (tx->tx_nfrags == 0);
139
140         tx->tx_gaps = false;
141         tx->tx_hstatus = LNET_MSG_STATUS_OK;
142
143         return tx;
144 }
145
146 static void
147 kiblnd_drop_rx(struct kib_rx *rx)
148 {
149         struct kib_conn *conn = rx->rx_conn;
150         struct kib_sched_info *sched = conn->ibc_sched;
151         unsigned long flags;
152
153         spin_lock_irqsave(&sched->ibs_lock, flags);
154         LASSERT(conn->ibc_nrx > 0);
155         conn->ibc_nrx--;
156         spin_unlock_irqrestore(&sched->ibs_lock, flags);
157
158         kiblnd_conn_decref(conn);
159 }
160
161 int
162 kiblnd_post_rx(struct kib_rx *rx, int credit)
163 {
164         struct kib_conn *conn = rx->rx_conn;
165         struct kib_net *net = conn->ibc_peer->ibp_ni->ni_data;
166         struct ib_recv_wr *bad_wrq = NULL;
167 #ifdef HAVE_IB_GET_DMA_MR
168         struct ib_mr *mr = conn->ibc_hdev->ibh_mrs;
169 #endif
170         int rc;
171
172         LASSERT (net != NULL);
173         LASSERT (!in_interrupt());
174         LASSERT (credit == IBLND_POSTRX_NO_CREDIT ||
175                  credit == IBLND_POSTRX_PEER_CREDIT ||
176                  credit == IBLND_POSTRX_RSRVD_CREDIT);
177 #ifdef HAVE_IB_GET_DMA_MR
178         LASSERT(mr != NULL);
179
180         rx->rx_sge.lkey   = mr->lkey;
181 #else
182         rx->rx_sge.lkey   = conn->ibc_hdev->ibh_pd->local_dma_lkey;
183 #endif
184         rx->rx_sge.addr   = rx->rx_msgaddr;
185         rx->rx_sge.length = IBLND_MSG_SIZE;
186
187         rx->rx_wrq.next = NULL;
188         rx->rx_wrq.sg_list = &rx->rx_sge;
189         rx->rx_wrq.num_sge = 1;
190         rx->rx_wrq.wr_id = kiblnd_ptr2wreqid(rx, IBLND_WID_RX);
191
192         LASSERT (conn->ibc_state >= IBLND_CONN_INIT);
193         LASSERT (rx->rx_nob >= 0);              /* not posted */
194
195         if (conn->ibc_state > IBLND_CONN_ESTABLISHED) {
196                 kiblnd_drop_rx(rx);             /* No more posts for this rx */
197                 return 0;
198         }
199
200         rx->rx_nob = -1;                        /* flag posted */
201
202         /* NB: need an extra reference after ib_post_recv because we don't
203          * own this rx (and rx::rx_conn) anymore, LU-5678.
204          */
205         kiblnd_conn_addref(conn);
206 #ifdef HAVE_IB_POST_SEND_RECV_CONST
207         rc = ib_post_recv(conn->ibc_cmid->qp, &rx->rx_wrq,
208                           (const struct ib_recv_wr **)&bad_wrq);
209 #else
210         rc = ib_post_recv(conn->ibc_cmid->qp, &rx->rx_wrq, &bad_wrq);
211 #endif
212         if (unlikely(rc != 0)) {
213                 CERROR("Can't post rx for %s: %d, bad_wrq: %p\n",
214                        libcfs_nid2str(conn->ibc_peer->ibp_nid), rc, bad_wrq);
215                 rx->rx_nob = 0;
216         }
217
218         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) /* Initial post */
219                 goto out;
220
221         if (unlikely(rc != 0)) {
222                 kiblnd_close_conn(conn, rc);
223                 kiblnd_drop_rx(rx);     /* No more posts for this rx */
224                 goto out;
225         }
226
227         if (credit == IBLND_POSTRX_NO_CREDIT)
228                 goto out;
229
230         spin_lock(&conn->ibc_lock);
231         if (credit == IBLND_POSTRX_PEER_CREDIT)
232                 conn->ibc_outstanding_credits++;
233         else
234                 conn->ibc_reserved_credits++;
235         kiblnd_check_sends_locked(conn);
236         spin_unlock(&conn->ibc_lock);
237
238 out:
239         kiblnd_conn_decref(conn);
240         return rc;
241 }
242
243 static struct kib_tx *
244 kiblnd_find_waiting_tx_locked(struct kib_conn *conn, int txtype, u64 cookie)
245 {
246         struct list_head *tmp;
247
248         list_for_each(tmp, &conn->ibc_active_txs) {
249                 struct kib_tx *tx = list_entry(tmp, struct kib_tx, tx_list);
250
251                 LASSERT(!tx->tx_queued);
252                 LASSERT(tx->tx_sending != 0 || tx->tx_waiting);
253
254                 if (tx->tx_cookie != cookie)
255                         continue;
256
257                 if (tx->tx_waiting &&
258                     tx->tx_msg->ibm_type == txtype)
259                         return tx;
260
261                 CWARN("Bad completion: %swaiting, type %x (wanted %x)\n",
262                       tx->tx_waiting ? "" : "NOT ",
263                       tx->tx_msg->ibm_type, txtype);
264         }
265         return NULL;
266 }
267
268 static void
269 kiblnd_handle_completion(struct kib_conn *conn, int txtype, int status, u64 cookie)
270 {
271         struct kib_tx *tx;
272         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
273         int idle;
274
275         spin_lock(&conn->ibc_lock);
276
277         tx = kiblnd_find_waiting_tx_locked(conn, txtype, cookie);
278         if (tx == NULL) {
279                 spin_unlock(&conn->ibc_lock);
280
281                 CWARN("Unmatched completion type %x cookie %#llx from %s\n",
282                       txtype, cookie, libcfs_nid2str(conn->ibc_peer->ibp_nid));
283                 kiblnd_close_conn(conn, -EPROTO);
284                 return;
285         }
286
287         if (tx->tx_status == 0) {               /* success so far */
288                 if (status < 0) {               /* failed? */
289                         tx->tx_status = status;
290                         tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
291                 } else if (txtype == IBLND_MSG_GET_REQ) {
292                         lnet_set_reply_msg_len(ni, tx->tx_lntmsg[1], status);
293                 }
294         }
295
296         tx->tx_waiting = 0;
297
298         idle = !tx->tx_queued && (tx->tx_sending == 0);
299         if (idle)
300                 list_del(&tx->tx_list);
301
302         spin_unlock(&conn->ibc_lock);
303
304         if (idle)
305                 kiblnd_tx_done(tx);
306 }
307
308 static void
309 kiblnd_send_completion(struct kib_conn *conn, int type, int status, u64 cookie)
310 {
311         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
312         struct kib_tx *tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
313
314         if (tx == NULL) {
315                 CERROR("Can't get tx for completion %x for %s\n",
316                        type, libcfs_nid2str(conn->ibc_peer->ibp_nid));
317                 return;
318         }
319
320         tx->tx_msg->ibm_u.completion.ibcm_status = status;
321         tx->tx_msg->ibm_u.completion.ibcm_cookie = cookie;
322         kiblnd_init_tx_msg(ni, tx, type, sizeof(struct kib_completion_msg));
323
324         kiblnd_queue_tx(tx, conn);
325 }
326
327 static void
328 kiblnd_handle_rx(struct kib_rx *rx)
329 {
330         struct kib_msg *msg = rx->rx_msg;
331         struct kib_conn   *conn = rx->rx_conn;
332         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
333         int           credits = msg->ibm_credits;
334         struct kib_tx *tx;
335         int           rc = 0;
336         int           rc2;
337         int           post_credit;
338
339         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
340
341         CDEBUG (D_NET, "Received %x[%d] from %s\n",
342                 msg->ibm_type, credits,
343                 libcfs_nid2str(conn->ibc_peer->ibp_nid));
344
345         if (credits != 0) {
346                 /* Have I received credits that will let me send? */
347                 spin_lock(&conn->ibc_lock);
348
349                 if (conn->ibc_credits + credits >
350                     conn->ibc_queue_depth) {
351                         rc2 = conn->ibc_credits;
352                         spin_unlock(&conn->ibc_lock);
353
354                         CERROR("Bad credits from %s: %d + %d > %d\n",
355                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
356                                rc2, credits,
357                                conn->ibc_queue_depth);
358
359                         kiblnd_close_conn(conn, -EPROTO);
360                         kiblnd_post_rx(rx, IBLND_POSTRX_NO_CREDIT);
361                         return;
362                 }
363
364                 conn->ibc_credits += credits;
365
366                 /* This ensures the credit taken by NOOP can be returned */
367                 if (msg->ibm_type == IBLND_MSG_NOOP &&
368                     !IBLND_OOB_CAPABLE(conn->ibc_version)) /* v1 only */
369                         conn->ibc_outstanding_credits++;
370
371                 kiblnd_check_sends_locked(conn);
372                 spin_unlock(&conn->ibc_lock);
373         }
374
375         switch (msg->ibm_type) {
376         default:
377                 CERROR("Bad IBLND message type %x from %s\n",
378                        msg->ibm_type, libcfs_nid2str(conn->ibc_peer->ibp_nid));
379                 post_credit = IBLND_POSTRX_NO_CREDIT;
380                 rc = -EPROTO;
381                 break;
382
383         case IBLND_MSG_NOOP:
384                 if (IBLND_OOB_CAPABLE(conn->ibc_version)) {
385                         post_credit = IBLND_POSTRX_NO_CREDIT;
386                         break;
387                 }
388
389                 if (credits != 0) /* credit already posted */
390                         post_credit = IBLND_POSTRX_NO_CREDIT;
391                 else              /* a keepalive NOOP */
392                         post_credit = IBLND_POSTRX_PEER_CREDIT;
393                 break;
394
395         case IBLND_MSG_IMMEDIATE:
396                 post_credit = IBLND_POSTRX_DONT_POST;
397                 rc = lnet_parse(ni, &msg->ibm_u.immediate.ibim_hdr,
398                                 msg->ibm_srcnid, rx, 0);
399                 if (rc < 0)                     /* repost on error */
400                         post_credit = IBLND_POSTRX_PEER_CREDIT;
401                 break;
402
403         case IBLND_MSG_PUT_REQ:
404                 post_credit = IBLND_POSTRX_DONT_POST;
405                 rc = lnet_parse(ni, &msg->ibm_u.putreq.ibprm_hdr,
406                                 msg->ibm_srcnid, rx, 1);
407                 if (rc < 0)                     /* repost on error */
408                         post_credit = IBLND_POSTRX_PEER_CREDIT;
409                 break;
410
411         case IBLND_MSG_PUT_NAK:
412                 CWARN ("PUT_NACK from %s\n",
413                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
414                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
415                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_REQ,
416                                          msg->ibm_u.completion.ibcm_status,
417                                          msg->ibm_u.completion.ibcm_cookie);
418                 break;
419
420         case IBLND_MSG_PUT_ACK:
421                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
422
423                 spin_lock(&conn->ibc_lock);
424                 tx = kiblnd_find_waiting_tx_locked(conn, IBLND_MSG_PUT_REQ,
425                                         msg->ibm_u.putack.ibpam_src_cookie);
426                 if (tx != NULL)
427                         list_del(&tx->tx_list);
428                 spin_unlock(&conn->ibc_lock);
429
430                 if (tx == NULL) {
431                         CERROR("Unmatched PUT_ACK from %s\n",
432                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
433                         rc = -EPROTO;
434                         break;
435                 }
436
437                 LASSERT (tx->tx_waiting);
438                 /* CAVEAT EMPTOR: I could be racing with tx_complete, but...
439                  * (a) I can overwrite tx_msg since my peer_ni has received it!
440                  * (b) tx_waiting set tells tx_complete() it's not done. */
441
442                 tx->tx_nwrq = tx->tx_nsge = 0;  /* overwrite PUT_REQ */
443
444                 rc2 = kiblnd_init_rdma(conn, tx, IBLND_MSG_PUT_DONE,
445                                        kiblnd_rd_size(&msg->ibm_u.putack.ibpam_rd),
446                                        &msg->ibm_u.putack.ibpam_rd,
447                                        msg->ibm_u.putack.ibpam_dst_cookie);
448                 if (rc2 < 0)
449                         CERROR("Can't setup rdma for PUT to %s: %d\n",
450                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc2);
451
452                 spin_lock(&conn->ibc_lock);
453                 tx->tx_waiting = 0;     /* clear waiting and queue atomically */
454                 kiblnd_queue_tx_locked(tx, conn);
455                 spin_unlock(&conn->ibc_lock);
456                 break;
457
458         case IBLND_MSG_PUT_DONE:
459                 post_credit = IBLND_POSTRX_PEER_CREDIT;
460                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_ACK,
461                                          msg->ibm_u.completion.ibcm_status,
462                                          msg->ibm_u.completion.ibcm_cookie);
463                 break;
464
465         case IBLND_MSG_GET_REQ:
466                 post_credit = IBLND_POSTRX_DONT_POST;
467                 rc = lnet_parse(ni, &msg->ibm_u.get.ibgm_hdr,
468                                 msg->ibm_srcnid, rx, 1);
469                 if (rc < 0)                     /* repost on error */
470                         post_credit = IBLND_POSTRX_PEER_CREDIT;
471                 break;
472
473         case IBLND_MSG_GET_DONE:
474                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
475                 kiblnd_handle_completion(conn, IBLND_MSG_GET_REQ,
476                                          msg->ibm_u.completion.ibcm_status,
477                                          msg->ibm_u.completion.ibcm_cookie);
478                 break;
479         }
480
481         if (rc < 0)                             /* protocol error */
482                 kiblnd_close_conn(conn, rc);
483
484         if (post_credit != IBLND_POSTRX_DONT_POST)
485                 kiblnd_post_rx(rx, post_credit);
486 }
487
488 static void
489 kiblnd_rx_complete(struct kib_rx *rx, int status, int nob)
490 {
491         struct kib_msg *msg = rx->rx_msg;
492         struct kib_conn   *conn = rx->rx_conn;
493         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
494         struct kib_net *net = ni->ni_data;
495         int rc;
496         int err = -EIO;
497
498         LASSERT (net != NULL);
499         LASSERT (rx->rx_nob < 0);               /* was posted */
500         rx->rx_nob = 0;                         /* isn't now */
501
502         if (conn->ibc_state > IBLND_CONN_ESTABLISHED)
503                 goto ignore;
504
505         if (status != IB_WC_SUCCESS) {
506                 CNETERR("Rx from %s failed: %d\n",
507                         libcfs_nid2str(conn->ibc_peer->ibp_nid), status);
508                 goto failed;
509         }
510
511         LASSERT (nob >= 0);
512         rx->rx_nob = nob;
513
514         rc = kiblnd_unpack_msg(msg, rx->rx_nob);
515         if (rc != 0) {
516                 CERROR ("Error %d unpacking rx from %s\n",
517                         rc, libcfs_nid2str(conn->ibc_peer->ibp_nid));
518                 goto failed;
519         }
520
521         if (msg->ibm_srcnid != conn->ibc_peer->ibp_nid ||
522             msg->ibm_dstnid != ni->ni_nid ||
523             msg->ibm_srcstamp != conn->ibc_incarnation ||
524             msg->ibm_dststamp != net->ibn_incarnation) {
525                 CERROR ("Stale rx from %s\n",
526                         libcfs_nid2str(conn->ibc_peer->ibp_nid));
527                 err = -ESTALE;
528                 goto failed;
529         }
530
531         /* set time last known alive */
532         kiblnd_peer_alive(conn->ibc_peer);
533
534         /* racing with connection establishment/teardown! */
535
536         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
537                 rwlock_t  *g_lock = &kiblnd_data.kib_global_lock;
538                 unsigned long  flags;
539
540                 write_lock_irqsave(g_lock, flags);
541                 /* must check holding global lock to eliminate race */
542                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
543                         list_add_tail(&rx->rx_list, &conn->ibc_early_rxs);
544                         write_unlock_irqrestore(g_lock, flags);
545                         return;
546                 }
547                 write_unlock_irqrestore(g_lock, flags);
548         }
549         kiblnd_handle_rx(rx);
550         return;
551
552  failed:
553         CDEBUG(D_NET, "rx %p conn %p\n", rx, conn);
554         kiblnd_close_conn(conn, err);
555  ignore:
556         kiblnd_drop_rx(rx);                     /* Don't re-post rx. */
557 }
558
559 static int
560 kiblnd_fmr_map_tx(struct kib_net *net, struct kib_tx *tx,
561                   struct kib_rdma_desc *rd, u32 nob)
562 {
563         struct kib_hca_dev *hdev;
564         struct kib_dev *dev;
565         struct kib_fmr_poolset *fps;
566         int                     cpt;
567         int                     rc;
568         int i;
569
570         LASSERT(tx->tx_pool != NULL);
571         LASSERT(tx->tx_pool->tpo_pool.po_owner != NULL);
572
573         dev = net->ibn_dev;
574         hdev = tx->tx_pool->tpo_hdev;
575         cpt = tx->tx_pool->tpo_pool.po_owner->ps_cpt;
576
577         /*
578          * If we're dealing with FastReg, but the device doesn't
579          * support GAPS and the tx has GAPS, then there is no real point
580          * in trying to map the memory, because it'll just fail. So
581          * preemptively fail with an appropriate message
582          */
583         if ((dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED) &&
584             !(dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT) &&
585             tx->tx_gaps) {
586                 CERROR("Using FastReg with no GAPS support, but tx has gaps. "
587                        "Try setting use_fastreg_gaps to 1\n");
588                 return -EPROTONOSUPPORT;
589         }
590
591         /*
592          * FMR does not support gaps but the tx has gaps then
593          * we should make sure that the number of fragments we'll be sending
594          * over fits within the number of fragments negotiated on the
595          * connection, otherwise, we won't be able to RDMA the data.
596          * We need to maintain the number of fragments negotiation on the
597          * connection for backwards compatibility.
598          */
599         if (tx->tx_gaps && (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)) {
600                 if (tx->tx_conn &&
601                     tx->tx_conn->ibc_max_frags <= rd->rd_nfrags) {
602                         CERROR("TX number of frags (%d) is <= than connection"
603                                " number of frags (%d). Consider setting peer's"
604                                " map_on_demand to 256\n", tx->tx_nfrags,
605                                tx->tx_conn->ibc_max_frags);
606                         return -EFBIG;
607                 }
608         }
609
610         fps = net->ibn_fmr_ps[cpt];
611         rc = kiblnd_fmr_pool_map(fps, tx, rd, nob, 0, &tx->tx_fmr);
612         if (rc != 0) {
613                 CERROR("Can't map %u pages: %d\n", nob, rc);
614                 return rc;
615         }
616
617         /*
618          * If rd is not tx_rd, it's going to get sent to a peer_ni, who will
619          * need the rkey
620          */
621         rd->rd_key = tx->tx_fmr.fmr_key;
622         /*
623          * for FastReg or FMR with no gaps we can accumulate all
624          * the fragments in one FastReg or FMR fragment.
625          */
626         if (((dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED) && !tx->tx_gaps) ||
627             (dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED)) {
628                 /* FMR requires zero based address */
629                 if (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)
630                         rd->rd_frags[0].rf_addr &= ~hdev->ibh_page_mask;
631                 rd->rd_frags[0].rf_nob = nob;
632                 rd->rd_nfrags = 1;
633         } else {
634                 /*
635                  * We're transmitting with gaps using FMR.
636                  * We'll need to use multiple fragments and identify the
637                  * zero based address of each fragment.
638                  */
639                 for (i = 0; i < rd->rd_nfrags; i++) {
640                         rd->rd_frags[i].rf_addr &= ~hdev->ibh_page_mask;
641                         rd->rd_frags[i].rf_addr += i << hdev->ibh_page_shift;
642                 }
643         }
644
645         return 0;
646 }
647
648 static void
649 kiblnd_unmap_tx(struct kib_tx *tx)
650 {
651         if (tx->tx_fmr.fmr_pfmr || tx->tx_fmr.fmr_frd)
652                 kiblnd_fmr_pool_unmap(&tx->tx_fmr, tx->tx_status);
653
654         if (tx->tx_nfrags != 0) {
655                 kiblnd_dma_unmap_sg(tx->tx_pool->tpo_hdev->ibh_ibdev,
656                                     tx->tx_frags, tx->tx_nfrags, tx->tx_dmadir);
657                 tx->tx_nfrags = 0;
658         }
659 }
660
661 #ifdef HAVE_IB_GET_DMA_MR
662 static struct ib_mr *
663 kiblnd_find_rd_dma_mr(struct lnet_ni *ni, struct kib_rdma_desc *rd)
664 {
665         struct kib_net *net = ni->ni_data;
666         struct kib_hca_dev *hdev = net->ibn_dev->ibd_hdev;
667         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
668
669         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
670
671         /*
672          * if map-on-demand is turned on and the device supports
673          * either FMR or FastReg then use that. Otherwise use global
674          * memory regions. If that's not available either, then you're
675          * dead in the water and fail the operation.
676          */
677         if (tunables->lnd_map_on_demand &&
678             (net->ibn_dev->ibd_dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED ||
679              net->ibn_dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED))
680                 return NULL;
681
682         /*
683          * hdev->ibh_mrs can be NULL. This case is dealt with gracefully
684          * in the call chain. The mapping will fail with appropriate error
685          * message.
686          */
687         return hdev->ibh_mrs;
688 }
689 #endif
690
691 static int kiblnd_map_tx(struct lnet_ni *ni, struct kib_tx *tx,
692                          struct kib_rdma_desc *rd, int nfrags)
693 {
694         struct kib_net *net = ni->ni_data;
695         struct kib_hca_dev *hdev = net->ibn_dev->ibd_hdev;
696 #ifdef HAVE_IB_GET_DMA_MR
697         struct ib_mr *mr = NULL;
698 #endif
699         __u32 nob;
700         int i;
701
702         /* If rd is not tx_rd, it's going to get sent to a peer_ni and I'm the
703          * RDMA sink */
704         tx->tx_dmadir = (rd != tx->tx_rd) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
705         tx->tx_nfrags = nfrags;
706
707         rd->rd_nfrags = kiblnd_dma_map_sg(hdev->ibh_ibdev, tx->tx_frags,
708                                           tx->tx_nfrags, tx->tx_dmadir);
709
710         for (i = 0, nob = 0; i < rd->rd_nfrags; i++) {
711                 rd->rd_frags[i].rf_nob  = kiblnd_sg_dma_len(
712                         hdev->ibh_ibdev, &tx->tx_frags[i]);
713                 rd->rd_frags[i].rf_addr = kiblnd_sg_dma_address(
714                         hdev->ibh_ibdev, &tx->tx_frags[i]);
715                 nob += rd->rd_frags[i].rf_nob;
716         }
717
718 #ifdef HAVE_IB_GET_DMA_MR
719         mr = kiblnd_find_rd_dma_mr(ni, rd);
720         if (mr != NULL) {
721                 /* found pre-mapping MR */
722                 rd->rd_key = (rd != tx->tx_rd) ? mr->rkey : mr->lkey;
723                 return 0;
724         }
725 #endif
726
727         if (net->ibn_fmr_ps != NULL)
728                 return kiblnd_fmr_map_tx(net, tx, rd, nob);
729
730         return -EINVAL;
731 }
732
733 static int kiblnd_setup_rd_iov(struct lnet_ni *ni, struct kib_tx *tx,
734                                struct kib_rdma_desc *rd, unsigned int niov,
735                                struct kvec *iov, int offset, int nob)
736 {
737         struct kib_net *net = ni->ni_data;
738         struct page *page;
739         struct scatterlist *sg;
740         unsigned long       vaddr;
741         int                 fragnob;
742         int                 page_offset;
743         unsigned int        max_niov;
744
745         LASSERT (nob > 0);
746         LASSERT (niov > 0);
747         LASSERT (net != NULL);
748
749         while (offset >= iov->iov_len) {
750                 offset -= iov->iov_len;
751                 niov--;
752                 iov++;
753                 LASSERT (niov > 0);
754         }
755
756         max_niov = niov;
757
758         sg = tx->tx_frags;
759         do {
760                 LASSERT(niov > 0);
761
762                 vaddr = ((unsigned long)iov->iov_base) + offset;
763                 page_offset = vaddr & (PAGE_SIZE - 1);
764                 page = lnet_kvaddr_to_page(vaddr);
765                 if (page == NULL) {
766                         CERROR("Can't find page\n");
767                         return -EFAULT;
768                 }
769
770                 fragnob = min((int)(iov->iov_len - offset), nob);
771                 fragnob = min(fragnob, (int)PAGE_SIZE - page_offset);
772
773                 /*
774                  * We're allowed to start at a non-aligned page offset in
775                  * the first fragment and end at a non-aligned page offset
776                  * in the last fragment.
777                  */
778                 if ((fragnob < (int)PAGE_SIZE - page_offset) &&
779                     (niov < max_niov) && nob > fragnob) {
780                         CDEBUG(D_NET, "fragnob %d < available page %d: with"
781                                       " remaining %d iovs with %d nob left\n",
782                                fragnob, (int)PAGE_SIZE - page_offset, niov,
783                                nob);
784                         tx->tx_gaps = true;
785                 }
786
787                 sg_set_page(sg, page, fragnob, page_offset);
788                 sg = sg_next(sg);
789                 if (!sg) {
790                         CERROR("lacking enough sg entries to map tx\n");
791                         return -EFAULT;
792                 }
793
794                 if (offset + fragnob < iov->iov_len) {
795                         offset += fragnob;
796                 } else {
797                         offset = 0;
798                         iov++;
799                         niov--;
800                 }
801                 nob -= fragnob;
802         } while (nob > 0);
803
804         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
805 }
806
807 static int kiblnd_setup_rd_kiov(struct lnet_ni *ni, struct kib_tx *tx,
808                                 struct kib_rdma_desc *rd, int nkiov,
809                                 lnet_kiov_t *kiov, int offset, int nob)
810 {
811         struct kib_net *net = ni->ni_data;
812         struct scatterlist *sg;
813         int                 fragnob;
814         int                 max_nkiov;
815
816         CDEBUG(D_NET, "niov %d offset %d nob %d\n", nkiov, offset, nob);
817
818         LASSERT(nob > 0);
819         LASSERT(nkiov > 0);
820         LASSERT(net != NULL);
821
822         while (offset >= kiov->kiov_len) {
823                 offset -= kiov->kiov_len;
824                 nkiov--;
825                 kiov++;
826                 LASSERT(nkiov > 0);
827         }
828
829         max_nkiov = nkiov;
830
831         sg = tx->tx_frags;
832         do {
833                 LASSERT(nkiov > 0);
834
835                 fragnob = min((int)(kiov->kiov_len - offset), nob);
836
837                 /*
838                  * We're allowed to start at a non-aligned page offset in
839                  * the first fragment and end at a non-aligned page offset
840                  * in the last fragment.
841                  */
842                 if ((fragnob < (int)(kiov->kiov_len - offset)) &&
843                     nkiov < max_nkiov && nob > fragnob) {
844                         CDEBUG(D_NET, "fragnob %d < available page %d: with"
845                                       " remaining %d kiovs with %d nob left\n",
846                                fragnob, (int)(kiov->kiov_len - offset),
847                                nkiov, nob);
848                         tx->tx_gaps = true;
849                 }
850
851                 sg_set_page(sg, kiov->kiov_page, fragnob,
852                             kiov->kiov_offset + offset);
853                 sg = sg_next(sg);
854                 if (!sg) {
855                         CERROR("lacking enough sg entries to map tx\n");
856                         return -EFAULT;
857                 }
858
859                 offset = 0;
860                 kiov++;
861                 nkiov--;
862                 nob -= fragnob;
863         } while (nob > 0);
864
865         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
866 }
867
868 static int
869 kiblnd_post_tx_locked(struct kib_conn *conn, struct kib_tx *tx, int credit)
870 __must_hold(&conn->ibc_lock)
871 {
872         struct kib_msg *msg = tx->tx_msg;
873         struct kib_peer_ni *peer_ni = conn->ibc_peer;
874         struct lnet_ni *ni = peer_ni->ibp_ni;
875         int ver = conn->ibc_version;
876         int rc;
877         int done;
878
879         LASSERT(tx->tx_queued);
880         /* We rely on this for QP sizing */
881         LASSERT(tx->tx_nwrq > 0 && tx->tx_nsge >= 0);
882         LASSERT(tx->tx_nwrq <= 1 + conn->ibc_max_frags);
883
884         LASSERT(credit == 0 || credit == 1);
885         LASSERT(conn->ibc_outstanding_credits >= 0);
886         LASSERT(conn->ibc_outstanding_credits <= conn->ibc_queue_depth);
887         LASSERT(conn->ibc_credits >= 0);
888         LASSERT(conn->ibc_credits <= conn->ibc_queue_depth);
889
890         if (conn->ibc_nsends_posted ==
891             kiblnd_concurrent_sends(ver, ni)) {
892                 /* tx completions outstanding... */
893                 CDEBUG(D_NET, "%s: posted enough\n",
894                        libcfs_nid2str(peer_ni->ibp_nid));
895                 return -EAGAIN;
896         }
897
898         if (credit != 0 && conn->ibc_credits == 0) {   /* no credits */
899                 CDEBUG(D_NET, "%s: no credits\n",
900                        libcfs_nid2str(peer_ni->ibp_nid));
901                 return -EAGAIN;
902         }
903
904         if (credit != 0 && !IBLND_OOB_CAPABLE(ver) &&
905             conn->ibc_credits == 1 &&   /* last credit reserved */
906             msg->ibm_type != IBLND_MSG_NOOP) {      /* for NOOP */
907                 CDEBUG(D_NET, "%s: not using last credit\n",
908                        libcfs_nid2str(peer_ni->ibp_nid));
909                 return -EAGAIN;
910         }
911
912         /* NB don't drop ibc_lock before bumping tx_sending */
913         list_del(&tx->tx_list);
914         tx->tx_queued = 0;
915
916         if (msg->ibm_type == IBLND_MSG_NOOP &&
917             (!kiblnd_need_noop(conn) ||     /* redundant NOOP */
918              (IBLND_OOB_CAPABLE(ver) && /* posted enough NOOP */
919               conn->ibc_noops_posted == IBLND_OOB_MSGS(ver)))) {
920                 /* OK to drop when posted enough NOOPs, since
921                  * kiblnd_check_sends_locked will queue NOOP again when
922                  * posted NOOPs complete */
923                 spin_unlock(&conn->ibc_lock);
924                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
925                 kiblnd_tx_done(tx);
926                 spin_lock(&conn->ibc_lock);
927                 CDEBUG(D_NET, "%s(%d): redundant or enough NOOP\n",
928                        libcfs_nid2str(peer_ni->ibp_nid),
929                        conn->ibc_noops_posted);
930                 return 0;
931         }
932
933         kiblnd_pack_msg(peer_ni->ibp_ni, msg, ver, conn->ibc_outstanding_credits,
934                         peer_ni->ibp_nid, conn->ibc_incarnation);
935
936         conn->ibc_credits -= credit;
937         conn->ibc_outstanding_credits = 0;
938         conn->ibc_nsends_posted++;
939         if (msg->ibm_type == IBLND_MSG_NOOP)
940                 conn->ibc_noops_posted++;
941
942         /* CAVEAT EMPTOR!  This tx could be the PUT_DONE of an RDMA
943          * PUT.  If so, it was first queued here as a PUT_REQ, sent and
944          * stashed on ibc_active_txs, matched by an incoming PUT_ACK,
945          * and then re-queued here.  It's (just) possible that
946          * tx_sending is non-zero if we've not done the tx_complete()
947          * from the first send; hence the ++ rather than = below. */
948         tx->tx_sending++;
949         list_add(&tx->tx_list, &conn->ibc_active_txs);
950
951         /* I'm still holding ibc_lock! */
952         if (conn->ibc_state != IBLND_CONN_ESTABLISHED) {
953                 rc = -ECONNABORTED;
954         } else if (tx->tx_pool->tpo_pool.po_failed ||
955                  conn->ibc_hdev != tx->tx_pool->tpo_hdev) {
956                 /* close_conn will launch failover */
957                 rc = -ENETDOWN;
958         } else {
959                 struct kib_fast_reg_descriptor *frd = tx->tx_fmr.fmr_frd;
960                 struct ib_send_wr *bad = &tx->tx_wrq[tx->tx_nwrq - 1].wr;
961                 struct ib_send_wr *wr  = &tx->tx_wrq[0].wr;
962
963                 if (frd != NULL) {
964                         if (!frd->frd_valid) {
965                                 wr = &frd->frd_inv_wr.wr;
966                                 wr->next = &frd->frd_fastreg_wr.wr;
967                         } else {
968                                 wr = &frd->frd_fastreg_wr.wr;
969                         }
970                         frd->frd_fastreg_wr.wr.next = &tx->tx_wrq[0].wr;
971                 }
972
973                 LASSERTF(bad->wr_id == kiblnd_ptr2wreqid(tx, IBLND_WID_TX),
974                          "bad wr_id %#llx, opc %d, flags %d, peer_ni: %s\n",
975                          bad->wr_id, bad->opcode, bad->send_flags,
976                          libcfs_nid2str(conn->ibc_peer->ibp_nid));
977
978                 bad = NULL;
979                 if (lnet_send_error_simulation(tx->tx_lntmsg[0], &tx->tx_hstatus))
980                         rc = -EINVAL;
981                 else
982 #ifdef HAVE_IB_POST_SEND_RECV_CONST
983                         rc = ib_post_send(conn->ibc_cmid->qp, wr,
984                                           (const struct ib_send_wr **)&bad);
985 #else
986                         rc = ib_post_send(conn->ibc_cmid->qp, wr, &bad);
987 #endif
988         }
989
990         conn->ibc_last_send = ktime_get();
991
992         if (rc == 0)
993                 return 0;
994
995         /* NB credits are transferred in the actual
996          * message, which can only be the last work item */
997         conn->ibc_credits += credit;
998         conn->ibc_outstanding_credits += msg->ibm_credits;
999         conn->ibc_nsends_posted--;
1000         if (msg->ibm_type == IBLND_MSG_NOOP)
1001                 conn->ibc_noops_posted--;
1002
1003         tx->tx_status = rc;
1004         tx->tx_waiting = 0;
1005         tx->tx_sending--;
1006
1007         done = (tx->tx_sending == 0);
1008         if (done)
1009                 list_del(&tx->tx_list);
1010
1011         spin_unlock(&conn->ibc_lock);
1012
1013         if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1014                 CERROR("Error %d posting transmit to %s\n",
1015                        rc, libcfs_nid2str(peer_ni->ibp_nid));
1016         else
1017                 CDEBUG(D_NET, "Error %d posting transmit to %s\n",
1018                        rc, libcfs_nid2str(peer_ni->ibp_nid));
1019
1020         kiblnd_close_conn(conn, rc);
1021
1022         if (done)
1023                 kiblnd_tx_done(tx);
1024
1025         spin_lock(&conn->ibc_lock);
1026
1027         return -EIO;
1028 }
1029
1030 static void
1031 kiblnd_check_sends_locked(struct kib_conn *conn)
1032 {
1033         int ver = conn->ibc_version;
1034         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
1035         struct kib_tx *tx;
1036
1037         /* Don't send anything until after the connection is established */
1038         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
1039                 CDEBUG(D_NET, "%s too soon\n",
1040                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
1041                 return;
1042         }
1043
1044         LASSERT(conn->ibc_nsends_posted <=
1045                 kiblnd_concurrent_sends(ver, ni));
1046         LASSERT (!IBLND_OOB_CAPABLE(ver) ||
1047                  conn->ibc_noops_posted <= IBLND_OOB_MSGS(ver));
1048         LASSERT (conn->ibc_reserved_credits >= 0);
1049
1050         while (conn->ibc_reserved_credits > 0 &&
1051                !list_empty(&conn->ibc_tx_queue_rsrvd)) {
1052                 tx = list_entry(conn->ibc_tx_queue_rsrvd.next,
1053                                 struct kib_tx, tx_list);
1054                 list_del(&tx->tx_list);
1055                 list_add_tail(&tx->tx_list, &conn->ibc_tx_queue);
1056                 conn->ibc_reserved_credits--;
1057         }
1058
1059         if (kiblnd_need_noop(conn)) {
1060                 spin_unlock(&conn->ibc_lock);
1061
1062                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1063                 if (tx != NULL)
1064                         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_NOOP, 0);
1065
1066                 spin_lock(&conn->ibc_lock);
1067                 if (tx != NULL)
1068                         kiblnd_queue_tx_locked(tx, conn);
1069         }
1070
1071         for (;;) {
1072                 int credit;
1073
1074                 if (!list_empty(&conn->ibc_tx_queue_nocred)) {
1075                         credit = 0;
1076                         tx = list_entry(conn->ibc_tx_queue_nocred.next,
1077                                         struct kib_tx, tx_list);
1078                 } else if (!list_empty(&conn->ibc_tx_noops)) {
1079                         LASSERT (!IBLND_OOB_CAPABLE(ver));
1080                         credit = 1;
1081                         tx = list_entry(conn->ibc_tx_noops.next,
1082                                         struct kib_tx, tx_list);
1083                 } else if (!list_empty(&conn->ibc_tx_queue)) {
1084                         credit = 1;
1085                         tx = list_entry(conn->ibc_tx_queue.next,
1086                                         struct kib_tx, tx_list);
1087                 } else
1088                         break;
1089
1090                 if (kiblnd_post_tx_locked(conn, tx, credit) != 0)
1091                         break;
1092         }
1093 }
1094
1095 static void
1096 kiblnd_tx_complete(struct kib_tx *tx, int status)
1097 {
1098         int           failed = (status != IB_WC_SUCCESS);
1099         struct kib_conn   *conn = tx->tx_conn;
1100         int           idle;
1101
1102         LASSERT (tx->tx_sending > 0);
1103
1104         if (failed) {
1105                 if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
1106                         CNETERR("Tx -> %s cookie %#llx"
1107                                 " sending %d waiting %d: failed %d\n",
1108                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
1109                                 tx->tx_cookie, tx->tx_sending, tx->tx_waiting,
1110                                 status);
1111
1112                 kiblnd_close_conn(conn, -EIO);
1113         } else {
1114                 kiblnd_peer_alive(conn->ibc_peer);
1115         }
1116
1117         spin_lock(&conn->ibc_lock);
1118
1119         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
1120          * gets to free it, which also drops its ref on 'conn'. */
1121
1122         tx->tx_sending--;
1123         conn->ibc_nsends_posted--;
1124         if (tx->tx_msg->ibm_type == IBLND_MSG_NOOP)
1125                 conn->ibc_noops_posted--;
1126
1127         if (failed) {
1128                 tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
1129                 tx->tx_waiting = 0;             /* don't wait for peer_ni */
1130                 tx->tx_status = -EIO;
1131         }
1132
1133         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
1134                !tx->tx_waiting &&               /* Not waiting for peer_ni */
1135                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
1136         if (idle)
1137                 list_del(&tx->tx_list);
1138
1139         kiblnd_check_sends_locked(conn);
1140         spin_unlock(&conn->ibc_lock);
1141
1142         if (idle)
1143                 kiblnd_tx_done(tx);
1144 }
1145
1146 static void
1147 kiblnd_init_tx_msg(struct lnet_ni *ni, struct kib_tx *tx, int type,
1148                    int body_nob)
1149 {
1150         struct kib_hca_dev *hdev = tx->tx_pool->tpo_hdev;
1151         struct ib_sge *sge = &tx->tx_msgsge;
1152         struct ib_rdma_wr *wrq;
1153         int nob = offsetof(struct kib_msg, ibm_u) + body_nob;
1154 #ifdef HAVE_IB_GET_DMA_MR
1155         struct ib_mr *mr = hdev->ibh_mrs;
1156 #endif
1157
1158         LASSERT(tx->tx_nwrq >= 0);
1159         LASSERT(tx->tx_nwrq < IBLND_MAX_RDMA_FRAGS + 1);
1160         LASSERT(nob <= IBLND_MSG_SIZE);
1161 #ifdef HAVE_IB_GET_DMA_MR
1162         LASSERT(mr != NULL);
1163 #endif
1164
1165         kiblnd_init_msg(tx->tx_msg, type, body_nob);
1166
1167 #ifdef HAVE_IB_GET_DMA_MR
1168         sge->lkey   = mr->lkey;
1169 #else
1170         sge->lkey   = hdev->ibh_pd->local_dma_lkey;
1171 #endif
1172         sge->addr   = tx->tx_msgaddr;
1173         sge->length = nob;
1174
1175         wrq = &tx->tx_wrq[tx->tx_nwrq];
1176         memset(wrq, 0, sizeof(*wrq));
1177
1178         wrq->wr.next            = NULL;
1179         wrq->wr.wr_id           = kiblnd_ptr2wreqid(tx, IBLND_WID_TX);
1180         wrq->wr.sg_list         = sge;
1181         wrq->wr.num_sge         = 1;
1182         wrq->wr.opcode          = IB_WR_SEND;
1183         wrq->wr.send_flags      = IB_SEND_SIGNALED;
1184
1185         tx->tx_nwrq++;
1186 }
1187
1188 static int
1189 kiblnd_init_rdma(struct kib_conn *conn, struct kib_tx *tx, int type,
1190                  int resid, struct kib_rdma_desc *dstrd, u64 dstcookie)
1191 {
1192         struct kib_msg *ibmsg = tx->tx_msg;
1193         struct kib_rdma_desc *srcrd = tx->tx_rd;
1194         struct ib_rdma_wr *wrq = NULL;
1195         struct ib_sge     *sge;
1196         int                rc  = resid;
1197         int                srcidx;
1198         int                dstidx;
1199         int                sge_nob;
1200         int                wrq_sge;
1201
1202         LASSERT(!in_interrupt());
1203         LASSERT(tx->tx_nwrq == 0 && tx->tx_nsge == 0);
1204         LASSERT(type == IBLND_MSG_GET_DONE || type == IBLND_MSG_PUT_DONE);
1205
1206         for (srcidx = dstidx = wrq_sge = sge_nob = 0;
1207              resid > 0; resid -= sge_nob) {
1208                 int     prev = dstidx;
1209
1210                 if (srcidx >= srcrd->rd_nfrags) {
1211                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1212                         rc = -EPROTO;
1213                         break;
1214                 }
1215
1216                 if (dstidx >= dstrd->rd_nfrags) {
1217                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1218                         rc = -EPROTO;
1219                         break;
1220                 }
1221
1222                 if (tx->tx_nwrq >= conn->ibc_max_frags) {
1223                         CERROR("RDMA has too many fragments for peer_ni %s (%d), "
1224                                "src idx/frags: %d/%d dst idx/frags: %d/%d\n",
1225                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
1226                                conn->ibc_max_frags,
1227                                srcidx, srcrd->rd_nfrags,
1228                                dstidx, dstrd->rd_nfrags);
1229                         rc = -EMSGSIZE;
1230                         break;
1231                 }
1232
1233                 sge_nob = MIN(MIN(kiblnd_rd_frag_size(srcrd, srcidx),
1234                                   kiblnd_rd_frag_size(dstrd, dstidx)), resid);
1235
1236                 sge = &tx->tx_sge[tx->tx_nsge];
1237                 sge->addr   = kiblnd_rd_frag_addr(srcrd, srcidx);
1238                 sge->lkey   = kiblnd_rd_frag_key(srcrd, srcidx);
1239                 sge->length = sge_nob;
1240
1241                 if (wrq_sge == 0) {
1242                         wrq = &tx->tx_wrq[tx->tx_nwrq];
1243
1244                         wrq->wr.next    = &(wrq + 1)->wr;
1245                         wrq->wr.wr_id   = kiblnd_ptr2wreqid(tx, IBLND_WID_RDMA);
1246                         wrq->wr.sg_list = sge;
1247                         wrq->wr.opcode  = IB_WR_RDMA_WRITE;
1248                         wrq->wr.send_flags = 0;
1249
1250 #ifdef HAVE_IB_RDMA_WR
1251                         wrq->remote_addr        = kiblnd_rd_frag_addr(dstrd,
1252                                                                       dstidx);
1253                         wrq->rkey               = kiblnd_rd_frag_key(dstrd,
1254                                                                      dstidx);
1255 #else
1256                         wrq->wr.wr.rdma.remote_addr = kiblnd_rd_frag_addr(dstrd,
1257                                                                         dstidx);
1258                         wrq->wr.wr.rdma.rkey    = kiblnd_rd_frag_key(dstrd,
1259                                                                      dstidx);
1260 #endif
1261                 }
1262
1263                 srcidx = kiblnd_rd_consume_frag(srcrd, srcidx, sge_nob);
1264                 dstidx = kiblnd_rd_consume_frag(dstrd, dstidx, sge_nob);
1265
1266                 wrq_sge++;
1267                 if (wrq_sge == *kiblnd_tunables.kib_wrq_sge || dstidx != prev) {
1268                         tx->tx_nwrq++;
1269                         wrq->wr.num_sge = wrq_sge;
1270                         wrq_sge = 0;
1271                 }
1272                 tx->tx_nsge++;
1273         }
1274
1275         if (rc < 0)     /* no RDMA if completing with failure */
1276                 tx->tx_nwrq = tx->tx_nsge = 0;
1277
1278         ibmsg->ibm_u.completion.ibcm_status = rc;
1279         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1280         kiblnd_init_tx_msg(conn->ibc_peer->ibp_ni, tx,
1281                            type, sizeof(struct kib_completion_msg));
1282
1283         return rc;
1284 }
1285
1286 static void
1287 kiblnd_queue_tx_locked(struct kib_tx *tx, struct kib_conn *conn)
1288 {
1289         struct list_head *q;
1290         s64 timeout_ns;
1291
1292         LASSERT(tx->tx_nwrq > 0);       /* work items set up */
1293         LASSERT(!tx->tx_queued);        /* not queued for sending already */
1294         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1295
1296         if (conn->ibc_state >= IBLND_CONN_DISCONNECTED) {
1297                 tx->tx_status = -ECONNABORTED;
1298                 tx->tx_waiting = 0;
1299                 if (tx->tx_conn != NULL) {
1300                         /* PUT_DONE first attached to conn as a PUT_REQ */
1301                         LASSERT(tx->tx_conn == conn);
1302                         LASSERT(tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1303                         tx->tx_conn = NULL;
1304                         kiblnd_conn_decref(conn);
1305                 }
1306                 list_add(&tx->tx_list, &conn->ibc_zombie_txs);
1307
1308                 return;
1309         }
1310
1311         timeout_ns = lnet_get_lnd_timeout() * NSEC_PER_SEC;
1312         tx->tx_queued = 1;
1313         tx->tx_deadline = ktime_add_ns(ktime_get(), timeout_ns);
1314
1315         if (tx->tx_conn == NULL) {
1316                 kiblnd_conn_addref(conn);
1317                 tx->tx_conn = conn;
1318                 LASSERT (tx->tx_msg->ibm_type != IBLND_MSG_PUT_DONE);
1319         } else {
1320                 /* PUT_DONE first attached to conn as a PUT_REQ */
1321                 LASSERT (tx->tx_conn == conn);
1322                 LASSERT (tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1323         }
1324
1325         switch (tx->tx_msg->ibm_type) {
1326         default:
1327                 LBUG();
1328
1329         case IBLND_MSG_PUT_REQ:
1330         case IBLND_MSG_GET_REQ:
1331                 q = &conn->ibc_tx_queue_rsrvd;
1332                 break;
1333
1334         case IBLND_MSG_PUT_NAK:
1335         case IBLND_MSG_PUT_ACK:
1336         case IBLND_MSG_PUT_DONE:
1337         case IBLND_MSG_GET_DONE:
1338                 q = &conn->ibc_tx_queue_nocred;
1339                 break;
1340
1341         case IBLND_MSG_NOOP:
1342                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
1343                         q = &conn->ibc_tx_queue_nocred;
1344                 else
1345                         q = &conn->ibc_tx_noops;
1346                 break;
1347
1348         case IBLND_MSG_IMMEDIATE:
1349                 q = &conn->ibc_tx_queue;
1350                 break;
1351         }
1352
1353         list_add_tail(&tx->tx_list, q);
1354 }
1355
1356 static void
1357 kiblnd_queue_tx(struct kib_tx *tx, struct kib_conn *conn)
1358 {
1359         spin_lock(&conn->ibc_lock);
1360         kiblnd_queue_tx_locked(tx, conn);
1361         kiblnd_check_sends_locked(conn);
1362         spin_unlock(&conn->ibc_lock);
1363 }
1364
1365 static int kiblnd_resolve_addr(struct rdma_cm_id *cmid,
1366                                struct sockaddr_in *srcaddr,
1367                                struct sockaddr_in *dstaddr,
1368                                int timeout_ms)
1369 {
1370         unsigned short port;
1371         int rc;
1372
1373         /* allow the port to be reused */
1374         rc = rdma_set_reuseaddr(cmid, 1);
1375         if (rc != 0) {
1376                 CERROR("Unable to set reuse on cmid: %d\n", rc);
1377                 return rc;
1378         }
1379
1380         /* look for a free privileged port */
1381         for (port = PROT_SOCK-1; port > 0; port--) {
1382                 srcaddr->sin_port = htons(port);
1383                 rc = rdma_resolve_addr(cmid,
1384                                        (struct sockaddr *)srcaddr,
1385                                        (struct sockaddr *)dstaddr,
1386                                        timeout_ms);
1387                 if (rc == 0) {
1388                         CDEBUG(D_NET, "bound to port %hu\n", port);
1389                         return 0;
1390                 } else if (rc == -EADDRINUSE || rc == -EADDRNOTAVAIL) {
1391                         CDEBUG(D_NET, "bind to port %hu failed: %d\n",
1392                                port, rc);
1393                 } else {
1394                         return rc;
1395                 }
1396         }
1397
1398         CERROR("Failed to bind to a free privileged port\n");
1399         return rc;
1400 }
1401
1402 static void
1403 kiblnd_connect_peer(struct kib_peer_ni *peer_ni)
1404 {
1405         struct rdma_cm_id *cmid;
1406         struct kib_dev *dev;
1407         struct kib_net *net = peer_ni->ibp_ni->ni_data;
1408         struct sockaddr_in srcaddr;
1409         struct sockaddr_in dstaddr;
1410         int rc;
1411
1412         LASSERT (net != NULL);
1413         LASSERT (peer_ni->ibp_connecting > 0);
1414
1415         cmid = kiblnd_rdma_create_id(peer_ni->ibp_ni->ni_net_ns,
1416                                      kiblnd_cm_callback, peer_ni,
1417                                      RDMA_PS_TCP, IB_QPT_RC);
1418
1419         if (IS_ERR(cmid)) {
1420                 CERROR("Can't create CMID for %s: %ld\n",
1421                        libcfs_nid2str(peer_ni->ibp_nid), PTR_ERR(cmid));
1422                 rc = PTR_ERR(cmid);
1423                 goto failed;
1424         }
1425
1426         dev = net->ibn_dev;
1427         memset(&srcaddr, 0, sizeof(srcaddr));
1428         srcaddr.sin_family = AF_INET;
1429         srcaddr.sin_addr.s_addr = htonl(dev->ibd_ifip);
1430
1431         memset(&dstaddr, 0, sizeof(dstaddr));
1432         dstaddr.sin_family = AF_INET;
1433         dstaddr.sin_port = htons(*kiblnd_tunables.kib_service);
1434         dstaddr.sin_addr.s_addr = htonl(LNET_NIDADDR(peer_ni->ibp_nid));
1435
1436         kiblnd_peer_addref(peer_ni);               /* cmid's ref */
1437
1438         if (*kiblnd_tunables.kib_use_priv_port) {
1439                 rc = kiblnd_resolve_addr(cmid, &srcaddr, &dstaddr,
1440                                          lnet_get_lnd_timeout() * 1000);
1441         } else {
1442                 rc = rdma_resolve_addr(cmid,
1443                                        (struct sockaddr *)&srcaddr,
1444                                        (struct sockaddr *)&dstaddr,
1445                                        lnet_get_lnd_timeout() * 1000);
1446         }
1447         if (rc != 0) {
1448                 /* Can't initiate address resolution:  */
1449                 CERROR("Can't resolve addr for %s: %d\n",
1450                        libcfs_nid2str(peer_ni->ibp_nid), rc);
1451                 goto failed2;
1452         }
1453
1454         return;
1455
1456  failed2:
1457         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1458         kiblnd_peer_decref(peer_ni);               /* cmid's ref */
1459         rdma_destroy_id(cmid);
1460         return;
1461  failed:
1462         kiblnd_peer_connect_failed(peer_ni, 1, rc);
1463 }
1464
1465 bool
1466 kiblnd_reconnect_peer(struct kib_peer_ni *peer_ni)
1467 {
1468         rwlock_t         *glock = &kiblnd_data.kib_global_lock;
1469         char             *reason = NULL;
1470         struct list_head  txs;
1471         unsigned long     flags;
1472
1473         INIT_LIST_HEAD(&txs);
1474
1475         write_lock_irqsave(glock, flags);
1476         if (peer_ni->ibp_reconnecting == 0) {
1477                 if (peer_ni->ibp_accepting)
1478                         reason = "accepting";
1479                 else if (peer_ni->ibp_connecting)
1480                         reason = "connecting";
1481                 else if (!list_empty(&peer_ni->ibp_conns))
1482                         reason = "connected";
1483                 else /* connected then closed */
1484                         reason = "closed";
1485
1486                 goto no_reconnect;
1487         }
1488
1489         if (peer_ni->ibp_accepting)
1490                 CNETERR("Detecting race between accepting and reconnecting\n");
1491         peer_ni->ibp_reconnecting--;
1492
1493         if (!kiblnd_peer_active(peer_ni)) {
1494                 list_splice_init(&peer_ni->ibp_tx_queue, &txs);
1495                 reason = "unlinked";
1496                 goto no_reconnect;
1497         }
1498
1499         peer_ni->ibp_connecting++;
1500         peer_ni->ibp_reconnected++;
1501
1502         write_unlock_irqrestore(glock, flags);
1503
1504         kiblnd_connect_peer(peer_ni);
1505         return true;
1506
1507  no_reconnect:
1508         write_unlock_irqrestore(glock, flags);
1509
1510         CWARN("Abort reconnection of %s: %s\n",
1511               libcfs_nid2str(peer_ni->ibp_nid), reason);
1512         kiblnd_txlist_done(&txs, -ECONNABORTED,
1513                            LNET_MSG_STATUS_LOCAL_ABORTED);
1514         return false;
1515 }
1516
1517 void
1518 kiblnd_launch_tx(struct lnet_ni *ni, struct kib_tx *tx, lnet_nid_t nid)
1519 {
1520         struct kib_peer_ni *peer_ni;
1521         struct kib_peer_ni *peer2;
1522         struct kib_conn *conn;
1523         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
1524         unsigned long      flags;
1525         int                rc;
1526         int                i;
1527         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
1528
1529         /* If I get here, I've committed to send, so I complete the tx with
1530          * failure on any problems */
1531
1532         LASSERT (tx == NULL || tx->tx_conn == NULL); /* only set when assigned a conn */
1533         LASSERT (tx == NULL || tx->tx_nwrq > 0);     /* work items have been set up */
1534
1535         /* First time, just use a read lock since I expect to find my peer_ni
1536          * connected */
1537         read_lock_irqsave(g_lock, flags);
1538
1539         peer_ni = kiblnd_find_peer_locked(ni, nid);
1540         if (peer_ni != NULL && !list_empty(&peer_ni->ibp_conns)) {
1541                 /* Found a peer_ni with an established connection */
1542                 conn = kiblnd_get_conn_locked(peer_ni);
1543                 kiblnd_conn_addref(conn); /* 1 ref for me... */
1544
1545                 read_unlock_irqrestore(g_lock, flags);
1546
1547                 if (tx != NULL)
1548                         kiblnd_queue_tx(tx, conn);
1549                 kiblnd_conn_decref(conn); /* ...to here */
1550                 return;
1551         }
1552
1553         read_unlock(g_lock);
1554         /* Re-try with a write lock */
1555         write_lock(g_lock);
1556
1557         peer_ni = kiblnd_find_peer_locked(ni, nid);
1558         if (peer_ni != NULL) {
1559                 if (list_empty(&peer_ni->ibp_conns)) {
1560                         /* found a peer_ni, but it's still connecting... */
1561                         LASSERT(kiblnd_peer_connecting(peer_ni));
1562                         if (tx != NULL)
1563                                 list_add_tail(&tx->tx_list,
1564                                                   &peer_ni->ibp_tx_queue);
1565                         write_unlock_irqrestore(g_lock, flags);
1566                 } else {
1567                         conn = kiblnd_get_conn_locked(peer_ni);
1568                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1569
1570                         write_unlock_irqrestore(g_lock, flags);
1571
1572                         if (tx != NULL)
1573                                 kiblnd_queue_tx(tx, conn);
1574                         kiblnd_conn_decref(conn); /* ...to here */
1575                 }
1576                 return;
1577         }
1578
1579         write_unlock_irqrestore(g_lock, flags);
1580
1581         /* Allocate a peer_ni ready to add to the peer_ni table and retry */
1582         rc = kiblnd_create_peer(ni, &peer_ni, nid);
1583         if (rc != 0) {
1584                 CERROR("Can't create peer_ni %s\n", libcfs_nid2str(nid));
1585                 if (tx != NULL) {
1586                         tx->tx_status = -EHOSTUNREACH;
1587                         tx->tx_waiting = 0;
1588                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1589                         kiblnd_tx_done(tx);
1590                 }
1591                 return;
1592         }
1593
1594         write_lock_irqsave(g_lock, flags);
1595
1596         peer2 = kiblnd_find_peer_locked(ni, nid);
1597         if (peer2 != NULL) {
1598                 if (list_empty(&peer2->ibp_conns)) {
1599                         /* found a peer_ni, but it's still connecting... */
1600                         LASSERT(kiblnd_peer_connecting(peer2));
1601                         if (tx != NULL)
1602                                 list_add_tail(&tx->tx_list,
1603                                                   &peer2->ibp_tx_queue);
1604                         write_unlock_irqrestore(g_lock, flags);
1605                 } else {
1606                         conn = kiblnd_get_conn_locked(peer2);
1607                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1608
1609                         write_unlock_irqrestore(g_lock, flags);
1610
1611                         if (tx != NULL)
1612                                 kiblnd_queue_tx(tx, conn);
1613                         kiblnd_conn_decref(conn); /* ...to here */
1614                 }
1615
1616                 kiblnd_peer_decref(peer_ni);
1617                 return;
1618         }
1619
1620         /* Brand new peer_ni */
1621         LASSERT(peer_ni->ibp_connecting == 0);
1622         tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
1623         peer_ni->ibp_connecting = tunables->lnd_conns_per_peer;
1624
1625         /* always called with a ref on ni, which prevents ni being shutdown */
1626         LASSERT(((struct kib_net *)ni->ni_data)->ibn_shutdown == 0);
1627
1628         if (tx != NULL)
1629                 list_add_tail(&tx->tx_list, &peer_ni->ibp_tx_queue);
1630
1631         kiblnd_peer_addref(peer_ni);
1632         list_add_tail(&peer_ni->ibp_list, kiblnd_nid2peerlist(nid));
1633
1634         write_unlock_irqrestore(g_lock, flags);
1635
1636         for (i = 0; i < tunables->lnd_conns_per_peer; i++)
1637                 kiblnd_connect_peer(peer_ni);
1638         kiblnd_peer_decref(peer_ni);
1639 }
1640
1641 int
1642 kiblnd_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg)
1643 {
1644         struct lnet_hdr *hdr = &lntmsg->msg_hdr;
1645         int               type = lntmsg->msg_type;
1646         struct lnet_process_id target = lntmsg->msg_target;
1647         int               target_is_router = lntmsg->msg_target_is_router;
1648         int               routing = lntmsg->msg_routing;
1649         unsigned int      payload_niov = lntmsg->msg_niov;
1650         struct kvec      *payload_iov = lntmsg->msg_iov;
1651         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
1652         unsigned int      payload_offset = lntmsg->msg_offset;
1653         unsigned int      payload_nob = lntmsg->msg_len;
1654         struct kib_msg *ibmsg;
1655         struct kib_rdma_desc *rd;
1656         struct kib_tx *tx;
1657         int               nob;
1658         int               rc;
1659
1660         /* NB 'private' is different depending on what we're sending.... */
1661
1662         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1663                payload_nob, payload_niov, libcfs_id2str(target));
1664
1665         LASSERT (payload_nob == 0 || payload_niov > 0);
1666         LASSERT (payload_niov <= LNET_MAX_IOV);
1667
1668         /* Thread context */
1669         LASSERT (!in_interrupt());
1670         /* payload is either all vaddrs or all pages */
1671         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1672
1673         switch (type) {
1674         default:
1675                 LBUG();
1676                 return (-EIO);
1677
1678         case LNET_MSG_ACK:
1679                 LASSERT (payload_nob == 0);
1680                 break;
1681
1682         case LNET_MSG_GET:
1683                 if (routing || target_is_router)
1684                         break;                  /* send IMMEDIATE */
1685
1686                 /* is the REPLY message too small for RDMA? */
1687                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1688                 if (nob <= IBLND_MSG_SIZE)
1689                         break;                  /* send IMMEDIATE */
1690
1691                 tx = kiblnd_get_idle_tx(ni, target.nid);
1692                 if (tx == NULL) {
1693                         CERROR("Can't allocate txd for GET to %s\n",
1694                                libcfs_nid2str(target.nid));
1695                         return -ENOMEM;
1696                 }
1697
1698                 ibmsg = tx->tx_msg;
1699                 rd = &ibmsg->ibm_u.get.ibgm_rd;
1700                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0)
1701                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1702                                                  lntmsg->msg_md->md_niov,
1703                                                  lntmsg->msg_md->md_iov.iov,
1704                                                  0, lntmsg->msg_md->md_length);
1705                 else
1706                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1707                                                   lntmsg->msg_md->md_niov,
1708                                                   lntmsg->msg_md->md_iov.kiov,
1709                                                   0, lntmsg->msg_md->md_length);
1710                 if (rc != 0) {
1711                         CERROR("Can't setup GET sink for %s: %d\n",
1712                                libcfs_nid2str(target.nid), rc);
1713                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1714                         kiblnd_tx_done(tx);
1715                         return -EIO;
1716                 }
1717
1718                 nob = offsetof(struct kib_get_msg, ibgm_rd.rd_frags[rd->rd_nfrags]);
1719                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1720                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1721
1722                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1723
1724                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1725                 if (tx->tx_lntmsg[1] == NULL) {
1726                         CERROR("Can't create reply for GET -> %s\n",
1727                                libcfs_nid2str(target.nid));
1728                         kiblnd_tx_done(tx);
1729                         return -EIO;
1730                 }
1731
1732                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1733                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1734                 kiblnd_launch_tx(ni, tx, target.nid);
1735                 return 0;
1736
1737         case LNET_MSG_REPLY:
1738         case LNET_MSG_PUT:
1739                 /* Is the payload small enough not to need RDMA? */
1740                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob]);
1741                 if (nob <= IBLND_MSG_SIZE)
1742                         break;                  /* send IMMEDIATE */
1743
1744                 tx = kiblnd_get_idle_tx(ni, target.nid);
1745                 if (tx == NULL) {
1746                         CERROR("Can't allocate %s txd for %s\n",
1747                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1748                                libcfs_nid2str(target.nid));
1749                         return -ENOMEM;
1750                 }
1751
1752                 if (payload_kiov == NULL)
1753                         rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1754                                                  payload_niov, payload_iov,
1755                                                  payload_offset, payload_nob);
1756                 else
1757                         rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1758                                                   payload_niov, payload_kiov,
1759                                                   payload_offset, payload_nob);
1760                 if (rc != 0) {
1761                         CERROR("Can't setup PUT src for %s: %d\n",
1762                                libcfs_nid2str(target.nid), rc);
1763                         kiblnd_tx_done(tx);
1764                         return -EIO;
1765                 }
1766
1767                 ibmsg = tx->tx_msg;
1768                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1769                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1770                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ,
1771                                    sizeof(struct kib_putreq_msg));
1772
1773                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1774                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1775                 kiblnd_launch_tx(ni, tx, target.nid);
1776                 return 0;
1777         }
1778
1779         /* send IMMEDIATE */
1780         LASSERT(offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[payload_nob])
1781                 <= IBLND_MSG_SIZE);
1782
1783         tx = kiblnd_get_idle_tx(ni, target.nid);
1784         if (tx == NULL) {
1785                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1786                         type, libcfs_nid2str(target.nid));
1787                 return -ENOMEM;
1788         }
1789
1790         ibmsg = tx->tx_msg;
1791         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1792
1793         if (payload_kiov != NULL)
1794                 lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1795                                     offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1796                                     payload_niov, payload_kiov,
1797                                     payload_offset, payload_nob);
1798         else
1799                 lnet_copy_iov2flat(IBLND_MSG_SIZE, ibmsg,
1800                                    offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1801                                    payload_niov, payload_iov,
1802                                    payload_offset, payload_nob);
1803
1804         nob = offsetof(struct kib_immediate_msg, ibim_payload[payload_nob]);
1805         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1806
1807         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1808         kiblnd_launch_tx(ni, tx, target.nid);
1809         return 0;
1810 }
1811
1812 static void
1813 kiblnd_reply(struct lnet_ni *ni, struct kib_rx *rx, struct lnet_msg *lntmsg)
1814 {
1815         struct lnet_process_id target = lntmsg->msg_target;
1816         unsigned int      niov = lntmsg->msg_niov;
1817         struct kvec      *iov = lntmsg->msg_iov;
1818         lnet_kiov_t      *kiov = lntmsg->msg_kiov;
1819         unsigned int      offset = lntmsg->msg_offset;
1820         unsigned int      nob = lntmsg->msg_len;
1821         struct kib_tx *tx;
1822         int               rc;
1823
1824         tx = kiblnd_get_idle_tx(ni, rx->rx_conn->ibc_peer->ibp_nid);
1825         if (tx == NULL) {
1826                 CERROR("Can't get tx for REPLY to %s\n",
1827                        libcfs_nid2str(target.nid));
1828                 goto failed_0;
1829         }
1830
1831         if (nob == 0)
1832                 rc = 0;
1833         else if (kiov == NULL)
1834                 rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1835                                          niov, iov, offset, nob);
1836         else
1837                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1838                                           niov, kiov, offset, nob);
1839
1840         if (rc != 0) {
1841                 CERROR("Can't setup GET src for %s: %d\n",
1842                        libcfs_nid2str(target.nid), rc);
1843                 goto failed_1;
1844         }
1845
1846         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1847                               IBLND_MSG_GET_DONE, nob,
1848                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1849                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1850         if (rc < 0) {
1851                 CERROR("Can't setup rdma for GET from %s: %d\n",
1852                        libcfs_nid2str(target.nid), rc);
1853                 goto failed_1;
1854         }
1855
1856         if (nob == 0) {
1857                 /* No RDMA: local completion may happen now! */
1858                 lnet_finalize(lntmsg, 0);
1859         } else {
1860                 /* RDMA: lnet_finalize(lntmsg) when it
1861                  * completes */
1862                 tx->tx_lntmsg[0] = lntmsg;
1863         }
1864
1865         kiblnd_queue_tx(tx, rx->rx_conn);
1866         return;
1867
1868
1869 failed_1:
1870         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1871         kiblnd_tx_done(tx);
1872 failed_0:
1873         lnet_finalize(lntmsg, -EIO);
1874 }
1875
1876 int
1877 kiblnd_recv(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg,
1878             int delayed, unsigned int niov, struct kvec *iov, lnet_kiov_t *kiov,
1879             unsigned int offset, unsigned int mlen, unsigned int rlen)
1880 {
1881         struct kib_rx *rx = private;
1882         struct kib_msg *rxmsg = rx->rx_msg;
1883         struct kib_conn *conn = rx->rx_conn;
1884         struct kib_tx *tx;
1885         __u64        ibprm_cookie;
1886         int          nob;
1887         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1888         int          rc = 0;
1889
1890         LASSERT (mlen <= rlen);
1891         LASSERT (!in_interrupt());
1892         /* Either all pages or all vaddrs */
1893         LASSERT (!(kiov != NULL && iov != NULL));
1894
1895         switch (rxmsg->ibm_type) {
1896         default:
1897                 LBUG();
1898
1899         case IBLND_MSG_IMMEDIATE:
1900                 nob = offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[rlen]);
1901                 if (nob > rx->rx_nob) {
1902                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1903                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1904                                 nob, rx->rx_nob);
1905                         rc = -EPROTO;
1906                         break;
1907                 }
1908
1909                 if (kiov != NULL)
1910                         lnet_copy_flat2kiov(niov, kiov, offset,
1911                                             IBLND_MSG_SIZE, rxmsg,
1912                                             offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1913                                             mlen);
1914                 else
1915                         lnet_copy_flat2iov(niov, iov, offset,
1916                                            IBLND_MSG_SIZE, rxmsg,
1917                                            offsetof(struct kib_msg, ibm_u.immediate.ibim_payload),
1918                                            mlen);
1919                 lnet_finalize(lntmsg, 0);
1920                 break;
1921
1922         case IBLND_MSG_PUT_REQ: {
1923                 struct kib_msg  *txmsg;
1924                 struct kib_rdma_desc *rd;
1925                 ibprm_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1926
1927                 if (mlen == 0) {
1928                         lnet_finalize(lntmsg, 0);
1929                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1930                                                0, ibprm_cookie);
1931                         break;
1932                 }
1933
1934                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1935                 if (tx == NULL) {
1936                         CERROR("Can't allocate tx for %s\n",
1937                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1938                         /* Not replying will break the connection */
1939                         rc = -ENOMEM;
1940                         break;
1941                 }
1942
1943                 txmsg = tx->tx_msg;
1944                 rd = &txmsg->ibm_u.putack.ibpam_rd;
1945                 if (kiov == NULL)
1946                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1947                                                  niov, iov, offset, mlen);
1948                 else
1949                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1950                                                   niov, kiov, offset, mlen);
1951                 if (rc != 0) {
1952                         CERROR("Can't setup PUT sink for %s: %d\n",
1953                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1954                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
1955                         kiblnd_tx_done(tx);
1956                         /* tell peer_ni it's over */
1957                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK,
1958                                                rc, ibprm_cookie);
1959                         break;
1960                 }
1961
1962                 nob = offsetof(struct kib_putack_msg, ibpam_rd.rd_frags[rd->rd_nfrags]);
1963                 txmsg->ibm_u.putack.ibpam_src_cookie = ibprm_cookie;
1964                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1965
1966                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1967
1968                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1969                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1970                 kiblnd_queue_tx(tx, conn);
1971
1972                 /* reposted buffer reserved for PUT_DONE */
1973                 post_credit = IBLND_POSTRX_NO_CREDIT;
1974                 break;
1975                 }
1976
1977         case IBLND_MSG_GET_REQ:
1978                 if (lntmsg != NULL) {
1979                         /* Optimized GET; RDMA lntmsg's payload */
1980                         kiblnd_reply(ni, rx, lntmsg);
1981                 } else {
1982                         /* GET didn't match anything */
1983                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1984                                                -ENODATA,
1985                                                rxmsg->ibm_u.get.ibgm_cookie);
1986                 }
1987                 break;
1988         }
1989
1990         kiblnd_post_rx(rx, post_credit);
1991         return rc;
1992 }
1993
1994 int
1995 kiblnd_thread_start(int (*fn)(void *arg), void *arg, char *name)
1996 {
1997         struct task_struct *task = kthread_run(fn, arg, name);
1998
1999         if (IS_ERR(task))
2000                 return PTR_ERR(task);
2001
2002         atomic_inc(&kiblnd_data.kib_nthreads);
2003         return 0;
2004 }
2005
2006 static void
2007 kiblnd_thread_fini (void)
2008 {
2009         atomic_dec (&kiblnd_data.kib_nthreads);
2010 }
2011
2012 static void
2013 kiblnd_peer_alive(struct kib_peer_ni *peer_ni)
2014 {
2015         /* This is racy, but everyone's only writing ktime_get_seconds() */
2016         peer_ni->ibp_last_alive = ktime_get_seconds();
2017         smp_mb();
2018 }
2019
2020 static void
2021 kiblnd_peer_notify(struct kib_peer_ni *peer_ni)
2022 {
2023         int           error = 0;
2024         time64_t last_alive = 0;
2025         unsigned long flags;
2026
2027         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2028
2029         if (kiblnd_peer_idle(peer_ni) && peer_ni->ibp_error != 0) {
2030                 error = peer_ni->ibp_error;
2031                 peer_ni->ibp_error = 0;
2032
2033                 last_alive = peer_ni->ibp_last_alive;
2034         }
2035
2036         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2037
2038         if (error != 0)
2039                 lnet_notify(peer_ni->ibp_ni,
2040                             peer_ni->ibp_nid, false, false, last_alive);
2041 }
2042
2043 void
2044 kiblnd_close_conn_locked(struct kib_conn *conn, int error)
2045 {
2046         /* This just does the immediate housekeeping.  'error' is zero for a
2047          * normal shutdown which can happen only after the connection has been
2048          * established.  If the connection is established, schedule the
2049          * connection to be finished off by the connd.  Otherwise the connd is
2050          * already dealing with it (either to set it up or tear it down).
2051          * Caller holds kib_global_lock exclusively in irq context */
2052         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2053         struct kib_dev *dev;
2054         unsigned long flags;
2055
2056         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2057
2058         if (error != 0 && conn->ibc_comms_error == 0)
2059                 conn->ibc_comms_error = error;
2060
2061         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
2062                 return; /* already being handled  */
2063
2064         if (error == 0 &&
2065             list_empty(&conn->ibc_tx_noops) &&
2066             list_empty(&conn->ibc_tx_queue) &&
2067             list_empty(&conn->ibc_tx_queue_rsrvd) &&
2068             list_empty(&conn->ibc_tx_queue_nocred) &&
2069             list_empty(&conn->ibc_active_txs)) {
2070                 CDEBUG(D_NET, "closing conn to %s\n", 
2071                        libcfs_nid2str(peer_ni->ibp_nid));
2072         } else {
2073                 CNETERR("Closing conn to %s: error %d%s%s%s%s%s\n",
2074                        libcfs_nid2str(peer_ni->ibp_nid), error,
2075                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
2076                        list_empty(&conn->ibc_tx_noops) ? "" : "(sending_noops)",
2077                        list_empty(&conn->ibc_tx_queue_rsrvd) ?
2078                                                 "" : "(sending_rsrvd)",
2079                        list_empty(&conn->ibc_tx_queue_nocred) ?
2080                                                  "" : "(sending_nocred)",
2081                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
2082         }
2083
2084         dev = ((struct kib_net *)peer_ni->ibp_ni->ni_data)->ibn_dev;
2085         if (peer_ni->ibp_next_conn == conn)
2086                 /* clear next_conn so it won't be used */
2087                 peer_ni->ibp_next_conn = NULL;
2088         list_del(&conn->ibc_list);
2089         /* connd (see below) takes over ibc_list's ref */
2090
2091         if (list_empty(&peer_ni->ibp_conns) &&    /* no more conns */
2092             kiblnd_peer_active(peer_ni)) {         /* still in peer_ni table */
2093                 kiblnd_unlink_peer_locked(peer_ni);
2094
2095                 /* set/clear error on last conn */
2096                 peer_ni->ibp_error = conn->ibc_comms_error;
2097         }
2098
2099         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
2100
2101         if (error != 0 &&
2102             kiblnd_dev_can_failover(dev)) {
2103                 list_add_tail(&dev->ibd_fail_list,
2104                               &kiblnd_data.kib_failed_devs);
2105                 wake_up(&kiblnd_data.kib_failover_waitq);
2106         }
2107
2108         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2109
2110         list_add_tail(&conn->ibc_list, &kiblnd_data.kib_connd_conns);
2111         wake_up(&kiblnd_data.kib_connd_waitq);
2112
2113         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
2114 }
2115
2116 void
2117 kiblnd_close_conn(struct kib_conn *conn, int error)
2118 {
2119         unsigned long flags;
2120
2121         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2122
2123         kiblnd_close_conn_locked(conn, error);
2124
2125         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2126 }
2127
2128 static void
2129 kiblnd_handle_early_rxs(struct kib_conn *conn)
2130 {
2131         unsigned long flags;
2132         struct kib_rx *rx;
2133
2134         LASSERT(!in_interrupt());
2135         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
2136
2137         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2138         while (!list_empty(&conn->ibc_early_rxs)) {
2139                 rx = list_entry(conn->ibc_early_rxs.next,
2140                                 struct kib_rx, rx_list);
2141                 list_del(&rx->rx_list);
2142                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2143
2144                 kiblnd_handle_rx(rx);
2145
2146                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2147         }
2148         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2149 }
2150
2151 void
2152 kiblnd_abort_txs(struct kib_conn *conn, struct list_head *txs)
2153 {
2154         LIST_HEAD(zombies);
2155         struct list_head        *tmp;
2156         struct list_head        *nxt;
2157         struct kib_tx *tx;
2158
2159         spin_lock(&conn->ibc_lock);
2160
2161         list_for_each_safe(tmp, nxt, txs) {
2162                 tx = list_entry(tmp, struct kib_tx, tx_list);
2163
2164                 if (txs == &conn->ibc_active_txs) {
2165                         LASSERT(!tx->tx_queued);
2166                         LASSERT(tx->tx_waiting ||
2167                                 tx->tx_sending != 0);
2168                         if (conn->ibc_comms_error == -ETIMEDOUT) {
2169                                 if (tx->tx_waiting && !tx->tx_sending)
2170                                         tx->tx_hstatus =
2171                                           LNET_MSG_STATUS_REMOTE_TIMEOUT;
2172                                 else if (tx->tx_sending)
2173                                         tx->tx_hstatus =
2174                                           LNET_MSG_STATUS_NETWORK_TIMEOUT;
2175                         }
2176                 } else {
2177                         LASSERT(tx->tx_queued);
2178                         if (conn->ibc_comms_error == -ETIMEDOUT)
2179                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2180                         else
2181                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
2182                 }
2183
2184                 tx->tx_status = -ECONNABORTED;
2185                 tx->tx_waiting = 0;
2186
2187                 /*
2188                  * TODO: This makes an assumption that
2189                  * kiblnd_tx_complete() will be called for each tx. If
2190                  * that event is dropped we could end up with stale
2191                  * connections floating around. We'd like to deal with
2192                  * that in a better way.
2193                  *
2194                  * Also that means we can exceed the timeout by many
2195                  * seconds.
2196                  */
2197                 if (tx->tx_sending == 0) {
2198                         tx->tx_queued = 0;
2199                         list_del(&tx->tx_list);
2200                         list_add(&tx->tx_list, &zombies);
2201                 }
2202         }
2203
2204         spin_unlock(&conn->ibc_lock);
2205
2206         /*
2207          * aborting transmits occurs when finalizing the connection.
2208          * The connection is finalized on error.
2209          * Passing LNET_MSG_STATUS_OK to txlist_done() will not
2210          * override the value already set in tx->tx_hstatus above.
2211          */
2212         kiblnd_txlist_done(&zombies, -ECONNABORTED, LNET_MSG_STATUS_OK);
2213 }
2214
2215 static void
2216 kiblnd_finalise_conn(struct kib_conn *conn)
2217 {
2218         LASSERT (!in_interrupt());
2219         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
2220
2221         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
2222          * for connections that didn't get as far as being connected, because
2223          * rdma_disconnect() does this for free. */
2224         kiblnd_abort_receives(conn);
2225
2226         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
2227
2228         /* Complete all tx descs not waiting for sends to complete.
2229          * NB we should be safe from RDMA now that the QP has changed state */
2230
2231         kiblnd_abort_txs(conn, &conn->ibc_tx_noops);
2232         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
2233         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
2234         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
2235         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
2236
2237         kiblnd_handle_early_rxs(conn);
2238 }
2239
2240 static void
2241 kiblnd_peer_connect_failed(struct kib_peer_ni *peer_ni, int active,
2242                            int error)
2243 {
2244         LIST_HEAD(zombies);
2245         unsigned long   flags;
2246
2247         LASSERT (error != 0);
2248         LASSERT (!in_interrupt());
2249
2250         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2251
2252         if (active) {
2253                 LASSERT(peer_ni->ibp_connecting > 0);
2254                 peer_ni->ibp_connecting--;
2255         } else {
2256                 LASSERT (peer_ni->ibp_accepting > 0);
2257                 peer_ni->ibp_accepting--;
2258         }
2259
2260         if (kiblnd_peer_connecting(peer_ni)) {
2261                 /* another connection attempt under way... */
2262                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2263                                         flags);
2264                 return;
2265         }
2266
2267         peer_ni->ibp_reconnected = 0;
2268         if (list_empty(&peer_ni->ibp_conns)) {
2269                 /* Take peer_ni's blocked transmits to complete with error */
2270                 list_splice_init(&peer_ni->ibp_tx_queue, &zombies);
2271
2272                 if (kiblnd_peer_active(peer_ni))
2273                         kiblnd_unlink_peer_locked(peer_ni);
2274
2275                 peer_ni->ibp_error = error;
2276         } else {
2277                 /* Can't have blocked transmits if there are connections */
2278                 LASSERT(list_empty(&peer_ni->ibp_tx_queue));
2279         }
2280
2281         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2282
2283         kiblnd_peer_notify(peer_ni);
2284
2285         if (list_empty(&zombies))
2286                 return;
2287
2288         CNETERR("Deleting messages for %s: connection failed\n",
2289                 libcfs_nid2str(peer_ni->ibp_nid));
2290
2291         kiblnd_txlist_done(&zombies, error,
2292                            LNET_MSG_STATUS_LOCAL_DROPPED);
2293 }
2294
2295 static void
2296 kiblnd_connreq_done(struct kib_conn *conn, int status)
2297 {
2298         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2299         struct kib_tx *tx;
2300         struct list_head txs;
2301         unsigned long    flags;
2302         int              active;
2303
2304         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2305
2306         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
2307                libcfs_nid2str(peer_ni->ibp_nid), active,
2308                conn->ibc_version, status);
2309
2310         LASSERT (!in_interrupt());
2311         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2312                   peer_ni->ibp_connecting > 0) ||
2313                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2314                   peer_ni->ibp_accepting > 0));
2315
2316         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2317         conn->ibc_connvars = NULL;
2318
2319         if (status != 0) {
2320                 /* failed to establish connection */
2321                 kiblnd_peer_connect_failed(peer_ni, active, status);
2322                 kiblnd_finalise_conn(conn);
2323                 return;
2324         }
2325
2326         /* connection established */
2327         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2328
2329         conn->ibc_last_send = ktime_get();
2330         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2331         kiblnd_peer_alive(peer_ni);
2332
2333         /* Add conn to peer_ni's list and nuke any dangling conns from a different
2334          * peer_ni instance... */
2335         kiblnd_conn_addref(conn);       /* +1 ref for ibc_list */
2336         list_add(&conn->ibc_list, &peer_ni->ibp_conns);
2337         peer_ni->ibp_reconnected = 0;
2338         if (active)
2339                 peer_ni->ibp_connecting--;
2340         else
2341                 peer_ni->ibp_accepting--;
2342
2343         if (peer_ni->ibp_version == 0) {
2344                 peer_ni->ibp_version     = conn->ibc_version;
2345                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2346         }
2347
2348         if (peer_ni->ibp_version     != conn->ibc_version ||
2349             peer_ni->ibp_incarnation != conn->ibc_incarnation) {
2350                 kiblnd_close_stale_conns_locked(peer_ni, conn->ibc_version,
2351                                                 conn->ibc_incarnation);
2352                 peer_ni->ibp_version     = conn->ibc_version;
2353                 peer_ni->ibp_incarnation = conn->ibc_incarnation;
2354         }
2355
2356         /* grab pending txs while I have the lock */
2357         INIT_LIST_HEAD(&txs);
2358         list_splice_init(&peer_ni->ibp_tx_queue, &txs);
2359
2360         if (!kiblnd_peer_active(peer_ni) ||        /* peer_ni has been deleted */
2361             conn->ibc_comms_error != 0) {       /* error has happened already */
2362
2363                 /* start to shut down connection */
2364                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2365                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2366
2367                 kiblnd_txlist_done(&txs, -ECONNABORTED,
2368                                    LNET_MSG_STATUS_LOCAL_ERROR);
2369
2370                 return;
2371         }
2372
2373         /* +1 ref for myself, this connection is visible to other threads
2374          * now, refcount of peer:ibp_conns can be released by connection
2375          * close from either a different thread, or the calling of
2376          * kiblnd_check_sends_locked() below. See bz21911 for details.
2377          */
2378         kiblnd_conn_addref(conn);
2379         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2380
2381         /* Schedule blocked txs
2382          * Note: if we are running with conns_per_peer > 1, these blocked
2383          * txs will all get scheduled to the first connection which gets
2384          * scheduled.  We won't be using round robin on this first batch.
2385          */
2386         spin_lock(&conn->ibc_lock);
2387         while (!list_empty(&txs)) {
2388                 tx = list_entry(txs.next, struct kib_tx, tx_list);
2389                 list_del(&tx->tx_list);
2390
2391                 kiblnd_queue_tx_locked(tx, conn);
2392         }
2393         kiblnd_check_sends_locked(conn);
2394         spin_unlock(&conn->ibc_lock);
2395
2396         /* schedule blocked rxs */
2397         kiblnd_handle_early_rxs(conn);
2398         kiblnd_conn_decref(conn);
2399 }
2400
2401 static void
2402 kiblnd_reject(struct rdma_cm_id *cmid, struct kib_rej *rej)
2403 {
2404         int          rc;
2405
2406         rc = rdma_reject(cmid, rej, sizeof(*rej));
2407
2408         if (rc != 0)
2409                 CWARN("Error %d sending reject\n", rc);
2410 }
2411
2412 static int
2413 kiblnd_passive_connect(struct rdma_cm_id *cmid, void *priv, int priv_nob)
2414 {
2415         rwlock_t                *g_lock = &kiblnd_data.kib_global_lock;
2416         struct kib_msg *reqmsg = priv;
2417         struct kib_msg *ackmsg;
2418         struct kib_dev *ibdev;
2419         struct kib_peer_ni *peer_ni;
2420         struct kib_peer_ni *peer2;
2421         struct kib_conn *conn;
2422         struct lnet_ni *ni = NULL;
2423         struct kib_net *net = NULL;
2424         lnet_nid_t             nid;
2425         struct rdma_conn_param cp;
2426         struct kib_rej rej;
2427         int                    version = IBLND_MSG_VERSION;
2428         unsigned long          flags;
2429         int                    rc;
2430         struct sockaddr_in    *peer_addr;
2431         LASSERT (!in_interrupt());
2432
2433         /* cmid inherits 'context' from the corresponding listener id */
2434         ibdev = cmid->context;
2435         LASSERT(ibdev);
2436
2437         memset(&rej, 0, sizeof(rej));
2438         rej.ibr_magic                = IBLND_MSG_MAGIC;
2439         rej.ibr_why                  = IBLND_REJECT_FATAL;
2440         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2441
2442         peer_addr = (struct sockaddr_in *)&(cmid->route.addr.dst_addr);
2443         if (*kiblnd_tunables.kib_require_priv_port &&
2444             ntohs(peer_addr->sin_port) >= PROT_SOCK) {
2445                 __u32 ip = ntohl(peer_addr->sin_addr.s_addr);
2446                 CERROR("peer_ni's port (%pI4h:%hu) is not privileged\n",
2447                        &ip, ntohs(peer_addr->sin_port));
2448                 goto failed;
2449         }
2450
2451         if (priv_nob < offsetof(struct kib_msg, ibm_type)) {
2452                 CERROR("Short connection request\n");
2453                 goto failed;
2454         }
2455
2456         /* Future protocol version compatibility support!  If the
2457          * o2iblnd-specific protocol changes, or when LNET unifies
2458          * protocols over all LNDs, the initial connection will
2459          * negotiate a protocol version.  I trap this here to avoid
2460          * console errors; the reject tells the peer_ni which protocol I
2461          * speak. */
2462         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2463             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2464                 goto failed;
2465         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2466             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2467             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2468                 goto failed;
2469         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2470             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2471             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2472                 goto failed;
2473
2474         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2475         if (rc != 0) {
2476                 CERROR("Can't parse connection request: %d\n", rc);
2477                 goto failed;
2478         }
2479
2480         nid = reqmsg->ibm_srcnid;
2481         ni  = lnet_nid2ni_addref(reqmsg->ibm_dstnid);
2482
2483         if (ni != NULL) {
2484                 net = (struct kib_net *)ni->ni_data;
2485                 rej.ibr_incarnation = net->ibn_incarnation;
2486         }
2487
2488         if (ni == NULL ||                         /* no matching net */
2489             ni->ni_nid != reqmsg->ibm_dstnid ||   /* right NET, wrong NID! */
2490             net->ibn_dev != ibdev) {              /* wrong device */
2491                 CERROR("Can't accept conn from %s on %s (%s:%d:%pI4h): "
2492                        "bad dst nid %s\n", libcfs_nid2str(nid),
2493                        ni == NULL ? "NA" : libcfs_nid2str(ni->ni_nid),
2494                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2495                         &ibdev->ibd_ifip,
2496                        libcfs_nid2str(reqmsg->ibm_dstnid));
2497
2498                 goto failed;
2499         }
2500
2501        /* check time stamp as soon as possible */
2502         if (reqmsg->ibm_dststamp != 0 &&
2503             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2504                 CWARN("Stale connection request\n");
2505                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2506                 goto failed;
2507         }
2508
2509         /* I can accept peer_ni's version */
2510         version = reqmsg->ibm_version;
2511
2512         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2513                 CERROR("Unexpected connreq msg type: %x from %s\n",
2514                        reqmsg->ibm_type, libcfs_nid2str(nid));
2515                 goto failed;
2516         }
2517
2518         if (reqmsg->ibm_u.connparams.ibcp_queue_depth >
2519             kiblnd_msg_queue_size(version, ni)) {
2520                 CERROR("Can't accept conn from %s, queue depth too large: "
2521                        " %d (<=%d wanted)\n",
2522                        libcfs_nid2str(nid),
2523                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2524                        kiblnd_msg_queue_size(version, ni));
2525
2526                 if (version == IBLND_MSG_VERSION)
2527                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2528
2529                 goto failed;
2530         }
2531
2532         if (reqmsg->ibm_u.connparams.ibcp_max_frags >
2533             IBLND_MAX_RDMA_FRAGS) {
2534                 CWARN("Can't accept conn from %s (version %x): "
2535                       "max_frags %d too large (%d wanted)\n",
2536                       libcfs_nid2str(nid), version,
2537                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2538                       IBLND_MAX_RDMA_FRAGS);
2539
2540                 if (version >= IBLND_MSG_VERSION)
2541                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2542
2543                 goto failed;
2544         } else if (reqmsg->ibm_u.connparams.ibcp_max_frags <
2545                    IBLND_MAX_RDMA_FRAGS &&
2546                    net->ibn_fmr_ps == NULL) {
2547                 CWARN("Can't accept conn from %s (version %x): "
2548                       "max_frags %d incompatible without FMR pool "
2549                       "(%d wanted)\n",
2550                       libcfs_nid2str(nid), version,
2551                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2552                       IBLND_MAX_RDMA_FRAGS);
2553
2554                 if (version == IBLND_MSG_VERSION)
2555                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2556
2557                 goto failed;
2558         }
2559
2560         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2561                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2562                        libcfs_nid2str(nid),
2563                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2564                        IBLND_MSG_SIZE);
2565                 goto failed;
2566         }
2567
2568         /* assume 'nid' is a new peer_ni; create  */
2569         rc = kiblnd_create_peer(ni, &peer_ni, nid);
2570         if (rc != 0) {
2571                 CERROR("Can't create peer_ni for %s\n", libcfs_nid2str(nid));
2572                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2573                 goto failed;
2574         }
2575
2576         /* We have validated the peer's parameters so use those */
2577         peer_ni->ibp_max_frags = reqmsg->ibm_u.connparams.ibcp_max_frags;
2578         peer_ni->ibp_queue_depth = reqmsg->ibm_u.connparams.ibcp_queue_depth;
2579
2580         write_lock_irqsave(g_lock, flags);
2581
2582         peer2 = kiblnd_find_peer_locked(ni, nid);
2583         if (peer2 != NULL) {
2584                 if (peer2->ibp_version == 0) {
2585                         peer2->ibp_version     = version;
2586                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2587                 }
2588
2589                 /* not the guy I've talked with */
2590                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2591                     peer2->ibp_version     != version) {
2592                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2593
2594                         if (kiblnd_peer_active(peer2)) {
2595                                 peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2596                                 peer2->ibp_version = version;
2597                         }
2598                         write_unlock_irqrestore(g_lock, flags);
2599
2600                         CWARN("Conn stale %s version %x/%x incarnation %llu/%llu\n",
2601                               libcfs_nid2str(nid), peer2->ibp_version, version,
2602                               peer2->ibp_incarnation, reqmsg->ibm_srcstamp);
2603
2604                         kiblnd_peer_decref(peer_ni);
2605                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2606                         goto failed;
2607                 }
2608
2609                 /* Tie-break connection race in favour of the higher NID.
2610                  * If we keep running into a race condition multiple times,
2611                  * we have to assume that the connection attempt with the
2612                  * higher NID is stuck in a connecting state and will never
2613                  * recover.  As such, we pass through this if-block and let
2614                  * the lower NID connection win so we can move forward.
2615                  */
2616                 if (peer2->ibp_connecting != 0 &&
2617                     nid < ni->ni_nid && peer2->ibp_races <
2618                     MAX_CONN_RACES_BEFORE_ABORT) {
2619                         peer2->ibp_races++;
2620                         write_unlock_irqrestore(g_lock, flags);
2621
2622                         CDEBUG(D_NET, "Conn race %s\n",
2623                                libcfs_nid2str(peer2->ibp_nid));
2624
2625                         kiblnd_peer_decref(peer_ni);
2626                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2627                         goto failed;
2628                 }
2629                 if (peer2->ibp_races >= MAX_CONN_RACES_BEFORE_ABORT)
2630                         CNETERR("Conn race %s: unresolved after %d attempts, letting lower NID win\n",
2631                                 libcfs_nid2str(peer2->ibp_nid),
2632                                 MAX_CONN_RACES_BEFORE_ABORT);
2633                 /*
2634                  * passive connection is allowed even this peer_ni is waiting for
2635                  * reconnection.
2636                  */
2637                 peer2->ibp_reconnecting = 0;
2638                 peer2->ibp_races = 0;
2639                 peer2->ibp_accepting++;
2640                 kiblnd_peer_addref(peer2);
2641
2642                 /* Race with kiblnd_launch_tx (active connect) to create peer_ni
2643                  * so copy validated parameters since we now know what the
2644                  * peer_ni's limits are */
2645                 peer2->ibp_max_frags = peer_ni->ibp_max_frags;
2646                 peer2->ibp_queue_depth = peer_ni->ibp_queue_depth;
2647
2648                 write_unlock_irqrestore(g_lock, flags);
2649                 kiblnd_peer_decref(peer_ni);
2650                 peer_ni = peer2;
2651         } else {
2652                 /* Brand new peer_ni */
2653                 LASSERT (peer_ni->ibp_accepting == 0);
2654                 LASSERT (peer_ni->ibp_version == 0 &&
2655                          peer_ni->ibp_incarnation == 0);
2656
2657                 peer_ni->ibp_accepting   = 1;
2658                 peer_ni->ibp_version     = version;
2659                 peer_ni->ibp_incarnation = reqmsg->ibm_srcstamp;
2660
2661                 /* I have a ref on ni that prevents it being shutdown */
2662                 LASSERT (net->ibn_shutdown == 0);
2663
2664                 kiblnd_peer_addref(peer_ni);
2665                 list_add_tail(&peer_ni->ibp_list, kiblnd_nid2peerlist(nid));
2666
2667                 write_unlock_irqrestore(g_lock, flags);
2668         }
2669
2670         conn = kiblnd_create_conn(peer_ni, cmid, IBLND_CONN_PASSIVE_WAIT, version);
2671         if (conn == NULL) {
2672                 kiblnd_peer_connect_failed(peer_ni, 0, -ENOMEM);
2673                 kiblnd_peer_decref(peer_ni);
2674                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2675                 goto failed;
2676         }
2677
2678         /* conn now "owns" cmid, so I return success from here on to ensure the
2679          * CM callback doesn't destroy cmid. */
2680         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2681         conn->ibc_credits          = conn->ibc_queue_depth;
2682         conn->ibc_reserved_credits = conn->ibc_queue_depth;
2683         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2684                 IBLND_OOB_MSGS(version) <= IBLND_RX_MSGS(conn));
2685
2686         ackmsg = &conn->ibc_connvars->cv_msg;
2687         memset(ackmsg, 0, sizeof(*ackmsg));
2688
2689         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2690                         sizeof(ackmsg->ibm_u.connparams));
2691         ackmsg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2692         ackmsg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2693         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2694
2695         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2696
2697         memset(&cp, 0, sizeof(cp));
2698         cp.private_data        = ackmsg;
2699         cp.private_data_len    = ackmsg->ibm_nob;
2700         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2701         cp.initiator_depth     = 0;
2702         cp.flow_control        = 1;
2703         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2704         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2705
2706         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2707
2708         rc = rdma_accept(cmid, &cp);
2709         if (rc != 0) {
2710                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2711                 rej.ibr_version = version;
2712                 rej.ibr_why     = IBLND_REJECT_FATAL;
2713
2714                 kiblnd_reject(cmid, &rej);
2715                 kiblnd_connreq_done(conn, rc);
2716                 kiblnd_conn_decref(conn);
2717         }
2718
2719         lnet_ni_decref(ni);
2720         return 0;
2721
2722  failed:
2723         if (ni != NULL) {
2724                 rej.ibr_cp.ibcp_queue_depth =
2725                         kiblnd_msg_queue_size(version, ni);
2726                 rej.ibr_cp.ibcp_max_frags   = IBLND_MAX_RDMA_FRAGS;
2727                 lnet_ni_decref(ni);
2728         }
2729
2730         rej.ibr_version = version;
2731         kiblnd_reject(cmid, &rej);
2732
2733         return -ECONNREFUSED;
2734 }
2735
2736 static void
2737 kiblnd_check_reconnect(struct kib_conn *conn, int version,
2738                        u64 incarnation, int why, struct kib_connparams *cp)
2739 {
2740         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
2741         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2742         char            *reason;
2743         int              msg_size = IBLND_MSG_SIZE;
2744         int              frag_num = -1;
2745         int              queue_dep = -1;
2746         bool             reconnect;
2747         unsigned long    flags;
2748
2749         LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2750         LASSERT(peer_ni->ibp_connecting > 0);   /* 'conn' at least */
2751
2752         if (cp) {
2753                 msg_size        = cp->ibcp_max_msg_size;
2754                 frag_num        = cp->ibcp_max_frags;
2755                 queue_dep       = cp->ibcp_queue_depth;
2756         }
2757
2758         write_lock_irqsave(glock, flags);
2759         /* retry connection if it's still needed and no other connection
2760          * attempts (active or passive) are in progress
2761          * NB: reconnect is still needed even when ibp_tx_queue is
2762          * empty if ibp_version != version because reconnect may be
2763          * initiated by kiblnd_query() */
2764         reconnect = (!list_empty(&peer_ni->ibp_tx_queue) ||
2765                      peer_ni->ibp_version != version) &&
2766                     peer_ni->ibp_connecting &&
2767                     peer_ni->ibp_accepting == 0;
2768         if (!reconnect) {
2769                 reason = "no need";
2770                 goto out;
2771         }
2772
2773         switch (why) {
2774         default:
2775                 reason = "Unknown";
2776                 break;
2777
2778         case IBLND_REJECT_RDMA_FRAGS: {
2779                 struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2780
2781                 if (!cp) {
2782                         reason = "can't negotiate max frags";
2783                         goto out;
2784                 }
2785                 tunables = &peer_ni->ibp_ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2786 #ifdef HAVE_IB_GET_DMA_MR
2787                 /*
2788                  * This check only makes sense if the kernel supports global
2789                  * memory registration. Otherwise, map_on_demand will never == 0
2790                  */
2791                 if (!tunables->lnd_map_on_demand) {
2792                         reason = "map_on_demand must be enabled";
2793                         goto out;
2794                 }
2795 #endif
2796                 if (conn->ibc_max_frags <= frag_num) {
2797                         reason = "unsupported max frags";
2798                         goto out;
2799                 }
2800
2801                 peer_ni->ibp_max_frags = frag_num;
2802                 reason = "rdma fragments";
2803                 break;
2804         }
2805         case IBLND_REJECT_MSG_QUEUE_SIZE:
2806                 if (!cp) {
2807                         reason = "can't negotiate queue depth";
2808                         goto out;
2809                 }
2810                 if (conn->ibc_queue_depth <= queue_dep) {
2811                         reason = "unsupported queue depth";
2812                         goto out;
2813                 }
2814
2815                 peer_ni->ibp_queue_depth = queue_dep;
2816                 reason = "queue depth";
2817                 break;
2818
2819         case IBLND_REJECT_CONN_STALE:
2820                 reason = "stale";
2821                 break;
2822
2823         case IBLND_REJECT_CONN_RACE:
2824                 reason = "conn race";
2825                 break;
2826
2827         case IBLND_REJECT_CONN_UNCOMPAT:
2828                 reason = "version negotiation";
2829                 break;
2830
2831         case IBLND_REJECT_INVALID_SRV_ID:
2832                 reason = "invalid service id";
2833                 break;
2834         }
2835
2836         conn->ibc_reconnect = 1;
2837         peer_ni->ibp_reconnecting++;
2838         peer_ni->ibp_version = version;
2839         if (incarnation != 0)
2840                 peer_ni->ibp_incarnation = incarnation;
2841  out:
2842         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2843
2844         CNETERR("%s: %s (%s), %x, %x, msg_size: %d, queue_depth: %d/%d, max_frags: %d/%d\n",
2845                 libcfs_nid2str(peer_ni->ibp_nid),
2846                 reconnect ? "reconnect" : "don't reconnect",
2847                 reason, IBLND_MSG_VERSION, version, msg_size,
2848                 conn->ibc_queue_depth, queue_dep,
2849                 conn->ibc_max_frags, frag_num);
2850         /*
2851          * if conn::ibc_reconnect is TRUE, connd will reconnect to the peer_ni
2852          * while destroying the zombie
2853          */
2854 }
2855
2856 static void
2857 kiblnd_rejected(struct kib_conn *conn, int reason, void *priv, int priv_nob)
2858 {
2859         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2860
2861         LASSERT (!in_interrupt());
2862         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2863
2864         switch (reason) {
2865         case IB_CM_REJ_STALE_CONN:
2866                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2867                                        IBLND_REJECT_CONN_STALE, NULL);
2868                 break;
2869
2870         case IB_CM_REJ_INVALID_SERVICE_ID:
2871                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2872                                        IBLND_REJECT_INVALID_SRV_ID, NULL);
2873                 CNETERR("%s rejected: no listener at %d\n",
2874                         libcfs_nid2str(peer_ni->ibp_nid),
2875                         *kiblnd_tunables.kib_service);
2876                 break;
2877
2878         case IB_CM_REJ_CONSUMER_DEFINED:
2879                 if (priv_nob >= offsetof(struct kib_rej, ibr_padding)) {
2880                         struct kib_rej *rej = priv;
2881                         struct kib_connparams *cp = NULL;
2882                         int               flip        = 0;
2883                         __u64             incarnation = -1;
2884
2885                         /* NB. default incarnation is -1 because:
2886                          * a) V1 will ignore dst incarnation in connreq.
2887                          * b) V2 will provide incarnation while rejecting me,
2888                          *    -1 will be overwrote.
2889                          *
2890                          * if I try to connect to a V1 peer_ni with V2 protocol,
2891                          * it rejected me then upgrade to V2, I have no idea
2892                          * about the upgrading and try to reconnect with V1,
2893                          * in this case upgraded V2 can find out I'm trying to
2894                          * talk to the old guy and reject me(incarnation is -1). 
2895                          */
2896
2897                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2898                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2899                                 __swab32s(&rej->ibr_magic);
2900                                 __swab16s(&rej->ibr_version);
2901                                 flip = 1;
2902                         }
2903
2904                         if (priv_nob >= sizeof(struct kib_rej) &&
2905                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2906                                 /* priv_nob is always 148 in current version
2907                                  * of OFED, so we still need to check version.
2908                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE) */
2909                                 cp = &rej->ibr_cp;
2910
2911                                 if (flip) {
2912                                         __swab64s(&rej->ibr_incarnation);
2913                                         __swab16s(&cp->ibcp_queue_depth);
2914                                         __swab16s(&cp->ibcp_max_frags);
2915                                         __swab32s(&cp->ibcp_max_msg_size);
2916                                 }
2917
2918                                 incarnation = rej->ibr_incarnation;
2919                         }
2920
2921                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2922                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2923                                 CERROR("%s rejected: consumer defined fatal error\n",
2924                                        libcfs_nid2str(peer_ni->ibp_nid));
2925                                 break;
2926                         }
2927
2928                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2929                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2930                                 CERROR("%s rejected: o2iblnd version %x error\n",
2931                                        libcfs_nid2str(peer_ni->ibp_nid),
2932                                        rej->ibr_version);
2933                                 break;
2934                         }
2935
2936                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2937                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2938                                 CDEBUG(D_NET, "rejected by old version peer_ni %s: %x\n",
2939                                        libcfs_nid2str(peer_ni->ibp_nid), rej->ibr_version);
2940
2941                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2942                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2943                         }
2944
2945                         switch (rej->ibr_why) {
2946                         case IBLND_REJECT_CONN_RACE:
2947                         case IBLND_REJECT_CONN_STALE:
2948                         case IBLND_REJECT_CONN_UNCOMPAT:
2949                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2950                         case IBLND_REJECT_RDMA_FRAGS:
2951                                 kiblnd_check_reconnect(conn, rej->ibr_version,
2952                                                 incarnation, rej->ibr_why, cp);
2953                                 break;
2954
2955                         case IBLND_REJECT_NO_RESOURCES:
2956                                 CERROR("%s rejected: o2iblnd no resources\n",
2957                                        libcfs_nid2str(peer_ni->ibp_nid));
2958                                 break;
2959
2960                         case IBLND_REJECT_FATAL:
2961                                 CERROR("%s rejected: o2iblnd fatal error\n",
2962                                        libcfs_nid2str(peer_ni->ibp_nid));
2963                                 break;
2964
2965                         default:
2966                                 CERROR("%s rejected: o2iblnd reason %d\n",
2967                                        libcfs_nid2str(peer_ni->ibp_nid),
2968                                        rej->ibr_why);
2969                                 break;
2970                         }
2971                         break;
2972                 }
2973                 /* fall through */
2974         default:
2975                 CNETERR("%s rejected: reason %d, size %d\n",
2976                         libcfs_nid2str(peer_ni->ibp_nid), reason, priv_nob);
2977                 break;
2978         }
2979
2980         kiblnd_connreq_done(conn, -ECONNREFUSED);
2981 }
2982
2983 static void
2984 kiblnd_check_connreply(struct kib_conn *conn, void *priv, int priv_nob)
2985 {
2986         struct kib_peer_ni *peer_ni = conn->ibc_peer;
2987         struct lnet_ni *ni = peer_ni->ibp_ni;
2988         struct kib_net *net = ni->ni_data;
2989         struct kib_msg *msg = priv;
2990         int            ver  = conn->ibc_version;
2991         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
2992         unsigned long  flags;
2993
2994         LASSERT (net != NULL);
2995
2996         if (rc != 0) {
2997                 CERROR("Can't unpack connack from %s: %d\n",
2998                        libcfs_nid2str(peer_ni->ibp_nid), rc);
2999                 goto failed;
3000         }
3001
3002         if (msg->ibm_type != IBLND_MSG_CONNACK) {
3003                 CERROR("Unexpected message %d from %s\n",
3004                        msg->ibm_type, libcfs_nid2str(peer_ni->ibp_nid));
3005                 rc = -EPROTO;
3006                 goto failed;
3007         }
3008
3009         if (ver != msg->ibm_version) {
3010                 CERROR("%s replied version %x is different with "
3011                        "requested version %x\n",
3012                        libcfs_nid2str(peer_ni->ibp_nid), msg->ibm_version, ver);
3013                 rc = -EPROTO;
3014                 goto failed;
3015         }
3016
3017         if (msg->ibm_u.connparams.ibcp_queue_depth >
3018             conn->ibc_queue_depth) {
3019                 CERROR("%s has incompatible queue depth %d (<=%d wanted)\n",
3020                        libcfs_nid2str(peer_ni->ibp_nid),
3021                        msg->ibm_u.connparams.ibcp_queue_depth,
3022                        conn->ibc_queue_depth);
3023                 rc = -EPROTO;
3024                 goto failed;
3025         }
3026
3027         if (msg->ibm_u.connparams.ibcp_max_frags >
3028             conn->ibc_max_frags) {
3029                 CERROR("%s has incompatible max_frags %d (<=%d wanted)\n",
3030                        libcfs_nid2str(peer_ni->ibp_nid),
3031                        msg->ibm_u.connparams.ibcp_max_frags,
3032                        conn->ibc_max_frags);
3033                 rc = -EPROTO;
3034                 goto failed;
3035         }
3036
3037         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
3038                 CERROR("%s max message size %d too big (%d max)\n",
3039                        libcfs_nid2str(peer_ni->ibp_nid),
3040                        msg->ibm_u.connparams.ibcp_max_msg_size,
3041                        IBLND_MSG_SIZE);
3042                 rc = -EPROTO;
3043                 goto failed;
3044         }
3045
3046         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3047         if (msg->ibm_dstnid == ni->ni_nid &&
3048             msg->ibm_dststamp == net->ibn_incarnation)
3049                 rc = 0;
3050         else
3051                 rc = -ESTALE;
3052         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3053
3054         if (rc != 0) {
3055                 CERROR("Bad connection reply from %s, rc = %d, "
3056                        "version: %x max_frags: %d\n",
3057                        libcfs_nid2str(peer_ni->ibp_nid), rc,
3058                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
3059                 goto failed;
3060         }
3061
3062         conn->ibc_incarnation      = msg->ibm_srcstamp;
3063         conn->ibc_credits          = msg->ibm_u.connparams.ibcp_queue_depth;
3064         conn->ibc_reserved_credits = msg->ibm_u.connparams.ibcp_queue_depth;
3065         conn->ibc_queue_depth      = msg->ibm_u.connparams.ibcp_queue_depth;
3066         conn->ibc_max_frags        = msg->ibm_u.connparams.ibcp_max_frags;
3067         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
3068                 IBLND_OOB_MSGS(ver) <= IBLND_RX_MSGS(conn));
3069
3070         kiblnd_connreq_done(conn, 0);
3071         return;
3072
3073  failed:
3074         /* NB My QP has already established itself, so I handle anything going
3075          * wrong here by setting ibc_comms_error.
3076          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
3077          * immediately tears it down. */
3078
3079         LASSERT (rc != 0);
3080         conn->ibc_comms_error = rc;
3081         kiblnd_connreq_done(conn, 0);
3082 }
3083
3084 static int
3085 kiblnd_active_connect(struct rdma_cm_id *cmid)
3086 {
3087         struct kib_peer_ni *peer_ni = cmid->context;
3088         struct kib_conn *conn;
3089         struct kib_msg *msg;
3090         struct rdma_conn_param cp;