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