nexthop.c 74.4 KB
Newer Older
D
David Ahern 已提交
1 2 3 4 5 6 7 8 9 10
// SPDX-License-Identifier: GPL-2.0
/* Generic nexthop implementation
 *
 * Copyright (c) 2017-19 Cumulus Networks
 * Copyright (c) 2017-19 David Ahern <dsa@cumulusnetworks.com>
 */

#include <linux/nexthop.h>
#include <linux/rtnetlink.h>
#include <linux/slab.h>
11
#include <net/arp.h>
12
#include <net/ipv6_stubs.h>
13
#include <net/lwtunnel.h>
14
#include <net/ndisc.h>
D
David Ahern 已提交
15
#include <net/nexthop.h>
16
#include <net/route.h>
D
David Ahern 已提交
17 18
#include <net/sock.h>

19 20 21
static void remove_nexthop(struct net *net, struct nexthop *nh,
			   struct nl_info *nlinfo);

22 23 24
#define NH_DEV_HASHBITS  8
#define NH_DEV_HASHSIZE (1U << NH_DEV_HASHBITS)

P
Petr Machata 已提交
25
static const struct nla_policy rtm_nh_policy_new[] = {
D
David Ahern 已提交
26 27 28 29 30 31 32 33
	[NHA_ID]		= { .type = NLA_U32 },
	[NHA_GROUP]		= { .type = NLA_BINARY },
	[NHA_GROUP_TYPE]	= { .type = NLA_U16 },
	[NHA_BLACKHOLE]		= { .type = NLA_FLAG },
	[NHA_OIF]		= { .type = NLA_U32 },
	[NHA_GATEWAY]		= { .type = NLA_BINARY },
	[NHA_ENCAP_TYPE]	= { .type = NLA_U16 },
	[NHA_ENCAP]		= { .type = NLA_NESTED },
34
	[NHA_FDB]		= { .type = NLA_FLAG },
D
David Ahern 已提交
35 36
};

37 38 39 40
static const struct nla_policy rtm_nh_policy_get[] = {
	[NHA_ID]		= { .type = NLA_U32 },
};

41 42 43 44 45 46 47
static const struct nla_policy rtm_nh_policy_dump[] = {
	[NHA_OIF]		= { .type = NLA_U32 },
	[NHA_GROUPS]		= { .type = NLA_FLAG },
	[NHA_MASTER]		= { .type = NLA_U32 },
	[NHA_FDB]		= { .type = NLA_FLAG },
};

48 49 50 51 52 53 54
static bool nexthop_notifiers_is_empty(struct net *net)
{
	return !net->nexthop.notifier_chain.head;
}

static void
__nh_notifier_single_info_init(struct nh_notifier_single_info *nh_info,
55
			       const struct nh_info *nhi)
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
{
	nh_info->dev = nhi->fib_nhc.nhc_dev;
	nh_info->gw_family = nhi->fib_nhc.nhc_gw_family;
	if (nh_info->gw_family == AF_INET)
		nh_info->ipv4 = nhi->fib_nhc.nhc_gw.ipv4;
	else if (nh_info->gw_family == AF_INET6)
		nh_info->ipv6 = nhi->fib_nhc.nhc_gw.ipv6;

	nh_info->is_reject = nhi->reject_nh;
	nh_info->is_fdb = nhi->fdb_nh;
	nh_info->has_encap = !!nhi->fib_nhc.nhc_lwtstate;
}

static int nh_notifier_single_info_init(struct nh_notifier_info *info,
					const struct nexthop *nh)
{
72 73
	struct nh_info *nhi = rtnl_dereference(nh->nh_info);

74
	info->type = NH_NOTIFIER_INFO_TYPE_SINGLE;
75 76 77 78
	info->nh = kzalloc(sizeof(*info->nh), GFP_KERNEL);
	if (!info->nh)
		return -ENOMEM;

79
	__nh_notifier_single_info_init(info->nh, nhi);
80 81 82 83 84 85 86 87 88

	return 0;
}

static void nh_notifier_single_info_fini(struct nh_notifier_info *info)
{
	kfree(info->nh);
}

89 90
static int nh_notifier_mp_info_init(struct nh_notifier_info *info,
				    struct nh_group *nhg)
91 92 93 94
{
	u16 num_nh = nhg->num_nh;
	int i;

95
	info->type = NH_NOTIFIER_INFO_TYPE_GRP;
96 97 98 99 100 101 102 103 104 105
	info->nh_grp = kzalloc(struct_size(info->nh_grp, nh_entries, num_nh),
			       GFP_KERNEL);
	if (!info->nh_grp)
		return -ENOMEM;

	info->nh_grp->num_nh = num_nh;
	info->nh_grp->is_fdb = nhg->fdb_nh;

	for (i = 0; i < num_nh; i++) {
		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
106
		struct nh_info *nhi;
107

108
		nhi = rtnl_dereference(nhge->nh->nh_info);
109 110 111
		info->nh_grp->nh_entries[i].id = nhge->nh->id;
		info->nh_grp->nh_entries[i].weight = nhge->weight;
		__nh_notifier_single_info_init(&info->nh_grp->nh_entries[i].nh,
112
					       nhi);
113 114 115 116 117
	}

	return 0;
}

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
static int nh_notifier_res_table_info_init(struct nh_notifier_info *info,
					   struct nh_group *nhg)
{
	struct nh_res_table *res_table = rtnl_dereference(nhg->res_table);
	u16 num_nh_buckets = res_table->num_nh_buckets;
	unsigned long size;
	u16 i;

	info->type = NH_NOTIFIER_INFO_TYPE_RES_TABLE;
	size = struct_size(info->nh_res_table, nhs, num_nh_buckets);
	info->nh_res_table = __vmalloc(size, GFP_KERNEL | __GFP_ZERO |
				       __GFP_NOWARN);
	if (!info->nh_res_table)
		return -ENOMEM;

	info->nh_res_table->num_nh_buckets = num_nh_buckets;

	for (i = 0; i < num_nh_buckets; i++) {
		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
		struct nh_grp_entry *nhge;
		struct nh_info *nhi;

		nhge = rtnl_dereference(bucket->nh_entry);
		nhi = rtnl_dereference(nhge->nh->nh_info);
		__nh_notifier_single_info_init(&info->nh_res_table->nhs[i],
					       nhi);
	}

	return 0;
}

149 150 151 152 153 154 155
static int nh_notifier_grp_info_init(struct nh_notifier_info *info,
				     const struct nexthop *nh)
{
	struct nh_group *nhg = rtnl_dereference(nh->nh_grp);

	if (nhg->mpath)
		return nh_notifier_mp_info_init(info, nhg);
156 157
	else if (nhg->resilient)
		return nh_notifier_res_table_info_init(info, nhg);
158 159 160 161 162
	return -EINVAL;
}

static void nh_notifier_grp_info_fini(struct nh_notifier_info *info,
				      const struct nexthop *nh)
163
{
164 165 166 167
	struct nh_group *nhg = rtnl_dereference(nh->nh_grp);

	if (nhg->mpath)
		kfree(info->nh_grp);
168 169
	else if (nhg->resilient)
		vfree(info->nh_res_table);
170 171 172 173 174 175 176
}

static int nh_notifier_info_init(struct nh_notifier_info *info,
				 const struct nexthop *nh)
{
	info->id = nh->id;

177
	if (nh->is_group)
178 179 180 181 182
		return nh_notifier_grp_info_init(info, nh);
	else
		return nh_notifier_single_info_init(info, nh);
}

183 184
static void nh_notifier_info_fini(struct nh_notifier_info *info,
				  const struct nexthop *nh)
185
{
186
	if (nh->is_group)
187
		nh_notifier_grp_info_fini(info, nh);
188 189 190 191
	else
		nh_notifier_single_info_fini(info);
}

192
static int call_nexthop_notifiers(struct net *net,
193
				  enum nexthop_event_type event_type,
194 195
				  struct nexthop *nh,
				  struct netlink_ext_ack *extack)
196
{
197 198 199 200
	struct nh_notifier_info info = {
		.net = net,
		.extack = extack,
	};
201 202
	int err;

203 204 205 206 207 208 209 210 211 212 213
	ASSERT_RTNL();

	if (nexthop_notifiers_is_empty(net))
		return 0;

	err = nh_notifier_info_init(&info, nh);
	if (err) {
		NL_SET_ERR_MSG(extack, "Failed to initialize nexthop notifier info");
		return err;
	}

214
	err = blocking_notifier_call_chain(&net->nexthop.notifier_chain,
215
					   event_type, &info);
216
	nh_notifier_info_fini(&info, nh);
217

218 219 220
	return notifier_to_errno(err);
}

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
static int
nh_notifier_res_bucket_idle_timer_get(const struct nh_notifier_info *info,
				      bool force, unsigned int *p_idle_timer_ms)
{
	struct nh_res_table *res_table;
	struct nh_group *nhg;
	struct nexthop *nh;
	int err = 0;

	/* When 'force' is false, nexthop bucket replacement is performed
	 * because the bucket was deemed to be idle. In this case, capable
	 * listeners can choose to perform an atomic replacement: The bucket is
	 * only replaced if it is inactive. However, if the idle timer interval
	 * is smaller than the interval in which a listener is querying
	 * buckets' activity from the device, then atomic replacement should
	 * not be tried. Pass the idle timer value to listeners, so that they
	 * could determine which type of replacement to perform.
	 */
	if (force) {
		*p_idle_timer_ms = 0;
		return 0;
	}

	rcu_read_lock();

	nh = nexthop_find_by_id(info->net, info->id);
	if (!nh) {
		err = -EINVAL;
		goto out;
	}

	nhg = rcu_dereference(nh->nh_grp);
	res_table = rcu_dereference(nhg->res_table);
	*p_idle_timer_ms = jiffies_to_msecs(res_table->idle_timer);

out:
	rcu_read_unlock();

	return err;
}

static int nh_notifier_res_bucket_info_init(struct nh_notifier_info *info,
					    u16 bucket_index, bool force,
					    struct nh_info *oldi,
					    struct nh_info *newi)
{
	unsigned int idle_timer_ms;
	int err;

	err = nh_notifier_res_bucket_idle_timer_get(info, force,
						    &idle_timer_ms);
	if (err)
		return err;

	info->type = NH_NOTIFIER_INFO_TYPE_RES_BUCKET;
	info->nh_res_bucket = kzalloc(sizeof(*info->nh_res_bucket),
				      GFP_KERNEL);
	if (!info->nh_res_bucket)
		return -ENOMEM;

	info->nh_res_bucket->bucket_index = bucket_index;
	info->nh_res_bucket->idle_timer_ms = idle_timer_ms;
	info->nh_res_bucket->force = force;
	__nh_notifier_single_info_init(&info->nh_res_bucket->old_nh, oldi);
	__nh_notifier_single_info_init(&info->nh_res_bucket->new_nh, newi);
	return 0;
}

static void nh_notifier_res_bucket_info_fini(struct nh_notifier_info *info)
{
	kfree(info->nh_res_bucket);
}

static int __call_nexthop_res_bucket_notifiers(struct net *net, u32 nhg_id,
					       u16 bucket_index, bool force,
					       struct nh_info *oldi,
					       struct nh_info *newi,
					       struct netlink_ext_ack *extack)
{
	struct nh_notifier_info info = {
		.net = net,
		.extack = extack,
		.id = nhg_id,
	};
	int err;

	if (nexthop_notifiers_is_empty(net))
		return 0;

	err = nh_notifier_res_bucket_info_init(&info, bucket_index, force,
					       oldi, newi);
	if (err)
		return err;

	err = blocking_notifier_call_chain(&net->nexthop.notifier_chain,
					   NEXTHOP_EVENT_BUCKET_REPLACE, &info);
	nh_notifier_res_bucket_info_fini(&info);

	return notifier_to_errno(err);
}

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
/* There are three users of RES_TABLE, and NHs etc. referenced from there:
 *
 * 1) a collection of callbacks for NH maintenance. This operates under
 *    RTNL,
 * 2) the delayed work that gradually balances the resilient table,
 * 3) and nexthop_select_path(), operating under RCU.
 *
 * Both the delayed work and the RTNL block are writers, and need to
 * maintain mutual exclusion. Since there are only two and well-known
 * writers for each table, the RTNL code can make sure it has exclusive
 * access thus:
 *
 * - Have the DW operate without locking;
 * - synchronously cancel the DW;
 * - do the writing;
 * - if the write was not actually a delete, call upkeep, which schedules
 *   DW again if necessary.
 *
 * The functions that are always called from the RTNL context use
 * rtnl_dereference(). The functions that can also be called from the DW do
 * a raw dereference and rely on the above mutual exclusion scheme.
 */
#define nh_res_dereference(p) (rcu_dereference_raw(p))

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
static int call_nexthop_res_bucket_notifiers(struct net *net, u32 nhg_id,
					     u16 bucket_index, bool force,
					     struct nexthop *old_nh,
					     struct nexthop *new_nh,
					     struct netlink_ext_ack *extack)
{
	struct nh_info *oldi = nh_res_dereference(old_nh->nh_info);
	struct nh_info *newi = nh_res_dereference(new_nh->nh_info);

	return __call_nexthop_res_bucket_notifiers(net, nhg_id, bucket_index,
						   force, oldi, newi, extack);
}

static int call_nexthop_res_table_notifiers(struct net *net, struct nexthop *nh,
					    struct netlink_ext_ack *extack)
{
	struct nh_notifier_info info = {
		.net = net,
		.extack = extack,
	};
	struct nh_group *nhg;
	int err;

	ASSERT_RTNL();

	if (nexthop_notifiers_is_empty(net))
		return 0;

	/* At this point, the nexthop buckets are still not populated. Only
	 * emit a notification with the logical nexthops, so that a listener
	 * could potentially veto it in case of unsupported configuration.
	 */
	nhg = rtnl_dereference(nh->nh_grp);
	err = nh_notifier_mp_info_init(&info, nhg);
	if (err) {
		NL_SET_ERR_MSG(extack, "Failed to initialize nexthop notifier info");
		return err;
	}

	err = blocking_notifier_call_chain(&net->nexthop.notifier_chain,
					   NEXTHOP_EVENT_RES_TABLE_PRE_REPLACE,
					   &info);
	kfree(info.nh_grp);

	return notifier_to_errno(err);
}

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
static int call_nexthop_notifier(struct notifier_block *nb, struct net *net,
				 enum nexthop_event_type event_type,
				 struct nexthop *nh,
				 struct netlink_ext_ack *extack)
{
	struct nh_notifier_info info = {
		.net = net,
		.extack = extack,
	};
	int err;

	err = nh_notifier_info_init(&info, nh);
	if (err)
		return err;

	err = nb->notifier_call(nb, event_type, &info);
409
	nh_notifier_info_fini(&info, nh);
410 411 412 413

	return notifier_to_errno(err);
}

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
static unsigned int nh_dev_hashfn(unsigned int val)
{
	unsigned int mask = NH_DEV_HASHSIZE - 1;

	return (val ^
		(val >> NH_DEV_HASHBITS) ^
		(val >> (NH_DEV_HASHBITS * 2))) & mask;
}

static void nexthop_devhash_add(struct net *net, struct nh_info *nhi)
{
	struct net_device *dev = nhi->fib_nhc.nhc_dev;
	struct hlist_head *head;
	unsigned int hash;

	WARN_ON(!dev);

	hash = nh_dev_hashfn(dev->ifindex);
	head = &net->nexthop.devhash[hash];
	hlist_add_head(&nhi->dev_hash, head);
}

D
David Ahern 已提交
436
static void nexthop_free_group(struct nexthop *nh)
437 438 439 440 441
{
	struct nh_group *nhg;
	int i;

	nhg = rcu_dereference_raw(nh->nh_grp);
442 443
	for (i = 0; i < nhg->num_nh; ++i) {
		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
444

445 446 447 448 449
		WARN_ON(!list_empty(&nhge->nh_list));
		nexthop_put(nhge->nh);
	}

	WARN_ON(nhg->spare == nhg);
450

451 452 453
	if (nhg->resilient)
		vfree(rcu_dereference_raw(nhg->res_table));

454
	kfree(nhg->spare);
455 456 457 458
	kfree(nhg);
}

static void nexthop_free_single(struct nexthop *nh)
D
David Ahern 已提交
459 460 461 462
{
	struct nh_info *nhi;

	nhi = rcu_dereference_raw(nh->nh_info);
463 464 465 466
	switch (nhi->family) {
	case AF_INET:
		fib_nh_release(nh->net, &nhi->fib_nh);
		break;
467 468 469
	case AF_INET6:
		ipv6_stub->fib6_nh_release(&nhi->fib6_nh);
		break;
470
	}
D
David Ahern 已提交
471
	kfree(nhi);
472 473 474 475 476 477 478
}

void nexthop_free_rcu(struct rcu_head *head)
{
	struct nexthop *nh = container_of(head, struct nexthop, rcu);

	if (nh->is_group)
D
David Ahern 已提交
479
		nexthop_free_group(nh);
480 481
	else
		nexthop_free_single(nh);
D
David Ahern 已提交
482 483 484 485 486 487 488 489 490 491

	kfree(nh);
}
EXPORT_SYMBOL_GPL(nexthop_free_rcu);

static struct nexthop *nexthop_alloc(void)
{
	struct nexthop *nh;

	nh = kzalloc(sizeof(struct nexthop), GFP_KERNEL);
492
	if (nh) {
493
		INIT_LIST_HEAD(&nh->fi_list);
494
		INIT_LIST_HEAD(&nh->f6i_list);
495
		INIT_LIST_HEAD(&nh->grp_list);
496
		INIT_LIST_HEAD(&nh->fdb_list);
497
	}
D
David Ahern 已提交
498 499 500
	return nh;
}

501 502 503 504
static struct nh_group *nexthop_grp_alloc(u16 num_nh)
{
	struct nh_group *nhg;

505
	nhg = kzalloc(struct_size(nhg, nh_entries, num_nh), GFP_KERNEL);
506 507 508 509 510 511
	if (nhg)
		nhg->num_nh = num_nh;

	return nhg;
}

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
static void nh_res_table_upkeep_dw(struct work_struct *work);

static struct nh_res_table *
nexthop_res_table_alloc(struct net *net, u32 nhg_id, struct nh_config *cfg)
{
	const u16 num_nh_buckets = cfg->nh_grp_res_num_buckets;
	struct nh_res_table *res_table;
	unsigned long size;

	size = struct_size(res_table, nh_buckets, num_nh_buckets);
	res_table = __vmalloc(size, GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN);
	if (!res_table)
		return NULL;

	res_table->net = net;
	res_table->nhg_id = nhg_id;
	INIT_DELAYED_WORK(&res_table->upkeep_dw, &nh_res_table_upkeep_dw);
	INIT_LIST_HEAD(&res_table->uw_nh_entries);
	res_table->idle_timer = cfg->nh_grp_res_idle_timer;
	res_table->unbalanced_timer = cfg->nh_grp_res_unbalanced_timer;
	res_table->num_nh_buckets = num_nh_buckets;
	return res_table;
}

D
David Ahern 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
static void nh_base_seq_inc(struct net *net)
{
	while (++net->nexthop.seq == 0)
		;
}

/* no reference taken; rcu lock or rtnl must be held */
struct nexthop *nexthop_find_by_id(struct net *net, u32 id)
{
	struct rb_node **pp, *parent = NULL, *next;

	pp = &net->nexthop.rb_root.rb_node;
	while (1) {
		struct nexthop *nh;

		next = rcu_dereference_raw(*pp);
		if (!next)
			break;
		parent = next;

		nh = rb_entry(parent, struct nexthop, rb_node);
		if (id < nh->id)
			pp = &next->rb_left;
		else if (id > nh->id)
			pp = &next->rb_right;
		else
			return nh;
	}
	return NULL;
}
EXPORT_SYMBOL_GPL(nexthop_find_by_id);

/* used for auto id allocation; called with rtnl held */
static u32 nh_find_unused_id(struct net *net)
{
	u32 id_start = net->nexthop.last_id_allocated;

	while (1) {
		net->nexthop.last_id_allocated++;
		if (net->nexthop.last_id_allocated == id_start)
			break;

		if (!nexthop_find_by_id(net, net->nexthop.last_id_allocated))
			return net->nexthop.last_id_allocated;
	}
	return 0;
}

584 585 586 587 588 589 590
static void nh_res_time_set_deadline(unsigned long next_time,
				     unsigned long *deadline)
{
	if (time_before(next_time, *deadline))
		*deadline = next_time;
}

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
static int nla_put_nh_group(struct sk_buff *skb, struct nh_group *nhg)
{
	struct nexthop_grp *p;
	size_t len = nhg->num_nh * sizeof(*p);
	struct nlattr *nla;
	u16 group_type = 0;
	int i;

	if (nhg->mpath)
		group_type = NEXTHOP_GRP_TYPE_MPATH;

	if (nla_put_u16(skb, NHA_GROUP_TYPE, group_type))
		goto nla_put_failure;

	nla = nla_reserve(skb, NHA_GROUP, len);
	if (!nla)
		goto nla_put_failure;

	p = nla_data(nla);
	for (i = 0; i < nhg->num_nh; ++i) {
		p->id = nhg->nh_entries[i].nh->id;
		p->weight = nhg->nh_entries[i].weight - 1;
		p += 1;
	}

	return 0;

nla_put_failure:
	return -EMSGSIZE;
}

D
David Ahern 已提交
622 623 624
static int nh_fill_node(struct sk_buff *skb, struct nexthop *nh,
			int event, u32 portid, u32 seq, unsigned int nlflags)
{
625
	struct fib6_nh *fib6_nh;
626
	struct fib_nh *fib_nh;
D
David Ahern 已提交
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
	struct nlmsghdr *nlh;
	struct nh_info *nhi;
	struct nhmsg *nhm;

	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*nhm), nlflags);
	if (!nlh)
		return -EMSGSIZE;

	nhm = nlmsg_data(nlh);
	nhm->nh_family = AF_UNSPEC;
	nhm->nh_flags = nh->nh_flags;
	nhm->nh_protocol = nh->protocol;
	nhm->nh_scope = 0;
	nhm->resvd = 0;

	if (nla_put_u32(skb, NHA_ID, nh->id))
		goto nla_put_failure;

645 646 647
	if (nh->is_group) {
		struct nh_group *nhg = rtnl_dereference(nh->nh_grp);

648 649
		if (nhg->fdb_nh && nla_put_flag(skb, NHA_FDB))
			goto nla_put_failure;
650 651 652 653 654
		if (nla_put_nh_group(skb, nhg))
			goto nla_put_failure;
		goto out;
	}

D
David Ahern 已提交
655 656 657 658 659 660
	nhi = rtnl_dereference(nh->nh_info);
	nhm->nh_family = nhi->family;
	if (nhi->reject_nh) {
		if (nla_put_flag(skb, NHA_BLACKHOLE))
			goto nla_put_failure;
		goto out;
661 662 663 664
	} else if (nhi->fdb_nh) {
		if (nla_put_flag(skb, NHA_FDB))
			goto nla_put_failure;
	} else {
665 666 667 668 669 670 671 672 673 674 675 676
		const struct net_device *dev;

		dev = nhi->fib_nhc.nhc_dev;
		if (dev && nla_put_u32(skb, NHA_OIF, dev->ifindex))
			goto nla_put_failure;
	}

	nhm->nh_scope = nhi->fib_nhc.nhc_scope;
	switch (nhi->family) {
	case AF_INET:
		fib_nh = &nhi->fib_nh;
		if (fib_nh->fib_nh_gw_family &&
677
		    nla_put_be32(skb, NHA_GATEWAY, fib_nh->fib_nh_gw4))
678 679
			goto nla_put_failure;
		break;
680 681 682 683 684 685 686

	case AF_INET6:
		fib6_nh = &nhi->fib6_nh;
		if (fib6_nh->fib_nh_gw_family &&
		    nla_put_in6_addr(skb, NHA_GATEWAY, &fib6_nh->fib_nh_gw6))
			goto nla_put_failure;
		break;
D
David Ahern 已提交
687 688
	}

689 690 691 692 693
	if (nhi->fib_nhc.nhc_lwtstate &&
	    lwtunnel_fill_encap(skb, nhi->fib_nhc.nhc_lwtstate,
				NHA_ENCAP, NHA_ENCAP_TYPE) < 0)
		goto nla_put_failure;

D
David Ahern 已提交
694 695 696 697 698
out:
	nlmsg_end(skb, nlh);
	return 0;

nla_put_failure:
699
	nlmsg_cancel(skb, nlh);
D
David Ahern 已提交
700 701 702
	return -EMSGSIZE;
}

703 704 705 706 707 708 709 710 711 712
static size_t nh_nlmsg_size_grp(struct nexthop *nh)
{
	struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
	size_t sz = sizeof(struct nexthop_grp) * nhg->num_nh;

	return nla_total_size(sz) +
	       nla_total_size(2);  /* NHA_GROUP_TYPE */
}

static size_t nh_nlmsg_size_single(struct nexthop *nh)
D
David Ahern 已提交
713
{
714
	struct nh_info *nhi = rtnl_dereference(nh->nh_info);
715
	size_t sz;
D
David Ahern 已提交
716 717 718 719

	/* covers NHA_BLACKHOLE since NHA_OIF and BLACKHOLE
	 * are mutually exclusive
	 */
720
	sz = nla_total_size(4);  /* NHA_OIF */
D
David Ahern 已提交
721

722 723 724 725 726
	switch (nhi->family) {
	case AF_INET:
		if (nhi->fib_nh.fib_nh_gw_family)
			sz += nla_total_size(4);  /* NHA_GATEWAY */
		break;
727 728 729 730 731 732

	case AF_INET6:
		/* NHA_GATEWAY */
		if (nhi->fib6_nh.fib_nh_gw_family)
			sz += nla_total_size(sizeof(const struct in6_addr));
		break;
733 734
	}

735 736 737 738 739
	if (nhi->fib_nhc.nhc_lwtstate) {
		sz += lwtunnel_get_encap_size(nhi->fib_nhc.nhc_lwtstate);
		sz += nla_total_size(2);  /* NHA_ENCAP_TYPE */
	}

D
David Ahern 已提交
740 741 742
	return sz;
}

743 744
static size_t nh_nlmsg_size(struct nexthop *nh)
{
745 746 747
	size_t sz = NLMSG_ALIGN(sizeof(struct nhmsg));

	sz += nla_total_size(4); /* NHA_ID */
748 749 750 751 752 753 754 755 756

	if (nh->is_group)
		sz += nh_nlmsg_size_grp(nh);
	else
		sz += nh_nlmsg_size_single(nh);

	return sz;
}

D
David Ahern 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
static void nexthop_notify(int event, struct nexthop *nh, struct nl_info *info)
{
	unsigned int nlflags = info->nlh ? info->nlh->nlmsg_flags : 0;
	u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
	struct sk_buff *skb;
	int err = -ENOBUFS;

	skb = nlmsg_new(nh_nlmsg_size(nh), gfp_any());
	if (!skb)
		goto errout;

	err = nh_fill_node(skb, nh, event, info->portid, seq, nlflags);
	if (err < 0) {
		/* -EMSGSIZE implies BUG in nh_nlmsg_size() */
		WARN_ON(err == -EMSGSIZE);
		kfree_skb(skb);
		goto errout;
	}

	rtnl_notify(skb, info->nl_net, info->portid, RTNLGRP_NEXTHOP,
		    info->nlh, gfp_any());
	return;
errout:
	if (err < 0)
		rtnl_set_sk_err(info->nl_net, RTNLGRP_NEXTHOP, err);
}

784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
static unsigned long nh_res_bucket_used_time(const struct nh_res_bucket *bucket)
{
	return (unsigned long)atomic_long_read(&bucket->used_time);
}

static unsigned long
nh_res_bucket_idle_point(const struct nh_res_table *res_table,
			 const struct nh_res_bucket *bucket,
			 unsigned long now)
{
	unsigned long time = nh_res_bucket_used_time(bucket);

	/* Bucket was not used since it was migrated. The idle time is now. */
	if (time == bucket->migrated_time)
		return now;

	return time + res_table->idle_timer;
}

static unsigned long
nh_res_table_unb_point(const struct nh_res_table *res_table)
{
	return res_table->unbalanced_since + res_table->unbalanced_timer;
}

static void nh_res_bucket_set_idle(const struct nh_res_table *res_table,
				   struct nh_res_bucket *bucket)
{
	unsigned long now = jiffies;

	atomic_long_set(&bucket->used_time, (long)now);
	bucket->migrated_time = now;
}

static void nh_res_bucket_set_busy(struct nh_res_bucket *bucket)
{
	atomic_long_set(&bucket->used_time, (long)jiffies);
}

823
static bool valid_group_nh(struct nexthop *nh, unsigned int npaths,
824
			   bool *is_fdb, struct netlink_ext_ack *extack)
825
{
826 827
	if (nh->is_group) {
		struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
828

829
		/* Nesting groups within groups is not supported. */
830 831 832 833 834
		if (nhg->mpath) {
			NL_SET_ERR_MSG(extack,
				       "Multipath group can not be a nexthop within a group");
			return false;
		}
835 836 837 838 839
		if (nhg->resilient) {
			NL_SET_ERR_MSG(extack,
				       "Resilient group can not be a nexthop within a group");
			return false;
		}
840
		*is_fdb = nhg->fdb_nh;
841 842 843 844 845 846 847 848
	} else {
		struct nh_info *nhi = rtnl_dereference(nh->nh_info);

		if (nhi->reject_nh && npaths > 1) {
			NL_SET_ERR_MSG(extack,
				       "Blackhole nexthop can not be used in a group with more than 1 path");
			return false;
		}
849
		*is_fdb = nhi->fdb_nh;
850 851 852 853 854
	}

	return true;
}

855 856 857 858 859
static int nh_check_attr_fdb_group(struct nexthop *nh, u8 *nh_family,
				   struct netlink_ext_ack *extack)
{
	struct nh_info *nhi;

860 861 862
	nhi = rtnl_dereference(nh->nh_info);

	if (!nhi->fdb_nh) {
863 864 865 866 867 868 869 870 871 872 873 874 875 876
		NL_SET_ERR_MSG(extack, "FDB nexthop group can only have fdb nexthops");
		return -EINVAL;
	}

	if (*nh_family == AF_UNSPEC) {
		*nh_family = nhi->family;
	} else if (*nh_family != nhi->family) {
		NL_SET_ERR_MSG(extack, "FDB nexthop group cannot have mixed family nexthops");
		return -EINVAL;
	}

	return 0;
}

P
Petr Machata 已提交
877 878
static int nh_check_attr_group(struct net *net,
			       struct nlattr *tb[], size_t tb_size,
879 880 881
			       struct netlink_ext_ack *extack)
{
	unsigned int len = nla_len(tb[NHA_GROUP]);
882
	u8 nh_family = AF_UNSPEC;
883 884
	struct nexthop_grp *nhg;
	unsigned int i, j;
885
	u8 nhg_fdb = 0;
886

887
	if (!len || len & (sizeof(struct nexthop_grp) - 1)) {
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
		NL_SET_ERR_MSG(extack,
			       "Invalid length for nexthop group attribute");
		return -EINVAL;
	}

	/* convert len to number of nexthop ids */
	len /= sizeof(*nhg);

	nhg = nla_data(tb[NHA_GROUP]);
	for (i = 0; i < len; ++i) {
		if (nhg[i].resvd1 || nhg[i].resvd2) {
			NL_SET_ERR_MSG(extack, "Reserved fields in nexthop_grp must be 0");
			return -EINVAL;
		}
		if (nhg[i].weight > 254) {
			NL_SET_ERR_MSG(extack, "Invalid value for weight");
			return -EINVAL;
		}
		for (j = i + 1; j < len; ++j) {
			if (nhg[i].id == nhg[j].id) {
				NL_SET_ERR_MSG(extack, "Nexthop id can not be used twice in a group");
				return -EINVAL;
			}
		}
	}

914 915
	if (tb[NHA_FDB])
		nhg_fdb = 1;
916 917 918
	nhg = nla_data(tb[NHA_GROUP]);
	for (i = 0; i < len; ++i) {
		struct nexthop *nh;
919
		bool is_fdb_nh;
920 921 922 923 924 925

		nh = nexthop_find_by_id(net, nhg[i].id);
		if (!nh) {
			NL_SET_ERR_MSG(extack, "Invalid nexthop id");
			return -EINVAL;
		}
926
		if (!valid_group_nh(nh, len, &is_fdb_nh, extack))
927
			return -EINVAL;
928 929 930 931

		if (nhg_fdb && nh_check_attr_fdb_group(nh, &nh_family, extack))
			return -EINVAL;

932
		if (!nhg_fdb && is_fdb_nh) {
933 934 935
			NL_SET_ERR_MSG(extack, "Non FDB nexthop group cannot have fdb nexthops");
			return -EINVAL;
		}
936
	}
P
Petr Machata 已提交
937
	for (i = NHA_GROUP_TYPE + 1; i < tb_size; ++i) {
938 939
		if (!tb[i])
			continue;
940
		if (i == NHA_FDB)
941
			continue;
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
		NL_SET_ERR_MSG(extack,
			       "No other attributes can be set in nexthop groups");
		return -EINVAL;
	}

	return 0;
}

static bool ipv6_good_nh(const struct fib6_nh *nh)
{
	int state = NUD_REACHABLE;
	struct neighbour *n;

	rcu_read_lock_bh();

	n = __ipv6_neigh_lookup_noref_stub(nh->fib_nh_dev, &nh->fib_nh_gw6);
	if (n)
		state = n->nud_state;

	rcu_read_unlock_bh();

	return !!(state & NUD_VALID);
}

static bool ipv4_good_nh(const struct fib_nh *nh)
{
	int state = NUD_REACHABLE;
	struct neighbour *n;

	rcu_read_lock_bh();

	n = __ipv4_neigh_lookup_noref(nh->fib_nh_dev,
				      (__force u32)nh->fib_nh_gw4);
	if (n)
		state = n->nud_state;

	rcu_read_unlock_bh();

	return !!(state & NUD_VALID);
}

983
static struct nexthop *nexthop_select_path_mp(struct nh_group *nhg, int hash)
984 985 986 987 988 989 990 991
{
	struct nexthop *rc = NULL;
	int i;

	for (i = 0; i < nhg->num_nh; ++i) {
		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
		struct nh_info *nhi;

992
		if (hash > atomic_read(&nhge->mpath.upper_bound))
993 994
			continue;

995 996
		nhi = rcu_dereference(nhge->nh->nh_info);
		if (nhi->fdb_nh)
997 998
			return nhge->nh;

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
		/* nexthops always check if it is good and does
		 * not rely on a sysctl for this behavior
		 */
		switch (nhi->family) {
		case AF_INET:
			if (ipv4_good_nh(&nhi->fib_nh))
				return nhge->nh;
			break;
		case AF_INET6:
			if (ipv6_good_nh(&nhi->fib6_nh))
				return nhge->nh;
			break;
		}

		if (!rc)
			rc = nhge->nh;
	}

	return rc;
}
1019

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
static struct nexthop *nexthop_select_path_res(struct nh_group *nhg, int hash)
{
	struct nh_res_table *res_table = rcu_dereference(nhg->res_table);
	u16 bucket_index = hash % res_table->num_nh_buckets;
	struct nh_res_bucket *bucket;
	struct nh_grp_entry *nhge;

	/* nexthop_select_path() is expected to return a non-NULL value, so
	 * skip protocol validation and just hand out whatever there is.
	 */
	bucket = &res_table->nh_buckets[bucket_index];
	nh_res_bucket_set_busy(bucket);
	nhge = rcu_dereference(bucket->nh_entry);
	return nhge->nh;
}

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
struct nexthop *nexthop_select_path(struct nexthop *nh, int hash)
{
	struct nh_group *nhg;

	if (!nh->is_group)
		return nh;

	nhg = rcu_dereference(nh->nh_grp);
	if (nhg->mpath)
		return nexthop_select_path_mp(nhg, hash);
1046 1047
	else if (nhg->resilient)
		return nexthop_select_path_res(nhg, hash);
1048 1049 1050 1051

	/* Unreachable. */
	return NULL;
}
1052 1053
EXPORT_SYMBOL_GPL(nexthop_select_path);

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
int nexthop_for_each_fib6_nh(struct nexthop *nh,
			     int (*cb)(struct fib6_nh *nh, void *arg),
			     void *arg)
{
	struct nh_info *nhi;
	int err;

	if (nh->is_group) {
		struct nh_group *nhg;
		int i;

		nhg = rcu_dereference_rtnl(nh->nh_grp);
		for (i = 0; i < nhg->num_nh; i++) {
			struct nh_grp_entry *nhge = &nhg->nh_entries[i];

			nhi = rcu_dereference_rtnl(nhge->nh->nh_info);
			err = cb(&nhi->fib6_nh, arg);
			if (err)
				return err;
		}
	} else {
		nhi = rcu_dereference_rtnl(nh->nh_info);
		err = cb(&nhi->fib6_nh, arg);
		if (err)
			return err;
	}

	return 0;
}
EXPORT_SYMBOL_GPL(nexthop_for_each_fib6_nh);

D
David Ahern 已提交
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
static int check_src_addr(const struct in6_addr *saddr,
			  struct netlink_ext_ack *extack)
{
	if (!ipv6_addr_any(saddr)) {
		NL_SET_ERR_MSG(extack, "IPv6 routes using source address can not use nexthop objects");
		return -EINVAL;
	}
	return 0;
}

1095 1096 1097 1098
int fib6_check_nexthop(struct nexthop *nh, struct fib6_config *cfg,
		       struct netlink_ext_ack *extack)
{
	struct nh_info *nhi;
1099
	bool is_fdb_nh;
1100

1101 1102 1103 1104 1105 1106
	/* fib6_src is unique to a fib6_info and limits the ability to cache
	 * routes in fib6_nh within a nexthop that is potentially shared
	 * across multiple fib entries. If the config wants to use source
	 * routing it can not use nexthop objects. mlxsw also does not allow
	 * fib6_src on routes.
	 */
D
David Ahern 已提交
1107
	if (cfg && check_src_addr(&cfg->fc_src, extack) < 0)
1108 1109 1110 1111 1112 1113 1114 1115
		return -EINVAL;

	if (nh->is_group) {
		struct nh_group *nhg;

		nhg = rtnl_dereference(nh->nh_grp);
		if (nhg->has_v4)
			goto no_v4_nh;
1116
		is_fdb_nh = nhg->fdb_nh;
1117 1118 1119 1120
	} else {
		nhi = rtnl_dereference(nh->nh_info);
		if (nhi->family == AF_INET)
			goto no_v4_nh;
1121 1122 1123 1124 1125 1126
		is_fdb_nh = nhi->fdb_nh;
	}

	if (is_fdb_nh) {
		NL_SET_ERR_MSG(extack, "Route cannot point to a fdb nexthop");
		return -EINVAL;
1127 1128 1129 1130 1131 1132 1133 1134 1135
	}

	return 0;
no_v4_nh:
	NL_SET_ERR_MSG(extack, "IPv6 routes can not use an IPv4 nexthop");
	return -EINVAL;
}
EXPORT_SYMBOL_GPL(fib6_check_nexthop);

D
David Ahern 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
/* if existing nexthop has ipv6 routes linked to it, need
 * to verify this new spec works with ipv6
 */
static int fib6_check_nh_list(struct nexthop *old, struct nexthop *new,
			      struct netlink_ext_ack *extack)
{
	struct fib6_info *f6i;

	if (list_empty(&old->f6i_list))
		return 0;

	list_for_each_entry(f6i, &old->f6i_list, nh_list) {
		if (check_src_addr(&f6i->fib6_src.addr, extack) < 0)
			return -EINVAL;
	}

	return fib6_check_nexthop(new, NULL, extack);
}

1155
static int nexthop_check_scope(struct nh_info *nhi, u8 scope,
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
			       struct netlink_ext_ack *extack)
{
	if (scope == RT_SCOPE_HOST && nhi->fib_nhc.nhc_gw_family) {
		NL_SET_ERR_MSG(extack,
			       "Route with host scope can not have a gateway");
		return -EINVAL;
	}

	if (nhi->fib_nhc.nhc_flags & RTNH_F_ONLINK && scope >= RT_SCOPE_LINK) {
		NL_SET_ERR_MSG(extack, "Scope mismatch with nexthop");
		return -EINVAL;
	}

	return 0;
}

/* Invoked by fib add code to verify nexthop by id is ok with
 * config for prefix; parts of fib_check_nh not done when nexthop
 * object is used.
 */
int fib_check_nexthop(struct nexthop *nh, u8 scope,
		      struct netlink_ext_ack *extack)
{
1179
	struct nh_info *nhi;
1180 1181 1182 1183 1184
	int err = 0;

	if (nh->is_group) {
		struct nh_group *nhg;

1185 1186 1187 1188 1189 1190 1191
		nhg = rtnl_dereference(nh->nh_grp);
		if (nhg->fdb_nh) {
			NL_SET_ERR_MSG(extack, "Route cannot point to a fdb nexthop");
			err = -EINVAL;
			goto out;
		}

1192 1193 1194 1195 1196 1197 1198
		if (scope == RT_SCOPE_HOST) {
			NL_SET_ERR_MSG(extack, "Route with host scope can not have multiple nexthops");
			err = -EINVAL;
			goto out;
		}

		/* all nexthops in a group have the same scope */
1199 1200
		nhi = rtnl_dereference(nhg->nh_entries[0].nh->nh_info);
		err = nexthop_check_scope(nhi, scope, extack);
1201
	} else {
1202 1203 1204 1205 1206 1207 1208
		nhi = rtnl_dereference(nh->nh_info);
		if (nhi->fdb_nh) {
			NL_SET_ERR_MSG(extack, "Route cannot point to a fdb nexthop");
			err = -EINVAL;
			goto out;
		}
		err = nexthop_check_scope(nhi, scope, extack);
1209
	}
1210

1211 1212 1213 1214
out:
	return err;
}

D
David Ahern 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
static int fib_check_nh_list(struct nexthop *old, struct nexthop *new,
			     struct netlink_ext_ack *extack)
{
	struct fib_info *fi;

	list_for_each_entry(fi, &old->fi_list, nh_list) {
		int err;

		err = fib_check_nexthop(new, fi->fib_scope, extack);
		if (err)
			return err;
	}
	return 0;
}

1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
static bool nh_res_nhge_is_balanced(const struct nh_grp_entry *nhge)
{
	return nhge->res.count_buckets == nhge->res.wants_buckets;
}

static bool nh_res_nhge_is_ow(const struct nh_grp_entry *nhge)
{
	return nhge->res.count_buckets > nhge->res.wants_buckets;
}

static bool nh_res_nhge_is_uw(const struct nh_grp_entry *nhge)
{
	return nhge->res.count_buckets < nhge->res.wants_buckets;
}

static bool nh_res_table_is_balanced(const struct nh_res_table *res_table)
{
	return list_empty(&res_table->uw_nh_entries);
}

static void nh_res_bucket_unset_nh(struct nh_res_bucket *bucket)
{
	struct nh_grp_entry *nhge;

	if (bucket->occupied) {
		nhge = nh_res_dereference(bucket->nh_entry);
		nhge->res.count_buckets--;
		bucket->occupied = false;
	}
}

static void nh_res_bucket_set_nh(struct nh_res_bucket *bucket,
				 struct nh_grp_entry *nhge)
{
	nh_res_bucket_unset_nh(bucket);

	bucket->occupied = true;
	rcu_assign_pointer(bucket->nh_entry, nhge);
	nhge->res.count_buckets++;
}

static bool nh_res_bucket_should_migrate(struct nh_res_table *res_table,
					 struct nh_res_bucket *bucket,
					 unsigned long *deadline, bool *force)
{
	unsigned long now = jiffies;
	struct nh_grp_entry *nhge;
	unsigned long idle_point;

	if (!bucket->occupied) {
		/* The bucket is not occupied, its NHGE pointer is either
		 * NULL or obsolete. We _have to_ migrate: set force.
		 */
		*force = true;
		return true;
	}

	nhge = nh_res_dereference(bucket->nh_entry);

	/* If the bucket is populated by an underweight or balanced
	 * nexthop, do not migrate.
	 */
	if (!nh_res_nhge_is_ow(nhge))
		return false;

	/* At this point we know that the bucket is populated with an
	 * overweight nexthop. It needs to be migrated to a new nexthop if
	 * the idle timer of unbalanced timer expired.
	 */

	idle_point = nh_res_bucket_idle_point(res_table, bucket, now);
	if (time_after_eq(now, idle_point)) {
		/* The bucket is idle. We _can_ migrate: unset force. */
		*force = false;
		return true;
	}

	/* Unbalanced timer of 0 means "never force". */
	if (res_table->unbalanced_timer) {
		unsigned long unb_point;

		unb_point = nh_res_table_unb_point(res_table);
		if (time_after(now, unb_point)) {
			/* The bucket is not idle, but the unbalanced timer
			 * expired. We _can_ migrate, but set force anyway,
			 * so that drivers know to ignore activity reports
			 * from the HW.
			 */
			*force = true;
			return true;
		}

		nh_res_time_set_deadline(unb_point, deadline);
	}

	nh_res_time_set_deadline(idle_point, deadline);
	return false;
}

static bool nh_res_bucket_migrate(struct nh_res_table *res_table,
1330
				  u16 bucket_index, bool notify, bool force)
1331 1332 1333
{
	struct nh_res_bucket *bucket = &res_table->nh_buckets[bucket_index];
	struct nh_grp_entry *new_nhge;
1334 1335
	struct netlink_ext_ack extack;
	int err;
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

	new_nhge = list_first_entry_or_null(&res_table->uw_nh_entries,
					    struct nh_grp_entry,
					    res.uw_nh_entry);
	if (WARN_ON_ONCE(!new_nhge))
		/* If this function is called, "bucket" is either not
		 * occupied, or it belongs to a next hop that is
		 * overweight. In either case, there ought to be a
		 * corresponding underweight next hop.
		 */
		return false;

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
	if (notify) {
		struct nh_grp_entry *old_nhge;

		old_nhge = nh_res_dereference(bucket->nh_entry);
		err = call_nexthop_res_bucket_notifiers(res_table->net,
							res_table->nhg_id,
							bucket_index, force,
							old_nhge->nh,
							new_nhge->nh, &extack);
		if (err) {
			pr_err_ratelimited("%s\n", extack._msg);
			if (!force)
				return false;
			/* It is not possible to veto a forced replacement, so
			 * just clear the hardware flags from the nexthop
			 * bucket to indicate to user space that this bucket is
			 * not correctly populated in hardware.
			 */
			bucket->nh_flags &= ~(RTNH_F_OFFLOAD | RTNH_F_TRAP);
		}
	}

1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
	nh_res_bucket_set_nh(bucket, new_nhge);
	nh_res_bucket_set_idle(res_table, bucket);

	if (nh_res_nhge_is_balanced(new_nhge))
		list_del(&new_nhge->res.uw_nh_entry);
	return true;
}

#define NH_RES_UPKEEP_DW_MINIMUM_INTERVAL (HZ / 2)

1380
static void nh_res_table_upkeep(struct nh_res_table *res_table, bool notify)
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
{
	unsigned long now = jiffies;
	unsigned long deadline;
	u16 i;

	/* Deadline is the next time that upkeep should be run. It is the
	 * earliest time at which one of the buckets might be migrated.
	 * Start at the most pessimistic estimate: either unbalanced_timer
	 * from now, or if there is none, idle_timer from now. For each
	 * encountered time point, call nh_res_time_set_deadline() to
	 * refine the estimate.
	 */
	if (res_table->unbalanced_timer)
		deadline = now + res_table->unbalanced_timer;
	else
		deadline = now + res_table->idle_timer;

	for (i = 0; i < res_table->num_nh_buckets; i++) {
		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
		bool force;

		if (nh_res_bucket_should_migrate(res_table, bucket,
						 &deadline, &force)) {
1404 1405
			if (!nh_res_bucket_migrate(res_table, i, notify,
						   force)) {
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
				unsigned long idle_point;

				/* A driver can override the migration
				 * decision if the HW reports that the
				 * bucket is actually not idle. Therefore
				 * remark the bucket as busy again and
				 * update the deadline.
				 */
				nh_res_bucket_set_busy(bucket);
				idle_point = nh_res_bucket_idle_point(res_table,
								      bucket,
								      now);
				nh_res_time_set_deadline(idle_point, &deadline);
			}
		}
	}

	/* If the group is still unbalanced, schedule the next upkeep to
	 * either the deadline computed above, or the minimum deadline,
	 * whichever comes later.
	 */
	if (!nh_res_table_is_balanced(res_table)) {
		unsigned long now = jiffies;
		unsigned long min_deadline;

		min_deadline = now + NH_RES_UPKEEP_DW_MINIMUM_INTERVAL;
		if (time_before(deadline, min_deadline))
			deadline = min_deadline;

		queue_delayed_work(system_power_efficient_wq,
				   &res_table->upkeep_dw, deadline - now);
	}
}

static void nh_res_table_upkeep_dw(struct work_struct *work)
{
	struct delayed_work *dw = to_delayed_work(work);
	struct nh_res_table *res_table;

	res_table = container_of(dw, struct nh_res_table, upkeep_dw);
1446
	nh_res_table_upkeep(res_table, true);
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
}

static void nh_res_table_cancel_upkeep(struct nh_res_table *res_table)
{
	cancel_delayed_work_sync(&res_table->upkeep_dw);
}

static void nh_res_group_rebalance(struct nh_group *nhg,
				   struct nh_res_table *res_table)
{
	int prev_upper_bound = 0;
	int total = 0;
	int w = 0;
	int i;

	INIT_LIST_HEAD(&res_table->uw_nh_entries);

	for (i = 0; i < nhg->num_nh; ++i)
		total += nhg->nh_entries[i].weight;

	for (i = 0; i < nhg->num_nh; ++i) {
		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
		int upper_bound;

		w += nhge->weight;
		upper_bound = DIV_ROUND_CLOSEST(res_table->num_nh_buckets * w,
						total);
		nhge->res.wants_buckets = upper_bound - prev_upper_bound;
		prev_upper_bound = upper_bound;

		if (nh_res_nhge_is_uw(nhge)) {
			if (list_empty(&res_table->uw_nh_entries))
				res_table->unbalanced_since = jiffies;
			list_add(&nhge->res.uw_nh_entry,
				 &res_table->uw_nh_entries);
		}
	}
}

/* Migrate buckets in res_table so that they reference NHGE's from NHG with
 * the right NH ID. Set those buckets that do not have a corresponding NHGE
 * entry in NHG as not occupied.
 */
static void nh_res_table_migrate_buckets(struct nh_res_table *res_table,
					 struct nh_group *nhg)
{
	u16 i;

	for (i = 0; i < res_table->num_nh_buckets; i++) {
		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
		u32 id = rtnl_dereference(bucket->nh_entry)->nh->id;
		bool found = false;
		int j;

		for (j = 0; j < nhg->num_nh; j++) {
			struct nh_grp_entry *nhge = &nhg->nh_entries[j];

			if (nhge->nh->id == id) {
				nh_res_bucket_set_nh(bucket, nhge);
				found = true;
				break;
			}
		}

		if (!found)
			nh_res_bucket_unset_nh(bucket);
	}
}

static void replace_nexthop_grp_res(struct nh_group *oldg,
				    struct nh_group *newg)
{
	/* For NH group replacement, the new NHG might only have a stub
	 * hash table with 0 buckets, because the number of buckets was not
	 * specified. For NH removal, oldg and newg both reference the same
	 * res_table. So in any case, in the following, we want to work
	 * with oldg->res_table.
	 */
	struct nh_res_table *old_res_table = rtnl_dereference(oldg->res_table);
	unsigned long prev_unbalanced_since = old_res_table->unbalanced_since;
	bool prev_has_uw = !list_empty(&old_res_table->uw_nh_entries);

	nh_res_table_cancel_upkeep(old_res_table);
	nh_res_table_migrate_buckets(old_res_table, newg);
	nh_res_group_rebalance(newg, old_res_table);
	if (prev_has_uw && !list_empty(&old_res_table->uw_nh_entries))
		old_res_table->unbalanced_since = prev_unbalanced_since;
1534
	nh_res_table_upkeep(old_res_table, true);
1535 1536 1537
}

static void nh_mp_group_rebalance(struct nh_group *nhg)
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
{
	int total = 0;
	int w = 0;
	int i;

	for (i = 0; i < nhg->num_nh; ++i)
		total += nhg->nh_entries[i].weight;

	for (i = 0; i < nhg->num_nh; ++i) {
		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
		int upper_bound;

		w += nhge->weight;
		upper_bound = DIV_ROUND_CLOSEST_ULL((u64)w << 31, total) - 1;
1552
		atomic_set(&nhge->mpath.upper_bound, upper_bound);
1553 1554 1555
	}
}

1556
static void remove_nh_grp_entry(struct net *net, struct nh_grp_entry *nhge,
1557 1558
				struct nl_info *nlinfo)
{
1559
	struct nh_grp_entry *nhges, *new_nhges;
1560
	struct nexthop *nhp = nhge->nh_parent;
1561
	struct netlink_ext_ack extack;
1562
	struct nexthop *nh = nhge->nh;
1563
	struct nh_group *nhg, *newg;
1564
	int i, j, err;
1565 1566 1567

	WARN_ON(!nh);

1568
	nhg = rtnl_dereference(nhp->nh_grp);
1569
	newg = nhg->spare;
1570

1571 1572 1573
	/* last entry, keep it visible and remove the parent */
	if (nhg->num_nh == 1) {
		remove_nexthop(net, nhp, nlinfo);
1574
		return;
1575
	}
1576

1577
	newg->has_v4 = false;
1578
	newg->is_multipath = nhg->is_multipath;
1579
	newg->mpath = nhg->mpath;
1580
	newg->resilient = nhg->resilient;
1581
	newg->fdb_nh = nhg->fdb_nh;
1582
	newg->num_nh = nhg->num_nh;
1583

1584 1585 1586 1587
	/* copy old entries to new except the one getting removed */
	nhges = nhg->nh_entries;
	new_nhges = newg->nh_entries;
	for (i = 0, j = 0; i < nhg->num_nh; ++i) {
1588 1589
		struct nh_info *nhi;

1590 1591 1592 1593 1594
		/* current nexthop getting removed */
		if (nhg->nh_entries[i].nh == nh) {
			newg->num_nh--;
			continue;
		}
1595

1596 1597 1598 1599
		nhi = rtnl_dereference(nhges[i].nh->nh_info);
		if (nhi->family == AF_INET)
			newg->has_v4 = true;

1600 1601 1602 1603 1604 1605 1606
		list_del(&nhges[i].nh_list);
		new_nhges[j].nh_parent = nhges[i].nh_parent;
		new_nhges[j].nh = nhges[i].nh;
		new_nhges[j].weight = nhges[i].weight;
		list_add(&new_nhges[j].nh_list, &new_nhges[j].nh->grp_list);
		j++;
	}
1607

1608 1609 1610 1611 1612
	if (newg->mpath)
		nh_mp_group_rebalance(newg);
	else if (newg->resilient)
		replace_nexthop_grp_res(nhg, newg);

1613 1614 1615 1616
	rcu_assign_pointer(nhp->nh_grp, newg);

	list_del(&nhge->nh_list);
	nexthop_put(nhge->nh);
1617

1618 1619 1620 1621 1622 1623 1624 1625 1626
	/* Removal of a NH from a resilient group is notified through
	 * bucket notifications.
	 */
	if (newg->mpath) {
		err = call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, nhp,
					     &extack);
		if (err)
			pr_err("%s\n", extack._msg);
	}
1627

1628
	if (nlinfo)
1629
		nexthop_notify(RTM_NEWNEXTHOP, nhp, nlinfo);
1630 1631 1632 1633 1634 1635 1636
}

static void remove_nexthop_from_groups(struct net *net, struct nexthop *nh,
				       struct nl_info *nlinfo)
{
	struct nh_grp_entry *nhge, *tmp;

1637 1638
	list_for_each_entry_safe(nhge, tmp, &nh->grp_list, nh_list)
		remove_nh_grp_entry(net, nhge, nlinfo);
1639

1640
	/* make sure all see the newly published array before releasing rtnl */
1641
	synchronize_net();
1642 1643 1644 1645 1646
}

static void remove_nexthop_group(struct nexthop *nh, struct nl_info *nlinfo)
{
	struct nh_group *nhg = rcu_dereference_rtnl(nh->nh_grp);
1647
	struct nh_res_table *res_table;
1648 1649 1650 1651 1652 1653 1654 1655
	int i, num_nh = nhg->num_nh;

	for (i = 0; i < num_nh; ++i) {
		struct nh_grp_entry *nhge = &nhg->nh_entries[i];

		if (WARN_ON(!nhge->nh))
			continue;

1656
		list_del_init(&nhge->nh_list);
1657
	}
1658 1659 1660 1661 1662

	if (nhg->resilient) {
		res_table = rtnl_dereference(nhg->res_table);
		nh_res_table_cancel_upkeep(res_table);
	}
1663 1664
}

D
David Ahern 已提交
1665
/* not called for nexthop replace */
1666 1667
static void __remove_nexthop_fib(struct net *net, struct nexthop *nh)
{
1668
	struct fib6_info *f6i, *tmp;
1669 1670 1671 1672 1673 1674 1675 1676 1677
	bool do_flush = false;
	struct fib_info *fi;

	list_for_each_entry(fi, &nh->fi_list, nh_list) {
		fi->fib_flags |= RTNH_F_DEAD;
		do_flush = true;
	}
	if (do_flush)
		fib_flush(net);
1678 1679 1680 1681 1682

	/* ip6_del_rt removes the entry from this list hence the _safe */
	list_for_each_entry_safe(f6i, tmp, &nh->f6i_list, nh_list) {
		/* __ip6_del_rt does a release, so do a hold here */
		fib6_info_hold(f6i);
1683 1684
		ipv6_stub->ip6_del_rt(net, f6i,
				      !net->ipv4.sysctl_nexthop_compat_mode);
1685
	}
1686 1687
}

1688 1689 1690
static void __remove_nexthop(struct net *net, struct nexthop *nh,
			     struct nl_info *nlinfo)
{
1691 1692
	__remove_nexthop_fib(net, nh);

1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
	if (nh->is_group) {
		remove_nexthop_group(nh, nlinfo);
	} else {
		struct nh_info *nhi;

		nhi = rtnl_dereference(nh->nh_info);
		if (nhi->fib_nhc.nhc_dev)
			hlist_del(&nhi->dev_hash);

		remove_nexthop_from_groups(net, nh, nlinfo);
	}
1704 1705
}

D
David Ahern 已提交
1706
static void remove_nexthop(struct net *net, struct nexthop *nh,
1707
			   struct nl_info *nlinfo)
D
David Ahern 已提交
1708
{
1709
	call_nexthop_notifiers(net, NEXTHOP_EVENT_DEL, nh, NULL);
1710

D
David Ahern 已提交
1711 1712 1713 1714 1715 1716
	/* remove from the tree */
	rb_erase(&nh->rb_node, &net->nexthop.rb_root);

	if (nlinfo)
		nexthop_notify(RTM_DELNEXTHOP, nh, nlinfo);

1717
	__remove_nexthop(net, nh, nlinfo);
D
David Ahern 已提交
1718 1719 1720 1721 1722
	nh_base_seq_inc(net);

	nexthop_put(nh);
}

D
David Ahern 已提交
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
/* if any FIB entries reference this nexthop, any dst entries
 * need to be regenerated
 */
static void nh_rt_cache_flush(struct net *net, struct nexthop *nh)
{
	struct fib6_info *f6i;

	if (!list_empty(&nh->fi_list))
		rt_cache_flush(net);

	list_for_each_entry(f6i, &nh->f6i_list, nh_list)
		ipv6_stub->fib6_update_sernum(net, f6i);
}

static int replace_nexthop_grp(struct net *net, struct nexthop *old,
1738
			       struct nexthop *new, const struct nh_config *cfg,
D
David Ahern 已提交
1739 1740
			       struct netlink_ext_ack *extack)
{
1741 1742 1743
	struct nh_res_table *tmp_table = NULL;
	struct nh_res_table *new_res_table;
	struct nh_res_table *old_res_table;
D
David Ahern 已提交
1744
	struct nh_group *oldg, *newg;
1745
	int i, err;
D
David Ahern 已提交
1746 1747 1748 1749 1750 1751 1752 1753 1754

	if (!new->is_group) {
		NL_SET_ERR_MSG(extack, "Can not replace a nexthop group with a nexthop.");
		return -EINVAL;
	}

	oldg = rtnl_dereference(old->nh_grp);
	newg = rtnl_dereference(new->nh_grp);

1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
	if (newg->mpath != oldg->mpath) {
		NL_SET_ERR_MSG(extack, "Can not replace a nexthop group with one of a different type.");
		return -EINVAL;
	}

	if (newg->mpath) {
		err = call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, new,
					     extack);
		if (err)
			return err;
	} else if (newg->resilient) {
		new_res_table = rtnl_dereference(newg->res_table);
		old_res_table = rtnl_dereference(oldg->res_table);

		/* Accept if num_nh_buckets was not given, but if it was
		 * given, demand that the value be correct.
		 */
		if (cfg->nh_grp_res_has_num_buckets &&
		    cfg->nh_grp_res_num_buckets !=
		    old_res_table->num_nh_buckets) {
			NL_SET_ERR_MSG(extack, "Can not change number of buckets of a resilient nexthop group.");
			return -EINVAL;
		}

1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
		/* Emit a pre-replace notification so that listeners could veto
		 * a potentially unsupported configuration. Otherwise,
		 * individual bucket replacement notifications would need to be
		 * vetoed, which is something that should only happen if the
		 * bucket is currently active.
		 */
		err = call_nexthop_res_table_notifiers(net, new, extack);
		if (err)
			return err;

1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
		if (cfg->nh_grp_res_has_idle_timer)
			old_res_table->idle_timer = cfg->nh_grp_res_idle_timer;
		if (cfg->nh_grp_res_has_unbalanced_timer)
			old_res_table->unbalanced_timer =
				cfg->nh_grp_res_unbalanced_timer;

		replace_nexthop_grp_res(oldg, newg);

		tmp_table = new_res_table;
		rcu_assign_pointer(newg->res_table, old_res_table);
		rcu_assign_pointer(newg->spare->res_table, old_res_table);
	}

D
David Ahern 已提交
1802 1803 1804 1805 1806 1807
	/* update parents - used by nexthop code for cleanup */
	for (i = 0; i < newg->num_nh; i++)
		newg->nh_entries[i].nh_parent = old;

	rcu_assign_pointer(old->nh_grp, newg);

1808 1809 1810 1811 1812
	if (newg->resilient) {
		rcu_assign_pointer(oldg->res_table, tmp_table);
		rcu_assign_pointer(oldg->spare->res_table, tmp_table);
	}

D
David Ahern 已提交
1813 1814 1815 1816 1817 1818 1819 1820
	for (i = 0; i < oldg->num_nh; i++)
		oldg->nh_entries[i].nh_parent = new;

	rcu_assign_pointer(new->nh_grp, oldg);

	return 0;
}

1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
static void nh_group_v4_update(struct nh_group *nhg)
{
	struct nh_grp_entry *nhges;
	bool has_v4 = false;
	int i;

	nhges = nhg->nh_entries;
	for (i = 0; i < nhg->num_nh; i++) {
		struct nh_info *nhi;

		nhi = rtnl_dereference(nhges[i].nh->nh_info);
		if (nhi->family == AF_INET)
			has_v4 = true;
	}
	nhg->has_v4 = has_v4;
}

1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
static int replace_nexthop_single_notify_res(struct net *net,
					     struct nh_res_table *res_table,
					     struct nexthop *old,
					     struct nh_info *oldi,
					     struct nh_info *newi,
					     struct netlink_ext_ack *extack)
{
	u32 nhg_id = res_table->nhg_id;
	int err;
	u16 i;

	for (i = 0; i < res_table->num_nh_buckets; i++) {
		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
		struct nh_grp_entry *nhge;

		nhge = rtnl_dereference(bucket->nh_entry);
		if (nhge->nh == old) {
			err = __call_nexthop_res_bucket_notifiers(net, nhg_id,
								  i, true,
								  oldi, newi,
								  extack);
			if (err)
				goto err_notify;
		}
	}

	return 0;

err_notify:
	while (i-- > 0) {
		struct nh_res_bucket *bucket = &res_table->nh_buckets[i];
		struct nh_grp_entry *nhge;

		nhge = rtnl_dereference(bucket->nh_entry);
		if (nhge->nh == old)
			__call_nexthop_res_bucket_notifiers(net, nhg_id, i,
							    true, newi, oldi,
							    extack);
	}
	return err;
}

static int replace_nexthop_single_notify(struct net *net,
					 struct nexthop *group_nh,
					 struct nexthop *old,
					 struct nh_info *oldi,
					 struct nh_info *newi,
					 struct netlink_ext_ack *extack)
{
	struct nh_group *nhg = rtnl_dereference(group_nh->nh_grp);
	struct nh_res_table *res_table;

	if (nhg->mpath) {
		return call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE,
					      group_nh, extack);
	} else if (nhg->resilient) {
		res_table = rtnl_dereference(nhg->res_table);
		return replace_nexthop_single_notify_res(net, res_table,
							 old, oldi, newi,
							 extack);
	}

	return -EINVAL;
}

D
David Ahern 已提交
1903 1904 1905 1906
static int replace_nexthop_single(struct net *net, struct nexthop *old,
				  struct nexthop *new,
				  struct netlink_ext_ack *extack)
{
1907
	u8 old_protocol, old_nh_flags;
D
David Ahern 已提交
1908
	struct nh_info *oldi, *newi;
1909
	struct nh_grp_entry *nhge;
1910
	int err;
D
David Ahern 已提交
1911 1912 1913 1914 1915 1916

	if (new->is_group) {
		NL_SET_ERR_MSG(extack, "Can not replace a nexthop with a nexthop group.");
		return -EINVAL;
	}

1917 1918 1919 1920 1921 1922 1923 1924 1925
	err = call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, new, extack);
	if (err)
		return err;

	/* Hardware flags were set on 'old' as 'new' is not in the red-black
	 * tree. Therefore, inherit the flags from 'old' to 'new'.
	 */
	new->nh_flags |= old->nh_flags & (RTNH_F_OFFLOAD | RTNH_F_TRAP);

D
David Ahern 已提交
1926 1927 1928 1929 1930 1931
	oldi = rtnl_dereference(old->nh_info);
	newi = rtnl_dereference(new->nh_info);

	newi->nh_parent = old;
	oldi->nh_parent = new;

1932 1933 1934
	old_protocol = old->protocol;
	old_nh_flags = old->nh_flags;

D
David Ahern 已提交
1935 1936 1937 1938 1939 1940
	old->protocol = new->protocol;
	old->nh_flags = new->nh_flags;

	rcu_assign_pointer(old->nh_info, newi);
	rcu_assign_pointer(new->nh_info, oldi);

1941 1942 1943 1944
	/* Send a replace notification for all the groups using the nexthop. */
	list_for_each_entry(nhge, &old->grp_list, nh_list) {
		struct nexthop *nhp = nhge->nh_parent;

1945 1946
		err = replace_nexthop_single_notify(net, nhp, old, oldi, newi,
						    extack);
1947 1948 1949 1950
		if (err)
			goto err_notify;
	}

1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
	/* When replacing an IPv4 nexthop with an IPv6 nexthop, potentially
	 * update IPv4 indication in all the groups using the nexthop.
	 */
	if (oldi->family == AF_INET && newi->family == AF_INET6) {
		list_for_each_entry(nhge, &old->grp_list, nh_list) {
			struct nexthop *nhp = nhge->nh_parent;
			struct nh_group *nhg;

			nhg = rtnl_dereference(nhp->nh_grp);
			nh_group_v4_update(nhg);
		}
	}

D
David Ahern 已提交
1964
	return 0;
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975

err_notify:
	rcu_assign_pointer(new->nh_info, newi);
	rcu_assign_pointer(old->nh_info, oldi);
	old->nh_flags = old_nh_flags;
	old->protocol = old_protocol;
	oldi->nh_parent = old;
	newi->nh_parent = new;
	list_for_each_entry_continue_reverse(nhge, &old->grp_list, nh_list) {
		struct nexthop *nhp = nhge->nh_parent;

1976
		replace_nexthop_single_notify(net, nhp, old, newi, oldi, NULL);
1977 1978 1979
	}
	call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, old, extack);
	return err;
D
David Ahern 已提交
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
}

static void __nexthop_replace_notify(struct net *net, struct nexthop *nh,
				     struct nl_info *info)
{
	struct fib6_info *f6i;

	if (!list_empty(&nh->fi_list)) {
		struct fib_info *fi;

		/* expectation is a few fib_info per nexthop and then
		 * a lot of routes per fib_info. So mark the fib_info
		 * and then walk the fib tables once
		 */
		list_for_each_entry(fi, &nh->fi_list, nh_list)
			fi->nh_updated = true;

		fib_info_notify_update(net, info);

		list_for_each_entry(fi, &nh->fi_list, nh_list)
			fi->nh_updated = false;
	}

	list_for_each_entry(f6i, &nh->f6i_list, nh_list)
		ipv6_stub->fib6_rt_update(net, f6i, info);
}

/* send RTM_NEWROUTE with REPLACE flag set for all FIB entries
 * linked to this nexthop and for all groups that the nexthop
 * is a member of
 */
static void nexthop_replace_notify(struct net *net, struct nexthop *nh,
				   struct nl_info *info)
{
	struct nh_grp_entry *nhge;

	__nexthop_replace_notify(net, nh, info);

	list_for_each_entry(nhge, &nh->grp_list, nh_list)
		__nexthop_replace_notify(net, nhge->nh_parent, info);
}

D
David Ahern 已提交
2022
static int replace_nexthop(struct net *net, struct nexthop *old,
2023 2024
			   struct nexthop *new, const struct nh_config *cfg,
			   struct netlink_ext_ack *extack)
D
David Ahern 已提交
2025
{
D
David Ahern 已提交
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
	bool new_is_reject = false;
	struct nh_grp_entry *nhge;
	int err;

	/* check that existing FIB entries are ok with the
	 * new nexthop definition
	 */
	err = fib_check_nh_list(old, new, extack);
	if (err)
		return err;

	err = fib6_check_nh_list(old, new, extack);
	if (err)
		return err;

	if (!new->is_group) {
		struct nh_info *nhi = rtnl_dereference(new->nh_info);

		new_is_reject = nhi->reject_nh;
	}

	list_for_each_entry(nhge, &old->grp_list, nh_list) {
		/* if new nexthop is a blackhole, any groups using this
		 * nexthop cannot have more than 1 path
		 */
		if (new_is_reject &&
		    nexthop_num_path(nhge->nh_parent) > 1) {
			NL_SET_ERR_MSG(extack, "Blackhole nexthop can not be a member of a group with more than one path");
			return -EINVAL;
		}

		err = fib_check_nh_list(nhge->nh_parent, new, extack);
		if (err)
			return err;

		err = fib6_check_nh_list(nhge->nh_parent, new, extack);
		if (err)
			return err;
	}

	if (old->is_group)
2067
		err = replace_nexthop_grp(net, old, new, cfg, extack);
D
David Ahern 已提交
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
	else
		err = replace_nexthop_single(net, old, new, extack);

	if (!err) {
		nh_rt_cache_flush(net, old);

		__remove_nexthop(net, new, NULL);
		nexthop_put(new);
	}

	return err;
D
David Ahern 已提交
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
}

/* called with rtnl_lock held */
static int insert_nexthop(struct net *net, struct nexthop *new_nh,
			  struct nh_config *cfg, struct netlink_ext_ack *extack)
{
	struct rb_node **pp, *parent = NULL, *next;
	struct rb_root *root = &net->nexthop.rb_root;
	bool replace = !!(cfg->nlflags & NLM_F_REPLACE);
	bool create = !!(cfg->nlflags & NLM_F_CREATE);
	u32 new_id = new_nh->id;
D
David Ahern 已提交
2090
	int replace_notify = 0;
D
David Ahern 已提交
2091 2092 2093 2094 2095 2096
	int rc = -EEXIST;

	pp = &root->rb_node;
	while (1) {
		struct nexthop *nh;

2097
		next = *pp;
D
David Ahern 已提交
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
		if (!next)
			break;

		parent = next;

		nh = rb_entry(parent, struct nexthop, rb_node);
		if (new_id < nh->id) {
			pp = &next->rb_left;
		} else if (new_id > nh->id) {
			pp = &next->rb_right;
		} else if (replace) {
2109
			rc = replace_nexthop(net, nh, new_nh, cfg, extack);
D
David Ahern 已提交
2110
			if (!rc) {
D
David Ahern 已提交
2111
				new_nh = nh; /* send notification with old nh */
D
David Ahern 已提交
2112 2113
				replace_notify = 1;
			}
D
David Ahern 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
			goto out;
		} else {
			/* id already exists and not a replace */
			goto out;
		}
	}

	if (replace && !create) {
		NL_SET_ERR_MSG(extack, "Replace specified without create and no entry exists");
		rc = -ENOENT;
		goto out;
	}

2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
	if (new_nh->is_group) {
		struct nh_group *nhg = rtnl_dereference(new_nh->nh_grp);
		struct nh_res_table *res_table;

		if (nhg->resilient) {
			res_table = rtnl_dereference(nhg->res_table);

			/* Not passing the number of buckets is OK when
			 * replacing, but not when creating a new group.
			 */
			if (!cfg->nh_grp_res_has_num_buckets) {
				NL_SET_ERR_MSG(extack, "Number of buckets not specified for nexthop group insertion");
				rc = -EINVAL;
				goto out;
			}

			nh_res_group_rebalance(nhg, res_table);
2144 2145 2146 2147 2148

			/* Do not send bucket notifications, we do full
			 * notification below.
			 */
			nh_res_table_upkeep(res_table, false);
2149 2150 2151
		}
	}

D
David Ahern 已提交
2152 2153
	rb_link_node_rcu(&new_nh->rb_node, parent, pp);
	rb_insert_color(&new_nh->rb_node, root);
2154

2155 2156 2157
	/* The initial insertion is a full notification for mpath as well
	 * as resilient groups.
	 */
2158 2159 2160 2161
	rc = call_nexthop_notifiers(net, NEXTHOP_EVENT_REPLACE, new_nh, extack);
	if (rc)
		rb_erase(&new_nh->rb_node, &net->nexthop.rb_root);

D
David Ahern 已提交
2162 2163 2164 2165
out:
	if (!rc) {
		nh_base_seq_inc(net);
		nexthop_notify(RTM_NEWNEXTHOP, new_nh, &cfg->nlinfo);
2166
		if (replace_notify && net->ipv4.sysctl_nexthop_compat_mode)
D
David Ahern 已提交
2167
			nexthop_replace_notify(net, new_nh, &cfg->nlinfo);
D
David Ahern 已提交
2168 2169 2170 2171 2172
	}

	return rc;
}

2173 2174
/* rtnl */
/* remove all nexthops tied to a device being deleted */
2175
static void nexthop_flush_dev(struct net_device *dev, unsigned long event)
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
{
	unsigned int hash = nh_dev_hashfn(dev->ifindex);
	struct net *net = dev_net(dev);
	struct hlist_head *head = &net->nexthop.devhash[hash];
	struct hlist_node *n;
	struct nh_info *nhi;

	hlist_for_each_entry_safe(nhi, n, head, dev_hash) {
		if (nhi->fib_nhc.nhc_dev != dev)
			continue;

2187 2188 2189 2190
		if (nhi->reject_nh &&
		    (event == NETDEV_DOWN || event == NETDEV_CHANGE))
			continue;

2191
		remove_nexthop(net, nhi->nh_parent, NULL);
2192 2193 2194
	}
}

D
David Ahern 已提交
2195 2196 2197 2198 2199 2200 2201 2202 2203
/* rtnl; called when net namespace is deleted */
static void flush_all_nexthops(struct net *net)
{
	struct rb_root *root = &net->nexthop.rb_root;
	struct rb_node *node;
	struct nexthop *nh;

	while ((node = rb_first(root))) {
		nh = rb_entry(node, struct nexthop, rb_node);
2204
		remove_nexthop(net, nh, NULL);
D
David Ahern 已提交
2205 2206 2207 2208
		cond_resched();
	}
}

2209 2210 2211 2212 2213
static struct nexthop *nexthop_create_group(struct net *net,
					    struct nh_config *cfg)
{
	struct nlattr *grps_attr = cfg->nh_grp;
	struct nexthop_grp *entry = nla_data(grps_attr);
2214
	u16 num_nh = nla_len(grps_attr) / sizeof(*entry);
2215 2216
	struct nh_group *nhg;
	struct nexthop *nh;
2217
	int err;
2218 2219
	int i;

2220 2221 2222
	if (WARN_ON(!num_nh))
		return ERR_PTR(-EINVAL);

2223 2224 2225 2226 2227 2228
	nh = nexthop_alloc();
	if (!nh)
		return ERR_PTR(-ENOMEM);

	nh->is_group = 1;

2229
	nhg = nexthop_grp_alloc(num_nh);
2230 2231 2232 2233 2234
	if (!nhg) {
		kfree(nh);
		return ERR_PTR(-ENOMEM);
	}

2235 2236
	/* spare group used for removals */
	nhg->spare = nexthop_grp_alloc(num_nh);
2237
	if (!nhg->spare) {
2238 2239
		kfree(nhg);
		kfree(nh);
2240
		return ERR_PTR(-ENOMEM);
2241 2242 2243
	}
	nhg->spare->spare = nhg;

2244 2245 2246 2247 2248
	for (i = 0; i < nhg->num_nh; ++i) {
		struct nexthop *nhe;
		struct nh_info *nhi;

		nhe = nexthop_find_by_id(net, entry[i].id);
2249 2250
		if (!nexthop_get(nhe)) {
			err = -ENOENT;
2251
			goto out_no_nh;
2252
		}
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263

		nhi = rtnl_dereference(nhe->nh_info);
		if (nhi->family == AF_INET)
			nhg->has_v4 = true;

		nhg->nh_entries[i].nh = nhe;
		nhg->nh_entries[i].weight = entry[i].weight + 1;
		list_add(&nhg->nh_entries[i].nh_list, &nhe->grp_list);
		nhg->nh_entries[i].nh_parent = nh;
	}

2264
	if (cfg->nh_grp_type == NEXTHOP_GRP_TYPE_MPATH) {
2265
		nhg->mpath = 1;
2266
		nhg->is_multipath = true;
2267
	} else if (cfg->nh_grp_type == NEXTHOP_GRP_TYPE_RES) {
2268 2269 2270 2271
		struct nh_res_table *res_table;

		/* Bounce resilient groups for now. */
		err = -EINVAL;
2272
		goto out_no_nh;
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283

		res_table = nexthop_res_table_alloc(net, cfg->nh_id, cfg);
		if (!res_table) {
			err = -ENOMEM;
			goto out_no_nh;
		}

		rcu_assign_pointer(nhg->spare->res_table, res_table);
		rcu_assign_pointer(nhg->res_table, res_table);
		nhg->resilient = true;
		nhg->is_multipath = true;
2284
	}
2285

2286
	WARN_ON_ONCE(nhg->mpath + nhg->resilient != 1);
2287 2288

	if (nhg->mpath)
2289
		nh_mp_group_rebalance(nhg);
2290

2291
	if (cfg->nh_fdb)
2292
		nhg->fdb_nh = 1;
2293

2294 2295 2296 2297 2298
	rcu_assign_pointer(nh->nh_grp, nhg);

	return nh;

out_no_nh:
2299 2300
	for (i--; i >= 0; --i) {
		list_del(&nhg->nh_entries[i].nh_list);
2301
		nexthop_put(nhg->nh_entries[i].nh);
2302
	}
2303

2304
	kfree(nhg->spare);
2305 2306 2307
	kfree(nhg);
	kfree(nh);

2308
	return ERR_PTR(err);
2309 2310
}

2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
static int nh_create_ipv4(struct net *net, struct nexthop *nh,
			  struct nh_info *nhi, struct nh_config *cfg,
			  struct netlink_ext_ack *extack)
{
	struct fib_nh *fib_nh = &nhi->fib_nh;
	struct fib_config fib_cfg = {
		.fc_oif   = cfg->nh_ifindex,
		.fc_gw4   = cfg->gw.ipv4,
		.fc_gw_family = cfg->gw.ipv4 ? AF_INET : 0,
		.fc_flags = cfg->nh_flags,
2321 2322
		.fc_encap = cfg->nh_encap,
		.fc_encap_type = cfg->nh_encap_type,
2323
	};
2324
	u32 tb_id = (cfg->dev ? l3mdev_fib_table(cfg->dev) : RT_TABLE_MAIN);
2325
	int err;
2326 2327 2328 2329 2330 2331 2332

	err = fib_nh_init(net, fib_nh, &fib_cfg, 1, extack);
	if (err) {
		fib_nh_release(net, fib_nh);
		goto out;
	}

2333
	if (nhi->fdb_nh)
2334 2335
		goto out;

2336 2337 2338 2339
	/* sets nh_dev if successful */
	err = fib_check_nh(net, fib_nh, tb_id, 0, extack);
	if (!err) {
		nh->nh_flags = fib_nh->fib_nh_flags;
2340 2341
		fib_info_update_nhc_saddr(net, &fib_nh->nh_common,
					  fib_nh->fib_nh_scope);
2342 2343 2344 2345 2346 2347 2348
	} else {
		fib_nh_release(net, fib_nh);
	}
out:
	return err;
}

2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
static int nh_create_ipv6(struct net *net,  struct nexthop *nh,
			  struct nh_info *nhi, struct nh_config *cfg,
			  struct netlink_ext_ack *extack)
{
	struct fib6_nh *fib6_nh = &nhi->fib6_nh;
	struct fib6_config fib6_cfg = {
		.fc_table = l3mdev_fib_table(cfg->dev),
		.fc_ifindex = cfg->nh_ifindex,
		.fc_gateway = cfg->gw.ipv6,
		.fc_flags = cfg->nh_flags,
2359 2360
		.fc_encap = cfg->nh_encap,
		.fc_encap_type = cfg->nh_encap_type,
2361
		.fc_is_fdb = cfg->nh_fdb,
2362
	};
2363
	int err;
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378

	if (!ipv6_addr_any(&cfg->gw.ipv6))
		fib6_cfg.fc_flags |= RTF_GATEWAY;

	/* sets nh_dev if successful */
	err = ipv6_stub->fib6_nh_init(net, fib6_nh, &fib6_cfg, GFP_KERNEL,
				      extack);
	if (err)
		ipv6_stub->fib6_nh_release(fib6_nh);
	else
		nh->nh_flags = fib6_nh->fib_nh_flags;

	return err;
}

D
David Ahern 已提交
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
static struct nexthop *nexthop_create(struct net *net, struct nh_config *cfg,
				      struct netlink_ext_ack *extack)
{
	struct nh_info *nhi;
	struct nexthop *nh;
	int err = 0;

	nh = nexthop_alloc();
	if (!nh)
		return ERR_PTR(-ENOMEM);

	nhi = kzalloc(sizeof(*nhi), GFP_KERNEL);
	if (!nhi) {
		kfree(nh);
		return ERR_PTR(-ENOMEM);
	}

	nh->nh_flags = cfg->nh_flags;
	nh->net = net;

	nhi->nh_parent = nh;
	nhi->family = cfg->nh_family;
	nhi->fib_nhc.nhc_scope = RT_SCOPE_LINK;

2403
	if (cfg->nh_fdb)
2404
		nhi->fdb_nh = 1;
2405

D
David Ahern 已提交
2406 2407 2408 2409 2410
	if (cfg->nh_blackhole) {
		nhi->reject_nh = 1;
		cfg->nh_ifindex = net->loopback_dev->ifindex;
	}

2411 2412 2413 2414
	switch (cfg->nh_family) {
	case AF_INET:
		err = nh_create_ipv4(net, nh, nhi, cfg, extack);
		break;
2415 2416 2417
	case AF_INET6:
		err = nh_create_ipv6(net, nh, nhi, cfg, extack);
		break;
2418 2419
	}

D
David Ahern 已提交
2420 2421 2422 2423 2424 2425
	if (err) {
		kfree(nhi);
		kfree(nh);
		return ERR_PTR(err);
	}

2426
	/* add the entry to the device based hash */
2427
	if (!nhi->fdb_nh)
2428
		nexthop_devhash_add(net, nhi);
2429

D
David Ahern 已提交
2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
	rcu_assign_pointer(nh->nh_info, nhi);

	return nh;
}

/* called with rtnl lock held */
static struct nexthop *nexthop_add(struct net *net, struct nh_config *cfg,
				   struct netlink_ext_ack *extack)
{
	struct nexthop *nh;
	int err;

	if (cfg->nlflags & NLM_F_REPLACE && !cfg->nh_id) {
		NL_SET_ERR_MSG(extack, "Replace requires nexthop id");
		return ERR_PTR(-EINVAL);
	}

	if (!cfg->nh_id) {
		cfg->nh_id = nh_find_unused_id(net);
		if (!cfg->nh_id) {
			NL_SET_ERR_MSG(extack, "No unused id");
			return ERR_PTR(-EINVAL);
		}
	}

2455 2456 2457 2458 2459
	if (cfg->nh_grp)
		nh = nexthop_create_group(net, cfg);
	else
		nh = nexthop_create(net, cfg, extack);

D
David Ahern 已提交
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
	if (IS_ERR(nh))
		return nh;

	refcount_set(&nh->refcnt, 1);
	nh->id = cfg->nh_id;
	nh->protocol = cfg->nh_protocol;
	nh->net = net;

	err = insert_nexthop(net, nh, cfg, extack);
	if (err) {
2470
		__remove_nexthop(net, nh, NULL);
D
David Ahern 已提交
2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
		nexthop_put(nh);
		nh = ERR_PTR(err);
	}

	return nh;
}

static int rtm_to_nh_config(struct net *net, struct sk_buff *skb,
			    struct nlmsghdr *nlh, struct nh_config *cfg,
			    struct netlink_ext_ack *extack)
{
	struct nhmsg *nhm = nlmsg_data(nlh);
P
Petr Machata 已提交
2483
	struct nlattr *tb[ARRAY_SIZE(rtm_nh_policy_new)];
D
David Ahern 已提交
2484 2485
	int err;

P
Petr Machata 已提交
2486 2487 2488
	err = nlmsg_parse(nlh, sizeof(*nhm), tb,
			  ARRAY_SIZE(rtm_nh_policy_new) - 1,
			  rtm_nh_policy_new, extack);
D
David Ahern 已提交
2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
	if (err < 0)
		return err;

	err = -EINVAL;
	if (nhm->resvd || nhm->nh_scope) {
		NL_SET_ERR_MSG(extack, "Invalid values in ancillary header");
		goto out;
	}
	if (nhm->nh_flags & ~NEXTHOP_VALID_USER_FLAGS) {
		NL_SET_ERR_MSG(extack, "Invalid nexthop flags in ancillary header");
		goto out;
	}

	switch (nhm->nh_family) {
2503
	case AF_INET:
2504
	case AF_INET6:
2505
		break;
2506 2507 2508
	case AF_UNSPEC:
		if (tb[NHA_GROUP])
			break;
J
Joe Perches 已提交
2509
		fallthrough;
D
David Ahern 已提交
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
	default:
		NL_SET_ERR_MSG(extack, "Invalid address family");
		goto out;
	}

	memset(cfg, 0, sizeof(*cfg));
	cfg->nlflags = nlh->nlmsg_flags;
	cfg->nlinfo.portid = NETLINK_CB(skb).portid;
	cfg->nlinfo.nlh = nlh;
	cfg->nlinfo.nl_net = net;

	cfg->nh_family = nhm->nh_family;
	cfg->nh_protocol = nhm->nh_protocol;
	cfg->nh_flags = nhm->nh_flags;

	if (tb[NHA_ID])
		cfg->nh_id = nla_get_u32(tb[NHA_ID]);

2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
	if (tb[NHA_FDB]) {
		if (tb[NHA_OIF] || tb[NHA_BLACKHOLE] ||
		    tb[NHA_ENCAP]   || tb[NHA_ENCAP_TYPE]) {
			NL_SET_ERR_MSG(extack, "Fdb attribute can not be used with encap, oif or blackhole");
			goto out;
		}
		if (nhm->nh_flags) {
			NL_SET_ERR_MSG(extack, "Unsupported nexthop flags in ancillary header");
			goto out;
		}
		cfg->nh_fdb = nla_get_flag(tb[NHA_FDB]);
	}

2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
	if (tb[NHA_GROUP]) {
		if (nhm->nh_family != AF_UNSPEC) {
			NL_SET_ERR_MSG(extack, "Invalid family for group");
			goto out;
		}
		cfg->nh_grp = tb[NHA_GROUP];

		cfg->nh_grp_type = NEXTHOP_GRP_TYPE_MPATH;
		if (tb[NHA_GROUP_TYPE])
			cfg->nh_grp_type = nla_get_u16(tb[NHA_GROUP_TYPE]);

		if (cfg->nh_grp_type > NEXTHOP_GRP_TYPE_MAX) {
			NL_SET_ERR_MSG(extack, "Invalid group type");
			goto out;
		}
P
Petr Machata 已提交
2556
		err = nh_check_attr_group(net, tb, ARRAY_SIZE(tb), extack);
2557 2558 2559 2560 2561

		/* no other attributes should be set */
		goto out;
	}

D
David Ahern 已提交
2562
	if (tb[NHA_BLACKHOLE]) {
2563
		if (tb[NHA_GATEWAY] || tb[NHA_OIF] ||
2564 2565
		    tb[NHA_ENCAP]   || tb[NHA_ENCAP_TYPE] || tb[NHA_FDB]) {
			NL_SET_ERR_MSG(extack, "Blackhole attribute can not be used with gateway, oif, encap or fdb");
D
David Ahern 已提交
2566 2567 2568 2569 2570 2571 2572 2573
			goto out;
		}

		cfg->nh_blackhole = 1;
		err = 0;
		goto out;
	}

2574 2575
	if (!cfg->nh_fdb && !tb[NHA_OIF]) {
		NL_SET_ERR_MSG(extack, "Device attribute required for non-blackhole and non-fdb nexthops");
D
David Ahern 已提交
2576 2577 2578
		goto out;
	}

2579 2580 2581 2582
	if (!cfg->nh_fdb && tb[NHA_OIF]) {
		cfg->nh_ifindex = nla_get_u32(tb[NHA_OIF]);
		if (cfg->nh_ifindex)
			cfg->dev = __dev_get_by_index(net, cfg->nh_ifindex);
D
David Ahern 已提交
2583

2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595
		if (!cfg->dev) {
			NL_SET_ERR_MSG(extack, "Invalid device index");
			goto out;
		} else if (!(cfg->dev->flags & IFF_UP)) {
			NL_SET_ERR_MSG(extack, "Nexthop device is not up");
			err = -ENETDOWN;
			goto out;
		} else if (!netif_carrier_ok(cfg->dev)) {
			NL_SET_ERR_MSG(extack, "Carrier for nexthop device is down");
			err = -ENETDOWN;
			goto out;
		}
D
David Ahern 已提交
2596 2597
	}

2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
	err = -EINVAL;
	if (tb[NHA_GATEWAY]) {
		struct nlattr *gwa = tb[NHA_GATEWAY];

		switch (cfg->nh_family) {
		case AF_INET:
			if (nla_len(gwa) != sizeof(u32)) {
				NL_SET_ERR_MSG(extack, "Invalid gateway");
				goto out;
			}
			cfg->gw.ipv4 = nla_get_be32(gwa);
			break;
2610 2611 2612 2613 2614 2615 2616
		case AF_INET6:
			if (nla_len(gwa) != sizeof(struct in6_addr)) {
				NL_SET_ERR_MSG(extack, "Invalid gateway");
				goto out;
			}
			cfg->gw.ipv6 = nla_get_in6_addr(gwa);
			break;
2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
		default:
			NL_SET_ERR_MSG(extack,
				       "Unknown address family for gateway");
			goto out;
		}
	} else {
		/* device only nexthop (no gateway) */
		if (cfg->nh_flags & RTNH_F_ONLINK) {
			NL_SET_ERR_MSG(extack,
				       "ONLINK flag can not be set for nexthop without a gateway");
			goto out;
		}
	}

2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
	if (tb[NHA_ENCAP]) {
		cfg->nh_encap = tb[NHA_ENCAP];

		if (!tb[NHA_ENCAP_TYPE]) {
			NL_SET_ERR_MSG(extack, "LWT encapsulation type is missing");
			goto out;
		}

		cfg->nh_encap_type = nla_get_u16(tb[NHA_ENCAP_TYPE]);
		err = lwtunnel_valid_encap_type(cfg->nh_encap_type, extack);
		if (err < 0)
			goto out;

	} else if (tb[NHA_ENCAP_TYPE]) {
		NL_SET_ERR_MSG(extack, "LWT encapsulation attribute is missing");
		goto out;
	}


D
David Ahern 已提交
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
	err = 0;
out:
	return err;
}

/* rtnl */
static int rtm_new_nexthop(struct sk_buff *skb, struct nlmsghdr *nlh,
			   struct netlink_ext_ack *extack)
{
	struct net *net = sock_net(skb->sk);
	struct nh_config cfg;
	struct nexthop *nh;
	int err;

	err = rtm_to_nh_config(net, skb, nlh, &cfg, extack);
	if (!err) {
		nh = nexthop_add(net, &cfg, extack);
		if (IS_ERR(nh))
			err = PTR_ERR(nh);
	}

	return err;
}

2674 2675 2676
static int __nh_valid_get_del_req(const struct nlmsghdr *nlh,
				  struct nlattr **tb, u32 *id,
				  struct netlink_ext_ack *extack)
D
David Ahern 已提交
2677 2678 2679 2680 2681
{
	struct nhmsg *nhm = nlmsg_data(nlh);

	if (nhm->nh_protocol || nhm->resvd || nhm->nh_scope || nhm->nh_flags) {
		NL_SET_ERR_MSG(extack, "Invalid values in header");
2682
		return -EINVAL;
D
David Ahern 已提交
2683 2684 2685 2686
	}

	if (!tb[NHA_ID]) {
		NL_SET_ERR_MSG(extack, "Nexthop id is missing");
2687
		return -EINVAL;
D
David Ahern 已提交
2688 2689 2690
	}

	*id = nla_get_u32(tb[NHA_ID]);
2691
	if (!(*id)) {
D
David Ahern 已提交
2692
		NL_SET_ERR_MSG(extack, "Invalid nexthop id");
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
		return -EINVAL;
	}

	return 0;
}

static int nh_valid_get_del_req(const struct nlmsghdr *nlh, u32 *id,
				struct netlink_ext_ack *extack)
{
	struct nlattr *tb[ARRAY_SIZE(rtm_nh_policy_get)];
	int err;

	err = nlmsg_parse(nlh, sizeof(struct nhmsg), tb,
			  ARRAY_SIZE(rtm_nh_policy_get) - 1,
			  rtm_nh_policy_get, extack);
	if (err < 0)
		return err;

	return __nh_valid_get_del_req(nlh, tb, id, extack);
D
David Ahern 已提交
2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
}

/* rtnl */
static int rtm_del_nexthop(struct sk_buff *skb, struct nlmsghdr *nlh,
			   struct netlink_ext_ack *extack)
{
	struct net *net = sock_net(skb->sk);
	struct nl_info nlinfo = {
		.nlh = nlh,
		.nl_net = net,
		.portid = NETLINK_CB(skb).portid,
	};
	struct nexthop *nh;
	int err;
	u32 id;

	err = nh_valid_get_del_req(nlh, &id, extack);
	if (err)
		return err;

	nh = nexthop_find_by_id(net, id);
	if (!nh)
		return -ENOENT;

2736
	remove_nexthop(net, nh, &nlinfo);
D
David Ahern 已提交
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779

	return 0;
}

/* rtnl */
static int rtm_get_nexthop(struct sk_buff *in_skb, struct nlmsghdr *nlh,
			   struct netlink_ext_ack *extack)
{
	struct net *net = sock_net(in_skb->sk);
	struct sk_buff *skb = NULL;
	struct nexthop *nh;
	int err;
	u32 id;

	err = nh_valid_get_del_req(nlh, &id, extack);
	if (err)
		return err;

	err = -ENOBUFS;
	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
	if (!skb)
		goto out;

	err = -ENOENT;
	nh = nexthop_find_by_id(net, id);
	if (!nh)
		goto errout_free;

	err = nh_fill_node(skb, nh, RTM_NEWNEXTHOP, NETLINK_CB(in_skb).portid,
			   nlh->nlmsg_seq, 0);
	if (err < 0) {
		WARN_ON(err == -EMSGSIZE);
		goto errout_free;
	}

	err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
out:
	return err;
errout_free:
	kfree_skb(skb);
	goto out;
}

2780 2781 2782 2783 2784 2785 2786 2787 2788
struct nh_dump_filter {
	int dev_idx;
	int master_idx;
	bool group_filter;
	bool fdb_filter;
};

static bool nh_dump_filtered(struct nexthop *nh,
			     struct nh_dump_filter *filter, u8 family)
D
David Ahern 已提交
2789 2790 2791 2792
{
	const struct net_device *dev;
	const struct nh_info *nhi;

2793
	if (filter->group_filter && !nh->is_group)
2794 2795
		return true;

2796
	if (!filter->dev_idx && !filter->master_idx && !family)
D
David Ahern 已提交
2797 2798
		return false;

2799 2800 2801
	if (nh->is_group)
		return true;

D
David Ahern 已提交
2802 2803 2804 2805 2806
	nhi = rtnl_dereference(nh->nh_info);
	if (family && nhi->family != family)
		return true;

	dev = nhi->fib_nhc.nhc_dev;
2807
	if (filter->dev_idx && (!dev || dev->ifindex != filter->dev_idx))
D
David Ahern 已提交
2808 2809
		return true;

2810
	if (filter->master_idx) {
D
David Ahern 已提交
2811 2812 2813 2814 2815 2816
		struct net_device *master;

		if (!dev)
			return true;

		master = netdev_master_upper_dev_get((struct net_device *)dev);
2817
		if (!master || master->ifindex != filter->master_idx)
D
David Ahern 已提交
2818 2819 2820 2821 2822 2823
			return true;
	}

	return false;
}

2824 2825 2826
static int __nh_valid_dump_req(const struct nlmsghdr *nlh, struct nlattr **tb,
			       struct nh_dump_filter *filter,
			       struct netlink_ext_ack *extack)
D
David Ahern 已提交
2827 2828 2829 2830
{
	struct nhmsg *nhm;
	u32 idx;

2831 2832 2833 2834 2835 2836
	if (tb[NHA_OIF]) {
		idx = nla_get_u32(tb[NHA_OIF]);
		if (idx > INT_MAX) {
			NL_SET_ERR_MSG(extack, "Invalid device index");
			return -EINVAL;
		}
2837
		filter->dev_idx = idx;
2838 2839 2840 2841 2842
	}
	if (tb[NHA_MASTER]) {
		idx = nla_get_u32(tb[NHA_MASTER]);
		if (idx > INT_MAX) {
			NL_SET_ERR_MSG(extack, "Invalid master device index");
D
David Ahern 已提交
2843 2844
			return -EINVAL;
		}
2845
		filter->master_idx = idx;
D
David Ahern 已提交
2846
	}
2847 2848
	filter->group_filter = nla_get_flag(tb[NHA_GROUPS]);
	filter->fdb_filter = nla_get_flag(tb[NHA_FDB]);
D
David Ahern 已提交
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858

	nhm = nlmsg_data(nlh);
	if (nhm->nh_protocol || nhm->resvd || nhm->nh_scope || nhm->nh_flags) {
		NL_SET_ERR_MSG(extack, "Invalid values in header for nexthop dump request");
		return -EINVAL;
	}

	return 0;
}

2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
static int nh_valid_dump_req(const struct nlmsghdr *nlh,
			     struct nh_dump_filter *filter,
			     struct netlink_callback *cb)
{
	struct nlattr *tb[ARRAY_SIZE(rtm_nh_policy_dump)];
	int err;

	err = nlmsg_parse(nlh, sizeof(struct nhmsg), tb,
			  ARRAY_SIZE(rtm_nh_policy_dump) - 1,
			  rtm_nh_policy_dump, cb->extack);
	if (err < 0)
		return err;

	return __nh_valid_dump_req(nlh, tb, filter, cb->extack);
}

2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
struct rtm_dump_nh_ctx {
	u32 idx;
};

static struct rtm_dump_nh_ctx *
rtm_dump_nh_ctx(struct netlink_callback *cb)
{
	struct rtm_dump_nh_ctx *ctx = (void *)cb->ctx;

	BUILD_BUG_ON(sizeof(*ctx) > sizeof(cb->ctx));
	return ctx;
}

2888 2889 2890 2891
static int rtm_dump_walk_nexthops(struct sk_buff *skb,
				  struct netlink_callback *cb,
				  struct rb_root *root,
				  struct rtm_dump_nh_ctx *ctx,
2892 2893 2894 2895
				  int (*nh_cb)(struct sk_buff *skb,
					       struct netlink_callback *cb,
					       struct nexthop *nh, void *data),
				  void *data)
D
David Ahern 已提交
2896 2897 2898 2899 2900
{
	struct rb_node *node;
	int idx = 0, s_idx;
	int err;

2901
	s_idx = ctx->idx;
D
David Ahern 已提交
2902 2903 2904 2905 2906 2907 2908
	for (node = rb_first(root); node; node = rb_next(node)) {
		struct nexthop *nh;

		if (idx < s_idx)
			goto cont;

		nh = rb_entry(node, struct nexthop, rb_node);
2909
		ctx->idx = idx;
2910 2911
		err = nh_cb(skb, cb, nh, data);
		if (err)
2912
			return err;
D
David Ahern 已提交
2913 2914 2915 2916
cont:
		idx++;
	}

2917 2918 2919 2920
	ctx->idx = idx;
	return 0;
}

2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934
static int rtm_dump_nexthop_cb(struct sk_buff *skb, struct netlink_callback *cb,
			       struct nexthop *nh, void *data)
{
	struct nhmsg *nhm = nlmsg_data(cb->nlh);
	struct nh_dump_filter *filter = data;

	if (nh_dump_filtered(nh, filter, nhm->nh_family))
		return 0;

	return nh_fill_node(skb, nh, RTM_NEWNEXTHOP,
			    NETLINK_CB(cb->skb).portid,
			    cb->nlh->nlmsg_seq, NLM_F_MULTI);
}

2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947
/* rtnl */
static int rtm_dump_nexthop(struct sk_buff *skb, struct netlink_callback *cb)
{
	struct rtm_dump_nh_ctx *ctx = rtm_dump_nh_ctx(cb);
	struct net *net = sock_net(skb->sk);
	struct rb_root *root = &net->nexthop.rb_root;
	struct nh_dump_filter filter = {};
	int err;

	err = nh_valid_dump_req(cb->nlh, &filter, cb);
	if (err < 0)
		return err;

2948 2949
	err = rtm_dump_walk_nexthops(skb, cb, root, ctx,
				     &rtm_dump_nexthop_cb, &filter);
2950 2951 2952 2953 2954 2955
	if (err < 0) {
		if (likely(skb->len))
			goto out;
		goto out_err;
	}

D
David Ahern 已提交
2956 2957 2958 2959 2960 2961 2962 2963
out:
	err = skb->len;
out_err:
	cb->seq = net->nexthop.seq;
	nl_dump_check_consistent(cb, nlmsg_hdr(skb));
	return err;
}

2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
static void nexthop_sync_mtu(struct net_device *dev, u32 orig_mtu)
{
	unsigned int hash = nh_dev_hashfn(dev->ifindex);
	struct net *net = dev_net(dev);
	struct hlist_head *head = &net->nexthop.devhash[hash];
	struct hlist_node *n;
	struct nh_info *nhi;

	hlist_for_each_entry_safe(nhi, n, head, dev_hash) {
		if (nhi->fib_nhc.nhc_dev == dev) {
			if (nhi->family == AF_INET)
				fib_nhc_update_mtu(&nhi->fib_nhc, dev->mtu,
						   orig_mtu);
		}
	}
}

/* rtnl */
static int nh_netdev_event(struct notifier_block *this,
			   unsigned long event, void *ptr)
{
	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
	struct netdev_notifier_info_ext *info_ext;

	switch (event) {
	case NETDEV_DOWN:
	case NETDEV_UNREGISTER:
2991
		nexthop_flush_dev(dev, event);
2992 2993 2994
		break;
	case NETDEV_CHANGE:
		if (!(dev_get_flags(dev) & (IFF_RUNNING | IFF_LOWER_UP)))
2995
			nexthop_flush_dev(dev, event);
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
		break;
	case NETDEV_CHANGEMTU:
		info_ext = ptr;
		nexthop_sync_mtu(dev, info_ext->ext.mtu);
		rt_cache_flush(dev_net(dev));
		break;
	}
	return NOTIFY_DONE;
}

static struct notifier_block nh_netdev_notifier = {
	.notifier_call = nh_netdev_event,
};

3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
static int nexthops_dump(struct net *net, struct notifier_block *nb,
			 struct netlink_ext_ack *extack)
{
	struct rb_root *root = &net->nexthop.rb_root;
	struct rb_node *node;
	int err = 0;

	for (node = rb_first(root); node; node = rb_next(node)) {
		struct nexthop *nh;

		nh = rb_entry(node, struct nexthop, rb_node);
		err = call_nexthop_notifier(nb, net, NEXTHOP_EVENT_REPLACE, nh,
					    extack);
		if (err)
			break;
	}

	return err;
}

3030 3031
int register_nexthop_notifier(struct net *net, struct notifier_block *nb,
			      struct netlink_ext_ack *extack)
3032
{
3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
	int err;

	rtnl_lock();
	err = nexthops_dump(net, nb, extack);
	if (err)
		goto unlock;
	err = blocking_notifier_chain_register(&net->nexthop.notifier_chain,
					       nb);
unlock:
	rtnl_unlock();
	return err;
3044 3045 3046 3047 3048
}
EXPORT_SYMBOL(register_nexthop_notifier);

int unregister_nexthop_notifier(struct net *net, struct notifier_block *nb)
{
3049 3050
	return blocking_notifier_chain_unregister(&net->nexthop.notifier_chain,
						  nb);
3051 3052 3053
}
EXPORT_SYMBOL(unregister_nexthop_notifier);

3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074
void nexthop_set_hw_flags(struct net *net, u32 id, bool offload, bool trap)
{
	struct nexthop *nexthop;

	rcu_read_lock();

	nexthop = nexthop_find_by_id(net, id);
	if (!nexthop)
		goto out;

	nexthop->nh_flags &= ~(RTNH_F_OFFLOAD | RTNH_F_TRAP);
	if (offload)
		nexthop->nh_flags |= RTNH_F_OFFLOAD;
	if (trap)
		nexthop->nh_flags |= RTNH_F_TRAP;

out:
	rcu_read_unlock();
}
EXPORT_SYMBOL(nexthop_set_hw_flags);

D
David Ahern 已提交
3075 3076 3077 3078 3079
static void __net_exit nexthop_net_exit(struct net *net)
{
	rtnl_lock();
	flush_all_nexthops(net);
	rtnl_unlock();
3080
	kfree(net->nexthop.devhash);
D
David Ahern 已提交
3081 3082 3083 3084
}

static int __net_init nexthop_net_init(struct net *net)
{
3085 3086
	size_t sz = sizeof(struct hlist_head) * NH_DEV_HASHSIZE;

D
David Ahern 已提交
3087
	net->nexthop.rb_root = RB_ROOT;
3088 3089 3090
	net->nexthop.devhash = kzalloc(sz, GFP_KERNEL);
	if (!net->nexthop.devhash)
		return -ENOMEM;
3091
	BLOCKING_INIT_NOTIFIER_HEAD(&net->nexthop.notifier_chain);
D
David Ahern 已提交
3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104

	return 0;
}

static struct pernet_operations nexthop_net_ops = {
	.init = nexthop_net_init,
	.exit = nexthop_net_exit,
};

static int __init nexthop_init(void)
{
	register_pernet_subsys(&nexthop_net_ops);

3105 3106
	register_netdevice_notifier(&nh_netdev_notifier);

D
David Ahern 已提交
3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
	rtnl_register(PF_UNSPEC, RTM_NEWNEXTHOP, rtm_new_nexthop, NULL, 0);
	rtnl_register(PF_UNSPEC, RTM_DELNEXTHOP, rtm_del_nexthop, NULL, 0);
	rtnl_register(PF_UNSPEC, RTM_GETNEXTHOP, rtm_get_nexthop,
		      rtm_dump_nexthop, 0);

	rtnl_register(PF_INET, RTM_NEWNEXTHOP, rtm_new_nexthop, NULL, 0);
	rtnl_register(PF_INET, RTM_GETNEXTHOP, NULL, rtm_dump_nexthop, 0);

	rtnl_register(PF_INET6, RTM_NEWNEXTHOP, rtm_new_nexthop, NULL, 0);
	rtnl_register(PF_INET6, RTM_GETNEXTHOP, NULL, rtm_dump_nexthop, 0);

	return 0;
}
subsys_initcall(nexthop_init);