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