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