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