Linux Audio

Check our new training course

Embedded Linux Audio

Check our new training course
with Creative Commons CC-BY-SA
lecture materials

Bootlin logo

Elixir Cross Referencer

Loading...
   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
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
// SPDX-License-Identifier: GPL-2.0
/* Copyright (c) 2017 - 2018 Covalent IO, Inc. http://covalent.io */

#include <linux/bpf.h>
#include <linux/btf_ids.h>
#include <linux/filter.h>
#include <linux/errno.h>
#include <linux/file.h>
#include <linux/net.h>
#include <linux/workqueue.h>
#include <linux/skmsg.h>
#include <linux/list.h>
#include <linux/jhash.h>
#include <linux/sock_diag.h>
#include <net/udp.h>

struct bpf_stab {
	struct bpf_map map;
	struct sock **sks;
	struct sk_psock_progs progs;
	raw_spinlock_t lock;
};

#define SOCK_CREATE_FLAG_MASK				\
	(BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY)

static int sock_map_prog_update(struct bpf_map *map, struct bpf_prog *prog,
				struct bpf_prog *old, u32 which);
static struct sk_psock_progs *sock_map_progs(struct bpf_map *map);

static struct bpf_map *sock_map_alloc(union bpf_attr *attr)
{
	struct bpf_stab *stab;

	if (!capable(CAP_NET_ADMIN))
		return ERR_PTR(-EPERM);
	if (attr->max_entries == 0 ||
	    attr->key_size    != 4 ||
	    (attr->value_size != sizeof(u32) &&
	     attr->value_size != sizeof(u64)) ||
	    attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
		return ERR_PTR(-EINVAL);

	stab = kzalloc(sizeof(*stab), GFP_USER | __GFP_ACCOUNT);
	if (!stab)
		return ERR_PTR(-ENOMEM);

	bpf_map_init_from_attr(&stab->map, attr);
	raw_spin_lock_init(&stab->lock);

	stab->sks = bpf_map_area_alloc((u64) stab->map.max_entries *
				       sizeof(struct sock *),
				       stab->map.numa_node);
	if (!stab->sks) {
		kfree(stab);
		return ERR_PTR(-ENOMEM);
	}

	return &stab->map;
}

int sock_map_get_from_fd(const union bpf_attr *attr, struct bpf_prog *prog)
{
	u32 ufd = attr->target_fd;
	struct bpf_map *map;
	struct fd f;
	int ret;

	if (attr->attach_flags || attr->replace_bpf_fd)
		return -EINVAL;

	f = fdget(ufd);
	map = __bpf_map_get(f);
	if (IS_ERR(map))
		return PTR_ERR(map);
	ret = sock_map_prog_update(map, prog, NULL, attr->attach_type);
	fdput(f);
	return ret;
}

int sock_map_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
{
	u32 ufd = attr->target_fd;
	struct bpf_prog *prog;
	struct bpf_map *map;
	struct fd f;
	int ret;

	if (attr->attach_flags || attr->replace_bpf_fd)
		return -EINVAL;

	f = fdget(ufd);
	map = __bpf_map_get(f);
	if (IS_ERR(map))
		return PTR_ERR(map);

	prog = bpf_prog_get(attr->attach_bpf_fd);
	if (IS_ERR(prog)) {
		ret = PTR_ERR(prog);
		goto put_map;
	}

	if (prog->type != ptype) {
		ret = -EINVAL;
		goto put_prog;
	}

	ret = sock_map_prog_update(map, NULL, prog, attr->attach_type);
put_prog:
	bpf_prog_put(prog);
put_map:
	fdput(f);
	return ret;
}

static void sock_map_sk_acquire(struct sock *sk)
	__acquires(&sk->sk_lock.slock)
{
	lock_sock(sk);
	preempt_disable();
	rcu_read_lock();
}

static void sock_map_sk_release(struct sock *sk)
	__releases(&sk->sk_lock.slock)
{
	rcu_read_unlock();
	preempt_enable();
	release_sock(sk);
}

static void sock_map_add_link(struct sk_psock *psock,
			      struct sk_psock_link *link,
			      struct bpf_map *map, void *link_raw)
{
	link->link_raw = link_raw;
	link->map = map;
	spin_lock_bh(&psock->link_lock);
	list_add_tail(&link->list, &psock->link);
	spin_unlock_bh(&psock->link_lock);
}

static void sock_map_del_link(struct sock *sk,
			      struct sk_psock *psock, void *link_raw)
{
	bool strp_stop = false, verdict_stop = false;
	struct sk_psock_link *link, *tmp;

	spin_lock_bh(&psock->link_lock);
	list_for_each_entry_safe(link, tmp, &psock->link, list) {
		if (link->link_raw == link_raw) {
			struct bpf_map *map = link->map;
			struct bpf_stab *stab = container_of(map, struct bpf_stab,
							     map);
			if (psock->saved_data_ready && stab->progs.stream_parser)
				strp_stop = true;
			if (psock->saved_data_ready && stab->progs.stream_verdict)
				verdict_stop = true;
			if (psock->saved_data_ready && stab->progs.skb_verdict)
				verdict_stop = true;
			list_del(&link->list);
			sk_psock_free_link(link);
		}
	}
	spin_unlock_bh(&psock->link_lock);
	if (strp_stop || verdict_stop) {
		write_lock_bh(&sk->sk_callback_lock);
		if (strp_stop)
			sk_psock_stop_strp(sk, psock);
		else
			sk_psock_stop_verdict(sk, psock);
		write_unlock_bh(&sk->sk_callback_lock);
	}
}

static void sock_map_unref(struct sock *sk, void *link_raw)
{
	struct sk_psock *psock = sk_psock(sk);

	if (likely(psock)) {
		sock_map_del_link(sk, psock, link_raw);
		sk_psock_put(sk, psock);
	}
}

static int sock_map_init_proto(struct sock *sk, struct sk_psock *psock)
{
	if (!sk->sk_prot->psock_update_sk_prot)
		return -EINVAL;
	psock->psock_update_sk_prot = sk->sk_prot->psock_update_sk_prot;
	return sk->sk_prot->psock_update_sk_prot(sk, psock, false);
}

static struct sk_psock *sock_map_psock_get_checked(struct sock *sk)
{
	struct sk_psock *psock;

	rcu_read_lock();
	psock = sk_psock(sk);
	if (psock) {
		if (sk->sk_prot->close != sock_map_close) {
			psock = ERR_PTR(-EBUSY);
			goto out;
		}

		if (!refcount_inc_not_zero(&psock->refcnt))
			psock = ERR_PTR(-EBUSY);
	}
out:
	rcu_read_unlock();
	return psock;
}

static bool sock_map_redirect_allowed(const struct sock *sk);

static int sock_map_link(struct bpf_map *map, struct sock *sk)
{
	struct sk_psock_progs *progs = sock_map_progs(map);
	struct bpf_prog *stream_verdict = NULL;
	struct bpf_prog *stream_parser = NULL;
	struct bpf_prog *skb_verdict = NULL;
	struct bpf_prog *msg_parser = NULL;
	struct sk_psock *psock;
	int ret;

	/* Only sockets we can redirect into/from in BPF need to hold
	 * refs to parser/verdict progs and have their sk_data_ready
	 * and sk_write_space callbacks overridden.
	 */
	if (!sock_map_redirect_allowed(sk))
		goto no_progs;

	stream_verdict = READ_ONCE(progs->stream_verdict);
	if (stream_verdict) {
		stream_verdict = bpf_prog_inc_not_zero(stream_verdict);
		if (IS_ERR(stream_verdict))
			return PTR_ERR(stream_verdict);
	}

	stream_parser = READ_ONCE(progs->stream_parser);
	if (stream_parser) {
		stream_parser = bpf_prog_inc_not_zero(stream_parser);
		if (IS_ERR(stream_parser)) {
			ret = PTR_ERR(stream_parser);
			goto out_put_stream_verdict;
		}
	}

	msg_parser = READ_ONCE(progs->msg_parser);
	if (msg_parser) {
		msg_parser = bpf_prog_inc_not_zero(msg_parser);
		if (IS_ERR(msg_parser)) {
			ret = PTR_ERR(msg_parser);
			goto out_put_stream_parser;
		}
	}

	skb_verdict = READ_ONCE(progs->skb_verdict);
	if (skb_verdict) {
		skb_verdict = bpf_prog_inc_not_zero(skb_verdict);
		if (IS_ERR(skb_verdict)) {
			ret = PTR_ERR(skb_verdict);
			goto out_put_msg_parser;
		}
	}

no_progs:
	psock = sock_map_psock_get_checked(sk);
	if (IS_ERR(psock)) {
		ret = PTR_ERR(psock);
		goto out_progs;
	}

	if (psock) {
		if ((msg_parser && READ_ONCE(psock->progs.msg_parser)) ||
		    (stream_parser  && READ_ONCE(psock->progs.stream_parser)) ||
		    (skb_verdict && READ_ONCE(psock->progs.skb_verdict)) ||
		    (skb_verdict && READ_ONCE(psock->progs.stream_verdict)) ||
		    (stream_verdict && READ_ONCE(psock->progs.skb_verdict)) ||
		    (stream_verdict && READ_ONCE(psock->progs.stream_verdict))) {
			sk_psock_put(sk, psock);
			ret = -EBUSY;
			goto out_progs;
		}
	} else {
		psock = sk_psock_init(sk, map->numa_node);
		if (IS_ERR(psock)) {
			ret = PTR_ERR(psock);
			goto out_progs;
		}
	}

	if (msg_parser)
		psock_set_prog(&psock->progs.msg_parser, msg_parser);

	ret = sock_map_init_proto(sk, psock);
	if (ret < 0)
		goto out_drop;

	write_lock_bh(&sk->sk_callback_lock);
	if (stream_parser && stream_verdict && !psock->saved_data_ready) {
		ret = sk_psock_init_strp(sk, psock);
		if (ret)
			goto out_unlock_drop;
		psock_set_prog(&psock->progs.stream_verdict, stream_verdict);
		psock_set_prog(&psock->progs.stream_parser, stream_parser);
		sk_psock_start_strp(sk, psock);
	} else if (!stream_parser && stream_verdict && !psock->saved_data_ready) {
		psock_set_prog(&psock->progs.stream_verdict, stream_verdict);
		sk_psock_start_verdict(sk,psock);
	} else if (!stream_verdict && skb_verdict && !psock->saved_data_ready) {
		psock_set_prog(&psock->progs.skb_verdict, skb_verdict);
		sk_psock_start_verdict(sk, psock);
	}
	write_unlock_bh(&sk->sk_callback_lock);
	return 0;
out_unlock_drop:
	write_unlock_bh(&sk->sk_callback_lock);
out_drop:
	sk_psock_put(sk, psock);
out_progs:
	if (skb_verdict)
		bpf_prog_put(skb_verdict);
out_put_msg_parser:
	if (msg_parser)
		bpf_prog_put(msg_parser);
out_put_stream_parser:
	if (stream_parser)
		bpf_prog_put(stream_parser);
out_put_stream_verdict:
	if (stream_verdict)
		bpf_prog_put(stream_verdict);
	return ret;
}

static void sock_map_free(struct bpf_map *map)
{
	struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
	int i;

	/* After the sync no updates or deletes will be in-flight so it
	 * is safe to walk map and remove entries without risking a race
	 * in EEXIST update case.
	 */
	synchronize_rcu();
	for (i = 0; i < stab->map.max_entries; i++) {
		struct sock **psk = &stab->sks[i];
		struct sock *sk;

		sk = xchg(psk, NULL);
		if (sk) {
			lock_sock(sk);
			rcu_read_lock();
			sock_map_unref(sk, psk);
			rcu_read_unlock();
			release_sock(sk);
		}
	}

	/* wait for psock readers accessing its map link */
	synchronize_rcu();

	bpf_map_area_free(stab->sks);
	kfree(stab);
}

static void sock_map_release_progs(struct bpf_map *map)
{
	psock_progs_drop(&container_of(map, struct bpf_stab, map)->progs);
}

static struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
{
	struct bpf_stab *stab = container_of(map, struct bpf_stab, map);

	WARN_ON_ONCE(!rcu_read_lock_held());

	if (unlikely(key >= map->max_entries))
		return NULL;
	return READ_ONCE(stab->sks[key]);
}

static void *sock_map_lookup(struct bpf_map *map, void *key)
{
	struct sock *sk;

	sk = __sock_map_lookup_elem(map, *(u32 *)key);
	if (!sk)
		return NULL;
	if (sk_is_refcounted(sk) && !refcount_inc_not_zero(&sk->sk_refcnt))
		return NULL;
	return sk;
}

static void *sock_map_lookup_sys(struct bpf_map *map, void *key)
{
	struct sock *sk;

	if (map->value_size != sizeof(u64))
		return ERR_PTR(-ENOSPC);

	sk = __sock_map_lookup_elem(map, *(u32 *)key);
	if (!sk)
		return ERR_PTR(-ENOENT);

	__sock_gen_cookie(sk);
	return &sk->sk_cookie;
}

static int __sock_map_delete(struct bpf_stab *stab, struct sock *sk_test,
			     struct sock **psk)
{
	struct sock *sk;
	int err = 0;

	raw_spin_lock_bh(&stab->lock);
	sk = *psk;
	if (!sk_test || sk_test == sk)
		sk = xchg(psk, NULL);

	if (likely(sk))
		sock_map_unref(sk, psk);
	else
		err = -EINVAL;

	raw_spin_unlock_bh(&stab->lock);
	return err;
}

static void sock_map_delete_from_link(struct bpf_map *map, struct sock *sk,
				      void *link_raw)
{
	struct bpf_stab *stab = container_of(map, struct bpf_stab, map);

	__sock_map_delete(stab, sk, link_raw);
}

static int sock_map_delete_elem(struct bpf_map *map, void *key)
{
	struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
	u32 i = *(u32 *)key;
	struct sock **psk;

	if (unlikely(i >= map->max_entries))
		return -EINVAL;

	psk = &stab->sks[i];
	return __sock_map_delete(stab, NULL, psk);
}

static int sock_map_get_next_key(struct bpf_map *map, void *key, void *next)
{
	struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
	u32 i = key ? *(u32 *)key : U32_MAX;
	u32 *key_next = next;

	if (i == stab->map.max_entries - 1)
		return -ENOENT;
	if (i >= stab->map.max_entries)
		*key_next = 0;
	else
		*key_next = i + 1;
	return 0;
}

static int sock_map_update_common(struct bpf_map *map, u32 idx,
				  struct sock *sk, u64 flags)
{
	struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
	struct sk_psock_link *link;
	struct sk_psock *psock;
	struct sock *osk;
	int ret;

	WARN_ON_ONCE(!rcu_read_lock_held());
	if (unlikely(flags > BPF_EXIST))
		return -EINVAL;
	if (unlikely(idx >= map->max_entries))
		return -E2BIG;

	link = sk_psock_init_link();
	if (!link)
		return -ENOMEM;

	ret = sock_map_link(map, sk);
	if (ret < 0)
		goto out_free;

	psock = sk_psock(sk);
	WARN_ON_ONCE(!psock);

	raw_spin_lock_bh(&stab->lock);
	osk = stab->sks[idx];
	if (osk && flags == BPF_NOEXIST) {
		ret = -EEXIST;
		goto out_unlock;
	} else if (!osk && flags == BPF_EXIST) {
		ret = -ENOENT;
		goto out_unlock;
	}

	sock_map_add_link(psock, link, map, &stab->sks[idx]);
	stab->sks[idx] = sk;
	if (osk)
		sock_map_unref(osk, &stab->sks[idx]);
	raw_spin_unlock_bh(&stab->lock);
	return 0;
out_unlock:
	raw_spin_unlock_bh(&stab->lock);
	if (psock)
		sk_psock_put(sk, psock);
out_free:
	sk_psock_free_link(link);
	return ret;
}

static bool sock_map_op_okay(const struct bpf_sock_ops_kern *ops)
{
	return ops->op == BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB ||
	       ops->op == BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB ||
	       ops->op == BPF_SOCK_OPS_TCP_LISTEN_CB;
}

static bool sk_is_tcp(const struct sock *sk)
{
	return sk->sk_type == SOCK_STREAM &&
	       sk->sk_protocol == IPPROTO_TCP;
}

static bool sk_is_udp(const struct sock *sk)
{
	return sk->sk_type == SOCK_DGRAM &&
	       sk->sk_protocol == IPPROTO_UDP;
}

static bool sock_map_redirect_allowed(const struct sock *sk)
{
	if (sk_is_tcp(sk))
		return sk->sk_state != TCP_LISTEN;
	else
		return sk->sk_state == TCP_ESTABLISHED;
}

static bool sock_map_sk_is_suitable(const struct sock *sk)
{
	return !!sk->sk_prot->psock_update_sk_prot;
}

static bool sock_map_sk_state_allowed(const struct sock *sk)
{
	if (sk_is_tcp(sk))
		return (1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_LISTEN);
	else if (sk_is_udp(sk))
		return sk_hashed(sk);

	return false;
}

static int sock_hash_update_common(struct bpf_map *map, void *key,
				   struct sock *sk, u64 flags);

int sock_map_update_elem_sys(struct bpf_map *map, void *key, void *value,
			     u64 flags)
{
	struct socket *sock;
	struct sock *sk;
	int ret;
	u64 ufd;

	if (map->value_size == sizeof(u64))
		ufd = *(u64 *)value;
	else
		ufd = *(u32 *)value;
	if (ufd > S32_MAX)
		return -EINVAL;

	sock = sockfd_lookup(ufd, &ret);
	if (!sock)
		return ret;
	sk = sock->sk;
	if (!sk) {
		ret = -EINVAL;
		goto out;
	}
	if (!sock_map_sk_is_suitable(sk)) {
		ret = -EOPNOTSUPP;
		goto out;
	}

	sock_map_sk_acquire(sk);
	if (!sock_map_sk_state_allowed(sk))
		ret = -EOPNOTSUPP;
	else if (map->map_type == BPF_MAP_TYPE_SOCKMAP)
		ret = sock_map_update_common(map, *(u32 *)key, sk, flags);
	else
		ret = sock_hash_update_common(map, key, sk, flags);
	sock_map_sk_release(sk);
out:
	sockfd_put(sock);
	return ret;
}

static int sock_map_update_elem(struct bpf_map *map, void *key,
				void *value, u64 flags)
{
	struct sock *sk = (struct sock *)value;
	int ret;

	if (unlikely(!sk || !sk_fullsock(sk)))
		return -EINVAL;

	if (!sock_map_sk_is_suitable(sk))
		return -EOPNOTSUPP;

	local_bh_disable();
	bh_lock_sock(sk);
	if (!sock_map_sk_state_allowed(sk))
		ret = -EOPNOTSUPP;
	else if (map->map_type == BPF_MAP_TYPE_SOCKMAP)
		ret = sock_map_update_common(map, *(u32 *)key, sk, flags);
	else
		ret = sock_hash_update_common(map, key, sk, flags);
	bh_unlock_sock(sk);
	local_bh_enable();
	return ret;
}

BPF_CALL_4(bpf_sock_map_update, struct bpf_sock_ops_kern *, sops,
	   struct bpf_map *, map, void *, key, u64, flags)
{
	WARN_ON_ONCE(!rcu_read_lock_held());

	if (likely(sock_map_sk_is_suitable(sops->sk) &&
		   sock_map_op_okay(sops)))
		return sock_map_update_common(map, *(u32 *)key, sops->sk,
					      flags);
	return -EOPNOTSUPP;
}

const struct bpf_func_proto bpf_sock_map_update_proto = {
	.func		= bpf_sock_map_update,
	.gpl_only	= false,
	.pkt_access	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_PTR_TO_MAP_KEY,
	.arg4_type	= ARG_ANYTHING,
};

BPF_CALL_4(bpf_sk_redirect_map, struct sk_buff *, skb,
	   struct bpf_map *, map, u32, key, u64, flags)
{
	struct sock *sk;

	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return SK_DROP;

	sk = __sock_map_lookup_elem(map, key);
	if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
		return SK_DROP;

	skb_bpf_set_redir(skb, sk, flags & BPF_F_INGRESS);
	return SK_PASS;
}

const struct bpf_func_proto bpf_sk_redirect_map_proto = {
	.func           = bpf_sk_redirect_map,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_CONST_MAP_PTR,
	.arg3_type      = ARG_ANYTHING,
	.arg4_type      = ARG_ANYTHING,
};

BPF_CALL_4(bpf_msg_redirect_map, struct sk_msg *, msg,
	   struct bpf_map *, map, u32, key, u64, flags)
{
	struct sock *sk;

	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return SK_DROP;

	sk = __sock_map_lookup_elem(map, key);
	if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
		return SK_DROP;

	msg->flags = flags;
	msg->sk_redir = sk;
	return SK_PASS;
}

const struct bpf_func_proto bpf_msg_redirect_map_proto = {
	.func           = bpf_msg_redirect_map,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_CONST_MAP_PTR,
	.arg3_type      = ARG_ANYTHING,
	.arg4_type      = ARG_ANYTHING,
};

struct sock_map_seq_info {
	struct bpf_map *map;
	struct sock *sk;
	u32 index;
};

struct bpf_iter__sockmap {
	__bpf_md_ptr(struct bpf_iter_meta *, meta);
	__bpf_md_ptr(struct bpf_map *, map);
	__bpf_md_ptr(void *, key);
	__bpf_md_ptr(struct sock *, sk);
};

DEFINE_BPF_ITER_FUNC(sockmap, struct bpf_iter_meta *meta,
		     struct bpf_map *map, void *key,
		     struct sock *sk)

static void *sock_map_seq_lookup_elem(struct sock_map_seq_info *info)
{
	if (unlikely(info->index >= info->map->max_entries))
		return NULL;

	info->sk = __sock_map_lookup_elem(info->map, info->index);

	/* can't return sk directly, since that might be NULL */
	return info;
}

static void *sock_map_seq_start(struct seq_file *seq, loff_t *pos)
	__acquires(rcu)
{
	struct sock_map_seq_info *info = seq->private;

	if (*pos == 0)
		++*pos;

	/* pairs with sock_map_seq_stop */
	rcu_read_lock();
	return sock_map_seq_lookup_elem(info);
}

static void *sock_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
	__must_hold(rcu)
{
	struct sock_map_seq_info *info = seq->private;

	++*pos;
	++info->index;

	return sock_map_seq_lookup_elem(info);
}

static int sock_map_seq_show(struct seq_file *seq, void *v)
	__must_hold(rcu)
{
	struct sock_map_seq_info *info = seq->private;
	struct bpf_iter__sockmap ctx = {};
	struct bpf_iter_meta meta;
	struct bpf_prog *prog;

	meta.seq = seq;
	prog = bpf_iter_get_info(&meta, !v);
	if (!prog)
		return 0;

	ctx.meta = &meta;
	ctx.map = info->map;
	if (v) {
		ctx.key = &info->index;
		ctx.sk = info->sk;
	}

	return bpf_iter_run_prog(prog, &ctx);
}

static void sock_map_seq_stop(struct seq_file *seq, void *v)
	__releases(rcu)
{
	if (!v)
		(void)sock_map_seq_show(seq, NULL);

	/* pairs with sock_map_seq_start */
	rcu_read_unlock();
}

static const struct seq_operations sock_map_seq_ops = {
	.start	= sock_map_seq_start,
	.next	= sock_map_seq_next,
	.stop	= sock_map_seq_stop,
	.show	= sock_map_seq_show,
};

static int sock_map_init_seq_private(void *priv_data,
				     struct bpf_iter_aux_info *aux)
{
	struct sock_map_seq_info *info = priv_data;

	info->map = aux->map;
	return 0;
}

static const struct bpf_iter_seq_info sock_map_iter_seq_info = {
	.seq_ops		= &sock_map_seq_ops,
	.init_seq_private	= sock_map_init_seq_private,
	.seq_priv_size		= sizeof(struct sock_map_seq_info),
};

static int sock_map_btf_id;
const struct bpf_map_ops sock_map_ops = {
	.map_meta_equal		= bpf_map_meta_equal,
	.map_alloc		= sock_map_alloc,
	.map_free		= sock_map_free,
	.map_get_next_key	= sock_map_get_next_key,
	.map_lookup_elem_sys_only = sock_map_lookup_sys,
	.map_update_elem	= sock_map_update_elem,
	.map_delete_elem	= sock_map_delete_elem,
	.map_lookup_elem	= sock_map_lookup,
	.map_release_uref	= sock_map_release_progs,
	.map_check_btf		= map_check_no_btf,
	.map_btf_name		= "bpf_stab",
	.map_btf_id		= &sock_map_btf_id,
	.iter_seq_info		= &sock_map_iter_seq_info,
};

struct bpf_shtab_elem {
	struct rcu_head rcu;
	u32 hash;
	struct sock *sk;
	struct hlist_node node;
	u8 key[];
};

struct bpf_shtab_bucket {
	struct hlist_head head;
	raw_spinlock_t lock;
};

struct bpf_shtab {
	struct bpf_map map;
	struct bpf_shtab_bucket *buckets;
	u32 buckets_num;
	u32 elem_size;
	struct sk_psock_progs progs;
	atomic_t count;
};

static inline u32 sock_hash_bucket_hash(const void *key, u32 len)
{
	return jhash(key, len, 0);
}

static struct bpf_shtab_bucket *sock_hash_select_bucket(struct bpf_shtab *htab,
							u32 hash)
{
	return &htab->buckets[hash & (htab->buckets_num - 1)];
}

static struct bpf_shtab_elem *
sock_hash_lookup_elem_raw(struct hlist_head *head, u32 hash, void *key,
			  u32 key_size)
{
	struct bpf_shtab_elem *elem;

	hlist_for_each_entry_rcu(elem, head, node) {
		if (elem->hash == hash &&
		    !memcmp(&elem->key, key, key_size))
			return elem;
	}

	return NULL;
}

static struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
{
	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
	u32 key_size = map->key_size, hash;
	struct bpf_shtab_bucket *bucket;
	struct bpf_shtab_elem *elem;

	WARN_ON_ONCE(!rcu_read_lock_held());

	hash = sock_hash_bucket_hash(key, key_size);
	bucket = sock_hash_select_bucket(htab, hash);
	elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);

	return elem ? elem->sk : NULL;
}

static void sock_hash_free_elem(struct bpf_shtab *htab,
				struct bpf_shtab_elem *elem)
{
	atomic_dec(&htab->count);
	kfree_rcu(elem, rcu);
}

static void sock_hash_delete_from_link(struct bpf_map *map, struct sock *sk,
				       void *link_raw)
{
	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
	struct bpf_shtab_elem *elem_probe, *elem = link_raw;
	struct bpf_shtab_bucket *bucket;

	WARN_ON_ONCE(!rcu_read_lock_held());
	bucket = sock_hash_select_bucket(htab, elem->hash);

	/* elem may be deleted in parallel from the map, but access here
	 * is okay since it's going away only after RCU grace period.
	 * However, we need to check whether it's still present.
	 */
	raw_spin_lock_bh(&bucket->lock);
	elem_probe = sock_hash_lookup_elem_raw(&bucket->head, elem->hash,
					       elem->key, map->key_size);
	if (elem_probe && elem_probe == elem) {
		hlist_del_rcu(&elem->node);
		sock_map_unref(elem->sk, elem);
		sock_hash_free_elem(htab, elem);
	}
	raw_spin_unlock_bh(&bucket->lock);
}

static int sock_hash_delete_elem(struct bpf_map *map, void *key)
{
	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
	u32 hash, key_size = map->key_size;
	struct bpf_shtab_bucket *bucket;
	struct bpf_shtab_elem *elem;
	int ret = -ENOENT;

	hash = sock_hash_bucket_hash(key, key_size);
	bucket = sock_hash_select_bucket(htab, hash);

	raw_spin_lock_bh(&bucket->lock);
	elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
	if (elem) {
		hlist_del_rcu(&elem->node);
		sock_map_unref(elem->sk, elem);
		sock_hash_free_elem(htab, elem);
		ret = 0;
	}
	raw_spin_unlock_bh(&bucket->lock);
	return ret;
}

static struct bpf_shtab_elem *sock_hash_alloc_elem(struct bpf_shtab *htab,
						   void *key, u32 key_size,
						   u32 hash, struct sock *sk,
						   struct bpf_shtab_elem *old)
{
	struct bpf_shtab_elem *new;

	if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
		if (!old) {
			atomic_dec(&htab->count);
			return ERR_PTR(-E2BIG);
		}
	}

	new = bpf_map_kmalloc_node(&htab->map, htab->elem_size,
				   GFP_ATOMIC | __GFP_NOWARN,
				   htab->map.numa_node);
	if (!new) {
		atomic_dec(&htab->count);
		return ERR_PTR(-ENOMEM);
	}
	memcpy(new->key, key, key_size);
	new->sk = sk;
	new->hash = hash;
	return new;
}

static int sock_hash_update_common(struct bpf_map *map, void *key,
				   struct sock *sk, u64 flags)
{
	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
	u32 key_size = map->key_size, hash;
	struct bpf_shtab_elem *elem, *elem_new;
	struct bpf_shtab_bucket *bucket;
	struct sk_psock_link *link;
	struct sk_psock *psock;
	int ret;

	WARN_ON_ONCE(!rcu_read_lock_held());
	if (unlikely(flags > BPF_EXIST))
		return -EINVAL;

	link = sk_psock_init_link();
	if (!link)
		return -ENOMEM;

	ret = sock_map_link(map, sk);
	if (ret < 0)
		goto out_free;

	psock = sk_psock(sk);
	WARN_ON_ONCE(!psock);

	hash = sock_hash_bucket_hash(key, key_size);
	bucket = sock_hash_select_bucket(htab, hash);

	raw_spin_lock_bh(&bucket->lock);
	elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
	if (elem && flags == BPF_NOEXIST) {
		ret = -EEXIST;
		goto out_unlock;
	} else if (!elem && flags == BPF_EXIST) {
		ret = -ENOENT;
		goto out_unlock;
	}

	elem_new = sock_hash_alloc_elem(htab, key, key_size, hash, sk, elem);
	if (IS_ERR(elem_new)) {
		ret = PTR_ERR(elem_new);
		goto out_unlock;
	}

	sock_map_add_link(psock, link, map, elem_new);
	/* Add new element to the head of the list, so that
	 * concurrent search will find it before old elem.
	 */
	hlist_add_head_rcu(&elem_new->node, &bucket->head);
	if (elem) {
		hlist_del_rcu(&elem->node);
		sock_map_unref(elem->sk, elem);
		sock_hash_free_elem(htab, elem);
	}
	raw_spin_unlock_bh(&bucket->lock);
	return 0;
out_unlock:
	raw_spin_unlock_bh(&bucket->lock);
	sk_psock_put(sk, psock);
out_free:
	sk_psock_free_link(link);
	return ret;
}

static int sock_hash_get_next_key(struct bpf_map *map, void *key,
				  void *key_next)
{
	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
	struct bpf_shtab_elem *elem, *elem_next;
	u32 hash, key_size = map->key_size;
	struct hlist_head *head;
	int i = 0;

	if (!key)
		goto find_first_elem;
	hash = sock_hash_bucket_hash(key, key_size);
	head = &sock_hash_select_bucket(htab, hash)->head;
	elem = sock_hash_lookup_elem_raw(head, hash, key, key_size);
	if (!elem)
		goto find_first_elem;

	elem_next = hlist_entry_safe(rcu_dereference(hlist_next_rcu(&elem->node)),
				     struct bpf_shtab_elem, node);
	if (elem_next) {
		memcpy(key_next, elem_next->key, key_size);
		return 0;
	}

	i = hash & (htab->buckets_num - 1);
	i++;
find_first_elem:
	for (; i < htab->buckets_num; i++) {
		head = &sock_hash_select_bucket(htab, i)->head;
		elem_next = hlist_entry_safe(rcu_dereference(hlist_first_rcu(head)),
					     struct bpf_shtab_elem, node);
		if (elem_next) {
			memcpy(key_next, elem_next->key, key_size);
			return 0;
		}
	}

	return -ENOENT;
}

static struct bpf_map *sock_hash_alloc(union bpf_attr *attr)
{
	struct bpf_shtab *htab;
	int i, err;

	if (!capable(CAP_NET_ADMIN))
		return ERR_PTR(-EPERM);
	if (attr->max_entries == 0 ||
	    attr->key_size    == 0 ||
	    (attr->value_size != sizeof(u32) &&
	     attr->value_size != sizeof(u64)) ||
	    attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
		return ERR_PTR(-EINVAL);
	if (attr->key_size > MAX_BPF_STACK)
		return ERR_PTR(-E2BIG);

	htab = kzalloc(sizeof(*htab), GFP_USER | __GFP_ACCOUNT);
	if (!htab)
		return ERR_PTR(-ENOMEM);

	bpf_map_init_from_attr(&htab->map, attr);

	htab->buckets_num = roundup_pow_of_two(htab->map.max_entries);
	htab->elem_size = sizeof(struct bpf_shtab_elem) +
			  round_up(htab->map.key_size, 8);
	if (htab->buckets_num == 0 ||
	    htab->buckets_num > U32_MAX / sizeof(struct bpf_shtab_bucket)) {
		err = -EINVAL;
		goto free_htab;
	}

	htab->buckets = bpf_map_area_alloc(htab->buckets_num *
					   sizeof(struct bpf_shtab_bucket),
					   htab->map.numa_node);
	if (!htab->buckets) {
		err = -ENOMEM;
		goto free_htab;
	}

	for (i = 0; i < htab->buckets_num; i++) {
		INIT_HLIST_HEAD(&htab->buckets[i].head);
		raw_spin_lock_init(&htab->buckets[i].lock);
	}

	return &htab->map;
free_htab:
	kfree(htab);
	return ERR_PTR(err);
}

static void sock_hash_free(struct bpf_map *map)
{
	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
	struct bpf_shtab_bucket *bucket;
	struct hlist_head unlink_list;
	struct bpf_shtab_elem *elem;
	struct hlist_node *node;
	int i;

	/* After the sync no updates or deletes will be in-flight so it
	 * is safe to walk map and remove entries without risking a race
	 * in EEXIST update case.
	 */
	synchronize_rcu();
	for (i = 0; i < htab->buckets_num; i++) {
		bucket = sock_hash_select_bucket(htab, i);

		/* We are racing with sock_hash_delete_from_link to
		 * enter the spin-lock critical section. Every socket on
		 * the list is still linked to sockhash. Since link
		 * exists, psock exists and holds a ref to socket. That
		 * lets us to grab a socket ref too.
		 */
		raw_spin_lock_bh(&bucket->lock);
		hlist_for_each_entry(elem, &bucket->head, node)
			sock_hold(elem->sk);
		hlist_move_list(&bucket->head, &unlink_list);
		raw_spin_unlock_bh(&bucket->lock);

		/* Process removed entries out of atomic context to
		 * block for socket lock before deleting the psock's
		 * link to sockhash.
		 */
		hlist_for_each_entry_safe(elem, node, &unlink_list, node) {
			hlist_del(&elem->node);
			lock_sock(elem->sk);
			rcu_read_lock();
			sock_map_unref(elem->sk, elem);
			rcu_read_unlock();
			release_sock(elem->sk);
			sock_put(elem->sk);
			sock_hash_free_elem(htab, elem);
		}
	}

	/* wait for psock readers accessing its map link */
	synchronize_rcu();

	bpf_map_area_free(htab->buckets);
	kfree(htab);
}

static void *sock_hash_lookup_sys(struct bpf_map *map, void *key)
{
	struct sock *sk;

	if (map->value_size != sizeof(u64))
		return ERR_PTR(-ENOSPC);

	sk = __sock_hash_lookup_elem(map, key);
	if (!sk)
		return ERR_PTR(-ENOENT);

	__sock_gen_cookie(sk);
	return &sk->sk_cookie;
}

static void *sock_hash_lookup(struct bpf_map *map, void *key)
{
	struct sock *sk;

	sk = __sock_hash_lookup_elem(map, key);
	if (!sk)
		return NULL;
	if (sk_is_refcounted(sk) && !refcount_inc_not_zero(&sk->sk_refcnt))
		return NULL;
	return sk;
}

static void sock_hash_release_progs(struct bpf_map *map)
{
	psock_progs_drop(&container_of(map, struct bpf_shtab, map)->progs);
}

BPF_CALL_4(bpf_sock_hash_update, struct bpf_sock_ops_kern *, sops,
	   struct bpf_map *, map, void *, key, u64, flags)
{
	WARN_ON_ONCE(!rcu_read_lock_held());

	if (likely(sock_map_sk_is_suitable(sops->sk) &&
		   sock_map_op_okay(sops)))
		return sock_hash_update_common(map, key, sops->sk, flags);
	return -EOPNOTSUPP;
}

const struct bpf_func_proto bpf_sock_hash_update_proto = {
	.func		= bpf_sock_hash_update,
	.gpl_only	= false,
	.pkt_access	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_PTR_TO_MAP_KEY,
	.arg4_type	= ARG_ANYTHING,
};

BPF_CALL_4(bpf_sk_redirect_hash, struct sk_buff *, skb,
	   struct bpf_map *, map, void *, key, u64, flags)
{
	struct sock *sk;

	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return SK_DROP;

	sk = __sock_hash_lookup_elem(map, key);
	if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
		return SK_DROP;

	skb_bpf_set_redir(skb, sk, flags & BPF_F_INGRESS);
	return SK_PASS;
}

const struct bpf_func_proto bpf_sk_redirect_hash_proto = {
	.func           = bpf_sk_redirect_hash,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_CONST_MAP_PTR,
	.arg3_type      = ARG_PTR_TO_MAP_KEY,
	.arg4_type      = ARG_ANYTHING,
};

BPF_CALL_4(bpf_msg_redirect_hash, struct sk_msg *, msg,
	   struct bpf_map *, map, void *, key, u64, flags)
{
	struct sock *sk;

	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return SK_DROP;

	sk = __sock_hash_lookup_elem(map, key);
	if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
		return SK_DROP;

	msg->flags = flags;
	msg->sk_redir = sk;
	return SK_PASS;
}

const struct bpf_func_proto bpf_msg_redirect_hash_proto = {
	.func           = bpf_msg_redirect_hash,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_CONST_MAP_PTR,
	.arg3_type      = ARG_PTR_TO_MAP_KEY,
	.arg4_type      = ARG_ANYTHING,
};

struct sock_hash_seq_info {
	struct bpf_map *map;
	struct bpf_shtab *htab;
	u32 bucket_id;
};

static void *sock_hash_seq_find_next(struct sock_hash_seq_info *info,
				     struct bpf_shtab_elem *prev_elem)
{
	const struct bpf_shtab *htab = info->htab;
	struct bpf_shtab_bucket *bucket;
	struct bpf_shtab_elem *elem;
	struct hlist_node *node;

	/* try to find next elem in the same bucket */
	if (prev_elem) {
		node = rcu_dereference(hlist_next_rcu(&prev_elem->node));
		elem = hlist_entry_safe(node, struct bpf_shtab_elem, node);
		if (elem)
			return elem;

		/* no more elements, continue in the next bucket */
		info->bucket_id++;
	}

	for (; info->bucket_id < htab->buckets_num; info->bucket_id++) {
		bucket = &htab->buckets[info->bucket_id];
		node = rcu_dereference(hlist_first_rcu(&bucket->head));
		elem = hlist_entry_safe(node, struct bpf_shtab_elem, node);
		if (elem)
			return elem;
	}

	return NULL;
}

static void *sock_hash_seq_start(struct seq_file *seq, loff_t *pos)
	__acquires(rcu)
{
	struct sock_hash_seq_info *info = seq->private;

	if (*pos == 0)
		++*pos;

	/* pairs with sock_hash_seq_stop */
	rcu_read_lock();
	return sock_hash_seq_find_next(info, NULL);
}

static void *sock_hash_seq_next(struct seq_file *seq, void *v, loff_t *pos)
	__must_hold(rcu)
{
	struct sock_hash_seq_info *info = seq->private;

	++*pos;
	return sock_hash_seq_find_next(info, v);
}

static int sock_hash_seq_show(struct seq_file *seq, void *v)
	__must_hold(rcu)
{
	struct sock_hash_seq_info *info = seq->private;
	struct bpf_iter__sockmap ctx = {};
	struct bpf_shtab_elem *elem = v;
	struct bpf_iter_meta meta;
	struct bpf_prog *prog;

	meta.seq = seq;
	prog = bpf_iter_get_info(&meta, !elem);
	if (!prog)
		return 0;

	ctx.meta = &meta;
	ctx.map = info->map;
	if (elem) {
		ctx.key = elem->key;
		ctx.sk = elem->sk;
	}

	return bpf_iter_run_prog(prog, &ctx);
}

static void sock_hash_seq_stop(struct seq_file *seq, void *v)
	__releases(rcu)
{
	if (!v)
		(void)sock_hash_seq_show(seq, NULL);

	/* pairs with sock_hash_seq_start */
	rcu_read_unlock();
}

static const struct seq_operations sock_hash_seq_ops = {
	.start	= sock_hash_seq_start,
	.next	= sock_hash_seq_next,
	.stop	= sock_hash_seq_stop,
	.show	= sock_hash_seq_show,
};

static int sock_hash_init_seq_private(void *priv_data,
				     struct bpf_iter_aux_info *aux)
{
	struct sock_hash_seq_info *info = priv_data;

	info->map = aux->map;
	info->htab = container_of(aux->map, struct bpf_shtab, map);
	return 0;
}

static const struct bpf_iter_seq_info sock_hash_iter_seq_info = {
	.seq_ops		= &sock_hash_seq_ops,
	.init_seq_private	= sock_hash_init_seq_private,
	.seq_priv_size		= sizeof(struct sock_hash_seq_info),
};

static int sock_hash_map_btf_id;
const struct bpf_map_ops sock_hash_ops = {
	.map_meta_equal		= bpf_map_meta_equal,
	.map_alloc		= sock_hash_alloc,
	.map_free		= sock_hash_free,
	.map_get_next_key	= sock_hash_get_next_key,
	.map_update_elem	= sock_map_update_elem,
	.map_delete_elem	= sock_hash_delete_elem,
	.map_lookup_elem	= sock_hash_lookup,
	.map_lookup_elem_sys_only = sock_hash_lookup_sys,
	.map_release_uref	= sock_hash_release_progs,
	.map_check_btf		= map_check_no_btf,
	.map_btf_name		= "bpf_shtab",
	.map_btf_id		= &sock_hash_map_btf_id,
	.iter_seq_info		= &sock_hash_iter_seq_info,
};

static struct sk_psock_progs *sock_map_progs(struct bpf_map *map)
{
	switch (map->map_type) {
	case BPF_MAP_TYPE_SOCKMAP:
		return &container_of(map, struct bpf_stab, map)->progs;
	case BPF_MAP_TYPE_SOCKHASH:
		return &container_of(map, struct bpf_shtab, map)->progs;
	default:
		break;
	}

	return NULL;
}

static int sock_map_prog_update(struct bpf_map *map, struct bpf_prog *prog,
				struct bpf_prog *old, u32 which)
{
	struct sk_psock_progs *progs = sock_map_progs(map);
	struct bpf_prog **pprog;

	if (!progs)
		return -EOPNOTSUPP;

	switch (which) {
	case BPF_SK_MSG_VERDICT:
		pprog = &progs->msg_parser;
		break;
#if IS_ENABLED(CONFIG_BPF_STREAM_PARSER)
	case BPF_SK_SKB_STREAM_PARSER:
		pprog = &progs->stream_parser;
		break;
#endif
	case BPF_SK_SKB_STREAM_VERDICT:
		if (progs->skb_verdict)
			return -EBUSY;
		pprog = &progs->stream_verdict;
		break;
	case BPF_SK_SKB_VERDICT:
		if (progs->stream_verdict)
			return -EBUSY;
		pprog = &progs->skb_verdict;
		break;
	default:
		return -EOPNOTSUPP;
	}

	if (old)
		return psock_replace_prog(pprog, prog, old);

	psock_set_prog(pprog, prog);
	return 0;
}

static void sock_map_unlink(struct sock *sk, struct sk_psock_link *link)
{
	switch (link->map->map_type) {
	case BPF_MAP_TYPE_SOCKMAP:
		return sock_map_delete_from_link(link->map, sk,
						 link->link_raw);
	case BPF_MAP_TYPE_SOCKHASH:
		return sock_hash_delete_from_link(link->map, sk,
						  link->link_raw);
	default:
		break;
	}
}

static void sock_map_remove_links(struct sock *sk, struct sk_psock *psock)
{
	struct sk_psock_link *link;

	while ((link = sk_psock_link_pop(psock))) {
		sock_map_unlink(sk, link);
		sk_psock_free_link(link);
	}
}

void sock_map_unhash(struct sock *sk)
{
	void (*saved_unhash)(struct sock *sk);
	struct sk_psock *psock;

	rcu_read_lock();
	psock = sk_psock(sk);
	if (unlikely(!psock)) {
		rcu_read_unlock();
		if (sk->sk_prot->unhash)
			sk->sk_prot->unhash(sk);
		return;
	}

	saved_unhash = psock->saved_unhash;
	sock_map_remove_links(sk, psock);
	rcu_read_unlock();
	saved_unhash(sk);
}

void sock_map_close(struct sock *sk, long timeout)
{
	void (*saved_close)(struct sock *sk, long timeout);
	struct sk_psock *psock;

	lock_sock(sk);
	rcu_read_lock();
	psock = sk_psock_get(sk);
	if (unlikely(!psock)) {
		rcu_read_unlock();
		release_sock(sk);
		return sk->sk_prot->close(sk, timeout);
	}

	saved_close = psock->saved_close;
	sock_map_remove_links(sk, psock);
	rcu_read_unlock();
	sk_psock_stop(psock, true);
	sk_psock_put(sk, psock);
	release_sock(sk);
	saved_close(sk, timeout);
}

static int sock_map_iter_attach_target(struct bpf_prog *prog,
				       union bpf_iter_link_info *linfo,
				       struct bpf_iter_aux_info *aux)
{
	struct bpf_map *map;
	int err = -EINVAL;

	if (!linfo->map.map_fd)
		return -EBADF;

	map = bpf_map_get_with_uref(linfo->map.map_fd);
	if (IS_ERR(map))
		return PTR_ERR(map);

	if (map->map_type != BPF_MAP_TYPE_SOCKMAP &&
	    map->map_type != BPF_MAP_TYPE_SOCKHASH)
		goto put_map;

	if (prog->aux->max_rdonly_access > map->key_size) {
		err = -EACCES;
		goto put_map;
	}

	aux->map = map;
	return 0;

put_map:
	bpf_map_put_with_uref(map);
	return err;
}

static void sock_map_iter_detach_target(struct bpf_iter_aux_info *aux)
{
	bpf_map_put_with_uref(aux->map);
}

static struct bpf_iter_reg sock_map_iter_reg = {
	.target			= "sockmap",
	.attach_target		= sock_map_iter_attach_target,
	.detach_target		= sock_map_iter_detach_target,
	.show_fdinfo		= bpf_iter_map_show_fdinfo,
	.fill_link_info		= bpf_iter_map_fill_link_info,
	.ctx_arg_info_size	= 2,
	.ctx_arg_info		= {
		{ offsetof(struct bpf_iter__sockmap, key),
		  PTR_TO_RDONLY_BUF_OR_NULL },
		{ offsetof(struct bpf_iter__sockmap, sk),
		  PTR_TO_BTF_ID_OR_NULL },
	},
};

static int __init bpf_sockmap_iter_init(void)
{
	sock_map_iter_reg.ctx_arg_info[1].btf_id =
		btf_sock_ids[BTF_SOCK_TYPE_SOCK];
	return bpf_iter_reg_target(&sock_map_iter_reg);
}
late_initcall(bpf_sockmap_iter_init);