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