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