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