Whamcloud - gitweb
945f0c8e6aa54e6ea1308ba55811241a0866e97c
[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                 BUILD_BUG_ON(sizeof(msg->ibm_type) != 1);
260                 BUILD_BUG_ON(sizeof(msg->ibm_credits) != 1);
261                 msg->ibm_nob     = msg_nob;
262                 __swab64s(&msg->ibm_srcnid);
263                 __swab64s(&msg->ibm_srcstamp);
264                 __swab64s(&msg->ibm_dstnid);
265                 __swab64s(&msg->ibm_dststamp);
266         }
267
268         if (msg->ibm_srcnid == LNET_NID_ANY) {
269                 CERROR("Bad src nid: %s\n", libcfs_nid2str(msg->ibm_srcnid));
270                 return -EPROTO;
271         }
272
273         if (msg_nob < kiblnd_msgtype2size(msg->ibm_type)) {
274                 CERROR("Short %s: %d(%d)\n", kiblnd_msgtype2str(msg->ibm_type),
275                        msg_nob, kiblnd_msgtype2size(msg->ibm_type));
276                 return -EPROTO;
277         }
278
279         switch (msg->ibm_type) {
280         default:
281                 CERROR("Unknown message type %x\n", msg->ibm_type);
282                 return -EPROTO;
283
284         case IBLND_MSG_NOOP:
285         case IBLND_MSG_IMMEDIATE:
286         case IBLND_MSG_PUT_REQ:
287                 break;
288
289         case IBLND_MSG_PUT_ACK:
290         case IBLND_MSG_GET_REQ:
291                 if (kiblnd_unpack_rd(msg, flip))
292                         return -EPROTO;
293                 break;
294
295         case IBLND_MSG_PUT_NAK:
296         case IBLND_MSG_PUT_DONE:
297         case IBLND_MSG_GET_DONE:
298                 if (flip)
299                         __swab32s(&msg->ibm_u.completion.ibcm_status);
300                 break;
301
302         case IBLND_MSG_CONNREQ:
303         case IBLND_MSG_CONNACK:
304                 if (flip) {
305                         __swab16s(&msg->ibm_u.connparams.ibcp_queue_depth);
306                         __swab16s(&msg->ibm_u.connparams.ibcp_max_frags);
307                         __swab32s(&msg->ibm_u.connparams.ibcp_max_msg_size);
308                 }
309                 break;
310         }
311         return 0;
312 }
313
314 int
315 kiblnd_create_peer(struct lnet_ni *ni, struct kib_peer_ni **peerp,
316                    lnet_nid_t nid)
317 {
318         struct kib_peer_ni *peer_ni;
319         struct kib_net *net = ni->ni_data;
320         int cpt = lnet_cpt_of_nid(nid, ni);
321         unsigned long flags;
322
323         LASSERT(net != NULL);
324         LASSERT(nid != LNET_NID_ANY);
325
326         LIBCFS_CPT_ALLOC(peer_ni, lnet_cpt_table(), cpt, sizeof(*peer_ni));
327         if (peer_ni == NULL) {
328                 CERROR("Cannot allocate peer_ni\n");
329                 return -ENOMEM;
330         }
331
332         peer_ni->ibp_ni = ni;
333         peer_ni->ibp_nid = nid;
334         peer_ni->ibp_error = 0;
335         peer_ni->ibp_last_alive = 0;
336         peer_ni->ibp_max_frags = IBLND_MAX_RDMA_FRAGS;
337         peer_ni->ibp_queue_depth = ni->ni_net->net_tunables.lct_peer_tx_credits;
338         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         LIST_HEAD(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
1015         LASSERT (!in_interrupt());
1016         LASSERT (atomic_read(&conn->ibc_refcount) == 0);
1017         LASSERT(list_empty(&conn->ibc_early_rxs));
1018         LASSERT(list_empty(&conn->ibc_tx_noops));
1019         LASSERT(list_empty(&conn->ibc_tx_queue));
1020         LASSERT(list_empty(&conn->ibc_tx_queue_rsrvd));
1021         LASSERT(list_empty(&conn->ibc_tx_queue_nocred));
1022         LASSERT(list_empty(&conn->ibc_active_txs));
1023         LASSERT (conn->ibc_noops_posted == 0);
1024         LASSERT (conn->ibc_nsends_posted == 0);
1025
1026         switch (conn->ibc_state) {
1027         default:
1028                 /* conn must be completely disengaged from the network */
1029                 LBUG();
1030
1031         case IBLND_CONN_DISCONNECTED:
1032                 /* connvars should have been freed already */
1033                 LASSERT (conn->ibc_connvars == NULL);
1034                 break;
1035
1036         case IBLND_CONN_INIT:
1037                 break;
1038         }
1039
1040         /* conn->ibc_cmid might be destroyed by CM already */
1041         if (cmid != NULL && cmid->qp != NULL)
1042                 rdma_destroy_qp(cmid);
1043
1044         if (conn->ibc_cq)
1045                 ib_destroy_cq(conn->ibc_cq);
1046
1047         kiblnd_txlist_done(&conn->ibc_zombie_txs, -ECONNABORTED,
1048                            LNET_MSG_STATUS_OK);
1049
1050         if (conn->ibc_rx_pages != NULL)
1051                 kiblnd_unmap_rx_descs(conn);
1052
1053         if (conn->ibc_rxs != NULL) {
1054                 LIBCFS_FREE(conn->ibc_rxs,
1055                             IBLND_RX_MSGS(conn) * sizeof(struct kib_rx));
1056         }
1057
1058         if (conn->ibc_connvars != NULL)
1059                 LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
1060
1061         if (conn->ibc_hdev != NULL)
1062                 kiblnd_hdev_decref(conn->ibc_hdev);
1063
1064         /* See CAVEAT EMPTOR above in kiblnd_create_conn */
1065         if (conn->ibc_state != IBLND_CONN_INIT) {
1066                 struct kib_net *net = peer_ni->ibp_ni->ni_data;
1067
1068                 kiblnd_peer_decref(peer_ni);
1069                 rdma_destroy_id(cmid);
1070                 atomic_dec(&net->ibn_nconns);
1071         }
1072 }
1073
1074 int
1075 kiblnd_close_peer_conns_locked(struct kib_peer_ni *peer_ni, int why)
1076 {
1077         struct kib_conn *conn;
1078         struct list_head        *ctmp;
1079         struct list_head        *cnxt;
1080         int                     count = 0;
1081
1082         list_for_each_safe(ctmp, cnxt, &peer_ni->ibp_conns) {
1083                 conn = list_entry(ctmp, struct kib_conn, ibc_list);
1084
1085                 CDEBUG(D_NET, "Closing conn -> %s, "
1086                               "version: %x, reason: %d\n",
1087                        libcfs_nid2str(peer_ni->ibp_nid),
1088                        conn->ibc_version, why);
1089
1090                 kiblnd_close_conn_locked(conn, why);
1091                 count++;
1092         }
1093
1094         return count;
1095 }
1096
1097 int
1098 kiblnd_close_stale_conns_locked(struct kib_peer_ni *peer_ni,
1099                                 int version, __u64 incarnation)
1100 {
1101         struct kib_conn *conn;
1102         struct list_head        *ctmp;
1103         struct list_head        *cnxt;
1104         int                     count = 0;
1105
1106         list_for_each_safe(ctmp, cnxt, &peer_ni->ibp_conns) {
1107                 conn = list_entry(ctmp, struct kib_conn, ibc_list);
1108
1109                 if (conn->ibc_version     == version &&
1110                     conn->ibc_incarnation == incarnation)
1111                         continue;
1112
1113                 CDEBUG(D_NET, "Closing stale conn -> %s version: %x, "
1114                               "incarnation:%#llx(%x, %#llx)\n",
1115                        libcfs_nid2str(peer_ni->ibp_nid),
1116                        conn->ibc_version, conn->ibc_incarnation,
1117                        version, incarnation);
1118
1119                 kiblnd_close_conn_locked(conn, -ESTALE);
1120                 count++;
1121         }
1122
1123         return count;
1124 }
1125
1126 static int
1127 kiblnd_close_matching_conns(struct lnet_ni *ni, lnet_nid_t nid)
1128 {
1129         struct kib_peer_ni              *peer_ni;
1130         struct list_head        *ptmp;
1131         struct list_head        *pnxt;
1132         int                     lo;
1133         int                     hi;
1134         int                     i;
1135         unsigned long           flags;
1136         int                     count = 0;
1137
1138         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1139
1140         if (nid != LNET_NID_ANY)
1141                 lo = hi = kiblnd_nid2peerlist(nid) - kiblnd_data.kib_peers;
1142         else {
1143                 lo = 0;
1144                 hi = kiblnd_data.kib_peer_hash_size - 1;
1145         }
1146
1147         for (i = lo; i <= hi; i++) {
1148                 list_for_each_safe(ptmp, pnxt, &kiblnd_data.kib_peers[i]) {
1149
1150                         peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
1151                         LASSERT(!kiblnd_peer_idle(peer_ni));
1152
1153                         if (peer_ni->ibp_ni != ni)
1154                                 continue;
1155
1156                         if (!(nid == LNET_NID_ANY || nid == peer_ni->ibp_nid))
1157                                 continue;
1158
1159                         count += kiblnd_close_peer_conns_locked(peer_ni, 0);
1160                 }
1161         }
1162
1163         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1164
1165         /* wildcards always succeed */
1166         if (nid == LNET_NID_ANY)
1167                 return 0;
1168
1169         return (count == 0) ? -ENOENT : 0;
1170 }
1171
1172 static int
1173 kiblnd_ctl(struct lnet_ni *ni, unsigned int cmd, void *arg)
1174 {
1175         struct libcfs_ioctl_data *data = arg;
1176         int                       rc = -EINVAL;
1177
1178         switch(cmd) {
1179         case IOC_LIBCFS_GET_PEER: {
1180                 lnet_nid_t   nid = 0;
1181                 int          count = 0;
1182
1183                 rc = kiblnd_get_peer_info(ni, data->ioc_count,
1184                                           &nid, &count);
1185                 data->ioc_nid    = nid;
1186                 data->ioc_count  = count;
1187                 break;
1188         }
1189
1190         case IOC_LIBCFS_DEL_PEER: {
1191                 rc = kiblnd_del_peer(ni, data->ioc_nid);
1192                 break;
1193         }
1194         case IOC_LIBCFS_GET_CONN: {
1195                 struct kib_conn *conn;
1196
1197                 rc = 0;
1198                 conn = kiblnd_get_conn_by_idx(ni, data->ioc_count);
1199                 if (conn == NULL) {
1200                         rc = -ENOENT;
1201                         break;
1202                 }
1203
1204                 LASSERT(conn->ibc_cmid != NULL);
1205                 data->ioc_nid = conn->ibc_peer->ibp_nid;
1206                 if (conn->ibc_cmid->route.path_rec == NULL)
1207                         data->ioc_u32[0] = 0; /* iWarp has no path MTU */
1208                 else
1209                         data->ioc_u32[0] =
1210                         ib_mtu_enum_to_int(conn->ibc_cmid->route.path_rec->mtu);
1211                 kiblnd_conn_decref(conn);
1212                 break;
1213         }
1214         case IOC_LIBCFS_CLOSE_CONNECTION: {
1215                 rc = kiblnd_close_matching_conns(ni, data->ioc_nid);
1216                 break;
1217         }
1218
1219         default:
1220                 break;
1221         }
1222
1223         return rc;
1224 }
1225
1226 static void
1227 kiblnd_query(struct lnet_ni *ni, lnet_nid_t nid, time64_t *when)
1228 {
1229         time64_t last_alive = 0;
1230         time64_t now = ktime_get_seconds();
1231         rwlock_t *glock = &kiblnd_data.kib_global_lock;
1232         struct kib_peer_ni *peer_ni;
1233         unsigned long flags;
1234
1235         read_lock_irqsave(glock, flags);
1236
1237         peer_ni = kiblnd_find_peer_locked(ni, nid);
1238         if (peer_ni != NULL)
1239                 last_alive = peer_ni->ibp_last_alive;
1240
1241         read_unlock_irqrestore(glock, flags);
1242
1243         if (last_alive != 0)
1244                 *when = last_alive;
1245
1246         /* peer_ni is not persistent in hash, trigger peer_ni creation
1247          * and connection establishment with a NULL tx */
1248         if (peer_ni == NULL)
1249                 kiblnd_launch_tx(ni, NULL, nid);
1250
1251         CDEBUG(D_NET, "peer_ni %s %p, alive %lld secs ago\n",
1252                libcfs_nid2str(nid), peer_ni,
1253                last_alive ? now - last_alive : -1);
1254 }
1255
1256 static void
1257 kiblnd_free_pages(struct kib_pages *p)
1258 {
1259         int     npages = p->ibp_npages;
1260         int     i;
1261
1262         for (i = 0; i < npages; i++) {
1263                 if (p->ibp_pages[i] != NULL)
1264                         __free_page(p->ibp_pages[i]);
1265         }
1266
1267         LIBCFS_FREE(p, offsetof(struct kib_pages, ibp_pages[npages]));
1268 }
1269
1270 int
1271 kiblnd_alloc_pages(struct kib_pages **pp, int cpt, int npages)
1272 {
1273         struct kib_pages *p;
1274         int i;
1275
1276         LIBCFS_CPT_ALLOC(p, lnet_cpt_table(), cpt,
1277                          offsetof(struct kib_pages, ibp_pages[npages]));
1278         if (p == NULL) {
1279                 CERROR("Can't allocate descriptor for %d pages\n", npages);
1280                 return -ENOMEM;
1281         }
1282
1283         memset(p, 0, offsetof(struct kib_pages, ibp_pages[npages]));
1284         p->ibp_npages = npages;
1285
1286         for (i = 0; i < npages; i++) {
1287                 p->ibp_pages[i] = cfs_page_cpt_alloc(lnet_cpt_table(), cpt,
1288                                                      GFP_NOFS);
1289                 if (p->ibp_pages[i] == NULL) {
1290                         CERROR("Can't allocate page %d of %d\n", i, npages);
1291                         kiblnd_free_pages(p);
1292                         return -ENOMEM;
1293                 }
1294         }
1295
1296         *pp = p;
1297         return 0;
1298 }
1299
1300 void
1301 kiblnd_unmap_rx_descs(struct kib_conn *conn)
1302 {
1303         struct kib_rx *rx;
1304         int       i;
1305
1306         LASSERT (conn->ibc_rxs != NULL);
1307         LASSERT (conn->ibc_hdev != NULL);
1308
1309         for (i = 0; i < IBLND_RX_MSGS(conn); i++) {
1310                 rx = &conn->ibc_rxs[i];
1311
1312                 LASSERT(rx->rx_nob >= 0); /* not posted */
1313
1314                 kiblnd_dma_unmap_single(conn->ibc_hdev->ibh_ibdev,
1315                                         KIBLND_UNMAP_ADDR(rx, rx_msgunmap,
1316                                                           rx->rx_msgaddr),
1317                                         IBLND_MSG_SIZE, DMA_FROM_DEVICE);
1318         }
1319
1320         kiblnd_free_pages(conn->ibc_rx_pages);
1321
1322         conn->ibc_rx_pages = NULL;
1323 }
1324
1325 void
1326 kiblnd_map_rx_descs(struct kib_conn *conn)
1327 {
1328         struct kib_rx *rx;
1329         struct page    *pg;
1330         int             pg_off;
1331         int             ipg;
1332         int             i;
1333
1334         for (pg_off = ipg = i = 0; i < IBLND_RX_MSGS(conn); i++) {
1335                 pg = conn->ibc_rx_pages->ibp_pages[ipg];
1336                 rx = &conn->ibc_rxs[i];
1337
1338                 rx->rx_conn = conn;
1339                 rx->rx_msg = (struct kib_msg *)(((char *)page_address(pg)) + pg_off);
1340
1341                 rx->rx_msgaddr =
1342                         kiblnd_dma_map_single(conn->ibc_hdev->ibh_ibdev,
1343                                               rx->rx_msg, IBLND_MSG_SIZE,
1344                                               DMA_FROM_DEVICE);
1345                 LASSERT(!kiblnd_dma_mapping_error(conn->ibc_hdev->ibh_ibdev,
1346                                                   rx->rx_msgaddr));
1347                 KIBLND_UNMAP_ADDR_SET(rx, rx_msgunmap, rx->rx_msgaddr);
1348
1349                 CDEBUG(D_NET, "rx %d: %p %#llx(%#llx)\n",
1350                        i, rx->rx_msg, rx->rx_msgaddr,
1351                        (__u64)(page_to_phys(pg) + pg_off));
1352
1353                 pg_off += IBLND_MSG_SIZE;
1354                 LASSERT(pg_off <= PAGE_SIZE);
1355
1356                 if (pg_off == PAGE_SIZE) {
1357                         pg_off = 0;
1358                         ipg++;
1359                         LASSERT(ipg <= IBLND_RX_MSG_PAGES(conn));
1360                 }
1361         }
1362 }
1363
1364 static void
1365 kiblnd_unmap_tx_pool(struct kib_tx_pool *tpo)
1366 {
1367         struct kib_hca_dev *hdev = tpo->tpo_hdev;
1368         struct kib_tx *tx;
1369         int i;
1370
1371         LASSERT (tpo->tpo_pool.po_allocated == 0);
1372
1373         if (hdev == NULL)
1374                 return;
1375
1376         for (i = 0; i < tpo->tpo_pool.po_size; i++) {
1377                 tx = &tpo->tpo_tx_descs[i];
1378                 kiblnd_dma_unmap_single(hdev->ibh_ibdev,
1379                                         KIBLND_UNMAP_ADDR(tx, tx_msgunmap,
1380                                                           tx->tx_msgaddr),
1381                                         IBLND_MSG_SIZE, DMA_TO_DEVICE);
1382         }
1383
1384         kiblnd_hdev_decref(hdev);
1385         tpo->tpo_hdev = NULL;
1386 }
1387
1388 static struct kib_hca_dev *
1389 kiblnd_current_hdev(struct kib_dev *dev)
1390 {
1391         struct kib_hca_dev *hdev;
1392         unsigned long  flags;
1393         int            i = 0;
1394
1395         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1396         while (dev->ibd_failover) {
1397                 read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1398                 if (i++ % 50 == 0)
1399                         CDEBUG(D_NET, "%s: Wait for failover\n",
1400                                dev->ibd_ifname);
1401                 set_current_state(TASK_INTERRUPTIBLE);
1402                 schedule_timeout(cfs_time_seconds(1) / 100);
1403
1404                 read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1405         }
1406
1407         kiblnd_hdev_addref_locked(dev->ibd_hdev);
1408         hdev = dev->ibd_hdev;
1409
1410         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1411
1412         return hdev;
1413 }
1414
1415 static void
1416 kiblnd_map_tx_pool(struct kib_tx_pool *tpo)
1417 {
1418         struct kib_pages *txpgs = tpo->tpo_tx_pages;
1419         struct kib_pool *pool = &tpo->tpo_pool;
1420         struct kib_net      *net   = pool->po_owner->ps_net;
1421         struct kib_dev *dev;
1422         struct page *page;
1423         struct kib_tx *tx;
1424         int             page_offset;
1425         int             ipage;
1426         int             i;
1427
1428         LASSERT (net != NULL);
1429
1430         dev = net->ibn_dev;
1431
1432         /* pre-mapped messages are not bigger than 1 page */
1433         BUILD_BUG_ON(IBLND_MSG_SIZE > PAGE_SIZE);
1434
1435         /* No fancy arithmetic when we do the buffer calculations */
1436         BUILD_BUG_ON(PAGE_SIZE % IBLND_MSG_SIZE != 0);
1437
1438         tpo->tpo_hdev = kiblnd_current_hdev(dev);
1439
1440         for (ipage = page_offset = i = 0; i < pool->po_size; i++) {
1441                 page = txpgs->ibp_pages[ipage];
1442                 tx = &tpo->tpo_tx_descs[i];
1443
1444                 tx->tx_msg = (struct kib_msg *)(((char *)page_address(page)) +
1445                                                 page_offset);
1446
1447                 tx->tx_msgaddr = kiblnd_dma_map_single(tpo->tpo_hdev->ibh_ibdev,
1448                                                        tx->tx_msg,
1449                                                        IBLND_MSG_SIZE,
1450                                                        DMA_TO_DEVICE);
1451                 LASSERT(!kiblnd_dma_mapping_error(tpo->tpo_hdev->ibh_ibdev,
1452                                                   tx->tx_msgaddr));
1453                 KIBLND_UNMAP_ADDR_SET(tx, tx_msgunmap, tx->tx_msgaddr);
1454
1455                 list_add(&tx->tx_list, &pool->po_free_list);
1456
1457                 page_offset += IBLND_MSG_SIZE;
1458                 LASSERT(page_offset <= PAGE_SIZE);
1459
1460                 if (page_offset == PAGE_SIZE) {
1461                         page_offset = 0;
1462                         ipage++;
1463                         LASSERT(ipage <= txpgs->ibp_npages);
1464                 }
1465         }
1466 }
1467
1468 static void
1469 kiblnd_destroy_fmr_pool(struct kib_fmr_pool *fpo)
1470 {
1471         LASSERT(fpo->fpo_map_count == 0);
1472
1473         if (fpo->fpo_is_fmr && fpo->fmr.fpo_fmr_pool) {
1474                 ib_destroy_fmr_pool(fpo->fmr.fpo_fmr_pool);
1475         } else {
1476                 struct kib_fast_reg_descriptor *frd, *tmp;
1477                 int i = 0;
1478
1479                 list_for_each_entry_safe(frd, tmp, &fpo->fast_reg.fpo_pool_list,
1480                                          frd_list) {
1481                         list_del(&frd->frd_list);
1482 #ifndef HAVE_IB_MAP_MR_SG
1483                         ib_free_fast_reg_page_list(frd->frd_frpl);
1484 #endif
1485                         ib_dereg_mr(frd->frd_mr);
1486                         LIBCFS_FREE(frd, sizeof(*frd));
1487                         i++;
1488                 }
1489                 if (i < fpo->fast_reg.fpo_pool_size)
1490                         CERROR("FastReg pool still has %d regions registered\n",
1491                                 fpo->fast_reg.fpo_pool_size - i);
1492         }
1493
1494         if (fpo->fpo_hdev)
1495                 kiblnd_hdev_decref(fpo->fpo_hdev);
1496
1497         LIBCFS_FREE(fpo, sizeof(*fpo));
1498 }
1499
1500 static void
1501 kiblnd_destroy_fmr_pool_list(struct list_head *head)
1502 {
1503         struct kib_fmr_pool *fpo, *tmp;
1504
1505         list_for_each_entry_safe(fpo, tmp, head, fpo_list) {
1506                 list_del(&fpo->fpo_list);
1507                 kiblnd_destroy_fmr_pool(fpo);
1508         }
1509 }
1510
1511 static int
1512 kiblnd_fmr_pool_size(struct lnet_ioctl_config_o2iblnd_tunables *tunables,
1513                      int ncpts)
1514 {
1515         int size = tunables->lnd_fmr_pool_size / ncpts;
1516
1517         return max(IBLND_FMR_POOL, size);
1518 }
1519
1520 static int
1521 kiblnd_fmr_flush_trigger(struct lnet_ioctl_config_o2iblnd_tunables *tunables,
1522                          int ncpts)
1523 {
1524         int size = tunables->lnd_fmr_flush_trigger / ncpts;
1525
1526         return max(IBLND_FMR_POOL_FLUSH, size);
1527 }
1528
1529 static int kiblnd_alloc_fmr_pool(struct kib_fmr_poolset *fps,
1530                                  struct kib_fmr_pool *fpo)
1531 {
1532         struct ib_fmr_pool_param param = {
1533                 .max_pages_per_fmr = LNET_MAX_IOV,
1534                 .page_shift        = PAGE_SHIFT,
1535                 .access            = (IB_ACCESS_LOCAL_WRITE |
1536                                       IB_ACCESS_REMOTE_WRITE),
1537                 .pool_size         = fps->fps_pool_size,
1538                 .dirty_watermark   = fps->fps_flush_trigger,
1539                 .flush_function    = NULL,
1540                 .flush_arg         = NULL,
1541                 .cache             = !!fps->fps_cache };
1542         int rc = 0;
1543
1544         fpo->fmr.fpo_fmr_pool = ib_create_fmr_pool(fpo->fpo_hdev->ibh_pd,
1545                                                    &param);
1546         if (IS_ERR(fpo->fmr.fpo_fmr_pool)) {
1547                 rc = PTR_ERR(fpo->fmr.fpo_fmr_pool);
1548                 if (rc != -ENOSYS)
1549                         CERROR("Failed to create FMR pool: %d\n", rc);
1550                 else
1551                         CERROR("FMRs are not supported\n");
1552         }
1553         fpo->fpo_is_fmr = true;
1554
1555         return rc;
1556 }
1557
1558 static int kiblnd_alloc_freg_pool(struct kib_fmr_poolset *fps,
1559                                   struct kib_fmr_pool *fpo,
1560                                   enum kib_dev_caps dev_caps)
1561 {
1562         struct kib_fast_reg_descriptor *frd, *tmp;
1563         int i, rc;
1564
1565         fpo->fpo_is_fmr = false;
1566
1567         INIT_LIST_HEAD(&fpo->fast_reg.fpo_pool_list);
1568         fpo->fast_reg.fpo_pool_size = 0;
1569         for (i = 0; i < fps->fps_pool_size; i++) {
1570                 LIBCFS_CPT_ALLOC(frd, lnet_cpt_table(), fps->fps_cpt,
1571                                  sizeof(*frd));
1572                 if (!frd) {
1573                         CERROR("Failed to allocate a new fast_reg descriptor\n");
1574                         rc = -ENOMEM;
1575                         goto out;
1576                 }
1577                 frd->frd_mr = NULL;
1578
1579 #ifndef HAVE_IB_MAP_MR_SG
1580                 frd->frd_frpl = ib_alloc_fast_reg_page_list(fpo->fpo_hdev->ibh_ibdev,
1581                                                             LNET_MAX_IOV);
1582                 if (IS_ERR(frd->frd_frpl)) {
1583                         rc = PTR_ERR(frd->frd_frpl);
1584                         CERROR("Failed to allocate ib_fast_reg_page_list: %d\n",
1585                                 rc);
1586                         frd->frd_frpl = NULL;
1587                         goto out_middle;
1588                 }
1589 #endif
1590
1591 #ifdef HAVE_IB_ALLOC_FAST_REG_MR
1592                 frd->frd_mr = ib_alloc_fast_reg_mr(fpo->fpo_hdev->ibh_pd,
1593                                                    LNET_MAX_IOV);
1594 #else
1595                 /*
1596                  * it is expected to get here if this is an MLX-5 card.
1597                  * MLX-4 cards will always use FMR and MLX-5 cards will
1598                  * always use fast_reg. It turns out that some MLX-5 cards
1599                  * (possibly due to older FW versions) do not natively support
1600                  * gaps. So we will need to track them here.
1601                  */
1602                 frd->frd_mr = ib_alloc_mr(fpo->fpo_hdev->ibh_pd,
1603 #ifdef IB_MR_TYPE_SG_GAPS
1604                                           ((*kiblnd_tunables.kib_use_fastreg_gaps == 1) &&
1605                                            (dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT)) ?
1606                                                 IB_MR_TYPE_SG_GAPS :
1607                                                 IB_MR_TYPE_MEM_REG,
1608 #else
1609                                                 IB_MR_TYPE_MEM_REG,
1610 #endif
1611                                           LNET_MAX_IOV);
1612                 if ((*kiblnd_tunables.kib_use_fastreg_gaps == 1) &&
1613                     (dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT))
1614                         CWARN("using IB_MR_TYPE_SG_GAPS, expect a performance drop\n");
1615 #endif
1616                 if (IS_ERR(frd->frd_mr)) {
1617                         rc = PTR_ERR(frd->frd_mr);
1618                         CERROR("Failed to allocate ib_fast_reg_mr: %d\n", rc);
1619                         frd->frd_mr = NULL;
1620                         goto out_middle;
1621                 }
1622
1623                 /* There appears to be a bug in MLX5 code where you must
1624                  * invalidate the rkey of a new FastReg pool before first
1625                  * using it. Thus, I am marking the FRD invalid here. */
1626                 frd->frd_valid = false;
1627
1628                 list_add_tail(&frd->frd_list, &fpo->fast_reg.fpo_pool_list);
1629                 fpo->fast_reg.fpo_pool_size++;
1630         }
1631
1632         return 0;
1633
1634 out_middle:
1635         if (frd->frd_mr)
1636                 ib_dereg_mr(frd->frd_mr);
1637 #ifndef HAVE_IB_MAP_MR_SG
1638         if (frd->frd_frpl)
1639                 ib_free_fast_reg_page_list(frd->frd_frpl);
1640 #endif
1641         LIBCFS_FREE(frd, sizeof(*frd));
1642
1643 out:
1644         list_for_each_entry_safe(frd, tmp, &fpo->fast_reg.fpo_pool_list,
1645                                  frd_list) {
1646                 list_del(&frd->frd_list);
1647 #ifndef HAVE_IB_MAP_MR_SG
1648                 ib_free_fast_reg_page_list(frd->frd_frpl);
1649 #endif
1650                 ib_dereg_mr(frd->frd_mr);
1651                 LIBCFS_FREE(frd, sizeof(*frd));
1652         }
1653
1654         return rc;
1655 }
1656
1657 static int kiblnd_create_fmr_pool(struct kib_fmr_poolset *fps,
1658                                   struct kib_fmr_pool **pp_fpo)
1659 {
1660         struct kib_dev *dev = fps->fps_net->ibn_dev;
1661         struct kib_fmr_pool *fpo;
1662         int rc;
1663
1664         LIBCFS_CPT_ALLOC(fpo, lnet_cpt_table(), fps->fps_cpt, sizeof(*fpo));
1665         if (!fpo) {
1666                 return -ENOMEM;
1667         }
1668         memset(fpo, 0, sizeof(*fpo));
1669
1670         fpo->fpo_hdev = kiblnd_current_hdev(dev);
1671
1672         if (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)
1673                 rc = kiblnd_alloc_fmr_pool(fps, fpo);
1674         else
1675                 rc = kiblnd_alloc_freg_pool(fps, fpo, dev->ibd_dev_caps);
1676         if (rc)
1677                 goto out_fpo;
1678
1679         fpo->fpo_deadline = ktime_get_seconds() + IBLND_POOL_DEADLINE;
1680         fpo->fpo_owner = fps;
1681         *pp_fpo = fpo;
1682
1683         return 0;
1684
1685 out_fpo:
1686         kiblnd_hdev_decref(fpo->fpo_hdev);
1687         LIBCFS_FREE(fpo, sizeof(*fpo));
1688         return rc;
1689 }
1690
1691 static void
1692 kiblnd_fail_fmr_poolset(struct kib_fmr_poolset *fps, struct list_head *zombies)
1693 {
1694         if (fps->fps_net == NULL) /* intialized? */
1695                 return;
1696
1697         spin_lock(&fps->fps_lock);
1698
1699         while (!list_empty(&fps->fps_pool_list)) {
1700                 struct kib_fmr_pool *fpo = list_entry(fps->fps_pool_list.next,
1701                                                       struct kib_fmr_pool,
1702                                                       fpo_list);
1703
1704                 fpo->fpo_failed = 1;
1705                 list_del(&fpo->fpo_list);
1706                 if (fpo->fpo_map_count == 0)
1707                         list_add(&fpo->fpo_list, zombies);
1708                 else
1709                         list_add(&fpo->fpo_list, &fps->fps_failed_pool_list);
1710         }
1711
1712         spin_unlock(&fps->fps_lock);
1713 }
1714
1715 static void
1716 kiblnd_fini_fmr_poolset(struct kib_fmr_poolset *fps)
1717 {
1718         if (fps->fps_net != NULL) { /* initialized? */
1719                 kiblnd_destroy_fmr_pool_list(&fps->fps_failed_pool_list);
1720                 kiblnd_destroy_fmr_pool_list(&fps->fps_pool_list);
1721         }
1722 }
1723
1724 static int
1725 kiblnd_init_fmr_poolset(struct kib_fmr_poolset *fps, int cpt, int ncpts,
1726                         struct kib_net *net,
1727                         struct lnet_ioctl_config_o2iblnd_tunables *tunables)
1728 {
1729         struct kib_fmr_pool *fpo;
1730         int rc;
1731
1732         memset(fps, 0, sizeof(struct kib_fmr_poolset));
1733
1734         fps->fps_net = net;
1735         fps->fps_cpt = cpt;
1736
1737         fps->fps_pool_size = kiblnd_fmr_pool_size(tunables, ncpts);
1738         fps->fps_flush_trigger = kiblnd_fmr_flush_trigger(tunables, ncpts);
1739         fps->fps_cache = tunables->lnd_fmr_cache;
1740
1741         spin_lock_init(&fps->fps_lock);
1742         INIT_LIST_HEAD(&fps->fps_pool_list);
1743         INIT_LIST_HEAD(&fps->fps_failed_pool_list);
1744
1745         rc = kiblnd_create_fmr_pool(fps, &fpo);
1746         if (rc == 0)
1747                 list_add_tail(&fpo->fpo_list, &fps->fps_pool_list);
1748
1749         return rc;
1750 }
1751
1752 static int
1753 kiblnd_fmr_pool_is_idle(struct kib_fmr_pool *fpo, time64_t now)
1754 {
1755         if (fpo->fpo_map_count != 0) /* still in use */
1756                 return 0;
1757         if (fpo->fpo_failed)
1758                 return 1;
1759         return now >= fpo->fpo_deadline;
1760 }
1761
1762 static int
1763 kiblnd_map_tx_pages(struct kib_tx *tx, struct kib_rdma_desc *rd)
1764 {
1765         struct kib_hca_dev *hdev;
1766         __u64           *pages = tx->tx_pages;
1767         int             npages;
1768         int             size;
1769         int             i;
1770
1771         hdev = tx->tx_pool->tpo_hdev;
1772
1773         for (i = 0, npages = 0; i < rd->rd_nfrags; i++) {
1774                 for (size = 0; size <  rd->rd_frags[i].rf_nob;
1775                         size += hdev->ibh_page_size) {
1776                         pages[npages++] = (rd->rd_frags[i].rf_addr &
1777                                            hdev->ibh_page_mask) + size;
1778                 }
1779         }
1780
1781         return npages;
1782 }
1783
1784 void
1785 kiblnd_fmr_pool_unmap(struct kib_fmr *fmr, int status)
1786 {
1787         LIST_HEAD(zombies);
1788         struct kib_fmr_pool *fpo = fmr->fmr_pool;
1789         struct kib_fmr_poolset *fps;
1790         time64_t now = ktime_get_seconds();
1791         struct kib_fmr_pool *tmp;
1792         int rc;
1793
1794         if (!fpo)
1795                 return;
1796
1797         fps = fpo->fpo_owner;
1798         if (fpo->fpo_is_fmr) {
1799                 if (fmr->fmr_pfmr) {
1800                         ib_fmr_pool_unmap(fmr->fmr_pfmr);
1801                         fmr->fmr_pfmr = NULL;
1802                 }
1803
1804                 if (status) {
1805                         rc = ib_flush_fmr_pool(fpo->fmr.fpo_fmr_pool);
1806                         LASSERT(!rc);
1807                 }
1808         } else {
1809                 struct kib_fast_reg_descriptor *frd = fmr->fmr_frd;
1810
1811                 if (frd) {
1812                         frd->frd_valid = false;
1813                         spin_lock(&fps->fps_lock);
1814                         list_add_tail(&frd->frd_list, &fpo->fast_reg.fpo_pool_list);
1815                         spin_unlock(&fps->fps_lock);
1816                         fmr->fmr_frd = NULL;
1817                 }
1818         }
1819         fmr->fmr_pool = NULL;
1820
1821         spin_lock(&fps->fps_lock);
1822         fpo->fpo_map_count--;   /* decref the pool */
1823
1824         list_for_each_entry_safe(fpo, tmp, &fps->fps_pool_list, fpo_list) {
1825                 /* the first pool is persistent */
1826                 if (fps->fps_pool_list.next == &fpo->fpo_list)
1827                         continue;
1828
1829                 if (kiblnd_fmr_pool_is_idle(fpo, now)) {
1830                         list_move(&fpo->fpo_list, &zombies);
1831                         fps->fps_version++;
1832                 }
1833         }
1834         spin_unlock(&fps->fps_lock);
1835
1836         if (!list_empty(&zombies))
1837                 kiblnd_destroy_fmr_pool_list(&zombies);
1838 }
1839
1840 int kiblnd_fmr_pool_map(struct kib_fmr_poolset *fps, struct kib_tx *tx,
1841                         struct kib_rdma_desc *rd, u32 nob, u64 iov,
1842                         struct kib_fmr *fmr)
1843 {
1844         struct kib_fmr_pool *fpo;
1845         __u64 *pages = tx->tx_pages;
1846         __u64 version;
1847         bool is_rx = (rd != tx->tx_rd);
1848         bool tx_pages_mapped = 0;
1849         int npages = 0;
1850         int rc;
1851
1852 again:
1853         spin_lock(&fps->fps_lock);
1854         version = fps->fps_version;
1855         list_for_each_entry(fpo, &fps->fps_pool_list, fpo_list) {
1856                 fpo->fpo_deadline = ktime_get_seconds() + IBLND_POOL_DEADLINE;
1857                 fpo->fpo_map_count++;
1858
1859                 if (fpo->fpo_is_fmr) {
1860                         struct ib_pool_fmr *pfmr;
1861
1862                         spin_unlock(&fps->fps_lock);
1863
1864                         if (!tx_pages_mapped) {
1865                                 npages = kiblnd_map_tx_pages(tx, rd);
1866                                 tx_pages_mapped = 1;
1867                         }
1868
1869                         pfmr = kib_fmr_pool_map(fpo->fmr.fpo_fmr_pool,
1870                                                 pages, npages, iov);
1871                         if (likely(!IS_ERR(pfmr))) {
1872                                 fmr->fmr_key  = is_rx ? pfmr->fmr->rkey
1873                                                       : pfmr->fmr->lkey;
1874                                 fmr->fmr_frd  = NULL;
1875                                 fmr->fmr_pfmr = pfmr;
1876                                 fmr->fmr_pool = fpo;
1877                                 return 0;
1878                         }
1879                         rc = PTR_ERR(pfmr);
1880                 } else {
1881                         if (!list_empty(&fpo->fast_reg.fpo_pool_list)) {
1882                                 struct kib_fast_reg_descriptor *frd;
1883 #ifdef HAVE_IB_MAP_MR_SG
1884                                 struct ib_reg_wr *wr;
1885                                 int n;
1886 #else
1887                                 struct ib_rdma_wr *wr;
1888                                 struct ib_fast_reg_page_list *frpl;
1889 #endif
1890                                 struct ib_mr *mr;
1891
1892                                 frd = list_first_entry(&fpo->fast_reg.fpo_pool_list,
1893                                                         struct kib_fast_reg_descriptor,
1894                                                         frd_list);
1895                                 list_del(&frd->frd_list);
1896                                 spin_unlock(&fps->fps_lock);
1897
1898 #ifndef HAVE_IB_MAP_MR_SG
1899                                 frpl = frd->frd_frpl;
1900 #endif
1901                                 mr   = frd->frd_mr;
1902
1903                                 if (!frd->frd_valid) {
1904                                         struct ib_rdma_wr *inv_wr;
1905                                         __u32 key = is_rx ? mr->rkey : mr->lkey;
1906
1907                                         inv_wr = &frd->frd_inv_wr;
1908                                         memset(inv_wr, 0, sizeof(*inv_wr));
1909
1910                                         inv_wr->wr.opcode = IB_WR_LOCAL_INV;
1911                                         inv_wr->wr.wr_id  = IBLND_WID_MR;
1912                                         inv_wr->wr.ex.invalidate_rkey = key;
1913
1914                                         /* Bump the key */
1915                                         key = ib_inc_rkey(key);
1916                                         ib_update_fast_reg_key(mr, key);
1917                                 }
1918
1919 #ifdef HAVE_IB_MAP_MR_SG
1920 #ifdef HAVE_IB_MAP_MR_SG_5ARGS
1921                                 n = ib_map_mr_sg(mr, tx->tx_frags,
1922                                                  tx->tx_nfrags, NULL, PAGE_SIZE);
1923 #else
1924                                 n = ib_map_mr_sg(mr, tx->tx_frags,
1925                                                  tx->tx_nfrags, PAGE_SIZE);
1926 #endif
1927                                 if (unlikely(n != tx->tx_nfrags)) {
1928                                         CERROR("Failed to map mr %d/%d "
1929                                                "elements\n", n, tx->tx_nfrags);
1930                                         return n < 0 ? n : -EINVAL;
1931                                 }
1932
1933                                 wr = &frd->frd_fastreg_wr;
1934                                 memset(wr, 0, sizeof(*wr));
1935
1936                                 wr->wr.opcode = IB_WR_REG_MR;
1937                                 wr->wr.wr_id  = IBLND_WID_MR;
1938                                 wr->wr.num_sge = 0;
1939                                 wr->wr.send_flags = 0;
1940                                 wr->mr = mr;
1941                                 wr->key = is_rx ? mr->rkey : mr->lkey;
1942                                 wr->access = (IB_ACCESS_LOCAL_WRITE |
1943                                               IB_ACCESS_REMOTE_WRITE);
1944 #else
1945                                 if (!tx_pages_mapped) {
1946                                         npages = kiblnd_map_tx_pages(tx, rd);
1947                                         tx_pages_mapped = 1;
1948                                 }
1949
1950                                 LASSERT(npages <= frpl->max_page_list_len);
1951                                 memcpy(frpl->page_list, pages,
1952                                         sizeof(*pages) * npages);
1953
1954                                 /* Prepare FastReg WR */
1955                                 wr = &frd->frd_fastreg_wr;
1956                                 memset(wr, 0, sizeof(*wr));
1957
1958                                 wr->wr.opcode = IB_WR_FAST_REG_MR;
1959                                 wr->wr.wr_id  = IBLND_WID_MR;
1960
1961                                 wr->wr.wr.fast_reg.iova_start = iov;
1962                                 wr->wr.wr.fast_reg.page_list  = frpl;
1963                                 wr->wr.wr.fast_reg.page_list_len = npages;
1964                                 wr->wr.wr.fast_reg.page_shift = PAGE_SHIFT;
1965                                 wr->wr.wr.fast_reg.length = nob;
1966                                 wr->wr.wr.fast_reg.rkey =
1967                                                 is_rx ? mr->rkey : mr->lkey;
1968                                 wr->wr.wr.fast_reg.access_flags =
1969                                                 (IB_ACCESS_LOCAL_WRITE |
1970                                                  IB_ACCESS_REMOTE_WRITE);
1971 #endif
1972
1973                                 fmr->fmr_key  = is_rx ? mr->rkey : mr->lkey;
1974                                 fmr->fmr_frd  = frd;
1975                                 fmr->fmr_pfmr = NULL;
1976                                 fmr->fmr_pool = fpo;
1977                                 return 0;
1978                         }
1979                         spin_unlock(&fps->fps_lock);
1980                         rc = -EAGAIN;
1981                 }
1982
1983                 spin_lock(&fps->fps_lock);
1984                 fpo->fpo_map_count--;
1985                 if (rc != -EAGAIN) {
1986                         spin_unlock(&fps->fps_lock);
1987                         return rc;
1988                 }
1989
1990                 /* EAGAIN and ... */
1991                 if (version != fps->fps_version) {
1992                         spin_unlock(&fps->fps_lock);
1993                         goto again;
1994                 }
1995         }
1996
1997         if (fps->fps_increasing) {
1998                 spin_unlock(&fps->fps_lock);
1999                 CDEBUG(D_NET, "Another thread is allocating new "
2000                        "FMR pool, waiting for her to complete\n");
2001                 schedule();
2002                 goto again;
2003
2004         }
2005
2006         if (ktime_get_seconds() < fps->fps_next_retry) {
2007                 /* someone failed recently */
2008                 spin_unlock(&fps->fps_lock);
2009                 return -EAGAIN;
2010         }
2011
2012         fps->fps_increasing = 1;
2013         spin_unlock(&fps->fps_lock);
2014
2015         CDEBUG(D_NET, "Allocate new FMR pool\n");
2016         rc = kiblnd_create_fmr_pool(fps, &fpo);
2017         spin_lock(&fps->fps_lock);
2018         fps->fps_increasing = 0;
2019         if (rc == 0) {
2020                 fps->fps_version++;
2021                 list_add_tail(&fpo->fpo_list, &fps->fps_pool_list);
2022         } else {
2023                 fps->fps_next_retry = ktime_get_seconds() + IBLND_POOL_RETRY;
2024         }
2025         spin_unlock(&fps->fps_lock);
2026
2027         goto again;
2028 }
2029
2030 static void
2031 kiblnd_fini_pool(struct kib_pool *pool)
2032 {
2033         LASSERT(list_empty(&pool->po_free_list));
2034         LASSERT(pool->po_allocated == 0);
2035
2036         CDEBUG(D_NET, "Finalize %s pool\n", pool->po_owner->ps_name);
2037 }
2038
2039 static void
2040 kiblnd_init_pool(struct kib_poolset *ps, struct kib_pool *pool, int size)
2041 {
2042         CDEBUG(D_NET, "Initialize %s pool\n", ps->ps_name);
2043
2044         memset(pool, 0, sizeof(struct kib_pool));
2045         INIT_LIST_HEAD(&pool->po_free_list);
2046         pool->po_deadline = ktime_get_seconds() + IBLND_POOL_DEADLINE;
2047         pool->po_owner = ps;
2048         pool->po_size = size;
2049 }
2050
2051 static void
2052 kiblnd_destroy_pool_list(struct list_head *head)
2053 {
2054         struct kib_pool *pool;
2055
2056         while (!list_empty(head)) {
2057                 pool = list_entry(head->next, struct kib_pool, po_list);
2058                 list_del(&pool->po_list);
2059
2060                 LASSERT(pool->po_owner != NULL);
2061                 pool->po_owner->ps_pool_destroy(pool);
2062         }
2063 }
2064
2065 static void
2066 kiblnd_fail_poolset(struct kib_poolset *ps, struct list_head *zombies)
2067 {
2068         if (ps->ps_net == NULL) /* intialized? */
2069                 return;
2070
2071         spin_lock(&ps->ps_lock);
2072         while (!list_empty(&ps->ps_pool_list)) {
2073                 struct kib_pool *po = list_entry(ps->ps_pool_list.next,
2074                                                  struct kib_pool, po_list);
2075
2076                 po->po_failed = 1;
2077                 list_del(&po->po_list);
2078                 if (po->po_allocated == 0)
2079                         list_add(&po->po_list, zombies);
2080                 else
2081                         list_add(&po->po_list, &ps->ps_failed_pool_list);
2082         }
2083         spin_unlock(&ps->ps_lock);
2084 }
2085
2086 static void
2087 kiblnd_fini_poolset(struct kib_poolset *ps)
2088 {
2089         if (ps->ps_net != NULL) { /* initialized? */
2090                 kiblnd_destroy_pool_list(&ps->ps_failed_pool_list);
2091                 kiblnd_destroy_pool_list(&ps->ps_pool_list);
2092         }
2093 }
2094
2095 static int
2096 kiblnd_init_poolset(struct kib_poolset *ps, int cpt,
2097                     struct kib_net *net, char *name, int size,
2098                     kib_ps_pool_create_t po_create,
2099                     kib_ps_pool_destroy_t po_destroy,
2100                     kib_ps_node_init_t nd_init,
2101                     kib_ps_node_fini_t nd_fini)
2102 {
2103         struct kib_pool *pool;
2104         int rc;
2105
2106         memset(ps, 0, sizeof(struct kib_poolset));
2107
2108         ps->ps_cpt          = cpt;
2109         ps->ps_net          = net;
2110         ps->ps_pool_create  = po_create;
2111         ps->ps_pool_destroy = po_destroy;
2112         ps->ps_node_init    = nd_init;
2113         ps->ps_node_fini    = nd_fini;
2114         ps->ps_pool_size    = size;
2115         if (strlcpy(ps->ps_name, name, sizeof(ps->ps_name))
2116             >= sizeof(ps->ps_name))
2117                 return -E2BIG;
2118         spin_lock_init(&ps->ps_lock);
2119         INIT_LIST_HEAD(&ps->ps_pool_list);
2120         INIT_LIST_HEAD(&ps->ps_failed_pool_list);
2121
2122         rc = ps->ps_pool_create(ps, size, &pool);
2123         if (rc == 0)
2124                 list_add(&pool->po_list, &ps->ps_pool_list);
2125         else
2126                 CERROR("Failed to create the first pool for %s\n", ps->ps_name);
2127
2128         return rc;
2129 }
2130
2131 static int
2132 kiblnd_pool_is_idle(struct kib_pool *pool, time64_t now)
2133 {
2134         if (pool->po_allocated != 0) /* still in use */
2135                 return 0;
2136         if (pool->po_failed)
2137                 return 1;
2138         return now >= pool->po_deadline;
2139 }
2140
2141 void
2142 kiblnd_pool_free_node(struct kib_pool *pool, struct list_head *node)
2143 {
2144         LIST_HEAD(zombies);
2145         struct kib_poolset *ps = pool->po_owner;
2146         struct kib_pool *tmp;
2147         time64_t now = ktime_get_seconds();
2148
2149         spin_lock(&ps->ps_lock);
2150
2151         if (ps->ps_node_fini != NULL)
2152                 ps->ps_node_fini(pool, node);
2153
2154         LASSERT(pool->po_allocated > 0);
2155         list_add(node, &pool->po_free_list);
2156         pool->po_allocated--;
2157
2158         list_for_each_entry_safe(pool, tmp, &ps->ps_pool_list, po_list) {
2159                 /* the first pool is persistent */
2160                 if (ps->ps_pool_list.next == &pool->po_list)
2161                         continue;
2162
2163                 if (kiblnd_pool_is_idle(pool, now))
2164                         list_move(&pool->po_list, &zombies);
2165         }
2166         spin_unlock(&ps->ps_lock);
2167
2168         if (!list_empty(&zombies))
2169                 kiblnd_destroy_pool_list(&zombies);
2170 }
2171
2172 struct list_head *
2173 kiblnd_pool_alloc_node(struct kib_poolset *ps)
2174 {
2175         struct list_head        *node;
2176         struct kib_pool *pool;
2177         int                     rc;
2178         unsigned int            interval = 1;
2179         ktime_t time_before;
2180         unsigned int trips = 0;
2181
2182 again:
2183         spin_lock(&ps->ps_lock);
2184         list_for_each_entry(pool, &ps->ps_pool_list, po_list) {
2185                 if (list_empty(&pool->po_free_list))
2186                         continue;
2187
2188                 pool->po_allocated++;
2189                 pool->po_deadline = ktime_get_seconds() +
2190                                     IBLND_POOL_DEADLINE;
2191                 node = pool->po_free_list.next;
2192                 list_del(node);
2193
2194                 if (ps->ps_node_init != NULL) {
2195                         /* still hold the lock */
2196                         ps->ps_node_init(pool, node);
2197                 }
2198                 spin_unlock(&ps->ps_lock);
2199                 return node;
2200         }
2201
2202         /* no available tx pool and ... */
2203         if (ps->ps_increasing) {
2204                 /* another thread is allocating a new pool */
2205                 spin_unlock(&ps->ps_lock);
2206                 trips++;
2207                 CDEBUG(D_NET, "Another thread is allocating new "
2208                        "%s pool, waiting %d HZs for her to complete."
2209                        "trips = %d\n",
2210                        ps->ps_name, interval, trips);
2211
2212                 set_current_state(TASK_INTERRUPTIBLE);
2213                 schedule_timeout(interval);
2214                 if (interval < cfs_time_seconds(1))
2215                         interval *= 2;
2216
2217                 goto again;
2218         }
2219
2220         if (ktime_get_seconds() < ps->ps_next_retry) {
2221                 /* someone failed recently */
2222                 spin_unlock(&ps->ps_lock);
2223                 return NULL;
2224         }
2225
2226         ps->ps_increasing = 1;
2227         spin_unlock(&ps->ps_lock);
2228
2229         CDEBUG(D_NET, "%s pool exhausted, allocate new pool\n", ps->ps_name);
2230         time_before = ktime_get();
2231         rc = ps->ps_pool_create(ps, ps->ps_pool_size, &pool);
2232         CDEBUG(D_NET, "ps_pool_create took %lld ms to complete",
2233                ktime_ms_delta(ktime_get(), time_before));
2234
2235         spin_lock(&ps->ps_lock);
2236         ps->ps_increasing = 0;
2237         if (rc == 0) {
2238                 list_add_tail(&pool->po_list, &ps->ps_pool_list);
2239         } else {
2240                 ps->ps_next_retry = ktime_get_seconds() + IBLND_POOL_RETRY;
2241                 CERROR("Can't allocate new %s pool because out of memory\n",
2242                        ps->ps_name);
2243         }
2244         spin_unlock(&ps->ps_lock);
2245
2246         goto again;
2247 }
2248
2249 static void
2250 kiblnd_destroy_tx_pool(struct kib_pool *pool)
2251 {
2252         struct kib_tx_pool *tpo = container_of(pool, struct kib_tx_pool,
2253                                                tpo_pool);
2254         int i;
2255
2256         LASSERT (pool->po_allocated == 0);
2257
2258         if (tpo->tpo_tx_pages != NULL) {
2259                 kiblnd_unmap_tx_pool(tpo);
2260                 kiblnd_free_pages(tpo->tpo_tx_pages);
2261         }
2262
2263         if (tpo->tpo_tx_descs == NULL)
2264                 goto out;
2265
2266         for (i = 0; i < pool->po_size; i++) {
2267                 struct kib_tx *tx = &tpo->tpo_tx_descs[i];
2268                 int       wrq_sge = *kiblnd_tunables.kib_wrq_sge;
2269
2270                 list_del(&tx->tx_list);
2271                 if (tx->tx_pages != NULL)
2272                         LIBCFS_FREE(tx->tx_pages,
2273                                     LNET_MAX_IOV *
2274                                     sizeof(*tx->tx_pages));
2275                 if (tx->tx_frags != NULL)
2276                         LIBCFS_FREE(tx->tx_frags,
2277                                     (1 + IBLND_MAX_RDMA_FRAGS) *
2278                                     sizeof(*tx->tx_frags));
2279                 if (tx->tx_wrq != NULL)
2280                         LIBCFS_FREE(tx->tx_wrq,
2281                                     (1 + IBLND_MAX_RDMA_FRAGS) *
2282                                     sizeof(*tx->tx_wrq));
2283                 if (tx->tx_sge != NULL)
2284                         LIBCFS_FREE(tx->tx_sge,
2285                                     (1 + IBLND_MAX_RDMA_FRAGS) * wrq_sge *
2286                                     sizeof(*tx->tx_sge));
2287                 if (tx->tx_rd != NULL)
2288                         LIBCFS_FREE(tx->tx_rd,
2289                                     offsetof(struct kib_rdma_desc,
2290                                              rd_frags[IBLND_MAX_RDMA_FRAGS]));
2291         }
2292
2293         LIBCFS_FREE(tpo->tpo_tx_descs,
2294                     pool->po_size * sizeof(struct kib_tx));
2295 out:
2296         kiblnd_fini_pool(pool);
2297         LIBCFS_FREE(tpo, sizeof(struct kib_tx_pool));
2298 }
2299
2300 static int kiblnd_tx_pool_size(struct lnet_ni *ni, int ncpts)
2301 {
2302         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2303         int ntx;
2304
2305         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2306         ntx = tunables->lnd_ntx / ncpts;
2307
2308         return max(IBLND_TX_POOL, ntx);
2309 }
2310
2311 static int
2312 kiblnd_create_tx_pool(struct kib_poolset *ps, int size, struct kib_pool **pp_po)
2313 {
2314         int            i;
2315         int            npg;
2316         struct kib_pool *pool;
2317         struct kib_tx_pool *tpo;
2318
2319         LIBCFS_CPT_ALLOC(tpo, lnet_cpt_table(), ps->ps_cpt, sizeof(*tpo));
2320         if (tpo == NULL) {
2321                 CERROR("Failed to allocate TX pool\n");
2322                 return -ENOMEM;
2323         }
2324
2325         pool = &tpo->tpo_pool;
2326         kiblnd_init_pool(ps, pool, size);
2327         tpo->tpo_tx_descs = NULL;
2328         tpo->tpo_tx_pages = NULL;
2329
2330         npg = (size * IBLND_MSG_SIZE + PAGE_SIZE - 1) / PAGE_SIZE;
2331         if (kiblnd_alloc_pages(&tpo->tpo_tx_pages, ps->ps_cpt, npg) != 0) {
2332                 CERROR("Can't allocate tx pages: %d\n", npg);
2333                 LIBCFS_FREE(tpo, sizeof(struct kib_tx_pool));
2334                 return -ENOMEM;
2335         }
2336
2337         LIBCFS_CPT_ALLOC(tpo->tpo_tx_descs, lnet_cpt_table(), ps->ps_cpt,
2338                          size * sizeof(struct kib_tx));
2339         if (tpo->tpo_tx_descs == NULL) {
2340                 CERROR("Can't allocate %d tx descriptors\n", size);
2341                 ps->ps_pool_destroy(pool);
2342                 return -ENOMEM;
2343         }
2344
2345         memset(tpo->tpo_tx_descs, 0, size * sizeof(struct kib_tx));
2346
2347         for (i = 0; i < size; i++) {
2348                 struct kib_tx *tx = &tpo->tpo_tx_descs[i];
2349                 int       wrq_sge = *kiblnd_tunables.kib_wrq_sge;
2350
2351                 tx->tx_pool = tpo;
2352                 if (ps->ps_net->ibn_fmr_ps != NULL) {
2353                         LIBCFS_CPT_ALLOC(tx->tx_pages,
2354                                          lnet_cpt_table(), ps->ps_cpt,
2355                                          LNET_MAX_IOV * sizeof(*tx->tx_pages));
2356                         if (tx->tx_pages == NULL)
2357                                 break;
2358                 }
2359
2360                 LIBCFS_CPT_ALLOC(tx->tx_frags, lnet_cpt_table(), ps->ps_cpt,
2361                                  (1 + IBLND_MAX_RDMA_FRAGS) *
2362                                  sizeof(*tx->tx_frags));
2363                 if (tx->tx_frags == NULL)
2364                         break;
2365
2366                 sg_init_table(tx->tx_frags, IBLND_MAX_RDMA_FRAGS + 1);
2367
2368                 LIBCFS_CPT_ALLOC(tx->tx_wrq, lnet_cpt_table(), ps->ps_cpt,
2369                                  (1 + IBLND_MAX_RDMA_FRAGS) *
2370                                  sizeof(*tx->tx_wrq));
2371                 if (tx->tx_wrq == NULL)
2372                         break;
2373
2374                 LIBCFS_CPT_ALLOC(tx->tx_sge, lnet_cpt_table(), ps->ps_cpt,
2375                                  (1 + IBLND_MAX_RDMA_FRAGS) * wrq_sge *
2376                                  sizeof(*tx->tx_sge));
2377                 if (tx->tx_sge == NULL)
2378                         break;
2379
2380                 LIBCFS_CPT_ALLOC(tx->tx_rd, lnet_cpt_table(), ps->ps_cpt,
2381                                  offsetof(struct kib_rdma_desc,
2382                                           rd_frags[IBLND_MAX_RDMA_FRAGS]));
2383                 if (tx->tx_rd == NULL)
2384                         break;
2385         }
2386
2387         if (i == size) {
2388                 kiblnd_map_tx_pool(tpo);
2389                 *pp_po = pool;
2390                 return 0;
2391         }
2392
2393         ps->ps_pool_destroy(pool);
2394         return -ENOMEM;
2395 }
2396
2397 static void
2398 kiblnd_tx_init(struct kib_pool *pool, struct list_head *node)
2399 {
2400         struct kib_tx_poolset *tps = container_of(pool->po_owner,
2401                                                   struct kib_tx_poolset,
2402                                                   tps_poolset);
2403         struct kib_tx *tx  = list_entry(node, struct kib_tx, tx_list);
2404
2405         tx->tx_cookie = tps->tps_next_tx_cookie++;
2406 }
2407
2408 static void
2409 kiblnd_net_fini_pools(struct kib_net *net)
2410 {
2411         int     i;
2412
2413         cfs_cpt_for_each(i, lnet_cpt_table()) {
2414                 struct kib_tx_poolset *tps;
2415                 struct kib_fmr_poolset *fps;
2416
2417                 if (net->ibn_tx_ps != NULL) {
2418                         tps = net->ibn_tx_ps[i];
2419                         kiblnd_fini_poolset(&tps->tps_poolset);
2420                 }
2421
2422                 if (net->ibn_fmr_ps != NULL) {
2423                         fps = net->ibn_fmr_ps[i];
2424                         kiblnd_fini_fmr_poolset(fps);
2425                 }
2426         }
2427
2428         if (net->ibn_tx_ps != NULL) {
2429                 cfs_percpt_free(net->ibn_tx_ps);
2430                 net->ibn_tx_ps = NULL;
2431         }
2432
2433         if (net->ibn_fmr_ps != NULL) {
2434                 cfs_percpt_free(net->ibn_fmr_ps);
2435                 net->ibn_fmr_ps = NULL;
2436         }
2437 }
2438
2439 static int
2440 kiblnd_net_init_pools(struct kib_net *net, struct lnet_ni *ni, __u32 *cpts,
2441                       int ncpts)
2442 {
2443         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2444 #ifdef HAVE_IB_GET_DMA_MR
2445         unsigned long   flags;
2446 #endif
2447         int             cpt;
2448         int             rc;
2449         int             i;
2450
2451         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2452
2453 #ifdef HAVE_IB_GET_DMA_MR
2454         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2455         /*
2456          * if lnd_map_on_demand is zero then we have effectively disabled
2457          * FMR or FastReg and we're using global memory regions
2458          * exclusively.
2459          */
2460         if (!tunables->lnd_map_on_demand) {
2461                 read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2462                                            flags);
2463                 goto create_tx_pool;
2464         }
2465
2466         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2467 #endif
2468
2469         if (tunables->lnd_fmr_pool_size < tunables->lnd_ntx / 4) {
2470                 CERROR("Can't set fmr pool size (%d) < ntx / 4(%d)\n",
2471                        tunables->lnd_fmr_pool_size,
2472                        tunables->lnd_ntx / 4);
2473                 rc = -EINVAL;
2474                 goto failed;
2475         }
2476
2477         /* TX pool must be created later than FMR, see LU-2268
2478          * for details */
2479         LASSERT(net->ibn_tx_ps == NULL);
2480
2481         /* premapping can fail if ibd_nmr > 1, so we always create
2482          * FMR pool and map-on-demand if premapping failed */
2483
2484         net->ibn_fmr_ps = cfs_percpt_alloc(lnet_cpt_table(),
2485                                            sizeof(struct kib_fmr_poolset));
2486         if (net->ibn_fmr_ps == NULL) {
2487                 CERROR("Failed to allocate FMR pool array\n");
2488                 rc = -ENOMEM;
2489                 goto failed;
2490         }
2491
2492         for (i = 0; i < ncpts; i++) {
2493                 cpt = (cpts == NULL) ? i : cpts[i];
2494                 rc = kiblnd_init_fmr_poolset(net->ibn_fmr_ps[cpt], cpt, ncpts,
2495                                              net, tunables);
2496                 if (rc != 0) {
2497                         CERROR("Can't initialize FMR pool for CPT %d: %d\n",
2498                                cpt, rc);
2499                         goto failed;
2500                 }
2501         }
2502
2503         if (i > 0)
2504                 LASSERT(i == ncpts);
2505
2506 #ifdef HAVE_IB_GET_DMA_MR
2507  create_tx_pool:
2508 #endif
2509         net->ibn_tx_ps = cfs_percpt_alloc(lnet_cpt_table(),
2510                                           sizeof(struct kib_tx_poolset));
2511         if (net->ibn_tx_ps == NULL) {
2512                 CERROR("Failed to allocate tx pool array\n");
2513                 rc = -ENOMEM;
2514                 goto failed;
2515         }
2516
2517         for (i = 0; i < ncpts; i++) {
2518                 cpt = (cpts == NULL) ? i : cpts[i];
2519                 rc = kiblnd_init_poolset(&net->ibn_tx_ps[cpt]->tps_poolset,
2520                                          cpt, net, "TX",
2521                                          kiblnd_tx_pool_size(ni, ncpts),
2522                                          kiblnd_create_tx_pool,
2523                                          kiblnd_destroy_tx_pool,
2524                                          kiblnd_tx_init, NULL);
2525                 if (rc != 0) {
2526                         CERROR("Can't initialize TX pool for CPT %d: %d\n",
2527                                cpt, rc);
2528                         goto failed;
2529                 }
2530         }
2531
2532         return 0;
2533  failed:
2534         kiblnd_net_fini_pools(net);
2535         LASSERT(rc != 0);
2536         return rc;
2537 }
2538
2539 static int
2540 kiblnd_hdev_get_attr(struct kib_hca_dev *hdev)
2541 {
2542         struct ib_device_attr *dev_attr;
2543         int rc = 0;
2544
2545         /* It's safe to assume a HCA can handle a page size
2546          * matching that of the native system */
2547         hdev->ibh_page_shift = PAGE_SHIFT;
2548         hdev->ibh_page_size  = 1 << PAGE_SHIFT;
2549         hdev->ibh_page_mask  = ~((__u64)hdev->ibh_page_size - 1);
2550
2551 #ifndef HAVE_IB_DEVICE_ATTRS
2552         LIBCFS_ALLOC(dev_attr, sizeof(*dev_attr));
2553         if (dev_attr == NULL) {
2554                 CERROR("Out of memory\n");
2555                 return -ENOMEM;
2556         }
2557
2558         rc = ib_query_device(hdev->ibh_ibdev, dev_attr);
2559         if (rc != 0) {
2560                 CERROR("Failed to query IB device: %d\n", rc);
2561                 goto out_clean_attr;
2562         }
2563 #else
2564         dev_attr = &hdev->ibh_ibdev->attrs;
2565 #endif
2566
2567         hdev->ibh_mr_size = dev_attr->max_mr_size;
2568         hdev->ibh_max_qp_wr = dev_attr->max_qp_wr;
2569
2570         /* Setup device Memory Registration capabilities */
2571 #ifdef HAVE_IB_DEVICE_OPS
2572         if (hdev->ibh_ibdev->ops.alloc_fmr &&
2573             hdev->ibh_ibdev->ops.dealloc_fmr &&
2574             hdev->ibh_ibdev->ops.map_phys_fmr &&
2575             hdev->ibh_ibdev->ops.unmap_fmr) {
2576 #else
2577         if (hdev->ibh_ibdev->alloc_fmr &&
2578             hdev->ibh_ibdev->dealloc_fmr &&
2579             hdev->ibh_ibdev->map_phys_fmr &&
2580             hdev->ibh_ibdev->unmap_fmr) {
2581 #endif
2582                 LCONSOLE_INFO("Using FMR for registration\n");
2583                 hdev->ibh_dev->ibd_dev_caps |= IBLND_DEV_CAPS_FMR_ENABLED;
2584         } else if (dev_attr->device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS) {
2585                 LCONSOLE_INFO("Using FastReg for registration\n");
2586                 hdev->ibh_dev->ibd_dev_caps |= IBLND_DEV_CAPS_FASTREG_ENABLED;
2587 #ifndef HAVE_IB_ALLOC_FAST_REG_MR
2588 #ifdef IB_DEVICE_SG_GAPS_REG
2589                 if (dev_attr->device_cap_flags & IB_DEVICE_SG_GAPS_REG)
2590                         hdev->ibh_dev->ibd_dev_caps |= IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT;
2591 #endif
2592 #endif
2593         } else {
2594                 rc = -ENOSYS;
2595         }
2596
2597         if (rc != 0)
2598                 rc = -EINVAL;
2599
2600 #ifndef HAVE_IB_DEVICE_ATTRS
2601 out_clean_attr:
2602         LIBCFS_FREE(dev_attr, sizeof(*dev_attr));
2603 #endif
2604
2605         if (rc == -ENOSYS)
2606                 CERROR("IB device does not support FMRs nor FastRegs, can't "
2607                        "register memory: %d\n", rc);
2608         else if (rc == -EINVAL)
2609                 CERROR("Invalid mr size: %#llx\n", hdev->ibh_mr_size);
2610         return rc;
2611 }
2612
2613 #ifdef HAVE_IB_GET_DMA_MR
2614 static void
2615 kiblnd_hdev_cleanup_mrs(struct kib_hca_dev *hdev)
2616 {
2617         if (hdev->ibh_mrs == NULL)
2618                 return;
2619
2620         ib_dereg_mr(hdev->ibh_mrs);
2621
2622         hdev->ibh_mrs = NULL;
2623 }
2624 #endif
2625
2626 void
2627 kiblnd_hdev_destroy(struct kib_hca_dev *hdev)
2628 {
2629 #ifdef HAVE_IB_GET_DMA_MR
2630         kiblnd_hdev_cleanup_mrs(hdev);
2631 #endif
2632
2633         if (hdev->ibh_pd != NULL)
2634                 ib_dealloc_pd(hdev->ibh_pd);
2635
2636         if (hdev->ibh_cmid != NULL)
2637                 rdma_destroy_id(hdev->ibh_cmid);
2638
2639         LIBCFS_FREE(hdev, sizeof(*hdev));
2640 }
2641
2642 #ifdef HAVE_IB_GET_DMA_MR
2643 static int
2644 kiblnd_hdev_setup_mrs(struct kib_hca_dev *hdev)
2645 {
2646         struct ib_mr *mr;
2647         int           acflags = IB_ACCESS_LOCAL_WRITE |
2648                                 IB_ACCESS_REMOTE_WRITE;
2649
2650         mr = ib_get_dma_mr(hdev->ibh_pd, acflags);
2651         if (IS_ERR(mr)) {
2652                 CERROR("Failed ib_get_dma_mr: %ld\n", PTR_ERR(mr));
2653                 kiblnd_hdev_cleanup_mrs(hdev);
2654                 return PTR_ERR(mr);
2655         }
2656
2657         hdev->ibh_mrs = mr;
2658
2659         return 0;
2660 }
2661 #endif
2662
2663 static int
2664 kiblnd_dummy_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
2665 {       /* DUMMY */
2666         return 0;
2667 }
2668
2669 static int
2670 kiblnd_dev_need_failover(struct kib_dev *dev, struct net *ns)
2671 {
2672         struct rdma_cm_id  *cmid;
2673         struct sockaddr_in  srcaddr;
2674         struct sockaddr_in  dstaddr;
2675         int                 rc;
2676
2677         if (dev->ibd_hdev == NULL || /* initializing */
2678             dev->ibd_hdev->ibh_cmid == NULL || /* listener is dead */
2679             *kiblnd_tunables.kib_dev_failover > 1) /* debugging */
2680                 return 1;
2681
2682         /* XXX: it's UGLY, but I don't have better way to find
2683          * ib-bonding HCA failover because:
2684          *
2685          * a. no reliable CM event for HCA failover...
2686          * b. no OFED API to get ib_device for current net_device...
2687          *
2688          * We have only two choices at this point:
2689          *
2690          * a. rdma_bind_addr(), it will conflict with listener cmid
2691          * b. rdma_resolve_addr() to zero addr */
2692         cmid = kiblnd_rdma_create_id(ns, kiblnd_dummy_callback, dev,
2693                                      RDMA_PS_TCP, IB_QPT_RC);
2694         if (IS_ERR(cmid)) {
2695                 rc = PTR_ERR(cmid);
2696                 CERROR("Failed to create cmid for failover: %d\n", rc);
2697                 return rc;
2698         }
2699
2700         memset(&srcaddr, 0, sizeof(srcaddr));
2701         srcaddr.sin_family      = AF_INET;
2702         srcaddr.sin_addr.s_addr = (__force u32)htonl(dev->ibd_ifip);
2703
2704         memset(&dstaddr, 0, sizeof(dstaddr));
2705         dstaddr.sin_family = AF_INET;
2706         rc = rdma_resolve_addr(cmid, (struct sockaddr *)&srcaddr,
2707                                (struct sockaddr *)&dstaddr, 1);
2708         if (rc != 0 || cmid->device == NULL) {
2709                 CERROR("Failed to bind %s:%pI4h to device(%p): %d\n",
2710                        dev->ibd_ifname, &dev->ibd_ifip,
2711                        cmid->device, rc);
2712                 rdma_destroy_id(cmid);
2713                 return rc;
2714         }
2715
2716         rc = dev->ibd_hdev->ibh_ibdev != cmid->device; /* true for failover */
2717         rdma_destroy_id(cmid);
2718         return rc;
2719 }
2720
2721 int
2722 kiblnd_dev_failover(struct kib_dev *dev, struct net *ns)
2723 {
2724         LIST_HEAD(zombie_tpo);
2725         LIST_HEAD(zombie_ppo);
2726         LIST_HEAD(zombie_fpo);
2727         struct rdma_cm_id  *cmid  = NULL;
2728         struct kib_hca_dev *hdev  = NULL;
2729         struct kib_hca_dev *old;
2730         struct ib_pd       *pd;
2731         struct kib_net *net;
2732         struct sockaddr_in  addr;
2733         unsigned long       flags;
2734         int                 rc = 0;
2735         int                 i;
2736
2737         LASSERT (*kiblnd_tunables.kib_dev_failover > 1 ||
2738                  dev->ibd_can_failover ||
2739                  dev->ibd_hdev == NULL);
2740
2741         rc = kiblnd_dev_need_failover(dev, ns);
2742         if (rc <= 0)
2743                 goto out;
2744
2745         if (dev->ibd_hdev != NULL &&
2746             dev->ibd_hdev->ibh_cmid != NULL) {
2747                 /* XXX it's not good to close old listener at here,
2748                  * because we can fail to create new listener.
2749                  * But we have to close it now, otherwise rdma_bind_addr
2750                  * will return EADDRINUSE... How crap! */
2751                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2752
2753                 cmid = dev->ibd_hdev->ibh_cmid;
2754                 /* make next schedule of kiblnd_dev_need_failover()
2755                  * return 1 for me */
2756                 dev->ibd_hdev->ibh_cmid  = NULL;
2757                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2758
2759                 rdma_destroy_id(cmid);
2760         }
2761
2762         cmid = kiblnd_rdma_create_id(ns, kiblnd_cm_callback, dev, RDMA_PS_TCP,
2763                                      IB_QPT_RC);
2764         if (IS_ERR(cmid)) {
2765                 rc = PTR_ERR(cmid);
2766                 CERROR("Failed to create cmid for failover: %d\n", rc);
2767                 goto out;
2768         }
2769
2770         memset(&addr, 0, sizeof(addr));
2771         addr.sin_family      = AF_INET;
2772         addr.sin_addr.s_addr = (__force u32)htonl(dev->ibd_ifip);
2773         addr.sin_port        = htons(*kiblnd_tunables.kib_service);
2774
2775         /* Bind to failover device or port */
2776         rc = rdma_bind_addr(cmid, (struct sockaddr *)&addr);
2777         if (rc != 0 || cmid->device == NULL) {
2778                 CERROR("Failed to bind %s:%pI4h to device(%p): %d\n",
2779                        dev->ibd_ifname, &dev->ibd_ifip,
2780                        cmid->device, rc);
2781                 rdma_destroy_id(cmid);
2782                 goto out;
2783         }
2784
2785         LIBCFS_ALLOC(hdev, sizeof(*hdev));
2786         if (hdev == NULL) {
2787                 CERROR("Failed to allocate kib_hca_dev\n");
2788                 rdma_destroy_id(cmid);
2789                 rc = -ENOMEM;
2790                 goto out;
2791         }
2792
2793         atomic_set(&hdev->ibh_ref, 1);
2794         hdev->ibh_dev   = dev;
2795         hdev->ibh_cmid  = cmid;
2796         hdev->ibh_ibdev = cmid->device;
2797
2798 #ifdef HAVE_IB_ALLOC_PD_2ARGS
2799         pd = ib_alloc_pd(cmid->device, 0);
2800 #else
2801         pd = ib_alloc_pd(cmid->device);
2802 #endif
2803         if (IS_ERR(pd)) {
2804                 rc = PTR_ERR(pd);
2805                 CERROR("Can't allocate PD: %d\n", rc);
2806                 goto out;
2807         }
2808
2809         hdev->ibh_pd = pd;
2810
2811         rc = rdma_listen(cmid, 0);
2812         if (rc != 0) {
2813                 CERROR("Can't start new listener: %d\n", rc);
2814                 goto out;
2815         }
2816
2817         rc = kiblnd_hdev_get_attr(hdev);
2818         if (rc != 0) {
2819                 CERROR("Can't get device attributes: %d\n", rc);
2820                 goto out;
2821         }
2822
2823 #ifdef HAVE_IB_GET_DMA_MR
2824         rc = kiblnd_hdev_setup_mrs(hdev);
2825         if (rc != 0) {
2826                 CERROR("Can't setup device: %d\n", rc);
2827                 goto out;
2828         }
2829 #endif
2830
2831         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2832
2833         old = dev->ibd_hdev;
2834         dev->ibd_hdev = hdev;   /* take over the refcount */
2835         hdev = old;
2836
2837         list_for_each_entry(net, &dev->ibd_nets, ibn_list) {
2838                 cfs_cpt_for_each(i, lnet_cpt_table()) {
2839                         kiblnd_fail_poolset(&net->ibn_tx_ps[i]->tps_poolset,
2840                                             &zombie_tpo);
2841
2842                         if (net->ibn_fmr_ps != NULL)
2843                                 kiblnd_fail_fmr_poolset(net->ibn_fmr_ps[i],
2844                                                         &zombie_fpo);
2845                 }
2846         }
2847
2848         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2849  out:
2850         if (!list_empty(&zombie_tpo))
2851                 kiblnd_destroy_pool_list(&zombie_tpo);
2852         if (!list_empty(&zombie_ppo))
2853                 kiblnd_destroy_pool_list(&zombie_ppo);
2854         if (!list_empty(&zombie_fpo))
2855                 kiblnd_destroy_fmr_pool_list(&zombie_fpo);
2856         if (hdev != NULL)
2857                 kiblnd_hdev_decref(hdev);
2858
2859         if (rc != 0)
2860                 dev->ibd_failed_failover++;
2861         else
2862                 dev->ibd_failed_failover = 0;
2863
2864         return rc;
2865 }
2866
2867 void
2868 kiblnd_destroy_dev(struct kib_dev *dev)
2869 {
2870         LASSERT(dev->ibd_nnets == 0);
2871         LASSERT(list_empty(&dev->ibd_nets));
2872
2873         list_del(&dev->ibd_fail_list);
2874         list_del(&dev->ibd_list);
2875
2876         if (dev->ibd_hdev != NULL)
2877                 kiblnd_hdev_decref(dev->ibd_hdev);
2878
2879         LIBCFS_FREE(dev, sizeof(*dev));
2880 }
2881
2882 static void
2883 kiblnd_base_shutdown(void)
2884 {
2885         struct kib_sched_info   *sched;
2886         int                     i;
2887
2888         LASSERT(list_empty(&kiblnd_data.kib_devs));
2889
2890         CDEBUG(D_MALLOC, "before LND base cleanup: kmem %d\n",
2891                atomic_read(&libcfs_kmemory));
2892
2893         switch (kiblnd_data.kib_init) {
2894         default:
2895                 LBUG();
2896
2897         case IBLND_INIT_ALL:
2898         case IBLND_INIT_DATA:
2899                 LASSERT (kiblnd_data.kib_peers != NULL);
2900                 for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++) {
2901                         LASSERT(list_empty(&kiblnd_data.kib_peers[i]));
2902                 }
2903                 LASSERT(list_empty(&kiblnd_data.kib_connd_zombies));
2904                 LASSERT(list_empty(&kiblnd_data.kib_connd_conns));
2905                 LASSERT(list_empty(&kiblnd_data.kib_reconn_list));
2906                 LASSERT(list_empty(&kiblnd_data.kib_reconn_wait));
2907
2908                 /* flag threads to terminate; wake and wait for them to die */
2909                 kiblnd_data.kib_shutdown = 1;
2910
2911                 /* NB: we really want to stop scheduler threads net by net
2912                  * instead of the whole module, this should be improved
2913                  * with dynamic configuration LNet */
2914                 cfs_percpt_for_each(sched, i, kiblnd_data.kib_scheds)
2915                         wake_up_all(&sched->ibs_waitq);
2916
2917                 wake_up_all(&kiblnd_data.kib_connd_waitq);
2918                 wake_up_all(&kiblnd_data.kib_failover_waitq);
2919
2920                 i = 2;
2921                 while (atomic_read(&kiblnd_data.kib_nthreads) != 0) {
2922                         i++;
2923                         /* power of 2? */
2924                         CDEBUG(((i & (-i)) == i) ? D_WARNING : D_NET,
2925                                "Waiting for %d threads to terminate\n",
2926                                atomic_read(&kiblnd_data.kib_nthreads));
2927                         set_current_state(TASK_UNINTERRUPTIBLE);
2928                         schedule_timeout(cfs_time_seconds(1));
2929                 }
2930
2931                 /* fall through */
2932
2933         case IBLND_INIT_NOTHING:
2934                 break;
2935         }
2936
2937         if (kiblnd_data.kib_peers != NULL) {
2938                 LIBCFS_FREE(kiblnd_data.kib_peers,
2939                             sizeof(struct list_head) *
2940                             kiblnd_data.kib_peer_hash_size);
2941         }
2942
2943         if (kiblnd_data.kib_scheds != NULL)
2944                 cfs_percpt_free(kiblnd_data.kib_scheds);
2945
2946         CDEBUG(D_MALLOC, "after LND base cleanup: kmem %d\n",
2947                atomic_read(&libcfs_kmemory));
2948
2949         kiblnd_data.kib_init = IBLND_INIT_NOTHING;
2950         module_put(THIS_MODULE);
2951 }
2952
2953 static void
2954 kiblnd_shutdown(struct lnet_ni *ni)
2955 {
2956         struct kib_net *net = ni->ni_data;
2957         rwlock_t     *g_lock = &kiblnd_data.kib_global_lock;
2958         int               i;
2959         unsigned long     flags;
2960
2961         LASSERT(kiblnd_data.kib_init == IBLND_INIT_ALL);
2962
2963         if (net == NULL)
2964                 goto out;
2965
2966         CDEBUG(D_MALLOC, "before LND net cleanup: kmem %d\n",
2967                atomic_read(&libcfs_kmemory));
2968
2969         write_lock_irqsave(g_lock, flags);
2970         net->ibn_shutdown = 1;
2971         write_unlock_irqrestore(g_lock, flags);
2972
2973         switch (net->ibn_init) {
2974         default:
2975                 LBUG();
2976
2977         case IBLND_INIT_ALL:
2978                 /* nuke all existing peers within this net */
2979                 kiblnd_del_peer(ni, LNET_NID_ANY);
2980
2981                 /* Wait for all peer_ni state to clean up */
2982                 i = 2;
2983                 while (atomic_read(&net->ibn_npeers) != 0) {
2984                         i++;
2985                         /* power of 2? */
2986                         CDEBUG(((i & (-i)) == i) ? D_WARNING : D_NET,
2987                                "%s: waiting for %d peers to disconnect\n",
2988                                libcfs_nid2str(ni->ni_nid),
2989                                atomic_read(&net->ibn_npeers));
2990                         set_current_state(TASK_UNINTERRUPTIBLE);
2991                         schedule_timeout(cfs_time_seconds(1));
2992                 }
2993
2994                 kiblnd_net_fini_pools(net);
2995
2996                 write_lock_irqsave(g_lock, flags);
2997                 LASSERT(net->ibn_dev->ibd_nnets > 0);
2998                 net->ibn_dev->ibd_nnets--;
2999                 list_del(&net->ibn_list);
3000                 write_unlock_irqrestore(g_lock, flags);
3001
3002                 /* fall through */
3003
3004         case IBLND_INIT_NOTHING:
3005                 LASSERT (atomic_read(&net->ibn_nconns) == 0);
3006
3007                 if (net->ibn_dev != NULL &&
3008                     net->ibn_dev->ibd_nnets == 0)
3009                         kiblnd_destroy_dev(net->ibn_dev);
3010
3011                 break;
3012         }
3013
3014         CDEBUG(D_MALLOC, "after LND net cleanup: kmem %d\n",
3015                atomic_read(&libcfs_kmemory));
3016
3017         net->ibn_init = IBLND_INIT_NOTHING;
3018         ni->ni_data = NULL;
3019
3020         LIBCFS_FREE(net, sizeof(*net));
3021
3022 out:
3023         if (list_empty(&kiblnd_data.kib_devs))
3024                 kiblnd_base_shutdown();
3025 }
3026
3027 static int
3028 kiblnd_base_startup(struct net *ns)
3029 {
3030         struct kib_sched_info   *sched;
3031         int                     rc;
3032         int                     i;
3033
3034         LASSERT(kiblnd_data.kib_init == IBLND_INIT_NOTHING);
3035
3036         try_module_get(THIS_MODULE);
3037         memset(&kiblnd_data, 0, sizeof(kiblnd_data)); /* zero pointers, flags etc */
3038
3039         rwlock_init(&kiblnd_data.kib_global_lock);
3040
3041         INIT_LIST_HEAD(&kiblnd_data.kib_devs);
3042         INIT_LIST_HEAD(&kiblnd_data.kib_failed_devs);
3043
3044         kiblnd_data.kib_peer_hash_size = IBLND_PEER_HASH_SIZE;
3045         LIBCFS_ALLOC(kiblnd_data.kib_peers,
3046                      sizeof(struct list_head) *
3047                      kiblnd_data.kib_peer_hash_size);
3048         if (kiblnd_data.kib_peers == NULL)
3049                 goto failed;
3050
3051         for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++)
3052                 INIT_LIST_HEAD(&kiblnd_data.kib_peers[i]);
3053
3054         spin_lock_init(&kiblnd_data.kib_connd_lock);
3055         INIT_LIST_HEAD(&kiblnd_data.kib_connd_conns);
3056         INIT_LIST_HEAD(&kiblnd_data.kib_connd_zombies);
3057         INIT_LIST_HEAD(&kiblnd_data.kib_reconn_list);
3058         INIT_LIST_HEAD(&kiblnd_data.kib_reconn_wait);
3059
3060         init_waitqueue_head(&kiblnd_data.kib_connd_waitq);
3061         init_waitqueue_head(&kiblnd_data.kib_failover_waitq);
3062
3063         kiblnd_data.kib_scheds = cfs_percpt_alloc(lnet_cpt_table(),
3064                                                   sizeof(*sched));
3065         if (kiblnd_data.kib_scheds == NULL)
3066                 goto failed;
3067
3068         cfs_percpt_for_each(sched, i, kiblnd_data.kib_scheds) {
3069                 int     nthrs;
3070
3071                 spin_lock_init(&sched->ibs_lock);
3072                 INIT_LIST_HEAD(&sched->ibs_conns);
3073                 init_waitqueue_head(&sched->ibs_waitq);
3074
3075                 nthrs = cfs_cpt_weight(lnet_cpt_table(), i);
3076                 if (*kiblnd_tunables.kib_nscheds > 0) {
3077                         nthrs = min(nthrs, *kiblnd_tunables.kib_nscheds);
3078                 } else {
3079                         /* max to half of CPUs, another half is reserved for
3080                          * upper layer modules */
3081                         nthrs = min(max(IBLND_N_SCHED, nthrs >> 1), nthrs);
3082                 }
3083
3084                 sched->ibs_nthreads_max = nthrs;
3085                 sched->ibs_cpt = i;
3086         }
3087
3088         kiblnd_data.kib_error_qpa.qp_state = IB_QPS_ERR;
3089
3090         /* lists/ptrs/locks initialised */
3091         kiblnd_data.kib_init = IBLND_INIT_DATA;
3092         /*****************************************************/
3093
3094         rc = kiblnd_thread_start(kiblnd_connd, NULL, "kiblnd_connd");
3095         if (rc != 0) {
3096                 CERROR("Can't spawn o2iblnd connd: %d\n", rc);
3097                 goto failed;
3098         }
3099
3100         if (*kiblnd_tunables.kib_dev_failover != 0)
3101                 rc = kiblnd_thread_start(kiblnd_failover_thread, ns,
3102                                          "kiblnd_failover");
3103
3104         if (rc != 0) {
3105                 CERROR("Can't spawn o2iblnd failover thread: %d\n", rc);
3106                 goto failed;
3107         }
3108
3109         /* flag everything initialised */
3110         kiblnd_data.kib_init = IBLND_INIT_ALL;
3111         /*****************************************************/
3112
3113         return 0;
3114
3115  failed:
3116         kiblnd_base_shutdown();
3117         return -ENETDOWN;
3118 }
3119
3120 static int
3121 kiblnd_start_schedulers(struct kib_sched_info *sched)
3122 {
3123         int     rc = 0;
3124         int     nthrs;
3125         int     i;
3126
3127         if (sched->ibs_nthreads == 0) {
3128                 if (*kiblnd_tunables.kib_nscheds > 0) {
3129                         nthrs = sched->ibs_nthreads_max;
3130                 } else {
3131                         nthrs = cfs_cpt_weight(lnet_cpt_table(),
3132                                                sched->ibs_cpt);
3133                         nthrs = min(max(IBLND_N_SCHED, nthrs >> 1), nthrs);
3134                         nthrs = min(IBLND_N_SCHED_HIGH, nthrs);
3135                 }
3136         } else {
3137                 LASSERT(sched->ibs_nthreads <= sched->ibs_nthreads_max);
3138                 /* increase one thread if there is new interface */
3139                 nthrs = (sched->ibs_nthreads < sched->ibs_nthreads_max);
3140         }
3141
3142         for (i = 0; i < nthrs; i++) {
3143                 long    id;
3144                 char    name[20];
3145                 id = KIB_THREAD_ID(sched->ibs_cpt, sched->ibs_nthreads + i);
3146                 snprintf(name, sizeof(name), "kiblnd_sd_%02ld_%02ld",
3147                          KIB_THREAD_CPT(id), KIB_THREAD_TID(id));
3148                 rc = kiblnd_thread_start(kiblnd_scheduler, (void *)id, name);
3149                 if (rc == 0)
3150                         continue;
3151
3152                 CERROR("Can't spawn thread %d for scheduler[%d]: %d\n",
3153                        sched->ibs_cpt, sched->ibs_nthreads + i, rc);
3154                 break;
3155         }
3156
3157         sched->ibs_nthreads += i;
3158         return rc;
3159 }
3160
3161 static int kiblnd_dev_start_threads(struct kib_dev *dev, bool newdev, u32 *cpts,
3162                                     int ncpts)
3163 {
3164         int     cpt;
3165         int     rc;
3166         int     i;
3167
3168         for (i = 0; i < ncpts; i++) {
3169                 struct kib_sched_info *sched;
3170
3171                 cpt = (cpts == NULL) ? i : cpts[i];
3172                 sched = kiblnd_data.kib_scheds[cpt];
3173
3174                 if (!newdev && sched->ibs_nthreads > 0)
3175                         continue;
3176
3177                 rc = kiblnd_start_schedulers(kiblnd_data.kib_scheds[cpt]);
3178                 if (rc != 0) {
3179                         CERROR("Failed to start scheduler threads for %s\n",
3180                                dev->ibd_ifname);
3181                         return rc;
3182                 }
3183         }
3184         return 0;
3185 }
3186
3187 static struct kib_dev *
3188 kiblnd_dev_search(char *ifname)
3189 {
3190         struct kib_dev *alias = NULL;
3191         struct kib_dev *dev;
3192         char            *colon;
3193         char            *colon2;
3194
3195         colon = strchr(ifname, ':');
3196         list_for_each_entry(dev, &kiblnd_data.kib_devs, ibd_list) {
3197                 if (strcmp(&dev->ibd_ifname[0], ifname) == 0)
3198                         return dev;
3199
3200                 if (alias != NULL)
3201                         continue;
3202
3203                 colon2 = strchr(dev->ibd_ifname, ':');
3204                 if (colon != NULL)
3205                         *colon = 0;
3206                 if (colon2 != NULL)
3207                         *colon2 = 0;
3208
3209                 if (strcmp(&dev->ibd_ifname[0], ifname) == 0)
3210                         alias = dev;
3211
3212                 if (colon != NULL)
3213                         *colon = ':';
3214                 if (colon2 != NULL)
3215                         *colon2 = ':';
3216         }
3217         return alias;
3218 }
3219
3220 static int
3221 kiblnd_startup(struct lnet_ni *ni)
3222 {
3223         char *ifname = NULL;
3224         struct lnet_inetdev *ifaces = NULL;
3225         struct kib_dev *ibdev = NULL;
3226         struct kib_net *net = NULL;
3227         unsigned long flags;
3228         int rc;
3229         int i;
3230         bool newdev;
3231
3232         LASSERT(ni->ni_net->net_lnd == &the_o2iblnd);
3233
3234         if (kiblnd_data.kib_init == IBLND_INIT_NOTHING) {
3235                 rc = kiblnd_base_startup(ni->ni_net_ns);
3236                 if (rc != 0)
3237                         return rc;
3238         }
3239
3240         LIBCFS_ALLOC(net, sizeof(*net));
3241         ni->ni_data = net;
3242         if (net == NULL) {
3243                 rc = -ENOMEM;
3244                 goto failed;
3245         }
3246
3247         net->ibn_incarnation = ktime_get_real_ns() / NSEC_PER_USEC;
3248
3249         kiblnd_tunables_setup(ni);
3250
3251         /*
3252          * ni_interfaces is only to support legacy pre Multi-Rail
3253          * tcp bonding for ksocklnd. Multi-Rail wants each secondary
3254          * IP to be treated as an unique 'struct ni' interfaces instead.
3255          */
3256         if (ni->ni_interfaces[0] != NULL) {
3257                 /* Use the IPoIB interface specified in 'networks=' */
3258                 if (ni->ni_interfaces[1] != NULL) {
3259                         CERROR("ko2iblnd: Multiple interfaces not supported\n");
3260                         rc = -EINVAL;
3261                         goto failed;
3262                 }
3263
3264                 ifname = ni->ni_interfaces[0];
3265         } else {
3266                 ifname = *kiblnd_tunables.kib_default_ipif;
3267         }
3268
3269         if (strlen(ifname) >= sizeof(ibdev->ibd_ifname)) {
3270                 CERROR("IPoIB interface name too long: %s\n", ifname);
3271                 rc = -E2BIG;
3272                 goto failed;
3273         }
3274
3275         rc = lnet_inet_enumerate(&ifaces, ni->ni_net_ns);
3276         if (rc < 0)
3277                 goto failed;
3278
3279         for (i = 0; i < rc; i++) {
3280                 if (strcmp(ifname, ifaces[i].li_name) == 0)
3281                         break;
3282         }
3283
3284         if (i == rc) {
3285                 CERROR("ko2iblnd: No matching interfaces\n");
3286                 rc = -ENOENT;
3287                 goto failed;
3288         }
3289
3290         ibdev = kiblnd_dev_search(ifname);
3291         newdev = ibdev == NULL;
3292         /* hmm...create kib_dev even for alias */
3293         if (ibdev == NULL || strcmp(&ibdev->ibd_ifname[0], ifname) != 0) {
3294                 LIBCFS_ALLOC(ibdev, sizeof(*ibdev));
3295                 if (!ibdev) {
3296                         rc = -ENOMEM;
3297                         goto failed;
3298                 }
3299
3300                 ibdev->ibd_ifip = ifaces[i].li_ipaddr;
3301                 strlcpy(ibdev->ibd_ifname, ifaces[i].li_name,
3302                         sizeof(ibdev->ibd_ifname));
3303                 ibdev->ibd_can_failover = !!(ifaces[i].li_flags & IFF_MASTER);
3304
3305                 INIT_LIST_HEAD(&ibdev->ibd_nets);
3306                 INIT_LIST_HEAD(&ibdev->ibd_list); /* not yet in kib_devs */
3307                 INIT_LIST_HEAD(&ibdev->ibd_fail_list);
3308
3309                 /* initialize the device */
3310                 rc = kiblnd_dev_failover(ibdev, ni->ni_net_ns);
3311                 if (rc) {
3312                         CERROR("ko2iblnd: Can't initialize device: rc = %d\n",
3313                                rc);
3314                         goto failed;
3315                 }
3316
3317                 list_add_tail(&ibdev->ibd_list, &kiblnd_data.kib_devs);
3318         }
3319
3320         net->ibn_dev = ibdev;
3321         ni->ni_nid = LNET_MKNID(LNET_NIDNET(ni->ni_nid), ibdev->ibd_ifip);
3322
3323         ni->ni_dev_cpt = ifaces[i].li_cpt;
3324
3325         rc = kiblnd_dev_start_threads(ibdev, newdev, ni->ni_cpts, ni->ni_ncpts);
3326         if (rc != 0)
3327                 goto failed;
3328
3329         rc = kiblnd_net_init_pools(net, ni, ni->ni_cpts, ni->ni_ncpts);
3330         if (rc != 0) {
3331                 CERROR("Failed to initialize NI pools: %d\n", rc);
3332                 goto failed;
3333         }
3334
3335         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3336         ibdev->ibd_nnets++;
3337         list_add_tail(&net->ibn_list, &ibdev->ibd_nets);
3338         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3339
3340         net->ibn_init = IBLND_INIT_ALL;
3341
3342         return 0;
3343
3344 failed:
3345         if (net != NULL && net->ibn_dev == NULL && ibdev != NULL)
3346                 kiblnd_destroy_dev(ibdev);
3347
3348         kfree(ifaces);
3349         kiblnd_shutdown(ni);
3350
3351         CDEBUG(D_NET, "Configuration of device %s failed: rc = %d\n",
3352                ifname ? ifname : "", rc);
3353
3354         return -ENETDOWN;
3355 }
3356
3357 static struct lnet_lnd the_o2iblnd = {
3358         .lnd_type       = O2IBLND,
3359         .lnd_startup    = kiblnd_startup,
3360         .lnd_shutdown   = kiblnd_shutdown,
3361         .lnd_ctl        = kiblnd_ctl,
3362         .lnd_query      = kiblnd_query,
3363         .lnd_send       = kiblnd_send,
3364         .lnd_recv       = kiblnd_recv,
3365 };
3366
3367 static void __exit ko2iblnd_exit(void)
3368 {
3369         lnet_unregister_lnd(&the_o2iblnd);
3370 }
3371
3372 static int __init ko2iblnd_init(void)
3373 {
3374         int rc;
3375
3376         BUILD_BUG_ON(sizeof(struct kib_msg) > IBLND_MSG_SIZE);
3377         BUILD_BUG_ON(offsetof(struct kib_msg,
3378                      ibm_u.get.ibgm_rd.rd_frags[IBLND_MAX_RDMA_FRAGS]) >
3379                      IBLND_MSG_SIZE);
3380         BUILD_BUG_ON(offsetof(struct kib_msg,
3381                      ibm_u.putack.ibpam_rd.rd_frags[IBLND_MAX_RDMA_FRAGS]) >
3382                      IBLND_MSG_SIZE);
3383
3384         rc = kiblnd_tunables_init();
3385         if (rc != 0)
3386                 return rc;
3387
3388         lnet_register_lnd(&the_o2iblnd);
3389
3390         return 0;
3391 }
3392
3393 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
3394 MODULE_DESCRIPTION("OpenIB gen2 LNet Network Driver");
3395 MODULE_VERSION("2.8.0");
3396 MODULE_LICENSE("GPL");
3397
3398 module_init(ko2iblnd_init);
3399 module_exit(ko2iblnd_exit);