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