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