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