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