Whamcloud - gitweb
LU-13780 lnet: Leverage peer aliveness more efficiently
[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 atomic_read(&route->lr_alive) == 1;
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 void
408 lnet_router_discovery_ping_reply(struct lnet_peer *lp)
409 {
410         struct lnet_ping_buffer *pbuf = lp->lp_data;
411         struct lnet_peer_net *llpn;
412         struct lnet_route *route;
413         bool single_hop = false;
414         bool net_up = false;
415         unsigned lp_state;
416         __u32 net;
417         int i;
418
419
420         spin_lock(&lp->lp_lock);
421         lp_state = lp->lp_state;
422
423         /* only handle replies if discovery is disabled. */
424         if (!lnet_is_discovery_disabled_locked(lp)) {
425                 spin_unlock(&lp->lp_lock);
426                 return;
427         }
428
429         spin_unlock(&lp->lp_lock);
430
431         if (lp_state & LNET_PEER_PING_FAILED ||
432             pbuf->pb_info.pi_features & LNET_PING_FEAT_RTE_DISABLED) {
433                 CDEBUG(D_NET, "Set routes down for gw %s because %s %d\n",
434                        libcfs_nid2str(lp->lp_primary_nid),
435                        lp_state & LNET_PEER_PING_FAILED ? "ping failed" :
436                        "route feature is disabled", lp->lp_ping_error);
437                 /* If the ping failed or the peer has routing disabled then
438                  * mark the routes served by this peer down
439                  */
440                 list_for_each_entry(route, &lp->lp_routes, lr_gwlist)
441                         lnet_set_route_aliveness(route, false);
442                 return;
443         }
444
445         CDEBUG(D_NET, "Discovery is disabled. Processing reply for gw: %s:%d\n",
446                libcfs_nid2str(lp->lp_primary_nid), pbuf->pb_info.pi_nnis);
447
448         /*
449          * examine the ping response to determine if the routes on that
450          * gateway should be declared alive.
451          * The route is alive if:
452          *  1. local network to reach the route is alive and
453          *  2. route is single hop, avoid_async_router_failure is set and
454          *     there exists at least one NI on the route's remote net
455          */
456         list_for_each_entry(route, &lp->lp_routes, lr_gwlist) {
457                 llpn = lnet_peer_get_net_locked(lp, route->lr_lnet);
458                 if (!llpn) {
459                         lnet_set_route_aliveness(route, false);
460                         continue;
461                 }
462
463                 if (!lnet_is_gateway_net_alive(llpn)) {
464                         lnet_set_route_aliveness(route, false);
465                         continue;
466                 }
467
468                 single_hop = net_up = false;
469                 for (i = 1; i < pbuf->pb_info.pi_nnis; i++) {
470                         net = LNET_NIDNET(pbuf->pb_info.pi_ni[i].ns_nid);
471
472                         if (route->lr_net == net) {
473                                 single_hop = true;
474                                 if (pbuf->pb_info.pi_ni[i].ns_status ==
475                                     LNET_NI_STATUS_UP) {
476                                         net_up = true;
477                                         break;
478                                 }
479                         }
480                 }
481
482                 route->lr_single_hop = single_hop;
483                 if (avoid_asym_router_failure &&
484                     (route->lr_hops == 1 ||
485                      route->lr_hops == LNET_UNDEFINED_HOPS))
486                         lnet_set_route_aliveness(route, net_up);
487                 else
488                         lnet_set_route_aliveness(route, true);
489
490                 /*
491                  * warn that the route is configured as single-hop but it
492                  * really is multi-hop as far as we can tell.
493                  */
494                 lnet_check_route_inconsistency(route);
495         }
496 }
497
498 void
499 lnet_router_discovery_complete(struct lnet_peer *lp)
500 {
501         struct lnet_peer_ni *lpni = NULL;
502         struct lnet_route *route;
503
504         spin_lock(&lp->lp_lock);
505         lp->lp_state &= ~LNET_PEER_RTR_DISCOVERY;
506         lp->lp_state |= LNET_PEER_RTR_DISCOVERED;
507         lp->lp_alive = lp->lp_dc_error == 0;
508         spin_unlock(&lp->lp_lock);
509
510         /* ping replies are being handled when discovery is disabled */
511         if (lnet_is_discovery_disabled_locked(lp))
512                 return;
513
514         if (!lp->lp_dc_error) {
515                 /*
516                 * mark single-hop routes.  If the remote net is not configured on
517                 * the gateway we assume this is intentional and we mark the
518                 * gateway as multi-hop
519                 */
520                 list_for_each_entry(route, &lp->lp_routes, lr_gwlist) {
521                         lnet_set_route_aliveness(route, true);
522                         lnet_set_route_hop_type(lp, route);
523                 }
524
525                 return;
526         }
527
528         /*
529          * We do not send messages directly to the remote interfaces
530          * of an LNet router. As such, we rely on the PING response
531          * to determine the up/down status of these interfaces. If
532          * a PING response is not receieved, or some other problem with
533          * discovery occurs that prevents us from getting this status,
534          * we assume all interfaces are down until we're able to
535          * determine otherwise.
536          */
537         CDEBUG(D_NET, "%s: Router discovery failed %d\n",
538                libcfs_nid2str(lp->lp_primary_nid), lp->lp_dc_error);
539         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL)
540                 lpni->lpni_ns_status = LNET_NI_STATUS_DOWN;
541
542         list_for_each_entry(route, &lp->lp_routes, lr_gwlist)
543                 lnet_set_route_aliveness(route, false);
544 }
545
546 static void
547 lnet_rtr_addref_locked(struct lnet_peer *lp)
548 {
549         LASSERT(lp->lp_rtr_refcount >= 0);
550
551         /* lnet_net_lock must be exclusively locked */
552         lp->lp_rtr_refcount++;
553         if (lp->lp_rtr_refcount == 1) {
554                 list_add_tail(&lp->lp_rtr_list, &the_lnet.ln_routers);
555                 /* addref for the_lnet.ln_routers */
556                 lnet_peer_addref_locked(lp);
557                 the_lnet.ln_routers_version++;
558         }
559 }
560
561 static void
562 lnet_rtr_decref_locked(struct lnet_peer *lp)
563 {
564         LASSERT(atomic_read(&lp->lp_refcount) > 0);
565         LASSERT(lp->lp_rtr_refcount > 0);
566
567         /* lnet_net_lock must be exclusively locked */
568         lp->lp_rtr_refcount--;
569         if (lp->lp_rtr_refcount == 0) {
570                 LASSERT(list_empty(&lp->lp_routes));
571
572                 list_del(&lp->lp_rtr_list);
573                 /* decref for the_lnet.ln_routers */
574                 lnet_peer_decref_locked(lp);
575                 the_lnet.ln_routers_version++;
576         }
577 }
578
579 struct lnet_remotenet *
580 lnet_find_rnet_locked(__u32 net)
581 {
582         struct lnet_remotenet *rnet;
583         struct list_head *tmp;
584         struct list_head *rn_list;
585
586         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
587
588         rn_list = lnet_net2rnethash(net);
589         list_for_each(tmp, rn_list) {
590                 rnet = list_entry(tmp, struct lnet_remotenet, lrn_list);
591
592                 if (rnet->lrn_net == net)
593                         return rnet;
594         }
595         return NULL;
596 }
597
598 static void lnet_shuffle_seed(void)
599 {
600         static int seeded;
601         struct lnet_ni *ni = NULL;
602
603         if (seeded)
604                 return;
605
606         /* Nodes with small feet have little entropy
607          * the NID for this node gives the most entropy in the low bits */
608         while ((ni = lnet_get_next_ni_locked(NULL, ni)))
609                 add_device_randomness(&ni->ni_nid, sizeof(ni->ni_nid));
610
611         seeded = 1;
612 }
613
614 /* NB expects LNET_LOCK held */
615 static void
616 lnet_add_route_to_rnet(struct lnet_remotenet *rnet, struct lnet_route *route)
617 {
618         struct lnet_peer_net *lpn;
619         unsigned int offset = 0;
620         unsigned int len = 0;
621         struct list_head *e;
622
623         lnet_shuffle_seed();
624
625         list_for_each(e, &rnet->lrn_routes)
626                 len++;
627
628         /*
629          * Randomly adding routes to the list is done to ensure that when
630          * different nodes are using the same list of routers, they end up
631          * preferring different routers.
632          */
633         offset = prandom_u32_max(len + 1);
634         list_for_each(e, &rnet->lrn_routes) {
635                 if (offset == 0)
636                         break;
637                 offset--;
638         }
639         list_add(&route->lr_list, e);
640         /*
641          * force a router check on the gateway to make sure the route is
642          * alive
643          */
644         list_for_each_entry(lpn, &route->lr_gateway->lp_peer_nets,
645                             lpn_peer_nets) {
646                 lpn->lpn_rtrcheck_timestamp = 0;
647         }
648
649         the_lnet.ln_remote_nets_version++;
650
651         /* add the route on the gateway list */
652         list_add(&route->lr_gwlist, &route->lr_gateway->lp_routes);
653
654         /* take a router reference count on the gateway */
655         lnet_rtr_addref_locked(route->lr_gateway);
656 }
657
658 int
659 lnet_add_route(__u32 net, __u32 hops, lnet_nid_t gateway,
660                __u32 priority, __u32 sensitivity)
661 {
662         struct list_head *route_entry;
663         struct lnet_remotenet *rnet;
664         struct lnet_remotenet *rnet2;
665         struct lnet_route *route;
666         struct lnet_peer_ni *lpni;
667         struct lnet_peer *gw;
668         int add_route;
669         int rc;
670
671         CDEBUG(D_NET, "Add route: remote net %s hops %d priority %u gw %s\n",
672                libcfs_net2str(net), hops, priority, libcfs_nid2str(gateway));
673
674         if (gateway == LNET_NID_ANY ||
675             gateway == LNET_NID_LO_0 ||
676             net == LNET_NET_ANY ||
677             LNET_NETTYP(net) == LOLND ||
678             LNET_NIDNET(gateway) == net ||
679             (hops != LNET_UNDEFINED_HOPS && (hops < 1 || hops > 255)))
680                 return -EINVAL;
681
682         /* it's a local network */
683         if (lnet_islocalnet(net))
684                 return -EEXIST;
685
686         if (!lnet_islocalnet(LNET_NIDNET(gateway))) {
687                 CERROR("Cannot add route with gateway %s. There is no local interface configured on LNet %s\n",
688                        libcfs_nid2str(gateway),
689                        libcfs_net2str(LNET_NIDNET(gateway)));
690                 return -EHOSTUNREACH;
691         }
692
693         /* Assume net, route, all new */
694         LIBCFS_ALLOC(route, sizeof(*route));
695         LIBCFS_ALLOC(rnet, sizeof(*rnet));
696         if (route == NULL || rnet == NULL) {
697                 CERROR("Out of memory creating route %s %d %s\n",
698                        libcfs_net2str(net), hops, libcfs_nid2str(gateway));
699                 if (route != NULL)
700                         LIBCFS_FREE(route, sizeof(*route));
701                 if (rnet != NULL)
702                         LIBCFS_FREE(rnet, sizeof(*rnet));
703                 return -ENOMEM;
704         }
705
706         INIT_LIST_HEAD(&rnet->lrn_routes);
707         rnet->lrn_net = net;
708         /* store the local and remote net that the route represents */
709         route->lr_lnet = LNET_NIDNET(gateway);
710         route->lr_net = net;
711         route->lr_nid = gateway;
712         route->lr_priority = priority;
713         route->lr_hops = hops;
714         if (lnet_peers_start_down())
715                 atomic_set(&route->lr_alive, 0);
716         else
717                 atomic_set(&route->lr_alive, 1);
718
719         lnet_net_lock(LNET_LOCK_EX);
720
721         /*
722          * lnet_nid2peerni_ex() grabs a ref on the lpni. We will need to
723          * lose that once we're done
724          */
725         lpni = lnet_nid2peerni_ex(gateway, LNET_LOCK_EX);
726         if (IS_ERR(lpni)) {
727                 lnet_net_unlock(LNET_LOCK_EX);
728
729                 LIBCFS_FREE(route, sizeof(*route));
730                 LIBCFS_FREE(rnet, sizeof(*rnet));
731
732                 rc = PTR_ERR(lpni);
733                 CERROR("Error %d creating route %s %d %s\n", rc,
734                         libcfs_net2str(net), hops,
735                         libcfs_nid2str(gateway));
736                 return rc;
737         }
738
739         LASSERT(lpni->lpni_peer_net && lpni->lpni_peer_net->lpn_peer);
740         gw = lpni->lpni_peer_net->lpn_peer;
741
742         route->lr_gateway = gw;
743
744         rnet2 = lnet_find_rnet_locked(net);
745         if (rnet2 == NULL) {
746                 /* new network */
747                 list_add_tail(&rnet->lrn_list, lnet_net2rnethash(net));
748                 rnet2 = rnet;
749         }
750
751         /* Search for a duplicate route (it's a NOOP if it is) */
752         add_route = 1;
753         list_for_each(route_entry, &rnet2->lrn_routes) {
754                 struct lnet_route *route2;
755
756                 route2 = list_entry(route_entry, struct lnet_route, lr_list);
757                 if (route2->lr_gateway == route->lr_gateway) {
758                         add_route = 0;
759                         break;
760                 }
761
762                 /* our lookups must be true */
763                 LASSERT(route2->lr_gateway->lp_primary_nid != gateway);
764         }
765
766         /*
767          * It is possible to add multiple routes through the same peer,
768          * but it'll be using a different NID of that peer. When the
769          * gateway is discovered, discovery will consolidate the different
770          * peers into one peer. In this case the discovery code will have
771          * to move the routes from the peer that's being deleted to the
772          * consolidated peer lp_routes list
773          */
774         if (add_route) {
775                 gw->lp_health_sensitivity = sensitivity;
776                 lnet_add_route_to_rnet(rnet2, route);
777                 if (lnet_peer_discovery_disabled)
778                         CWARN("Consider turning discovery on to enable full "
779                               "Multi-Rail routing functionality\n");
780         }
781
782         /*
783          * get rid of the reference on the lpni.
784          */
785         lnet_peer_ni_decref_locked(lpni);
786         lnet_net_unlock(LNET_LOCK_EX);
787
788         rc = 0;
789
790         if (!add_route) {
791                 rc = -EEXIST;
792                 LIBCFS_FREE(route, sizeof(*route));
793         }
794
795         if (rnet != rnet2)
796                 LIBCFS_FREE(rnet, sizeof(*rnet));
797
798         /* kick start the monitor thread to handle the added route */
799         complete(&the_lnet.ln_mt_wait_complete);
800
801         return rc;
802 }
803
804 void
805 lnet_del_route_from_rnet(lnet_nid_t gw_nid, struct list_head *route_list,
806                          struct list_head *zombies)
807 {
808         struct lnet_peer *gateway;
809         struct lnet_route *route;
810         struct lnet_route *tmp;
811
812         list_for_each_entry_safe(route, tmp, route_list, lr_list) {
813                 gateway = route->lr_gateway;
814                 if (gw_nid != LNET_NID_ANY &&
815                     gw_nid != gateway->lp_primary_nid)
816                         continue;
817
818                 /*
819                  * move to zombie to delete outside the lock
820                  * Note that this function is called with the
821                  * ln_api_mutex held as well as the exclusive net
822                  * lock. Adding to the remote net list happens
823                  * under the same conditions. Same goes for the
824                  * gateway router list
825                  */
826                 list_move(&route->lr_list, zombies);
827                 the_lnet.ln_remote_nets_version++;
828
829                 list_del(&route->lr_gwlist);
830                 lnet_rtr_decref_locked(gateway);
831         }
832 }
833
834 int
835 lnet_del_route(__u32 net, lnet_nid_t gw_nid)
836 {
837         LIST_HEAD(rnet_zombies);
838         struct lnet_remotenet *rnet;
839         struct lnet_remotenet *tmp;
840         struct list_head *rn_list;
841         struct lnet_peer_ni *lpni;
842         struct lnet_route *route;
843         LIST_HEAD(zombies);
844         struct lnet_peer *lp = NULL;
845         int i = 0;
846
847         CDEBUG(D_NET, "Del route: net %s : gw %s\n",
848                libcfs_net2str(net), libcfs_nid2str(gw_nid));
849
850         /* NB Caller may specify either all routes via the given gateway
851          * or a specific route entry actual NIDs) */
852
853         lnet_net_lock(LNET_LOCK_EX);
854
855         lpni = lnet_find_peer_ni_locked(gw_nid);
856         if (lpni) {
857                 lp = lpni->lpni_peer_net->lpn_peer;
858                 LASSERT(lp);
859                 gw_nid = lp->lp_primary_nid;
860                 lnet_peer_ni_decref_locked(lpni);
861         }
862
863         if (net != LNET_NET_ANY) {
864                 rnet = lnet_find_rnet_locked(net);
865                 if (!rnet) {
866                         lnet_net_unlock(LNET_LOCK_EX);
867                         return -ENOENT;
868                 }
869                 lnet_del_route_from_rnet(gw_nid, &rnet->lrn_routes,
870                                          &zombies);
871                 if (list_empty(&rnet->lrn_routes))
872                         list_move(&rnet->lrn_list, &rnet_zombies);
873                 goto delete_zombies;
874         }
875
876         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
877                 rn_list = &the_lnet.ln_remote_nets_hash[i];
878
879                 list_for_each_entry_safe(rnet, tmp, rn_list, lrn_list) {
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                 }
885         }
886
887 delete_zombies:
888         /*
889          * check if there are any routes remaining on the gateway
890          * If there are no more routes make sure to set the peer's
891          * lp_disc_net_id to 0 (invalid), in case we add more routes in
892          * the future on that gateway, then we start our discovery process
893          * from scratch
894          */
895         if (lpni) {
896                 if (list_empty(&lp->lp_routes))
897                         lp->lp_disc_net_id = 0;
898         }
899
900         lnet_net_unlock(LNET_LOCK_EX);
901
902         while (!list_empty(&zombies)) {
903                 route = list_first_entry(&zombies, struct lnet_route, lr_list);
904                 list_del(&route->lr_list);
905                 LIBCFS_FREE(route, sizeof(*route));
906         }
907
908         while (!list_empty(&rnet_zombies)) {
909                 rnet = list_first_entry(&rnet_zombies, struct lnet_remotenet,
910                                         lrn_list);
911                 list_del(&rnet->lrn_list);
912                 LIBCFS_FREE(rnet, sizeof(*rnet));
913         }
914
915         return 0;
916 }
917
918 void
919 lnet_destroy_routes (void)
920 {
921         lnet_del_route(LNET_NET_ANY, LNET_NID_ANY);
922 }
923
924 int lnet_get_rtr_pool_cfg(int cpt, struct lnet_ioctl_pool_cfg *pool_cfg)
925 {
926         struct lnet_rtrbufpool *rbp;
927         int i, rc = -ENOENT, j;
928
929         if (the_lnet.ln_rtrpools == NULL)
930                 return rc;
931
932
933         cfs_percpt_for_each(rbp, i, the_lnet.ln_rtrpools) {
934                 if (i != cpt)
935                         continue;
936
937                 lnet_net_lock(i);
938                 for (j = 0; j < LNET_NRBPOOLS; j++) {
939                         pool_cfg->pl_pools[j].pl_npages = rbp[j].rbp_npages;
940                         pool_cfg->pl_pools[j].pl_nbuffers = rbp[j].rbp_nbuffers;
941                         pool_cfg->pl_pools[j].pl_credits = rbp[j].rbp_credits;
942                         pool_cfg->pl_pools[j].pl_mincredits = rbp[j].rbp_mincredits;
943                 }
944                 lnet_net_unlock(i);
945                 rc = 0;
946                 break;
947         }
948
949         lnet_net_lock(LNET_LOCK_EX);
950         pool_cfg->pl_routing = the_lnet.ln_routing;
951         lnet_net_unlock(LNET_LOCK_EX);
952
953         return rc;
954 }
955
956 int
957 lnet_get_route(int idx, __u32 *net, __u32 *hops,
958                lnet_nid_t *gateway, __u32 *flags, __u32 *priority, __u32 *sensitivity)
959 {
960         struct lnet_remotenet *rnet;
961         struct list_head *rn_list;
962         struct lnet_route *route;
963         struct list_head *e1;
964         struct list_head *e2;
965         int cpt;
966         int i;
967
968         cpt = lnet_net_lock_current();
969
970         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
971                 rn_list = &the_lnet.ln_remote_nets_hash[i];
972                 list_for_each(e1, rn_list) {
973                         rnet = list_entry(e1, struct lnet_remotenet, lrn_list);
974
975                         list_for_each(e2, &rnet->lrn_routes) {
976                                 route = list_entry(e2, struct lnet_route,
977                                                    lr_list);
978
979                                 if (idx-- == 0) {
980                                         *net      = rnet->lrn_net;
981                                         *gateway  = route->lr_nid;
982                                         *hops     = route->lr_hops;
983                                         *priority = route->lr_priority;
984                                         *sensitivity = route->lr_gateway->
985                                                 lp_health_sensitivity;
986                                         if (lnet_is_route_alive(route))
987                                                 *flags |= LNET_RT_ALIVE;
988                                         else
989                                                 *flags &= ~LNET_RT_ALIVE;
990                                         if (route->lr_single_hop)
991                                                 *flags &= ~LNET_RT_MULTI_HOP;
992                                         else
993                                                 *flags |= LNET_RT_MULTI_HOP;
994                                         lnet_net_unlock(cpt);
995                                         return 0;
996                                 }
997                         }
998                 }
999         }
1000
1001         lnet_net_unlock(cpt);
1002         return -ENOENT;
1003 }
1004
1005 static void
1006 lnet_wait_known_routerstate(void)
1007 {
1008         struct lnet_peer *rtr;
1009         struct list_head *entry;
1010         int all_known;
1011
1012         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING);
1013
1014         for (;;) {
1015                 int cpt = lnet_net_lock_current();
1016
1017                 all_known = 1;
1018                 list_for_each(entry, &the_lnet.ln_routers) {
1019                         rtr = list_entry(entry, struct lnet_peer,
1020                                          lp_rtr_list);
1021
1022                         spin_lock(&rtr->lp_lock);
1023
1024                         if ((rtr->lp_state & LNET_PEER_RTR_DISCOVERED) == 0) {
1025                                 all_known = 0;
1026                                 spin_unlock(&rtr->lp_lock);
1027                                 break;
1028                         }
1029                         spin_unlock(&rtr->lp_lock);
1030                 }
1031
1032                 lnet_net_unlock(cpt);
1033
1034                 if (all_known)
1035                         return;
1036
1037                 schedule_timeout_uninterruptible(cfs_time_seconds(1));
1038         }
1039 }
1040
1041 static inline bool
1042 lnet_net_set_status_locked(struct lnet_net *net, __u32 status)
1043 {
1044         struct lnet_ni *ni;
1045         bool update = false;
1046
1047         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1048                 if (lnet_ni_set_status(ni, status))
1049                         update = true;
1050
1051         return update;
1052 }
1053
1054 static bool
1055 lnet_update_ni_status_locked(void)
1056 {
1057         struct lnet_net *net;
1058         struct lnet_ni *ni;
1059         bool push = false;
1060         time64_t now;
1061         time64_t timeout;
1062
1063         LASSERT(the_lnet.ln_routing);
1064
1065         timeout = router_ping_timeout + alive_router_check_interval;
1066
1067         now = ktime_get_real_seconds();
1068         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1069                 if (net->net_lnd->lnd_type == LOLND)
1070                         continue;
1071
1072                 if (now < net->net_last_alive + timeout)
1073                         goto check_ni_fatal;
1074
1075                 spin_lock(&net->net_lock);
1076                 /* re-check with lock */
1077                 if (now < net->net_last_alive + timeout) {
1078                         spin_unlock(&net->net_lock);
1079                         goto check_ni_fatal;
1080                 }
1081                 spin_unlock(&net->net_lock);
1082
1083                 /*
1084                  * if the net didn't receive any traffic for past the
1085                  * timeout on any of its constituent NIs, then mark all
1086                  * the NIs down.
1087                  */
1088                 if (lnet_net_set_status_locked(net, LNET_NI_STATUS_DOWN)) {
1089                         push = true;
1090                         continue;
1091                 }
1092
1093 check_ni_fatal:
1094                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1095                         /* lnet_ni_set_status() will perform the same check of
1096                          * ni_status while holding the ni lock. We can safely
1097                          * check ni_status without that lock because it is only
1098                          * written to under net_lock/EX and our caller is
1099                          * holding a net lock.
1100                          */
1101                         if (atomic_read(&ni->ni_fatal_error_on) &&
1102                             ni->ni_status &&
1103                             ni->ni_status->ns_status != LNET_NI_STATUS_DOWN &&
1104                             lnet_ni_set_status(ni, LNET_NI_STATUS_DOWN))
1105                                 push = true;
1106                 }
1107         }
1108
1109         return push;
1110 }
1111
1112 void lnet_wait_router_start(void)
1113 {
1114         if (check_routers_before_use) {
1115                 /* Note that a helpful side-effect of pinging all known routers
1116                  * at startup is that it makes them drop stale connections they
1117                  * may have to a previous instance of me. */
1118                 lnet_wait_known_routerstate();
1119         }
1120 }
1121
1122 /*
1123  * This function is called from the monitor thread to check if there are
1124  * any active routers that need to be checked.
1125  */
1126 bool lnet_router_checker_active(void)
1127 {
1128         /* Router Checker thread needs to run when routing is enabled in
1129          * order to call lnet_update_ni_status_locked() */
1130         if (the_lnet.ln_routing)
1131                 return true;
1132
1133         return !list_empty(&the_lnet.ln_routers) &&
1134                 alive_router_check_interval > 0;
1135 }
1136
1137 void
1138 lnet_check_routers(void)
1139 {
1140         struct lnet_peer_net *first_lpn = NULL;
1141         struct lnet_peer_net *lpn;
1142         struct lnet_peer_ni *lpni;
1143         struct list_head *entry;
1144         struct lnet_peer *rtr;
1145         bool push = false;
1146         bool found_lpn;
1147         __u64 version;
1148         __u32 net_id;
1149         time64_t now;
1150         int cpt;
1151         int rc;
1152
1153         cpt = lnet_net_lock_current();
1154 rescan:
1155         version = the_lnet.ln_routers_version;
1156
1157         list_for_each(entry, &the_lnet.ln_routers) {
1158                 rtr = list_entry(entry, struct lnet_peer,
1159                                  lp_rtr_list);
1160
1161                 now = ktime_get_real_seconds();
1162
1163                 /*
1164                  * only discover the router if we've passed
1165                  * alive_router_check_interval seconds. Some of the router
1166                  * interfaces could be down and in that case they would be
1167                  * undergoing recovery separately from this discovery.
1168                  */
1169                 /* find next peer net which is also local */
1170                 net_id = rtr->lp_disc_net_id;
1171                 do {
1172                         lpn = lnet_get_next_peer_net_locked(rtr, net_id);
1173                         if (!lpn) {
1174                                 CERROR("gateway %s has no networks\n",
1175                                 libcfs_nid2str(rtr->lp_primary_nid));
1176                                 break;
1177                         }
1178                         if (first_lpn == lpn)
1179                                 break;
1180                         if (!first_lpn)
1181                                 first_lpn = lpn;
1182                         found_lpn = lnet_islocalnet_locked(lpn->lpn_net_id);
1183                         net_id = lpn->lpn_net_id;
1184                 } while (!found_lpn);
1185
1186                 if (!found_lpn || !lpn) {
1187                         CERROR("no local network found for gateway %s\n",
1188                                libcfs_nid2str(rtr->lp_primary_nid));
1189                         continue;
1190                 }
1191
1192                 if (now - lpn->lpn_rtrcheck_timestamp <
1193                     alive_router_check_interval / lnet_current_net_count)
1194                        continue;
1195
1196                 /*
1197                  * If we're currently discovering the peer then don't
1198                  * issue another discovery
1199                  */
1200                 spin_lock(&rtr->lp_lock);
1201                 if (rtr->lp_state & LNET_PEER_RTR_DISCOVERY) {
1202                         spin_unlock(&rtr->lp_lock);
1203                         continue;
1204                 }
1205                 /* make sure we fully discover the router */
1206                 rtr->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
1207                 rtr->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH |
1208                         LNET_PEER_RTR_DISCOVERY;
1209                 spin_unlock(&rtr->lp_lock);
1210
1211                 /* find the peer_ni associated with the primary NID */
1212                 lpni = lnet_peer_get_ni_locked(rtr, rtr->lp_primary_nid);
1213                 if (!lpni) {
1214                         CDEBUG(D_NET, "Expected to find an lpni for %s, but non found\n",
1215                                libcfs_nid2str(rtr->lp_primary_nid));
1216                         continue;
1217                 }
1218                 lnet_peer_ni_addref_locked(lpni);
1219
1220                 /* specify the net to use */
1221                 rtr->lp_disc_net_id = lpn->lpn_net_id;
1222
1223                 /* discover the router */
1224                 CDEBUG(D_NET, "discover %s, cpt = %d\n",
1225                        libcfs_nid2str(lpni->lpni_nid), cpt);
1226                 rc = lnet_discover_peer_locked(lpni, cpt, false);
1227
1228                 /* decrement ref count acquired by find_peer_ni_locked() */
1229                 lnet_peer_ni_decref_locked(lpni);
1230
1231                 if (!rc)
1232                         lpn->lpn_rtrcheck_timestamp = now;
1233                 else
1234                         CERROR("Failed to discover router %s\n",
1235                                libcfs_nid2str(rtr->lp_primary_nid));
1236
1237                 /* NB dropped lock */
1238                 if (version != the_lnet.ln_routers_version) {
1239                         /* the routers list has changed */
1240                         goto rescan;
1241                 }
1242         }
1243
1244         if (the_lnet.ln_routing)
1245                 push = lnet_update_ni_status_locked();
1246
1247         lnet_net_unlock(cpt);
1248
1249         /* if the status of the ni changed update the peers */
1250         if (push)
1251                 lnet_push_update_to_peers(1);
1252 }
1253
1254 void
1255 lnet_destroy_rtrbuf(struct lnet_rtrbuf *rb, int npages)
1256 {
1257         int sz = offsetof(struct lnet_rtrbuf, rb_kiov[npages]);
1258
1259         while (--npages >= 0)
1260                 __free_page(rb->rb_kiov[npages].bv_page);
1261
1262         LIBCFS_FREE(rb, sz);
1263 }
1264
1265 static struct lnet_rtrbuf *
1266 lnet_new_rtrbuf(struct lnet_rtrbufpool *rbp, int cpt)
1267 {
1268         int            npages = rbp->rbp_npages;
1269         int            sz = offsetof(struct lnet_rtrbuf, rb_kiov[npages]);
1270         struct page   *page;
1271         struct lnet_rtrbuf *rb;
1272         int            i;
1273
1274         LIBCFS_CPT_ALLOC(rb, lnet_cpt_table(), cpt, sz);
1275         if (rb == NULL)
1276                 return NULL;
1277
1278         rb->rb_pool = rbp;
1279
1280         for (i = 0; i < npages; i++) {
1281                 page = cfs_page_cpt_alloc(lnet_cpt_table(), cpt,
1282                                           GFP_KERNEL | __GFP_ZERO);
1283                 if (page == NULL) {
1284                         while (--i >= 0)
1285                                 __free_page(rb->rb_kiov[i].bv_page);
1286
1287                         LIBCFS_FREE(rb, sz);
1288                         return NULL;
1289                 }
1290
1291                 rb->rb_kiov[i].bv_len = PAGE_SIZE;
1292                 rb->rb_kiov[i].bv_offset = 0;
1293                 rb->rb_kiov[i].bv_page = page;
1294         }
1295
1296         return rb;
1297 }
1298
1299 static void
1300 lnet_rtrpool_free_bufs(struct lnet_rtrbufpool *rbp, int cpt)
1301 {
1302         int npages = rbp->rbp_npages;
1303         struct lnet_rtrbuf *rb;
1304         LIST_HEAD(tmp);
1305
1306         if (rbp->rbp_nbuffers == 0) /* not initialized or already freed */
1307                 return;
1308
1309         lnet_net_lock(cpt);
1310         list_splice_init(&rbp->rbp_msgs, &tmp);
1311         lnet_drop_routed_msgs_locked(&tmp, cpt);
1312         list_splice_init(&rbp->rbp_bufs, &tmp);
1313         rbp->rbp_req_nbuffers = 0;
1314         rbp->rbp_nbuffers = rbp->rbp_credits = 0;
1315         rbp->rbp_mincredits = 0;
1316         lnet_net_unlock(cpt);
1317
1318         /* Free buffers on the free list. */
1319         while (!list_empty(&tmp)) {
1320                 rb = list_entry(tmp.next, struct lnet_rtrbuf, rb_list);
1321                 list_del(&rb->rb_list);
1322                 lnet_destroy_rtrbuf(rb, npages);
1323         }
1324 }
1325
1326 static int
1327 lnet_rtrpool_adjust_bufs(struct lnet_rtrbufpool *rbp, int nbufs, int cpt)
1328 {
1329         LIST_HEAD(rb_list);
1330         struct lnet_rtrbuf *rb;
1331         int             num_rb;
1332         int             num_buffers = 0;
1333         int             old_req_nbufs;
1334         int             npages = rbp->rbp_npages;
1335
1336         lnet_net_lock(cpt);
1337         /* If we are called for less buffers than already in the pool, we
1338          * just lower the req_nbuffers number and excess buffers will be
1339          * thrown away as they are returned to the free list.  Credits
1340          * then get adjusted as well.
1341          * If we already have enough buffers allocated to serve the
1342          * increase requested, then we can treat that the same way as we
1343          * do the decrease. */
1344         num_rb = nbufs - rbp->rbp_nbuffers;
1345         if (nbufs <= rbp->rbp_req_nbuffers || num_rb <= 0) {
1346                 rbp->rbp_req_nbuffers = nbufs;
1347                 lnet_net_unlock(cpt);
1348                 return 0;
1349         }
1350         /* store the older value of rbp_req_nbuffers and then set it to
1351          * the new request to prevent lnet_return_rx_credits_locked() from
1352          * freeing buffers that we need to keep around */
1353         old_req_nbufs = rbp->rbp_req_nbuffers;
1354         rbp->rbp_req_nbuffers = nbufs;
1355         lnet_net_unlock(cpt);
1356
1357         /* allocate the buffers on a local list first.  If all buffers are
1358          * allocated successfully then join this list to the rbp buffer
1359          * list.  If not then free all allocated buffers. */
1360         while (num_rb-- > 0) {
1361                 rb = lnet_new_rtrbuf(rbp, cpt);
1362                 if (rb == NULL) {
1363                         CERROR("Failed to allocate %d route bufs of %d pages\n",
1364                                nbufs, npages);
1365
1366                         lnet_net_lock(cpt);
1367                         rbp->rbp_req_nbuffers = old_req_nbufs;
1368                         lnet_net_unlock(cpt);
1369
1370                         goto failed;
1371                 }
1372
1373                 list_add(&rb->rb_list, &rb_list);
1374                 num_buffers++;
1375         }
1376
1377         lnet_net_lock(cpt);
1378
1379         list_splice_tail(&rb_list, &rbp->rbp_bufs);
1380         rbp->rbp_nbuffers += num_buffers;
1381         rbp->rbp_credits += num_buffers;
1382         rbp->rbp_mincredits = rbp->rbp_credits;
1383         /* We need to schedule blocked msg using the newly
1384          * added buffers. */
1385         while (!list_empty(&rbp->rbp_bufs) &&
1386                !list_empty(&rbp->rbp_msgs))
1387                 lnet_schedule_blocked_locked(rbp);
1388
1389         lnet_net_unlock(cpt);
1390
1391         return 0;
1392
1393 failed:
1394         while (!list_empty(&rb_list)) {
1395                 rb = list_entry(rb_list.next, struct lnet_rtrbuf, rb_list);
1396                 list_del(&rb->rb_list);
1397                 lnet_destroy_rtrbuf(rb, npages);
1398         }
1399
1400         return -ENOMEM;
1401 }
1402
1403 static void
1404 lnet_rtrpool_init(struct lnet_rtrbufpool *rbp, int npages)
1405 {
1406         INIT_LIST_HEAD(&rbp->rbp_msgs);
1407         INIT_LIST_HEAD(&rbp->rbp_bufs);
1408
1409         rbp->rbp_npages = npages;
1410         rbp->rbp_credits = 0;
1411         rbp->rbp_mincredits = 0;
1412 }
1413
1414 void
1415 lnet_rtrpools_free(int keep_pools)
1416 {
1417         struct lnet_rtrbufpool *rtrp;
1418         int               i;
1419
1420         if (the_lnet.ln_rtrpools == NULL) /* uninitialized or freed */
1421                 return;
1422
1423         cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1424                 lnet_rtrpool_free_bufs(&rtrp[LNET_TINY_BUF_IDX], i);
1425                 lnet_rtrpool_free_bufs(&rtrp[LNET_SMALL_BUF_IDX], i);
1426                 lnet_rtrpool_free_bufs(&rtrp[LNET_LARGE_BUF_IDX], i);
1427         }
1428
1429         if (!keep_pools) {
1430                 cfs_percpt_free(the_lnet.ln_rtrpools);
1431                 the_lnet.ln_rtrpools = NULL;
1432         }
1433 }
1434
1435 static int
1436 lnet_nrb_tiny_calculate(void)
1437 {
1438         int     nrbs = LNET_NRB_TINY;
1439
1440         if (tiny_router_buffers < 0) {
1441                 LCONSOLE_ERROR_MSG(0x10c,
1442                                    "tiny_router_buffers=%d invalid when "
1443                                    "routing enabled\n", tiny_router_buffers);
1444                 return -EINVAL;
1445         }
1446
1447         if (tiny_router_buffers > 0)
1448                 nrbs = tiny_router_buffers;
1449
1450         nrbs /= LNET_CPT_NUMBER;
1451         return max(nrbs, LNET_NRB_TINY_MIN);
1452 }
1453
1454 static int
1455 lnet_nrb_small_calculate(void)
1456 {
1457         int     nrbs = LNET_NRB_SMALL;
1458
1459         if (small_router_buffers < 0) {
1460                 LCONSOLE_ERROR_MSG(0x10c,
1461                                    "small_router_buffers=%d invalid when "
1462                                    "routing enabled\n", small_router_buffers);
1463                 return -EINVAL;
1464         }
1465
1466         if (small_router_buffers > 0)
1467                 nrbs = small_router_buffers;
1468
1469         nrbs /= LNET_CPT_NUMBER;
1470         return max(nrbs, LNET_NRB_SMALL_MIN);
1471 }
1472
1473 static int
1474 lnet_nrb_large_calculate(void)
1475 {
1476         int     nrbs = LNET_NRB_LARGE;
1477
1478         if (large_router_buffers < 0) {
1479                 LCONSOLE_ERROR_MSG(0x10c,
1480                                    "large_router_buffers=%d invalid when "
1481                                    "routing enabled\n", large_router_buffers);
1482                 return -EINVAL;
1483         }
1484
1485         if (large_router_buffers > 0)
1486                 nrbs = large_router_buffers;
1487
1488         nrbs /= LNET_CPT_NUMBER;
1489         return max(nrbs, LNET_NRB_LARGE_MIN);
1490 }
1491
1492 int
1493 lnet_rtrpools_alloc(int im_a_router)
1494 {
1495         struct lnet_rtrbufpool *rtrp;
1496         int     nrb_tiny;
1497         int     nrb_small;
1498         int     nrb_large;
1499         int     rc;
1500         int     i;
1501
1502         if (!strcmp(forwarding, "")) {
1503                 /* not set either way */
1504                 if (!im_a_router)
1505                         return 0;
1506         } else if (!strcmp(forwarding, "disabled")) {
1507                 /* explicitly disabled */
1508                 return 0;
1509         } else if (!strcmp(forwarding, "enabled")) {
1510                 /* explicitly enabled */
1511         } else {
1512                 LCONSOLE_ERROR_MSG(0x10b, "'forwarding' not set to either "
1513                                    "'enabled' or 'disabled'\n");
1514                 return -EINVAL;
1515         }
1516
1517         nrb_tiny = lnet_nrb_tiny_calculate();
1518         if (nrb_tiny < 0)
1519                 return -EINVAL;
1520
1521         nrb_small = lnet_nrb_small_calculate();
1522         if (nrb_small < 0)
1523                 return -EINVAL;
1524
1525         nrb_large = lnet_nrb_large_calculate();
1526         if (nrb_large < 0)
1527                 return -EINVAL;
1528
1529         the_lnet.ln_rtrpools = cfs_percpt_alloc(lnet_cpt_table(),
1530                                                 LNET_NRBPOOLS *
1531                                                 sizeof(struct lnet_rtrbufpool));
1532         if (the_lnet.ln_rtrpools == NULL) {
1533                 LCONSOLE_ERROR_MSG(0x10c,
1534                                    "Failed to initialize router buffe pool\n");
1535                 return -ENOMEM;
1536         }
1537
1538         cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1539                 lnet_rtrpool_init(&rtrp[LNET_TINY_BUF_IDX], 0);
1540                 rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_TINY_BUF_IDX],
1541                                               nrb_tiny, i);
1542                 if (rc != 0)
1543                         goto failed;
1544
1545                 lnet_rtrpool_init(&rtrp[LNET_SMALL_BUF_IDX],
1546                                   LNET_NRB_SMALL_PAGES);
1547                 rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_SMALL_BUF_IDX],
1548                                               nrb_small, i);
1549                 if (rc != 0)
1550                         goto failed;
1551
1552                 lnet_rtrpool_init(&rtrp[LNET_LARGE_BUF_IDX],
1553                                   LNET_NRB_LARGE_PAGES);
1554                 rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_LARGE_BUF_IDX],
1555                                               nrb_large, i);
1556                 if (rc != 0)
1557                         goto failed;
1558         }
1559
1560         lnet_net_lock(LNET_LOCK_EX);
1561         the_lnet.ln_routing = 1;
1562         lnet_net_unlock(LNET_LOCK_EX);
1563         complete(&the_lnet.ln_mt_wait_complete);
1564         return 0;
1565
1566  failed:
1567         lnet_rtrpools_free(0);
1568         return rc;
1569 }
1570
1571 static int
1572 lnet_rtrpools_adjust_helper(int tiny, int small, int large)
1573 {
1574         int nrb = 0;
1575         int rc = 0;
1576         int i;
1577         struct lnet_rtrbufpool *rtrp;
1578
1579         /* If the provided values for each buffer pool are different than the
1580          * configured values, we need to take action. */
1581         if (tiny >= 0) {
1582                 tiny_router_buffers = tiny;
1583                 nrb = lnet_nrb_tiny_calculate();
1584                 cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1585                         rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_TINY_BUF_IDX],
1586                                                       nrb, i);
1587                         if (rc != 0)
1588                                 return rc;
1589                 }
1590         }
1591         if (small >= 0) {
1592                 small_router_buffers = small;
1593                 nrb = lnet_nrb_small_calculate();
1594                 cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1595                         rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_SMALL_BUF_IDX],
1596                                                       nrb, i);
1597                         if (rc != 0)
1598                                 return rc;
1599                 }
1600         }
1601         if (large >= 0) {
1602                 large_router_buffers = large;
1603                 nrb = lnet_nrb_large_calculate();
1604                 cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1605                         rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_LARGE_BUF_IDX],
1606                                                       nrb, i);
1607                         if (rc != 0)
1608                                 return rc;
1609                 }
1610         }
1611
1612         return 0;
1613 }
1614
1615 int
1616 lnet_rtrpools_adjust(int tiny, int small, int large)
1617 {
1618         /* this function doesn't revert the changes if adding new buffers
1619          * failed.  It's up to the user space caller to revert the
1620          * changes. */
1621
1622         if (!the_lnet.ln_routing)
1623                 return 0;
1624
1625         return lnet_rtrpools_adjust_helper(tiny, small, large);
1626 }
1627
1628 int
1629 lnet_rtrpools_enable(void)
1630 {
1631         int rc = 0;
1632
1633         if (the_lnet.ln_routing)
1634                 return 0;
1635
1636         if (the_lnet.ln_rtrpools == NULL)
1637                 /* If routing is turned off, and we have never
1638                  * initialized the pools before, just call the
1639                  * standard buffer pool allocation routine as
1640                  * if we are just configuring this for the first
1641                  * time. */
1642                 rc = lnet_rtrpools_alloc(1);
1643         else
1644                 rc = lnet_rtrpools_adjust_helper(0, 0, 0);
1645         if (rc != 0)
1646                 return rc;
1647
1648         lnet_net_lock(LNET_LOCK_EX);
1649         the_lnet.ln_routing = 1;
1650
1651         the_lnet.ln_ping_target->pb_info.pi_features &=
1652                 ~LNET_PING_FEAT_RTE_DISABLED;
1653         lnet_net_unlock(LNET_LOCK_EX);
1654
1655         if (lnet_peer_discovery_disabled)
1656                 CWARN("Consider turning discovery on to enable full "
1657                       "Multi-Rail routing functionality\n");
1658
1659         return rc;
1660 }
1661
1662 void
1663 lnet_rtrpools_disable(void)
1664 {
1665         if (!the_lnet.ln_routing)
1666                 return;
1667
1668         lnet_net_lock(LNET_LOCK_EX);
1669         the_lnet.ln_routing = 0;
1670         the_lnet.ln_ping_target->pb_info.pi_features |=
1671                 LNET_PING_FEAT_RTE_DISABLED;
1672
1673         tiny_router_buffers = 0;
1674         small_router_buffers = 0;
1675         large_router_buffers = 0;
1676         lnet_net_unlock(LNET_LOCK_EX);
1677         lnet_rtrpools_free(1);
1678 }
1679
1680 static inline void
1681 lnet_notify_peer_down(struct lnet_ni *ni, lnet_nid_t nid)
1682 {
1683         if (ni->ni_net->net_lnd->lnd_notify_peer_down != NULL)
1684                 (ni->ni_net->net_lnd->lnd_notify_peer_down)(nid);
1685 }
1686
1687 /*
1688  * ni: local NI used to communicate with the peer
1689  * nid: peer NID
1690  * alive: true if peer is alive, false otherwise
1691  * reset: reset health value. This is requested by the LND.
1692  * when: notificaiton time.
1693  */
1694 int
1695 lnet_notify(struct lnet_ni *ni, lnet_nid_t nid, bool alive, bool reset,
1696             time64_t when)
1697 {
1698         struct lnet_peer_ni *lpni = NULL;
1699         struct lnet_route *route;
1700         struct lnet_peer *lp;
1701         time64_t now = ktime_get_seconds();
1702         int cpt;
1703
1704         LASSERT(!in_interrupt());
1705
1706         CDEBUG(D_NET, "%s notifying %s: %s\n",
1707                (ni == NULL) ? "userspace" : libcfs_nid2str(ni->ni_nid),
1708                libcfs_nid2str(nid), alive ? "up" : "down");
1709
1710         if (ni != NULL &&
1711             LNET_NIDNET(ni->ni_nid) != LNET_NIDNET(nid)) {
1712                 CWARN("Ignoring notification of %s %s by %s (different net)\n",
1713                       libcfs_nid2str(nid), alive ? "birth" : "death",
1714                       libcfs_nid2str(ni->ni_nid));
1715                 return -EINVAL;
1716         }
1717
1718         /* can't do predictions... */
1719         if (when > now) {
1720                 CWARN("Ignoring prediction from %s of %s %s "
1721                       "%lld seconds in the future\n",
1722                       (ni == NULL) ? "userspace" : libcfs_nid2str(ni->ni_nid),
1723                       libcfs_nid2str(nid), alive ? "up" : "down", when - now);
1724                 return -EINVAL;
1725         }
1726
1727         if (ni != NULL && !alive &&             /* LND telling me she's down */
1728             !auto_down) {                       /* auto-down disabled */
1729                 CDEBUG(D_NET, "Auto-down disabled\n");
1730                 return 0;
1731         }
1732
1733         /* must lock 0 since this is used for synchronization */
1734         lnet_net_lock(0);
1735
1736         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
1737                 lnet_net_unlock(0);
1738                 return -ESHUTDOWN;
1739         }
1740
1741         lpni = lnet_find_peer_ni_locked(nid);
1742         if (lpni == NULL) {
1743                 /* nid not found */
1744                 lnet_net_unlock(0);
1745                 CDEBUG(D_NET, "%s not found\n", libcfs_nid2str(nid));
1746                 return 0;
1747         }
1748
1749         if (alive) {
1750                 if (reset) {
1751                         lpni->lpni_ns_status = LNET_NI_STATUS_UP;
1752                         lnet_set_lpni_healthv_locked(lpni,
1753                                                      LNET_MAX_HEALTH_VALUE);
1754                 } else {
1755                         __u32 sensitivity = lpni->lpni_peer_net->
1756                                         lpn_peer->lp_health_sensitivity;
1757
1758                         lnet_inc_lpni_healthv_locked(lpni,
1759                                         (sensitivity) ? sensitivity :
1760                                         lnet_health_sensitivity);
1761                 }
1762         } else if (reset) {
1763                 lpni->lpni_ns_status = LNET_NI_STATUS_DOWN;
1764         }
1765
1766         /* recalculate aliveness */
1767         alive = lnet_is_peer_ni_alive(lpni);
1768
1769         lp = lpni->lpni_peer_net->lpn_peer;
1770         /* If this is an LNet router then update route aliveness */
1771         if (lp->lp_rtr_refcount) {
1772                 if (reset)
1773                         /* reset flag indicates gateway peer went up or down */
1774                         lp->lp_alive = alive;
1775
1776                 /* If discovery is disabled, locally or on the gateway, then
1777                  * any routes using lpni as next-hop need to be updated
1778                  *
1779                  * NB: We can get many notifications while a route is down, so
1780                  * we try and avoid the expensive net_lock/EX here for the
1781                  * common case of receiving duplicate lnet_notify() calls (i.e.
1782                  * only grab EX lock when we actually need to update the route
1783                  * aliveness).
1784                  */
1785                 if (lnet_is_discovery_disabled(lp)) {
1786                         list_for_each_entry(route, &lp->lp_routes, lr_gwlist) {
1787                                 if (route->lr_nid == lpni->lpni_nid)
1788                                         lnet_set_route_aliveness(route, alive);
1789                         }
1790                 }
1791         }
1792
1793         lnet_net_unlock(0);
1794
1795         if (ni != NULL && !alive)
1796                 lnet_notify_peer_down(ni, lpni->lpni_nid);
1797
1798         cpt = lpni->lpni_cpt;
1799         lnet_net_lock(cpt);
1800         lnet_peer_ni_decref_locked(lpni);
1801         lnet_net_unlock(cpt);
1802
1803         return 0;
1804 }
1805 EXPORT_SYMBOL(lnet_notify);