xref: /linux/drivers/thunderbolt/stream.c (revision 1b78070aaef63512688aebfbc82365ef9d6660f1)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Stream data over Thunderbolt/USB4 cable
4  *
5  * Copyright (C) 2026, Intel Corporation
6  * Authors: Alan Borzeszkowski <alan.borzeszkowski@linux.intel.com>
7  *	    Mika Westerberg <mika.westerberg@linux.intel.com>
8  */
9 
10 #define pr_fmt(fmt) "tbstream: " fmt
11 
12 #include <linux/delay.h>
13 #include <linux/configfs.h>
14 #include <linux/file.h>
15 #include <linux/fs.h>
16 #include <linux/idr.h>
17 #include <linux/ktime.h>
18 #include <linux/miscdevice.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/poll.h>
22 #include <linux/sizes.h>
23 #include <linux/thunderbolt.h>
24 #include <linux/uaccess.h>
25 #include <linux/uio.h>
26 #include <linux/uuid.h>
27 #include <linux/wait.h>
28 
29 /*
30  * USB4STREAM - Stream data directly over Thunderbolt/USB4 cable
31  *
32  * HopIDs are configured by the user. In Linux this is done through
33  * ConfigFS. Once that is done paths are be established the first time
34  * the stream is opened. Typically the read side is opened first to make
35  * sure all the data will be received.
36  *
37  * End-to-end flow control is mandatory on both sides.
38  *
39  * Data is sent to the other side as tunneled DATA packets. All the data
40  * is owned by the user and passed as-is from the writer to the reader.
41  *
42  * Once the stream device is closed, a CLOSE packet is sent to the peer
43  * so it can take the necessary action. On Linux this typically results
44  * in EOF being returned to the reader.
45  *
46  * Tunneled packet types:
47  *
48  * +-------+---------+------------------+
49  * |  PDF  |  Type   | Payload size     |
50  * +-------+---------+------------------+
51  * |   2   | DATA    | up to 4 KiB      |
52  * |   3   | CLOSE   | up to 256 bytes  |
53  * +-------+---------+------------------+
54  *
55  * Each stream can optionally publish configuration values under its own
56  * XDomain property directory. The name of the directory is the name of
57  * the stream in question and the UUID is up to the stream. For example
58  * if the stream exposes video output then the directory name could be
59  * "video".
60  *
61  * Below values are reserved and can be used by the stream:
62  *
63  * +----------+-----------+-------------------------+
64  * |   Key    |   Type    | Contents                |
65  * +----------+-----------+-------------------------+
66  * | inhopid  | IMMEDIATE | Configured input HopID  |
67  * | outhopid | IMMEDIATE | Configured output HopID |
68  * +----------+-----------+-------------------------+
69  *
70  * It is allowed to add more stream specific properties as well if the
71  * above are not enough.
72  */
73 
74 #define TBSTREAM_DEV_RING_SIZE		256
75 #define TBSTREAM_DEV_MIN_RING_SIZE	32
76 #define TBSTREAM_DEV_MAX_RING_SIZE	4096
77 #define TBSTREAM_DEV_THROTTLING		8192
78 #define TBSTREAM_DEV_MAX_THROTTLING	16776960
79 
80 /**
81  * enum tbstream_frame_pdf - PDF numbers for tunneled frames
82  * @TBSTREAM_FRAME_START: PDF of the start of the frame
83  * @TBSTREAM_DATA: PDF of the DATA frame
84  * @TBSTREAM_CLOSE: PDF of the CLOSE frame
85  */
86 enum tbstream_frame_pdf {
87 	TBSTREAM_FRAME_START = 1,
88 	TBSTREAM_DATA,
89 	TBSTREAM_CLOSE,
90 };
91 
92 /**
93  * struct tbstream_frame - Frame submitted to/from the rings
94  * @sdev: Pointer to the stream device
95  * @page: Page holding the packet
96  * @offset: Offset inside @page if partial read is done
97  * @completed: %true if the RX frame is completed
98  * @frame: Underlying frame structure
99  */
100 struct tbstream_frame {
101 	struct tbstream_dev *sdev;
102 	struct page *page;
103 	unsigned int offset;
104 	bool completed;
105 	struct ring_frame frame;
106 };
107 
108 /**
109  * struct tbstream_ring - Stream RX/TX ring structure
110  * @ring: Pointer to the API ring
111  * @prod: Current value of producer
112  * @cons: Current value of consumer
113  * @frames: Holds the ring frames
114  */
115 struct tbstream_ring {
116 	struct tb_ring *ring;
117 	unsigned long prod;
118 	unsigned long cons;
119 	struct tbstream_frame *frames;
120 };
121 
122 /**
123  * struct tbstream_dev - Stream character device
124  * @group: ConfigFS group for this device
125  * @stream: Pointer to the stream if it is attached (%NULL otherwise)
126  * @misc: Character device used for tunneling
127  * @kref: Reference count
128  * @index: Unique identifier for the character device
129  * @in_hopid: In HopID
130  * @out_hopid: Out HopID
131  * @ring_size: Size of the rings
132  * @throttling: Interrupt throttling rate in ns
133  * @busy_poll: Instead of interrupts, busy poll the rings
134  * @users: Number of times @cdev has been opened
135  * @closed: CLOSE packet was received
136  * @removed: Userspace removed the ConfigFS group underneath.
137  * @wait: Waitqueue for open, read and write
138  * @lock: Lock protecting this structure
139  * @tx_ring: Transmit ring
140  * @rx_ring: Receive ring
141  * @list: Stream devices are linked through this
142  */
143 struct tbstream_dev {
144 	struct config_group group;
145 	struct tbstream *stream;
146 	struct miscdevice misc;
147 	struct kref kref;
148 	int index;
149 	int in_hopid;
150 	int out_hopid;
151 	unsigned int ring_size;
152 	unsigned int throttling;
153 	bool busy_poll;
154 	int users;
155 	bool closed;
156 	bool removed;
157 	wait_queue_head_t wait;
158 	struct mutex lock;
159 	struct tbstream_ring tx_ring;
160 	struct tbstream_ring rx_ring;
161 	struct list_head list;
162 };
163 
164 /**
165  * struct tbstream_group - Config group for stream
166  * @group: ConfigFS group for @stream
167  * @stream: Stream the ConfigFS group is attached to. %NULL if there is
168  *	    no stream attached.
169  * @lock: Lock protecting this structure
170  * @dev_list: List of stream devices
171  *
172  * This is the ConfigFS directory for one connection to another host.
173  * There can be several &struct stream_dev linked through @dev_list of
174  * this structure. Reference count managed through @group.
175  */
176 struct tbstream_group {
177 	struct config_group group;
178 	struct tbstream *stream;
179 	struct mutex lock;
180 	struct list_head dev_list;
181 };
182 
183 /**
184  * struct tbstream - Stream service private data
185  * @kref: Reference count
186  * @svc: Pointer to the service device
187  * @list: Streams are linked through this in @stream_list
188  *
189  * This represents the actual physical connection between two hosts.
190  */
191 struct tbstream {
192 	struct kref kref;
193 	struct tb_service *svc;
194 	struct list_head list;
195 };
196 
197 static DEFINE_IDA(tbstream_indices);
198 
199 /* Protects tbstream_list */
200 static DEFINE_MUTEX(tbstream_lock);
201 static LIST_HEAD(tbstream_list);
202 
203 /* Serializes tbstream_get()/put() */
204 static DEFINE_MUTEX(tbstream_kref_lock);
205 
206 /* Serializes tbstream_dev_get()/put() */
207 static DEFINE_MUTEX(tbstream_dev_kref_lock);
208 
209 /* Stream property directory UUID: 3a1cb984-c4d9-4469-a277-ce2fdfd11f0d */
210 static const uuid_t tbstream_dir_uuid =
211 	UUID_INIT(0x3a1cb984, 0xc4d9, 0x4469,
212 		  0xa2, 0x77, 0xce, 0x2f, 0xdf, 0xd1, 0x1f, 0x0d);
213 
214 static struct tb_property_dir *tbstream_dir;
215 
216 static void tbstream_release(struct kref *kref)
217 {
218 	struct tbstream *stream = container_of(kref, typeof(*stream), kref);
219 
220 	tb_service_put(stream->svc);
221 	kfree(stream);
222 }
223 
224 static void tbstream_put(struct tbstream *stream)
225 {
226 	if (stream) {
227 		guard(mutex)(&tbstream_kref_lock);
228 		kref_put(&stream->kref, tbstream_release);
229 	}
230 }
231 
232 static struct tbstream *tbstream_get(struct tbstream *stream)
233 {
234 	if (stream) {
235 		guard(mutex)(&tbstream_kref_lock);
236 		kref_get(&stream->kref);
237 	}
238 	return stream;
239 }
240 
241 static inline bool tbstream_valid(const struct tbstream *stream)
242 {
243 	if (stream)
244 		return !tb_service_parent(stream->svc)->is_unplugged;
245 	return false;
246 }
247 
248 static void tbstream_ring_free(struct tbstream_ring *ring)
249 {
250 	struct device *dma_dev = tb_ring_dma_device(ring->ring);
251 	enum dma_data_direction dir;
252 	int i;
253 
254 	if (ring->ring->is_tx)
255 		dir = DMA_TO_DEVICE;
256 	else
257 		dir = DMA_FROM_DEVICE;
258 
259 	for (i = 0; i < tb_ring_size(ring->ring); i++) {
260 		struct tbstream_frame *sf = &ring->frames[i];
261 
262 		if (sf->frame.buffer_phy)
263 			dma_unmap_page(dma_dev, sf->frame.buffer_phy,
264 				       TB_MAX_FRAME_SIZE, dir);
265 		sf->frame.buffer_phy = 0;
266 		if (sf->page)
267 			__free_page(sf->page);
268 		sf->page = NULL;
269 	}
270 
271 	ring->prod = 0;
272 	ring->cons = 0;
273 	kfree(ring->frames);
274 }
275 
276 static inline bool tbstream_ring_available(const struct tbstream_ring *ring)
277 {
278 	return ring->prod > ring->cons;
279 }
280 
281 static inline struct tb_xdomain *tbstream_dev_xdomain(struct tbstream_dev *sdev)
282 {
283 	if (sdev->stream)
284 		return tb_service_parent(sdev->stream->svc);
285 	return NULL;
286 }
287 
288 static void tbstream_dev_release(struct kref *kref)
289 {
290 	struct tbstream_dev *sdev = container_of(kref, struct tbstream_dev, kref);
291 
292 	if (sdev->stream) {
293 		struct tb_xdomain *xd = tbstream_dev_xdomain(sdev);
294 
295 		if (sdev->out_hopid > 0)
296 			tb_xdomain_release_out_hopid(xd, sdev->out_hopid);
297 		if (sdev->in_hopid > 0)
298 			tb_xdomain_release_in_hopid(xd, sdev->in_hopid);
299 
300 		tbstream_put(sdev->stream);
301 	}
302 	ida_free(&tbstream_indices, sdev->index);
303 	kfree(sdev->misc.name);
304 	kfree(sdev);
305 }
306 
307 static inline void tbstream_dev_put(struct tbstream_dev *sdev)
308 {
309 	guard(mutex)(&tbstream_dev_kref_lock);
310 	kref_put(&sdev->kref, tbstream_dev_release);
311 }
312 
313 static inline struct tbstream_dev *tbstream_dev_get(struct tbstream_dev *sdev)
314 {
315 	guard(mutex)(&tbstream_dev_kref_lock);
316 	kref_get(&sdev->kref);
317 	return sdev;
318 }
319 
320 static inline struct tbstream_dev *to_tbstream_dev(struct miscdevice *misc)
321 {
322 	return container_of(misc, struct tbstream_dev, misc);
323 }
324 
325 static inline int tbstream_dev_valid(const struct tbstream_dev *sdev)
326 {
327 	const struct tbstream *stream = sdev->stream;
328 
329 	if (!tbstream_valid(stream))
330 		return -ENXIO;
331 	if (sdev->in_hopid <= 0 || sdev->out_hopid <= 0)
332 		return -EINVAL;
333 	return 0;
334 }
335 
336 static inline bool tbstream_dev_removed(const struct tbstream_dev *sdev)
337 {
338 	return sdev->removed;
339 }
340 
341 static inline bool tbstream_dev_closed(const struct tbstream_dev *sdev)
342 {
343 	return sdev->closed;
344 }
345 
346 static void
347 tbstream_dev_rx_callback(struct tb_ring *ring, struct ring_frame *frame,
348 			 bool canceled)
349 {
350 	struct tbstream_frame *sf = container_of(frame, typeof(*sf), frame);
351 	struct tbstream_dev *sdev = sf->sdev;
352 
353 	if (canceled)
354 		return;
355 
356 	sf->completed = true;
357 	sdev->rx_ring.prod++;
358 
359 	if (sf->frame.flags & RING_DESC_CRC_ERROR)
360 		pr_warn("RX CRC error\n");
361 	else if (sf->frame.flags & RING_DESC_BUFFER_OVERRUN)
362 		pr_warn("RX buffer overrun\n");
363 	else
364 		wake_up_interruptible_poll(&sdev->wait, EPOLLIN | EPOLLRDNORM);
365 }
366 
367 static struct tbstream_frame *
368 tbstream_dev_completed_rx(struct tbstream_dev *sdev)
369 {
370 	struct device *dma_dev = tb_ring_dma_device(sdev->rx_ring.ring);
371 	struct tbstream_frame *sf;
372 	int index;
373 
374 	index = sdev->rx_ring.cons % tb_ring_size(sdev->rx_ring.ring);
375 	sf = &sdev->rx_ring.frames[index];
376 	if (!sf->completed)
377 		return NULL;
378 
379 	dma_sync_single_for_cpu(dma_dev, sf->frame.buffer_phy,
380 				tb_ring_frame_size(&sf->frame),
381 				DMA_FROM_DEVICE);
382 	return sf;
383 }
384 
385 static int tbstream_dev_consume_rx(struct tbstream_dev *sdev)
386 {
387 	struct device *dma_dev = tb_ring_dma_device(sdev->rx_ring.ring);
388 	struct tbstream_frame *sf;
389 	int index;
390 
391 	index = sdev->rx_ring.cons % tb_ring_size(sdev->rx_ring.ring);
392 	sdev->rx_ring.cons++;
393 
394 	sf = &sdev->rx_ring.frames[index];
395 	sf->completed = false;
396 	sf->offset = 0;
397 	sf->frame.size = 0;
398 
399 	dma_sync_single_for_device(dma_dev, sf->frame.buffer_phy,
400 				   tb_ring_frame_size(&sf->frame),
401 				   DMA_FROM_DEVICE);
402 
403 	return tb_ring_rx(sdev->rx_ring.ring, &sf->frame);
404 }
405 
406 static int tbstream_dev_alloc_rx_buffers(struct tbstream_dev *sdev)
407 {
408 	size_t ring_size = tb_ring_size(sdev->rx_ring.ring);
409 	int i;
410 
411 	sdev->rx_ring.frames = kcalloc(ring_size, sizeof(struct tbstream_frame),
412 				       GFP_KERNEL);
413 	if (!sdev->rx_ring.frames)
414 		return -ENOMEM;
415 
416 	for (i = 0; i < ring_size; i++) {
417 		struct device *dma_dev = tb_ring_dma_device(sdev->rx_ring.ring);
418 		struct tbstream_frame *sf = &sdev->rx_ring.frames[i];
419 		dma_addr_t dma_addr;
420 
421 		sf->page = alloc_page(GFP_KERNEL);
422 		if (!sf->page)
423 			return -ENOMEM;
424 
425 		dma_addr = dma_map_page(dma_dev, sf->page, 0, TB_MAX_FRAME_SIZE,
426 					DMA_FROM_DEVICE);
427 		if (dma_mapping_error(dma_dev, dma_addr)) {
428 			__free_page(sf->page);
429 			sf->page = NULL;
430 			return -ENOMEM;
431 		}
432 
433 		sf->sdev = sdev;
434 		sf->frame.callback = tbstream_dev_rx_callback;
435 		sf->frame.buffer_phy = dma_addr;
436 
437 		tb_ring_rx(sdev->rx_ring.ring, &sf->frame);
438 	}
439 
440 	sdev->rx_ring.cons = 0;
441 	sdev->rx_ring.prod = 0;
442 	return 0;
443 }
444 
445 static void
446 tbstream_dev_tx_callback(struct tb_ring *ring, struct ring_frame *frame,
447 			 bool canceled)
448 {
449 	struct tbstream_frame *sf = container_of(frame, typeof(*sf), frame);
450 	struct tbstream_dev *sdev = sf->sdev;
451 
452 	if (canceled)
453 		return;
454 
455 	sdev->tx_ring.prod++;
456 	if (sf->frame.eof == TBSTREAM_DATA)
457 		wake_up_interruptible_poll(&sdev->wait, EPOLLOUT | EPOLLWRNORM);
458 }
459 
460 static int tbstream_dev_alloc_tx_buffers(struct tbstream_dev *sdev)
461 {
462 	struct device *dma_dev = tb_ring_dma_device(sdev->tx_ring.ring);
463 	size_t ring_size = tb_ring_size(sdev->tx_ring.ring);
464 	int i;
465 
466 	sdev->tx_ring.frames = kcalloc(ring_size, sizeof(struct tbstream_frame),
467 				       GFP_KERNEL);
468 	if (!sdev->tx_ring.frames)
469 		return -ENOMEM;
470 
471 	for (i = 0; i < ring_size; i++) {
472 		struct tbstream_frame *sf = &sdev->tx_ring.frames[i];
473 		dma_addr_t dma_addr;
474 
475 		sf->page = alloc_page(GFP_KERNEL);
476 		if (!sf->page)
477 			return -ENOMEM;
478 
479 		dma_addr = dma_map_page(dma_dev, sf->page, 0, TB_MAX_FRAME_SIZE,
480 					DMA_TO_DEVICE);
481 		if (dma_mapping_error(dma_dev, dma_addr)) {
482 			__free_page(sf->page);
483 			sf->page = NULL;
484 			return -ENOMEM;
485 		}
486 
487 		sf->sdev = sdev;
488 		sf->frame.callback = tbstream_dev_tx_callback;
489 		sf->frame.buffer_phy = dma_addr;
490 		sf->frame.sof = TBSTREAM_FRAME_START;
491 	}
492 
493 	sdev->tx_ring.cons = 0;
494 	sdev->tx_ring.prod = ring_size - 1;
495 	return 0;
496 }
497 
498 static struct tbstream_frame *
499 tbstream_dev_alloc_tx(struct tbstream_dev *sdev, enum tbstream_frame_pdf pdf,
500 		      struct iov_iter *from, size_t size)
501 {
502 	struct device *dma_dev = tb_ring_dma_device(sdev->tx_ring.ring);
503 	struct tbstream_frame *sf;
504 	int index;
505 
506 	if (!tbstream_ring_available(&sdev->tx_ring))
507 		return ERR_PTR(-ENOBUFS);
508 
509 	index = sdev->tx_ring.cons % tb_ring_size(sdev->tx_ring.ring);
510 	sdev->tx_ring.cons++;
511 
512 	sf = &sdev->tx_ring.frames[index];
513 	sf->frame.size = size < TB_MAX_FRAME_SIZE ? size : 0;
514 	sf->frame.eof = pdf;
515 
516 	dma_sync_single_for_cpu(dma_dev, sf->frame.buffer_phy, size,
517 				DMA_TO_DEVICE);
518 	if (pdf == TBSTREAM_DATA) {
519 		if (copy_page_from_iter(sf->page, 0, size, from) != size) {
520 			sdev->tx_ring.cons--;
521 			return ERR_PTR(-EFAULT);
522 		}
523 	} else {
524 		memset(page_address(sf->page), 0, size);
525 	}
526 	dma_sync_single_for_device(dma_dev, sf->frame.buffer_phy, size,
527 				   DMA_TO_DEVICE);
528 	return sf;
529 }
530 
531 static int
532 tbstream_dev_send_data(struct tbstream_dev *sdev, struct iov_iter *from,
533 		       size_t size)
534 {
535 	struct tbstream_frame *sf;
536 
537 	sf = tbstream_dev_alloc_tx(sdev, TBSTREAM_DATA, from, size);
538 	if (IS_ERR(sf))
539 		return PTR_ERR(sf);
540 	return tb_ring_tx(sdev->tx_ring.ring, &sf->frame);
541 }
542 
543 static void
544 tbstream_dev_poll_ring(struct tbstream_dev *sdev, struct tbstream_ring *ring)
545 {
546 	struct ring_frame *frame;
547 
548 	if (!sdev->busy_poll)
549 		return;
550 
551 	while ((frame = tb_ring_poll(ring->ring)))
552 		frame->callback(ring->ring, frame, false);
553 }
554 
555 static int tbstream_dev_send_close(struct tbstream_dev *sdev)
556 {
557 	struct tbstream_frame *sf;
558 
559 	if (sdev->busy_poll) {
560 		/*
561 		 * When busy polling it's the write(2) path that
562 		 * advances the completions so it is possible that the
563 		 * ring is full at this point. Advance the ring here so
564 		 * that there is room for the CLOSE packet to be sent.
565 		 */
566 		ktime_t timeout = ktime_add_ms(ktime_get(), 500);
567 
568 		do {
569 			if (tbstream_ring_available(&sdev->tx_ring))
570 				break;
571 			tbstream_dev_poll_ring(sdev, &sdev->tx_ring);
572 			fsleep(15);
573 		} while (ktime_before(ktime_get(), timeout));
574 	}
575 
576 	sf = tbstream_dev_alloc_tx(sdev, TBSTREAM_CLOSE, NULL, SZ_256);
577 	if (IS_ERR(sf))
578 		return PTR_ERR(sf);
579 	return tb_ring_tx(sdev->tx_ring.ring, &sf->frame);
580 }
581 
582 static int tbstream_dev_start(struct tbstream_dev *sdev)
583 {
584 	struct tb_xdomain *xd = tbstream_dev_xdomain(sdev);
585 	unsigned int flags = RING_FLAG_FRAME | RING_FLAG_E2E;
586 	u16 sof_mask, eof_mask;
587 	struct tb_ring *ring;
588 	int ret, e2e_tx_hop;
589 
590 	if (sdev->busy_poll)
591 		flags |= RING_FLAG_NO_INTERRUPT;
592 
593 	ring = tb_ring_alloc_tx(xd->tb->nhi, -1, sdev->ring_size, flags);
594 	if (!ring)
595 		return -ENOMEM;
596 	sdev->tx_ring.ring = ring;
597 
598 	ret = tbstream_dev_alloc_tx_buffers(sdev);
599 	if (ret)
600 		goto err_free_tx;
601 
602 	e2e_tx_hop = ring->hop;
603 	sof_mask = BIT(TBSTREAM_FRAME_START);
604 	eof_mask = BIT(TBSTREAM_DATA) | BIT(TBSTREAM_CLOSE);
605 
606 	ring = tb_ring_alloc_rx(xd->tb->nhi, -1, sdev->ring_size, flags,
607 				e2e_tx_hop, sof_mask, eof_mask, NULL, NULL);
608 	if (!ring) {
609 		ret = -ENOMEM;
610 		goto err_free_tx_buffers;
611 	}
612 	sdev->rx_ring.ring = ring;
613 
614 	ret = tb_xdomain_enable_paths(xd, sdev->out_hopid,
615 				     sdev->tx_ring.ring->hop,
616 				     sdev->in_hopid,
617 				     sdev->rx_ring.ring->hop);
618 	if (ret)
619 		goto err_free_rx;
620 
621 	tb_ring_throttling(sdev->tx_ring.ring, sdev->throttling);
622 	tb_ring_throttling(sdev->rx_ring.ring, sdev->throttling);
623 
624 	tb_ring_start(sdev->tx_ring.ring);
625 	tb_ring_start(sdev->rx_ring.ring);
626 
627 	ret = tbstream_dev_alloc_rx_buffers(sdev);
628 	if (ret)
629 		goto err_stop;
630 	return 0;
631 
632 err_stop:
633 	tb_ring_stop(sdev->rx_ring.ring);
634 	tb_ring_stop(sdev->tx_ring.ring);
635 err_free_rx:
636 	tb_ring_free(sdev->rx_ring.ring);
637 err_free_tx_buffers:
638 	tbstream_ring_free(&sdev->tx_ring);
639 err_free_tx:
640 	tb_ring_free(sdev->tx_ring.ring);
641 
642 	return ret;
643 }
644 
645 static bool tbstream_dev_tx_drained(const struct tbstream_dev *sdev)
646 {
647 	const struct tbstream_ring *ring = &sdev->tx_ring;
648 
649 	/*
650 	 * Everything is completed when number of free TX slots is back
651 	 * to the maximum.
652 	 */
653 	return ring->prod - ring->cons == tb_ring_size(ring->ring) - 1;
654 }
655 
656 static void tbstream_dev_stop(struct tbstream_dev *sdev)
657 {
658 	struct tb_xdomain *xd;
659 
660 	if (sdev->busy_poll) {
661 		/*
662 		 * When busy polling we must advance the ring ourselves
663 		 * to push all outstanding frames on the wire.
664 		 */
665 		ktime_t timeout = ktime_add_ms(ktime_get(), 500);
666 
667 		do {
668 			if (tbstream_dev_tx_drained(sdev))
669 				break;
670 			tbstream_dev_poll_ring(sdev, &sdev->tx_ring);
671 			fsleep(15);
672 		} while (ktime_before(ktime_get(), timeout));
673 
674 		tb_ring_stop(sdev->tx_ring.ring);
675 		tb_ring_stop(sdev->rx_ring.ring);
676 	} else {
677 		tb_ring_flush(sdev->tx_ring.ring, 500);
678 		tb_ring_stop(sdev->tx_ring.ring);
679 		tb_ring_flush(sdev->rx_ring.ring, 500);
680 		tb_ring_stop(sdev->rx_ring.ring);
681 	}
682 
683 	xd = tbstream_dev_xdomain(sdev);
684 	if (xd) {
685 		tb_xdomain_disable_paths(xd, sdev->out_hopid,
686 					 sdev->tx_ring.ring->hop,
687 					 sdev->in_hopid,
688 					 sdev->rx_ring.ring->hop);
689 	}
690 
691 	tbstream_ring_free(&sdev->rx_ring);
692 	tb_ring_free(sdev->rx_ring.ring);
693 	sdev->rx_ring.ring = NULL;
694 	tbstream_ring_free(&sdev->tx_ring);
695 	tb_ring_free(sdev->tx_ring.ring);
696 	sdev->tx_ring.ring = NULL;
697 }
698 
699 /* Use only with read_iter/write_iter() to handle nowait */
700 static int tbstream_dev_lock(struct tbstream_dev *sdev, bool nowait)
701 {
702 	if (nowait) {
703 		if (!mutex_trylock(&sdev->lock))
704 			return -EAGAIN;
705 	} else {
706 		if (mutex_lock_interruptible(&sdev->lock))
707 			return -ERESTARTSYS;
708 	}
709 	return 0;
710 }
711 
712 static ssize_t
713 tbstream_dev_fops_read_iter(struct kiocb *kiocb, struct iov_iter *to)
714 {
715 	struct file *file = kiocb->ki_filp;
716 	bool nowait = file->f_flags & O_NONBLOCK || kiocb->ki_flags & IOCB_NOWAIT;
717 	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);
718 	size_t nbytes;
719 	int ret;
720 
721 	ret = tbstream_dev_valid(sdev);
722 	if (ret)
723 		return ret;
724 
725 	ret = tbstream_dev_lock(sdev, nowait);
726 	if (ret)
727 		return ret;
728 
729 	for (;;) {
730 		/* When busy polling, advance any completions manually */
731 		tbstream_dev_poll_ring(sdev, &sdev->rx_ring);
732 
733 		ret = tbstream_dev_valid(sdev);
734 		if (ret) {
735 			mutex_unlock(&sdev->lock);
736 			return ret;
737 		}
738 
739 		if (tbstream_dev_closed(sdev) || tbstream_dev_removed(sdev)) {
740 			mutex_unlock(&sdev->lock);
741 			return 0;
742 		}
743 
744 		if (tbstream_ring_available(&sdev->rx_ring))
745 			break;
746 
747 		mutex_unlock(&sdev->lock);
748 
749 		if (nowait)
750 			return -EAGAIN;
751 
752 		if (sdev->busy_poll) {
753 			if (signal_pending(current))
754 				return -ERESTARTSYS;
755 			cond_resched();
756 		} else {
757 			ret = wait_event_interruptible(sdev->wait,
758 					tbstream_ring_available(&sdev->rx_ring) ||
759 					tbstream_dev_valid(sdev) != 0 ||
760 					tbstream_dev_closed(sdev) ||
761 					tbstream_dev_removed(sdev));
762 			if (ret)
763 				return ret;
764 		}
765 
766 		ret = tbstream_dev_lock(sdev, nowait);
767 		if (ret)
768 			return ret;
769 	}
770 
771 	nbytes = 0;
772 	while (iov_iter_count(to)) {
773 		struct tbstream_frame *sf;
774 		size_t size, sf_size;
775 
776 		sf = tbstream_dev_completed_rx(sdev);
777 		if (!sf)
778 			break;
779 		/*
780 		 * CLOSE tunneled packet. If userspace already read
781 		 * something then we stop processing now and return
782 		 * those bytes. Next time the first frame will be CLOSE
783 		 * in which case we return EOF to the user.
784 		 */
785 		if (sf->frame.eof == TBSTREAM_CLOSE) {
786 			if (!nbytes) {
787 				tbstream_dev_consume_rx(sdev);
788 				sdev->closed = true;
789 			}
790 			break;
791 		}
792 
793 		sf_size = tb_ring_frame_size(&sf->frame);
794 		size = min(iov_iter_count(to), sf_size);
795 
796 		if (copy_page_to_iter(sf->page, sf->offset, size, to) != size) {
797 			ret = -EFAULT;
798 			break;
799 		}
800 
801 		/*
802 		 * If not all data from the frame is read so leave it in
803 		 * place and update the offset accordingly so next read
804 		 * gets the rest.
805 		 */
806 		if (size < sf_size) {
807 			sf->offset += size;
808 			sf->frame.size = sf_size - size;
809 		} else {
810 			ret = tbstream_dev_consume_rx(sdev);
811 			if (ret)
812 				break;
813 		}
814 
815 		nbytes += size;
816 	}
817 
818 	mutex_unlock(&sdev->lock);
819 	if (ret)
820 		return ret;
821 	return nbytes;
822 }
823 
824 static ssize_t
825 tbstream_dev_fops_write_iter(struct kiocb *kiocb, struct iov_iter *from)
826 {
827 	struct file *file = kiocb->ki_filp;
828 	bool nowait = file->f_flags & O_NONBLOCK || kiocb->ki_flags & IOCB_NOWAIT;
829 	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);
830 	size_t nbytes;
831 	int ret;
832 
833 	ret = tbstream_dev_valid(sdev);
834 	if (ret)
835 		return ret;
836 
837 	ret = tbstream_dev_lock(sdev, nowait);
838 	if (ret)
839 		return ret;
840 
841 	for (;;) {
842 		tbstream_dev_poll_ring(sdev, &sdev->tx_ring);
843 
844 		ret = tbstream_dev_valid(sdev);
845 		if (ret) {
846 			mutex_unlock(&sdev->lock);
847 			return ret;
848 		}
849 
850 		if (tbstream_dev_closed(sdev) || tbstream_dev_removed(sdev)) {
851 			mutex_unlock(&sdev->lock);
852 			return -ENXIO;
853 		}
854 
855 		if (tbstream_ring_available(&sdev->tx_ring))
856 			break;
857 
858 		mutex_unlock(&sdev->lock);
859 
860 		if (nowait)
861 			return -EAGAIN;
862 
863 		if (sdev->busy_poll) {
864 			if (signal_pending(current))
865 				return -ERESTARTSYS;
866 			cond_resched();
867 		} else {
868 			ret = wait_event_interruptible(sdev->wait,
869 					tbstream_ring_available(&sdev->tx_ring) ||
870 					tbstream_dev_valid(sdev) != 0 ||
871 					tbstream_dev_closed(sdev) ||
872 					tbstream_dev_removed(sdev));
873 			if (ret)
874 				return ret;
875 		}
876 
877 		ret = tbstream_dev_lock(sdev, nowait);
878 		if (ret)
879 			return ret;
880 	}
881 
882 	nbytes = 0;
883 	while (iov_iter_count(from)) {
884 		size_t size;
885 
886 		size = min(iov_iter_count(from), TB_MAX_FRAME_SIZE);
887 		ret = tbstream_dev_send_data(sdev, from, size);
888 		if (ret) {
889 			/*
890 			 * If there are no more buffers we are done for
891 			 * this write.
892 			 */
893 			if (ret == -ENOBUFS)
894 				ret = 0;
895 			break;
896 		}
897 
898 		nbytes += size;
899 	}
900 
901 	mutex_unlock(&sdev->lock);
902 	if (ret)
903 		return ret;
904 	return nbytes;
905 }
906 
907 static __poll_t
908 tbstream_dev_fops_poll(struct file *file, struct poll_table_struct *wait)
909 {
910 	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);
911 	__poll_t mask = 0;
912 
913 	/*
914 	 * Without interrupts there is nothing that can wake us up so
915 	 * return failure instead.
916 	 */
917 	if (sdev->busy_poll)
918 		return EPOLLERR;
919 
920 	poll_wait(file, &sdev->wait, wait);
921 	guard(mutex)(&sdev->lock);
922 	if (tbstream_dev_valid(sdev) != 0) {
923 		mask |= EPOLLHUP | EPOLLERR;
924 	} else {
925 		if (tbstream_ring_available(&sdev->tx_ring))
926 			mask |= EPOLLOUT | EPOLLWRNORM;
927 		if (tbstream_ring_available(&sdev->rx_ring))
928 			mask |= EPOLLIN | EPOLLRDNORM;
929 	}
930 	return mask;
931 }
932 
933 static int tbstream_dev_fops_open(struct inode *inode, struct file *file)
934 {
935 	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);
936 	int ret;
937 
938 	tbstream_dev_get(sdev);
939 
940 	if (mutex_lock_interruptible(&sdev->lock)) {
941 		tbstream_dev_put(sdev);
942 		return -ERESTARTSYS;
943 	}
944 
945 	/*
946 	 * If there is no stream attached yet, block until it appears
947 	 * unless this is opened in non-blocking mode.
948 	 */
949 	while ((ret = tbstream_dev_valid(sdev))) {
950 		mutex_unlock(&sdev->lock);
951 
952 		if (ret != -ENXIO || (file->f_flags & O_NONBLOCK))
953 			goto err_put;
954 
955 		ret = wait_event_interruptible(sdev->wait,
956 				tbstream_dev_valid(sdev) == 0 ||
957 				tbstream_dev_removed(sdev));
958 		if (ret)
959 			goto err_put;
960 
961 		if (tbstream_dev_removed(sdev)) {
962 			ret = -ENXIO;
963 			goto err_put;
964 		}
965 
966 		if (mutex_lock_interruptible(&sdev->lock)) {
967 			ret = -ERESTARTSYS;
968 			goto err_put;
969 		}
970 	}
971 
972 	/* Only on first open we allocate rings and enable paths */
973 	if (!sdev->users++) {
974 		ret = tbstream_dev_start(sdev);
975 		if (ret) {
976 			sdev->users--;
977 			goto err_unlock;
978 		}
979 		sdev->closed = false;
980 	}
981 
982 	mutex_unlock(&sdev->lock);
983 	return 0;
984 
985 err_unlock:
986 	mutex_unlock(&sdev->lock);
987 err_put:
988 	tbstream_dev_put(sdev);
989 
990 	return ret;
991 }
992 
993 static int tbstream_dev_fops_release(struct inode *inode, struct file *file)
994 {
995 	struct tbstream_dev *sdev = to_tbstream_dev(file->private_data);
996 
997 	mutex_lock(&sdev->lock);
998 	if (--sdev->users == 0) {
999 		/*
1000 		 * Send CLOSE tunneled packet to notify the other end
1001 		 * that we are closing the file. We do this twice if the
1002 		 * first one fails.
1003 		 */
1004 		tbstream_dev_send_close(sdev);
1005 		tbstream_dev_stop(sdev);
1006 	}
1007 	mutex_unlock(&sdev->lock);
1008 
1009 	tbstream_dev_put(sdev);
1010 	return 0;
1011 }
1012 
1013 static const struct file_operations tbstream_dev_fops = {
1014 	.owner = THIS_MODULE,
1015 	.llseek = noop_llseek,
1016 	.read_iter = tbstream_dev_fops_read_iter,
1017 	.write_iter = tbstream_dev_fops_write_iter,
1018 	.poll = tbstream_dev_fops_poll,
1019 	.open = tbstream_dev_fops_open,
1020 	.release = tbstream_dev_fops_release,
1021 };
1022 
1023 static inline struct tbstream_dev *
1024 tbstream_dev_from_group(struct config_group *group)
1025 {
1026 	return container_of(group, struct tbstream_dev, group);
1027 }
1028 
1029 static ssize_t tbstream_dev_busy_poll_show(struct config_item *item, char *buf)
1030 {
1031 	struct config_group *group = to_config_group(item);
1032 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1033 
1034 	return sysfs_emit(buf, "%u\n", sdev->busy_poll);
1035 }
1036 
1037 static ssize_t
1038 tbstream_dev_busy_poll_store(struct config_item *item, const char *buf,
1039 			     size_t count)
1040 {
1041 	struct config_group *group = to_config_group(item);
1042 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1043 	bool busy_poll;
1044 	int ret;
1045 
1046 	ret = kstrtobool(buf, &busy_poll);
1047 	if (ret)
1048 		return ret;
1049 
1050 	guard(mutex)(&sdev->lock);
1051 	if (sdev->users)
1052 		return -EBUSY;
1053 	sdev->busy_poll = busy_poll;
1054 	return count;
1055 }
1056 CONFIGFS_ATTR(tbstream_dev_, busy_poll);
1057 
1058 static ssize_t tbstream_dev_index_show(struct config_item *item, char *buf)
1059 {
1060 	struct config_group *group = to_config_group(item);
1061 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1062 
1063 	return sysfs_emit(buf, "%d\n", sdev->index);
1064 }
1065 CONFIGFS_ATTR_RO(tbstream_dev_, index);
1066 
1067 static ssize_t tbstream_dev_in_hopid_show(struct config_item *item, char *buf)
1068 {
1069 	struct config_group *group = to_config_group(item);
1070 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1071 
1072 	return sysfs_emit(buf, "%d\n", sdev->in_hopid);
1073 }
1074 
1075 /* svc->lock must be held */
1076 static void service_remove_properties(struct tb_service *svc, const char *name)
1077 {
1078 	struct tb_property *p;
1079 
1080 	if (!svc->local_properties)
1081 		return;
1082 
1083 	p = tb_property_find(svc->local_properties, name,
1084 			     TB_PROPERTY_TYPE_DIRECTORY);
1085 	if (p) {
1086 		tb_property_free_dir(p->value.dir);
1087 		tb_property_remove(p);
1088 
1089 		dev_dbg(&svc->dev, "removed local directory %s\n", name);
1090 
1091 		/*
1092 		 * Is the service directory empty already? If it is then
1093 		 * we can release it as well.
1094 		 */
1095 		tb_property_for_each(svc->local_properties, p) {
1096 			if (p->type == TB_PROPERTY_TYPE_DIRECTORY)
1097 				return;
1098 		}
1099 
1100 		tb_property_free_dir(svc->local_properties);
1101 		svc->local_properties = NULL;
1102 	}
1103 }
1104 
1105 static int service_update_properties(struct tb_service *svc, const char *name,
1106 				     int in_hopid, int out_hopid)
1107 {
1108 	struct tb_property_dir *dir;
1109 	struct tb_property *p;
1110 
1111 	guard(mutex)(&svc->lock);
1112 
1113 	if (in_hopid < 8 || out_hopid < 8) {
1114 		service_remove_properties(svc, name);
1115 		return 0;
1116 	}
1117 
1118 	if (!svc->local_properties) {
1119 		/*
1120 		 * Add the service directory first time we
1121 		 * populate the entries.
1122 		 */
1123 		svc->local_properties = tb_property_copy_dir(tbstream_dir);
1124 		if (!svc->local_properties)
1125 			return -ENOMEM;
1126 	}
1127 
1128 	p = tb_property_find(svc->local_properties, name,
1129 			     TB_PROPERTY_TYPE_DIRECTORY);
1130 	if (p) {
1131 		dir = p->value.dir;
1132 
1133 		p = tb_property_find(dir, "inhopid", TB_PROPERTY_TYPE_VALUE);
1134 		if (p && p->value.immediate != in_hopid)
1135 			p->value.immediate = in_hopid;
1136 		p = tb_property_find(dir, "outhopid", TB_PROPERTY_TYPE_VALUE);
1137 		if (p && p->value.immediate != out_hopid)
1138 			p->value.immediate = out_hopid;
1139 
1140 		dev_dbg(&svc->dev,
1141 			"updated local directory %s: in HopID %d, out HopID %d\n",
1142 			name, in_hopid, out_hopid);
1143 	} else {
1144 		uuid_t uuid;
1145 		int ret;
1146 
1147 		uuid_gen(&uuid);
1148 		dir = tb_property_create_dir(&uuid);
1149 		if (!dir)
1150 			return -ENOMEM;
1151 
1152 		tb_property_add_immediate(dir, "inhopid", in_hopid);
1153 		tb_property_add_immediate(dir, "outhopid", out_hopid);
1154 
1155 		ret = tb_property_add_dir(svc->local_properties, name, dir);
1156 		if (ret) {
1157 			tb_property_free_dir(dir);
1158 			return ret;
1159 		}
1160 
1161 		dev_dbg(&svc->dev,
1162 			"added local directory %s: in HopID %d, out HopID %d\n",
1163 			name, in_hopid, out_hopid);
1164 	}
1165 
1166 	return 0;
1167 }
1168 
1169 static int tbstream_dev_update_properties(struct tbstream_dev *sdev)
1170 {
1171 	struct tbstream *stream;
1172 	int ret;
1173 
1174 	stream = tbstream_get(sdev->stream);
1175 	if (!stream)
1176 		return 0;
1177 
1178 	ret = service_update_properties(stream->svc,
1179 					config_item_name(&sdev->group.cg_item),
1180 					sdev->in_hopid, sdev->out_hopid);
1181 	if (!ret)
1182 		tb_service_properties_changed(stream->svc);
1183 
1184 	tbstream_put(stream);
1185 	return ret;
1186 }
1187 
1188 static int tbstream_dev_alloc_in_hopid(struct tbstream_dev *sdev, int hopid)
1189 {
1190 	struct tb_xdomain *xd = tbstream_dev_xdomain(sdev);
1191 	int ret;
1192 
1193 	if (sdev->in_hopid > 0 && sdev->in_hopid != hopid)
1194 		tb_xdomain_release_in_hopid(xd, sdev->in_hopid);
1195 	if (!hopid) {
1196 		sdev->in_hopid = hopid;
1197 		return 0;
1198 	}
1199 	ret = tb_xdomain_alloc_in_hopid(xd, hopid);
1200 	if (ret < 0)
1201 		return ret;
1202 	/*
1203 	 * If specific HopID was asked by the user and we did not get
1204 	 * that one then release and return error instead.
1205 	 */
1206 	if (hopid > 0 && hopid != ret) {
1207 		tb_xdomain_release_in_hopid(xd, ret);
1208 		return -EBUSY;
1209 	}
1210 	sdev->in_hopid = ret;
1211 	return 0;
1212 }
1213 
1214 static int tbstream_dev_alloc_out_hopid(struct tbstream_dev *sdev, int hopid)
1215 {
1216 	struct tb_xdomain *xd = tbstream_dev_xdomain(sdev);
1217 	int ret;
1218 
1219 	if (sdev->out_hopid > 0 && sdev->out_hopid != hopid)
1220 		tb_xdomain_release_out_hopid(xd, sdev->out_hopid);
1221 	if (!hopid) {
1222 		sdev->out_hopid = hopid;
1223 		return 0;
1224 	}
1225 	ret = tb_xdomain_alloc_out_hopid(xd, hopid);
1226 	if (ret < 0)
1227 		return ret;
1228 	if (hopid > 0 && hopid != ret) {
1229 		tb_xdomain_release_out_hopid(xd, ret);
1230 		return -EBUSY;
1231 	}
1232 	sdev->out_hopid = ret;
1233 	return 0;
1234 }
1235 
1236 static ssize_t
1237 tbstream_dev_in_hopid_store(struct config_item *item, const char *buf,
1238 			    size_t count)
1239 {
1240 	struct config_group *group = to_config_group(item);
1241 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1242 	int ret, in_hopid;
1243 
1244 	ret = kstrtoint(buf, 0, &in_hopid);
1245 	if (ret)
1246 		return ret;
1247 
1248 	guard(mutex)(&sdev->lock);
1249 	if (sdev->users)
1250 		return -EBUSY;
1251 	if (sdev->stream) {
1252 		ret = tbstream_dev_alloc_in_hopid(sdev, in_hopid);
1253 		if (ret)
1254 			return ret;
1255 		ret = tbstream_dev_update_properties(sdev);
1256 	} else {
1257 		sdev->in_hopid = in_hopid;
1258 	}
1259 	return ret ? ret : count;
1260 }
1261 CONFIGFS_ATTR(tbstream_dev_, in_hopid);
1262 
1263 static ssize_t tbstream_dev_out_hopid_show(struct config_item *item, char *buf)
1264 {
1265 	struct config_group *group = to_config_group(item);
1266 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1267 
1268 	return sysfs_emit(buf, "%d\n", sdev->out_hopid);
1269 }
1270 
1271 static ssize_t
1272 tbstream_dev_out_hopid_store(struct config_item *item, const char *buf,
1273 			     size_t count)
1274 {
1275 	struct config_group *group = to_config_group(item);
1276 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1277 	int ret, out_hopid;
1278 
1279 	ret = kstrtoint(buf, 0, &out_hopid);
1280 	if (ret)
1281 		return ret;
1282 
1283 	guard(mutex)(&sdev->lock);
1284 	if (sdev->users)
1285 		return -EBUSY;
1286 	if (sdev->stream) {
1287 		ret = tbstream_dev_alloc_out_hopid(sdev, out_hopid);
1288 		if (ret)
1289 			return ret;
1290 		ret = tbstream_dev_update_properties(sdev);
1291 	} else {
1292 		sdev->out_hopid = out_hopid;
1293 	}
1294 	return ret ? ret : count;
1295 }
1296 CONFIGFS_ATTR(tbstream_dev_, out_hopid);
1297 
1298 static ssize_t tbstream_dev_ring_size_show(struct config_item *item, char *buf)
1299 {
1300 	struct config_group *group = to_config_group(item);
1301 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1302 
1303 	return sysfs_emit(buf, "%u\n", sdev->ring_size);
1304 }
1305 
1306 static ssize_t
1307 tbstream_dev_ring_size_store(struct config_item *item, const char *buf,
1308 			     size_t count)
1309 {
1310 	struct config_group *group = to_config_group(item);
1311 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1312 	unsigned int ring_size;
1313 	int ret;
1314 
1315 	ret = kstrtouint(buf, 0, &ring_size);
1316 	if (ret)
1317 		return ret;
1318 
1319 	if (ring_size < TBSTREAM_DEV_MIN_RING_SIZE ||
1320 	    ring_size > TBSTREAM_DEV_MAX_RING_SIZE)
1321 		return -EINVAL;
1322 
1323 	guard(mutex)(&sdev->lock);
1324 	if (sdev->users)
1325 		return -EBUSY;
1326 	sdev->ring_size = ring_size;
1327 	return count;
1328 }
1329 CONFIGFS_ATTR(tbstream_dev_, ring_size);
1330 
1331 static ssize_t tbstream_dev_throttling_show(struct config_item *item, char *buf)
1332 {
1333 	struct config_group *group = to_config_group(item);
1334 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1335 
1336 	return sysfs_emit(buf, "%u\n", sdev->throttling);
1337 }
1338 
1339 static ssize_t
1340 tbstream_dev_throttling_store(struct config_item *item, const char *buf,
1341 			      size_t count)
1342 {
1343 	struct config_group *group = to_config_group(item);
1344 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1345 	unsigned int throttling;
1346 	int ret;
1347 
1348 	ret = kstrtouint(buf, 0, &throttling);
1349 	if (ret)
1350 		return ret;
1351 
1352 	if (throttling > TBSTREAM_DEV_MAX_THROTTLING)
1353 		return -EINVAL;
1354 
1355 	guard(mutex)(&sdev->lock);
1356 	if (sdev->users)
1357 		return -EBUSY;
1358 	sdev->throttling = throttling;
1359 	return count;
1360 }
1361 CONFIGFS_ATTR(tbstream_dev_, throttling);
1362 
1363 static struct configfs_attribute *tbstream_dev_attrs[] = {
1364 	&tbstream_dev_attr_busy_poll,
1365 	&tbstream_dev_attr_index,
1366 	&tbstream_dev_attr_in_hopid,
1367 	&tbstream_dev_attr_out_hopid,
1368 	&tbstream_dev_attr_ring_size,
1369 	&tbstream_dev_attr_throttling,
1370 	NULL,
1371 };
1372 
1373 static void tbstream_dev_item_release(struct config_item *item)
1374 {
1375 	struct config_group *group = to_config_group(item);
1376 	struct tbstream_dev *sdev = tbstream_dev_from_group(group);
1377 
1378 	misc_deregister(&sdev->misc);
1379 	tbstream_dev_put(sdev);
1380 }
1381 
1382 static struct configfs_item_operations tbstream_dev_item_ops = {
1383 	.release = tbstream_dev_item_release,
1384 };
1385 
1386 static const struct config_item_type tbstream_dev_type = {
1387 	.ct_owner = THIS_MODULE,
1388 	.ct_item_ops = &tbstream_dev_item_ops,
1389 	.ct_attrs = tbstream_dev_attrs,
1390 };
1391 
1392 static void service_get_hopids(struct tb_service *svc, const char *name,
1393 			       int *in_hopid, int *out_hopid)
1394 {
1395 	struct tb_property_dir *dir;
1396 	struct tb_property *p;
1397 
1398 	guard(mutex)(&svc->lock);
1399 
1400 	/* See if we have directory entry with the matching name */
1401 	p = tb_property_find(svc->remote_properties, name,
1402 			     TB_PROPERTY_TYPE_DIRECTORY);
1403 	if (!p)
1404 		return;
1405 
1406 	dir = p->value.dir;
1407 
1408 	/*
1409 	 * We need to reverse the HopIDs on our end so that in becomes
1410 	 * out and vice versa.
1411 	 */
1412 	p = tb_property_find(dir, "inhopid", TB_PROPERTY_TYPE_VALUE);
1413 	if (p && p->value.immediate >= 8)
1414 		*out_hopid = p->value.immediate;
1415 	p = tb_property_find(dir, "outhopid", TB_PROPERTY_TYPE_VALUE);
1416 	if (p && p->value.immediate >= 8)
1417 		*in_hopid = p->value.immediate;
1418 }
1419 
1420 static void
1421 tbstream_dev_attach_stream(struct tbstream_dev *sdev, struct tbstream_group *sg)
1422 {
1423 	const char *name = config_item_name(&sdev->group.cg_item);
1424 	struct tbstream *stream;
1425 
1426 	stream = tbstream_get(sg->stream);
1427 	if (!stream)
1428 		return;
1429 
1430 	scoped_guard(mutex, &sdev->lock) {
1431 		sdev->stream = stream;
1432 		/*
1433 		 * If there is no existing configuration (or automatic
1434 		 * configuration is being used) check if the other side
1435 		 * has configuration for this and use it.
1436 		 */
1437 		if (sdev->in_hopid <= 0 && sdev->out_hopid <= 0)
1438 			service_get_hopids(stream->svc, name, &sdev->in_hopid,
1439 					   &sdev->out_hopid);
1440 		if (sdev->in_hopid)
1441 			tbstream_dev_alloc_in_hopid(sdev, sdev->in_hopid);
1442 		if (sdev->out_hopid)
1443 			tbstream_dev_alloc_out_hopid(sdev, sdev->out_hopid);
1444 	}
1445 
1446 	service_update_properties(stream->svc, name, sdev->in_hopid,
1447 				  sdev->out_hopid);
1448 	tb_service_properties_changed(stream->svc);
1449 
1450 	/* Notify any openerers that the stream is now attached */
1451 	wake_up_interruptible(&sdev->wait);
1452 }
1453 
1454 static void tbstream_dev_detach_stream(struct tbstream_dev *sdev)
1455 {
1456 	const char *name = config_item_name(&sdev->group.cg_item);
1457 	struct tbstream *stream;
1458 	struct tb_xdomain *xd;
1459 
1460 	scoped_guard(mutex, &sdev->lock) {
1461 		stream = sdev->stream;
1462 		if (!stream)
1463 			return;
1464 		sdev->stream = NULL;
1465 		xd = tb_service_parent(stream->svc);
1466 		if (sdev->out_hopid > 0)
1467 			tb_xdomain_release_out_hopid(xd, sdev->out_hopid);
1468 		if (sdev->in_hopid > 0)
1469 			tb_xdomain_release_in_hopid(xd, sdev->in_hopid);
1470 	}
1471 
1472 	service_update_properties(stream->svc, name, 0, 0);
1473 	tb_service_properties_changed(stream->svc);
1474 
1475 	tbstream_put(stream);
1476 
1477 	/* Notify any task that the stream is not valid anymore */
1478 	wake_up_interruptible_poll(&sdev->wait, EPOLLHUP | EPOLLERR);
1479 }
1480 
1481 static inline struct tbstream_group *
1482 to_tbstream_group(struct config_group *group)
1483 {
1484 	return container_of(group, struct tbstream_group, group);
1485 }
1486 
1487 static struct config_group *
1488 tbstream_dev_make_group(struct config_group *group, const char *name)
1489 {
1490 	struct tbstream_group *sg = to_tbstream_group(group);
1491 	struct tbstream_dev *sdev;
1492 	int ret, index;
1493 
1494 	/*
1495 	 * We want the names to be suitable for passing as property
1496 	 * directory names.
1497 	 */
1498 	if (strlen(name) > TB_PROPERTY_KEY_SIZE)
1499 		return ERR_PTR(-ENAMETOOLONG);
1500 
1501 	sdev = kzalloc_obj(*sdev, GFP_KERNEL);
1502 	if (!sdev)
1503 		return ERR_PTR(-ENOMEM);
1504 
1505 	index = ida_alloc(&tbstream_indices, GFP_KERNEL);
1506 	if (index < 0) {
1507 		kfree(sdev);
1508 		return ERR_PTR(index);
1509 	}
1510 
1511 	sdev->index = index;
1512 	sdev->ring_size = TBSTREAM_DEV_RING_SIZE;
1513 	sdev->throttling = TBSTREAM_DEV_THROTTLING;
1514 	mutex_init(&sdev->lock);
1515 	init_waitqueue_head(&sdev->wait);
1516 	INIT_LIST_HEAD(&sdev->list);
1517 	/* This point forward tbstream_dev_put() must be used to release sdev */
1518 	kref_init(&sdev->kref);
1519 
1520 	config_group_init_type_name(&sdev->group, name, &tbstream_dev_type);
1521 
1522 	scoped_guard(mutex, &sg->lock)
1523 		list_add_tail(&sdev->list, &sg->dev_list);
1524 
1525 	tbstream_dev_attach_stream(sdev, sg);
1526 
1527 	sdev->misc.name = kasprintf(GFP_KERNEL, "tbstream%d", index);
1528 	sdev->misc.minor = MISC_DYNAMIC_MINOR;
1529 	sdev->misc.fops = &tbstream_dev_fops;
1530 
1531 	ret = misc_register(&sdev->misc);
1532 	if (ret) {
1533 		tbstream_dev_detach_stream(sdev);
1534 		scoped_guard(mutex, &sg->lock)
1535 			list_del(&sdev->list);
1536 		/* Calls tbstream_dev_put() */
1537 		config_group_put(&sdev->group);
1538 		return ERR_PTR(ret);
1539 	}
1540 
1541 	return &sdev->group;
1542 }
1543 
1544 static void
1545 tbstream_dev_drop_item(struct config_group *group, struct config_item *item)
1546 {
1547 	struct config_group *sdev_group = to_config_group(item);
1548 	struct tbstream_dev *sdev = tbstream_dev_from_group(sdev_group);
1549 	struct tbstream_group *sg = to_tbstream_group(group);
1550 
1551 	scoped_guard(mutex, &sg->lock)
1552 		list_del(&sdev->list);
1553 	/* Notify any task that the underlying group was removed  */
1554 	sdev->removed = true;
1555 	wake_up_interruptible_poll(&sdev->wait, EPOLLHUP | EPOLLERR);
1556 	config_item_put(item);
1557 }
1558 
1559 static struct configfs_group_operations tbstream_dev_group_ops = {
1560 	.make_group = tbstream_dev_make_group,
1561 	.drop_item = tbstream_dev_drop_item,
1562 };
1563 
1564 static void tbstream_item_release(struct config_item *item)
1565 {
1566 	struct config_group *group = to_config_group(item);
1567 	struct tbstream_group *sg = to_tbstream_group(group);
1568 
1569 	tbstream_put(sg->stream);
1570 	kfree(sg);
1571 }
1572 
1573 static struct configfs_item_operations tbstream_item_ops = {
1574 	.release = tbstream_item_release,
1575 };
1576 
1577 static const struct config_item_type tbstream_dev_group_type = {
1578 	.ct_owner = THIS_MODULE,
1579 	.ct_group_ops = &tbstream_dev_group_ops,
1580 	.ct_item_ops = &tbstream_item_ops,
1581 };
1582 
1583 static struct config_group *
1584 tbstream_make_group(struct config_group *group, const char *name)
1585 {
1586 	struct tbstream_group *sg;
1587 	struct tbstream *stream;
1588 	int domain, index;
1589 	u64 route;
1590 
1591 	/* Make sure the format is correct */
1592 	if (sscanf(name, "%u-%llx.%u", &domain, &route, &index) != 3)
1593 		return ERR_PTR(-EINVAL);
1594 
1595 	sg = kzalloc_obj(*sg, GFP_KERNEL);
1596 	if (!sg)
1597 		return ERR_PTR(-ENOMEM);
1598 
1599 	mutex_init(&sg->lock);
1600 	INIT_LIST_HEAD(&sg->dev_list);
1601 
1602 	guard(mutex)(&tbstream_lock);
1603 	list_for_each_entry(stream, &tbstream_list, list) {
1604 		tbstream_get(stream);
1605 		if (sysfs_streq(name, dev_name(&stream->svc->dev))) {
1606 			sg->stream = stream;
1607 			break;
1608 		}
1609 		tbstream_put(stream);
1610 	}
1611 
1612 	config_group_init_type_name(&sg->group, name, &tbstream_dev_group_type);
1613 	return &sg->group;
1614 }
1615 
1616 static struct configfs_group_operations tbstream_group_ops = {
1617 	.make_group = tbstream_make_group,
1618 };
1619 
1620 static const struct config_item_type tbstream_group_type = {
1621 	.ct_owner = THIS_MODULE,
1622 	.ct_group_ops = &tbstream_group_ops,
1623 };
1624 
1625 static struct config_group tbstream_group = {
1626 	.cg_item = {
1627 		.ci_namebuf = "stream",
1628 		.ci_type = &tbstream_group_type,
1629 	},
1630 };
1631 
1632 /* Returns reference count increased */
1633 static struct tbstream_group *tbstream_group_find(struct tbstream *stream)
1634 {
1635 	const char *name = dev_name(&stream->svc->dev);
1636 	struct config_item *item;
1637 
1638 	guard(mutex)(&tbstream_group.cg_subsys->su_mutex);
1639 	item = config_group_find_item(&tbstream_group, name);
1640 	if (!item)
1641 		return NULL;
1642 	return to_tbstream_group(to_config_group(item));
1643 }
1644 
1645 static void tbstream_group_attach_stream(struct tbstream *stream)
1646 {
1647 	struct tbstream_group *sg;
1648 	struct tbstream_dev *sdev;
1649 
1650 	sg = tbstream_group_find(stream);
1651 	if (!sg)
1652 		return;
1653 
1654 	guard(mutex)(&sg->lock);
1655 	if (WARN_ON(sg->stream)) {
1656 		config_group_put(&sg->group);
1657 		return;
1658 	}
1659 	sg->stream = tbstream_get(stream);
1660 	/*
1661 	 * If there are existing stream devices, attach the stream to
1662 	 * them now.
1663 	 */
1664 	list_for_each_entry(sdev, &sg->dev_list, list) {
1665 		tbstream_dev_get(sdev);
1666 		tbstream_dev_attach_stream(sdev, sg);
1667 		tbstream_dev_put(sdev);
1668 	}
1669 
1670 	config_group_put(&sg->group);
1671 }
1672 
1673 static void tbstream_group_detach_stream(struct tbstream *stream)
1674 {
1675 	struct tbstream_group *sg;
1676 	struct tbstream_dev *sdev;
1677 
1678 	sg = tbstream_group_find(stream);
1679 	if (!sg)
1680 		return;
1681 
1682 	guard(mutex)(&sg->lock);
1683 	if (sg->stream) {
1684 		/* Detach this stream from the stream devices */
1685 		list_for_each_entry_reverse(sdev, &sg->dev_list, list) {
1686 			tbstream_dev_get(sdev);
1687 			tbstream_dev_detach_stream(sdev);
1688 			tbstream_dev_put(sdev);
1689 		}
1690 		tbstream_put(sg->stream);
1691 		sg->stream = NULL;
1692 	}
1693 
1694 	config_group_put(&sg->group);
1695 }
1696 
1697 static int tbstream_probe(struct tb_service *svc)
1698 {
1699 	struct tbstream *stream;
1700 
1701 	stream = kzalloc_obj(*stream, GFP_KERNEL);
1702 	if (!stream)
1703 		return -ENOMEM;
1704 
1705 	/* After this point, release stream by calling tbstream_put() */
1706 	kref_init(&stream->kref);
1707 	stream->svc = tb_service_get(svc);
1708 	INIT_LIST_HEAD(&stream->list);
1709 
1710 	scoped_guard(mutex, &tbstream_lock)
1711 		list_add_tail(&stream->list, &tbstream_list);
1712 
1713 	tbstream_group_attach_stream(stream);
1714 	tb_service_set_drvdata(svc, stream);
1715 	return 0;
1716 }
1717 
1718 static void tbstream_remove(struct tb_service *svc)
1719 {
1720 	struct tbstream *stream = tb_service_get_drvdata(svc);
1721 
1722 	tbstream_group_detach_stream(stream);
1723 	scoped_guard(mutex, &tbstream_lock)
1724 		list_del(&stream->list);
1725 	tbstream_put(stream);
1726 }
1727 
1728 static int __maybe_unused tbstream_suspend(struct device *dev)
1729 {
1730 	struct tb_service *svc = tb_to_service(dev);
1731 	struct tbstream *stream = tb_service_get_drvdata(svc);
1732 	struct tbstream_group *sg;
1733 	struct tbstream_dev *sdev;
1734 
1735 	sg = tbstream_group_find(stream);
1736 	if (!sg)
1737 		return 0;
1738 
1739 	list_for_each_entry_reverse(sdev, &sg->dev_list, list) {
1740 		tbstream_dev_get(sdev);
1741 		/* Stop the stream (if it was open) */
1742 		if (sdev->users)
1743 			tbstream_dev_stop(sdev);
1744 		tbstream_dev_put(sdev);
1745 	}
1746 
1747 	config_group_put(&sg->group);
1748 	return 0;
1749 }
1750 
1751 static int __maybe_unused tbstream_resume(struct device *dev)
1752 {
1753 	struct tb_service *svc = tb_to_service(dev);
1754 	struct tbstream *stream = tb_service_get_drvdata(svc);
1755 	struct tbstream_group *sg;
1756 	struct tbstream_dev *sdev;
1757 
1758 	sg = tbstream_group_find(stream);
1759 	if (!sg)
1760 		return 0;
1761 
1762 	list_for_each_entry(sdev, &sg->dev_list, list) {
1763 		tbstream_dev_get(sdev);
1764 		if (sdev->users) {
1765 			int ret;
1766 
1767 			ret = tbstream_dev_start(sdev);
1768 			if (ret) {
1769 				tbstream_dev_put(sdev);
1770 				config_group_put(&sg->group);
1771 				return ret;
1772 			}
1773 		}
1774 		tbstream_dev_put(sdev);
1775 	}
1776 
1777 	config_group_put(&sg->group);
1778 	return 0;
1779 }
1780 
1781 static const struct dev_pm_ops tbstream_pm_ops = {
1782 	SET_SYSTEM_SLEEP_PM_OPS(tbstream_suspend, tbstream_resume)
1783 };
1784 
1785 static const struct tb_service_id tbstream_ids[] = {
1786 	{ TB_SERVICE("stream", 1) },
1787 	{ }
1788 };
1789 MODULE_DEVICE_TABLE(tbsvc, tbstream_ids);
1790 
1791 static struct tb_service_driver tbstream_driver = {
1792 	.driver = {
1793 		.owner = THIS_MODULE,
1794 		.name = "thunderbolt_stream",
1795 		.pm = &tbstream_pm_ops,
1796 	},
1797 	.probe = tbstream_probe,
1798 	.remove = tbstream_remove,
1799 	.id_table = tbstream_ids,
1800 };
1801 
1802 static int __init tbstream_init(void)
1803 {
1804 	int ret;
1805 
1806 	tbstream_dir = tb_property_create_dir(&tbstream_dir_uuid);
1807 	if (!tbstream_dir)
1808 		return -ENOMEM;
1809 
1810 	tb_property_add_immediate(tbstream_dir, "prtcid", 1);
1811 	tb_property_add_immediate(tbstream_dir, "prtcvers", 1);
1812 	tb_property_add_immediate(tbstream_dir, "prtcrevs", 0);
1813 	tb_property_add_immediate(tbstream_dir, "prtcstns", 0);
1814 
1815 	ret = tb_register_property_dir("stream", tbstream_dir);
1816 	if (ret)
1817 		goto err_free_dir;
1818 
1819 	config_group_init(&tbstream_group);
1820 	ret = tb_configfs_register_group(&tbstream_group);
1821 	if (ret)
1822 		goto err_unregister_dir;
1823 
1824 	ret = tb_register_service_driver(&tbstream_driver);
1825 	if (ret)
1826 		goto err_unregister_group;
1827 	return 0;
1828 
1829 err_unregister_group:
1830 	tb_configfs_unregister_group(&tbstream_group);
1831 err_unregister_dir:
1832 	tb_unregister_property_dir("stream", tbstream_dir);
1833 err_free_dir:
1834 	tb_property_free_dir(tbstream_dir);
1835 	return ret;
1836 }
1837 module_init(tbstream_init);
1838 
1839 static void __exit tbstream_exit(void)
1840 {
1841 	tb_unregister_service_driver(&tbstream_driver);
1842 	tb_configfs_unregister_group(&tbstream_group);
1843 	tb_unregister_property_dir("stream", tbstream_dir);
1844 	tb_property_free_dir(tbstream_dir);
1845 	ida_destroy(&tbstream_indices);
1846 }
1847 module_exit(tbstream_exit);
1848 
1849 MODULE_AUTHOR("Alan Borzeszkowski <alan.borzeszkowski@linux.intel.com>");
1850 MODULE_AUTHOR("Mika Westerberg <mika.westerberg@linux.intel.com>");
1851 MODULE_DESCRIPTION("Stream data over Thunderbolt/USB4 cable");
1852 MODULE_LICENSE("GPL");
1853