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