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