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