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