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