xref: /linux/drivers/thunderbolt/nhi.c (revision 15bcac35ba045a9a459144901443210d8b1df7a3)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Thunderbolt driver - NHI driver
4  *
5  * The NHI (native host interface) is the device that allows us to send and
6  * receive frames from the thunderbolt bus.
7  *
8  * Copyright (c) 2014 Andreas Noever <andreas.noever@gmail.com>
9  * Copyright (C) 2018, Intel Corporation
10  */
11 
12 #include <linux/pm_runtime.h>
13 #include <linux/slab.h>
14 #include <linux/errno.h>
15 #include <linux/dma-mapping.h>
16 #include <linux/interrupt.h>
17 #include <linux/iommu.h>
18 #include <linux/module.h>
19 #include <linux/delay.h>
20 #include <linux/property.h>
21 #include <linux/string_choices.h>
22 #include <linux/string_helpers.h>
23 
24 #include "nhi.h"
25 #include "nhi_regs.h"
26 #include "tb.h"
27 
28 #define RING_TYPE(ring) ((ring)->is_tx ? "TX ring" : "RX ring")
29 
30 #define RING_FIRST_USABLE_HOPID	1
31 /*
32  * Used with QUIRK_E2E to specify an unused HopID the Rx credits are
33  * transferred.
34  */
35 #define RING_E2E_RESERVED_HOPID	RING_FIRST_USABLE_HOPID
36 
37 #define NHI_MAILBOX_TIMEOUT	500 /* ms */
38 
39 static bool host_reset = true;
40 module_param(host_reset, bool, 0444);
41 MODULE_PARM_DESC(host_reset, "reset USB4 host router (default: true)");
42 
43 static int ring_interrupt_index(const struct tb_ring *ring)
44 {
45 	int bit = ring->hop;
46 	if (!ring->is_tx)
47 		bit += ring->nhi->hop_count;
48 	return bit;
49 }
50 
51 static void nhi_mask_interrupt(struct tb_nhi *nhi, int mask, int ring)
52 {
53 	if (nhi->quirks & QUIRK_AUTO_CLEAR_INT) {
54 		u32 val;
55 
56 		val = ioread32(nhi->iobase + REG_RING_INTERRUPT_BASE + ring);
57 		iowrite32(val & ~mask, nhi->iobase + REG_RING_INTERRUPT_BASE + ring);
58 	} else {
59 		iowrite32(mask, nhi->iobase + REG_RING_INTERRUPT_MASK_CLEAR_BASE + ring);
60 	}
61 }
62 
63 static void nhi_clear_interrupt(struct tb_nhi *nhi, int ring)
64 {
65 	if (nhi->quirks & QUIRK_AUTO_CLEAR_INT)
66 		ioread32(nhi->iobase + REG_RING_NOTIFY_BASE + ring);
67 	else
68 		iowrite32(~0, nhi->iobase + REG_RING_INT_CLEAR + ring);
69 }
70 
71 /*
72  * ring_interrupt_active() - activate/deactivate interrupts for a single ring
73  *
74  * ring->nhi->lock must be held.
75  */
76 static void ring_interrupt_active(struct tb_ring *ring, bool active)
77 {
78 	int index = ring_interrupt_index(ring) / 32 * 4;
79 	int reg = REG_RING_INTERRUPT_BASE + index;
80 	int interrupt_bit = ring_interrupt_index(ring) & 31;
81 	int mask = 1 << interrupt_bit;
82 	u32 old, new;
83 
84 	if (ring->irq > 0) {
85 		u32 step, shift, ivr, misc, itr;
86 		void __iomem *ivr_base;
87 		int auto_clear_bit;
88 		int index;
89 
90 		if (ring->is_tx)
91 			index = ring->hop;
92 		else
93 			index = ring->hop + ring->nhi->hop_count;
94 
95 		/*
96 		 * Intel routers support a bit that isn't part of
97 		 * the USB4 spec to ask the hardware to clear
98 		 * interrupt status bits automatically since
99 		 * we already know which interrupt was triggered.
100 		 *
101 		 * Other routers explicitly disable auto-clear
102 		 * to prevent conditions that may occur where two
103 		 * MSIX interrupts are simultaneously active and
104 		 * reading the register clears both of them.
105 		 */
106 		misc = ioread32(ring->nhi->iobase + REG_DMA_MISC);
107 		if (ring->nhi->quirks & QUIRK_AUTO_CLEAR_INT)
108 			auto_clear_bit = REG_DMA_MISC_INT_AUTO_CLEAR;
109 		else
110 			auto_clear_bit = REG_DMA_MISC_DISABLE_AUTO_CLEAR;
111 		if (!(misc & auto_clear_bit))
112 			iowrite32(misc | auto_clear_bit,
113 				  ring->nhi->iobase + REG_DMA_MISC);
114 
115 		ivr_base = ring->nhi->iobase + REG_INT_VEC_ALLOC_BASE;
116 		step = index / REG_INT_VEC_ALLOC_REGS * REG_INT_VEC_ALLOC_BITS;
117 		shift = index % REG_INT_VEC_ALLOC_REGS * REG_INT_VEC_ALLOC_BITS;
118 		ivr = ioread32(ivr_base + step);
119 		ivr &= ~(REG_INT_VEC_ALLOC_MASK << shift);
120 		if (active)
121 			ivr |= ring->vector << shift;
122 		iowrite32(ivr, ivr_base + step);
123 
124 		/* Throttling is specified in 256ns increments */
125 		itr = DIV_ROUND_UP(ring->interval_nsec, 256);
126 		itr &= REG_INT_THROTTLING_RATE_INTERVAL_MASK;
127 		iowrite32(itr, ring->nhi->iobase + REG_INT_THROTTLING_RATE +
128 			  ring->vector * 4);
129 	}
130 
131 	old = ioread32(ring->nhi->iobase + reg);
132 	if (active)
133 		new = old | mask;
134 	else
135 		new = old & ~mask;
136 
137 	dev_dbg(ring->nhi->dev,
138 		"%s interrupt at register %#x bit %d (%#x -> %#x)\n",
139 		active ? "enabling" : "disabling", reg, interrupt_bit, old, new);
140 
141 	if (new == old)
142 		dev_WARN(ring->nhi->dev, "interrupt for %s %d is already %s\n",
143 			 RING_TYPE(ring), ring->hop,
144 			 str_enabled_disabled(active));
145 
146 	if (active)
147 		iowrite32(new, ring->nhi->iobase + reg);
148 	else
149 		nhi_mask_interrupt(ring->nhi, mask, index);
150 }
151 
152 /*
153  * nhi_disable_interrupts() - disable interrupts for all rings
154  *
155  * Use only during init and shutdown.
156  */
157 void nhi_disable_interrupts(struct tb_nhi *nhi)
158 {
159 	int i = 0;
160 	/* disable interrupts */
161 	for (i = 0; i < RING_INTERRUPT_REG_COUNT(nhi); i++)
162 		nhi_mask_interrupt(nhi, ~0, 4 * i);
163 
164 	/* clear interrupt status bits */
165 	for (i = 0; i < RING_NOTIFY_REG_COUNT(nhi); i++)
166 		nhi_clear_interrupt(nhi, 4 * i);
167 }
168 
169 /* ring helper methods */
170 
171 static void __iomem *ring_desc_base(struct tb_ring *ring)
172 {
173 	void __iomem *io = ring->nhi->iobase;
174 	io += ring->is_tx ? REG_TX_RING_BASE : REG_RX_RING_BASE;
175 	io += ring->hop * 16;
176 	return io;
177 }
178 
179 static void __iomem *ring_options_base(struct tb_ring *ring)
180 {
181 	void __iomem *io = ring->nhi->iobase;
182 	io += ring->is_tx ? REG_TX_OPTIONS_BASE : REG_RX_OPTIONS_BASE;
183 	io += ring->hop * 32;
184 	return io;
185 }
186 
187 static void ring_iowrite_cons(struct tb_ring *ring, u16 cons)
188 {
189 	/*
190 	 * The other 16-bits in the register is read-only and writes to it
191 	 * are ignored by the hardware so we can save one ioread32() by
192 	 * filling the read-only bits with zeroes.
193 	 */
194 	iowrite32(cons, ring_desc_base(ring) + 8);
195 }
196 
197 static void ring_iowrite_prod(struct tb_ring *ring, u16 prod)
198 {
199 	/* See ring_iowrite_cons() above for explanation */
200 	iowrite32(prod << 16, ring_desc_base(ring) + 8);
201 }
202 
203 static void ring_iowrite32desc(struct tb_ring *ring, u32 value, u32 offset)
204 {
205 	iowrite32(value, ring_desc_base(ring) + offset);
206 }
207 
208 static void ring_iowrite64desc(struct tb_ring *ring, u64 value, u32 offset)
209 {
210 	iowrite32(value, ring_desc_base(ring) + offset);
211 	iowrite32(value >> 32, ring_desc_base(ring) + offset + 4);
212 }
213 
214 static void ring_iowrite32options(struct tb_ring *ring, u32 value, u32 offset)
215 {
216 	iowrite32(value, ring_options_base(ring) + offset);
217 }
218 
219 static bool ring_full(struct tb_ring *ring)
220 {
221 	return ((ring->head + 1) % ring->size) == ring->tail;
222 }
223 
224 static bool ring_empty(struct tb_ring *ring)
225 {
226 	return ring->head == ring->tail;
227 }
228 
229 /*
230  * ring_write_descriptors() - post frames from ring->queue to the controller
231  *
232  * ring->lock is held.
233  */
234 static void ring_write_descriptors(struct tb_ring *ring)
235 {
236 	struct ring_frame *frame, *n;
237 	struct ring_desc *descriptor;
238 	list_for_each_entry_safe(frame, n, &ring->queue, list) {
239 		if (ring_full(ring))
240 			break;
241 		list_move_tail(&frame->list, &ring->in_flight);
242 		descriptor = &ring->descriptors[ring->head];
243 		descriptor->phys = frame->buffer_phy;
244 		descriptor->time = 0;
245 		descriptor->flags = RING_DESC_POSTED | RING_DESC_INTERRUPT;
246 		if (ring->is_tx) {
247 			descriptor->length = frame->size;
248 			descriptor->eof = frame->eof;
249 			descriptor->sof = frame->sof;
250 		}
251 		ring->head = (ring->head + 1) % ring->size;
252 		if (ring->is_tx)
253 			ring_iowrite_prod(ring, ring->head);
254 		else
255 			ring_iowrite_cons(ring, ring->head);
256 	}
257 }
258 
259 /*
260  * ring_work() - progress completed frames
261  *
262  * If the ring is shutting down then all frames are marked as canceled and
263  * their callbacks are invoked.
264  *
265  * Otherwise we collect all completed frame from the ring buffer, write new
266  * frame to the ring buffer and invoke the callbacks for the completed frames.
267  */
268 static void ring_work(struct work_struct *work)
269 {
270 	struct tb_ring *ring = container_of(work, typeof(*ring), work);
271 	struct ring_frame *frame;
272 	bool canceled = false;
273 	unsigned long flags;
274 	LIST_HEAD(done);
275 
276 	spin_lock_irqsave(&ring->lock, flags);
277 
278 	if (!ring->running) {
279 		/*  Move all frames to done and mark them as canceled. */
280 		list_splice_tail_init(&ring->in_flight, &done);
281 		list_splice_tail_init(&ring->queue, &done);
282 		canceled = true;
283 		goto invoke_callback;
284 	}
285 
286 	while (!ring_empty(ring)) {
287 		if (!(ring->descriptors[ring->tail].flags
288 				& RING_DESC_COMPLETED))
289 			break;
290 		frame = list_first_entry(&ring->in_flight, typeof(*frame),
291 					 list);
292 		list_move_tail(&frame->list, &done);
293 		if (!ring->is_tx) {
294 			frame->size = ring->descriptors[ring->tail].length;
295 			frame->eof = ring->descriptors[ring->tail].eof;
296 			frame->sof = ring->descriptors[ring->tail].sof;
297 			frame->flags = ring->descriptors[ring->tail].flags;
298 		}
299 		ring->tail = (ring->tail + 1) % ring->size;
300 	}
301 	ring_write_descriptors(ring);
302 
303 invoke_callback:
304 	/* allow callbacks to schedule new work */
305 	spin_unlock_irqrestore(&ring->lock, flags);
306 	while (!list_empty(&done)) {
307 		frame = list_first_entry(&done, typeof(*frame), list);
308 		/*
309 		 * The callback may reenqueue or delete frame.
310 		 * Do not hold on to it.
311 		 */
312 		list_del_init(&frame->list);
313 		if (frame->callback)
314 			frame->callback(ring, frame, canceled);
315 	}
316 
317 	wake_up(&ring->wait);
318 }
319 
320 int __tb_ring_enqueue(struct tb_ring *ring, struct ring_frame *frame)
321 {
322 	unsigned long flags;
323 	int ret = 0;
324 
325 	spin_lock_irqsave(&ring->lock, flags);
326 	if (ring->running) {
327 		list_add_tail(&frame->list, &ring->queue);
328 		ring_write_descriptors(ring);
329 	} else {
330 		ret = -ESHUTDOWN;
331 	}
332 	spin_unlock_irqrestore(&ring->lock, flags);
333 	return ret;
334 }
335 EXPORT_SYMBOL_GPL(__tb_ring_enqueue);
336 
337 /**
338  * tb_ring_poll() - Poll one completed frame from the ring
339  * @ring: Ring to poll
340  *
341  * This function can be called when @start_poll callback of the @ring
342  * has been called. It will read one completed frame from the ring and
343  * return it to the caller.
344  *
345  * Return: Pointer to &struct ring_frame, %NULL if there is no more
346  * completed frames.
347  */
348 struct ring_frame *tb_ring_poll(struct tb_ring *ring)
349 {
350 	struct ring_frame *frame = NULL;
351 	unsigned long flags;
352 
353 	spin_lock_irqsave(&ring->lock, flags);
354 	if (!ring->running)
355 		goto unlock;
356 	if (ring_empty(ring))
357 		goto unlock;
358 
359 	if (ring->descriptors[ring->tail].flags & RING_DESC_COMPLETED) {
360 		frame = list_first_entry(&ring->in_flight, typeof(*frame),
361 					 list);
362 		list_del_init(&frame->list);
363 
364 		if (!ring->is_tx) {
365 			frame->size = ring->descriptors[ring->tail].length;
366 			frame->eof = ring->descriptors[ring->tail].eof;
367 			frame->sof = ring->descriptors[ring->tail].sof;
368 			frame->flags = ring->descriptors[ring->tail].flags;
369 		}
370 
371 		ring->tail = (ring->tail + 1) % ring->size;
372 	}
373 
374 unlock:
375 	spin_unlock_irqrestore(&ring->lock, flags);
376 	return frame;
377 }
378 EXPORT_SYMBOL_GPL(tb_ring_poll);
379 
380 static void __ring_interrupt_mask(struct tb_ring *ring, bool mask)
381 {
382 	int idx = ring_interrupt_index(ring);
383 	int reg = REG_RING_INTERRUPT_BASE + idx / 32 * 4;
384 	int bit = idx % 32;
385 	u32 val;
386 
387 	val = ioread32(ring->nhi->iobase + reg);
388 	if (mask)
389 		val &= ~BIT(bit);
390 	else
391 		val |= BIT(bit);
392 	iowrite32(val, ring->nhi->iobase + reg);
393 }
394 
395 /* Both @nhi->lock and @ring->lock should be held */
396 static void __ring_interrupt(struct tb_ring *ring)
397 {
398 	if (!ring->running)
399 		return;
400 
401 	if (ring->start_poll) {
402 		__ring_interrupt_mask(ring, true);
403 		ring->start_poll(ring->poll_data);
404 	} else {
405 		schedule_work(&ring->work);
406 	}
407 }
408 
409 /**
410  * tb_ring_poll_complete() - Re-start interrupt for the ring
411  * @ring: Ring to re-start the interrupt
412  *
413  * This will re-start (unmask) the ring interrupt once the user is done
414  * with polling.
415  */
416 void tb_ring_poll_complete(struct tb_ring *ring)
417 {
418 	unsigned long flags;
419 
420 	spin_lock_irqsave(&ring->nhi->lock, flags);
421 	spin_lock(&ring->lock);
422 	if (ring->start_poll)
423 		__ring_interrupt_mask(ring, false);
424 	spin_unlock(&ring->lock);
425 	spin_unlock_irqrestore(&ring->nhi->lock, flags);
426 }
427 EXPORT_SYMBOL_GPL(tb_ring_poll_complete);
428 
429 static void ring_clear_msix(const struct tb_ring *ring)
430 {
431 	int bit;
432 
433 	if (ring->nhi->quirks & QUIRK_AUTO_CLEAR_INT)
434 		return;
435 
436 	bit = ring_interrupt_index(ring) & 31;
437 	if (ring->is_tx)
438 		iowrite32(BIT(bit), ring->nhi->iobase + REG_RING_INT_CLEAR);
439 	else
440 		iowrite32(BIT(bit), ring->nhi->iobase + REG_RING_INT_CLEAR +
441 			  4 * (ring->nhi->hop_count / 32));
442 }
443 
444 irqreturn_t ring_msix(int irq, void *data)
445 {
446 	struct tb_ring *ring = data;
447 
448 	spin_lock(&ring->nhi->lock);
449 	ring_clear_msix(ring);
450 	spin_lock(&ring->lock);
451 	__ring_interrupt(ring);
452 	spin_unlock(&ring->lock);
453 	spin_unlock(&ring->nhi->lock);
454 
455 	return IRQ_HANDLED;
456 }
457 
458 static int nhi_alloc_hop(struct tb_nhi *nhi, struct tb_ring *ring)
459 {
460 	unsigned int start_hop = RING_FIRST_USABLE_HOPID;
461 	int ret = 0;
462 
463 	if (nhi->quirks & QUIRK_E2E) {
464 		start_hop = RING_FIRST_USABLE_HOPID + 1;
465 		if (ring->flags & RING_FLAG_E2E && !ring->is_tx) {
466 			dev_dbg(nhi->dev, "quirking E2E TX HopID %u -> %u\n",
467 				ring->e2e_tx_hop, RING_E2E_RESERVED_HOPID);
468 			ring->e2e_tx_hop = RING_E2E_RESERVED_HOPID;
469 		}
470 	}
471 
472 	spin_lock_irq(&nhi->lock);
473 
474 	if (ring->hop < 0) {
475 		unsigned int i;
476 
477 		/*
478 		 * Automatically allocate HopID from the non-reserved
479 		 * range 1 .. hop_count - 1.
480 		 */
481 		for (i = start_hop; i < nhi->hop_count; i++) {
482 			if (ring->is_tx) {
483 				if (!nhi->tx_rings[i]) {
484 					ring->hop = i;
485 					break;
486 				}
487 			} else {
488 				if (!nhi->rx_rings[i]) {
489 					ring->hop = i;
490 					break;
491 				}
492 			}
493 		}
494 	}
495 
496 	if (ring->hop > 0 && ring->hop < start_hop) {
497 		dev_warn(nhi->dev, "invalid hop: %d\n", ring->hop);
498 		ret = -EINVAL;
499 		goto err_unlock;
500 	}
501 	if (ring->hop < 0 || ring->hop >= nhi->hop_count) {
502 		dev_warn(nhi->dev, "invalid hop: %d\n", ring->hop);
503 		ret = -EINVAL;
504 		goto err_unlock;
505 	}
506 	if (ring->is_tx && nhi->tx_rings[ring->hop]) {
507 		dev_warn(nhi->dev, "TX hop %d already allocated\n",
508 			 ring->hop);
509 		ret = -EBUSY;
510 		goto err_unlock;
511 	}
512 	if (!ring->is_tx && nhi->rx_rings[ring->hop]) {
513 		dev_warn(nhi->dev, "RX hop %d already allocated\n",
514 			 ring->hop);
515 		ret = -EBUSY;
516 		goto err_unlock;
517 	}
518 
519 	if (ring->is_tx)
520 		nhi->tx_rings[ring->hop] = ring;
521 	else
522 		nhi->rx_rings[ring->hop] = ring;
523 
524 err_unlock:
525 	spin_unlock_irq(&nhi->lock);
526 
527 	return ret;
528 }
529 
530 static struct tb_ring *tb_ring_alloc(struct tb_nhi *nhi, u32 hop, int size,
531 				     bool transmit, unsigned int flags,
532 				     int e2e_tx_hop, u16 sof_mask, u16 eof_mask,
533 				     void (*start_poll)(void *),
534 				     void *poll_data)
535 {
536 	struct tb_ring *ring = NULL;
537 
538 	dev_dbg(nhi->dev, "allocating %s ring %d of size %d\n",
539 		transmit ? "TX" : "RX", hop, size);
540 
541 	ring = kzalloc_obj(*ring);
542 	if (!ring)
543 		return NULL;
544 
545 	spin_lock_init(&ring->lock);
546 	INIT_LIST_HEAD(&ring->queue);
547 	INIT_LIST_HEAD(&ring->in_flight);
548 	INIT_WORK(&ring->work, ring_work);
549 	init_waitqueue_head(&ring->wait);
550 
551 	ring->nhi = nhi;
552 	ring->hop = hop;
553 	ring->is_tx = transmit;
554 	ring->size = size;
555 	ring->flags = flags;
556 	ring->e2e_tx_hop = e2e_tx_hop;
557 	ring->sof_mask = sof_mask;
558 	ring->eof_mask = eof_mask;
559 	ring->head = 0;
560 	ring->tail = 0;
561 	ring->running = false;
562 	ring->start_poll = start_poll;
563 	ring->poll_data = poll_data;
564 
565 	ring->descriptors = dma_alloc_coherent(ring->nhi->dev,
566 					       size * sizeof(*ring->descriptors),
567 					       &ring->descriptors_dma, GFP_KERNEL | __GFP_ZERO);
568 	if (!ring->descriptors)
569 		goto err_free_ring;
570 
571 	if (nhi->ops->request_ring_irq) {
572 		if (nhi->ops->request_ring_irq(ring, flags & RING_FLAG_NO_SUSPEND))
573 			goto err_free_descs;
574 	}
575 
576 	if (nhi_alloc_hop(nhi, ring))
577 		goto err_release_msix;
578 
579 	return ring;
580 
581 err_release_msix:
582 	if (nhi->ops->release_ring_irq)
583 		nhi->ops->release_ring_irq(ring);
584 err_free_descs:
585 	dma_free_coherent(ring->nhi->dev,
586 			  ring->size * sizeof(*ring->descriptors),
587 			  ring->descriptors, ring->descriptors_dma);
588 err_free_ring:
589 	kfree(ring);
590 
591 	return NULL;
592 }
593 
594 /**
595  * tb_ring_alloc_tx() - Allocate DMA ring for transmit
596  * @nhi: Pointer to the NHI the ring is to be allocated
597  * @hop: HopID (ring) to allocate
598  * @size: Number of entries in the ring
599  * @flags: Flags for the ring
600  *
601  * Return: Pointer to &struct tb_ring, %NULL otherwise.
602  */
603 struct tb_ring *tb_ring_alloc_tx(struct tb_nhi *nhi, int hop, int size,
604 				 unsigned int flags)
605 {
606 	return tb_ring_alloc(nhi, hop, size, true, flags, 0, 0, 0, NULL, NULL);
607 }
608 EXPORT_SYMBOL_GPL(tb_ring_alloc_tx);
609 
610 /**
611  * tb_ring_alloc_rx() - Allocate DMA ring for receive
612  * @nhi: Pointer to the NHI the ring is to be allocated
613  * @hop: HopID (ring) to allocate. Pass %-1 for automatic allocation.
614  * @size: Number of entries in the ring
615  * @flags: Flags for the ring
616  * @e2e_tx_hop: Transmit HopID when E2E is enabled in @flags
617  * @sof_mask: Mask of PDF values that start a frame
618  * @eof_mask: Mask of PDF values that end a frame
619  * @start_poll: If not %NULL the ring will call this function when an
620  *		interrupt is triggered and masked, instead of callback
621  *		in each Rx frame.
622  * @poll_data: Optional data passed to @start_poll
623  *
624  * Return: Pointer to &struct tb_ring, %NULL otherwise.
625  */
626 struct tb_ring *tb_ring_alloc_rx(struct tb_nhi *nhi, int hop, int size,
627 				 unsigned int flags, int e2e_tx_hop,
628 				 u16 sof_mask, u16 eof_mask,
629 				 void (*start_poll)(void *), void *poll_data)
630 {
631 	return tb_ring_alloc(nhi, hop, size, false, flags, e2e_tx_hop, sof_mask, eof_mask,
632 			     start_poll, poll_data);
633 }
634 EXPORT_SYMBOL_GPL(tb_ring_alloc_rx);
635 
636 /**
637  * tb_ring_start() - enable a ring
638  * @ring: Ring to start
639  *
640  * Must not be invoked in parallel with tb_ring_stop().
641  */
642 void tb_ring_start(struct tb_ring *ring)
643 {
644 	u16 frame_size;
645 	u32 flags;
646 
647 	spin_lock_irq(&ring->nhi->lock);
648 	spin_lock(&ring->lock);
649 	if (ring->nhi->going_away)
650 		goto err;
651 	if (ring->running) {
652 		dev_WARN(ring->nhi->dev, "ring already started\n");
653 		goto err;
654 	}
655 	dev_dbg(ring->nhi->dev, "starting %s %d\n",
656 		RING_TYPE(ring), ring->hop);
657 
658 	if (ring->flags & RING_FLAG_FRAME) {
659 		/* Means 4096 */
660 		frame_size = 0;
661 		flags = RING_FLAG_ENABLE;
662 	} else {
663 		frame_size = TB_FRAME_SIZE;
664 		flags = RING_FLAG_ENABLE | RING_FLAG_RAW;
665 	}
666 
667 	ring_iowrite64desc(ring, ring->descriptors_dma, 0);
668 	if (ring->is_tx) {
669 		ring_iowrite32desc(ring, ring->size, 12);
670 		ring_iowrite32options(ring, 0, 4);
671 		ring_iowrite32options(ring, flags, 0);
672 	} else {
673 		u32 sof_eof_mask = ring->sof_mask << 16 | ring->eof_mask;
674 
675 		ring_iowrite32desc(ring, (frame_size << 16) | ring->size, 12);
676 		ring_iowrite32options(ring, sof_eof_mask, 4);
677 		ring_iowrite32options(ring, flags, 0);
678 	}
679 
680 	/*
681 	 * Now that the ring valid bit is set we can configure E2E if
682 	 * enabled for the ring.
683 	 */
684 	if (ring->flags & RING_FLAG_E2E) {
685 		if (!ring->is_tx) {
686 			u32 hop;
687 
688 			hop = ring->e2e_tx_hop << REG_RX_OPTIONS_E2E_HOP_SHIFT;
689 			hop &= REG_RX_OPTIONS_E2E_HOP_MASK;
690 			flags |= hop;
691 
692 			dev_dbg(ring->nhi->dev,
693 				"enabling E2E for %s %d with TX HopID %d\n",
694 				RING_TYPE(ring), ring->hop, ring->e2e_tx_hop);
695 		} else {
696 			dev_dbg(ring->nhi->dev, "enabling E2E for %s %d\n",
697 				RING_TYPE(ring), ring->hop);
698 		}
699 
700 		flags |= RING_FLAG_E2E_FLOW_CONTROL;
701 		ring_iowrite32options(ring, flags, 0);
702 	}
703 
704 	ring_interrupt_active(ring, true);
705 	ring->running = true;
706 err:
707 	spin_unlock(&ring->lock);
708 	spin_unlock_irq(&ring->nhi->lock);
709 }
710 EXPORT_SYMBOL_GPL(tb_ring_start);
711 
712 static bool tb_ring_empty(struct tb_ring *ring)
713 {
714 	guard(spinlock_irqsave)(&ring->lock);
715 	return list_empty(&ring->in_flight);
716 }
717 
718 /**
719  * tb_ring_flush() - Waits for a ring to be empty
720  * @ring: Ring to wait
721  * @timeout_msec: Timeout in ms how long to wait.
722  *
723  * This can be called before stopping a ring to make sure all the frames
724  * submitted prior have been completed.
725  *
726  * Return: %true if the ring is empty now, %false otherwise.
727  */
728 bool tb_ring_flush(struct tb_ring *ring, unsigned int timeout_msec)
729 {
730 	if (!wait_event_timeout(ring->wait, tb_ring_empty(ring),
731 				msecs_to_jiffies(timeout_msec)))
732 		return false;
733 	return tb_ring_empty(ring);
734 }
735 EXPORT_SYMBOL_GPL(tb_ring_flush);
736 
737 /**
738  * tb_ring_stop() - shutdown a ring
739  * @ring: Ring to stop
740  *
741  * Must not be invoked from a callback.
742  *
743  * This method will disable the ring. Further calls to
744  * tb_ring_tx/tb_ring_rx will return -ESHUTDOWN until ring_stop has been
745  * called.
746  *
747  * All enqueued frames will be canceled and their callbacks will be executed
748  * with frame->canceled set to true (on the callback thread). This method
749  * returns only after all callback invocations have finished.
750  */
751 void tb_ring_stop(struct tb_ring *ring)
752 {
753 	spin_lock_irq(&ring->nhi->lock);
754 	spin_lock(&ring->lock);
755 	dev_dbg(ring->nhi->dev, "stopping %s %d\n",
756 		RING_TYPE(ring), ring->hop);
757 	if (ring->nhi->going_away)
758 		goto err;
759 	if (!ring->running) {
760 		dev_WARN(ring->nhi->dev, "%s %d already stopped\n",
761 			 RING_TYPE(ring), ring->hop);
762 		goto err;
763 	}
764 	ring_interrupt_active(ring, false);
765 
766 	ring_iowrite32options(ring, 0, 0);
767 	ring_iowrite64desc(ring, 0, 0);
768 	ring_iowrite32desc(ring, 0, 8);
769 	ring_iowrite32desc(ring, 0, 12);
770 	ring->head = 0;
771 	ring->tail = 0;
772 	ring->running = false;
773 
774 err:
775 	spin_unlock(&ring->lock);
776 	spin_unlock_irq(&ring->nhi->lock);
777 
778 	/*
779 	 * schedule ring->work to invoke callbacks on all remaining frames.
780 	 */
781 	schedule_work(&ring->work);
782 	flush_work(&ring->work);
783 }
784 EXPORT_SYMBOL_GPL(tb_ring_stop);
785 
786 /*
787  * tb_ring_free() - free ring
788  *
789  * When this method returns all invocations of ring->callback will have
790  * finished.
791  *
792  * Ring must be stopped.
793  *
794  * Must NOT be called from ring_frame->callback!
795  */
796 void tb_ring_free(struct tb_ring *ring)
797 {
798 	struct tb_nhi *nhi = ring->nhi;
799 
800 	spin_lock_irq(&ring->nhi->lock);
801 	/*
802 	 * Dissociate the ring from the NHI. This also ensures that
803 	 * nhi_interrupt_work cannot reschedule ring->work.
804 	 */
805 	if (ring->is_tx)
806 		ring->nhi->tx_rings[ring->hop] = NULL;
807 	else
808 		ring->nhi->rx_rings[ring->hop] = NULL;
809 
810 	if (ring->running) {
811 		dev_WARN(ring->nhi->dev, "%s %d still running\n",
812 			 RING_TYPE(ring), ring->hop);
813 	}
814 	spin_unlock_irq(&ring->nhi->lock);
815 
816 	if (nhi->ops->release_ring_irq)
817 		nhi->ops->release_ring_irq(ring);
818 
819 	dma_free_coherent(ring->nhi->dev,
820 			  ring->size * sizeof(*ring->descriptors),
821 			  ring->descriptors, ring->descriptors_dma);
822 
823 	ring->descriptors = NULL;
824 	ring->descriptors_dma = 0;
825 
826 
827 	dev_dbg(ring->nhi->dev, "freeing %s %d\n", RING_TYPE(ring),
828 		ring->hop);
829 
830 	/*
831 	 * ring->work can no longer be scheduled (it is scheduled only
832 	 * by nhi_interrupt_work, ring_stop and ring_msix). Wait for it
833 	 * to finish before freeing the ring.
834 	 */
835 	flush_work(&ring->work);
836 	kfree(ring);
837 }
838 EXPORT_SYMBOL_GPL(tb_ring_free);
839 
840 /**
841  * tb_ring_throttling() - Configure throttling for ring interrupt
842  * @ring: Ring to configure
843  * @interval_nsec: Interval counter for moderation (in ns), %0 disables
844  *
845  * Enables or disables ring interrupt throttling. The ring must be
846  * stopped for this to be called. Granularity is 256 ns.
847  *
848  * Return: %0 on success, negative errno otherwise.
849  */
850 int tb_ring_throttling(struct tb_ring *ring, unsigned int interval_nsec)
851 {
852 	guard(spinlock_irqsave)(&ring->lock);
853 	if (WARN_ON_ONCE(ring->running))
854 		return -EBUSY;
855 	ring->interval_nsec = interval_nsec;
856 	return 0;
857 }
858 EXPORT_SYMBOL_GPL(tb_ring_throttling);
859 
860 /**
861  * nhi_mailbox_cmd() - Send a command through NHI mailbox
862  * @nhi: Pointer to the NHI structure
863  * @cmd: Command to send
864  * @data: Data to be send with the command
865  *
866  * Sends mailbox command to the firmware running on NHI.
867  *
868  * Return: %0 on success, negative errno otherwise.
869  */
870 int nhi_mailbox_cmd(struct tb_nhi *nhi, enum nhi_mailbox_cmd cmd, u32 data)
871 {
872 	ktime_t timeout;
873 	u32 val;
874 
875 	iowrite32(data, nhi->iobase + REG_INMAIL_DATA);
876 
877 	val = ioread32(nhi->iobase + REG_INMAIL_CMD);
878 	val &= ~(REG_INMAIL_CMD_MASK | REG_INMAIL_ERROR);
879 	val |= REG_INMAIL_OP_REQUEST | cmd;
880 	iowrite32(val, nhi->iobase + REG_INMAIL_CMD);
881 
882 	timeout = ktime_add_ms(ktime_get(), NHI_MAILBOX_TIMEOUT);
883 	do {
884 		val = ioread32(nhi->iobase + REG_INMAIL_CMD);
885 		if (!(val & REG_INMAIL_OP_REQUEST))
886 			break;
887 		usleep_range(10, 20);
888 	} while (ktime_before(ktime_get(), timeout));
889 
890 	if (val & REG_INMAIL_OP_REQUEST)
891 		return -ETIMEDOUT;
892 	if (val & REG_INMAIL_ERROR)
893 		return -EIO;
894 
895 	return 0;
896 }
897 
898 /**
899  * nhi_mailbox_mode() - Return current firmware operation mode
900  * @nhi: Pointer to the NHI structure
901  *
902  * The function reads current firmware operation mode using NHI mailbox
903  * registers and returns it to the caller.
904  *
905  * Return: &enum nhi_fw_mode.
906  */
907 enum nhi_fw_mode nhi_mailbox_mode(struct tb_nhi *nhi)
908 {
909 	u32 val;
910 
911 	val = ioread32(nhi->iobase + REG_OUTMAIL_CMD);
912 	val &= REG_OUTMAIL_CMD_OPMODE_MASK;
913 	val >>= REG_OUTMAIL_CMD_OPMODE_SHIFT;
914 
915 	return (enum nhi_fw_mode)val;
916 }
917 
918 void nhi_interrupt_work(struct work_struct *work)
919 {
920 	struct tb_nhi *nhi = container_of(work, typeof(*nhi), interrupt_work);
921 	int value = 0; /* Suppress uninitialized usage warning. */
922 	int bit;
923 	int hop = -1;
924 	int type = 0; /* current interrupt type 0: TX, 1: RX, 2: RX overflow */
925 	struct tb_ring *ring;
926 
927 	spin_lock_irq(&nhi->lock);
928 
929 	/*
930 	 * Starting at REG_RING_NOTIFY_BASE there are three status bitfields
931 	 * (TX, RX, RX overflow). We iterate over the bits and read a new
932 	 * dwords as required. The registers are cleared on read.
933 	 */
934 	for (bit = 0; bit < 3 * nhi->hop_count; bit++) {
935 		if (bit % 32 == 0)
936 			value = ioread32(nhi->iobase
937 					 + REG_RING_NOTIFY_BASE
938 					 + 4 * (bit / 32));
939 		if (++hop == nhi->hop_count) {
940 			hop = 0;
941 			type++;
942 		}
943 		if ((value & (1 << (bit % 32))) == 0)
944 			continue;
945 		if (type == 2) {
946 			dev_warn(nhi->dev, "RX overflow for ring %d\n", hop);
947 			continue;
948 		}
949 		if (type == 0)
950 			ring = nhi->tx_rings[hop];
951 		else
952 			ring = nhi->rx_rings[hop];
953 		if (ring == NULL) {
954 			dev_warn(nhi->dev,
955 				 "got interrupt for inactive %s ring %d\n",
956 				 type ? "RX" : "TX",
957 				 hop);
958 			continue;
959 		}
960 
961 		spin_lock(&ring->lock);
962 		__ring_interrupt(ring);
963 		spin_unlock(&ring->lock);
964 	}
965 	spin_unlock_irq(&nhi->lock);
966 }
967 
968 irqreturn_t nhi_msi(int irq, void *data)
969 {
970 	struct tb_nhi *nhi = data;
971 	schedule_work(&nhi->interrupt_work);
972 	return IRQ_HANDLED;
973 }
974 
975 static int __nhi_suspend_noirq(struct device *dev, bool wakeup)
976 {
977 	struct tb *tb = dev_get_drvdata(dev);
978 	struct tb_nhi *nhi = tb->nhi;
979 	int ret;
980 
981 	ret = tb_domain_suspend_noirq(tb);
982 	if (ret)
983 		return ret;
984 
985 	if (nhi->ops->suspend_noirq) {
986 		ret = nhi->ops->suspend_noirq(tb->nhi, wakeup);
987 		if (ret)
988 			return ret;
989 	}
990 
991 	return 0;
992 }
993 
994 static int nhi_suspend_noirq(struct device *dev)
995 {
996 	return __nhi_suspend_noirq(dev, device_may_wakeup(dev));
997 }
998 
999 static int nhi_freeze_noirq(struct device *dev)
1000 {
1001 	struct tb *tb = dev_get_drvdata(dev);
1002 
1003 	return tb_domain_freeze_noirq(tb);
1004 }
1005 
1006 static int nhi_thaw_noirq(struct device *dev)
1007 {
1008 	struct tb *tb = dev_get_drvdata(dev);
1009 
1010 	return tb_domain_thaw_noirq(tb);
1011 }
1012 
1013 static bool nhi_wake_supported(struct device *dev)
1014 {
1015 	u8 val;
1016 
1017 	/*
1018 	 * If power rails are sustainable for wakeup from S4 this
1019 	 * property is set by the BIOS.
1020 	 */
1021 	if (!device_property_read_u8(dev, "WAKE_SUPPORTED", &val))
1022 		return !!val;
1023 
1024 	return true;
1025 }
1026 
1027 static int nhi_poweroff_noirq(struct device *dev)
1028 {
1029 	bool wakeup;
1030 
1031 	wakeup = device_may_wakeup(dev) && nhi_wake_supported(dev);
1032 	return __nhi_suspend_noirq(dev, wakeup);
1033 }
1034 
1035 static int nhi_resume_noirq(struct device *dev)
1036 {
1037 	struct tb *tb = dev_get_drvdata(dev);
1038 	struct tb_nhi *nhi = tb->nhi;
1039 	int ret;
1040 
1041 	/*
1042 	 * Check that the device is still there. It may be that the user
1043 	 * unplugged last device which causes the host controller to go
1044 	 * away on PCs.
1045 	 */
1046 	if ((nhi->ops->is_present && !nhi->ops->is_present(nhi))) {
1047 		nhi->going_away = true;
1048 	} else if (nhi->ops->resume_noirq) {
1049 		ret = nhi->ops->resume_noirq(nhi);
1050 		if (ret)
1051 			return ret;
1052 	}
1053 
1054 	return tb_domain_resume_noirq(tb);
1055 }
1056 
1057 static int nhi_suspend(struct device *dev)
1058 {
1059 	struct tb *tb = dev_get_drvdata(dev);
1060 
1061 	return tb_domain_suspend(tb);
1062 }
1063 
1064 static void nhi_complete(struct device *dev)
1065 {
1066 	struct tb *tb = dev_get_drvdata(dev);
1067 
1068 	/*
1069 	 * If we were runtime suspended when system suspend started,
1070 	 * schedule runtime resume now. It should bring the domain back
1071 	 * to functional state.
1072 	 */
1073 	if (pm_runtime_suspended(dev))
1074 		pm_runtime_resume(dev);
1075 	else
1076 		tb_domain_complete(tb);
1077 }
1078 
1079 static int nhi_runtime_suspend(struct device *dev)
1080 {
1081 	struct tb *tb = dev_get_drvdata(dev);
1082 	struct tb_nhi *nhi = tb->nhi;
1083 	int ret;
1084 
1085 	ret = tb_domain_runtime_suspend(tb);
1086 	if (ret)
1087 		return ret;
1088 
1089 	if (nhi->ops->runtime_suspend) {
1090 		ret = nhi->ops->runtime_suspend(tb->nhi);
1091 		if (ret)
1092 			return ret;
1093 	}
1094 	return 0;
1095 }
1096 
1097 static int nhi_runtime_resume(struct device *dev)
1098 {
1099 	struct tb *tb = dev_get_drvdata(dev);
1100 	struct tb_nhi *nhi = tb->nhi;
1101 	int ret;
1102 
1103 	if (nhi->ops->runtime_resume) {
1104 		ret = nhi->ops->runtime_resume(nhi);
1105 		if (ret)
1106 			return ret;
1107 	}
1108 
1109 	return tb_domain_runtime_resume(tb);
1110 }
1111 
1112 void nhi_shutdown(struct tb_nhi *nhi)
1113 {
1114 	int i;
1115 
1116 	dev_dbg(nhi->dev, "shutdown\n");
1117 
1118 	for (i = 0; i < nhi->hop_count; i++) {
1119 		if (nhi->tx_rings[i])
1120 			dev_WARN(nhi->dev,
1121 				 "TX ring %d is still active\n", i);
1122 		if (nhi->rx_rings[i])
1123 			dev_WARN(nhi->dev,
1124 				 "RX ring %d is still active\n", i);
1125 	}
1126 	nhi_disable_interrupts(nhi);
1127 
1128 	if (nhi->ops->shutdown)
1129 		nhi->ops->shutdown(nhi);
1130 }
1131 
1132 static void nhi_reset(struct tb_nhi *nhi)
1133 {
1134 	ktime_t timeout;
1135 	u32 val;
1136 
1137 	val = ioread32(nhi->iobase + REG_CAPS);
1138 	/* Reset only v2 and later routers */
1139 	if (FIELD_GET(REG_CAPS_VERSION_MASK, val) < REG_CAPS_VERSION_2)
1140 		return;
1141 
1142 	if (!host_reset) {
1143 		dev_dbg(nhi->dev, "skipping host router reset\n");
1144 		return;
1145 	}
1146 
1147 	iowrite32(REG_RESET_HRR, nhi->iobase + REG_RESET);
1148 	msleep(100);
1149 
1150 	timeout = ktime_add_ms(ktime_get(), 500);
1151 	do {
1152 		val = ioread32(nhi->iobase + REG_RESET);
1153 		if (!(val & REG_RESET_HRR)) {
1154 			dev_warn(nhi->dev, "host router reset successful\n");
1155 			return;
1156 		}
1157 		usleep_range(10, 20);
1158 	} while (ktime_before(ktime_get(), timeout));
1159 
1160 	dev_warn(nhi->dev, "timeout resetting host router\n");
1161 }
1162 
1163 static struct tb *nhi_select_cm(struct tb_nhi *nhi)
1164 {
1165 	struct tb *tb;
1166 
1167 	/*
1168 	 * USB4 case is simple. If we got control of any of the
1169 	 * capabilities, we use software CM.
1170 	 */
1171 	if (tb_acpi_is_native())
1172 		return tb_probe(nhi);
1173 
1174 	/*
1175 	 * Either firmware based CM is running (we did not get control
1176 	 * from the firmware) or this is pre-USB4 PC so try first
1177 	 * firmware CM and then fallback to software CM.
1178 	 */
1179 	tb = icm_probe(nhi);
1180 	if (!tb)
1181 		tb = tb_probe(nhi);
1182 
1183 	return tb;
1184 }
1185 
1186 int nhi_probe(struct tb_nhi *nhi)
1187 {
1188 	struct device *dev = nhi->dev;
1189 	struct tb *tb;
1190 	int res;
1191 
1192 	if (!nhi->ops)
1193 		return dev_err_probe(dev, -EINVAL, "NHI ops not set\n");
1194 
1195 	if (!nhi->ops->init_interrupts)
1196 		return dev_err_probe(dev, -EINVAL, "missing required NHI ops\n");
1197 
1198 	nhi->hop_count = ioread32(nhi->iobase + REG_CAPS) & 0x3ff;
1199 	dev_dbg(dev, "total paths: %d\n", nhi->hop_count);
1200 
1201 	nhi->tx_rings = devm_kcalloc(dev, nhi->hop_count,
1202 				     sizeof(*nhi->tx_rings), GFP_KERNEL);
1203 	nhi->rx_rings = devm_kcalloc(dev, nhi->hop_count,
1204 				     sizeof(*nhi->rx_rings), GFP_KERNEL);
1205 	if (!nhi->tx_rings || !nhi->rx_rings)
1206 		return -ENOMEM;
1207 
1208 	nhi_reset(nhi);
1209 
1210 	/* In case someone left them on. */
1211 	nhi_disable_interrupts(nhi);
1212 
1213 	res = nhi->ops->init_interrupts(nhi);
1214 	if (res)
1215 		return dev_err_probe(dev, res, "cannot enable interrupts, aborting\n");
1216 
1217 	spin_lock_init(&nhi->lock);
1218 
1219 	res = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64));
1220 	if (res)
1221 		return dev_err_probe(dev, res, "failed to set DMA mask\n");
1222 
1223 	if (nhi->ops->init) {
1224 		res = nhi->ops->init(nhi);
1225 		if (res)
1226 			return dev_err_probe(dev, res, "NHI specific init failed\n");
1227 	}
1228 
1229 	tb = nhi_select_cm(nhi);
1230 	if (!tb)
1231 		return dev_err_probe(dev, -ENODEV,
1232 			"failed to determine connection manager, aborting\n");
1233 
1234 	dev_dbg(dev, "NHI initialized, starting thunderbolt\n");
1235 
1236 	init_completion(&nhi->domain_released);
1237 
1238 	res = tb_domain_add(tb, host_reset);
1239 	if (res) {
1240 		/*
1241 		 * At this point the RX/TX rings might already have been
1242 		 * activated. Do a proper shutdown.
1243 		 */
1244 		tb_domain_put(tb);
1245 		wait_for_completion(&nhi->domain_released);
1246 		nhi_shutdown(nhi);
1247 		return dev_err_probe(dev, res, "failed to add domain\n");
1248 	}
1249 	dev_set_drvdata(dev, tb);
1250 
1251 	device_wakeup_enable(dev);
1252 
1253 	pm_runtime_allow(dev);
1254 	pm_runtime_set_autosuspend_delay(dev, TB_AUTOSUSPEND_DELAY);
1255 	pm_runtime_use_autosuspend(dev);
1256 	pm_runtime_put_autosuspend(dev);
1257 
1258 	return 0;
1259 }
1260 
1261 /*
1262  * The tunneled pci bridges are siblings of us. Use resume_noirq to reenable
1263  * the tunnels asap. A corresponding pci quirk blocks the downstream bridges
1264  * resume_noirq until we are done.
1265  */
1266 const struct dev_pm_ops nhi_pm_ops = {
1267 	.suspend_noirq = nhi_suspend_noirq,
1268 	.resume_noirq = nhi_resume_noirq,
1269 	.freeze_noirq = nhi_freeze_noirq,  /*
1270 					    * we just disable hotplug, the
1271 					    * pci-tunnels stay alive.
1272 					    */
1273 	.thaw_noirq = nhi_thaw_noirq,
1274 	.restore_noirq = nhi_resume_noirq,
1275 	.suspend = nhi_suspend,
1276 	.poweroff_noirq = nhi_poweroff_noirq,
1277 	.poweroff = nhi_suspend,
1278 	.complete = nhi_complete,
1279 	.runtime_suspend = nhi_runtime_suspend,
1280 	.runtime_resume = nhi_runtime_resume,
1281 };
1282