Whamcloud - gitweb
LU-12901 o2iblnd: retry qp creation with reduced queue depth
[fs/lustre-release.git] / lnet / klnds / o2iblnd / o2iblnd.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) 2011, 2017, 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.c
33  *
34  * Author: Eric Barton <eric@bartonsoftware.com>
35  */
36
37 #include <asm/page.h>
38 #include <linux/inetdevice.h>
39
40 #include "o2iblnd.h"
41
42 static const struct lnet_lnd the_o2iblnd;
43
44 struct kib_data kiblnd_data;
45
46 static __u32
47 kiblnd_cksum (void *ptr, int nob)
48 {
49         char  *c  = ptr;
50         __u32  sum = 0;
51
52         while (nob-- > 0)
53                 sum = ((sum << 1) | (sum >> 31)) + *c++;
54
55         /* ensure I don't return 0 (== no checksum) */
56         return (sum == 0) ? 1 : sum;
57 }
58
59 static char *
60 kiblnd_msgtype2str(int type)
61 {
62         switch (type) {
63         case IBLND_MSG_CONNREQ:
64                 return "CONNREQ";
65
66         case IBLND_MSG_CONNACK:
67                 return "CONNACK";
68
69         case IBLND_MSG_NOOP:
70                 return "NOOP";
71
72         case IBLND_MSG_IMMEDIATE:
73                 return "IMMEDIATE";
74
75         case IBLND_MSG_PUT_REQ:
76                 return "PUT_REQ";
77
78         case IBLND_MSG_PUT_NAK:
79                 return "PUT_NAK";
80
81         case IBLND_MSG_PUT_ACK:
82                 return "PUT_ACK";
83
84         case IBLND_MSG_PUT_DONE:
85                 return "PUT_DONE";
86
87         case IBLND_MSG_GET_REQ:
88                 return "GET_REQ";
89
90         case IBLND_MSG_GET_DONE:
91                 return "GET_DONE";
92
93         default:
94                 return "???";
95         }
96 }
97
98 static int
99 kiblnd_msgtype2size(int type)
100 {
101         const int hdr_size = offsetof(struct kib_msg, ibm_u);
102
103         switch (type) {
104         case IBLND_MSG_CONNREQ:
105         case IBLND_MSG_CONNACK:
106                 return hdr_size + sizeof(struct kib_connparams);
107
108         case IBLND_MSG_NOOP:
109                 return hdr_size;
110
111         case IBLND_MSG_IMMEDIATE:
112                 return offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[0]);
113
114         case IBLND_MSG_PUT_REQ:
115                 return hdr_size + sizeof(struct kib_putreq_msg);
116
117         case IBLND_MSG_PUT_ACK:
118                 return hdr_size + sizeof(struct kib_putack_msg);
119
120         case IBLND_MSG_GET_REQ:
121                 return hdr_size + sizeof(struct kib_get_msg);
122
123         case IBLND_MSG_PUT_NAK:
124         case IBLND_MSG_PUT_DONE:
125         case IBLND_MSG_GET_DONE:
126                 return hdr_size + sizeof(struct kib_completion_msg);
127         default:
128                 return -1;
129         }
130 }
131
132 static int kiblnd_unpack_rd(struct kib_msg *msg, int flip)
133 {
134         struct kib_rdma_desc *rd;
135         int                nob;
136         int                n;
137         int                i;
138
139         LASSERT (msg->ibm_type == IBLND_MSG_GET_REQ ||
140                  msg->ibm_type == IBLND_MSG_PUT_ACK);
141
142         rd = msg->ibm_type == IBLND_MSG_GET_REQ ?
143                               &msg->ibm_u.get.ibgm_rd :
144                               &msg->ibm_u.putack.ibpam_rd;
145
146         if (flip) {
147                 __swab32s(&rd->rd_key);
148                 __swab32s(&rd->rd_nfrags);
149         }
150
151         n = rd->rd_nfrags;
152
153         if (n <= 0 || n > IBLND_MAX_RDMA_FRAGS) {
154                 CERROR("Bad nfrags: %d, should be 0 < n <= %d\n",
155                        n, IBLND_MAX_RDMA_FRAGS);
156                 return 1;
157         }
158
159         nob = offsetof(struct kib_msg, ibm_u) +
160               kiblnd_rd_msg_size(rd, msg->ibm_type, n);
161
162         if (msg->ibm_nob < nob) {
163                 CERROR("Short %s: %d(%d)\n",
164                        kiblnd_msgtype2str(msg->ibm_type), msg->ibm_nob, nob);
165                 return 1;
166         }
167
168         if (!flip)
169                 return 0;
170
171         for (i = 0; i < n; i++) {
172                 __swab32s(&rd->rd_frags[i].rf_nob);
173                 __swab64s(&rd->rd_frags[i].rf_addr);
174         }
175
176         return 0;
177 }
178
179 void kiblnd_pack_msg(struct lnet_ni *ni, struct kib_msg *msg, int version,
180                      int credits, lnet_nid_t dstnid, __u64 dststamp)
181 {
182         struct kib_net *net = ni->ni_data;
183
184         /* CAVEAT EMPTOR! all message fields not set here should have been
185          * initialised previously. */
186         msg->ibm_magic    = IBLND_MSG_MAGIC;
187         msg->ibm_version  = version;
188         /*   ibm_type */
189         msg->ibm_credits  = credits;
190         /*   ibm_nob */
191         msg->ibm_cksum    = 0;
192         msg->ibm_srcnid   = ni->ni_nid;
193         msg->ibm_srcstamp = net->ibn_incarnation;
194         msg->ibm_dstnid   = dstnid;
195         msg->ibm_dststamp = dststamp;
196
197         if (*kiblnd_tunables.kib_cksum) {
198                 /* NB ibm_cksum zero while computing cksum */
199                 msg->ibm_cksum = kiblnd_cksum(msg, msg->ibm_nob);
200         }
201 }
202
203 int kiblnd_unpack_msg(struct kib_msg *msg, int nob)
204 {
205         const int hdr_size = offsetof(struct kib_msg, ibm_u);
206         __u32     msg_cksum;
207         __u16     version;
208         int       msg_nob;
209         int       flip;
210
211         /* 6 bytes are enough to have received magic + version */
212         if (nob < 6) {
213                 CERROR("Short message: %d\n", nob);
214                 return -EPROTO;
215         }
216
217         if (msg->ibm_magic == IBLND_MSG_MAGIC) {
218                 flip = 0;
219         } else if (msg->ibm_magic == __swab32(IBLND_MSG_MAGIC)) {
220                 flip = 1;
221         } else {
222                 CERROR("Bad magic: %08x\n", msg->ibm_magic);
223                 return -EPROTO;
224         }
225
226         version = flip ? __swab16(msg->ibm_version) : msg->ibm_version;
227         if (version != IBLND_MSG_VERSION &&
228             version != IBLND_MSG_VERSION_1) {
229                 CERROR("Bad version: %x\n", version);
230                 return -EPROTO;
231         }
232
233         if (nob < hdr_size) {
234                 CERROR("Short message: %d\n", nob);
235                 return -EPROTO;
236         }
237
238         msg_nob = flip ? __swab32(msg->ibm_nob) : msg->ibm_nob;
239         if (msg_nob > nob) {
240                 CERROR("Short message: got %d, wanted %d\n", nob, msg_nob);
241                 return -EPROTO;
242         }
243
244         /* checksum must be computed with ibm_cksum zero and BEFORE anything
245          * gets flipped */
246         msg_cksum = flip ? __swab32(msg->ibm_cksum) : msg->ibm_cksum;
247         msg->ibm_cksum = 0;
248         if (msg_cksum != 0 &&
249             msg_cksum != kiblnd_cksum(msg, msg_nob)) {
250                 CERROR("Bad checksum\n");
251                 return -EPROTO;
252         }
253
254         msg->ibm_cksum = msg_cksum;
255
256         if (flip) {
257                 /* leave magic unflipped as a clue to peer_ni endianness */
258                 msg->ibm_version = version;
259                 BUILD_BUG_ON(sizeof(msg->ibm_type) != 1);
260                 BUILD_BUG_ON(sizeof(msg->ibm_credits) != 1);
261                 msg->ibm_nob     = msg_nob;
262                 __swab64s(&msg->ibm_srcnid);
263                 __swab64s(&msg->ibm_srcstamp);
264                 __swab64s(&msg->ibm_dstnid);
265                 __swab64s(&msg->ibm_dststamp);
266         }
267
268         if (msg->ibm_srcnid == LNET_NID_ANY) {
269                 CERROR("Bad src nid: %s\n", libcfs_nid2str(msg->ibm_srcnid));
270                 return -EPROTO;
271         }
272
273         if (msg_nob < kiblnd_msgtype2size(msg->ibm_type)) {
274                 CERROR("Short %s: %d(%d)\n", kiblnd_msgtype2str(msg->ibm_type),
275                        msg_nob, kiblnd_msgtype2size(msg->ibm_type));
276                 return -EPROTO;
277         }
278
279         switch (msg->ibm_type) {
280         default:
281                 CERROR("Unknown message type %x\n", msg->ibm_type);
282                 return -EPROTO;
283
284         case IBLND_MSG_NOOP:
285         case IBLND_MSG_IMMEDIATE:
286         case IBLND_MSG_PUT_REQ:
287                 break;
288
289         case IBLND_MSG_PUT_ACK:
290         case IBLND_MSG_GET_REQ:
291                 if (kiblnd_unpack_rd(msg, flip))
292                         return -EPROTO;
293                 break;
294
295         case IBLND_MSG_PUT_NAK:
296         case IBLND_MSG_PUT_DONE:
297         case IBLND_MSG_GET_DONE:
298                 if (flip)
299                         __swab32s(&msg->ibm_u.completion.ibcm_status);
300                 break;
301
302         case IBLND_MSG_CONNREQ:
303         case IBLND_MSG_CONNACK:
304                 if (flip) {
305                         __swab16s(&msg->ibm_u.connparams.ibcp_queue_depth);
306                         __swab16s(&msg->ibm_u.connparams.ibcp_max_frags);
307                         __swab32s(&msg->ibm_u.connparams.ibcp_max_msg_size);
308                 }
309                 break;
310         }
311         return 0;
312 }
313
314 int
315 kiblnd_create_peer(struct lnet_ni *ni, struct kib_peer_ni **peerp,
316                    lnet_nid_t nid)
317 {
318         struct kib_peer_ni *peer_ni;
319         struct kib_net *net = ni->ni_data;
320         int cpt = lnet_cpt_of_nid(nid, ni);
321         unsigned long flags;
322
323         LASSERT(net != NULL);
324         LASSERT(nid != LNET_NID_ANY);
325
326         LIBCFS_CPT_ALLOC(peer_ni, lnet_cpt_table(), cpt, sizeof(*peer_ni));
327         if (peer_ni == NULL) {
328                 CERROR("Cannot allocate peer_ni\n");
329                 return -ENOMEM;
330         }
331
332         peer_ni->ibp_ni = ni;
333         peer_ni->ibp_nid = nid;
334         peer_ni->ibp_error = 0;
335         peer_ni->ibp_last_alive = 0;
336         peer_ni->ibp_max_frags = IBLND_MAX_RDMA_FRAGS;
337         peer_ni->ibp_queue_depth = ni->ni_net->net_tunables.lct_peer_tx_credits;
338         peer_ni->ibp_queue_depth_mod = 0;       /* try to use the default */
339         atomic_set(&peer_ni->ibp_refcount, 1);  /* 1 ref for caller */
340
341         INIT_LIST_HEAD(&peer_ni->ibp_list);     /* not in the peer_ni table yet */
342         INIT_LIST_HEAD(&peer_ni->ibp_conns);
343         INIT_LIST_HEAD(&peer_ni->ibp_tx_queue);
344
345         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
346
347         /* always called with a ref on ni, which prevents ni being shutdown */
348         LASSERT(net->ibn_shutdown == 0);
349
350         /* npeers only grows with the global lock held */
351         atomic_inc(&net->ibn_npeers);
352
353         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
354
355         *peerp = peer_ni;
356         return 0;
357 }
358
359 void
360 kiblnd_destroy_peer(struct kib_peer_ni *peer_ni)
361 {
362         struct kib_net *net = peer_ni->ibp_ni->ni_data;
363
364         LASSERT(net != NULL);
365         LASSERT (atomic_read(&peer_ni->ibp_refcount) == 0);
366         LASSERT(!kiblnd_peer_active(peer_ni));
367         LASSERT(kiblnd_peer_idle(peer_ni));
368         LASSERT(list_empty(&peer_ni->ibp_tx_queue));
369
370         LIBCFS_FREE(peer_ni, sizeof(*peer_ni));
371
372         /* NB a peer_ni's connections keep a reference on their peer_ni until
373          * they are destroyed, so we can be assured that _all_ state to do
374          * with this peer_ni has been cleaned up when its refcount drops to
375          * zero. */
376         if (atomic_dec_and_test(&net->ibn_npeers))
377                 wake_up_var(&net->ibn_npeers);
378 }
379
380 struct kib_peer_ni *
381 kiblnd_find_peer_locked(struct lnet_ni *ni, lnet_nid_t nid)
382 {
383         /* the caller is responsible for accounting the additional reference
384          * that this creates */
385         struct list_head        *peer_list = kiblnd_nid2peerlist(nid);
386         struct list_head        *tmp;
387         struct kib_peer_ni              *peer_ni;
388
389         list_for_each(tmp, peer_list) {
390
391                 peer_ni = list_entry(tmp, struct kib_peer_ni, ibp_list);
392                 LASSERT(!kiblnd_peer_idle(peer_ni));
393
394                 /*
395                  * Match a peer if its NID and the NID of the local NI it
396                  * communicates over are the same. Otherwise don't match
397                  * the peer, which will result in a new lnd peer being
398                  * created.
399                  */
400                 if (peer_ni->ibp_nid != nid ||
401                     peer_ni->ibp_ni->ni_nid != ni->ni_nid)
402                         continue;
403
404                 CDEBUG(D_NET, "got peer_ni [%p] -> %s (%d) version: %x\n",
405                        peer_ni, libcfs_nid2str(nid),
406                        atomic_read(&peer_ni->ibp_refcount),
407                        peer_ni->ibp_version);
408                 return peer_ni;
409         }
410         return NULL;
411 }
412
413 void
414 kiblnd_unlink_peer_locked(struct kib_peer_ni *peer_ni)
415 {
416         LASSERT(list_empty(&peer_ni->ibp_conns));
417
418         LASSERT (kiblnd_peer_active(peer_ni));
419         list_del_init(&peer_ni->ibp_list);
420         /* lose peerlist's ref */
421         kiblnd_peer_decref(peer_ni);
422 }
423
424 static int
425 kiblnd_get_peer_info(struct lnet_ni *ni, int index,
426                      lnet_nid_t *nidp, int *count)
427 {
428         struct kib_peer_ni              *peer_ni;
429         struct list_head        *ptmp;
430         int                      i;
431         unsigned long            flags;
432
433         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
434
435         for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++) {
436
437                 list_for_each(ptmp, &kiblnd_data.kib_peers[i]) {
438
439                         peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
440                         LASSERT(!kiblnd_peer_idle(peer_ni));
441
442                         if (peer_ni->ibp_ni != ni)
443                                 continue;
444
445                         if (index-- > 0)
446                                 continue;
447
448                         *nidp = peer_ni->ibp_nid;
449                         *count = atomic_read(&peer_ni->ibp_refcount);
450
451                         read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
452                                                flags);
453                         return 0;
454                 }
455         }
456
457         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
458         return -ENOENT;
459 }
460
461 static void
462 kiblnd_del_peer_locked(struct kib_peer_ni *peer_ni)
463 {
464         struct kib_conn *cnxt;
465         struct kib_conn *conn;
466
467         if (list_empty(&peer_ni->ibp_conns)) {
468                 kiblnd_unlink_peer_locked(peer_ni);
469         } else {
470                 list_for_each_entry_safe(conn, cnxt, &peer_ni->ibp_conns,
471                                          ibc_list)
472                         kiblnd_close_conn_locked(conn, 0);
473                 /* NB closing peer_ni's last conn unlinked it. */
474         }
475         /* NB peer_ni now unlinked; might even be freed if the peer_ni table had the
476          * last ref on it. */
477 }
478
479 static int
480 kiblnd_del_peer(struct lnet_ni *ni, lnet_nid_t nid)
481 {
482         LIST_HEAD(zombies);
483         struct list_head        *ptmp;
484         struct list_head        *pnxt;
485         struct kib_peer_ni              *peer_ni;
486         int                     lo;
487         int                     hi;
488         int                     i;
489         unsigned long           flags;
490         int                     rc = -ENOENT;
491
492         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
493
494         if (nid != LNET_NID_ANY) {
495                 lo = hi = kiblnd_nid2peerlist(nid) - kiblnd_data.kib_peers;
496         } else {
497                 lo = 0;
498                 hi = kiblnd_data.kib_peer_hash_size - 1;
499         }
500
501         for (i = lo; i <= hi; i++) {
502                 list_for_each_safe(ptmp, pnxt, &kiblnd_data.kib_peers[i]) {
503                         peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
504                         LASSERT(!kiblnd_peer_idle(peer_ni));
505
506                         if (peer_ni->ibp_ni != ni)
507                                 continue;
508
509                         if (!(nid == LNET_NID_ANY || peer_ni->ibp_nid == nid))
510                                 continue;
511
512                         if (!list_empty(&peer_ni->ibp_tx_queue)) {
513                                 LASSERT(list_empty(&peer_ni->ibp_conns));
514
515                                 list_splice_init(&peer_ni->ibp_tx_queue,
516                                                  &zombies);
517                         }
518
519                         kiblnd_del_peer_locked(peer_ni);
520                         rc = 0;         /* matched something */
521                 }
522         }
523
524         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
525
526         kiblnd_txlist_done(&zombies, -EIO, LNET_MSG_STATUS_LOCAL_ERROR);
527
528         return rc;
529 }
530
531 static struct kib_conn *
532 kiblnd_get_conn_by_idx(struct lnet_ni *ni, int index)
533 {
534         struct kib_peer_ni              *peer_ni;
535         struct list_head        *ptmp;
536         struct kib_conn *conn;
537         struct list_head        *ctmp;
538         int                     i;
539         unsigned long           flags;
540
541         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
542
543         for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++) {
544                 list_for_each(ptmp, &kiblnd_data.kib_peers[i]) {
545
546                         peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
547                         LASSERT(!kiblnd_peer_idle(peer_ni));
548
549                         if (peer_ni->ibp_ni != ni)
550                                 continue;
551
552                         list_for_each(ctmp, &peer_ni->ibp_conns) {
553                                 if (index-- > 0)
554                                         continue;
555
556                                 conn = list_entry(ctmp, struct kib_conn, ibc_list);
557                                 kiblnd_conn_addref(conn);
558                                 read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
559                                                        flags);
560                                 return conn;
561                         }
562                 }
563         }
564
565         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
566         return NULL;
567 }
568
569 static void
570 kiblnd_debug_rx(struct kib_rx *rx)
571 {
572         CDEBUG(D_CONSOLE, "      %p msg_type %x cred %d\n",
573                rx, rx->rx_msg->ibm_type,
574                rx->rx_msg->ibm_credits);
575 }
576
577 static void
578 kiblnd_debug_tx(struct kib_tx *tx)
579 {
580         CDEBUG(D_CONSOLE, "      %p snd %d q %d w %d rc %d dl %lld "
581                "cookie %#llx msg %s%s type %x cred %d\n",
582                tx, tx->tx_sending, tx->tx_queued, tx->tx_waiting,
583                tx->tx_status, ktime_to_ns(tx->tx_deadline), tx->tx_cookie,
584                tx->tx_lntmsg[0] == NULL ? "-" : "!",
585                tx->tx_lntmsg[1] == NULL ? "-" : "!",
586                tx->tx_msg->ibm_type, tx->tx_msg->ibm_credits);
587 }
588
589 void
590 kiblnd_debug_conn(struct kib_conn *conn)
591 {
592         struct list_head        *tmp;
593         int                     i;
594
595         spin_lock(&conn->ibc_lock);
596
597         CDEBUG(D_CONSOLE, "conn[%d] %p [version %x] -> %s:\n",
598                atomic_read(&conn->ibc_refcount), conn,
599                conn->ibc_version, libcfs_nid2str(conn->ibc_peer->ibp_nid));
600         CDEBUG(D_CONSOLE, "   state %d nposted %d/%d cred %d o_cred %d "
601                " r_cred %d\n", conn->ibc_state, conn->ibc_noops_posted,
602                conn->ibc_nsends_posted, conn->ibc_credits,
603                conn->ibc_outstanding_credits, conn->ibc_reserved_credits);
604         CDEBUG(D_CONSOLE, "   comms_err %d\n", conn->ibc_comms_error);
605
606         CDEBUG(D_CONSOLE, "   early_rxs:\n");
607         list_for_each(tmp, &conn->ibc_early_rxs)
608                 kiblnd_debug_rx(list_entry(tmp, struct kib_rx, rx_list));
609
610         CDEBUG(D_CONSOLE, "   tx_noops:\n");
611         list_for_each(tmp, &conn->ibc_tx_noops)
612                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
613
614         CDEBUG(D_CONSOLE, "   tx_queue_nocred:\n");
615         list_for_each(tmp, &conn->ibc_tx_queue_nocred)
616                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
617
618         CDEBUG(D_CONSOLE, "   tx_queue_rsrvd:\n");
619         list_for_each(tmp, &conn->ibc_tx_queue_rsrvd)
620                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
621
622         CDEBUG(D_CONSOLE, "   tx_queue:\n");
623         list_for_each(tmp, &conn->ibc_tx_queue)
624                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
625
626         CDEBUG(D_CONSOLE, "   active_txs:\n");
627         list_for_each(tmp, &conn->ibc_active_txs)
628                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
629
630         CDEBUG(D_CONSOLE, "   rxs:\n");
631         for (i = 0; i < IBLND_RX_MSGS(conn); i++)
632                 kiblnd_debug_rx(&conn->ibc_rxs[i]);
633
634         spin_unlock(&conn->ibc_lock);
635 }
636
637 static void
638 kiblnd_setup_mtu_locked(struct rdma_cm_id *cmid)
639 {
640         /* XXX There is no path record for iWARP, set by netdev->change_mtu? */
641         if (cmid->route.path_rec == NULL)
642                 return;
643
644         if (*kiblnd_tunables.kib_ib_mtu)
645                 cmid->route.path_rec->mtu =
646                         ib_mtu_int_to_enum(*kiblnd_tunables.kib_ib_mtu);
647 }
648
649 static int
650 kiblnd_get_completion_vector(struct kib_conn *conn, int cpt)
651 {
652         cpumask_var_t   *mask;
653         int             vectors;
654         int             off;
655         int             i;
656         lnet_nid_t      ibp_nid;
657
658         vectors = conn->ibc_cmid->device->num_comp_vectors;
659         if (vectors <= 1)
660                 return 0;
661
662         mask = cfs_cpt_cpumask(lnet_cpt_table(), cpt);
663
664         /* hash NID to CPU id in this partition... */
665         ibp_nid = conn->ibc_peer->ibp_nid;
666         off = do_div(ibp_nid, cpumask_weight(*mask));
667         for_each_cpu(i, *mask) {
668                 if (off-- == 0)
669                         return i % vectors;
670         }
671
672         LBUG();
673         return 1;
674 }
675
676 /*
677  * Get the scheduler bound to this CPT. If the scheduler has no
678  * threads, which means that the CPT has no CPUs, then grab the
679  * next scheduler that we can use.
680  *
681  * This case would be triggered if a NUMA node is configured with
682  * no associated CPUs.
683  */
684 static struct kib_sched_info *
685 kiblnd_get_scheduler(int cpt)
686 {
687         struct kib_sched_info *sched;
688         int i;
689
690         sched = kiblnd_data.kib_scheds[cpt];
691
692         if (sched->ibs_nthreads > 0)
693                 return sched;
694
695         cfs_percpt_for_each(sched, i, kiblnd_data.kib_scheds) {
696                 if (sched->ibs_nthreads > 0) {
697                         CDEBUG(D_NET, "scheduler[%d] has no threads. selected scheduler[%d]\n",
698                                         cpt, sched->ibs_cpt);
699                         return sched;
700                 }
701         }
702
703         return NULL;
704 }
705
706 static unsigned int kiblnd_send_wrs(struct kib_conn *conn)
707 {
708         /*
709          * One WR for the LNet message
710          * And ibc_max_frags for the transfer WRs
711          */
712         int ret;
713         int multiplier = 1 + conn->ibc_max_frags;
714         enum kib_dev_caps dev_caps = conn->ibc_hdev->ibh_dev->ibd_dev_caps;
715
716         /* FastReg needs two extra WRs for map and invalidate */
717         if (dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED)
718                 multiplier += 2;
719
720         /* account for a maximum of ibc_queue_depth in-flight transfers */
721         ret = multiplier * conn->ibc_queue_depth;
722
723         if (ret > conn->ibc_hdev->ibh_max_qp_wr) {
724                 CDEBUG(D_NET, "peer_credits %u will result in send work "
725                        "request size %d larger than maximum %d device "
726                        "can handle\n", conn->ibc_queue_depth, ret,
727                        conn->ibc_hdev->ibh_max_qp_wr);
728                 conn->ibc_queue_depth =
729                         conn->ibc_hdev->ibh_max_qp_wr / multiplier;
730         }
731
732         /* don't go beyond the maximum the device can handle */
733         return min(ret, conn->ibc_hdev->ibh_max_qp_wr);
734 }
735
736 struct kib_conn *
737 kiblnd_create_conn(struct kib_peer_ni *peer_ni, struct rdma_cm_id *cmid,
738                    int state, int version)
739 {
740         /* CAVEAT EMPTOR:
741          * If the new conn is created successfully it takes over the caller's
742          * ref on 'peer_ni'.  It also "owns" 'cmid' and destroys it when it itself
743          * is destroyed.  On failure, the caller's ref on 'peer_ni' remains and
744          * she must dispose of 'cmid'.  (Actually I'd block forever if I tried
745          * to destroy 'cmid' here since I'm called from the CM which still has
746          * its ref on 'cmid'). */
747         rwlock_t               *glock = &kiblnd_data.kib_global_lock;
748         struct kib_net              *net = peer_ni->ibp_ni->ni_data;
749         struct kib_dev *dev;
750         struct ib_qp_init_attr init_qp_attr = {};
751         struct kib_sched_info   *sched;
752 #ifdef HAVE_IB_CQ_INIT_ATTR
753         struct ib_cq_init_attr  cq_attr = {};
754 #endif
755         struct kib_conn *conn;
756         struct ib_cq            *cq;
757         unsigned long           flags;
758         int                     cpt;
759         int                     rc;
760         int                     i;
761
762         LASSERT(net != NULL);
763         LASSERT(!in_interrupt());
764
765         dev = net->ibn_dev;
766
767         cpt = lnet_cpt_of_nid(peer_ni->ibp_nid, peer_ni->ibp_ni);
768         sched = kiblnd_get_scheduler(cpt);
769
770         if (sched == NULL) {
771                 CERROR("no schedulers available. node is unhealthy\n");
772                 goto failed_0;
773         }
774
775         /*
776          * The cpt might have changed if we ended up selecting a non cpt
777          * native scheduler. So use the scheduler's cpt instead.
778          */
779         cpt = sched->ibs_cpt;
780
781         LIBCFS_CPT_ALLOC(conn, lnet_cpt_table(), cpt, sizeof(*conn));
782         if (conn == NULL) {
783                 CERROR("Can't allocate connection for %s\n",
784                        libcfs_nid2str(peer_ni->ibp_nid));
785                 goto failed_0;
786         }
787
788         conn->ibc_state = IBLND_CONN_INIT;
789         conn->ibc_version = version;
790         conn->ibc_peer = peer_ni;                       /* I take the caller's ref */
791         cmid->context = conn;                   /* for future CM callbacks */
792         conn->ibc_cmid = cmid;
793         conn->ibc_max_frags = peer_ni->ibp_max_frags;
794         conn->ibc_queue_depth = peer_ni->ibp_queue_depth;
795         conn->ibc_rxs = NULL;
796         conn->ibc_rx_pages = NULL;
797
798         INIT_LIST_HEAD(&conn->ibc_early_rxs);
799         INIT_LIST_HEAD(&conn->ibc_tx_noops);
800         INIT_LIST_HEAD(&conn->ibc_tx_queue);
801         INIT_LIST_HEAD(&conn->ibc_tx_queue_rsrvd);
802         INIT_LIST_HEAD(&conn->ibc_tx_queue_nocred);
803         INIT_LIST_HEAD(&conn->ibc_active_txs);
804         INIT_LIST_HEAD(&conn->ibc_zombie_txs);
805         spin_lock_init(&conn->ibc_lock);
806
807         LIBCFS_CPT_ALLOC(conn->ibc_connvars, lnet_cpt_table(), cpt,
808                          sizeof(*conn->ibc_connvars));
809         if (conn->ibc_connvars == NULL) {
810                 CERROR("Can't allocate in-progress connection state\n");
811                 goto failed_2;
812         }
813
814         write_lock_irqsave(glock, flags);
815         if (dev->ibd_failover) {
816                 write_unlock_irqrestore(glock, flags);
817                 CERROR("%s: failover in progress\n", dev->ibd_ifname);
818                 goto failed_2;
819         }
820
821         if (dev->ibd_hdev->ibh_ibdev != cmid->device) {
822                 /* wakeup failover thread and teardown connection */
823                 if (kiblnd_dev_can_failover(dev)) {
824                         list_add_tail(&dev->ibd_fail_list,
825                                       &kiblnd_data.kib_failed_devs);
826                         wake_up(&kiblnd_data.kib_failover_waitq);
827                 }
828
829                 write_unlock_irqrestore(glock, flags);
830                 CERROR("cmid HCA(%s), kib_dev(%s) need failover\n",
831                        cmid->device->name, dev->ibd_ifname);
832                 goto failed_2;
833         }
834
835         kiblnd_hdev_addref_locked(dev->ibd_hdev);
836         conn->ibc_hdev = dev->ibd_hdev;
837
838         kiblnd_setup_mtu_locked(cmid);
839
840         write_unlock_irqrestore(glock, flags);
841
842 #ifdef HAVE_IB_CQ_INIT_ATTR
843         cq_attr.cqe = IBLND_CQ_ENTRIES(conn);
844         cq_attr.comp_vector = kiblnd_get_completion_vector(conn, cpt);
845         cq = ib_create_cq(cmid->device,
846                           kiblnd_cq_completion, kiblnd_cq_event, conn,
847                           &cq_attr);
848 #else
849         cq = ib_create_cq(cmid->device,
850                           kiblnd_cq_completion, kiblnd_cq_event, conn,
851                           IBLND_CQ_ENTRIES(conn),
852                           kiblnd_get_completion_vector(conn, cpt));
853 #endif
854         if (IS_ERR(cq)) {
855                 /*
856                  * on MLX-5 (possibly MLX-4 as well) this error could be
857                  * hit if the concurrent_sends and/or peer_tx_credits is set
858                  * too high. Or due to an MLX-5 bug which tries to
859                  * allocate 256kb via kmalloc for WR cookie array
860                  */
861                 CERROR("Failed to create CQ with %d CQEs: %ld\n",
862                         IBLND_CQ_ENTRIES(conn), PTR_ERR(cq));
863                 goto failed_2;
864         }
865
866         conn->ibc_cq = cq;
867
868         rc = ib_req_notify_cq(cq, IB_CQ_NEXT_COMP);
869         if (rc != 0) {
870                 CERROR("Can't request completion notification: %d\n", rc);
871                 goto failed_2;
872         }
873
874         init_qp_attr.event_handler = kiblnd_qp_event;
875         init_qp_attr.qp_context = conn;
876         init_qp_attr.cap.max_send_sge = *kiblnd_tunables.kib_wrq_sge;
877         init_qp_attr.cap.max_recv_sge = 1;
878         init_qp_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
879         init_qp_attr.qp_type = IB_QPT_RC;
880         init_qp_attr.send_cq = cq;
881         init_qp_attr.recv_cq = cq;
882
883         if (peer_ni->ibp_queue_depth_mod &&
884             peer_ni->ibp_queue_depth_mod < peer_ni->ibp_queue_depth) {
885                 conn->ibc_queue_depth = peer_ni->ibp_queue_depth_mod;
886                 CDEBUG(D_NET, "Use reduced queue depth %u (from %u)\n",
887                        peer_ni->ibp_queue_depth_mod,
888                        peer_ni->ibp_queue_depth);
889         }
890
891         do {
892                 /* kiblnd_send_wrs() can change the connection's queue depth if
893                  * the maximum work requests for the device is maxed out
894                  */
895                 init_qp_attr.cap.max_send_wr = kiblnd_send_wrs(conn);
896                 init_qp_attr.cap.max_recv_wr = IBLND_RECV_WRS(conn);
897                 rc = rdma_create_qp(cmid, conn->ibc_hdev->ibh_pd,
898                                     &init_qp_attr);
899                 if (rc != -ENOMEM || conn->ibc_queue_depth < 2)
900                         break;
901                 conn->ibc_queue_depth--;
902         } while (rc);
903
904         if (rc) {
905                 CERROR("Can't create QP: %d, send_wr: %d, recv_wr: %d, "
906                        "send_sge: %d, recv_sge: %d\n",
907                        rc, init_qp_attr.cap.max_send_wr,
908                        init_qp_attr.cap.max_recv_wr,
909                        init_qp_attr.cap.max_send_sge,
910                        init_qp_attr.cap.max_recv_sge);
911                 goto failed_2;
912         }
913
914         conn->ibc_sched = sched;
915
916         if (!peer_ni->ibp_queue_depth_mod &&
917             conn->ibc_queue_depth != peer_ni->ibp_queue_depth) {
918                 CWARN("peer %s - queue depth reduced from %u to %u"
919                       "  to allow for qp creation\n",
920                       libcfs_nid2str(peer_ni->ibp_nid),
921                       peer_ni->ibp_queue_depth,
922                       conn->ibc_queue_depth);
923                 peer_ni->ibp_queue_depth_mod = conn->ibc_queue_depth;
924         }
925
926         LIBCFS_CPT_ALLOC(conn->ibc_rxs, lnet_cpt_table(), cpt,
927                          IBLND_RX_MSGS(conn) * sizeof(struct kib_rx));
928         if (conn->ibc_rxs == NULL) {
929                 CERROR("Cannot allocate RX buffers\n");
930                 goto failed_2;
931         }
932
933         rc = kiblnd_alloc_pages(&conn->ibc_rx_pages, cpt,
934                                 IBLND_RX_MSG_PAGES(conn));
935         if (rc != 0)
936                 goto failed_2;
937
938         kiblnd_map_rx_descs(conn);
939
940         /* 1 ref for caller and each rxmsg */
941         atomic_set(&conn->ibc_refcount, 1 + IBLND_RX_MSGS(conn));
942         conn->ibc_nrx = IBLND_RX_MSGS(conn);
943
944         /* post receives */
945         for (i = 0; i < IBLND_RX_MSGS(conn); i++) {
946                 rc = kiblnd_post_rx(&conn->ibc_rxs[i], IBLND_POSTRX_NO_CREDIT);
947                 if (rc != 0) {
948                         CERROR("Can't post rxmsg: %d\n", rc);
949
950                         /* Make posted receives complete */
951                         kiblnd_abort_receives(conn);
952
953                         /* correct # of posted buffers
954                          * NB locking needed now I'm racing with completion */
955                         spin_lock_irqsave(&sched->ibs_lock, flags);
956                         conn->ibc_nrx -= IBLND_RX_MSGS(conn) - i;
957                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
958
959                         /* cmid will be destroyed by CM(ofed) after cm_callback
960                          * returned, so we can't refer it anymore
961                          * (by kiblnd_connd()->kiblnd_destroy_conn) */
962                         rdma_destroy_qp(conn->ibc_cmid);
963                         conn->ibc_cmid = NULL;
964
965                         /* Drop my own and unused rxbuffer refcounts */
966                         while (i++ <= IBLND_RX_MSGS(conn))
967                                 kiblnd_conn_decref(conn);
968
969                         return NULL;
970                 }
971         }
972
973         /* Init successful! */
974         LASSERT (state == IBLND_CONN_ACTIVE_CONNECT ||
975                  state == IBLND_CONN_PASSIVE_WAIT);
976         conn->ibc_state = state;
977
978         /* 1 more conn */
979         atomic_inc(&net->ibn_nconns);
980         return conn;
981
982  failed_2:
983         kiblnd_destroy_conn(conn);
984         LIBCFS_FREE(conn, sizeof(*conn));
985  failed_0:
986         return NULL;
987 }
988
989 void
990 kiblnd_destroy_conn(struct kib_conn *conn)
991 {
992         struct rdma_cm_id *cmid = conn->ibc_cmid;
993         struct kib_peer_ni *peer_ni = conn->ibc_peer;
994
995         LASSERT (!in_interrupt());
996         LASSERT (atomic_read(&conn->ibc_refcount) == 0);
997         LASSERT(list_empty(&conn->ibc_early_rxs));
998         LASSERT(list_empty(&conn->ibc_tx_noops));
999         LASSERT(list_empty(&conn->ibc_tx_queue));
1000         LASSERT(list_empty(&conn->ibc_tx_queue_rsrvd));
1001         LASSERT(list_empty(&conn->ibc_tx_queue_nocred));
1002         LASSERT(list_empty(&conn->ibc_active_txs));
1003         LASSERT (conn->ibc_noops_posted == 0);
1004         LASSERT (conn->ibc_nsends_posted == 0);
1005
1006         switch (conn->ibc_state) {
1007         default:
1008                 /* conn must be completely disengaged from the network */
1009                 LBUG();
1010
1011         case IBLND_CONN_DISCONNECTED:
1012                 /* connvars should have been freed already */
1013                 LASSERT (conn->ibc_connvars == NULL);
1014                 break;
1015
1016         case IBLND_CONN_INIT:
1017                 break;
1018         }
1019
1020         /* conn->ibc_cmid might be destroyed by CM already */
1021         if (cmid != NULL && cmid->qp != NULL)
1022                 rdma_destroy_qp(cmid);
1023
1024         if (conn->ibc_cq)
1025                 ib_destroy_cq(conn->ibc_cq);
1026
1027         kiblnd_txlist_done(&conn->ibc_zombie_txs, -ECONNABORTED,
1028                            LNET_MSG_STATUS_OK);
1029
1030         if (conn->ibc_rx_pages != NULL)
1031                 kiblnd_unmap_rx_descs(conn);
1032
1033         if (conn->ibc_rxs != NULL)
1034                 CFS_FREE_PTR_ARRAY(conn->ibc_rxs, IBLND_RX_MSGS(conn));
1035
1036         if (conn->ibc_connvars != NULL)
1037                 LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
1038
1039         if (conn->ibc_hdev != NULL)
1040                 kiblnd_hdev_decref(conn->ibc_hdev);
1041
1042         /* See CAVEAT EMPTOR above in kiblnd_create_conn */
1043         if (conn->ibc_state != IBLND_CONN_INIT) {
1044                 struct kib_net *net = peer_ni->ibp_ni->ni_data;
1045
1046                 kiblnd_peer_decref(peer_ni);
1047                 rdma_destroy_id(cmid);
1048                 atomic_dec(&net->ibn_nconns);
1049         }
1050 }
1051
1052 int
1053 kiblnd_close_peer_conns_locked(struct kib_peer_ni *peer_ni, int why)
1054 {
1055         struct kib_conn *conn;
1056         struct kib_conn *cnxt;
1057         int count = 0;
1058
1059         list_for_each_entry_safe(conn, cnxt, &peer_ni->ibp_conns,
1060                                  ibc_list) {
1061                 CDEBUG(D_NET, "Closing conn -> %s, "
1062                               "version: %x, reason: %d\n",
1063                        libcfs_nid2str(peer_ni->ibp_nid),
1064                        conn->ibc_version, why);
1065
1066                 kiblnd_close_conn_locked(conn, why);
1067                 count++;
1068         }
1069
1070         return count;
1071 }
1072
1073 int
1074 kiblnd_close_stale_conns_locked(struct kib_peer_ni *peer_ni,
1075                                 int version, __u64 incarnation)
1076 {
1077         struct kib_conn *conn;
1078         struct kib_conn *cnxt;
1079         int count = 0;
1080
1081         list_for_each_entry_safe(conn, cnxt, &peer_ni->ibp_conns,
1082                                  ibc_list) {
1083                 if (conn->ibc_version     == version &&
1084                     conn->ibc_incarnation == incarnation)
1085                         continue;
1086
1087                 CDEBUG(D_NET, "Closing stale conn -> %s version: %x, "
1088                               "incarnation:%#llx(%x, %#llx)\n",
1089                        libcfs_nid2str(peer_ni->ibp_nid),
1090                        conn->ibc_version, conn->ibc_incarnation,
1091                        version, incarnation);
1092
1093                 kiblnd_close_conn_locked(conn, -ESTALE);
1094                 count++;
1095         }
1096
1097         return count;
1098 }
1099
1100 static int
1101 kiblnd_close_matching_conns(struct lnet_ni *ni, lnet_nid_t nid)
1102 {
1103         struct kib_peer_ni              *peer_ni;
1104         struct list_head        *ptmp;
1105         struct list_head        *pnxt;
1106         int                     lo;
1107         int                     hi;
1108         int                     i;
1109         unsigned long           flags;
1110         int                     count = 0;
1111
1112         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1113
1114         if (nid != LNET_NID_ANY)
1115                 lo = hi = kiblnd_nid2peerlist(nid) - kiblnd_data.kib_peers;
1116         else {
1117                 lo = 0;
1118                 hi = kiblnd_data.kib_peer_hash_size - 1;
1119         }
1120
1121         for (i = lo; i <= hi; i++) {
1122                 list_for_each_safe(ptmp, pnxt, &kiblnd_data.kib_peers[i]) {
1123
1124                         peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
1125                         LASSERT(!kiblnd_peer_idle(peer_ni));
1126
1127                         if (peer_ni->ibp_ni != ni)
1128                                 continue;
1129
1130                         if (!(nid == LNET_NID_ANY || nid == peer_ni->ibp_nid))
1131                                 continue;
1132
1133                         count += kiblnd_close_peer_conns_locked(peer_ni, 0);
1134                 }
1135         }
1136
1137         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1138
1139         /* wildcards always succeed */
1140         if (nid == LNET_NID_ANY)
1141                 return 0;
1142
1143         return (count == 0) ? -ENOENT : 0;
1144 }
1145
1146 static int
1147 kiblnd_ctl(struct lnet_ni *ni, unsigned int cmd, void *arg)
1148 {
1149         struct libcfs_ioctl_data *data = arg;
1150         int                       rc = -EINVAL;
1151
1152         switch(cmd) {
1153         case IOC_LIBCFS_GET_PEER: {
1154                 lnet_nid_t   nid = 0;
1155                 int          count = 0;
1156
1157                 rc = kiblnd_get_peer_info(ni, data->ioc_count,
1158                                           &nid, &count);
1159                 data->ioc_nid    = nid;
1160                 data->ioc_count  = count;
1161                 break;
1162         }
1163
1164         case IOC_LIBCFS_DEL_PEER: {
1165                 rc = kiblnd_del_peer(ni, data->ioc_nid);
1166                 break;
1167         }
1168         case IOC_LIBCFS_GET_CONN: {
1169                 struct kib_conn *conn;
1170
1171                 rc = 0;
1172                 conn = kiblnd_get_conn_by_idx(ni, data->ioc_count);
1173                 if (conn == NULL) {
1174                         rc = -ENOENT;
1175                         break;
1176                 }
1177
1178                 LASSERT(conn->ibc_cmid != NULL);
1179                 data->ioc_nid = conn->ibc_peer->ibp_nid;
1180                 if (conn->ibc_cmid->route.path_rec == NULL)
1181                         data->ioc_u32[0] = 0; /* iWarp has no path MTU */
1182                 else
1183                         data->ioc_u32[0] =
1184                         ib_mtu_enum_to_int(conn->ibc_cmid->route.path_rec->mtu);
1185                 kiblnd_conn_decref(conn);
1186                 break;
1187         }
1188         case IOC_LIBCFS_CLOSE_CONNECTION: {
1189                 rc = kiblnd_close_matching_conns(ni, data->ioc_nid);
1190                 break;
1191         }
1192
1193         default:
1194                 break;
1195         }
1196
1197         return rc;
1198 }
1199
1200 static void
1201 kiblnd_free_pages(struct kib_pages *p)
1202 {
1203         int     npages = p->ibp_npages;
1204         int     i;
1205
1206         for (i = 0; i < npages; i++) {
1207                 if (p->ibp_pages[i] != NULL)
1208                         __free_page(p->ibp_pages[i]);
1209         }
1210
1211         LIBCFS_FREE(p, offsetof(struct kib_pages, ibp_pages[npages]));
1212 }
1213
1214 int
1215 kiblnd_alloc_pages(struct kib_pages **pp, int cpt, int npages)
1216 {
1217         struct kib_pages *p;
1218         int i;
1219
1220         LIBCFS_CPT_ALLOC(p, lnet_cpt_table(), cpt,
1221                          offsetof(struct kib_pages, ibp_pages[npages]));
1222         if (p == NULL) {
1223                 CERROR("Can't allocate descriptor for %d pages\n", npages);
1224                 return -ENOMEM;
1225         }
1226
1227         memset(p, 0, offsetof(struct kib_pages, ibp_pages[npages]));
1228         p->ibp_npages = npages;
1229
1230         for (i = 0; i < npages; i++) {
1231                 p->ibp_pages[i] = cfs_page_cpt_alloc(lnet_cpt_table(), cpt,
1232                                                      GFP_NOFS);
1233                 if (p->ibp_pages[i] == NULL) {
1234                         CERROR("Can't allocate page %d of %d\n", i, npages);
1235                         kiblnd_free_pages(p);
1236                         return -ENOMEM;
1237                 }
1238         }
1239
1240         *pp = p;
1241         return 0;
1242 }
1243
1244 void
1245 kiblnd_unmap_rx_descs(struct kib_conn *conn)
1246 {
1247         struct kib_rx *rx;
1248         int       i;
1249
1250         LASSERT (conn->ibc_rxs != NULL);
1251         LASSERT (conn->ibc_hdev != NULL);
1252
1253         for (i = 0; i < IBLND_RX_MSGS(conn); i++) {
1254                 rx = &conn->ibc_rxs[i];
1255
1256                 LASSERT(rx->rx_nob >= 0); /* not posted */
1257
1258                 kiblnd_dma_unmap_single(conn->ibc_hdev->ibh_ibdev,
1259                                         KIBLND_UNMAP_ADDR(rx, rx_msgunmap,
1260                                                           rx->rx_msgaddr),
1261                                         IBLND_MSG_SIZE, DMA_FROM_DEVICE);
1262         }
1263
1264         kiblnd_free_pages(conn->ibc_rx_pages);
1265
1266         conn->ibc_rx_pages = NULL;
1267 }
1268
1269 void
1270 kiblnd_map_rx_descs(struct kib_conn *conn)
1271 {
1272         struct kib_rx *rx;
1273         struct page    *pg;
1274         int             pg_off;
1275         int             ipg;
1276         int             i;
1277
1278         for (pg_off = ipg = i = 0; i < IBLND_RX_MSGS(conn); i++) {
1279                 pg = conn->ibc_rx_pages->ibp_pages[ipg];
1280                 rx = &conn->ibc_rxs[i];
1281
1282                 rx->rx_conn = conn;
1283                 rx->rx_msg = (struct kib_msg *)(((char *)page_address(pg)) + pg_off);
1284
1285                 rx->rx_msgaddr =
1286                         kiblnd_dma_map_single(conn->ibc_hdev->ibh_ibdev,
1287                                               rx->rx_msg, IBLND_MSG_SIZE,
1288                                               DMA_FROM_DEVICE);
1289                 LASSERT(!kiblnd_dma_mapping_error(conn->ibc_hdev->ibh_ibdev,
1290                                                   rx->rx_msgaddr));
1291                 KIBLND_UNMAP_ADDR_SET(rx, rx_msgunmap, rx->rx_msgaddr);
1292
1293                 CDEBUG(D_NET, "rx %d: %p %#llx(%#llx)\n",
1294                        i, rx->rx_msg, rx->rx_msgaddr,
1295                        (__u64)(page_to_phys(pg) + pg_off));
1296
1297                 pg_off += IBLND_MSG_SIZE;
1298                 LASSERT(pg_off <= PAGE_SIZE);
1299
1300                 if (pg_off == PAGE_SIZE) {
1301                         pg_off = 0;
1302                         ipg++;
1303                         LASSERT(ipg <= IBLND_RX_MSG_PAGES(conn));
1304                 }
1305         }
1306 }
1307
1308 static void
1309 kiblnd_unmap_tx_pool(struct kib_tx_pool *tpo)
1310 {
1311         struct kib_hca_dev *hdev = tpo->tpo_hdev;
1312         struct kib_tx *tx;
1313         int i;
1314
1315         LASSERT (tpo->tpo_pool.po_allocated == 0);
1316
1317         if (hdev == NULL)
1318                 return;
1319
1320         for (i = 0; i < tpo->tpo_pool.po_size; i++) {
1321                 tx = &tpo->tpo_tx_descs[i];
1322                 kiblnd_dma_unmap_single(hdev->ibh_ibdev,
1323                                         KIBLND_UNMAP_ADDR(tx, tx_msgunmap,
1324                                                           tx->tx_msgaddr),
1325                                         IBLND_MSG_SIZE, DMA_TO_DEVICE);
1326         }
1327
1328         kiblnd_hdev_decref(hdev);
1329         tpo->tpo_hdev = NULL;
1330 }
1331
1332 static struct kib_hca_dev *
1333 kiblnd_current_hdev(struct kib_dev *dev)
1334 {
1335         struct kib_hca_dev *hdev;
1336         unsigned long  flags;
1337         int            i = 0;
1338
1339         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1340         while (dev->ibd_failover) {
1341                 read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1342                 if (i++ % 50 == 0)
1343                         CDEBUG(D_NET, "%s: Wait for failover\n",
1344                                dev->ibd_ifname);
1345                 schedule_timeout_interruptible(cfs_time_seconds(1) / 100);
1346
1347                 read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1348         }
1349
1350         kiblnd_hdev_addref_locked(dev->ibd_hdev);
1351         hdev = dev->ibd_hdev;
1352
1353         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1354
1355         return hdev;
1356 }
1357
1358 static void
1359 kiblnd_map_tx_pool(struct kib_tx_pool *tpo)
1360 {
1361         struct kib_pages *txpgs = tpo->tpo_tx_pages;
1362         struct kib_pool *pool = &tpo->tpo_pool;
1363         struct kib_net      *net   = pool->po_owner->ps_net;
1364         struct kib_dev *dev;
1365         struct page *page;
1366         struct kib_tx *tx;
1367         int             page_offset;
1368         int             ipage;
1369         int             i;
1370
1371         LASSERT (net != NULL);
1372
1373         dev = net->ibn_dev;
1374
1375         /* pre-mapped messages are not bigger than 1 page */
1376         BUILD_BUG_ON(IBLND_MSG_SIZE > PAGE_SIZE);
1377
1378         /* No fancy arithmetic when we do the buffer calculations */
1379         BUILD_BUG_ON(PAGE_SIZE % IBLND_MSG_SIZE != 0);
1380
1381         tpo->tpo_hdev = kiblnd_current_hdev(dev);
1382
1383         for (ipage = page_offset = i = 0; i < pool->po_size; i++) {
1384                 page = txpgs->ibp_pages[ipage];
1385                 tx = &tpo->tpo_tx_descs[i];
1386
1387                 tx->tx_msg = (struct kib_msg *)(((char *)page_address(page)) +
1388                                                 page_offset);
1389
1390                 tx->tx_msgaddr = kiblnd_dma_map_single(tpo->tpo_hdev->ibh_ibdev,
1391                                                        tx->tx_msg,
1392                                                        IBLND_MSG_SIZE,
1393                                                        DMA_TO_DEVICE);
1394                 LASSERT(!kiblnd_dma_mapping_error(tpo->tpo_hdev->ibh_ibdev,
1395                                                   tx->tx_msgaddr));
1396                 KIBLND_UNMAP_ADDR_SET(tx, tx_msgunmap, tx->tx_msgaddr);
1397
1398                 list_add(&tx->tx_list, &pool->po_free_list);
1399
1400                 page_offset += IBLND_MSG_SIZE;
1401                 LASSERT(page_offset <= PAGE_SIZE);
1402
1403                 if (page_offset == PAGE_SIZE) {
1404                         page_offset = 0;
1405                         ipage++;
1406                         LASSERT(ipage <= txpgs->ibp_npages);
1407                 }
1408         }
1409 }
1410
1411 static void
1412 kiblnd_destroy_fmr_pool(struct kib_fmr_pool *fpo)
1413 {
1414         LASSERT(fpo->fpo_map_count == 0);
1415
1416         if (fpo->fpo_is_fmr && fpo->fmr.fpo_fmr_pool) {
1417                 ib_destroy_fmr_pool(fpo->fmr.fpo_fmr_pool);
1418         } else {
1419                 struct kib_fast_reg_descriptor *frd, *tmp;
1420                 int i = 0;
1421
1422                 list_for_each_entry_safe(frd, tmp, &fpo->fast_reg.fpo_pool_list,
1423                                          frd_list) {
1424                         list_del(&frd->frd_list);
1425 #ifndef HAVE_IB_MAP_MR_SG
1426                         ib_free_fast_reg_page_list(frd->frd_frpl);
1427 #endif
1428                         ib_dereg_mr(frd->frd_mr);
1429                         LIBCFS_FREE(frd, sizeof(*frd));
1430                         i++;
1431                 }
1432                 if (i < fpo->fast_reg.fpo_pool_size)
1433                         CERROR("FastReg pool still has %d regions registered\n",
1434                                 fpo->fast_reg.fpo_pool_size - i);
1435         }
1436
1437         if (fpo->fpo_hdev)
1438                 kiblnd_hdev_decref(fpo->fpo_hdev);
1439
1440         LIBCFS_FREE(fpo, sizeof(*fpo));
1441 }
1442
1443 static void
1444 kiblnd_destroy_fmr_pool_list(struct list_head *head)
1445 {
1446         struct kib_fmr_pool *fpo, *tmp;
1447
1448         list_for_each_entry_safe(fpo, tmp, head, fpo_list) {
1449                 list_del(&fpo->fpo_list);
1450                 kiblnd_destroy_fmr_pool(fpo);
1451         }
1452 }
1453
1454 static int
1455 kiblnd_fmr_pool_size(struct lnet_ioctl_config_o2iblnd_tunables *tunables,
1456                      int ncpts)
1457 {
1458         int size = tunables->lnd_fmr_pool_size / ncpts;
1459
1460         return max(IBLND_FMR_POOL, size);
1461 }
1462
1463 static int
1464 kiblnd_fmr_flush_trigger(struct lnet_ioctl_config_o2iblnd_tunables *tunables,
1465                          int ncpts)
1466 {
1467         int size = tunables->lnd_fmr_flush_trigger / ncpts;
1468
1469         return max(IBLND_FMR_POOL_FLUSH, size);
1470 }
1471
1472 static int kiblnd_alloc_fmr_pool(struct kib_fmr_poolset *fps,
1473                                  struct kib_fmr_pool *fpo)
1474 {
1475         struct ib_fmr_pool_param param = {
1476                 .max_pages_per_fmr = LNET_MAX_IOV,
1477                 .page_shift        = PAGE_SHIFT,
1478                 .access            = (IB_ACCESS_LOCAL_WRITE |
1479                                       IB_ACCESS_REMOTE_WRITE),
1480                 .pool_size         = fps->fps_pool_size,
1481                 .dirty_watermark   = fps->fps_flush_trigger,
1482                 .flush_function    = NULL,
1483                 .flush_arg         = NULL,
1484                 .cache             = !!fps->fps_cache };
1485         int rc = 0;
1486
1487         fpo->fmr.fpo_fmr_pool = ib_create_fmr_pool(fpo->fpo_hdev->ibh_pd,
1488                                                    &param);
1489         if (IS_ERR(fpo->fmr.fpo_fmr_pool)) {
1490                 rc = PTR_ERR(fpo->fmr.fpo_fmr_pool);
1491                 if (rc != -ENOSYS)
1492                         CERROR("Failed to create FMR pool: %d\n", rc);
1493                 else
1494                         CERROR("FMRs are not supported\n");
1495         }
1496         fpo->fpo_is_fmr = true;
1497
1498         return rc;
1499 }
1500
1501 static int kiblnd_alloc_freg_pool(struct kib_fmr_poolset *fps,
1502                                   struct kib_fmr_pool *fpo,
1503                                   enum kib_dev_caps dev_caps)
1504 {
1505         struct kib_fast_reg_descriptor *frd, *tmp;
1506         int i, rc;
1507
1508         fpo->fpo_is_fmr = false;
1509
1510         INIT_LIST_HEAD(&fpo->fast_reg.fpo_pool_list);
1511         fpo->fast_reg.fpo_pool_size = 0;
1512         for (i = 0; i < fps->fps_pool_size; i++) {
1513                 LIBCFS_CPT_ALLOC(frd, lnet_cpt_table(), fps->fps_cpt,
1514                                  sizeof(*frd));
1515                 if (!frd) {
1516                         CERROR("Failed to allocate a new fast_reg descriptor\n");
1517                         rc = -ENOMEM;
1518                         goto out;
1519                 }
1520                 frd->frd_mr = NULL;
1521
1522 #ifndef HAVE_IB_MAP_MR_SG
1523                 frd->frd_frpl = ib_alloc_fast_reg_page_list(fpo->fpo_hdev->ibh_ibdev,
1524                                                             LNET_MAX_IOV);
1525                 if (IS_ERR(frd->frd_frpl)) {
1526                         rc = PTR_ERR(frd->frd_frpl);
1527                         CERROR("Failed to allocate ib_fast_reg_page_list: %d\n",
1528                                 rc);
1529                         frd->frd_frpl = NULL;
1530                         goto out_middle;
1531                 }
1532 #endif
1533
1534 #ifdef HAVE_IB_ALLOC_FAST_REG_MR
1535                 frd->frd_mr = ib_alloc_fast_reg_mr(fpo->fpo_hdev->ibh_pd,
1536                                                    LNET_MAX_IOV);
1537 #else
1538                 /*
1539                  * it is expected to get here if this is an MLX-5 card.
1540                  * MLX-4 cards will always use FMR and MLX-5 cards will
1541                  * always use fast_reg. It turns out that some MLX-5 cards
1542                  * (possibly due to older FW versions) do not natively support
1543                  * gaps. So we will need to track them here.
1544                  */
1545                 frd->frd_mr = ib_alloc_mr(fpo->fpo_hdev->ibh_pd,
1546 #ifdef IB_MR_TYPE_SG_GAPS
1547                                           ((*kiblnd_tunables.kib_use_fastreg_gaps == 1) &&
1548                                            (dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT)) ?
1549                                                 IB_MR_TYPE_SG_GAPS :
1550                                                 IB_MR_TYPE_MEM_REG,
1551 #else
1552                                                 IB_MR_TYPE_MEM_REG,
1553 #endif
1554                                           LNET_MAX_IOV);
1555                 if ((*kiblnd_tunables.kib_use_fastreg_gaps == 1) &&
1556                     (dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT))
1557                         CWARN("using IB_MR_TYPE_SG_GAPS, expect a performance drop\n");
1558 #endif
1559                 if (IS_ERR(frd->frd_mr)) {
1560                         rc = PTR_ERR(frd->frd_mr);
1561                         CERROR("Failed to allocate ib_fast_reg_mr: %d\n", rc);
1562                         frd->frd_mr = NULL;
1563                         goto out_middle;
1564                 }
1565
1566                 /* There appears to be a bug in MLX5 code where you must
1567                  * invalidate the rkey of a new FastReg pool before first
1568                  * using it. Thus, I am marking the FRD invalid here. */
1569                 frd->frd_valid = false;
1570
1571                 list_add_tail(&frd->frd_list, &fpo->fast_reg.fpo_pool_list);
1572                 fpo->fast_reg.fpo_pool_size++;
1573         }
1574
1575         return 0;
1576
1577 out_middle:
1578         if (frd->frd_mr)
1579                 ib_dereg_mr(frd->frd_mr);
1580 #ifndef HAVE_IB_MAP_MR_SG
1581         if (frd->frd_frpl)
1582                 ib_free_fast_reg_page_list(frd->frd_frpl);
1583 #endif
1584         LIBCFS_FREE(frd, sizeof(*frd));
1585
1586 out:
1587         list_for_each_entry_safe(frd, tmp, &fpo->fast_reg.fpo_pool_list,
1588                                  frd_list) {
1589                 list_del(&frd->frd_list);
1590 #ifndef HAVE_IB_MAP_MR_SG
1591                 ib_free_fast_reg_page_list(frd->frd_frpl);
1592 #endif
1593                 ib_dereg_mr(frd->frd_mr);
1594                 LIBCFS_FREE(frd, sizeof(*frd));
1595         }
1596
1597         return rc;
1598 }
1599
1600 static int kiblnd_create_fmr_pool(struct kib_fmr_poolset *fps,
1601                                   struct kib_fmr_pool **pp_fpo)
1602 {
1603         struct kib_dev *dev = fps->fps_net->ibn_dev;
1604         struct kib_fmr_pool *fpo;
1605         int rc;
1606
1607         LIBCFS_CPT_ALLOC(fpo, lnet_cpt_table(), fps->fps_cpt, sizeof(*fpo));
1608         if (!fpo) {
1609                 return -ENOMEM;
1610         }
1611         memset(fpo, 0, sizeof(*fpo));
1612
1613         fpo->fpo_hdev = kiblnd_current_hdev(dev);
1614
1615         if (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)
1616                 rc = kiblnd_alloc_fmr_pool(fps, fpo);
1617         else
1618                 rc = kiblnd_alloc_freg_pool(fps, fpo, dev->ibd_dev_caps);
1619         if (rc)
1620                 goto out_fpo;
1621
1622         fpo->fpo_deadline = ktime_get_seconds() + IBLND_POOL_DEADLINE;
1623         fpo->fpo_owner = fps;
1624         *pp_fpo = fpo;
1625
1626         return 0;
1627
1628 out_fpo:
1629         kiblnd_hdev_decref(fpo->fpo_hdev);
1630         LIBCFS_FREE(fpo, sizeof(*fpo));
1631         return rc;
1632 }
1633
1634 static void
1635 kiblnd_fail_fmr_poolset(struct kib_fmr_poolset *fps, struct list_head *zombies)
1636 {
1637         if (fps->fps_net == NULL) /* intialized? */
1638                 return;
1639
1640         spin_lock(&fps->fps_lock);
1641
1642         while (!list_empty(&fps->fps_pool_list)) {
1643                 struct kib_fmr_pool *fpo = list_entry(fps->fps_pool_list.next,
1644                                                       struct kib_fmr_pool,
1645                                                       fpo_list);
1646
1647                 fpo->fpo_failed = 1;
1648                 if (fpo->fpo_map_count == 0)
1649                         list_move(&fpo->fpo_list, zombies);
1650                 else
1651                         list_move(&fpo->fpo_list, &fps->fps_failed_pool_list);
1652         }
1653
1654         spin_unlock(&fps->fps_lock);
1655 }
1656
1657 static void
1658 kiblnd_fini_fmr_poolset(struct kib_fmr_poolset *fps)
1659 {
1660         if (fps->fps_net != NULL) { /* initialized? */
1661                 kiblnd_destroy_fmr_pool_list(&fps->fps_failed_pool_list);
1662                 kiblnd_destroy_fmr_pool_list(&fps->fps_pool_list);
1663         }
1664 }
1665
1666 static int
1667 kiblnd_init_fmr_poolset(struct kib_fmr_poolset *fps, int cpt, int ncpts,
1668                         struct kib_net *net,
1669                         struct lnet_ioctl_config_o2iblnd_tunables *tunables)
1670 {
1671         struct kib_fmr_pool *fpo;
1672         int rc;
1673
1674         memset(fps, 0, sizeof(struct kib_fmr_poolset));
1675
1676         fps->fps_net = net;
1677         fps->fps_cpt = cpt;
1678
1679         fps->fps_pool_size = kiblnd_fmr_pool_size(tunables, ncpts);
1680         fps->fps_flush_trigger = kiblnd_fmr_flush_trigger(tunables, ncpts);
1681         fps->fps_cache = tunables->lnd_fmr_cache;
1682
1683         spin_lock_init(&fps->fps_lock);
1684         INIT_LIST_HEAD(&fps->fps_pool_list);
1685         INIT_LIST_HEAD(&fps->fps_failed_pool_list);
1686
1687         rc = kiblnd_create_fmr_pool(fps, &fpo);
1688         if (rc == 0)
1689                 list_add_tail(&fpo->fpo_list, &fps->fps_pool_list);
1690
1691         return rc;
1692 }
1693
1694 static int
1695 kiblnd_fmr_pool_is_idle(struct kib_fmr_pool *fpo, time64_t now)
1696 {
1697         if (fpo->fpo_map_count != 0) /* still in use */
1698                 return 0;
1699         if (fpo->fpo_failed)
1700                 return 1;
1701         return now >= fpo->fpo_deadline;
1702 }
1703
1704 static int
1705 kiblnd_map_tx_pages(struct kib_tx *tx, struct kib_rdma_desc *rd)
1706 {
1707         struct kib_hca_dev *hdev;
1708         __u64           *pages = tx->tx_pages;
1709         int             npages;
1710         int             size;
1711         int             i;
1712
1713         hdev = tx->tx_pool->tpo_hdev;
1714
1715         for (i = 0, npages = 0; i < rd->rd_nfrags; i++) {
1716                 for (size = 0; size <  rd->rd_frags[i].rf_nob;
1717                         size += hdev->ibh_page_size) {
1718                         pages[npages++] = (rd->rd_frags[i].rf_addr &
1719                                            hdev->ibh_page_mask) + size;
1720                 }
1721         }
1722
1723         return npages;
1724 }
1725
1726 void
1727 kiblnd_fmr_pool_unmap(struct kib_fmr *fmr, int status)
1728 {
1729         LIST_HEAD(zombies);
1730         struct kib_fmr_pool *fpo = fmr->fmr_pool;
1731         struct kib_fmr_poolset *fps;
1732         time64_t now = ktime_get_seconds();
1733         struct kib_fmr_pool *tmp;
1734         int rc;
1735
1736         if (!fpo)
1737                 return;
1738
1739         fps = fpo->fpo_owner;
1740         if (fpo->fpo_is_fmr) {
1741                 if (fmr->fmr_pfmr) {
1742                         ib_fmr_pool_unmap(fmr->fmr_pfmr);
1743                         fmr->fmr_pfmr = NULL;
1744                 }
1745
1746                 if (status) {
1747                         rc = ib_flush_fmr_pool(fpo->fmr.fpo_fmr_pool);
1748                         LASSERT(!rc);
1749                 }
1750         } else {
1751                 struct kib_fast_reg_descriptor *frd = fmr->fmr_frd;
1752
1753                 if (frd) {
1754                         frd->frd_valid = false;
1755                         spin_lock(&fps->fps_lock);
1756                         list_add_tail(&frd->frd_list, &fpo->fast_reg.fpo_pool_list);
1757                         spin_unlock(&fps->fps_lock);
1758                         fmr->fmr_frd = NULL;
1759                 }
1760         }
1761         fmr->fmr_pool = NULL;
1762
1763         spin_lock(&fps->fps_lock);
1764         fpo->fpo_map_count--;   /* decref the pool */
1765
1766         list_for_each_entry_safe(fpo, tmp, &fps->fps_pool_list, fpo_list) {
1767                 /* the first pool is persistent */
1768                 if (fps->fps_pool_list.next == &fpo->fpo_list)
1769                         continue;
1770
1771                 if (kiblnd_fmr_pool_is_idle(fpo, now)) {
1772                         list_move(&fpo->fpo_list, &zombies);
1773                         fps->fps_version++;
1774                 }
1775         }
1776         spin_unlock(&fps->fps_lock);
1777
1778         if (!list_empty(&zombies))
1779                 kiblnd_destroy_fmr_pool_list(&zombies);
1780 }
1781
1782 int kiblnd_fmr_pool_map(struct kib_fmr_poolset *fps, struct kib_tx *tx,
1783                         struct kib_rdma_desc *rd, u32 nob, u64 iov,
1784                         struct kib_fmr *fmr)
1785 {
1786         struct kib_fmr_pool *fpo;
1787         __u64 *pages = tx->tx_pages;
1788         __u64 version;
1789         bool is_rx = (rd != tx->tx_rd);
1790         bool tx_pages_mapped = 0;
1791         int npages = 0;
1792         int rc;
1793
1794 again:
1795         spin_lock(&fps->fps_lock);
1796         version = fps->fps_version;
1797         list_for_each_entry(fpo, &fps->fps_pool_list, fpo_list) {
1798                 fpo->fpo_deadline = ktime_get_seconds() + IBLND_POOL_DEADLINE;
1799                 fpo->fpo_map_count++;
1800
1801                 if (fpo->fpo_is_fmr) {
1802                         struct ib_pool_fmr *pfmr;
1803
1804                         spin_unlock(&fps->fps_lock);
1805
1806                         if (!tx_pages_mapped) {
1807                                 npages = kiblnd_map_tx_pages(tx, rd);
1808                                 tx_pages_mapped = 1;
1809                         }
1810
1811                         pfmr = kib_fmr_pool_map(fpo->fmr.fpo_fmr_pool,
1812                                                 pages, npages, iov);
1813                         if (likely(!IS_ERR(pfmr))) {
1814                                 fmr->fmr_key  = is_rx ? pfmr->fmr->rkey
1815                                                       : pfmr->fmr->lkey;
1816                                 fmr->fmr_frd  = NULL;
1817                                 fmr->fmr_pfmr = pfmr;
1818                                 fmr->fmr_pool = fpo;
1819                                 return 0;
1820                         }
1821                         rc = PTR_ERR(pfmr);
1822                 } else {
1823                         if (!list_empty(&fpo->fast_reg.fpo_pool_list)) {
1824                                 struct kib_fast_reg_descriptor *frd;
1825 #ifdef HAVE_IB_MAP_MR_SG
1826                                 struct ib_reg_wr *wr;
1827                                 int n;
1828 #else
1829                                 struct ib_rdma_wr *wr;
1830                                 struct ib_fast_reg_page_list *frpl;
1831 #endif
1832                                 struct ib_mr *mr;
1833
1834                                 frd = list_first_entry(&fpo->fast_reg.fpo_pool_list,
1835                                                         struct kib_fast_reg_descriptor,
1836                                                         frd_list);
1837                                 list_del(&frd->frd_list);
1838                                 spin_unlock(&fps->fps_lock);
1839
1840 #ifndef HAVE_IB_MAP_MR_SG
1841                                 frpl = frd->frd_frpl;
1842 #endif
1843                                 mr   = frd->frd_mr;
1844
1845                                 if (!frd->frd_valid) {
1846                                         struct ib_rdma_wr *inv_wr;
1847                                         __u32 key = is_rx ? mr->rkey : mr->lkey;
1848
1849                                         inv_wr = &frd->frd_inv_wr;
1850                                         memset(inv_wr, 0, sizeof(*inv_wr));
1851
1852                                         inv_wr->wr.opcode = IB_WR_LOCAL_INV;
1853                                         inv_wr->wr.wr_id  = IBLND_WID_MR;
1854                                         inv_wr->wr.ex.invalidate_rkey = key;
1855
1856                                         /* Bump the key */
1857                                         key = ib_inc_rkey(key);
1858                                         ib_update_fast_reg_key(mr, key);
1859                                 }
1860
1861 #ifdef HAVE_IB_MAP_MR_SG
1862 #ifdef HAVE_IB_MAP_MR_SG_5ARGS
1863                                 n = ib_map_mr_sg(mr, tx->tx_frags,
1864                                                  rd->rd_nfrags, NULL, PAGE_SIZE);
1865 #else
1866                                 n = ib_map_mr_sg(mr, tx->tx_frags,
1867                                                  rd->rd_nfrags, PAGE_SIZE);
1868 #endif
1869                                 if (unlikely(n != rd->rd_nfrags)) {
1870                                         CERROR("Failed to map mr %d/%d "
1871                                                "elements\n", n, rd->rd_nfrags);
1872                                         return n < 0 ? n : -EINVAL;
1873                                 }
1874
1875                                 wr = &frd->frd_fastreg_wr;
1876                                 memset(wr, 0, sizeof(*wr));
1877
1878                                 wr->wr.opcode = IB_WR_REG_MR;
1879                                 wr->wr.wr_id  = IBLND_WID_MR;
1880                                 wr->wr.num_sge = 0;
1881                                 wr->wr.send_flags = 0;
1882                                 wr->mr = mr;
1883                                 wr->key = is_rx ? mr->rkey : mr->lkey;
1884                                 wr->access = (IB_ACCESS_LOCAL_WRITE |
1885                                               IB_ACCESS_REMOTE_WRITE);
1886 #else
1887                                 if (!tx_pages_mapped) {
1888                                         npages = kiblnd_map_tx_pages(tx, rd);
1889                                         tx_pages_mapped = 1;
1890                                 }
1891
1892                                 LASSERT(npages <= frpl->max_page_list_len);
1893                                 memcpy(frpl->page_list, pages,
1894                                         sizeof(*pages) * npages);
1895
1896                                 /* Prepare FastReg WR */
1897                                 wr = &frd->frd_fastreg_wr;
1898                                 memset(wr, 0, sizeof(*wr));
1899
1900                                 wr->wr.opcode = IB_WR_FAST_REG_MR;
1901                                 wr->wr.wr_id  = IBLND_WID_MR;
1902
1903                                 wr->wr.wr.fast_reg.iova_start = iov;
1904                                 wr->wr.wr.fast_reg.page_list  = frpl;
1905                                 wr->wr.wr.fast_reg.page_list_len = npages;
1906                                 wr->wr.wr.fast_reg.page_shift = PAGE_SHIFT;
1907                                 wr->wr.wr.fast_reg.length = nob;
1908                                 wr->wr.wr.fast_reg.rkey =
1909                                                 is_rx ? mr->rkey : mr->lkey;
1910                                 wr->wr.wr.fast_reg.access_flags =
1911                                                 (IB_ACCESS_LOCAL_WRITE |
1912                                                  IB_ACCESS_REMOTE_WRITE);
1913 #endif
1914
1915                                 fmr->fmr_key  = is_rx ? mr->rkey : mr->lkey;
1916                                 fmr->fmr_frd  = frd;
1917                                 fmr->fmr_pfmr = NULL;
1918                                 fmr->fmr_pool = fpo;
1919                                 return 0;
1920                         }
1921                         spin_unlock(&fps->fps_lock);
1922                         rc = -EAGAIN;
1923                 }
1924
1925                 spin_lock(&fps->fps_lock);
1926                 fpo->fpo_map_count--;
1927                 if (rc != -EAGAIN) {
1928                         spin_unlock(&fps->fps_lock);
1929                         return rc;
1930                 }
1931
1932                 /* EAGAIN and ... */
1933                 if (version != fps->fps_version) {
1934                         spin_unlock(&fps->fps_lock);
1935                         goto again;
1936                 }
1937         }
1938
1939         if (fps->fps_increasing) {
1940                 spin_unlock(&fps->fps_lock);
1941                 CDEBUG(D_NET, "Another thread is allocating new "
1942                        "FMR pool, waiting for her to complete\n");
1943                 wait_var_event(fps, !fps->fps_increasing);
1944                 goto again;
1945
1946         }
1947
1948         if (ktime_get_seconds() < fps->fps_next_retry) {
1949                 /* someone failed recently */
1950                 spin_unlock(&fps->fps_lock);
1951                 return -EAGAIN;
1952         }
1953
1954         fps->fps_increasing = 1;
1955         spin_unlock(&fps->fps_lock);
1956
1957         CDEBUG(D_NET, "Allocate new FMR pool\n");
1958         rc = kiblnd_create_fmr_pool(fps, &fpo);
1959         spin_lock(&fps->fps_lock);
1960         fps->fps_increasing = 0;
1961         wake_up_var(fps);
1962         if (rc == 0) {
1963                 fps->fps_version++;
1964                 list_add_tail(&fpo->fpo_list, &fps->fps_pool_list);
1965         } else {
1966                 fps->fps_next_retry = ktime_get_seconds() + IBLND_POOL_RETRY;
1967         }
1968         spin_unlock(&fps->fps_lock);
1969
1970         goto again;
1971 }
1972
1973 static void
1974 kiblnd_fini_pool(struct kib_pool *pool)
1975 {
1976         LASSERT(list_empty(&pool->po_free_list));
1977         LASSERT(pool->po_allocated == 0);
1978
1979         CDEBUG(D_NET, "Finalize %s pool\n", pool->po_owner->ps_name);
1980 }
1981
1982 static void
1983 kiblnd_init_pool(struct kib_poolset *ps, struct kib_pool *pool, int size)
1984 {
1985         CDEBUG(D_NET, "Initialize %s pool\n", ps->ps_name);
1986
1987         memset(pool, 0, sizeof(struct kib_pool));
1988         INIT_LIST_HEAD(&pool->po_free_list);
1989         pool->po_deadline = ktime_get_seconds() + IBLND_POOL_DEADLINE;
1990         pool->po_owner = ps;
1991         pool->po_size = size;
1992 }
1993
1994 static void
1995 kiblnd_destroy_pool_list(struct list_head *head)
1996 {
1997         struct kib_pool *pool;
1998
1999         while (!list_empty(head)) {
2000                 pool = list_entry(head->next, struct kib_pool, po_list);
2001                 list_del(&pool->po_list);
2002
2003                 LASSERT(pool->po_owner != NULL);
2004                 pool->po_owner->ps_pool_destroy(pool);
2005         }
2006 }
2007
2008 static void
2009 kiblnd_fail_poolset(struct kib_poolset *ps, struct list_head *zombies)
2010 {
2011         if (ps->ps_net == NULL) /* intialized? */
2012                 return;
2013
2014         spin_lock(&ps->ps_lock);
2015         while (!list_empty(&ps->ps_pool_list)) {
2016                 struct kib_pool *po = list_entry(ps->ps_pool_list.next,
2017                                                  struct kib_pool, po_list);
2018
2019                 po->po_failed = 1;
2020                 if (po->po_allocated == 0)
2021                         list_move(&po->po_list, zombies);
2022                 else
2023                         list_move(&po->po_list, &ps->ps_failed_pool_list);
2024         }
2025         spin_unlock(&ps->ps_lock);
2026 }
2027
2028 static void
2029 kiblnd_fini_poolset(struct kib_poolset *ps)
2030 {
2031         if (ps->ps_net != NULL) { /* initialized? */
2032                 kiblnd_destroy_pool_list(&ps->ps_failed_pool_list);
2033                 kiblnd_destroy_pool_list(&ps->ps_pool_list);
2034         }
2035 }
2036
2037 static int
2038 kiblnd_init_poolset(struct kib_poolset *ps, int cpt,
2039                     struct kib_net *net, char *name, int size,
2040                     kib_ps_pool_create_t po_create,
2041                     kib_ps_pool_destroy_t po_destroy,
2042                     kib_ps_node_init_t nd_init,
2043                     kib_ps_node_fini_t nd_fini)
2044 {
2045         struct kib_pool *pool;
2046         int rc;
2047
2048         memset(ps, 0, sizeof(struct kib_poolset));
2049
2050         ps->ps_cpt          = cpt;
2051         ps->ps_net          = net;
2052         ps->ps_pool_create  = po_create;
2053         ps->ps_pool_destroy = po_destroy;
2054         ps->ps_node_init    = nd_init;
2055         ps->ps_node_fini    = nd_fini;
2056         ps->ps_pool_size    = size;
2057         if (strlcpy(ps->ps_name, name, sizeof(ps->ps_name))
2058             >= sizeof(ps->ps_name))
2059                 return -E2BIG;
2060         spin_lock_init(&ps->ps_lock);
2061         INIT_LIST_HEAD(&ps->ps_pool_list);
2062         INIT_LIST_HEAD(&ps->ps_failed_pool_list);
2063
2064         rc = ps->ps_pool_create(ps, size, &pool);
2065         if (rc == 0)
2066                 list_add(&pool->po_list, &ps->ps_pool_list);
2067         else
2068                 CERROR("Failed to create the first pool for %s\n", ps->ps_name);
2069
2070         return rc;
2071 }
2072
2073 static int
2074 kiblnd_pool_is_idle(struct kib_pool *pool, time64_t now)
2075 {
2076         if (pool->po_allocated != 0) /* still in use */
2077                 return 0;
2078         if (pool->po_failed)
2079                 return 1;
2080         return now >= pool->po_deadline;
2081 }
2082
2083 void
2084 kiblnd_pool_free_node(struct kib_pool *pool, struct list_head *node)
2085 {
2086         LIST_HEAD(zombies);
2087         struct kib_poolset *ps = pool->po_owner;
2088         struct kib_pool *tmp;
2089         time64_t now = ktime_get_seconds();
2090
2091         spin_lock(&ps->ps_lock);
2092
2093         if (ps->ps_node_fini != NULL)
2094                 ps->ps_node_fini(pool, node);
2095
2096         LASSERT(pool->po_allocated > 0);
2097         list_add(node, &pool->po_free_list);
2098         pool->po_allocated--;
2099
2100         list_for_each_entry_safe(pool, tmp, &ps->ps_pool_list, po_list) {
2101                 /* the first pool is persistent */
2102                 if (ps->ps_pool_list.next == &pool->po_list)
2103                         continue;
2104
2105                 if (kiblnd_pool_is_idle(pool, now))
2106                         list_move(&pool->po_list, &zombies);
2107         }
2108         spin_unlock(&ps->ps_lock);
2109
2110         if (!list_empty(&zombies))
2111                 kiblnd_destroy_pool_list(&zombies);
2112 }
2113
2114 struct list_head *
2115 kiblnd_pool_alloc_node(struct kib_poolset *ps)
2116 {
2117         struct list_head        *node;
2118         struct kib_pool *pool;
2119         int                     rc;
2120         unsigned int            interval = 1;
2121         ktime_t time_before;
2122         unsigned int trips = 0;
2123
2124 again:
2125         spin_lock(&ps->ps_lock);
2126         list_for_each_entry(pool, &ps->ps_pool_list, po_list) {
2127                 if (list_empty(&pool->po_free_list))
2128                         continue;
2129
2130                 pool->po_allocated++;
2131                 pool->po_deadline = ktime_get_seconds() +
2132                                     IBLND_POOL_DEADLINE;
2133                 node = pool->po_free_list.next;
2134                 list_del(node);
2135
2136                 if (ps->ps_node_init != NULL) {
2137                         /* still hold the lock */
2138                         ps->ps_node_init(pool, node);
2139                 }
2140                 spin_unlock(&ps->ps_lock);
2141                 return node;
2142         }
2143
2144         /* no available tx pool and ... */
2145         if (ps->ps_increasing) {
2146                 /* another thread is allocating a new pool */
2147                 spin_unlock(&ps->ps_lock);
2148                 trips++;
2149                 CDEBUG(D_NET,
2150                        "Another thread is allocating new %s pool, waiting %d jiffies for her to complete. trips = %d\n",
2151                        ps->ps_name, interval, trips);
2152
2153                 schedule_timeout_interruptible(interval);
2154                 if (interval < cfs_time_seconds(1))
2155                         interval *= 2;
2156
2157                 goto again;
2158         }
2159
2160         if (ktime_get_seconds() < ps->ps_next_retry) {
2161                 /* someone failed recently */
2162                 spin_unlock(&ps->ps_lock);
2163                 return NULL;
2164         }
2165
2166         ps->ps_increasing = 1;
2167         spin_unlock(&ps->ps_lock);
2168
2169         CDEBUG(D_NET, "%s pool exhausted, allocate new pool\n", ps->ps_name);
2170         time_before = ktime_get();
2171         rc = ps->ps_pool_create(ps, ps->ps_pool_size, &pool);
2172         CDEBUG(D_NET, "ps_pool_create took %lld ms to complete",
2173                ktime_ms_delta(ktime_get(), time_before));
2174
2175         spin_lock(&ps->ps_lock);
2176         ps->ps_increasing = 0;
2177         if (rc == 0) {
2178                 list_add_tail(&pool->po_list, &ps->ps_pool_list);
2179         } else {
2180                 ps->ps_next_retry = ktime_get_seconds() + IBLND_POOL_RETRY;
2181                 CERROR("Can't allocate new %s pool because out of memory\n",
2182                        ps->ps_name);
2183         }
2184         spin_unlock(&ps->ps_lock);
2185
2186         goto again;
2187 }
2188
2189 static void
2190 kiblnd_destroy_tx_pool(struct kib_pool *pool)
2191 {
2192         struct kib_tx_pool *tpo = container_of(pool, struct kib_tx_pool,
2193                                                tpo_pool);
2194         int i;
2195
2196         LASSERT (pool->po_allocated == 0);
2197
2198         if (tpo->tpo_tx_pages != NULL) {
2199                 kiblnd_unmap_tx_pool(tpo);
2200                 kiblnd_free_pages(tpo->tpo_tx_pages);
2201         }
2202
2203         if (tpo->tpo_tx_descs == NULL)
2204                 goto out;
2205
2206         for (i = 0; i < pool->po_size; i++) {
2207                 struct kib_tx *tx = &tpo->tpo_tx_descs[i];
2208                 int       wrq_sge = *kiblnd_tunables.kib_wrq_sge;
2209
2210                 list_del(&tx->tx_list);
2211                 if (tx->tx_pages != NULL)
2212                         CFS_FREE_PTR_ARRAY(tx->tx_pages, LNET_MAX_IOV);
2213                 if (tx->tx_frags != NULL)
2214                         CFS_FREE_PTR_ARRAY(tx->tx_frags,
2215                                            (1 + IBLND_MAX_RDMA_FRAGS));
2216                 if (tx->tx_wrq != NULL)
2217                         CFS_FREE_PTR_ARRAY(tx->tx_wrq,
2218                                            (1 + IBLND_MAX_RDMA_FRAGS));
2219                 if (tx->tx_sge != NULL)
2220                         CFS_FREE_PTR_ARRAY(tx->tx_sge,
2221                                            (1 + IBLND_MAX_RDMA_FRAGS) *
2222                                            wrq_sge);
2223                 if (tx->tx_rd != NULL)
2224                         LIBCFS_FREE(tx->tx_rd,
2225                                     offsetof(struct kib_rdma_desc,
2226                                              rd_frags[IBLND_MAX_RDMA_FRAGS]));
2227         }
2228
2229         CFS_FREE_PTR_ARRAY(tpo->tpo_tx_descs, pool->po_size);
2230 out:
2231         kiblnd_fini_pool(pool);
2232         CFS_FREE_PTR(tpo);
2233 }
2234
2235 static int kiblnd_tx_pool_size(struct lnet_ni *ni, int ncpts)
2236 {
2237         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2238         int ntx;
2239
2240         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2241         ntx = tunables->lnd_ntx / ncpts;
2242
2243         return max(IBLND_TX_POOL, ntx);
2244 }
2245
2246 static int
2247 kiblnd_create_tx_pool(struct kib_poolset *ps, int size, struct kib_pool **pp_po)
2248 {
2249         int            i;
2250         int            npg;
2251         struct kib_pool *pool;
2252         struct kib_tx_pool *tpo;
2253
2254         LIBCFS_CPT_ALLOC(tpo, lnet_cpt_table(), ps->ps_cpt, sizeof(*tpo));
2255         if (tpo == NULL) {
2256                 CERROR("Failed to allocate TX pool\n");
2257                 return -ENOMEM;
2258         }
2259
2260         pool = &tpo->tpo_pool;
2261         kiblnd_init_pool(ps, pool, size);
2262         tpo->tpo_tx_descs = NULL;
2263         tpo->tpo_tx_pages = NULL;
2264
2265         npg = (size * IBLND_MSG_SIZE + PAGE_SIZE - 1) / PAGE_SIZE;
2266         if (kiblnd_alloc_pages(&tpo->tpo_tx_pages, ps->ps_cpt, npg) != 0) {
2267                 CERROR("Can't allocate tx pages: %d\n", npg);
2268                 CFS_FREE_PTR(tpo);
2269                 return -ENOMEM;
2270         }
2271
2272         LIBCFS_CPT_ALLOC(tpo->tpo_tx_descs, lnet_cpt_table(), ps->ps_cpt,
2273                          size * sizeof(struct kib_tx));
2274         if (tpo->tpo_tx_descs == NULL) {
2275                 CERROR("Can't allocate %d tx descriptors\n", size);
2276                 ps->ps_pool_destroy(pool);
2277                 return -ENOMEM;
2278         }
2279
2280         memset(tpo->tpo_tx_descs, 0, size * sizeof(struct kib_tx));
2281
2282         for (i = 0; i < size; i++) {
2283                 struct kib_tx *tx = &tpo->tpo_tx_descs[i];
2284                 int       wrq_sge = *kiblnd_tunables.kib_wrq_sge;
2285
2286                 tx->tx_pool = tpo;
2287                 if (ps->ps_net->ibn_fmr_ps != NULL) {
2288                         LIBCFS_CPT_ALLOC(tx->tx_pages,
2289                                          lnet_cpt_table(), ps->ps_cpt,
2290                                          LNET_MAX_IOV * sizeof(*tx->tx_pages));
2291                         if (tx->tx_pages == NULL)
2292                                 break;
2293                 }
2294
2295                 LIBCFS_CPT_ALLOC(tx->tx_frags, lnet_cpt_table(), ps->ps_cpt,
2296                                  (1 + IBLND_MAX_RDMA_FRAGS) *
2297                                  sizeof(*tx->tx_frags));
2298                 if (tx->tx_frags == NULL)
2299                         break;
2300
2301                 sg_init_table(tx->tx_frags, IBLND_MAX_RDMA_FRAGS + 1);
2302
2303                 LIBCFS_CPT_ALLOC(tx->tx_wrq, lnet_cpt_table(), ps->ps_cpt,
2304                                  (1 + IBLND_MAX_RDMA_FRAGS) *
2305                                  sizeof(*tx->tx_wrq));
2306                 if (tx->tx_wrq == NULL)
2307                         break;
2308
2309                 LIBCFS_CPT_ALLOC(tx->tx_sge, lnet_cpt_table(), ps->ps_cpt,
2310                                  (1 + IBLND_MAX_RDMA_FRAGS) * wrq_sge *
2311                                  sizeof(*tx->tx_sge));
2312                 if (tx->tx_sge == NULL)
2313                         break;
2314
2315                 LIBCFS_CPT_ALLOC(tx->tx_rd, lnet_cpt_table(), ps->ps_cpt,
2316                                  offsetof(struct kib_rdma_desc,
2317                                           rd_frags[IBLND_MAX_RDMA_FRAGS]));
2318                 if (tx->tx_rd == NULL)
2319                         break;
2320         }
2321
2322         if (i == size) {
2323                 kiblnd_map_tx_pool(tpo);
2324                 *pp_po = pool;
2325                 return 0;
2326         }
2327
2328         ps->ps_pool_destroy(pool);
2329         return -ENOMEM;
2330 }
2331
2332 static void
2333 kiblnd_tx_init(struct kib_pool *pool, struct list_head *node)
2334 {
2335         struct kib_tx_poolset *tps = container_of(pool->po_owner,
2336                                                   struct kib_tx_poolset,
2337                                                   tps_poolset);
2338         struct kib_tx *tx  = list_entry(node, struct kib_tx, tx_list);
2339
2340         tx->tx_cookie = tps->tps_next_tx_cookie++;
2341 }
2342
2343 static void
2344 kiblnd_net_fini_pools(struct kib_net *net)
2345 {
2346         int     i;
2347
2348         cfs_cpt_for_each(i, lnet_cpt_table()) {
2349                 struct kib_tx_poolset *tps;
2350                 struct kib_fmr_poolset *fps;
2351
2352                 if (net->ibn_tx_ps != NULL) {
2353                         tps = net->ibn_tx_ps[i];
2354                         kiblnd_fini_poolset(&tps->tps_poolset);
2355                 }
2356
2357                 if (net->ibn_fmr_ps != NULL) {
2358                         fps = net->ibn_fmr_ps[i];
2359                         kiblnd_fini_fmr_poolset(fps);
2360                 }
2361         }
2362
2363         if (net->ibn_tx_ps != NULL) {
2364                 cfs_percpt_free(net->ibn_tx_ps);
2365                 net->ibn_tx_ps = NULL;
2366         }
2367
2368         if (net->ibn_fmr_ps != NULL) {
2369                 cfs_percpt_free(net->ibn_fmr_ps);
2370                 net->ibn_fmr_ps = NULL;
2371         }
2372 }
2373
2374 static int
2375 kiblnd_net_init_pools(struct kib_net *net, struct lnet_ni *ni, __u32 *cpts,
2376                       int ncpts)
2377 {
2378         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2379 #ifdef HAVE_IB_GET_DMA_MR
2380         unsigned long   flags;
2381 #endif
2382         int             cpt;
2383         int             rc;
2384         int             i;
2385
2386         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2387
2388 #ifdef HAVE_IB_GET_DMA_MR
2389         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2390         /*
2391          * if lnd_map_on_demand is zero then we have effectively disabled
2392          * FMR or FastReg and we're using global memory regions
2393          * exclusively.
2394          */
2395         if (!tunables->lnd_map_on_demand) {
2396                 read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2397                                            flags);
2398                 goto create_tx_pool;
2399         }
2400
2401         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2402 #endif
2403
2404         if (tunables->lnd_fmr_pool_size < tunables->lnd_ntx / 4) {
2405                 CERROR("Can't set fmr pool size (%d) < ntx / 4(%d)\n",
2406                        tunables->lnd_fmr_pool_size,
2407                        tunables->lnd_ntx / 4);
2408                 rc = -EINVAL;
2409                 goto failed;
2410         }
2411
2412         /* TX pool must be created later than FMR, see LU-2268
2413          * for details */
2414         LASSERT(net->ibn_tx_ps == NULL);
2415
2416         /* premapping can fail if ibd_nmr > 1, so we always create
2417          * FMR pool and map-on-demand if premapping failed */
2418
2419         net->ibn_fmr_ps = cfs_percpt_alloc(lnet_cpt_table(),
2420                                            sizeof(struct kib_fmr_poolset));
2421         if (net->ibn_fmr_ps == NULL) {
2422                 CERROR("Failed to allocate FMR pool array\n");
2423                 rc = -ENOMEM;
2424                 goto failed;
2425         }
2426
2427         for (i = 0; i < ncpts; i++) {
2428                 cpt = (cpts == NULL) ? i : cpts[i];
2429                 rc = kiblnd_init_fmr_poolset(net->ibn_fmr_ps[cpt], cpt, ncpts,
2430                                              net, tunables);
2431                 if (rc != 0) {
2432                         CERROR("Can't initialize FMR pool for CPT %d: %d\n",
2433                                cpt, rc);
2434                         goto failed;
2435                 }
2436         }
2437
2438         if (i > 0)
2439                 LASSERT(i == ncpts);
2440
2441 #ifdef HAVE_IB_GET_DMA_MR
2442  create_tx_pool:
2443 #endif
2444         net->ibn_tx_ps = cfs_percpt_alloc(lnet_cpt_table(),
2445                                           sizeof(struct kib_tx_poolset));
2446         if (net->ibn_tx_ps == NULL) {
2447                 CERROR("Failed to allocate tx pool array\n");
2448                 rc = -ENOMEM;
2449                 goto failed;
2450         }
2451
2452         for (i = 0; i < ncpts; i++) {
2453                 cpt = (cpts == NULL) ? i : cpts[i];
2454                 rc = kiblnd_init_poolset(&net->ibn_tx_ps[cpt]->tps_poolset,
2455                                          cpt, net, "TX",
2456                                          kiblnd_tx_pool_size(ni, ncpts),
2457                                          kiblnd_create_tx_pool,
2458                                          kiblnd_destroy_tx_pool,
2459                                          kiblnd_tx_init, NULL);
2460                 if (rc != 0) {
2461                         CERROR("Can't initialize TX pool for CPT %d: %d\n",
2462                                cpt, rc);
2463                         goto failed;
2464                 }
2465         }
2466
2467         return 0;
2468  failed:
2469         kiblnd_net_fini_pools(net);
2470         LASSERT(rc != 0);
2471         return rc;
2472 }
2473
2474 static int
2475 kiblnd_port_get_attr(struct kib_hca_dev *hdev)
2476 {
2477         struct ib_port_attr *port_attr;
2478         int rc;
2479         unsigned long flags;
2480         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
2481
2482         LIBCFS_ALLOC(port_attr, sizeof(*port_attr));
2483         if (port_attr == NULL) {
2484                 CDEBUG(D_NETERROR, "Out of memory\n");
2485                 return -ENOMEM;
2486         }
2487
2488         rc = ib_query_port(hdev->ibh_ibdev, hdev->ibh_port, port_attr);
2489
2490         write_lock_irqsave(g_lock, flags);
2491
2492         if (rc == 0)
2493                 hdev->ibh_state = port_attr->state == IB_PORT_ACTIVE
2494                                  ? IBLND_DEV_PORT_ACTIVE
2495                                  : IBLND_DEV_PORT_DOWN;
2496
2497         write_unlock_irqrestore(g_lock, flags);
2498         LIBCFS_FREE(port_attr, sizeof(*port_attr));
2499
2500         if (rc != 0) {
2501                 CDEBUG(D_NETERROR, "Failed to query IB port: %d\n", rc);
2502                 return rc;
2503         }
2504         return 0;
2505 }
2506
2507 static inline void
2508 kiblnd_set_ni_fatal_on(struct kib_hca_dev *hdev, int val)
2509 {
2510         struct kib_net  *net;
2511
2512         /* for health check */
2513         list_for_each_entry(net, &hdev->ibh_dev->ibd_nets, ibn_list) {
2514                 if (val)
2515                         CDEBUG(D_NETERROR, "Fatal device error for NI %s\n",
2516                                         libcfs_nid2str(net->ibn_ni->ni_nid));
2517                 atomic_set(&net->ibn_ni->ni_fatal_error_on, val);
2518         }
2519 }
2520
2521 void
2522 kiblnd_event_handler(struct ib_event_handler *handler, struct ib_event *event)
2523 {
2524         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
2525         struct kib_hca_dev  *hdev;
2526         unsigned long flags;
2527
2528         hdev = container_of(handler, struct kib_hca_dev, ibh_event_handler);
2529
2530         write_lock_irqsave(g_lock, flags);
2531
2532         switch (event->event) {
2533         case IB_EVENT_DEVICE_FATAL:
2534                 CDEBUG(D_NET, "IB device fatal\n");
2535                 hdev->ibh_state = IBLND_DEV_FATAL;
2536                 kiblnd_set_ni_fatal_on(hdev, 1);
2537                 break;
2538         case IB_EVENT_PORT_ACTIVE:
2539                 CDEBUG(D_NET, "IB port active\n");
2540                 if (event->element.port_num == hdev->ibh_port) {
2541                         hdev->ibh_state = IBLND_DEV_PORT_ACTIVE;
2542                         kiblnd_set_ni_fatal_on(hdev, 0);
2543                 }
2544                 break;
2545         case IB_EVENT_PORT_ERR:
2546                 CDEBUG(D_NET, "IB port err\n");
2547                 if (event->element.port_num == hdev->ibh_port) {
2548                         hdev->ibh_state = IBLND_DEV_PORT_DOWN;
2549                         kiblnd_set_ni_fatal_on(hdev, 1);
2550                 }
2551                 break;
2552         default:
2553                 break;
2554         }
2555         write_unlock_irqrestore(g_lock, flags);
2556 }
2557
2558 static int
2559 kiblnd_hdev_get_attr(struct kib_hca_dev *hdev)
2560 {
2561         struct ib_device_attr *dev_attr;
2562         int rc = 0;
2563         int rc2 = 0;
2564
2565         /* It's safe to assume a HCA can handle a page size
2566          * matching that of the native system */
2567         hdev->ibh_page_shift = PAGE_SHIFT;
2568         hdev->ibh_page_size  = 1 << PAGE_SHIFT;
2569         hdev->ibh_page_mask  = ~((__u64)hdev->ibh_page_size - 1);
2570
2571 #ifndef HAVE_IB_DEVICE_ATTRS
2572         LIBCFS_ALLOC(dev_attr, sizeof(*dev_attr));
2573         if (dev_attr == NULL) {
2574                 CERROR("Out of memory\n");
2575                 return -ENOMEM;
2576         }
2577
2578         rc = ib_query_device(hdev->ibh_ibdev, dev_attr);
2579         if (rc != 0) {
2580                 CERROR("Failed to query IB device: %d\n", rc);
2581                 goto out_clean_attr;
2582         }
2583 #else
2584         dev_attr = &hdev->ibh_ibdev->attrs;
2585 #endif
2586
2587         hdev->ibh_mr_size = dev_attr->max_mr_size;
2588         hdev->ibh_max_qp_wr = dev_attr->max_qp_wr;
2589
2590         /* Setup device Memory Registration capabilities */
2591 #ifdef HAVE_IB_DEVICE_OPS
2592         if (hdev->ibh_ibdev->ops.alloc_fmr &&
2593             hdev->ibh_ibdev->ops.dealloc_fmr &&
2594             hdev->ibh_ibdev->ops.map_phys_fmr &&
2595             hdev->ibh_ibdev->ops.unmap_fmr) {
2596 #else
2597         if (hdev->ibh_ibdev->alloc_fmr &&
2598             hdev->ibh_ibdev->dealloc_fmr &&
2599             hdev->ibh_ibdev->map_phys_fmr &&
2600             hdev->ibh_ibdev->unmap_fmr) {
2601 #endif
2602                 LCONSOLE_INFO("Using FMR for registration\n");
2603                 hdev->ibh_dev->ibd_dev_caps |= IBLND_DEV_CAPS_FMR_ENABLED;
2604         } else if (dev_attr->device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS) {
2605                 LCONSOLE_INFO("Using FastReg for registration\n");
2606                 hdev->ibh_dev->ibd_dev_caps |= IBLND_DEV_CAPS_FASTREG_ENABLED;
2607 #ifndef HAVE_IB_ALLOC_FAST_REG_MR
2608 #ifdef IB_DEVICE_SG_GAPS_REG
2609                 if (dev_attr->device_cap_flags & IB_DEVICE_SG_GAPS_REG)
2610                         hdev->ibh_dev->ibd_dev_caps |= IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT;
2611 #endif
2612 #endif
2613         } else {
2614                 rc = -ENOSYS;
2615         }
2616
2617         rc2 = kiblnd_port_get_attr(hdev);
2618         if (rc2 != 0)
2619                 return rc2;
2620
2621         if (rc != 0)
2622                 rc = -EINVAL;
2623
2624 #ifndef HAVE_IB_DEVICE_ATTRS
2625 out_clean_attr:
2626         LIBCFS_FREE(dev_attr, sizeof(*dev_attr));
2627 #endif
2628
2629         if (rc == -ENOSYS)
2630                 CERROR("IB device does not support FMRs nor FastRegs, can't "
2631                        "register memory: %d\n", rc);
2632         else if (rc == -EINVAL)
2633                 CERROR("Invalid mr size: %#llx\n", hdev->ibh_mr_size);
2634         return rc;
2635 }
2636
2637 #ifdef HAVE_IB_GET_DMA_MR
2638 static void
2639 kiblnd_hdev_cleanup_mrs(struct kib_hca_dev *hdev)
2640 {
2641         if (hdev->ibh_mrs == NULL)
2642                 return;
2643
2644         ib_dereg_mr(hdev->ibh_mrs);
2645
2646         hdev->ibh_mrs = NULL;
2647 }
2648 #endif
2649
2650 void
2651 kiblnd_hdev_destroy(struct kib_hca_dev *hdev)
2652 {
2653         if (hdev->ibh_event_handler.device != NULL)
2654                 ib_unregister_event_handler(&hdev->ibh_event_handler);
2655
2656 #ifdef HAVE_IB_GET_DMA_MR
2657         kiblnd_hdev_cleanup_mrs(hdev);
2658 #endif
2659
2660         if (hdev->ibh_pd != NULL)
2661                 ib_dealloc_pd(hdev->ibh_pd);
2662
2663         if (hdev->ibh_cmid != NULL)
2664                 rdma_destroy_id(hdev->ibh_cmid);
2665
2666         LIBCFS_FREE(hdev, sizeof(*hdev));
2667 }
2668
2669 #ifdef HAVE_IB_GET_DMA_MR
2670 static int
2671 kiblnd_hdev_setup_mrs(struct kib_hca_dev *hdev)
2672 {
2673         struct ib_mr *mr;
2674         int           acflags = IB_ACCESS_LOCAL_WRITE |
2675                                 IB_ACCESS_REMOTE_WRITE;
2676
2677         mr = ib_get_dma_mr(hdev->ibh_pd, acflags);
2678         if (IS_ERR(mr)) {
2679                 CERROR("Failed ib_get_dma_mr: %ld\n", PTR_ERR(mr));
2680                 kiblnd_hdev_cleanup_mrs(hdev);
2681                 return PTR_ERR(mr);
2682         }
2683
2684         hdev->ibh_mrs = mr;
2685
2686         return 0;
2687 }
2688 #endif
2689
2690 static int
2691 kiblnd_dummy_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
2692 {       /* DUMMY */
2693         return 0;
2694 }
2695
2696 static int
2697 kiblnd_dev_need_failover(struct kib_dev *dev, struct net *ns)
2698 {
2699         struct rdma_cm_id  *cmid;
2700         struct sockaddr_in  srcaddr;
2701         struct sockaddr_in  dstaddr;
2702         int                 rc;
2703
2704         if (dev->ibd_hdev == NULL || /* initializing */
2705             dev->ibd_hdev->ibh_cmid == NULL || /* listener is dead */
2706             *kiblnd_tunables.kib_dev_failover > 1) /* debugging */
2707                 return 1;
2708
2709         /* XXX: it's UGLY, but I don't have better way to find
2710          * ib-bonding HCA failover because:
2711          *
2712          * a. no reliable CM event for HCA failover...
2713          * b. no OFED API to get ib_device for current net_device...
2714          *
2715          * We have only two choices at this point:
2716          *
2717          * a. rdma_bind_addr(), it will conflict with listener cmid
2718          * b. rdma_resolve_addr() to zero addr */
2719         cmid = kiblnd_rdma_create_id(ns, kiblnd_dummy_callback, dev,
2720                                      RDMA_PS_TCP, IB_QPT_RC);
2721         if (IS_ERR(cmid)) {
2722                 rc = PTR_ERR(cmid);
2723                 CERROR("Failed to create cmid for failover: %d\n", rc);
2724                 return rc;
2725         }
2726
2727         memset(&srcaddr, 0, sizeof(srcaddr));
2728         srcaddr.sin_family      = AF_INET;
2729         srcaddr.sin_addr.s_addr = (__force u32)htonl(dev->ibd_ifip);
2730
2731         memset(&dstaddr, 0, sizeof(dstaddr));
2732         dstaddr.sin_family = AF_INET;
2733         rc = rdma_resolve_addr(cmid, (struct sockaddr *)&srcaddr,
2734                                (struct sockaddr *)&dstaddr, 1);
2735         if (rc != 0 || cmid->device == NULL) {
2736                 CERROR("Failed to bind %s:%pI4h to device(%p): %d\n",
2737                        dev->ibd_ifname, &dev->ibd_ifip,
2738                        cmid->device, rc);
2739                 rdma_destroy_id(cmid);
2740                 return rc;
2741         }
2742
2743         rc = dev->ibd_hdev->ibh_ibdev != cmid->device; /* true for failover */
2744         rdma_destroy_id(cmid);
2745         return rc;
2746 }
2747
2748 int
2749 kiblnd_dev_failover(struct kib_dev *dev, struct net *ns)
2750 {
2751         LIST_HEAD(zombie_tpo);
2752         LIST_HEAD(zombie_ppo);
2753         LIST_HEAD(zombie_fpo);
2754         struct rdma_cm_id  *cmid  = NULL;
2755         struct kib_hca_dev *hdev  = NULL;
2756         struct kib_hca_dev *old;
2757         struct ib_pd       *pd;
2758         struct kib_net *net;
2759         struct sockaddr_in  addr;
2760         unsigned long       flags;
2761         int                 rc = 0;
2762         int                 i;
2763
2764         LASSERT (*kiblnd_tunables.kib_dev_failover > 1 ||
2765                  dev->ibd_can_failover ||
2766                  dev->ibd_hdev == NULL);
2767
2768         rc = kiblnd_dev_need_failover(dev, ns);
2769         if (rc <= 0)
2770                 goto out;
2771
2772         if (dev->ibd_hdev != NULL &&
2773             dev->ibd_hdev->ibh_cmid != NULL) {
2774                 /* XXX it's not good to close old listener at here,
2775                  * because we can fail to create new listener.
2776                  * But we have to close it now, otherwise rdma_bind_addr
2777                  * will return EADDRINUSE... How crap! */
2778                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2779
2780                 cmid = dev->ibd_hdev->ibh_cmid;
2781                 /* make next schedule of kiblnd_dev_need_failover()
2782                  * return 1 for me */
2783                 dev->ibd_hdev->ibh_cmid  = NULL;
2784                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2785
2786                 rdma_destroy_id(cmid);
2787         }
2788
2789         cmid = kiblnd_rdma_create_id(ns, kiblnd_cm_callback, dev, RDMA_PS_TCP,
2790                                      IB_QPT_RC);
2791         if (IS_ERR(cmid)) {
2792                 rc = PTR_ERR(cmid);
2793                 CERROR("Failed to create cmid for failover: %d\n", rc);
2794                 goto out;
2795         }
2796
2797         memset(&addr, 0, sizeof(addr));
2798         addr.sin_family      = AF_INET;
2799         addr.sin_addr.s_addr = (__force u32)htonl(dev->ibd_ifip);
2800         addr.sin_port        = htons(*kiblnd_tunables.kib_service);
2801
2802         /* Bind to failover device or port */
2803         rc = rdma_bind_addr(cmid, (struct sockaddr *)&addr);
2804         if (rc != 0 || cmid->device == NULL) {
2805                 CERROR("Failed to bind %s:%pI4h to device(%p): %d\n",
2806                        dev->ibd_ifname, &dev->ibd_ifip,
2807                        cmid->device, rc);
2808                 rdma_destroy_id(cmid);
2809                 goto out;
2810         }
2811
2812         LIBCFS_ALLOC(hdev, sizeof(*hdev));
2813         if (hdev == NULL) {
2814                 CERROR("Failed to allocate kib_hca_dev\n");
2815                 rdma_destroy_id(cmid);
2816                 rc = -ENOMEM;
2817                 goto out;
2818         }
2819
2820         atomic_set(&hdev->ibh_ref, 1);
2821         hdev->ibh_dev   = dev;
2822         hdev->ibh_cmid  = cmid;
2823         hdev->ibh_ibdev = cmid->device;
2824         hdev->ibh_port  = cmid->port_num;
2825
2826 #ifdef HAVE_IB_ALLOC_PD_2ARGS
2827         pd = ib_alloc_pd(cmid->device, 0);
2828 #else
2829         pd = ib_alloc_pd(cmid->device);
2830 #endif
2831         if (IS_ERR(pd)) {
2832                 rc = PTR_ERR(pd);
2833                 CERROR("Can't allocate PD: %d\n", rc);
2834                 goto out;
2835         }
2836
2837         hdev->ibh_pd = pd;
2838
2839         rc = rdma_listen(cmid, 0);
2840         if (rc != 0) {
2841                 CERROR("Can't start new listener: %d\n", rc);
2842                 goto out;
2843         }
2844
2845         rc = kiblnd_hdev_get_attr(hdev);
2846         if (rc != 0) {
2847                 CERROR("Can't get device attributes: %d\n", rc);
2848                 goto out;
2849         }
2850
2851 #ifdef HAVE_IB_GET_DMA_MR
2852         rc = kiblnd_hdev_setup_mrs(hdev);
2853         if (rc != 0) {
2854                 CERROR("Can't setup device: %d\n", rc);
2855                 goto out;
2856         }
2857 #endif
2858
2859         INIT_IB_EVENT_HANDLER(&hdev->ibh_event_handler,
2860                                 hdev->ibh_ibdev, kiblnd_event_handler);
2861         ib_register_event_handler(&hdev->ibh_event_handler);
2862
2863         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2864
2865         old = dev->ibd_hdev;
2866         dev->ibd_hdev = hdev;   /* take over the refcount */
2867         hdev = old;
2868
2869         list_for_each_entry(net, &dev->ibd_nets, ibn_list) {
2870                 cfs_cpt_for_each(i, lnet_cpt_table()) {
2871                         kiblnd_fail_poolset(&net->ibn_tx_ps[i]->tps_poolset,
2872                                             &zombie_tpo);
2873
2874                         if (net->ibn_fmr_ps != NULL)
2875                                 kiblnd_fail_fmr_poolset(net->ibn_fmr_ps[i],
2876                                                         &zombie_fpo);
2877                 }
2878         }
2879
2880         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2881  out:
2882         if (!list_empty(&zombie_tpo))
2883                 kiblnd_destroy_pool_list(&zombie_tpo);
2884         if (!list_empty(&zombie_ppo))
2885                 kiblnd_destroy_pool_list(&zombie_ppo);
2886         if (!list_empty(&zombie_fpo))
2887                 kiblnd_destroy_fmr_pool_list(&zombie_fpo);
2888         if (hdev != NULL)
2889                 kiblnd_hdev_decref(hdev);
2890
2891         if (rc != 0)
2892                 dev->ibd_failed_failover++;
2893         else
2894                 dev->ibd_failed_failover = 0;
2895
2896         return rc;
2897 }
2898
2899 void
2900 kiblnd_destroy_dev(struct kib_dev *dev)
2901 {
2902         LASSERT(dev->ibd_nnets == 0);
2903         LASSERT(list_empty(&dev->ibd_nets));
2904
2905         list_del(&dev->ibd_fail_list);
2906         list_del(&dev->ibd_list);
2907
2908         if (dev->ibd_hdev != NULL)
2909                 kiblnd_hdev_decref(dev->ibd_hdev);
2910
2911         LIBCFS_FREE(dev, sizeof(*dev));
2912 }
2913
2914 static void
2915 kiblnd_base_shutdown(void)
2916 {
2917         struct kib_sched_info   *sched;
2918         int                     i;
2919
2920         LASSERT(list_empty(&kiblnd_data.kib_devs));
2921
2922         CDEBUG(D_MALLOC, "before LND base cleanup: kmem %lld\n",
2923                libcfs_kmem_read());
2924
2925         switch (kiblnd_data.kib_init) {
2926         default:
2927                 LBUG();
2928
2929         case IBLND_INIT_ALL:
2930         case IBLND_INIT_DATA:
2931                 LASSERT (kiblnd_data.kib_peers != NULL);
2932                 for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++) {
2933                         LASSERT(list_empty(&kiblnd_data.kib_peers[i]));
2934                 }
2935                 LASSERT(list_empty(&kiblnd_data.kib_connd_zombies));
2936                 LASSERT(list_empty(&kiblnd_data.kib_connd_conns));
2937                 LASSERT(list_empty(&kiblnd_data.kib_reconn_list));
2938                 LASSERT(list_empty(&kiblnd_data.kib_reconn_wait));
2939
2940                 /* flag threads to terminate; wake and wait for them to die */
2941                 kiblnd_data.kib_shutdown = 1;
2942
2943                 /* NB: we really want to stop scheduler threads net by net
2944                  * instead of the whole module, this should be improved
2945                  * with dynamic configuration LNet */
2946                 cfs_percpt_for_each(sched, i, kiblnd_data.kib_scheds)
2947                         wake_up_all(&sched->ibs_waitq);
2948
2949                 wake_up_all(&kiblnd_data.kib_connd_waitq);
2950                 wake_up_all(&kiblnd_data.kib_failover_waitq);
2951
2952                 wait_var_event_warning(&kiblnd_data.kib_nthreads,
2953                                        !atomic_read(&kiblnd_data.kib_nthreads),
2954                                        "Waiting for %d threads to terminate\n",
2955                                        atomic_read(&kiblnd_data.kib_nthreads));
2956                 /* fall through */
2957
2958         case IBLND_INIT_NOTHING:
2959                 break;
2960         }
2961
2962         if (kiblnd_data.kib_peers)
2963                 CFS_FREE_PTR_ARRAY(kiblnd_data.kib_peers,
2964                                    kiblnd_data.kib_peer_hash_size);
2965
2966         if (kiblnd_data.kib_scheds != NULL)
2967                 cfs_percpt_free(kiblnd_data.kib_scheds);
2968
2969         CDEBUG(D_MALLOC, "after LND base cleanup: kmem %lld\n",
2970                libcfs_kmem_read());
2971
2972         kiblnd_data.kib_init = IBLND_INIT_NOTHING;
2973         module_put(THIS_MODULE);
2974 }
2975
2976 static void
2977 kiblnd_shutdown(struct lnet_ni *ni)
2978 {
2979         struct kib_net *net = ni->ni_data;
2980         rwlock_t     *g_lock = &kiblnd_data.kib_global_lock;
2981         unsigned long     flags;
2982
2983         LASSERT(kiblnd_data.kib_init == IBLND_INIT_ALL);
2984
2985         if (net == NULL)
2986                 goto out;
2987
2988         CDEBUG(D_MALLOC, "before LND net cleanup: kmem %lld\n",
2989                libcfs_kmem_read());
2990
2991         write_lock_irqsave(g_lock, flags);
2992         net->ibn_shutdown = 1;
2993         write_unlock_irqrestore(g_lock, flags);
2994
2995         switch (net->ibn_init) {
2996         default:
2997                 LBUG();
2998
2999         case IBLND_INIT_ALL:
3000                 /* nuke all existing peers within this net */
3001                 kiblnd_del_peer(ni, LNET_NID_ANY);
3002
3003                 /* Wait for all peer_ni state to clean up */
3004                 wait_var_event_warning(&net->ibn_npeers,
3005                                        atomic_read(&net->ibn_npeers) == 0,
3006                                        "%s: waiting for %d peers to disconnect\n",
3007                                        libcfs_nid2str(ni->ni_nid),
3008                                        atomic_read(&net->ibn_npeers));
3009
3010                 kiblnd_net_fini_pools(net);
3011
3012                 write_lock_irqsave(g_lock, flags);
3013                 LASSERT(net->ibn_dev->ibd_nnets > 0);
3014                 net->ibn_dev->ibd_nnets--;
3015                 list_del(&net->ibn_list);
3016                 write_unlock_irqrestore(g_lock, flags);
3017
3018                 /* fall through */
3019
3020         case IBLND_INIT_NOTHING:
3021                 LASSERT (atomic_read(&net->ibn_nconns) == 0);
3022
3023                 if (net->ibn_dev != NULL &&
3024                     net->ibn_dev->ibd_nnets == 0)
3025                         kiblnd_destroy_dev(net->ibn_dev);
3026
3027                 break;
3028         }
3029
3030         CDEBUG(D_MALLOC, "after LND net cleanup: kmem %lld\n",
3031                libcfs_kmem_read());
3032
3033         net->ibn_init = IBLND_INIT_NOTHING;
3034         ni->ni_data = NULL;
3035
3036         LIBCFS_FREE(net, sizeof(*net));
3037
3038 out:
3039         if (list_empty(&kiblnd_data.kib_devs))
3040                 kiblnd_base_shutdown();
3041 }
3042
3043 static int
3044 kiblnd_base_startup(struct net *ns)
3045 {
3046         struct kib_sched_info   *sched;
3047         int                     rc;
3048         int                     i;
3049
3050         LASSERT(kiblnd_data.kib_init == IBLND_INIT_NOTHING);
3051
3052         if (!try_module_get(THIS_MODULE))
3053                 goto failed;
3054
3055         memset(&kiblnd_data, 0, sizeof(kiblnd_data)); /* zero pointers, flags etc */
3056
3057         rwlock_init(&kiblnd_data.kib_global_lock);
3058
3059         INIT_LIST_HEAD(&kiblnd_data.kib_devs);
3060         INIT_LIST_HEAD(&kiblnd_data.kib_failed_devs);
3061
3062         kiblnd_data.kib_peer_hash_size = IBLND_PEER_HASH_SIZE;
3063         CFS_ALLOC_PTR_ARRAY(kiblnd_data.kib_peers,
3064                             kiblnd_data.kib_peer_hash_size);
3065         if (kiblnd_data.kib_peers == NULL)
3066                 goto failed;
3067
3068         for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++)
3069                 INIT_LIST_HEAD(&kiblnd_data.kib_peers[i]);
3070
3071         spin_lock_init(&kiblnd_data.kib_connd_lock);
3072         INIT_LIST_HEAD(&kiblnd_data.kib_connd_conns);
3073         INIT_LIST_HEAD(&kiblnd_data.kib_connd_waits);
3074         INIT_LIST_HEAD(&kiblnd_data.kib_connd_zombies);
3075         INIT_LIST_HEAD(&kiblnd_data.kib_reconn_list);
3076         INIT_LIST_HEAD(&kiblnd_data.kib_reconn_wait);
3077
3078         init_waitqueue_head(&kiblnd_data.kib_connd_waitq);
3079         init_waitqueue_head(&kiblnd_data.kib_failover_waitq);
3080
3081         kiblnd_data.kib_scheds = cfs_percpt_alloc(lnet_cpt_table(),
3082                                                   sizeof(*sched));
3083         if (kiblnd_data.kib_scheds == NULL)
3084                 goto failed;
3085
3086         cfs_percpt_for_each(sched, i, kiblnd_data.kib_scheds) {
3087                 int     nthrs;
3088
3089                 spin_lock_init(&sched->ibs_lock);
3090                 INIT_LIST_HEAD(&sched->ibs_conns);
3091                 init_waitqueue_head(&sched->ibs_waitq);
3092
3093                 nthrs = cfs_cpt_weight(lnet_cpt_table(), i);
3094                 if (*kiblnd_tunables.kib_nscheds > 0) {
3095                         nthrs = min(nthrs, *kiblnd_tunables.kib_nscheds);
3096                 } else {
3097                         /* max to half of CPUs, another half is reserved for
3098                          * upper layer modules */
3099                         nthrs = min(max(IBLND_N_SCHED, nthrs >> 1), nthrs);
3100                 }
3101
3102                 sched->ibs_nthreads_max = nthrs;
3103                 sched->ibs_cpt = i;
3104         }
3105
3106         kiblnd_data.kib_error_qpa.qp_state = IB_QPS_ERR;
3107
3108         /* lists/ptrs/locks initialised */
3109         kiblnd_data.kib_init = IBLND_INIT_DATA;
3110         /*****************************************************/
3111
3112         rc = kiblnd_thread_start(kiblnd_connd, NULL, "kiblnd_connd");
3113         if (rc != 0) {
3114                 CERROR("Can't spawn o2iblnd connd: %d\n", rc);
3115                 goto failed;
3116         }
3117
3118         if (*kiblnd_tunables.kib_dev_failover != 0)
3119                 rc = kiblnd_thread_start(kiblnd_failover_thread, ns,
3120                                          "kiblnd_failover");
3121
3122         if (rc != 0) {
3123                 CERROR("Can't spawn o2iblnd failover thread: %d\n", rc);
3124                 goto failed;
3125         }
3126
3127         /* flag everything initialised */
3128         kiblnd_data.kib_init = IBLND_INIT_ALL;
3129         /*****************************************************/
3130
3131         return 0;
3132
3133  failed:
3134         kiblnd_base_shutdown();
3135         return -ENETDOWN;
3136 }
3137
3138 static int
3139 kiblnd_start_schedulers(struct kib_sched_info *sched)
3140 {
3141         int     rc = 0;
3142         int     nthrs;
3143         int     i;
3144
3145         if (sched->ibs_nthreads == 0) {
3146                 if (*kiblnd_tunables.kib_nscheds > 0) {
3147                         nthrs = sched->ibs_nthreads_max;
3148                 } else {
3149                         nthrs = cfs_cpt_weight(lnet_cpt_table(),
3150                                                sched->ibs_cpt);
3151                         nthrs = min(max(IBLND_N_SCHED, nthrs >> 1), nthrs);
3152                         nthrs = min(IBLND_N_SCHED_HIGH, nthrs);
3153                 }
3154         } else {
3155                 LASSERT(sched->ibs_nthreads <= sched->ibs_nthreads_max);
3156                 /* increase one thread if there is new interface */
3157                 nthrs = (sched->ibs_nthreads < sched->ibs_nthreads_max);
3158         }
3159
3160         for (i = 0; i < nthrs; i++) {
3161                 long    id;
3162                 char    name[20];
3163                 id = KIB_THREAD_ID(sched->ibs_cpt, sched->ibs_nthreads + i);
3164                 snprintf(name, sizeof(name), "kiblnd_sd_%02ld_%02ld",
3165                          KIB_THREAD_CPT(id), KIB_THREAD_TID(id));
3166                 rc = kiblnd_thread_start(kiblnd_scheduler, (void *)id, name);
3167                 if (rc == 0)
3168                         continue;
3169
3170                 CERROR("Can't spawn thread %d for scheduler[%d]: %d\n",
3171                        sched->ibs_cpt, sched->ibs_nthreads + i, rc);
3172                 break;
3173         }
3174
3175         sched->ibs_nthreads += i;
3176         return rc;
3177 }
3178
3179 static int kiblnd_dev_start_threads(struct kib_dev *dev, bool newdev, u32 *cpts,
3180                                     int ncpts)
3181 {
3182         int     cpt;
3183         int     rc;
3184         int     i;
3185
3186         for (i = 0; i < ncpts; i++) {
3187                 struct kib_sched_info *sched;
3188
3189                 cpt = (cpts == NULL) ? i : cpts[i];
3190                 sched = kiblnd_data.kib_scheds[cpt];
3191
3192                 if (!newdev && sched->ibs_nthreads > 0)
3193                         continue;
3194
3195                 rc = kiblnd_start_schedulers(kiblnd_data.kib_scheds[cpt]);
3196                 if (rc != 0) {
3197                         CERROR("Failed to start scheduler threads for %s\n",
3198                                dev->ibd_ifname);
3199                         return rc;
3200                 }
3201         }
3202         return 0;
3203 }
3204
3205 static struct kib_dev *
3206 kiblnd_dev_search(char *ifname)
3207 {
3208         struct kib_dev *alias = NULL;
3209         struct kib_dev *dev;
3210         char            *colon;
3211         char            *colon2;
3212
3213         colon = strchr(ifname, ':');
3214         list_for_each_entry(dev, &kiblnd_data.kib_devs, ibd_list) {
3215                 if (strcmp(&dev->ibd_ifname[0], ifname) == 0)
3216                         return dev;
3217
3218                 if (alias != NULL)
3219                         continue;
3220
3221                 colon2 = strchr(dev->ibd_ifname, ':');
3222                 if (colon != NULL)
3223                         *colon = 0;
3224                 if (colon2 != NULL)
3225                         *colon2 = 0;
3226
3227                 if (strcmp(&dev->ibd_ifname[0], ifname) == 0)
3228                         alias = dev;
3229
3230                 if (colon != NULL)
3231                         *colon = ':';
3232                 if (colon2 != NULL)
3233                         *colon2 = ':';
3234         }
3235         return alias;
3236 }
3237
3238 static int
3239 kiblnd_startup(struct lnet_ni *ni)
3240 {
3241         char *ifname = NULL;
3242         struct lnet_inetdev *ifaces = NULL;
3243         struct kib_dev *ibdev = NULL;
3244         struct kib_net *net = NULL;
3245         unsigned long flags;
3246         int rc;
3247         int i;
3248         bool newdev;
3249
3250         LASSERT(ni->ni_net->net_lnd == &the_o2iblnd);
3251
3252         if (kiblnd_data.kib_init == IBLND_INIT_NOTHING) {
3253                 rc = kiblnd_base_startup(ni->ni_net_ns);
3254                 if (rc != 0)
3255                         return rc;
3256         }
3257
3258         LIBCFS_ALLOC(net, sizeof(*net));
3259         ni->ni_data = net;
3260         if (net == NULL) {
3261                 rc = -ENOMEM;
3262                 goto failed;
3263         }
3264
3265         net->ibn_ni = ni;
3266         net->ibn_incarnation = ktime_get_real_ns() / NSEC_PER_USEC;
3267
3268         kiblnd_tunables_setup(ni);
3269
3270         /*
3271          * ni_interfaces is only to support legacy pre Multi-Rail
3272          * tcp bonding for ksocklnd. Multi-Rail wants each secondary
3273          * IP to be treated as an unique 'struct ni' interfaces instead.
3274          */
3275         if (ni->ni_interfaces[0] != NULL) {
3276                 /* Use the IPoIB interface specified in 'networks=' */
3277                 if (ni->ni_interfaces[1] != NULL) {
3278                         CERROR("ko2iblnd: Multiple interfaces not supported\n");
3279                         rc = -EINVAL;
3280                         goto failed;
3281                 }
3282
3283                 ifname = ni->ni_interfaces[0];
3284         } else {
3285                 ifname = *kiblnd_tunables.kib_default_ipif;
3286         }
3287
3288         if (strlen(ifname) >= sizeof(ibdev->ibd_ifname)) {
3289                 CERROR("IPoIB interface name too long: %s\n", ifname);
3290                 rc = -E2BIG;
3291                 goto failed;
3292         }
3293
3294         rc = lnet_inet_enumerate(&ifaces, ni->ni_net_ns);
3295         if (rc < 0)
3296                 goto failed;
3297
3298         for (i = 0; i < rc; i++) {
3299                 if (strcmp(ifname, ifaces[i].li_name) == 0)
3300                         break;
3301         }
3302
3303         if (i == rc) {
3304                 CERROR("ko2iblnd: No matching interfaces\n");
3305                 rc = -ENOENT;
3306                 goto failed;
3307         }
3308
3309         ibdev = kiblnd_dev_search(ifname);
3310         newdev = ibdev == NULL;
3311         /* hmm...create kib_dev even for alias */
3312         if (ibdev == NULL || strcmp(&ibdev->ibd_ifname[0], ifname) != 0) {
3313                 LIBCFS_ALLOC(ibdev, sizeof(*ibdev));
3314                 if (!ibdev) {
3315                         rc = -ENOMEM;
3316                         goto failed;
3317                 }
3318
3319                 ibdev->ibd_ifip = ifaces[i].li_ipaddr;
3320                 strlcpy(ibdev->ibd_ifname, ifaces[i].li_name,
3321                         sizeof(ibdev->ibd_ifname));
3322                 ibdev->ibd_can_failover = !!(ifaces[i].li_flags & IFF_MASTER);
3323
3324                 INIT_LIST_HEAD(&ibdev->ibd_nets);
3325                 INIT_LIST_HEAD(&ibdev->ibd_list); /* not yet in kib_devs */
3326                 INIT_LIST_HEAD(&ibdev->ibd_fail_list);
3327
3328                 /* initialize the device */
3329                 rc = kiblnd_dev_failover(ibdev, ni->ni_net_ns);
3330                 if (rc) {
3331                         CERROR("ko2iblnd: Can't initialize device: rc = %d\n",
3332                                rc);
3333                         goto failed;
3334                 }
3335
3336                 list_add_tail(&ibdev->ibd_list, &kiblnd_data.kib_devs);
3337         }
3338
3339         net->ibn_dev = ibdev;
3340         ni->ni_nid = LNET_MKNID(LNET_NIDNET(ni->ni_nid), ibdev->ibd_ifip);
3341
3342         ni->ni_dev_cpt = ifaces[i].li_cpt;
3343
3344         rc = kiblnd_dev_start_threads(ibdev, newdev, ni->ni_cpts, ni->ni_ncpts);
3345         if (rc != 0)
3346                 goto failed;
3347
3348         rc = kiblnd_net_init_pools(net, ni, ni->ni_cpts, ni->ni_ncpts);
3349         if (rc != 0) {
3350                 CERROR("Failed to initialize NI pools: %d\n", rc);
3351                 goto failed;
3352         }
3353
3354         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3355         ibdev->ibd_nnets++;
3356         list_add_tail(&net->ibn_list, &ibdev->ibd_nets);
3357         /* for health check */
3358         if (ibdev->ibd_hdev->ibh_state == IBLND_DEV_PORT_DOWN)
3359                 kiblnd_set_ni_fatal_on(ibdev->ibd_hdev, 1);
3360         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3361
3362         net->ibn_init = IBLND_INIT_ALL;
3363
3364         return 0;
3365
3366 failed:
3367         if (net != NULL && net->ibn_dev == NULL && ibdev != NULL)
3368                 kiblnd_destroy_dev(ibdev);
3369
3370         kfree(ifaces);
3371         kiblnd_shutdown(ni);
3372
3373         CDEBUG(D_NET, "Configuration of device %s failed: rc = %d\n",
3374                ifname ? ifname : "", rc);
3375
3376         return -ENETDOWN;
3377 }
3378
3379 static const struct lnet_lnd the_o2iblnd = {
3380         .lnd_type       = O2IBLND,
3381         .lnd_startup    = kiblnd_startup,
3382         .lnd_shutdown   = kiblnd_shutdown,
3383         .lnd_ctl        = kiblnd_ctl,
3384         .lnd_send       = kiblnd_send,
3385         .lnd_recv       = kiblnd_recv,
3386 };
3387
3388 static void __exit ko2iblnd_exit(void)
3389 {
3390         lnet_unregister_lnd(&the_o2iblnd);
3391 }
3392
3393 static int __init ko2iblnd_init(void)
3394 {
3395         int rc;
3396
3397         BUILD_BUG_ON(sizeof(struct kib_msg) > IBLND_MSG_SIZE);
3398         BUILD_BUG_ON(offsetof(struct kib_msg,
3399                      ibm_u.get.ibgm_rd.rd_frags[IBLND_MAX_RDMA_FRAGS]) >
3400                      IBLND_MSG_SIZE);
3401         BUILD_BUG_ON(offsetof(struct kib_msg,
3402                      ibm_u.putack.ibpam_rd.rd_frags[IBLND_MAX_RDMA_FRAGS]) >
3403                      IBLND_MSG_SIZE);
3404
3405         rc = kiblnd_tunables_init();
3406         if (rc != 0)
3407                 return rc;
3408
3409         lnet_register_lnd(&the_o2iblnd);
3410
3411         return 0;
3412 }
3413
3414 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
3415 MODULE_DESCRIPTION("OpenIB gen2 LNet Network Driver");
3416 MODULE_VERSION("2.8.0");
3417 MODULE_LICENSE("GPL");
3418
3419 module_init(ko2iblnd_init);
3420 module_exit(ko2iblnd_exit);