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