Whamcloud - gitweb
replace #if by #ifdef
[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         list_add_tail(&tx->tx_list, &peer->ibp_tx_queue);
1462
1463         kiblnd_peer_addref(peer);
1464         list_add_tail(&peer->ibp_list, kiblnd_nid2peerlist(nid));
1465
1466         write_unlock_irqrestore(g_lock, flags);
1467
1468         kiblnd_connect_peer(peer);
1469         kiblnd_peer_decref(peer);
1470 }
1471
1472 int
1473 kiblnd_send (lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg)
1474 {
1475         lnet_hdr_t       *hdr = &lntmsg->msg_hdr;
1476         int               type = lntmsg->msg_type;
1477         lnet_process_id_t target = lntmsg->msg_target;
1478         int               target_is_router = lntmsg->msg_target_is_router;
1479         int               routing = lntmsg->msg_routing;
1480         unsigned int      payload_niov = lntmsg->msg_niov;
1481         struct iovec     *payload_iov = lntmsg->msg_iov;
1482         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
1483         unsigned int      payload_offset = lntmsg->msg_offset;
1484         unsigned int      payload_nob = lntmsg->msg_len;
1485         kib_msg_t        *ibmsg;
1486         kib_tx_t         *tx;
1487         int               nob;
1488         int               rc;
1489
1490         /* NB 'private' is different depending on what we're sending.... */
1491
1492         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1493                payload_nob, payload_niov, libcfs_id2str(target));
1494
1495         LASSERT (payload_nob == 0 || payload_niov > 0);
1496         LASSERT (payload_niov <= LNET_MAX_IOV);
1497
1498         /* Thread context */
1499         LASSERT (!in_interrupt());
1500         /* payload is either all vaddrs or all pages */
1501         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1502
1503         switch (type) {
1504         default:
1505                 LBUG();
1506                 return (-EIO);
1507
1508         case LNET_MSG_ACK:
1509                 LASSERT (payload_nob == 0);
1510                 break;
1511
1512         case LNET_MSG_GET:
1513                 if (routing || target_is_router)
1514                         break;                  /* send IMMEDIATE */
1515
1516                 /* is the REPLY message too small for RDMA? */
1517                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1518                 if (nob <= IBLND_MSG_SIZE)
1519                         break;                  /* send IMMEDIATE */
1520
1521                 tx = kiblnd_get_idle_tx(ni);
1522                 if (tx == NULL) {
1523                         CERROR("Can allocate txd for GET to %s: \n",
1524                                libcfs_nid2str(target.nid));
1525                         return -ENOMEM;
1526                 }
1527
1528                 ibmsg = tx->tx_msg;
1529                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1530                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1531
1532                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0)
1533                         rc = kiblnd_setup_rd_iov(ni, tx,
1534                                                  &ibmsg->ibm_u.get.ibgm_rd,
1535                                                  lntmsg->msg_md->md_niov,
1536                                                  lntmsg->msg_md->md_iov.iov,
1537                                                  0, lntmsg->msg_md->md_length);
1538                 else
1539                         rc = kiblnd_setup_rd_kiov(ni, tx,
1540                                                   &ibmsg->ibm_u.get.ibgm_rd,
1541                                                   lntmsg->msg_md->md_niov,
1542                                                   lntmsg->msg_md->md_iov.kiov,
1543                                                   0, lntmsg->msg_md->md_length);
1544                 if (rc != 0) {
1545                         CERROR("Can't setup GET sink for %s: %d\n",
1546                                libcfs_nid2str(target.nid), rc);
1547                         kiblnd_tx_done(ni, tx);
1548                         return -EIO;
1549                 }
1550 #if IBLND_MAP_ON_DEMAND
1551                 nob = sizeof(kib_get_msg_t);
1552 #else
1553                 nob = offsetof(kib_get_msg_t, ibgm_rd.rd_frags[tx->tx_nfrags]);
1554 #endif
1555                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1556
1557                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1558                 if (tx->tx_lntmsg[1] == NULL) {
1559                         CERROR("Can't create reply for GET -> %s\n",
1560                                libcfs_nid2str(target.nid));
1561                         kiblnd_tx_done(ni, tx);
1562                         return -EIO;
1563                 }
1564
1565                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1566                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1567                 kiblnd_launch_tx(ni, tx, target.nid);
1568                 return 0;
1569
1570         case LNET_MSG_REPLY:
1571         case LNET_MSG_PUT:
1572                 /* Is the payload small enough not to need RDMA? */
1573                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob]);
1574                 if (nob <= IBLND_MSG_SIZE)
1575                         break;                  /* send IMMEDIATE */
1576
1577                 tx = kiblnd_get_idle_tx(ni);
1578                 if (tx == NULL) {
1579                         CERROR("Can't allocate %s txd for %s\n",
1580                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1581                                libcfs_nid2str(target.nid));
1582                         return -ENOMEM;
1583                 }
1584
1585                 if (payload_kiov == NULL)
1586                         rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1587                                                  payload_niov, payload_iov,
1588                                                  payload_offset, payload_nob);
1589                 else
1590                         rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1591                                                   payload_niov, payload_kiov,
1592                                                   payload_offset, payload_nob);
1593                 if (rc != 0) {
1594                         CERROR("Can't setup PUT src for %s: %d\n",
1595                                libcfs_nid2str(target.nid), rc);
1596                         kiblnd_tx_done(ni, tx);
1597                         return -EIO;
1598                 }
1599
1600                 ibmsg = tx->tx_msg;
1601                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1602                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1603                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ, sizeof(kib_putreq_msg_t));
1604
1605                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1606                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1607                 kiblnd_launch_tx(ni, tx, target.nid);
1608                 return 0;
1609         }
1610
1611         /* send IMMEDIATE */
1612
1613         LASSERT (offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob])
1614                  <= IBLND_MSG_SIZE);
1615
1616         tx = kiblnd_get_idle_tx(ni);
1617         if (tx == NULL) {
1618                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1619                         type, libcfs_nid2str(target.nid));
1620                 return -ENOMEM;
1621         }
1622
1623         ibmsg = tx->tx_msg;
1624         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1625
1626         if (payload_kiov != NULL)
1627                 lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1628                                     offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1629                                     payload_niov, payload_kiov,
1630                                     payload_offset, payload_nob);
1631         else
1632                 lnet_copy_iov2flat(IBLND_MSG_SIZE, ibmsg,
1633                                    offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1634                                    payload_niov, payload_iov,
1635                                    payload_offset, payload_nob);
1636
1637         nob = offsetof(kib_immediate_msg_t, ibim_payload[payload_nob]);
1638         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1639
1640         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1641         kiblnd_launch_tx(ni, tx, target.nid);
1642         return 0;
1643 }
1644
1645 void
1646 kiblnd_reply (lnet_ni_t *ni, kib_rx_t *rx, lnet_msg_t *lntmsg)
1647 {
1648         lnet_process_id_t target = lntmsg->msg_target;
1649         unsigned int      niov = lntmsg->msg_niov;
1650         struct iovec     *iov = lntmsg->msg_iov;
1651         lnet_kiov_t      *kiov = lntmsg->msg_kiov;
1652         unsigned int      offset = lntmsg->msg_offset;
1653         unsigned int      nob = lntmsg->msg_len;
1654         kib_tx_t         *tx;
1655         int               rc;
1656
1657         tx = kiblnd_get_idle_tx(ni);
1658         if (tx == NULL) {
1659                 CERROR("Can't get tx for REPLY to %s\n",
1660                        libcfs_nid2str(target.nid));
1661                 goto failed_0;
1662         }
1663
1664         if (nob == 0)
1665                 rc = 0;
1666         else if (kiov == NULL)
1667                 rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1668                                          niov, iov, offset, nob);
1669         else
1670                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1671                                           niov, kiov, offset, nob);
1672
1673         if (rc != 0) {
1674                 CERROR("Can't setup GET src for %s: %d\n",
1675                        libcfs_nid2str(target.nid), rc);
1676                 goto failed_1;
1677         }
1678
1679         rc = kiblnd_init_rdma(ni, tx, IBLND_MSG_GET_DONE, nob,
1680                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1681                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1682         if (rc < 0) {
1683                 CERROR("Can't setup rdma for GET from %s: %d\n",
1684                        libcfs_nid2str(target.nid), rc);
1685                 goto failed_1;
1686         }
1687         
1688         if (nob == 0) {
1689                 /* No RDMA: local completion may happen now! */
1690                 lnet_finalize(ni, lntmsg, 0);
1691         } else {
1692                 /* RDMA: lnet_finalize(lntmsg) when it
1693                  * completes */
1694                 tx->tx_lntmsg[0] = lntmsg;
1695         }
1696
1697         kiblnd_queue_tx(tx, rx->rx_conn);
1698         return;
1699
1700  failed_1:
1701         kiblnd_tx_done(ni, tx);
1702  failed_0:
1703         lnet_finalize(ni, lntmsg, -EIO);
1704 }
1705
1706 int
1707 kiblnd_recv (lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg, int delayed,
1708              unsigned int niov, struct iovec *iov, lnet_kiov_t *kiov,
1709              unsigned int offset, unsigned int mlen, unsigned int rlen)
1710 {
1711         kib_rx_t    *rx = private;
1712         kib_msg_t   *rxmsg = rx->rx_msg;
1713         kib_conn_t  *conn = rx->rx_conn;
1714         kib_tx_t    *tx;
1715         kib_msg_t   *txmsg;
1716         int          nob;
1717         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1718         int          rc = 0;
1719
1720         LASSERT (mlen <= rlen);
1721         LASSERT (!in_interrupt());
1722         /* Either all pages or all vaddrs */
1723         LASSERT (!(kiov != NULL && iov != NULL));
1724
1725         switch (rxmsg->ibm_type) {
1726         default:
1727                 LBUG();
1728
1729         case IBLND_MSG_IMMEDIATE:
1730                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[rlen]);
1731                 if (nob > rx->rx_nob) {
1732                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1733                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1734                                 nob, rx->rx_nob);
1735                         rc = -EPROTO;
1736                         break;
1737                 }
1738
1739                 if (kiov != NULL)
1740                         lnet_copy_flat2kiov(niov, kiov, offset,
1741                                             IBLND_MSG_SIZE, rxmsg,
1742                                             offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1743                                             mlen);
1744                 else
1745                         lnet_copy_flat2iov(niov, iov, offset,
1746                                            IBLND_MSG_SIZE, rxmsg,
1747                                            offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1748                                            mlen);
1749                 lnet_finalize (ni, lntmsg, 0);
1750                 break;
1751
1752         case IBLND_MSG_PUT_REQ:
1753                 if (mlen == 0) {
1754                         lnet_finalize(ni, lntmsg, 0);
1755                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK, 0,
1756                                                rxmsg->ibm_u.putreq.ibprm_cookie);
1757                         break;
1758                 }
1759
1760                 tx = kiblnd_get_idle_tx(ni);
1761                 if (tx == NULL) {
1762                         CERROR("Can't allocate tx for %s\n",
1763                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1764                         /* Not replying will break the connection */
1765                         rc = -ENOMEM;
1766                         break;
1767                 }
1768
1769                 txmsg = tx->tx_msg;
1770                 if (kiov == NULL)
1771                         rc = kiblnd_setup_rd_iov(ni, tx,
1772                                                  &txmsg->ibm_u.putack.ibpam_rd,
1773                                                  niov, iov, offset, mlen);
1774                 else
1775                         rc = kiblnd_setup_rd_kiov(ni, tx, 
1776                                                   &txmsg->ibm_u.putack.ibpam_rd,
1777                                                   niov, kiov, offset, mlen);
1778                 if (rc != 0) {
1779                         CERROR("Can't setup PUT sink for %s: %d\n",
1780                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1781                         kiblnd_tx_done(ni, tx);
1782                         /* tell peer it's over */
1783                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK, rc,
1784                                                rxmsg->ibm_u.putreq.ibprm_cookie);
1785                         break;
1786                 }
1787
1788                 txmsg->ibm_u.putack.ibpam_src_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1789                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1790 #if IBLND_MAP_ON_DEMAND
1791                 nob = sizeof(kib_putack_msg_t);
1792 #else
1793                 nob = offsetof(kib_putack_msg_t, ibpam_rd.rd_frags[tx->tx_nfrags]);
1794 #endif
1795                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1796
1797                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1798                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1799                 kiblnd_queue_tx(tx, conn);
1800
1801                 /* reposted buffer reserved for PUT_DONE */
1802                 post_credit = IBLND_POSTRX_NO_CREDIT;
1803                 break;
1804
1805         case IBLND_MSG_GET_REQ:
1806                 if (lntmsg != NULL) {
1807                         /* Optimized GET; RDMA lntmsg's payload */
1808                         kiblnd_reply(ni, rx, lntmsg);
1809                 } else {
1810                         /* GET didn't match anything */
1811                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1812                                                -ENODATA,
1813                                                rxmsg->ibm_u.get.ibgm_cookie);
1814                 }
1815                 break;
1816         }
1817
1818         kiblnd_post_rx(rx, post_credit);
1819         return rc;
1820 }
1821
1822 int
1823 kiblnd_thread_start (int (*fn)(void *arg), void *arg)
1824 {
1825         long    pid = kernel_thread (fn, arg, 0);
1826
1827         if (pid < 0)
1828                 return ((int)pid);
1829
1830         atomic_inc (&kiblnd_data.kib_nthreads);
1831         return (0);
1832 }
1833
1834 void
1835 kiblnd_thread_fini (void)
1836 {
1837         atomic_dec (&kiblnd_data.kib_nthreads);
1838 }
1839
1840 void
1841 kiblnd_peer_alive (kib_peer_t *peer)
1842 {
1843         /* This is racy, but everyone's only writing cfs_time_current() */
1844         peer->ibp_last_alive = cfs_time_current();
1845         mb();
1846 }
1847
1848 void
1849 kiblnd_peer_notify (kib_peer_t *peer)
1850 {
1851         time_t        last_alive = 0;
1852         int           error = 0;
1853         unsigned long flags;
1854         
1855         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1856
1857         if (list_empty(&peer->ibp_conns) &&
1858             peer->ibp_accepting == 0 &&
1859             peer->ibp_connecting == 0 &&
1860             peer->ibp_error != 0) {
1861                 error = peer->ibp_error;
1862                 peer->ibp_error = 0;
1863                 
1864                 last_alive = cfs_time_current_sec() -
1865                              cfs_duration_sec(cfs_time_current() -
1866                                               peer->ibp_last_alive);
1867         }
1868         
1869         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1870         
1871         if (error != 0)
1872                 lnet_notify(peer->ibp_ni,
1873                             peer->ibp_nid, 0, last_alive);
1874 }
1875
1876 void
1877 kiblnd_close_conn_locked (kib_conn_t *conn, int error)
1878 {
1879         /* This just does the immediate housekeeping.  'error' is zero for a
1880          * normal shutdown which can happen only after the connection has been
1881          * established.  If the connection is established, schedule the
1882          * connection to be finished off by the connd.  Otherwise the connd is
1883          * already dealing with it (either to set it up or tear it down).
1884          * Caller holds kib_global_lock exclusively in irq context */
1885         unsigned long     flags;
1886         kib_peer_t       *peer = conn->ibc_peer;
1887
1888         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1889
1890         if (error != 0 && conn->ibc_comms_error == 0)
1891                 conn->ibc_comms_error = error;
1892
1893         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
1894                 return; /* already being handled  */
1895
1896         if (error == 0 &&
1897             list_empty(&conn->ibc_tx_queue) &&
1898             list_empty(&conn->ibc_tx_queue_rsrvd) &&
1899             list_empty(&conn->ibc_tx_queue_nocred) &&
1900             list_empty(&conn->ibc_active_txs)) {
1901                 CDEBUG(D_NET, "closing conn to %s\n", 
1902                        libcfs_nid2str(peer->ibp_nid));
1903         } else {
1904                 CDEBUG(D_NETERROR, "Closing conn to %s: error %d%s%s%s%s\n",
1905                        libcfs_nid2str(peer->ibp_nid), error,
1906                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
1907                        list_empty(&conn->ibc_tx_queue_rsrvd) ? "" : "(sending_rsrvd)",
1908                        list_empty(&conn->ibc_tx_queue_nocred) ? "" : "(sending_nocred)",
1909                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
1910         }
1911
1912         list_del (&conn->ibc_list);
1913         /* connd (see below) takes over ibc_list's ref */
1914
1915         if (list_empty (&peer->ibp_conns) &&    /* no more conns */
1916             kiblnd_peer_active(peer)) {         /* still in peer table */
1917                 kiblnd_unlink_peer_locked(peer);
1918
1919                 /* set/clear error on last conn */
1920                 peer->ibp_error = conn->ibc_comms_error;
1921         }
1922
1923         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
1924
1925         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
1926
1927         list_add_tail (&conn->ibc_list, &kiblnd_data.kib_connd_conns);
1928         wake_up (&kiblnd_data.kib_connd_waitq);
1929
1930         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
1931 }
1932
1933 void
1934 kiblnd_close_conn (kib_conn_t *conn, int error)
1935 {
1936         unsigned long flags;
1937
1938         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1939
1940         kiblnd_close_conn_locked(conn, error);
1941
1942         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1943 }
1944
1945 void
1946 kiblnd_handle_early_rxs(kib_conn_t *conn)
1947 {
1948         unsigned long    flags;
1949         kib_rx_t        *rx;
1950
1951         LASSERT (!in_interrupt());
1952         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1953
1954         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1955         while (!list_empty(&conn->ibc_early_rxs)) {
1956                 rx = list_entry(conn->ibc_early_rxs.next,
1957                                 kib_rx_t, rx_list);
1958                 list_del(&rx->rx_list);
1959                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1960
1961                 kiblnd_handle_rx(rx);
1962
1963                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1964         }
1965         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1966 }
1967
1968 void
1969 kiblnd_abort_txs(kib_conn_t *conn, struct list_head *txs)
1970 {
1971         LIST_HEAD           (zombies); 
1972         struct list_head    *tmp;
1973         struct list_head    *nxt;
1974         kib_tx_t            *tx;
1975
1976         spin_lock(&conn->ibc_lock);
1977
1978         list_for_each_safe (tmp, nxt, txs) {
1979                 tx = list_entry (tmp, kib_tx_t, tx_list);
1980
1981                 if (txs == &conn->ibc_active_txs) {
1982                         LASSERT (!tx->tx_queued);
1983                         LASSERT (tx->tx_waiting ||
1984                                  tx->tx_sending != 0);
1985                 } else {
1986                         LASSERT (tx->tx_queued);
1987                 }
1988                 
1989                 tx->tx_status = -ECONNABORTED;
1990                 tx->tx_queued = 0;
1991                 tx->tx_waiting = 0;
1992                 
1993                 if (tx->tx_sending == 0) {
1994                         list_del (&tx->tx_list);
1995                         list_add (&tx->tx_list, &zombies);
1996                 }
1997         }
1998
1999         spin_unlock(&conn->ibc_lock);
2000
2001         kiblnd_txlist_done(conn->ibc_peer->ibp_ni,
2002                            &zombies, -ECONNABORTED);
2003 }
2004
2005 void
2006 kiblnd_finalise_conn (kib_conn_t *conn)
2007 {
2008         LASSERT (!in_interrupt());
2009         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
2010
2011         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
2012
2013         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
2014          * for connections that didn't get as far as being connected, because
2015          * rdma_disconnect() does this for free. */
2016         kiblnd_abort_receives(conn);
2017
2018         /* Complete all tx descs not waiting for sends to complete.
2019          * NB we should be safe from RDMA now that the QP has changed state */
2020
2021         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
2022         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
2023         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
2024         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
2025
2026         kiblnd_handle_early_rxs(conn);
2027 }
2028
2029 void
2030 kiblnd_peer_connect_failed (kib_peer_t *peer, int active, int error)
2031 {
2032         LIST_HEAD        (zombies);
2033         unsigned long     flags;
2034
2035         LASSERT (error != 0);
2036         LASSERT (!in_interrupt());
2037
2038         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2039
2040         if (active) {
2041                 LASSERT (peer->ibp_connecting > 0);
2042                 peer->ibp_connecting--;
2043         } else {
2044                 LASSERT (peer->ibp_accepting > 0);
2045                 peer->ibp_accepting--;
2046         }
2047
2048         if (peer->ibp_connecting != 0 ||
2049             peer->ibp_accepting != 0) {
2050                 /* another connection attempt under way... */
2051                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2052                 return;
2053         }
2054
2055         if (list_empty(&peer->ibp_conns)) {
2056                 /* Take peer's blocked transmits to complete with error */
2057                 list_add(&zombies, &peer->ibp_tx_queue);
2058                 list_del_init(&peer->ibp_tx_queue);
2059
2060                 if (kiblnd_peer_active(peer))
2061                         kiblnd_unlink_peer_locked(peer);
2062
2063                 peer->ibp_error = error;
2064         } else {
2065                 /* Can't have blocked transmits if there are connections */
2066                 LASSERT (list_empty(&peer->ibp_tx_queue));
2067         }
2068
2069         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2070
2071         kiblnd_peer_notify(peer);
2072
2073         if (list_empty (&zombies))
2074                 return;
2075
2076         CDEBUG (D_NETERROR, "Deleting messages for %s: connection failed\n",
2077                 libcfs_nid2str(peer->ibp_nid));
2078
2079         kiblnd_txlist_done(peer->ibp_ni, &zombies, -EHOSTUNREACH);
2080 }
2081
2082 void
2083 kiblnd_connreq_done(kib_conn_t *conn, int status)
2084 {
2085         struct list_head   txs;
2086
2087         kib_peer_t        *peer = conn->ibc_peer;
2088         int                active;
2089         unsigned long      flags;
2090         kib_tx_t          *tx;
2091
2092         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2093
2094         CDEBUG(D_NET,"%s: %d, %d\n", libcfs_nid2str(peer->ibp_nid), 
2095                active, status);
2096
2097         LASSERT (!in_interrupt());
2098         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
2099                   peer->ibp_connecting > 0) ||
2100                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
2101                   peer->ibp_accepting > 0));
2102
2103         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
2104         conn->ibc_connvars = NULL;
2105
2106         if (status != 0) {
2107                 /* failed to establish connection */
2108                 kiblnd_peer_connect_failed(conn->ibc_peer, active, status);
2109                 kiblnd_finalise_conn(conn);
2110                 return;
2111         }
2112
2113         /* connection established */
2114         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2115
2116         conn->ibc_last_send = jiffies;
2117         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2118         kiblnd_peer_alive(peer);
2119
2120         /* Add conn to peer's list and nuke any dangling conns from a different
2121          * peer instance... */
2122         kiblnd_conn_addref(conn);               /* +1 ref for ibc_list */
2123         list_add(&conn->ibc_list, &peer->ibp_conns);
2124         if (active)
2125                 peer->ibp_connecting--;
2126         else
2127                 peer->ibp_accepting--;
2128
2129         kiblnd_close_stale_conns_locked(conn->ibc_peer,
2130                                         conn->ibc_incarnation);
2131
2132         if (!kiblnd_peer_active(peer) ||        /* peer has been deleted */
2133             conn->ibc_comms_error != 0) {       /* error has happened already */
2134
2135                 /* start to shut down connection */
2136                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2137                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2138                 return;
2139         }
2140
2141         /* grab pending txs while I have the lock */
2142         list_add(&txs, &peer->ibp_tx_queue);
2143         list_del_init(&peer->ibp_tx_queue);
2144
2145         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2146
2147         /* Schedule blocked txs */
2148         spin_lock (&conn->ibc_lock);
2149         while (!list_empty (&txs)) {
2150                 tx = list_entry (txs.next, kib_tx_t, tx_list);
2151                 list_del (&tx->tx_list);
2152
2153                 kiblnd_queue_tx_locked(tx, conn);
2154         }
2155         spin_unlock (&conn->ibc_lock);
2156
2157         kiblnd_check_sends(conn);
2158
2159         /* schedule blocked rxs */
2160         kiblnd_handle_early_rxs(conn);
2161 }
2162
2163 void
2164 kiblnd_reject(struct rdma_cm_id *cmid, int why)
2165 {
2166         int          rc;
2167         kib_rej_t    rej = {.ibr_magic   = IBLND_MSG_MAGIC,
2168                             .ibr_version = IBLND_MSG_VERSION,
2169                             .ibr_why     = why};
2170
2171         rc = rdma_reject(cmid, &rej, sizeof(rej));
2172
2173         if (rc != 0)
2174                 CWARN("Error %d sending reject\n", rc);
2175 }
2176
2177 int
2178 kiblnd_passive_connect (struct rdma_cm_id *cmid, void *priv, int priv_nob)
2179 {
2180         kib_msg_t             *ackmsg;
2181         kib_msg_t             *reqmsg = priv;
2182         rwlock_t              *g_lock = &kiblnd_data.kib_global_lock;
2183         struct rdma_conn_param cp;
2184         unsigned long          flags;
2185         lnet_ni_t             *ni = NULL;
2186         kib_dev_t             *ibdev;
2187         kib_peer_t            *peer;
2188         kib_peer_t            *peer2;
2189         kib_conn_t            *conn;
2190         lnet_nid_t             nid;
2191         int                    rc;
2192         int                    rej = IBLND_REJECT_FATAL;
2193
2194         LASSERT (!in_interrupt());
2195
2196         /* cmid inherits 'context' from the corresponding listener id */
2197         ibdev = (kib_dev_t *)cmid->context;
2198         LASSERT (ibdev != NULL);
2199
2200         if (priv_nob < offsetof(kib_msg_t, ibm_type)) {
2201                 CERROR("Short connection request\n");
2202                 goto failed;
2203         }
2204
2205         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2206             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC) ||
2207             (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2208              reqmsg->ibm_version != IBLND_MSG_VERSION) ||
2209             (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2210              reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION))) {
2211                 /* Future protocol version compatibility support!  If the
2212                  * o2iblnd-specific protocol changes, or when LNET unifies
2213                  * protocols over all LNDs, the initial connection will
2214                  * negotiate a protocol version.  I trap this here to avoid
2215                  * console errors; the reject tells the peer which protocol I
2216                  * speak. */
2217                 goto failed;
2218         }
2219
2220         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2221         if (rc != 0) {
2222                 CERROR("Can't parse connection request: %d\n", rc);
2223                 goto failed;
2224         }
2225
2226         nid = reqmsg->ibm_srcnid;
2227
2228         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2229                 CERROR("Unexpected connreq msg type: %x from %s\n",
2230                        reqmsg->ibm_type, libcfs_nid2str(nid));
2231                 goto failed;
2232         }
2233
2234         if (reqmsg->ibm_u.connparams.ibcp_queue_depth != IBLND_MSG_QUEUE_SIZE) {
2235                 CERROR("Can't accept %s: incompatible queue depth %d (%d wanted)\n",
2236                        libcfs_nid2str(nid),
2237                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2238                        IBLND_MSG_QUEUE_SIZE);
2239                 goto failed;
2240         }
2241
2242         if (reqmsg->ibm_u.connparams.ibcp_max_frags != IBLND_MAX_RDMA_FRAGS) {
2243                 CERROR("Can't accept %s: incompatible max_frags %d (%d wanted)\n",
2244                        libcfs_nid2str(nid),
2245                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2246                        IBLND_MSG_QUEUE_SIZE);
2247                 goto failed;
2248         }
2249
2250         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2251                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2252                        libcfs_nid2str(nid),
2253                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2254                        IBLND_MSG_SIZE);
2255                 goto failed;
2256         }
2257
2258         ni = lnet_net2ni(LNET_NIDNET(reqmsg->ibm_dstnid));
2259         if (ni == NULL ||                               /* no matching net */
2260             ni->ni_nid != reqmsg->ibm_dstnid ||   /* right NET, wrong NID! */
2261             ((kib_net_t*)ni->ni_data)->ibn_dev != ibdev) { /* wrong device */
2262                 CERROR("Can't accept %s: bad dst nid %s\n",
2263                        libcfs_nid2str(nid),
2264                        libcfs_nid2str(reqmsg->ibm_dstnid));
2265
2266                 goto failed;
2267         }
2268         
2269         /* assume 'nid' is a new peer; create  */
2270         rc = kiblnd_create_peer(ni, &peer, nid);
2271         if (rc != 0) {
2272                 CERROR("Can't create peer for %s\n", libcfs_nid2str(nid));
2273                 rej = IBLND_REJECT_NO_RESOURCES;
2274                 goto failed;
2275         }
2276
2277         write_lock_irqsave(g_lock, flags);
2278
2279         peer2 = kiblnd_find_peer_locked(nid);
2280         if (peer2 != NULL) {
2281                 /* tie-break connection race in favour of the higher NID */                
2282                 if (peer2->ibp_connecting != 0 &&
2283                     nid < ni->ni_nid) {
2284                         write_unlock_irqrestore(g_lock, flags);
2285
2286                         CWARN("Conn race %s\n",
2287                               libcfs_nid2str(peer2->ibp_nid));
2288
2289                         kiblnd_peer_decref(peer);
2290                         rej = IBLND_REJECT_CONN_RACE;
2291                         goto failed;
2292                 }
2293
2294                 peer2->ibp_accepting++;
2295                 kiblnd_peer_addref(peer2);
2296
2297                 write_unlock_irqrestore(g_lock, flags);
2298                 kiblnd_peer_decref(peer);
2299                 peer = peer2;
2300         } else {
2301                 /* Brand new peer */
2302                 LASSERT (peer->ibp_accepting == 0);
2303                 peer->ibp_accepting = 1;
2304
2305                 kiblnd_peer_addref(peer);
2306                 list_add_tail(&peer->ibp_list, kiblnd_nid2peerlist(nid));
2307
2308                 write_unlock_irqrestore(g_lock, flags);
2309         }
2310
2311         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_PASSIVE_WAIT);
2312         if (conn == NULL) {
2313                 kiblnd_peer_connect_failed(peer, 0, -ENOMEM);
2314                 kiblnd_peer_decref(peer);
2315                 rej = IBLND_REJECT_NO_RESOURCES;
2316                 goto failed;
2317         }
2318
2319         /* conn now "owns" cmid, so I return success from here on to ensure the
2320          * CM callback doesn't destroy cmid. */
2321
2322         conn->ibc_incarnation = reqmsg->ibm_srcstamp;
2323         conn->ibc_credits = IBLND_MSG_QUEUE_SIZE;
2324         conn->ibc_reserved_credits = IBLND_MSG_QUEUE_SIZE;
2325         LASSERT (conn->ibc_credits + conn->ibc_reserved_credits
2326                  <= IBLND_RX_MSGS);
2327
2328         ackmsg = &conn->ibc_connvars->cv_msg;
2329         memset(ackmsg, 0, sizeof(*ackmsg));
2330
2331         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2332                         sizeof(ackmsg->ibm_u.connparams));
2333         ackmsg->ibm_u.connparams.ibcp_queue_depth = IBLND_MSG_QUEUE_SIZE;
2334         ackmsg->ibm_u.connparams.ibcp_max_frags = IBLND_MAX_RDMA_FRAGS;
2335         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2336         kiblnd_pack_msg(ni, ackmsg, 0, nid, reqmsg->ibm_srcstamp);
2337
2338         memset(&cp, 0, sizeof(cp));
2339         cp.private_data        = ackmsg;
2340         cp.private_data_len    = ackmsg->ibm_nob;
2341         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2342         cp.initiator_depth     = 0;
2343         cp.flow_control        = 1;
2344         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2345         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2346
2347         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2348
2349         rc = rdma_accept(cmid, &cp);
2350         if (rc != 0) {
2351                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2352                 kiblnd_reject(cmid, IBLND_REJECT_FATAL);
2353                 kiblnd_connreq_done(conn, rc);
2354                 kiblnd_conn_decref(conn);
2355         }
2356
2357         lnet_ni_decref(ni);
2358         return 0;
2359
2360  failed:
2361         if (ni != NULL)
2362                 lnet_ni_decref(ni);
2363
2364         kiblnd_reject(cmid, rej);
2365         return -ECONNREFUSED;
2366 }
2367
2368 void
2369 kiblnd_reconnect (kib_conn_t *conn, char *why)
2370 {
2371         kib_peer_t    *peer = conn->ibc_peer;
2372         int            retry = 0;
2373         unsigned long  flags;
2374         
2375         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2376         LASSERT (peer->ibp_connecting > 0);     /* 'conn' at least */
2377
2378         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2379
2380         /* retry connection if it's still needed and no other connection
2381          * attempts (active or passive) are in progress */
2382         if (!list_empty(&peer->ibp_tx_queue) &&
2383             peer->ibp_connecting == 1 &&
2384             peer->ibp_accepting == 0) {
2385                 retry = 1;
2386                 peer->ibp_connecting++;
2387         }
2388         
2389         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2390
2391         if (retry) {
2392                 CDEBUG(D_NETERROR, "%s: retrying (%s)\n", 
2393                        libcfs_nid2str(peer->ibp_nid), why);
2394                 kiblnd_connect_peer(peer);
2395         }
2396 }
2397
2398 void
2399 kiblnd_rejected (kib_conn_t *conn, int reason, void *priv, int priv_nob)
2400 {
2401         kib_peer_t    *peer = conn->ibc_peer;
2402
2403         LASSERT (!in_interrupt());
2404         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2405
2406         switch (reason) {
2407         case IB_CM_REJ_STALE_CONN:
2408                 kiblnd_reconnect(conn, "stale");
2409                 break;
2410
2411         case IB_CM_REJ_CONSUMER_DEFINED:
2412                 if (priv_nob >= sizeof(kib_rej_t)) {
2413                         kib_rej_t *rej = priv;
2414
2415                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2416                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2417                                 __swab32s(&rej->ibr_magic);
2418                                 __swab16s(&rej->ibr_version);
2419                         }
2420
2421                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2422                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2423                                 CERROR("%s rejected: consumer defined fatal error\n",
2424                                        libcfs_nid2str(peer->ibp_nid));
2425                                 break;
2426                         }
2427                         
2428                         if (rej->ibr_version != IBLND_MSG_VERSION) {
2429                                 CERROR("%s rejected: o2iblnd version %d error\n",
2430                                        libcfs_nid2str(peer->ibp_nid),
2431                                        rej->ibr_version);
2432                                 break;
2433                         }
2434                         
2435                         switch (rej->ibr_why) {
2436                         case IBLND_REJECT_CONN_RACE:
2437                                 kiblnd_reconnect(conn, "conn race");
2438                                 break;
2439                                 
2440                         case IBLND_REJECT_NO_RESOURCES:
2441                                 CERROR("%s rejected: o2iblnd no resources\n",
2442                                        libcfs_nid2str(peer->ibp_nid));
2443                                 break;
2444                         case IBLND_REJECT_FATAL:
2445                                 CERROR("%s rejected: o2iblnd fatal error\n",
2446                                        libcfs_nid2str(peer->ibp_nid));
2447                                 break;
2448                         default:
2449                                 CERROR("%s rejected: o2iblnd reason %d\n",
2450                                        libcfs_nid2str(peer->ibp_nid),
2451                                        rej->ibr_why);
2452                                 break;
2453                         }
2454                         break;
2455                 }
2456                 /* fall through */
2457         default:
2458                 CDEBUG(D_NETERROR, "%s rejected: reason %d, size %d\n",
2459                        libcfs_nid2str(peer->ibp_nid), reason, priv_nob);
2460                 break;
2461         }
2462
2463         kiblnd_connreq_done(conn, -ECONNREFUSED);
2464 }
2465
2466 void
2467 kiblnd_check_connreply (kib_conn_t *conn, void *priv, int priv_nob)
2468 {
2469         kib_peer_t    *peer = conn->ibc_peer;
2470         lnet_ni_t     *ni = peer->ibp_ni;
2471         kib_net_t     *net = ni->ni_data;
2472         kib_msg_t     *msg = priv;
2473         int            rc = kiblnd_unpack_msg(msg, priv_nob);
2474         unsigned long  flags;
2475
2476         LASSERT (net != NULL);
2477
2478         if (rc != 0) {
2479                 CERROR("Can't unpack connack from %s: %d\n",
2480                        libcfs_nid2str(peer->ibp_nid), rc);
2481                 goto failed;
2482         }
2483
2484         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2485                 CERROR("Unexpected message %d from %s\n",
2486                        msg->ibm_type, libcfs_nid2str(peer->ibp_nid));
2487                 rc = -EPROTO;
2488                 goto failed;
2489         }
2490
2491         if (msg->ibm_u.connparams.ibcp_queue_depth != IBLND_MSG_QUEUE_SIZE) {
2492                 CERROR("%s has incompatible queue depth %d(%d wanted)\n",
2493                        libcfs_nid2str(peer->ibp_nid),
2494                        msg->ibm_u.connparams.ibcp_queue_depth,
2495                        IBLND_MSG_QUEUE_SIZE);
2496                 rc = -EPROTO;
2497                 goto failed;
2498         }
2499
2500         if (msg->ibm_u.connparams.ibcp_max_frags != IBLND_MAX_RDMA_FRAGS) {
2501                 CERROR("%s has incompatible max_frags %d (%d wanted)\n",
2502                        libcfs_nid2str(peer->ibp_nid),
2503                        msg->ibm_u.connparams.ibcp_queue_depth,
2504                        IBLND_MSG_QUEUE_SIZE);
2505                 rc = -EPROTO;
2506                 goto failed;
2507         }
2508
2509         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2510                 CERROR("%s max message size %d too big (%d max)\n",
2511                        libcfs_nid2str(peer->ibp_nid),
2512                        msg->ibm_u.connparams.ibcp_max_msg_size,
2513                        IBLND_MSG_SIZE);
2514                 rc = -EPROTO;
2515                 goto failed;
2516         }
2517
2518         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2519         if (msg->ibm_dstnid == ni->ni_nid &&
2520             msg->ibm_dststamp == net->ibn_incarnation)
2521                 rc = 0;
2522         else
2523                 rc = -ESTALE;
2524         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2525
2526         if (rc != 0) {
2527                 CERROR("Stale connection reply from %s\n",
2528                        libcfs_nid2str(peer->ibp_nid));
2529                 goto failed;
2530         }
2531
2532         conn->ibc_incarnation = msg->ibm_srcstamp;
2533         conn->ibc_credits = IBLND_MSG_QUEUE_SIZE;
2534         conn->ibc_reserved_credits = IBLND_MSG_QUEUE_SIZE;
2535         LASSERT (conn->ibc_credits + conn->ibc_reserved_credits
2536                  <= IBLND_RX_MSGS);
2537
2538         kiblnd_connreq_done(conn, 0);
2539         return;
2540
2541  failed:
2542         /* NB My QP has already established itself, so I handle anything going
2543          * wrong here by setting ibc_comms_error.
2544          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
2545          * immediately tears it down. */
2546
2547         LASSERT (rc != 0);
2548         conn->ibc_comms_error = rc;
2549         kiblnd_connreq_done(conn, 0);
2550 }
2551
2552 int
2553 kiblnd_active_connect (struct rdma_cm_id *cmid)
2554 {
2555         kib_peer_t              *peer = (kib_peer_t *)cmid->context;
2556         kib_conn_t              *conn;
2557         kib_msg_t               *msg;
2558         struct rdma_conn_param   cp;
2559         int                      rc;
2560
2561         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_ACTIVE_CONNECT);
2562         if (conn == NULL) {
2563                 kiblnd_peer_connect_failed(peer, 1, -ENOMEM);
2564                 kiblnd_peer_decref(peer); /* lose cmid's ref */
2565                 return -ENOMEM;
2566         }
2567
2568         /* conn "owns" cmid now, so I return success from here on to ensure the
2569          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
2570          * on peer */
2571
2572         msg = &conn->ibc_connvars->cv_msg;
2573
2574         memset(msg, 0, sizeof(*msg));
2575         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
2576         msg->ibm_u.connparams.ibcp_queue_depth = IBLND_MSG_QUEUE_SIZE;
2577         msg->ibm_u.connparams.ibcp_max_frags = IBLND_MAX_RDMA_FRAGS;
2578         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2579         kiblnd_pack_msg(peer->ibp_ni, msg, 0, peer->ibp_nid, 0);
2580         
2581         memset(&cp, 0, sizeof(cp));
2582         cp.private_data        = msg;
2583         cp.private_data_len    = msg->ibm_nob;
2584         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2585         cp.initiator_depth     = 0;
2586         cp.flow_control        = 1;
2587         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2588         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2589
2590         LASSERT(cmid->context == (void *)conn);
2591         LASSERT(conn->ibc_cmid == cmid);
2592         
2593         rc = rdma_connect(cmid, &cp);
2594         if (rc != 0) {
2595                 CERROR("Can't connect to %s: %d\n",
2596                        libcfs_nid2str(peer->ibp_nid), rc);
2597                 kiblnd_connreq_done(conn, rc);
2598                 kiblnd_conn_decref(conn);
2599         }
2600
2601         return 0;
2602 }
2603
2604 int
2605 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
2606 {
2607         kib_peer_t  *peer;
2608         kib_conn_t  *conn;
2609         int          rc;
2610
2611         switch (event->event) {
2612         default:
2613                 LBUG();
2614
2615         case RDMA_CM_EVENT_CONNECT_REQUEST:
2616                 /* destroy cmid on failure */
2617                 rc = kiblnd_passive_connect(cmid, 
2618                                             (void *)KIBLND_CONN_PARAM(event),
2619                                             KIBLND_CONN_PARAM_LEN(event));
2620                 CDEBUG(D_NET, "connreq: %d\n", rc);
2621                 return rc;
2622                 
2623         case RDMA_CM_EVENT_ADDR_ERROR:
2624                 peer = (kib_peer_t *)cmid->context;
2625                 CDEBUG(D_NETERROR, "%s: ADDR ERROR %d\n",
2626                        libcfs_nid2str(peer->ibp_nid), event->status);
2627                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2628                 kiblnd_peer_decref(peer);
2629                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
2630
2631         case RDMA_CM_EVENT_ADDR_RESOLVED:
2632                 peer = (kib_peer_t *)cmid->context;
2633
2634                 CDEBUG(D_NET,"%s Addr resolved: %d\n",
2635                        libcfs_nid2str(peer->ibp_nid), event->status);
2636
2637                 if (event->status != 0) {
2638                         CDEBUG(D_NETERROR, "Can't resolve address for %s: %d\n",
2639                                libcfs_nid2str(peer->ibp_nid), event->status);
2640                         rc = event->status;
2641                 } else {
2642                         rc = rdma_resolve_route(
2643                                 cmid, *kiblnd_tunables.kib_timeout * 1000);
2644                         if (rc == 0)
2645                                 return 0;
2646                         /* Can't initiate route resolution */
2647                         CERROR("Can't resolve route for %s: %d\n",
2648                                libcfs_nid2str(peer->ibp_nid), rc);
2649                 }
2650                 kiblnd_peer_connect_failed(peer, 1, rc);
2651                 kiblnd_peer_decref(peer);
2652                 return rc;                      /* rc != 0 destroys cmid */
2653
2654         case RDMA_CM_EVENT_ROUTE_ERROR:
2655                 peer = (kib_peer_t *)cmid->context;
2656                 CDEBUG(D_NETERROR, "%s: ROUTE ERROR %d\n",
2657                        libcfs_nid2str(peer->ibp_nid), event->status);
2658                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2659                 kiblnd_peer_decref(peer);
2660                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
2661
2662         case RDMA_CM_EVENT_ROUTE_RESOLVED:
2663                 peer = (kib_peer_t *)cmid->context;
2664                 CDEBUG(D_NET,"%s Route resolved: %d\n",
2665                        libcfs_nid2str(peer->ibp_nid), event->status);
2666
2667                 if (event->status == 0)
2668                         return kiblnd_active_connect(cmid);
2669
2670                 CDEBUG(D_NETERROR, "Can't resolve route for %s: %d\n",
2671                        libcfs_nid2str(peer->ibp_nid), event->status);
2672                 kiblnd_peer_connect_failed(peer, 1, event->status);
2673                 kiblnd_peer_decref(peer);
2674                 return event->status;           /* rc != 0 destroys cmid */
2675                 
2676         case RDMA_CM_EVENT_UNREACHABLE:
2677                 conn = (kib_conn_t *)cmid->context;
2678                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
2679                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
2680                 CDEBUG(D_NETERROR, "%s: UNREACHABLE %d\n",
2681                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
2682                 kiblnd_connreq_done(conn, -ENETDOWN);
2683                 kiblnd_conn_decref(conn);
2684                 return 0;
2685
2686         case RDMA_CM_EVENT_CONNECT_ERROR:
2687                 conn = (kib_conn_t *)cmid->context;
2688                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
2689                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
2690                 CDEBUG(D_NETERROR, "%s: CONNECT ERROR %d\n",
2691                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
2692                 kiblnd_connreq_done(conn, -ENOTCONN);
2693                 kiblnd_conn_decref(conn);
2694                 return 0;
2695
2696         case RDMA_CM_EVENT_REJECTED:
2697                 conn = (kib_conn_t *)cmid->context;
2698                 switch (conn->ibc_state) {
2699                 default:
2700                         LBUG();
2701
2702                 case IBLND_CONN_PASSIVE_WAIT:
2703                         CERROR ("%s: REJECTED %d\n",
2704                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
2705                                 event->status);
2706                         kiblnd_connreq_done(conn, -ECONNRESET);
2707                         break;
2708
2709                 case IBLND_CONN_ACTIVE_CONNECT:
2710                         kiblnd_rejected(conn, event->status,
2711                                         (void *)KIBLND_CONN_PARAM(event),
2712                                         KIBLND_CONN_PARAM_LEN(event));
2713                         break;
2714                 }
2715                 kiblnd_conn_decref(conn);
2716                 return 0;
2717
2718         case RDMA_CM_EVENT_ESTABLISHED:
2719                 conn = (kib_conn_t *)cmid->context;
2720                 switch (conn->ibc_state) {
2721                 default:
2722                         LBUG();
2723
2724                 case IBLND_CONN_PASSIVE_WAIT:
2725                         CDEBUG(D_NET, "ESTABLISHED (passive): %s\n",
2726                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2727                         kiblnd_connreq_done(conn, 0);
2728                         break;
2729
2730                 case IBLND_CONN_ACTIVE_CONNECT:
2731                         CDEBUG(D_NET, "ESTABLISHED(active): %s\n",
2732                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2733                         kiblnd_check_connreply(conn,
2734                                                (void *)KIBLND_CONN_PARAM(event),
2735                                                KIBLND_CONN_PARAM_LEN(event));
2736                         break;
2737                 }
2738                 /* net keeps its ref on conn! */
2739                 return 0;
2740
2741         case RDMA_CM_EVENT_DISCONNECTED:
2742                 conn = (kib_conn_t *)cmid->context;
2743                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
2744                         CERROR("%s DISCONNECTED\n",
2745                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2746                         kiblnd_connreq_done(conn, -ECONNRESET);
2747                 } else {
2748                         kiblnd_close_conn(conn, 0);
2749                 }
2750                 kiblnd_conn_decref(conn);
2751                 return 0;
2752
2753         case RDMA_CM_EVENT_DEVICE_REMOVAL:
2754                 LCONSOLE_ERROR_MSG(0x131, 
2755                                    "Received notification of device removal\n"
2756                                    "Please shutdown LNET to allow this to proceed\n");
2757                 /* Can't remove network from underneath LNET for now, so I have
2758                  * to ignore this */
2759                 return 0;
2760         }
2761 }
2762
2763 int
2764 kiblnd_check_txs (kib_conn_t *conn, struct list_head *txs)
2765 {
2766         kib_tx_t          *tx;
2767         struct list_head  *ttmp;
2768         int                timed_out = 0;
2769
2770         spin_lock(&conn->ibc_lock);
2771
2772         list_for_each (ttmp, txs) {
2773                 tx = list_entry (ttmp, kib_tx_t, tx_list);
2774
2775                 if (txs != &conn->ibc_active_txs) {
2776                         LASSERT (tx->tx_queued);
2777                 } else {
2778                         LASSERT (!tx->tx_queued);
2779                         LASSERT (tx->tx_waiting || tx->tx_sending != 0);
2780                 }                        
2781
2782                 if (time_after_eq (jiffies, tx->tx_deadline)) {
2783                         timed_out = 1;
2784                         break;
2785                 }
2786         }
2787
2788         spin_unlock(&conn->ibc_lock);
2789         return timed_out;
2790 }
2791
2792 int
2793 kiblnd_conn_timed_out (kib_conn_t *conn)
2794 {
2795         return  kiblnd_check_txs(conn, &conn->ibc_tx_queue) ||
2796                 kiblnd_check_txs(conn, &conn->ibc_tx_queue_rsrvd) ||
2797                 kiblnd_check_txs(conn, &conn->ibc_tx_queue_nocred) ||
2798                 kiblnd_check_txs(conn, &conn->ibc_active_txs);
2799 }
2800
2801 void
2802 kiblnd_check_conns (int idx)
2803 {
2804         struct list_head  *peers = &kiblnd_data.kib_peers[idx];
2805         struct list_head  *ptmp;
2806         kib_peer_t        *peer;
2807         kib_conn_t        *conn;
2808         struct list_head  *ctmp;
2809         unsigned long      flags;
2810
2811  again:
2812         /* NB. We expect to have a look at all the peers and not find any
2813          * rdmas to time out, so we just use a shared lock while we
2814          * take a look... */
2815         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2816
2817         list_for_each (ptmp, peers) {
2818                 peer = list_entry (ptmp, kib_peer_t, ibp_list);
2819
2820                 list_for_each (ctmp, &peer->ibp_conns) {
2821                         conn = list_entry (ctmp, kib_conn_t, ibc_list);
2822
2823                         LASSERT (conn->ibc_state == IBLND_CONN_ESTABLISHED);
2824
2825                         /* In case we have enough credits to return via a
2826                          * NOOP, but there were no non-blocking tx descs
2827                          * free to do it last time... */
2828                         kiblnd_check_sends(conn);
2829
2830                         if (!kiblnd_conn_timed_out(conn))
2831                                 continue;
2832
2833                         /* Handle timeout by closing the whole connection.  We
2834                          * can only be sure RDMA activity has ceased once the
2835                          * QP has been modified. */
2836
2837                         kiblnd_conn_addref(conn); /* 1 ref for me... */
2838
2839                         read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2840                                                flags);
2841
2842                         CERROR("Timed out RDMA with %s\n",
2843                                libcfs_nid2str(peer->ibp_nid));
2844
2845                         kiblnd_close_conn(conn, -ETIMEDOUT);
2846                         kiblnd_conn_decref(conn); /* ...until here */
2847
2848                         /* start again now I've dropped the lock */
2849                         goto again;
2850                 }
2851         }
2852
2853         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2854 }
2855
2856 void
2857 kiblnd_disconnect_conn (kib_conn_t *conn)
2858 {
2859         LASSERT (!in_interrupt());
2860         LASSERT (current == kiblnd_data.kib_connd);
2861         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
2862
2863         rdma_disconnect(conn->ibc_cmid);
2864         kiblnd_finalise_conn(conn);
2865
2866         kiblnd_peer_notify(conn->ibc_peer);
2867 }
2868
2869 int
2870 kiblnd_connd (void *arg)
2871 {
2872         wait_queue_t       wait;
2873         unsigned long      flags;
2874         kib_conn_t        *conn;
2875         int                timeout;
2876         int                i;
2877         int                dropped_lock;
2878         int                peer_index = 0;
2879         unsigned long      deadline = jiffies;
2880
2881         cfs_daemonize ("kiblnd_connd");
2882         cfs_block_allsigs ();
2883
2884         init_waitqueue_entry (&wait, current);
2885         kiblnd_data.kib_connd = current;
2886
2887         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2888
2889         while (!kiblnd_data.kib_shutdown) {
2890
2891                 dropped_lock = 0;
2892
2893                 if (!list_empty (&kiblnd_data.kib_connd_zombies)) {
2894                         conn = list_entry (kiblnd_data.kib_connd_zombies.next,
2895                                            kib_conn_t, ibc_list);
2896                         list_del (&conn->ibc_list);
2897
2898                         spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock, flags);
2899                         dropped_lock = 1;
2900
2901                         kiblnd_destroy_conn(conn);
2902
2903                         spin_lock_irqsave (&kiblnd_data.kib_connd_lock, flags);
2904                 }
2905
2906                 if (!list_empty (&kiblnd_data.kib_connd_conns)) {
2907                         conn = list_entry (kiblnd_data.kib_connd_conns.next,
2908                                            kib_conn_t, ibc_list);
2909                         list_del (&conn->ibc_list);
2910
2911                         spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock, flags);
2912                         dropped_lock = 1;
2913
2914                         kiblnd_disconnect_conn(conn);
2915                         kiblnd_conn_decref(conn);
2916
2917                         spin_lock_irqsave (&kiblnd_data.kib_connd_lock, flags);
2918                 }
2919
2920                 /* careful with the jiffy wrap... */
2921                 timeout = (int)(deadline - jiffies);
2922                 if (timeout <= 0) {
2923                         const int n = 4;
2924                         const int p = 1;
2925                         int       chunk = kiblnd_data.kib_peer_hash_size;
2926
2927                         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
2928                         dropped_lock = 1;
2929
2930                         /* Time to check for RDMA timeouts on a few more
2931                          * peers: I do checks every 'p' seconds on a
2932                          * proportion of the peer table and I need to check
2933                          * every connection 'n' times within a timeout
2934                          * interval, to ensure I detect a timeout on any
2935                          * connection within (n+1)/n times the timeout
2936                          * interval. */
2937
2938                         if (*kiblnd_tunables.kib_timeout > n * p)
2939                                 chunk = (chunk * n * p) /
2940                                         *kiblnd_tunables.kib_timeout;
2941                         if (chunk == 0)
2942                                 chunk = 1;
2943
2944                         for (i = 0; i < chunk; i++) {
2945                                 kiblnd_check_conns(peer_index);
2946                                 peer_index = (peer_index + 1) %
2947                                              kiblnd_data.kib_peer_hash_size;
2948                         }
2949
2950                         deadline += p * HZ;
2951                         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2952                 }
2953
2954                 if (dropped_lock)
2955                         continue;
2956
2957                 /* Nothing to do for 'timeout'  */
2958                 set_current_state (TASK_INTERRUPTIBLE);
2959                 add_wait_queue (&kiblnd_data.kib_connd_waitq, &wait);
2960                 spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock, flags);
2961
2962                 schedule_timeout (timeout);
2963
2964                 set_current_state (TASK_RUNNING);
2965                 remove_wait_queue (&kiblnd_data.kib_connd_waitq, &wait);
2966                 spin_lock_irqsave (&kiblnd_data.kib_connd_lock, flags);
2967         }
2968
2969         spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock, flags);
2970
2971         kiblnd_thread_fini();
2972         return (0);
2973 }
2974
2975 void
2976 kiblnd_qp_event(struct ib_event *event, void *arg)
2977 {
2978         kib_conn_t *conn = arg;
2979
2980         switch (event->event) {
2981         case IB_EVENT_COMM_EST:
2982                 CDEBUG(D_NET, "%s established\n",
2983                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
2984                 return;
2985                 
2986         default:
2987                 CERROR("%s: Async QP event type %d\n",
2988                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
2989                 return;
2990         }
2991 }
2992
2993 void
2994 kiblnd_complete (struct ib_wc *wc)
2995 {
2996         switch (kiblnd_wreqid2type(wc->wr_id)) {
2997         default:
2998                 LBUG();
2999
3000         case IBLND_WID_RDMA:
3001                 /* We only get RDMA completion notification if it fails.  All
3002                  * subsequent work items, including the final SEND will fail
3003                  * too.  However we can't print out any more info about the
3004                  * failing RDMA because 'tx' might be back on the idle list or
3005                  * even reused already if we didn't manage to post all our work
3006                  * items */
3007                 CDEBUG(D_NETERROR, "RDMA (tx: %p) failed: %d\n",
3008                        kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3009                 return;
3010
3011         case IBLND_WID_TX:
3012                 kiblnd_tx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3013                 return;
3014
3015         case IBLND_WID_RX:
3016                 kiblnd_rx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status,
3017                                    wc->byte_len);
3018                 return;
3019         }
3020 }
3021
3022 void
3023 kiblnd_cq_completion (struct ib_cq *cq, void *arg)
3024 {
3025         /* NB I'm not allowed to schedule this conn once its refcount has
3026          * reached 0.  Since fundamentally I'm racing with scheduler threads
3027          * consuming my CQ I could be called after all completions have
3028          * occurred.  But in this case, ibc_nrx == 0 && ibc_nsends_posted == 0
3029          * and this CQ is about to be destroyed so I NOOP. */
3030         kib_conn_t     *conn = (kib_conn_t *)arg;
3031         unsigned long   flags;
3032         
3033         LASSERT (cq == conn->ibc_cq);
3034
3035         spin_lock_irqsave(&kiblnd_data.kib_sched_lock, flags);
3036
3037         conn->ibc_ready = 1;
3038
3039         if (!conn->ibc_scheduled &&
3040             (conn->ibc_nrx > 0 ||
3041              conn->ibc_nsends_posted > 0)) {
3042                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3043                 conn->ibc_scheduled = 1;
3044                 list_add_tail(&conn->ibc_sched_list,
3045                               &kiblnd_data.kib_sched_conns);
3046                 wake_up(&kiblnd_data.kib_sched_waitq);
3047         }
3048
3049         spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock, flags);
3050 }
3051
3052 void
3053 kiblnd_cq_event(struct ib_event *event, void *arg)
3054 {
3055         kib_conn_t *conn = arg;
3056
3057         CERROR("%s: async CQ event type %d\n",
3058                libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3059 }
3060
3061 int
3062 kiblnd_scheduler(void *arg)
3063 {
3064         long            id = (long)arg;
3065         wait_queue_t    wait;
3066         char            name[16];
3067         unsigned long   flags;
3068         kib_conn_t     *conn;
3069         struct ib_wc    wc;
3070         int             rc;
3071         int             did_something;
3072         int             busy_loops = 0;
3073
3074         snprintf(name, sizeof(name), "kiblnd_sd_%02ld", id);
3075         cfs_daemonize(name);
3076         cfs_block_allsigs();
3077
3078         init_waitqueue_entry(&wait, current);
3079
3080         spin_lock_irqsave(&kiblnd_data.kib_sched_lock, flags);
3081
3082         while (!kiblnd_data.kib_shutdown) {
3083                 if (busy_loops++ >= IBLND_RESCHED) {
3084                         spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock,
3085                                                flags);
3086
3087                         our_cond_resched();
3088                         busy_loops = 0;
3089
3090                         spin_lock_irqsave(&kiblnd_data.kib_sched_lock, flags);
3091                 }
3092
3093                 did_something = 0;
3094
3095                 if (!list_empty(&kiblnd_data.kib_sched_conns)) {
3096                         conn = list_entry(kiblnd_data.kib_sched_conns.next,
3097                                           kib_conn_t, ibc_sched_list);
3098                         /* take over kib_sched_conns' ref on conn... */
3099                         LASSERT(conn->ibc_scheduled);
3100                         list_del(&conn->ibc_sched_list);
3101                         conn->ibc_ready = 0;
3102                         
3103                         spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock,
3104                                                flags);
3105
3106                         rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3107                         if (rc == 0) {
3108                                 rc = ib_req_notify_cq(conn->ibc_cq,
3109                                                       IB_CQ_NEXT_COMP);
3110                                 LASSERT (rc >= 0);
3111
3112                                 rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3113                         }
3114
3115                         LASSERT (rc >= 0);
3116
3117                         spin_lock_irqsave(&kiblnd_data.kib_sched_lock,
3118                                           flags);
3119
3120                         if (rc != 0 || conn->ibc_ready) {
3121                                 /* There may be another completion waiting; get
3122                                  * another scheduler to check while I handle
3123                                  * this one... */
3124                                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3125                                 list_add_tail(&conn->ibc_sched_list,
3126                                               &kiblnd_data.kib_sched_conns);
3127                                 wake_up(&kiblnd_data.kib_sched_waitq);
3128                         } else {
3129                                 conn->ibc_scheduled = 0;
3130                         }
3131                         
3132                         if (rc != 0) {
3133                                 spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock,
3134                                                        flags);
3135
3136                                 kiblnd_complete(&wc);
3137
3138                                 spin_lock_irqsave(&kiblnd_data.kib_sched_lock,
3139                                                   flags);
3140                         }
3141
3142                         kiblnd_conn_decref(conn); /* ...drop my ref from above */
3143                         did_something = 1;
3144                 }
3145
3146                 if (did_something)
3147                         continue;
3148
3149                 set_current_state(TASK_INTERRUPTIBLE);
3150                 add_wait_queue_exclusive(&kiblnd_data.kib_sched_waitq, &wait);
3151                 spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock, flags);
3152
3153                 schedule();
3154                 busy_loops = 0;
3155
3156                 remove_wait_queue(&kiblnd_data.kib_sched_waitq, &wait);
3157                 set_current_state(TASK_RUNNING);
3158                 spin_lock_irqsave(&kiblnd_data.kib_sched_lock, flags);
3159         }
3160
3161         spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock, flags);
3162
3163         kiblnd_thread_fini();
3164         return (0);
3165 }