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