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