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