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