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