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