Whamcloud - gitweb
b=23076 fix for o2iblnd reconnect
[fs/lustre-release.git] / lnet / klnds / o2iblnd / o2iblnd_cb.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
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 void
44 kiblnd_tx_done (lnet_ni_t *ni, kib_tx_t *tx)
45 {
46         lnet_msg_t *lntmsg[2];
47         kib_net_t  *net = ni->ni_data;
48         int         rc;
49         int         i;
50
51         LASSERT (net != NULL);
52         LASSERT (!cfs_in_interrupt());
53         LASSERT (!tx->tx_queued);               /* mustn't be queued for sending */
54         LASSERT (tx->tx_sending == 0);          /* mustn't be awaiting sent callback */
55         LASSERT (!tx->tx_waiting);              /* mustn't be awaiting peer response */
56         LASSERT (tx->tx_pool != NULL);
57
58         kiblnd_unmap_tx(ni, tx);
59
60         /* tx may have up to 2 lnet msgs to finalise */
61         lntmsg[0] = tx->tx_lntmsg[0]; tx->tx_lntmsg[0] = NULL;
62         lntmsg[1] = tx->tx_lntmsg[1]; tx->tx_lntmsg[1] = NULL;
63         rc = tx->tx_status;
64
65         if (tx->tx_conn != NULL) {
66                 LASSERT (ni == tx->tx_conn->ibc_peer->ibp_ni);
67
68                 kiblnd_conn_decref(tx->tx_conn);
69                 tx->tx_conn = NULL;
70         }
71
72         tx->tx_nwrq = 0;
73         tx->tx_status = 0;
74
75         kiblnd_pool_free_node(&tx->tx_pool->tpo_pool, &tx->tx_list);
76
77         /* delay finalize until my descs have been freed */
78         for (i = 0; i < 2; i++) {
79                 if (lntmsg[i] == NULL)
80                         continue;
81
82                 lnet_finalize(ni, lntmsg[i], rc);
83         }
84 }
85
86 void
87 kiblnd_txlist_done (lnet_ni_t *ni, cfs_list_t *txlist, int status)
88 {
89         kib_tx_t *tx;
90
91         while (!cfs_list_empty (txlist)) {
92                 tx = cfs_list_entry (txlist->next, kib_tx_t, tx_list);
93
94                 cfs_list_del(&tx->tx_list);
95                 /* complete now */
96                 tx->tx_waiting = 0;
97                 tx->tx_status = status;
98                 kiblnd_tx_done(ni, tx);
99         }
100 }
101
102 kib_tx_t *
103 kiblnd_get_idle_tx (lnet_ni_t *ni)
104 {
105         kib_net_t            *net = (kib_net_t *)ni->ni_data;
106         cfs_list_t           *node;
107         kib_tx_t             *tx;
108
109         node = kiblnd_pool_alloc_node(&net->ibn_tx_ps.tps_poolset);
110         if (node == NULL)
111                 return NULL;
112         tx = container_of(node, kib_tx_t, tx_list);
113
114         LASSERT (tx->tx_nwrq == 0);
115         LASSERT (!tx->tx_queued);
116         LASSERT (tx->tx_sending == 0);
117         LASSERT (!tx->tx_waiting);
118         LASSERT (tx->tx_status == 0);
119         LASSERT (tx->tx_conn == NULL);
120         LASSERT (tx->tx_lntmsg[0] == NULL);
121         LASSERT (tx->tx_lntmsg[1] == NULL);
122         LASSERT (tx->tx_u.pmr == NULL);
123         LASSERT (tx->tx_nfrags == 0);
124
125         return tx;
126 }
127
128 void
129 kiblnd_drop_rx (kib_rx_t *rx)
130 {
131         kib_conn_t         *conn = rx->rx_conn;
132         unsigned long       flags;
133         
134         cfs_spin_lock_irqsave(&kiblnd_data.kib_sched_lock, flags);
135         LASSERT (conn->ibc_nrx > 0);
136         conn->ibc_nrx--;
137         cfs_spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock, flags);
138
139         kiblnd_conn_decref(conn);
140 }
141
142 int
143 kiblnd_post_rx (kib_rx_t *rx, int credit)
144 {
145         kib_conn_t         *conn = rx->rx_conn;
146         kib_net_t          *net = conn->ibc_peer->ibp_ni->ni_data;
147         struct ib_recv_wr  *bad_wrq = NULL;
148         struct ib_mr       *mr;
149         int                 rc;
150
151         LASSERT (net != NULL);
152         LASSERT (!cfs_in_interrupt());
153         LASSERT (credit == IBLND_POSTRX_NO_CREDIT ||
154                  credit == IBLND_POSTRX_PEER_CREDIT ||
155                  credit == IBLND_POSTRX_RSRVD_CREDIT);
156
157         mr = kiblnd_find_dma_mr(net, rx->rx_msgaddr, IBLND_MSG_SIZE);
158         LASSERT (mr != NULL);
159
160         rx->rx_sge.lkey   = mr->lkey;
161         rx->rx_sge.addr   = rx->rx_msgaddr;
162         rx->rx_sge.length = IBLND_MSG_SIZE;
163
164         rx->rx_wrq.next = NULL;
165         rx->rx_wrq.sg_list = &rx->rx_sge;
166         rx->rx_wrq.num_sge = 1;
167         rx->rx_wrq.wr_id = kiblnd_ptr2wreqid(rx, IBLND_WID_RX);
168
169         LASSERT (conn->ibc_state >= IBLND_CONN_INIT);
170         LASSERT (rx->rx_nob >= 0);              /* not posted */
171
172         if (conn->ibc_state > IBLND_CONN_ESTABLISHED) {
173                 kiblnd_drop_rx(rx);             /* No more posts for this rx */
174                 return 0;
175         }
176
177         rx->rx_nob = -1;                        /* flag posted */
178
179         rc = ib_post_recv(conn->ibc_cmid->qp, &rx->rx_wrq, &bad_wrq);
180         if (rc != 0) {
181                 CERROR("Can't post rx for %s: %d, bad_wrq: %p\n",
182                        libcfs_nid2str(conn->ibc_peer->ibp_nid), rc, bad_wrq);
183                 rx->rx_nob = 0;
184         }
185
186         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) /* Initial post */
187                 return rc;
188
189         if (rc != 0) {
190                 kiblnd_close_conn(conn, rc);
191                 kiblnd_drop_rx(rx);             /* No more posts for this rx */
192                 return rc;
193         }
194
195         if (credit == IBLND_POSTRX_NO_CREDIT)
196                 return 0;
197
198         cfs_spin_lock(&conn->ibc_lock);
199         if (credit == IBLND_POSTRX_PEER_CREDIT)
200                 conn->ibc_outstanding_credits++;
201         else
202                 conn->ibc_reserved_credits++;
203         cfs_spin_unlock(&conn->ibc_lock);
204
205         kiblnd_check_sends(conn);
206         return 0;
207 }
208
209 kib_tx_t *
210 kiblnd_find_waiting_tx_locked(kib_conn_t *conn, int txtype, __u64 cookie)
211 {
212         cfs_list_t   *tmp;
213
214         cfs_list_for_each(tmp, &conn->ibc_active_txs) {
215                 kib_tx_t *tx = cfs_list_entry(tmp, kib_tx_t, tx_list);
216
217                 LASSERT (!tx->tx_queued);
218                 LASSERT (tx->tx_sending != 0 || tx->tx_waiting);
219
220                 if (tx->tx_cookie != cookie)
221                         continue;
222
223                 if (tx->tx_waiting &&
224                     tx->tx_msg->ibm_type == txtype)
225                         return tx;
226
227                 CWARN("Bad completion: %swaiting, type %x (wanted %x)\n",
228                       tx->tx_waiting ? "" : "NOT ",
229                       tx->tx_msg->ibm_type, txtype);
230         }
231         return NULL;
232 }
233
234 void
235 kiblnd_handle_completion(kib_conn_t *conn, int txtype, int status, __u64 cookie)
236 {
237         kib_tx_t    *tx;
238         lnet_ni_t   *ni = conn->ibc_peer->ibp_ni;
239         int          idle;
240
241         cfs_spin_lock(&conn->ibc_lock);
242
243         tx = kiblnd_find_waiting_tx_locked(conn, txtype, cookie);
244         if (tx == NULL) {
245                 cfs_spin_unlock(&conn->ibc_lock);
246
247                 CWARN("Unmatched completion type %x cookie "LPX64" from %s\n",
248                       txtype, cookie, libcfs_nid2str(conn->ibc_peer->ibp_nid));
249                 kiblnd_close_conn(conn, -EPROTO);
250                 return;
251         }
252
253         if (tx->tx_status == 0) {               /* success so far */
254                 if (status < 0) {               /* failed? */
255                         tx->tx_status = status;
256                 } else if (txtype == IBLND_MSG_GET_REQ) {
257                         lnet_set_reply_msg_len(ni, tx->tx_lntmsg[1], status);
258                 }
259         }
260
261         tx->tx_waiting = 0;
262
263         idle = !tx->tx_queued && (tx->tx_sending == 0);
264         if (idle)
265                 cfs_list_del(&tx->tx_list);
266
267         cfs_spin_unlock(&conn->ibc_lock);
268
269         if (idle)
270                 kiblnd_tx_done(ni, tx);
271 }
272
273 void
274 kiblnd_send_completion (kib_conn_t *conn, int type, int status, __u64 cookie)
275 {
276         lnet_ni_t   *ni = conn->ibc_peer->ibp_ni;
277         kib_tx_t    *tx = kiblnd_get_idle_tx(ni);
278
279         if (tx == NULL) {
280                 CERROR("Can't get tx for completion %x for %s\n",
281                        type, libcfs_nid2str(conn->ibc_peer->ibp_nid));
282                 return;
283         }
284
285         tx->tx_msg->ibm_u.completion.ibcm_status = status;
286         tx->tx_msg->ibm_u.completion.ibcm_cookie = cookie;
287         kiblnd_init_tx_msg(ni, tx, type, sizeof(kib_completion_msg_t));
288
289         kiblnd_queue_tx(tx, conn);
290 }
291
292 void
293 kiblnd_handle_rx (kib_rx_t *rx)
294 {
295         kib_msg_t    *msg = rx->rx_msg;
296         kib_conn_t   *conn = rx->rx_conn;
297         lnet_ni_t    *ni = conn->ibc_peer->ibp_ni;
298         int           credits = msg->ibm_credits;
299         kib_tx_t     *tx;
300         int           rc = 0;
301         int           rc2;
302         int           post_credit;
303
304         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
305
306         CDEBUG (D_NET, "Received %x[%d] from %s\n",
307                 msg->ibm_type, credits,
308                 libcfs_nid2str(conn->ibc_peer->ibp_nid));
309
310         if (credits != 0) {
311                 /* Have I received credits that will let me send? */
312                 cfs_spin_lock(&conn->ibc_lock);
313
314                 if (conn->ibc_credits + credits >
315                     IBLND_MSG_QUEUE_SIZE(conn->ibc_version)) {
316                         rc2 = conn->ibc_credits;
317                         cfs_spin_unlock(&conn->ibc_lock);
318
319                         CERROR("Bad credits from %s: %d + %d > %d\n",
320                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
321                                rc2, credits,
322                                IBLND_MSG_QUEUE_SIZE(conn->ibc_version));
323
324                         kiblnd_close_conn(conn, -EPROTO);
325                         kiblnd_post_rx(rx, IBLND_POSTRX_NO_CREDIT);
326                         return;
327                 }
328
329                 conn->ibc_credits += credits;
330
331                 cfs_spin_unlock(&conn->ibc_lock);
332                 kiblnd_check_sends(conn);
333         }
334
335         switch (msg->ibm_type) {
336         default:
337                 CERROR("Bad IBLND message type %x from %s\n",
338                        msg->ibm_type, libcfs_nid2str(conn->ibc_peer->ibp_nid));
339                 post_credit = IBLND_POSTRX_NO_CREDIT;
340                 rc = -EPROTO;
341                 break;
342
343         case IBLND_MSG_NOOP:
344                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
345                         post_credit = IBLND_POSTRX_NO_CREDIT;
346                 else
347                         post_credit = IBLND_POSTRX_PEER_CREDIT;
348                 break;
349
350         case IBLND_MSG_IMMEDIATE:
351                 post_credit = IBLND_POSTRX_DONT_POST;
352                 rc = lnet_parse(ni, &msg->ibm_u.immediate.ibim_hdr,
353                                 msg->ibm_srcnid, rx, 0);
354                 if (rc < 0)                     /* repost on error */
355                         post_credit = IBLND_POSTRX_PEER_CREDIT;
356                 break;
357
358         case IBLND_MSG_PUT_REQ:
359                 post_credit = IBLND_POSTRX_DONT_POST;
360                 rc = lnet_parse(ni, &msg->ibm_u.putreq.ibprm_hdr,
361                                 msg->ibm_srcnid, rx, 1);
362                 if (rc < 0)                     /* repost on error */
363                         post_credit = IBLND_POSTRX_PEER_CREDIT;
364                 break;
365
366         case IBLND_MSG_PUT_NAK:
367                 CWARN ("PUT_NACK from %s\n",
368                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
369                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
370                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_REQ,
371                                          msg->ibm_u.completion.ibcm_status,
372                                          msg->ibm_u.completion.ibcm_cookie);
373                 break;
374
375         case IBLND_MSG_PUT_ACK:
376                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
377
378                 cfs_spin_lock(&conn->ibc_lock);
379                 tx = kiblnd_find_waiting_tx_locked(conn, IBLND_MSG_PUT_REQ,
380                                                    msg->ibm_u.putack.ibpam_src_cookie);
381                 if (tx != NULL)
382                         cfs_list_del(&tx->tx_list);
383                 cfs_spin_unlock(&conn->ibc_lock);
384
385                 if (tx == NULL) {
386                         CERROR("Unmatched PUT_ACK from %s\n",
387                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
388                         rc = -EPROTO;
389                         break;
390                 }
391
392                 LASSERT (tx->tx_waiting);
393                 /* CAVEAT EMPTOR: I could be racing with tx_complete, but...
394                  * (a) I can overwrite tx_msg since my peer has received it!
395                  * (b) tx_waiting set tells tx_complete() it's not done. */
396
397                 tx->tx_nwrq = 0;                /* overwrite PUT_REQ */
398
399                 rc2 = kiblnd_init_rdma(conn, tx, IBLND_MSG_PUT_DONE,
400                                        kiblnd_rd_size(&msg->ibm_u.putack.ibpam_rd),
401                                        &msg->ibm_u.putack.ibpam_rd,
402                                        msg->ibm_u.putack.ibpam_dst_cookie);
403                 if (rc2 < 0)
404                         CERROR("Can't setup rdma for PUT to %s: %d\n",
405                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc2);
406
407                 cfs_spin_lock(&conn->ibc_lock);
408                 tx->tx_waiting = 0;             /* clear waiting and queue atomically */
409                 kiblnd_queue_tx_locked(tx, conn);
410                 cfs_spin_unlock(&conn->ibc_lock);
411                 break;
412
413         case IBLND_MSG_PUT_DONE:
414                 post_credit = IBLND_POSTRX_PEER_CREDIT;
415                 kiblnd_handle_completion(conn, IBLND_MSG_PUT_ACK,
416                                          msg->ibm_u.completion.ibcm_status,
417                                          msg->ibm_u.completion.ibcm_cookie);
418                 break;
419
420         case IBLND_MSG_GET_REQ:
421                 post_credit = IBLND_POSTRX_DONT_POST;
422                 rc = lnet_parse(ni, &msg->ibm_u.get.ibgm_hdr,
423                                 msg->ibm_srcnid, rx, 1);
424                 if (rc < 0)                     /* repost on error */
425                         post_credit = IBLND_POSTRX_PEER_CREDIT;
426                 break;
427
428         case IBLND_MSG_GET_DONE:
429                 post_credit = IBLND_POSTRX_RSRVD_CREDIT;
430                 kiblnd_handle_completion(conn, IBLND_MSG_GET_REQ,
431                                          msg->ibm_u.completion.ibcm_status,
432                                          msg->ibm_u.completion.ibcm_cookie);
433                 break;
434         }
435
436         if (rc < 0)                             /* protocol error */
437                 kiblnd_close_conn(conn, rc);
438
439         if (post_credit != IBLND_POSTRX_DONT_POST)
440                 kiblnd_post_rx(rx, post_credit);
441 }
442
443 void
444 kiblnd_rx_complete (kib_rx_t *rx, int status, int nob)
445 {
446         kib_msg_t    *msg = rx->rx_msg;
447         kib_conn_t   *conn = rx->rx_conn;
448         lnet_ni_t    *ni = conn->ibc_peer->ibp_ni;
449         kib_net_t    *net = ni->ni_data;
450         int           rc;
451         int           err = -EIO;
452
453         LASSERT (net != NULL);
454         LASSERT (rx->rx_nob < 0);               /* was posted */
455         rx->rx_nob = 0;                         /* isn't now */
456
457         if (conn->ibc_state > IBLND_CONN_ESTABLISHED)
458                 goto ignore;
459
460         if (status != IB_WC_SUCCESS) {
461                 CDEBUG(D_NETERROR, "Rx from %s failed: %d\n",
462                        libcfs_nid2str(conn->ibc_peer->ibp_nid), status);
463                 goto failed;
464         }
465
466         LASSERT (nob >= 0);
467         rx->rx_nob = nob;
468
469         rc = kiblnd_unpack_msg(msg, rx->rx_nob);
470         if (rc != 0) {
471                 CERROR ("Error %d unpacking rx from %s\n",
472                         rc, libcfs_nid2str(conn->ibc_peer->ibp_nid));
473                 goto failed;
474         }
475
476         if (msg->ibm_srcnid != conn->ibc_peer->ibp_nid ||
477             msg->ibm_dstnid != ni->ni_nid ||
478             msg->ibm_srcstamp != conn->ibc_incarnation ||
479             msg->ibm_dststamp != net->ibn_incarnation) {
480                 CERROR ("Stale rx from %s\n",
481                         libcfs_nid2str(conn->ibc_peer->ibp_nid));
482                 err = -ESTALE;
483                 goto failed;
484         }
485
486         /* set time last known alive */
487         kiblnd_peer_alive(conn->ibc_peer);
488
489         /* racing with connection establishment/teardown! */
490
491         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
492                 cfs_rwlock_t  *g_lock = &kiblnd_data.kib_global_lock;
493                 unsigned long  flags;
494
495                 cfs_write_lock_irqsave(g_lock, flags);
496                 /* must check holding global lock to eliminate race */
497                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
498                         cfs_list_add_tail(&rx->rx_list, &conn->ibc_early_rxs);
499                         cfs_write_unlock_irqrestore(g_lock, flags);
500                         return;
501                 }
502                 cfs_write_unlock_irqrestore(g_lock, flags);
503         }
504         kiblnd_handle_rx(rx);
505         return;
506
507  failed:
508         CDEBUG(D_NET, "rx %p conn %p\n", rx, conn);
509         kiblnd_close_conn(conn, err);
510  ignore:
511         kiblnd_drop_rx(rx);                     /* Don't re-post rx. */
512 }
513
514 struct page *
515 kiblnd_kvaddr_to_page (unsigned long vaddr)
516 {
517         struct page *page;
518
519         if (vaddr >= VMALLOC_START &&
520             vaddr < VMALLOC_END) {
521                 page = vmalloc_to_page ((void *)vaddr);
522                 LASSERT (page != NULL);
523                 return page;
524         }
525 #ifdef CONFIG_HIGHMEM
526         if (vaddr >= PKMAP_BASE &&
527             vaddr < (PKMAP_BASE + LAST_PKMAP * PAGE_SIZE)) {
528                 /* No highmem pages only used for bulk (kiov) I/O */
529                 CERROR("find page for address in highmem\n");
530                 LBUG();
531         }
532 #endif
533         page = virt_to_page (vaddr);
534         LASSERT (page != NULL);
535         return page;
536 }
537
538 static int
539 kiblnd_fmr_map_tx(kib_net_t *net, kib_tx_t *tx, kib_rdma_desc_t *rd, int nob)
540 {
541         kib_dev_t          *ibdev  = net->ibn_dev;
542         __u64              *pages  = tx->tx_pages;
543         int                 npages;
544         int                 size;
545         int                 rc;
546         int                 i;
547
548         for (i = 0, npages = 0; i < rd->rd_nfrags; i++) {
549                 for (size = 0; size <  rd->rd_frags[i].rf_nob;
550                                size += ibdev->ibd_page_size) {
551                         pages[npages ++] = (rd->rd_frags[i].rf_addr &
552                                             ibdev->ibd_page_mask) + size;
553                 }
554         }
555
556         rc = kiblnd_fmr_pool_map(&net->ibn_fmr_ps, pages, npages, 0, &tx->tx_u.fmr);
557         if (rc != 0) {
558                 CERROR ("Can't map %d pages: %d\n", npages, rc);
559                 return rc;
560         }
561
562         /* If rd is not tx_rd, it's going to get sent to a peer, who will need
563          * the rkey */
564         rd->rd_key = (rd != tx->tx_rd) ? tx->tx_u.fmr.fmr_pfmr->fmr->rkey :
565                                          tx->tx_u.fmr.fmr_pfmr->fmr->lkey;
566         rd->rd_frags[0].rf_addr &= ~ibdev->ibd_page_mask;
567         rd->rd_frags[0].rf_nob   = nob;
568         rd->rd_nfrags = 1;
569
570         return 0;
571 }
572
573 static int
574 kiblnd_pmr_map_tx(kib_net_t *net, kib_tx_t *tx, kib_rdma_desc_t *rd, int nob)
575 {
576         __u64   iova;
577         int     rc;
578
579         iova = rd->rd_frags[0].rf_addr & ~net->ibn_dev->ibd_page_mask;
580
581         rc = kiblnd_pmr_pool_map(&net->ibn_pmr_ps, rd, &iova, &tx->tx_u.pmr);
582         if (rc != 0) {
583                 CERROR("Failed to create MR by phybuf: %d\n", rc);
584                 return rc;
585         }
586
587         /* If rd is not tx_rd, it's going to get sent to a peer, who will need
588          * the rkey */
589         rd->rd_key = (rd != tx->tx_rd) ? tx->tx_u.pmr->pmr_mr->rkey :
590                                          tx->tx_u.pmr->pmr_mr->lkey;
591         rd->rd_nfrags = 1;
592         rd->rd_frags[0].rf_addr = iova;
593         rd->rd_frags[0].rf_nob  = nob;
594
595         return 0;
596 }
597
598 void
599 kiblnd_unmap_tx(lnet_ni_t *ni, kib_tx_t *tx)
600 {
601         kib_net_t  *net = ni->ni_data;
602
603         LASSERT (net != NULL);
604
605         if (net->ibn_with_fmr && tx->tx_u.fmr.fmr_pfmr != NULL) {
606                 kiblnd_fmr_pool_unmap(&tx->tx_u.fmr, tx->tx_status);
607                 tx->tx_u.fmr.fmr_pfmr = NULL;
608         } else if (net->ibn_with_pmr && tx->tx_u.pmr != NULL) {
609                 kiblnd_pmr_pool_unmap(tx->tx_u.pmr);
610                 tx->tx_u.pmr = NULL;
611         }
612
613         if (tx->tx_nfrags != 0) {
614                 kiblnd_dma_unmap_sg(net->ibn_dev->ibd_cmid->device,
615                                     tx->tx_frags, tx->tx_nfrags, tx->tx_dmadir);
616                 tx->tx_nfrags = 0;
617         }
618 }
619
620 int
621 kiblnd_map_tx(lnet_ni_t *ni, kib_tx_t *tx,
622               kib_rdma_desc_t *rd, int nfrags)
623 {
624         kib_net_t          *net   = ni->ni_data;
625         struct ib_mr       *mr    = NULL;
626         __u32               nob;
627         int                 i;
628
629         /* If rd is not tx_rd, it's going to get sent to a peer and I'm the
630          * RDMA sink */
631         tx->tx_dmadir = (rd != tx->tx_rd) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
632         tx->tx_nfrags = nfrags;
633
634         rd->rd_nfrags =
635                 kiblnd_dma_map_sg(net->ibn_dev->ibd_cmid->device,
636                                   tx->tx_frags, tx->tx_nfrags, tx->tx_dmadir);
637
638         for (i = 0, nob = 0; i < rd->rd_nfrags; i++) {
639                 rd->rd_frags[i].rf_nob  = kiblnd_sg_dma_len(
640                         net->ibn_dev->ibd_cmid->device, &tx->tx_frags[i]);
641                 rd->rd_frags[i].rf_addr = kiblnd_sg_dma_address(
642                         net->ibn_dev->ibd_cmid->device, &tx->tx_frags[i]);
643                 nob += rd->rd_frags[i].rf_nob;
644         }
645
646         /* looking for pre-mapping MR */
647         mr = kiblnd_find_rd_dma_mr(net, rd);
648         if (mr != NULL) {
649                 /* found pre-mapping MR */
650                 rd->rd_key = (rd != tx->tx_rd) ? mr->rkey : mr->lkey;
651                 return 0;
652         }
653
654         if (net->ibn_with_fmr)
655                 return kiblnd_fmr_map_tx(net, tx, rd, nob);
656         else if (net->ibn_with_pmr)
657                 return kiblnd_pmr_map_tx(net, tx, rd, nob);
658
659         return -EINVAL;
660 }
661
662
663 int
664 kiblnd_setup_rd_iov(lnet_ni_t *ni, kib_tx_t *tx, kib_rdma_desc_t *rd,
665                     unsigned int niov, struct iovec *iov, int offset, int nob)
666 {
667         kib_net_t          *net = ni->ni_data;
668         struct page        *page;
669         struct scatterlist *sg;
670         unsigned long       vaddr;
671         int                 fragnob;
672         int                 page_offset;
673
674         LASSERT (nob > 0);
675         LASSERT (niov > 0);
676         LASSERT (net != NULL);
677
678         while (offset >= iov->iov_len) {
679                 offset -= iov->iov_len;
680                 niov--;
681                 iov++;
682                 LASSERT (niov > 0);
683         }
684
685         sg = tx->tx_frags;
686         do {
687                 LASSERT (niov > 0);
688
689                 vaddr = ((unsigned long)iov->iov_base) + offset;
690                 page_offset = vaddr & (PAGE_SIZE - 1);
691                 page = kiblnd_kvaddr_to_page(vaddr);
692                 if (page == NULL) {
693                         CERROR ("Can't find page\n");
694                         return -EFAULT;
695                 }
696
697                 fragnob = min((int)(iov->iov_len - offset), nob);
698                 fragnob = min(fragnob, (int)PAGE_SIZE - page_offset);
699
700                 sg_set_page(sg, page, fragnob, page_offset);
701                 sg++;
702
703                 if (offset + fragnob < iov->iov_len) {
704                         offset += fragnob;
705                 } else {
706                         offset = 0;
707                         iov++;
708                         niov--;
709                 }
710                 nob -= fragnob;
711         } while (nob > 0);
712
713         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
714 }
715
716 static inline int
717 get_kiov_length (int nkiov, lnet_kiov_t *kiov, int offset, int nob)
718 {
719         int fragnob;
720         int count = 0;
721
722         do {
723                 LASSERT (nkiov > 0);
724
725                 fragnob = min((int)(kiov->kiov_len - offset), nob);
726
727                 count++;
728
729                 offset = 0;
730                 kiov++;
731                 nkiov--;
732                 nob -= fragnob;
733         } while (nob > 0);
734
735         return count;
736 }
737
738 int
739 kiblnd_setup_rd_kiov (lnet_ni_t *ni, kib_tx_t *tx, kib_rdma_desc_t *rd,
740                       int nkiov, lnet_kiov_t *kiov, int offset, int nob)
741 {
742         kib_net_t          *net = ni->ni_data;
743         struct scatterlist *sg;
744         int                 fragnob;
745
746         CDEBUG(D_NET, "niov %d offset %d nob %d\n", nkiov, offset, nob);
747
748         LASSERT (nob > 0);
749         LASSERT (nkiov > 0);
750         LASSERT (net != NULL);
751
752         while (offset >= kiov->kiov_len) {
753                 offset -= kiov->kiov_len;
754                 nkiov--;
755                 kiov++;
756                 LASSERT (nkiov > 0);
757         }
758
759         sg = tx->tx_frags;
760         tx->tx_nfrags = get_kiov_length(nkiov, kiov, offset, nob);
761         sg_init_table(sg, tx->tx_nfrags);
762         do {
763                 LASSERT (nkiov > 0);
764
765                 fragnob = min((int)(kiov->kiov_len - offset), nob);
766
767                 sg_set_page(sg, kiov->kiov_page, fragnob,
768                             kiov->kiov_offset + offset);
769                 sg++;
770
771                 offset = 0;
772                 kiov++;
773                 nkiov--;
774                 nob -= fragnob;
775         } while (nob > 0);
776
777         return kiblnd_map_tx(ni, tx, rd, sg - tx->tx_frags);
778 }
779
780 int
781 kiblnd_post_tx_locked (kib_conn_t *conn, kib_tx_t *tx, int credit)
782 {
783         kib_msg_t         *msg = tx->tx_msg;
784         kib_peer_t        *peer = conn->ibc_peer;
785         int                ver = conn->ibc_version;
786         int                rc;
787         int                done;
788         struct ib_send_wr *bad_wrq;
789
790         LASSERT (tx->tx_queued);
791         /* We rely on this for QP sizing */
792         LASSERT (tx->tx_nwrq > 0);
793         LASSERT (tx->tx_nwrq <= 1 + IBLND_RDMA_FRAGS(ver));
794
795         LASSERT (credit == 0 || credit == 1);
796         LASSERT (conn->ibc_outstanding_credits >= 0);
797         LASSERT (conn->ibc_outstanding_credits <= IBLND_MSG_QUEUE_SIZE(ver));
798         LASSERT (conn->ibc_credits >= 0);
799         LASSERT (conn->ibc_credits <= IBLND_MSG_QUEUE_SIZE(ver));
800
801         if (conn->ibc_nsends_posted == IBLND_CONCURRENT_SENDS(ver)) {
802                 /* tx completions outstanding... */
803                 CDEBUG(D_NET, "%s: posted enough\n",
804                        libcfs_nid2str(peer->ibp_nid));
805                 return -EAGAIN;
806         }
807
808         if (credit != 0 && conn->ibc_credits == 0) {   /* no credits */
809                 CDEBUG(D_NET, "%s: no credits\n",
810                        libcfs_nid2str(peer->ibp_nid));
811                 return -EAGAIN;
812         }
813
814         if (credit != 0 && !IBLND_OOB_CAPABLE(ver) &&
815             conn->ibc_credits == 1 &&   /* last credit reserved for */
816             conn->ibc_outstanding_credits == 0) { /* giving back credits */
817                 CDEBUG(D_NET, "%s: not using last credit\n",
818                        libcfs_nid2str(peer->ibp_nid));
819                 return -EAGAIN;
820         }
821
822         /* NB don't drop ibc_lock before bumping tx_sending */
823         cfs_list_del(&tx->tx_list);
824         tx->tx_queued = 0;
825
826         if (msg->ibm_type == IBLND_MSG_NOOP &&
827             (!kiblnd_send_noop(conn) ||     /* redundant NOOP */
828              (IBLND_OOB_CAPABLE(ver) && /* posted enough NOOP */
829               conn->ibc_noops_posted == IBLND_OOB_MSGS(ver)))) {
830                 /* OK to drop when posted enough NOOPs, since
831                  * kiblnd_check_sends will queue NOOP again when
832                  * posted NOOPs complete */
833                 cfs_spin_unlock(&conn->ibc_lock);
834                 kiblnd_tx_done(peer->ibp_ni, tx);
835                 cfs_spin_lock(&conn->ibc_lock);
836                 CDEBUG(D_NET, "%s(%d): redundant or enough NOOP\n",
837                        libcfs_nid2str(peer->ibp_nid),
838                        conn->ibc_noops_posted);
839                 return 0;
840         }
841
842         kiblnd_pack_msg(peer->ibp_ni, msg, ver, conn->ibc_outstanding_credits,
843                         peer->ibp_nid, conn->ibc_incarnation);
844
845         conn->ibc_credits -= credit;
846         conn->ibc_outstanding_credits = 0;
847         conn->ibc_nsends_posted++;
848         if (msg->ibm_type == IBLND_MSG_NOOP)
849                 conn->ibc_noops_posted++;
850
851         /* CAVEAT EMPTOR!  This tx could be the PUT_DONE of an RDMA
852          * PUT.  If so, it was first queued here as a PUT_REQ, sent and
853          * stashed on ibc_active_txs, matched by an incoming PUT_ACK,
854          * and then re-queued here.  It's (just) possible that
855          * tx_sending is non-zero if we've not done the tx_complete()
856          * from the first send; hence the ++ rather than = below. */
857         tx->tx_sending++;
858         cfs_list_add(&tx->tx_list, &conn->ibc_active_txs);
859
860         /* I'm still holding ibc_lock! */
861         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
862                 rc = -ECONNABORTED;
863         else
864                 rc = ib_post_send(conn->ibc_cmid->qp,
865                                   tx->tx_wrq, &bad_wrq);
866         conn->ibc_last_send = jiffies;
867
868         if (rc == 0)
869                 return 0;
870
871         /* NB credits are transferred in the actual
872          * message, which can only be the last work item */
873         conn->ibc_credits += credit;
874         conn->ibc_outstanding_credits += msg->ibm_credits;
875         conn->ibc_nsends_posted--;
876         if (msg->ibm_type == IBLND_MSG_NOOP)
877                 conn->ibc_noops_posted--;
878
879         tx->tx_status = rc;
880         tx->tx_waiting = 0;
881         tx->tx_sending--;
882
883         done = (tx->tx_sending == 0);
884         if (done)
885                 cfs_list_del(&tx->tx_list);
886
887         cfs_spin_unlock(&conn->ibc_lock);
888
889         if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
890                 CERROR("Error %d posting transmit to %s\n",
891                        rc, libcfs_nid2str(peer->ibp_nid));
892         else
893                 CDEBUG(D_NET, "Error %d posting transmit to %s\n",
894                        rc, libcfs_nid2str(peer->ibp_nid));
895
896         kiblnd_close_conn(conn, rc);
897
898         if (done)
899                 kiblnd_tx_done(peer->ibp_ni, tx);
900
901         cfs_spin_lock(&conn->ibc_lock);
902
903         return -EIO;
904 }
905
906 void
907 kiblnd_check_sends (kib_conn_t *conn)
908 {
909         int        ver = conn->ibc_version;
910         lnet_ni_t *ni = conn->ibc_peer->ibp_ni;
911         kib_tx_t  *tx;
912
913         /* Don't send anything until after the connection is established */
914         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
915                 CDEBUG(D_NET, "%s too soon\n",
916                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
917                 return;
918         }
919
920         cfs_spin_lock(&conn->ibc_lock);
921
922         LASSERT (conn->ibc_nsends_posted <= IBLND_CONCURRENT_SENDS(ver));
923         LASSERT (!IBLND_OOB_CAPABLE(ver) ||
924                  conn->ibc_noops_posted <= IBLND_OOB_MSGS(ver));
925         LASSERT (conn->ibc_reserved_credits >= 0);
926
927         while (conn->ibc_reserved_credits > 0 &&
928                !cfs_list_empty(&conn->ibc_tx_queue_rsrvd)) {
929                 tx = cfs_list_entry(conn->ibc_tx_queue_rsrvd.next,
930                                     kib_tx_t, tx_list);
931                 cfs_list_del(&tx->tx_list);
932                 cfs_list_add_tail(&tx->tx_list, &conn->ibc_tx_queue);
933                 conn->ibc_reserved_credits--;
934         }
935
936         if (kiblnd_send_noop(conn)) {
937                 cfs_spin_unlock(&conn->ibc_lock);
938
939                 tx = kiblnd_get_idle_tx(ni);
940                 if (tx != NULL)
941                         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_NOOP, 0);
942
943                 cfs_spin_lock(&conn->ibc_lock);
944                 if (tx != NULL)
945                         kiblnd_queue_tx_locked(tx, conn);
946         }
947
948         kiblnd_conn_addref(conn); /* 1 ref for me.... (see b21911) */
949
950         for (;;) {
951                 int credit;
952
953                 if (!cfs_list_empty(&conn->ibc_tx_queue_nocred)) {
954                         credit = 0;
955                         tx = cfs_list_entry(conn->ibc_tx_queue_nocred.next,
956                                             kib_tx_t, tx_list);
957                 } else if (!cfs_list_empty(&conn->ibc_tx_queue)) {
958                         credit = 1;
959                         tx = cfs_list_entry(conn->ibc_tx_queue.next,
960                                             kib_tx_t, tx_list);
961                 } else
962                         break;
963
964                 if (kiblnd_post_tx_locked(conn, tx, credit) != 0)
965                         break;
966         }
967
968         cfs_spin_unlock(&conn->ibc_lock);
969
970         kiblnd_conn_decref(conn); /* ...until here */
971 }
972
973 void
974 kiblnd_tx_complete (kib_tx_t *tx, int status)
975 {
976         int           failed = (status != IB_WC_SUCCESS);
977         kib_conn_t   *conn = tx->tx_conn;
978         int           idle;
979
980         LASSERT (tx->tx_sending > 0);
981
982         if (failed) {
983                 if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
984                         CDEBUG(D_NETERROR, "Tx -> %s cookie "LPX64
985                                " sending %d waiting %d: failed %d\n",
986                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
987                                tx->tx_cookie, tx->tx_sending, tx->tx_waiting,
988                                status);
989
990                 kiblnd_close_conn(conn, -EIO);
991         } else {
992                 kiblnd_peer_alive(conn->ibc_peer);
993         }
994
995         cfs_spin_lock(&conn->ibc_lock);
996
997         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
998          * gets to free it, which also drops its ref on 'conn'. */
999
1000         tx->tx_sending--;
1001         conn->ibc_nsends_posted--;
1002         if (tx->tx_msg->ibm_type == IBLND_MSG_NOOP)
1003                 conn->ibc_noops_posted--;
1004
1005         if (failed) {
1006                 tx->tx_waiting = 0;             /* don't wait for peer */
1007                 tx->tx_status = -EIO;
1008         }
1009
1010         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
1011                !tx->tx_waiting &&               /* Not waiting for peer */
1012                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
1013         if (idle)
1014                 cfs_list_del(&tx->tx_list);
1015
1016         kiblnd_conn_addref(conn);               /* 1 ref for me.... */
1017
1018         cfs_spin_unlock(&conn->ibc_lock);
1019
1020         if (idle)
1021                 kiblnd_tx_done(conn->ibc_peer->ibp_ni, tx);
1022
1023         kiblnd_check_sends(conn);
1024
1025         kiblnd_conn_decref(conn);               /* ...until here */
1026 }
1027
1028 void
1029 kiblnd_init_tx_msg (lnet_ni_t *ni, kib_tx_t *tx, int type, int body_nob)
1030 {
1031         kib_net_t         *net = ni->ni_data;
1032         struct ib_sge     *sge = &tx->tx_sge[tx->tx_nwrq];
1033         struct ib_send_wr *wrq = &tx->tx_wrq[tx->tx_nwrq];
1034         int                nob = offsetof (kib_msg_t, ibm_u) + body_nob;
1035         struct ib_mr      *mr;
1036
1037         LASSERT (net != NULL);
1038         LASSERT (tx->tx_nwrq >= 0);
1039         LASSERT (tx->tx_nwrq < IBLND_MAX_RDMA_FRAGS + 1);
1040         LASSERT (nob <= IBLND_MSG_SIZE);
1041
1042         kiblnd_init_msg(tx->tx_msg, type, body_nob);
1043
1044         mr = kiblnd_find_dma_mr(net, tx->tx_msgaddr, nob);
1045         LASSERT (mr != NULL);
1046
1047         sge->lkey   = mr->lkey;
1048         sge->addr   = tx->tx_msgaddr;
1049         sge->length = nob;
1050
1051         memset(wrq, 0, sizeof(*wrq));
1052
1053         wrq->next       = NULL;
1054         wrq->wr_id      = kiblnd_ptr2wreqid(tx, IBLND_WID_TX);
1055         wrq->sg_list    = sge;
1056         wrq->num_sge    = 1;
1057         wrq->opcode     = IB_WR_SEND;
1058         wrq->send_flags = IB_SEND_SIGNALED;
1059
1060         tx->tx_nwrq++;
1061 }
1062
1063 int
1064 kiblnd_init_rdma (kib_conn_t *conn, kib_tx_t *tx, int type,
1065                   int resid, kib_rdma_desc_t *dstrd, __u64 dstcookie)
1066 {
1067         kib_msg_t         *ibmsg = tx->tx_msg;
1068         kib_rdma_desc_t   *srcrd = tx->tx_rd;
1069         struct ib_sge     *sge = &tx->tx_sge[0];
1070         struct ib_send_wr *wrq = &tx->tx_wrq[0];
1071         int                rc  = resid;
1072         int                srcidx;
1073         int                dstidx;
1074         int                wrknob;
1075
1076         LASSERT (!cfs_in_interrupt());
1077         LASSERT (tx->tx_nwrq == 0);
1078         LASSERT (type == IBLND_MSG_GET_DONE ||
1079                  type == IBLND_MSG_PUT_DONE);
1080
1081         srcidx = dstidx = 0;
1082
1083         while (resid > 0) {
1084                 if (srcidx >= srcrd->rd_nfrags) {
1085                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1086                         rc = -EPROTO;
1087                         break;
1088                 }
1089
1090                 if (dstidx == dstrd->rd_nfrags) {
1091                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1092                         rc = -EPROTO;
1093                         break;
1094                 }
1095
1096                 if (tx->tx_nwrq == IBLND_RDMA_FRAGS(conn->ibc_version)) {
1097                         CERROR("RDMA too fragmented for %s (%d): "
1098                                "%d/%d src %d/%d dst frags\n",
1099                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
1100                                IBLND_RDMA_FRAGS(conn->ibc_version),
1101                                srcidx, srcrd->rd_nfrags,
1102                                dstidx, dstrd->rd_nfrags);
1103                         rc = -EMSGSIZE;
1104                         break;
1105                 }
1106
1107                 wrknob = MIN(MIN(kiblnd_rd_frag_size(srcrd, srcidx),
1108                                  kiblnd_rd_frag_size(dstrd, dstidx)), resid);
1109
1110                 sge = &tx->tx_sge[tx->tx_nwrq];
1111                 sge->addr   = kiblnd_rd_frag_addr(srcrd, srcidx);
1112                 sge->lkey   = kiblnd_rd_frag_key(srcrd, srcidx);
1113                 sge->length = wrknob;
1114
1115                 wrq = &tx->tx_wrq[tx->tx_nwrq];
1116
1117                 wrq->next       = wrq + 1;
1118                 wrq->wr_id      = kiblnd_ptr2wreqid(tx, IBLND_WID_RDMA);
1119                 wrq->sg_list    = sge;
1120                 wrq->num_sge    = 1;
1121                 wrq->opcode     = IB_WR_RDMA_WRITE;
1122                 wrq->send_flags = 0;
1123
1124                 wrq->wr.rdma.remote_addr = kiblnd_rd_frag_addr(dstrd, dstidx);
1125                 wrq->wr.rdma.rkey        = kiblnd_rd_frag_key(dstrd, dstidx);
1126
1127                 srcidx = kiblnd_rd_consume_frag(srcrd, srcidx, wrknob);
1128                 dstidx = kiblnd_rd_consume_frag(dstrd, dstidx, wrknob);
1129
1130                 resid -= wrknob;
1131
1132                 tx->tx_nwrq++;
1133                 wrq++;
1134                 sge++;
1135         }
1136
1137         if (rc < 0)                             /* no RDMA if completing with failure */
1138                 tx->tx_nwrq = 0;
1139
1140         ibmsg->ibm_u.completion.ibcm_status = rc;
1141         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1142         kiblnd_init_tx_msg(conn->ibc_peer->ibp_ni, tx,
1143                            type, sizeof (kib_completion_msg_t));
1144
1145         return rc;
1146 }
1147
1148 void
1149 kiblnd_queue_tx_locked (kib_tx_t *tx, kib_conn_t *conn)
1150 {
1151         cfs_list_t   *q;
1152
1153         LASSERT (tx->tx_nwrq > 0);              /* work items set up */
1154         LASSERT (!tx->tx_queued);               /* not queued for sending already */
1155         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1156
1157         tx->tx_queued = 1;
1158         tx->tx_deadline = jiffies + (*kiblnd_tunables.kib_timeout * CFS_HZ);
1159
1160         if (tx->tx_conn == NULL) {
1161                 kiblnd_conn_addref(conn);
1162                 tx->tx_conn = conn;
1163                 LASSERT (tx->tx_msg->ibm_type != IBLND_MSG_PUT_DONE);
1164         } else {
1165                 /* PUT_DONE first attached to conn as a PUT_REQ */
1166                 LASSERT (tx->tx_conn == conn);
1167                 LASSERT (tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1168         }
1169
1170         switch (tx->tx_msg->ibm_type) {
1171         default:
1172                 LBUG();
1173
1174         case IBLND_MSG_PUT_REQ:
1175         case IBLND_MSG_GET_REQ:
1176                 q = &conn->ibc_tx_queue_rsrvd;
1177                 break;
1178
1179         case IBLND_MSG_PUT_NAK:
1180         case IBLND_MSG_PUT_ACK:
1181         case IBLND_MSG_PUT_DONE:
1182         case IBLND_MSG_GET_DONE:
1183                 q = &conn->ibc_tx_queue_nocred;
1184                 break;
1185
1186         case IBLND_MSG_NOOP:
1187                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
1188                         q = &conn->ibc_tx_queue_nocred;
1189                 else
1190                         q = &conn->ibc_tx_queue;
1191                 break;
1192
1193         case IBLND_MSG_IMMEDIATE:
1194                 q = &conn->ibc_tx_queue;
1195                 break;
1196         }
1197
1198         cfs_list_add_tail(&tx->tx_list, q);
1199 }
1200
1201 void
1202 kiblnd_queue_tx (kib_tx_t *tx, kib_conn_t *conn)
1203 {
1204         cfs_spin_lock(&conn->ibc_lock);
1205         kiblnd_queue_tx_locked(tx, conn);
1206         cfs_spin_unlock(&conn->ibc_lock);
1207
1208         kiblnd_check_sends(conn);
1209 }
1210
1211 void
1212 kiblnd_connect_peer (kib_peer_t *peer)
1213 {
1214         struct rdma_cm_id *cmid;
1215         kib_dev_t         *dev;
1216         kib_net_t         *net = peer->ibp_ni->ni_data;
1217         struct sockaddr_in srcaddr;
1218         struct sockaddr_in dstaddr;
1219         int                rc;
1220
1221         LASSERT (net != NULL);
1222         LASSERT (peer->ibp_connecting > 0);
1223
1224         cmid = rdma_create_id(kiblnd_cm_callback, peer, RDMA_PS_TCP);
1225         if (IS_ERR(cmid)) {
1226                 CERROR("Can't create CMID for %s: %ld\n",
1227                        libcfs_nid2str(peer->ibp_nid), PTR_ERR(cmid));
1228                 rc = PTR_ERR(cmid);
1229                 goto failed;
1230         }
1231
1232         dev = net->ibn_dev;
1233         memset(&srcaddr, 0, sizeof(srcaddr));
1234         srcaddr.sin_family = AF_INET;
1235         srcaddr.sin_addr.s_addr = htonl(dev->ibd_ifip);
1236
1237         memset(&dstaddr, 0, sizeof(dstaddr));
1238         dstaddr.sin_family = AF_INET;
1239         dstaddr.sin_port = htons(*kiblnd_tunables.kib_service);
1240         dstaddr.sin_addr.s_addr = htonl(LNET_NIDADDR(peer->ibp_nid));
1241
1242         kiblnd_peer_addref(peer);               /* cmid's ref */
1243
1244         rc = rdma_resolve_addr(cmid,
1245                                (struct sockaddr *)&srcaddr,
1246                                (struct sockaddr *)&dstaddr,
1247                                *kiblnd_tunables.kib_timeout * 1000);
1248         if (rc == 0) {
1249                 LASSERT (cmid->device != NULL);
1250                 CDEBUG(D_NET, "%s: connection bound to %s:%u.%u.%u.%u:%s\n",
1251                        libcfs_nid2str(peer->ibp_nid), dev->ibd_ifname,
1252                        HIPQUAD(dev->ibd_ifip), cmid->device->name);
1253                 return;
1254         }
1255
1256         /* Can't initiate address resolution:  */
1257         CERROR("Can't resolve addr for %s: %d\n",
1258                libcfs_nid2str(peer->ibp_nid), rc);
1259
1260         kiblnd_peer_decref(peer);               /* cmid's ref */
1261         rdma_destroy_id(cmid);
1262  failed:
1263         kiblnd_peer_connect_failed(peer, 1, rc);
1264 }
1265
1266 void
1267 kiblnd_launch_tx (lnet_ni_t *ni, kib_tx_t *tx, lnet_nid_t nid)
1268 {
1269         kib_peer_t        *peer;
1270         kib_peer_t        *peer2;
1271         kib_conn_t        *conn;
1272         cfs_rwlock_t      *g_lock = &kiblnd_data.kib_global_lock;
1273         unsigned long      flags;
1274         int                rc;
1275
1276         /* If I get here, I've committed to send, so I complete the tx with
1277          * failure on any problems */
1278
1279         LASSERT (tx == NULL || tx->tx_conn == NULL); /* only set when assigned a conn */
1280         LASSERT (tx == NULL || tx->tx_nwrq > 0);     /* work items have been set up */
1281
1282         /* First time, just use a read lock since I expect to find my peer
1283          * connected */
1284         cfs_read_lock_irqsave(g_lock, flags);
1285
1286         peer = kiblnd_find_peer_locked(nid);
1287         if (peer != NULL && !cfs_list_empty(&peer->ibp_conns)) {
1288                 /* Found a peer with an established connection */
1289                 conn = kiblnd_get_conn_locked(peer);
1290                 kiblnd_conn_addref(conn); /* 1 ref for me... */
1291
1292                 cfs_read_unlock_irqrestore(g_lock, flags);
1293
1294                 if (tx != NULL)
1295                         kiblnd_queue_tx(tx, conn);
1296                 kiblnd_conn_decref(conn); /* ...to here */
1297                 return;
1298         }
1299
1300         cfs_read_unlock(g_lock);
1301         /* Re-try with a write lock */
1302         cfs_write_lock(g_lock);
1303
1304         peer = kiblnd_find_peer_locked(nid);
1305         if (peer != NULL) {
1306                 if (cfs_list_empty(&peer->ibp_conns)) {
1307                         /* found a peer, but it's still connecting... */
1308                         LASSERT (peer->ibp_connecting != 0 ||
1309                                  peer->ibp_accepting != 0);
1310                         if (tx != NULL)
1311                                 cfs_list_add_tail(&tx->tx_list,
1312                                                   &peer->ibp_tx_queue);
1313                         cfs_write_unlock_irqrestore(g_lock, flags);
1314                 } else {
1315                         conn = kiblnd_get_conn_locked(peer);
1316                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1317
1318                         cfs_write_unlock_irqrestore(g_lock, flags);
1319
1320                         if (tx != NULL)
1321                                 kiblnd_queue_tx(tx, conn);
1322                         kiblnd_conn_decref(conn); /* ...to here */
1323                 }
1324                 return;
1325         }
1326
1327         cfs_write_unlock_irqrestore(g_lock, flags);
1328
1329         /* Allocate a peer ready to add to the peer table and retry */
1330         rc = kiblnd_create_peer(ni, &peer, nid);
1331         if (rc != 0) {
1332                 CERROR("Can't create peer %s\n", libcfs_nid2str(nid));
1333                 if (tx != NULL) {
1334                         tx->tx_status = -EHOSTUNREACH;
1335                         tx->tx_waiting = 0;
1336                         kiblnd_tx_done(ni, tx);
1337                 }
1338                 return;
1339         }
1340
1341         cfs_write_lock_irqsave(g_lock, flags);
1342
1343         peer2 = kiblnd_find_peer_locked(nid);
1344         if (peer2 != NULL) {
1345                 if (cfs_list_empty(&peer2->ibp_conns)) {
1346                         /* found a peer, but it's still connecting... */
1347                         LASSERT (peer2->ibp_connecting != 0 ||
1348                                  peer2->ibp_accepting != 0);
1349                         if (tx != NULL)
1350                                 cfs_list_add_tail(&tx->tx_list,
1351                                                   &peer2->ibp_tx_queue);
1352                         cfs_write_unlock_irqrestore(g_lock, flags);
1353                 } else {
1354                         conn = kiblnd_get_conn_locked(peer2);
1355                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1356
1357                         cfs_write_unlock_irqrestore(g_lock, flags);
1358
1359                         if (tx != NULL)
1360                                 kiblnd_queue_tx(tx, conn);
1361                         kiblnd_conn_decref(conn); /* ...to here */
1362                 }
1363
1364                 kiblnd_peer_decref(peer);
1365                 return;
1366         }
1367
1368         /* Brand new peer */
1369         LASSERT (peer->ibp_connecting == 0);
1370         peer->ibp_connecting = 1;
1371
1372         /* always called with a ref on ni, which prevents ni being shutdown */
1373         LASSERT (((kib_net_t *)ni->ni_data)->ibn_shutdown == 0);
1374
1375         if (tx != NULL)
1376                 cfs_list_add_tail(&tx->tx_list, &peer->ibp_tx_queue);
1377
1378         kiblnd_peer_addref(peer);
1379         cfs_list_add_tail(&peer->ibp_list, kiblnd_nid2peerlist(nid));
1380
1381         cfs_write_unlock_irqrestore(g_lock, flags);
1382
1383         kiblnd_connect_peer(peer);
1384         kiblnd_peer_decref(peer);
1385 }
1386
1387 int
1388 kiblnd_send (lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg)
1389 {
1390         lnet_hdr_t       *hdr = &lntmsg->msg_hdr;
1391         int               type = lntmsg->msg_type;
1392         lnet_process_id_t target = lntmsg->msg_target;
1393         int               target_is_router = lntmsg->msg_target_is_router;
1394         int               routing = lntmsg->msg_routing;
1395         unsigned int      payload_niov = lntmsg->msg_niov;
1396         struct iovec     *payload_iov = lntmsg->msg_iov;
1397         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
1398         unsigned int      payload_offset = lntmsg->msg_offset;
1399         unsigned int      payload_nob = lntmsg->msg_len;
1400         kib_msg_t        *ibmsg;
1401         kib_tx_t         *tx;
1402         int               nob;
1403         int               rc;
1404
1405         /* NB 'private' is different depending on what we're sending.... */
1406
1407         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1408                payload_nob, payload_niov, libcfs_id2str(target));
1409
1410         LASSERT (payload_nob == 0 || payload_niov > 0);
1411         LASSERT (payload_niov <= LNET_MAX_IOV);
1412
1413         /* Thread context */
1414         LASSERT (!cfs_in_interrupt());
1415         /* payload is either all vaddrs or all pages */
1416         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1417
1418         switch (type) {
1419         default:
1420                 LBUG();
1421                 return (-EIO);
1422
1423         case LNET_MSG_ACK:
1424                 LASSERT (payload_nob == 0);
1425                 break;
1426
1427         case LNET_MSG_GET:
1428                 if (routing || target_is_router)
1429                         break;                  /* send IMMEDIATE */
1430
1431                 /* is the REPLY message too small for RDMA? */
1432                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1433                 if (nob <= IBLND_MSG_SIZE)
1434                         break;                  /* send IMMEDIATE */
1435
1436                 tx = kiblnd_get_idle_tx(ni);
1437                 if (tx == NULL) {
1438                         CERROR("Can't allocate txd for GET to %s: \n",
1439                                libcfs_nid2str(target.nid));
1440                         return -ENOMEM;
1441                 }
1442
1443                 ibmsg = tx->tx_msg;
1444
1445                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0)
1446                         rc = kiblnd_setup_rd_iov(ni, tx,
1447                                                  &ibmsg->ibm_u.get.ibgm_rd,
1448                                                  lntmsg->msg_md->md_niov,
1449                                                  lntmsg->msg_md->md_iov.iov,
1450                                                  0, lntmsg->msg_md->md_length);
1451                 else
1452                         rc = kiblnd_setup_rd_kiov(ni, tx,
1453                                                   &ibmsg->ibm_u.get.ibgm_rd,
1454                                                   lntmsg->msg_md->md_niov,
1455                                                   lntmsg->msg_md->md_iov.kiov,
1456                                                   0, lntmsg->msg_md->md_length);
1457                 if (rc != 0) {
1458                         CERROR("Can't setup GET sink for %s: %d\n",
1459                                libcfs_nid2str(target.nid), rc);
1460                         kiblnd_tx_done(ni, tx);
1461                         return -EIO;
1462                 }
1463
1464                 nob = offsetof(kib_get_msg_t, ibgm_rd.rd_frags[tx->tx_nfrags]);
1465                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1466                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1467
1468                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1469
1470                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1471                 if (tx->tx_lntmsg[1] == NULL) {
1472                         CERROR("Can't create reply for GET -> %s\n",
1473                                libcfs_nid2str(target.nid));
1474                         kiblnd_tx_done(ni, tx);
1475                         return -EIO;
1476                 }
1477
1478                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1479                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1480                 kiblnd_launch_tx(ni, tx, target.nid);
1481                 return 0;
1482
1483         case LNET_MSG_REPLY:
1484         case LNET_MSG_PUT:
1485                 /* Is the payload small enough not to need RDMA? */
1486                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob]);
1487                 if (nob <= IBLND_MSG_SIZE)
1488                         break;                  /* send IMMEDIATE */
1489
1490                 tx = kiblnd_get_idle_tx(ni);
1491                 if (tx == NULL) {
1492                         CERROR("Can't allocate %s txd for %s\n",
1493                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1494                                libcfs_nid2str(target.nid));
1495                         return -ENOMEM;
1496                 }
1497
1498                 if (payload_kiov == NULL)
1499                         rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1500                                                  payload_niov, payload_iov,
1501                                                  payload_offset, payload_nob);
1502                 else
1503                         rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1504                                                   payload_niov, payload_kiov,
1505                                                   payload_offset, payload_nob);
1506                 if (rc != 0) {
1507                         CERROR("Can't setup PUT src for %s: %d\n",
1508                                libcfs_nid2str(target.nid), rc);
1509                         kiblnd_tx_done(ni, tx);
1510                         return -EIO;
1511                 }
1512
1513                 ibmsg = tx->tx_msg;
1514                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1515                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1516                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ, sizeof(kib_putreq_msg_t));
1517
1518                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1519                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1520                 kiblnd_launch_tx(ni, tx, target.nid);
1521                 return 0;
1522         }
1523
1524         /* send IMMEDIATE */
1525
1526         LASSERT (offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob])
1527                  <= IBLND_MSG_SIZE);
1528
1529         tx = kiblnd_get_idle_tx(ni);
1530         if (tx == NULL) {
1531                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1532                         type, libcfs_nid2str(target.nid));
1533                 return -ENOMEM;
1534         }
1535
1536         ibmsg = tx->tx_msg;
1537         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1538
1539         if (payload_kiov != NULL)
1540                 lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1541                                     offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1542                                     payload_niov, payload_kiov,
1543                                     payload_offset, payload_nob);
1544         else
1545                 lnet_copy_iov2flat(IBLND_MSG_SIZE, ibmsg,
1546                                    offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1547                                    payload_niov, payload_iov,
1548                                    payload_offset, payload_nob);
1549
1550         nob = offsetof(kib_immediate_msg_t, ibim_payload[payload_nob]);
1551         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1552
1553         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1554         kiblnd_launch_tx(ni, tx, target.nid);
1555         return 0;
1556 }
1557
1558 void
1559 kiblnd_reply (lnet_ni_t *ni, kib_rx_t *rx, lnet_msg_t *lntmsg)
1560 {
1561         lnet_process_id_t target = lntmsg->msg_target;
1562         unsigned int      niov = lntmsg->msg_niov;
1563         struct iovec     *iov = lntmsg->msg_iov;
1564         lnet_kiov_t      *kiov = lntmsg->msg_kiov;
1565         unsigned int      offset = lntmsg->msg_offset;
1566         unsigned int      nob = lntmsg->msg_len;
1567         kib_tx_t         *tx;
1568         int               rc;
1569
1570         tx = kiblnd_get_idle_tx(ni);
1571         if (tx == NULL) {
1572                 CERROR("Can't get tx for REPLY to %s\n",
1573                        libcfs_nid2str(target.nid));
1574                 goto failed_0;
1575         }
1576
1577         if (nob == 0)
1578                 rc = 0;
1579         else if (kiov == NULL)
1580                 rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1581                                          niov, iov, offset, nob);
1582         else
1583                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1584                                           niov, kiov, offset, nob);
1585
1586         if (rc != 0) {
1587                 CERROR("Can't setup GET src for %s: %d\n",
1588                        libcfs_nid2str(target.nid), rc);
1589                 goto failed_1;
1590         }
1591
1592         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1593                               IBLND_MSG_GET_DONE, nob,
1594                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1595                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1596         if (rc < 0) {
1597                 CERROR("Can't setup rdma for GET from %s: %d\n",
1598                        libcfs_nid2str(target.nid), rc);
1599                 goto failed_1;
1600         }
1601         
1602         if (nob == 0) {
1603                 /* No RDMA: local completion may happen now! */
1604                 lnet_finalize(ni, lntmsg, 0);
1605         } else {
1606                 /* RDMA: lnet_finalize(lntmsg) when it
1607                  * completes */
1608                 tx->tx_lntmsg[0] = lntmsg;
1609         }
1610
1611         kiblnd_queue_tx(tx, rx->rx_conn);
1612         return;
1613
1614  failed_1:
1615         kiblnd_tx_done(ni, tx);
1616  failed_0:
1617         lnet_finalize(ni, lntmsg, -EIO);
1618 }
1619
1620 int
1621 kiblnd_recv (lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg, int delayed,
1622              unsigned int niov, struct iovec *iov, lnet_kiov_t *kiov,
1623              unsigned int offset, unsigned int mlen, unsigned int rlen)
1624 {
1625         kib_rx_t    *rx = private;
1626         kib_msg_t   *rxmsg = rx->rx_msg;
1627         kib_conn_t  *conn = rx->rx_conn;
1628         kib_tx_t    *tx;
1629         kib_msg_t   *txmsg;
1630         int          nob;
1631         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1632         int          rc = 0;
1633
1634         LASSERT (mlen <= rlen);
1635         LASSERT (!cfs_in_interrupt());
1636         /* Either all pages or all vaddrs */
1637         LASSERT (!(kiov != NULL && iov != NULL));
1638
1639         switch (rxmsg->ibm_type) {
1640         default:
1641                 LBUG();
1642
1643         case IBLND_MSG_IMMEDIATE:
1644                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[rlen]);
1645                 if (nob > rx->rx_nob) {
1646                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1647                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1648                                 nob, rx->rx_nob);
1649                         rc = -EPROTO;
1650                         break;
1651                 }
1652
1653                 if (kiov != NULL)
1654                         lnet_copy_flat2kiov(niov, kiov, offset,
1655                                             IBLND_MSG_SIZE, rxmsg,
1656                                             offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1657                                             mlen);
1658                 else
1659                         lnet_copy_flat2iov(niov, iov, offset,
1660                                            IBLND_MSG_SIZE, rxmsg,
1661                                            offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1662                                            mlen);
1663                 lnet_finalize (ni, lntmsg, 0);
1664                 break;
1665
1666         case IBLND_MSG_PUT_REQ:
1667                 if (mlen == 0) {
1668                         lnet_finalize(ni, lntmsg, 0);
1669                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK, 0,
1670                                                rxmsg->ibm_u.putreq.ibprm_cookie);
1671                         break;
1672                 }
1673
1674                 tx = kiblnd_get_idle_tx(ni);
1675                 if (tx == NULL) {
1676                         CERROR("Can't allocate tx for %s\n",
1677                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1678                         /* Not replying will break the connection */
1679                         rc = -ENOMEM;
1680                         break;
1681                 }
1682
1683                 txmsg = tx->tx_msg;
1684                 if (kiov == NULL)
1685                         rc = kiblnd_setup_rd_iov(ni, tx,
1686                                                  &txmsg->ibm_u.putack.ibpam_rd,
1687                                                  niov, iov, offset, mlen);
1688                 else
1689                         rc = kiblnd_setup_rd_kiov(ni, tx,
1690                                                   &txmsg->ibm_u.putack.ibpam_rd,
1691                                                   niov, kiov, offset, mlen);
1692                 if (rc != 0) {
1693                         CERROR("Can't setup PUT sink for %s: %d\n",
1694                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1695                         kiblnd_tx_done(ni, tx);
1696                         /* tell peer it's over */
1697                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK, rc,
1698                                                rxmsg->ibm_u.putreq.ibprm_cookie);
1699                         break;
1700                 }
1701
1702                 nob = offsetof(kib_putack_msg_t, ibpam_rd.rd_frags[tx->tx_nfrags]);
1703                 txmsg->ibm_u.putack.ibpam_src_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1704                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1705
1706                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1707
1708                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1709                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1710                 kiblnd_queue_tx(tx, conn);
1711
1712                 /* reposted buffer reserved for PUT_DONE */
1713                 post_credit = IBLND_POSTRX_NO_CREDIT;
1714                 break;
1715
1716         case IBLND_MSG_GET_REQ:
1717                 if (lntmsg != NULL) {
1718                         /* Optimized GET; RDMA lntmsg's payload */
1719                         kiblnd_reply(ni, rx, lntmsg);
1720                 } else {
1721                         /* GET didn't match anything */
1722                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1723                                                -ENODATA,
1724                                                rxmsg->ibm_u.get.ibgm_cookie);
1725                 }
1726                 break;
1727         }
1728
1729         kiblnd_post_rx(rx, post_credit);
1730         return rc;
1731 }
1732
1733 int
1734 kiblnd_thread_start (int (*fn)(void *arg), void *arg)
1735 {
1736         long    pid = cfs_kernel_thread (fn, arg, 0);
1737
1738         if (pid < 0)
1739                 return ((int)pid);
1740
1741         cfs_atomic_inc (&kiblnd_data.kib_nthreads);
1742         return (0);
1743 }
1744
1745 void
1746 kiblnd_thread_fini (void)
1747 {
1748         cfs_atomic_dec (&kiblnd_data.kib_nthreads);
1749 }
1750
1751 void
1752 kiblnd_peer_alive (kib_peer_t *peer)
1753 {
1754         /* This is racy, but everyone's only writing cfs_time_current() */
1755         peer->ibp_last_alive = cfs_time_current();
1756         cfs_mb();
1757 }
1758
1759 void
1760 kiblnd_peer_notify (kib_peer_t *peer)
1761 {
1762         int           error = 0;
1763         cfs_time_t    last_alive = 0;
1764         unsigned long flags;
1765
1766         cfs_read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1767
1768         if (cfs_list_empty(&peer->ibp_conns) &&
1769             peer->ibp_accepting == 0 &&
1770             peer->ibp_connecting == 0 &&
1771             peer->ibp_error != 0) {
1772                 error = peer->ibp_error;
1773                 peer->ibp_error = 0;
1774
1775                 last_alive = peer->ibp_last_alive;
1776         }
1777
1778         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1779
1780         if (error != 0)
1781                 lnet_notify(peer->ibp_ni,
1782                             peer->ibp_nid, 0, last_alive);
1783 }
1784
1785 void
1786 kiblnd_close_conn_locked (kib_conn_t *conn, int error)
1787 {
1788         /* This just does the immediate housekeeping.  'error' is zero for a
1789          * normal shutdown which can happen only after the connection has been
1790          * established.  If the connection is established, schedule the
1791          * connection to be finished off by the connd.  Otherwise the connd is
1792          * already dealing with it (either to set it up or tear it down).
1793          * Caller holds kib_global_lock exclusively in irq context */
1794         unsigned long     flags;
1795         kib_peer_t       *peer = conn->ibc_peer;
1796
1797         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1798
1799         if (error != 0 && conn->ibc_comms_error == 0)
1800                 conn->ibc_comms_error = error;
1801
1802         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
1803                 return; /* already being handled  */
1804
1805         if (error == 0 &&
1806             cfs_list_empty(&conn->ibc_tx_queue) &&
1807             cfs_list_empty(&conn->ibc_tx_queue_rsrvd) &&
1808             cfs_list_empty(&conn->ibc_tx_queue_nocred) &&
1809             cfs_list_empty(&conn->ibc_active_txs)) {
1810                 CDEBUG(D_NET, "closing conn to %s\n", 
1811                        libcfs_nid2str(peer->ibp_nid));
1812         } else {
1813                 CDEBUG(D_NETERROR, "Closing conn to %s: error %d%s%s%s%s\n",
1814                        libcfs_nid2str(peer->ibp_nid), error,
1815                        cfs_list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
1816                        cfs_list_empty(&conn->ibc_tx_queue_rsrvd) ? "" : "(sending_rsrvd)",
1817                        cfs_list_empty(&conn->ibc_tx_queue_nocred) ? "" : "(sending_nocred)",
1818                        cfs_list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
1819         }
1820
1821         cfs_list_del(&conn->ibc_list);
1822         /* connd (see below) takes over ibc_list's ref */
1823
1824         if (cfs_list_empty (&peer->ibp_conns) &&    /* no more conns */
1825             kiblnd_peer_active(peer)) {         /* still in peer table */
1826                 kiblnd_unlink_peer_locked(peer);
1827
1828                 /* set/clear error on last conn */
1829                 peer->ibp_error = conn->ibc_comms_error;
1830         }
1831
1832         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
1833
1834         cfs_spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
1835
1836         cfs_list_add_tail (&conn->ibc_list, &kiblnd_data.kib_connd_conns);
1837         cfs_waitq_signal (&kiblnd_data.kib_connd_waitq);
1838
1839         cfs_spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
1840 }
1841
1842 void
1843 kiblnd_close_conn (kib_conn_t *conn, int error)
1844 {
1845         unsigned long flags;
1846
1847         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1848
1849         kiblnd_close_conn_locked(conn, error);
1850
1851         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1852 }
1853
1854 void
1855 kiblnd_handle_early_rxs(kib_conn_t *conn)
1856 {
1857         unsigned long    flags;
1858         kib_rx_t        *rx;
1859
1860         LASSERT (!cfs_in_interrupt());
1861         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1862
1863         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1864         while (!cfs_list_empty(&conn->ibc_early_rxs)) {
1865                 rx = cfs_list_entry(conn->ibc_early_rxs.next,
1866                                 kib_rx_t, rx_list);
1867                 cfs_list_del(&rx->rx_list);
1868                 cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
1869                                             flags);
1870
1871                 kiblnd_handle_rx(rx);
1872
1873                 cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1874         }
1875         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1876 }
1877
1878 void
1879 kiblnd_abort_txs(kib_conn_t *conn, cfs_list_t *txs)
1880 {
1881         CFS_LIST_HEAD       (zombies);
1882         cfs_list_t          *tmp;
1883         cfs_list_t          *nxt;
1884         kib_tx_t            *tx;
1885
1886         cfs_spin_lock(&conn->ibc_lock);
1887
1888         cfs_list_for_each_safe (tmp, nxt, txs) {
1889                 tx = cfs_list_entry (tmp, kib_tx_t, tx_list);
1890
1891                 if (txs == &conn->ibc_active_txs) {
1892                         LASSERT (!tx->tx_queued);
1893                         LASSERT (tx->tx_waiting ||
1894                                  tx->tx_sending != 0);
1895                 } else {
1896                         LASSERT (tx->tx_queued);
1897                 }
1898
1899                 tx->tx_status = -ECONNABORTED;
1900                 tx->tx_waiting = 0;
1901
1902                 if (tx->tx_sending == 0) {
1903                         tx->tx_queued = 0;
1904                         cfs_list_del (&tx->tx_list);
1905                         cfs_list_add (&tx->tx_list, &zombies);
1906                 }
1907         }
1908
1909         cfs_spin_unlock(&conn->ibc_lock);
1910
1911         kiblnd_txlist_done(conn->ibc_peer->ibp_ni,
1912                            &zombies, -ECONNABORTED);
1913 }
1914
1915 void
1916 kiblnd_finalise_conn (kib_conn_t *conn)
1917 {
1918         LASSERT (!cfs_in_interrupt());
1919         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
1920
1921         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
1922
1923         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
1924          * for connections that didn't get as far as being connected, because
1925          * rdma_disconnect() does this for free. */
1926         kiblnd_abort_receives(conn);
1927
1928         /* Complete all tx descs not waiting for sends to complete.
1929          * NB we should be safe from RDMA now that the QP has changed state */
1930
1931         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
1932         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
1933         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
1934         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
1935
1936         kiblnd_handle_early_rxs(conn);
1937 }
1938
1939 void
1940 kiblnd_peer_connect_failed (kib_peer_t *peer, int active, int error)
1941 {
1942         CFS_LIST_HEAD    (zombies);
1943         unsigned long     flags;
1944
1945         LASSERT (error != 0);
1946         LASSERT (!cfs_in_interrupt());
1947
1948         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1949
1950         if (active) {
1951                 LASSERT (peer->ibp_connecting > 0);
1952                 peer->ibp_connecting--;
1953         } else {
1954                 LASSERT (peer->ibp_accepting > 0);
1955                 peer->ibp_accepting--;
1956         }
1957
1958         if (peer->ibp_connecting != 0 ||
1959             peer->ibp_accepting != 0) {
1960                 /* another connection attempt under way... */
1961                 cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
1962                                             flags);
1963                 return;
1964         }
1965
1966         if (cfs_list_empty(&peer->ibp_conns)) {
1967                 /* Take peer's blocked transmits to complete with error */
1968                 cfs_list_add(&zombies, &peer->ibp_tx_queue);
1969                 cfs_list_del_init(&peer->ibp_tx_queue);
1970
1971                 if (kiblnd_peer_active(peer))
1972                         kiblnd_unlink_peer_locked(peer);
1973
1974                 peer->ibp_error = error;
1975         } else {
1976                 /* Can't have blocked transmits if there are connections */
1977                 LASSERT (cfs_list_empty(&peer->ibp_tx_queue));
1978         }
1979
1980         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1981
1982         kiblnd_peer_notify(peer);
1983
1984         if (cfs_list_empty (&zombies))
1985                 return;
1986
1987         CDEBUG (D_NETERROR, "Deleting messages for %s: connection failed\n",
1988                 libcfs_nid2str(peer->ibp_nid));
1989
1990         kiblnd_txlist_done(peer->ibp_ni, &zombies, -EHOSTUNREACH);
1991 }
1992
1993 void
1994 kiblnd_connreq_done(kib_conn_t *conn, int status)
1995 {
1996         kib_peer_t        *peer = conn->ibc_peer;
1997         kib_tx_t          *tx;
1998         cfs_list_t         txs;
1999         unsigned long      flags;
2000         int                active;
2001
2002         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2003
2004         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
2005                libcfs_nid2str(peer->ibp_nid), active,
2006                conn->ibc_version, status);
2007
2008         LASSERT (!cfs_in_interrupt());
2009         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2010                   peer->ibp_connecting > 0) ||
2011                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2012                   peer->ibp_accepting > 0));
2013
2014         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2015         conn->ibc_connvars = NULL;
2016
2017         if (status != 0) {
2018                 /* failed to establish connection */
2019                 kiblnd_peer_connect_failed(peer, active, status);
2020                 kiblnd_finalise_conn(conn);
2021                 return;
2022         }
2023
2024         /* connection established */
2025         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2026
2027         conn->ibc_last_send = jiffies;
2028         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2029         kiblnd_peer_alive(peer);
2030
2031         /* Add conn to peer's list and nuke any dangling conns from a different
2032          * peer instance... */
2033         kiblnd_conn_addref(conn);               /* +1 ref for ibc_list */
2034         cfs_list_add(&conn->ibc_list, &peer->ibp_conns);
2035         if (active)
2036                 peer->ibp_connecting--;
2037         else
2038                 peer->ibp_accepting--;
2039
2040         if (peer->ibp_version == 0) {
2041                 peer->ibp_version     = conn->ibc_version;
2042                 peer->ibp_incarnation = conn->ibc_incarnation;
2043         }
2044
2045         if (peer->ibp_version     != conn->ibc_version ||
2046             peer->ibp_incarnation != conn->ibc_incarnation) {
2047                 kiblnd_close_stale_conns_locked(peer, conn->ibc_version,
2048                                                 conn->ibc_incarnation);
2049                 peer->ibp_version     = conn->ibc_version;
2050                 peer->ibp_incarnation = conn->ibc_incarnation;
2051         }
2052
2053         /* grab pending txs while I have the lock */
2054         cfs_list_add(&txs, &peer->ibp_tx_queue);
2055         cfs_list_del_init(&peer->ibp_tx_queue);
2056
2057         if (!kiblnd_peer_active(peer) ||        /* peer has been deleted */
2058             conn->ibc_comms_error != 0) {       /* error has happened already */
2059                 lnet_ni_t *ni = peer->ibp_ni;
2060
2061                 /* start to shut down connection */
2062                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2063                 cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2064                                             flags);
2065
2066                 kiblnd_txlist_done(ni, &txs, -ECONNABORTED);
2067
2068                 return;
2069         }
2070
2071         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2072
2073         /* Schedule blocked txs */
2074         cfs_spin_lock (&conn->ibc_lock);
2075         while (!cfs_list_empty (&txs)) {
2076                 tx = cfs_list_entry (txs.next, kib_tx_t, tx_list);
2077                 cfs_list_del(&tx->tx_list);
2078
2079                 kiblnd_queue_tx_locked(tx, conn);
2080         }
2081         cfs_spin_unlock (&conn->ibc_lock);
2082
2083         kiblnd_check_sends(conn);
2084
2085         /* schedule blocked rxs */
2086         kiblnd_handle_early_rxs(conn);
2087 }
2088
2089 void
2090 kiblnd_reject(struct rdma_cm_id *cmid, kib_rej_t *rej)
2091 {
2092         int          rc;
2093
2094         rc = rdma_reject(cmid, rej, sizeof(*rej));
2095
2096         if (rc != 0)
2097                 CWARN("Error %d sending reject\n", rc);
2098 }
2099
2100 int
2101 kiblnd_passive_connect (struct rdma_cm_id *cmid, void *priv, int priv_nob)
2102 {
2103         cfs_rwlock_t          *g_lock = &kiblnd_data.kib_global_lock;
2104         kib_msg_t             *reqmsg = priv;
2105         kib_msg_t             *ackmsg;
2106         kib_dev_t             *ibdev;
2107         kib_peer_t            *peer;
2108         kib_peer_t            *peer2;
2109         kib_conn_t            *conn;
2110         lnet_ni_t             *ni  = NULL;
2111         kib_net_t             *net = NULL;
2112         lnet_nid_t             nid;
2113         struct rdma_conn_param cp;
2114         kib_rej_t              rej;
2115         int                    version = IBLND_MSG_VERSION;
2116         unsigned long          flags;
2117         int                    rc;
2118
2119         LASSERT (!cfs_in_interrupt());
2120
2121         /* cmid inherits 'context' from the corresponding listener id */
2122         ibdev = (kib_dev_t *)cmid->context;
2123         LASSERT (ibdev != NULL);
2124
2125         memset(&rej, 0, sizeof(rej));
2126         rej.ibr_magic                = IBLND_MSG_MAGIC;
2127         rej.ibr_why                  = IBLND_REJECT_FATAL;
2128         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2129
2130         if (priv_nob < offsetof(kib_msg_t, ibm_type)) {
2131                 CERROR("Short connection request\n");
2132                 goto failed;
2133         }
2134
2135         /* Future protocol version compatibility support!  If the
2136          * o2iblnd-specific protocol changes, or when LNET unifies
2137          * protocols over all LNDs, the initial connection will
2138          * negotiate a protocol version.  I trap this here to avoid
2139          * console errors; the reject tells the peer which protocol I
2140          * speak. */
2141         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2142             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2143                 goto failed;
2144         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2145             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2146             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2147                 goto failed;
2148         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2149             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2150             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2151                 goto failed;
2152
2153         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2154         if (rc != 0) {
2155                 CERROR("Can't parse connection request: %d\n", rc);
2156                 goto failed;
2157         }
2158
2159         nid = reqmsg->ibm_srcnid;
2160         ni  = lnet_net2ni(LNET_NIDNET(reqmsg->ibm_dstnid));
2161
2162         if (ni != NULL) {
2163                 net = (kib_net_t *)ni->ni_data;
2164                 rej.ibr_incarnation = net->ibn_incarnation;
2165         }
2166
2167         if (ni == NULL ||                         /* no matching net */
2168             ni->ni_nid != reqmsg->ibm_dstnid ||   /* right NET, wrong NID! */
2169             net->ibn_dev != ibdev) {              /* wrong device */
2170                 CERROR("Can't accept %s on %s (%s:%d:%u.%u.%u.%u): "
2171                        "bad dst nid %s\n", libcfs_nid2str(nid),
2172                        ni == NULL ? "NA" : libcfs_nid2str(ni->ni_nid),
2173                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2174                        HIPQUAD(ibdev->ibd_ifip),
2175                        libcfs_nid2str(reqmsg->ibm_dstnid));
2176
2177                 goto failed;
2178         }
2179
2180        /* check time stamp as soon as possible */
2181         if (reqmsg->ibm_dststamp != 0 &&
2182             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2183                 CWARN("Stale connection request\n");
2184                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2185                 goto failed;
2186         }
2187
2188         /* I can accept peer's version */
2189         version = reqmsg->ibm_version;
2190
2191         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2192                 CERROR("Unexpected connreq msg type: %x from %s\n",
2193                        reqmsg->ibm_type, libcfs_nid2str(nid));
2194                 goto failed;
2195         }
2196
2197         if (reqmsg->ibm_u.connparams.ibcp_queue_depth !=
2198             IBLND_MSG_QUEUE_SIZE(version)) {
2199                 CERROR("Can't accept %s: incompatible queue depth %d (%d wanted)\n",
2200                        libcfs_nid2str(nid), reqmsg->ibm_u.connparams.ibcp_queue_depth,
2201                        IBLND_MSG_QUEUE_SIZE(version));
2202
2203                 if (version == IBLND_MSG_VERSION)
2204                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2205
2206                 goto failed;
2207         }
2208
2209         if (reqmsg->ibm_u.connparams.ibcp_max_frags !=
2210             IBLND_RDMA_FRAGS(version)) {
2211                 CERROR("Can't accept %s(version %x): "
2212                        "incompatible max_frags %d (%d wanted)\n",
2213                        libcfs_nid2str(nid), version,
2214                        reqmsg->ibm_u.connparams.ibcp_max_frags,
2215                        IBLND_RDMA_FRAGS(version));
2216
2217                 if (version == IBLND_MSG_VERSION)
2218                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2219
2220                 goto failed;
2221
2222         }
2223
2224         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2225                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2226                        libcfs_nid2str(nid),
2227                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2228                        IBLND_MSG_SIZE);
2229                 goto failed;
2230         }
2231
2232         /* assume 'nid' is a new peer; create  */
2233         rc = kiblnd_create_peer(ni, &peer, nid);
2234         if (rc != 0) {
2235                 CERROR("Can't create peer for %s\n", libcfs_nid2str(nid));
2236                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2237                 goto failed;
2238         }
2239
2240         cfs_write_lock_irqsave(g_lock, flags);
2241
2242         peer2 = kiblnd_find_peer_locked(nid);
2243         if (peer2 != NULL) {
2244                 if (peer2->ibp_version == 0) {
2245                         peer2->ibp_version     = version;
2246                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2247                 }
2248
2249                 /* not the guy I've talked with */
2250                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2251                     peer2->ibp_version     != version) {
2252                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2253                         cfs_write_unlock_irqrestore(g_lock, flags);
2254
2255                         CWARN("Conn stale %s [old ver: %x, new ver: %x]\n",
2256                               libcfs_nid2str(nid), peer2->ibp_version, version);
2257
2258                         kiblnd_peer_decref(peer);
2259                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2260                         goto failed;
2261                 }
2262
2263                 /* tie-break connection race in favour of the higher NID */
2264                 if (peer2->ibp_connecting != 0 &&
2265                     nid < ni->ni_nid) {
2266                         cfs_write_unlock_irqrestore(g_lock, flags);
2267
2268                         CWARN("Conn race %s\n", libcfs_nid2str(peer2->ibp_nid));
2269
2270                         kiblnd_peer_decref(peer);
2271                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2272                         goto failed;
2273                 }
2274
2275                 peer2->ibp_accepting++;
2276                 kiblnd_peer_addref(peer2);
2277
2278                 cfs_write_unlock_irqrestore(g_lock, flags);
2279                 kiblnd_peer_decref(peer);
2280                 peer = peer2;
2281         } else {
2282                 /* Brand new peer */
2283                 LASSERT (peer->ibp_accepting == 0);
2284                 LASSERT (peer->ibp_version == 0 &&
2285                          peer->ibp_incarnation == 0);
2286
2287                 peer->ibp_accepting   = 1;
2288                 peer->ibp_version     = version;
2289                 peer->ibp_incarnation = reqmsg->ibm_srcstamp;
2290
2291                 /* I have a ref on ni that prevents it being shutdown */
2292                 LASSERT (net->ibn_shutdown == 0);
2293
2294                 kiblnd_peer_addref(peer);
2295                 cfs_list_add_tail(&peer->ibp_list, kiblnd_nid2peerlist(nid));
2296
2297                 cfs_write_unlock_irqrestore(g_lock, flags);
2298         }
2299
2300         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_PASSIVE_WAIT, version);
2301         if (conn == NULL) {
2302                 kiblnd_peer_connect_failed(peer, 0, -ENOMEM);
2303                 kiblnd_peer_decref(peer);
2304                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2305                 goto failed;
2306         }
2307
2308         /* conn now "owns" cmid, so I return success from here on to ensure the
2309          * CM callback doesn't destroy cmid. */
2310
2311         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2312         conn->ibc_credits          = IBLND_MSG_QUEUE_SIZE(version);
2313         conn->ibc_reserved_credits = IBLND_MSG_QUEUE_SIZE(version);
2314         LASSERT (conn->ibc_credits + conn->ibc_reserved_credits + IBLND_OOB_MSGS(version)
2315                  <= IBLND_RX_MSGS(version));
2316
2317         ackmsg = &conn->ibc_connvars->cv_msg;
2318         memset(ackmsg, 0, sizeof(*ackmsg));
2319
2320         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2321                         sizeof(ackmsg->ibm_u.connparams));
2322         ackmsg->ibm_u.connparams.ibcp_queue_depth  = IBLND_MSG_QUEUE_SIZE(version);
2323         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2324         ackmsg->ibm_u.connparams.ibcp_max_frags    = IBLND_RDMA_FRAGS(version);
2325
2326         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2327
2328         memset(&cp, 0, sizeof(cp));
2329         cp.private_data        = ackmsg;
2330         cp.private_data_len    = ackmsg->ibm_nob;
2331         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2332         cp.initiator_depth     = 0;
2333         cp.flow_control        = 1;
2334         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2335         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2336
2337         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2338
2339         rc = rdma_accept(cmid, &cp);
2340         if (rc != 0) {
2341                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2342                 rej.ibr_version = version;
2343                 rej.ibr_why     = IBLND_REJECT_FATAL;
2344
2345                 kiblnd_reject(cmid, &rej);
2346                 kiblnd_connreq_done(conn, rc);
2347                 kiblnd_conn_decref(conn);
2348         }
2349
2350         lnet_ni_decref(ni);
2351         return 0;
2352
2353  failed:
2354         if (ni != NULL)
2355                 lnet_ni_decref(ni);
2356
2357         rej.ibr_version = version;
2358         rej.ibr_cp.ibcp_queue_depth = IBLND_MSG_QUEUE_SIZE(version);
2359         rej.ibr_cp.ibcp_max_frags   = IBLND_RDMA_FRAGS(version);
2360         kiblnd_reject(cmid, &rej);
2361
2362         return -ECONNREFUSED;
2363 }
2364
2365 void
2366 kiblnd_reconnect (kib_conn_t *conn, int version,
2367                   __u64 incarnation, int why, kib_connparams_t *cp)
2368 {
2369         kib_peer_t    *peer = conn->ibc_peer;
2370         char          *reason;
2371         int            retry = 0;
2372         unsigned long  flags;
2373
2374         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2375         LASSERT (peer->ibp_connecting > 0);     /* 'conn' at least */
2376
2377         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2378
2379         /* retry connection if it's still needed and no other connection
2380          * attempts (active or passive) are in progress
2381          * NB: reconnect is still needed even when ibp_tx_queue is
2382          * empty if ibp_version != version because reconnect may be
2383          * initiated by kiblnd_query() */
2384         if ((!cfs_list_empty(&peer->ibp_tx_queue) ||
2385              peer->ibp_version != version) &&
2386             peer->ibp_connecting == 1 &&
2387             peer->ibp_accepting == 0) {
2388                 retry = 1;
2389                 peer->ibp_connecting++;
2390
2391                 peer->ibp_version     = version;
2392                 peer->ibp_incarnation = incarnation;
2393         }
2394
2395         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2396
2397         if (!retry)
2398                 return;
2399
2400         switch (why) {
2401         default:
2402                 reason = "Unknown";
2403                 break;
2404
2405         case IBLND_REJECT_CONN_STALE:
2406                 reason = "stale";
2407                 break;
2408
2409         case IBLND_REJECT_CONN_RACE:
2410                 reason = "conn race";
2411                 break;
2412
2413         case IBLND_REJECT_CONN_UNCOMPAT:
2414                 reason = "version negotiation";
2415                 break;
2416         }
2417
2418         CDEBUG(D_NETERROR, "%s: retrying (%s), %x, %x, "
2419                            "queue_dep: %d, max_frag: %d, msg_size: %d\n",
2420                libcfs_nid2str(peer->ibp_nid),
2421                reason, IBLND_MSG_VERSION, version,
2422                cp != NULL ? cp->ibcp_queue_depth : IBLND_MSG_QUEUE_SIZE(version),
2423                cp != NULL ? cp->ibcp_max_frags   : IBLND_RDMA_FRAGS(version),
2424                cp != NULL ? cp->ibcp_max_msg_size: IBLND_MSG_SIZE);
2425
2426         kiblnd_connect_peer(peer);
2427 }
2428
2429 void
2430 kiblnd_rejected (kib_conn_t *conn, int reason, void *priv, int priv_nob)
2431 {
2432         kib_peer_t    *peer = conn->ibc_peer;
2433
2434         LASSERT (!cfs_in_interrupt());
2435         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2436
2437         switch (reason) {
2438         case IB_CM_REJ_STALE_CONN:
2439                 kiblnd_reconnect(conn, IBLND_MSG_VERSION, 0,
2440                                  IBLND_REJECT_CONN_STALE, NULL);
2441                 break;
2442
2443         case IB_CM_REJ_INVALID_SERVICE_ID:
2444                 CDEBUG(D_NETERROR, "%s rejected: no listener at %d\n",
2445                        libcfs_nid2str(peer->ibp_nid),
2446                        *kiblnd_tunables.kib_service);
2447                 break;
2448
2449         case IB_CM_REJ_CONSUMER_DEFINED:
2450                 if (priv_nob >= offsetof(kib_rej_t, ibr_padding)) {
2451                         kib_rej_t        *rej         = priv;
2452                         kib_connparams_t *cp          = NULL;
2453                         int               flip        = 0;
2454                         __u64             incarnation = -1;
2455
2456                         /* NB. default incarnation is -1 because:
2457                          * a) V1 will ignore dst incarnation in connreq.
2458                          * b) V2 will provide incarnation while rejecting me,
2459                          *    -1 will be overwrote.
2460                          *
2461                          * if I try to connect to a V1 peer with V2 protocol,
2462                          * it rejected me then upgrade to V2, I have no idea
2463                          * about the upgrading and try to reconnect with V1,
2464                          * in this case upgraded V2 can find out I'm trying to
2465                          * talk to the old guy and reject me(incarnation is -1). 
2466                          */
2467
2468                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2469                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2470                                 __swab32s(&rej->ibr_magic);
2471                                 __swab16s(&rej->ibr_version);
2472                                 flip = 1;
2473                         }
2474
2475                         if (priv_nob >= sizeof(kib_rej_t) &&
2476                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2477                                 /* priv_nob is always 148 in current version
2478                                  * of OFED, so we still need to check version.
2479                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE) */
2480                                 cp = &rej->ibr_cp;
2481
2482                                 if (flip) {
2483                                         __swab64s(&rej->ibr_incarnation);
2484                                         __swab16s(&cp->ibcp_queue_depth);
2485                                         __swab16s(&cp->ibcp_max_frags);
2486                                         __swab32s(&cp->ibcp_max_msg_size);
2487                                 }
2488
2489                                 incarnation = rej->ibr_incarnation;
2490                         }
2491
2492                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2493                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2494                                 CERROR("%s rejected: consumer defined fatal error\n",
2495                                        libcfs_nid2str(peer->ibp_nid));
2496                                 break;
2497                         }
2498
2499                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2500                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2501                                 CERROR("%s rejected: o2iblnd version %x error\n",
2502                                        libcfs_nid2str(peer->ibp_nid),
2503                                        rej->ibr_version);
2504                                 break;
2505                         }
2506
2507                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2508                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2509                                 CDEBUG(D_NET, "rejected by old version peer %s: %x\n",
2510                                        libcfs_nid2str(peer->ibp_nid), rej->ibr_version);
2511
2512                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2513                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2514                         }
2515
2516                         switch (rej->ibr_why) {
2517                         case IBLND_REJECT_CONN_RACE:
2518                         case IBLND_REJECT_CONN_STALE:
2519                         case IBLND_REJECT_CONN_UNCOMPAT:
2520                                 kiblnd_reconnect(conn, rej->ibr_version,
2521                                                  incarnation, rej->ibr_why, cp);
2522                                 break;
2523
2524                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2525                                 CERROR("%s rejected: incompatible message queue depth %d, %d\n",
2526                                        libcfs_nid2str(peer->ibp_nid), cp->ibcp_queue_depth,
2527                                        IBLND_MSG_QUEUE_SIZE(conn->ibc_version));
2528                                 break;
2529
2530                         case IBLND_REJECT_RDMA_FRAGS:
2531                                 CERROR("%s rejected: incompatible # of RDMA fragments %d, %d\n",
2532                                        libcfs_nid2str(peer->ibp_nid), cp->ibcp_max_frags,
2533                                        IBLND_RDMA_FRAGS(conn->ibc_version));
2534                                 break;
2535
2536                         case IBLND_REJECT_NO_RESOURCES:
2537                                 CERROR("%s rejected: o2iblnd no resources\n",
2538                                        libcfs_nid2str(peer->ibp_nid));
2539                                 break;
2540
2541                         case IBLND_REJECT_FATAL:
2542                                 CERROR("%s rejected: o2iblnd fatal error\n",
2543                                        libcfs_nid2str(peer->ibp_nid));
2544                                 break;
2545
2546                         default:
2547                                 CERROR("%s rejected: o2iblnd reason %d\n",
2548                                        libcfs_nid2str(peer->ibp_nid),
2549                                        rej->ibr_why);
2550                                 break;
2551                         }
2552                         break;
2553                 }
2554                 /* fall through */
2555         default:
2556                 CDEBUG(D_NETERROR, "%s rejected: reason %d, size %d\n",
2557                        libcfs_nid2str(peer->ibp_nid), reason, priv_nob);
2558                 break;
2559         }
2560
2561         kiblnd_connreq_done(conn, -ECONNREFUSED);
2562 }
2563
2564 void
2565 kiblnd_check_connreply (kib_conn_t *conn, void *priv, int priv_nob)
2566 {
2567         kib_peer_t    *peer = conn->ibc_peer;
2568         lnet_ni_t     *ni   = peer->ibp_ni;
2569         kib_net_t     *net  = ni->ni_data;
2570         kib_msg_t     *msg  = priv;
2571         int            ver  = conn->ibc_version;
2572         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
2573         unsigned long  flags;
2574
2575         LASSERT (net != NULL);
2576
2577         if (rc != 0) {
2578                 CERROR("Can't unpack connack from %s: %d\n",
2579                        libcfs_nid2str(peer->ibp_nid), rc);
2580                 goto failed;
2581         }
2582
2583         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2584                 CERROR("Unexpected message %d from %s\n",
2585                        msg->ibm_type, libcfs_nid2str(peer->ibp_nid));
2586                 rc = -EPROTO;
2587                 goto failed;
2588         }
2589
2590         if (ver != msg->ibm_version) {
2591                 CERROR("%s replied version %x is different with "
2592                        "requested version %x\n",
2593                        libcfs_nid2str(peer->ibp_nid), msg->ibm_version, ver);
2594                 rc = -EPROTO;
2595                 goto failed;
2596         }
2597
2598         if (msg->ibm_u.connparams.ibcp_queue_depth !=
2599             IBLND_MSG_QUEUE_SIZE(ver)) {
2600                 CERROR("%s has incompatible queue depth %d(%d wanted)\n",
2601                        libcfs_nid2str(peer->ibp_nid),
2602                        msg->ibm_u.connparams.ibcp_queue_depth,
2603                        IBLND_MSG_QUEUE_SIZE(ver));
2604                 rc = -EPROTO;
2605                 goto failed;
2606         }
2607
2608         if (msg->ibm_u.connparams.ibcp_max_frags !=
2609             IBLND_RDMA_FRAGS(ver)) {
2610                 CERROR("%s has incompatible max_frags %d (%d wanted)\n",
2611                        libcfs_nid2str(peer->ibp_nid),
2612                        msg->ibm_u.connparams.ibcp_max_frags,
2613                        IBLND_RDMA_FRAGS(ver));
2614                 rc = -EPROTO;
2615                 goto failed;
2616         }
2617
2618         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2619                 CERROR("%s max message size %d too big (%d max)\n",
2620                        libcfs_nid2str(peer->ibp_nid),
2621                        msg->ibm_u.connparams.ibcp_max_msg_size,
2622                        IBLND_MSG_SIZE);
2623                 rc = -EPROTO;
2624                 goto failed;
2625         }
2626
2627         cfs_read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2628         if (msg->ibm_dstnid == ni->ni_nid &&
2629             msg->ibm_dststamp == net->ibn_incarnation)
2630                 rc = 0;
2631         else
2632                 rc = -ESTALE;
2633         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2634
2635         if (rc != 0) {
2636                 CERROR("Bad connection reply from %s, rc = %d, "
2637                        "version: %x max_frags: %d\n",
2638                        libcfs_nid2str(peer->ibp_nid), rc,
2639                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
2640                 goto failed;
2641         }
2642
2643         conn->ibc_incarnation      = msg->ibm_srcstamp;
2644         conn->ibc_credits          =
2645         conn->ibc_reserved_credits = IBLND_MSG_QUEUE_SIZE(ver);
2646         LASSERT (conn->ibc_credits + conn->ibc_reserved_credits + IBLND_OOB_MSGS(ver)
2647                  <= IBLND_RX_MSGS(ver));
2648
2649         kiblnd_connreq_done(conn, 0);
2650         return;
2651
2652  failed:
2653         /* NB My QP has already established itself, so I handle anything going
2654          * wrong here by setting ibc_comms_error.
2655          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
2656          * immediately tears it down. */
2657
2658         LASSERT (rc != 0);
2659         conn->ibc_comms_error = rc;
2660         kiblnd_connreq_done(conn, 0);
2661 }
2662
2663 int
2664 kiblnd_active_connect (struct rdma_cm_id *cmid)
2665 {
2666         kib_peer_t              *peer = (kib_peer_t *)cmid->context;
2667         kib_conn_t              *conn;
2668         kib_msg_t               *msg;
2669         struct rdma_conn_param   cp;
2670         int                      version;
2671         __u64                    incarnation;
2672         unsigned long            flags;
2673         int                      rc;
2674
2675         cfs_read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2676
2677         incarnation = peer->ibp_incarnation;
2678         version     = (peer->ibp_version == 0) ? IBLND_MSG_VERSION : peer->ibp_version;
2679
2680         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2681
2682         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_ACTIVE_CONNECT, version);
2683         if (conn == NULL) {
2684                 kiblnd_peer_connect_failed(peer, 1, -ENOMEM);
2685                 kiblnd_peer_decref(peer); /* lose cmid's ref */
2686                 return -ENOMEM;
2687         }
2688
2689         /* conn "owns" cmid now, so I return success from here on to ensure the
2690          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
2691          * on peer */
2692
2693         msg = &conn->ibc_connvars->cv_msg;
2694
2695         memset(msg, 0, sizeof(*msg));
2696         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
2697         msg->ibm_u.connparams.ibcp_queue_depth  = IBLND_MSG_QUEUE_SIZE(version);
2698         msg->ibm_u.connparams.ibcp_max_frags    = IBLND_RDMA_FRAGS(version);
2699         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2700
2701         kiblnd_pack_msg(peer->ibp_ni, msg, version,
2702                         0, peer->ibp_nid, incarnation);
2703
2704         memset(&cp, 0, sizeof(cp));
2705         cp.private_data        = msg;
2706         cp.private_data_len    = msg->ibm_nob;
2707         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2708         cp.initiator_depth     = 0;
2709         cp.flow_control        = 1;
2710         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2711         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2712
2713         LASSERT(cmid->context == (void *)conn);
2714         LASSERT(conn->ibc_cmid == cmid);
2715
2716         rc = rdma_connect(cmid, &cp);
2717         if (rc != 0) {
2718                 CERROR("Can't connect to %s: %d\n",
2719                        libcfs_nid2str(peer->ibp_nid), rc);
2720                 kiblnd_connreq_done(conn, rc);
2721                 kiblnd_conn_decref(conn);
2722         }
2723
2724         return 0;
2725 }
2726
2727 int
2728 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
2729 {
2730         kib_peer_t  *peer;
2731         kib_conn_t  *conn;
2732         int          rc;
2733
2734         switch (event->event) {
2735         default:
2736                 CERROR("Unexpected event: %d, status: %d\n",
2737                        event->event, event->status);
2738                 LBUG();
2739
2740         case RDMA_CM_EVENT_CONNECT_REQUEST:
2741                 /* destroy cmid on failure */
2742                 rc = kiblnd_passive_connect(cmid, 
2743                                             (void *)KIBLND_CONN_PARAM(event),
2744                                             KIBLND_CONN_PARAM_LEN(event));
2745                 CDEBUG(D_NET, "connreq: %d\n", rc);
2746                 return rc;
2747                 
2748         case RDMA_CM_EVENT_ADDR_ERROR:
2749                 peer = (kib_peer_t *)cmid->context;
2750                 CDEBUG(D_NETERROR, "%s: ADDR ERROR %d\n",
2751                        libcfs_nid2str(peer->ibp_nid), event->status);
2752                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2753                 kiblnd_peer_decref(peer);
2754                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
2755
2756         case RDMA_CM_EVENT_ADDR_RESOLVED:
2757                 peer = (kib_peer_t *)cmid->context;
2758
2759                 CDEBUG(D_NET,"%s Addr resolved: %d\n",
2760                        libcfs_nid2str(peer->ibp_nid), event->status);
2761
2762                 if (event->status != 0) {
2763                         CDEBUG(D_NETERROR, "Can't resolve address for %s: %d\n",
2764                                libcfs_nid2str(peer->ibp_nid), event->status);
2765                         rc = event->status;
2766                 } else {
2767                         rc = rdma_resolve_route(
2768                                 cmid, *kiblnd_tunables.kib_timeout * 1000);
2769                         if (rc == 0)
2770                                 return 0;
2771                         /* Can't initiate route resolution */
2772                         CERROR("Can't resolve route for %s: %d\n",
2773                                libcfs_nid2str(peer->ibp_nid), rc);
2774                 }
2775                 kiblnd_peer_connect_failed(peer, 1, rc);
2776                 kiblnd_peer_decref(peer);
2777                 return rc;                      /* rc != 0 destroys cmid */
2778
2779         case RDMA_CM_EVENT_ROUTE_ERROR:
2780                 peer = (kib_peer_t *)cmid->context;
2781                 CDEBUG(D_NETERROR, "%s: ROUTE ERROR %d\n",
2782                        libcfs_nid2str(peer->ibp_nid), event->status);
2783                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2784                 kiblnd_peer_decref(peer);
2785                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
2786
2787         case RDMA_CM_EVENT_ROUTE_RESOLVED:
2788                 peer = (kib_peer_t *)cmid->context;
2789                 CDEBUG(D_NET,"%s Route resolved: %d\n",
2790                        libcfs_nid2str(peer->ibp_nid), event->status);
2791
2792                 if (event->status == 0)
2793                         return kiblnd_active_connect(cmid);
2794
2795                 CDEBUG(D_NETERROR, "Can't resolve route for %s: %d\n",
2796                        libcfs_nid2str(peer->ibp_nid), event->status);
2797                 kiblnd_peer_connect_failed(peer, 1, event->status);
2798                 kiblnd_peer_decref(peer);
2799                 return event->status;           /* rc != 0 destroys cmid */
2800                 
2801         case RDMA_CM_EVENT_UNREACHABLE:
2802                 conn = (kib_conn_t *)cmid->context;
2803                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
2804                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
2805                 CDEBUG(D_NETERROR, "%s: UNREACHABLE %d\n",
2806                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
2807                 kiblnd_connreq_done(conn, -ENETDOWN);
2808                 kiblnd_conn_decref(conn);
2809                 return 0;
2810
2811         case RDMA_CM_EVENT_CONNECT_ERROR:
2812                 conn = (kib_conn_t *)cmid->context;
2813                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
2814                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
2815                 CDEBUG(D_NETERROR, "%s: CONNECT ERROR %d\n",
2816                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
2817                 kiblnd_connreq_done(conn, -ENOTCONN);
2818                 kiblnd_conn_decref(conn);
2819                 return 0;
2820
2821         case RDMA_CM_EVENT_REJECTED:
2822                 conn = (kib_conn_t *)cmid->context;
2823                 switch (conn->ibc_state) {
2824                 default:
2825                         LBUG();
2826
2827                 case IBLND_CONN_PASSIVE_WAIT:
2828                         CERROR ("%s: REJECTED %d\n",
2829                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
2830                                 event->status);
2831                         kiblnd_connreq_done(conn, -ECONNRESET);
2832                         break;
2833
2834                 case IBLND_CONN_ACTIVE_CONNECT:
2835                         kiblnd_rejected(conn, event->status,
2836                                         (void *)KIBLND_CONN_PARAM(event),
2837                                         KIBLND_CONN_PARAM_LEN(event));
2838                         break;
2839                 }
2840                 kiblnd_conn_decref(conn);
2841                 return 0;
2842
2843         case RDMA_CM_EVENT_ESTABLISHED:
2844                 conn = (kib_conn_t *)cmid->context;
2845                 switch (conn->ibc_state) {
2846                 default:
2847                         LBUG();
2848
2849                 case IBLND_CONN_PASSIVE_WAIT:
2850                         CDEBUG(D_NET, "ESTABLISHED (passive): %s\n",
2851                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2852                         kiblnd_connreq_done(conn, 0);
2853                         break;
2854
2855                 case IBLND_CONN_ACTIVE_CONNECT:
2856                         CDEBUG(D_NET, "ESTABLISHED(active): %s\n",
2857                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2858                         kiblnd_check_connreply(conn,
2859                                                (void *)KIBLND_CONN_PARAM(event),
2860                                                KIBLND_CONN_PARAM_LEN(event));
2861                         break;
2862                 }
2863                 /* net keeps its ref on conn! */
2864                 return 0;
2865
2866 #ifdef HAVE_OFED_RDMA_CMEV_TIMEWAIT_EXIT
2867         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
2868                 CDEBUG(D_NET, "Ignore TIMEWAIT_EXIT event\n");
2869                 return 0;
2870 #endif
2871         case RDMA_CM_EVENT_DISCONNECTED:
2872                 conn = (kib_conn_t *)cmid->context;
2873                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
2874                         CERROR("%s DISCONNECTED\n",
2875                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2876                         kiblnd_connreq_done(conn, -ECONNRESET);
2877                 } else {
2878                         kiblnd_close_conn(conn, 0);
2879                 }
2880                 kiblnd_conn_decref(conn);
2881                 cmid->context = NULL;
2882                 return 0;
2883
2884         case RDMA_CM_EVENT_DEVICE_REMOVAL:
2885                 LCONSOLE_ERROR_MSG(0x131,
2886                                    "Received notification of device removal\n"
2887                                    "Please shutdown LNET to allow this to proceed\n");
2888                 /* Can't remove network from underneath LNET for now, so I have
2889                  * to ignore this */
2890                 return 0;
2891
2892 #ifdef HAVE_OFED_RDMA_CMEV_ADDRCHANGE
2893         case RDMA_CM_EVENT_ADDR_CHANGE:
2894                 LCONSOLE_INFO("Physical link changed (eg hca/port)\n");
2895                 return 0;
2896 #endif
2897         }
2898 }
2899
2900 int
2901 kiblnd_check_txs (kib_conn_t *conn, cfs_list_t *txs)
2902 {
2903         kib_tx_t          *tx;
2904         cfs_list_t        *ttmp;
2905         int                timed_out = 0;
2906
2907         cfs_spin_lock(&conn->ibc_lock);
2908
2909         cfs_list_for_each (ttmp, txs) {
2910                 tx = cfs_list_entry (ttmp, kib_tx_t, tx_list);
2911
2912                 if (txs != &conn->ibc_active_txs) {
2913                         LASSERT (tx->tx_queued);
2914                 } else {
2915                         LASSERT (!tx->tx_queued);
2916                         LASSERT (tx->tx_waiting || tx->tx_sending != 0);
2917                 }
2918
2919                 if (cfs_time_aftereq (jiffies, tx->tx_deadline)) {
2920                         timed_out = 1;
2921                         CERROR("Timed out tx: %s, %lu seconds\n",
2922                                kiblnd_queue2str(conn, txs),
2923                                cfs_duration_sec(jiffies - tx->tx_deadline));
2924                         break;
2925                 }
2926         }
2927
2928         cfs_spin_unlock(&conn->ibc_lock);
2929         return timed_out;
2930 }
2931
2932 int
2933 kiblnd_conn_timed_out (kib_conn_t *conn)
2934 {
2935         return  kiblnd_check_txs(conn, &conn->ibc_tx_queue) ||
2936                 kiblnd_check_txs(conn, &conn->ibc_tx_queue_rsrvd) ||
2937                 kiblnd_check_txs(conn, &conn->ibc_tx_queue_nocred) ||
2938                 kiblnd_check_txs(conn, &conn->ibc_active_txs);
2939 }
2940
2941 void
2942 kiblnd_check_conns (int idx)
2943 {
2944         cfs_list_t        *peers = &kiblnd_data.kib_peers[idx];
2945         cfs_list_t        *ptmp;
2946         kib_peer_t        *peer;
2947         kib_conn_t        *conn;
2948         cfs_list_t        *ctmp;
2949         unsigned long      flags;
2950
2951  again:
2952         /* NB. We expect to have a look at all the peers and not find any
2953          * rdmas to time out, so we just use a shared lock while we
2954          * take a look... */
2955         cfs_read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2956
2957         cfs_list_for_each (ptmp, peers) {
2958                 peer = cfs_list_entry (ptmp, kib_peer_t, ibp_list);
2959
2960                 cfs_list_for_each (ctmp, &peer->ibp_conns) {
2961                         conn = cfs_list_entry (ctmp, kib_conn_t, ibc_list);
2962
2963                         LASSERT (conn->ibc_state == IBLND_CONN_ESTABLISHED);
2964
2965                         /* In case we have enough credits to return via a
2966                          * NOOP, but there were no non-blocking tx descs
2967                          * free to do it last time... */
2968                         kiblnd_check_sends(conn);
2969
2970                         if (!kiblnd_conn_timed_out(conn))
2971                                 continue;
2972
2973                         /* Handle timeout by closing the whole connection.  We
2974                          * can only be sure RDMA activity has ceased once the
2975                          * QP has been modified. */
2976
2977                         kiblnd_conn_addref(conn); /* 1 ref for me... */
2978
2979                         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2980                                                    flags);
2981
2982                         CERROR("Timed out RDMA with %s (%lu)\n",
2983                                libcfs_nid2str(peer->ibp_nid),
2984                                cfs_duration_sec(cfs_time_current() -
2985                                                 peer->ibp_last_alive));
2986
2987                         kiblnd_close_conn(conn, -ETIMEDOUT);
2988                         kiblnd_conn_decref(conn); /* ...until here */
2989
2990                         /* start again now I've dropped the lock */
2991                         goto again;
2992                 }
2993         }
2994
2995         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2996 }
2997
2998 void
2999 kiblnd_disconnect_conn (kib_conn_t *conn)
3000 {
3001         LASSERT (!cfs_in_interrupt());
3002         LASSERT (current == kiblnd_data.kib_connd);
3003         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
3004
3005         rdma_disconnect(conn->ibc_cmid);
3006         kiblnd_finalise_conn(conn);
3007
3008         kiblnd_peer_notify(conn->ibc_peer);
3009 }
3010
3011 int
3012 kiblnd_connd (void *arg)
3013 {
3014         cfs_waitlink_t     wait;
3015         unsigned long      flags;
3016         kib_conn_t        *conn;
3017         int                timeout;
3018         int                i;
3019         int                dropped_lock;
3020         int                peer_index = 0;
3021         unsigned long      deadline = jiffies;
3022
3023         cfs_daemonize ("kiblnd_connd");
3024         cfs_block_allsigs ();
3025
3026         cfs_waitlink_init (&wait);
3027         kiblnd_data.kib_connd = current;
3028
3029         cfs_spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
3030
3031         while (!kiblnd_data.kib_shutdown) {
3032
3033                 dropped_lock = 0;
3034
3035                 if (!cfs_list_empty (&kiblnd_data.kib_connd_zombies)) {
3036                         conn = cfs_list_entry(kiblnd_data. \
3037                                               kib_connd_zombies.next,
3038                                               kib_conn_t, ibc_list);
3039                         cfs_list_del(&conn->ibc_list);
3040
3041                         cfs_spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock,
3042                                                    flags);
3043                         dropped_lock = 1;
3044
3045                         kiblnd_destroy_conn(conn);
3046
3047                         cfs_spin_lock_irqsave (&kiblnd_data.kib_connd_lock,
3048                                                flags);
3049                 }
3050
3051                 if (!cfs_list_empty (&kiblnd_data.kib_connd_conns)) {
3052                         conn = cfs_list_entry (kiblnd_data.kib_connd_conns.next,
3053                                                kib_conn_t, ibc_list);
3054                         cfs_list_del(&conn->ibc_list);
3055
3056                         cfs_spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock,
3057                                                     flags);
3058                         dropped_lock = 1;
3059
3060                         kiblnd_disconnect_conn(conn);
3061                         kiblnd_conn_decref(conn);
3062
3063                         cfs_spin_lock_irqsave (&kiblnd_data.kib_connd_lock,
3064                                                flags);
3065                 }
3066
3067                 /* careful with the jiffy wrap... */
3068                 timeout = (int)(deadline - jiffies);
3069                 if (timeout <= 0) {
3070                         const int n = 4;
3071                         const int p = 1;
3072                         int       chunk = kiblnd_data.kib_peer_hash_size;
3073
3074                         cfs_spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
3075                         dropped_lock = 1;
3076
3077                         /* Time to check for RDMA timeouts on a few more
3078                          * peers: I do checks every 'p' seconds on a
3079                          * proportion of the peer table and I need to check
3080                          * every connection 'n' times within a timeout
3081                          * interval, to ensure I detect a timeout on any
3082                          * connection within (n+1)/n times the timeout
3083                          * interval. */
3084
3085                         if (*kiblnd_tunables.kib_timeout > n * p)
3086                                 chunk = (chunk * n * p) /
3087                                         *kiblnd_tunables.kib_timeout;
3088                         if (chunk == 0)
3089                                 chunk = 1;
3090
3091                         for (i = 0; i < chunk; i++) {
3092                                 kiblnd_check_conns(peer_index);
3093                                 peer_index = (peer_index + 1) %
3094                                              kiblnd_data.kib_peer_hash_size;
3095                         }
3096
3097                         deadline += p * CFS_HZ;
3098                         cfs_spin_lock_irqsave(&kiblnd_data.kib_connd_lock,
3099                                               flags);
3100                 }
3101
3102                 if (dropped_lock)