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