Whamcloud - gitweb
1917dc4130eabc8756909d72ca52fb17e17d5412
[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 "LPX64" 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++;
692
693                 if (offset + fragnob < iov->iov_len) {
694                         offset += fragnob;
695                 } else {
696                         offset = 0;
697                         iov++;
698                         niov--;
699                 }
700                 nob -= fragnob;
701         } while (nob > 0);
702
703         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
704 }
705
706 static int
707 kiblnd_setup_rd_kiov (lnet_ni_t *ni, kib_tx_t *tx, kib_rdma_desc_t *rd,
708                       int nkiov, lnet_kiov_t *kiov, int offset, int nob)
709 {
710         kib_net_t          *net = ni->ni_data;
711         struct scatterlist *sg;
712         int                 fragnob;
713
714         CDEBUG(D_NET, "niov %d offset %d nob %d\n", nkiov, offset, nob);
715
716         LASSERT (nob > 0);
717         LASSERT (nkiov > 0);
718         LASSERT (net != NULL);
719
720         while (offset >= kiov->kiov_len) {
721                 offset -= kiov->kiov_len;
722                 nkiov--;
723                 kiov++;
724                 LASSERT (nkiov > 0);
725         }
726
727         sg = tx->tx_frags;
728         do {
729                 LASSERT (nkiov > 0);
730
731                 fragnob = min((int)(kiov->kiov_len - offset), nob);
732
733                 sg_set_page(sg, kiov->kiov_page, fragnob,
734                             kiov->kiov_offset + offset);
735                 sg++;
736
737                 offset = 0;
738                 kiov++;
739                 nkiov--;
740                 nob -= fragnob;
741         } while (nob > 0);
742
743         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
744 }
745
746 static int
747 kiblnd_post_tx_locked (kib_conn_t *conn, kib_tx_t *tx, int credit)
748 __must_hold(&conn->ibc_lock)
749 {
750         kib_msg_t         *msg = tx->tx_msg;
751         kib_peer_t        *peer = conn->ibc_peer;
752         struct lnet_ni    *ni = peer->ibp_ni;
753         int                ver = conn->ibc_version;
754         int                rc;
755         int                done;
756
757         LASSERT(tx->tx_queued);
758         /* We rely on this for QP sizing */
759         LASSERT(tx->tx_nwrq > 0);
760         LASSERT(tx->tx_nwrq <= 1 + conn->ibc_max_frags);
761
762         LASSERT(credit == 0 || credit == 1);
763         LASSERT(conn->ibc_outstanding_credits >= 0);
764         LASSERT(conn->ibc_outstanding_credits <= conn->ibc_queue_depth);
765         LASSERT(conn->ibc_credits >= 0);
766         LASSERT(conn->ibc_credits <= conn->ibc_queue_depth);
767
768         if (conn->ibc_nsends_posted ==
769             kiblnd_concurrent_sends(ver, ni)) {
770                 /* tx completions outstanding... */
771                 CDEBUG(D_NET, "%s: posted enough\n",
772                        libcfs_nid2str(peer->ibp_nid));
773                 return -EAGAIN;
774         }
775
776         if (credit != 0 && conn->ibc_credits == 0) {   /* no credits */
777                 CDEBUG(D_NET, "%s: no credits\n",
778                        libcfs_nid2str(peer->ibp_nid));
779                 return -EAGAIN;
780         }
781
782         if (credit != 0 && !IBLND_OOB_CAPABLE(ver) &&
783             conn->ibc_credits == 1 &&   /* last credit reserved */
784             msg->ibm_type != IBLND_MSG_NOOP) {      /* for NOOP */
785                 CDEBUG(D_NET, "%s: not using last credit\n",
786                        libcfs_nid2str(peer->ibp_nid));
787                 return -EAGAIN;
788         }
789
790         /* NB don't drop ibc_lock before bumping tx_sending */
791         list_del(&tx->tx_list);
792         tx->tx_queued = 0;
793
794         if (msg->ibm_type == IBLND_MSG_NOOP &&
795             (!kiblnd_need_noop(conn) ||     /* redundant NOOP */
796              (IBLND_OOB_CAPABLE(ver) && /* posted enough NOOP */
797               conn->ibc_noops_posted == IBLND_OOB_MSGS(ver)))) {
798                 /* OK to drop when posted enough NOOPs, since
799                  * kiblnd_check_sends will queue NOOP again when
800                  * posted NOOPs complete */
801                 spin_unlock(&conn->ibc_lock);
802                 kiblnd_tx_done(peer->ibp_ni, tx);
803                 spin_lock(&conn->ibc_lock);
804                 CDEBUG(D_NET, "%s(%d): redundant or enough NOOP\n",
805                        libcfs_nid2str(peer->ibp_nid),
806                        conn->ibc_noops_posted);
807                 return 0;
808         }
809
810         kiblnd_pack_msg(peer->ibp_ni, msg, ver, conn->ibc_outstanding_credits,
811                         peer->ibp_nid, conn->ibc_incarnation);
812
813         conn->ibc_credits -= credit;
814         conn->ibc_outstanding_credits = 0;
815         conn->ibc_nsends_posted++;
816         if (msg->ibm_type == IBLND_MSG_NOOP)
817                 conn->ibc_noops_posted++;
818
819         /* CAVEAT EMPTOR!  This tx could be the PUT_DONE of an RDMA
820          * PUT.  If so, it was first queued here as a PUT_REQ, sent and
821          * stashed on ibc_active_txs, matched by an incoming PUT_ACK,
822          * and then re-queued here.  It's (just) possible that
823          * tx_sending is non-zero if we've not done the tx_complete()
824          * from the first send; hence the ++ rather than = below. */
825         tx->tx_sending++;
826         list_add(&tx->tx_list, &conn->ibc_active_txs);
827
828         /* I'm still holding ibc_lock! */
829         if (conn->ibc_state != IBLND_CONN_ESTABLISHED) {
830                 rc = -ECONNABORTED;
831         } else if (tx->tx_pool->tpo_pool.po_failed ||
832                  conn->ibc_hdev != tx->tx_pool->tpo_hdev) {
833                 /* close_conn will launch failover */
834                 rc = -ENETDOWN;
835         } else {
836                 struct kib_fast_reg_descriptor *frd = tx->fmr.fmr_frd;
837                 struct ib_send_wr *bad = &tx->tx_wrq[tx->tx_nwrq - 1];
838                 struct ib_send_wr *wrq = tx->tx_wrq;
839
840                 if (frd != NULL) {
841                         if (!frd->frd_valid) {
842                                 wrq = &frd->frd_inv_wr;
843 #ifdef HAVE_IB_MAP_MR_SG
844                                 wrq->next = &frd->frd_fastreg_wr.wr;
845                         } else {
846                                 wrq = &frd->frd_fastreg_wr.wr;
847                         }
848                         frd->frd_fastreg_wr.wr.next = tx->tx_wrq;
849 #else
850                                 wrq->next = &frd->frd_fastreg_wr;
851                         } else {
852                                 wrq = &frd->frd_fastreg_wr;
853                         }
854                         frd->frd_fastreg_wr.next = tx->tx_wrq;
855 #endif
856                 }
857
858                 LASSERTF(bad->wr_id == kiblnd_ptr2wreqid(tx, IBLND_WID_TX),
859                          "bad wr_id "LPX64", 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                 bad = NULL;
863                 rc = ib_post_send(conn->ibc_cmid->qp, wrq, &bad);
864         }
865
866         conn->ibc_last_send = jiffies;
867
868         if (rc == 0)
869                 return 0;
870
871         /* NB credits are transferred in the actual
872          * message, which can only be the last work item */
873         conn->ibc_credits += credit;
874         conn->ibc_outstanding_credits += msg->ibm_credits;
875         conn->ibc_nsends_posted--;
876         if (msg->ibm_type == IBLND_MSG_NOOP)
877                 conn->ibc_noops_posted--;
878
879         tx->tx_status = rc;
880         tx->tx_waiting = 0;
881         tx->tx_sending--;
882
883         done = (tx->tx_sending == 0);
884         if (done)
885                 list_del(&tx->tx_list);
886
887         spin_unlock(&conn->ibc_lock);
888
889         if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
890                 CERROR("Error %d posting transmit to %s\n",
891                        rc, libcfs_nid2str(peer->ibp_nid));
892         else
893                 CDEBUG(D_NET, "Error %d posting transmit to %s\n",
894                        rc, libcfs_nid2str(peer->ibp_nid));
895
896         kiblnd_close_conn(conn, rc);
897
898         if (done)
899                 kiblnd_tx_done(peer->ibp_ni, tx);
900
901         spin_lock(&conn->ibc_lock);
902
903         return -EIO;
904 }
905
906 static void
907 kiblnd_check_sends (kib_conn_t *conn)
908 {
909         int        ver = conn->ibc_version;
910         lnet_ni_t *ni = conn->ibc_peer->ibp_ni;
911         kib_tx_t  *tx;
912
913         /* Don't send anything until after the connection is established */
914         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
915                 CDEBUG(D_NET, "%s too soon\n",
916                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
917                 return;
918         }
919
920         spin_lock(&conn->ibc_lock);
921
922         LASSERT(conn->ibc_nsends_posted <=
923                 kiblnd_concurrent_sends(ver, ni));
924         LASSERT (!IBLND_OOB_CAPABLE(ver) ||
925                  conn->ibc_noops_posted <= IBLND_OOB_MSGS(ver));
926         LASSERT (conn->ibc_reserved_credits >= 0);
927
928         while (conn->ibc_reserved_credits > 0 &&
929                !list_empty(&conn->ibc_tx_queue_rsrvd)) {
930                 tx = list_entry(conn->ibc_tx_queue_rsrvd.next,
931                                     kib_tx_t, tx_list);
932                 list_del(&tx->tx_list);
933                 list_add_tail(&tx->tx_list, &conn->ibc_tx_queue);
934                 conn->ibc_reserved_credits--;
935         }
936
937         if (kiblnd_need_noop(conn)) {
938                 spin_unlock(&conn->ibc_lock);
939
940                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
941                 if (tx != NULL)
942                         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_NOOP, 0);
943
944                 spin_lock(&conn->ibc_lock);
945                 if (tx != NULL)
946                         kiblnd_queue_tx_locked(tx, conn);
947         }
948
949         for (;;) {
950                 int credit;
951
952                 if (!list_empty(&conn->ibc_tx_queue_nocred)) {
953                         credit = 0;
954                         tx = list_entry(conn->ibc_tx_queue_nocred.next,
955                                             kib_tx_t, tx_list);
956                 } else if (!list_empty(&conn->ibc_tx_noops)) {
957                         LASSERT (!IBLND_OOB_CAPABLE(ver));
958                         credit = 1;
959                         tx = list_entry(conn->ibc_tx_noops.next,
960                                         kib_tx_t, tx_list);
961                 } else if (!list_empty(&conn->ibc_tx_queue)) {
962                         credit = 1;
963                         tx = list_entry(conn->ibc_tx_queue.next,
964                                             kib_tx_t, tx_list);
965                 } else
966                         break;
967
968                 if (kiblnd_post_tx_locked(conn, tx, credit) != 0)
969                         break;
970         }
971
972         spin_unlock(&conn->ibc_lock);
973 }
974
975 static void
976 kiblnd_tx_complete (kib_tx_t *tx, int status)
977 {
978         int           failed = (status != IB_WC_SUCCESS);
979         kib_conn_t   *conn = tx->tx_conn;
980         int           idle;
981
982         LASSERT (tx->tx_sending > 0);
983
984         if (failed) {
985                 if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
986                         CNETERR("Tx -> %s cookie "LPX64
987                                 " sending %d waiting %d: failed %d\n",
988                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
989                                 tx->tx_cookie, tx->tx_sending, tx->tx_waiting,
990                                 status);
991
992                 kiblnd_close_conn(conn, -EIO);
993         } else {
994                 kiblnd_peer_alive(conn->ibc_peer);
995         }
996
997         spin_lock(&conn->ibc_lock);
998
999         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
1000          * gets to free it, which also drops its ref on 'conn'. */
1001
1002         tx->tx_sending--;
1003         conn->ibc_nsends_posted--;
1004         if (tx->tx_msg->ibm_type == IBLND_MSG_NOOP)
1005                 conn->ibc_noops_posted--;
1006
1007         if (failed) {
1008                 tx->tx_waiting = 0;             /* don't wait for peer */
1009                 tx->tx_status = -EIO;
1010         }
1011
1012         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
1013                !tx->tx_waiting &&               /* Not waiting for peer */
1014                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
1015         if (idle)
1016                 list_del(&tx->tx_list);
1017
1018         kiblnd_conn_addref(conn);               /* 1 ref for me.... */
1019
1020         spin_unlock(&conn->ibc_lock);
1021
1022         if (idle)
1023                 kiblnd_tx_done(conn->ibc_peer->ibp_ni, tx);
1024
1025         kiblnd_check_sends(conn);
1026
1027         kiblnd_conn_decref(conn);               /* ...until here */
1028 }
1029
1030 static void
1031 kiblnd_init_tx_msg (lnet_ni_t *ni, kib_tx_t *tx, int type, int body_nob)
1032 {
1033         kib_hca_dev_t     *hdev = tx->tx_pool->tpo_hdev;
1034         struct ib_sge     *sge = &tx->tx_sge[tx->tx_nwrq];
1035         struct ib_send_wr *wrq = &tx->tx_wrq[tx->tx_nwrq];
1036         int                nob = offsetof (kib_msg_t, ibm_u) + body_nob;
1037         struct ib_mr      *mr = hdev->ibh_mrs;
1038
1039         LASSERT(tx->tx_nwrq >= 0);
1040         LASSERT(tx->tx_nwrq < IBLND_MAX_RDMA_FRAGS + 1);
1041         LASSERT(nob <= IBLND_MSG_SIZE);
1042         LASSERT(mr != NULL);
1043
1044         kiblnd_init_msg(tx->tx_msg, type, body_nob);
1045
1046         sge->lkey   = mr->lkey;
1047         sge->addr   = tx->tx_msgaddr;
1048         sge->length = nob;
1049
1050         memset(wrq, 0, sizeof(*wrq));
1051
1052         wrq->next       = NULL;
1053         wrq->wr_id      = kiblnd_ptr2wreqid(tx, IBLND_WID_TX);
1054         wrq->sg_list    = sge;
1055         wrq->num_sge    = 1;
1056         wrq->opcode     = IB_WR_SEND;
1057         wrq->send_flags = IB_SEND_SIGNALED;
1058
1059         tx->tx_nwrq++;
1060 }
1061
1062 static int
1063 kiblnd_init_rdma(kib_conn_t *conn, kib_tx_t *tx, int type,
1064                  int resid, kib_rdma_desc_t *dstrd, __u64 dstcookie)
1065 {
1066         kib_msg_t         *ibmsg = tx->tx_msg;
1067         kib_rdma_desc_t   *srcrd = tx->tx_rd;
1068         struct ib_sge     *sge = &tx->tx_sge[0];
1069         struct ib_send_wr *wrq = &tx->tx_wrq[0];
1070         int                rc  = resid;
1071         int                srcidx;
1072         int                dstidx;
1073         int                wrknob;
1074
1075         LASSERT (!in_interrupt());
1076         LASSERT (tx->tx_nwrq == 0);
1077         LASSERT (type == IBLND_MSG_GET_DONE ||
1078                  type == IBLND_MSG_PUT_DONE);
1079
1080         srcidx = dstidx = 0;
1081
1082         while (resid > 0) {
1083                 if (srcidx >= srcrd->rd_nfrags) {
1084                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1085                         rc = -EPROTO;
1086                         break;
1087                 }
1088
1089                 if (dstidx == dstrd->rd_nfrags) {
1090                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1091                         rc = -EPROTO;
1092                         break;
1093                 }
1094
1095                 if (tx->tx_nwrq >= conn->ibc_max_frags) {
1096                         CERROR("RDMA has too many fragments for peer %s (%d), "
1097                                "src idx/frags: %d/%d dst idx/frags: %d/%d\n",
1098                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
1099                                conn->ibc_max_frags,
1100                                srcidx, srcrd->rd_nfrags,
1101                                dstidx, dstrd->rd_nfrags);
1102                         rc = -EMSGSIZE;
1103                         break;
1104                 }
1105
1106                 wrknob = MIN(MIN(kiblnd_rd_frag_size(srcrd, srcidx),
1107                                  kiblnd_rd_frag_size(dstrd, dstidx)), resid);
1108
1109                 sge = &tx->tx_sge[tx->tx_nwrq];
1110                 sge->addr   = kiblnd_rd_frag_addr(srcrd, srcidx);
1111                 sge->lkey   = kiblnd_rd_frag_key(srcrd, srcidx);
1112                 sge->length = wrknob;
1113
1114                 wrq = &tx->tx_wrq[tx->tx_nwrq];
1115
1116                 wrq->next       = wrq + 1;
1117                 wrq->wr_id      = kiblnd_ptr2wreqid(tx, IBLND_WID_RDMA);
1118                 wrq->sg_list    = sge;
1119                 wrq->num_sge    = 1;
1120                 wrq->opcode     = IB_WR_RDMA_WRITE;
1121                 wrq->send_flags = 0;
1122
1123                 wrq->wr.rdma.remote_addr = kiblnd_rd_frag_addr(dstrd, dstidx);
1124                 wrq->wr.rdma.rkey        = kiblnd_rd_frag_key(dstrd, dstidx);
1125
1126                 srcidx = kiblnd_rd_consume_frag(srcrd, srcidx, wrknob);
1127                 dstidx = kiblnd_rd_consume_frag(dstrd, dstidx, wrknob);
1128
1129                 resid -= wrknob;
1130
1131                 tx->tx_nwrq++;
1132                 wrq++;
1133                 sge++;
1134         }
1135
1136         if (rc < 0)                             /* no RDMA if completing with failure */
1137                 tx->tx_nwrq = 0;
1138
1139         ibmsg->ibm_u.completion.ibcm_status = rc;
1140         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1141         kiblnd_init_tx_msg(conn->ibc_peer->ibp_ni, tx,
1142                            type, sizeof (kib_completion_msg_t));
1143
1144         return rc;
1145 }
1146
1147 static void
1148 kiblnd_queue_tx_locked(kib_tx_t *tx, kib_conn_t *conn)
1149 {
1150         struct list_head *q;
1151
1152         LASSERT(tx->tx_nwrq > 0);       /* work items set up */
1153         LASSERT(!tx->tx_queued);        /* not queued for sending already */
1154         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1155
1156         tx->tx_queued = 1;
1157         tx->tx_deadline = jiffies +
1158                           msecs_to_jiffies(*kiblnd_tunables.kib_timeout *
1159                                            MSEC_PER_SEC);
1160
1161         if (tx->tx_conn == NULL) {
1162                 kiblnd_conn_addref(conn);
1163                 tx->tx_conn = conn;
1164                 LASSERT (tx->tx_msg->ibm_type != IBLND_MSG_PUT_DONE);
1165         } else {
1166                 /* PUT_DONE first attached to conn as a PUT_REQ */
1167                 LASSERT (tx->tx_conn == conn);
1168                 LASSERT (tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1169         }
1170
1171         switch (tx->tx_msg->ibm_type) {
1172         default:
1173                 LBUG();
1174
1175         case IBLND_MSG_PUT_REQ:
1176         case IBLND_MSG_GET_REQ:
1177                 q = &conn->ibc_tx_queue_rsrvd;
1178                 break;
1179
1180         case IBLND_MSG_PUT_NAK:
1181         case IBLND_MSG_PUT_ACK:
1182         case IBLND_MSG_PUT_DONE:
1183         case IBLND_MSG_GET_DONE:
1184                 q = &conn->ibc_tx_queue_nocred;
1185                 break;
1186
1187         case IBLND_MSG_NOOP:
1188                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
1189                         q = &conn->ibc_tx_queue_nocred;
1190                 else
1191                         q = &conn->ibc_tx_noops;
1192                 break;
1193
1194         case IBLND_MSG_IMMEDIATE:
1195                 q = &conn->ibc_tx_queue;
1196                 break;
1197         }
1198
1199         list_add_tail(&tx->tx_list, q);
1200 }
1201
1202 static void
1203 kiblnd_queue_tx (kib_tx_t *tx, kib_conn_t *conn)
1204 {
1205         spin_lock(&conn->ibc_lock);
1206         kiblnd_queue_tx_locked(tx, conn);
1207         spin_unlock(&conn->ibc_lock);
1208
1209         kiblnd_check_sends(conn);
1210 }
1211
1212 static int kiblnd_resolve_addr(struct rdma_cm_id *cmid,
1213                                struct sockaddr_in *srcaddr,
1214                                struct sockaddr_in *dstaddr,
1215                                int timeout_ms)
1216 {
1217         unsigned short port;
1218         int rc;
1219
1220         /* allow the port to be reused */
1221         rc = rdma_set_reuseaddr(cmid, 1);
1222         if (rc != 0) {
1223                 CERROR("Unable to set reuse on cmid: %d\n", rc);
1224                 return rc;
1225         }
1226
1227         /* look for a free privileged port */
1228         for (port = PROT_SOCK-1; port > 0; port--) {
1229                 srcaddr->sin_port = htons(port);
1230                 rc = rdma_resolve_addr(cmid,
1231                                        (struct sockaddr *)srcaddr,
1232                                        (struct sockaddr *)dstaddr,
1233                                        timeout_ms);
1234                 if (rc == 0) {
1235                         CDEBUG(D_NET, "bound to port %hu\n", port);
1236                         return 0;
1237                 } else if (rc == -EADDRINUSE || rc == -EADDRNOTAVAIL) {
1238                         CDEBUG(D_NET, "bind to port %hu failed: %d\n",
1239                                port, rc);
1240                 } else {
1241                         return rc;
1242                 }
1243         }
1244
1245         CERROR("Failed to bind to a free privileged port\n");
1246         return rc;
1247 }
1248
1249 static void
1250 kiblnd_connect_peer (kib_peer_t *peer)
1251 {
1252         struct rdma_cm_id *cmid;
1253         kib_dev_t         *dev;
1254         kib_net_t         *net = peer->ibp_ni->ni_data;
1255         struct sockaddr_in srcaddr;
1256         struct sockaddr_in dstaddr;
1257         int                rc;
1258
1259         LASSERT (net != NULL);
1260         LASSERT (peer->ibp_connecting > 0);
1261         LASSERT(!peer->ibp_reconnecting);
1262
1263         cmid = kiblnd_rdma_create_id(kiblnd_cm_callback, peer, RDMA_PS_TCP,
1264                                      IB_QPT_RC);
1265
1266         if (IS_ERR(cmid)) {
1267                 CERROR("Can't create CMID for %s: %ld\n",
1268                        libcfs_nid2str(peer->ibp_nid), PTR_ERR(cmid));
1269                 rc = PTR_ERR(cmid);
1270                 goto failed;
1271         }
1272
1273         dev = net->ibn_dev;
1274         memset(&srcaddr, 0, sizeof(srcaddr));
1275         srcaddr.sin_family = AF_INET;
1276         srcaddr.sin_addr.s_addr = htonl(dev->ibd_ifip);
1277
1278         memset(&dstaddr, 0, sizeof(dstaddr));
1279         dstaddr.sin_family = AF_INET;
1280         dstaddr.sin_port = htons(*kiblnd_tunables.kib_service);
1281         dstaddr.sin_addr.s_addr = htonl(LNET_NIDADDR(peer->ibp_nid));
1282
1283         kiblnd_peer_addref(peer);               /* cmid's ref */
1284
1285         if (*kiblnd_tunables.kib_use_priv_port) {
1286                 rc = kiblnd_resolve_addr(cmid, &srcaddr, &dstaddr,
1287                                          *kiblnd_tunables.kib_timeout * 1000);
1288         } else {
1289                 rc = rdma_resolve_addr(cmid,
1290                                        (struct sockaddr *)&srcaddr,
1291                                        (struct sockaddr *)&dstaddr,
1292                                        *kiblnd_tunables.kib_timeout * 1000);
1293         }
1294         if (rc != 0) {
1295                 /* Can't initiate address resolution:  */
1296                 CERROR("Can't resolve addr for %s: %d\n",
1297                        libcfs_nid2str(peer->ibp_nid), rc);
1298                 goto failed2;
1299         }
1300
1301         LASSERT (cmid->device != NULL);
1302         CDEBUG(D_NET, "%s: connection bound to %s:%pI4h:%s\n",
1303                libcfs_nid2str(peer->ibp_nid), dev->ibd_ifname,
1304                &dev->ibd_ifip, cmid->device->name);
1305
1306         return;
1307
1308  failed2:
1309         kiblnd_peer_connect_failed(peer, 1, rc);
1310         kiblnd_peer_decref(peer);               /* cmid's ref */
1311         rdma_destroy_id(cmid);
1312         return;
1313  failed:
1314         kiblnd_peer_connect_failed(peer, 1, rc);
1315 }
1316
1317 bool
1318 kiblnd_reconnect_peer(kib_peer_t *peer)
1319 {
1320         rwlock_t         *glock = &kiblnd_data.kib_global_lock;
1321         char             *reason = NULL;
1322         struct list_head  txs;
1323         unsigned long     flags;
1324
1325         INIT_LIST_HEAD(&txs);
1326
1327         write_lock_irqsave(glock, flags);
1328         if (peer->ibp_reconnecting == 0) {
1329                 if (peer->ibp_accepting)
1330                         reason = "accepting";
1331                 else if (peer->ibp_connecting)
1332                         reason = "connecting";
1333                 else if (!list_empty(&peer->ibp_conns))
1334                         reason = "connected";
1335                 else /* connected then closed */
1336                         reason = "closed";
1337
1338                 goto no_reconnect;
1339         }
1340
1341         LASSERT(!peer->ibp_accepting && !peer->ibp_connecting &&
1342                 list_empty(&peer->ibp_conns));
1343         peer->ibp_reconnecting = 0;
1344
1345         if (!kiblnd_peer_active(peer)) {
1346                 list_splice_init(&peer->ibp_tx_queue, &txs);
1347                 reason = "unlinked";
1348                 goto no_reconnect;
1349         }
1350
1351         peer->ibp_connecting++;
1352         peer->ibp_reconnected++;
1353         write_unlock_irqrestore(glock, flags);
1354
1355         kiblnd_connect_peer(peer);
1356         return true;
1357
1358  no_reconnect:
1359         write_unlock_irqrestore(glock, flags);
1360
1361         CWARN("Abort reconnection of %s: %s\n",
1362               libcfs_nid2str(peer->ibp_nid), reason);
1363         kiblnd_txlist_done(peer->ibp_ni, &txs, -ECONNABORTED);
1364         return false;
1365 }
1366
1367 void
1368 kiblnd_launch_tx (lnet_ni_t *ni, kib_tx_t *tx, lnet_nid_t nid)
1369 {
1370         kib_peer_t        *peer;
1371         kib_peer_t        *peer2;
1372         kib_conn_t        *conn;
1373         rwlock_t        *g_lock = &kiblnd_data.kib_global_lock;
1374         unsigned long      flags;
1375         int                rc;
1376
1377         /* If I get here, I've committed to send, so I complete the tx with
1378          * failure on any problems */
1379
1380         LASSERT (tx == NULL || tx->tx_conn == NULL); /* only set when assigned a conn */
1381         LASSERT (tx == NULL || tx->tx_nwrq > 0);     /* work items have been set up */
1382
1383         /* First time, just use a read lock since I expect to find my peer
1384          * connected */
1385         read_lock_irqsave(g_lock, flags);
1386
1387         peer = kiblnd_find_peer_locked(nid);
1388         if (peer != NULL && !list_empty(&peer->ibp_conns)) {
1389                 /* Found a peer with an established connection */
1390                 conn = kiblnd_get_conn_locked(peer);
1391                 kiblnd_conn_addref(conn); /* 1 ref for me... */
1392
1393                 read_unlock_irqrestore(g_lock, flags);
1394
1395                 if (tx != NULL)
1396                         kiblnd_queue_tx(tx, conn);
1397                 kiblnd_conn_decref(conn); /* ...to here */
1398                 return;
1399         }
1400
1401         read_unlock(g_lock);
1402         /* Re-try with a write lock */
1403         write_lock(g_lock);
1404
1405         peer = kiblnd_find_peer_locked(nid);
1406         if (peer != NULL) {
1407                 if (list_empty(&peer->ibp_conns)) {
1408                         /* found a peer, but it's still connecting... */
1409                         LASSERT(kiblnd_peer_connecting(peer));
1410                         if (tx != NULL)
1411                                 list_add_tail(&tx->tx_list,
1412                                                   &peer->ibp_tx_queue);
1413                         write_unlock_irqrestore(g_lock, flags);
1414                 } else {
1415                         conn = kiblnd_get_conn_locked(peer);
1416                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1417
1418                         write_unlock_irqrestore(g_lock, flags);
1419
1420                         if (tx != NULL)
1421                                 kiblnd_queue_tx(tx, conn);
1422                         kiblnd_conn_decref(conn); /* ...to here */
1423                 }
1424                 return;
1425         }
1426
1427         write_unlock_irqrestore(g_lock, flags);
1428
1429         /* Allocate a peer ready to add to the peer table and retry */
1430         rc = kiblnd_create_peer(ni, &peer, nid);
1431         if (rc != 0) {
1432                 CERROR("Can't create peer %s\n", libcfs_nid2str(nid));
1433                 if (tx != NULL) {
1434                         tx->tx_status = -EHOSTUNREACH;
1435                         tx->tx_waiting = 0;
1436                         kiblnd_tx_done(ni, tx);
1437                 }
1438                 return;
1439         }
1440
1441         write_lock_irqsave(g_lock, flags);
1442
1443         peer2 = kiblnd_find_peer_locked(nid);
1444         if (peer2 != NULL) {
1445                 if (list_empty(&peer2->ibp_conns)) {
1446                         /* found a peer, but it's still connecting... */
1447                         LASSERT(kiblnd_peer_connecting(peer2));
1448                         if (tx != NULL)
1449                                 list_add_tail(&tx->tx_list,
1450                                                   &peer2->ibp_tx_queue);
1451                         write_unlock_irqrestore(g_lock, flags);
1452                 } else {
1453                         conn = kiblnd_get_conn_locked(peer2);
1454                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1455
1456                         write_unlock_irqrestore(g_lock, flags);
1457
1458                         if (tx != NULL)
1459                                 kiblnd_queue_tx(tx, conn);
1460                         kiblnd_conn_decref(conn); /* ...to here */
1461                 }
1462
1463                 kiblnd_peer_decref(peer);
1464                 return;
1465         }
1466
1467         /* Brand new peer */
1468         LASSERT (peer->ibp_connecting == 0);
1469         peer->ibp_connecting = 1;
1470
1471         /* always called with a ref on ni, which prevents ni being shutdown */
1472         LASSERT (((kib_net_t *)ni->ni_data)->ibn_shutdown == 0);
1473
1474         if (tx != NULL)
1475                 list_add_tail(&tx->tx_list, &peer->ibp_tx_queue);
1476
1477         kiblnd_peer_addref(peer);
1478         list_add_tail(&peer->ibp_list, kiblnd_nid2peerlist(nid));
1479
1480         write_unlock_irqrestore(g_lock, flags);
1481
1482         kiblnd_connect_peer(peer);
1483         kiblnd_peer_decref(peer);
1484 }
1485
1486 int
1487 kiblnd_send (lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg)
1488 {
1489         lnet_hdr_t       *hdr = &lntmsg->msg_hdr;
1490         int               type = lntmsg->msg_type;
1491         lnet_process_id_t target = lntmsg->msg_target;
1492         int               target_is_router = lntmsg->msg_target_is_router;
1493         int               routing = lntmsg->msg_routing;
1494         unsigned int      payload_niov = lntmsg->msg_niov;
1495         struct kvec      *payload_iov = lntmsg->msg_iov;
1496         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
1497         unsigned int      payload_offset = lntmsg->msg_offset;
1498         unsigned int      payload_nob = lntmsg->msg_len;
1499         kib_msg_t        *ibmsg;
1500         kib_rdma_desc_t  *rd;
1501         kib_tx_t         *tx;
1502         int               nob;
1503         int               rc;
1504
1505         /* NB 'private' is different depending on what we're sending.... */
1506
1507         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1508                payload_nob, payload_niov, libcfs_id2str(target));
1509
1510         LASSERT (payload_nob == 0 || payload_niov > 0);
1511         LASSERT (payload_niov <= LNET_MAX_IOV);
1512
1513         /* Thread context */
1514         LASSERT (!in_interrupt());
1515         /* payload is either all vaddrs or all pages */
1516         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1517
1518         switch (type) {
1519         default:
1520                 LBUG();
1521                 return (-EIO);
1522
1523         case LNET_MSG_ACK:
1524                 LASSERT (payload_nob == 0);
1525                 break;
1526
1527         case LNET_MSG_GET:
1528                 if (routing || target_is_router)
1529                         break;                  /* send IMMEDIATE */
1530
1531                 /* is the REPLY message too small for RDMA? */
1532                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1533                 if (nob <= IBLND_MSG_SIZE)
1534                         break;                  /* send IMMEDIATE */
1535
1536                 tx = kiblnd_get_idle_tx(ni, target.nid);
1537                 if (tx == NULL) {
1538                         CERROR("Can't allocate txd for GET to %s\n",
1539                                libcfs_nid2str(target.nid));
1540                         return -ENOMEM;
1541                 }
1542
1543                 ibmsg = tx->tx_msg;
1544                 rd = &ibmsg->ibm_u.get.ibgm_rd;
1545                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0)
1546                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1547                                                  lntmsg->msg_md->md_niov,
1548                                                  lntmsg->msg_md->md_iov.iov,
1549                                                  0, lntmsg->msg_md->md_length);
1550                 else
1551                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1552                                                   lntmsg->msg_md->md_niov,
1553                                                   lntmsg->msg_md->md_iov.kiov,
1554                                                   0, lntmsg->msg_md->md_length);
1555                 if (rc != 0) {
1556                         CERROR("Can't setup GET sink for %s: %d\n",
1557                                libcfs_nid2str(target.nid), rc);
1558                         kiblnd_tx_done(ni, tx);
1559                         return -EIO;
1560                 }
1561
1562                 nob = offsetof(kib_get_msg_t, ibgm_rd.rd_frags[rd->rd_nfrags]);
1563                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1564                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1565
1566                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1567
1568                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1569                 if (tx->tx_lntmsg[1] == NULL) {
1570                         CERROR("Can't create reply for GET -> %s\n",
1571                                libcfs_nid2str(target.nid));
1572                         kiblnd_tx_done(ni, tx);
1573                         return -EIO;
1574                 }
1575
1576                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1577                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1578                 kiblnd_launch_tx(ni, tx, target.nid);
1579                 return 0;
1580
1581         case LNET_MSG_REPLY:
1582         case LNET_MSG_PUT:
1583                 /* Is the payload small enough not to need RDMA? */
1584                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob]);
1585                 if (nob <= IBLND_MSG_SIZE)
1586                         break;                  /* send IMMEDIATE */
1587
1588                 tx = kiblnd_get_idle_tx(ni, target.nid);
1589                 if (tx == NULL) {
1590                         CERROR("Can't allocate %s txd for %s\n",
1591                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1592                                libcfs_nid2str(target.nid));
1593                         return -ENOMEM;
1594                 }
1595
1596                 if (payload_kiov == NULL)
1597                         rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1598                                                  payload_niov, payload_iov,
1599                                                  payload_offset, payload_nob);
1600                 else
1601                         rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1602                                                   payload_niov, payload_kiov,
1603                                                   payload_offset, payload_nob);
1604                 if (rc != 0) {
1605                         CERROR("Can't setup PUT src for %s: %d\n",
1606                                libcfs_nid2str(target.nid), rc);
1607                         kiblnd_tx_done(ni, tx);
1608                         return -EIO;
1609                 }
1610
1611                 ibmsg = tx->tx_msg;
1612                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1613                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1614                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ, sizeof(kib_putreq_msg_t));
1615
1616                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1617                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1618                 kiblnd_launch_tx(ni, tx, target.nid);
1619                 return 0;
1620         }
1621
1622         /* send IMMEDIATE */
1623
1624         LASSERT (offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob])
1625                  <= IBLND_MSG_SIZE);
1626
1627         tx = kiblnd_get_idle_tx(ni, target.nid);
1628         if (tx == NULL) {
1629                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1630                         type, libcfs_nid2str(target.nid));
1631                 return -ENOMEM;
1632         }
1633
1634         ibmsg = tx->tx_msg;
1635         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1636
1637         if (payload_kiov != NULL)
1638                 lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1639                                     offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1640                                     payload_niov, payload_kiov,
1641                                     payload_offset, payload_nob);
1642         else
1643                 lnet_copy_iov2flat(IBLND_MSG_SIZE, ibmsg,
1644                                    offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1645                                    payload_niov, payload_iov,
1646                                    payload_offset, payload_nob);
1647
1648         nob = offsetof(kib_immediate_msg_t, ibim_payload[payload_nob]);
1649         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1650
1651         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1652         kiblnd_launch_tx(ni, tx, target.nid);
1653         return 0;
1654 }
1655
1656 static void
1657 kiblnd_reply (lnet_ni_t *ni, kib_rx_t *rx, lnet_msg_t *lntmsg)
1658 {
1659         lnet_process_id_t target = lntmsg->msg_target;
1660         unsigned int      niov = lntmsg->msg_niov;
1661         struct kvec      *iov = lntmsg->msg_iov;
1662         lnet_kiov_t      *kiov = lntmsg->msg_kiov;
1663         unsigned int      offset = lntmsg->msg_offset;
1664         unsigned int      nob = lntmsg->msg_len;
1665         kib_tx_t         *tx;
1666         int               rc;
1667
1668         tx = kiblnd_get_idle_tx(ni, rx->rx_conn->ibc_peer->ibp_nid);
1669         if (tx == NULL) {
1670                 CERROR("Can't get tx for REPLY to %s\n",
1671                        libcfs_nid2str(target.nid));
1672                 goto failed_0;
1673         }
1674
1675         if (nob == 0)
1676                 rc = 0;
1677         else if (kiov == NULL)
1678                 rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1679                                          niov, iov, offset, nob);
1680         else
1681                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1682                                           niov, kiov, offset, nob);
1683
1684         if (rc != 0) {
1685                 CERROR("Can't setup GET src for %s: %d\n",
1686                        libcfs_nid2str(target.nid), rc);
1687                 goto failed_1;
1688         }
1689
1690         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1691                               IBLND_MSG_GET_DONE, nob,
1692                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1693                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1694         if (rc < 0) {
1695                 CERROR("Can't setup rdma for GET from %s: %d\n",
1696                        libcfs_nid2str(target.nid), rc);
1697                 goto failed_1;
1698         }
1699         
1700         if (nob == 0) {
1701                 /* No RDMA: local completion may happen now! */
1702                 lnet_finalize(ni, lntmsg, 0);
1703         } else {
1704                 /* RDMA: lnet_finalize(lntmsg) when it
1705                  * completes */
1706                 tx->tx_lntmsg[0] = lntmsg;
1707         }
1708
1709         kiblnd_queue_tx(tx, rx->rx_conn);
1710         return;
1711
1712  failed_1:
1713         kiblnd_tx_done(ni, tx);
1714  failed_0:
1715         lnet_finalize(ni, lntmsg, -EIO);
1716 }
1717
1718 int
1719 kiblnd_recv(lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg, int delayed,
1720             unsigned int niov, struct kvec *iov, lnet_kiov_t *kiov,
1721             unsigned int offset, unsigned int mlen, unsigned int rlen)
1722 {
1723         kib_rx_t    *rx = private;
1724         kib_msg_t   *rxmsg = rx->rx_msg;
1725         kib_conn_t  *conn = rx->rx_conn;
1726         kib_tx_t    *tx;
1727         int          nob;
1728         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1729         int          rc = 0;
1730
1731         LASSERT (mlen <= rlen);
1732         LASSERT (!in_interrupt());
1733         /* Either all pages or all vaddrs */
1734         LASSERT (!(kiov != NULL && iov != NULL));
1735
1736         switch (rxmsg->ibm_type) {
1737         default:
1738                 LBUG();
1739
1740         case IBLND_MSG_IMMEDIATE:
1741                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[rlen]);
1742                 if (nob > rx->rx_nob) {
1743                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1744                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1745                                 nob, rx->rx_nob);
1746                         rc = -EPROTO;
1747                         break;
1748                 }
1749
1750                 if (kiov != NULL)
1751                         lnet_copy_flat2kiov(niov, kiov, offset,
1752                                             IBLND_MSG_SIZE, rxmsg,
1753                                             offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1754                                             mlen);
1755                 else
1756                         lnet_copy_flat2iov(niov, iov, offset,
1757                                            IBLND_MSG_SIZE, rxmsg,
1758                                            offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1759                                            mlen);
1760                 lnet_finalize (ni, lntmsg, 0);
1761                 break;
1762
1763         case IBLND_MSG_PUT_REQ: {
1764                 kib_msg_t       *txmsg;
1765                 kib_rdma_desc_t *rd;
1766
1767                 if (mlen == 0) {
1768                         lnet_finalize(ni, lntmsg, 0);
1769                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK, 0,
1770                                                rxmsg->ibm_u.putreq.ibprm_cookie);
1771                         break;
1772                 }
1773
1774                 tx = kiblnd_get_idle_tx(ni, conn->ibc_peer->ibp_nid);
1775                 if (tx == NULL) {
1776                         CERROR("Can't allocate tx for %s\n",
1777                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1778                         /* Not replying will break the connection */
1779                         rc = -ENOMEM;
1780                         break;
1781                 }
1782
1783                 txmsg = tx->tx_msg;
1784                 rd = &txmsg->ibm_u.putack.ibpam_rd;
1785                 if (kiov == NULL)
1786                         rc = kiblnd_setup_rd_iov(ni, tx, rd,
1787                                                  niov, iov, offset, mlen);
1788                 else
1789                         rc = kiblnd_setup_rd_kiov(ni, tx, rd,
1790                                                   niov, kiov, offset, mlen);
1791                 if (rc != 0) {
1792                         CERROR("Can't setup PUT sink for %s: %d\n",
1793                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1794                         kiblnd_tx_done(ni, tx);
1795                         /* tell peer it's over */
1796                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK, rc,
1797                                                rxmsg->ibm_u.putreq.ibprm_cookie);
1798                         break;
1799                 }
1800
1801                 nob = offsetof(kib_putack_msg_t, ibpam_rd.rd_frags[rd->rd_nfrags]);
1802                 txmsg->ibm_u.putack.ibpam_src_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1803                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1804
1805                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1806
1807                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1808                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1809                 kiblnd_queue_tx(tx, conn);
1810
1811                 /* reposted buffer reserved for PUT_DONE */
1812                 post_credit = IBLND_POSTRX_NO_CREDIT;
1813                 break;
1814                 }
1815
1816         case IBLND_MSG_GET_REQ:
1817                 if (lntmsg != NULL) {
1818                         /* Optimized GET; RDMA lntmsg's payload */
1819                         kiblnd_reply(ni, rx, lntmsg);
1820                 } else {
1821                         /* GET didn't match anything */
1822                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1823                                                -ENODATA,
1824                                                rxmsg->ibm_u.get.ibgm_cookie);
1825                 }
1826                 break;
1827         }
1828
1829         kiblnd_post_rx(rx, post_credit);
1830         return rc;
1831 }
1832
1833 int
1834 kiblnd_thread_start(int (*fn)(void *arg), void *arg, char *name)
1835 {
1836         struct task_struct *task = kthread_run(fn, arg, name);
1837
1838         if (IS_ERR(task))
1839                 return PTR_ERR(task);
1840
1841         atomic_inc(&kiblnd_data.kib_nthreads);
1842         return 0;
1843 }
1844
1845 static void
1846 kiblnd_thread_fini (void)
1847 {
1848         atomic_dec (&kiblnd_data.kib_nthreads);
1849 }
1850
1851 static void
1852 kiblnd_peer_alive (kib_peer_t *peer)
1853 {
1854         /* This is racy, but everyone's only writing cfs_time_current() */
1855         peer->ibp_last_alive = cfs_time_current();
1856         smp_mb();
1857 }
1858
1859 static void
1860 kiblnd_peer_notify (kib_peer_t *peer)
1861 {
1862         int           error = 0;
1863         cfs_time_t    last_alive = 0;
1864         unsigned long flags;
1865
1866         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1867
1868         if (kiblnd_peer_idle(peer) && peer->ibp_error != 0) {
1869                 error = peer->ibp_error;
1870                 peer->ibp_error = 0;
1871
1872                 last_alive = peer->ibp_last_alive;
1873         }
1874
1875         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1876
1877         if (error != 0)
1878                 lnet_notify(peer->ibp_ni,
1879                             peer->ibp_nid, 0, last_alive);
1880 }
1881
1882 void
1883 kiblnd_close_conn_locked (kib_conn_t *conn, int error)
1884 {
1885         /* This just does the immediate housekeeping.  'error' is zero for a
1886          * normal shutdown which can happen only after the connection has been
1887          * established.  If the connection is established, schedule the
1888          * connection to be finished off by the connd.  Otherwise the connd is
1889          * already dealing with it (either to set it up or tear it down).
1890          * Caller holds kib_global_lock exclusively in irq context */
1891         kib_peer_t       *peer = conn->ibc_peer;
1892         kib_dev_t        *dev;
1893         unsigned long     flags;
1894
1895         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1896
1897         if (error != 0 && conn->ibc_comms_error == 0)
1898                 conn->ibc_comms_error = error;
1899
1900         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
1901                 return; /* already being handled  */
1902
1903         if (error == 0 &&
1904             list_empty(&conn->ibc_tx_noops) &&
1905             list_empty(&conn->ibc_tx_queue) &&
1906             list_empty(&conn->ibc_tx_queue_rsrvd) &&
1907             list_empty(&conn->ibc_tx_queue_nocred) &&
1908             list_empty(&conn->ibc_active_txs)) {
1909                 CDEBUG(D_NET, "closing conn to %s\n", 
1910                        libcfs_nid2str(peer->ibp_nid));
1911         } else {
1912                 CNETERR("Closing conn to %s: error %d%s%s%s%s%s\n",
1913                        libcfs_nid2str(peer->ibp_nid), error,
1914                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
1915                        list_empty(&conn->ibc_tx_noops) ? "" : "(sending_noops)",
1916                        list_empty(&conn->ibc_tx_queue_rsrvd) ?
1917                                                 "" : "(sending_rsrvd)",
1918                        list_empty(&conn->ibc_tx_queue_nocred) ?
1919                                                  "" : "(sending_nocred)",
1920                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
1921         }
1922
1923         dev = ((kib_net_t *)peer->ibp_ni->ni_data)->ibn_dev;
1924         list_del(&conn->ibc_list);
1925         /* connd (see below) takes over ibc_list's ref */
1926
1927         if (list_empty(&peer->ibp_conns) &&    /* no more conns */
1928             kiblnd_peer_active(peer)) {         /* still in peer table */
1929                 kiblnd_unlink_peer_locked(peer);
1930
1931                 /* set/clear error on last conn */
1932                 peer->ibp_error = conn->ibc_comms_error;
1933         }
1934
1935         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
1936
1937         if (error != 0 &&
1938             kiblnd_dev_can_failover(dev)) {
1939                 list_add_tail(&dev->ibd_fail_list,
1940                               &kiblnd_data.kib_failed_devs);
1941                 wake_up(&kiblnd_data.kib_failover_waitq);
1942         }
1943
1944         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
1945
1946         list_add_tail(&conn->ibc_list, &kiblnd_data.kib_connd_conns);
1947         wake_up(&kiblnd_data.kib_connd_waitq);
1948
1949         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
1950 }
1951
1952 void
1953 kiblnd_close_conn(kib_conn_t *conn, int error)
1954 {
1955         unsigned long flags;
1956
1957         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1958
1959         kiblnd_close_conn_locked(conn, error);
1960
1961         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1962 }
1963
1964 static void
1965 kiblnd_handle_early_rxs(kib_conn_t *conn)
1966 {
1967         unsigned long    flags;
1968         kib_rx_t        *rx;
1969
1970         LASSERT(!in_interrupt());
1971         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1972
1973         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1974         while (!list_empty(&conn->ibc_early_rxs)) {
1975                 rx = list_entry(conn->ibc_early_rxs.next,
1976                                     kib_rx_t, rx_list);
1977                 list_del(&rx->rx_list);
1978                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1979
1980                 kiblnd_handle_rx(rx);
1981
1982                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1983         }
1984         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1985 }
1986
1987 static void
1988 kiblnd_abort_txs(kib_conn_t *conn, struct list_head *txs)
1989 {
1990         struct list_head         zombies = LIST_HEAD_INIT(zombies);
1991         struct list_head        *tmp;
1992         struct list_head        *nxt;
1993         kib_tx_t                *tx;
1994
1995         spin_lock(&conn->ibc_lock);
1996
1997         list_for_each_safe(tmp, nxt, txs) {
1998                 tx = list_entry(tmp, kib_tx_t, tx_list);
1999
2000                 if (txs == &conn->ibc_active_txs) {
2001                         LASSERT(!tx->tx_queued);
2002                         LASSERT(tx->tx_waiting ||
2003                                 tx->tx_sending != 0);
2004                 } else {
2005                         LASSERT(tx->tx_queued);
2006                 }
2007
2008                 tx->tx_status = -ECONNABORTED;
2009                 tx->tx_waiting = 0;
2010
2011                 if (tx->tx_sending == 0) {
2012                         tx->tx_queued = 0;
2013                         list_del(&tx->tx_list);
2014                         list_add(&tx->tx_list, &zombies);
2015                 }
2016         }
2017
2018         spin_unlock(&conn->ibc_lock);
2019
2020         kiblnd_txlist_done(conn->ibc_peer->ibp_ni, &zombies, -ECONNABORTED);
2021 }
2022
2023 static void
2024 kiblnd_finalise_conn (kib_conn_t *conn)
2025 {
2026         LASSERT (!in_interrupt());
2027         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
2028
2029         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
2030
2031         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
2032          * for connections that didn't get as far as being connected, because
2033          * rdma_disconnect() does this for free. */
2034         kiblnd_abort_receives(conn);
2035
2036         /* Complete all tx descs not waiting for sends to complete.
2037          * NB we should be safe from RDMA now that the QP has changed state */
2038
2039         kiblnd_abort_txs(conn, &conn->ibc_tx_noops);
2040         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
2041         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
2042         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
2043         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
2044
2045         kiblnd_handle_early_rxs(conn);
2046 }
2047
2048 static void
2049 kiblnd_peer_connect_failed(kib_peer_t *peer, int active, int error)
2050 {
2051         struct list_head zombies = LIST_HEAD_INIT(zombies);
2052         unsigned long   flags;
2053
2054         LASSERT (error != 0);
2055         LASSERT (!in_interrupt());
2056
2057         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2058
2059         if (active) {
2060                 LASSERT (peer->ibp_connecting > 0);
2061                 peer->ibp_connecting--;
2062         } else {
2063                 LASSERT (peer->ibp_accepting > 0);
2064                 peer->ibp_accepting--;
2065         }
2066
2067         if (kiblnd_peer_connecting(peer)) {
2068                 /* another connection attempt under way... */
2069                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2070                                         flags);
2071                 return;
2072         }
2073
2074         peer->ibp_reconnected = 0;
2075         if (list_empty(&peer->ibp_conns)) {
2076                 /* Take peer's blocked transmits to complete with error */
2077                 list_add(&zombies, &peer->ibp_tx_queue);
2078                 list_del_init(&peer->ibp_tx_queue);
2079
2080                 if (kiblnd_peer_active(peer))
2081                         kiblnd_unlink_peer_locked(peer);
2082
2083                 peer->ibp_error = error;
2084         } else {
2085                 /* Can't have blocked transmits if there are connections */
2086                 LASSERT(list_empty(&peer->ibp_tx_queue));
2087         }
2088
2089         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2090
2091         kiblnd_peer_notify(peer);
2092
2093         if (list_empty(&zombies))
2094                 return;
2095
2096         CNETERR("Deleting messages for %s: connection failed\n",
2097                 libcfs_nid2str(peer->ibp_nid));
2098
2099         kiblnd_txlist_done(peer->ibp_ni, &zombies, -EHOSTUNREACH);
2100 }
2101
2102 static void
2103 kiblnd_connreq_done(kib_conn_t *conn, int status)
2104 {
2105         kib_peer_t       *peer = conn->ibc_peer;
2106         kib_tx_t         *tx;
2107         struct list_head txs;
2108         unsigned long    flags;
2109         int              active;
2110
2111         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2112
2113         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
2114                libcfs_nid2str(peer->ibp_nid), active,
2115                conn->ibc_version, status);
2116
2117         LASSERT (!in_interrupt());
2118         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2119                   peer->ibp_connecting > 0) ||
2120                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2121                   peer->ibp_accepting > 0));
2122
2123         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2124         conn->ibc_connvars = NULL;
2125
2126         if (status != 0) {
2127                 /* failed to establish connection */
2128                 kiblnd_peer_connect_failed(peer, active, status);
2129                 kiblnd_finalise_conn(conn);
2130                 return;
2131         }
2132
2133         /* connection established */
2134         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2135
2136         conn->ibc_last_send = jiffies;
2137         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2138         kiblnd_peer_alive(peer);
2139
2140         /* Add conn to peer's list and nuke any dangling conns from a different
2141          * peer instance... */
2142         kiblnd_conn_addref(conn);       /* +1 ref for ibc_list */
2143         list_add(&conn->ibc_list, &peer->ibp_conns);
2144         peer->ibp_reconnected = 0;
2145         if (active)
2146                 peer->ibp_connecting--;
2147         else
2148                 peer->ibp_accepting--;
2149
2150         if (peer->ibp_version == 0) {
2151                 peer->ibp_version     = conn->ibc_version;
2152                 peer->ibp_incarnation = conn->ibc_incarnation;
2153         }
2154
2155         if (peer->ibp_version     != conn->ibc_version ||
2156             peer->ibp_incarnation != conn->ibc_incarnation) {
2157                 kiblnd_close_stale_conns_locked(peer, conn->ibc_version,
2158                                                 conn->ibc_incarnation);
2159                 peer->ibp_version     = conn->ibc_version;
2160                 peer->ibp_incarnation = conn->ibc_incarnation;
2161         }
2162
2163         /* grab pending txs while I have the lock */
2164         list_add(&txs, &peer->ibp_tx_queue);
2165         list_del_init(&peer->ibp_tx_queue);
2166
2167         if (!kiblnd_peer_active(peer) ||        /* peer has been deleted */
2168             conn->ibc_comms_error != 0) {       /* error has happened already */
2169                 lnet_ni_t *ni = peer->ibp_ni;
2170
2171                 /* start to shut down connection */
2172                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2173                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2174
2175                 kiblnd_txlist_done(ni, &txs, -ECONNABORTED);
2176
2177                 return;
2178         }
2179
2180         /* refcount taken by cmid is not reliable after I released the glock
2181          * because this connection is visible to other threads now, another
2182          * thread can find and close this connection right after I released
2183          * the glock, if kiblnd_cm_callback for RDMA_CM_EVENT_DISCONNECTED is
2184          * called, it can release the connection refcount taken by cmid.
2185          * It means the connection could be destroyed before I finish my
2186          * operations on it.
2187          */
2188         kiblnd_conn_addref(conn);
2189         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2190
2191         /* Schedule blocked txs */
2192         spin_lock(&conn->ibc_lock);
2193         while (!list_empty(&txs)) {
2194                 tx = list_entry(txs.next, kib_tx_t, tx_list);
2195                 list_del(&tx->tx_list);
2196
2197                 kiblnd_queue_tx_locked(tx, conn);
2198         }
2199         spin_unlock(&conn->ibc_lock);
2200
2201         kiblnd_check_sends(conn);
2202
2203         /* schedule blocked rxs */
2204         kiblnd_handle_early_rxs(conn);
2205
2206         kiblnd_conn_decref(conn);
2207 }
2208
2209 static void
2210 kiblnd_reject(struct rdma_cm_id *cmid, kib_rej_t *rej)
2211 {
2212         int          rc;
2213
2214         rc = rdma_reject(cmid, rej, sizeof(*rej));
2215
2216         if (rc != 0)
2217                 CWARN("Error %d sending reject\n", rc);
2218 }
2219
2220 static int
2221 kiblnd_passive_connect(struct rdma_cm_id *cmid, void *priv, int priv_nob)
2222 {
2223         rwlock_t                *g_lock = &kiblnd_data.kib_global_lock;
2224         kib_msg_t             *reqmsg = priv;
2225         kib_msg_t             *ackmsg;
2226         kib_dev_t             *ibdev;
2227         kib_peer_t            *peer;
2228         kib_peer_t            *peer2;
2229         kib_conn_t            *conn;
2230         lnet_ni_t             *ni  = NULL;
2231         kib_net_t             *net = NULL;
2232         lnet_nid_t             nid;
2233         struct rdma_conn_param cp;
2234         kib_rej_t              rej;
2235         int                    version = IBLND_MSG_VERSION;
2236         unsigned long          flags;
2237         int                    rc;
2238         struct sockaddr_in    *peer_addr;
2239         LASSERT (!in_interrupt());
2240
2241         /* cmid inherits 'context' from the corresponding listener id */
2242         ibdev = (kib_dev_t *)cmid->context;
2243         LASSERT (ibdev != NULL);
2244
2245         memset(&rej, 0, sizeof(rej));
2246         rej.ibr_magic                = IBLND_MSG_MAGIC;
2247         rej.ibr_why                  = IBLND_REJECT_FATAL;
2248         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2249
2250         peer_addr = (struct sockaddr_in *)&(cmid->route.addr.dst_addr);
2251         if (*kiblnd_tunables.kib_require_priv_port &&
2252             ntohs(peer_addr->sin_port) >= PROT_SOCK) {
2253                 __u32 ip = ntohl(peer_addr->sin_addr.s_addr);
2254                 CERROR("Peer's port (%pI4h:%hu) is not privileged\n",
2255                        &ip, ntohs(peer_addr->sin_port));
2256                 goto failed;
2257         }
2258
2259         if (priv_nob < offsetof(kib_msg_t, ibm_type)) {
2260                 CERROR("Short connection request\n");
2261                 goto failed;
2262         }
2263
2264         /* Future protocol version compatibility support!  If the
2265          * o2iblnd-specific protocol changes, or when LNET unifies
2266          * protocols over all LNDs, the initial connection will
2267          * negotiate a protocol version.  I trap this here to avoid
2268          * console errors; the reject tells the peer which protocol I
2269          * speak. */
2270         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2271             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2272                 goto failed;
2273         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2274             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2275             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2276                 goto failed;
2277         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2278             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2279             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2280                 goto failed;
2281
2282         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2283         if (rc != 0) {
2284                 CERROR("Can't parse connection request: %d\n", rc);
2285                 goto failed;
2286         }
2287
2288         nid = reqmsg->ibm_srcnid;
2289         ni  = lnet_net2ni(LNET_NIDNET(reqmsg->ibm_dstnid));
2290
2291         if (ni != NULL) {
2292                 net = (kib_net_t *)ni->ni_data;
2293                 rej.ibr_incarnation = net->ibn_incarnation;
2294         }
2295
2296         if (ni == NULL ||                         /* no matching net */
2297             ni->ni_nid != reqmsg->ibm_dstnid ||   /* right NET, wrong NID! */
2298             net->ibn_dev != ibdev) {              /* wrong device */
2299                 CERROR("Can't accept conn from %s on %s (%s:%d:%pI4h): "
2300                        "bad dst nid %s\n", libcfs_nid2str(nid),
2301                        ni == NULL ? "NA" : libcfs_nid2str(ni->ni_nid),
2302                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2303                         &ibdev->ibd_ifip,
2304                        libcfs_nid2str(reqmsg->ibm_dstnid));
2305
2306                 goto failed;
2307         }
2308
2309        /* check time stamp as soon as possible */
2310         if (reqmsg->ibm_dststamp != 0 &&
2311             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2312                 CWARN("Stale connection request\n");
2313                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2314                 goto failed;
2315         }
2316
2317         /* I can accept peer's version */
2318         version = reqmsg->ibm_version;
2319
2320         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2321                 CERROR("Unexpected connreq msg type: %x from %s\n",
2322                        reqmsg->ibm_type, libcfs_nid2str(nid));
2323                 goto failed;
2324         }
2325
2326         if (reqmsg->ibm_u.connparams.ibcp_queue_depth >
2327             kiblnd_msg_queue_size(version, ni)) {
2328                 CERROR("Can't accept conn from %s, queue depth too large: "
2329                        " %d (<=%d wanted)\n",
2330                        libcfs_nid2str(nid),
2331                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2332                        kiblnd_msg_queue_size(version, ni));
2333
2334                 if (version == IBLND_MSG_VERSION)
2335                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2336
2337                 goto failed;
2338         }
2339
2340         if (reqmsg->ibm_u.connparams.ibcp_max_frags >
2341             kiblnd_rdma_frags(version, ni)) {
2342                 CWARN("Can't accept conn from %s (version %x): "
2343                       "max_frags %d too large (%d wanted)\n",
2344                       libcfs_nid2str(nid), version,
2345                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2346                       kiblnd_rdma_frags(version, ni));
2347
2348                 if (version >= IBLND_MSG_VERSION)
2349                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2350
2351                 goto failed;
2352         } else if (reqmsg->ibm_u.connparams.ibcp_max_frags <
2353                    kiblnd_rdma_frags(version, ni) &&
2354                    net->ibn_fmr_ps == NULL) {
2355                 CWARN("Can't accept conn from %s (version %x): "
2356                       "max_frags %d incompatible without FMR pool "
2357                       "(%d wanted)\n",
2358                       libcfs_nid2str(nid), version,
2359                       reqmsg->ibm_u.connparams.ibcp_max_frags,
2360                       kiblnd_rdma_frags(version, ni));
2361
2362                 if (version == IBLND_MSG_VERSION)
2363                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2364
2365                 goto failed;
2366         }
2367
2368         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2369                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2370                        libcfs_nid2str(nid),
2371                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2372                        IBLND_MSG_SIZE);
2373                 goto failed;
2374         }
2375
2376         /* assume 'nid' is a new peer; create  */
2377         rc = kiblnd_create_peer(ni, &peer, nid);
2378         if (rc != 0) {
2379                 CERROR("Can't create peer for %s\n", libcfs_nid2str(nid));
2380                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2381                 goto failed;
2382         }
2383
2384         /* We have validated the peer's parameters so use those */
2385         peer->ibp_max_frags = reqmsg->ibm_u.connparams.ibcp_max_frags;
2386         peer->ibp_queue_depth = reqmsg->ibm_u.connparams.ibcp_queue_depth;
2387
2388         write_lock_irqsave(g_lock, flags);
2389
2390         peer2 = kiblnd_find_peer_locked(nid);
2391         if (peer2 != NULL) {
2392                 if (peer2->ibp_version == 0) {
2393                         peer2->ibp_version     = version;
2394                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2395                 }
2396
2397                 /* not the guy I've talked with */
2398                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2399                     peer2->ibp_version     != version) {
2400                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2401
2402                         if (kiblnd_peer_active(peer2)) {
2403                                 peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2404                                 peer2->ibp_version = version;
2405                         }
2406                         write_unlock_irqrestore(g_lock, flags);
2407
2408                         CWARN("Conn stale %s version %x/%x incarnation "LPU64"/"LPU64"\n",
2409                               libcfs_nid2str(nid), peer2->ibp_version, version,
2410                               peer2->ibp_incarnation, reqmsg->ibm_srcstamp);
2411
2412                         kiblnd_peer_decref(peer);
2413                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2414                         goto failed;
2415                 }
2416
2417                 /* tie-break connection race in favour of the higher NID */
2418                 if (peer2->ibp_connecting != 0 &&
2419                     nid < ni->ni_nid) {
2420                         write_unlock_irqrestore(g_lock, flags);
2421
2422                         CWARN("Conn race %s\n", libcfs_nid2str(peer2->ibp_nid));
2423
2424                         kiblnd_peer_decref(peer);
2425                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2426                         goto failed;
2427                 }
2428                 /*
2429                  * passive connection is allowed even this peer is waiting for
2430                  * reconnection.
2431                  */
2432                 peer2->ibp_reconnecting = 0;
2433                 peer2->ibp_accepting++;
2434                 kiblnd_peer_addref(peer2);
2435
2436                 /* Race with kiblnd_launch_tx (active connect) to create peer
2437                  * so copy validated parameters since we now know what the
2438                  * peer's limits are */
2439                 peer2->ibp_max_frags = peer->ibp_max_frags;
2440                 peer2->ibp_queue_depth = peer->ibp_queue_depth;
2441
2442                 write_unlock_irqrestore(g_lock, flags);
2443                 kiblnd_peer_decref(peer);
2444                 peer = peer2;
2445         } else {
2446                 /* Brand new peer */
2447                 LASSERT (peer->ibp_accepting == 0);
2448                 LASSERT (peer->ibp_version == 0 &&
2449                          peer->ibp_incarnation == 0);
2450
2451                 peer->ibp_accepting   = 1;
2452                 peer->ibp_version     = version;
2453                 peer->ibp_incarnation = reqmsg->ibm_srcstamp;
2454
2455                 /* I have a ref on ni that prevents it being shutdown */
2456                 LASSERT (net->ibn_shutdown == 0);
2457
2458                 kiblnd_peer_addref(peer);
2459                 list_add_tail(&peer->ibp_list, kiblnd_nid2peerlist(nid));
2460
2461                 write_unlock_irqrestore(g_lock, flags);
2462         }
2463
2464         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_PASSIVE_WAIT, version);
2465         if (conn == NULL) {
2466                 kiblnd_peer_connect_failed(peer, 0, -ENOMEM);
2467                 kiblnd_peer_decref(peer);
2468                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2469                 goto failed;
2470         }
2471
2472         /* conn now "owns" cmid, so I return success from here on to ensure the
2473          * CM callback doesn't destroy cmid. */
2474         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2475         conn->ibc_credits          = conn->ibc_queue_depth;
2476         conn->ibc_reserved_credits = conn->ibc_queue_depth;
2477         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2478                 IBLND_OOB_MSGS(version) <= IBLND_RX_MSGS(conn));
2479
2480         ackmsg = &conn->ibc_connvars->cv_msg;
2481         memset(ackmsg, 0, sizeof(*ackmsg));
2482
2483         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2484                         sizeof(ackmsg->ibm_u.connparams));
2485         ackmsg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2486         ackmsg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2487         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2488
2489         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2490
2491         memset(&cp, 0, sizeof(cp));
2492         cp.private_data        = ackmsg;
2493         cp.private_data_len    = ackmsg->ibm_nob;
2494         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2495         cp.initiator_depth     = 0;
2496         cp.flow_control        = 1;
2497         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2498         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2499
2500         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2501
2502         rc = rdma_accept(cmid, &cp);
2503         if (rc != 0) {
2504                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2505                 rej.ibr_version = version;
2506                 rej.ibr_why     = IBLND_REJECT_FATAL;
2507
2508                 kiblnd_reject(cmid, &rej);
2509                 kiblnd_connreq_done(conn, rc);
2510                 kiblnd_conn_decref(conn);
2511         }
2512
2513         lnet_ni_decref(ni);
2514         return 0;
2515
2516  failed:
2517         if (ni != NULL)
2518                 lnet_ni_decref(ni);
2519
2520         rej.ibr_version = version;
2521         rej.ibr_cp.ibcp_queue_depth = kiblnd_msg_queue_size(version, ni);
2522         rej.ibr_cp.ibcp_max_frags   = kiblnd_rdma_frags(version, ni);
2523         kiblnd_reject(cmid, &rej);
2524
2525         return -ECONNREFUSED;
2526 }
2527
2528 static void
2529 kiblnd_check_reconnect(kib_conn_t *conn, int version,
2530                        __u64 incarnation, int why, kib_connparams_t *cp)
2531 {
2532         rwlock_t        *glock = &kiblnd_data.kib_global_lock;
2533         kib_peer_t      *peer = conn->ibc_peer;
2534         char            *reason;
2535         int              msg_size = IBLND_MSG_SIZE;
2536         int              frag_num = -1;
2537         int              queue_dep = -1;
2538         bool             reconnect;
2539         unsigned long    flags;
2540
2541         LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2542         LASSERT(peer->ibp_connecting > 0);      /* 'conn' at least */
2543         LASSERT(!peer->ibp_reconnecting);
2544
2545         if (cp) {
2546                 msg_size        = cp->ibcp_max_msg_size;
2547                 frag_num        = cp->ibcp_max_frags;
2548                 queue_dep       = cp->ibcp_queue_depth;
2549         }
2550
2551         write_lock_irqsave(glock, flags);
2552         /* retry connection if it's still needed and no other connection
2553          * attempts (active or passive) are in progress
2554          * NB: reconnect is still needed even when ibp_tx_queue is
2555          * empty if ibp_version != version because reconnect may be
2556          * initiated by kiblnd_query() */
2557         reconnect = (!list_empty(&peer->ibp_tx_queue) ||
2558                      peer->ibp_version != version) &&
2559                     peer->ibp_connecting == 1 &&
2560                     peer->ibp_accepting == 0;
2561         if (!reconnect) {
2562                 reason = "no need";
2563                 goto out;
2564         }
2565
2566         switch (why) {
2567         default:
2568                 reason = "Unknown";
2569                 break;
2570
2571         case IBLND_REJECT_RDMA_FRAGS: {
2572                 struct lnet_ioctl_config_lnd_tunables *tunables;
2573
2574                 if (!cp) {
2575                         reason = "can't negotiate max frags";
2576                         goto out;
2577                 }
2578                 tunables = peer->ibp_ni->ni_lnd_tunables;
2579                 if (!tunables->lt_tun_u.lt_o2ib.lnd_map_on_demand) {
2580                         reason = "map_on_demand must be enabled";
2581                         goto out;
2582                 }
2583                 if (conn->ibc_max_frags <= frag_num) {
2584                         reason = "unsupported max frags";
2585                         goto out;
2586                 }
2587
2588                 peer->ibp_max_frags = frag_num;
2589                 reason = "rdma fragments";
2590                 break;
2591         }
2592         case IBLND_REJECT_MSG_QUEUE_SIZE:
2593                 if (!cp) {
2594                         reason = "can't negotiate queue depth";
2595                         goto out;
2596                 }
2597                 if (conn->ibc_queue_depth <= queue_dep) {
2598                         reason = "unsupported queue depth";
2599                         goto out;
2600                 }
2601
2602                 peer->ibp_queue_depth = queue_dep;
2603                 reason = "queue depth";
2604                 break;
2605
2606         case IBLND_REJECT_CONN_STALE:
2607                 reason = "stale";
2608                 break;
2609
2610         case IBLND_REJECT_CONN_RACE:
2611                 reason = "conn race";
2612                 break;
2613
2614         case IBLND_REJECT_CONN_UNCOMPAT:
2615                 reason = "version negotiation";
2616                 break;
2617         }
2618
2619         conn->ibc_reconnect = 1;
2620         peer->ibp_reconnecting = 1;
2621         peer->ibp_version = version;
2622         if (incarnation != 0)
2623                 peer->ibp_incarnation = incarnation;
2624  out:
2625         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2626
2627         CNETERR("%s: %s (%s), %x, %x, msg_size: %d, queue_depth: %d/%d, max_frags: %d/%d\n",
2628                 libcfs_nid2str(peer->ibp_nid),
2629                 reconnect ? "reconnect" : "don't reconnect",
2630                 reason, IBLND_MSG_VERSION, version, msg_size,
2631                 conn->ibc_queue_depth, queue_dep,
2632                 conn->ibc_max_frags, frag_num);
2633         /*
2634          * if conn::ibc_reconnect is TRUE, connd will reconnect to the peer
2635          * while destroying the zombie
2636          */
2637 }
2638
2639 static void
2640 kiblnd_rejected (kib_conn_t *conn, int reason, void *priv, int priv_nob)
2641 {
2642         kib_peer_t    *peer = conn->ibc_peer;
2643
2644         LASSERT (!in_interrupt());
2645         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2646
2647         switch (reason) {
2648         case IB_CM_REJ_STALE_CONN:
2649                 kiblnd_check_reconnect(conn, IBLND_MSG_VERSION, 0,
2650                                        IBLND_REJECT_CONN_STALE, NULL);
2651                 break;
2652
2653         case IB_CM_REJ_INVALID_SERVICE_ID:
2654                 CNETERR("%s rejected: no listener at %d\n",
2655                         libcfs_nid2str(peer->ibp_nid),
2656                         *kiblnd_tunables.kib_service);
2657                 break;
2658
2659         case IB_CM_REJ_CONSUMER_DEFINED:
2660                 if (priv_nob >= offsetof(kib_rej_t, ibr_padding)) {
2661                         kib_rej_t        *rej         = priv;
2662                         kib_connparams_t *cp          = NULL;
2663                         int               flip        = 0;
2664                         __u64             incarnation = -1;
2665
2666                         /* NB. default incarnation is -1 because:
2667                          * a) V1 will ignore dst incarnation in connreq.
2668                          * b) V2 will provide incarnation while rejecting me,
2669                          *    -1 will be overwrote.
2670                          *
2671                          * if I try to connect to a V1 peer with V2 protocol,
2672                          * it rejected me then upgrade to V2, I have no idea
2673                          * about the upgrading and try to reconnect with V1,
2674                          * in this case upgraded V2 can find out I'm trying to
2675                          * talk to the old guy and reject me(incarnation is -1). 
2676                          */
2677
2678                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2679                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2680                                 __swab32s(&rej->ibr_magic);
2681                                 __swab16s(&rej->ibr_version);
2682                                 flip = 1;
2683                         }
2684
2685                         if (priv_nob >= sizeof(kib_rej_t) &&
2686                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2687                                 /* priv_nob is always 148 in current version
2688                                  * of OFED, so we still need to check version.
2689                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE) */
2690                                 cp = &rej->ibr_cp;
2691
2692                                 if (flip) {
2693                                         __swab64s(&rej->ibr_incarnation);
2694                                         __swab16s(&cp->ibcp_queue_depth);
2695                                         __swab16s(&cp->ibcp_max_frags);
2696                                         __swab32s(&cp->ibcp_max_msg_size);
2697                                 }
2698
2699                                 incarnation = rej->ibr_incarnation;
2700                         }
2701
2702                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2703                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2704                                 CERROR("%s rejected: consumer defined fatal error\n",
2705                                        libcfs_nid2str(peer->ibp_nid));
2706                                 break;
2707                         }
2708
2709                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2710                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2711                                 CERROR("%s rejected: o2iblnd version %x error\n",
2712                                        libcfs_nid2str(peer->ibp_nid),
2713                                        rej->ibr_version);
2714                                 break;
2715                         }
2716
2717                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2718                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2719                                 CDEBUG(D_NET, "rejected by old version peer %s: %x\n",
2720                                        libcfs_nid2str(peer->ibp_nid), rej->ibr_version);
2721
2722                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2723                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2724                         }
2725
2726                         switch (rej->ibr_why) {
2727                         case IBLND_REJECT_CONN_RACE:
2728                         case IBLND_REJECT_CONN_STALE:
2729                         case IBLND_REJECT_CONN_UNCOMPAT:
2730                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2731                         case IBLND_REJECT_RDMA_FRAGS:
2732                                 kiblnd_check_reconnect(conn, rej->ibr_version,
2733                                                 incarnation, rej->ibr_why, cp);
2734                                 break;
2735
2736                         case IBLND_REJECT_NO_RESOURCES:
2737                                 CERROR("%s rejected: o2iblnd no resources\n",
2738                                        libcfs_nid2str(peer->ibp_nid));
2739                                 break;
2740
2741                         case IBLND_REJECT_FATAL:
2742                                 CERROR("%s rejected: o2iblnd fatal error\n",
2743                                        libcfs_nid2str(peer->ibp_nid));
2744                                 break;
2745
2746                         default:
2747                                 CERROR("%s rejected: o2iblnd reason %d\n",
2748                                        libcfs_nid2str(peer->ibp_nid),
2749                                        rej->ibr_why);
2750                                 break;
2751                         }
2752                         break;
2753                 }
2754                 /* fall through */
2755         default:
2756                 CNETERR("%s rejected: reason %d, size %d\n",
2757                         libcfs_nid2str(peer->ibp_nid), reason, priv_nob);
2758                 break;
2759         }
2760
2761         kiblnd_connreq_done(conn, -ECONNREFUSED);
2762 }
2763
2764 static void
2765 kiblnd_check_connreply (kib_conn_t *conn, void *priv, int priv_nob)
2766 {
2767         kib_peer_t    *peer = conn->ibc_peer;
2768         lnet_ni_t     *ni   = peer->ibp_ni;
2769         kib_net_t     *net  = ni->ni_data;
2770         kib_msg_t     *msg  = priv;
2771         int            ver  = conn->ibc_version;
2772         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
2773         unsigned long  flags;
2774
2775         LASSERT (net != NULL);
2776
2777         if (rc != 0) {
2778                 CERROR("Can't unpack connack from %s: %d\n",
2779                        libcfs_nid2str(peer->ibp_nid), rc);
2780                 goto failed;
2781         }
2782
2783         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2784                 CERROR("Unexpected message %d from %s\n",
2785                        msg->ibm_type, libcfs_nid2str(peer->ibp_nid));
2786                 rc = -EPROTO;
2787                 goto failed;
2788         }
2789
2790         if (ver != msg->ibm_version) {
2791                 CERROR("%s replied version %x is different with "
2792                        "requested version %x\n",
2793                        libcfs_nid2str(peer->ibp_nid), msg->ibm_version, ver);
2794                 rc = -EPROTO;
2795                 goto failed;
2796         }
2797
2798         if (msg->ibm_u.connparams.ibcp_queue_depth >
2799             conn->ibc_queue_depth) {
2800                 CERROR("%s has incompatible queue depth %d (<=%d wanted)\n",
2801                        libcfs_nid2str(peer->ibp_nid),
2802                        msg->ibm_u.connparams.ibcp_queue_depth,
2803                        conn->ibc_queue_depth);
2804                 rc = -EPROTO;
2805                 goto failed;
2806         }
2807
2808         if (msg->ibm_u.connparams.ibcp_max_frags >
2809             conn->ibc_max_frags) {
2810                 CERROR("%s has incompatible max_frags %d (<=%d wanted)\n",
2811                        libcfs_nid2str(peer->ibp_nid),
2812                        msg->ibm_u.connparams.ibcp_max_frags,
2813                        conn->ibc_max_frags);
2814                 rc = -EPROTO;
2815                 goto failed;
2816         }
2817
2818         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2819                 CERROR("%s max message size %d too big (%d max)\n",
2820                        libcfs_nid2str(peer->ibp_nid),
2821                        msg->ibm_u.connparams.ibcp_max_msg_size,
2822                        IBLND_MSG_SIZE);
2823                 rc = -EPROTO;
2824                 goto failed;
2825         }
2826
2827         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2828         if (msg->ibm_dstnid == ni->ni_nid &&
2829             msg->ibm_dststamp == net->ibn_incarnation)
2830                 rc = 0;
2831         else
2832                 rc = -ESTALE;
2833         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2834
2835         if (rc != 0) {
2836                 CERROR("Bad connection reply from %s, rc = %d, "
2837                        "version: %x max_frags: %d\n",
2838                        libcfs_nid2str(peer->ibp_nid), rc,
2839                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
2840                 goto failed;
2841         }
2842
2843         conn->ibc_incarnation      = msg->ibm_srcstamp;
2844         conn->ibc_credits          = msg->ibm_u.connparams.ibcp_queue_depth;
2845         conn->ibc_reserved_credits = msg->ibm_u.connparams.ibcp_queue_depth;
2846         conn->ibc_queue_depth      = msg->ibm_u.connparams.ibcp_queue_depth;
2847         conn->ibc_max_frags        = msg->ibm_u.connparams.ibcp_max_frags;
2848         LASSERT(conn->ibc_credits + conn->ibc_reserved_credits +
2849                 IBLND_OOB_MSGS(ver) <= IBLND_RX_MSGS(conn));
2850
2851         kiblnd_connreq_done(conn, 0);
2852         return;
2853
2854  failed:
2855         /* NB My QP has already established itself, so I handle anything going
2856          * wrong here by setting ibc_comms_error.
2857          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
2858          * immediately tears it down. */
2859
2860         LASSERT (rc != 0);
2861         conn->ibc_comms_error = rc;
2862         kiblnd_connreq_done(conn, 0);
2863 }
2864
2865 static int
2866 kiblnd_active_connect (struct rdma_cm_id *cmid)
2867 {
2868         kib_peer_t              *peer = (kib_peer_t *)cmid->context;
2869         kib_conn_t              *conn;
2870         kib_msg_t               *msg;
2871         struct rdma_conn_param   cp;
2872         int                      version;
2873         __u64                    incarnation;
2874         unsigned long            flags;
2875         int                      rc;
2876
2877         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2878
2879         incarnation = peer->ibp_incarnation;
2880         version     = (peer->ibp_version == 0) ? IBLND_MSG_VERSION :
2881                                                  peer->ibp_version;
2882
2883         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2884
2885         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_ACTIVE_CONNECT,
2886                                   version);
2887         if (conn == NULL) {
2888                 kiblnd_peer_connect_failed(peer, 1, -ENOMEM);
2889                 kiblnd_peer_decref(peer); /* lose cmid's ref */
2890                 return -ENOMEM;
2891         }
2892
2893         /* conn "owns" cmid now, so I return success from here on to ensure the
2894          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
2895          * on peer */
2896
2897         msg = &conn->ibc_connvars->cv_msg;
2898
2899         memset(msg, 0, sizeof(*msg));
2900         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
2901         msg->ibm_u.connparams.ibcp_queue_depth  = conn->ibc_queue_depth;
2902         msg->ibm_u.connparams.ibcp_max_frags    = conn->ibc_max_frags;
2903         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2904
2905         kiblnd_pack_msg(peer->ibp_ni, msg, version,
2906                         0, peer->ibp_nid, incarnation);
2907
2908         memset(&cp, 0, sizeof(cp));
2909         cp.private_data        = msg;
2910         cp.private_data_len    = msg->ibm_nob;
2911         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2912         cp.initiator_depth     = 0;
2913         cp.flow_control        = 1;
2914         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2915         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2916
2917         LASSERT(cmid->context == (void *)conn);
2918         LASSERT(conn->ibc_cmid == cmid);
2919
2920         rc = rdma_connect(cmid, &cp);
2921         if (rc != 0) {
2922                 CERROR("Can't connect to %s: %d\n",
2923                        libcfs_nid2str(peer->ibp_nid), rc);
2924                 kiblnd_connreq_done(conn, rc);
2925                 kiblnd_conn_decref(conn);
2926         }
2927
2928         return 0;
2929 }
2930
2931 int
2932 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
2933 {
2934         kib_peer_t  *peer;
2935         kib_conn_t  *conn;
2936         int          rc;
2937
2938         switch (event->event) {
2939         default:
2940                 CERROR("Unexpected event: %d, status: %d\n",
2941                        event->event, event->status);
2942                 LBUG();
2943
2944         case RDMA_CM_EVENT_CONNECT_REQUEST:
2945                 /* destroy cmid on failure */
2946                 rc = kiblnd_passive_connect(cmid, 
2947                                             (void *)KIBLND_CONN_PARAM(event),
2948                                             KIBLND_CONN_PARAM_LEN(event));
2949                 CDEBUG(D_NET, "connreq: %d\n", rc);
2950                 return rc;
2951                 
2952         case RDMA_CM_EVENT_ADDR_ERROR:
2953                 peer = (kib_peer_t *)cmid->context;
2954                 CNETERR("%s: ADDR ERROR %d\n",
2955                        libcfs_nid2str(peer->ibp_nid), event->status);
2956                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2957                 kiblnd_peer_decref(peer);
2958                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
2959
2960         case RDMA_CM_EVENT_ADDR_RESOLVED:
2961                 peer = (kib_peer_t *)cmid->context;
2962
2963                 CDEBUG(D_NET,"%s Addr resolved: %d\n",
2964                        libcfs_nid2str(peer->ibp_nid), event->status);
2965
2966                 if (event->status != 0) {
2967                         CNETERR("Can't resolve address for %s: %d\n",
2968                                 libcfs_nid2str(peer->ibp_nid), event->status);
2969                         rc = event->status;
2970                 } else {
2971                         rc = rdma_resolve_route(
2972                                 cmid, *kiblnd_tunables.kib_timeout * 1000);
2973                         if (rc == 0)
2974                                 return 0;
2975                         /* Can't initiate route resolution */
2976                         CERROR("Can't resolve route for %s: %d\n",
2977                                libcfs_nid2str(peer->ibp_nid), rc);
2978                 }
2979                 kiblnd_peer_connect_failed(peer, 1, rc);
2980                 kiblnd_peer_decref(peer);
2981                 return rc;                      /* rc != 0 destroys cmid */
2982
2983         case RDMA_CM_EVENT_ROUTE_ERROR:
2984                 peer = (kib_peer_t *)cmid->context;
2985                 CNETERR("%s: ROUTE ERROR %d\n",
2986                         libcfs_nid2str(peer->ibp_nid), event->status);
2987                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2988                 kiblnd_peer_decref(peer);
2989                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
2990
2991         case RDMA_CM_EVENT_ROUTE_RESOLVED:
2992                 peer = (kib_peer_t *)cmid->context;
2993                 CDEBUG(D_NET,"%s Route resolved: %d\n",
2994                        libcfs_nid2str(peer->ibp_nid), event->status);
2995
2996                 if (event->status == 0)
2997                         return kiblnd_active_connect(cmid);
2998
2999                 CNETERR("Can't resolve route for %s: %d\n",
3000                        libcfs_nid2str(peer->ibp_nid), event->status);
3001                 kiblnd_peer_connect_failed(peer, 1, event->status);
3002                 kiblnd_peer_decref(peer);
3003                 return event->status;           /* rc != 0 destroys cmid */
3004                 
3005         case RDMA_CM_EVENT_UNREACHABLE:
3006                 conn = (kib_conn_t *)cmid->context;
3007                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3008                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3009                 CNETERR("%s: UNREACHABLE %d\n",
3010                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3011                 kiblnd_connreq_done(conn, -ENETDOWN);
3012                 kiblnd_conn_decref(conn);
3013                 return 0;
3014
3015         case RDMA_CM_EVENT_CONNECT_ERROR:
3016                 conn = (kib_conn_t *)cmid->context;
3017                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
3018                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
3019                 CNETERR("%s: CONNECT ERROR %d\n",
3020                         libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
3021                 kiblnd_connreq_done(conn, -ENOTCONN);
3022                 kiblnd_conn_decref(conn);
3023                 return 0;
3024
3025         case RDMA_CM_EVENT_REJECTED:
3026                 conn = (kib_conn_t *)cmid->context;
3027                 switch (conn->ibc_state) {
3028                 default:
3029                         LBUG();
3030
3031                 case IBLND_CONN_PASSIVE_WAIT:
3032                         CERROR ("%s: REJECTED %d\n",
3033                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
3034                                 event->status);
3035                         kiblnd_connreq_done(conn, -ECONNRESET);
3036                         break;
3037
3038                 case IBLND_CONN_ACTIVE_CONNECT:
3039                         kiblnd_rejected(conn, event->status,
3040                                         (void *)KIBLND_CONN_PARAM(event),
3041                                         KIBLND_CONN_PARAM_LEN(event));
3042                         break;
3043                 }
3044                 kiblnd_conn_decref(conn);
3045                 return 0;
3046
3047         case RDMA_CM_EVENT_ESTABLISHED:
3048                 conn = (kib_conn_t *)cmid->context;
3049                 switch (conn->ibc_state) {
3050                 default:
3051                         LBUG();
3052
3053                 case IBLND_CONN_PASSIVE_WAIT:
3054                         CDEBUG(D_NET, "ESTABLISHED (passive): %s\n",
3055                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3056                         kiblnd_connreq_done(conn, 0);
3057                         break;
3058
3059                 case IBLND_CONN_ACTIVE_CONNECT:
3060                         CDEBUG(D_NET, "ESTABLISHED(active): %s\n",
3061                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3062                         kiblnd_check_connreply(conn,
3063                                                (void *)KIBLND_CONN_PARAM(event),
3064                                                KIBLND_CONN_PARAM_LEN(event));
3065                         break;
3066                 }
3067                 /* net keeps its ref on conn! */
3068                 return 0;
3069
3070         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
3071                 CDEBUG(D_NET, "Ignore TIMEWAIT_EXIT event\n");
3072                 return 0;
3073
3074         case RDMA_CM_EVENT_DISCONNECTED:
3075                 conn = (kib_conn_t *)cmid->context;
3076                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
3077                         CERROR("%s DISCONNECTED\n",
3078                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
3079                         kiblnd_connreq_done(conn, -ECONNRESET);
3080                 } else {
3081                         kiblnd_close_conn(conn, 0);
3082                 }
3083                 kiblnd_conn_decref(conn);
3084                 cmid->context = NULL;
3085                 return 0;
3086
3087         case RDMA_CM_EVENT_DEVICE_REMOVAL:
3088                 LCONSOLE_ERROR_MSG(0x131,
3089                                    "Received notification of device removal\n"
3090                                    "Please shutdown LNET to allow this to proceed\n");
3091                 /* Can't remove network from underneath LNET for now, so I have
3092                  * to ignore this */
3093                 return 0;
3094
3095         case RDMA_CM_EVENT_ADDR_CHANGE:
3096                 LCONSOLE_INFO("Physical link changed (eg hca/port)\n");
3097                 return 0;
3098         }
3099 }
3100
3101 static int
3102 kiblnd_check_txs_locked(kib_conn_t *conn, struct list_head *txs)
3103 {
3104         kib_tx_t         *tx;
3105         struct list_head *ttmp;
3106
3107         list_for_each(ttmp, txs) {
3108                 tx = list_entry(ttmp, kib_tx_t, tx_list);
3109
3110                 if (txs != &conn->ibc_active_txs) {
3111                         LASSERT(tx->tx_queued);
3112                 } else {
3113                         LASSERT(!tx->tx_queued);
3114                         LASSERT(tx->tx_waiting || tx->tx_sending != 0);
3115                 }
3116
3117                 if (cfs_time_aftereq(jiffies, tx->tx_deadline)) {
3118                         CERROR("Timed out tx: %s, %lu seconds\n",
3119                                kiblnd_queue2str(conn, txs),
3120                                cfs_duration_sec(jiffies - tx->tx_deadline));
3121                         return 1;
3122                 }
3123         }
3124
3125         return 0;
3126 }
3127
3128 static int
3129 kiblnd_conn_timed_out_locked(kib_conn_t *conn)
3130 {
3131         return  kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue) ||
3132                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_noops) ||
3133                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_rsrvd) ||
3134                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_nocred) ||
3135                 kiblnd_check_txs_locked(conn, &conn->ibc_active_txs);
3136 }
3137
3138 static void
3139 kiblnd_check_conns (int idx)
3140 {
3141         struct list_head  closes = LIST_HEAD_INIT(closes);
3142         struct list_head  checksends = LIST_HEAD_INIT(checksends);
3143         struct list_head *peers = &kiblnd_data.kib_peers[idx];
3144         struct list_head *ptmp;
3145         kib_peer_t       *peer;
3146         kib_conn_t       *conn;
3147         struct list_head *ctmp;
3148         unsigned long     flags;
3149
3150         /* NB. We expect to have a look at all the peers and not find any
3151          * RDMAs to time out, so we just use a shared lock while we
3152          * take a look... */
3153         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3154
3155         list_for_each(ptmp, peers) {
3156                 peer = list_entry(ptmp, kib_peer_t, ibp_list);
3157
3158                 list_for_each(ctmp, &peer->ibp_conns) {
3159                         int timedout;
3160                         int sendnoop;
3161
3162                         conn = list_entry(ctmp, kib_conn_t, ibc_list);
3163
3164                         LASSERT(conn->ibc_state == IBLND_CONN_ESTABLISHED);
3165
3166                         spin_lock(&conn->ibc_lock);
3167
3168                         sendnoop = kiblnd_need_noop(conn);
3169                         timedout = kiblnd_conn_timed_out_locked(conn);
3170                         if (!sendnoop && !timedout) {
3171                                 spin_unlock(&conn->ibc_lock);
3172                                 continue;
3173                         }
3174
3175                         if (timedout) {
3176                                 CERROR("Timed out RDMA with %s (%lu): "
3177                                        "c: %u, oc: %u, rc: %u\n",
3178                                        libcfs_nid2str(peer->ibp_nid),
3179                                        cfs_duration_sec(cfs_time_current() -
3180                                                         peer->ibp_last_alive),
3181                                        conn->ibc_credits,
3182                                        conn->ibc_outstanding_credits,
3183                                        conn->ibc_reserved_credits);
3184                                 list_add(&conn->ibc_connd_list, &closes);
3185                         } else {
3186                                 list_add(&conn->ibc_connd_list, &checksends);
3187                         }
3188                         /* +ref for 'closes' or 'checksends' */
3189                         kiblnd_conn_addref(conn);
3190
3191                         spin_unlock(&conn->ibc_lock);
3192                 }
3193         }
3194
3195         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3196
3197         /* Handle timeout by closing the whole
3198          * connection. We can only be sure RDMA activity
3199          * has ceased once the QP has been modified. */
3200         while (!list_empty(&closes)) {
3201                 conn = list_entry(closes.next,
3202                                   kib_conn_t, ibc_connd_list);
3203                 list_del(&conn->ibc_connd_list);
3204                 kiblnd_close_conn(conn, -ETIMEDOUT);
3205                 kiblnd_conn_decref(conn);
3206         }
3207
3208         /* In case we have enough credits to return via a
3209          * NOOP, but there were no non-blocking tx descs
3210          * free to do it last time... */
3211         while (!list_empty(&checksends)) {
3212                 conn = list_entry(checksends.next,
3213                                   kib_conn_t, ibc_connd_list);
3214                 list_del(&conn->ibc_connd_list);
3215                 kiblnd_check_sends(conn);
3216                 kiblnd_conn_decref(conn);
3217         }
3218 }
3219
3220 static void
3221 kiblnd_disconnect_conn (kib_conn_t *conn)
3222 {
3223         LASSERT (!in_interrupt());
3224         LASSERT (current == kiblnd_data.kib_connd);
3225         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
3226
3227         rdma_disconnect(conn->ibc_cmid);
3228         kiblnd_finalise_conn(conn);
3229
3230         kiblnd_peer_notify(conn->ibc_peer);
3231 }
3232
3233 /*
3234  * High-water for reconnection to the same peer, reconnection attempt should
3235  * be delayed after trying more than KIB_RECONN_HIGH_RACE.
3236  */
3237 #define KIB_RECONN_HIGH_RACE    10
3238 /*
3239  * Allow connd to take a break and handle other things after consecutive
3240  * reconnection attemps.
3241  */
3242 #define KIB_RECONN_BREAK        100
3243
3244 int
3245 kiblnd_connd (void *arg)
3246 {
3247         spinlock_t        *lock= &kiblnd_data.kib_connd_lock;
3248         wait_queue_t       wait;
3249         unsigned long      flags;
3250         kib_conn_t        *conn;
3251         int                timeout;
3252         int                i;
3253         int                dropped_lock;
3254         int                peer_index = 0;
3255         unsigned long      deadline = jiffies;
3256
3257         cfs_block_allsigs();
3258
3259         init_waitqueue_entry(&wait, current);
3260         kiblnd_data.kib_connd = current;
3261
3262         spin_lock_irqsave(lock, flags);
3263
3264         while (!kiblnd_data.kib_shutdown) {
3265                 int reconn = 0;
3266
3267                 dropped_lock = 0;
3268
3269                 if (!list_empty(&kiblnd_data.kib_connd_zombies)) {
3270                         kib_peer_t *peer = NULL;
3271
3272                         conn = list_entry(kiblnd_data.kib_connd_zombies.next,
3273                                           kib_conn_t, ibc_list);
3274                         list_del(&conn->ibc_list);
3275                         if (conn->ibc_reconnect) {
3276                                 peer = conn->ibc_peer;
3277                                 kiblnd_peer_addref(peer);
3278                         }
3279
3280                         spin_unlock_irqrestore(lock, flags);
3281                         dropped_lock = 1;
3282
3283                         kiblnd_destroy_conn(conn, !peer);
3284
3285                         spin_lock_irqsave(lock, flags);
3286                         if (!peer)
3287                                 continue;
3288
3289                         conn->ibc_peer = peer;
3290                         if (peer->ibp_reconnected < KIB_RECONN_HIGH_RACE)
3291                                 list_add_tail(&conn->ibc_list,
3292                                               &kiblnd_data.kib_reconn_list);
3293                         else
3294                                 list_add_tail(&conn->ibc_list,
3295                                               &kiblnd_data.kib_reconn_wait);
3296                 }
3297
3298                 if (!list_empty(&kiblnd_data.kib_connd_conns)) {
3299                         conn = list_entry(kiblnd_data.kib_connd_conns.next,
3300                                               kib_conn_t, ibc_list);
3301                         list_del(&conn->ibc_list);
3302
3303                         spin_unlock_irqrestore(lock, flags);
3304                         dropped_lock = 1;
3305
3306                         kiblnd_disconnect_conn(conn);
3307                         kiblnd_conn_decref(conn);
3308
3309                         spin_lock_irqsave(lock, flags);
3310                 }
3311
3312                 while (reconn < KIB_RECONN_BREAK) {
3313                         if (kiblnd_data.kib_reconn_sec != get_seconds()) {
3314                                 kiblnd_data.kib_reconn_sec = get_seconds();
3315                                 list_splice_init(&kiblnd_data.kib_reconn_wait,
3316                                                  &kiblnd_data.kib_reconn_list);
3317                         }
3318
3319                         if (list_empty(&kiblnd_data.kib_reconn_list))
3320                                 break;
3321
3322                         conn = list_entry(kiblnd_data.kib_reconn_list.next,
3323                                           kib_conn_t, ibc_list);
3324                         list_del(&conn->ibc_list);
3325
3326                         spin_unlock_irqrestore(lock, flags);
3327                         dropped_lock = 1;
3328
3329                         reconn += kiblnd_reconnect_peer(conn->ibc_peer);
3330                         kiblnd_peer_decref(conn->ibc_peer);
3331                         LIBCFS_FREE(conn, sizeof(*conn));
3332
3333                         spin_lock_irqsave(lock, flags);
3334                 }
3335
3336                 /* careful with the jiffy wrap... */
3337                 timeout = (int)(deadline - jiffies);
3338                 if (timeout <= 0) {
3339                         const int n = 4;
3340                         const int p = 1;
3341                         int       chunk = kiblnd_data.kib_peer_hash_size;
3342
3343                         spin_unlock_irqrestore(lock, flags);
3344                         dropped_lock = 1;
3345
3346                         /* Time to check for RDMA timeouts on a few more
3347                          * peers: I do checks every 'p' seconds on a
3348                          * proportion of the peer table and I need to check
3349                          * every connection 'n' times within a timeout
3350                          * interval, to ensure I detect a timeout on any
3351                          * connection within (n+1)/n times the timeout
3352                          * interval. */
3353
3354                         if (*kiblnd_tunables.kib_timeout > n * p)
3355                                 chunk = (chunk * n * p) /
3356                                         *kiblnd_tunables.kib_timeout;
3357                         if (chunk == 0)
3358                                 chunk = 1;
3359
3360                         for (i = 0; i < chunk; i++) {
3361                                 kiblnd_check_conns(peer_index);
3362                                 peer_index = (peer_index + 1) %
3363                                              kiblnd_data.kib_peer_hash_size;
3364                         }
3365
3366                         deadline += msecs_to_jiffies(p * MSEC_PER_SEC);
3367                         spin_lock_irqsave(lock, flags);
3368                 }
3369
3370                 if (dropped_lock)
3371                         continue;
3372
3373                 /* Nothing to do for 'timeout'  */
3374                 set_current_state(TASK_INTERRUPTIBLE);
3375                 add_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3376                 spin_unlock_irqrestore(lock, flags);
3377
3378                 schedule_timeout(timeout);
3379
3380                 set_current_state(TASK_RUNNING);
3381                 remove_wait_queue(&kiblnd_data.kib_connd_waitq, &wait);
3382                 spin_lock_irqsave(lock, flags);
3383         }
3384
3385         spin_unlock_irqrestore(lock, flags);
3386
3387         kiblnd_thread_fini();
3388         return 0;
3389 }
3390
3391 void
3392 kiblnd_qp_event(struct ib_event *event, void *arg)
3393 {
3394         kib_conn_t *conn = arg;
3395
3396         switch (event->event) {
3397         case IB_EVENT_COMM_EST:
3398                 CDEBUG(D_NET, "%s established\n",
3399                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
3400                 return;
3401
3402         default:
3403                 CERROR("%s: Async QP event type %d\n",
3404                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3405                 return;
3406         }
3407 }
3408
3409 static void
3410 kiblnd_complete (struct ib_wc *wc)
3411 {
3412         switch (kiblnd_wreqid2type(wc->wr_id)) {
3413         default:
3414                 LBUG();
3415
3416         case IBLND_WID_MR:
3417                 if (wc->status != IB_WC_SUCCESS &&
3418                     wc->status != IB_WC_WR_FLUSH_ERR)
3419                         CNETERR("FastReg failed: %d\n", wc->status);
3420                 return;
3421
3422         case IBLND_WID_RDMA:
3423                 /* We only get RDMA completion notification if it fails.  All
3424                  * subsequent work items, including the final SEND will fail
3425                  * too.  However we can't print out any more info about the
3426                  * failing RDMA because 'tx' might be back on the idle list or
3427                  * even reused already if we didn't manage to post all our work
3428                  * items */
3429                 CNETERR("RDMA (tx: %p) failed: %d\n",
3430                         kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3431                 return;
3432
3433         case IBLND_WID_TX:
3434                 kiblnd_tx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3435                 return;
3436
3437         case IBLND_WID_RX:
3438                 kiblnd_rx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status,
3439                                    wc->byte_len);
3440                 return;
3441         }
3442 }
3443
3444 void
3445 kiblnd_cq_completion(struct ib_cq *cq, void *arg)
3446 {
3447         /* NB I'm not allowed to schedule this conn once its refcount has
3448          * reached 0.  Since fundamentally I'm racing with scheduler threads
3449          * consuming my CQ I could be called after all completions have
3450          * occurred.  But in this case, ibc_nrx == 0 && ibc_nsends_posted == 0
3451          * and this CQ is about to be destroyed so I NOOP. */
3452         kib_conn_t              *conn = (kib_conn_t *)arg;
3453         struct kib_sched_info   *sched = conn->ibc_sched;
3454         unsigned long           flags;
3455
3456         LASSERT(cq == conn->ibc_cq);
3457
3458         spin_lock_irqsave(&sched->ibs_lock, flags);
3459
3460         conn->ibc_ready = 1;
3461
3462         if (!conn->ibc_scheduled &&
3463             (conn->ibc_nrx > 0 ||
3464              conn->ibc_nsends_posted > 0)) {
3465                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3466                 conn->ibc_scheduled = 1;
3467                 list_add_tail(&conn->ibc_sched_list, &sched->ibs_conns);
3468
3469                 if (waitqueue_active(&sched->ibs_waitq))
3470                         wake_up(&sched->ibs_waitq);
3471         }
3472
3473         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3474 }
3475
3476 void
3477 kiblnd_cq_event(struct ib_event *event, void *arg)
3478 {
3479         kib_conn_t *conn = arg;
3480
3481         CERROR("%s: async CQ event type %d\n",
3482                libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3483 }
3484
3485 int
3486 kiblnd_scheduler(void *arg)
3487 {
3488         long                    id = (long)arg;
3489         struct kib_sched_info   *sched;
3490         kib_conn_t              *conn;
3491         wait_queue_t            wait;
3492         unsigned long           flags;
3493         struct ib_wc            wc;
3494         int                     did_something;
3495         int                     busy_loops = 0;
3496         int                     rc;
3497
3498         cfs_block_allsigs();
3499
3500         init_waitqueue_entry(&wait, current);
3501
3502         sched = kiblnd_data.kib_scheds[KIB_THREAD_CPT(id)];
3503
3504         rc = cfs_cpt_bind(lnet_cpt_table(), sched->ibs_cpt);
3505         if (rc != 0) {
3506                 CWARN("Failed to bind on CPT %d, please verify whether "
3507                       "all CPUs are healthy and reload modules if necessary, "
3508                       "otherwise your system might under risk of low "
3509                       "performance\n", sched->ibs_cpt);
3510         }
3511
3512         spin_lock_irqsave(&sched->ibs_lock, flags);
3513
3514         while (!kiblnd_data.kib_shutdown) {
3515                 if (busy_loops++ >= IBLND_RESCHED) {
3516                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3517
3518                         cond_resched();
3519                         busy_loops = 0;
3520
3521                         spin_lock_irqsave(&sched->ibs_lock, flags);
3522                 }
3523
3524                 did_something = 0;
3525
3526                 if (!list_empty(&sched->ibs_conns)) {
3527                         conn = list_entry(sched->ibs_conns.next,
3528                                               kib_conn_t, ibc_sched_list);
3529                         /* take over kib_sched_conns' ref on conn... */
3530                         LASSERT(conn->ibc_scheduled);
3531                         list_del(&conn->ibc_sched_list);
3532                         conn->ibc_ready = 0;
3533
3534                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
3535
3536                         wc.wr_id = IBLND_WID_INVAL;
3537
3538                         rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3539                         if (rc == 0) {
3540                                 rc = ib_req_notify_cq(conn->ibc_cq,
3541                                                       IB_CQ_NEXT_COMP);
3542                                 if (rc < 0) {
3543                                         CWARN("%s: ib_req_notify_cq failed: %d, "
3544                                               "closing connection\n",
3545                                               libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
3546                                         kiblnd_close_conn(conn, -EIO);
3547                                         kiblnd_conn_decref(conn);
3548                                         spin_lock_irqsave(&sched->ibs_lock,
3549                                                               flags);
3550                                         continue;
3551                                 }
3552
3553                                 rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3554                         }
3555