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