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