Whamcloud - gitweb
b20288 fix a deadlock in kiblnd_check_conns i=isaac i=maxim
[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 (c) 2007, 2010, Oracle and/or its affiliates. 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
878         cfs_spin_lock(&conn->ibc_lock);
879
880         return -EIO;
881 }
882
883 void
884 kiblnd_check_sends (kib_conn_t *conn)
885 {
886         int        ver = conn->ibc_version;
887         lnet_ni_t *ni = conn->ibc_peer->ibp_ni;
888         kib_tx_t  *tx;
889
890         /* Don't send anything until after the connection is established */
891         if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
892                 CDEBUG(D_NET, "%s too soon\n",
893                        libcfs_nid2str(conn->ibc_peer->ibp_nid));
894                 return;
895         }
896
897         cfs_spin_lock(&conn->ibc_lock);
898
899         LASSERT (conn->ibc_nsends_posted <= IBLND_CONCURRENT_SENDS(ver));
900         LASSERT (!IBLND_OOB_CAPABLE(ver) ||
901                  conn->ibc_noops_posted <= IBLND_OOB_MSGS(ver));
902         LASSERT (conn->ibc_reserved_credits >= 0);
903
904         while (conn->ibc_reserved_credits > 0 &&
905                !cfs_list_empty(&conn->ibc_tx_queue_rsrvd)) {
906                 tx = cfs_list_entry(conn->ibc_tx_queue_rsrvd.next,
907                                     kib_tx_t, tx_list);
908                 cfs_list_del(&tx->tx_list);
909                 cfs_list_add_tail(&tx->tx_list, &conn->ibc_tx_queue);
910                 conn->ibc_reserved_credits--;
911         }
912
913         conn->ibc_retry_noop = 0;
914         if (kiblnd_send_noop(conn)) {
915                 cfs_spin_unlock(&conn->ibc_lock);
916
917                 tx = kiblnd_get_idle_tx(ni);
918                 if (tx != NULL)
919                         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_NOOP, 0);
920
921                 cfs_spin_lock(&conn->ibc_lock);
922                 if (tx != NULL)
923                         kiblnd_queue_tx_locked(tx, conn);
924                 else if (kiblnd_send_noop(conn)) /* still... */
925                         conn->ibc_retry_noop = 1;
926         }
927
928         kiblnd_conn_addref(conn); /* 1 ref for me.... (see b21911) */
929
930         for (;;) {
931                 int credit;
932
933                 if (!cfs_list_empty(&conn->ibc_tx_queue_nocred)) {
934                         credit = 0;
935                         tx = cfs_list_entry(conn->ibc_tx_queue_nocred.next,
936                                             kib_tx_t, tx_list);
937                 } else if (!cfs_list_empty(&conn->ibc_tx_queue)) {
938                         credit = 1;
939                         tx = cfs_list_entry(conn->ibc_tx_queue.next,
940                                             kib_tx_t, tx_list);
941                 } else
942                         break;
943
944                 if (kiblnd_post_tx_locked(conn, tx, credit) != 0)
945                         break;
946         }
947
948         cfs_spin_unlock(&conn->ibc_lock);
949
950         kiblnd_conn_decref(conn); /* ...until here */
951 }
952
953 void
954 kiblnd_tx_complete (kib_tx_t *tx, int status)
955 {
956         int           failed = (status != IB_WC_SUCCESS);
957         kib_conn_t   *conn = tx->tx_conn;
958         int           idle;
959
960         LASSERT (tx->tx_sending > 0);
961
962         if (failed) {
963                 if (conn->ibc_state == IBLND_CONN_ESTABLISHED)
964                         CDEBUG(D_NETERROR, "Tx -> %s cookie "LPX64
965                                " sending %d waiting %d: failed %d\n",
966                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
967                                tx->tx_cookie, tx->tx_sending, tx->tx_waiting,
968                                status);
969
970                 kiblnd_close_conn(conn, -EIO);
971         } else {
972                 kiblnd_peer_alive(conn->ibc_peer);
973         }
974
975         cfs_spin_lock(&conn->ibc_lock);
976
977         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
978          * gets to free it, which also drops its ref on 'conn'. */
979
980         tx->tx_sending--;
981         conn->ibc_nsends_posted--;
982         if (tx->tx_msg->ibm_type == IBLND_MSG_NOOP)
983                 conn->ibc_noops_posted--;
984
985         if (failed) {
986                 tx->tx_waiting = 0;             /* don't wait for peer */
987                 tx->tx_status = -EIO;
988         }
989
990         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
991                !tx->tx_waiting &&               /* Not waiting for peer */
992                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
993         if (idle)
994                 cfs_list_del(&tx->tx_list);
995
996         kiblnd_conn_addref(conn);               /* 1 ref for me.... */
997
998         cfs_spin_unlock(&conn->ibc_lock);
999
1000         if (idle)
1001                 kiblnd_tx_done(conn->ibc_peer->ibp_ni, tx);
1002
1003         kiblnd_check_sends(conn);
1004
1005         kiblnd_conn_decref(conn);               /* ...until here */
1006 }
1007
1008 void
1009 kiblnd_init_tx_msg (lnet_ni_t *ni, kib_tx_t *tx, int type, int body_nob)
1010 {
1011         kib_net_t         *net = ni->ni_data;
1012         struct ib_sge     *sge = &tx->tx_sge[tx->tx_nwrq];
1013         struct ib_send_wr *wrq = &tx->tx_wrq[tx->tx_nwrq];
1014         int                nob = offsetof (kib_msg_t, ibm_u) + body_nob;
1015         struct ib_mr      *mr;
1016
1017         LASSERT (net != NULL);
1018         LASSERT (tx->tx_nwrq >= 0);
1019         LASSERT (tx->tx_nwrq < IBLND_MAX_RDMA_FRAGS + 1);
1020         LASSERT (nob <= IBLND_MSG_SIZE);
1021
1022         kiblnd_init_msg(tx->tx_msg, type, body_nob);
1023
1024         mr = kiblnd_find_dma_mr(net, tx->tx_msgaddr, nob);
1025         LASSERT (mr != NULL);
1026
1027         sge->lkey   = mr->lkey;
1028         sge->addr   = tx->tx_msgaddr;
1029         sge->length = nob;
1030
1031         memset(wrq, 0, sizeof(*wrq));
1032
1033         wrq->next       = NULL;
1034         wrq->wr_id      = kiblnd_ptr2wreqid(tx, IBLND_WID_TX);
1035         wrq->sg_list    = sge;
1036         wrq->num_sge    = 1;
1037         wrq->opcode     = IB_WR_SEND;
1038         wrq->send_flags = IB_SEND_SIGNALED;
1039
1040         tx->tx_nwrq++;
1041 }
1042
1043 int
1044 kiblnd_init_rdma (kib_conn_t *conn, kib_tx_t *tx, int type,
1045                   int resid, kib_rdma_desc_t *dstrd, __u64 dstcookie)
1046 {
1047         kib_msg_t         *ibmsg = tx->tx_msg;
1048         kib_rdma_desc_t   *srcrd = tx->tx_rd;
1049         struct ib_sge     *sge = &tx->tx_sge[0];
1050         struct ib_send_wr *wrq = &tx->tx_wrq[0];
1051         int                rc  = resid;
1052         int                srcidx;
1053         int                dstidx;
1054         int                wrknob;
1055
1056         LASSERT (!cfs_in_interrupt());
1057         LASSERT (tx->tx_nwrq == 0);
1058         LASSERT (type == IBLND_MSG_GET_DONE ||
1059                  type == IBLND_MSG_PUT_DONE);
1060
1061         srcidx = dstidx = 0;
1062
1063         while (resid > 0) {
1064                 if (srcidx >= srcrd->rd_nfrags) {
1065                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1066                         rc = -EPROTO;
1067                         break;
1068                 }
1069
1070                 if (dstidx == dstrd->rd_nfrags) {
1071                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1072                         rc = -EPROTO;
1073                         break;
1074                 }
1075
1076                 if (tx->tx_nwrq == IBLND_RDMA_FRAGS(conn->ibc_version)) {
1077                         CERROR("RDMA too fragmented for %s (%d): "
1078                                "%d/%d src %d/%d dst frags\n",
1079                                libcfs_nid2str(conn->ibc_peer->ibp_nid),
1080                                IBLND_RDMA_FRAGS(conn->ibc_version),
1081                                srcidx, srcrd->rd_nfrags,
1082                                dstidx, dstrd->rd_nfrags);
1083                         rc = -EMSGSIZE;
1084                         break;
1085                 }
1086
1087                 wrknob = MIN(MIN(kiblnd_rd_frag_size(srcrd, srcidx),
1088                                  kiblnd_rd_frag_size(dstrd, dstidx)), resid);
1089
1090                 sge = &tx->tx_sge[tx->tx_nwrq];
1091                 sge->addr   = kiblnd_rd_frag_addr(srcrd, srcidx);
1092                 sge->lkey   = kiblnd_rd_frag_key(srcrd, srcidx);
1093                 sge->length = wrknob;
1094
1095                 wrq = &tx->tx_wrq[tx->tx_nwrq];
1096
1097                 wrq->next       = wrq + 1;
1098                 wrq->wr_id      = kiblnd_ptr2wreqid(tx, IBLND_WID_RDMA);
1099                 wrq->sg_list    = sge;
1100                 wrq->num_sge    = 1;
1101                 wrq->opcode     = IB_WR_RDMA_WRITE;
1102                 wrq->send_flags = 0;
1103
1104                 wrq->wr.rdma.remote_addr = kiblnd_rd_frag_addr(dstrd, dstidx);
1105                 wrq->wr.rdma.rkey        = kiblnd_rd_frag_key(dstrd, dstidx);
1106
1107                 srcidx = kiblnd_rd_consume_frag(srcrd, srcidx, wrknob);
1108                 dstidx = kiblnd_rd_consume_frag(dstrd, dstidx, wrknob);
1109
1110                 resid -= wrknob;
1111
1112                 tx->tx_nwrq++;
1113                 wrq++;
1114                 sge++;
1115         }
1116
1117         if (rc < 0)                             /* no RDMA if completing with failure */
1118                 tx->tx_nwrq = 0;
1119
1120         ibmsg->ibm_u.completion.ibcm_status = rc;
1121         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1122         kiblnd_init_tx_msg(conn->ibc_peer->ibp_ni, tx,
1123                            type, sizeof (kib_completion_msg_t));
1124
1125         return rc;
1126 }
1127
1128 void
1129 kiblnd_queue_tx_locked (kib_tx_t *tx, kib_conn_t *conn)
1130 {
1131         cfs_list_t   *q;
1132
1133         LASSERT (tx->tx_nwrq > 0);              /* work items set up */
1134         LASSERT (!tx->tx_queued);               /* not queued for sending already */
1135         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1136
1137         tx->tx_queued = 1;
1138         tx->tx_deadline = jiffies + (*kiblnd_tunables.kib_timeout * CFS_HZ);
1139
1140         if (tx->tx_conn == NULL) {
1141                 kiblnd_conn_addref(conn);
1142                 tx->tx_conn = conn;
1143                 LASSERT (tx->tx_msg->ibm_type != IBLND_MSG_PUT_DONE);
1144         } else {
1145                 /* PUT_DONE first attached to conn as a PUT_REQ */
1146                 LASSERT (tx->tx_conn == conn);
1147                 LASSERT (tx->tx_msg->ibm_type == IBLND_MSG_PUT_DONE);
1148         }
1149
1150         switch (tx->tx_msg->ibm_type) {
1151         default:
1152                 LBUG();
1153
1154         case IBLND_MSG_PUT_REQ:
1155         case IBLND_MSG_GET_REQ:
1156                 q = &conn->ibc_tx_queue_rsrvd;
1157                 break;
1158
1159         case IBLND_MSG_PUT_NAK:
1160         case IBLND_MSG_PUT_ACK:
1161         case IBLND_MSG_PUT_DONE:
1162         case IBLND_MSG_GET_DONE:
1163                 q = &conn->ibc_tx_queue_nocred;
1164                 break;
1165
1166         case IBLND_MSG_NOOP:
1167                 if (IBLND_OOB_CAPABLE(conn->ibc_version))
1168                         q = &conn->ibc_tx_queue_nocred;
1169                 else
1170                         q = &conn->ibc_tx_queue;
1171                 break;
1172
1173         case IBLND_MSG_IMMEDIATE:
1174                 q = &conn->ibc_tx_queue;
1175                 break;
1176         }
1177
1178         cfs_list_add_tail(&tx->tx_list, q);
1179 }
1180
1181 void
1182 kiblnd_queue_tx (kib_tx_t *tx, kib_conn_t *conn)
1183 {
1184         cfs_spin_lock(&conn->ibc_lock);
1185         kiblnd_queue_tx_locked(tx, conn);
1186         cfs_spin_unlock(&conn->ibc_lock);
1187
1188         kiblnd_check_sends(conn);
1189 }
1190
1191 void
1192 kiblnd_connect_peer (kib_peer_t *peer)
1193 {
1194         struct rdma_cm_id *cmid;
1195         kib_dev_t         *dev;
1196         kib_net_t         *net = peer->ibp_ni->ni_data;
1197         struct sockaddr_in srcaddr;
1198         struct sockaddr_in dstaddr;
1199         int                rc;
1200
1201         LASSERT (net != NULL);
1202         LASSERT (peer->ibp_connecting > 0);
1203
1204         cmid = rdma_create_id(kiblnd_cm_callback, peer, RDMA_PS_TCP);
1205         if (IS_ERR(cmid)) {
1206                 CERROR("Can't create CMID for %s: %ld\n",
1207                        libcfs_nid2str(peer->ibp_nid), PTR_ERR(cmid));
1208                 rc = PTR_ERR(cmid);
1209                 goto failed;
1210         }
1211
1212         dev = net->ibn_dev;
1213         memset(&srcaddr, 0, sizeof(srcaddr));
1214         srcaddr.sin_family = AF_INET;
1215         srcaddr.sin_addr.s_addr = htonl(dev->ibd_ifip);
1216
1217         memset(&dstaddr, 0, sizeof(dstaddr));
1218         dstaddr.sin_family = AF_INET;
1219         dstaddr.sin_port = htons(*kiblnd_tunables.kib_service);
1220         dstaddr.sin_addr.s_addr = htonl(LNET_NIDADDR(peer->ibp_nid));
1221
1222         kiblnd_peer_addref(peer);               /* cmid's ref */
1223
1224         rc = rdma_resolve_addr(cmid,
1225                                (struct sockaddr *)&srcaddr,
1226                                (struct sockaddr *)&dstaddr,
1227                                *kiblnd_tunables.kib_timeout * 1000);
1228         if (rc == 0) {
1229                 LASSERT (cmid->device != NULL);
1230                 CDEBUG(D_NET, "%s: connection bound to %s:%u.%u.%u.%u:%s\n",
1231                        libcfs_nid2str(peer->ibp_nid), dev->ibd_ifname,
1232                        HIPQUAD(dev->ibd_ifip), cmid->device->name);
1233                 return;
1234         }
1235
1236         /* Can't initiate address resolution:  */
1237         CERROR("Can't resolve addr for %s: %d\n",
1238                libcfs_nid2str(peer->ibp_nid), rc);
1239
1240         kiblnd_peer_decref(peer);               /* cmid's ref */
1241         rdma_destroy_id(cmid);
1242  failed:
1243         kiblnd_peer_connect_failed(peer, 1, rc);
1244 }
1245
1246 void
1247 kiblnd_launch_tx (lnet_ni_t *ni, kib_tx_t *tx, lnet_nid_t nid)
1248 {
1249         kib_peer_t        *peer;
1250         kib_peer_t        *peer2;
1251         kib_conn_t        *conn;
1252         cfs_rwlock_t      *g_lock = &kiblnd_data.kib_global_lock;
1253         unsigned long      flags;
1254         int                rc;
1255
1256         /* If I get here, I've committed to send, so I complete the tx with
1257          * failure on any problems */
1258
1259         LASSERT (tx == NULL || tx->tx_conn == NULL); /* only set when assigned a conn */
1260         LASSERT (tx == NULL || tx->tx_nwrq > 0);     /* work items have been set up */
1261
1262         /* First time, just use a read lock since I expect to find my peer
1263          * connected */
1264         cfs_read_lock_irqsave(g_lock, flags);
1265
1266         peer = kiblnd_find_peer_locked(nid);
1267         if (peer != NULL && !cfs_list_empty(&peer->ibp_conns)) {
1268                 /* Found a peer with an established connection */
1269                 conn = kiblnd_get_conn_locked(peer);
1270                 kiblnd_conn_addref(conn); /* 1 ref for me... */
1271
1272                 cfs_read_unlock_irqrestore(g_lock, flags);
1273
1274                 if (tx != NULL)
1275                         kiblnd_queue_tx(tx, conn);
1276                 kiblnd_conn_decref(conn); /* ...to here */
1277                 return;
1278         }
1279
1280         cfs_read_unlock(g_lock);
1281         /* Re-try with a write lock */
1282         cfs_write_lock(g_lock);
1283
1284         peer = kiblnd_find_peer_locked(nid);
1285         if (peer != NULL) {
1286                 if (cfs_list_empty(&peer->ibp_conns)) {
1287                         /* found a peer, but it's still connecting... */
1288                         LASSERT (peer->ibp_connecting != 0 ||
1289                                  peer->ibp_accepting != 0);
1290                         if (tx != NULL)
1291                                 cfs_list_add_tail(&tx->tx_list,
1292                                                   &peer->ibp_tx_queue);
1293                         cfs_write_unlock_irqrestore(g_lock, flags);
1294                 } else {
1295                         conn = kiblnd_get_conn_locked(peer);
1296                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1297
1298                         cfs_write_unlock_irqrestore(g_lock, flags);
1299
1300                         if (tx != NULL)
1301                                 kiblnd_queue_tx(tx, conn);
1302                         kiblnd_conn_decref(conn); /* ...to here */
1303                 }
1304                 return;
1305         }
1306
1307         cfs_write_unlock_irqrestore(g_lock, flags);
1308
1309         /* Allocate a peer ready to add to the peer table and retry */
1310         rc = kiblnd_create_peer(ni, &peer, nid);
1311         if (rc != 0) {
1312                 CERROR("Can't create peer %s\n", libcfs_nid2str(nid));
1313                 if (tx != NULL) {
1314                         tx->tx_status = -EHOSTUNREACH;
1315                         tx->tx_waiting = 0;
1316                         kiblnd_tx_done(ni, tx);
1317                 }
1318                 return;
1319         }
1320
1321         cfs_write_lock_irqsave(g_lock, flags);
1322
1323         peer2 = kiblnd_find_peer_locked(nid);
1324         if (peer2 != NULL) {
1325                 if (cfs_list_empty(&peer2->ibp_conns)) {
1326                         /* found a peer, but it's still connecting... */
1327                         LASSERT (peer2->ibp_connecting != 0 ||
1328                                  peer2->ibp_accepting != 0);
1329                         if (tx != NULL)
1330                                 cfs_list_add_tail(&tx->tx_list,
1331                                                   &peer2->ibp_tx_queue);
1332                         cfs_write_unlock_irqrestore(g_lock, flags);
1333                 } else {
1334                         conn = kiblnd_get_conn_locked(peer2);
1335                         kiblnd_conn_addref(conn); /* 1 ref for me... */
1336
1337                         cfs_write_unlock_irqrestore(g_lock, flags);
1338
1339                         if (tx != NULL)
1340                                 kiblnd_queue_tx(tx, conn);
1341                         kiblnd_conn_decref(conn); /* ...to here */
1342                 }
1343
1344                 kiblnd_peer_decref(peer);
1345                 return;
1346         }
1347
1348         /* Brand new peer */
1349         LASSERT (peer->ibp_connecting == 0);
1350         peer->ibp_connecting = 1;
1351
1352         /* always called with a ref on ni, which prevents ni being shutdown */
1353         LASSERT (((kib_net_t *)ni->ni_data)->ibn_shutdown == 0);
1354
1355         if (tx != NULL)
1356                 cfs_list_add_tail(&tx->tx_list, &peer->ibp_tx_queue);
1357
1358         kiblnd_peer_addref(peer);
1359         cfs_list_add_tail(&peer->ibp_list, kiblnd_nid2peerlist(nid));
1360
1361         cfs_write_unlock_irqrestore(g_lock, flags);
1362
1363         kiblnd_connect_peer(peer);
1364         kiblnd_peer_decref(peer);
1365 }
1366
1367 int
1368 kiblnd_send (lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg)
1369 {
1370         lnet_hdr_t       *hdr = &lntmsg->msg_hdr;
1371         int               type = lntmsg->msg_type;
1372         lnet_process_id_t target = lntmsg->msg_target;
1373         int               target_is_router = lntmsg->msg_target_is_router;
1374         int               routing = lntmsg->msg_routing;
1375         unsigned int      payload_niov = lntmsg->msg_niov;
1376         struct iovec     *payload_iov = lntmsg->msg_iov;
1377         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
1378         unsigned int      payload_offset = lntmsg->msg_offset;
1379         unsigned int      payload_nob = lntmsg->msg_len;
1380         kib_msg_t        *ibmsg;
1381         kib_tx_t         *tx;
1382         int               nob;
1383         int               rc;
1384
1385         /* NB 'private' is different depending on what we're sending.... */
1386
1387         CDEBUG(D_NET, "sending %d bytes in %d frags to %s\n",
1388                payload_nob, payload_niov, libcfs_id2str(target));
1389
1390         LASSERT (payload_nob == 0 || payload_niov > 0);
1391         LASSERT (payload_niov <= LNET_MAX_IOV);
1392
1393         /* Thread context */
1394         LASSERT (!cfs_in_interrupt());
1395         /* payload is either all vaddrs or all pages */
1396         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1397
1398         switch (type) {
1399         default:
1400                 LBUG();
1401                 return (-EIO);
1402
1403         case LNET_MSG_ACK:
1404                 LASSERT (payload_nob == 0);
1405                 break;
1406
1407         case LNET_MSG_GET:
1408                 if (routing || target_is_router)
1409                         break;                  /* send IMMEDIATE */
1410
1411                 /* is the REPLY message too small for RDMA? */
1412                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[lntmsg->msg_md->md_length]);
1413                 if (nob <= IBLND_MSG_SIZE)
1414                         break;                  /* send IMMEDIATE */
1415
1416                 tx = kiblnd_get_idle_tx(ni);
1417                 if (tx == NULL) {
1418                         CERROR("Can't allocate txd for GET to %s: \n",
1419                                libcfs_nid2str(target.nid));
1420                         return -ENOMEM;
1421                 }
1422
1423                 ibmsg = tx->tx_msg;
1424
1425                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0)
1426                         rc = kiblnd_setup_rd_iov(ni, tx,
1427                                                  &ibmsg->ibm_u.get.ibgm_rd,
1428                                                  lntmsg->msg_md->md_niov,
1429                                                  lntmsg->msg_md->md_iov.iov,
1430                                                  0, lntmsg->msg_md->md_length);
1431                 else
1432                         rc = kiblnd_setup_rd_kiov(ni, tx,
1433                                                   &ibmsg->ibm_u.get.ibgm_rd,
1434                                                   lntmsg->msg_md->md_niov,
1435                                                   lntmsg->msg_md->md_iov.kiov,
1436                                                   0, lntmsg->msg_md->md_length);
1437                 if (rc != 0) {
1438                         CERROR("Can't setup GET sink for %s: %d\n",
1439                                libcfs_nid2str(target.nid), rc);
1440                         kiblnd_tx_done(ni, tx);
1441                         return -EIO;
1442                 }
1443
1444                 nob = offsetof(kib_get_msg_t, ibgm_rd.rd_frags[tx->tx_nfrags]);
1445                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1446                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1447
1448                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_GET_REQ, nob);
1449
1450                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
1451                 if (tx->tx_lntmsg[1] == NULL) {
1452                         CERROR("Can't create reply for GET -> %s\n",
1453                                libcfs_nid2str(target.nid));
1454                         kiblnd_tx_done(ni, tx);
1455                         return -EIO;
1456                 }
1457
1458                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg[0,1] on completion */
1459                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1460                 kiblnd_launch_tx(ni, tx, target.nid);
1461                 return 0;
1462
1463         case LNET_MSG_REPLY:
1464         case LNET_MSG_PUT:
1465                 /* Is the payload small enough not to need RDMA? */
1466                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob]);
1467                 if (nob <= IBLND_MSG_SIZE)
1468                         break;                  /* send IMMEDIATE */
1469
1470                 tx = kiblnd_get_idle_tx(ni);
1471                 if (tx == NULL) {
1472                         CERROR("Can't allocate %s txd for %s\n",
1473                                type == LNET_MSG_PUT ? "PUT" : "REPLY",
1474                                libcfs_nid2str(target.nid));
1475                         return -ENOMEM;
1476                 }
1477
1478                 if (payload_kiov == NULL)
1479                         rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1480                                                  payload_niov, payload_iov,
1481                                                  payload_offset, payload_nob);
1482                 else
1483                         rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1484                                                   payload_niov, payload_kiov,
1485                                                   payload_offset, payload_nob);
1486                 if (rc != 0) {
1487                         CERROR("Can't setup PUT src for %s: %d\n",
1488                                libcfs_nid2str(target.nid), rc);
1489                         kiblnd_tx_done(ni, tx);
1490                         return -EIO;
1491                 }
1492
1493                 ibmsg = tx->tx_msg;
1494                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1495                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1496                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_REQ, sizeof(kib_putreq_msg_t));
1497
1498                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1499                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1500                 kiblnd_launch_tx(ni, tx, target.nid);
1501                 return 0;
1502         }
1503
1504         /* send IMMEDIATE */
1505
1506         LASSERT (offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob])
1507                  <= IBLND_MSG_SIZE);
1508
1509         tx = kiblnd_get_idle_tx(ni);
1510         if (tx == NULL) {
1511                 CERROR ("Can't send %d to %s: tx descs exhausted\n",
1512                         type, libcfs_nid2str(target.nid));
1513                 return -ENOMEM;
1514         }
1515
1516         ibmsg = tx->tx_msg;
1517         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1518
1519         if (payload_kiov != NULL)
1520                 lnet_copy_kiov2flat(IBLND_MSG_SIZE, ibmsg,
1521                                     offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1522                                     payload_niov, payload_kiov,
1523                                     payload_offset, payload_nob);
1524         else
1525                 lnet_copy_iov2flat(IBLND_MSG_SIZE, ibmsg,
1526                                    offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1527                                    payload_niov, payload_iov,
1528                                    payload_offset, payload_nob);
1529
1530         nob = offsetof(kib_immediate_msg_t, ibim_payload[payload_nob]);
1531         kiblnd_init_tx_msg(ni, tx, IBLND_MSG_IMMEDIATE, nob);
1532
1533         tx->tx_lntmsg[0] = lntmsg;              /* finalise lntmsg on completion */
1534         kiblnd_launch_tx(ni, tx, target.nid);
1535         return 0;
1536 }
1537
1538 void
1539 kiblnd_reply (lnet_ni_t *ni, kib_rx_t *rx, lnet_msg_t *lntmsg)
1540 {
1541         lnet_process_id_t target = lntmsg->msg_target;
1542         unsigned int      niov = lntmsg->msg_niov;
1543         struct iovec     *iov = lntmsg->msg_iov;
1544         lnet_kiov_t      *kiov = lntmsg->msg_kiov;
1545         unsigned int      offset = lntmsg->msg_offset;
1546         unsigned int      nob = lntmsg->msg_len;
1547         kib_tx_t         *tx;
1548         int               rc;
1549
1550         tx = kiblnd_get_idle_tx(ni);
1551         if (tx == NULL) {
1552                 CERROR("Can't get tx for REPLY to %s\n",
1553                        libcfs_nid2str(target.nid));
1554                 goto failed_0;
1555         }
1556
1557         if (nob == 0)
1558                 rc = 0;
1559         else if (kiov == NULL)
1560                 rc = kiblnd_setup_rd_iov(ni, tx, tx->tx_rd,
1561                                          niov, iov, offset, nob);
1562         else
1563                 rc = kiblnd_setup_rd_kiov(ni, tx, tx->tx_rd,
1564                                           niov, kiov, offset, nob);
1565
1566         if (rc != 0) {
1567                 CERROR("Can't setup GET src for %s: %d\n",
1568                        libcfs_nid2str(target.nid), rc);
1569                 goto failed_1;
1570         }
1571
1572         rc = kiblnd_init_rdma(rx->rx_conn, tx,
1573                               IBLND_MSG_GET_DONE, nob,
1574                               &rx->rx_msg->ibm_u.get.ibgm_rd,
1575                               rx->rx_msg->ibm_u.get.ibgm_cookie);
1576         if (rc < 0) {
1577                 CERROR("Can't setup rdma for GET from %s: %d\n",
1578                        libcfs_nid2str(target.nid), rc);
1579                 goto failed_1;
1580         }
1581         
1582         if (nob == 0) {
1583                 /* No RDMA: local completion may happen now! */
1584                 lnet_finalize(ni, lntmsg, 0);
1585         } else {
1586                 /* RDMA: lnet_finalize(lntmsg) when it
1587                  * completes */
1588                 tx->tx_lntmsg[0] = lntmsg;
1589         }
1590
1591         kiblnd_queue_tx(tx, rx->rx_conn);
1592         return;
1593
1594  failed_1:
1595         kiblnd_tx_done(ni, tx);
1596  failed_0:
1597         lnet_finalize(ni, lntmsg, -EIO);
1598 }
1599
1600 int
1601 kiblnd_recv (lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg, int delayed,
1602              unsigned int niov, struct iovec *iov, lnet_kiov_t *kiov,
1603              unsigned int offset, unsigned int mlen, unsigned int rlen)
1604 {
1605         kib_rx_t    *rx = private;
1606         kib_msg_t   *rxmsg = rx->rx_msg;
1607         kib_conn_t  *conn = rx->rx_conn;
1608         kib_tx_t    *tx;
1609         kib_msg_t   *txmsg;
1610         int          nob;
1611         int          post_credit = IBLND_POSTRX_PEER_CREDIT;
1612         int          rc = 0;
1613
1614         LASSERT (mlen <= rlen);
1615         LASSERT (!cfs_in_interrupt());
1616         /* Either all pages or all vaddrs */
1617         LASSERT (!(kiov != NULL && iov != NULL));
1618
1619         switch (rxmsg->ibm_type) {
1620         default:
1621                 LBUG();
1622
1623         case IBLND_MSG_IMMEDIATE:
1624                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[rlen]);
1625                 if (nob > rx->rx_nob) {
1626                         CERROR ("Immediate message from %s too big: %d(%d)\n",
1627                                 libcfs_nid2str(rxmsg->ibm_u.immediate.ibim_hdr.src_nid),
1628                                 nob, rx->rx_nob);
1629                         rc = -EPROTO;
1630                         break;
1631                 }
1632
1633                 if (kiov != NULL)
1634                         lnet_copy_flat2kiov(niov, kiov, offset,
1635                                             IBLND_MSG_SIZE, rxmsg,
1636                                             offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1637                                             mlen);
1638                 else
1639                         lnet_copy_flat2iov(niov, iov, offset,
1640                                            IBLND_MSG_SIZE, rxmsg,
1641                                            offsetof(kib_msg_t, ibm_u.immediate.ibim_payload),
1642                                            mlen);
1643                 lnet_finalize (ni, lntmsg, 0);
1644                 break;
1645
1646         case IBLND_MSG_PUT_REQ:
1647                 if (mlen == 0) {
1648                         lnet_finalize(ni, lntmsg, 0);
1649                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK, 0,
1650                                                rxmsg->ibm_u.putreq.ibprm_cookie);
1651                         break;
1652                 }
1653
1654                 tx = kiblnd_get_idle_tx(ni);
1655                 if (tx == NULL) {
1656                         CERROR("Can't allocate tx for %s\n",
1657                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
1658                         /* Not replying will break the connection */
1659                         rc = -ENOMEM;
1660                         break;
1661                 }
1662
1663                 txmsg = tx->tx_msg;
1664                 if (kiov == NULL)
1665                         rc = kiblnd_setup_rd_iov(ni, tx,
1666                                                  &txmsg->ibm_u.putack.ibpam_rd,
1667                                                  niov, iov, offset, mlen);
1668                 else
1669                         rc = kiblnd_setup_rd_kiov(ni, tx,
1670                                                   &txmsg->ibm_u.putack.ibpam_rd,
1671                                                   niov, kiov, offset, mlen);
1672                 if (rc != 0) {
1673                         CERROR("Can't setup PUT sink for %s: %d\n",
1674                                libcfs_nid2str(conn->ibc_peer->ibp_nid), rc);
1675                         kiblnd_tx_done(ni, tx);
1676                         /* tell peer it's over */
1677                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_PUT_NAK, rc,
1678                                                rxmsg->ibm_u.putreq.ibprm_cookie);
1679                         break;
1680                 }
1681
1682                 nob = offsetof(kib_putack_msg_t, ibpam_rd.rd_frags[tx->tx_nfrags]);
1683                 txmsg->ibm_u.putack.ibpam_src_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1684                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1685
1686                 kiblnd_init_tx_msg(ni, tx, IBLND_MSG_PUT_ACK, nob);
1687
1688                 tx->tx_lntmsg[0] = lntmsg;      /* finalise lntmsg on completion */
1689                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1690                 kiblnd_queue_tx(tx, conn);
1691
1692                 /* reposted buffer reserved for PUT_DONE */
1693                 post_credit = IBLND_POSTRX_NO_CREDIT;
1694                 break;
1695
1696         case IBLND_MSG_GET_REQ:
1697                 if (lntmsg != NULL) {
1698                         /* Optimized GET; RDMA lntmsg's payload */
1699                         kiblnd_reply(ni, rx, lntmsg);
1700                 } else {
1701                         /* GET didn't match anything */
1702                         kiblnd_send_completion(rx->rx_conn, IBLND_MSG_GET_DONE,
1703                                                -ENODATA,
1704                                                rxmsg->ibm_u.get.ibgm_cookie);
1705                 }
1706                 break;
1707         }
1708
1709         kiblnd_post_rx(rx, post_credit);
1710         return rc;
1711 }
1712
1713 int
1714 kiblnd_thread_start (int (*fn)(void *arg), void *arg)
1715 {
1716         long    pid = cfs_kernel_thread (fn, arg, 0);
1717
1718         if (pid < 0)
1719                 return ((int)pid);
1720
1721         cfs_atomic_inc (&kiblnd_data.kib_nthreads);
1722         return (0);
1723 }
1724
1725 void
1726 kiblnd_thread_fini (void)
1727 {
1728         cfs_atomic_dec (&kiblnd_data.kib_nthreads);
1729 }
1730
1731 void
1732 kiblnd_peer_alive (kib_peer_t *peer)
1733 {
1734         /* This is racy, but everyone's only writing cfs_time_current() */
1735         peer->ibp_last_alive = cfs_time_current();
1736         cfs_mb();
1737 }
1738
1739 void
1740 kiblnd_peer_notify (kib_peer_t *peer)
1741 {
1742         int           error = 0;
1743         cfs_time_t    last_alive = 0;
1744         unsigned long flags;
1745
1746         cfs_read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1747
1748         if (cfs_list_empty(&peer->ibp_conns) &&
1749             peer->ibp_accepting == 0 &&
1750             peer->ibp_connecting == 0 &&
1751             peer->ibp_error != 0) {
1752                 error = peer->ibp_error;
1753                 peer->ibp_error = 0;
1754
1755                 last_alive = peer->ibp_last_alive;
1756         }
1757
1758         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1759
1760         if (error != 0)
1761                 lnet_notify(peer->ibp_ni,
1762                             peer->ibp_nid, 0, last_alive);
1763 }
1764
1765 void
1766 kiblnd_close_conn_locked (kib_conn_t *conn, int error)
1767 {
1768         /* This just does the immediate housekeeping.  'error' is zero for a
1769          * normal shutdown which can happen only after the connection has been
1770          * established.  If the connection is established, schedule the
1771          * connection to be finished off by the connd.  Otherwise the connd is
1772          * already dealing with it (either to set it up or tear it down).
1773          * Caller holds kib_global_lock exclusively in irq context */
1774         unsigned long     flags;
1775         kib_peer_t       *peer = conn->ibc_peer;
1776
1777         LASSERT (error != 0 || conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1778
1779         if (error != 0 && conn->ibc_comms_error == 0)
1780                 conn->ibc_comms_error = error;
1781
1782         if (conn->ibc_state != IBLND_CONN_ESTABLISHED)
1783                 return; /* already being handled  */
1784
1785         if (error == 0 &&
1786             cfs_list_empty(&conn->ibc_tx_queue) &&
1787             cfs_list_empty(&conn->ibc_tx_queue_rsrvd) &&
1788             cfs_list_empty(&conn->ibc_tx_queue_nocred) &&
1789             cfs_list_empty(&conn->ibc_active_txs)) {
1790                 CDEBUG(D_NET, "closing conn to %s\n", 
1791                        libcfs_nid2str(peer->ibp_nid));
1792         } else {
1793                 CDEBUG(D_NETERROR, "Closing conn to %s: error %d%s%s%s%s\n",
1794                        libcfs_nid2str(peer->ibp_nid), error,
1795                        cfs_list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
1796                        cfs_list_empty(&conn->ibc_tx_queue_rsrvd) ? "" : "(sending_rsrvd)",
1797                        cfs_list_empty(&conn->ibc_tx_queue_nocred) ? "" : "(sending_nocred)",
1798                        cfs_list_empty(&conn->ibc_active_txs) ? "" : "(waiting)");
1799         }
1800
1801         cfs_list_del(&conn->ibc_list);
1802         /* connd (see below) takes over ibc_list's ref */
1803
1804         if (cfs_list_empty (&peer->ibp_conns) &&    /* no more conns */
1805             kiblnd_peer_active(peer)) {         /* still in peer table */
1806                 kiblnd_unlink_peer_locked(peer);
1807
1808                 /* set/clear error on last conn */
1809                 peer->ibp_error = conn->ibc_comms_error;
1810         }
1811
1812         kiblnd_set_conn_state(conn, IBLND_CONN_CLOSING);
1813
1814         cfs_spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
1815
1816         cfs_list_add_tail (&conn->ibc_list, &kiblnd_data.kib_connd_conns);
1817         cfs_waitq_signal (&kiblnd_data.kib_connd_waitq);
1818
1819         cfs_spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
1820 }
1821
1822 void
1823 kiblnd_close_conn (kib_conn_t *conn, int error)
1824 {
1825         unsigned long flags;
1826
1827         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1828
1829         kiblnd_close_conn_locked(conn, error);
1830
1831         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1832 }
1833
1834 void
1835 kiblnd_handle_early_rxs(kib_conn_t *conn)
1836 {
1837         unsigned long    flags;
1838         kib_rx_t        *rx;
1839
1840         LASSERT (!cfs_in_interrupt());
1841         LASSERT (conn->ibc_state >= IBLND_CONN_ESTABLISHED);
1842
1843         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1844         while (!cfs_list_empty(&conn->ibc_early_rxs)) {
1845                 rx = cfs_list_entry(conn->ibc_early_rxs.next,
1846                                 kib_rx_t, rx_list);
1847                 cfs_list_del(&rx->rx_list);
1848                 cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
1849                                             flags);
1850
1851                 kiblnd_handle_rx(rx);
1852
1853                 cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1854         }
1855         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1856 }
1857
1858 void
1859 kiblnd_abort_txs(kib_conn_t *conn, cfs_list_t *txs)
1860 {
1861         CFS_LIST_HEAD       (zombies);
1862         cfs_list_t          *tmp;
1863         cfs_list_t          *nxt;
1864         kib_tx_t            *tx;
1865
1866         cfs_spin_lock(&conn->ibc_lock);
1867
1868         cfs_list_for_each_safe (tmp, nxt, txs) {
1869                 tx = cfs_list_entry (tmp, kib_tx_t, tx_list);
1870
1871                 if (txs == &conn->ibc_active_txs) {
1872                         LASSERT (!tx->tx_queued);
1873                         LASSERT (tx->tx_waiting ||
1874                                  tx->tx_sending != 0);
1875                 } else {
1876                         LASSERT (tx->tx_queued);
1877                 }
1878
1879                 tx->tx_status = -ECONNABORTED;
1880                 tx->tx_waiting = 0;
1881
1882                 if (tx->tx_sending == 0) {
1883                         tx->tx_queued = 0;
1884                         cfs_list_del (&tx->tx_list);
1885                         cfs_list_add (&tx->tx_list, &zombies);
1886                 }
1887         }
1888
1889         cfs_spin_unlock(&conn->ibc_lock);
1890
1891         kiblnd_txlist_done(conn->ibc_peer->ibp_ni,
1892                            &zombies, -ECONNABORTED);
1893 }
1894
1895 void
1896 kiblnd_finalise_conn (kib_conn_t *conn)
1897 {
1898         LASSERT (!cfs_in_interrupt());
1899         LASSERT (conn->ibc_state > IBLND_CONN_INIT);
1900
1901         kiblnd_set_conn_state(conn, IBLND_CONN_DISCONNECTED);
1902
1903         /* abort_receives moves QP state to IB_QPS_ERR.  This is only required
1904          * for connections that didn't get as far as being connected, because
1905          * rdma_disconnect() does this for free. */
1906         kiblnd_abort_receives(conn);
1907
1908         /* Complete all tx descs not waiting for sends to complete.
1909          * NB we should be safe from RDMA now that the QP has changed state */
1910
1911         kiblnd_abort_txs(conn, &conn->ibc_tx_queue);
1912         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_rsrvd);
1913         kiblnd_abort_txs(conn, &conn->ibc_tx_queue_nocred);
1914         kiblnd_abort_txs(conn, &conn->ibc_active_txs);
1915
1916         kiblnd_handle_early_rxs(conn);
1917 }
1918
1919 void
1920 kiblnd_peer_connect_failed (kib_peer_t *peer, int active, int error)
1921 {
1922         CFS_LIST_HEAD    (zombies);
1923         unsigned long     flags;
1924
1925         LASSERT (error != 0);
1926         LASSERT (!cfs_in_interrupt());
1927
1928         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1929
1930         if (active) {
1931                 LASSERT (peer->ibp_connecting > 0);
1932                 peer->ibp_connecting--;
1933         } else {
1934                 LASSERT (peer->ibp_accepting > 0);
1935                 peer->ibp_accepting--;
1936         }
1937
1938         if (peer->ibp_connecting != 0 ||
1939             peer->ibp_accepting != 0) {
1940                 /* another connection attempt under way... */
1941                 cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
1942                                             flags);
1943                 return;
1944         }
1945
1946         if (cfs_list_empty(&peer->ibp_conns)) {
1947                 /* Take peer's blocked transmits to complete with error */
1948                 cfs_list_add(&zombies, &peer->ibp_tx_queue);
1949                 cfs_list_del_init(&peer->ibp_tx_queue);
1950
1951                 if (kiblnd_peer_active(peer))
1952                         kiblnd_unlink_peer_locked(peer);
1953
1954                 peer->ibp_error = error;
1955         } else {
1956                 /* Can't have blocked transmits if there are connections */
1957                 LASSERT (cfs_list_empty(&peer->ibp_tx_queue));
1958         }
1959
1960         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1961
1962         kiblnd_peer_notify(peer);
1963
1964         if (cfs_list_empty (&zombies))
1965                 return;
1966
1967         CDEBUG (D_NETERROR, "Deleting messages for %s: connection failed\n",
1968                 libcfs_nid2str(peer->ibp_nid));
1969
1970         kiblnd_txlist_done(peer->ibp_ni, &zombies, -EHOSTUNREACH);
1971 }
1972
1973 void
1974 kiblnd_connreq_done(kib_conn_t *conn, int status)
1975 {
1976         kib_peer_t        *peer = conn->ibc_peer;
1977         kib_tx_t          *tx;
1978         cfs_list_t         txs;
1979         unsigned long      flags;
1980         int                active;
1981
1982         active = (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
1983
1984         CDEBUG(D_NET,"%s: active(%d), version(%x), status(%d)\n",
1985                libcfs_nid2str(peer->ibp_nid), active,
1986                conn->ibc_version, status);
1987
1988         LASSERT (!cfs_in_interrupt());
1989         LASSERT ((conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT &&
1990                   peer->ibp_connecting > 0) ||
1991                  (conn->ibc_state == IBLND_CONN_PASSIVE_WAIT &&
1992                   peer->ibp_accepting > 0));
1993
1994         LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
1995         conn->ibc_connvars = NULL;
1996
1997         if (status != 0) {
1998                 /* failed to establish connection */
1999                 kiblnd_peer_connect_failed(peer, active, status);
2000                 kiblnd_finalise_conn(conn);
2001                 return;
2002         }
2003
2004         /* connection established */
2005         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2006
2007         conn->ibc_last_send = jiffies;
2008         kiblnd_set_conn_state(conn, IBLND_CONN_ESTABLISHED);
2009         kiblnd_peer_alive(peer);
2010
2011         /* Add conn to peer's list and nuke any dangling conns from a different
2012          * peer instance... */
2013         kiblnd_conn_addref(conn);               /* +1 ref for ibc_list */
2014         cfs_list_add(&conn->ibc_list, &peer->ibp_conns);
2015         if (active)
2016                 peer->ibp_connecting--;
2017         else
2018                 peer->ibp_accepting--;
2019
2020         if (peer->ibp_version == 0) {
2021                 peer->ibp_version     = conn->ibc_version;
2022                 peer->ibp_incarnation = conn->ibc_incarnation;
2023         }
2024
2025         if (peer->ibp_version     != conn->ibc_version ||
2026             peer->ibp_incarnation != conn->ibc_incarnation) {
2027                 kiblnd_close_stale_conns_locked(peer, conn->ibc_version,
2028                                                 conn->ibc_incarnation);
2029                 peer->ibp_version     = conn->ibc_version;
2030                 peer->ibp_incarnation = conn->ibc_incarnation;
2031         }
2032
2033         /* grab pending txs while I have the lock */
2034         cfs_list_add(&txs, &peer->ibp_tx_queue);
2035         cfs_list_del_init(&peer->ibp_tx_queue);
2036
2037         if (!kiblnd_peer_active(peer) ||        /* peer has been deleted */
2038             conn->ibc_comms_error != 0) {       /* error has happened already */
2039                 lnet_ni_t *ni = peer->ibp_ni;
2040
2041                 /* start to shut down connection */
2042                 kiblnd_close_conn_locked(conn, -ECONNABORTED);
2043                 cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2044                                             flags);
2045
2046                 kiblnd_txlist_done(ni, &txs, -ECONNABORTED);
2047
2048                 return;
2049         }
2050
2051         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2052
2053         /* Schedule blocked txs */
2054         cfs_spin_lock (&conn->ibc_lock);
2055         while (!cfs_list_empty (&txs)) {
2056                 tx = cfs_list_entry (txs.next, kib_tx_t, tx_list);
2057                 cfs_list_del(&tx->tx_list);
2058
2059                 kiblnd_queue_tx_locked(tx, conn);
2060         }
2061         cfs_spin_unlock (&conn->ibc_lock);
2062
2063         kiblnd_check_sends(conn);
2064
2065         /* schedule blocked rxs */
2066         kiblnd_handle_early_rxs(conn);
2067 }
2068
2069 void
2070 kiblnd_reject(struct rdma_cm_id *cmid, kib_rej_t *rej)
2071 {
2072         int          rc;
2073
2074         rc = rdma_reject(cmid, rej, sizeof(*rej));
2075
2076         if (rc != 0)
2077                 CWARN("Error %d sending reject\n", rc);
2078 }
2079
2080 int
2081 kiblnd_passive_connect (struct rdma_cm_id *cmid, void *priv, int priv_nob)
2082 {
2083         cfs_rwlock_t          *g_lock = &kiblnd_data.kib_global_lock;
2084         kib_msg_t             *reqmsg = priv;
2085         kib_msg_t             *ackmsg;
2086         kib_dev_t             *ibdev;
2087         kib_peer_t            *peer;
2088         kib_peer_t            *peer2;
2089         kib_conn_t            *conn;
2090         lnet_ni_t             *ni  = NULL;
2091         kib_net_t             *net = NULL;
2092         lnet_nid_t             nid;
2093         struct rdma_conn_param cp;
2094         kib_rej_t              rej;
2095         int                    version = IBLND_MSG_VERSION;
2096         unsigned long          flags;
2097         int                    rc;
2098
2099         LASSERT (!cfs_in_interrupt());
2100
2101         /* cmid inherits 'context' from the corresponding listener id */
2102         ibdev = (kib_dev_t *)cmid->context;
2103         LASSERT (ibdev != NULL);
2104
2105         memset(&rej, 0, sizeof(rej));
2106         rej.ibr_magic                = IBLND_MSG_MAGIC;
2107         rej.ibr_why                  = IBLND_REJECT_FATAL;
2108         rej.ibr_cp.ibcp_max_msg_size = IBLND_MSG_SIZE;
2109
2110         if (priv_nob < offsetof(kib_msg_t, ibm_type)) {
2111                 CERROR("Short connection request\n");
2112                 goto failed;
2113         }
2114
2115         /* Future protocol version compatibility support!  If the
2116          * o2iblnd-specific protocol changes, or when LNET unifies
2117          * protocols over all LNDs, the initial connection will
2118          * negotiate a protocol version.  I trap this here to avoid
2119          * console errors; the reject tells the peer which protocol I
2120          * speak. */
2121         if (reqmsg->ibm_magic == LNET_PROTO_MAGIC ||
2122             reqmsg->ibm_magic == __swab32(LNET_PROTO_MAGIC))
2123                 goto failed;
2124         if (reqmsg->ibm_magic == IBLND_MSG_MAGIC &&
2125             reqmsg->ibm_version != IBLND_MSG_VERSION &&
2126             reqmsg->ibm_version != IBLND_MSG_VERSION_1)
2127                 goto failed;
2128         if (reqmsg->ibm_magic == __swab32(IBLND_MSG_MAGIC) &&
2129             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION) &&
2130             reqmsg->ibm_version != __swab16(IBLND_MSG_VERSION_1))
2131                 goto failed;
2132
2133         rc = kiblnd_unpack_msg(reqmsg, priv_nob);
2134         if (rc != 0) {
2135                 CERROR("Can't parse connection request: %d\n", rc);
2136                 goto failed;
2137         }
2138
2139         nid = reqmsg->ibm_srcnid;
2140         ni  = lnet_net2ni(LNET_NIDNET(reqmsg->ibm_dstnid));
2141
2142         if (ni != NULL) {
2143                 net = (kib_net_t *)ni->ni_data;
2144                 rej.ibr_incarnation = net->ibn_incarnation;
2145         }
2146
2147         if (ni == NULL ||                         /* no matching net */
2148             ni->ni_nid != reqmsg->ibm_dstnid ||   /* right NET, wrong NID! */
2149             net->ibn_dev != ibdev) {              /* wrong device */
2150                 CERROR("Can't accept %s on %s (%s:%d:%u.%u.%u.%u): "
2151                        "bad dst nid %s\n", libcfs_nid2str(nid),
2152                        ni == NULL ? "NA" : libcfs_nid2str(ni->ni_nid),
2153                        ibdev->ibd_ifname, ibdev->ibd_nnets,
2154                        HIPQUAD(ibdev->ibd_ifip),
2155                        libcfs_nid2str(reqmsg->ibm_dstnid));
2156
2157                 goto failed;
2158         }
2159
2160        /* check time stamp as soon as possible */
2161         if (reqmsg->ibm_dststamp != 0 &&
2162             reqmsg->ibm_dststamp != net->ibn_incarnation) {
2163                 CWARN("Stale connection request\n");
2164                 rej.ibr_why = IBLND_REJECT_CONN_STALE;
2165                 goto failed;
2166         }
2167
2168         /* I can accept peer's version */
2169         version = reqmsg->ibm_version;
2170
2171         if (reqmsg->ibm_type != IBLND_MSG_CONNREQ) {
2172                 CERROR("Unexpected connreq msg type: %x from %s\n",
2173                        reqmsg->ibm_type, libcfs_nid2str(nid));
2174                 goto failed;
2175         }
2176
2177         if (reqmsg->ibm_u.connparams.ibcp_queue_depth !=
2178             IBLND_MSG_QUEUE_SIZE(version)) {
2179                 CERROR("Can't accept %s: incompatible queue depth %d (%d wanted)\n",
2180                        libcfs_nid2str(nid), reqmsg->ibm_u.connparams.ibcp_queue_depth,
2181                        IBLND_MSG_QUEUE_SIZE(version));
2182
2183                 if (version == IBLND_MSG_VERSION)
2184                         rej.ibr_why = IBLND_REJECT_MSG_QUEUE_SIZE;
2185
2186                 goto failed;
2187         }
2188
2189         if (reqmsg->ibm_u.connparams.ibcp_max_frags !=
2190             IBLND_RDMA_FRAGS(version)) {
2191                 CERROR("Can't accept %s(version %x): "
2192                        "incompatible max_frags %d (%d wanted)\n",
2193                        libcfs_nid2str(nid), version,
2194                        reqmsg->ibm_u.connparams.ibcp_max_frags,
2195                        IBLND_RDMA_FRAGS(version));
2196
2197                 if (version == IBLND_MSG_VERSION)
2198                         rej.ibr_why = IBLND_REJECT_RDMA_FRAGS;
2199
2200                 goto failed;
2201
2202         }
2203
2204         if (reqmsg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2205                 CERROR("Can't accept %s: message size %d too big (%d max)\n",
2206                        libcfs_nid2str(nid),
2207                        reqmsg->ibm_u.connparams.ibcp_max_msg_size,
2208                        IBLND_MSG_SIZE);
2209                 goto failed;
2210         }
2211
2212         /* assume 'nid' is a new peer; create  */
2213         rc = kiblnd_create_peer(ni, &peer, nid);
2214         if (rc != 0) {
2215                 CERROR("Can't create peer for %s\n", libcfs_nid2str(nid));
2216                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2217                 goto failed;
2218         }
2219
2220         cfs_write_lock_irqsave(g_lock, flags);
2221
2222         peer2 = kiblnd_find_peer_locked(nid);
2223         if (peer2 != NULL) {
2224                 if (peer2->ibp_version == 0) {
2225                         peer2->ibp_version     = version;
2226                         peer2->ibp_incarnation = reqmsg->ibm_srcstamp;
2227                 }
2228
2229                 /* not the guy I've talked with */
2230                 if (peer2->ibp_incarnation != reqmsg->ibm_srcstamp ||
2231                     peer2->ibp_version     != version) {
2232                         kiblnd_close_peer_conns_locked(peer2, -ESTALE);
2233                         cfs_write_unlock_irqrestore(g_lock, flags);
2234
2235                         CWARN("Conn stale %s [old ver: %x, new ver: %x]\n",
2236                               libcfs_nid2str(nid), peer2->ibp_version, version);
2237
2238                         kiblnd_peer_decref(peer);
2239                         rej.ibr_why = IBLND_REJECT_CONN_STALE;
2240                         goto failed;
2241                 }
2242
2243                 /* tie-break connection race in favour of the higher NID */
2244                 if (peer2->ibp_connecting != 0 &&
2245                     nid < ni->ni_nid) {
2246                         cfs_write_unlock_irqrestore(g_lock, flags);
2247
2248                         CWARN("Conn race %s\n", libcfs_nid2str(peer2->ibp_nid));
2249
2250                         kiblnd_peer_decref(peer);
2251                         rej.ibr_why = IBLND_REJECT_CONN_RACE;
2252                         goto failed;
2253                 }
2254
2255                 peer2->ibp_accepting++;
2256                 kiblnd_peer_addref(peer2);
2257
2258                 cfs_write_unlock_irqrestore(g_lock, flags);
2259                 kiblnd_peer_decref(peer);
2260                 peer = peer2;
2261         } else {
2262                 /* Brand new peer */
2263                 LASSERT (peer->ibp_accepting == 0);
2264                 LASSERT (peer->ibp_version == 0 &&
2265                          peer->ibp_incarnation == 0);
2266
2267                 peer->ibp_accepting   = 1;
2268                 peer->ibp_version     = version;
2269                 peer->ibp_incarnation = reqmsg->ibm_srcstamp;
2270
2271                 /* I have a ref on ni that prevents it being shutdown */
2272                 LASSERT (net->ibn_shutdown == 0);
2273
2274                 kiblnd_peer_addref(peer);
2275                 cfs_list_add_tail(&peer->ibp_list, kiblnd_nid2peerlist(nid));
2276
2277                 cfs_write_unlock_irqrestore(g_lock, flags);
2278         }
2279
2280         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_PASSIVE_WAIT, version);
2281         if (conn == NULL) {
2282                 kiblnd_peer_connect_failed(peer, 0, -ENOMEM);
2283                 kiblnd_peer_decref(peer);
2284                 rej.ibr_why = IBLND_REJECT_NO_RESOURCES;
2285                 goto failed;
2286         }
2287
2288         /* conn now "owns" cmid, so I return success from here on to ensure the
2289          * CM callback doesn't destroy cmid. */
2290
2291         conn->ibc_incarnation      = reqmsg->ibm_srcstamp;
2292         conn->ibc_credits          = IBLND_MSG_QUEUE_SIZE(version);
2293         conn->ibc_reserved_credits = IBLND_MSG_QUEUE_SIZE(version);
2294         LASSERT (conn->ibc_credits + conn->ibc_reserved_credits + IBLND_OOB_MSGS(version)
2295                  <= IBLND_RX_MSGS(version));
2296
2297         ackmsg = &conn->ibc_connvars->cv_msg;
2298         memset(ackmsg, 0, sizeof(*ackmsg));
2299
2300         kiblnd_init_msg(ackmsg, IBLND_MSG_CONNACK,
2301                         sizeof(ackmsg->ibm_u.connparams));
2302         ackmsg->ibm_u.connparams.ibcp_queue_depth  = IBLND_MSG_QUEUE_SIZE(version);
2303         ackmsg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2304         ackmsg->ibm_u.connparams.ibcp_max_frags    = IBLND_RDMA_FRAGS(version);
2305
2306         kiblnd_pack_msg(ni, ackmsg, version, 0, nid, reqmsg->ibm_srcstamp);
2307
2308         memset(&cp, 0, sizeof(cp));
2309         cp.private_data        = ackmsg;
2310         cp.private_data_len    = ackmsg->ibm_nob;
2311         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2312         cp.initiator_depth     = 0;
2313         cp.flow_control        = 1;
2314         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2315         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2316
2317         CDEBUG(D_NET, "Accept %s\n", libcfs_nid2str(nid));
2318
2319         rc = rdma_accept(cmid, &cp);
2320         if (rc != 0) {
2321                 CERROR("Can't accept %s: %d\n", libcfs_nid2str(nid), rc);
2322                 rej.ibr_version = version;
2323                 rej.ibr_why     = IBLND_REJECT_FATAL;
2324
2325                 kiblnd_reject(cmid, &rej);
2326                 kiblnd_connreq_done(conn, rc);
2327                 kiblnd_conn_decref(conn);
2328         }
2329
2330         lnet_ni_decref(ni);
2331         return 0;
2332
2333  failed:
2334         if (ni != NULL)
2335                 lnet_ni_decref(ni);
2336
2337         rej.ibr_version = version;
2338         rej.ibr_cp.ibcp_queue_depth = IBLND_MSG_QUEUE_SIZE(version);
2339         rej.ibr_cp.ibcp_max_frags   = IBLND_RDMA_FRAGS(version);
2340         kiblnd_reject(cmid, &rej);
2341
2342         return -ECONNREFUSED;
2343 }
2344
2345 void
2346 kiblnd_reconnect (kib_conn_t *conn, int version,
2347                   __u64 incarnation, int why, kib_connparams_t *cp)
2348 {
2349         kib_peer_t    *peer = conn->ibc_peer;
2350         char          *reason;
2351         int            retry = 0;
2352         unsigned long  flags;
2353
2354         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2355         LASSERT (peer->ibp_connecting > 0);     /* 'conn' at least */
2356
2357         cfs_write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2358
2359         /* retry connection if it's still needed and no other connection
2360          * attempts (active or passive) are in progress
2361          * NB: reconnect is still needed even when ibp_tx_queue is
2362          * empty if ibp_version != version because reconnect may be
2363          * initiated by kiblnd_query() */
2364         if ((!cfs_list_empty(&peer->ibp_tx_queue) ||
2365              peer->ibp_version != version) &&
2366             peer->ibp_connecting == 1 &&
2367             peer->ibp_accepting == 0) {
2368                 retry = 1;
2369                 peer->ibp_connecting++;
2370
2371                 peer->ibp_version     = version;
2372                 peer->ibp_incarnation = incarnation;
2373         }
2374
2375         cfs_write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2376
2377         if (!retry)
2378                 return;
2379
2380         switch (why) {
2381         default:
2382                 reason = "Unknown";
2383                 break;
2384
2385         case IBLND_REJECT_CONN_STALE:
2386                 reason = "stale";
2387                 break;
2388
2389         case IBLND_REJECT_CONN_RACE:
2390                 reason = "conn race";
2391                 break;
2392
2393         case IBLND_REJECT_CONN_UNCOMPAT:
2394                 reason = "version negotiation";
2395                 break;
2396         }
2397
2398         CDEBUG(D_NETERROR, "%s: retrying (%s), %x, %x, "
2399                            "queue_dep: %d, max_frag: %d, msg_size: %d\n",
2400                libcfs_nid2str(peer->ibp_nid),
2401                reason, IBLND_MSG_VERSION, version,
2402                cp != NULL ? cp->ibcp_queue_depth : IBLND_MSG_QUEUE_SIZE(version),
2403                cp != NULL ? cp->ibcp_max_frags   : IBLND_RDMA_FRAGS(version),
2404                cp != NULL ? cp->ibcp_max_msg_size: IBLND_MSG_SIZE);
2405
2406         kiblnd_connect_peer(peer);
2407 }
2408
2409 void
2410 kiblnd_rejected (kib_conn_t *conn, int reason, void *priv, int priv_nob)
2411 {
2412         kib_peer_t    *peer = conn->ibc_peer;
2413
2414         LASSERT (!cfs_in_interrupt());
2415         LASSERT (conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT);
2416
2417         switch (reason) {
2418         case IB_CM_REJ_STALE_CONN:
2419                 kiblnd_reconnect(conn, IBLND_MSG_VERSION, 0,
2420                                  IBLND_REJECT_CONN_STALE, NULL);
2421                 break;
2422
2423         case IB_CM_REJ_INVALID_SERVICE_ID:
2424                 CDEBUG(D_NETERROR, "%s rejected: no listener at %d\n",
2425                        libcfs_nid2str(peer->ibp_nid),
2426                        *kiblnd_tunables.kib_service);
2427                 break;
2428
2429         case IB_CM_REJ_CONSUMER_DEFINED:
2430                 if (priv_nob >= offsetof(kib_rej_t, ibr_padding)) {
2431                         kib_rej_t        *rej         = priv;
2432                         kib_connparams_t *cp          = NULL;
2433                         int               flip        = 0;
2434                         __u64             incarnation = -1;
2435
2436                         /* NB. default incarnation is -1 because:
2437                          * a) V1 will ignore dst incarnation in connreq.
2438                          * b) V2 will provide incarnation while rejecting me,
2439                          *    -1 will be overwrote.
2440                          *
2441                          * if I try to connect to a V1 peer with V2 protocol,
2442                          * it rejected me then upgrade to V2, I have no idea
2443                          * about the upgrading and try to reconnect with V1,
2444                          * in this case upgraded V2 can find out I'm trying to
2445                          * talk to the old guy and reject me(incarnation is -1). 
2446                          */
2447
2448                         if (rej->ibr_magic == __swab32(IBLND_MSG_MAGIC) ||
2449                             rej->ibr_magic == __swab32(LNET_PROTO_MAGIC)) {
2450                                 __swab32s(&rej->ibr_magic);
2451                                 __swab16s(&rej->ibr_version);
2452                                 flip = 1;
2453                         }
2454
2455                         if (priv_nob >= sizeof(kib_rej_t) &&
2456                             rej->ibr_version > IBLND_MSG_VERSION_1) {
2457                                 /* priv_nob is always 148 in current version
2458                                  * of OFED, so we still need to check version.
2459                                  * (define of IB_CM_REJ_PRIVATE_DATA_SIZE) */
2460                                 cp = &rej->ibr_cp;
2461
2462                                 if (flip) {
2463                                         __swab64s(&rej->ibr_incarnation);
2464                                         __swab16s(&cp->ibcp_queue_depth);
2465                                         __swab16s(&cp->ibcp_max_frags);
2466                                         __swab32s(&cp->ibcp_max_msg_size);
2467                                 }
2468
2469                                 incarnation = rej->ibr_incarnation;
2470                         }
2471
2472                         if (rej->ibr_magic != IBLND_MSG_MAGIC &&
2473                             rej->ibr_magic != LNET_PROTO_MAGIC) {
2474                                 CERROR("%s rejected: consumer defined fatal error\n",
2475                                        libcfs_nid2str(peer->ibp_nid));
2476                                 break;
2477                         }
2478
2479                         if (rej->ibr_version != IBLND_MSG_VERSION &&
2480                             rej->ibr_version != IBLND_MSG_VERSION_1) {
2481                                 CERROR("%s rejected: o2iblnd version %x error\n",
2482                                        libcfs_nid2str(peer->ibp_nid),
2483                                        rej->ibr_version);
2484                                 break;
2485                         }
2486
2487                         if (rej->ibr_why     == IBLND_REJECT_FATAL &&
2488                             rej->ibr_version == IBLND_MSG_VERSION_1) {
2489                                 CDEBUG(D_NET, "rejected by old version peer %s: %x\n",
2490                                        libcfs_nid2str(peer->ibp_nid), rej->ibr_version);
2491
2492                                 if (conn->ibc_version != IBLND_MSG_VERSION_1)
2493                                         rej->ibr_why = IBLND_REJECT_CONN_UNCOMPAT;
2494                         }
2495
2496                         switch (rej->ibr_why) {
2497                         case IBLND_REJECT_CONN_RACE:
2498                         case IBLND_REJECT_CONN_STALE:
2499                         case IBLND_REJECT_CONN_UNCOMPAT:
2500                                 kiblnd_reconnect(conn, rej->ibr_version,
2501                                                  incarnation, rej->ibr_why, cp);
2502                                 break;
2503
2504                         case IBLND_REJECT_MSG_QUEUE_SIZE:
2505                                 CERROR("%s rejected: incompatible message queue depth %d, %d\n",
2506                                        libcfs_nid2str(peer->ibp_nid), cp->ibcp_queue_depth,
2507                                        IBLND_MSG_QUEUE_SIZE(conn->ibc_version));
2508                                 break;
2509
2510                         case IBLND_REJECT_RDMA_FRAGS:
2511                                 CERROR("%s rejected: incompatible # of RDMA fragments %d, %d\n",
2512                                        libcfs_nid2str(peer->ibp_nid), cp->ibcp_max_frags,
2513                                        IBLND_RDMA_FRAGS(conn->ibc_version));
2514                                 break;
2515
2516                         case IBLND_REJECT_NO_RESOURCES:
2517                                 CERROR("%s rejected: o2iblnd no resources\n",
2518                                        libcfs_nid2str(peer->ibp_nid));
2519                                 break;
2520
2521                         case IBLND_REJECT_FATAL:
2522                                 CERROR("%s rejected: o2iblnd fatal error\n",
2523                                        libcfs_nid2str(peer->ibp_nid));
2524                                 break;
2525
2526                         default:
2527                                 CERROR("%s rejected: o2iblnd reason %d\n",
2528                                        libcfs_nid2str(peer->ibp_nid),
2529                                        rej->ibr_why);
2530                                 break;
2531                         }
2532                         break;
2533                 }
2534                 /* fall through */
2535         default:
2536                 CDEBUG(D_NETERROR, "%s rejected: reason %d, size %d\n",
2537                        libcfs_nid2str(peer->ibp_nid), reason, priv_nob);
2538                 break;
2539         }
2540
2541         kiblnd_connreq_done(conn, -ECONNREFUSED);
2542 }
2543
2544 void
2545 kiblnd_check_connreply (kib_conn_t *conn, void *priv, int priv_nob)
2546 {
2547         kib_peer_t    *peer = conn->ibc_peer;
2548         lnet_ni_t     *ni   = peer->ibp_ni;
2549         kib_net_t     *net  = ni->ni_data;
2550         kib_msg_t     *msg  = priv;
2551         int            ver  = conn->ibc_version;
2552         int            rc   = kiblnd_unpack_msg(msg, priv_nob);
2553         unsigned long  flags;
2554
2555         LASSERT (net != NULL);
2556
2557         if (rc != 0) {
2558                 CERROR("Can't unpack connack from %s: %d\n",
2559                        libcfs_nid2str(peer->ibp_nid), rc);
2560                 goto failed;
2561         }
2562
2563         if (msg->ibm_type != IBLND_MSG_CONNACK) {
2564                 CERROR("Unexpected message %d from %s\n",
2565                        msg->ibm_type, libcfs_nid2str(peer->ibp_nid));
2566                 rc = -EPROTO;
2567                 goto failed;
2568         }
2569
2570         if (ver != msg->ibm_version) {
2571                 CERROR("%s replied version %x is different with "
2572                        "requested version %x\n",
2573                        libcfs_nid2str(peer->ibp_nid), msg->ibm_version, ver);
2574                 rc = -EPROTO;
2575                 goto failed;
2576         }
2577
2578         if (msg->ibm_u.connparams.ibcp_queue_depth !=
2579             IBLND_MSG_QUEUE_SIZE(ver)) {
2580                 CERROR("%s has incompatible queue depth %d(%d wanted)\n",
2581                        libcfs_nid2str(peer->ibp_nid),
2582                        msg->ibm_u.connparams.ibcp_queue_depth,
2583                        IBLND_MSG_QUEUE_SIZE(ver));
2584                 rc = -EPROTO;
2585                 goto failed;
2586         }
2587
2588         if (msg->ibm_u.connparams.ibcp_max_frags !=
2589             IBLND_RDMA_FRAGS(ver)) {
2590                 CERROR("%s has incompatible max_frags %d (%d wanted)\n",
2591                        libcfs_nid2str(peer->ibp_nid),
2592                        msg->ibm_u.connparams.ibcp_max_frags,
2593                        IBLND_RDMA_FRAGS(ver));
2594                 rc = -EPROTO;
2595                 goto failed;
2596         }
2597
2598         if (msg->ibm_u.connparams.ibcp_max_msg_size > IBLND_MSG_SIZE) {
2599                 CERROR("%s max message size %d too big (%d max)\n",
2600                        libcfs_nid2str(peer->ibp_nid),
2601                        msg->ibm_u.connparams.ibcp_max_msg_size,
2602                        IBLND_MSG_SIZE);
2603                 rc = -EPROTO;
2604                 goto failed;
2605         }
2606
2607         cfs_read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2608         if (msg->ibm_dstnid == ni->ni_nid &&
2609             msg->ibm_dststamp == net->ibn_incarnation)
2610                 rc = 0;
2611         else
2612                 rc = -ESTALE;
2613         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2614
2615         if (rc != 0) {
2616                 CERROR("Bad connection reply from %s, rc = %d, "
2617                        "version: %x max_frags: %d\n",
2618                        libcfs_nid2str(peer->ibp_nid), rc,
2619                        msg->ibm_version, msg->ibm_u.connparams.ibcp_max_frags);
2620                 goto failed;
2621         }
2622
2623         conn->ibc_incarnation      = msg->ibm_srcstamp;
2624         conn->ibc_credits          =
2625         conn->ibc_reserved_credits = IBLND_MSG_QUEUE_SIZE(ver);
2626         LASSERT (conn->ibc_credits + conn->ibc_reserved_credits + IBLND_OOB_MSGS(ver)
2627                  <= IBLND_RX_MSGS(ver));
2628
2629         kiblnd_connreq_done(conn, 0);
2630         return;
2631
2632  failed:
2633         /* NB My QP has already established itself, so I handle anything going
2634          * wrong here by setting ibc_comms_error.
2635          * kiblnd_connreq_done(0) moves the conn state to ESTABLISHED, but then
2636          * immediately tears it down. */
2637
2638         LASSERT (rc != 0);
2639         conn->ibc_comms_error = rc;
2640         kiblnd_connreq_done(conn, 0);
2641 }
2642
2643 int
2644 kiblnd_active_connect (struct rdma_cm_id *cmid)
2645 {
2646         kib_peer_t              *peer = (kib_peer_t *)cmid->context;
2647         kib_conn_t              *conn;
2648         kib_msg_t               *msg;
2649         struct rdma_conn_param   cp;
2650         int                      version;
2651         __u64                    incarnation;
2652         unsigned long            flags;
2653         int                      rc;
2654
2655         cfs_read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2656
2657         incarnation = peer->ibp_incarnation;
2658         version     = (peer->ibp_version == 0) ? IBLND_MSG_VERSION : peer->ibp_version;
2659
2660         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2661
2662         conn = kiblnd_create_conn(peer, cmid, IBLND_CONN_ACTIVE_CONNECT, version);
2663         if (conn == NULL) {
2664                 kiblnd_peer_connect_failed(peer, 1, -ENOMEM);
2665                 kiblnd_peer_decref(peer); /* lose cmid's ref */
2666                 return -ENOMEM;
2667         }
2668
2669         /* conn "owns" cmid now, so I return success from here on to ensure the
2670          * CM callback doesn't destroy cmid. conn also takes over cmid's ref
2671          * on peer */
2672
2673         msg = &conn->ibc_connvars->cv_msg;
2674
2675         memset(msg, 0, sizeof(*msg));
2676         kiblnd_init_msg(msg, IBLND_MSG_CONNREQ, sizeof(msg->ibm_u.connparams));
2677         msg->ibm_u.connparams.ibcp_queue_depth  = IBLND_MSG_QUEUE_SIZE(version);
2678         msg->ibm_u.connparams.ibcp_max_frags    = IBLND_RDMA_FRAGS(version);
2679         msg->ibm_u.connparams.ibcp_max_msg_size = IBLND_MSG_SIZE;
2680
2681         kiblnd_pack_msg(peer->ibp_ni, msg, version,
2682                         0, peer->ibp_nid, incarnation);
2683
2684         memset(&cp, 0, sizeof(cp));
2685         cp.private_data        = msg;
2686         cp.private_data_len    = msg->ibm_nob;
2687         cp.responder_resources = 0;             /* No atomic ops or RDMA reads */
2688         cp.initiator_depth     = 0;
2689         cp.flow_control        = 1;
2690         cp.retry_count         = *kiblnd_tunables.kib_retry_count;
2691         cp.rnr_retry_count     = *kiblnd_tunables.kib_rnr_retry_count;
2692
2693         LASSERT(cmid->context == (void *)conn);
2694         LASSERT(conn->ibc_cmid == cmid);
2695
2696         rc = rdma_connect(cmid, &cp);
2697         if (rc != 0) {
2698                 CERROR("Can't connect to %s: %d\n",
2699                        libcfs_nid2str(peer->ibp_nid), rc);
2700                 kiblnd_connreq_done(conn, rc);
2701                 kiblnd_conn_decref(conn);
2702         }
2703
2704         return 0;
2705 }
2706
2707 int
2708 kiblnd_cm_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
2709 {
2710         kib_peer_t  *peer;
2711         kib_conn_t  *conn;
2712         int          rc;
2713
2714         switch (event->event) {
2715         default:
2716                 CERROR("Unexpected event: %d, status: %d\n",
2717                        event->event, event->status);
2718                 LBUG();
2719
2720         case RDMA_CM_EVENT_CONNECT_REQUEST:
2721                 /* destroy cmid on failure */
2722                 rc = kiblnd_passive_connect(cmid, 
2723                                             (void *)KIBLND_CONN_PARAM(event),
2724                                             KIBLND_CONN_PARAM_LEN(event));
2725                 CDEBUG(D_NET, "connreq: %d\n", rc);
2726                 return rc;
2727                 
2728         case RDMA_CM_EVENT_ADDR_ERROR:
2729                 peer = (kib_peer_t *)cmid->context;
2730                 CDEBUG(D_NETERROR, "%s: ADDR ERROR %d\n",
2731                        libcfs_nid2str(peer->ibp_nid), event->status);
2732                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2733                 kiblnd_peer_decref(peer);
2734                 return -EHOSTUNREACH;      /* rc != 0 destroys cmid */
2735
2736         case RDMA_CM_EVENT_ADDR_RESOLVED:
2737                 peer = (kib_peer_t *)cmid->context;
2738
2739                 CDEBUG(D_NET,"%s Addr resolved: %d\n",
2740                        libcfs_nid2str(peer->ibp_nid), event->status);
2741
2742                 if (event->status != 0) {
2743                         CDEBUG(D_NETERROR, "Can't resolve address for %s: %d\n",
2744                                libcfs_nid2str(peer->ibp_nid), event->status);
2745                         rc = event->status;
2746                 } else {
2747                         rc = rdma_resolve_route(
2748                                 cmid, *kiblnd_tunables.kib_timeout * 1000);
2749                         if (rc == 0)
2750                                 return 0;
2751                         /* Can't initiate route resolution */
2752                         CERROR("Can't resolve route for %s: %d\n",
2753                                libcfs_nid2str(peer->ibp_nid), rc);
2754                 }
2755                 kiblnd_peer_connect_failed(peer, 1, rc);
2756                 kiblnd_peer_decref(peer);
2757                 return rc;                      /* rc != 0 destroys cmid */
2758
2759         case RDMA_CM_EVENT_ROUTE_ERROR:
2760                 peer = (kib_peer_t *)cmid->context;
2761                 CDEBUG(D_NETERROR, "%s: ROUTE ERROR %d\n",
2762                        libcfs_nid2str(peer->ibp_nid), event->status);
2763                 kiblnd_peer_connect_failed(peer, 1, -EHOSTUNREACH);
2764                 kiblnd_peer_decref(peer);
2765                 return -EHOSTUNREACH;           /* rc != 0 destroys cmid */
2766
2767         case RDMA_CM_EVENT_ROUTE_RESOLVED:
2768                 peer = (kib_peer_t *)cmid->context;
2769                 CDEBUG(D_NET,"%s Route resolved: %d\n",
2770                        libcfs_nid2str(peer->ibp_nid), event->status);
2771
2772                 if (event->status == 0)
2773                         return kiblnd_active_connect(cmid);
2774
2775                 CDEBUG(D_NETERROR, "Can't resolve route for %s: %d\n",
2776                        libcfs_nid2str(peer->ibp_nid), event->status);
2777                 kiblnd_peer_connect_failed(peer, 1, event->status);
2778                 kiblnd_peer_decref(peer);
2779                 return event->status;           /* rc != 0 destroys cmid */
2780                 
2781         case RDMA_CM_EVENT_UNREACHABLE:
2782                 conn = (kib_conn_t *)cmid->context;
2783                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
2784                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
2785                 CDEBUG(D_NETERROR, "%s: UNREACHABLE %d\n",
2786                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
2787                 kiblnd_connreq_done(conn, -ENETDOWN);
2788                 kiblnd_conn_decref(conn);
2789                 return 0;
2790
2791         case RDMA_CM_EVENT_CONNECT_ERROR:
2792                 conn = (kib_conn_t *)cmid->context;
2793                 LASSERT(conn->ibc_state == IBLND_CONN_ACTIVE_CONNECT ||
2794                         conn->ibc_state == IBLND_CONN_PASSIVE_WAIT);
2795                 CDEBUG(D_NETERROR, "%s: CONNECT ERROR %d\n",
2796                        libcfs_nid2str(conn->ibc_peer->ibp_nid), event->status);
2797                 kiblnd_connreq_done(conn, -ENOTCONN);
2798                 kiblnd_conn_decref(conn);
2799                 return 0;
2800
2801         case RDMA_CM_EVENT_REJECTED:
2802                 conn = (kib_conn_t *)cmid->context;
2803                 switch (conn->ibc_state) {
2804                 default:
2805                         LBUG();
2806
2807                 case IBLND_CONN_PASSIVE_WAIT:
2808                         CERROR ("%s: REJECTED %d\n",
2809                                 libcfs_nid2str(conn->ibc_peer->ibp_nid),
2810                                 event->status);
2811                         kiblnd_connreq_done(conn, -ECONNRESET);
2812                         break;
2813
2814                 case IBLND_CONN_ACTIVE_CONNECT:
2815                         kiblnd_rejected(conn, event->status,
2816                                         (void *)KIBLND_CONN_PARAM(event),
2817                                         KIBLND_CONN_PARAM_LEN(event));
2818                         break;
2819                 }
2820                 kiblnd_conn_decref(conn);
2821                 return 0;
2822
2823         case RDMA_CM_EVENT_ESTABLISHED:
2824                 conn = (kib_conn_t *)cmid->context;
2825                 switch (conn->ibc_state) {
2826                 default:
2827                         LBUG();
2828
2829                 case IBLND_CONN_PASSIVE_WAIT:
2830                         CDEBUG(D_NET, "ESTABLISHED (passive): %s\n",
2831                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2832                         kiblnd_connreq_done(conn, 0);
2833                         break;
2834
2835                 case IBLND_CONN_ACTIVE_CONNECT:
2836                         CDEBUG(D_NET, "ESTABLISHED(active): %s\n",
2837                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2838                         kiblnd_check_connreply(conn,
2839                                                (void *)KIBLND_CONN_PARAM(event),
2840                                                KIBLND_CONN_PARAM_LEN(event));
2841                         break;
2842                 }
2843                 /* net keeps its ref on conn! */
2844                 return 0;
2845
2846 #ifdef HAVE_OFED_RDMA_CMEV_TIMEWAIT_EXIT
2847         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
2848                 CDEBUG(D_NET, "Ignore TIMEWAIT_EXIT event\n");
2849                 return 0;
2850 #endif
2851         case RDMA_CM_EVENT_DISCONNECTED:
2852                 conn = (kib_conn_t *)cmid->context;
2853                 if (conn->ibc_state < IBLND_CONN_ESTABLISHED) {
2854                         CERROR("%s DISCONNECTED\n",
2855                                libcfs_nid2str(conn->ibc_peer->ibp_nid));
2856                         kiblnd_connreq_done(conn, -ECONNRESET);
2857                 } else {
2858                         kiblnd_close_conn(conn, 0);
2859                 }
2860                 kiblnd_conn_decref(conn);
2861                 cmid->context = NULL;
2862                 return 0;
2863
2864         case RDMA_CM_EVENT_DEVICE_REMOVAL:
2865                 LCONSOLE_ERROR_MSG(0x131,
2866                                    "Received notification of device removal\n"
2867                                    "Please shutdown LNET to allow this to proceed\n");
2868                 /* Can't remove network from underneath LNET for now, so I have
2869                  * to ignore this */
2870                 return 0;
2871
2872 #ifdef HAVE_OFED_RDMA_CMEV_ADDRCHANGE
2873         case RDMA_CM_EVENT_ADDR_CHANGE:
2874                 LCONSOLE_INFO("Physical link changed (eg hca/port)\n");
2875                 return 0;
2876 #endif
2877         }
2878 }
2879
2880 static int
2881 kiblnd_check_txs_locked (kib_conn_t *conn, cfs_list_t *txs)
2882 {
2883         kib_tx_t          *tx;
2884         cfs_list_t        *ttmp;
2885
2886         cfs_list_for_each (ttmp, txs) {
2887                 tx = cfs_list_entry (ttmp, kib_tx_t, tx_list);
2888
2889                 if (txs != &conn->ibc_active_txs) {
2890                         LASSERT (tx->tx_queued);
2891                 } else {
2892                         LASSERT (!tx->tx_queued);
2893                         LASSERT (tx->tx_waiting || tx->tx_sending != 0);
2894                 }
2895
2896                 if (cfs_time_aftereq (jiffies, tx->tx_deadline)) {
2897                         CERROR("Timed out tx: %s, %lu seconds\n",
2898                                kiblnd_queue2str(conn, txs),
2899                                cfs_duration_sec(jiffies - tx->tx_deadline));
2900                         return 1;
2901                 }
2902         }
2903
2904         return 0;
2905 }
2906
2907 static int
2908 kiblnd_conn_timed_out_locked (kib_conn_t *conn)
2909 {
2910         return  kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue) ||
2911                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_rsrvd) ||
2912                 kiblnd_check_txs_locked(conn, &conn->ibc_tx_queue_nocred) ||
2913                 kiblnd_check_txs_locked(conn, &conn->ibc_active_txs);
2914 }
2915
2916 void
2917 kiblnd_check_conns (int idx)
2918 {
2919         cfs_list_t        *peers = &kiblnd_data.kib_peers[idx];
2920         cfs_list_t        *ptmp;
2921         kib_peer_t        *peer;
2922         kib_conn_t        *conn;
2923         cfs_list_t        *ctmp;
2924         unsigned long      flags;
2925
2926  again:
2927         /* NB. We expect to have a look at all the peers and not find any
2928          * rdmas to time out, so we just use a shared lock while we
2929          * take a look... */
2930         cfs_read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2931
2932         cfs_list_for_each (ptmp, peers) {
2933                 peer = cfs_list_entry (ptmp, kib_peer_t, ibp_list);
2934
2935                 cfs_list_for_each (ctmp, &peer->ibp_conns) {
2936                         int     check_sends;
2937                         int     timedout;
2938
2939                         conn = cfs_list_entry (ctmp, kib_conn_t, ibc_list);
2940
2941                         LASSERT (conn->ibc_state == IBLND_CONN_ESTABLISHED);
2942
2943                         cfs_spin_lock(&conn->ibc_lock);
2944
2945                         check_sends = conn->ibc_retry_noop;
2946                         timedout    = kiblnd_conn_timed_out_locked(conn);
2947                         if (!check_sends && !timedout) {
2948                                 cfs_spin_unlock(&conn->ibc_lock);
2949                                 continue;
2950                         }
2951
2952                         if (timedout) {
2953                                 CERROR("Timed out RDMA with %s (%lu): "
2954                                        "c: %u, oc: %u, rc: %u\n",
2955                                        libcfs_nid2str(peer->ibp_nid),
2956                                        cfs_duration_sec(cfs_time_current() -
2957                                                         peer->ibp_last_alive),
2958                                        conn->ibc_credits,
2959                                        conn->ibc_outstanding_credits,
2960                                        conn->ibc_reserved_credits);
2961                         }
2962
2963                         cfs_spin_unlock(&conn->ibc_lock);
2964
2965                         /* Handle timeout by closing the whole connection.  We
2966                          * can only be sure RDMA activity has ceased once the
2967                          * QP has been modified. */
2968
2969                         kiblnd_conn_addref(conn); /* 1 ref for me... */
2970
2971                         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2972                                                    flags);
2973
2974                         if (timedout) {
2975                                 kiblnd_close_conn(conn, -ETIMEDOUT);
2976                         } else {
2977                                 /* In case we have enough credits to return via a
2978                                  * NOOP, but there were no non-blocking tx descs
2979                                  * free to do it last time... */
2980                                 kiblnd_check_sends(conn);
2981                         }
2982
2983                         kiblnd_conn_decref(conn); /* ...until here */
2984
2985                         /* start again now I've dropped the lock */
2986                         goto again;
2987                 }
2988         }
2989
2990         cfs_read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2991 }
2992
2993 void
2994 kiblnd_disconnect_conn (kib_conn_t *conn)
2995 {
2996         LASSERT (!cfs_in_interrupt());
2997         LASSERT (current == kiblnd_data.kib_connd);
2998         LASSERT (conn->ibc_state == IBLND_CONN_CLOSING);
2999
3000         rdma_disconnect(conn->ibc_cmid);
3001         kiblnd_finalise_conn(conn);
3002
3003         kiblnd_peer_notify(conn->ibc_peer);
3004 }
3005
3006 int
3007 kiblnd_connd (void *arg)
3008 {
3009         cfs_waitlink_t     wait;
3010         unsigned long      flags;
3011         kib_conn_t        *conn;
3012         int                timeout;
3013         int                i;
3014         int                dropped_lock;
3015         int                peer_index = 0;
3016         unsigned long      deadline = jiffies;
3017
3018         cfs_daemonize ("kiblnd_connd");
3019         cfs_block_allsigs ();
3020
3021         cfs_waitlink_init (&wait);
3022         kiblnd_data.kib_connd = current;
3023
3024         cfs_spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);
3025
3026         while (!kiblnd_data.kib_shutdown) {
3027
3028                 dropped_lock = 0;
3029
3030                 if (!cfs_list_empty (&kiblnd_data.kib_connd_zombies)) {
3031                         conn = cfs_list_entry(kiblnd_data. \
3032                                               kib_connd_zombies.next,
3033                                               kib_conn_t, ibc_list);
3034                         cfs_list_del(&conn->ibc_list);
3035
3036                         cfs_spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock,
3037                                                    flags);
3038                         dropped_lock = 1;
3039
3040                         kiblnd_destroy_conn(conn);
3041
3042                         cfs_spin_lock_irqsave (&kiblnd_data.kib_connd_lock,
3043                                                flags);
3044                 }
3045
3046                 if (!cfs_list_empty (&kiblnd_data.kib_connd_conns)) {
3047                         conn = cfs_list_entry (kiblnd_data.kib_connd_conns.next,
3048                                                kib_conn_t, ibc_list);
3049                         cfs_list_del(&conn->ibc_list);
3050
3051                         cfs_spin_unlock_irqrestore (&kiblnd_data.kib_connd_lock,
3052                                                     flags);
3053                         dropped_lock = 1;
3054
3055                         kiblnd_disconnect_conn(conn);
3056                         kiblnd_conn_decref(conn);
3057
3058                         cfs_spin_lock_irqsave (&kiblnd_data.kib_connd_lock,
3059                                                flags);
3060                 }
3061
3062                 /* careful with the jiffy wrap... */
3063                 timeout = (int)(deadline - jiffies);
3064                 if (timeout <= 0) {
3065                         const int n = 4;
3066                         const int p = 1;
3067                         int       chunk = kiblnd_data.kib_peer_hash_size;
3068
3069                         cfs_spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);
3070                         dropped_lock = 1;
3071
3072                         /* Time to check for RDMA timeouts on a few more
3073                          * peers: I do checks every 'p' seconds on a
3074                          * proportion of the peer table and I need to check
3075                          * every connection 'n' times within a timeout
3076                          * interval, to ensure I detect a timeout on any
3077                          * connection within (n+1)/n times the timeout
3078                          * interval. */
3079
3080                         if (*kiblnd_tunables.kib_timeout > n * p)
3081                                 chunk = (chunk * n * p) /
3082                                         *kiblnd_tunables.kib_timeout;
3083                         if (chunk == 0)
3084                                 chunk = 1;
3085
3086                         for (i = 0; i < chunk; i++) {
3087                                 kiblnd_check_conns(peer_index);
3088                                 peer_index = (peer_index + 1) %
3089                                              kiblnd_data.kib_peer_hash_size;
3090                         }
3091
3092                         deadline += p * CFS_HZ;
3093                         cfs_spin_lock_irqsave(&kiblnd_data.kib_connd_lock,
30