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
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
// SPDX-License-Identifier: GPL-2.0
/*
 * Stream data over Thunderbolt/USB4 cable
 *
 * Copyright (C) 2026, Intel Corporation
 * Authors: Alan Borzeszkowski <alan.borzeszkowski@linux.intel.com>
 *	    Mika Westerberg <mika.westerberg@linux.intel.com>
 */

#define pr_fmt(fmt) "tbstream: " fmt

#include <linux/delay.h>
#include <linux/configfs.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/idr.h>
#include <linux/ktime.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/poll.h>
#include <linux/sizes.h>
#include <linux/thunderbolt.h>
#include <linux/uaccess.h>
#include <linux/uio.h>
#include <linux/uuid.h>
#include <linux/wait.h>

/*
 * USB4STREAM - Stream data directly over Thunderbolt/USB4 cable
 *
 * HopIDs are configured by the user. In Linux this is done through
 * ConfigFS. Once that is done paths are be established the first time
 * the stream is opened. Typically the read side is opened first to make
 * sure all the data will be received.
 *
 * End-to-end flow control is mandatory on both sides.
 *
 * Data is sent to the other side as tunneled DATA packets. All the data
 * is owned by the user and passed as-is from the writer to the reader.
 *
 * Once the stream device is closed, a CLOSE packet is sent to the peer
 * so it can take the necessary action. On Linux this typically results
 * in EOF being returned to the reader.
 *
 * Tunneled packet types:
 *
 * +-------+---------+------------------+
 * |  PDF  |  Type   | Payload size     |
 * +-------+---------+------------------+
 * |   2   | DATA    | up to 4 KiB      |
 * |   3   | CLOSE   | up to 256 bytes  |
 * +-------+---------+------------------+
 *
 * Each stream can optionally publish configuration values under its own
 * XDomain property directory. The name of the directory is the name of
 * the stream in question and the UUID is up to the stream. For example
 * if the stream exposes video output then the directory name could be
 * "video".
 *
 * Below values are reserved and can be used by the stream:
 *
 * +----------+-----------+-------------------------+
 * |   Key    |   Type    | Contents                |
 * +----------+-----------+-------------------------+
 * | inhopid  | IMMEDIATE | Configured input HopID  |
 * | outhopid | IMMEDIATE | Configured output HopID |
 * +----------+-----------+-------------------------+
 *
 * It is allowed to add more stream specific properties as well if the
 * above are not enough.
 */

#define TBSTREAM_DEV_RING_SIZE		256
#define TBSTREAM_DEV_MIN_RING_SIZE	32
#define TBSTREAM_DEV_MAX_RING_SIZE	4096
#define TBSTREAM_DEV_THROTTLING		8192
#define TBSTREAM_DEV_MAX_THROTTLING	16776960

/**
 * enum tbstream_frame_pdf - PDF numbers for tunneled frames
 * @TBSTREAM_FRAME_START: PDF of the start of the frame
 * @TBSTREAM_DATA: PDF of the DATA frame
 * @TBSTREAM_CLOSE: PDF of the CLOSE frame
 */
enum tbstream_frame_pdf {
	TBSTREAM_FRAME_START = 1,
	TBSTREAM_DATA,
	TBSTREAM_CLOSE,
};

/**
 * struct tbstream_frame - Frame submitted to/from the rings
 * @sdev: Pointer to the stream device
 * @page: Page holding the packet
 * @offset: Offset inside @page if partial read is done
 * @completed: %true if the RX frame is completed
 * @frame: Underlying frame structure
 */
struct tbstream_frame {
	struct tbstream_dev *sdev;
	struct page *page;
	unsigned int offset;
	bool completed;
	struct ring_frame frame;
};

/**
 * struct tbstream_ring - Stream RX/TX ring structure
 * @ring: Pointer to the API ring
 * @prod: Current value of producer
 * @cons: Current value of consumer
 * @frames: Holds the ring frames
 */
struct tbstream_ring {
	struct tb_ring *ring;
	unsigned long prod;
	unsigned long cons;
	struct tbstream_frame *frames;
};

/**
 * struct tbstream_dev - Stream character device
 * @group: ConfigFS group for this device
 * @stream: Pointer to the stream if it is attached (%NULL otherwise)
 * @misc: Character device used for tunneling
 * @kref: Reference count
 * @index: Unique identifier for the character device
 * @in_hopid: In HopID
 * @out_hopid: Out HopID
 * @ring_size: Size of the rings
 * @throttling: Interrupt throttling rate in ns
 * @busy_poll: Instead of interrupts, busy poll the rings
 * @users: Number of times @cdev has been opened
 * @closed: CLOSE packet was received
 * @removed: Userspace removed the ConfigFS group underneath.
 * @wait: Waitqueue for open, read and write
 * @lock: Lock protecting this structure
 * @tx_ring: Transmit ring
 * @rx_ring: Receive ring
 * @list: Stream devices are linked through this
 */
struct tbstream_dev {
	struct config_group group;
	struct tbstream *stream;
	struct miscdevice misc;
	struct kref kref;
	int index;
	int in_hopid;
	int out_hopid;
	unsigned int ring_size;
	unsigned int throttling;
	bool busy_poll;
	int users;
	bool closed;
	bool removed;
	wait_queue_head_t wait;
	struct mutex lock;
	struct tbstream_ring tx_ring;
	struct tbstream_ring rx_ring;
	struct list_head list;
};

/**
 * struct tbstream_group - Config group for stream
 * @group: ConfigFS group for @stream
 * @stream: Stream the ConfigFS group is attached to. %NULL if there is
 *	    no stream attached.
 * @lock: Lock protecting this structure
 * @dev_list: List of stream devices
 *
 * This is the ConfigFS directory for one connection to another host.
 * There can be several &struct stream_dev linked through @dev_list of
 * this structure. Reference count managed through @group.
 */
struct tbstream_group {
	struct config_group group;
	struct tbstream *stream;
	struct mutex lock;
	struct list_head dev_list;
};

/**
 * struct tbstream - Stream service private data
 * @kref: Reference count
 * @svc: Pointer to the service device
 * @list: Streams are linked through this in @stream_list
 *
 * This represents the actual physical connection between two hosts.
 */
struct tbstream {
	struct kref kref;
	struct tb_service *svc;
	struct list_head list;
};

static DEFINE_IDA(tbstream_indices);

/* Protects tbstream_list */
static DEFINE_MUTEX(tbstream_lock);
static LIST_HEAD(tbstream_list);

/* Serializes tbstream_get()/put() */
static DEFINE_MUTEX(tbstream_kref_lock);

/* Serializes tbstream_dev_get()/put() */
static DEFINE_MUTEX(tbstream_dev_kref_lock);

/* Stream property directory UUID: 3a1cb984-c4d9-4469-a277-ce2fdfd11f0d */
static const uuid_t tbstream_dir_uuid =
	UUID_INIT(0x3a1cb984, 0xc4d9, 0x4469,
		  0xa2, 0x77, 0xce, 0x2f, 0xdf, 0xd1, 0x1f, 0x0d);

static struct tb_property_dir *tbstream_dir;

static void tbstream_release(struct kref *kref)
{
	struct tbstream *stream = container_of(kref, typeof(*stream), kref);

	tb_service_put(stream->svc);
	kfree(stream);
}

static void tbstream_put(struct tbstream *stream)
{
	if (stream) {
		guard(mutex)(&tbstream_kref_lock);
		kref_put(&stream->kref, tbstream_release);
	}
}

static struct tbstream *tbstream_get(struct tbstream *stream)
{
	if (stream) {
		guard(mutex)(&tbstream_kref_lock);
		kref_get(&stream->kref);
	}
	return stream;
}

static inline bool tbstream_valid(const struct tbstream *stream)
{
	if (stream)
		return !tb_service_parent(stream->svc)->is_unplugged;
	return false;
}

static void tbstream_ring_free(struct tbstream_ring *ring)
{
	struct device *dma_dev = tb_ring_dma_device(ring->ring);
	enum dma_data_direction dir;
	int i;

	if (ring->ring->is_tx)
		dir = DMA_TO_DEVICE;
	else
		dir = DMA_FROM_DEVICE;

	for (i = 0; i < tb_ring_size(ring->ring); i++) {
		struct tbstream_frame *sf = &ring->frames[i];

		if (sf->frame.buffer_phy)
			dma_unmap_page(dma_dev, sf->frame.buffer_phy,
				       TB_MAX_FRAME_SIZE, dir);
		sf->frame.buffer_phy = 0;
		if (sf->page)
			__free_page(sf->page);
		sf->page = NULL;
	}

	ring->prod = 0;
	ring->cons = 0;
	kfree(ring->frames);
}

static inline bool tbstream_ring_available(const struct tbstream_ring *ring)
{
	return ring->prod > ring->cons;
}

static inline struct tb_xdomain *tbstream_dev_xdomain(struct tbstream_dev *sdev)
{
	if (sdev->stream)
		return tb_service_parent(sdev->stream->svc);
	return NULL;
}

static void tbstream_dev_release(struct kref *kref)
{
	struct tbstream_dev *sdev = container_of(kref, struct tbstream_dev, kref);

	if (sdev->stream) {
		struct tb_xdomain *xd = tbstream_dev_xdomain(sdev);

		if (sdev->out_hopid > 0)
			tb_xdomain_release_out_hopid(xd, sdev->out_hopid);
		if (sdev->in_hopid > 0)
			tb_xdomain_release_in_hopid(xd, sdev->in_hopid);

		tbstream_put(sdev->stream);
	}
	ida_free(&tbstream_indices, sdev->index);
	kfree(sdev->misc.name);
	kfree(sdev);
}

static inline void tbstream_dev_put(struct tbstream_dev *sdev)
{
	guard(mutex)(&tbstream_dev_kref_lock);
	kref_put(&sdev->kref, tbstream_dev_release);
}

static inline struct tbstream_dev *tbstream_dev_get(struct tbstream_dev *sdev)
{
	guard(mutex)(&tbstream_dev_kref_lock);
	kref_get(&sdev->kref);
	return sdev;
}

static inline struct tbstream_dev *to_tbstream_dev(struct miscdevice *misc)
{
	return container_of(misc, struct tbstream_dev, misc);
}

static inline int tbstream_dev_valid(const struct tbstream_dev *sdev)
{
	const struct tbstream *stream = sdev->stream;

	if (!tbstream_valid(stream))
		return -ENXIO;
	if (sdev->in_hopid <= 0 || sdev->out_hopid <= 0)
		return -EINVAL;
	return 0;
}

static inline bool tbstream_dev_removed(const struct tbstream_dev *sdev)
{
	return sdev->removed;
}

static inline bool tbstream_dev_closed(const struct tbstream_dev *sdev)
{
	return sdev->closed;
}

static void
tbstream_dev_rx_callback(struct tb_ring *ring, struct ring_frame *frame,
			 bool canceled)
{
	struct tbstream_frame *sf = container_of(frame, typeof(*sf), frame);
	struct tbstream_dev *sdev = sf->sdev;

	if (canceled)
		return;

	sf->completed = true;
	sdev->rx_ring.prod++;

	if (sf->frame.flags & RING_DESC_CRC_ERROR)
		pr_warn("RX CRC error\n");
	else if (sf->frame.flags & RING_DESC_BUFFER_OVERRUN)
		pr_warn("RX buffer overrun\n");
	else
		wake_up_interruptible_poll(&sdev->wait, EPOLLIN | EPOLLRDNORM);
}

static struct tbstream_frame *
tbstream_dev_completed_rx(struct tbstream_dev *sdev)
{
	struct device *dma_dev = tb_ring_dma_device(sdev->rx_ring.ring);
	struct tbstream_frame *sf;
	int index;

	index = sdev->rx_ring.cons % tb_ring_size(sdev->rx_ring.ring);
	sf = &sdev->rx_ring.frames[index];
	if (!sf->completed)
		return NULL;

	dma_sync_single_for_cpu(dma_dev, sf->frame.buffer_phy,
				tb_ring_frame_size(&sf->frame),
				DMA_FROM_DEVICE);
	return sf;
}

static int tbstream_dev_consume_rx(struct tbstream_dev *sdev)
{
	struct device *dma_dev = tb_ring_dma_device(sdev->rx_ring.ring);
	struct tbstream_frame *sf;
	int index;

	index = sdev->rx_ring.cons % tb_ring_size(sdev->rx_ring.ring);
	sdev->rx_ring.cons++;

	sf = &sdev->rx_ring.frames[index];
	sf->completed = false;
	sf->offset = 0;
	sf->frame.size = 0;

	dma_sync_single_for_device(dma_dev, sf->frame.buffer_phy,
				   tb_ring_frame_size(&sf->frame),
				   DMA_FROM_DEVICE);

	return tb_ring_rx(sdev->rx_ring.ring, &sf->frame);
}

static int tbstream_dev_alloc_rx_buffers(struct tbstream_dev *sdev)
{
	size_t ring_size = tb_ring_size(sdev->rx_ring.ring);
	int i;

	sdev->rx_ring.frames = kcalloc(ring_size, sizeof(struct tbstream_frame),
				       GFP_KERNEL);
	if (!sdev->rx_ring.frames)
		return -ENOMEM;

	for (i = 0; i < ring_size; i++) {
		struct device *dma_dev = tb_ring_dma_device(sdev->rx_ring.ring);
		struct tbstream_frame *sf = &sdev->rx_ring.frames[i];
		dma_addr_t dma_addr;

		sf->page = alloc_page(GFP_KERNEL);
		if (!sf->page)
			return -ENOMEM;

		dma_addr = dma_map_page(dma_dev, sf->page, 0, TB_MAX_FRAME_SIZE,
					DMA_FROM_DEVICE);
		if (dma_mapping_error(dma_dev, dma_addr)) {
			__free_page(sf->page);
			sf->page = NULL;
			return -ENOMEM;
		}

		sf->sdev = sdev;
		sf->frame.callback = tbstream_dev_rx_callback;
		sf->frame.buffer_phy = dma_addr;

		tb_ring_rx(sdev->rx_ring.ring, &sf->frame);
	}

	sdev->rx_ring.cons = 0;
	sdev->rx_ring.prod = 0;
	return 0;
}

static void
tbstream_dev_tx_callback(struct tb_ring *ring, struct ring_frame *frame,
			 bool canceled)
{
	struct tbstream_frame *sf = container_of(frame, typeof(*sf), frame);
	struct tbstream_dev *sdev = sf->sdev;

	if (canceled)
		return;

	sdev->tx_ring.prod++;
	if (sf->frame.eof == TBSTREAM_DATA)
		wake_up_interruptible_poll(&sdev->wait, EPOLLOUT | EPOLLWRNORM);
}

static int tbstream_dev_alloc_tx_buffers(struct tbstream_dev *sdev)
{
	struct device *dma_dev = tb_ring_dma_device(sdev->tx_ring.ring);
	size_t ring_size = tb_ring_size(sdev->tx_ring.ring);
	int i;

	sdev->tx_ring.frames = kcalloc(ring_size, sizeof(struct tbstream_frame),
				       GFP_KERNEL);
	if (!sdev->tx_ring.frames)
		return -ENOMEM;

	for (i = 0; i < ring_size; i++) {
		struct tbstream_frame *sf = &sdev->tx_ring.frames[i];
		dma_addr_t dma_addr;

		sf->page = alloc_page(GFP_KERNEL);
		if (!sf->page)
			return -ENOMEM;

		dma_addr = dma_map_page(dma_dev, sf->page, 0, TB_MAX_FRAME_SIZE,
					DMA_TO_DEVICE);
		if (dma_mapping_error(dma_dev, dma_addr)) {
			__free_page(sf->page);
			sf->page = NULL;
			return -ENOMEM;
		}

		sf->sdev = sdev;
		sf->frame.callback = tbstream_dev_tx_callback;
		sf->frame.buffer_phy = dma_addr;
		sf->frame.sof = TBSTREAM_FRAME_START;
	}

	sdev->tx_ring.cons = 0;
	sdev->tx_ring.prod = ring_size - 1;
	return 0;
}

static struct tbstream_frame *
tbstream_dev_alloc_tx(struct tbstream_dev *sdev, enum tbstream_frame_pdf pdf,
		      struct iov_iter *from, size_t size)
{
	struct device *dma_dev = tb_ring_dma_device(sdev->tx_ring.ring);
	struct tbstream_frame *sf;
	int index;

	if (!tbstream_ring_available(&sdev->tx_ring))
		return ERR_PTR(-ENOBUFS);

	index = sdev->tx_ring.cons % tb_ring_size(sdev->tx_ring.ring);
	sdev->tx_ring.cons++;

	sf = &sdev->tx_ring.frames[index];
	sf->frame.size = size < TB_MAX_FRAME_SIZE ? size : 0;
	sf->frame.eof = pdf;

	dma_sync_single_for_cpu(dma_dev, sf->frame.buffer_phy, size,
				DMA_TO_DEVICE);
	if (pdf == TBSTREAM_DATA) {
		if (copy_page_from_iter(sf->page, 0, size, from) != size) {
			sdev->tx_ring.cons--;
			return ERR_PTR(-EFAULT);
		}
	} else {
		memset(page_address(sf->page), 0, size);
	}
	dma_sync_single_for_device(dma_dev, sf->frame.buffer_phy, size,
				   DMA_TO_DEVICE);
	return sf;
}

static int
tbstream_dev_send_data(struct tbstream_dev *sdev, struct iov_iter *from,
		       size_t size)
{
	struct tbstream_frame *sf;

	sf = tbstream_dev_alloc_tx(sdev, TBSTREAM_DATA, from, size);
	if (IS_ERR(sf))
		return PTR_ERR(sf);
	return tb_ring_tx(sdev->tx_ring.ring, &sf->frame);
}

static void
tbstream_dev_poll_ring(struct tbstream_dev *sdev, struct tbstream_ring *ring)
{
	struct ring_frame *frame;

	if (!sdev->busy_poll)
		return;

	while ((frame = tb_ring_poll(ring->ring)))
		frame->callback(ring->ring, frame, false);
}

static int tbstream_dev_send_close(struct tbstream_dev *sdev)
{
	struct tbstream_frame *sf;

	if (sdev->busy_poll) {
		/*
		 * When busy polling it's the write(2) path that
		 * advances the completions so it is possible that the
		 * ring is full at this point. Advance the ring here so
		 * that there is room for the CLOSE packet to be sent.
		 */
		ktime_t timeout = ktime_add_ms(ktime_get(), 500);

		do {
			if (tbstream_ring_available(&sdev->tx_ring))
				break;
			tbstream_dev_poll_ring(sdev, &sdev->tx_ring);
			fsleep(15);
		} while (ktime_before(ktime_get(), timeout));
	}

	sf = tbstream_dev_alloc_tx(sdev, TBSTREAM_CLOSE, NULL, SZ_256);
	if (IS_ERR(sf))
		return PTR_ERR(sf);
	return tb_ring_tx(sdev->tx_ring.ring, &sf->frame);
}

static int tbstream_dev_start(struct tbstream_dev *sdev)
{
	struct tb_xdomain *xd = tbstream_dev_xdomain(sdev);
	unsigned int flags = RING_FLAG_FRAME | RING_FLAG_E2E;
	u16 sof_mask, eof_mask;
	struct tb_ring *ring;
	int ret, e2e_tx_hop;

	if (sdev->busy_poll)
		flags |= RING_FLAG_NO_INTERRUPT;

	ring = tb_ring_alloc_tx(xd->tb->nhi, -1, sdev->ring_size, flags);
	if (!ring)
		return -ENOMEM;
	sdev->tx_ring.ring = ring;

	ret = tbstream_dev_alloc_tx_buffers(sdev);
	if (ret)
		goto err_free_tx;

	e2e_tx_hop = ring->hop;
	sof_mask = BIT(TBSTREAM_FRAME_START);
	eof_mask = BIT(TBSTREAM_DATA) | BIT(TBSTREAM_CLOSE);

	ring = tb_ring_alloc_rx(xd->tb->nhi, -1, sdev->ring_size, flags,
				e2e_tx_hop, sof_mask, eof_mask, NULL, NULL);
	if (!ring) {
		ret = -ENOMEM;
		goto err_free_tx_buffers;
	}
	sdev->rx_ring.ring = ring;

	ret = tb_xdomain_enable_paths(xd, sdev->out_hopid,
				     sdev->tx_ring.ring->hop,
				     sdev->in_hopid,
				     sdev->rx_ring.ring->hop);
	if (ret)
		goto err_free_rx;

	tb_ring_throttling(sdev->tx_ring.ring, sdev->throttling);
	tb_ring_throttling(sdev->rx_ring.ring, sdev->throttling);

	tb_ring_start(sdev->tx_ring.ring);
	tb_ring_start(sdev->rx_ring.ring);

	ret = tbstream_dev_alloc_rx_buffers(sdev);
	if (ret)
		goto err_stop;
	return 0;

err_stop:
	tb_ring_stop(sdev->rx_ring.ring);
	tb_ring_stop(sdev->tx_ring.ring);
err_free_rx:
	tb_ring_free(sdev->rx_ring.ring);
err_free_tx_buffers:
	tbstream_ring_free(&sdev->tx_ring);
err_free_tx:
	tb_ring_free(sdev->tx_ring.ring);

	return ret;
}

static bool tbstream_dev_tx_drained(const struct tbstream_dev *sdev)
{
	const struct tbstream_ring *ring = &sdev->tx_ring;

	/*
	 * Everything is completed when number of free TX slots is back
	 * to the maximum.
	 */
	return ring->prod - ring->cons == tb_ring_size(ring->ring) - 1;
}

static void tbstream_dev_stop(struct tbstream_dev *sdev)
{
	struct tb_xdomain *xd;

	if (sdev->busy_poll) {
		/*
		 * When busy polling we must advance the ring ourselves
		 * to push all outstanding frames on the wire.
		 */
		ktime_t timeout = ktime_add_ms(ktime_get(), 500);

		do {
			if (tbstream_dev_tx_drained(sdev))
				break;
			tbstream_dev_poll_ring(sdev, &sdev->tx_ring);
			fsleep(15);
		} while (ktime_before(ktime_get(), timeout));

		tb_ring_stop(sdev->tx_ring.ring);
		tb_ring_stop(sdev->rx_ring.ring);
	} else {
		tb_ring_flush(sdev->tx_ring.ring, 500);
		tb_ring_stop(sdev->tx_ring.ring);
		tb_ring_flush(sdev->rx_ring.ring, 500);
		tb_ring_stop(sdev->rx_ring.ring);
	}

	xd = tbstream_dev_xdomain(sdev);
	if (xd) {
		tb_xdomain_disable_paths(xd, sdev->out_hopid,
					 sdev->tx_ring.ring->hop,
					 sdev->in_hopid,
					 sdev->rx_ring.ring->hop);
	}

	tbstream_ring_free(&sdev->rx_ring);
	tb_ring_free(sdev->rx_ring.ring);
	sdev->rx_ring.ring = NULL;
	tbstream_ring_free(&sdev->tx_ring);
	tb_ring_free(sdev->tx_ring.ring);
	sdev->tx_ring.ring = NULL;
}

/* Use only with read_iter/write_iter() to handle nowait */
static int tbstream_dev_lock(struct tbstream_dev *sdev, bool nowait)
{
	if (nowait) {
		if (!mutex_trylock(&sdev->lock))
			return -EAGAIN;
	} else {
		if (mutex_lock_interruptible(&sdev->lock))
			return -ERESTARTSYS;
	}
	return 0;
}

static ssize_t
tbstream_dev_fops_read_iter(struct kiocb *kiocb, struct iov_iter *to)
{
	struct file *file = kiocb->ki_filp;
	bool nowait = file->f_flags & O_NONBLOCK || kiocb->ki_flags & IOCB_NOWAIT;
	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);
	size_t nbytes;
	int ret;

	ret = tbstream_dev_valid(sdev);
	if (ret)
		return ret;

	ret = tbstream_dev_lock(sdev, nowait);
	if (ret)
		return ret;

	for (;;) {
		/* When busy polling, advance any completions manually */
		tbstream_dev_poll_ring(sdev, &sdev->rx_ring);

		ret = tbstream_dev_valid(sdev);
		if (ret) {
			mutex_unlock(&sdev->lock);
			return ret;
		}

		if (tbstream_dev_closed(sdev) || tbstream_dev_removed(sdev)) {
			mutex_unlock(&sdev->lock);
			return 0;
		}

		if (tbstream_ring_available(&sdev->rx_ring))
			break;

		mutex_unlock(&sdev->lock);

		if (nowait)
			return -EAGAIN;

		if (sdev->busy_poll) {
			if (signal_pending(current))
				return -ERESTARTSYS;
			cond_resched();
		} else {
			ret = wait_event_interruptible(sdev->wait,
					tbstream_ring_available(&sdev->rx_ring) ||
					tbstream_dev_valid(sdev) != 0 ||
					tbstream_dev_closed(sdev) ||
					tbstream_dev_removed(sdev));
			if (ret)
				return ret;
		}

		ret = tbstream_dev_lock(sdev, nowait);
		if (ret)
			return ret;
	}

	nbytes = 0;
	while (iov_iter_count(to)) {
		struct tbstream_frame *sf;
		size_t size, sf_size;

		sf = tbstream_dev_completed_rx(sdev);
		if (!sf)
			break;
		/*
		 * CLOSE tunneled packet. If userspace already read
		 * something then we stop processing now and return
		 * those bytes. Next time the first frame will be CLOSE
		 * in which case we return EOF to the user.
		 */
		if (sf->frame.eof == TBSTREAM_CLOSE) {
			if (!nbytes) {
				tbstream_dev_consume_rx(sdev);
				sdev->closed = true;
			}
			break;
		}

		sf_size = tb_ring_frame_size(&sf->frame);
		size = min(iov_iter_count(to), sf_size);

		if (copy_page_to_iter(sf->page, sf->offset, size, to) != size) {
			ret = -EFAULT;
			break;
		}

		/*
		 * If not all data from the frame is read so leave it in
		 * place and update the offset accordingly so next read
		 * gets the rest.
		 */
		if (size < sf_size) {
			sf->offset += size;
			sf->frame.size = sf_size - size;
		} else {
			ret = tbstream_dev_consume_rx(sdev);
			if (ret)
				break;
		}

		nbytes += size;
	}

	mutex_unlock(&sdev->lock);
	if (ret)
		return ret;
	return nbytes;
}

static ssize_t
tbstream_dev_fops_write_iter(struct kiocb *kiocb, struct iov_iter *from)
{
	struct file *file = kiocb->ki_filp;
	bool nowait = file->f_flags & O_NONBLOCK || kiocb->ki_flags & IOCB_NOWAIT;
	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);
	size_t nbytes;
	int ret;

	ret = tbstream_dev_valid(sdev);
	if (ret)
		return ret;

	ret = tbstream_dev_lock(sdev, nowait);
	if (ret)
		return ret;

	for (;;) {
		tbstream_dev_poll_ring(sdev, &sdev->tx_ring);

		ret = tbstream_dev_valid(sdev);
		if (ret) {
			mutex_unlock(&sdev->lock);
			return ret;
		}

		if (tbstream_dev_closed(sdev) || tbstream_dev_removed(sdev)) {
			mutex_unlock(&sdev->lock);
			return -ENXIO;
		}

		if (tbstream_ring_available(&sdev->tx_ring))
			break;

		mutex_unlock(&sdev->lock);

		if (nowait)
			return -EAGAIN;

		if (sdev->busy_poll) {
			if (signal_pending(current))
				return -ERESTARTSYS;
			cond_resched();
		} else {
			ret = wait_event_interruptible(sdev->wait,
					tbstream_ring_available(&sdev->tx_ring) ||
					tbstream_dev_valid(sdev) != 0 ||
					tbstream_dev_closed(sdev) ||
					tbstream_dev_removed(sdev));
			if (ret)
				return ret;
		}

		ret = tbstream_dev_lock(sdev, nowait);
		if (ret)
			return ret;
	}

	nbytes = 0;
	while (iov_iter_count(from)) {
		size_t size;

		size = min(iov_iter_count(from), TB_MAX_FRAME_SIZE);
		ret = tbstream_dev_send_data(sdev, from, size);
		if (ret) {
			/*
			 * If there are no more buffers we are done for
			 * this write.
			 */
			if (ret == -ENOBUFS)
				ret = 0;
			break;
		}

		nbytes += size;
	}

	mutex_unlock(&sdev->lock);
	if (ret)
		return ret;
	return nbytes;
}

static __poll_t
tbstream_dev_fops_poll(struct file *file, struct poll_table_struct *wait)
{
	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);
	__poll_t mask = 0;

	/*
	 * Without interrupts there is nothing that can wake us up so
	 * return failure instead.
	 */
	if (sdev->busy_poll)
		return EPOLLERR;

	poll_wait(file, &sdev->wait, wait);
	guard(mutex)(&sdev->lock);
	if (tbstream_dev_valid(sdev) != 0) {
		mask |= EPOLLHUP | EPOLLERR;
	} else {
		if (tbstream_ring_available(&sdev->tx_ring))
			mask |= EPOLLOUT | EPOLLWRNORM;
		if (tbstream_ring_available(&sdev->rx_ring))
			mask |= EPOLLIN | EPOLLRDNORM;
	}
	return mask;
}

static int tbstream_dev_fops_open(struct inode *inode, struct file *file)
{
	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);
	int ret;

	tbstream_dev_get(sdev);

	if (mutex_lock_interruptible(&sdev->lock)) {
		tbstream_dev_put(sdev);
		return -ERESTARTSYS;
	}

	/*
	 * If there is no stream attached yet, block until it appears
	 * unless this is opened in non-blocking mode.
	 */
	while ((ret = tbstream_dev_valid(sdev))) {
		mutex_unlock(&sdev->lock);

		if (ret != -ENXIO || (file->f_flags & O_NONBLOCK))
			goto err_put;

		ret = wait_event_interruptible(sdev->wait,
				tbstream_dev_valid(sdev) == 0 ||
				tbstream_dev_removed(sdev));
		if (ret)
			goto err_put;

		if (tbstream_dev_removed(sdev)) {
			ret = -ENXIO;
			goto err_put;
		}

		if (mutex_lock_interruptible(&sdev->lock)) {
			ret = -ERESTARTSYS;
			goto err_put;
		}
	}

	/* Only on first open we allocate rings and enable paths */
	if (!sdev->users++) {
		ret = tbstream_dev_start(sdev);
		if (ret) {
			sdev->users--;
			goto err_unlock;
		}
		sdev->closed = false;
	}

	mutex_unlock(&sdev->lock);
	return 0;

err_unlock:
	mutex_unlock(&sdev->lock);
err_put:
	tbstream_dev_put(sdev);

	return ret;
}

static int tbstream_dev_fops_release(struct inode *inode, struct file *file)
{
	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);

	mutex_lock(&sdev->lock);
	if (--sdev->users == 0) {
		/*
		 * Send CLOSE tunneled packet to notify the other end
		 * that we are closing the file. We do this twice if the
		 * first one fails.
		 */
		tbstream_dev_send_close(sdev);
		tbstream_dev_stop(sdev);
	}
	mutex_unlock(&sdev->lock);

	tbstream_dev_put(sdev);
	return 0;
}

static const struct file_operations tbstream_dev_fops = {
	.owner = THIS_MODULE,
	.llseek = noop_llseek,
	.read_iter = tbstream_dev_fops_read_iter,
	.write_iter = tbstream_dev_fops_write_iter,
	.poll = tbstream_dev_fops_poll,
	.open = tbstream_dev_fops_open,
	.release = tbstream_dev_fops_release,
};

static inline struct tbstream_dev *
tbstream_dev_from_group(struct config_group *group)
{
	return container_of(group, struct tbstream_dev, group);
}

static ssize_t tbstream_dev_busy_poll_show(struct config_item *item, char *buf)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);

	return sysfs_emit(buf, "%u\n", sdev->busy_poll);
}

static ssize_t
tbstream_dev_busy_poll_store(struct config_item *item, const char *buf,
			     size_t count)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
	bool busy_poll;
	int ret;

	ret = kstrtobool(buf, &busy_poll);
	if (ret)
		return ret;

	guard(mutex)(&sdev->lock);
	if (sdev->users)
		return -EBUSY;
	sdev->busy_poll = busy_poll;
	return count;
}
CONFIGFS_ATTR(tbstream_dev_, busy_poll);

static ssize_t tbstream_dev_index_show(struct config_item *item, char *buf)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);

	return sysfs_emit(buf, "%d\n", sdev->index);
}
CONFIGFS_ATTR_RO(tbstream_dev_, index);

static ssize_t tbstream_dev_in_hopid_show(struct config_item *item, char *buf)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);

	return sysfs_emit(buf, "%d\n", sdev->in_hopid);
}

/* svc->lock must be held */
static void service_remove_properties(struct tb_service *svc, const char *name)
{
	struct tb_property *p;

	if (!svc->local_properties)
		return;

	p = tb_property_find(svc->local_properties, name,
			     TB_PROPERTY_TYPE_DIRECTORY);
	if (p) {
		tb_property_free_dir(p->value.dir);
		tb_property_remove(p);

		dev_dbg(&svc->dev, "removed local directory %s\n", name);

		/*
		 * Is the service directory empty already? If it is then
		 * we can release it as well.
		 */
		tb_property_for_each(svc->local_properties, p) {
			if (p->type == TB_PROPERTY_TYPE_DIRECTORY)
				return;
		}

		tb_property_free_dir(svc->local_properties);
		svc->local_properties = NULL;
	}
}

static int service_update_properties(struct tb_service *svc, const char *name,
				     int in_hopid, int out_hopid)
{
	struct tb_property_dir *dir;
	struct tb_property *p;

	guard(mutex)(&svc->lock);

	if (in_hopid < 8 || out_hopid < 8) {
		service_remove_properties(svc, name);
		return 0;
	}

	if (!svc->local_properties) {
		/*
		 * Add the service directory first time we
		 * populate the entries.
		 */
		svc->local_properties = tb_property_copy_dir(tbstream_dir);
		if (!svc->local_properties)
			return -ENOMEM;
	}

	p = tb_property_find(svc->local_properties, name,
			     TB_PROPERTY_TYPE_DIRECTORY);
	if (p) {
		dir = p->value.dir;

		p = tb_property_find(dir, "inhopid", TB_PROPERTY_TYPE_VALUE);
		if (p && p->value.immediate != in_hopid)
			p->value.immediate = in_hopid;
		p = tb_property_find(dir, "outhopid", TB_PROPERTY_TYPE_VALUE);
		if (p && p->value.immediate != out_hopid)
			p->value.immediate = out_hopid;

		dev_dbg(&svc->dev,
			"updated local directory %s: in HopID %d, out HopID %d\n",
			name, in_hopid, out_hopid);
	} else {
		uuid_t uuid;
		int ret;

		uuid_gen(&uuid);
		dir = tb_property_create_dir(&uuid);
		if (!dir)
			return -ENOMEM;

		tb_property_add_immediate(dir, "inhopid", in_hopid);
		tb_property_add_immediate(dir, "outhopid", out_hopid);

		ret = tb_property_add_dir(svc->local_properties, name, dir);
		if (ret) {
			tb_property_free_dir(dir);
			return ret;
		}

		dev_dbg(&svc->dev,
			"added local directory %s: in HopID %d, out HopID %d\n",
			name, in_hopid, out_hopid);
	}

	return 0;
}

static int tbstream_dev_update_properties(struct tbstream_dev *sdev)
{
	struct tbstream *stream;
	int ret;

	stream = tbstream_get(sdev->stream);
	if (!stream)
		return 0;

	ret = service_update_properties(stream->svc,
					config_item_name(&sdev->group.cg_item),
					sdev->in_hopid, sdev->out_hopid);
	if (!ret)
		tb_service_properties_changed(stream->svc);

	tbstream_put(stream);
	return ret;
}

static int tbstream_dev_alloc_in_hopid(struct tbstream_dev *sdev, int hopid)
{
	struct tb_xdomain *xd = tbstream_dev_xdomain(sdev);
	int ret;

	if (sdev->in_hopid > 0 && sdev->in_hopid != hopid)
		tb_xdomain_release_in_hopid(xd, sdev->in_hopid);
	if (!hopid) {
		sdev->in_hopid = hopid;
		return 0;
	}
	ret = tb_xdomain_alloc_in_hopid(xd, hopid);
	if (ret < 0)
		return ret;
	/*
	 * If specific HopID was asked by the user and we did not get
	 * that one then release and return error instead.
	 */
	if (hopid > 0 && hopid != ret) {
		tb_xdomain_release_in_hopid(xd, ret);
		return -EBUSY;
	}
	sdev->in_hopid = ret;
	return 0;
}

static int tbstream_dev_alloc_out_hopid(struct tbstream_dev *sdev, int hopid)
{
	struct tb_xdomain *xd = tbstream_dev_xdomain(sdev);
	int ret;

	if (sdev->out_hopid > 0 && sdev->out_hopid != hopid)
		tb_xdomain_release_out_hopid(xd, sdev->out_hopid);
	if (!hopid) {
		sdev->out_hopid = hopid;
		return 0;
	}
	ret = tb_xdomain_alloc_out_hopid(xd, hopid);
	if (ret < 0)
		return ret;
	if (hopid > 0 && hopid != ret) {
		tb_xdomain_release_out_hopid(xd, ret);
		return -EBUSY;
	}
	sdev->out_hopid = ret;
	return 0;
}

static ssize_t
tbstream_dev_in_hopid_store(struct config_item *item, const char *buf,
			    size_t count)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
	int ret, in_hopid;

	ret = kstrtoint(buf, 0, &in_hopid);
	if (ret)
		return ret;

	guard(mutex)(&sdev->lock);
	if (sdev->users)
		return -EBUSY;
	if (sdev->stream) {
		ret = tbstream_dev_alloc_in_hopid(sdev, in_hopid);
		if (ret)
			return ret;
		ret = tbstream_dev_update_properties(sdev);
	} else {
		sdev->in_hopid = in_hopid;
	}
	return ret ? ret : count;
}
CONFIGFS_ATTR(tbstream_dev_, in_hopid);

static ssize_t tbstream_dev_out_hopid_show(struct config_item *item, char *buf)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);

	return sysfs_emit(buf, "%d\n", sdev->out_hopid);
}

static ssize_t
tbstream_dev_out_hopid_store(struct config_item *item, const char *buf,
			     size_t count)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
	int ret, out_hopid;

	ret = kstrtoint(buf, 0, &out_hopid);
	if (ret)
		return ret;

	guard(mutex)(&sdev->lock);
	if (sdev->users)
		return -EBUSY;
	if (sdev->stream) {
		ret = tbstream_dev_alloc_out_hopid(sdev, out_hopid);
		if (ret)
			return ret;
		ret = tbstream_dev_update_properties(sdev);
	} else {
		sdev->out_hopid = out_hopid;
	}
	return ret ? ret : count;
}
CONFIGFS_ATTR(tbstream_dev_, out_hopid);

static ssize_t tbstream_dev_ring_size_show(struct config_item *item, char *buf)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);

	return sysfs_emit(buf, "%u\n", sdev->ring_size);
}

static ssize_t
tbstream_dev_ring_size_store(struct config_item *item, const char *buf,
			     size_t count)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
	unsigned int ring_size;
	int ret;

	ret = kstrtouint(buf, 0, &ring_size);
	if (ret)
		return ret;

	if (ring_size < TBSTREAM_DEV_MIN_RING_SIZE ||
	    ring_size > TBSTREAM_DEV_MAX_RING_SIZE)
		return -EINVAL;

	guard(mutex)(&sdev->lock);
	if (sdev->users)
		return -EBUSY;
	sdev->ring_size = ring_size;
	return count;
}
CONFIGFS_ATTR(tbstream_dev_, ring_size);

static ssize_t tbstream_dev_throttling_show(struct config_item *item, char *buf)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);

	return sysfs_emit(buf, "%u\n", sdev->throttling);
}

static ssize_t
tbstream_dev_throttling_store(struct config_item *item, const char *buf,
			      size_t count)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
	unsigned int throttling;
	int ret;

	ret = kstrtouint(buf, 0, &throttling);
	if (ret)
		return ret;

	if (throttling > TBSTREAM_DEV_MAX_THROTTLING)
		return -EINVAL;

	guard(mutex)(&sdev->lock);
	if (sdev->users)
		return -EBUSY;
	sdev->throttling = throttling;
	return count;
}
CONFIGFS_ATTR(tbstream_dev_, throttling);

static struct configfs_attribute *tbstream_dev_attrs[] = {
	&tbstream_dev_attr_busy_poll,
	&tbstream_dev_attr_index,
	&tbstream_dev_attr_in_hopid,
	&tbstream_dev_attr_out_hopid,
	&tbstream_dev_attr_ring_size,
	&tbstream_dev_attr_throttling,
	NULL,
};

static void tbstream_dev_item_release(struct config_item *item)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(group);

	misc_deregister(&sdev->misc);
	tbstream_dev_put(sdev);
}

static struct configfs_item_operations tbstream_dev_item_ops = {
	.release = tbstream_dev_item_release,
};

static const struct config_item_type tbstream_dev_type = {
	.ct_owner = THIS_MODULE,
	.ct_item_ops = &tbstream_dev_item_ops,
	.ct_attrs = tbstream_dev_attrs,
};

static void service_get_hopids(struct tb_service *svc, const char *name,
			       int *in_hopid, int *out_hopid)
{
	struct tb_property_dir *dir;
	struct tb_property *p;

	guard(mutex)(&svc->lock);

	/* See if we have directory entry with the matching name */
	p = tb_property_find(svc->remote_properties, name,
			     TB_PROPERTY_TYPE_DIRECTORY);
	if (!p)
		return;

	dir = p->value.dir;

	/*
	 * We need to reverse the HopIDs on our end so that in becomes
	 * out and vice versa.
	 */
	p = tb_property_find(dir, "inhopid", TB_PROPERTY_TYPE_VALUE);
	if (p && p->value.immediate >= 8)
		*out_hopid = p->value.immediate;
	p = tb_property_find(dir, "outhopid", TB_PROPERTY_TYPE_VALUE);
	if (p && p->value.immediate >= 8)
		*in_hopid = p->value.immediate;
}

static void
tbstream_dev_attach_stream(struct tbstream_dev *sdev, struct tbstream_group *sg)
{
	const char *name = config_item_name(&sdev->group.cg_item);
	struct tbstream *stream;

	stream = tbstream_get(sg->stream);
	if (!stream)
		return;

	scoped_guard(mutex, &sdev->lock) {
		sdev->stream = stream;
		/*
		 * If there is no existing configuration (or automatic
		 * configuration is being used) check if the other side
		 * has configuration for this and use it.
		 */
		if (sdev->in_hopid <= 0 && sdev->out_hopid <= 0)
			service_get_hopids(stream->svc, name, &sdev->in_hopid,
					   &sdev->out_hopid);
		if (sdev->in_hopid)
			tbstream_dev_alloc_in_hopid(sdev, sdev->in_hopid);
		if (sdev->out_hopid)
			tbstream_dev_alloc_out_hopid(sdev, sdev->out_hopid);
	}

	service_update_properties(stream->svc, name, sdev->in_hopid,
				  sdev->out_hopid);
	tb_service_properties_changed(stream->svc);

	/* Notify any openerers that the stream is now attached */
	wake_up_interruptible(&sdev->wait);
}

static void tbstream_dev_detach_stream(struct tbstream_dev *sdev)
{
	const char *name = config_item_name(&sdev->group.cg_item);
	struct tbstream *stream;
	struct tb_xdomain *xd;

	scoped_guard(mutex, &sdev->lock) {
		stream = sdev->stream;
		if (!stream)
			return;
		sdev->stream = NULL;
		xd = tb_service_parent(stream->svc);
		if (sdev->out_hopid > 0)
			tb_xdomain_release_out_hopid(xd, sdev->out_hopid);
		if (sdev->in_hopid > 0)
			tb_xdomain_release_in_hopid(xd, sdev->in_hopid);
	}

	service_update_properties(stream->svc, name, 0, 0);
	tb_service_properties_changed(stream->svc);

	tbstream_put(stream);

	/* Notify any task that the stream is not valid anymore */
	wake_up_interruptible_poll(&sdev->wait, EPOLLHUP | EPOLLERR);
}

static inline struct tbstream_group *
to_tbstream_group(struct config_group *group)
{
	return container_of(group, struct tbstream_group, group);
}

static struct config_group *
tbstream_dev_make_group(struct config_group *group, const char *name)
{
	struct tbstream_group *sg = to_tbstream_group(group);
	struct tbstream_dev *sdev;
	int ret, index;

	/*
	 * We want the names to be suitable for passing as property
	 * directory names.
	 */
	if (strlen(name) > TB_PROPERTY_KEY_SIZE)
		return ERR_PTR(-ENAMETOOLONG);

	sdev = kzalloc_obj(*sdev, GFP_KERNEL);
	if (!sdev)
		return ERR_PTR(-ENOMEM);

	index = ida_alloc(&tbstream_indices, GFP_KERNEL);
	if (index < 0) {
		kfree(sdev);
		return ERR_PTR(index);
	}

	sdev->index = index;
	sdev->ring_size = TBSTREAM_DEV_RING_SIZE;
	sdev->throttling = TBSTREAM_DEV_THROTTLING;
	mutex_init(&sdev->lock);
	init_waitqueue_head(&sdev->wait);
	INIT_LIST_HEAD(&sdev->list);
	/* This point forward tbstream_dev_put() must be used to release sdev */
	kref_init(&sdev->kref);

	config_group_init_type_name(&sdev->group, name, &tbstream_dev_type);

	scoped_guard(mutex, &sg->lock)
		list_add_tail(&sdev->list, &sg->dev_list);

	tbstream_dev_attach_stream(sdev, sg);

	sdev->misc.name = kasprintf(GFP_KERNEL, "tbstream%d", index);
	sdev->misc.minor = MISC_DYNAMIC_MINOR;
	sdev->misc.fops = &tbstream_dev_fops;

	ret = misc_register(&sdev->misc);
	if (ret) {
		tbstream_dev_detach_stream(sdev);
		scoped_guard(mutex, &sg->lock)
			list_del(&sdev->list);
		/* Calls tbstream_dev_put() */
		config_group_put(&sdev->group);
		return ERR_PTR(ret);
	}

	return &sdev->group;
}

static void
tbstream_dev_drop_item(struct config_group *group, struct config_item *item)
{
	struct config_group *sdev_group = to_config_group(item);
	struct tbstream_dev *sdev = tbstream_dev_from_group(sdev_group);
	struct tbstream_group *sg = to_tbstream_group(group);

	scoped_guard(mutex, &sg->lock)
		list_del(&sdev->list);
	/* Notify any task that the underlying group was removed  */
	sdev->removed = true;
	wake_up_interruptible_poll(&sdev->wait, EPOLLHUP | EPOLLERR);
	config_item_put(item);
}

static struct configfs_group_operations tbstream_dev_group_ops = {
	.make_group = tbstream_dev_make_group,
	.drop_item = tbstream_dev_drop_item,
};

static void tbstream_item_release(struct config_item *item)
{
	struct config_group *group = to_config_group(item);
	struct tbstream_group *sg = to_tbstream_group(group);

	tbstream_put(sg->stream);
	kfree(sg);
}

static struct configfs_item_operations tbstream_item_ops = {
	.release = tbstream_item_release,
};

static const struct config_item_type tbstream_dev_group_type = {
	.ct_owner = THIS_MODULE,
	.ct_group_ops = &tbstream_dev_group_ops,
	.ct_item_ops = &tbstream_item_ops,
};

static struct config_group *
tbstream_make_group(struct config_group *group, const char *name)
{
	struct tbstream_group *sg;
	struct tbstream *stream;
	int domain, index;
	u64 route;

	/* Make sure the format is correct */
	if (sscanf(name, "%u-%llx.%u", &domain, &route, &index) != 3)
		return ERR_PTR(-EINVAL);

	sg = kzalloc_obj(*sg, GFP_KERNEL);
	if (!sg)
		return ERR_PTR(-ENOMEM);

	mutex_init(&sg->lock);
	INIT_LIST_HEAD(&sg->dev_list);

	guard(mutex)(&tbstream_lock);
	list_for_each_entry(stream, &tbstream_list, list) {
		tbstream_get(stream);
		if (sysfs_streq(name, dev_name(&stream->svc->dev))) {
			sg->stream = stream;
			break;
		}
		tbstream_put(stream);
	}

	config_group_init_type_name(&sg->group, name, &tbstream_dev_group_type);
	return &sg->group;
}

static struct configfs_group_operations tbstream_group_ops = {
	.make_group = tbstream_make_group,
};

static const struct config_item_type tbstream_group_type = {
	.ct_owner = THIS_MODULE,
	.ct_group_ops = &tbstream_group_ops,
};

static struct config_group tbstream_group = {
	.cg_item = {
		.ci_namebuf = "stream",
		.ci_type = &tbstream_group_type,
	},
};

/* Returns reference count increased */
static struct tbstream_group *tbstream_group_find(struct tbstream *stream)
{
	const char *name = dev_name(&stream->svc->dev);
	struct config_item *item;

	guard(mutex)(&tbstream_group.cg_subsys->su_mutex);
	item = config_group_find_item(&tbstream_group, name);
	if (!item)
		return NULL;
	return to_tbstream_group(to_config_group(item));
}

static void tbstream_group_attach_stream(struct tbstream *stream)
{
	struct tbstream_group *sg;
	struct tbstream_dev *sdev;

	sg = tbstream_group_find(stream);
	if (!sg)
		return;

	guard(mutex)(&sg->lock);
	if (WARN_ON(sg->stream)) {
		config_group_put(&sg->group);
		return;
	}
	sg->stream = tbstream_get(stream);
	/*
	 * If there are existing stream devices, attach the stream to
	 * them now.
	 */
	list_for_each_entry(sdev, &sg->dev_list, list) {
		tbstream_dev_get(sdev);
		tbstream_dev_attach_stream(sdev, sg);
		tbstream_dev_put(sdev);
	}

	config_group_put(&sg->group);
}

static void tbstream_group_detach_stream(struct tbstream *stream)
{
	struct tbstream_group *sg;
	struct tbstream_dev *sdev;

	sg = tbstream_group_find(stream);
	if (!sg)
		return;

	guard(mutex)(&sg->lock);
	if (sg->stream) {
		/* Detach this stream from the stream devices */
		list_for_each_entry_reverse(sdev, &sg->dev_list, list) {
			tbstream_dev_get(sdev);
			tbstream_dev_detach_stream(sdev);
			tbstream_dev_put(sdev);
		}
		tbstream_put(sg->stream);
		sg->stream = NULL;
	}

	config_group_put(&sg->group);
}

static int tbstream_probe(struct tb_service *svc)
{
	struct tbstream *stream;

	stream = kzalloc_obj(*stream, GFP_KERNEL);
	if (!stream)
		return -ENOMEM;

	/* After this point, release stream by calling tbstream_put() */
	kref_init(&stream->kref);
	stream->svc = tb_service_get(svc);
	INIT_LIST_HEAD(&stream->list);

	scoped_guard(mutex, &tbstream_lock)
		list_add_tail(&stream->list, &tbstream_list);

	tbstream_group_attach_stream(stream);
	tb_service_set_drvdata(svc, stream);
	return 0;
}

static void tbstream_remove(struct tb_service *svc)
{
	struct tbstream *stream = tb_service_get_drvdata(svc);

	tbstream_group_detach_stream(stream);
	scoped_guard(mutex, &tbstream_lock)
		list_del(&stream->list);
	tbstream_put(stream);
}

static int __maybe_unused tbstream_suspend(struct device *dev)
{
	struct tb_service *svc = tb_to_service(dev);
	struct tbstream *stream = tb_service_get_drvdata(svc);
	struct tbstream_group *sg;
	struct tbstream_dev *sdev;

	sg = tbstream_group_find(stream);
	if (!sg)
		return 0;

	list_for_each_entry_reverse(sdev, &sg->dev_list, list) {
		tbstream_dev_get(sdev);
		/* Stop the stream (if it was open) */
		if (sdev->users)
			tbstream_dev_stop(sdev);
		tbstream_dev_put(sdev);
	}

	config_group_put(&sg->group);
	return 0;
}

static int __maybe_unused tbstream_resume(struct device *dev)
{
	struct tb_service *svc = tb_to_service(dev);
	struct tbstream *stream = tb_service_get_drvdata(svc);
	struct tbstream_group *sg;
	struct tbstream_dev *sdev;

	sg = tbstream_group_find(stream);
	if (!sg)
		return 0;

	list_for_each_entry(sdev, &sg->dev_list, list) {
		tbstream_dev_get(sdev);
		if (sdev->users) {
			int ret;

			ret = tbstream_dev_start(sdev);
			if (ret) {
				tbstream_dev_put(sdev);
				config_group_put(&sg->group);
				return ret;
			}
		}
		tbstream_dev_put(sdev);
	}

	config_group_put(&sg->group);
	return 0;
}

static const struct dev_pm_ops tbstream_pm_ops = {
	SET_SYSTEM_SLEEP_PM_OPS(tbstream_suspend, tbstream_resume)
};

static const struct tb_service_id tbstream_ids[] = {
	{ TB_SERVICE("stream", 1) },
	{ }
};
MODULE_DEVICE_TABLE(tbsvc, tbstream_ids);

static struct tb_service_driver tbstream_driver = {
	.driver = {
		.owner = THIS_MODULE,
		.name = "thunderbolt_stream",
		.pm = &tbstream_pm_ops,
	},
	.probe = tbstream_probe,
	.remove = tbstream_remove,
	.id_table = tbstream_ids,
};

static int __init tbstream_init(void)
{
	int ret;

	tbstream_dir = tb_property_create_dir(&tbstream_dir_uuid);
	if (!tbstream_dir)
		return -ENOMEM;

	tb_property_add_immediate(tbstream_dir, "prtcid", 1);
	tb_property_add_immediate(tbstream_dir, "prtcvers", 1);
	tb_property_add_immediate(tbstream_dir, "prtcrevs", 0);
	tb_property_add_immediate(tbstream_dir, "prtcstns", 0);

	ret = tb_register_property_dir("stream", tbstream_dir);
	if (ret)
		goto err_free_dir;

	config_group_init(&tbstream_group);
	ret = tb_configfs_register_group(&tbstream_group);
	if (ret)
		goto err_unregister_dir;

	ret = tb_register_service_driver(&tbstream_driver);
	if (ret)
		goto err_unregister_group;
	return 0;

err_unregister_group:
	tb_configfs_unregister_group(&tbstream_group);
err_unregister_dir:
	tb_unregister_property_dir("stream", tbstream_dir);
err_free_dir:
	tb_property_free_dir(tbstream_dir);
	return ret;
}
module_init(tbstream_init);

static void __exit tbstream_exit(void)
{
	tb_unregister_service_driver(&tbstream_driver);
	tb_configfs_unregister_group(&tbstream_group);
	tb_unregister_property_dir("stream", tbstream_dir);
	tb_property_free_dir(tbstream_dir);
	ida_destroy(&tbstream_indices);
}
module_exit(tbstream_exit);

MODULE_AUTHOR("Alan Borzeszkowski <alan.borzeszkowski@linux.intel.com>");
MODULE_AUTHOR("Mika Westerberg <mika.westerberg@linux.intel.com>");
MODULE_DESCRIPTION("Stream data over Thunderbolt/USB4 cable");
MODULE_LICENSE("GPL");