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