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