Whamcloud - gitweb
fb60c56d0fb40f56caff1bbda4effc5d8e288dd1
[fs/lustre-release.git] / lnet / lnet / router.c
1 /*
2  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
3  *
4  * Copyright (c) 2011, 2017, Intel Corporation.
5  *
6  *   This file is part of Lustre, https://wiki.whamcloud.com/
7  *
8  *   Portals is free software; you can redistribute it and/or
9  *   modify it under the terms of version 2 of the GNU General Public
10  *   License as published by the Free Software Foundation.
11  *
12  *   Portals is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with Portals; if not, write to the Free Software
19  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  */
22
23 #define DEBUG_SUBSYSTEM S_LNET
24
25 #include <linux/random.h>
26 #include <lnet/lib-lnet.h>
27
28 #define LNET_NRB_TINY_MIN       512     /* min value for each CPT */
29 #define LNET_NRB_TINY           (LNET_NRB_TINY_MIN * 4)
30 #define LNET_NRB_SMALL_MIN      4096    /* min value for each CPT */
31 #define LNET_NRB_SMALL          (LNET_NRB_SMALL_MIN * 4)
32 #define LNET_NRB_SMALL_PAGES    1
33 #define LNET_NRB_LARGE_MIN      256     /* min value for each CPT */
34 #define LNET_NRB_LARGE          (LNET_NRB_LARGE_MIN * 4)
35 #define LNET_NRB_LARGE_PAGES    ((LNET_MTU + PAGE_SIZE - 1) >> \
36                                   PAGE_SHIFT)
37
38 static char *forwarding = "";
39 module_param(forwarding, charp, 0444);
40 MODULE_PARM_DESC(forwarding, "Explicitly enable/disable forwarding between networks");
41
42 static int tiny_router_buffers;
43 module_param(tiny_router_buffers, int, 0444);
44 MODULE_PARM_DESC(tiny_router_buffers, "# of 0 payload messages to buffer in the router");
45 static int small_router_buffers;
46 module_param(small_router_buffers, int, 0444);
47 MODULE_PARM_DESC(small_router_buffers, "# of small (1 page) messages to buffer in the router");
48 static int large_router_buffers;
49 module_param(large_router_buffers, int, 0444);
50 MODULE_PARM_DESC(large_router_buffers, "# of large messages to buffer in the router");
51 static int peer_buffer_credits;
52 module_param(peer_buffer_credits, int, 0444);
53 MODULE_PARM_DESC(peer_buffer_credits, "# router buffer credits per peer");
54
55 static int auto_down = 1;
56 module_param(auto_down, int, 0444);
57 MODULE_PARM_DESC(auto_down, "Automatically mark peers down on comms error");
58
59 int
60 lnet_peer_buffer_credits(struct lnet_net *net)
61 {
62         /* NI option overrides LNet default */
63         if (net->net_tunables.lct_peer_rtr_credits > 0)
64                 return net->net_tunables.lct_peer_rtr_credits;
65         if (peer_buffer_credits > 0)
66                 return peer_buffer_credits;
67
68         /* As an approximation, allow this peer the same number of router
69          * buffers as it is allowed outstanding sends */
70         return net->net_tunables.lct_peer_tx_credits;
71 }
72
73 static int check_routers_before_use;
74 module_param(check_routers_before_use, int, 0444);
75 MODULE_PARM_DESC(check_routers_before_use, "Assume routers are down and ping them before use");
76
77 int avoid_asym_router_failure = 1;
78 module_param(avoid_asym_router_failure, int, 0644);
79 MODULE_PARM_DESC(avoid_asym_router_failure, "Avoid asymmetrical router failures (0 to disable)");
80
81 int dead_router_check_interval = INT_MIN;
82 module_param(dead_router_check_interval, int, 0444);
83 MODULE_PARM_DESC(dead_router_check_interval, "(DEPRECATED - Use alive_router_check_interval)");
84
85 int live_router_check_interval = INT_MIN;
86 module_param(live_router_check_interval, int, 0444);
87 MODULE_PARM_DESC(live_router_check_interval, "(DEPRECATED - Use alive_router_check_interval)");
88
89 int alive_router_check_interval = 60;
90 module_param(alive_router_check_interval, int, 0644);
91 MODULE_PARM_DESC(alive_router_check_interval, "Seconds between live router health checks (<= 0 to disable)");
92
93 static int router_ping_timeout = 50;
94 module_param(router_ping_timeout, int, 0644);
95 MODULE_PARM_DESC(router_ping_timeout, "Seconds to wait for the reply to a router health query");
96
97 /*
98  * A value between 0 and 100. 0 meaning that even if router's interfaces
99  * have the worse health still consider the gateway usable.
100  * 100 means that at least one interface on the route's remote net is 100%
101  * healthy to consider the route alive.
102  * The default is set to 100 to ensure we maintain the original behavior.
103  */
104 unsigned int router_sensitivity_percentage = 100;
105 static int rtr_sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp);
106 static struct kernel_param_ops param_ops_rtr_sensitivity = {
107         .set = rtr_sensitivity_set,
108         .get = param_get_int,
109 };
110 #define param_check_rtr_sensitivity(name, p) \
111                 __param_check(name, p, int)
112 #ifdef HAVE_KERNEL_PARAM_OPS
113 module_param(router_sensitivity_percentage, rtr_sensitivity, S_IRUGO|S_IWUSR);
114 #else
115 module_param_call(router_sensitivity_percentage, rtr_sensitivity_set, param_get_int,
116                   &router_sensitivity_percentage, S_IRUGO|S_IWUSR);
117 #endif
118 MODULE_PARM_DESC(router_sensitivity_percentage,
119                 "How healthy a gateway should be to be used in percent");
120
121 static void lnet_add_route_to_rnet(struct lnet_remotenet *rnet,
122                                    struct lnet_route *route);
123 static void lnet_del_route_from_rnet(lnet_nid_t gw_nid, struct list_head *route_list,
124                                      struct list_head *zombies);
125
126 static int
127 rtr_sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp)
128 {
129         int rc;
130         unsigned *sen = (unsigned *)kp->arg;
131         unsigned long value;
132
133         rc = kstrtoul(val, 0, &value);
134         if (rc) {
135                 CERROR("Invalid module parameter value for 'router_sensitivity_percentage'\n");
136                 return rc;
137         }
138
139         if (value < 0 || value > 100) {
140                 CERROR("Invalid value: %lu for 'router_sensitivity_percentage'\n", value);
141                 return -EINVAL;
142         }
143
144         /*
145          * The purpose of locking the api_mutex here is to ensure that
146          * the correct value ends up stored properly.
147          */
148         mutex_lock(&the_lnet.ln_api_mutex);
149
150         *sen = value;
151
152         mutex_unlock(&the_lnet.ln_api_mutex);
153
154         return 0;
155 }
156
157 void
158 lnet_move_route(struct lnet_route *route, struct lnet_peer *lp,
159                 struct list_head *rt_list)
160 {
161         struct lnet_remotenet *rnet;
162         struct list_head zombies;
163         struct list_head *l;
164
165         INIT_LIST_HEAD(&zombies);
166
167         if (rt_list)
168                 l = rt_list;
169         else
170                 l = &zombies;
171
172         rnet = lnet_find_rnet_locked(route->lr_net);
173         LASSERT(rnet);
174
175         CDEBUG(D_NET, "deleting route %s->%s\n",
176                libcfs_net2str(route->lr_net),
177                libcfs_nid2str(route->lr_nid));
178
179         /*
180          * use the gateway's lp_primary_nid to delete the route as the
181          * lr_nid can be a constituent NID of the peer
182          */
183         lnet_del_route_from_rnet(route->lr_gateway->lp_primary_nid,
184                                  &rnet->lrn_routes, l);
185
186         if (lp) {
187                 route = list_first_entry(l, struct lnet_route,
188                                         lr_list);
189                 route->lr_gateway = lp;
190                 lnet_add_route_to_rnet(rnet, route);
191         } else {
192                 while (!list_empty(l) && !rt_list) {
193                         route = list_first_entry(l, struct lnet_route,
194                                  lr_list);
195                         list_del(&route->lr_list);
196                         LIBCFS_FREE(route, sizeof(*route));
197                 }
198         }
199 }
200
201 void
202 lnet_rtr_transfer_to_peer(struct lnet_peer *src, struct lnet_peer *target)
203 {
204         struct lnet_route *route;
205         struct lnet_route *tmp, *tmp2;
206
207         lnet_net_lock(LNET_LOCK_EX);
208         CDEBUG(D_NET, "transfering routes from %s -> %s\n",
209                libcfs_nid2str(src->lp_primary_nid),
210                libcfs_nid2str(target->lp_primary_nid));
211         list_for_each_entry(route, &src->lp_routes, lr_gwlist) {
212                 CDEBUG(D_NET, "%s: %s->%s\n", libcfs_nid2str(src->lp_primary_nid),
213                        libcfs_net2str(route->lr_net),
214                        libcfs_nid2str(route->lr_nid));
215         }
216         list_splice_init(&src->lp_rtrq, &target->lp_rtrq);
217         list_for_each_entry_safe(route, tmp, &src->lp_routes, lr_gwlist) {
218                 struct lnet_route *r2;
219                 bool present = false;
220                 list_for_each_entry_safe(r2, tmp2, &target->lp_routes, lr_gwlist) {
221                         if (route->lr_net == r2->lr_net) {
222                                 if (route->lr_priority >= r2->lr_priority)
223                                         present = true;
224                                 else if (route->lr_hops >= r2->lr_hops)
225                                         present = true;
226                                 else
227                                         lnet_move_route(r2, NULL, NULL);
228                         }
229                 }
230                 if (present)
231                         lnet_move_route(route, NULL, NULL);
232                 else
233                         lnet_move_route(route, target, NULL);
234         }
235
236         if (list_empty(&target->lp_rtr_list)) {
237                 lnet_peer_addref_locked(target);
238                 list_add_tail(&target->lp_rtr_list, &the_lnet.ln_routers);
239         }
240
241         the_lnet.ln_routers_version++;
242         lnet_net_unlock(LNET_LOCK_EX);
243 }
244
245 int
246 lnet_peers_start_down(void)
247 {
248         return check_routers_before_use;
249 }
250
251 /*
252  * The peer_net of a gateway is alive if at least one of the peer_ni's on
253  * that peer_net is alive.
254  */
255 static bool
256 lnet_is_gateway_net_alive(struct lnet_peer_net *lpn)
257 {
258         struct lnet_peer_ni *lpni;
259
260         list_for_each_entry(lpni, &lpn->lpn_peer_nis, lpni_peer_nis) {
261                 if (lnet_is_peer_ni_alive(lpni))
262                         return true;
263         }
264
265         return false;
266 }
267
268 /*
269  * a gateway is alive only if all its nets are alive
270  * called with cpt lock held
271  */
272 bool lnet_is_gateway_alive(struct lnet_peer *gw)
273 {
274         struct lnet_peer_net *lpn;
275
276         if (!gw->lp_alive)
277                 return false;
278
279         list_for_each_entry(lpn, &gw->lp_peer_nets, lpn_peer_nets) {
280                 if (!lnet_is_gateway_net_alive(lpn))
281                         return false;
282         }
283
284         return true;
285 }
286
287 /*
288  * lnet_is_route_alive() needs to be called with cpt lock held
289  * A route is alive if the gateway can route between the local network and
290  * the remote network of the route.
291  * This means at least one NI is alive on each of the local and remote
292  * networks of the gateway.
293  */
294 bool lnet_is_route_alive(struct lnet_route *route)
295 {
296         struct lnet_peer *gw = route->lr_gateway;
297         struct lnet_peer_net *llpn;
298         struct lnet_peer_net *rlpn;
299
300         /* If the gateway is down then all routes are considered down */
301         if (!gw->lp_alive)
302                 return false;
303
304         /*
305          * if discovery is disabled then rely on the cached aliveness
306          * information. This is handicapped information which we log when
307          * we receive the discovery ping response. The most uptodate
308          * aliveness information can only be obtained when discovery is
309          * enabled.
310          */
311         if (lnet_is_discovery_disabled(gw))
312                 return route->lr_alive;
313
314         /*
315          * check the gateway's interfaces on the local network
316          */
317         llpn = lnet_peer_get_net_locked(gw, route->lr_lnet);
318         if (!llpn)
319                 return false;
320
321         if (!lnet_is_gateway_net_alive(llpn))
322                 return false;
323
324         /*
325          * For single hop routes avoid_asym_router_failure dictates
326          * that the remote net must exist on the gateway. For multi-hop
327          * routes the next-hop will not have the remote net.
328          */
329         if (avoid_asym_router_failure &&
330             (route->lr_hops == 1 || route->lr_hops == LNET_UNDEFINED_HOPS)) {
331                 rlpn = lnet_peer_get_net_locked(gw, route->lr_net);
332                 if (!rlpn)
333                         return false;
334                 if (!lnet_is_gateway_net_alive(rlpn))
335                         return false;
336         }
337
338         spin_lock(&gw->lp_lock);
339         if (!(gw->lp_state & LNET_PEER_ROUTER_ENABLED)) {
340                 spin_unlock(&gw->lp_lock);
341                 if (gw->lp_rtr_refcount > 0)
342                         CERROR("peer %s is being used as a gateway but routing feature is not turned on\n",
343                                libcfs_nid2str(gw->lp_primary_nid));
344                 return false;
345         }
346         spin_unlock(&gw->lp_lock);
347
348         return true;
349 }
350
351 void
352 lnet_consolidate_routes_locked(struct lnet_peer *orig_lp,
353                                struct lnet_peer *new_lp)
354 {
355         struct lnet_peer_ni *lpni;
356         struct lnet_route *route;
357
358         /*
359          * Although a route is correlated with a peer, but when it's added
360          * a specific NID is used. That NID refers to a peer_ni within
361          * a peer. There could be other peer_nis on the same net, which
362          * can be used to send to that gateway. However when we are
363          * consolidating gateways because of discovery, the nid used to
364          * add the route might've moved between gateway peers. In this
365          * case we want to move the route to the new gateway as well. The
366          * intent here is not to confuse the user who added the route.
367          */
368         list_for_each_entry(route, &orig_lp->lp_routes, lr_gwlist) {
369                 lpni = lnet_peer_get_ni_locked(orig_lp, route->lr_nid);
370                 if (!lpni) {
371                         lnet_net_lock(LNET_LOCK_EX);
372                         list_move(&route->lr_gwlist, &new_lp->lp_routes);
373                         lnet_net_unlock(LNET_LOCK_EX);
374                 }
375         }
376 }
377
378 static inline void
379 lnet_check_route_inconsistency(struct lnet_route *route)
380 {
381         if (!route->lr_single_hop &&
382             (route->lr_hops == 1 || route->lr_hops == LNET_UNDEFINED_HOPS)) {
383                 CWARN("route %s->%s is detected to be multi-hop but hop count is set to %d\n",
384                         libcfs_net2str(route->lr_net),
385                         libcfs_nid2str(route->lr_gateway->lp_primary_nid),
386                         (int) route->lr_hops);
387         }
388 }
389
390 static void
391 lnet_set_route_hop_type(struct lnet_peer *gw, struct lnet_route *route)
392 {
393         struct lnet_peer_net *lpn;
394         bool single_hop = false;
395
396         list_for_each_entry(lpn, &gw->lp_peer_nets, lpn_peer_nets) {
397                 if (route->lr_net == lpn->lpn_net_id) {
398                         single_hop = true;
399                         break;
400                 }
401         }
402         route->lr_single_hop = single_hop;
403         lnet_check_route_inconsistency(route);
404 }
405
406 /* Must hold net_lock/EX */
407 static inline void
408 lnet_set_route_aliveness(struct lnet_route *route, bool alive)
409 {
410         /* Log when there's a state change */
411         if (route->lr_alive != alive) {
412                 CERROR("route to %s through %s has gone from %s to %s\n",
413                        libcfs_net2str(route->lr_net),
414                        libcfs_nid2str(route->lr_gateway->lp_primary_nid),
415                        (route->lr_alive) ? "up" : "down",
416                        alive ? "up" : "down");
417                 route->lr_alive = alive;
418         }
419 }
420
421 /* Must hold net_lock/EX */
422 void
423 lnet_router_discovery_ping_reply(struct lnet_peer *lp)
424 {
425         struct lnet_ping_buffer *pbuf = lp->lp_data;
426         struct lnet_peer_net *llpn;
427         struct lnet_route *route;
428         bool single_hop = false;
429         bool net_up = false;
430         unsigned lp_state;
431         __u32 net;
432         int i;
433
434
435         spin_lock(&lp->lp_lock);
436         lp_state = lp->lp_state;
437
438         /* only handle replies if discovery is disabled. */
439         if (!lnet_is_discovery_disabled_locked(lp)) {
440                 spin_unlock(&lp->lp_lock);
441                 return;
442         }
443
444         spin_unlock(&lp->lp_lock);
445
446         if (lp_state & LNET_PEER_PING_FAILED ||
447             pbuf->pb_info.pi_features & LNET_PING_FEAT_RTE_DISABLED) {
448                 CDEBUG(D_NET, "Set routes down for gw %s because %s %d\n",
449                        libcfs_nid2str(lp->lp_primary_nid),
450                        lp_state & LNET_PEER_PING_FAILED ? "ping failed" :
451                        "route feature is disabled", lp->lp_ping_error);
452                 /* If the ping failed or the peer has routing disabled then
453                  * mark the routes served by this peer down
454                  */
455                 list_for_each_entry(route, &lp->lp_routes, lr_gwlist)
456                         lnet_set_route_aliveness(route, false);
457                 return;
458         }
459
460         CDEBUG(D_NET, "Discovery is disabled. Processing reply for gw: %s:%d\n",
461                libcfs_nid2str(lp->lp_primary_nid), pbuf->pb_info.pi_nnis);
462
463         /*
464          * examine the ping response to determine if the routes on that
465          * gateway should be declared alive.
466          * The route is alive if:
467          *  1. local network to reach the route is alive and
468          *  2. route is single hop, avoid_async_router_failure is set and
469          *     there exists at least one NI on the route's remote net
470          */
471         list_for_each_entry(route, &lp->lp_routes, lr_gwlist) {
472                 llpn = lnet_peer_get_net_locked(lp, route->lr_lnet);
473                 if (!llpn) {
474                         lnet_set_route_aliveness(route, false);
475                         continue;
476                 }
477
478                 if (!lnet_is_gateway_net_alive(llpn)) {
479                         lnet_set_route_aliveness(route, false);
480                         continue;
481                 }
482
483                 single_hop = net_up = false;
484                 for (i = 1; i < pbuf->pb_info.pi_nnis; i++) {
485                         net = LNET_NIDNET(pbuf->pb_info.pi_ni[i].ns_nid);
486
487                         if (route->lr_net == net) {
488                                 single_hop = true;
489                                 if (pbuf->pb_info.pi_ni[i].ns_status ==
490                                     LNET_NI_STATUS_UP) {
491                                         net_up = true;
492                                         break;
493                                 }
494                         }
495                 }
496
497                 route->lr_single_hop = single_hop;
498                 if (avoid_asym_router_failure &&
499                     (route->lr_hops == 1 ||
500                      route->lr_hops == LNET_UNDEFINED_HOPS))
501                         lnet_set_route_aliveness(route, net_up);
502                 else
503                         lnet_set_route_aliveness(route, true);
504
505                 /*
506                  * warn that the route is configured as single-hop but it
507                  * really is multi-hop as far as we can tell.
508                  */
509                 lnet_check_route_inconsistency(route);
510         }
511 }
512
513 void
514 lnet_router_discovery_complete(struct lnet_peer *lp)
515 {
516         struct lnet_peer_ni *lpni = NULL;
517         struct lnet_route *route;
518
519         spin_lock(&lp->lp_lock);
520         lp->lp_state &= ~LNET_PEER_RTR_DISCOVERY;
521         lp->lp_state |= LNET_PEER_RTR_DISCOVERED;
522         lp->lp_alive = lp->lp_dc_error == 0;
523         spin_unlock(&lp->lp_lock);
524
525         /* ping replies are being handled when discovery is disabled */
526         if (lnet_is_discovery_disabled_locked(lp))
527                 return;
528
529         if (!lp->lp_dc_error) {
530                 /*
531                 * mark single-hop routes.  If the remote net is not configured on
532                 * the gateway we assume this is intentional and we mark the
533                 * gateway as multi-hop
534                 */
535                 list_for_each_entry(route, &lp->lp_routes, lr_gwlist) {
536                         lnet_set_route_aliveness(route, true);
537                         lnet_set_route_hop_type(lp, route);
538                 }
539
540                 return;
541         }
542
543         /*
544          * We do not send messages directly to the remote interfaces
545          * of an LNet router. As such, we rely on the PING response
546          * to determine the up/down status of these interfaces. If
547          * a PING response is not receieved, or some other problem with
548          * discovery occurs that prevents us from getting this status,
549          * we assume all interfaces are down until we're able to
550          * determine otherwise.
551          */
552         CDEBUG(D_NET, "%s: Router discovery failed %d\n",
553                libcfs_nid2str(lp->lp_primary_nid), lp->lp_dc_error);
554         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL)
555                 lpni->lpni_ns_status = LNET_NI_STATUS_DOWN;
556
557         list_for_each_entry(route, &lp->lp_routes, lr_gwlist)
558                 lnet_set_route_aliveness(route, false);
559 }
560
561 static void
562 lnet_rtr_addref_locked(struct lnet_peer *lp)
563 {
564         LASSERT(lp->lp_rtr_refcount >= 0);
565
566         /* lnet_net_lock must be exclusively locked */
567         lp->lp_rtr_refcount++;
568         if (lp->lp_rtr_refcount == 1) {
569                 list_add_tail(&lp->lp_rtr_list, &the_lnet.ln_routers);
570                 /* addref for the_lnet.ln_routers */
571                 lnet_peer_addref_locked(lp);
572                 the_lnet.ln_routers_version++;
573         }
574 }
575
576 static void
577 lnet_rtr_decref_locked(struct lnet_peer *lp)
578 {
579         LASSERT(atomic_read(&lp->lp_refcount) > 0);
580         LASSERT(lp->lp_rtr_refcount > 0);
581
582         /* lnet_net_lock must be exclusively locked */
583         lp->lp_rtr_refcount--;
584         if (lp->lp_rtr_refcount == 0) {
585                 LASSERT(list_empty(&lp->lp_routes));
586
587                 list_del(&lp->lp_rtr_list);
588                 /* decref for the_lnet.ln_routers */
589                 lnet_peer_decref_locked(lp);
590                 the_lnet.ln_routers_version++;
591         }
592 }
593
594 struct lnet_remotenet *
595 lnet_find_rnet_locked(__u32 net)
596 {
597         struct lnet_remotenet *rnet;
598         struct list_head *tmp;
599         struct list_head *rn_list;
600
601         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
602
603         rn_list = lnet_net2rnethash(net);
604         list_for_each(tmp, rn_list) {
605                 rnet = list_entry(tmp, struct lnet_remotenet, lrn_list);
606
607                 if (rnet->lrn_net == net)
608                         return rnet;
609         }
610         return NULL;
611 }
612
613 static void lnet_shuffle_seed(void)
614 {
615         static int seeded;
616         struct lnet_ni *ni = NULL;
617
618         if (seeded)
619                 return;
620
621         /* Nodes with small feet have little entropy
622          * the NID for this node gives the most entropy in the low bits */
623         while ((ni = lnet_get_next_ni_locked(NULL, ni)))
624                 add_device_randomness(&ni->ni_nid, sizeof(ni->ni_nid));
625
626         seeded = 1;
627 }
628
629 /* NB expects LNET_LOCK held */
630 static void
631 lnet_add_route_to_rnet(struct lnet_remotenet *rnet, struct lnet_route *route)
632 {
633         struct lnet_peer_net *lpn;
634         unsigned int offset = 0;
635         unsigned int len = 0;
636         struct list_head *e;
637
638         lnet_shuffle_seed();
639
640         list_for_each(e, &rnet->lrn_routes)
641                 len++;
642
643         /*
644          * Randomly adding routes to the list is done to ensure that when
645          * different nodes are using the same list of routers, they end up
646          * preferring different routers.
647          */
648         offset = prandom_u32_max(len + 1);
649         list_for_each(e, &rnet->lrn_routes) {
650                 if (offset == 0)
651                         break;
652                 offset--;
653         }
654         list_add(&route->lr_list, e);
655         /*
656          * force a router check on the gateway to make sure the route is
657          * alive
658          */
659         list_for_each_entry(lpn, &route->lr_gateway->lp_peer_nets,
660                             lpn_peer_nets) {
661                 lpn->lpn_rtrcheck_timestamp = 0;
662         }
663
664         the_lnet.ln_remote_nets_version++;
665
666         /* add the route on the gateway list */
667         list_add(&route->lr_gwlist, &route->lr_gateway->lp_routes);
668
669         /* take a router reference count on the gateway */
670         lnet_rtr_addref_locked(route->lr_gateway);
671 }
672
673 int
674 lnet_add_route(__u32 net, __u32 hops, lnet_nid_t gateway,
675                __u32 priority, __u32 sensitivity)
676 {
677         struct list_head *route_entry;
678         struct lnet_remotenet *rnet;
679         struct lnet_remotenet *rnet2;
680         struct lnet_route *route;
681         struct lnet_peer_ni *lpni;
682         struct lnet_peer *gw;
683         int add_route;
684         int rc;
685
686         CDEBUG(D_NET, "Add route: remote net %s hops %d priority %u gw %s\n",
687                libcfs_net2str(net), hops, priority, libcfs_nid2str(gateway));
688
689         if (gateway == LNET_NID_ANY ||
690             gateway == LNET_NID_LO_0 ||
691             net == LNET_NET_ANY ||
692             LNET_NETTYP(net) == LOLND ||
693             LNET_NIDNET(gateway) == net ||
694             (hops != LNET_UNDEFINED_HOPS && (hops < 1 || hops > 255)))
695                 return -EINVAL;
696
697         /* it's a local network */
698         if (lnet_islocalnet(net))
699                 return -EEXIST;
700
701         if (!lnet_islocalnet(LNET_NIDNET(gateway))) {
702                 CERROR("Cannot add route with gateway %s. There is no local interface configured on LNet %s\n",
703                        libcfs_nid2str(gateway),
704                        libcfs_net2str(LNET_NIDNET(gateway)));
705                 return -EHOSTUNREACH;
706         }
707
708         /* Assume net, route, all new */
709         LIBCFS_ALLOC(route, sizeof(*route));
710         LIBCFS_ALLOC(rnet, sizeof(*rnet));
711         if (route == NULL || rnet == NULL) {
712                 CERROR("Out of memory creating route %s %d %s\n",
713                        libcfs_net2str(net), hops, libcfs_nid2str(gateway));
714                 if (route != NULL)
715                         LIBCFS_FREE(route, sizeof(*route));
716                 if (rnet != NULL)
717                         LIBCFS_FREE(rnet, sizeof(*rnet));
718                 return -ENOMEM;
719         }
720
721         INIT_LIST_HEAD(&rnet->lrn_routes);
722         rnet->lrn_net = net;
723         /* store the local and remote net that the route represents */
724         route->lr_lnet = LNET_NIDNET(gateway);
725         route->lr_net = net;
726         route->lr_nid = gateway;
727         route->lr_priority = priority;
728         route->lr_hops = hops;
729
730         lnet_net_lock(LNET_LOCK_EX);
731
732         /*
733          * lnet_nid2peerni_ex() grabs a ref on the lpni. We will need to
734          * lose that once we're done
735          */
736         lpni = lnet_nid2peerni_ex(gateway, LNET_LOCK_EX);
737         if (IS_ERR(lpni)) {
738                 lnet_net_unlock(LNET_LOCK_EX);
739
740                 LIBCFS_FREE(route, sizeof(*route));
741                 LIBCFS_FREE(rnet, sizeof(*rnet));
742
743                 rc = PTR_ERR(lpni);
744                 CERROR("Error %d creating route %s %d %s\n", rc,
745                         libcfs_net2str(net), hops,
746                         libcfs_nid2str(gateway));
747                 return rc;
748         }
749
750         LASSERT(lpni->lpni_peer_net && lpni->lpni_peer_net->lpn_peer);
751         gw = lpni->lpni_peer_net->lpn_peer;
752
753         route->lr_gateway = gw;
754
755         rnet2 = lnet_find_rnet_locked(net);
756         if (rnet2 == NULL) {
757                 /* new network */
758                 list_add_tail(&rnet->lrn_list, lnet_net2rnethash(net));
759                 rnet2 = rnet;
760         }
761
762         /* Search for a duplicate route (it's a NOOP if it is) */
763         add_route = 1;
764         list_for_each(route_entry, &rnet2->lrn_routes) {
765                 struct lnet_route *route2;
766
767                 route2 = list_entry(route_entry, struct lnet_route, lr_list);
768                 if (route2->lr_gateway == route->lr_gateway) {
769                         add_route = 0;
770                         break;
771                 }
772
773                 /* our lookups must be true */
774                 LASSERT(route2->lr_gateway->lp_primary_nid != gateway);
775         }
776
777         /*
778          * It is possible to add multiple routes through the same peer,
779          * but it'll be using a different NID of that peer. When the
780          * gateway is discovered, discovery will consolidate the different
781          * peers into one peer. In this case the discovery code will have
782          * to move the routes from the peer that's being deleted to the
783          * consolidated peer lp_routes list
784          */
785         if (add_route) {
786                 gw->lp_health_sensitivity = sensitivity;
787                 lnet_add_route_to_rnet(rnet2, route);
788                 if (lnet_peer_discovery_disabled)
789                         CWARN("Consider turning discovery on to enable full "
790                               "Multi-Rail routing functionality\n");
791         }
792
793         /*
794          * get rid of the reference on the lpni.
795          */
796         lnet_peer_ni_decref_locked(lpni);
797         lnet_net_unlock(LNET_LOCK_EX);
798
799         rc = 0;
800
801         if (!add_route) {
802                 rc = -EEXIST;
803                 LIBCFS_FREE(route, sizeof(*route));
804         }
805
806         if (rnet != rnet2)
807                 LIBCFS_FREE(rnet, sizeof(*rnet));
808
809         /* kick start the monitor thread to handle the added route */
810         complete(&the_lnet.ln_mt_wait_complete);
811
812         return rc;
813 }
814
815 void
816 lnet_del_route_from_rnet(lnet_nid_t gw_nid, struct list_head *route_list,
817                          struct list_head *zombies)
818 {
819         struct lnet_peer *gateway;
820         struct lnet_route *route;
821         struct lnet_route *tmp;
822
823         list_for_each_entry_safe(route, tmp, route_list, lr_list) {
824                 gateway = route->lr_gateway;
825                 if (gw_nid != LNET_NID_ANY &&
826                     gw_nid != gateway->lp_primary_nid)
827                         continue;
828
829                 /*
830                  * move to zombie to delete outside the lock
831                  * Note that this function is called with the
832                  * ln_api_mutex held as well as the exclusive net
833                  * lock. Adding to the remote net list happens
834                  * under the same conditions. Same goes for the
835                  * gateway router list
836                  */
837                 list_move(&route->lr_list, zombies);
838                 the_lnet.ln_remote_nets_version++;
839
840                 list_del(&route->lr_gwlist);
841                 lnet_rtr_decref_locked(gateway);
842         }
843 }
844
845 int
846 lnet_del_route(__u32 net, lnet_nid_t gw_nid)
847 {
848         LIST_HEAD(rnet_zombies);
849         struct lnet_remotenet *rnet;
850         struct lnet_remotenet *tmp;
851         struct list_head *rn_list;
852         struct lnet_peer_ni *lpni;
853         struct lnet_route *route;
854         LIST_HEAD(zombies);
855         struct lnet_peer *lp = NULL;
856         int i = 0;
857
858         CDEBUG(D_NET, "Del route: net %s : gw %s\n",
859                libcfs_net2str(net), libcfs_nid2str(gw_nid));
860
861         /* NB Caller may specify either all routes via the given gateway
862          * or a specific route entry actual NIDs) */
863
864         lnet_net_lock(LNET_LOCK_EX);
865
866         lpni = lnet_find_peer_ni_locked(gw_nid);
867         if (lpni) {
868                 lp = lpni->lpni_peer_net->lpn_peer;
869                 LASSERT(lp);
870                 gw_nid = lp->lp_primary_nid;
871                 lnet_peer_ni_decref_locked(lpni);
872         }
873
874         if (net != LNET_NET_ANY) {
875                 rnet = lnet_find_rnet_locked(net);
876                 if (!rnet) {
877                         lnet_net_unlock(LNET_LOCK_EX);
878                         return -ENOENT;
879                 }
880                 lnet_del_route_from_rnet(gw_nid, &rnet->lrn_routes,
881                                          &zombies);
882                 if (list_empty(&rnet->lrn_routes))
883                         list_move(&rnet->lrn_list, &rnet_zombies);
884                 goto delete_zombies;
885         }
886
887         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
888                 rn_list = &the_lnet.ln_remote_nets_hash[i];
889
890                 list_for_each_entry_safe(rnet, tmp, rn_list, lrn_list) {
891                         lnet_del_route_from_rnet(gw_nid, &rnet->lrn_routes,
892                                                  &zombies);
893                         if (list_empty(&rnet->lrn_routes))
894                                 list_move(&rnet->lrn_list, &rnet_zombies);
895                 }
896         }
897
898 delete_zombies:
899         /*
900          * check if there are any routes remaining on the gateway
901          * If there are no more routes make sure to set the peer's
902          * lp_disc_net_id to 0 (invalid), in case we add more routes in
903          * the future on that gateway, then we start our discovery process
904          * from scratch
905          */
906         if (lpni) {
907                 if (list_empty(&lp->lp_routes))
908                         lp->lp_disc_net_id = 0;
909         }
910
911         lnet_net_unlock(LNET_LOCK_EX);
912
913         while (!list_empty(&zombies)) {
914                 route = list_first_entry(&zombies, struct lnet_route, lr_list);
915                 list_del(&route->lr_list);
916                 LIBCFS_FREE(route, sizeof(*route));
917         }
918
919         while (!list_empty(&rnet_zombies)) {
920                 rnet = list_first_entry(&rnet_zombies, struct lnet_remotenet,
921                                         lrn_list);
922                 list_del(&rnet->lrn_list);
923                 LIBCFS_FREE(rnet, sizeof(*rnet));
924         }
925
926         return 0;
927 }
928
929 void
930 lnet_destroy_routes (void)
931 {
932         lnet_del_route(LNET_NET_ANY, LNET_NID_ANY);
933 }
934
935 int lnet_get_rtr_pool_cfg(int cpt, struct lnet_ioctl_pool_cfg *pool_cfg)
936 {
937         struct lnet_rtrbufpool *rbp;
938         int i, rc = -ENOENT, j;
939
940         if (the_lnet.ln_rtrpools == NULL)
941                 return rc;
942
943
944         cfs_percpt_for_each(rbp, i, the_lnet.ln_rtrpools) {
945                 if (i != cpt)
946                         continue;
947
948                 lnet_net_lock(i);
949                 for (j = 0; j < LNET_NRBPOOLS; j++) {
950                         pool_cfg->pl_pools[j].pl_npages = rbp[j].rbp_npages;
951                         pool_cfg->pl_pools[j].pl_nbuffers = rbp[j].rbp_nbuffers;
952                         pool_cfg->pl_pools[j].pl_credits = rbp[j].rbp_credits;
953                         pool_cfg->pl_pools[j].pl_mincredits = rbp[j].rbp_mincredits;
954                 }
955                 lnet_net_unlock(i);
956                 rc = 0;
957                 break;
958         }
959
960         lnet_net_lock(LNET_LOCK_EX);
961         pool_cfg->pl_routing = the_lnet.ln_routing;
962         lnet_net_unlock(LNET_LOCK_EX);
963
964         return rc;
965 }
966
967 int
968 lnet_get_route(int idx, __u32 *net, __u32 *hops,
969                lnet_nid_t *gateway, __u32 *flags, __u32 *priority, __u32 *sensitivity)
970 {
971         struct lnet_remotenet *rnet;
972         struct list_head *rn_list;
973         struct lnet_route *route;
974         struct list_head *e1;
975         struct list_head *e2;
976         int cpt;
977         int i;
978
979         cpt = lnet_net_lock_current();
980
981         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
982                 rn_list = &the_lnet.ln_remote_nets_hash[i];
983                 list_for_each(e1, rn_list) {
984                         rnet = list_entry(e1, struct lnet_remotenet, lrn_list);
985
986                         list_for_each(e2, &rnet->lrn_routes) {
987                                 route = list_entry(e2, struct lnet_route,
988                                                    lr_list);
989
990                                 if (idx-- == 0) {
991                                         *net      = rnet->lrn_net;
992                                         *gateway  = route->lr_nid;
993                                         *hops     = route->lr_hops;
994                                         *priority = route->lr_priority;
995                                         *sensitivity = route->lr_gateway->
996                                                 lp_health_sensitivity;
997                                         if (lnet_is_route_alive(route))
998                                                 *flags |= LNET_RT_ALIVE;
999                                         else
1000                                                 *flags &= ~LNET_RT_ALIVE;
1001                                         if (route->lr_single_hop)
1002                                                 *flags &= ~LNET_RT_MULTI_HOP;
1003                                         else
1004                                                 *flags |= LNET_RT_MULTI_HOP;
1005                                         lnet_net_unlock(cpt);
1006                                         return 0;
1007                                 }
1008                         }
1009                 }
1010         }
1011
1012         lnet_net_unlock(cpt);
1013         return -ENOENT;
1014 }
1015
1016 static void
1017 lnet_wait_known_routerstate(void)
1018 {
1019         struct lnet_peer *rtr;
1020         struct list_head *entry;
1021         int all_known;
1022
1023         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING);
1024
1025         for (;;) {
1026                 int cpt = lnet_net_lock_current();
1027
1028                 all_known = 1;
1029                 list_for_each(entry, &the_lnet.ln_routers) {
1030                         rtr = list_entry(entry, struct lnet_peer,
1031                                          lp_rtr_list);
1032
1033                         spin_lock(&rtr->lp_lock);
1034
1035                         if ((rtr->lp_state & LNET_PEER_RTR_DISCOVERED) == 0) {
1036                                 all_known = 0;
1037                                 spin_unlock(&rtr->lp_lock);
1038                                 break;
1039                         }
1040                         spin_unlock(&rtr->lp_lock);
1041                 }
1042
1043                 lnet_net_unlock(cpt);
1044
1045                 if (all_known)
1046                         return;
1047
1048                 schedule_timeout_uninterruptible(cfs_time_seconds(1));
1049         }
1050 }
1051
1052 static inline bool
1053 lnet_net_set_status_locked(struct lnet_net *net, __u32 status)
1054 {
1055         struct lnet_ni *ni;
1056         bool update = false;
1057
1058         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1059                 if (lnet_ni_set_status(ni, status))
1060                         update = true;
1061
1062         return update;
1063 }
1064
1065 static bool
1066 lnet_update_ni_status_locked(void)
1067 {
1068         struct lnet_net *net;
1069         struct lnet_ni *ni;
1070         bool push = false;
1071         time64_t now;
1072         time64_t timeout;
1073
1074         LASSERT(the_lnet.ln_routing);
1075
1076         timeout = router_ping_timeout + alive_router_check_interval;
1077
1078         now = ktime_get_real_seconds();
1079         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1080                 if (net->net_lnd->lnd_type == LOLND)
1081                         continue;
1082
1083                 if (now < net->net_last_alive + timeout)
1084                         goto check_ni_fatal;
1085
1086                 spin_lock(&net->net_lock);
1087                 /* re-check with lock */
1088                 if (now < net->net_last_alive + timeout) {
1089                         spin_unlock(&net->net_lock);
1090                         goto check_ni_fatal;
1091                 }
1092                 spin_unlock(&net->net_lock);
1093
1094                 /*
1095                  * if the net didn't receive any traffic for past the
1096                  * timeout on any of its constituent NIs, then mark all
1097                  * the NIs down.
1098                  */
1099                 if (lnet_net_set_status_locked(net, LNET_NI_STATUS_DOWN)) {
1100                         push = true;
1101                         continue;
1102                 }
1103
1104 check_ni_fatal:
1105                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1106                         /* lnet_ni_set_status() will perform the same check of
1107                          * ni_status while holding the ni lock. We can safely
1108                          * check ni_status without that lock because it is only
1109                          * written to under net_lock/EX and our caller is
1110                          * holding a net lock.
1111                          */
1112                         if (atomic_read(&ni->ni_fatal_error_on) &&
1113                             ni->ni_status &&
1114                             ni->ni_status->ns_status != LNET_NI_STATUS_DOWN &&
1115                             lnet_ni_set_status(ni, LNET_NI_STATUS_DOWN))
1116                                 push = true;
1117                 }
1118         }
1119
1120         return push;
1121 }
1122
1123 void lnet_wait_router_start(void)
1124 {
1125         if (check_routers_before_use) {
1126                 /* Note that a helpful side-effect of pinging all known routers
1127                  * at startup is that it makes them drop stale connections they
1128                  * may have to a previous instance of me. */
1129                 lnet_wait_known_routerstate();
1130         }
1131 }
1132
1133 /*
1134  * This function is called from the monitor thread to check if there are
1135  * any active routers that need to be checked.
1136  */
1137 bool lnet_router_checker_active(void)
1138 {
1139         /* Router Checker thread needs to run when routing is enabled in
1140          * order to call lnet_update_ni_status_locked() */
1141         if (the_lnet.ln_routing)
1142                 return true;
1143
1144         return !list_empty(&the_lnet.ln_routers) &&
1145                 alive_router_check_interval > 0;
1146 }
1147
1148 void
1149 lnet_check_routers(void)
1150 {
1151         struct lnet_peer_net *first_lpn = NULL;
1152         struct lnet_peer_net *lpn;
1153         struct lnet_peer_ni *lpni;
1154         struct list_head *entry;
1155         struct lnet_peer *rtr;
1156         bool push = false;
1157         bool found_lpn;
1158         __u64 version;
1159         __u32 net_id;
1160         time64_t now;
1161         int cpt;
1162         int rc;
1163
1164         cpt = lnet_net_lock_current();
1165 rescan:
1166         version = the_lnet.ln_routers_version;
1167
1168         list_for_each(entry, &the_lnet.ln_routers) {
1169                 rtr = list_entry(entry, struct lnet_peer,
1170                                  lp_rtr_list);
1171
1172                 now = ktime_get_real_seconds();
1173
1174                 /*
1175                  * only discover the router if we've passed
1176                  * alive_router_check_interval seconds. Some of the router
1177                  * interfaces could be down and in that case they would be
1178                  * undergoing recovery separately from this discovery.
1179                  */
1180                 /* find next peer net which is also local */
1181                 net_id = rtr->lp_disc_net_id;
1182                 do {
1183                         lpn = lnet_get_next_peer_net_locked(rtr, net_id);
1184                         if (!lpn) {
1185                                 CERROR("gateway %s has no networks\n",
1186                                 libcfs_nid2str(rtr->lp_primary_nid));
1187                                 break;
1188                         }
1189                         if (first_lpn == lpn)
1190                                 break;
1191                         if (!first_lpn)
1192                                 first_lpn = lpn;
1193                         found_lpn = lnet_islocalnet_locked(lpn->lpn_net_id);
1194                         net_id = lpn->lpn_net_id;
1195                 } while (!found_lpn);
1196
1197                 if (!found_lpn || !lpn) {
1198                         CERROR("no local network found for gateway %s\n",
1199                                libcfs_nid2str(rtr->lp_primary_nid));
1200                         continue;
1201                 }
1202
1203                 if (now - lpn->lpn_rtrcheck_timestamp <
1204                     alive_router_check_interval / lnet_current_net_count)
1205                        continue;
1206
1207                 /*
1208                  * If we're currently discovering the peer then don't
1209                  * issue another discovery
1210                  */
1211                 spin_lock(&rtr->lp_lock);
1212                 if (rtr->lp_state & LNET_PEER_RTR_DISCOVERY) {
1213                         spin_unlock(&rtr->lp_lock);
1214                         continue;
1215                 }
1216                 /* make sure we fully discover the router */
1217                 rtr->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
1218                 rtr->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH |
1219                         LNET_PEER_RTR_DISCOVERY;
1220                 spin_unlock(&rtr->lp_lock);
1221
1222                 /* find the peer_ni associated with the primary NID */
1223                 lpni = lnet_peer_get_ni_locked(rtr, rtr->lp_primary_nid);
1224                 if (!lpni) {
1225                         CDEBUG(D_NET, "Expected to find an lpni for %s, but non found\n",
1226                                libcfs_nid2str(rtr->lp_primary_nid));
1227                         continue;
1228                 }
1229                 lnet_peer_ni_addref_locked(lpni);
1230
1231                 /* specify the net to use */
1232                 rtr->lp_disc_net_id = lpn->lpn_net_id;
1233
1234                 /* discover the router */
1235                 CDEBUG(D_NET, "discover %s, cpt = %d\n",
1236                        libcfs_nid2str(lpni->lpni_nid), cpt);
1237                 rc = lnet_discover_peer_locked(lpni, cpt, false);
1238
1239                 /* decrement ref count acquired by find_peer_ni_locked() */
1240                 lnet_peer_ni_decref_locked(lpni);
1241
1242                 if (!rc)
1243                         lpn->lpn_rtrcheck_timestamp = now;
1244                 else
1245                         CERROR("Failed to discover router %s\n",
1246                                libcfs_nid2str(rtr->lp_primary_nid));
1247
1248                 /* NB dropped lock */
1249                 if (version != the_lnet.ln_routers_version) {
1250                         /* the routers list has changed */
1251                         goto rescan;
1252                 }
1253         }
1254
1255         if (the_lnet.ln_routing)
1256                 push = lnet_update_ni_status_locked();
1257
1258         lnet_net_unlock(cpt);
1259
1260         /* if the status of the ni changed update the peers */
1261         if (push)
1262                 lnet_push_update_to_peers(1);
1263 }
1264
1265 void
1266 lnet_destroy_rtrbuf(struct lnet_rtrbuf *rb, int npages)
1267 {
1268         int sz = offsetof(struct lnet_rtrbuf, rb_kiov[npages]);
1269
1270         while (--npages >= 0)
1271                 __free_page(rb->rb_kiov[npages].bv_page);
1272
1273         LIBCFS_FREE(rb, sz);
1274 }
1275
1276 static struct lnet_rtrbuf *
1277 lnet_new_rtrbuf(struct lnet_rtrbufpool *rbp, int cpt)
1278 {
1279         int            npages = rbp->rbp_npages;
1280         int            sz = offsetof(struct lnet_rtrbuf, rb_kiov[npages]);
1281         struct page   *page;
1282         struct lnet_rtrbuf *rb;
1283         int            i;
1284
1285         LIBCFS_CPT_ALLOC(rb, lnet_cpt_table(), cpt, sz);
1286         if (rb == NULL)
1287                 return NULL;
1288
1289         rb->rb_pool = rbp;
1290
1291         for (i = 0; i < npages; i++) {
1292                 page = cfs_page_cpt_alloc(lnet_cpt_table(), cpt,
1293                                           GFP_KERNEL | __GFP_ZERO);
1294                 if (page == NULL) {
1295                         while (--i >= 0)
1296                                 __free_page(rb->rb_kiov[i].bv_page);
1297
1298                         LIBCFS_FREE(rb, sz);
1299                         return NULL;
1300                 }
1301
1302                 rb->rb_kiov[i].bv_len = PAGE_SIZE;
1303                 rb->rb_kiov[i].bv_offset = 0;
1304                 rb->rb_kiov[i].bv_page = page;
1305         }
1306
1307         return rb;
1308 }
1309
1310 static void
1311 lnet_rtrpool_free_bufs(struct lnet_rtrbufpool *rbp, int cpt)
1312 {
1313         int npages = rbp->rbp_npages;
1314         struct lnet_rtrbuf *rb;
1315         LIST_HEAD(tmp);
1316
1317         if (rbp->rbp_nbuffers == 0) /* not initialized or already freed */
1318                 return;
1319
1320         lnet_net_lock(cpt);
1321         list_splice_init(&rbp->rbp_msgs, &tmp);
1322         lnet_drop_routed_msgs_locked(&tmp, cpt);
1323         list_splice_init(&rbp->rbp_bufs, &tmp);
1324         rbp->rbp_req_nbuffers = 0;
1325         rbp->rbp_nbuffers = rbp->rbp_credits = 0;
1326         rbp->rbp_mincredits = 0;
1327         lnet_net_unlock(cpt);
1328
1329         /* Free buffers on the free list. */
1330         while (!list_empty(&tmp)) {
1331                 rb = list_entry(tmp.next, struct lnet_rtrbuf, rb_list);
1332                 list_del(&rb->rb_list);
1333                 lnet_destroy_rtrbuf(rb, npages);
1334         }
1335 }
1336
1337 static int
1338 lnet_rtrpool_adjust_bufs(struct lnet_rtrbufpool *rbp, int nbufs, int cpt)
1339 {
1340         LIST_HEAD(rb_list);
1341         struct lnet_rtrbuf *rb;
1342         int             num_rb;
1343         int             num_buffers = 0;
1344         int             old_req_nbufs;
1345         int             npages = rbp->rbp_npages;
1346
1347         lnet_net_lock(cpt);
1348         /* If we are called for less buffers than already in the pool, we
1349          * just lower the req_nbuffers number and excess buffers will be
1350          * thrown away as they are returned to the free list.  Credits
1351          * then get adjusted as well.
1352          * If we already have enough buffers allocated to serve the
1353          * increase requested, then we can treat that the same way as we
1354          * do the decrease. */
1355         num_rb = nbufs - rbp->rbp_nbuffers;
1356         if (nbufs <= rbp->rbp_req_nbuffers || num_rb <= 0) {
1357                 rbp->rbp_req_nbuffers = nbufs;
1358                 lnet_net_unlock(cpt);
1359                 return 0;
1360         }
1361         /* store the older value of rbp_req_nbuffers and then set it to
1362          * the new request to prevent lnet_return_rx_credits_locked() from
1363          * freeing buffers that we need to keep around */
1364         old_req_nbufs = rbp->rbp_req_nbuffers;
1365         rbp->rbp_req_nbuffers = nbufs;
1366         lnet_net_unlock(cpt);
1367
1368         /* allocate the buffers on a local list first.  If all buffers are
1369          * allocated successfully then join this list to the rbp buffer
1370          * list.  If not then free all allocated buffers. */
1371         while (num_rb-- > 0) {
1372                 rb = lnet_new_rtrbuf(rbp, cpt);
1373                 if (rb == NULL) {
1374                         CERROR("Failed to allocate %d route bufs of %d pages\n",
1375                                nbufs, npages);
1376
1377                         lnet_net_lock(cpt);
1378                         rbp->rbp_req_nbuffers = old_req_nbufs;
1379                         lnet_net_unlock(cpt);
1380
1381                         goto failed;
1382                 }
1383
1384                 list_add(&rb->rb_list, &rb_list);
1385                 num_buffers++;
1386         }
1387
1388         lnet_net_lock(cpt);
1389
1390         list_splice_tail(&rb_list, &rbp->rbp_bufs);
1391         rbp->rbp_nbuffers += num_buffers;
1392         rbp->rbp_credits += num_buffers;
1393         rbp->rbp_mincredits = rbp->rbp_credits;
1394         /* We need to schedule blocked msg using the newly
1395          * added buffers. */
1396         while (!list_empty(&rbp->rbp_bufs) &&
1397                !list_empty(&rbp->rbp_msgs))
1398                 lnet_schedule_blocked_locked(rbp);
1399
1400         lnet_net_unlock(cpt);
1401
1402         return 0;
1403
1404 failed:
1405         while (!list_empty(&rb_list)) {
1406                 rb = list_entry(rb_list.next, struct lnet_rtrbuf, rb_list);
1407                 list_del(&rb->rb_list);
1408                 lnet_destroy_rtrbuf(rb, npages);
1409         }
1410
1411         return -ENOMEM;
1412 }
1413
1414 static void
1415 lnet_rtrpool_init(struct lnet_rtrbufpool *rbp, int npages)
1416 {
1417         INIT_LIST_HEAD(&rbp->rbp_msgs);
1418         INIT_LIST_HEAD(&rbp->rbp_bufs);
1419
1420         rbp->rbp_npages = npages;
1421         rbp->rbp_credits = 0;
1422         rbp->rbp_mincredits = 0;
1423 }
1424
1425 void
1426 lnet_rtrpools_free(int keep_pools)
1427 {
1428         struct lnet_rtrbufpool *rtrp;
1429         int               i;
1430
1431         if (the_lnet.ln_rtrpools == NULL) /* uninitialized or freed */
1432                 return;
1433
1434         cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1435                 lnet_rtrpool_free_bufs(&rtrp[LNET_TINY_BUF_IDX], i);
1436                 lnet_rtrpool_free_bufs(&rtrp[LNET_SMALL_BUF_IDX], i);
1437                 lnet_rtrpool_free_bufs(&rtrp[LNET_LARGE_BUF_IDX], i);
1438         }
1439
1440         if (!keep_pools) {
1441                 cfs_percpt_free(the_lnet.ln_rtrpools);
1442                 the_lnet.ln_rtrpools = NULL;
1443         }
1444 }
1445
1446 static int
1447 lnet_nrb_tiny_calculate(void)
1448 {
1449         int     nrbs = LNET_NRB_TINY;
1450
1451         if (tiny_router_buffers < 0) {
1452                 LCONSOLE_ERROR_MSG(0x10c,
1453                                    "tiny_router_buffers=%d invalid when "
1454                                    "routing enabled\n", tiny_router_buffers);
1455                 return -EINVAL;
1456         }
1457
1458         if (tiny_router_buffers > 0)
1459                 nrbs = tiny_router_buffers;
1460
1461         nrbs /= LNET_CPT_NUMBER;
1462         return max(nrbs, LNET_NRB_TINY_MIN);
1463 }
1464
1465 static int
1466 lnet_nrb_small_calculate(void)
1467 {
1468         int     nrbs = LNET_NRB_SMALL;
1469
1470         if (small_router_buffers < 0) {
1471                 LCONSOLE_ERROR_MSG(0x10c,
1472                                    "small_router_buffers=%d invalid when "
1473                                    "routing enabled\n", small_router_buffers);
1474                 return -EINVAL;
1475         }
1476
1477         if (small_router_buffers > 0)
1478                 nrbs = small_router_buffers;
1479
1480         nrbs /= LNET_CPT_NUMBER;
1481         return max(nrbs, LNET_NRB_SMALL_MIN);
1482 }
1483
1484 static int
1485 lnet_nrb_large_calculate(void)
1486 {
1487         int     nrbs = LNET_NRB_LARGE;
1488
1489         if (large_router_buffers < 0) {
1490                 LCONSOLE_ERROR_MSG(0x10c,
1491                                    "large_router_buffers=%d invalid when "
1492                                    "routing enabled\n", large_router_buffers);
1493                 return -EINVAL;
1494         }
1495
1496         if (large_router_buffers > 0)
1497                 nrbs = large_router_buffers;
1498
1499         nrbs /= LNET_CPT_NUMBER;
1500         return max(nrbs, LNET_NRB_LARGE_MIN);
1501 }
1502
1503 int
1504 lnet_rtrpools_alloc(int im_a_router)
1505 {
1506         struct lnet_rtrbufpool *rtrp;
1507         int     nrb_tiny;
1508         int     nrb_small;
1509         int     nrb_large;
1510         int     rc;
1511         int     i;
1512
1513         if (!strcmp(forwarding, "")) {
1514                 /* not set either way */
1515                 if (!im_a_router)
1516                         return 0;
1517         } else if (!strcmp(forwarding, "disabled")) {
1518                 /* explicitly disabled */
1519                 return 0;
1520         } else if (!strcmp(forwarding, "enabled")) {
1521                 /* explicitly enabled */
1522         } else {
1523                 LCONSOLE_ERROR_MSG(0x10b, "'forwarding' not set to either "
1524                                    "'enabled' or 'disabled'\n");
1525                 return -EINVAL;
1526         }
1527
1528         nrb_tiny = lnet_nrb_tiny_calculate();
1529         if (nrb_tiny < 0)
1530                 return -EINVAL;
1531
1532         nrb_small = lnet_nrb_small_calculate();
1533         if (nrb_small < 0)
1534                 return -EINVAL;
1535
1536         nrb_large = lnet_nrb_large_calculate();
1537         if (nrb_large < 0)
1538                 return -EINVAL;
1539
1540         the_lnet.ln_rtrpools = cfs_percpt_alloc(lnet_cpt_table(),
1541                                                 LNET_NRBPOOLS *
1542                                                 sizeof(struct lnet_rtrbufpool));
1543         if (the_lnet.ln_rtrpools == NULL) {
1544                 LCONSOLE_ERROR_MSG(0x10c,
1545                                    "Failed to initialize router buffe pool\n");
1546                 return -ENOMEM;
1547         }
1548
1549         cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1550                 lnet_rtrpool_init(&rtrp[LNET_TINY_BUF_IDX], 0);
1551                 rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_TINY_BUF_IDX],
1552                                               nrb_tiny, i);
1553                 if (rc != 0)
1554                         goto failed;
1555
1556                 lnet_rtrpool_init(&rtrp[LNET_SMALL_BUF_IDX],
1557                                   LNET_NRB_SMALL_PAGES);
1558                 rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_SMALL_BUF_IDX],
1559                                               nrb_small, i);
1560                 if (rc != 0)
1561                         goto failed;
1562
1563                 lnet_rtrpool_init(&rtrp[LNET_LARGE_BUF_IDX],
1564                                   LNET_NRB_LARGE_PAGES);
1565                 rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_LARGE_BUF_IDX],
1566                                               nrb_large, i);
1567                 if (rc != 0)
1568                         goto failed;
1569         }
1570
1571         lnet_net_lock(LNET_LOCK_EX);
1572         the_lnet.ln_routing = 1;
1573         lnet_net_unlock(LNET_LOCK_EX);
1574         complete(&the_lnet.ln_mt_wait_complete);
1575         return 0;
1576
1577  failed:
1578         lnet_rtrpools_free(0);
1579         return rc;
1580 }
1581
1582 static int
1583 lnet_rtrpools_adjust_helper(int tiny, int small, int large)
1584 {
1585         int nrb = 0;
1586         int rc = 0;
1587         int i;
1588         struct lnet_rtrbufpool *rtrp;
1589
1590         /* If the provided values for each buffer pool are different than the
1591          * configured values, we need to take action. */
1592         if (tiny >= 0) {
1593                 tiny_router_buffers = tiny;
1594                 nrb = lnet_nrb_tiny_calculate();
1595                 cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1596                         rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_TINY_BUF_IDX],
1597                                                       nrb, i);
1598                         if (rc != 0)
1599                                 return rc;
1600                 }
1601         }
1602         if (small >= 0) {
1603                 small_router_buffers = small;
1604                 nrb = lnet_nrb_small_calculate();
1605                 cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1606                         rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_SMALL_BUF_IDX],
1607                                                       nrb, i);
1608                         if (rc != 0)
1609                                 return rc;
1610                 }
1611         }
1612         if (large >= 0) {
1613                 large_router_buffers = large;
1614                 nrb = lnet_nrb_large_calculate();
1615                 cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1616                         rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_LARGE_BUF_IDX],
1617                                                       nrb, i);
1618                         if (rc != 0)
1619                                 return rc;
1620                 }
1621         }
1622
1623         return 0;
1624 }
1625
1626 int
1627 lnet_rtrpools_adjust(int tiny, int small, int large)
1628 {
1629         /* this function doesn't revert the changes if adding new buffers
1630          * failed.  It's up to the user space caller to revert the
1631          * changes. */
1632
1633         if (!the_lnet.ln_routing)
1634                 return 0;
1635
1636         return lnet_rtrpools_adjust_helper(tiny, small, large);
1637 }
1638
1639 int
1640 lnet_rtrpools_enable(void)
1641 {
1642         int rc = 0;
1643
1644         if (the_lnet.ln_routing)
1645                 return 0;
1646
1647         if (the_lnet.ln_rtrpools == NULL)
1648                 /* If routing is turned off, and we have never
1649                  * initialized the pools before, just call the
1650                  * standard buffer pool allocation routine as
1651                  * if we are just configuring this for the first
1652                  * time. */
1653                 rc = lnet_rtrpools_alloc(1);
1654         else
1655                 rc = lnet_rtrpools_adjust_helper(0, 0, 0);
1656         if (rc != 0)
1657                 return rc;
1658
1659         lnet_net_lock(LNET_LOCK_EX);
1660         the_lnet.ln_routing = 1;
1661
1662         the_lnet.ln_ping_target->pb_info.pi_features &=
1663                 ~LNET_PING_FEAT_RTE_DISABLED;
1664         lnet_net_unlock(LNET_LOCK_EX);
1665
1666         if (lnet_peer_discovery_disabled)
1667                 CWARN("Consider turning discovery on to enable full "
1668                       "Multi-Rail routing functionality\n");
1669
1670         return rc;
1671 }
1672
1673 void
1674 lnet_rtrpools_disable(void)
1675 {
1676         if (!the_lnet.ln_routing)
1677                 return;
1678
1679         lnet_net_lock(LNET_LOCK_EX);
1680         the_lnet.ln_routing = 0;
1681         the_lnet.ln_ping_target->pb_info.pi_features |=
1682                 LNET_PING_FEAT_RTE_DISABLED;
1683
1684         tiny_router_buffers = 0;
1685         small_router_buffers = 0;
1686         large_router_buffers = 0;
1687         lnet_net_unlock(LNET_LOCK_EX);
1688         lnet_rtrpools_free(1);
1689 }
1690
1691 static inline void
1692 lnet_notify_peer_down(struct lnet_ni *ni, lnet_nid_t nid)
1693 {
1694         if (ni->ni_net->net_lnd->lnd_notify_peer_down != NULL)
1695                 (ni->ni_net->net_lnd->lnd_notify_peer_down)(nid);
1696 }
1697
1698 /*
1699  * ni: local NI used to communicate with the peer
1700  * nid: peer NID
1701  * alive: true if peer is alive, false otherwise
1702  * reset: reset health value. This is requested by the LND.
1703  * when: notificaiton time.
1704  */
1705 int
1706 lnet_notify(struct lnet_ni *ni, lnet_nid_t nid, bool alive, bool reset,
1707             time64_t when)
1708 {
1709         struct lnet_peer_ni *lpni = NULL;
1710         struct lnet_route *route;
1711         struct lnet_peer *lp;
1712         time64_t now = ktime_get_seconds();
1713         int cpt;
1714
1715         LASSERT(!in_interrupt());
1716
1717         CDEBUG(D_NET, "%s notifying %s: %s\n",
1718                (ni == NULL) ? "userspace" : libcfs_nid2str(ni->ni_nid),
1719                libcfs_nid2str(nid), alive ? "up" : "down");
1720
1721         if (ni != NULL &&
1722             LNET_NIDNET(ni->ni_nid) != LNET_NIDNET(nid)) {
1723                 CWARN("Ignoring notification of %s %s by %s (different net)\n",
1724                       libcfs_nid2str(nid), alive ? "birth" : "death",
1725                       libcfs_nid2str(ni->ni_nid));
1726                 return -EINVAL;
1727         }
1728
1729         /* can't do predictions... */
1730         if (when > now) {
1731                 CWARN("Ignoring prediction from %s of %s %s "
1732                       "%lld seconds in the future\n",
1733                       (ni == NULL) ? "userspace" : libcfs_nid2str(ni->ni_nid),
1734                       libcfs_nid2str(nid), alive ? "up" : "down", when - now);
1735                 return -EINVAL;
1736         }
1737
1738         if (ni != NULL && !alive &&             /* LND telling me she's down */
1739             !auto_down) {                       /* auto-down disabled */
1740                 CDEBUG(D_NET, "Auto-down disabled\n");
1741                 return 0;
1742         }
1743
1744         /* must lock 0 since this is used for synchronization */
1745         lnet_net_lock(0);
1746
1747         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
1748                 lnet_net_unlock(0);
1749                 return -ESHUTDOWN;
1750         }
1751
1752         lpni = lnet_find_peer_ni_locked(nid);
1753         if (lpni == NULL) {
1754                 /* nid not found */
1755                 lnet_net_unlock(0);
1756                 CDEBUG(D_NET, "%s not found\n", libcfs_nid2str(nid));
1757                 return 0;
1758         }
1759
1760         if (alive) {
1761                 if (reset) {
1762                         lpni->lpni_ns_status = LNET_NI_STATUS_UP;
1763                         lnet_set_lpni_healthv_locked(lpni,
1764                                                      LNET_MAX_HEALTH_VALUE);
1765                 } else {
1766                         __u32 sensitivity = lpni->lpni_peer_net->
1767                                         lpn_peer->lp_health_sensitivity;
1768
1769                         lnet_inc_lpni_healthv_locked(lpni,
1770                                         (sensitivity) ? sensitivity :
1771                                         lnet_health_sensitivity);
1772                 }
1773         } else if (reset) {
1774                 lpni->lpni_ns_status = LNET_NI_STATUS_DOWN;
1775         }
1776
1777         /* recalculate aliveness */
1778         alive = lnet_is_peer_ni_alive(lpni);
1779
1780         lp = lpni->lpni_peer_net->lpn_peer;
1781         /* If this is an LNet router then update route aliveness */
1782         if (lp->lp_rtr_refcount) {
1783                 if (reset)
1784                         /* reset flag indicates gateway peer went up or down */
1785                         lp->lp_alive = alive;
1786
1787                 /* If discovery is disabled, locally or on the gateway, then
1788                  * any routes using lpni as next-hop need to be updated
1789                  *
1790                  * NB: We can get many notifications while a route is down, so
1791                  * we try and avoid the expensive net_lock/EX here for the
1792                  * common case of receiving duplicate lnet_notify() calls (i.e.
1793                  * only grab EX lock when we actually need to update the route
1794                  * aliveness).
1795                  */
1796                 if (lnet_is_discovery_disabled(lp)) {
1797                         list_for_each_entry(route, &lp->lp_routes, lr_gwlist) {
1798                                 if (route->lr_nid == lpni->lpni_nid &&
1799                                     route->lr_alive != alive) {
1800                                         lnet_net_unlock(0);
1801                                         lnet_net_lock(LNET_LOCK_EX);
1802                                         lnet_set_route_aliveness(route, alive);
1803                                         lnet_net_unlock(LNET_LOCK_EX);
1804                                         lnet_net_lock(0);
1805                                 }
1806                         }
1807                 }
1808         }
1809
1810         lnet_net_unlock(0);
1811
1812         if (ni != NULL && !alive)
1813                 lnet_notify_peer_down(ni, lpni->lpni_nid);
1814
1815         cpt = lpni->lpni_cpt;
1816         lnet_net_lock(cpt);
1817         lnet_peer_ni_decref_locked(lpni);
1818         lnet_net_unlock(cpt);
1819
1820         return 0;
1821 }
1822 EXPORT_SYMBOL(lnet_notify);