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