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