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