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