1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 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
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 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
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 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
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 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
 584
 585
 586
 587
 588
 589
 590
 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
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 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
 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
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 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
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 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
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
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
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
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
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
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
1446
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
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
// SPDX-License-Identifier: GPL-2.0-or-later

#include <linux/bits.h>
#include <linux/bitfield.h>
#include <linux/idr.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/netlink.h>
#include <linux/skbuff.h>
#include <linux/xarray.h>
#include <net/devlink.h>
#include <net/net_shaper.h>

#include "shaper_nl_gen.h"

#include "../core/dev.h"

#define NET_SHAPER_SCOPE_SHIFT	26
#define NET_SHAPER_ID_MASK	GENMASK(NET_SHAPER_SCOPE_SHIFT - 1, 0)
#define NET_SHAPER_SCOPE_MASK	GENMASK(31, NET_SHAPER_SCOPE_SHIFT)

#define NET_SHAPER_ID_UNSPEC NET_SHAPER_ID_MASK

static_assert(NET_SHAPER_ID_UNSPEC == NET_SHAPER_MAX_HANDLE_ID + 1);

struct net_shaper_hierarchy {
	struct xarray shapers;
};

struct net_shaper_nl_ctx {
	struct net_shaper_binding binding;
	netdevice_tracker dev_tracker;
	unsigned long start_index;
};

static struct net_shaper_binding *net_shaper_binding_from_ctx(void *ctx)
{
	return &((struct net_shaper_nl_ctx *)ctx)->binding;
}

static struct net_shaper_hierarchy *
net_shaper_hierarchy(struct net_shaper_binding *binding)
{
	/* Pairs with WRITE_ONCE() in net_shaper_hierarchy_setup. */
	if (binding->type == NET_SHAPER_BINDING_TYPE_NETDEV)
		return READ_ONCE(binding->netdev->net_shaper_hierarchy);

	/* No other type supported yet. */
	return NULL;
}

static struct net_shaper_hierarchy *
net_shaper_hierarchy_rcu(struct net_shaper_binding *binding)
{
	/* Readers look up the device and take a ref, then take RCU lock
	 * later at which point netdev may have been unregistered and flushed.
	 * READ_ONCE() pairs with WRITE_ONCE() in net_shaper_hierarchy_setup.
	 */
	if (binding->type == NET_SHAPER_BINDING_TYPE_NETDEV &&
	    READ_ONCE(binding->netdev->reg_state) <= NETREG_REGISTERED)
		return READ_ONCE(binding->netdev->net_shaper_hierarchy);

	/* No other type supported yet. */
	return NULL;
}

static const struct net_shaper_ops *
net_shaper_ops(struct net_shaper_binding *binding)
{
	if (binding->type == NET_SHAPER_BINDING_TYPE_NETDEV)
		return binding->netdev->netdev_ops->net_shaper_ops;

	/* No other type supported yet. */
	return NULL;
}

/* Count the number of [multi] attributes of the given type. */
static int net_shaper_list_len(struct genl_info *info, int type)
{
	struct nlattr *attr;
	int rem, cnt = 0;

	nla_for_each_attr_type(attr, type, genlmsg_data(info->genlhdr),
			       genlmsg_len(info->genlhdr), rem)
		cnt++;
	return cnt;
}

static int net_shaper_handle_size(void)
{
	return nla_total_size(nla_total_size(sizeof(u32)) +
			      nla_total_size(sizeof(u32)));
}

static int net_shaper_group_reply_size(void)
{
	return nla_total_size(sizeof(u32)) +	/* NET_SHAPER_A_IFINDEX */
	       net_shaper_handle_size();	/* NET_SHAPER_A_HANDLE */
}

static int net_shaper_fill_binding(struct sk_buff *msg,
				   const struct net_shaper_binding *binding,
				   u32 type)
{
	/* Should never happen, as currently only NETDEV is supported. */
	if (WARN_ON_ONCE(binding->type != NET_SHAPER_BINDING_TYPE_NETDEV))
		return -EINVAL;

	if (nla_put_u32(msg, type, binding->netdev->ifindex))
		return -EMSGSIZE;

	return 0;
}

static int net_shaper_fill_handle(struct sk_buff *msg,
				  const struct net_shaper_handle *handle,
				  u32 type)
{
	struct nlattr *handle_attr;

	if (handle->scope == NET_SHAPER_SCOPE_UNSPEC)
		return 0;

	handle_attr = nla_nest_start(msg, type);
	if (!handle_attr)
		return -EMSGSIZE;

	if (nla_put_u32(msg, NET_SHAPER_A_HANDLE_SCOPE, handle->scope) ||
	    (handle->scope >= NET_SHAPER_SCOPE_QUEUE &&
	     nla_put_u32(msg, NET_SHAPER_A_HANDLE_ID, handle->id)))
		goto handle_nest_cancel;

	nla_nest_end(msg, handle_attr);
	return 0;

handle_nest_cancel:
	nla_nest_cancel(msg, handle_attr);
	return -EMSGSIZE;
}

static void net_shaper_copy(struct net_shaper *dst,
			    const struct net_shaper *src)
{
	WRITE_ONCE(dst->parent.scope, READ_ONCE(src->parent.scope));
	WRITE_ONCE(dst->parent.id, READ_ONCE(src->parent.id));
	WRITE_ONCE(dst->handle.scope, READ_ONCE(src->handle.scope));
	WRITE_ONCE(dst->handle.id, READ_ONCE(src->handle.id));

	WRITE_ONCE(dst->metric, READ_ONCE(src->metric));
	WRITE_ONCE(dst->bw_min, READ_ONCE(src->bw_min));
	WRITE_ONCE(dst->bw_max, READ_ONCE(src->bw_max));
	WRITE_ONCE(dst->burst, READ_ONCE(src->burst));
	WRITE_ONCE(dst->priority, READ_ONCE(src->priority));
	WRITE_ONCE(dst->weight, READ_ONCE(src->weight));

	/* private fields are only used on the write path under the lock */
	data_race(dst->leaves = src->leaves);
}

static int
net_shaper_fill_one(struct sk_buff *msg,
		    const struct net_shaper_binding *binding,
		    const struct net_shaper *shaper,
		    const struct genl_info *info)
{
	struct net_shaper cur;
	void *hdr;

	hdr = genlmsg_iput(msg, info);
	if (!hdr)
		return -EMSGSIZE;

	/* Make a copy to avoid data races */
	net_shaper_copy(&cur, shaper);

	if (net_shaper_fill_binding(msg, binding, NET_SHAPER_A_IFINDEX) ||
	    net_shaper_fill_handle(msg, &cur.parent,
				   NET_SHAPER_A_PARENT) ||
	    net_shaper_fill_handle(msg, &cur.handle,
				   NET_SHAPER_A_HANDLE) ||
	    ((cur.bw_min || cur.bw_max || cur.burst) &&
	     nla_put_u32(msg, NET_SHAPER_A_METRIC, cur.metric)) ||
	    (cur.bw_min &&
	     nla_put_uint(msg, NET_SHAPER_A_BW_MIN, cur.bw_min)) ||
	    (cur.bw_max &&
	     nla_put_uint(msg, NET_SHAPER_A_BW_MAX, cur.bw_max)) ||
	    (cur.burst &&
	     nla_put_uint(msg, NET_SHAPER_A_BURST, cur.burst)) ||
	    (cur.priority &&
	     nla_put_u32(msg, NET_SHAPER_A_PRIORITY, cur.priority)) ||
	    (cur.weight &&
	     nla_put_u32(msg, NET_SHAPER_A_WEIGHT, cur.weight)))
		goto nla_put_failure;

	genlmsg_end(msg, hdr);

	return 0;

nla_put_failure:
	genlmsg_cancel(msg, hdr);
	return -EMSGSIZE;
}

/* Initialize the context fetching the relevant device and
 * acquiring a reference to it.
 */
static int net_shaper_ctx_setup(const struct genl_info *info, int type,
				struct net_shaper_nl_ctx *ctx)
{
	struct net *ns = genl_info_net(info);
	struct net_device *dev;
	int ifindex;

	if (GENL_REQ_ATTR_CHECK(info, type))
		return -EINVAL;

	ifindex = nla_get_u32(info->attrs[type]);
	dev = netdev_get_by_index(ns, ifindex, &ctx->dev_tracker, GFP_KERNEL);
	if (!dev) {
		NL_SET_BAD_ATTR(info->extack, info->attrs[type]);
		return -ENOENT;
	}

	if (!dev->netdev_ops->net_shaper_ops) {
		NL_SET_BAD_ATTR(info->extack, info->attrs[type]);
		netdev_put(dev, &ctx->dev_tracker);
		return -EOPNOTSUPP;
	}

	ctx->binding.type = NET_SHAPER_BINDING_TYPE_NETDEV;
	ctx->binding.netdev = dev;
	return 0;
}

/* Like net_shaper_ctx_setup(), but for "write" handlers (never for dumps!)
 * Acquires the lock protecting the hierarchy (instance lock for netdev).
 */
static int net_shaper_ctx_setup_lock(const struct genl_info *info, int type,
				     struct net_shaper_nl_ctx *ctx)
{
	struct net *ns = genl_info_net(info);
	struct net_device *dev;
	int ifindex;

	if (GENL_REQ_ATTR_CHECK(info, type))
		return -EINVAL;

	ifindex = nla_get_u32(info->attrs[type]);
	dev = netdev_get_by_index_lock(ns, ifindex);
	if (!dev) {
		NL_SET_BAD_ATTR(info->extack, info->attrs[type]);
		return -ENOENT;
	}

	if (!dev->netdev_ops->net_shaper_ops) {
		NL_SET_BAD_ATTR(info->extack, info->attrs[type]);
		netdev_unlock(dev);
		return -EOPNOTSUPP;
	}

	ctx->binding.type = NET_SHAPER_BINDING_TYPE_NETDEV;
	ctx->binding.netdev = dev;
	return 0;
}

static void net_shaper_ctx_cleanup(struct net_shaper_nl_ctx *ctx)
{
	if (ctx->binding.type == NET_SHAPER_BINDING_TYPE_NETDEV)
		netdev_put(ctx->binding.netdev, &ctx->dev_tracker);
}

static void net_shaper_ctx_cleanup_unlock(struct net_shaper_nl_ctx *ctx)
{
	if (ctx->binding.type == NET_SHAPER_BINDING_TYPE_NETDEV)
		netdev_unlock(ctx->binding.netdev);
}

static u32 net_shaper_handle_to_index(const struct net_shaper_handle *handle)
{
	return FIELD_PREP(NET_SHAPER_SCOPE_MASK, handle->scope) |
		FIELD_PREP(NET_SHAPER_ID_MASK, handle->id);
}

static void net_shaper_index_to_handle(u32 index,
				       struct net_shaper_handle *handle)
{
	handle->scope = FIELD_GET(NET_SHAPER_SCOPE_MASK, index);
	handle->id = FIELD_GET(NET_SHAPER_ID_MASK, index);
}

static void net_shaper_default_parent(const struct net_shaper_handle *handle,
				      struct net_shaper_handle *parent)
{
	switch (handle->scope) {
	case NET_SHAPER_SCOPE_UNSPEC:
	case NET_SHAPER_SCOPE_NETDEV:
	case __NET_SHAPER_SCOPE_MAX:
		parent->scope = NET_SHAPER_SCOPE_UNSPEC;
		break;

	case NET_SHAPER_SCOPE_QUEUE:
	case NET_SHAPER_SCOPE_NODE:
		parent->scope = NET_SHAPER_SCOPE_NETDEV;
		break;
	}
	parent->id = 0;
}

static struct net_shaper *
net_shaper_lookup(struct net_shaper_binding *binding,
		  const struct net_shaper_handle *handle)
{
	u32 index = net_shaper_handle_to_index(handle);
	struct net_shaper_hierarchy *hierarchy;
	struct net_shaper *cur;

	hierarchy = net_shaper_hierarchy_rcu(binding);
	if (!hierarchy)
		return NULL;

	cur = xa_load(&hierarchy->shapers, index);
	/* Check valid before reading fields */
	if (!cur || !smp_load_acquire(&cur->valid))
		return NULL;

	return cur;
}

/* Allocate on demand the per device shaper's hierarchy container.
 * Called under the lock protecting the hierarchy (instance lock for netdev)
 */
static struct net_shaper_hierarchy *
net_shaper_hierarchy_setup(struct net_shaper_binding *binding)
{
	struct net_shaper_hierarchy *hierarchy = net_shaper_hierarchy(binding);

	if (hierarchy)
		return hierarchy;

	hierarchy = kmalloc_obj(*hierarchy);
	if (!hierarchy)
		return NULL;

	/* The flag is required for ID allocation */
	xa_init_flags(&hierarchy->shapers, XA_FLAGS_ALLOC);

	switch (binding->type) {
	case NET_SHAPER_BINDING_TYPE_NETDEV:
		/* Pairs with READ_ONCE in net_shaper_hierarchy. */
		WRITE_ONCE(binding->netdev->net_shaper_hierarchy, hierarchy);
		break;
	}
	return hierarchy;
}

/* Prepare the hierarchy container to actually insert the given shaper, doing
 * in advance the needed allocations.
 */
static int net_shaper_pre_insert(struct net_shaper_binding *binding,
				 struct net_shaper_handle *handle,
				 struct netlink_ext_ack *extack)
{
	struct net_shaper_hierarchy *hierarchy = net_shaper_hierarchy(binding);
	struct net_shaper *prev, *cur;
	bool id_allocated = false;
	int ret, index;

	if (!hierarchy)
		return -ENOMEM;

	index = net_shaper_handle_to_index(handle);
	cur = xa_load(&hierarchy->shapers, index);
	if (cur)
		return 0;

	/* Allocated a new id, if needed. */
	if (handle->scope == NET_SHAPER_SCOPE_NODE &&
	    handle->id == NET_SHAPER_ID_UNSPEC) {
		u32 min, max;

		handle->id = NET_SHAPER_MAX_HANDLE_ID;
		max = net_shaper_handle_to_index(handle);
		handle->id = 0;
		min = net_shaper_handle_to_index(handle);

		ret = xa_alloc(&hierarchy->shapers, &index, NULL,
			       XA_LIMIT(min, max), GFP_KERNEL);
		if (ret < 0) {
			NL_SET_ERR_MSG(extack, "Can't allocate new id for NODE shaper");
			return ret;
		}

		net_shaper_index_to_handle(index, handle);
		id_allocated = true;
	}

	cur = kzalloc_obj(*cur);
	if (!cur) {
		ret = -ENOMEM;
		goto free_id;
	}

	/* Insert as 'tentative' (no VALID mark). The mark will be set by
	 * net_shaper_commit() once the driver-side configuration succeeds.
	 */
	prev = xa_store(&hierarchy->shapers, index, cur, GFP_KERNEL);
	if (xa_err(prev)) {
		NL_SET_ERR_MSG(extack, "Can't insert shaper into device store");
		kfree(cur);
		ret = xa_err(prev);
		goto free_id;
	}
	return 0;

free_id:
	if (id_allocated)
		xa_erase(&hierarchy->shapers, index);
	return ret;
}

/* Commit the tentative insert with the actual values.
 * Must be called only after a successful net_shaper_pre_insert().
 */
static void net_shaper_commit(struct net_shaper_binding *binding,
			      int nr_shapers, const struct net_shaper *shapers)
{
	struct net_shaper_hierarchy *hierarchy = net_shaper_hierarchy(binding);
	struct net_shaper *cur;
	int index;
	int i;

	for (i = 0; i < nr_shapers; ++i) {
		index = net_shaper_handle_to_index(&shapers[i].handle);

		cur = xa_load(&hierarchy->shapers, index);
		if (WARN_ON_ONCE(!cur))
			continue;

		/* Successful update: update the hierarchy container... */
		net_shaper_copy(cur, &shapers[i]);
		/* ... publish to lockless readers. */
		smp_store_release(&cur->valid, true);
	}
}

/* Rollback all the tentative inserts from the hierarchy. */
static void net_shaper_rollback(struct net_shaper_binding *binding)
{
	struct net_shaper_hierarchy *hierarchy = net_shaper_hierarchy(binding);
	struct net_shaper *cur;
	unsigned long index;

	if (!hierarchy)
		return;

	xa_for_each(&hierarchy->shapers, index, cur) {
		if (cur->valid)
			continue;
		xa_erase(&hierarchy->shapers, index);
		kfree_rcu(cur, rcu);
	}
}

static int net_shaper_parse_handle(const struct nlattr *attr,
				   const struct genl_info *info,
				   struct net_shaper_handle *handle)
{
	struct nlattr *tb[NET_SHAPER_A_HANDLE_MAX + 1];
	struct nlattr *id_attr;
	u32 id = 0;
	int ret;

	ret = nla_parse_nested(tb, NET_SHAPER_A_HANDLE_MAX, attr,
			       net_shaper_handle_nl_policy, info->extack);
	if (ret < 0)
		return ret;

	if (NL_REQ_ATTR_CHECK(info->extack, attr, tb,
			      NET_SHAPER_A_HANDLE_SCOPE))
		return -EINVAL;

	handle->scope = nla_get_u32(tb[NET_SHAPER_A_HANDLE_SCOPE]);

	/* The default id for NODE scope shapers is an invalid one
	 * to help the 'group' operation discriminate between new
	 * NODE shaper creation (ID_UNSPEC) and reuse of existing
	 * shaper (any other value).
	 */
	id_attr = tb[NET_SHAPER_A_HANDLE_ID];
	if (id_attr) {
		id = nla_get_u32(id_attr);
	} else if (handle->scope == NET_SHAPER_SCOPE_NODE) {
		id = NET_SHAPER_ID_UNSPEC;
	} else if (handle->scope == NET_SHAPER_SCOPE_QUEUE) {
		NL_SET_ERR_ATTR_MISS(info->extack, attr,
				     NET_SHAPER_A_HANDLE_ID);
		return -EINVAL;
	}

	if (id && handle->scope == NET_SHAPER_SCOPE_NETDEV) {
		NL_SET_ERR_MSG_ATTR(info->extack, id_attr,
				    "Netdev scope is a singleton, must use ID 0");
		return -EINVAL;
	}

	handle->id = id;
	return 0;
}

static int net_shaper_validate_caps(struct net_shaper_binding *binding,
				    struct nlattr **tb,
				    const struct genl_info *info,
				    struct net_shaper *shaper)
{
	const struct net_shaper_ops *ops = net_shaper_ops(binding);
	struct nlattr *bad = NULL;
	unsigned long caps = 0;

	ops->capabilities(binding, shaper->handle.scope, &caps);

	if (tb[NET_SHAPER_A_PRIORITY] &&
	    !(caps & BIT(NET_SHAPER_A_CAPS_SUPPORT_PRIORITY)))
		bad = tb[NET_SHAPER_A_PRIORITY];
	if (tb[NET_SHAPER_A_WEIGHT] &&
	    !(caps & BIT(NET_SHAPER_A_CAPS_SUPPORT_WEIGHT)))
		bad = tb[NET_SHAPER_A_WEIGHT];
	if (tb[NET_SHAPER_A_BW_MIN] &&
	    !(caps & BIT(NET_SHAPER_A_CAPS_SUPPORT_BW_MIN)))
		bad = tb[NET_SHAPER_A_BW_MIN];
	if (tb[NET_SHAPER_A_BW_MAX] &&
	    !(caps & BIT(NET_SHAPER_A_CAPS_SUPPORT_BW_MAX)))
		bad = tb[NET_SHAPER_A_BW_MAX];
	if (tb[NET_SHAPER_A_BURST] &&
	    !(caps & BIT(NET_SHAPER_A_CAPS_SUPPORT_BURST)))
		bad = tb[NET_SHAPER_A_BURST];

	if (!caps)
		bad = tb[NET_SHAPER_A_HANDLE];

	if (bad) {
		NL_SET_BAD_ATTR(info->extack, bad);
		return -EOPNOTSUPP;
	}

	if (shaper->handle.scope == NET_SHAPER_SCOPE_QUEUE &&
	    binding->type == NET_SHAPER_BINDING_TYPE_NETDEV &&
	    shaper->handle.id >= binding->netdev->real_num_tx_queues) {
		NL_SET_ERR_MSG_FMT(info->extack,
				   "Not existing queue id %d max %d",
				   shaper->handle.id,
				   binding->netdev->real_num_tx_queues);
		return -ENOENT;
	}

	/* The metric is really used only if there is *any* rate-related
	 * setting, either in current attributes set or in pre-existing
	 * values.
	 */
	if (shaper->burst || shaper->bw_min || shaper->bw_max) {
		u32 metric_cap = NET_SHAPER_A_CAPS_SUPPORT_METRIC_BPS +
				 shaper->metric;

		/* The metric test can fail even when the user did not
		 * specify the METRIC attribute. Pointing to rate related
		 * attribute will be confusing, as the attribute itself
		 * could be indeed supported, with a different metric.
		 * Be more specific.
		 */
		if (!(caps & BIT(metric_cap))) {
			NL_SET_ERR_MSG_FMT(info->extack, "Bad metric %d",
					   shaper->metric);
			return -EOPNOTSUPP;
		}
	}
	return 0;
}

static int net_shaper_parse_info(struct net_shaper_binding *binding,
				 struct nlattr **tb,
				 const struct genl_info *info,
				 struct net_shaper *shaper,
				 bool *exists)
{
	struct net_shaper *old;
	int ret;

	/* The shaper handle is the only mandatory attribute. */
	if (NL_REQ_ATTR_CHECK(info->extack, NULL, tb, NET_SHAPER_A_HANDLE))
		return -EINVAL;

	ret = net_shaper_parse_handle(tb[NET_SHAPER_A_HANDLE], info,
				      &shaper->handle);
	if (ret)
		return ret;

	if (shaper->handle.scope == NET_SHAPER_SCOPE_UNSPEC) {
		NL_SET_BAD_ATTR(info->extack, tb[NET_SHAPER_A_HANDLE]);
		return -EINVAL;
	}

	/* Fetch existing hierarchy, if any, so that user provide info will
	 * incrementally update the existing shaper configuration.
	 */
	old = net_shaper_lookup(binding, &shaper->handle);
	if (old)
		*shaper = *old;
	*exists = !!old;

	if (tb[NET_SHAPER_A_METRIC])
		shaper->metric = nla_get_u32(tb[NET_SHAPER_A_METRIC]);

	if (tb[NET_SHAPER_A_BW_MIN])
		shaper->bw_min = nla_get_uint(tb[NET_SHAPER_A_BW_MIN]);

	if (tb[NET_SHAPER_A_BW_MAX])
		shaper->bw_max = nla_get_uint(tb[NET_SHAPER_A_BW_MAX]);

	if (tb[NET_SHAPER_A_BURST])
		shaper->burst = nla_get_uint(tb[NET_SHAPER_A_BURST]);

	if (tb[NET_SHAPER_A_PRIORITY])
		shaper->priority = nla_get_u32(tb[NET_SHAPER_A_PRIORITY]);

	if (tb[NET_SHAPER_A_WEIGHT])
		shaper->weight = nla_get_u32(tb[NET_SHAPER_A_WEIGHT]);

	ret = net_shaper_validate_caps(binding, tb, info, shaper);
	if (ret < 0)
		return ret;

	return 0;
}

static int net_shaper_validate_nesting(struct net_shaper_binding *binding,
				       const struct net_shaper *shaper,
				       struct netlink_ext_ack *extack)
{
	const struct net_shaper_ops *ops = net_shaper_ops(binding);
	unsigned long caps = 0;

	ops->capabilities(binding, shaper->handle.scope, &caps);
	if (!(caps & BIT(NET_SHAPER_A_CAPS_SUPPORT_NESTING))) {
		NL_SET_ERR_MSG_FMT(extack,
				   "Nesting not supported for scope %d",
				   shaper->handle.scope);
		return -EOPNOTSUPP;
	}
	return 0;
}

/* Fetch the existing leaf and update it with the user-provided
 * attributes.
 */
static int net_shaper_parse_leaf(struct net_shaper_binding *binding,
				 const struct nlattr *attr,
				 const struct genl_info *info,
				 const struct net_shaper *node,
				 struct net_shaper *shaper)
{
	struct nlattr *tb[NET_SHAPER_A_WEIGHT + 1];
	bool exists;
	int ret;

	ret = nla_parse_nested(tb, NET_SHAPER_A_WEIGHT, attr,
			       net_shaper_leaf_info_nl_policy, info->extack);
	if (ret < 0)
		return ret;

	ret = net_shaper_parse_info(binding, tb, info, shaper, &exists);
	if (ret < 0)
		return ret;

	if (shaper->handle.scope != NET_SHAPER_SCOPE_QUEUE) {
		NL_SET_BAD_ATTR(info->extack, tb[NET_SHAPER_A_HANDLE]);
		return -EINVAL;
	}

	if (node->handle.scope == NET_SHAPER_SCOPE_NODE) {
		ret = net_shaper_validate_nesting(binding, shaper,
						  info->extack);
		if (ret < 0)
			return ret;
	}

	if (!exists)
		net_shaper_default_parent(&shaper->handle, &shaper->parent);
	return 0;
}

/* Alike net_parse_shaper_info(), but additionally allow the user specifying
 * the shaper's parent handle.
 */
static int net_shaper_parse_node(struct net_shaper_binding *binding,
				 struct nlattr **tb,
				 const struct genl_info *info,
				 struct net_shaper *shaper)
{
	bool exists;
	int ret;

	ret = net_shaper_parse_info(binding, tb, info, shaper, &exists);
	if (ret)
		return ret;

	if (shaper->handle.scope != NET_SHAPER_SCOPE_NODE &&
	    shaper->handle.scope != NET_SHAPER_SCOPE_NETDEV) {
		NL_SET_BAD_ATTR(info->extack, tb[NET_SHAPER_A_HANDLE]);
		return -EINVAL;
	}

	if (tb[NET_SHAPER_A_PARENT]) {
		ret = net_shaper_parse_handle(tb[NET_SHAPER_A_PARENT], info,
					      &shaper->parent);
		if (ret)
			return ret;

		if (shaper->parent.scope != NET_SHAPER_SCOPE_NODE &&
		    shaper->parent.scope != NET_SHAPER_SCOPE_NETDEV) {
			NL_SET_BAD_ATTR(info->extack, tb[NET_SHAPER_A_PARENT]);
			return -EINVAL;
		}
	}
	return 0;
}

static int net_shaper_generic_pre(struct genl_info *info, int type)
{
	struct net_shaper_nl_ctx *ctx = (struct net_shaper_nl_ctx *)info->ctx;

	BUILD_BUG_ON(sizeof(*ctx) > sizeof(info->ctx));

	return net_shaper_ctx_setup(info, type, ctx);
}

int net_shaper_nl_pre_doit(const struct genl_split_ops *ops,
			   struct sk_buff *skb, struct genl_info *info)
{
	return net_shaper_generic_pre(info, NET_SHAPER_A_IFINDEX);
}

static void net_shaper_generic_post(struct genl_info *info)
{
	net_shaper_ctx_cleanup((struct net_shaper_nl_ctx *)info->ctx);
}

void net_shaper_nl_post_doit(const struct genl_split_ops *ops,
			     struct sk_buff *skb, struct genl_info *info)
{
	net_shaper_generic_post(info);
}

int net_shaper_nl_pre_doit_write(const struct genl_split_ops *ops,
				struct sk_buff *skb, struct genl_info *info)
{
	struct net_shaper_nl_ctx *ctx = (struct net_shaper_nl_ctx *)info->ctx;

	BUILD_BUG_ON(sizeof(*ctx) > sizeof(info->ctx));

	return net_shaper_ctx_setup_lock(info, NET_SHAPER_A_IFINDEX, ctx);
}

void net_shaper_nl_post_doit_write(const struct genl_split_ops *ops,
				   struct sk_buff *skb, struct genl_info *info)
{
	net_shaper_ctx_cleanup_unlock((struct net_shaper_nl_ctx *)info->ctx);
}

int net_shaper_nl_pre_dumpit(struct netlink_callback *cb)
{
	struct net_shaper_nl_ctx *ctx = (struct net_shaper_nl_ctx *)cb->ctx;
	const struct genl_info *info = genl_info_dump(cb);

	return net_shaper_ctx_setup(info, NET_SHAPER_A_IFINDEX, ctx);
}

int net_shaper_nl_post_dumpit(struct netlink_callback *cb)
{
	net_shaper_ctx_cleanup((struct net_shaper_nl_ctx *)cb->ctx);
	return 0;
}

int net_shaper_nl_cap_pre_doit(const struct genl_split_ops *ops,
			       struct sk_buff *skb, struct genl_info *info)
{
	return net_shaper_generic_pre(info, NET_SHAPER_A_CAPS_IFINDEX);
}

void net_shaper_nl_cap_post_doit(const struct genl_split_ops *ops,
				 struct sk_buff *skb, struct genl_info *info)
{
	net_shaper_generic_post(info);
}

int net_shaper_nl_cap_pre_dumpit(struct netlink_callback *cb)
{
	struct net_shaper_nl_ctx *ctx = (struct net_shaper_nl_ctx *)cb->ctx;

	return net_shaper_ctx_setup(genl_info_dump(cb),
				    NET_SHAPER_A_CAPS_IFINDEX, ctx);
}

int net_shaper_nl_cap_post_dumpit(struct netlink_callback *cb)
{
	struct net_shaper_nl_ctx *ctx = (struct net_shaper_nl_ctx *)cb->ctx;

	net_shaper_ctx_cleanup(ctx);
	return 0;
}

int net_shaper_nl_get_doit(struct sk_buff *skb, struct genl_info *info)
{
	struct net_shaper_binding *binding;
	struct net_shaper_handle handle;
	struct net_shaper *shaper;
	struct sk_buff *msg;
	int ret;

	if (GENL_REQ_ATTR_CHECK(info, NET_SHAPER_A_HANDLE))
		return -EINVAL;

	binding = net_shaper_binding_from_ctx(info->ctx);
	ret = net_shaper_parse_handle(info->attrs[NET_SHAPER_A_HANDLE], info,
				      &handle);
	if (ret < 0)
		return ret;

	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
	if (!msg)
		return -ENOMEM;

	rcu_read_lock();
	shaper = net_shaper_lookup(binding, &handle);
	if (!shaper) {
		NL_SET_BAD_ATTR(info->extack,
				info->attrs[NET_SHAPER_A_HANDLE]);
		rcu_read_unlock();
		ret = -ENOENT;
		goto free_msg;
	}

	ret = net_shaper_fill_one(msg, binding, shaper, info);
	rcu_read_unlock();
	if (ret)
		goto free_msg;

	return genlmsg_reply(msg, info);

free_msg:
	nlmsg_free(msg);
	return ret;
}

int net_shaper_nl_get_dumpit(struct sk_buff *skb,
			     struct netlink_callback *cb)
{
	struct net_shaper_nl_ctx *ctx = (struct net_shaper_nl_ctx *)cb->ctx;
	const struct genl_info *info = genl_info_dump(cb);
	struct net_shaper_hierarchy *hierarchy;
	struct net_shaper_binding *binding;
	struct net_shaper *shaper;
	int ret = 0;

	/* Don't error out dumps performed before any set operation. */
	binding = net_shaper_binding_from_ctx(ctx);

	rcu_read_lock();
	hierarchy = net_shaper_hierarchy_rcu(binding);
	if (!hierarchy)
		goto out_unlock;

	for (; (shaper = xa_find(&hierarchy->shapers, &ctx->start_index,
				 U32_MAX, XA_PRESENT));
	     ctx->start_index++) {
		/* Check valid before reading fields */
		if (!smp_load_acquire(&shaper->valid))
			continue;

		ret = net_shaper_fill_one(skb, binding, shaper, info);
		if (ret)
			break;
	}
out_unlock:
	rcu_read_unlock();

	return ret;
}

int net_shaper_nl_set_doit(struct sk_buff *skb, struct genl_info *info)
{
	struct net_shaper_hierarchy *hierarchy;
	struct net_shaper_binding *binding;
	const struct net_shaper_ops *ops;
	struct net_shaper_handle handle;
	struct net_shaper shaper = {};
	bool exists;
	int ret;

	binding = net_shaper_binding_from_ctx(info->ctx);

	ret = net_shaper_parse_info(binding, info->attrs, info, &shaper,
				    &exists);
	if (ret)
		return ret;

	if (!exists)
		net_shaper_default_parent(&shaper.handle, &shaper.parent);

	hierarchy = net_shaper_hierarchy_setup(binding);
	if (!hierarchy)
		return -ENOMEM;

	/* The 'set' operation can't create node-scope shapers. */
	handle = shaper.handle;
	if (handle.scope == NET_SHAPER_SCOPE_NODE &&
	    !net_shaper_lookup(binding, &handle))
		return -ENOENT;

	ret = net_shaper_pre_insert(binding, &handle, info->extack);
	if (ret)
		return ret;

	ops = net_shaper_ops(binding);
	ret = ops->set(binding, &shaper, info->extack);
	if (ret) {
		net_shaper_rollback(binding);
		return ret;
	}

	net_shaper_commit(binding, 1, &shaper);

	return 0;
}

static int __net_shaper_delete(struct net_shaper_binding *binding,
			       struct net_shaper *shaper,
			       struct netlink_ext_ack *extack)
{
	struct net_shaper_hierarchy *hierarchy = net_shaper_hierarchy(binding);
	struct net_shaper_handle parent_handle, handle = shaper->handle;
	const struct net_shaper_ops *ops = net_shaper_ops(binding);
	int ret;

again:
	parent_handle = shaper->parent;

	ret = ops->delete(binding, &handle, extack);
	if (ret < 0)
		return ret;

	xa_erase(&hierarchy->shapers, net_shaper_handle_to_index(&handle));
	kfree_rcu(shaper, rcu);

	/* Eventually delete the parent, if it is left over with no leaves. */
	if (parent_handle.scope == NET_SHAPER_SCOPE_NODE) {
		shaper = net_shaper_lookup(binding, &parent_handle);
		if (shaper && !--shaper->leaves) {
			handle = parent_handle;
			goto again;
		}
	}
	return 0;
}

static int net_shaper_handle_cmp(const struct net_shaper_handle *a,
				 const struct net_shaper_handle *b)
{
	/* Must avoid holes in struct net_shaper_handle. */
	BUILD_BUG_ON(sizeof(*a) != 8);

	return memcmp(a, b, sizeof(*a));
}

static int net_shaper_parse_leaves(struct net_shaper_binding *binding,
				   struct genl_info *info,
				   const struct net_shaper *node,
				   struct net_shaper *leaves,
				   int leaves_count)
{
	struct nlattr *attr;
	int i, j, ret, rem;

	i = 0;
	nla_for_each_attr_type(attr, NET_SHAPER_A_LEAVES,
			       genlmsg_data(info->genlhdr),
			       genlmsg_len(info->genlhdr), rem) {
		if (WARN_ON_ONCE(i >= leaves_count))
			return -EINVAL;

		ret = net_shaper_parse_leaf(binding, attr, info,
					    node, &leaves[i]);
		if (ret)
			return ret;

		/* Reject duplicates */
		for (j = 0; j < i; j++) {
			if (net_shaper_handle_cmp(&leaves[i].handle,
						  &leaves[j].handle))
				continue;

			NL_SET_ERR_MSG_ATTR_FMT(info->extack, attr,
						"Duplicate leaf shaper %d:%d",
						leaves[i].handle.scope,
						leaves[i].handle.id);
			return -EINVAL;
		}

		i++;
	}

	return 0;
}

static int net_shaper_parent_from_leaves(int leaves_count,
					 const struct net_shaper *leaves,
					 struct net_shaper *node,
					 struct netlink_ext_ack *extack)
{
	struct net_shaper_handle parent = leaves[0].parent;
	int i;

	for (i = 1; i < leaves_count; ++i) {
		if (net_shaper_handle_cmp(&leaves[i].parent, &parent)) {
			NL_SET_ERR_MSG_FMT(extack, "All the leaves shapers must have the same old parent");
			return -EINVAL;
		}
	}

	node->parent = parent;
	return 0;
}

static int __net_shaper_group(struct net_shaper_binding *binding,
			      bool update_node, int leaves_count,
			      struct net_shaper *leaves,
			      struct net_shaper *node,
			      struct netlink_ext_ack *extack)
{
	const struct net_shaper_ops *ops = net_shaper_ops(binding);
	struct net_shaper_handle leaf_handle;
	struct net_shaper *parent = NULL;
	bool new_node = false;
	int i, ret;

	if (node->handle.scope == NET_SHAPER_SCOPE_NODE) {
		struct net_shaper *cur = NULL;

		new_node = node->handle.id == NET_SHAPER_ID_UNSPEC;

		if (!new_node) {
			cur = net_shaper_lookup(binding, &node->handle);
			if (!cur) {
				/* The related attribute is not available
				 * when reaching here from the delete() op.
				 */
				NL_SET_ERR_MSG_FMT(extack,
						   "Node shaper %d:%d does not exist",
						   node->handle.scope,
						   node->handle.id);
				return -ENOENT;
			}
		}

		/* When unspecified, the node parent scope is inherited from
		 * the leaves.
		 */
		if (node->parent.scope == NET_SHAPER_SCOPE_UNSPEC) {
			ret = net_shaper_parent_from_leaves(leaves_count,
							    leaves, node,
							    extack);
			if (ret)
				return ret;
		}

		if (cur && net_shaper_handle_cmp(&cur->parent,
						 &node->parent)) {
			NL_SET_ERR_MSG_FMT(extack,
					   "Cannot reparent node shaper %d:%d",
					   node->handle.scope,
					   node->handle.id);
			return -EOPNOTSUPP;
		}

	} else {
		net_shaper_default_parent(&node->handle, &node->parent);
	}

	if (node->parent.scope == NET_SHAPER_SCOPE_NODE) {
		parent = net_shaper_lookup(binding, &node->parent);
		if (!parent) {
			NL_SET_ERR_MSG_FMT(extack, "Node parent shaper %d:%d does not exists",
					   node->parent.scope, node->parent.id);
			return -ENOENT;
		}

		ret = net_shaper_validate_nesting(binding, node, extack);
		if (ret < 0)
			return ret;
	}

	if (update_node) {
		/* For newly created node scope shaper, the following will
		 * update the handle, due to id allocation.
		 */
		ret = net_shaper_pre_insert(binding, &node->handle, extack);
		if (ret)
			return ret;
	}

	for (i = 0; i < leaves_count; ++i) {
		leaf_handle = leaves[i].handle;

		ret = net_shaper_pre_insert(binding, &leaf_handle, extack);
		if (ret)
			goto rollback;

		if (!net_shaper_handle_cmp(&leaves[i].parent, &node->handle))
			continue;

		/* The leaves shapers will be nested to the node, update the
		 * linking accordingly.
		 */
		leaves[i].parent = node->handle;
		node->leaves++;
	}

	ret = ops->group(binding, leaves_count, leaves, node, extack);
	if (ret < 0)
		goto rollback;

	/* The node's parent gains a new leaf only when the node itself
	 * is created by this group operation
	 */
	if (new_node && parent)
		parent->leaves++;
	if (update_node)
		net_shaper_commit(binding, 1, node);
	net_shaper_commit(binding, leaves_count, leaves);
	return 0;

rollback:
	net_shaper_rollback(binding);
	return ret;
}

static int net_shaper_pre_del_node(struct net_shaper_binding *binding,
				   const struct net_shaper *shaper,
				   struct netlink_ext_ack *extack)
{
	struct net_shaper_hierarchy *hierarchy = net_shaper_hierarchy(binding);
	struct net_shaper *cur, *leaves, node = {};
	int ret, leaves_count = 0;
	unsigned long index;
	bool update_node;

	if (!shaper->leaves)
		return 0;

	/* Fetch the new node information. */
	node.handle = shaper->parent;
	cur = net_shaper_lookup(binding, &node.handle);
	if (cur) {
		node = *cur;
	} else {
		/* A scope NODE shaper can be nested only to the NETDEV scope
		 * shaper without creating the latter, this check may fail only
		 * if the data is in inconsistent status.
		 */
		if (WARN_ON_ONCE(node.handle.scope != NET_SHAPER_SCOPE_NETDEV))
			return -EINVAL;
	}

	leaves = kzalloc_objs(struct net_shaper, shaper->leaves);
	if (!leaves)
		return -ENOMEM;

	/* Build the leaves arrays. */
	xa_for_each(&hierarchy->shapers, index, cur) {
		if (net_shaper_handle_cmp(&cur->parent, &shaper->handle))
			continue;

		if (WARN_ON_ONCE(leaves_count == shaper->leaves)) {
			ret = -EINVAL;
			goto free;
		}

		leaves[leaves_count++] = *cur;
	}

	/* When re-linking to the netdev shaper, avoid the eventual, implicit,
	 * creation of the new node, would be surprising since the user is
	 * doing a delete operation.
	 */
	update_node = node.handle.scope != NET_SHAPER_SCOPE_NETDEV;
	ret = __net_shaper_group(binding, update_node, leaves_count,
				 leaves, &node, extack);

free:
	kfree(leaves);
	return ret;
}

int net_shaper_nl_delete_doit(struct sk_buff *skb, struct genl_info *info)
{
	struct net_shaper_hierarchy *hierarchy;
	struct net_shaper_binding *binding;
	struct net_shaper_handle handle;
	struct net_shaper *shaper;
	int ret;

	if (GENL_REQ_ATTR_CHECK(info, NET_SHAPER_A_HANDLE))
		return -EINVAL;

	binding = net_shaper_binding_from_ctx(info->ctx);

	ret = net_shaper_parse_handle(info->attrs[NET_SHAPER_A_HANDLE], info,
				      &handle);
	if (ret)
		return ret;

	hierarchy = net_shaper_hierarchy(binding);
	if (!hierarchy)
		return -ENOENT;

	shaper = net_shaper_lookup(binding, &handle);
	if (!shaper)
		return -ENOENT;

	if (handle.scope == NET_SHAPER_SCOPE_NODE) {
		ret = net_shaper_pre_del_node(binding, shaper, info->extack);
		if (ret)
			return ret;
	}

	return __net_shaper_delete(binding, shaper, info->extack);
}

static int net_shaper_group_send_reply(struct net_shaper_binding *binding,
				       const struct net_shaper_handle *handle,
				       struct genl_info *info,
				       struct sk_buff *msg)
{
	void *hdr;

	hdr = genlmsg_iput(msg, info);
	if (!hdr)
		goto free_msg;

	if (net_shaper_fill_binding(msg, binding, NET_SHAPER_A_IFINDEX) ||
	    net_shaper_fill_handle(msg, handle, NET_SHAPER_A_HANDLE))
		goto free_msg;

	genlmsg_end(msg, hdr);

	return genlmsg_reply(msg, info);

free_msg:
	/* Should never happen as msg is pre-allocated with enough space. */
	WARN_ONCE(true, "calculated message payload length (%d)",
		  net_shaper_group_reply_size());
	nlmsg_free(msg);
	return -EMSGSIZE;
}

int net_shaper_nl_group_doit(struct sk_buff *skb, struct genl_info *info)
{
	struct net_shaper **old_nodes, *leaves, node = {};
	struct net_shaper_hierarchy *hierarchy;
	struct net_shaper_binding *binding;
	int i, ret, leaves_count;
	int old_nodes_count = 0;
	struct sk_buff *msg;

	if (GENL_REQ_ATTR_CHECK(info, NET_SHAPER_A_LEAVES))
		return -EINVAL;

	binding = net_shaper_binding_from_ctx(info->ctx);

	/* The group operation is optional. */
	if (!net_shaper_ops(binding)->group)
		return -EOPNOTSUPP;

	leaves_count = net_shaper_list_len(info, NET_SHAPER_A_LEAVES);
	if (!leaves_count) {
		NL_SET_BAD_ATTR(info->extack,
				info->attrs[NET_SHAPER_A_LEAVES]);
		return -EINVAL;
	}

	leaves = kcalloc(leaves_count, sizeof(struct net_shaper) +
			 sizeof(struct net_shaper *), GFP_KERNEL);
	if (!leaves)
		return -ENOMEM;
	old_nodes = (void *)&leaves[leaves_count];

	ret = net_shaper_parse_node(binding, info->attrs, info, &node);
	if (ret)
		goto free_leaves;

	ret = net_shaper_parse_leaves(binding, info, &node,
				      leaves, leaves_count);
	if (ret)
		goto free_leaves;

	/* Prepare the msg reply in advance, to avoid device operation
	 * rollback on allocation failure.
	 */
	msg = genlmsg_new(net_shaper_group_reply_size(), GFP_KERNEL);
	if (!msg) {
		ret = -ENOMEM;
		goto free_leaves;
	}

	hierarchy = net_shaper_hierarchy_setup(binding);
	if (!hierarchy) {
		ret = -ENOMEM;
		goto free_msg;
	}

	/* Record the node shapers that this group() operation can make
	 * childless for later cleanup.
	 */
	for (i = 0; i < leaves_count; i++) {
		if (leaves[i].parent.scope == NET_SHAPER_SCOPE_NODE &&
		    net_shaper_handle_cmp(&leaves[i].parent, &node.handle)) {
			struct net_shaper *tmp;

			tmp = net_shaper_lookup(binding, &leaves[i].parent);
			if (!tmp)
				continue;

			old_nodes[old_nodes_count++] = tmp;
		}
	}

	ret = __net_shaper_group(binding, true, leaves_count, leaves, &node,
				 info->extack);
	if (ret)
		goto free_msg;

	/* Check if we need to delete any node left alone by the new leaves
	 * linkage.
	 */
	for (i = 0; i < old_nodes_count; ++i) {
		struct net_shaper *tmp = old_nodes[i];

		if (--tmp->leaves > 0)
			continue;

		/* Errors here are not fatal: the grouping operation is
		 * completed, and user-space can still explicitly clean-up
		 * left-over nodes.
		 */
		__net_shaper_delete(binding, tmp, info->extack);
	}

	ret = net_shaper_group_send_reply(binding, &node.handle, info, msg);
	if (ret)
		GENL_SET_ERR_MSG_FMT(info, "Can't send reply");

free_leaves:
	kfree(leaves);
	return ret;

free_msg:
	kfree_skb(msg);
	goto free_leaves;
}

static int
net_shaper_cap_fill_one(struct sk_buff *msg,
			struct net_shaper_binding *binding,
			enum net_shaper_scope scope, unsigned long flags,
			const struct genl_info *info)
{
	unsigned long cur;
	void *hdr;

	hdr = genlmsg_iput(msg, info);
	if (!hdr)
		return -EMSGSIZE;

	if (net_shaper_fill_binding(msg, binding, NET_SHAPER_A_CAPS_IFINDEX) ||
	    nla_put_u32(msg, NET_SHAPER_A_CAPS_SCOPE, scope))
		goto nla_put_failure;

	for (cur = NET_SHAPER_A_CAPS_SUPPORT_METRIC_BPS;
	     cur <= NET_SHAPER_A_CAPS_MAX; ++cur) {
		if (flags & BIT(cur) && nla_put_flag(msg, cur))
			goto nla_put_failure;
	}

	genlmsg_end(msg, hdr);

	return 0;

nla_put_failure:
	genlmsg_cancel(msg, hdr);
	return -EMSGSIZE;
}

int net_shaper_nl_cap_get_doit(struct sk_buff *skb, struct genl_info *info)
{
	struct net_shaper_binding *binding;
	const struct net_shaper_ops *ops;
	enum net_shaper_scope scope;
	unsigned long flags = 0;
	struct sk_buff *msg;
	int ret;

	if (GENL_REQ_ATTR_CHECK(info, NET_SHAPER_A_CAPS_SCOPE))
		return -EINVAL;

	binding = net_shaper_binding_from_ctx(info->ctx);
	scope = nla_get_u32(info->attrs[NET_SHAPER_A_CAPS_SCOPE]);
	ops = net_shaper_ops(binding);
	ops->capabilities(binding, scope, &flags);
	if (!flags)
		return -EOPNOTSUPP;

	msg = genlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
	if (!msg)
		return -ENOMEM;

	ret = net_shaper_cap_fill_one(msg, binding, scope, flags, info);
	if (ret)
		goto free_msg;

	return genlmsg_reply(msg, info);

free_msg:
	nlmsg_free(msg);
	return ret;
}

int net_shaper_nl_cap_get_dumpit(struct sk_buff *skb,
				 struct netlink_callback *cb)
{
	const struct genl_info *info = genl_info_dump(cb);
	struct net_shaper_binding *binding;
	const struct net_shaper_ops *ops;
	enum net_shaper_scope scope;
	int ret;

	binding = net_shaper_binding_from_ctx(cb->ctx);
	ops = net_shaper_ops(binding);
	for (scope = 0; scope <= NET_SHAPER_SCOPE_MAX; ++scope) {
		unsigned long flags = 0;

		ops->capabilities(binding, scope, &flags);
		if (!flags)
			continue;

		ret = net_shaper_cap_fill_one(skb, binding, scope, flags,
					      info);
		/* cap dumps are tiny, we expect them to fit in a single skb */
		WARN_ON_ONCE(ret == -EMSGSIZE);
		if (ret)
			return ret;
	}

	return 0;
}

static void net_shaper_flush(struct net_shaper_binding *binding)
{
	struct net_shaper_hierarchy *hierarchy = net_shaper_hierarchy(binding);
	struct net_shaper *cur;
	unsigned long index;

	if (!hierarchy)
		return;

	xa_for_each(&hierarchy->shapers, index, cur) {
		xa_erase(&hierarchy->shapers, index);
		/* No need to use kfree_rcu(), netdev is already unpublished,
		 * and synchronize_rcu() has been run as part of
		 * unregister_netdevice().
		 */
		kfree(cur);
	}

	kfree(hierarchy);
}

void net_shaper_flush_netdev(struct net_device *dev)
{
	struct net_shaper_binding binding = {
		.type = NET_SHAPER_BINDING_TYPE_NETDEV,
		.netdev = dev,
	};

	net_shaper_flush(&binding);
}

void net_shaper_set_real_num_tx_queues(struct net_device *dev,
				       unsigned int txq)
{
	struct net_shaper_hierarchy *hierarchy;
	struct net_shaper_binding binding;
	int i;

	binding.type = NET_SHAPER_BINDING_TYPE_NETDEV;
	binding.netdev = dev;
	hierarchy = net_shaper_hierarchy(&binding);
	if (!hierarchy)
		return;

	/* Only drivers implementing shapers support ensure
	 * the lock is acquired in advance.
	 */
	netdev_assert_locked(dev);

	/* Take action only when decreasing the tx queue number. */
	for (i = txq; i < dev->real_num_tx_queues; ++i) {
		struct net_shaper_handle handle, parent_handle;
		struct net_shaper *shaper;
		u32 index;

		handle.scope = NET_SHAPER_SCOPE_QUEUE;
		handle.id = i;
		shaper = net_shaper_lookup(&binding, &handle);
		if (!shaper)
			continue;

		/* Don't touch the H/W for the queue shaper, the drivers already
		 * deleted the queue and related resources.
		 */
		parent_handle = shaper->parent;
		index = net_shaper_handle_to_index(&handle);
		xa_erase(&hierarchy->shapers, index);
		kfree_rcu(shaper, rcu);

		/* The recursion on parent does the full job. */
		if (parent_handle.scope != NET_SHAPER_SCOPE_NODE)
			continue;

		shaper = net_shaper_lookup(&binding, &parent_handle);
		if (shaper && !--shaper->leaves)
			__net_shaper_delete(&binding, shaper, NULL);
	}
}

static int __init shaper_init(void)
{
	return genl_register_family(&net_shaper_nl_family);
}

subsys_initcall(shaper_init);