Whamcloud - gitweb
dfe69198cd1222bd35c9bd2f21ec1e93680dd169
[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(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(peer, conn->ibc_incarnation);
2154
2155         /* grab pending txs while I have the lock */
2156         list_add(&txs, &peer->ibp_tx_queue);
2157         list_del_init(&peer->ibp_tx_queue);
2158
2159         if (!kiblnd_peer_active(peer) ||        /* peer has been deleted */
2160             conn->ibc_comms_error != 0) {       /* error has happened already */
2161                 lnet_ni_t *ni = peer->ibp_ni;
2162
2163                 /* start to shut down connection */
2164                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2165                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2166
2167                 kiblnd_txlist_done(ni, &txs, -ECONNABORTED);
2168
2169                 return;
2170         }
2171
2172         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2173
2174         /* Schedule blocked txs */
2175         spin_lock (&conn->ibc_lock);
2176         while (!list_empty (&txs)) {
2177                 tx = list_entry (txs.next, kib_tx_t, tx_list);
2178                 list_del (&tx->tx_list);
2179
2180                 kiblnd_queue_tx_locked(tx, conn);
2181         }
2182         spin_unlock (&conn->ibc_lock);
2183
2184         kiblnd_check_sends(conn);
2185
2186         /* schedule blocked rxs */
2187         kiblnd_handle_early_rxs(conn);
2188 }
2189
2190 void
2191 kiblnd_reject(struct rdma_cm_id *cmid, int why)
2192 {
2193         int          rc;
2194         kib_rej_t    rej = {.ibr_magic   = IBLND_MSG_MAGIC,
2195                             .ibr_version = IBLND_MSG_VERSION,
2196                             .ibr_why     = why};
2197
2198         rc = rdma_reject(cmid, &rej, sizeof(rej));
2199
2200         if (rc != 0)
2201                 CWARN("Error %d sending reject\n", rc);
2202 }
2203
2204 int
2205 kiblnd_passive_connect (struct rdma_cm_id *cmid, void *priv, int priv_nob)
2206 {
2207         kib_msg_t             *ackmsg;
2208         kib_msg_t             *reqmsg = priv;
2209         rwlock_t              *g_lock = &kiblnd_data.kib_global_lock;
2210         struct rdma_conn_param cp;
2211         unsigned long          flags;
2212         lnet_ni_t             *ni = NULL;
2213         kib_dev_t             *ibdev;
2214         kib_peer_t            *peer;
2215         kib_peer_t            *peer2;
2216         kib_conn_t            *conn;
2217         lnet_nid_t             nid;
2218         int                    rc;
2219         int                    rej = IBLND_REJECT_FATAL;
2220
2221         LASSERT (!in_interrupt());
2222
2223         /* cmid inherits 'context' from the corresponding listener id */
2224         ibdev = (kib_dev_t *)cmid->context;
2225         LASSERT (ibdev != NULL);
2226
2227         if (priv_nob < offsetof(kib_msg_t, ibm_type)) {
2228                 CERROR("Short connection request\n");
2229                 goto failed;
2230         }
2231
2232         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2233             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC) ||
2234             (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2235              reqmsg->ibm_version != IBLND_MSG_VERSION) ||
2236             (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2237              reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION))) {
2238                 /* Future protocol version compatibility support!  If the
2239                  * o2iblnd-specific protocol changes, or when LNET unifies
2240                  * protocols over all LNDs, the initial connection will
2241                  * negotiate a protocol version.  I trap this here to avoid
2242                  * console errors; the reject tells the peer which protocol I
2243                  * speak. */
2244                 goto failed;
2245         }
2246
2247         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2248         if (rc != 0) {
2249                 CERROR("Can't parse connection request: %d\n", rc);
2250                 goto failed;
2251         }
2252
2253         nid = reqmsg->ibm_srcnid;
2254
2255         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2256                 CERROR("Unexpected connreq msg type: %x from %s\n",
2257                        reqmsg->ibm_type, libcfs_nid2str(nid));
2258                 goto failed;
2259         }
2260
2261         if (reqmsg->ibm_u.connparams.ibcp_queue_depth != IBLND_MSG_QUEUE_SIZE) {
2262                 CERROR("Can't accept %s: incompatible queue depth %d (%d wanted)\n",
2263                        libcfs_nid2str(nid),
2264                        reqmsg->ibm_u.connparams.ibcp_queue_depth,
2265                        IBLND_MSG_QUEUE_SIZE);
2266                 goto failed;
2267         }
2268
2269         if (reqmsg->ibm_u.connparams.ibcp_max_frags != IBLND_MAX_RDMA_FRAGS) {
2270                 CERROR("Can't accept %s: incompatible max_frags %d (%d wanted)\n",
2271                        libcfs_nid2str(nid),
2272                        reqmsg->ibm_u.connparams.ibcp_max_frags,
2273                        IBLND_MAX_RDMA_FRAGS);
2274                 goto failed;
2275         }
2276
2277         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2278                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2279                        libcfs_nid2str(nid),
2280                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2281                        IBLND_MSG_SIZE);
2282                 goto failed;
2283         }
2284
2285         ni = lnet_net2ni(LNET_NIDNET(reqmsg->ibm_dstnid));
2286         if (ni == NULL ||                               /* no matching net */
2287             ni->ni_nid != reqmsg->ibm_dstnid ||   /* right NET, wrong NID! */
2288             ((kib_net_t*)ni->ni_data)->ibn_dev != ibdev) { /* wrong device */
2289                 CERROR("Can't accept %s: bad dst nid %s\n",
2290                        libcfs_nid2str(nid),
2291                        libcfs_nid2str(reqmsg->ibm_dstnid));
2292
2293                 goto failed;
2294         }
2295         
2296         /* assume 'nid' is a new peer; create  */
2297         rc = kiblnd_create_peer(ni, &peer, nid);
2298         if (rc != 0) {
2299                 CERROR("Can't create peer for %s\n", libcfs_nid2str(nid));
2300                 rej = IBLND_REJECT_NO_RESOURCES;
2301                 goto failed;
2302         }
2303
2304         write_lock_irqsave(g_lock, flags);
2305
2306         peer2 = kiblnd_find_peer_locked(nid);
2307         if (peer2 != NULL) {
2308                 /* tie-break connection race in favour of the higher NID */                
2309                 if (peer2->ibp_connecting != 0 &&
2310                     nid < ni->ni_nid) {
2311                         write_unlock_irqrestore(g_lock, flags);
2312
2313                         CWARN("Conn race %s\n",
2314                               libcfs_nid2str(peer2->ibp_nid));
2315
2316                         kiblnd_peer_decref(peer);
2317                         rej = IBLND_REJECT_CONN_RACE;
2318                         goto failed;
2319                 }
2320
2321                 peer2->ibp_accepting++;
2322                 kiblnd_peer_addref(peer2);
2323
2324                 write_unlock_irqrestore(g_lock, flags);
2325                 kiblnd_peer_decref(peer);
2326                 peer = peer2;
2327         } else {
2328                 /* Brand new peer */
2329                 LASSERT (peer->ibp_accepting == 0);
2330                 peer->ibp_accepting = 1;
2331
2332                 /* I have a ref on ni that prevents it being shutdown */
2333                 LASSERT (((kib_net_t *)ni->ni_data)->ibn_shutdown == 0);
2334
2335                 kiblnd_peer_addref(peer);
2336                 list_add_tail(&peer->ibp_list, kiblnd_nid2peerlist(nid));
2337
2338                 write_unlock_irqrestore(g_lock, flags);
2339         }
2340
2341         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_PASSIVE_WAIT);
2342         if (conn == NULL) {
2343                 kiblnd_peer_connect_failed(peer, 0, -ENOMEM);
2344                 kiblnd_peer_decref(peer);
2345                 rej = IBLND_REJECT_NO_RESOURCES;
2346                 goto failed;
2347         }
2348
2349         /* conn now "owns" cmid, so I return success from here on to ensure the
2350          * CM callback doesn't destroy cmid. */
2351
2352         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2353         conn->ibc_credits          = IBLND_MSG_QUEUE_SIZE;
2354         conn->ibc_reserved_credits = IBLND_MSG_QUEUE_SIZE;
2355         LASSERT (conn->ibc_credits + conn->ibc_reserved_credits
2356                  <= IBLND_RX_MSGS);
2357
2358         ackmsg = &conn->ibc_connvars->cv_msg;
2359         memset(ackmsg, 0, sizeof(*ackmsg));
2360
2361         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2362                         sizeof(ackmsg->ibm_u.connparams));
2363         ackmsg->ibm_u.connparams.ibcp_queue_depth = IBLND_MSG_QUEUE_SIZE;
2364         ackmsg->ibm_u.connparams.ibcp_max_frags = IBLND_MAX_RDMA_FRAGS;
2365         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2366         kiblnd_pack_msg(ni, ackmsg, 0, nid, reqmsg->ibm_srcstamp);
2367
2368         memset(&cp, 0, sizeof(cp));
2369         cp.private_data        = ackmsg;
2370         cp.private_data_len    = ackmsg->ibm_nob;
2371         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2372         cp.initiator_depth     = 0;
2373         cp.flow_control        = 1;
2374         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2375         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2376
2377         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2378
2379         rc = rdma_accept(cmid, &cp);
2380         if (rc != 0) {
2381                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2382                 kiblnd_reject(cmid, IBLND_REJECT_FATAL);
2383                 kiblnd_connreq_done(conn, rc);
2384                 kiblnd_conn_decref(conn);
2385         }
2386
2387         lnet_ni_decref(ni);
2388         return 0;
2389
2390  failed:
2391         if (ni != NULL)
2392                 lnet_ni_decref(ni);
2393
2394         kiblnd_reject(cmid, rej);
2395         return -ECONNREFUSED;
2396 }
2397
2398 void
2399 kiblnd_reconnect (kib_conn_t *conn, char *why)
2400 {
2401         kib_peer_t    *peer = conn->ibc_peer;
2402         int            retry = 0;
2403         unsigned long  flags;
2404         
2405         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2406         LASSERT (peer->ibp_connecting > 0);     /* 'conn' at least */
2407
2408         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2409
2410         /* retry connection if it's still needed and no other connection
2411          * attempts (active or passive) are in progress */
2412         if (!list_empty(&peer->ibp_tx_queue) &&
2413             peer->ibp_connecting == 1 &&
2414             peer->ibp_accepting == 0) {
2415                 retry = 1;
2416                 peer->ibp_connecting++;
2417         }
2418         
2419         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2420
2421         if (retry) {
2422                 CDEBUG(D_NETERROR, "%s: retrying (%s)\n", 
2423                        libcfs_nid2str(peer->ibp_nid), why);
2424                 kiblnd_connect_peer(peer);
2425         }
2426 }
2427
2428 void
2429 kiblnd_rejected (kib_conn_t *conn, int reason, void *priv, int priv_nob)
2430 {
2431         kib_peer_t    *peer = conn->ibc_peer;
2432
2433         LASSERT (!in_interrupt());
2434         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2435
2436         switch (reason) {
2437         case IB_CM_REJ_STALE_CONN:
2438                 kiblnd_reconnect(conn, "stale");
2439                 break;
2440
2441         case IB_CM_REJ_CONSUMER_DEFINED:
2442                 if (priv_nob >= sizeof(kib_rej_t)) {
2443                         kib_rej_t *rej = priv;
2444
2445                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2446                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2447                                 __swab32s(&rej->ibr_magic);
2448                                 __swab16s(&rej->ibr_version);
2449                         }
2450
2451                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2452                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2453                                 CERROR("%s rejected: consumer defined fatal error\n",
2454                                        libcfs_nid2str(peer->ibp_nid));
2455                                 break;
2456                         }
2457                         
2458                         if (rej->ibr_version != IBLND_MSG_VERSION) {
2459                                 CERROR("%s rejected: o2iblnd version %d error\n",
2460                                        libcfs_nid2str(peer->ibp_nid),
2461                                        rej->ibr_version);
2462                                 break;
2463                         }
2464                         
2465                         switch (rej->ibr_why) {
2466                         case IBLND_REJECT_CONN_RACE:
2467                                 kiblnd_reconnect(conn, "conn race");
2468                                 break;
2469                                 
2470                         case IBLND_REJECT_NO_RESOURCES:
2471                                 CERROR("%s rejected: o2iblnd no resources\n",
2472                                        libcfs_nid2str(peer->ibp_nid));
2473                                 break;
2474                         case IBLND_REJECT_FATAL:
2475                                 CERROR("%s rejected: o2iblnd fatal error\n",
2476                                        libcfs_nid2str(peer->ibp_nid));
2477                                 break;
2478                         default:
2479                                 CERROR("%s rejected: o2iblnd reason %d\n",
2480                                        libcfs_nid2str(peer->ibp_nid),
2481                                        rej->ibr_why);
2482                                 break;
2483                         }
2484                         break;
2485                 }
2486                 /* fall through */
2487         default:
2488                 CDEBUG(D_NETERROR, "%s rejected: reason %d, size %d\n",
2489                        libcfs_nid2str(peer->ibp_nid), reason, priv_nob);
2490                 break;
2491         }
2492
2493         kiblnd_connreq_done(conn, -ECONNREFUSED);
2494 }
2495
2496 void
2497 kiblnd_check_connreply (kib_conn_t *conn, void *priv, int priv_nob)
2498 {
2499         kib_peer_t    *peer = conn->ibc_peer;
2500         lnet_ni_t     *ni = peer->ibp_ni;
2501         kib_net_t     *net = ni->ni_data;
2502         kib_msg_t     *msg = priv;
2503         int            rc = kiblnd_unpack_msg(msg, priv_nob);
2504         unsigned long  flags;
2505
2506         LASSERT (net != NULL);
2507
2508         if (rc != 0) {
2509                 CERROR("Can't unpack connack from %s: %d\n",
2510                        libcfs_nid2str(peer->ibp_nid), rc);
2511                 goto failed;
2512         }
2513
2514         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2515                 CERROR("Unexpected message %d from %s\n",
2516                        msg->ibm_type, libcfs_nid2str(peer->ibp_nid));
2517                 rc = -EPROTO;
2518                 goto failed;
2519         }
2520
2521         if (msg->ibm_u.connparams.ibcp_queue_depth != IBLND_MSG_QUEUE_SIZE) {
2522                 CERROR("%s has incompatible queue depth %d(%d wanted)\n",
2523                        libcfs_nid2str(peer->ibp_nid),
2524                        msg->ibm_u.connparams.ibcp_queue_depth,
2525                        IBLND_MSG_QUEUE_SIZE);
2526                 rc = -EPROTO;
2527                 goto failed;
2528         }
2529
2530         if (msg->ibm_u.connparams.ibcp_max_frags != IBLND_MAX_RDMA_FRAGS) {
2531                 CERROR("%s has incompatible max_frags %d (%d wanted)\n",
2532                        libcfs_nid2str(peer->ibp_nid),
2533                        msg->ibm_u.connparams.ibcp_max_frags,
2534                        IBLND_MAX_RDMA_FRAGS);
2535                 rc = -EPROTO;
2536                 goto failed;
2537         }
2538
2539         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2540                 CERROR("%s max message size %d too big (%d max)\n",
2541                        libcfs_nid2str(peer->ibp_nid),
2542                        msg->ibm_u.connparams.ibcp_max_msg_size,
2543                        IBLND_MSG_SIZE);
2544                 rc = -EPROTO;
2545                 goto failed;
2546         }
2547
2548         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2549         if (msg->ibm_dstnid == ni->ni_nid &&
2550             msg->ibm_dststamp == net->ibn_incarnation)
2551                 rc = 0;
2552         else
2553                 rc = -ESTALE;
2554         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2555
2556         if (rc != 0) {
2557                 CERROR("Stale connection reply from %s\n",
2558                        libcfs_nid2str(peer->ibp_nid));
2559                 goto failed;
2560         }
2561
2562         conn->ibc_incarnation      = msg->ibm_srcstamp;
2563         conn->ibc_credits          = IBLND_MSG_QUEUE_SIZE;
2564         conn->ibc_reserved_credits = IBLND_MSG_QUEUE_SIZE;
2565         LASSERT (conn->ibc_credits + conn->ibc_reserved_credits
2566                  <= IBLND_RX_MSGS);
2567
2568         kiblnd_connreq_done(conn, 0);
2569         return;
2570
2571  failed:
2572         /* NB My QP has already established itself, so I handle anything going
2573          * wrong here by setting ibc_comms_error.
2574          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
2575          * immediately tears it down. */
2576
2577         LASSERT (rc != 0);
2578         conn->ibc_comms_error = rc;
2579         kiblnd_connreq_done(conn, 0);
2580 }
2581
2582 int
2583 kiblnd_active_connect (struct rdma_cm_id *cmid)
2584 {
2585         kib_peer_t              *peer = (kib_peer_t *)cmid->context;
2586         kib_conn_t              *conn;
2587         kib_msg_t               *msg;
2588         struct rdma_conn_param   cp;
2589         int                      rc;
2590
2591         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_ACTIVE_CONNECT);
2592         if (conn == NULL) {
2593                 kiblnd_peer_connect_failed(peer, 1, -ENOMEM);
2594                 kiblnd_peer_decref(peer); /* lose cmid's ref */
2595                 return -ENOMEM;
2596         }
2597
2598         /* conn "owns" cmid now, so I return success from here on to ensure the
2599          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
2600          * on peer */
2601
2602         msg = &conn->ibc_connvars->cv_msg;
2603
2604         memset(msg, 0, sizeof(*msg));
2605         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
2606         msg->ibm_u.connparams.ibcp_queue_depth = IBLND_MSG_QUEUE_SIZE;
2607         msg->ibm_u.connparams.ibcp_max_frags = IBLND_MAX_RDMA_FRAGS;
2608         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2609         kiblnd_pack_msg(peer->ibp_ni, msg, 0, peer->ibp_nid, 0);
2610         
2611         memset(&cp, 0, sizeof(cp));
2612         cp.private_data        = msg;
2613         cp.private_data_len    = msg->ibm_nob;
2614         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2615         cp.initiator_depth     = 0;
2616         cp.flow_control        = 1;
2617         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2618         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2619
2620         LASSERT(cmid->context == (void *)conn);
2621         LASSERT(conn->ibc_cmid == cmid);
2622         
2623         rc = rdma_connect(cmid, &cp);
2624         if (rc != 0) {
2625                 CERROR("Can't connect to %s: %d\n",
2626                        libcfs_nid2str(peer->ibp_nid), rc);
2627                 kiblnd_connreq_done(conn, rc);
2628                 kiblnd_conn_decref(conn);
2629         }
2630
2631         return 0;
2632 }
2633
2634 int
2635 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
2636 {
2637         kib_peer_t  *peer;
2638         kib_conn_t  *conn;
2639         int          rc;
2640
2641         switch (event->event) {
2642         default:
2643                 LBUG();
2644
2645         case RDMA_CM_EVENT_CONNECT_REQUEST:
2646                 /* destroy cmid on failure */
2647                 rc = kiblnd_passive_connect(cmid, 
2648                                             (void *)KIBLND_CONN_PARAM(event),
2649                                             KIBLND_CONN_PARAM_LEN(event));
2650                 CDEBUG(D_NET, "connreq: %d\n", rc);
2651                 return rc;
2652                 
2653         case RDMA_CM_EVENT_ADDR_ERROR:
2654                 peer = (kib_peer_t *)cmid->context;
2655                 CDEBUG(D_NETERROR, "%s: ADDR ERROR %d\n",
2656                        libcfs_nid2str(peer->ibp_nid), event->status);
2657                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2658                 kiblnd_peer_decref(peer);
2659                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
2660
2661         case RDMA_CM_EVENT_ADDR_RESOLVED:
2662                 peer = (kib_peer_t *)cmid->context;
2663
2664                 CDEBUG(D_NET,"%s Addr resolved: %d\n",
2665                        libcfs_nid2str(peer->ibp_nid), event->status);
2666
2667                 if (event->status != 0) {
2668                         CDEBUG(D_NETERROR, "Can't resolve address for %s: %d\n",
2669                                libcfs_nid2str(peer->ibp_nid), event->status);
2670                         rc = event->status;
2671                 } else {
2672                         rc = rdma_resolve_route(
2673                                 cmid, *kiblnd_tunables.kib_timeout * 1000);
2674                         if (rc == 0)
2675                                 return 0;
2676                         /* Can't initiate route resolution */
2677                         CERROR("Can't resolve route for %s: %d\n",
2678                                libcfs_nid2str(peer->ibp_nid), rc);
2679                 }
2680                 kiblnd_peer_connect_failed(peer, 1, rc);
2681                 kiblnd_peer_decref(peer);
2682                 return rc;                      /* rc != 0 destroys cmid */
2683
2684         case RDMA_CM_EVENT_ROUTE_ERROR:
2685                 peer = (kib_peer_t *)cmid->context;
2686                 CDEBUG(D_NETERROR, "%s: ROUTE ERROR %d\n",
2687                        libcfs_nid2str(peer->ibp_nid), event->status);
2688                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2689                 kiblnd_peer_decref(peer);
2690                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
2691
2692         case RDMA_CM_EVENT_ROUTE_RESOLVED:
2693                 peer = (kib_peer_t *)cmid->context;
2694                 CDEBUG(D_NET,"%s Route resolved: %d\n",
2695                        libcfs_nid2str(peer->ibp_nid), event->status);
2696
2697                 if (event->status == 0)
2698                         return kiblnd_active_connect(cmid);
2699
2700                 CDEBUG(D_NETERROR, "Can't resolve route for %s: %d\n",
2701                        libcfs_nid2str(peer->ibp_nid), event->status);
2702                 kiblnd_peer_connect_failed(peer, 1, event->status);
2703                 kiblnd_peer_decref(peer);
2704                 return event->status;           /* rc != 0 destroys cmid */
2705                 
2706         case RDMA_CM_EVENT_UNREACHABLE:
2707                 conn = (kib_conn_t *)cmid->context;
2708                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
2709                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
2710                 CDEBUG(D_NETERROR, "%s: UNREACHABLE %d\n",
2711                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
2712                 kiblnd_connreq_done(conn, -ENETDOWN);
2713                 kiblnd_conn_decref(conn);
2714                 return 0;
2715
2716         case RDMA_CM_EVENT_CONNECT_ERROR:
2717                 conn = (kib_conn_t *)cmid->context;
2718                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
2719                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
2720                 CDEBUG(D_NETERROR, "%s: CONNECT ERROR %d\n",
2721                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
2722                 kiblnd_connreq_done(conn, -ENOTCONN);
2723                 kiblnd_conn_decref(conn);
2724                 return 0;
2725
2726         case RDMA_CM_EVENT_REJECTED:
2727                 conn = (kib_conn_t *)cmid->context;
2728                 switch (conn->ibc_state) {
2729                 default:
2730                         LBUG();
2731
2732                 case IBLND_CONN_PASSIVE_WAIT:
2733                         CERROR ("%s: REJECTED %d\n",
2734                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
2735                                 event->status);
2736                         kiblnd_connreq_done(conn, -ECONNRESET);
2737                         break;
2738
2739                 case IBLND_CONN_ACTIVE_CONNECT:
2740                         kiblnd_rejected(conn, event->status,
2741                                         (void *)KIBLND_CONN_PARAM(event),
2742                                         KIBLND_CONN_PARAM_LEN(event));
2743                         break;
2744                 }
2745                 kiblnd_conn_decref(conn);
2746                 return 0;
2747
2748         case RDMA_CM_EVENT_ESTABLISHED:
2749                 conn = (kib_conn_t *)cmid->context;
2750                 switch (conn->ibc_state) {
2751                 default:
2752                         LBUG();
2753
2754                 case IBLND_CONN_PASSIVE_WAIT:
2755                         CDEBUG(D_NET, "ESTABLISHED (passive): %s\n",
2756                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2757                         kiblnd_connreq_done(conn, 0);
2758                         break;
2759
2760                 case IBLND_CONN_ACTIVE_CONNECT:
2761                         CDEBUG(D_NET, "ESTABLISHED(active): %s\n",
2762                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2763                         kiblnd_check_connreply(conn,
2764                                                (void *)KIBLND_CONN_PARAM(event),
2765                                                KIBLND_CONN_PARAM_LEN(event));
2766                         break;
2767                 }
2768                 /* net keeps its ref on conn! */
2769                 return 0;
2770
2771         case RDMA_CM_EVENT_DISCONNECTED:
2772                 conn = (kib_conn_t *)cmid->context;
2773                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
2774                         CERROR("%s DISCONNECTED\n",
2775                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2776                         kiblnd_connreq_done(conn, -ECONNRESET);
2777                 } else {
2778                         kiblnd_close_conn(conn, 0);
2779                 }
2780                 kiblnd_conn_decref(conn);
2781                 return 0;
2782
2783         case RDMA_CM_EVENT_DEVICE_REMOVAL:
2784                 LCONSOLE_ERROR_MSG(0x131, 
2785                                    "Received notification of device removal\n"
2786                                    "Please shutdown LNET to allow this to proceed\n");
2787                 /* Can't remove network from underneath LNET for now, so I have
2788                  * to ignore this */
2789                 return 0;
2790         }
2791 }
2792
2793 int
2794 kiblnd_check_txs (kib_conn_t *conn, struct list_head *txs)
2795 {
2796         kib_tx_t          *tx;
2797         struct list_head  *ttmp;
2798         int                timed_out = 0;
2799
2800         spin_lock(&conn->ibc_lock);
2801
2802         list_for_each (ttmp, txs) {
2803                 tx = list_entry (ttmp, kib_tx_t, tx_list);
2804
2805                 if (txs != &conn->ibc_active_txs) {
2806                         LASSERT (tx->tx_queued);
2807                 } else {
2808                         LASSERT (!tx->tx_queued);
2809                         LASSERT (tx->tx_waiting || tx->tx_sending != 0);
2810                 }                        
2811
2812                 if (time_after_eq (jiffies, tx->tx_deadline)) {
2813                         timed_out = 1;
2814                         break;
2815                 }
2816         }
2817
2818         spin_unlock(&conn->ibc_lock);
2819         return timed_out;
2820 }
2821
2822 int
2823 kiblnd_conn_timed_out (kib_conn_t *conn)
2824 {
2825         return  kiblnd_check_txs(conn, &conn->ibc_tx_queue) ||
2826                 kiblnd_check_txs(conn, &conn->ibc_tx_noops) ||
2827                 kiblnd_check_txs(conn, &conn->ibc_tx_queue_rsrvd) ||
2828                 kiblnd_check_txs(conn, &conn->ibc_tx_queue_nocred) ||
2829                 kiblnd_check_txs(conn, &conn->ibc_active_txs);
2830 }
2831
2832 void
2833 kiblnd_check_conns (int idx)
2834 {
2835         struct list_head  *peers = &kiblnd_data.kib_peers[idx];
2836         struct list_head  *ptmp;
2837         kib_peer_t        *peer;
2838         kib_conn_t        *conn;
2839         struct list_head  *ctmp;
2840         unsigned long      flags;
2841
2842  again:
2843         /* NB. We expect to have a look at all the peers and not find any
2844          * rdmas to time out, so we just use a shared lock while we
2845          * take a look... */
2846         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2847
2848         list_for_each (ptmp, peers) {
2849                 peer = list_entry (ptmp, kib_peer_t, ibp_list);
2850
2851                 list_for_each (ctmp, &peer->ibp_conns) {
2852                         conn = list_entry (ctmp, kib_conn_t, ibc_list);
2853
2854                         LASSERT (conn->ibc_state == IBLND_CONN_ESTABLISHED);
2855
2856                         /* In case we have enough credits to return via a
2857                          * NOOP, but there were no non-blocking tx descs
2858                          * free to do it last time... */
2859                         kiblnd_check_sends(conn);
2860
2861                         if (!kiblnd_conn_timed_out(conn))
2862                                 continue;
2863
2864                         /* Handle timeout by closing the whole connection.  We
2865                          * can only be sure RDMA activity has ceased once the
2866                          * QP has been modified. */
2867
2868                         kiblnd_conn_addref(conn); /* 1 ref for me... */
2869
2870                         read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2871                                                flags);
2872
2873                         CERROR("Timed out RDMA with %s\n",
2874                                libcfs_nid2str(peer->ibp_nid));
2875
2876                         kiblnd_close_conn(conn, -ETIMEDOUT);
2877                         kiblnd_conn_decref(conn); /* ...until here */
2878
2879                         /* start again now I've dropped the lock */
2880                         goto again;
2881                 }
2882         }
2883
2884         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2885 }
2886
2887 void
2888 kiblnd_disconnect_conn (kib_conn_t *conn)
2889 {
2890         LASSERT (!in_interrupt());
2891         LASSERT (current == kiblnd_data.kib_connd);
2892         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
2893
2894         rdma_disconnect(conn->ibc_cmid);
2895         kiblnd_finalise_conn(conn);
2896
2897         kiblnd_peer_notify(conn->ibc_peer);
2898 }
2899
2900 int
2901 kiblnd_connd (void *arg)
2902 {
2903         wait_queue_t       wait;
2904         unsigned long      flags;
2905         kib_conn_t        *conn;
2906         int                timeout;
2907         int                i;
2908         int                dropped_lock;
2909         int                peer_index = 0;
2910         unsigned long      deadline = jiffies;
2911
2912         cfs_daemonize ("kiblnd_connd");
2913         cfs_block_allsigs ();
2914
2915         init_waitqueue_entry (&wait, current);
2916         kiblnd_data.kib_connd = current;
2917
2918         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2919
2920         while (!kiblnd_data.kib_shutdown) {
2921
2922                 dropped_lock = 0;
2923
2924                 if (!list_empty (&kiblnd_data.kib_connd_zombies)) {
2925                         conn = list_entry (kiblnd_data.kib_connd_zombies.next,
2926                                            kib_conn_t, ibc_list);
2927                         list_del (&conn->ibc_list);
2928
2929                         spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock, flags);
2930                         dropped_lock = 1;
2931
2932                         kiblnd_destroy_conn(conn);
2933
2934                         spin_lock_irqsave (&kiblnd_data.kib_connd_lock, flags);
2935                 }
2936
2937                 if (!list_empty (&kiblnd_data.kib_connd_conns)) {
2938                         conn = list_entry (kiblnd_data.kib_connd_conns.next,
2939                                            kib_conn_t, ibc_list);
2940                         list_del (&conn->ibc_list);
2941
2942                         spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock, flags);
2943                         dropped_lock = 1;
2944
2945                         kiblnd_disconnect_conn(conn);
2946                         kiblnd_conn_decref(conn);
2947
2948                         spin_lock_irqsave (&kiblnd_data.kib_connd_lock, flags);
2949                 }
2950
2951                 /* careful with the jiffy wrap... */
2952                 timeout = (int)(deadline - jiffies);
2953                 if (timeout <= 0) {
2954                         const int n = 4;
2955                         const int p = 1;
2956                         int       chunk = kiblnd_data.kib_peer_hash_size;
2957
2958                         spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
2959                         dropped_lock = 1;
2960
2961                         /* Time to check for RDMA timeouts on a few more
2962                          * peers: I do checks every 'p' seconds on a
2963                          * proportion of the peer table and I need to check
2964                          * every connection 'n' times within a timeout
2965                          * interval, to ensure I detect a timeout on any
2966                          * connection within (n+1)/n times the timeout
2967                          * interval. */
2968
2969                         if (*kiblnd_tunables.kib_timeout > n * p)
2970                                 chunk = (chunk * n * p) /
2971                                         *kiblnd_tunables.kib_timeout;
2972                         if (chunk == 0)
2973                                 chunk = 1;
2974
2975                         for (i = 0; i < chunk; i++) {
2976                                 kiblnd_check_conns(peer_index);
2977                                 peer_index = (peer_index + 1) %
2978                                              kiblnd_data.kib_peer_hash_size;
2979                         }
2980
2981                         deadline += p * HZ;
2982                         spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
2983                 }
2984
2985                 if (dropped_lock)
2986                         continue;
2987
2988                 /* Nothing to do for 'timeout'  */
2989                 set_current_state (TASK_INTERRUPTIBLE);
2990                 add_wait_queue (&kiblnd_data.kib_connd_waitq, &wait);
2991                 spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock, flags);
2992
2993                 schedule_timeout (timeout);
2994
2995                 set_current_state (TASK_RUNNING);
2996                 remove_wait_queue (&kiblnd_data.kib_connd_waitq, &wait);
2997                 spin_lock_irqsave (&kiblnd_data.kib_connd_lock, flags);
2998         }
2999
3000         spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock, flags);
3001
3002         kiblnd_thread_fini();
3003         return (0);
3004 }
3005
3006 void
3007 kiblnd_qp_event(struct ib_event *event, void *arg)
3008 {
3009         kib_conn_t *conn = arg;
3010
3011         switch (event->event) {
3012         case IB_EVENT_COMM_EST:
3013                 CDEBUG(D_NET, "%s established\n",
3014                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
3015                 return;
3016                 
3017         default:
3018                 CERROR("%s: Async QP event type %d\n",
3019                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3020                 return;
3021         }
3022 }
3023
3024 void
3025 kiblnd_complete (struct ib_wc *wc)
3026 {
3027         switch (kiblnd_wreqid2type(wc->wr_id)) {
3028         default:
3029                 LBUG();
3030
3031         case IBLND_WID_RDMA:
3032                 /* We only get RDMA completion notification if it fails.  All
3033                  * subsequent work items, including the final SEND will fail
3034                  * too.  However we can't print out any more info about the
3035                  * failing RDMA because 'tx' might be back on the idle list or
3036                  * even reused already if we didn't manage to post all our work
3037                  * items */
3038                 CDEBUG(D_NETERROR, "RDMA (tx: %p) failed: %d\n",
3039                        kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3040                 return;
3041
3042         case IBLND_WID_TX:
3043                 kiblnd_tx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status);
3044                 return;
3045
3046         case IBLND_WID_RX:
3047                 kiblnd_rx_complete(kiblnd_wreqid2ptr(wc->wr_id), wc->status,
3048                                    wc->byte_len);
3049                 return;
3050         }
3051 }
3052
3053 void
3054 kiblnd_cq_completion (struct ib_cq *cq, void *arg)
3055 {
3056         /* NB I'm not allowed to schedule this conn once its refcount has
3057          * reached 0.  Since fundamentally I'm racing with scheduler threads
3058          * consuming my CQ I could be called after all completions have
3059          * occurred.  But in this case, ibc_nrx == 0 && ibc_nsends_posted == 0
3060          * and this CQ is about to be destroyed so I NOOP. */
3061         kib_conn_t     *conn = (kib_conn_t *)arg;
3062         unsigned long   flags;
3063         
3064         LASSERT (cq == conn->ibc_cq);
3065
3066         spin_lock_irqsave(&kiblnd_data.kib_sched_lock, flags);
3067
3068         conn->ibc_ready = 1;
3069
3070         if (!conn->ibc_scheduled &&
3071             (conn->ibc_nrx > 0 ||
3072              conn->ibc_nsends_posted > 0)) {
3073                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3074                 conn->ibc_scheduled = 1;
3075                 list_add_tail(&conn->ibc_sched_list,
3076                               &kiblnd_data.kib_sched_conns);
3077                 wake_up(&kiblnd_data.kib_sched_waitq);
3078         }
3079
3080         spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock, flags);
3081 }
3082
3083 void
3084 kiblnd_cq_event(struct ib_event *event, void *arg)
3085 {
3086         kib_conn_t *conn = arg;
3087
3088         CERROR("%s: async CQ event type %d\n",
3089                libcfs_nid2str(conn->ibc_peer->ibp_nid), event->event);
3090 }
3091
3092 int
3093 kiblnd_scheduler(void *arg)
3094 {
3095         long            id = (long)arg;
3096         wait_queue_t    wait;
3097         char            name[16];
3098         unsigned long   flags;
3099         kib_conn_t     *conn;
3100         struct ib_wc    wc;
3101         int             rc;
3102         int             did_something;
3103         int             busy_loops = 0;
3104
3105         snprintf(name, sizeof(name), "kiblnd_sd_%02ld", id);
3106         cfs_daemonize(name);
3107         cfs_block_allsigs();
3108
3109         init_waitqueue_entry(&wait, current);
3110
3111         spin_lock_irqsave(&kiblnd_data.kib_sched_lock, flags);
3112
3113         while (!kiblnd_data.kib_shutdown) {
3114                 if (busy_loops++ >= IBLND_RESCHED) {
3115                         spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock,
3116                                                flags);
3117
3118                         our_cond_resched();
3119                         busy_loops = 0;
3120
3121                         spin_lock_irqsave(&kiblnd_data.kib_sched_lock, flags);
3122                 }
3123
3124                 did_something = 0;
3125
3126                 if (!list_empty(&kiblnd_data.kib_sched_conns)) {
3127                         conn = list_entry(kiblnd_data.kib_sched_conns.next,
3128                                           kib_conn_t, ibc_sched_list);
3129                         /* take over kib_sched_conns' ref on conn... */
3130                         LASSERT(conn->ibc_scheduled);
3131                         list_del(&conn->ibc_sched_list);
3132                         conn->ibc_ready = 0;
3133                         
3134                         spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock,
3135                                                flags);
3136
3137                         rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3138                         if (rc == 0) {
3139                                 rc = ib_req_notify_cq(conn->ibc_cq,
3140                                                       IB_CQ_NEXT_COMP);
3141                                 LASSERT (rc >= 0);
3142
3143                                 rc = ib_poll_cq(conn->ibc_cq, 1, &wc);
3144                         }
3145
3146                         LASSERT (rc >= 0);
3147
3148                         spin_lock_irqsave(&kiblnd_data.kib_sched_lock,
3149                                           flags);
3150
3151                         if (rc != 0 || conn->ibc_ready) {
3152                                 /* There may be another completion waiting; get
3153                                  * another scheduler to check while I handle
3154                                  * this one... */
3155                                 kiblnd_conn_addref(conn); /* +1 ref for sched_conns */
3156                                 list_add_tail(&conn->ibc_sched_list,
3157                                               &kiblnd_data.kib_sched_conns);
3158                                 wake_up(&kiblnd_data.kib_sched_waitq);
3159                         } else {
3160                                 conn->ibc_scheduled = 0;
3161                         }
3162                         
3163                         if (rc != 0) {
3164                                 spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock,
3165                                                        flags);
3166
3167                                 kiblnd_complete(&wc);
3168
3169                                 spin_lock_irqsave(&kiblnd_data.kib_sched_lock,
3170                                                   flags);
3171                         }
3172
3173                         kiblnd_conn_decref(conn); /* ...drop my ref from above */
3174                         did_something = 1;
3175                 }
3176
3177                 if (did_something)
3178                         continue;
3179
3180                 set_current_state(TASK_INTERRUPTIBLE);
3181                 add_wait_queue_exclusive(&kiblnd_data.kib_sched_waitq, &wait);
3182                 spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock, flags);
3183
3184                 schedule();
3185                 busy_loops = 0;
3186
3187                 remove_wait_queue(&kiblnd_data.kib_sched_waitq, &wait);
3188                 set_current_state(TASK_RUNNING);
3189                 spin_lock_irqsave(&kiblnd_data.kib_sched_lock, flags);
3190         }
3191
3192         spin_unlock_irqrestore(&kiblnd_data.kib_sched_lock, flags);
3193
3194         kiblnd_thread_fini();
3195         return (0);
3196 }