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