xref: /linux/net/ipv4/nexthop.c (revision f4cdf7ca9a1fdcca413157df19753f388a5a224e)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Generic nexthop implementation
3  *
4  * Copyright (c) 2017-19 Cumulus Networks
5  * Copyright (c) 2017-19 David Ahern <dsa@cumulusnetworks.com>
6  */
7 
8 #include <linux/nexthop.h>
9 #include <linux/rtnetlink.h>
10 #include <linux/slab.h>
11 #include <linux/vmalloc.h>
12 #include <net/arp.h>
13 #include <net/ip6_route.h>
14 #include <net/lwtunnel.h>
15 #include <net/ndisc.h>
16 #include <net/nexthop.h>
17 #include <net/route.h>
18 #include <net/sock.h>
19 
20 #define NH_RES_DEFAULT_IDLE_TIMER	(120 * HZ)
21 #define NH_RES_DEFAULT_UNBALANCED_TIMER	0	/* No forced rebalancing. */
22 
23 static bool __must_check remove_nexthop(struct net *net, struct nexthop *nh,
24 					struct nl_info *nlinfo);
25 
26 #define NH_DEV_HASHBITS  8
27 #define NH_DEV_HASHSIZE (1U << NH_DEV_HASHBITS)
28 
29 #define NHA_OP_FLAGS_DUMP_ALL (NHA_OP_FLAG_DUMP_STATS |		\
30 			       NHA_OP_FLAG_DUMP_HW_STATS)
31 
32 static const struct nla_policy rtm_nh_policy_new[] = {
33 	[NHA_ID]		= { .type = NLA_U32 },
34 	[NHA_GROUP]		= { .type = NLA_BINARY },
35 	[NHA_GROUP_TYPE]	= { .type = NLA_U16 },
36 	[NHA_BLACKHOLE]		= { .type = NLA_FLAG },
37 	[NHA_OIF]		= { .type = NLA_U32 },
38 	[NHA_GATEWAY]		= { .type = NLA_BINARY },
39 	[NHA_ENCAP_TYPE]	= { .type = NLA_U16 },
40 	[NHA_ENCAP]		= { .type = NLA_NESTED },
41 	[NHA_FDB]		= { .type = NLA_FLAG },
42 	[NHA_RES_GROUP]		= { .type = NLA_NESTED },
43 	[NHA_HW_STATS_ENABLE]	= NLA_POLICY_MAX(NLA_U32, true),
44 };
45 
46 static const struct nla_policy rtm_nh_policy_get[] = {
47 	[NHA_ID]		= { .type = NLA_U32 },
48 	[NHA_OP_FLAGS]		= NLA_POLICY_MASK(NLA_U32,
49 						  NHA_OP_FLAGS_DUMP_ALL),
50 };
51 
52 static const struct nla_policy rtm_nh_policy_del[] = {
53 	[NHA_ID]		= { .type = NLA_U32 },
54 };
55 
56 static const struct nla_policy rtm_nh_policy_dump[] = {
57 	[NHA_OIF]		= { .type = NLA_U32 },
58 	[NHA_GROUPS]		= { .type = NLA_FLAG },
59 	[NHA_MASTER]		= { .type = NLA_U32 },
60 	[NHA_FDB]		= { .type = NLA_FLAG },
61 	[NHA_OP_FLAGS]		= NLA_POLICY_MASK(NLA_U32,
62 						  NHA_OP_FLAGS_DUMP_ALL),
63 };
64 
65 static const struct nla_policy rtm_nh_res_policy_new[] = {
66 	[NHA_RES_GROUP_BUCKETS]			= { .type = NLA_U16 },
67 	[NHA_RES_GROUP_IDLE_TIMER]		= { .type = NLA_U32 },
68 	[NHA_RES_GROUP_UNBALANCED_TIMER]	= { .type = NLA_U32 },
69 };
70 
71 static const struct nla_policy rtm_nh_policy_dump_bucket[] = {
72 	[NHA_ID]		= { .type = NLA_U32 },
73 	[NHA_OIF]		= { .type = NLA_U32 },
74 	[NHA_MASTER]		= { .type = NLA_U32 },
75 	[NHA_RES_BUCKET]	= { .type = NLA_NESTED },
76 };
77 
78 static const struct nla_policy rtm_nh_res_bucket_policy_dump[] = {
79 	[NHA_RES_BUCKET_NH_ID]	= { .type = NLA_U32 },
80 };
81 
82 static const struct nla_policy rtm_nh_policy_get_bucket[] = {
83 	[NHA_ID]		= { .type = NLA_U32 },
84 	[NHA_RES_BUCKET]	= { .type = NLA_NESTED },
85 };
86 
87 static const struct nla_policy rtm_nh_res_bucket_policy_get[] = {
88 	[NHA_RES_BUCKET_INDEX]	= { .type = NLA_U16 },
89 };
90 
91 static bool nexthop_notifiers_is_empty(struct net *net)
92 {
93 	return !net->nexthop.notifier_chain.head;
94 }
95 
96 static void
97 __nh_notifier_single_info_init(struct nh_notifier_single_info *nh_info,
98 			       const struct nh_info *nhi)
99 {
100 	nh_info->dev = nhi->fib_nhc.nhc_dev;
101 	nh_info->gw_family = nhi->fib_nhc.nhc_gw_family;
102 	if (nh_info->gw_family == AF_INET)
103 		nh_info->ipv4 = nhi->fib_nhc.nhc_gw.ipv4;
104 	else if (nh_info->gw_family == AF_INET6)
105 		nh_info->ipv6 = nhi->fib_nhc.nhc_gw.ipv6;
106 
107 	nh_info->id = nhi->nh_parent->id;
108 	nh_info->is_reject = nhi->reject_nh;
109 	nh_info->is_fdb = nhi->fdb_nh;
110 	nh_info->has_encap = !!nhi->fib_nhc.nhc_lwtstate;
111 }
112 
113 static int nh_notifier_single_info_init(struct nh_notifier_info *info,
114 					const struct nexthop *nh)
115 {
116 	struct nh_info *nhi = rtnl_dereference(nh->nh_info);
117 
118 	info->type = NH_NOTIFIER_INFO_TYPE_SINGLE;
119 	info->nh = kzalloc_obj(*info->nh);
120 	if (!info->nh)
121 		return -ENOMEM;
122 
123 	__nh_notifier_single_info_init(info->nh, nhi);
124 
125 	return 0;
126 }
127 
128 static void nh_notifier_single_info_fini(struct nh_notifier_info *info)
129 {
130 	kfree(info->nh);
131 }
132 
133 static int nh_notifier_mpath_info_init(struct nh_notifier_info *info,
134 				       struct nh_group *nhg)
135 {
136 	u16 num_nh = nhg->num_nh;
137 	int i;
138 
139 	info->type = NH_NOTIFIER_INFO_TYPE_GRP;
140 	info->nh_grp = kzalloc_flex(*info->nh_grp, nh_entries, num_nh);
141 	if (!info->nh_grp)
142 		return -ENOMEM;
143 
144 	info->nh_grp->num_nh = num_nh;
145 	info->nh_grp->is_fdb = nhg->fdb_nh;
146 	info->nh_grp->hw_stats = nhg->hw_stats;
147 
148 	for (i = 0; i < num_nh; i++) {
149 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
150 		struct nh_info *nhi;
151 
152 		nhi = rtnl_dereference(nhge->nh->nh_info);
153 		info->nh_grp->nh_entries[i].weight = nhge->weight;
154 		__nh_notifier_single_info_init(&info->nh_grp->nh_entries[i].nh,
155 					       nhi);
156 	}
157 
158 	return 0;
159 }
160 
161 static int nh_notifier_res_table_info_init(struct nh_notifier_info *info,
162 					   struct nh_group *nhg)
163 {
164 	struct nh_res_table *res_table = rtnl_dereference(nhg->res_table);
165 	u16 num_nh_buckets = res_table->num_nh_buckets;
166 	unsigned long size;
167 	u16 i;
168 
169 	info->type = NH_NOTIFIER_INFO_TYPE_RES_TABLE;
170 	size = struct_size(info->nh_res_table, nhs, num_nh_buckets);
171 	info->nh_res_table = __vmalloc(size, GFP_KERNEL | __GFP_ZERO |
172 				       __GFP_NOWARN);
173 	if (!info->nh_res_table)
174 		return -ENOMEM;
175 
176 	info->nh_res_table->num_nh_buckets = num_nh_buckets;
177 	info->nh_res_table->hw_stats = nhg->hw_stats;
178 
179 	for (i = 0; i < num_nh_buckets; i++) {
180 		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
181 		struct nh_grp_entry *nhge;
182 		struct nh_info *nhi;
183 
184 		nhge = rtnl_dereference(bucket->nh_entry);
185 		nhi = rtnl_dereference(nhge->nh->nh_info);
186 		__nh_notifier_single_info_init(&info->nh_res_table->nhs[i],
187 					       nhi);
188 	}
189 
190 	return 0;
191 }
192 
193 static int nh_notifier_grp_info_init(struct nh_notifier_info *info,
194 				     const struct nexthop *nh)
195 {
196 	struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
197 
198 	if (nhg->hash_threshold)
199 		return nh_notifier_mpath_info_init(info, nhg);
200 	else if (nhg->resilient)
201 		return nh_notifier_res_table_info_init(info, nhg);
202 	return -EINVAL;
203 }
204 
205 static void nh_notifier_grp_info_fini(struct nh_notifier_info *info,
206 				      const struct nexthop *nh)
207 {
208 	struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
209 
210 	if (nhg->hash_threshold)
211 		kfree(info->nh_grp);
212 	else if (nhg->resilient)
213 		vfree(info->nh_res_table);
214 }
215 
216 static int nh_notifier_info_init(struct nh_notifier_info *info,
217 				 const struct nexthop *nh)
218 {
219 	info->id = nh->id;
220 
221 	if (nh->is_group)
222 		return nh_notifier_grp_info_init(info, nh);
223 	else
224 		return nh_notifier_single_info_init(info, nh);
225 }
226 
227 static void nh_notifier_info_fini(struct nh_notifier_info *info,
228 				  const struct nexthop *nh)
229 {
230 	if (nh->is_group)
231 		nh_notifier_grp_info_fini(info, nh);
232 	else
233 		nh_notifier_single_info_fini(info);
234 }
235 
236 static int call_nexthop_notifiers(struct net *net,
237 				  enum nexthop_event_type event_type,
238 				  struct nexthop *nh,
239 				  struct netlink_ext_ack *extack)
240 {
241 	struct nh_notifier_info info = {
242 		.net = net,
243 		.extack = extack,
244 	};
245 	int err;
246 
247 	ASSERT_RTNL();
248 
249 	if (nexthop_notifiers_is_empty(net))
250 		return 0;
251 
252 	err = nh_notifier_info_init(&info, nh);
253 	if (err) {
254 		NL_SET_ERR_MSG(extack, "Failed to initialize nexthop notifier info");
255 		return err;
256 	}
257 
258 	err = blocking_notifier_call_chain(&net->nexthop.notifier_chain,
259 					   event_type, &info);
260 	nh_notifier_info_fini(&info, nh);
261 
262 	return notifier_to_errno(err);
263 }
264 
265 static int
266 nh_notifier_res_bucket_idle_timer_get(const struct nh_notifier_info *info,
267 				      bool force, unsigned int *p_idle_timer_ms)
268 {
269 	struct nh_res_table *res_table;
270 	struct nh_group *nhg;
271 	struct nexthop *nh;
272 	int err = 0;
273 
274 	/* When 'force' is false, nexthop bucket replacement is performed
275 	 * because the bucket was deemed to be idle. In this case, capable
276 	 * listeners can choose to perform an atomic replacement: The bucket is
277 	 * only replaced if it is inactive. However, if the idle timer interval
278 	 * is smaller than the interval in which a listener is querying
279 	 * buckets' activity from the device, then atomic replacement should
280 	 * not be tried. Pass the idle timer value to listeners, so that they
281 	 * could determine which type of replacement to perform.
282 	 */
283 	if (force) {
284 		*p_idle_timer_ms = 0;
285 		return 0;
286 	}
287 
288 	rcu_read_lock();
289 
290 	nh = nexthop_find_by_id(info->net, info->id);
291 	if (!nh) {
292 		err = -EINVAL;
293 		goto out;
294 	}
295 
296 	nhg = rcu_dereference(nh->nh_grp);
297 	res_table = rcu_dereference(nhg->res_table);
298 	*p_idle_timer_ms = jiffies_to_msecs(res_table->idle_timer);
299 
300 out:
301 	rcu_read_unlock();
302 
303 	return err;
304 }
305 
306 static int nh_notifier_res_bucket_info_init(struct nh_notifier_info *info,
307 					    u16 bucket_index, bool force,
308 					    struct nh_info *oldi,
309 					    struct nh_info *newi)
310 {
311 	unsigned int idle_timer_ms;
312 	int err;
313 
314 	err = nh_notifier_res_bucket_idle_timer_get(info, force,
315 						    &idle_timer_ms);
316 	if (err)
317 		return err;
318 
319 	info->type = NH_NOTIFIER_INFO_TYPE_RES_BUCKET;
320 	info->nh_res_bucket = kzalloc_obj(*info->nh_res_bucket);
321 	if (!info->nh_res_bucket)
322 		return -ENOMEM;
323 
324 	info->nh_res_bucket->bucket_index = bucket_index;
325 	info->nh_res_bucket->idle_timer_ms = idle_timer_ms;
326 	info->nh_res_bucket->force = force;
327 	__nh_notifier_single_info_init(&info->nh_res_bucket->old_nh, oldi);
328 	__nh_notifier_single_info_init(&info->nh_res_bucket->new_nh, newi);
329 	return 0;
330 }
331 
332 static void nh_notifier_res_bucket_info_fini(struct nh_notifier_info *info)
333 {
334 	kfree(info->nh_res_bucket);
335 }
336 
337 static int __call_nexthop_res_bucket_notifiers(struct net *net, u32 nhg_id,
338 					       u16 bucket_index, bool force,
339 					       struct nh_info *oldi,
340 					       struct nh_info *newi,
341 					       struct netlink_ext_ack *extack)
342 {
343 	struct nh_notifier_info info = {
344 		.net = net,
345 		.extack = extack,
346 		.id = nhg_id,
347 	};
348 	int err;
349 
350 	if (nexthop_notifiers_is_empty(net))
351 		return 0;
352 
353 	err = nh_notifier_res_bucket_info_init(&info, bucket_index, force,
354 					       oldi, newi);
355 	if (err)
356 		return err;
357 
358 	err = blocking_notifier_call_chain(&net->nexthop.notifier_chain,
359 					   NEXTHOP_EVENT_BUCKET_REPLACE, &info);
360 	nh_notifier_res_bucket_info_fini(&info);
361 
362 	return notifier_to_errno(err);
363 }
364 
365 /* There are three users of RES_TABLE, and NHs etc. referenced from there:
366  *
367  * 1) a collection of callbacks for NH maintenance. This operates under
368  *    RTNL,
369  * 2) the delayed work that gradually balances the resilient table,
370  * 3) and nexthop_select_path(), operating under RCU.
371  *
372  * Both the delayed work and the RTNL block are writers, and need to
373  * maintain mutual exclusion. Since there are only two and well-known
374  * writers for each table, the RTNL code can make sure it has exclusive
375  * access thus:
376  *
377  * - Have the DW operate without locking;
378  * - synchronously cancel the DW;
379  * - do the writing;
380  * - if the write was not actually a delete, call upkeep, which schedules
381  *   DW again if necessary.
382  *
383  * The functions that are always called from the RTNL context use
384  * rtnl_dereference(). The functions that can also be called from the DW do
385  * a raw dereference and rely on the above mutual exclusion scheme.
386  */
387 #define nh_res_dereference(p) (rcu_dereference_raw(p))
388 
389 static int call_nexthop_res_bucket_notifiers(struct net *net, u32 nhg_id,
390 					     u16 bucket_index, bool force,
391 					     struct nexthop *old_nh,
392 					     struct nexthop *new_nh,
393 					     struct netlink_ext_ack *extack)
394 {
395 	struct nh_info *oldi = nh_res_dereference(old_nh->nh_info);
396 	struct nh_info *newi = nh_res_dereference(new_nh->nh_info);
397 
398 	return __call_nexthop_res_bucket_notifiers(net, nhg_id, bucket_index,
399 						   force, oldi, newi, extack);
400 }
401 
402 static int call_nexthop_res_table_notifiers(struct net *net, struct nexthop *nh,
403 					    struct netlink_ext_ack *extack)
404 {
405 	struct nh_notifier_info info = {
406 		.net = net,
407 		.extack = extack,
408 		.id = nh->id,
409 	};
410 	struct nh_group *nhg;
411 	int err;
412 
413 	ASSERT_RTNL();
414 
415 	if (nexthop_notifiers_is_empty(net))
416 		return 0;
417 
418 	/* At this point, the nexthop buckets are still not populated. Only
419 	 * emit a notification with the logical nexthops, so that a listener
420 	 * could potentially veto it in case of unsupported configuration.
421 	 */
422 	nhg = rtnl_dereference(nh->nh_grp);
423 	err = nh_notifier_mpath_info_init(&info, nhg);
424 	if (err) {
425 		NL_SET_ERR_MSG(extack, "Failed to initialize nexthop notifier info");
426 		return err;
427 	}
428 
429 	err = blocking_notifier_call_chain(&net->nexthop.notifier_chain,
430 					   NEXTHOP_EVENT_RES_TABLE_PRE_REPLACE,
431 					   &info);
432 	kfree(info.nh_grp);
433 
434 	return notifier_to_errno(err);
435 }
436 
437 static int call_nexthop_notifier(struct notifier_block *nb, struct net *net,
438 				 enum nexthop_event_type event_type,
439 				 struct nexthop *nh,
440 				 struct netlink_ext_ack *extack)
441 {
442 	struct nh_notifier_info info = {
443 		.net = net,
444 		.extack = extack,
445 	};
446 	int err;
447 
448 	err = nh_notifier_info_init(&info, nh);
449 	if (err)
450 		return err;
451 
452 	err = nb->notifier_call(nb, event_type, &info);
453 	nh_notifier_info_fini(&info, nh);
454 
455 	return notifier_to_errno(err);
456 }
457 
458 static unsigned int nh_dev_hashfn(unsigned int val)
459 {
460 	unsigned int mask = NH_DEV_HASHSIZE - 1;
461 
462 	return (val ^
463 		(val >> NH_DEV_HASHBITS) ^
464 		(val >> (NH_DEV_HASHBITS * 2))) & mask;
465 }
466 
467 static void nexthop_devhash_add(struct net *net, struct nh_info *nhi)
468 {
469 	struct net_device *dev = nhi->fib_nhc.nhc_dev;
470 	struct hlist_head *head;
471 	unsigned int hash;
472 
473 	WARN_ON(!dev);
474 
475 	hash = nh_dev_hashfn(dev->ifindex);
476 	head = &net->nexthop.devhash[hash];
477 	hlist_add_head(&nhi->dev_hash, head);
478 }
479 
480 static void nexthop_free_group(struct nexthop *nh)
481 {
482 	struct nh_group *nhg;
483 	int i;
484 
485 	nhg = rcu_dereference_raw(nh->nh_grp);
486 	for (i = 0; i < nhg->num_nh; ++i) {
487 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
488 
489 		WARN_ON(!list_empty(&nhge->nh_list));
490 		free_percpu(nhge->stats);
491 		nexthop_put(nhge->nh);
492 	}
493 
494 	WARN_ON(nhg->spare == nhg);
495 
496 	if (nhg->resilient)
497 		vfree(rcu_dereference_raw(nhg->res_table));
498 
499 	kfree(nhg->spare);
500 	kfree(nhg);
501 }
502 
503 static void nexthop_free_single(struct nexthop *nh)
504 {
505 	struct nh_info *nhi;
506 
507 	nhi = rcu_dereference_raw(nh->nh_info);
508 	switch (nhi->family) {
509 	case AF_INET:
510 		fib_nh_release(nh->net, &nhi->fib_nh);
511 		break;
512 	case AF_INET6:
513 		fib6_nh_release(&nhi->fib6_nh);
514 		break;
515 	}
516 	kfree(nhi);
517 }
518 
519 void nexthop_free_rcu(struct rcu_head *head)
520 {
521 	struct nexthop *nh = container_of(head, struct nexthop, rcu);
522 
523 	if (nh->is_group)
524 		nexthop_free_group(nh);
525 	else
526 		nexthop_free_single(nh);
527 
528 	kfree(nh);
529 }
530 EXPORT_SYMBOL_GPL(nexthop_free_rcu);
531 
532 static struct nexthop *nexthop_alloc(void)
533 {
534 	struct nexthop *nh;
535 
536 	nh = kzalloc_obj(struct nexthop);
537 	if (nh) {
538 		INIT_LIST_HEAD(&nh->fi_list);
539 		INIT_LIST_HEAD(&nh->f6i_list);
540 		INIT_LIST_HEAD(&nh->grp_list);
541 		INIT_LIST_HEAD(&nh->fdb_list);
542 		spin_lock_init(&nh->lock);
543 	}
544 	return nh;
545 }
546 
547 static struct nh_group *nexthop_grp_alloc(u16 num_nh)
548 {
549 	struct nh_group *nhg;
550 
551 	nhg = kzalloc_flex(*nhg, nh_entries, num_nh);
552 	if (nhg)
553 		nhg->num_nh = num_nh;
554 
555 	return nhg;
556 }
557 
558 static void nh_res_table_upkeep_dw(struct work_struct *work);
559 
560 static struct nh_res_table *
561 nexthop_res_table_alloc(struct net *net, u32 nhg_id, struct nh_config *cfg)
562 {
563 	const u16 num_nh_buckets = cfg->nh_grp_res_num_buckets;
564 	struct nh_res_table *res_table;
565 	unsigned long size;
566 
567 	size = struct_size(res_table, nh_buckets, num_nh_buckets);
568 	res_table = __vmalloc(size, GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN);
569 	if (!res_table)
570 		return NULL;
571 
572 	res_table->net = net;
573 	res_table->nhg_id = nhg_id;
574 	INIT_DELAYED_WORK(&res_table->upkeep_dw, &nh_res_table_upkeep_dw);
575 	INIT_LIST_HEAD(&res_table->uw_nh_entries);
576 	res_table->idle_timer = cfg->nh_grp_res_idle_timer;
577 	res_table->unbalanced_timer = cfg->nh_grp_res_unbalanced_timer;
578 	res_table->num_nh_buckets = num_nh_buckets;
579 	return res_table;
580 }
581 
582 static void nh_base_seq_inc(struct net *net)
583 {
584 	while (++net->nexthop.seq == 0)
585 		;
586 }
587 
588 /* no reference taken; rcu lock or rtnl must be held */
589 struct nexthop *nexthop_find_by_id(struct net *net, u32 id)
590 {
591 	struct rb_node **pp, *parent = NULL, *next;
592 
593 	pp = &net->nexthop.rb_root.rb_node;
594 	while (1) {
595 		struct nexthop *nh;
596 
597 		next = rcu_dereference_raw(*pp);
598 		if (!next)
599 			break;
600 		parent = next;
601 
602 		nh = rb_entry(parent, struct nexthop, rb_node);
603 		if (id < nh->id)
604 			pp = &next->rb_left;
605 		else if (id > nh->id)
606 			pp = &next->rb_right;
607 		else
608 			return nh;
609 	}
610 	return NULL;
611 }
612 EXPORT_SYMBOL_GPL(nexthop_find_by_id);
613 
614 /* used for auto id allocation; called with rtnl held */
615 static u32 nh_find_unused_id(struct net *net)
616 {
617 	u32 id_start = net->nexthop.last_id_allocated;
618 
619 	while (1) {
620 		net->nexthop.last_id_allocated++;
621 		if (net->nexthop.last_id_allocated == id_start)
622 			break;
623 
624 		if (!nexthop_find_by_id(net, net->nexthop.last_id_allocated))
625 			return net->nexthop.last_id_allocated;
626 	}
627 	return 0;
628 }
629 
630 static void nh_res_time_set_deadline(unsigned long next_time,
631 				     unsigned long *deadline)
632 {
633 	if (time_before(next_time, *deadline))
634 		*deadline = next_time;
635 }
636 
637 static clock_t nh_res_table_unbalanced_time(struct nh_res_table *res_table)
638 {
639 	if (list_empty(&res_table->uw_nh_entries))
640 		return 0;
641 	return jiffies_delta_to_clock_t(jiffies - res_table->unbalanced_since);
642 }
643 
644 static int nla_put_nh_group_res(struct sk_buff *skb, struct nh_group *nhg)
645 {
646 	struct nh_res_table *res_table = rtnl_dereference(nhg->res_table);
647 	struct nlattr *nest;
648 
649 	nest = nla_nest_start(skb, NHA_RES_GROUP);
650 	if (!nest)
651 		return -EMSGSIZE;
652 
653 	if (nla_put_u16(skb, NHA_RES_GROUP_BUCKETS,
654 			res_table->num_nh_buckets) ||
655 	    nla_put_u32(skb, NHA_RES_GROUP_IDLE_TIMER,
656 			jiffies_to_clock_t(res_table->idle_timer)) ||
657 	    nla_put_u32(skb, NHA_RES_GROUP_UNBALANCED_TIMER,
658 			jiffies_to_clock_t(res_table->unbalanced_timer)) ||
659 	    nla_put_u64_64bit(skb, NHA_RES_GROUP_UNBALANCED_TIME,
660 			      nh_res_table_unbalanced_time(res_table),
661 			      NHA_RES_GROUP_PAD))
662 		goto nla_put_failure;
663 
664 	nla_nest_end(skb, nest);
665 	return 0;
666 
667 nla_put_failure:
668 	nla_nest_cancel(skb, nest);
669 	return -EMSGSIZE;
670 }
671 
672 static void nh_grp_entry_stats_inc(struct nh_grp_entry *nhge)
673 {
674 	struct nh_grp_entry_stats *cpu_stats;
675 
676 	cpu_stats = get_cpu_ptr(nhge->stats);
677 	u64_stats_update_begin(&cpu_stats->syncp);
678 	u64_stats_inc(&cpu_stats->packets);
679 	u64_stats_update_end(&cpu_stats->syncp);
680 	put_cpu_ptr(cpu_stats);
681 }
682 
683 static void nh_grp_entry_stats_read(struct nh_grp_entry *nhge,
684 				    u64 *ret_packets)
685 {
686 	int i;
687 
688 	*ret_packets = 0;
689 
690 	for_each_possible_cpu(i) {
691 		struct nh_grp_entry_stats *cpu_stats;
692 		unsigned int start;
693 		u64 packets;
694 
695 		cpu_stats = per_cpu_ptr(nhge->stats, i);
696 		do {
697 			start = u64_stats_fetch_begin(&cpu_stats->syncp);
698 			packets = u64_stats_read(&cpu_stats->packets);
699 		} while (u64_stats_fetch_retry(&cpu_stats->syncp, start));
700 
701 		*ret_packets += packets;
702 	}
703 }
704 
705 static int nh_notifier_grp_hw_stats_init(struct nh_notifier_info *info,
706 					 const struct nexthop *nh)
707 {
708 	struct nh_group *nhg;
709 	int i;
710 
711 	ASSERT_RTNL();
712 	nhg = rtnl_dereference(nh->nh_grp);
713 
714 	info->id = nh->id;
715 	info->type = NH_NOTIFIER_INFO_TYPE_GRP_HW_STATS;
716 	info->nh_grp_hw_stats = kzalloc_flex(*info->nh_grp_hw_stats, stats,
717 					     nhg->num_nh);
718 	if (!info->nh_grp_hw_stats)
719 		return -ENOMEM;
720 
721 	info->nh_grp_hw_stats->num_nh = nhg->num_nh;
722 	for (i = 0; i < nhg->num_nh; i++) {
723 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
724 
725 		info->nh_grp_hw_stats->stats[i].id = nhge->nh->id;
726 	}
727 
728 	return 0;
729 }
730 
731 static void nh_notifier_grp_hw_stats_fini(struct nh_notifier_info *info)
732 {
733 	kfree(info->nh_grp_hw_stats);
734 }
735 
736 void nh_grp_hw_stats_report_delta(struct nh_notifier_grp_hw_stats_info *info,
737 				  unsigned int nh_idx,
738 				  u64 delta_packets)
739 {
740 	info->hw_stats_used = true;
741 	info->stats[nh_idx].packets += delta_packets;
742 }
743 EXPORT_SYMBOL(nh_grp_hw_stats_report_delta);
744 
745 static void nh_grp_hw_stats_apply_update(struct nexthop *nh,
746 					 struct nh_notifier_info *info)
747 {
748 	struct nh_group *nhg;
749 	int i;
750 
751 	ASSERT_RTNL();
752 	nhg = rtnl_dereference(nh->nh_grp);
753 
754 	for (i = 0; i < nhg->num_nh; i++) {
755 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
756 
757 		nhge->packets_hw += info->nh_grp_hw_stats->stats[i].packets;
758 	}
759 }
760 
761 static int nh_grp_hw_stats_update(struct nexthop *nh, bool *hw_stats_used)
762 {
763 	struct nh_notifier_info info = {
764 		.net = nh->net,
765 	};
766 	struct net *net = nh->net;
767 	int err;
768 
769 	if (nexthop_notifiers_is_empty(net)) {
770 		*hw_stats_used = false;
771 		return 0;
772 	}
773 
774 	err = nh_notifier_grp_hw_stats_init(&info, nh);
775 	if (err)
776 		return err;
777 
778 	err = blocking_notifier_call_chain(&net->nexthop.notifier_chain,
779 					   NEXTHOP_EVENT_HW_STATS_REPORT_DELTA,
780 					   &info);
781 
782 	/* Cache whatever we got, even if there was an error, otherwise the
783 	 * successful stats retrievals would get lost.
784 	 */
785 	nh_grp_hw_stats_apply_update(nh, &info);
786 	*hw_stats_used = info.nh_grp_hw_stats->hw_stats_used;
787 
788 	nh_notifier_grp_hw_stats_fini(&info);
789 	return notifier_to_errno(err);
790 }
791 
792 static int nla_put_nh_group_stats_entry(struct sk_buff *skb,
793 					struct nh_grp_entry *nhge,
794 					u32 op_flags)
795 {
796 	struct nlattr *nest;
797 	u64 packets;
798 
799 	nh_grp_entry_stats_read(nhge, &packets);
800 
801 	nest = nla_nest_start(skb, NHA_GROUP_STATS_ENTRY);
802 	if (!nest)
803 		return -EMSGSIZE;
804 
805 	if (nla_put_u32(skb, NHA_GROUP_STATS_ENTRY_ID, nhge->nh->id) ||
806 	    nla_put_uint(skb, NHA_GROUP_STATS_ENTRY_PACKETS,
807 			 packets + nhge->packets_hw))
808 		goto nla_put_failure;
809 
810 	if (op_flags & NHA_OP_FLAG_DUMP_HW_STATS &&
811 	    nla_put_uint(skb, NHA_GROUP_STATS_ENTRY_PACKETS_HW,
812 			 nhge->packets_hw))
813 		goto nla_put_failure;
814 
815 	nla_nest_end(skb, nest);
816 	return 0;
817 
818 nla_put_failure:
819 	nla_nest_cancel(skb, nest);
820 	return -EMSGSIZE;
821 }
822 
823 static int nla_put_nh_group_stats(struct sk_buff *skb, struct nexthop *nh,
824 				  u32 op_flags)
825 {
826 	struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
827 	struct nlattr *nest;
828 	bool hw_stats_used;
829 	int err;
830 	int i;
831 
832 	if (nla_put_u32(skb, NHA_HW_STATS_ENABLE, nhg->hw_stats))
833 		goto err_out;
834 
835 	if (op_flags & NHA_OP_FLAG_DUMP_HW_STATS &&
836 	    nhg->hw_stats) {
837 		err = nh_grp_hw_stats_update(nh, &hw_stats_used);
838 		if (err)
839 			goto out;
840 
841 		if (nla_put_u32(skb, NHA_HW_STATS_USED, hw_stats_used))
842 			goto err_out;
843 	}
844 
845 	nest = nla_nest_start(skb, NHA_GROUP_STATS);
846 	if (!nest)
847 		goto err_out;
848 
849 	for (i = 0; i < nhg->num_nh; i++)
850 		if (nla_put_nh_group_stats_entry(skb, &nhg->nh_entries[i],
851 						 op_flags))
852 			goto cancel_out;
853 
854 	nla_nest_end(skb, nest);
855 	return 0;
856 
857 cancel_out:
858 	nla_nest_cancel(skb, nest);
859 err_out:
860 	err = -EMSGSIZE;
861 out:
862 	return err;
863 }
864 
865 static int nla_put_nh_group(struct sk_buff *skb, struct nexthop *nh,
866 			    u32 op_flags, u32 *resp_op_flags)
867 {
868 	struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
869 	struct nexthop_grp *p;
870 	size_t len = nhg->num_nh * sizeof(*p);
871 	struct nlattr *nla;
872 	u16 group_type = 0;
873 	u16 weight;
874 	int i;
875 
876 	*resp_op_flags |= NHA_OP_FLAG_RESP_GRP_RESVD_0;
877 
878 	if (nhg->hash_threshold)
879 		group_type = NEXTHOP_GRP_TYPE_MPATH;
880 	else if (nhg->resilient)
881 		group_type = NEXTHOP_GRP_TYPE_RES;
882 
883 	if (nla_put_u16(skb, NHA_GROUP_TYPE, group_type))
884 		goto nla_put_failure;
885 
886 	nla = nla_reserve(skb, NHA_GROUP, len);
887 	if (!nla)
888 		goto nla_put_failure;
889 
890 	p = nla_data(nla);
891 	for (i = 0; i < nhg->num_nh; ++i) {
892 		weight = nhg->nh_entries[i].weight - 1;
893 
894 		*p++ = (struct nexthop_grp) {
895 			.id = nhg->nh_entries[i].nh->id,
896 			.weight = weight,
897 			.weight_high = weight >> 8,
898 		};
899 	}
900 
901 	if (nhg->resilient && nla_put_nh_group_res(skb, nhg))
902 		goto nla_put_failure;
903 
904 	if (op_flags & NHA_OP_FLAG_DUMP_STATS &&
905 	    nla_put_nh_group_stats(skb, nh, op_flags))
906 		goto nla_put_failure;
907 
908 	return 0;
909 
910 nla_put_failure:
911 	return -EMSGSIZE;
912 }
913 
914 static int nh_fill_node(struct sk_buff *skb, struct nexthop *nh,
915 			int event, u32 portid, u32 seq, unsigned int nlflags,
916 			u32 op_flags)
917 {
918 	struct fib6_nh *fib6_nh;
919 	struct fib_nh *fib_nh;
920 	struct nlmsghdr *nlh;
921 	struct nh_info *nhi;
922 	struct nhmsg *nhm;
923 
924 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*nhm), nlflags);
925 	if (!nlh)
926 		return -EMSGSIZE;
927 
928 	nhm = nlmsg_data(nlh);
929 	nhm->nh_family = AF_UNSPEC;
930 	nhm->nh_flags = nh->nh_flags;
931 	nhm->nh_protocol = nh->protocol;
932 	nhm->nh_scope = 0;
933 	nhm->resvd = 0;
934 
935 	if (nla_put_u32(skb, NHA_ID, nh->id))
936 		goto nla_put_failure;
937 
938 	if (nh->is_group) {
939 		struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
940 		u32 resp_op_flags = 0;
941 
942 		if (nhg->fdb_nh && nla_put_flag(skb, NHA_FDB))
943 			goto nla_put_failure;
944 		if (nla_put_nh_group(skb, nh, op_flags, &resp_op_flags) ||
945 		    nla_put_u32(skb, NHA_OP_FLAGS, resp_op_flags))
946 			goto nla_put_failure;
947 		goto out;
948 	}
949 
950 	nhi = rtnl_dereference(nh->nh_info);
951 	nhm->nh_family = nhi->family;
952 	if (nhi->reject_nh) {
953 		if (nla_put_flag(skb, NHA_BLACKHOLE))
954 			goto nla_put_failure;
955 		goto out;
956 	} else if (nhi->fdb_nh) {
957 		if (nla_put_flag(skb, NHA_FDB))
958 			goto nla_put_failure;
959 	} else {
960 		const struct net_device *dev;
961 
962 		dev = nhi->fib_nhc.nhc_dev;
963 		if (dev && nla_put_u32(skb, NHA_OIF, dev->ifindex))
964 			goto nla_put_failure;
965 	}
966 
967 	nhm->nh_scope = nhi->fib_nhc.nhc_scope;
968 	switch (nhi->family) {
969 	case AF_INET:
970 		fib_nh = &nhi->fib_nh;
971 		if (fib_nh->fib_nh_gw_family &&
972 		    nla_put_be32(skb, NHA_GATEWAY, fib_nh->fib_nh_gw4))
973 			goto nla_put_failure;
974 		break;
975 
976 	case AF_INET6:
977 		fib6_nh = &nhi->fib6_nh;
978 		if (fib6_nh->fib_nh_gw_family &&
979 		    nla_put_in6_addr(skb, NHA_GATEWAY, &fib6_nh->fib_nh_gw6))
980 			goto nla_put_failure;
981 		break;
982 	}
983 
984 	if (lwtunnel_fill_encap(skb, nhi->fib_nhc.nhc_lwtstate,
985 				NHA_ENCAP, NHA_ENCAP_TYPE) < 0)
986 		goto nla_put_failure;
987 
988 out:
989 	nlmsg_end(skb, nlh);
990 	return 0;
991 
992 nla_put_failure:
993 	nlmsg_cancel(skb, nlh);
994 	return -EMSGSIZE;
995 }
996 
997 static size_t nh_nlmsg_size_grp_res(struct nh_group *nhg)
998 {
999 	return nla_total_size(0) +	/* NHA_RES_GROUP */
1000 		nla_total_size(2) +	/* NHA_RES_GROUP_BUCKETS */
1001 		nla_total_size(4) +	/* NHA_RES_GROUP_IDLE_TIMER */
1002 		nla_total_size(4) +	/* NHA_RES_GROUP_UNBALANCED_TIMER */
1003 		nla_total_size_64bit(8);/* NHA_RES_GROUP_UNBALANCED_TIME */
1004 }
1005 
1006 static size_t nh_nlmsg_size_grp(struct nexthop *nh, u32 op_flags)
1007 {
1008 	struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
1009 	size_t sz = sizeof(struct nexthop_grp) * nhg->num_nh;
1010 	size_t tot = nla_total_size(sz) +
1011 		nla_total_size(2) +	/* NHA_GROUP_TYPE */
1012 		nla_total_size(0);	/* NHA_FDB */
1013 
1014 	if (nhg->resilient)
1015 		tot += nh_nlmsg_size_grp_res(nhg);
1016 
1017 	if (op_flags & NHA_OP_FLAG_DUMP_STATS) {
1018 		tot += nla_total_size(0) +	  /* NHA_GROUP_STATS */
1019 		       nla_total_size(4);	  /* NHA_HW_STATS_ENABLE */
1020 		tot += nhg->num_nh *
1021 		       (nla_total_size(0) +	  /* NHA_GROUP_STATS_ENTRY */
1022 			nla_total_size(4) +	  /* NHA_GROUP_STATS_ENTRY_ID */
1023 			nla_total_size_64bit(8)); /* NHA_GROUP_STATS_ENTRY_PACKETS */
1024 
1025 		if (op_flags & NHA_OP_FLAG_DUMP_HW_STATS) {
1026 			tot += nhg->num_nh *
1027 			       nla_total_size_64bit(8); /* NHA_GROUP_STATS_ENTRY_PACKETS_HW */
1028 			tot += nla_total_size(4);	/* NHA_HW_STATS_USED */
1029 		}
1030 	}
1031 
1032 	return tot;
1033 }
1034 
1035 static size_t nh_nlmsg_size_single(struct nexthop *nh)
1036 {
1037 	struct nh_info *nhi = rtnl_dereference(nh->nh_info);
1038 	size_t sz;
1039 
1040 	/* covers NHA_BLACKHOLE since NHA_OIF and BLACKHOLE
1041 	 * are mutually exclusive
1042 	 */
1043 	sz = nla_total_size(4);  /* NHA_OIF */
1044 
1045 	switch (nhi->family) {
1046 	case AF_INET:
1047 		if (nhi->fib_nh.fib_nh_gw_family)
1048 			sz += nla_total_size(4);  /* NHA_GATEWAY */
1049 		break;
1050 
1051 	case AF_INET6:
1052 		/* NHA_GATEWAY */
1053 		if (nhi->fib6_nh.fib_nh_gw_family)
1054 			sz += nla_total_size(sizeof(const struct in6_addr));
1055 		break;
1056 	}
1057 
1058 	if (nhi->fib_nhc.nhc_lwtstate) {
1059 		sz += lwtunnel_get_encap_size(nhi->fib_nhc.nhc_lwtstate);
1060 		sz += nla_total_size(2);  /* NHA_ENCAP_TYPE */
1061 	}
1062 
1063 	return sz;
1064 }
1065 
1066 static size_t nh_nlmsg_size(struct nexthop *nh, u32 op_flags)
1067 {
1068 	size_t sz = NLMSG_ALIGN(sizeof(struct nhmsg));
1069 
1070 	sz += nla_total_size(4); /* NHA_ID */
1071 
1072 	if (nh->is_group)
1073 		sz += nh_nlmsg_size_grp(nh, op_flags) +
1074 		      nla_total_size(4) +	/* NHA_OP_FLAGS */
1075 		      0;
1076 	else
1077 		sz += nh_nlmsg_size_single(nh);
1078 
1079 	return sz;
1080 }
1081 
1082 static void nexthop_notify(int event, struct nexthop *nh, struct nl_info *info)
1083 {
1084 	unsigned int nlflags = info->nlh ? info->nlh->nlmsg_flags : 0;
1085 	u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
1086 	struct sk_buff *skb;
1087 	int err = -ENOBUFS;
1088 
1089 	skb = nlmsg_new(nh_nlmsg_size(nh, 0), gfp_any());
1090 	if (!skb)
1091 		goto errout;
1092 
1093 	err = nh_fill_node(skb, nh, event, info->portid, seq, nlflags, 0);
1094 	if (err < 0) {
1095 		/* -EMSGSIZE implies BUG in nh_nlmsg_size() */
1096 		WARN_ON(err == -EMSGSIZE);
1097 		kfree_skb(skb);
1098 		goto errout;
1099 	}
1100 
1101 	rtnl_notify(skb, info->nl_net, info->portid, RTNLGRP_NEXTHOP,
1102 		    info->nlh, gfp_any());
1103 	return;
1104 errout:
1105 	rtnl_set_sk_err(info->nl_net, RTNLGRP_NEXTHOP, err);
1106 }
1107 
1108 static unsigned long nh_res_bucket_used_time(const struct nh_res_bucket *bucket)
1109 {
1110 	return (unsigned long)atomic_long_read(&bucket->used_time);
1111 }
1112 
1113 static unsigned long
1114 nh_res_bucket_idle_point(const struct nh_res_table *res_table,
1115 			 const struct nh_res_bucket *bucket,
1116 			 unsigned long now)
1117 {
1118 	unsigned long time = nh_res_bucket_used_time(bucket);
1119 
1120 	/* Bucket was not used since it was migrated. The idle time is now. */
1121 	if (time == bucket->migrated_time)
1122 		return now;
1123 
1124 	return time + res_table->idle_timer;
1125 }
1126 
1127 static unsigned long
1128 nh_res_table_unb_point(const struct nh_res_table *res_table)
1129 {
1130 	return res_table->unbalanced_since + res_table->unbalanced_timer;
1131 }
1132 
1133 static void nh_res_bucket_set_idle(const struct nh_res_table *res_table,
1134 				   struct nh_res_bucket *bucket)
1135 {
1136 	unsigned long now = jiffies;
1137 
1138 	atomic_long_set(&bucket->used_time, (long)now);
1139 	bucket->migrated_time = now;
1140 }
1141 
1142 static void nh_res_bucket_set_busy(struct nh_res_bucket *bucket)
1143 {
1144 	atomic_long_set(&bucket->used_time, (long)jiffies);
1145 }
1146 
1147 static clock_t nh_res_bucket_idle_time(const struct nh_res_bucket *bucket)
1148 {
1149 	unsigned long used_time = nh_res_bucket_used_time(bucket);
1150 
1151 	return jiffies_delta_to_clock_t(jiffies - used_time);
1152 }
1153 
1154 static int nh_fill_res_bucket(struct sk_buff *skb, struct nexthop *nh,
1155 			      struct nh_res_bucket *bucket, u16 bucket_index,
1156 			      int event, u32 portid, u32 seq,
1157 			      unsigned int nlflags,
1158 			      struct netlink_ext_ack *extack)
1159 {
1160 	struct nh_grp_entry *nhge = nh_res_dereference(bucket->nh_entry);
1161 	struct nlmsghdr *nlh;
1162 	struct nlattr *nest;
1163 	struct nhmsg *nhm;
1164 
1165 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*nhm), nlflags);
1166 	if (!nlh)
1167 		return -EMSGSIZE;
1168 
1169 	nhm = nlmsg_data(nlh);
1170 	nhm->nh_family = AF_UNSPEC;
1171 	nhm->nh_flags = bucket->nh_flags;
1172 	nhm->nh_protocol = nh->protocol;
1173 	nhm->nh_scope = 0;
1174 	nhm->resvd = 0;
1175 
1176 	if (nla_put_u32(skb, NHA_ID, nh->id))
1177 		goto nla_put_failure;
1178 
1179 	nest = nla_nest_start(skb, NHA_RES_BUCKET);
1180 	if (!nest)
1181 		goto nla_put_failure;
1182 
1183 	if (nla_put_u16(skb, NHA_RES_BUCKET_INDEX, bucket_index) ||
1184 	    nla_put_u32(skb, NHA_RES_BUCKET_NH_ID, nhge->nh->id) ||
1185 	    nla_put_u64_64bit(skb, NHA_RES_BUCKET_IDLE_TIME,
1186 			      nh_res_bucket_idle_time(bucket),
1187 			      NHA_RES_BUCKET_PAD))
1188 		goto nla_put_failure_nest;
1189 
1190 	nla_nest_end(skb, nest);
1191 	nlmsg_end(skb, nlh);
1192 	return 0;
1193 
1194 nla_put_failure_nest:
1195 	nla_nest_cancel(skb, nest);
1196 nla_put_failure:
1197 	nlmsg_cancel(skb, nlh);
1198 	return -EMSGSIZE;
1199 }
1200 
1201 static void nexthop_bucket_notify(struct nh_res_table *res_table,
1202 				  u16 bucket_index)
1203 {
1204 	struct nh_res_bucket *bucket = &res_table->nh_buckets[bucket_index];
1205 	struct nh_grp_entry *nhge = nh_res_dereference(bucket->nh_entry);
1206 	struct nexthop *nh = nhge->nh_parent;
1207 	struct sk_buff *skb;
1208 	int err = -ENOBUFS;
1209 
1210 	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
1211 	if (!skb)
1212 		goto errout;
1213 
1214 	err = nh_fill_res_bucket(skb, nh, bucket, bucket_index,
1215 				 RTM_NEWNEXTHOPBUCKET, 0, 0, NLM_F_REPLACE,
1216 				 NULL);
1217 	if (err < 0) {
1218 		kfree_skb(skb);
1219 		goto errout;
1220 	}
1221 
1222 	rtnl_notify(skb, nh->net, 0, RTNLGRP_NEXTHOP, NULL, GFP_KERNEL);
1223 	return;
1224 errout:
1225 	rtnl_set_sk_err(nh->net, RTNLGRP_NEXTHOP, err);
1226 }
1227 
1228 static bool valid_group_nh(struct nexthop *nh, unsigned int npaths,
1229 			   bool *is_fdb, struct netlink_ext_ack *extack)
1230 {
1231 	if (nh->is_group) {
1232 		struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
1233 
1234 		/* Nesting groups within groups is not supported. */
1235 		if (nhg->hash_threshold) {
1236 			NL_SET_ERR_MSG(extack,
1237 				       "Hash-threshold group can not be a nexthop within a group");
1238 			return false;
1239 		}
1240 		if (nhg->resilient) {
1241 			NL_SET_ERR_MSG(extack,
1242 				       "Resilient group can not be a nexthop within a group");
1243 			return false;
1244 		}
1245 		*is_fdb = nhg->fdb_nh;
1246 	} else {
1247 		struct nh_info *nhi = rtnl_dereference(nh->nh_info);
1248 
1249 		if (nhi->reject_nh && npaths > 1) {
1250 			NL_SET_ERR_MSG(extack,
1251 				       "Blackhole nexthop can not be used in a group with more than 1 path");
1252 			return false;
1253 		}
1254 		*is_fdb = nhi->fdb_nh;
1255 	}
1256 
1257 	return true;
1258 }
1259 
1260 static int nh_check_attr_fdb_group(struct nexthop *nh, u8 *nh_family,
1261 				   struct netlink_ext_ack *extack)
1262 {
1263 	struct nh_info *nhi;
1264 
1265 	nhi = rtnl_dereference(nh->nh_info);
1266 
1267 	if (!nhi->fdb_nh) {
1268 		NL_SET_ERR_MSG(extack, "FDB nexthop group can only have fdb nexthops");
1269 		return -EINVAL;
1270 	}
1271 
1272 	if (*nh_family == AF_UNSPEC) {
1273 		*nh_family = nhi->family;
1274 	} else if (*nh_family != nhi->family) {
1275 		NL_SET_ERR_MSG(extack, "FDB nexthop group cannot have mixed family nexthops");
1276 		return -EINVAL;
1277 	}
1278 
1279 	return 0;
1280 }
1281 
1282 static int nh_check_attr_group(struct net *net,
1283 			       struct nlattr *tb[], size_t tb_size,
1284 			       u16 nh_grp_type, struct netlink_ext_ack *extack)
1285 {
1286 	unsigned int len = nla_len(tb[NHA_GROUP]);
1287 	struct nexthop_grp *nhg;
1288 	unsigned int i, j;
1289 
1290 	if (!len || len & (sizeof(struct nexthop_grp) - 1)) {
1291 		NL_SET_ERR_MSG(extack,
1292 			       "Invalid length for nexthop group attribute");
1293 		return -EINVAL;
1294 	}
1295 
1296 	/* convert len to number of nexthop ids */
1297 	len /= sizeof(*nhg);
1298 
1299 	nhg = nla_data(tb[NHA_GROUP]);
1300 	for (i = 0; i < len; ++i) {
1301 		if (nhg[i].resvd2) {
1302 			NL_SET_ERR_MSG(extack, "Reserved field in nexthop_grp must be 0");
1303 			return -EINVAL;
1304 		}
1305 		if (nexthop_grp_weight(&nhg[i]) == 0) {
1306 			/* 0xffff got passed in, representing weight of 0x10000,
1307 			 * which is too heavy.
1308 			 */
1309 			NL_SET_ERR_MSG(extack, "Invalid value for weight");
1310 			return -EINVAL;
1311 		}
1312 		for (j = i + 1; j < len; ++j) {
1313 			if (nhg[i].id == nhg[j].id) {
1314 				NL_SET_ERR_MSG(extack, "Nexthop id can not be used twice in a group");
1315 				return -EINVAL;
1316 			}
1317 		}
1318 	}
1319 
1320 	nhg = nla_data(tb[NHA_GROUP]);
1321 	for (i = NHA_GROUP_TYPE + 1; i < tb_size; ++i) {
1322 		if (!tb[i])
1323 			continue;
1324 		switch (i) {
1325 		case NHA_HW_STATS_ENABLE:
1326 		case NHA_FDB:
1327 			continue;
1328 		case NHA_RES_GROUP:
1329 			if (nh_grp_type == NEXTHOP_GRP_TYPE_RES)
1330 				continue;
1331 			break;
1332 		}
1333 		NL_SET_ERR_MSG(extack,
1334 			       "No other attributes can be set in nexthop groups");
1335 		return -EINVAL;
1336 	}
1337 
1338 	return 0;
1339 }
1340 
1341 static int nh_check_attr_group_rtnl(struct net *net, struct nlattr *tb[],
1342 				    struct netlink_ext_ack *extack)
1343 {
1344 	u8 nh_family = AF_UNSPEC;
1345 	struct nexthop_grp *nhg;
1346 	unsigned int len;
1347 	unsigned int i;
1348 	u8 nhg_fdb;
1349 
1350 	len = nla_len(tb[NHA_GROUP]) / sizeof(*nhg);
1351 	nhg = nla_data(tb[NHA_GROUP]);
1352 	nhg_fdb = !!tb[NHA_FDB];
1353 
1354 	for (i = 0; i < len; i++) {
1355 		struct nexthop *nh;
1356 		bool is_fdb_nh;
1357 
1358 		nh = nexthop_find_by_id(net, nhg[i].id);
1359 		if (!nh) {
1360 			NL_SET_ERR_MSG(extack, "Invalid nexthop id");
1361 			return -EINVAL;
1362 		}
1363 		if (!valid_group_nh(nh, len, &is_fdb_nh, extack))
1364 			return -EINVAL;
1365 
1366 		if (nhg_fdb && nh_check_attr_fdb_group(nh, &nh_family, extack))
1367 			return -EINVAL;
1368 
1369 		if (!nhg_fdb && is_fdb_nh) {
1370 			NL_SET_ERR_MSG(extack, "Non FDB nexthop group cannot have fdb nexthops");
1371 			return -EINVAL;
1372 		}
1373 	}
1374 
1375 	return 0;
1376 }
1377 
1378 static bool ipv6_good_nh(const struct fib6_nh *nh)
1379 {
1380 	int state = NUD_REACHABLE;
1381 	struct neighbour *n;
1382 
1383 	rcu_read_lock();
1384 
1385 	n = __ipv6_neigh_lookup_noref(nh->fib_nh_dev, &nh->fib_nh_gw6);
1386 	if (n)
1387 		state = READ_ONCE(n->nud_state);
1388 
1389 	rcu_read_unlock();
1390 
1391 	return !!(state & NUD_VALID);
1392 }
1393 
1394 static bool ipv4_good_nh(const struct fib_nh *nh)
1395 {
1396 	int state = NUD_REACHABLE;
1397 	struct neighbour *n;
1398 
1399 	rcu_read_lock();
1400 
1401 	n = __ipv4_neigh_lookup_noref(nh->fib_nh_dev,
1402 				      (__force u32)nh->fib_nh_gw4);
1403 	if (n)
1404 		state = READ_ONCE(n->nud_state);
1405 
1406 	rcu_read_unlock();
1407 
1408 	return !!(state & NUD_VALID);
1409 }
1410 
1411 static bool nexthop_is_good_nh(const struct nexthop *nh)
1412 {
1413 	struct nh_info *nhi = rcu_dereference(nh->nh_info);
1414 
1415 	switch (nhi->family) {
1416 	case AF_INET:
1417 		return ipv4_good_nh(&nhi->fib_nh);
1418 	case AF_INET6:
1419 		return IS_ENABLED(CONFIG_IPV6) && ipv6_good_nh(&nhi->fib6_nh);
1420 	}
1421 
1422 	return false;
1423 }
1424 
1425 static struct nexthop *nexthop_select_path_fdb(struct nh_group *nhg, int hash)
1426 {
1427 	int i;
1428 
1429 	for (i = 0; i < nhg->num_nh; i++) {
1430 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
1431 
1432 		if (hash > atomic_read(&nhge->hthr.upper_bound))
1433 			continue;
1434 
1435 		nh_grp_entry_stats_inc(nhge);
1436 		return nhge->nh;
1437 	}
1438 
1439 	WARN_ON_ONCE(1);
1440 	return NULL;
1441 }
1442 
1443 static struct nexthop *nexthop_select_path_hthr(struct nh_group *nhg, int hash)
1444 {
1445 	struct nh_grp_entry *nhge0 = NULL;
1446 	int i;
1447 
1448 	if (nhg->fdb_nh)
1449 		return nexthop_select_path_fdb(nhg, hash);
1450 
1451 	for (i = 0; i < nhg->num_nh; ++i) {
1452 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
1453 
1454 		/* nexthops always check if it is good and does
1455 		 * not rely on a sysctl for this behavior
1456 		 */
1457 		if (!nexthop_is_good_nh(nhge->nh))
1458 			continue;
1459 
1460 		if (!nhge0)
1461 			nhge0 = nhge;
1462 
1463 		if (hash > atomic_read(&nhge->hthr.upper_bound))
1464 			continue;
1465 
1466 		nh_grp_entry_stats_inc(nhge);
1467 		return nhge->nh;
1468 	}
1469 
1470 	if (!nhge0)
1471 		nhge0 = &nhg->nh_entries[0];
1472 	nh_grp_entry_stats_inc(nhge0);
1473 	return nhge0->nh;
1474 }
1475 
1476 static struct nexthop *nexthop_select_path_res(struct nh_group *nhg, int hash)
1477 {
1478 	struct nh_res_table *res_table = rcu_dereference(nhg->res_table);
1479 	u16 bucket_index = hash % res_table->num_nh_buckets;
1480 	struct nh_res_bucket *bucket;
1481 	struct nh_grp_entry *nhge;
1482 
1483 	/* nexthop_select_path() is expected to return a non-NULL value, so
1484 	 * skip protocol validation and just hand out whatever there is.
1485 	 */
1486 	bucket = &res_table->nh_buckets[bucket_index];
1487 	nh_res_bucket_set_busy(bucket);
1488 	nhge = rcu_dereference(bucket->nh_entry);
1489 	nh_grp_entry_stats_inc(nhge);
1490 	return nhge->nh;
1491 }
1492 
1493 struct nexthop *nexthop_select_path(struct nexthop *nh, int hash)
1494 {
1495 	struct nh_group *nhg;
1496 
1497 	if (!nh->is_group)
1498 		return nh;
1499 
1500 	nhg = rcu_dereference(nh->nh_grp);
1501 	if (nhg->hash_threshold)
1502 		return nexthop_select_path_hthr(nhg, hash);
1503 	else if (nhg->resilient)
1504 		return nexthop_select_path_res(nhg, hash);
1505 
1506 	/* Unreachable. */
1507 	return NULL;
1508 }
1509 EXPORT_SYMBOL_GPL(nexthop_select_path);
1510 
1511 int nexthop_for_each_fib6_nh(struct nexthop *nh,
1512 			     int (*cb)(struct fib6_nh *nh, void *arg),
1513 			     void *arg)
1514 {
1515 	struct nh_info *nhi;
1516 	int err;
1517 
1518 	if (nh->is_group) {
1519 		struct nh_group *nhg;
1520 		int i;
1521 
1522 		nhg = rcu_dereference_rtnl(nh->nh_grp);
1523 		for (i = 0; i < nhg->num_nh; i++) {
1524 			struct nh_grp_entry *nhge = &nhg->nh_entries[i];
1525 
1526 			nhi = rcu_dereference_rtnl(nhge->nh->nh_info);
1527 			err = cb(&nhi->fib6_nh, arg);
1528 			if (err)
1529 				return err;
1530 		}
1531 	} else {
1532 		nhi = rcu_dereference_rtnl(nh->nh_info);
1533 		err = cb(&nhi->fib6_nh, arg);
1534 		if (err)
1535 			return err;
1536 	}
1537 
1538 	return 0;
1539 }
1540 EXPORT_SYMBOL_GPL(nexthop_for_each_fib6_nh);
1541 
1542 static int check_src_addr(const struct in6_addr *saddr,
1543 			  struct netlink_ext_ack *extack)
1544 {
1545 	if (!ipv6_addr_any(saddr)) {
1546 		NL_SET_ERR_MSG(extack, "IPv6 routes using source address can not use nexthop objects");
1547 		return -EINVAL;
1548 	}
1549 	return 0;
1550 }
1551 
1552 int fib6_check_nexthop(struct nexthop *nh, struct fib6_config *cfg,
1553 		       struct netlink_ext_ack *extack)
1554 {
1555 	struct nh_info *nhi;
1556 	bool is_fdb_nh;
1557 
1558 	/* fib6_src is unique to a fib6_info and limits the ability to cache
1559 	 * routes in fib6_nh within a nexthop that is potentially shared
1560 	 * across multiple fib entries. If the config wants to use source
1561 	 * routing it can not use nexthop objects. mlxsw also does not allow
1562 	 * fib6_src on routes.
1563 	 */
1564 	if (cfg && check_src_addr(&cfg->fc_src, extack) < 0)
1565 		return -EINVAL;
1566 
1567 	if (nh->is_group) {
1568 		struct nh_group *nhg;
1569 
1570 		nhg = rcu_dereference_rtnl(nh->nh_grp);
1571 		if (nhg->has_v4)
1572 			goto no_v4_nh;
1573 		is_fdb_nh = nhg->fdb_nh;
1574 	} else {
1575 		nhi = rcu_dereference_rtnl(nh->nh_info);
1576 		if (nhi->family == AF_INET)
1577 			goto no_v4_nh;
1578 		is_fdb_nh = nhi->fdb_nh;
1579 	}
1580 
1581 	if (is_fdb_nh) {
1582 		NL_SET_ERR_MSG(extack, "Route cannot point to a fdb nexthop");
1583 		return -EINVAL;
1584 	}
1585 
1586 	return 0;
1587 no_v4_nh:
1588 	NL_SET_ERR_MSG(extack, "IPv6 routes can not use an IPv4 nexthop");
1589 	return -EINVAL;
1590 }
1591 EXPORT_SYMBOL_GPL(fib6_check_nexthop);
1592 
1593 /* if existing nexthop has ipv6 routes linked to it, need
1594  * to verify this new spec works with ipv6
1595  */
1596 static int fib6_check_nh_list(struct nexthop *old, struct nexthop *new,
1597 			      struct netlink_ext_ack *extack)
1598 {
1599 	struct fib6_info *f6i;
1600 	int err = 0;
1601 
1602 	if (list_empty(&old->f6i_list))
1603 		return 0;
1604 
1605 	spin_lock_bh(&old->lock);
1606 	list_for_each_entry(f6i, &old->f6i_list, nh_list) {
1607 		err = check_src_addr(&f6i->fib6_src.addr, extack);
1608 		if (err)
1609 			break;
1610 	}
1611 	spin_unlock_bh(&old->lock);
1612 
1613 	if (err)
1614 		return err;
1615 
1616 	return fib6_check_nexthop(new, NULL, extack);
1617 }
1618 
1619 static int nexthop_check_scope(struct nh_info *nhi, u8 scope,
1620 			       struct netlink_ext_ack *extack)
1621 {
1622 	if (scope == RT_SCOPE_HOST && nhi->fib_nhc.nhc_gw_family) {
1623 		NL_SET_ERR_MSG(extack,
1624 			       "Route with host scope can not have a gateway");
1625 		return -EINVAL;
1626 	}
1627 
1628 	if (nhi->fib_nhc.nhc_flags & RTNH_F_ONLINK && scope >= RT_SCOPE_LINK) {
1629 		NL_SET_ERR_MSG(extack, "Scope mismatch with nexthop");
1630 		return -EINVAL;
1631 	}
1632 
1633 	return 0;
1634 }
1635 
1636 /* Invoked by fib add code to verify nexthop by id is ok with
1637  * config for prefix; parts of fib_check_nh not done when nexthop
1638  * object is used.
1639  */
1640 int fib_check_nexthop(struct nexthop *nh, u8 scope,
1641 		      struct netlink_ext_ack *extack)
1642 {
1643 	struct nh_info *nhi;
1644 	int err = 0;
1645 
1646 	if (nh->is_group) {
1647 		struct nh_group *nhg;
1648 
1649 		nhg = rtnl_dereference(nh->nh_grp);
1650 		if (nhg->fdb_nh) {
1651 			NL_SET_ERR_MSG(extack, "Route cannot point to a fdb nexthop");
1652 			err = -EINVAL;
1653 			goto out;
1654 		}
1655 
1656 		if (scope == RT_SCOPE_HOST) {
1657 			NL_SET_ERR_MSG(extack, "Route with host scope can not have multiple nexthops");
1658 			err = -EINVAL;
1659 			goto out;
1660 		}
1661 
1662 		/* all nexthops in a group have the same scope */
1663 		nhi = rtnl_dereference(nhg->nh_entries[0].nh->nh_info);
1664 		err = nexthop_check_scope(nhi, scope, extack);
1665 	} else {
1666 		nhi = rtnl_dereference(nh->nh_info);
1667 		if (nhi->fdb_nh) {
1668 			NL_SET_ERR_MSG(extack, "Route cannot point to a fdb nexthop");
1669 			err = -EINVAL;
1670 			goto out;
1671 		}
1672 		err = nexthop_check_scope(nhi, scope, extack);
1673 	}
1674 
1675 out:
1676 	return err;
1677 }
1678 
1679 static int fib_check_nh_list(struct nexthop *old, struct nexthop *new,
1680 			     struct netlink_ext_ack *extack)
1681 {
1682 	struct fib_info *fi;
1683 
1684 	list_for_each_entry(fi, &old->fi_list, nh_list) {
1685 		int err;
1686 
1687 		err = fib_check_nexthop(new, fi->fib_scope, extack);
1688 		if (err)
1689 			return err;
1690 	}
1691 	return 0;
1692 }
1693 
1694 static bool nh_res_nhge_is_balanced(const struct nh_grp_entry *nhge)
1695 {
1696 	return nhge->res.count_buckets == nhge->res.wants_buckets;
1697 }
1698 
1699 static bool nh_res_nhge_is_ow(const struct nh_grp_entry *nhge)
1700 {
1701 	return nhge->res.count_buckets > nhge->res.wants_buckets;
1702 }
1703 
1704 static bool nh_res_nhge_is_uw(const struct nh_grp_entry *nhge)
1705 {
1706 	return nhge->res.count_buckets < nhge->res.wants_buckets;
1707 }
1708 
1709 static bool nh_res_table_is_balanced(const struct nh_res_table *res_table)
1710 {
1711 	return list_empty(&res_table->uw_nh_entries);
1712 }
1713 
1714 static void nh_res_bucket_unset_nh(struct nh_res_bucket *bucket)
1715 {
1716 	struct nh_grp_entry *nhge;
1717 
1718 	if (bucket->occupied) {
1719 		nhge = nh_res_dereference(bucket->nh_entry);
1720 		nhge->res.count_buckets--;
1721 		bucket->occupied = false;
1722 	}
1723 }
1724 
1725 static void nh_res_bucket_set_nh(struct nh_res_bucket *bucket,
1726 				 struct nh_grp_entry *nhge)
1727 {
1728 	nh_res_bucket_unset_nh(bucket);
1729 
1730 	bucket->occupied = true;
1731 	rcu_assign_pointer(bucket->nh_entry, nhge);
1732 	nhge->res.count_buckets++;
1733 }
1734 
1735 static bool nh_res_bucket_should_migrate(struct nh_res_table *res_table,
1736 					 struct nh_res_bucket *bucket,
1737 					 unsigned long *deadline, bool *force)
1738 {
1739 	unsigned long now = jiffies;
1740 	struct nh_grp_entry *nhge;
1741 	unsigned long idle_point;
1742 
1743 	if (!bucket->occupied) {
1744 		/* The bucket is not occupied, its NHGE pointer is either
1745 		 * NULL or obsolete. We _have to_ migrate: set force.
1746 		 */
1747 		*force = true;
1748 		return true;
1749 	}
1750 
1751 	nhge = nh_res_dereference(bucket->nh_entry);
1752 
1753 	/* If the bucket is populated by an underweight or balanced
1754 	 * nexthop, do not migrate.
1755 	 */
1756 	if (!nh_res_nhge_is_ow(nhge))
1757 		return false;
1758 
1759 	/* At this point we know that the bucket is populated with an
1760 	 * overweight nexthop. It needs to be migrated to a new nexthop if
1761 	 * the idle timer of unbalanced timer expired.
1762 	 */
1763 
1764 	idle_point = nh_res_bucket_idle_point(res_table, bucket, now);
1765 	if (time_after_eq(now, idle_point)) {
1766 		/* The bucket is idle. We _can_ migrate: unset force. */
1767 		*force = false;
1768 		return true;
1769 	}
1770 
1771 	/* Unbalanced timer of 0 means "never force". */
1772 	if (res_table->unbalanced_timer) {
1773 		unsigned long unb_point;
1774 
1775 		unb_point = nh_res_table_unb_point(res_table);
1776 		if (time_after(now, unb_point)) {
1777 			/* The bucket is not idle, but the unbalanced timer
1778 			 * expired. We _can_ migrate, but set force anyway,
1779 			 * so that drivers know to ignore activity reports
1780 			 * from the HW.
1781 			 */
1782 			*force = true;
1783 			return true;
1784 		}
1785 
1786 		nh_res_time_set_deadline(unb_point, deadline);
1787 	}
1788 
1789 	nh_res_time_set_deadline(idle_point, deadline);
1790 	return false;
1791 }
1792 
1793 static bool nh_res_bucket_migrate(struct nh_res_table *res_table,
1794 				  u16 bucket_index, bool notify,
1795 				  bool notify_nl, bool force)
1796 {
1797 	struct nh_res_bucket *bucket = &res_table->nh_buckets[bucket_index];
1798 	struct netlink_ext_ack extack = {};
1799 	struct nh_grp_entry *new_nhge;
1800 	int err;
1801 
1802 	new_nhge = list_first_entry_or_null(&res_table->uw_nh_entries,
1803 					    struct nh_grp_entry,
1804 					    res.uw_nh_entry);
1805 	if (WARN_ON_ONCE(!new_nhge))
1806 		/* If this function is called, "bucket" is either not
1807 		 * occupied, or it belongs to a next hop that is
1808 		 * overweight. In either case, there ought to be a
1809 		 * corresponding underweight next hop.
1810 		 */
1811 		return false;
1812 
1813 	if (notify) {
1814 		struct nh_grp_entry *old_nhge;
1815 
1816 		old_nhge = nh_res_dereference(bucket->nh_entry);
1817 		err = call_nexthop_res_bucket_notifiers(res_table->net,
1818 							res_table->nhg_id,
1819 							bucket_index, force,
1820 							old_nhge->nh,
1821 							new_nhge->nh, &extack);
1822 		if (err) {
1823 			pr_err_ratelimited("%s\n", extack._msg);
1824 			if (!force)
1825 				return false;
1826 			/* It is not possible to veto a forced replacement, so
1827 			 * just clear the hardware flags from the nexthop
1828 			 * bucket to indicate to user space that this bucket is
1829 			 * not correctly populated in hardware.
1830 			 */
1831 			bucket->nh_flags &= ~(RTNH_F_OFFLOAD | RTNH_F_TRAP);
1832 		}
1833 	}
1834 
1835 	nh_res_bucket_set_nh(bucket, new_nhge);
1836 	nh_res_bucket_set_idle(res_table, bucket);
1837 
1838 	if (notify_nl)
1839 		nexthop_bucket_notify(res_table, bucket_index);
1840 
1841 	if (nh_res_nhge_is_balanced(new_nhge))
1842 		list_del(&new_nhge->res.uw_nh_entry);
1843 	return true;
1844 }
1845 
1846 #define NH_RES_UPKEEP_DW_MINIMUM_INTERVAL (HZ / 2)
1847 
1848 static void nh_res_table_upkeep(struct nh_res_table *res_table,
1849 				bool notify, bool notify_nl)
1850 {
1851 	unsigned long now = jiffies;
1852 	unsigned long deadline;
1853 	u16 i;
1854 
1855 	/* Deadline is the next time that upkeep should be run. It is the
1856 	 * earliest time at which one of the buckets might be migrated.
1857 	 * Start at the most pessimistic estimate: either unbalanced_timer
1858 	 * from now, or if there is none, idle_timer from now. For each
1859 	 * encountered time point, call nh_res_time_set_deadline() to
1860 	 * refine the estimate.
1861 	 */
1862 	if (res_table->unbalanced_timer)
1863 		deadline = now + res_table->unbalanced_timer;
1864 	else
1865 		deadline = now + res_table->idle_timer;
1866 
1867 	for (i = 0; i < res_table->num_nh_buckets; i++) {
1868 		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
1869 		bool force;
1870 
1871 		if (nh_res_bucket_should_migrate(res_table, bucket,
1872 						 &deadline, &force)) {
1873 			if (!nh_res_bucket_migrate(res_table, i, notify,
1874 						   notify_nl, force)) {
1875 				unsigned long idle_point;
1876 
1877 				/* A driver can override the migration
1878 				 * decision if the HW reports that the
1879 				 * bucket is actually not idle. Therefore
1880 				 * remark the bucket as busy again and
1881 				 * update the deadline.
1882 				 */
1883 				nh_res_bucket_set_busy(bucket);
1884 				idle_point = nh_res_bucket_idle_point(res_table,
1885 								      bucket,
1886 								      now);
1887 				nh_res_time_set_deadline(idle_point, &deadline);
1888 			}
1889 		}
1890 	}
1891 
1892 	/* If the group is still unbalanced, schedule the next upkeep to
1893 	 * either the deadline computed above, or the minimum deadline,
1894 	 * whichever comes later.
1895 	 */
1896 	if (!nh_res_table_is_balanced(res_table)) {
1897 		unsigned long now = jiffies;
1898 		unsigned long min_deadline;
1899 
1900 		min_deadline = now + NH_RES_UPKEEP_DW_MINIMUM_INTERVAL;
1901 		if (time_before(deadline, min_deadline))
1902 			deadline = min_deadline;
1903 
1904 		queue_delayed_work(system_power_efficient_wq,
1905 				   &res_table->upkeep_dw, deadline - now);
1906 	}
1907 }
1908 
1909 static void nh_res_table_upkeep_dw(struct work_struct *work)
1910 {
1911 	struct delayed_work *dw = to_delayed_work(work);
1912 	struct nh_res_table *res_table;
1913 
1914 	res_table = container_of(dw, struct nh_res_table, upkeep_dw);
1915 	nh_res_table_upkeep(res_table, true, true);
1916 }
1917 
1918 static void nh_res_table_cancel_upkeep(struct nh_res_table *res_table)
1919 {
1920 	cancel_delayed_work_sync(&res_table->upkeep_dw);
1921 }
1922 
1923 static void nh_res_group_rebalance(struct nh_group *nhg,
1924 				   struct nh_res_table *res_table)
1925 {
1926 	u16 prev_upper_bound = 0;
1927 	u32 total = 0;
1928 	u32 w = 0;
1929 	int i;
1930 
1931 	INIT_LIST_HEAD(&res_table->uw_nh_entries);
1932 
1933 	for (i = 0; i < nhg->num_nh; ++i)
1934 		total += nhg->nh_entries[i].weight;
1935 
1936 	for (i = 0; i < nhg->num_nh; ++i) {
1937 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
1938 		u16 upper_bound;
1939 		u64 btw;
1940 
1941 		w += nhge->weight;
1942 		btw = ((u64)res_table->num_nh_buckets) * w;
1943 		upper_bound = DIV_ROUND_CLOSEST_ULL(btw, total);
1944 		nhge->res.wants_buckets = upper_bound - prev_upper_bound;
1945 		prev_upper_bound = upper_bound;
1946 
1947 		if (nh_res_nhge_is_uw(nhge)) {
1948 			if (list_empty(&res_table->uw_nh_entries))
1949 				res_table->unbalanced_since = jiffies;
1950 			list_add(&nhge->res.uw_nh_entry,
1951 				 &res_table->uw_nh_entries);
1952 		}
1953 	}
1954 }
1955 
1956 /* Migrate buckets in res_table so that they reference NHGE's from NHG with
1957  * the right NH ID. Set those buckets that do not have a corresponding NHGE
1958  * entry in NHG as not occupied.
1959  */
1960 static void nh_res_table_migrate_buckets(struct nh_res_table *res_table,
1961 					 struct nh_group *nhg)
1962 {
1963 	u16 i;
1964 
1965 	for (i = 0; i < res_table->num_nh_buckets; i++) {
1966 		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
1967 		u32 id = rtnl_dereference(bucket->nh_entry)->nh->id;
1968 		bool found = false;
1969 		int j;
1970 
1971 		for (j = 0; j < nhg->num_nh; j++) {
1972 			struct nh_grp_entry *nhge = &nhg->nh_entries[j];
1973 
1974 			if (nhge->nh->id == id) {
1975 				nh_res_bucket_set_nh(bucket, nhge);
1976 				found = true;
1977 				break;
1978 			}
1979 		}
1980 
1981 		if (!found)
1982 			nh_res_bucket_unset_nh(bucket);
1983 	}
1984 }
1985 
1986 static void replace_nexthop_grp_res(struct nh_group *oldg,
1987 				    struct nh_group *newg)
1988 {
1989 	/* For NH group replacement, the new NHG might only have a stub
1990 	 * hash table with 0 buckets, because the number of buckets was not
1991 	 * specified. For NH removal, oldg and newg both reference the same
1992 	 * res_table. So in any case, in the following, we want to work
1993 	 * with oldg->res_table.
1994 	 */
1995 	struct nh_res_table *old_res_table = rtnl_dereference(oldg->res_table);
1996 	unsigned long prev_unbalanced_since = old_res_table->unbalanced_since;
1997 	bool prev_has_uw = !list_empty(&old_res_table->uw_nh_entries);
1998 
1999 	nh_res_table_cancel_upkeep(old_res_table);
2000 	nh_res_table_migrate_buckets(old_res_table, newg);
2001 	nh_res_group_rebalance(newg, old_res_table);
2002 	if (prev_has_uw && !list_empty(&old_res_table->uw_nh_entries))
2003 		old_res_table->unbalanced_since = prev_unbalanced_since;
2004 	nh_res_table_upkeep(old_res_table, true, false);
2005 }
2006 
2007 static void nh_hthr_group_rebalance(struct nh_group *nhg)
2008 {
2009 	u32 total = 0;
2010 	u32 w = 0;
2011 	int i;
2012 
2013 	for (i = 0; i < nhg->num_nh; ++i)
2014 		total += nhg->nh_entries[i].weight;
2015 
2016 	for (i = 0; i < nhg->num_nh; ++i) {
2017 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
2018 		u32 upper_bound;
2019 
2020 		w += nhge->weight;
2021 		upper_bound = DIV_ROUND_CLOSEST_ULL((u64)w << 31, total) - 1;
2022 		atomic_set(&nhge->hthr.upper_bound, upper_bound);
2023 	}
2024 }
2025 
2026 static bool __must_check
2027 remove_nh_grp_entry(struct net *net, struct nh_grp_entry *nhge,
2028 		    struct nl_info *nlinfo, struct list_head *deferred_free)
2029 {
2030 	struct nh_grp_entry *nhges, *new_nhges;
2031 	struct nexthop *nhp = nhge->nh_parent;
2032 	struct netlink_ext_ack extack;
2033 	struct nexthop *nh = nhge->nh;
2034 	struct nh_group *nhg, *newg;
2035 	int i, j, err;
2036 
2037 	WARN_ON(!nh);
2038 
2039 	nhg = rtnl_dereference(nhp->nh_grp);
2040 	newg = nhg->spare;
2041 
2042 	/* last entry, keep it visible and remove the parent */
2043 	if (nhg->num_nh == 1)
2044 		return remove_nexthop(net, nhp, nlinfo);
2045 
2046 	newg->has_v4 = false;
2047 	newg->is_multipath = nhg->is_multipath;
2048 	newg->hash_threshold = nhg->hash_threshold;
2049 	newg->resilient = nhg->resilient;
2050 	newg->fdb_nh = nhg->fdb_nh;
2051 	newg->num_nh = nhg->num_nh;
2052 
2053 	/* copy old entries to new except the one getting removed */
2054 	nhges = nhg->nh_entries;
2055 	new_nhges = newg->nh_entries;
2056 	for (i = 0, j = 0; i < nhg->num_nh; ++i) {
2057 		struct nh_info *nhi;
2058 
2059 		/* current nexthop getting removed */
2060 		if (nhg->nh_entries[i].nh == nh) {
2061 			newg->num_nh--;
2062 			continue;
2063 		}
2064 
2065 		nhi = rtnl_dereference(nhges[i].nh->nh_info);
2066 		if (nhi->family == AF_INET)
2067 			newg->has_v4 = true;
2068 
2069 		list_del(&nhges[i].nh_list);
2070 		new_nhges[j].stats = nhges[i].stats;
2071 		new_nhges[j].nh_parent = nhges[i].nh_parent;
2072 		new_nhges[j].nh = nhges[i].nh;
2073 		new_nhges[j].weight = nhges[i].weight;
2074 		list_add(&new_nhges[j].nh_list, &new_nhges[j].nh->grp_list);
2075 		j++;
2076 	}
2077 
2078 	if (newg->hash_threshold)
2079 		nh_hthr_group_rebalance(newg);
2080 	else if (newg->resilient)
2081 		replace_nexthop_grp_res(nhg, newg);
2082 
2083 	rcu_assign_pointer(nhp->nh_grp, newg);
2084 
2085 	list_del(&nhge->nh_list);
2086 	nexthop_put(nhge->nh);
2087 	list_add(&nhge->nh_list, deferred_free);
2088 
2089 	/* Removal of a NH from a resilient group is notified through
2090 	 * bucket notifications.
2091 	 */
2092 	if (newg->hash_threshold) {
2093 		err = call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, nhp,
2094 					     &extack);
2095 		if (err)
2096 			pr_err("%s\n", extack._msg);
2097 	}
2098 
2099 	if (nlinfo)
2100 		nexthop_notify(RTM_NEWNEXTHOP, nhp, nlinfo);
2101 
2102 	return false;
2103 }
2104 
2105 static bool __must_check
2106 remove_nexthop_from_groups(struct net *net, struct nexthop *nh,
2107 			   struct nl_info *nlinfo)
2108 {
2109 	struct nh_grp_entry *nhge, *tmp;
2110 	LIST_HEAD(deferred_free);
2111 	bool need_flush = false;
2112 
2113 	/* If there is nothing to do, let's avoid the costly call to
2114 	 * synchronize_net()
2115 	 */
2116 	if (list_empty(&nh->grp_list))
2117 		return false;
2118 
2119 	list_for_each_entry_safe(nhge, tmp, &nh->grp_list, nh_list)
2120 		need_flush |= remove_nh_grp_entry(net, nhge, nlinfo,
2121 						  &deferred_free);
2122 
2123 	/* make sure all see the newly published array before releasing rtnl */
2124 	synchronize_net();
2125 
2126 	/* Now safe to free percpu stats — all RCU readers have finished */
2127 	list_for_each_entry_safe(nhge, tmp, &deferred_free, nh_list) {
2128 		list_del(&nhge->nh_list);
2129 		free_percpu(nhge->stats);
2130 	}
2131 
2132 	return need_flush;
2133 }
2134 
2135 static void remove_nexthop_group(struct nexthop *nh, struct nl_info *nlinfo)
2136 {
2137 	struct nh_group *nhg = rcu_dereference_rtnl(nh->nh_grp);
2138 	struct nh_res_table *res_table;
2139 	int i, num_nh = nhg->num_nh;
2140 
2141 	for (i = 0; i < num_nh; ++i) {
2142 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
2143 
2144 		if (WARN_ON(!nhge->nh))
2145 			continue;
2146 
2147 		list_del_init(&nhge->nh_list);
2148 	}
2149 
2150 	if (nhg->resilient) {
2151 		res_table = rtnl_dereference(nhg->res_table);
2152 		nh_res_table_cancel_upkeep(res_table);
2153 	}
2154 }
2155 
2156 /* not called for nexthop replace */
2157 static bool __must_check __remove_nexthop_fib(struct net *net,
2158 					      struct nexthop *nh)
2159 {
2160 	bool need_flush = !list_empty(&nh->fi_list);
2161 	struct fib6_info *f6i;
2162 	struct fib_info *fi;
2163 
2164 	list_for_each_entry(fi, &nh->fi_list, nh_list)
2165 		fi->fib_flags |= RTNH_F_DEAD;
2166 
2167 	spin_lock_bh(&nh->lock);
2168 
2169 	nh->dead = true;
2170 
2171 	while (!list_empty(&nh->f6i_list)) {
2172 		f6i = list_first_entry(&nh->f6i_list, typeof(*f6i), nh_list);
2173 
2174 		/* __ip6_del_rt does a release, so do a hold here */
2175 		fib6_info_hold(f6i);
2176 
2177 		spin_unlock_bh(&nh->lock);
2178 		ip6_del_rt(net, f6i,
2179 			   !READ_ONCE(net->ipv4.sysctl_nexthop_compat_mode));
2180 
2181 		spin_lock_bh(&nh->lock);
2182 	}
2183 
2184 	spin_unlock_bh(&nh->lock);
2185 
2186 	return need_flush;
2187 }
2188 
2189 static bool __must_check __remove_nexthop(struct net *net, struct nexthop *nh,
2190 					  struct nl_info *nlinfo)
2191 {
2192 	bool need_flush = __remove_nexthop_fib(net, nh);
2193 
2194 	if (nh->is_group) {
2195 		remove_nexthop_group(nh, nlinfo);
2196 	} else {
2197 		struct nh_info *nhi;
2198 
2199 		nhi = rtnl_dereference(nh->nh_info);
2200 		if (nhi->fib_nhc.nhc_dev)
2201 			hlist_del(&nhi->dev_hash);
2202 
2203 		need_flush |= remove_nexthop_from_groups(net, nh, nlinfo);
2204 	}
2205 
2206 	return need_flush;
2207 }
2208 
2209 static bool __must_check remove_nexthop(struct net *net, struct nexthop *nh,
2210 					struct nl_info *nlinfo)
2211 {
2212 	bool need_flush;
2213 
2214 	call_nexthop_notifiers(net, NEXTHOP_EVENT_DEL, nh, NULL);
2215 
2216 	/* remove from the tree */
2217 	rb_erase(&nh->rb_node, &net->nexthop.rb_root);
2218 
2219 	if (nlinfo)
2220 		nexthop_notify(RTM_DELNEXTHOP, nh, nlinfo);
2221 
2222 	need_flush = __remove_nexthop(net, nh, nlinfo);
2223 	nh_base_seq_inc(net);
2224 
2225 	nexthop_put(nh);
2226 
2227 	return need_flush;
2228 }
2229 
2230 static void remove_one_nexthop(struct net *net, struct nexthop *nh,
2231 			       struct nl_info *nlinfo)
2232 {
2233 	if (remove_nexthop(net, nh, nlinfo))
2234 		fib_flush(net);
2235 }
2236 
2237 /* if any FIB entries reference this nexthop, any dst entries
2238  * need to be regenerated
2239  */
2240 static void nh_rt_cache_flush(struct net *net, struct nexthop *nh,
2241 			      struct nexthop *replaced_nh)
2242 {
2243 	struct nh_group *nhg;
2244 	bool have_f6i;
2245 	int i;
2246 
2247 	if (!list_empty(&nh->fi_list))
2248 		rt_cache_flush(net);
2249 
2250 	spin_lock_bh(&nh->lock);
2251 	have_f6i = !list_empty(&nh->f6i_list);
2252 	spin_unlock_bh(&nh->lock);
2253 	if (have_f6i)
2254 		rt_genid_bump_ipv6(net);
2255 
2256 	/* if an IPv6 group was replaced, we have to release all old
2257 	 * dsts to make sure all refcounts are released
2258 	 */
2259 	if (!replaced_nh->is_group)
2260 		return;
2261 
2262 	nhg = rtnl_dereference(replaced_nh->nh_grp);
2263 	for (i = 0; i < nhg->num_nh; i++) {
2264 		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
2265 		struct nh_info *nhi = rtnl_dereference(nhge->nh->nh_info);
2266 
2267 		if (nhi->family == AF_INET6)
2268 			fib6_nh_release_dsts(&nhi->fib6_nh);
2269 	}
2270 }
2271 
2272 static int replace_nexthop_grp(struct net *net, struct nexthop *old,
2273 			       struct nexthop *new, const struct nh_config *cfg,
2274 			       struct netlink_ext_ack *extack)
2275 {
2276 	struct nh_res_table *tmp_table = NULL;
2277 	struct nh_res_table *new_res_table;
2278 	struct nh_res_table *old_res_table;
2279 	struct nh_group *oldg, *newg;
2280 	int i, err;
2281 
2282 	if (!new->is_group) {
2283 		NL_SET_ERR_MSG(extack, "Can not replace a nexthop group with a nexthop.");
2284 		return -EINVAL;
2285 	}
2286 
2287 	oldg = rtnl_dereference(old->nh_grp);
2288 	newg = rtnl_dereference(new->nh_grp);
2289 
2290 	if (newg->hash_threshold != oldg->hash_threshold) {
2291 		NL_SET_ERR_MSG(extack, "Can not replace a nexthop group with one of a different type.");
2292 		return -EINVAL;
2293 	}
2294 
2295 	if (newg->hash_threshold) {
2296 		err = call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, new,
2297 					     extack);
2298 		if (err)
2299 			return err;
2300 	} else if (newg->resilient) {
2301 		new_res_table = rtnl_dereference(newg->res_table);
2302 		old_res_table = rtnl_dereference(oldg->res_table);
2303 
2304 		/* Accept if num_nh_buckets was not given, but if it was
2305 		 * given, demand that the value be correct.
2306 		 */
2307 		if (cfg->nh_grp_res_has_num_buckets &&
2308 		    cfg->nh_grp_res_num_buckets !=
2309 		    old_res_table->num_nh_buckets) {
2310 			NL_SET_ERR_MSG(extack, "Can not change number of buckets of a resilient nexthop group.");
2311 			return -EINVAL;
2312 		}
2313 
2314 		/* Emit a pre-replace notification so that listeners could veto
2315 		 * a potentially unsupported configuration. Otherwise,
2316 		 * individual bucket replacement notifications would need to be
2317 		 * vetoed, which is something that should only happen if the
2318 		 * bucket is currently active.
2319 		 */
2320 		err = call_nexthop_res_table_notifiers(net, new, extack);
2321 		if (err)
2322 			return err;
2323 
2324 		if (cfg->nh_grp_res_has_idle_timer)
2325 			old_res_table->idle_timer = cfg->nh_grp_res_idle_timer;
2326 		if (cfg->nh_grp_res_has_unbalanced_timer)
2327 			old_res_table->unbalanced_timer =
2328 				cfg->nh_grp_res_unbalanced_timer;
2329 
2330 		replace_nexthop_grp_res(oldg, newg);
2331 
2332 		tmp_table = new_res_table;
2333 		rcu_assign_pointer(newg->res_table, old_res_table);
2334 		rcu_assign_pointer(newg->spare->res_table, old_res_table);
2335 	}
2336 
2337 	/* update parents - used by nexthop code for cleanup */
2338 	for (i = 0; i < newg->num_nh; i++)
2339 		newg->nh_entries[i].nh_parent = old;
2340 
2341 	rcu_assign_pointer(old->nh_grp, newg);
2342 
2343 	/* Make sure concurrent readers are not using 'oldg' anymore. */
2344 	synchronize_net();
2345 
2346 	if (newg->resilient) {
2347 		rcu_assign_pointer(oldg->res_table, tmp_table);
2348 		rcu_assign_pointer(oldg->spare->res_table, tmp_table);
2349 	}
2350 
2351 	for (i = 0; i < oldg->num_nh; i++)
2352 		oldg->nh_entries[i].nh_parent = new;
2353 
2354 	rcu_assign_pointer(new->nh_grp, oldg);
2355 
2356 	return 0;
2357 }
2358 
2359 static void nh_group_v4_update(struct nh_group *nhg)
2360 {
2361 	struct nh_grp_entry *nhges;
2362 	bool has_v4 = false;
2363 	int i;
2364 
2365 	nhges = nhg->nh_entries;
2366 	for (i = 0; i < nhg->num_nh; i++) {
2367 		struct nh_info *nhi;
2368 
2369 		nhi = rtnl_dereference(nhges[i].nh->nh_info);
2370 		if (nhi->family == AF_INET)
2371 			has_v4 = true;
2372 	}
2373 	nhg->has_v4 = has_v4;
2374 }
2375 
2376 static int replace_nexthop_single_notify_res(struct net *net,
2377 					     struct nh_res_table *res_table,
2378 					     struct nexthop *old,
2379 					     struct nh_info *oldi,
2380 					     struct nh_info *newi,
2381 					     struct netlink_ext_ack *extack)
2382 {
2383 	u32 nhg_id = res_table->nhg_id;
2384 	int err;
2385 	u16 i;
2386 
2387 	for (i = 0; i < res_table->num_nh_buckets; i++) {
2388 		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
2389 		struct nh_grp_entry *nhge;
2390 
2391 		nhge = rtnl_dereference(bucket->nh_entry);
2392 		if (nhge->nh == old) {
2393 			err = __call_nexthop_res_bucket_notifiers(net, nhg_id,
2394 								  i, true,
2395 								  oldi, newi,
2396 								  extack);
2397 			if (err)
2398 				goto err_notify;
2399 		}
2400 	}
2401 
2402 	return 0;
2403 
2404 err_notify:
2405 	while (i-- > 0) {
2406 		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
2407 		struct nh_grp_entry *nhge;
2408 
2409 		nhge = rtnl_dereference(bucket->nh_entry);
2410 		if (nhge->nh == old)
2411 			__call_nexthop_res_bucket_notifiers(net, nhg_id, i,
2412 							    true, newi, oldi,
2413 							    extack);
2414 	}
2415 	return err;
2416 }
2417 
2418 static int replace_nexthop_single_notify(struct net *net,
2419 					 struct nexthop *group_nh,
2420 					 struct nexthop *old,
2421 					 struct nh_info *oldi,
2422 					 struct nh_info *newi,
2423 					 struct netlink_ext_ack *extack)
2424 {
2425 	struct nh_group *nhg = rtnl_dereference(group_nh->nh_grp);
2426 	struct nh_res_table *res_table;
2427 
2428 	if (nhg->hash_threshold) {
2429 		return call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE,
2430 					      group_nh, extack);
2431 	} else if (nhg->resilient) {
2432 		res_table = rtnl_dereference(nhg->res_table);
2433 		return replace_nexthop_single_notify_res(net, res_table,
2434 							 old, oldi, newi,
2435 							 extack);
2436 	}
2437 
2438 	return -EINVAL;
2439 }
2440 
2441 static int replace_nexthop_single(struct net *net, struct nexthop *old,
2442 				  struct nexthop *new,
2443 				  struct netlink_ext_ack *extack)
2444 {
2445 	u8 old_protocol, old_nh_flags;
2446 	struct nh_info *oldi, *newi;
2447 	struct nh_grp_entry *nhge;
2448 	int err;
2449 
2450 	if (new->is_group) {
2451 		NL_SET_ERR_MSG(extack, "Can not replace a nexthop with a nexthop group.");
2452 		return -EINVAL;
2453 	}
2454 
2455 	if (!list_empty(&old->grp_list) &&
2456 	    rtnl_dereference(new->nh_info)->fdb_nh !=
2457 	    rtnl_dereference(old->nh_info)->fdb_nh) {
2458 		NL_SET_ERR_MSG(extack, "Cannot change nexthop FDB status while in a group");
2459 		return -EINVAL;
2460 	}
2461 
2462 	err = call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, new, extack);
2463 	if (err)
2464 		return err;
2465 
2466 	/* Hardware flags were set on 'old' as 'new' is not in the red-black
2467 	 * tree. Therefore, inherit the flags from 'old' to 'new'.
2468 	 */
2469 	new->nh_flags |= old->nh_flags & (RTNH_F_OFFLOAD | RTNH_F_TRAP);
2470 
2471 	oldi = rtnl_dereference(old->nh_info);
2472 	newi = rtnl_dereference(new->nh_info);
2473 
2474 	newi->nh_parent = old;
2475 	oldi->nh_parent = new;
2476 
2477 	old_protocol = old->protocol;
2478 	old_nh_flags = old->nh_flags;
2479 
2480 	old->protocol = new->protocol;
2481 	old->nh_flags = new->nh_flags;
2482 
2483 	rcu_assign_pointer(old->nh_info, newi);
2484 	rcu_assign_pointer(new->nh_info, oldi);
2485 
2486 	/* Send a replace notification for all the groups using the nexthop. */
2487 	list_for_each_entry(nhge, &old->grp_list, nh_list) {
2488 		struct nexthop *nhp = nhge->nh_parent;
2489 
2490 		err = replace_nexthop_single_notify(net, nhp, old, oldi, newi,
2491 						    extack);
2492 		if (err)
2493 			goto err_notify;
2494 	}
2495 
2496 	/* When replacing a nexthop with one of a different family, potentially
2497 	 * update IPv4 indication in all the groups using the nexthop.
2498 	 */
2499 	if (oldi->family != newi->family) {
2500 		list_for_each_entry(nhge, &old->grp_list, nh_list) {
2501 			struct nexthop *nhp = nhge->nh_parent;
2502 			struct nh_group *nhg;
2503 
2504 			nhg = rtnl_dereference(nhp->nh_grp);
2505 			nh_group_v4_update(nhg);
2506 		}
2507 	}
2508 
2509 	return 0;
2510 
2511 err_notify:
2512 	rcu_assign_pointer(new->nh_info, newi);
2513 	rcu_assign_pointer(old->nh_info, oldi);
2514 	old->nh_flags = old_nh_flags;
2515 	old->protocol = old_protocol;
2516 	oldi->nh_parent = old;
2517 	newi->nh_parent = new;
2518 	list_for_each_entry_continue_reverse(nhge, &old->grp_list, nh_list) {
2519 		struct nexthop *nhp = nhge->nh_parent;
2520 
2521 		replace_nexthop_single_notify(net, nhp, old, newi, oldi, NULL);
2522 	}
2523 	call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, old, extack);
2524 	return err;
2525 }
2526 
2527 static void __nexthop_replace_notify(struct net *net, struct nexthop *nh,
2528 				     struct nl_info *info)
2529 {
2530 	struct fib6_info *f6i;
2531 
2532 	if (!list_empty(&nh->fi_list)) {
2533 		struct fib_info *fi;
2534 
2535 		/* expectation is a few fib_info per nexthop and then
2536 		 * a lot of routes per fib_info. So mark the fib_info
2537 		 * and then walk the fib tables once
2538 		 */
2539 		list_for_each_entry(fi, &nh->fi_list, nh_list)
2540 			fi->nh_updated = true;
2541 
2542 		fib_info_notify_update(net, info);
2543 
2544 		list_for_each_entry(fi, &nh->fi_list, nh_list)
2545 			fi->nh_updated = false;
2546 	}
2547 
2548 	spin_lock_bh(&nh->lock);
2549 	list_for_each_entry(f6i, &nh->f6i_list, nh_list)
2550 		fib6_rt_update(net, f6i, info);
2551 	spin_unlock_bh(&nh->lock);
2552 }
2553 
2554 /* send RTM_NEWROUTE with REPLACE flag set for all FIB entries
2555  * linked to this nexthop and for all groups that the nexthop
2556  * is a member of
2557  */
2558 static void nexthop_replace_notify(struct net *net, struct nexthop *nh,
2559 				   struct nl_info *info)
2560 {
2561 	struct nh_grp_entry *nhge;
2562 
2563 	__nexthop_replace_notify(net, nh, info);
2564 
2565 	list_for_each_entry(nhge, &nh->grp_list, nh_list)
2566 		__nexthop_replace_notify(net, nhge->nh_parent, info);
2567 }
2568 
2569 static int replace_nexthop(struct net *net, struct nexthop *old,
2570 			   struct nexthop *new, const struct nh_config *cfg,
2571 			   struct netlink_ext_ack *extack)
2572 {
2573 	bool new_is_reject = false;
2574 	struct nh_grp_entry *nhge;
2575 	int err;
2576 
2577 	/* check that existing FIB entries are ok with the
2578 	 * new nexthop definition
2579 	 */
2580 	err = fib_check_nh_list(old, new, extack);
2581 	if (err)
2582 		return err;
2583 
2584 	err = fib6_check_nh_list(old, new, extack);
2585 	if (err)
2586 		return err;
2587 
2588 	if (!new->is_group) {
2589 		struct nh_info *nhi = rtnl_dereference(new->nh_info);
2590 
2591 		new_is_reject = nhi->reject_nh;
2592 	}
2593 
2594 	list_for_each_entry(nhge, &old->grp_list, nh_list) {
2595 		/* if new nexthop is a blackhole, any groups using this
2596 		 * nexthop cannot have more than 1 path
2597 		 */
2598 		if (new_is_reject &&
2599 		    nexthop_num_path(nhge->nh_parent) > 1) {
2600 			NL_SET_ERR_MSG(extack, "Blackhole nexthop can not be a member of a group with more than one path");
2601 			return -EINVAL;
2602 		}
2603 
2604 		err = fib_check_nh_list(nhge->nh_parent, new, extack);
2605 		if (err)
2606 			return err;
2607 
2608 		err = fib6_check_nh_list(nhge->nh_parent, new, extack);
2609 		if (err)
2610 			return err;
2611 	}
2612 
2613 	if (old->is_group)
2614 		err = replace_nexthop_grp(net, old, new, cfg, extack);
2615 	else
2616 		err = replace_nexthop_single(net, old, new, extack);
2617 
2618 	if (!err) {
2619 		nh_rt_cache_flush(net, old, new);
2620 
2621 		WARN_ON_ONCE(__remove_nexthop(net, new, NULL));
2622 		nexthop_put(new);
2623 	}
2624 
2625 	return err;
2626 }
2627 
2628 /* called with rtnl_lock held */
2629 static int insert_nexthop(struct net *net, struct nexthop *new_nh,
2630 			  struct nh_config *cfg, struct netlink_ext_ack *extack)
2631 {
2632 	struct rb_node **pp, *parent = NULL, *next;
2633 	struct rb_root *root = &net->nexthop.rb_root;
2634 	bool replace = !!(cfg->nlflags & NLM_F_REPLACE);
2635 	bool create = !!(cfg->nlflags & NLM_F_CREATE);
2636 	u32 new_id = new_nh->id;
2637 	int replace_notify = 0;
2638 	int rc = -EEXIST;
2639 
2640 	pp = &root->rb_node;
2641 	while (1) {
2642 		struct nexthop *nh;
2643 
2644 		next = *pp;
2645 		if (!next)
2646 			break;
2647 
2648 		parent = next;
2649 
2650 		nh = rb_entry(parent, struct nexthop, rb_node);
2651 		if (new_id < nh->id) {
2652 			pp = &next->rb_left;
2653 		} else if (new_id > nh->id) {
2654 			pp = &next->rb_right;
2655 		} else if (replace) {
2656 			rc = replace_nexthop(net, nh, new_nh, cfg, extack);
2657 			if (!rc) {
2658 				new_nh = nh; /* send notification with old nh */
2659 				replace_notify = 1;
2660 			}
2661 			goto out;
2662 		} else {
2663 			/* id already exists and not a replace */
2664 			goto out;
2665 		}
2666 	}
2667 
2668 	if (replace && !create) {
2669 		NL_SET_ERR_MSG(extack, "Replace specified without create and no entry exists");
2670 		rc = -ENOENT;
2671 		goto out;
2672 	}
2673 
2674 	if (new_nh->is_group) {
2675 		struct nh_group *nhg = rtnl_dereference(new_nh->nh_grp);
2676 		struct nh_res_table *res_table;
2677 
2678 		if (nhg->resilient) {
2679 			res_table = rtnl_dereference(nhg->res_table);
2680 
2681 			/* Not passing the number of buckets is OK when
2682 			 * replacing, but not when creating a new group.
2683 			 */
2684 			if (!cfg->nh_grp_res_has_num_buckets) {
2685 				NL_SET_ERR_MSG(extack, "Number of buckets not specified for nexthop group insertion");
2686 				rc = -EINVAL;
2687 				goto out;
2688 			}
2689 
2690 			nh_res_group_rebalance(nhg, res_table);
2691 
2692 			/* Do not send bucket notifications, we do full
2693 			 * notification below.
2694 			 */
2695 			nh_res_table_upkeep(res_table, false, false);
2696 		}
2697 	}
2698 
2699 	rb_link_node_rcu(&new_nh->rb_node, parent, pp);
2700 	rb_insert_color(&new_nh->rb_node, root);
2701 
2702 	/* The initial insertion is a full notification for hash-threshold as
2703 	 * well as resilient groups.
2704 	 */
2705 	rc = call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, new_nh, extack);
2706 	if (rc)
2707 		rb_erase(&new_nh->rb_node, &net->nexthop.rb_root);
2708 
2709 out:
2710 	if (!rc) {
2711 		nh_base_seq_inc(net);
2712 		nexthop_notify(RTM_NEWNEXTHOP, new_nh, &cfg->nlinfo);
2713 		if (replace_notify &&
2714 		    READ_ONCE(net->ipv4.sysctl_nexthop_compat_mode))
2715 			nexthop_replace_notify(net, new_nh, &cfg->nlinfo);
2716 	}
2717 
2718 	return rc;
2719 }
2720 
2721 /* rtnl */
2722 /* remove all nexthops tied to a device being deleted */
2723 static void nexthop_flush_dev(struct net_device *dev, unsigned long event)
2724 {
2725 	unsigned int hash = nh_dev_hashfn(dev->ifindex);
2726 	struct net *net = dev_net(dev);
2727 	struct hlist_head *head = &net->nexthop.devhash[hash];
2728 	bool need_flush = false;
2729 	struct hlist_node *n;
2730 	struct nh_info *nhi;
2731 
2732 	hlist_for_each_entry_safe(nhi, n, head, dev_hash) {
2733 		if (nhi->fib_nhc.nhc_dev != dev)
2734 			continue;
2735 
2736 		if (nhi->reject_nh &&
2737 		    (event == NETDEV_DOWN || event == NETDEV_CHANGE))
2738 			continue;
2739 
2740 		need_flush |= remove_nexthop(net, nhi->nh_parent, NULL);
2741 	}
2742 
2743 	if (need_flush)
2744 		fib_flush(net);
2745 }
2746 
2747 /* rtnl; called when net namespace is deleted */
2748 static void flush_all_nexthops(struct net *net)
2749 {
2750 	struct rb_root *root = &net->nexthop.rb_root;
2751 	bool need_flush = false;
2752 	struct rb_node *node;
2753 	struct nexthop *nh;
2754 
2755 	while ((node = rb_first(root))) {
2756 		nh = rb_entry(node, struct nexthop, rb_node);
2757 		need_flush |= remove_nexthop(net, nh, NULL);
2758 		cond_resched();
2759 	}
2760 	if (need_flush)
2761 		fib_flush(net);
2762 }
2763 
2764 static struct nexthop *nexthop_create_group(struct net *net,
2765 					    struct nh_config *cfg)
2766 {
2767 	struct nlattr *grps_attr = cfg->nh_grp;
2768 	struct nexthop_grp *entry = nla_data(grps_attr);
2769 	u16 num_nh = nla_len(grps_attr) / sizeof(*entry);
2770 	struct nh_group *nhg;
2771 	struct nexthop *nh;
2772 	int err;
2773 	int i;
2774 
2775 	nh = nexthop_alloc();
2776 	if (!nh)
2777 		return ERR_PTR(-ENOMEM);
2778 
2779 	nh->is_group = 1;
2780 
2781 	nhg = nexthop_grp_alloc(num_nh);
2782 	if (!nhg) {
2783 		kfree(nh);
2784 		return ERR_PTR(-ENOMEM);
2785 	}
2786 
2787 	/* spare group used for removals */
2788 	nhg->spare = nexthop_grp_alloc(num_nh);
2789 	if (!nhg->spare) {
2790 		kfree(nhg);
2791 		kfree(nh);
2792 		return ERR_PTR(-ENOMEM);
2793 	}
2794 	nhg->spare->spare = nhg;
2795 
2796 	for (i = 0; i < nhg->num_nh; ++i) {
2797 		struct nexthop *nhe;
2798 		struct nh_info *nhi;
2799 
2800 		nhe = nexthop_find_by_id(net, entry[i].id);
2801 		if (!nexthop_get(nhe)) {
2802 			err = -ENOENT;
2803 			goto out_no_nh;
2804 		}
2805 
2806 		nhi = rtnl_dereference(nhe->nh_info);
2807 		if (nhi->family == AF_INET)
2808 			nhg->has_v4 = true;
2809 
2810 		nhg->nh_entries[i].stats =
2811 			netdev_alloc_pcpu_stats(struct nh_grp_entry_stats);
2812 		if (!nhg->nh_entries[i].stats) {
2813 			err = -ENOMEM;
2814 			nexthop_put(nhe);
2815 			goto out_no_nh;
2816 		}
2817 		nhg->nh_entries[i].nh = nhe;
2818 		nhg->nh_entries[i].weight = nexthop_grp_weight(&entry[i]);
2819 
2820 		list_add(&nhg->nh_entries[i].nh_list, &nhe->grp_list);
2821 		nhg->nh_entries[i].nh_parent = nh;
2822 	}
2823 
2824 	if (cfg->nh_grp_type == NEXTHOP_GRP_TYPE_MPATH) {
2825 		nhg->hash_threshold = 1;
2826 		nhg->is_multipath = true;
2827 	} else if (cfg->nh_grp_type == NEXTHOP_GRP_TYPE_RES) {
2828 		struct nh_res_table *res_table;
2829 
2830 		res_table = nexthop_res_table_alloc(net, cfg->nh_id, cfg);
2831 		if (!res_table) {
2832 			err = -ENOMEM;
2833 			goto out_no_nh;
2834 		}
2835 
2836 		rcu_assign_pointer(nhg->spare->res_table, res_table);
2837 		rcu_assign_pointer(nhg->res_table, res_table);
2838 		nhg->resilient = true;
2839 		nhg->is_multipath = true;
2840 	}
2841 
2842 	WARN_ON_ONCE(nhg->hash_threshold + nhg->resilient != 1);
2843 
2844 	if (nhg->hash_threshold)
2845 		nh_hthr_group_rebalance(nhg);
2846 
2847 	if (cfg->nh_fdb)
2848 		nhg->fdb_nh = 1;
2849 
2850 	if (cfg->nh_hw_stats)
2851 		nhg->hw_stats = true;
2852 
2853 	rcu_assign_pointer(nh->nh_grp, nhg);
2854 
2855 	return nh;
2856 
2857 out_no_nh:
2858 	for (i--; i >= 0; --i) {
2859 		list_del(&nhg->nh_entries[i].nh_list);
2860 		free_percpu(nhg->nh_entries[i].stats);
2861 		nexthop_put(nhg->nh_entries[i].nh);
2862 	}
2863 
2864 	kfree(nhg->spare);
2865 	kfree(nhg);
2866 	kfree(nh);
2867 
2868 	return ERR_PTR(err);
2869 }
2870 
2871 static int nh_create_ipv4(struct net *net, struct nexthop *nh,
2872 			  struct nh_info *nhi, struct nh_config *cfg,
2873 			  struct netlink_ext_ack *extack)
2874 {
2875 	struct fib_nh *fib_nh = &nhi->fib_nh;
2876 	struct fib_config fib_cfg = {
2877 		.fc_oif   = cfg->nh_ifindex,
2878 		.fc_gw4   = cfg->gw.ipv4,
2879 		.fc_gw_family = cfg->gw.ipv4 ? AF_INET : 0,
2880 		.fc_flags = cfg->nh_flags,
2881 		.fc_nlinfo = cfg->nlinfo,
2882 		.fc_encap = cfg->nh_encap,
2883 		.fc_encap_type = cfg->nh_encap_type,
2884 	};
2885 	u32 tb_id = (cfg->dev ? l3mdev_fib_table(cfg->dev) : RT_TABLE_MAIN);
2886 	int err;
2887 
2888 	err = fib_nh_init(net, fib_nh, &fib_cfg, 1, extack);
2889 	if (err) {
2890 		fib_nh_release(net, fib_nh);
2891 		goto out;
2892 	}
2893 
2894 	if (nhi->fdb_nh)
2895 		goto out;
2896 
2897 	/* sets nh_dev if successful */
2898 	err = fib_check_nh(net, fib_nh, tb_id, 0, extack);
2899 	if (!err) {
2900 		nh->nh_flags = fib_nh->fib_nh_flags;
2901 		fib_info_update_nhc_saddr(net, &fib_nh->nh_common,
2902 					  !fib_nh->fib_nh_scope ? 0 : fib_nh->fib_nh_scope - 1);
2903 	} else {
2904 		fib_nh_release(net, fib_nh);
2905 	}
2906 out:
2907 	return err;
2908 }
2909 
2910 static int nh_create_ipv6(struct net *net,  struct nexthop *nh,
2911 			  struct nh_info *nhi, struct nh_config *cfg,
2912 			  struct netlink_ext_ack *extack)
2913 {
2914 	struct fib6_nh *fib6_nh = &nhi->fib6_nh;
2915 	struct fib6_config fib6_cfg = {
2916 		.fc_table = l3mdev_fib_table(cfg->dev),
2917 		.fc_ifindex = cfg->nh_ifindex,
2918 		.fc_gateway = cfg->gw.ipv6,
2919 		.fc_flags = cfg->nh_flags,
2920 		.fc_nlinfo = cfg->nlinfo,
2921 		.fc_encap = cfg->nh_encap,
2922 		.fc_encap_type = cfg->nh_encap_type,
2923 		.fc_is_fdb = cfg->nh_fdb,
2924 	};
2925 	int err;
2926 
2927 	if (!ipv6_addr_any(&cfg->gw.ipv6))
2928 		fib6_cfg.fc_flags |= RTF_GATEWAY;
2929 
2930 	/* sets nh_dev if successful */
2931 	err = fib6_nh_init(net, fib6_nh, &fib6_cfg, GFP_KERNEL, extack);
2932 	if (err) {
2933 		/* IPv6 is not enabled, don't call fib6_nh_release */
2934 		if (err == -EAFNOSUPPORT)
2935 			goto out;
2936 		fib6_nh_release(fib6_nh);
2937 	} else {
2938 		nh->nh_flags = fib6_nh->fib_nh_flags;
2939 	}
2940 out:
2941 	return err;
2942 }
2943 
2944 static struct nexthop *nexthop_create(struct net *net, struct nh_config *cfg,
2945 				      struct netlink_ext_ack *extack)
2946 {
2947 	struct nh_info *nhi;
2948 	struct nexthop *nh;
2949 	int err = 0;
2950 
2951 	nh = nexthop_alloc();
2952 	if (!nh)
2953 		return ERR_PTR(-ENOMEM);
2954 
2955 	nhi = kzalloc_obj(*nhi);
2956 	if (!nhi) {
2957 		kfree(nh);
2958 		return ERR_PTR(-ENOMEM);
2959 	}
2960 
2961 	nh->nh_flags = cfg->nh_flags;
2962 	nh->net = net;
2963 
2964 	nhi->nh_parent = nh;
2965 	nhi->family = cfg->nh_family;
2966 	nhi->fib_nhc.nhc_scope = RT_SCOPE_LINK;
2967 
2968 	if (cfg->nh_fdb)
2969 		nhi->fdb_nh = 1;
2970 
2971 	if (cfg->nh_blackhole) {
2972 		nhi->reject_nh = 1;
2973 		cfg->nh_ifindex = net->loopback_dev->ifindex;
2974 	}
2975 
2976 	switch (cfg->nh_family) {
2977 	case AF_INET:
2978 		err = nh_create_ipv4(net, nh, nhi, cfg, extack);
2979 		break;
2980 	case AF_INET6:
2981 		err = nh_create_ipv6(net, nh, nhi, cfg, extack);
2982 		break;
2983 	}
2984 
2985 	if (err) {
2986 		kfree(nhi);
2987 		kfree(nh);
2988 		return ERR_PTR(err);
2989 	}
2990 
2991 	/* add the entry to the device based hash */
2992 	if (!nhi->fdb_nh)
2993 		nexthop_devhash_add(net, nhi);
2994 
2995 	rcu_assign_pointer(nh->nh_info, nhi);
2996 
2997 	return nh;
2998 }
2999 
3000 /* called with rtnl lock held */
3001 static struct nexthop *nexthop_add(struct net *net, struct nh_config *cfg,
3002 				   struct netlink_ext_ack *extack)
3003 {
3004 	struct nexthop *nh;
3005 	int err;
3006 
3007 	if (!cfg->nh_id) {
3008 		cfg->nh_id = nh_find_unused_id(net);
3009 		if (!cfg->nh_id) {
3010 			NL_SET_ERR_MSG(extack, "No unused id");
3011 			return ERR_PTR(-EINVAL);
3012 		}
3013 	}
3014 
3015 	if (cfg->nh_grp)
3016 		nh = nexthop_create_group(net, cfg);
3017 	else
3018 		nh = nexthop_create(net, cfg, extack);
3019 
3020 	if (IS_ERR(nh))
3021 		return nh;
3022 
3023 	refcount_set(&nh->refcnt, 1);
3024 	nh->id = cfg->nh_id;
3025 	nh->protocol = cfg->nh_protocol;
3026 	nh->net = net;
3027 
3028 	err = insert_nexthop(net, nh, cfg, extack);
3029 	if (err) {
3030 		WARN_ON_ONCE(__remove_nexthop(net, nh, NULL));
3031 		nexthop_put(nh);
3032 		nh = ERR_PTR(err);
3033 	}
3034 
3035 	return nh;
3036 }
3037 
3038 static int rtm_nh_get_timer(struct nlattr *attr, unsigned long fallback,
3039 			    unsigned long *timer_p, bool *has_p,
3040 			    struct netlink_ext_ack *extack)
3041 {
3042 	unsigned long timer;
3043 	u32 value;
3044 
3045 	if (!attr) {
3046 		*timer_p = fallback;
3047 		*has_p = false;
3048 		return 0;
3049 	}
3050 
3051 	value = nla_get_u32(attr);
3052 	timer = clock_t_to_jiffies(value);
3053 	if (timer == ~0UL) {
3054 		NL_SET_ERR_MSG(extack, "Timer value too large");
3055 		return -EINVAL;
3056 	}
3057 
3058 	*timer_p = timer;
3059 	*has_p = true;
3060 	return 0;
3061 }
3062 
3063 static int rtm_to_nh_config_grp_res(struct nlattr *res, struct nh_config *cfg,
3064 				    struct netlink_ext_ack *extack)
3065 {
3066 	struct nlattr *tb[ARRAY_SIZE(rtm_nh_res_policy_new)] = {};
3067 	int err;
3068 
3069 	if (res) {
3070 		err = nla_parse_nested(tb,
3071 				       ARRAY_SIZE(rtm_nh_res_policy_new) - 1,
3072 				       res, rtm_nh_res_policy_new, extack);
3073 		if (err < 0)
3074 			return err;
3075 	}
3076 
3077 	if (tb[NHA_RES_GROUP_BUCKETS]) {
3078 		cfg->nh_grp_res_num_buckets =
3079 			nla_get_u16(tb[NHA_RES_GROUP_BUCKETS]);
3080 		cfg->nh_grp_res_has_num_buckets = true;
3081 		if (!cfg->nh_grp_res_num_buckets) {
3082 			NL_SET_ERR_MSG(extack, "Number of buckets needs to be non-0");
3083 			return -EINVAL;
3084 		}
3085 	}
3086 
3087 	err = rtm_nh_get_timer(tb[NHA_RES_GROUP_IDLE_TIMER],
3088 			       NH_RES_DEFAULT_IDLE_TIMER,
3089 			       &cfg->nh_grp_res_idle_timer,
3090 			       &cfg->nh_grp_res_has_idle_timer,
3091 			       extack);
3092 	if (err)
3093 		return err;
3094 
3095 	return rtm_nh_get_timer(tb[NHA_RES_GROUP_UNBALANCED_TIMER],
3096 				NH_RES_DEFAULT_UNBALANCED_TIMER,
3097 				&cfg->nh_grp_res_unbalanced_timer,
3098 				&cfg->nh_grp_res_has_unbalanced_timer,
3099 				extack);
3100 }
3101 
3102 static int rtm_to_nh_config(struct net *net, struct sk_buff *skb,
3103 			    struct nlmsghdr *nlh, struct nlattr **tb,
3104 			    struct nh_config *cfg,
3105 			    struct netlink_ext_ack *extack)
3106 {
3107 	struct nhmsg *nhm = nlmsg_data(nlh);
3108 	int err;
3109 
3110 	err = -EINVAL;
3111 	if (nhm->resvd || nhm->nh_scope) {
3112 		NL_SET_ERR_MSG(extack, "Invalid values in ancillary header");
3113 		goto out;
3114 	}
3115 	if (nhm->nh_flags & ~NEXTHOP_VALID_USER_FLAGS) {
3116 		NL_SET_ERR_MSG(extack, "Invalid nexthop flags in ancillary header");
3117 		goto out;
3118 	}
3119 
3120 	switch (nhm->nh_family) {
3121 	case AF_INET:
3122 	case AF_INET6:
3123 		break;
3124 	case AF_UNSPEC:
3125 		if (tb[NHA_GROUP])
3126 			break;
3127 		fallthrough;
3128 	default:
3129 		NL_SET_ERR_MSG(extack, "Invalid address family");
3130 		goto out;
3131 	}
3132 
3133 	memset(cfg, 0, sizeof(*cfg));
3134 	cfg->nlflags = nlh->nlmsg_flags;
3135 	cfg->nlinfo.portid = NETLINK_CB(skb).portid;
3136 	cfg->nlinfo.nlh = nlh;
3137 	cfg->nlinfo.nl_net = net;
3138 
3139 	cfg->nh_family = nhm->nh_family;
3140 	cfg->nh_protocol = nhm->nh_protocol;
3141 	cfg->nh_flags = nhm->nh_flags;
3142 
3143 	if (tb[NHA_ID])
3144 		cfg->nh_id = nla_get_u32(tb[NHA_ID]);
3145 
3146 	if (tb[NHA_FDB]) {
3147 		if (tb[NHA_OIF] || tb[NHA_BLACKHOLE] ||
3148 		    tb[NHA_ENCAP]   || tb[NHA_ENCAP_TYPE]) {
3149 			NL_SET_ERR_MSG(extack, "Fdb attribute can not be used with encap, oif or blackhole");
3150 			goto out;
3151 		}
3152 		if (nhm->nh_flags) {
3153 			NL_SET_ERR_MSG(extack, "Unsupported nexthop flags in ancillary header");
3154 			goto out;
3155 		}
3156 		cfg->nh_fdb = nla_get_flag(tb[NHA_FDB]);
3157 	}
3158 
3159 	if (tb[NHA_GROUP]) {
3160 		if (nhm->nh_family != AF_UNSPEC) {
3161 			NL_SET_ERR_MSG(extack, "Invalid family for group");
3162 			goto out;
3163 		}
3164 		cfg->nh_grp = tb[NHA_GROUP];
3165 
3166 		cfg->nh_grp_type = NEXTHOP_GRP_TYPE_MPATH;
3167 		if (tb[NHA_GROUP_TYPE])
3168 			cfg->nh_grp_type = nla_get_u16(tb[NHA_GROUP_TYPE]);
3169 
3170 		if (cfg->nh_grp_type > NEXTHOP_GRP_TYPE_MAX) {
3171 			NL_SET_ERR_MSG(extack, "Invalid group type");
3172 			goto out;
3173 		}
3174 
3175 		err = nh_check_attr_group(net, tb, ARRAY_SIZE(rtm_nh_policy_new),
3176 					  cfg->nh_grp_type, extack);
3177 		if (err)
3178 			goto out;
3179 
3180 		if (cfg->nh_grp_type == NEXTHOP_GRP_TYPE_RES)
3181 			err = rtm_to_nh_config_grp_res(tb[NHA_RES_GROUP],
3182 						       cfg, extack);
3183 
3184 		if (tb[NHA_HW_STATS_ENABLE])
3185 			cfg->nh_hw_stats = nla_get_u32(tb[NHA_HW_STATS_ENABLE]);
3186 
3187 		/* no other attributes should be set */
3188 		goto out;
3189 	}
3190 
3191 	if (tb[NHA_BLACKHOLE]) {
3192 		if (tb[NHA_GATEWAY] || tb[NHA_OIF] ||
3193 		    tb[NHA_ENCAP]   || tb[NHA_ENCAP_TYPE] || tb[NHA_FDB]) {
3194 			NL_SET_ERR_MSG(extack, "Blackhole attribute can not be used with gateway, oif, encap or fdb");
3195 			goto out;
3196 		}
3197 
3198 		cfg->nh_blackhole = 1;
3199 		err = 0;
3200 		goto out;
3201 	}
3202 
3203 	if (!cfg->nh_fdb && !tb[NHA_OIF]) {
3204 		NL_SET_ERR_MSG(extack, "Device attribute required for non-blackhole and non-fdb nexthops");
3205 		goto out;
3206 	}
3207 
3208 	err = -EINVAL;
3209 	if (tb[NHA_GATEWAY]) {
3210 		struct nlattr *gwa = tb[NHA_GATEWAY];
3211 
3212 		switch (cfg->nh_family) {
3213 		case AF_INET:
3214 			if (nla_len(gwa) != sizeof(u32)) {
3215 				NL_SET_ERR_MSG(extack, "Invalid gateway");
3216 				goto out;
3217 			}
3218 			cfg->gw.ipv4 = nla_get_be32(gwa);
3219 			break;
3220 		case AF_INET6:
3221 			if (nla_len(gwa) != sizeof(struct in6_addr)) {
3222 				NL_SET_ERR_MSG(extack, "Invalid gateway");
3223 				goto out;
3224 			}
3225 			cfg->gw.ipv6 = nla_get_in6_addr(gwa);
3226 			break;
3227 		default:
3228 			NL_SET_ERR_MSG(extack,
3229 				       "Unknown address family for gateway");
3230 			goto out;
3231 		}
3232 	} else {
3233 		/* device only nexthop (no gateway) */
3234 		if (cfg->nh_flags & RTNH_F_ONLINK) {
3235 			NL_SET_ERR_MSG(extack,
3236 				       "ONLINK flag can not be set for nexthop without a gateway");
3237 			goto out;
3238 		}
3239 	}
3240 
3241 	if (tb[NHA_ENCAP]) {
3242 		cfg->nh_encap = tb[NHA_ENCAP];
3243 
3244 		if (!tb[NHA_ENCAP_TYPE]) {
3245 			NL_SET_ERR_MSG(extack, "LWT encapsulation type is missing");
3246 			goto out;
3247 		}
3248 
3249 		cfg->nh_encap_type = nla_get_u16(tb[NHA_ENCAP_TYPE]);
3250 		err = lwtunnel_valid_encap_type(cfg->nh_encap_type, extack);
3251 		if (err < 0)
3252 			goto out;
3253 
3254 	} else if (tb[NHA_ENCAP_TYPE]) {
3255 		NL_SET_ERR_MSG(extack, "LWT encapsulation attribute is missing");
3256 		goto out;
3257 	}
3258 
3259 	if (tb[NHA_HW_STATS_ENABLE]) {
3260 		NL_SET_ERR_MSG(extack, "Cannot enable nexthop hardware statistics for non-group nexthops");
3261 		goto out;
3262 	}
3263 
3264 	err = 0;
3265 out:
3266 	return err;
3267 }
3268 
3269 static int rtm_to_nh_config_rtnl(struct net *net, struct nlattr **tb,
3270 				 struct nh_config *cfg,
3271 				 struct netlink_ext_ack *extack)
3272 {
3273 	if (tb[NHA_GROUP])
3274 		return nh_check_attr_group_rtnl(net, tb, extack);
3275 
3276 	if (tb[NHA_OIF]) {
3277 		cfg->nh_ifindex = nla_get_u32(tb[NHA_OIF]);
3278 		if (cfg->nh_ifindex)
3279 			cfg->dev = __dev_get_by_index(net, cfg->nh_ifindex);
3280 
3281 		if (!cfg->dev) {
3282 			NL_SET_ERR_MSG(extack, "Invalid device index");
3283 			return -EINVAL;
3284 		}
3285 
3286 		if (!(cfg->dev->flags & IFF_UP)) {
3287 			NL_SET_ERR_MSG(extack, "Nexthop device is not up");
3288 			return -ENETDOWN;
3289 		}
3290 
3291 		if (!netif_carrier_ok(cfg->dev)) {
3292 			NL_SET_ERR_MSG(extack, "Carrier for nexthop device is down");
3293 			return -ENETDOWN;
3294 		}
3295 	}
3296 
3297 	return 0;
3298 }
3299 
3300 /* rtnl */
3301 static int rtm_new_nexthop(struct sk_buff *skb, struct nlmsghdr *nlh,
3302 			   struct netlink_ext_ack *extack)
3303 {
3304 	struct nlattr *tb[ARRAY_SIZE(rtm_nh_policy_new)];
3305 	struct net *net = sock_net(skb->sk);
3306 	struct nh_config cfg;
3307 	struct nexthop *nh;
3308 	int err;
3309 
3310 	err = nlmsg_parse(nlh, sizeof(struct nhmsg), tb,
3311 			  ARRAY_SIZE(rtm_nh_policy_new) - 1,
3312 			  rtm_nh_policy_new, extack);
3313 	if (err < 0)
3314 		goto out;
3315 
3316 	err = rtm_to_nh_config(net, skb, nlh, tb, &cfg, extack);
3317 	if (err)
3318 		goto out;
3319 
3320 	if (cfg.nlflags & NLM_F_REPLACE && !cfg.nh_id) {
3321 		NL_SET_ERR_MSG(extack, "Replace requires nexthop id");
3322 		err = -EINVAL;
3323 		goto out;
3324 	}
3325 
3326 	rtnl_net_lock(net);
3327 
3328 	err = rtm_to_nh_config_rtnl(net, tb, &cfg, extack);
3329 	if (err)
3330 		goto unlock;
3331 
3332 	nh = nexthop_add(net, &cfg, extack);
3333 	if (IS_ERR(nh))
3334 		err = PTR_ERR(nh);
3335 
3336 unlock:
3337 	rtnl_net_unlock(net);
3338 out:
3339 	return err;
3340 }
3341 
3342 static int nh_valid_get_del_req(const struct nlmsghdr *nlh,
3343 				struct nlattr **tb, u32 *id, u32 *op_flags,
3344 				struct netlink_ext_ack *extack)
3345 {
3346 	struct nhmsg *nhm = nlmsg_data(nlh);
3347 
3348 	if (nhm->nh_protocol || nhm->resvd || nhm->nh_scope || nhm->nh_flags) {
3349 		NL_SET_ERR_MSG(extack, "Invalid values in header");
3350 		return -EINVAL;
3351 	}
3352 
3353 	if (!tb[NHA_ID]) {
3354 		NL_SET_ERR_MSG(extack, "Nexthop id is missing");
3355 		return -EINVAL;
3356 	}
3357 
3358 	*id = nla_get_u32(tb[NHA_ID]);
3359 	if (!(*id)) {
3360 		NL_SET_ERR_MSG(extack, "Invalid nexthop id");
3361 		return -EINVAL;
3362 	}
3363 
3364 	if (op_flags)
3365 		*op_flags = nla_get_u32_default(tb[NHA_OP_FLAGS], 0);
3366 
3367 	return 0;
3368 }
3369 
3370 /* rtnl */
3371 static int rtm_del_nexthop(struct sk_buff *skb, struct nlmsghdr *nlh,
3372 			   struct netlink_ext_ack *extack)
3373 {
3374 	struct nlattr *tb[ARRAY_SIZE(rtm_nh_policy_del)];
3375 	struct net *net = sock_net(skb->sk);
3376 	struct nl_info nlinfo = {
3377 		.nlh = nlh,
3378 		.nl_net = net,
3379 		.portid = NETLINK_CB(skb).portid,
3380 	};
3381 	struct nexthop *nh;
3382 	int err;
3383 	u32 id;
3384 
3385 	err = nlmsg_parse(nlh, sizeof(struct nhmsg), tb,
3386 			  ARRAY_SIZE(rtm_nh_policy_del) - 1, rtm_nh_policy_del,
3387 			  extack);
3388 	if (err < 0)
3389 		return err;
3390 
3391 	err = nh_valid_get_del_req(nlh, tb, &id, NULL, extack);
3392 	if (err)
3393 		return err;
3394 
3395 	rtnl_net_lock(net);
3396 
3397 	nh = nexthop_find_by_id(net, id);
3398 	if (nh)
3399 		remove_one_nexthop(net, nh, &nlinfo);
3400 	else
3401 		err = -ENOENT;
3402 
3403 	rtnl_net_unlock(net);
3404 
3405 	return err;
3406 }
3407 
3408 /* rtnl */
3409 static int rtm_get_nexthop(struct sk_buff *in_skb, struct nlmsghdr *nlh,
3410 			   struct netlink_ext_ack *extack)
3411 {
3412 	struct nlattr *tb[ARRAY_SIZE(rtm_nh_policy_get)];
3413 	struct net *net = sock_net(in_skb->sk);
3414 	struct sk_buff *skb = NULL;
3415 	struct nexthop *nh;
3416 	u32 op_flags;
3417 	int err;
3418 	u32 id;
3419 
3420 	err = nlmsg_parse(nlh, sizeof(struct nhmsg), tb,
3421 			  ARRAY_SIZE(rtm_nh_policy_get) - 1, rtm_nh_policy_get,
3422 			  extack);
3423 	if (err < 0)
3424 		return err;
3425 
3426 	err = nh_valid_get_del_req(nlh, tb, &id, &op_flags, extack);
3427 	if (err)
3428 		return err;
3429 
3430 	err = -ENOENT;
3431 	nh = nexthop_find_by_id(net, id);
3432 	if (!nh)
3433 		goto out;
3434 
3435 	err = -ENOBUFS;
3436 	skb = nlmsg_new(nh_nlmsg_size(nh, op_flags), GFP_KERNEL);
3437 	if (!skb)
3438 		goto out;
3439 
3440 	err = nh_fill_node(skb, nh, RTM_NEWNEXTHOP, NETLINK_CB(in_skb).portid,
3441 			   nlh->nlmsg_seq, 0, op_flags);
3442 	if (err < 0) {
3443 		WARN_ON(err == -EMSGSIZE);
3444 		goto errout_free;
3445 	}
3446 
3447 	err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
3448 out:
3449 	return err;
3450 errout_free:
3451 	kfree_skb(skb);
3452 	goto out;
3453 }
3454 
3455 struct nh_dump_filter {
3456 	u32 nh_id;
3457 	int dev_idx;
3458 	int master_idx;
3459 	bool group_filter;
3460 	bool fdb_filter;
3461 	u32 res_bucket_nh_id;
3462 	u32 op_flags;
3463 };
3464 
3465 static bool nh_dump_filtered(struct nexthop *nh,
3466 			     struct nh_dump_filter *filter, u8 family)
3467 {
3468 	const struct net_device *dev;
3469 	const struct nh_info *nhi;
3470 
3471 	if (filter->group_filter && !nh->is_group)
3472 		return true;
3473 
3474 	if (!filter->dev_idx && !filter->master_idx && !family)
3475 		return false;
3476 
3477 	if (nh->is_group)
3478 		return true;
3479 
3480 	nhi = rtnl_dereference(nh->nh_info);
3481 	if (family && nhi->family != family)
3482 		return true;
3483 
3484 	dev = nhi->fib_nhc.nhc_dev;
3485 	if (filter->dev_idx && (!dev || dev->ifindex != filter->dev_idx))
3486 		return true;
3487 
3488 	if (filter->master_idx) {
3489 		struct net_device *master;
3490 
3491 		if (!dev)
3492 			return true;
3493 
3494 		master = netdev_master_upper_dev_get((struct net_device *)dev);
3495 		if (!master || master->ifindex != filter->master_idx)
3496 			return true;
3497 	}
3498 
3499 	return false;
3500 }
3501 
3502 static int __nh_valid_dump_req(const struct nlmsghdr *nlh, struct nlattr **tb,
3503 			       struct nh_dump_filter *filter,
3504 			       struct netlink_ext_ack *extack)
3505 {
3506 	struct nhmsg *nhm;
3507 	u32 idx;
3508 
3509 	if (tb[NHA_OIF]) {
3510 		idx = nla_get_u32(tb[NHA_OIF]);
3511 		if (idx > INT_MAX) {
3512 			NL_SET_ERR_MSG(extack, "Invalid device index");
3513 			return -EINVAL;
3514 		}
3515 		filter->dev_idx = idx;
3516 	}
3517 	if (tb[NHA_MASTER]) {
3518 		idx = nla_get_u32(tb[NHA_MASTER]);
3519 		if (idx > INT_MAX) {
3520 			NL_SET_ERR_MSG(extack, "Invalid master device index");
3521 			return -EINVAL;
3522 		}
3523 		filter->master_idx = idx;
3524 	}
3525 	filter->group_filter = nla_get_flag(tb[NHA_GROUPS]);
3526 	filter->fdb_filter = nla_get_flag(tb[NHA_FDB]);
3527 
3528 	nhm = nlmsg_data(nlh);
3529 	if (nhm->nh_protocol || nhm->resvd || nhm->nh_scope || nhm->nh_flags) {
3530 		NL_SET_ERR_MSG(extack, "Invalid values in header for nexthop dump request");
3531 		return -EINVAL;
3532 	}
3533 
3534 	return 0;
3535 }
3536 
3537 static int nh_valid_dump_req(const struct nlmsghdr *nlh,
3538 			     struct nh_dump_filter *filter,
3539 			     struct netlink_callback *cb)
3540 {
3541 	struct nlattr *tb[ARRAY_SIZE(rtm_nh_policy_dump)];
3542 	int err;
3543 
3544 	err = nlmsg_parse(nlh, sizeof(struct nhmsg), tb,
3545 			  ARRAY_SIZE(rtm_nh_policy_dump) - 1,
3546 			  rtm_nh_policy_dump, cb->extack);
3547 	if (err < 0)
3548 		return err;
3549 
3550 	filter->op_flags = nla_get_u32_default(tb[NHA_OP_FLAGS], 0);
3551 
3552 	return __nh_valid_dump_req(nlh, tb, filter, cb->extack);
3553 }
3554 
3555 struct rtm_dump_nh_ctx {
3556 	u32 idx;
3557 };
3558 
3559 static struct rtm_dump_nh_ctx *
3560 rtm_dump_nh_ctx(struct netlink_callback *cb)
3561 {
3562 	struct rtm_dump_nh_ctx *ctx = (void *)cb->ctx;
3563 
3564 	BUILD_BUG_ON(sizeof(*ctx) > sizeof(cb->ctx));
3565 	return ctx;
3566 }
3567 
3568 static int rtm_dump_walk_nexthops(struct sk_buff *skb,
3569 				  struct netlink_callback *cb,
3570 				  struct rb_root *root,
3571 				  struct rtm_dump_nh_ctx *ctx,
3572 				  int (*nh_cb)(struct sk_buff *skb,
3573 					       struct netlink_callback *cb,
3574 					       struct nexthop *nh, void *data),
3575 				  void *data)
3576 {
3577 	struct rb_node *node;
3578 	int s_idx;
3579 	int err;
3580 
3581 	s_idx = ctx->idx;
3582 
3583 	/* If this is not the first invocation, ctx->idx will contain the id of
3584 	 * the last nexthop we processed. Instead of starting from the very
3585 	 * first element of the red/black tree again and linearly skipping the
3586 	 * (potentially large) set of nodes with an id smaller than s_idx, walk
3587 	 * the tree and find the left-most node whose id is >= s_idx.  This
3588 	 * provides an efficient O(log n) starting point for the dump
3589 	 * continuation.
3590 	 */
3591 	if (s_idx != 0) {
3592 		struct rb_node *tmp = root->rb_node;
3593 
3594 		node = NULL;
3595 		while (tmp) {
3596 			struct nexthop *nh;
3597 
3598 			nh = rb_entry(tmp, struct nexthop, rb_node);
3599 			if (nh->id < s_idx) {
3600 				tmp = tmp->rb_right;
3601 			} else {
3602 				/* Track current candidate and keep looking on
3603 				 * the left side to find the left-most
3604 				 * (smallest id) that is still >= s_idx.
3605 				 */
3606 				node = tmp;
3607 				tmp = tmp->rb_left;
3608 			}
3609 		}
3610 	} else {
3611 		node = rb_first(root);
3612 	}
3613 
3614 	for (; node; node = rb_next(node)) {
3615 		struct nexthop *nh;
3616 
3617 		nh = rb_entry(node, struct nexthop, rb_node);
3618 
3619 		ctx->idx = nh->id;
3620 		err = nh_cb(skb, cb, nh, data);
3621 		if (err)
3622 			return err;
3623 	}
3624 
3625 	return 0;
3626 }
3627 
3628 static int rtm_dump_nexthop_cb(struct sk_buff *skb, struct netlink_callback *cb,
3629 			       struct nexthop *nh, void *data)
3630 {
3631 	struct nhmsg *nhm = nlmsg_data(cb->nlh);
3632 	struct nh_dump_filter *filter = data;
3633 
3634 	if (nh_dump_filtered(nh, filter, nhm->nh_family))
3635 		return 0;
3636 
3637 	return nh_fill_node(skb, nh, RTM_NEWNEXTHOP,
3638 			    NETLINK_CB(cb->skb).portid,
3639 			    cb->nlh->nlmsg_seq, NLM_F_MULTI, filter->op_flags);
3640 }
3641 
3642 /* rtnl */
3643 static int rtm_dump_nexthop(struct sk_buff *skb, struct netlink_callback *cb)
3644 {
3645 	struct rtm_dump_nh_ctx *ctx = rtm_dump_nh_ctx(cb);
3646 	struct net *net = sock_net(skb->sk);
3647 	struct rb_root *root = &net->nexthop.rb_root;
3648 	struct nh_dump_filter filter = {};
3649 	int err;
3650 
3651 	err = nh_valid_dump_req(cb->nlh, &filter, cb);
3652 	if (err < 0)
3653 		return err;
3654 
3655 	err = rtm_dump_walk_nexthops(skb, cb, root, ctx,
3656 				     &rtm_dump_nexthop_cb, &filter);
3657 
3658 	cb->seq = net->nexthop.seq;
3659 	nl_dump_check_consistent(cb, nlmsg_hdr(skb));
3660 	return err;
3661 }
3662 
3663 static struct nexthop *
3664 nexthop_find_group_resilient(struct net *net, u32 id,
3665 			     struct netlink_ext_ack *extack)
3666 {
3667 	struct nh_group *nhg;
3668 	struct nexthop *nh;
3669 
3670 	nh = nexthop_find_by_id(net, id);
3671 	if (!nh)
3672 		return ERR_PTR(-ENOENT);
3673 
3674 	if (!nh->is_group) {
3675 		NL_SET_ERR_MSG(extack, "Not a nexthop group");
3676 		return ERR_PTR(-EINVAL);
3677 	}
3678 
3679 	nhg = rtnl_dereference(nh->nh_grp);
3680 	if (!nhg->resilient) {
3681 		NL_SET_ERR_MSG(extack, "Nexthop group not of type resilient");
3682 		return ERR_PTR(-EINVAL);
3683 	}
3684 
3685 	return nh;
3686 }
3687 
3688 static int nh_valid_dump_nhid(struct nlattr *attr, u32 *nh_id_p,
3689 			      struct netlink_ext_ack *extack)
3690 {
3691 	u32 idx;
3692 
3693 	if (attr) {
3694 		idx = nla_get_u32(attr);
3695 		if (!idx) {
3696 			NL_SET_ERR_MSG(extack, "Invalid nexthop id");
3697 			return -EINVAL;
3698 		}
3699 		*nh_id_p = idx;
3700 	} else {
3701 		*nh_id_p = 0;
3702 	}
3703 
3704 	return 0;
3705 }
3706 
3707 static int nh_valid_dump_bucket_req(const struct nlmsghdr *nlh,
3708 				    struct nh_dump_filter *filter,
3709 				    struct netlink_callback *cb)
3710 {
3711 	struct nlattr *res_tb[ARRAY_SIZE(rtm_nh_res_bucket_policy_dump)];
3712 	struct nlattr *tb[ARRAY_SIZE(rtm_nh_policy_dump_bucket)];
3713 	int err;
3714 
3715 	err = nlmsg_parse(nlh, sizeof(struct nhmsg), tb,
3716 			  ARRAY_SIZE(rtm_nh_policy_dump_bucket) - 1,
3717 			  rtm_nh_policy_dump_bucket, NULL);
3718 	if (err < 0)
3719 		return err;
3720 
3721 	err = nh_valid_dump_nhid(tb[NHA_ID], &filter->nh_id, cb->extack);
3722 	if (err)
3723 		return err;
3724 
3725 	if (tb[NHA_RES_BUCKET]) {
3726 		size_t max = ARRAY_SIZE(rtm_nh_res_bucket_policy_dump) - 1;
3727 
3728 		err = nla_parse_nested(res_tb, max,
3729 				       tb[NHA_RES_BUCKET],
3730 				       rtm_nh_res_bucket_policy_dump,
3731 				       cb->extack);
3732 		if (err < 0)
3733 			return err;
3734 
3735 		err = nh_valid_dump_nhid(res_tb[NHA_RES_BUCKET_NH_ID],
3736 					 &filter->res_bucket_nh_id,
3737 					 cb->extack);
3738 		if (err)
3739 			return err;
3740 	}
3741 
3742 	return __nh_valid_dump_req(nlh, tb, filter, cb->extack);
3743 }
3744 
3745 struct rtm_dump_res_bucket_ctx {
3746 	struct rtm_dump_nh_ctx nh;
3747 	u16 bucket_index;
3748 };
3749 
3750 static struct rtm_dump_res_bucket_ctx *
3751 rtm_dump_res_bucket_ctx(struct netlink_callback *cb)
3752 {
3753 	struct rtm_dump_res_bucket_ctx *ctx = (void *)cb->ctx;
3754 
3755 	BUILD_BUG_ON(sizeof(*ctx) > sizeof(cb->ctx));
3756 	return ctx;
3757 }
3758 
3759 struct rtm_dump_nexthop_bucket_data {
3760 	struct rtm_dump_res_bucket_ctx *ctx;
3761 	struct nh_dump_filter filter;
3762 };
3763 
3764 static int rtm_dump_nexthop_bucket_nh(struct sk_buff *skb,
3765 				      struct netlink_callback *cb,
3766 				      struct nexthop *nh,
3767 				      struct rtm_dump_nexthop_bucket_data *dd)
3768 {
3769 	u32 portid = NETLINK_CB(cb->skb).portid;
3770 	struct nhmsg *nhm = nlmsg_data(cb->nlh);
3771 	struct nh_res_table *res_table;
3772 	struct nh_group *nhg;
3773 	u16 bucket_index;
3774 	int err;
3775 
3776 	nhg = rtnl_dereference(nh->nh_grp);
3777 	res_table = rtnl_dereference(nhg->res_table);
3778 	for (bucket_index = dd->ctx->bucket_index;
3779 	     bucket_index < res_table->num_nh_buckets;
3780 	     bucket_index++) {
3781 		struct nh_res_bucket *bucket;
3782 		struct nh_grp_entry *nhge;
3783 
3784 		bucket = &res_table->nh_buckets[bucket_index];
3785 		nhge = rtnl_dereference(bucket->nh_entry);
3786 		if (nh_dump_filtered(nhge->nh, &dd->filter, nhm->nh_family))
3787 			continue;
3788 
3789 		if (dd->filter.res_bucket_nh_id &&
3790 		    dd->filter.res_bucket_nh_id != nhge->nh->id)
3791 			continue;
3792 
3793 		dd->ctx->bucket_index = bucket_index;
3794 		err = nh_fill_res_bucket(skb, nh, bucket, bucket_index,
3795 					 RTM_NEWNEXTHOPBUCKET, portid,
3796 					 cb->nlh->nlmsg_seq, NLM_F_MULTI,
3797 					 cb->extack);
3798 		if (err)
3799 			return err;
3800 	}
3801 
3802 	dd->ctx->bucket_index = 0;
3803 
3804 	return 0;
3805 }
3806 
3807 static int rtm_dump_nexthop_bucket_cb(struct sk_buff *skb,
3808 				      struct netlink_callback *cb,
3809 				      struct nexthop *nh, void *data)
3810 {
3811 	struct rtm_dump_nexthop_bucket_data *dd = data;
3812 	struct nh_group *nhg;
3813 
3814 	if (!nh->is_group)
3815 		return 0;
3816 
3817 	nhg = rtnl_dereference(nh->nh_grp);
3818 	if (!nhg->resilient)
3819 		return 0;
3820 
3821 	return rtm_dump_nexthop_bucket_nh(skb, cb, nh, dd);
3822 }
3823 
3824 /* rtnl */
3825 static int rtm_dump_nexthop_bucket(struct sk_buff *skb,
3826 				   struct netlink_callback *cb)
3827 {
3828 	struct rtm_dump_res_bucket_ctx *ctx = rtm_dump_res_bucket_ctx(cb);
3829 	struct rtm_dump_nexthop_bucket_data dd = { .ctx = ctx };
3830 	struct net *net = sock_net(skb->sk);
3831 	struct nexthop *nh;
3832 	int err;
3833 
3834 	err = nh_valid_dump_bucket_req(cb->nlh, &dd.filter, cb);
3835 	if (err)
3836 		return err;
3837 
3838 	if (dd.filter.nh_id) {
3839 		nh = nexthop_find_group_resilient(net, dd.filter.nh_id,
3840 						  cb->extack);
3841 		if (IS_ERR(nh))
3842 			return PTR_ERR(nh);
3843 		err = rtm_dump_nexthop_bucket_nh(skb, cb, nh, &dd);
3844 	} else {
3845 		struct rb_root *root = &net->nexthop.rb_root;
3846 
3847 		err = rtm_dump_walk_nexthops(skb, cb, root, &ctx->nh,
3848 					     &rtm_dump_nexthop_bucket_cb, &dd);
3849 	}
3850 
3851 	cb->seq = net->nexthop.seq;
3852 	nl_dump_check_consistent(cb, nlmsg_hdr(skb));
3853 	return err;
3854 }
3855 
3856 static int nh_valid_get_bucket_req_res_bucket(struct nlattr *res,
3857 					      u16 *bucket_index,
3858 					      struct netlink_ext_ack *extack)
3859 {
3860 	struct nlattr *tb[ARRAY_SIZE(rtm_nh_res_bucket_policy_get)];
3861 	int err;
3862 
3863 	err = nla_parse_nested(tb, ARRAY_SIZE(rtm_nh_res_bucket_policy_get) - 1,
3864 			       res, rtm_nh_res_bucket_policy_get, extack);
3865 	if (err < 0)
3866 		return err;
3867 
3868 	if (!tb[NHA_RES_BUCKET_INDEX]) {
3869 		NL_SET_ERR_MSG(extack, "Bucket index is missing");
3870 		return -EINVAL;
3871 	}
3872 
3873 	*bucket_index = nla_get_u16(tb[NHA_RES_BUCKET_INDEX]);
3874 	return 0;
3875 }
3876 
3877 static int nh_valid_get_bucket_req(const struct nlmsghdr *nlh,
3878 				   u32 *id, u16 *bucket_index,
3879 				   struct netlink_ext_ack *extack)
3880 {
3881 	struct nlattr *tb[ARRAY_SIZE(rtm_nh_policy_get_bucket)];
3882 	int err;
3883 
3884 	err = nlmsg_parse(nlh, sizeof(struct nhmsg), tb,
3885 			  ARRAY_SIZE(rtm_nh_policy_get_bucket) - 1,
3886 			  rtm_nh_policy_get_bucket, extack);
3887 	if (err < 0)
3888 		return err;
3889 
3890 	err = nh_valid_get_del_req(nlh, tb, id, NULL, extack);
3891 	if (err)
3892 		return err;
3893 
3894 	if (!tb[NHA_RES_BUCKET]) {
3895 		NL_SET_ERR_MSG(extack, "Bucket information is missing");
3896 		return -EINVAL;
3897 	}
3898 
3899 	err = nh_valid_get_bucket_req_res_bucket(tb[NHA_RES_BUCKET],
3900 						 bucket_index, extack);
3901 	if (err)
3902 		return err;
3903 
3904 	return 0;
3905 }
3906 
3907 /* rtnl */
3908 static int rtm_get_nexthop_bucket(struct sk_buff *in_skb, struct nlmsghdr *nlh,
3909 				  struct netlink_ext_ack *extack)
3910 {
3911 	struct net *net = sock_net(in_skb->sk);
3912 	struct nh_res_table *res_table;
3913 	struct sk_buff *skb = NULL;
3914 	struct nh_group *nhg;
3915 	struct nexthop *nh;
3916 	u16 bucket_index;
3917 	int err;
3918 	u32 id;
3919 
3920 	err = nh_valid_get_bucket_req(nlh, &id, &bucket_index, extack);
3921 	if (err)
3922 		return err;
3923 
3924 	nh = nexthop_find_group_resilient(net, id, extack);
3925 	if (IS_ERR(nh))
3926 		return PTR_ERR(nh);
3927 
3928 	nhg = rtnl_dereference(nh->nh_grp);
3929 	res_table = rtnl_dereference(nhg->res_table);
3930 	if (bucket_index >= res_table->num_nh_buckets) {
3931 		NL_SET_ERR_MSG(extack, "Bucket index out of bounds");
3932 		return -ENOENT;
3933 	}
3934 
3935 	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
3936 	if (!skb)
3937 		return -ENOBUFS;
3938 
3939 	err = nh_fill_res_bucket(skb, nh, &res_table->nh_buckets[bucket_index],
3940 				 bucket_index, RTM_NEWNEXTHOPBUCKET,
3941 				 NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
3942 				 0, extack);
3943 	if (err < 0) {
3944 		WARN_ON(err == -EMSGSIZE);
3945 		goto errout_free;
3946 	}
3947 
3948 	return rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
3949 
3950 errout_free:
3951 	kfree_skb(skb);
3952 	return err;
3953 }
3954 
3955 static void nexthop_sync_mtu(struct net_device *dev, u32 orig_mtu)
3956 {
3957 	unsigned int hash = nh_dev_hashfn(dev->ifindex);
3958 	struct net *net = dev_net(dev);
3959 	struct hlist_head *head = &net->nexthop.devhash[hash];
3960 	struct hlist_node *n;
3961 	struct nh_info *nhi;
3962 
3963 	hlist_for_each_entry_safe(nhi, n, head, dev_hash) {
3964 		if (nhi->fib_nhc.nhc_dev == dev) {
3965 			if (nhi->family == AF_INET)
3966 				fib_nhc_update_mtu(&nhi->fib_nhc, dev->mtu,
3967 						   orig_mtu);
3968 		}
3969 	}
3970 }
3971 
3972 /* rtnl */
3973 static int nh_netdev_event(struct notifier_block *this,
3974 			   unsigned long event, void *ptr)
3975 {
3976 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3977 	struct netdev_notifier_info_ext *info_ext;
3978 
3979 	switch (event) {
3980 	case NETDEV_DOWN:
3981 	case NETDEV_UNREGISTER:
3982 		nexthop_flush_dev(dev, event);
3983 		break;
3984 	case NETDEV_CHANGE:
3985 		if (!(netif_get_flags(dev) & (IFF_RUNNING | IFF_LOWER_UP)))
3986 			nexthop_flush_dev(dev, event);
3987 		break;
3988 	case NETDEV_CHANGEMTU:
3989 		info_ext = ptr;
3990 		nexthop_sync_mtu(dev, info_ext->ext.mtu);
3991 		rt_cache_flush(dev_net(dev));
3992 		break;
3993 	}
3994 	return NOTIFY_DONE;
3995 }
3996 
3997 static struct notifier_block nh_netdev_notifier = {
3998 	.notifier_call = nh_netdev_event,
3999 };
4000 
4001 static int nexthops_dump(struct net *net, struct notifier_block *nb,
4002 			 enum nexthop_event_type event_type,
4003 			 struct netlink_ext_ack *extack)
4004 {
4005 	struct rb_root *root = &net->nexthop.rb_root;
4006 	struct rb_node *node;
4007 	int err = 0;
4008 
4009 	for (node = rb_first(root); node; node = rb_next(node)) {
4010 		struct nexthop *nh;
4011 
4012 		nh = rb_entry(node, struct nexthop, rb_node);
4013 		err = call_nexthop_notifier(nb, net, event_type, nh, extack);
4014 		if (err)
4015 			break;
4016 	}
4017 
4018 	return err;
4019 }
4020 
4021 int register_nexthop_notifier(struct net *net, struct notifier_block *nb,
4022 			      struct netlink_ext_ack *extack)
4023 {
4024 	int err;
4025 
4026 	rtnl_lock();
4027 	err = nexthops_dump(net, nb, NEXTHOP_EVENT_REPLACE, extack);
4028 	if (err)
4029 		goto unlock;
4030 	err = blocking_notifier_chain_register(&net->nexthop.notifier_chain,
4031 					       nb);
4032 unlock:
4033 	rtnl_unlock();
4034 	return err;
4035 }
4036 EXPORT_SYMBOL(register_nexthop_notifier);
4037 
4038 int __unregister_nexthop_notifier(struct net *net, struct notifier_block *nb)
4039 {
4040 	int err;
4041 
4042 	err = blocking_notifier_chain_unregister(&net->nexthop.notifier_chain,
4043 						 nb);
4044 	if (!err)
4045 		nexthops_dump(net, nb, NEXTHOP_EVENT_DEL, NULL);
4046 	return err;
4047 }
4048 EXPORT_SYMBOL(__unregister_nexthop_notifier);
4049 
4050 int unregister_nexthop_notifier(struct net *net, struct notifier_block *nb)
4051 {
4052 	int err;
4053 
4054 	rtnl_lock();
4055 	err = __unregister_nexthop_notifier(net, nb);
4056 	rtnl_unlock();
4057 	return err;
4058 }
4059 EXPORT_SYMBOL(unregister_nexthop_notifier);
4060 
4061 void nexthop_set_hw_flags(struct net *net, u32 id, bool offload, bool trap)
4062 {
4063 	struct nexthop *nexthop;
4064 
4065 	rcu_read_lock();
4066 
4067 	nexthop = nexthop_find_by_id(net, id);
4068 	if (!nexthop)
4069 		goto out;
4070 
4071 	nexthop->nh_flags &= ~(RTNH_F_OFFLOAD | RTNH_F_TRAP);
4072 	if (offload)
4073 		nexthop->nh_flags |= RTNH_F_OFFLOAD;
4074 	if (trap)
4075 		nexthop->nh_flags |= RTNH_F_TRAP;
4076 
4077 out:
4078 	rcu_read_unlock();
4079 }
4080 EXPORT_SYMBOL(nexthop_set_hw_flags);
4081 
4082 void nexthop_bucket_set_hw_flags(struct net *net, u32 id, u16 bucket_index,
4083 				 bool offload, bool trap)
4084 {
4085 	struct nh_res_table *res_table;
4086 	struct nh_res_bucket *bucket;
4087 	struct nexthop *nexthop;
4088 	struct nh_group *nhg;
4089 
4090 	rcu_read_lock();
4091 
4092 	nexthop = nexthop_find_by_id(net, id);
4093 	if (!nexthop || !nexthop->is_group)
4094 		goto out;
4095 
4096 	nhg = rcu_dereference(nexthop->nh_grp);
4097 	if (!nhg->resilient)
4098 		goto out;
4099 
4100 	if (bucket_index >= nhg->res_table->num_nh_buckets)
4101 		goto out;
4102 
4103 	res_table = rcu_dereference(nhg->res_table);
4104 	bucket = &res_table->nh_buckets[bucket_index];
4105 	bucket->nh_flags &= ~(RTNH_F_OFFLOAD | RTNH_F_TRAP);
4106 	if (offload)
4107 		bucket->nh_flags |= RTNH_F_OFFLOAD;
4108 	if (trap)
4109 		bucket->nh_flags |= RTNH_F_TRAP;
4110 
4111 out:
4112 	rcu_read_unlock();
4113 }
4114 EXPORT_SYMBOL(nexthop_bucket_set_hw_flags);
4115 
4116 void nexthop_res_grp_activity_update(struct net *net, u32 id, u16 num_buckets,
4117 				     unsigned long *activity)
4118 {
4119 	struct nh_res_table *res_table;
4120 	struct nexthop *nexthop;
4121 	struct nh_group *nhg;
4122 	u16 i;
4123 
4124 	rcu_read_lock();
4125 
4126 	nexthop = nexthop_find_by_id(net, id);
4127 	if (!nexthop || !nexthop->is_group)
4128 		goto out;
4129 
4130 	nhg = rcu_dereference(nexthop->nh_grp);
4131 	if (!nhg->resilient)
4132 		goto out;
4133 
4134 	/* Instead of silently ignoring some buckets, demand that the sizes
4135 	 * be the same.
4136 	 */
4137 	res_table = rcu_dereference(nhg->res_table);
4138 	if (num_buckets != res_table->num_nh_buckets)
4139 		goto out;
4140 
4141 	for (i = 0; i < num_buckets; i++) {
4142 		if (test_bit(i, activity))
4143 			nh_res_bucket_set_busy(&res_table->nh_buckets[i]);
4144 	}
4145 
4146 out:
4147 	rcu_read_unlock();
4148 }
4149 EXPORT_SYMBOL(nexthop_res_grp_activity_update);
4150 
4151 static void __net_exit nexthop_net_exit_rtnl(struct net *net,
4152 					     struct list_head *dev_to_kill)
4153 {
4154 	ASSERT_RTNL_NET(net);
4155 	flush_all_nexthops(net);
4156 }
4157 
4158 static void __net_exit nexthop_net_exit(struct net *net)
4159 {
4160 	kfree(net->nexthop.devhash);
4161 	net->nexthop.devhash = NULL;
4162 }
4163 
4164 static int __net_init nexthop_net_init(struct net *net)
4165 {
4166 	size_t sz = sizeof(struct hlist_head) * NH_DEV_HASHSIZE;
4167 
4168 	net->nexthop.rb_root = RB_ROOT;
4169 	net->nexthop.devhash = kzalloc(sz, GFP_KERNEL);
4170 	if (!net->nexthop.devhash)
4171 		return -ENOMEM;
4172 	BLOCKING_INIT_NOTIFIER_HEAD(&net->nexthop.notifier_chain);
4173 
4174 	return 0;
4175 }
4176 
4177 static struct pernet_operations nexthop_net_ops = {
4178 	.init = nexthop_net_init,
4179 	.exit = nexthop_net_exit,
4180 	.exit_rtnl = nexthop_net_exit_rtnl,
4181 };
4182 
4183 static const struct rtnl_msg_handler nexthop_rtnl_msg_handlers[] __initconst = {
4184 	{.msgtype = RTM_NEWNEXTHOP, .doit = rtm_new_nexthop,
4185 	 .flags = RTNL_FLAG_DOIT_PERNET},
4186 	{.msgtype = RTM_DELNEXTHOP, .doit = rtm_del_nexthop,
4187 	 .flags = RTNL_FLAG_DOIT_PERNET},
4188 	{.msgtype = RTM_GETNEXTHOP, .doit = rtm_get_nexthop,
4189 	 .dumpit = rtm_dump_nexthop},
4190 	{.msgtype = RTM_GETNEXTHOPBUCKET, .doit = rtm_get_nexthop_bucket,
4191 	 .dumpit = rtm_dump_nexthop_bucket},
4192 	{.protocol = PF_INET, .msgtype = RTM_NEWNEXTHOP,
4193 	 .doit = rtm_new_nexthop, .flags = RTNL_FLAG_DOIT_PERNET},
4194 	{.protocol = PF_INET, .msgtype = RTM_GETNEXTHOP,
4195 	 .dumpit = rtm_dump_nexthop},
4196 	{.protocol = PF_INET6, .msgtype = RTM_NEWNEXTHOP,
4197 	 .doit = rtm_new_nexthop, .flags = RTNL_FLAG_DOIT_PERNET},
4198 	{.protocol = PF_INET6, .msgtype = RTM_GETNEXTHOP,
4199 	 .dumpit = rtm_dump_nexthop},
4200 };
4201 
4202 static int __init nexthop_init(void)
4203 {
4204 	register_pernet_subsys(&nexthop_net_ops);
4205 
4206 	register_netdevice_notifier(&nh_netdev_notifier);
4207 
4208 	rtnl_register_many(nexthop_rtnl_msg_handlers);
4209 
4210 	return 0;
4211 }
4212 subsys_initcall(nexthop_init);
4213