xref: /openbmc/linux/drivers/thunderbolt/nhi.c (revision b848b26c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Thunderbolt driver - NHI driver
4  *
5  * The NHI (native host interface) is the pci 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/pci.h>
16 #include <linux/dma-mapping.h>
17 #include <linux/interrupt.h>
18 #include <linux/iommu.h>
19 #include <linux/module.h>
20 #include <linux/delay.h>
21 #include <linux/property.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  * Minimal number of vectors when we use MSI-X. Two for control channel
38  * Rx/Tx and the rest four are for cross domain DMA paths.
39  */
40 #define MSIX_MIN_VECS		6
41 #define MSIX_MAX_VECS		16
42 
43 #define NHI_MAILBOX_TIMEOUT	500 /* ms */
44 
45 /* Host interface quirks */
46 #define QUIRK_AUTO_CLEAR_INT	BIT(0)
47 #define QUIRK_E2E		BIT(1)
48 
49 static int ring_interrupt_index(const struct tb_ring *ring)
50 {
51 	int bit = ring->hop;
52 	if (!ring->is_tx)
53 		bit += ring->nhi->hop_count;
54 	return bit;
55 }
56 
57 static void nhi_mask_interrupt(struct tb_nhi *nhi, int mask, int ring)
58 {
59 	if (nhi->quirks & QUIRK_AUTO_CLEAR_INT) {
60 		u32 val;
61 
62 		val = ioread32(nhi->iobase + REG_RING_INTERRUPT_BASE + ring);
63 		iowrite32(val & ~mask, nhi->iobase + REG_RING_INTERRUPT_BASE + ring);
64 	} else {
65 		iowrite32(mask, nhi->iobase + REG_RING_INTERRUPT_MASK_CLEAR_BASE + ring);
66 	}
67 }
68 
69 static void nhi_clear_interrupt(struct tb_nhi *nhi, int ring)
70 {
71 	if (nhi->quirks & QUIRK_AUTO_CLEAR_INT)
72 		ioread32(nhi->iobase + REG_RING_NOTIFY_BASE + ring);
73 	else
74 		iowrite32(~0, nhi->iobase + REG_RING_INT_CLEAR + ring);
75 }
76 
77 /*
78  * ring_interrupt_active() - activate/deactivate interrupts for a single ring
79  *
80  * ring->nhi->lock must be held.
81  */
82 static void ring_interrupt_active(struct tb_ring *ring, bool active)
83 {
84 	int index = ring_interrupt_index(ring) / 32 * 4;
85 	int reg = REG_RING_INTERRUPT_BASE + index;
86 	int interrupt_bit = ring_interrupt_index(ring) & 31;
87 	int mask = 1 << interrupt_bit;
88 	u32 old, new;
89 
90 	if (ring->irq > 0) {
91 		u32 step, shift, ivr, misc;
92 		void __iomem *ivr_base;
93 		int auto_clear_bit;
94 		int index;
95 
96 		if (ring->is_tx)
97 			index = ring->hop;
98 		else
99 			index = ring->hop + ring->nhi->hop_count;
100 
101 		/*
102 		 * Intel routers support a bit that isn't part of
103 		 * the USB4 spec to ask the hardware to clear
104 		 * interrupt status bits automatically since
105 		 * we already know which interrupt was triggered.
106 		 *
107 		 * Other routers explicitly disable auto-clear
108 		 * to prevent conditions that may occur where two
109 		 * MSIX interrupts are simultaneously active and
110 		 * reading the register clears both of them.
111 		 */
112 		misc = ioread32(ring->nhi->iobase + REG_DMA_MISC);
113 		if (ring->nhi->quirks & QUIRK_AUTO_CLEAR_INT)
114 			auto_clear_bit = REG_DMA_MISC_INT_AUTO_CLEAR;
115 		else
116 			auto_clear_bit = REG_DMA_MISC_DISABLE_AUTO_CLEAR;
117 		if (!(misc & auto_clear_bit))
118 			iowrite32(misc | auto_clear_bit,
119 				  ring->nhi->iobase + REG_DMA_MISC);
120 
121 		ivr_base = ring->nhi->iobase + REG_INT_VEC_ALLOC_BASE;
122 		step = index / REG_INT_VEC_ALLOC_REGS * REG_INT_VEC_ALLOC_BITS;
123 		shift = index % REG_INT_VEC_ALLOC_REGS * REG_INT_VEC_ALLOC_BITS;
124 		ivr = ioread32(ivr_base + step);
125 		ivr &= ~(REG_INT_VEC_ALLOC_MASK << shift);
126 		if (active)
127 			ivr |= ring->vector << shift;
128 		iowrite32(ivr, ivr_base + step);
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->pdev->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->pdev->dev,
143 					 "interrupt for %s %d is already %s\n",
144 					 RING_TYPE(ring), ring->hop,
145 					 active ? "enabled" : "disabled");
146 
147 	if (active)
148 		iowrite32(new, ring->nhi->iobase + reg);
149 	else
150 		nhi_mask_interrupt(ring->nhi, mask, index);
151 }
152 
153 /*
154  * nhi_disable_interrupts() - disable interrupts for all rings
155  *
156  * Use only during init and shutdown.
157  */
158 static void nhi_disable_interrupts(struct tb_nhi *nhi)
159 {
160 	int i = 0;
161 	/* disable interrupts */
162 	for (i = 0; i < RING_INTERRUPT_REG_COUNT(nhi); i++)
163 		nhi_mask_interrupt(nhi, ~0, 4 * i);
164 
165 	/* clear interrupt status bits */
166 	for (i = 0; i < RING_NOTIFY_REG_COUNT(nhi); i++)
167 		nhi_clear_interrupt(nhi, 4 * i);
168 }
169 
170 /* ring helper methods */
171 
172 static void __iomem *ring_desc_base(struct tb_ring *ring)
173 {
174 	void __iomem *io = ring->nhi->iobase;
175 	io += ring->is_tx ? REG_TX_RING_BASE : REG_RX_RING_BASE;
176 	io += ring->hop * 16;
177 	return io;
178 }
179 
180 static void __iomem *ring_options_base(struct tb_ring *ring)
181 {
182 	void __iomem *io = ring->nhi->iobase;
183 	io += ring->is_tx ? REG_TX_OPTIONS_BASE : REG_RX_OPTIONS_BASE;
184 	io += ring->hop * 32;
185 	return io;
186 }
187 
188 static void ring_iowrite_cons(struct tb_ring *ring, u16 cons)
189 {
190 	/*
191 	 * The other 16-bits in the register is read-only and writes to it
192 	 * are ignored by the hardware so we can save one ioread32() by
193 	 * filling the read-only bits with zeroes.
194 	 */
195 	iowrite32(cons, ring_desc_base(ring) + 8);
196 }
197 
198 static void ring_iowrite_prod(struct tb_ring *ring, u16 prod)
199 {
200 	/* See ring_iowrite_cons() above for explanation */
201 	iowrite32(prod << 16, ring_desc_base(ring) + 8);
202 }
203 
204 static void ring_iowrite32desc(struct tb_ring *ring, u32 value, u32 offset)
205 {
206 	iowrite32(value, ring_desc_base(ring) + offset);
207 }
208 
209 static void ring_iowrite64desc(struct tb_ring *ring, u64 value, u32 offset)
210 {
211 	iowrite32(value, ring_desc_base(ring) + offset);
212 	iowrite32(value >> 32, ring_desc_base(ring) + offset + 4);
213 }
214 
215 static void ring_iowrite32options(struct tb_ring *ring, u32 value, u32 offset)
216 {
217 	iowrite32(value, ring_options_base(ring) + offset);
218 }
219 
220 static bool ring_full(struct tb_ring *ring)
221 {
222 	return ((ring->head + 1) % ring->size) == ring->tail;
223 }
224 
225 static bool ring_empty(struct tb_ring *ring)
226 {
227 	return ring->head == ring->tail;
228 }
229 
230 /*
231  * ring_write_descriptors() - post frames from ring->queue to the controller
232  *
233  * ring->lock is held.
234  */
235 static void ring_write_descriptors(struct tb_ring *ring)
236 {
237 	struct ring_frame *frame, *n;
238 	struct ring_desc *descriptor;
239 	list_for_each_entry_safe(frame, n, &ring->queue, list) {
240 		if (ring_full(ring))
241 			break;
242 		list_move_tail(&frame->list, &ring->in_flight);
243 		descriptor = &ring->descriptors[ring->head];
244 		descriptor->phys = frame->buffer_phy;
245 		descriptor->time = 0;
246 		descriptor->flags = RING_DESC_POSTED | RING_DESC_INTERRUPT;
247 		if (ring->is_tx) {
248 			descriptor->length = frame->size;
249 			descriptor->eof = frame->eof;
250 			descriptor->sof = frame->sof;
251 		}
252 		ring->head = (ring->head + 1) % ring->size;
253 		if (ring->is_tx)
254 			ring_iowrite_prod(ring, ring->head);
255 		else
256 			ring_iowrite_cons(ring, ring->head);
257 	}
258 }
259 
260 /*
261  * ring_work() - progress completed frames
262  *
263  * If the ring is shutting down then all frames are marked as canceled and
264  * their callbacks are invoked.
265  *
266  * Otherwise we collect all completed frame from the ring buffer, write new
267  * frame to the ring buffer and invoke the callbacks for the completed frames.
268  */
269 static void ring_work(struct work_struct *work)
270 {
271 	struct tb_ring *ring = container_of(work, typeof(*ring), work);
272 	struct ring_frame *frame;
273 	bool canceled = false;
274 	unsigned long flags;
275 	LIST_HEAD(done);
276 
277 	spin_lock_irqsave(&ring->lock, flags);
278 
279 	if (!ring->running) {
280 		/*  Move all frames to done and mark them as canceled. */
281 		list_splice_tail_init(&ring->in_flight, &done);
282 		list_splice_tail_init(&ring->queue, &done);
283 		canceled = true;
284 		goto invoke_callback;
285 	}
286 
287 	while (!ring_empty(ring)) {
288 		if (!(ring->descriptors[ring->tail].flags
289 				& RING_DESC_COMPLETED))
290 			break;
291 		frame = list_first_entry(&ring->in_flight, typeof(*frame),
292 					 list);
293 		list_move_tail(&frame->list, &done);
294 		if (!ring->is_tx) {
295 			frame->size = ring->descriptors[ring->tail].length;
296 			frame->eof = ring->descriptors[ring->tail].eof;
297 			frame->sof = ring->descriptors[ring->tail].sof;
298 			frame->flags = ring->descriptors[ring->tail].flags;
299 		}
300 		ring->tail = (ring->tail + 1) % ring->size;
301 	}
302 	ring_write_descriptors(ring);
303 
304 invoke_callback:
305 	/* allow callbacks to schedule new work */
306 	spin_unlock_irqrestore(&ring->lock, flags);
307 	while (!list_empty(&done)) {
308 		frame = list_first_entry(&done, typeof(*frame), list);
309 		/*
310 		 * The callback may reenqueue or delete frame.
311 		 * Do not hold on to it.
312 		 */
313 		list_del_init(&frame->list);
314 		if (frame->callback)
315 			frame->callback(ring, frame, canceled);
316 	}
317 }
318 
319 int __tb_ring_enqueue(struct tb_ring *ring, struct ring_frame *frame)
320 {
321 	unsigned long flags;
322 	int ret = 0;
323 
324 	spin_lock_irqsave(&ring->lock, flags);
325 	if (ring->running) {
326 		list_add_tail(&frame->list, &ring->queue);
327 		ring_write_descriptors(ring);
328 	} else {
329 		ret = -ESHUTDOWN;
330 	}
331 	spin_unlock_irqrestore(&ring->lock, flags);
332 	return ret;
333 }
334 EXPORT_SYMBOL_GPL(__tb_ring_enqueue);
335 
336 /**
337  * tb_ring_poll() - Poll one completed frame from the ring
338  * @ring: Ring to poll
339  *
340  * This function can be called when @start_poll callback of the @ring
341  * has been called. It will read one completed frame from the ring and
342  * return it to the caller. Returns %NULL if there is no more completed
343  * frames.
344  */
345 struct ring_frame *tb_ring_poll(struct tb_ring *ring)
346 {
347 	struct ring_frame *frame = NULL;
348 	unsigned long flags;
349 
350 	spin_lock_irqsave(&ring->lock, flags);
351 	if (!ring->running)
352 		goto unlock;
353 	if (ring_empty(ring))
354 		goto unlock;
355 
356 	if (ring->descriptors[ring->tail].flags & RING_DESC_COMPLETED) {
357 		frame = list_first_entry(&ring->in_flight, typeof(*frame),
358 					 list);
359 		list_del_init(&frame->list);
360 
361 		if (!ring->is_tx) {
362 			frame->size = ring->descriptors[ring->tail].length;
363 			frame->eof = ring->descriptors[ring->tail].eof;
364 			frame->sof = ring->descriptors[ring->tail].sof;
365 			frame->flags = ring->descriptors[ring->tail].flags;
366 		}
367 
368 		ring->tail = (ring->tail + 1) % ring->size;
369 	}
370 
371 unlock:
372 	spin_unlock_irqrestore(&ring->lock, flags);
373 	return frame;
374 }
375 EXPORT_SYMBOL_GPL(tb_ring_poll);
376 
377 static void __ring_interrupt_mask(struct tb_ring *ring, bool mask)
378 {
379 	int idx = ring_interrupt_index(ring);
380 	int reg = REG_RING_INTERRUPT_BASE + idx / 32 * 4;
381 	int bit = idx % 32;
382 	u32 val;
383 
384 	val = ioread32(ring->nhi->iobase + reg);
385 	if (mask)
386 		val &= ~BIT(bit);
387 	else
388 		val |= BIT(bit);
389 	iowrite32(val, ring->nhi->iobase + reg);
390 }
391 
392 /* Both @nhi->lock and @ring->lock should be held */
393 static void __ring_interrupt(struct tb_ring *ring)
394 {
395 	if (!ring->running)
396 		return;
397 
398 	if (ring->start_poll) {
399 		__ring_interrupt_mask(ring, true);
400 		ring->start_poll(ring->poll_data);
401 	} else {
402 		schedule_work(&ring->work);
403 	}
404 }
405 
406 /**
407  * tb_ring_poll_complete() - Re-start interrupt for the ring
408  * @ring: Ring to re-start the interrupt
409  *
410  * This will re-start (unmask) the ring interrupt once the user is done
411  * with polling.
412  */
413 void tb_ring_poll_complete(struct tb_ring *ring)
414 {
415 	unsigned long flags;
416 
417 	spin_lock_irqsave(&ring->nhi->lock, flags);
418 	spin_lock(&ring->lock);
419 	if (ring->start_poll)
420 		__ring_interrupt_mask(ring, false);
421 	spin_unlock(&ring->lock);
422 	spin_unlock_irqrestore(&ring->nhi->lock, flags);
423 }
424 EXPORT_SYMBOL_GPL(tb_ring_poll_complete);
425 
426 static void ring_clear_msix(const struct tb_ring *ring)
427 {
428 	int bit;
429 
430 	if (ring->nhi->quirks & QUIRK_AUTO_CLEAR_INT)
431 		return;
432 
433 	bit = ring_interrupt_index(ring) & 31;
434 	if (ring->is_tx)
435 		iowrite32(BIT(bit), ring->nhi->iobase + REG_RING_INT_CLEAR);
436 	else
437 		iowrite32(BIT(bit), ring->nhi->iobase + REG_RING_INT_CLEAR +
438 			  4 * (ring->nhi->hop_count / 32));
439 }
440 
441 static irqreturn_t ring_msix(int irq, void *data)
442 {
443 	struct tb_ring *ring = data;
444 
445 	spin_lock(&ring->nhi->lock);
446 	ring_clear_msix(ring);
447 	spin_lock(&ring->lock);
448 	__ring_interrupt(ring);
449 	spin_unlock(&ring->lock);
450 	spin_unlock(&ring->nhi->lock);
451 
452 	return IRQ_HANDLED;
453 }
454 
455 static int ring_request_msix(struct tb_ring *ring, bool no_suspend)
456 {
457 	struct tb_nhi *nhi = ring->nhi;
458 	unsigned long irqflags;
459 	int ret;
460 
461 	if (!nhi->pdev->msix_enabled)
462 		return 0;
463 
464 	ret = ida_simple_get(&nhi->msix_ida, 0, MSIX_MAX_VECS, GFP_KERNEL);
465 	if (ret < 0)
466 		return ret;
467 
468 	ring->vector = ret;
469 
470 	ret = pci_irq_vector(ring->nhi->pdev, ring->vector);
471 	if (ret < 0)
472 		goto err_ida_remove;
473 
474 	ring->irq = ret;
475 
476 	irqflags = no_suspend ? IRQF_NO_SUSPEND : 0;
477 	ret = request_irq(ring->irq, ring_msix, irqflags, "thunderbolt", ring);
478 	if (ret)
479 		goto err_ida_remove;
480 
481 	return 0;
482 
483 err_ida_remove:
484 	ida_simple_remove(&nhi->msix_ida, ring->vector);
485 
486 	return ret;
487 }
488 
489 static void ring_release_msix(struct tb_ring *ring)
490 {
491 	if (ring->irq <= 0)
492 		return;
493 
494 	free_irq(ring->irq, ring);
495 	ida_simple_remove(&ring->nhi->msix_ida, ring->vector);
496 	ring->vector = 0;
497 	ring->irq = 0;
498 }
499 
500 static int nhi_alloc_hop(struct tb_nhi *nhi, struct tb_ring *ring)
501 {
502 	unsigned int start_hop = RING_FIRST_USABLE_HOPID;
503 	int ret = 0;
504 
505 	if (nhi->quirks & QUIRK_E2E) {
506 		start_hop = RING_FIRST_USABLE_HOPID + 1;
507 		if (ring->flags & RING_FLAG_E2E && !ring->is_tx) {
508 			dev_dbg(&nhi->pdev->dev, "quirking E2E TX HopID %u -> %u\n",
509 				ring->e2e_tx_hop, RING_E2E_RESERVED_HOPID);
510 			ring->e2e_tx_hop = RING_E2E_RESERVED_HOPID;
511 		}
512 	}
513 
514 	spin_lock_irq(&nhi->lock);
515 
516 	if (ring->hop < 0) {
517 		unsigned int i;
518 
519 		/*
520 		 * Automatically allocate HopID from the non-reserved
521 		 * range 1 .. hop_count - 1.
522 		 */
523 		for (i = start_hop; i < nhi->hop_count; i++) {
524 			if (ring->is_tx) {
525 				if (!nhi->tx_rings[i]) {
526 					ring->hop = i;
527 					break;
528 				}
529 			} else {
530 				if (!nhi->rx_rings[i]) {
531 					ring->hop = i;
532 					break;
533 				}
534 			}
535 		}
536 	}
537 
538 	if (ring->hop > 0 && ring->hop < start_hop) {
539 		dev_warn(&nhi->pdev->dev, "invalid hop: %d\n", ring->hop);
540 		ret = -EINVAL;
541 		goto err_unlock;
542 	}
543 	if (ring->hop < 0 || ring->hop >= nhi->hop_count) {
544 		dev_warn(&nhi->pdev->dev, "invalid hop: %d\n", ring->hop);
545 		ret = -EINVAL;
546 		goto err_unlock;
547 	}
548 	if (ring->is_tx && nhi->tx_rings[ring->hop]) {
549 		dev_warn(&nhi->pdev->dev, "TX hop %d already allocated\n",
550 			 ring->hop);
551 		ret = -EBUSY;
552 		goto err_unlock;
553 	}
554 	if (!ring->is_tx && nhi->rx_rings[ring->hop]) {
555 		dev_warn(&nhi->pdev->dev, "RX hop %d already allocated\n",
556 			 ring->hop);
557 		ret = -EBUSY;
558 		goto err_unlock;
559 	}
560 
561 	if (ring->is_tx)
562 		nhi->tx_rings[ring->hop] = ring;
563 	else
564 		nhi->rx_rings[ring->hop] = ring;
565 
566 err_unlock:
567 	spin_unlock_irq(&nhi->lock);
568 
569 	return ret;
570 }
571 
572 static struct tb_ring *tb_ring_alloc(struct tb_nhi *nhi, u32 hop, int size,
573 				     bool transmit, unsigned int flags,
574 				     int e2e_tx_hop, u16 sof_mask, u16 eof_mask,
575 				     void (*start_poll)(void *),
576 				     void *poll_data)
577 {
578 	struct tb_ring *ring = NULL;
579 
580 	dev_dbg(&nhi->pdev->dev, "allocating %s ring %d of size %d\n",
581 		transmit ? "TX" : "RX", hop, size);
582 
583 	ring = kzalloc(sizeof(*ring), GFP_KERNEL);
584 	if (!ring)
585 		return NULL;
586 
587 	spin_lock_init(&ring->lock);
588 	INIT_LIST_HEAD(&ring->queue);
589 	INIT_LIST_HEAD(&ring->in_flight);
590 	INIT_WORK(&ring->work, ring_work);
591 
592 	ring->nhi = nhi;
593 	ring->hop = hop;
594 	ring->is_tx = transmit;
595 	ring->size = size;
596 	ring->flags = flags;
597 	ring->e2e_tx_hop = e2e_tx_hop;
598 	ring->sof_mask = sof_mask;
599 	ring->eof_mask = eof_mask;
600 	ring->head = 0;
601 	ring->tail = 0;
602 	ring->running = false;
603 	ring->start_poll = start_poll;
604 	ring->poll_data = poll_data;
605 
606 	ring->descriptors = dma_alloc_coherent(&ring->nhi->pdev->dev,
607 			size * sizeof(*ring->descriptors),
608 			&ring->descriptors_dma, GFP_KERNEL | __GFP_ZERO);
609 	if (!ring->descriptors)
610 		goto err_free_ring;
611 
612 	if (ring_request_msix(ring, flags & RING_FLAG_NO_SUSPEND))
613 		goto err_free_descs;
614 
615 	if (nhi_alloc_hop(nhi, ring))
616 		goto err_release_msix;
617 
618 	return ring;
619 
620 err_release_msix:
621 	ring_release_msix(ring);
622 err_free_descs:
623 	dma_free_coherent(&ring->nhi->pdev->dev,
624 			  ring->size * sizeof(*ring->descriptors),
625 			  ring->descriptors, ring->descriptors_dma);
626 err_free_ring:
627 	kfree(ring);
628 
629 	return NULL;
630 }
631 
632 /**
633  * tb_ring_alloc_tx() - Allocate DMA ring for transmit
634  * @nhi: Pointer to the NHI the ring is to be allocated
635  * @hop: HopID (ring) to allocate
636  * @size: Number of entries in the ring
637  * @flags: Flags for the ring
638  */
639 struct tb_ring *tb_ring_alloc_tx(struct tb_nhi *nhi, int hop, int size,
640 				 unsigned int flags)
641 {
642 	return tb_ring_alloc(nhi, hop, size, true, flags, 0, 0, 0, NULL, NULL);
643 }
644 EXPORT_SYMBOL_GPL(tb_ring_alloc_tx);
645 
646 /**
647  * tb_ring_alloc_rx() - Allocate DMA ring for receive
648  * @nhi: Pointer to the NHI the ring is to be allocated
649  * @hop: HopID (ring) to allocate. Pass %-1 for automatic allocation.
650  * @size: Number of entries in the ring
651  * @flags: Flags for the ring
652  * @e2e_tx_hop: Transmit HopID when E2E is enabled in @flags
653  * @sof_mask: Mask of PDF values that start a frame
654  * @eof_mask: Mask of PDF values that end a frame
655  * @start_poll: If not %NULL the ring will call this function when an
656  *		interrupt is triggered and masked, instead of callback
657  *		in each Rx frame.
658  * @poll_data: Optional data passed to @start_poll
659  */
660 struct tb_ring *tb_ring_alloc_rx(struct tb_nhi *nhi, int hop, int size,
661 				 unsigned int flags, int e2e_tx_hop,
662 				 u16 sof_mask, u16 eof_mask,
663 				 void (*start_poll)(void *), void *poll_data)
664 {
665 	return tb_ring_alloc(nhi, hop, size, false, flags, e2e_tx_hop, sof_mask, eof_mask,
666 			     start_poll, poll_data);
667 }
668 EXPORT_SYMBOL_GPL(tb_ring_alloc_rx);
669 
670 /**
671  * tb_ring_start() - enable a ring
672  * @ring: Ring to start
673  *
674  * Must not be invoked in parallel with tb_ring_stop().
675  */
676 void tb_ring_start(struct tb_ring *ring)
677 {
678 	u16 frame_size;
679 	u32 flags;
680 
681 	spin_lock_irq(&ring->nhi->lock);
682 	spin_lock(&ring->lock);
683 	if (ring->nhi->going_away)
684 		goto err;
685 	if (ring->running) {
686 		dev_WARN(&ring->nhi->pdev->dev, "ring already started\n");
687 		goto err;
688 	}
689 	dev_dbg(&ring->nhi->pdev->dev, "starting %s %d\n",
690 		RING_TYPE(ring), ring->hop);
691 
692 	if (ring->flags & RING_FLAG_FRAME) {
693 		/* Means 4096 */
694 		frame_size = 0;
695 		flags = RING_FLAG_ENABLE;
696 	} else {
697 		frame_size = TB_FRAME_SIZE;
698 		flags = RING_FLAG_ENABLE | RING_FLAG_RAW;
699 	}
700 
701 	ring_iowrite64desc(ring, ring->descriptors_dma, 0);
702 	if (ring->is_tx) {
703 		ring_iowrite32desc(ring, ring->size, 12);
704 		ring_iowrite32options(ring, 0, 4); /* time releated ? */
705 		ring_iowrite32options(ring, flags, 0);
706 	} else {
707 		u32 sof_eof_mask = ring->sof_mask << 16 | ring->eof_mask;
708 
709 		ring_iowrite32desc(ring, (frame_size << 16) | ring->size, 12);
710 		ring_iowrite32options(ring, sof_eof_mask, 4);
711 		ring_iowrite32options(ring, flags, 0);
712 	}
713 
714 	/*
715 	 * Now that the ring valid bit is set we can configure E2E if
716 	 * enabled for the ring.
717 	 */
718 	if (ring->flags & RING_FLAG_E2E) {
719 		if (!ring->is_tx) {
720 			u32 hop;
721 
722 			hop = ring->e2e_tx_hop << REG_RX_OPTIONS_E2E_HOP_SHIFT;
723 			hop &= REG_RX_OPTIONS_E2E_HOP_MASK;
724 			flags |= hop;
725 
726 			dev_dbg(&ring->nhi->pdev->dev,
727 				"enabling E2E for %s %d with TX HopID %d\n",
728 				RING_TYPE(ring), ring->hop, ring->e2e_tx_hop);
729 		} else {
730 			dev_dbg(&ring->nhi->pdev->dev, "enabling E2E for %s %d\n",
731 				RING_TYPE(ring), ring->hop);
732 		}
733 
734 		flags |= RING_FLAG_E2E_FLOW_CONTROL;
735 		ring_iowrite32options(ring, flags, 0);
736 	}
737 
738 	ring_interrupt_active(ring, true);
739 	ring->running = true;
740 err:
741 	spin_unlock(&ring->lock);
742 	spin_unlock_irq(&ring->nhi->lock);
743 }
744 EXPORT_SYMBOL_GPL(tb_ring_start);
745 
746 /**
747  * tb_ring_stop() - shutdown a ring
748  * @ring: Ring to stop
749  *
750  * Must not be invoked from a callback.
751  *
752  * This method will disable the ring. Further calls to
753  * tb_ring_tx/tb_ring_rx will return -ESHUTDOWN until ring_stop has been
754  * called.
755  *
756  * All enqueued frames will be canceled and their callbacks will be executed
757  * with frame->canceled set to true (on the callback thread). This method
758  * returns only after all callback invocations have finished.
759  */
760 void tb_ring_stop(struct tb_ring *ring)
761 {
762 	spin_lock_irq(&ring->nhi->lock);
763 	spin_lock(&ring->lock);
764 	dev_dbg(&ring->nhi->pdev->dev, "stopping %s %d\n",
765 		RING_TYPE(ring), ring->hop);
766 	if (ring->nhi->going_away)
767 		goto err;
768 	if (!ring->running) {
769 		dev_WARN(&ring->nhi->pdev->dev, "%s %d already stopped\n",
770 			 RING_TYPE(ring), ring->hop);
771 		goto err;
772 	}
773 	ring_interrupt_active(ring, false);
774 
775 	ring_iowrite32options(ring, 0, 0);
776 	ring_iowrite64desc(ring, 0, 0);
777 	ring_iowrite32desc(ring, 0, 8);
778 	ring_iowrite32desc(ring, 0, 12);
779 	ring->head = 0;
780 	ring->tail = 0;
781 	ring->running = false;
782 
783 err:
784 	spin_unlock(&ring->lock);
785 	spin_unlock_irq(&ring->nhi->lock);
786 
787 	/*
788 	 * schedule ring->work to invoke callbacks on all remaining frames.
789 	 */
790 	schedule_work(&ring->work);
791 	flush_work(&ring->work);
792 }
793 EXPORT_SYMBOL_GPL(tb_ring_stop);
794 
795 /*
796  * tb_ring_free() - free ring
797  *
798  * When this method returns all invocations of ring->callback will have
799  * finished.
800  *
801  * Ring must be stopped.
802  *
803  * Must NOT be called from ring_frame->callback!
804  */
805 void tb_ring_free(struct tb_ring *ring)
806 {
807 	spin_lock_irq(&ring->nhi->lock);
808 	/*
809 	 * Dissociate the ring from the NHI. This also ensures that
810 	 * nhi_interrupt_work cannot reschedule ring->work.
811 	 */
812 	if (ring->is_tx)
813 		ring->nhi->tx_rings[ring->hop] = NULL;
814 	else
815 		ring->nhi->rx_rings[ring->hop] = NULL;
816 
817 	if (ring->running) {
818 		dev_WARN(&ring->nhi->pdev->dev, "%s %d still running\n",
819 			 RING_TYPE(ring), ring->hop);
820 	}
821 	spin_unlock_irq(&ring->nhi->lock);
822 
823 	ring_release_msix(ring);
824 
825 	dma_free_coherent(&ring->nhi->pdev->dev,
826 			  ring->size * sizeof(*ring->descriptors),
827 			  ring->descriptors, ring->descriptors_dma);
828 
829 	ring->descriptors = NULL;
830 	ring->descriptors_dma = 0;
831 
832 
833 	dev_dbg(&ring->nhi->pdev->dev, "freeing %s %d\n", RING_TYPE(ring),
834 		ring->hop);
835 
836 	/*
837 	 * ring->work can no longer be scheduled (it is scheduled only
838 	 * by nhi_interrupt_work, ring_stop and ring_msix). Wait for it
839 	 * to finish before freeing the ring.
840 	 */
841 	flush_work(&ring->work);
842 	kfree(ring);
843 }
844 EXPORT_SYMBOL_GPL(tb_ring_free);
845 
846 /**
847  * nhi_mailbox_cmd() - Send a command through NHI mailbox
848  * @nhi: Pointer to the NHI structure
849  * @cmd: Command to send
850  * @data: Data to be send with the command
851  *
852  * Sends mailbox command to the firmware running on NHI. Returns %0 in
853  * case of success and negative errno in case of failure.
854  */
855 int nhi_mailbox_cmd(struct tb_nhi *nhi, enum nhi_mailbox_cmd cmd, u32 data)
856 {
857 	ktime_t timeout;
858 	u32 val;
859 
860 	iowrite32(data, nhi->iobase + REG_INMAIL_DATA);
861 
862 	val = ioread32(nhi->iobase + REG_INMAIL_CMD);
863 	val &= ~(REG_INMAIL_CMD_MASK | REG_INMAIL_ERROR);
864 	val |= REG_INMAIL_OP_REQUEST | cmd;
865 	iowrite32(val, nhi->iobase + REG_INMAIL_CMD);
866 
867 	timeout = ktime_add_ms(ktime_get(), NHI_MAILBOX_TIMEOUT);
868 	do {
869 		val = ioread32(nhi->iobase + REG_INMAIL_CMD);
870 		if (!(val & REG_INMAIL_OP_REQUEST))
871 			break;
872 		usleep_range(10, 20);
873 	} while (ktime_before(ktime_get(), timeout));
874 
875 	if (val & REG_INMAIL_OP_REQUEST)
876 		return -ETIMEDOUT;
877 	if (val & REG_INMAIL_ERROR)
878 		return -EIO;
879 
880 	return 0;
881 }
882 
883 /**
884  * nhi_mailbox_mode() - Return current firmware operation mode
885  * @nhi: Pointer to the NHI structure
886  *
887  * The function reads current firmware operation mode using NHI mailbox
888  * registers and returns it to the caller.
889  */
890 enum nhi_fw_mode nhi_mailbox_mode(struct tb_nhi *nhi)
891 {
892 	u32 val;
893 
894 	val = ioread32(nhi->iobase + REG_OUTMAIL_CMD);
895 	val &= REG_OUTMAIL_CMD_OPMODE_MASK;
896 	val >>= REG_OUTMAIL_CMD_OPMODE_SHIFT;
897 
898 	return (enum nhi_fw_mode)val;
899 }
900 
901 static void nhi_interrupt_work(struct work_struct *work)
902 {
903 	struct tb_nhi *nhi = container_of(work, typeof(*nhi), interrupt_work);
904 	int value = 0; /* Suppress uninitialized usage warning. */
905 	int bit;
906 	int hop = -1;
907 	int type = 0; /* current interrupt type 0: TX, 1: RX, 2: RX overflow */
908 	struct tb_ring *ring;
909 
910 	spin_lock_irq(&nhi->lock);
911 
912 	/*
913 	 * Starting at REG_RING_NOTIFY_BASE there are three status bitfields
914 	 * (TX, RX, RX overflow). We iterate over the bits and read a new
915 	 * dwords as required. The registers are cleared on read.
916 	 */
917 	for (bit = 0; bit < 3 * nhi->hop_count; bit++) {
918 		if (bit % 32 == 0)
919 			value = ioread32(nhi->iobase
920 					 + REG_RING_NOTIFY_BASE
921 					 + 4 * (bit / 32));
922 		if (++hop == nhi->hop_count) {
923 			hop = 0;
924 			type++;
925 		}
926 		if ((value & (1 << (bit % 32))) == 0)
927 			continue;
928 		if (type == 2) {
929 			dev_warn(&nhi->pdev->dev,
930 				 "RX overflow for ring %d\n",
931 				 hop);
932 			continue;
933 		}
934 		if (type == 0)
935 			ring = nhi->tx_rings[hop];
936 		else
937 			ring = nhi->rx_rings[hop];
938 		if (ring == NULL) {
939 			dev_warn(&nhi->pdev->dev,
940 				 "got interrupt for inactive %s ring %d\n",
941 				 type ? "RX" : "TX",
942 				 hop);
943 			continue;
944 		}
945 
946 		spin_lock(&ring->lock);
947 		__ring_interrupt(ring);
948 		spin_unlock(&ring->lock);
949 	}
950 	spin_unlock_irq(&nhi->lock);
951 }
952 
953 static irqreturn_t nhi_msi(int irq, void *data)
954 {
955 	struct tb_nhi *nhi = data;
956 	schedule_work(&nhi->interrupt_work);
957 	return IRQ_HANDLED;
958 }
959 
960 static int __nhi_suspend_noirq(struct device *dev, bool wakeup)
961 {
962 	struct pci_dev *pdev = to_pci_dev(dev);
963 	struct tb *tb = pci_get_drvdata(pdev);
964 	struct tb_nhi *nhi = tb->nhi;
965 	int ret;
966 
967 	ret = tb_domain_suspend_noirq(tb);
968 	if (ret)
969 		return ret;
970 
971 	if (nhi->ops && nhi->ops->suspend_noirq) {
972 		ret = nhi->ops->suspend_noirq(tb->nhi, wakeup);
973 		if (ret)
974 			return ret;
975 	}
976 
977 	return 0;
978 }
979 
980 static int nhi_suspend_noirq(struct device *dev)
981 {
982 	return __nhi_suspend_noirq(dev, device_may_wakeup(dev));
983 }
984 
985 static int nhi_freeze_noirq(struct device *dev)
986 {
987 	struct pci_dev *pdev = to_pci_dev(dev);
988 	struct tb *tb = pci_get_drvdata(pdev);
989 
990 	return tb_domain_freeze_noirq(tb);
991 }
992 
993 static int nhi_thaw_noirq(struct device *dev)
994 {
995 	struct pci_dev *pdev = to_pci_dev(dev);
996 	struct tb *tb = pci_get_drvdata(pdev);
997 
998 	return tb_domain_thaw_noirq(tb);
999 }
1000 
1001 static bool nhi_wake_supported(struct pci_dev *pdev)
1002 {
1003 	u8 val;
1004 
1005 	/*
1006 	 * If power rails are sustainable for wakeup from S4 this
1007 	 * property is set by the BIOS.
1008 	 */
1009 	if (device_property_read_u8(&pdev->dev, "WAKE_SUPPORTED", &val))
1010 		return !!val;
1011 
1012 	return true;
1013 }
1014 
1015 static int nhi_poweroff_noirq(struct device *dev)
1016 {
1017 	struct pci_dev *pdev = to_pci_dev(dev);
1018 	bool wakeup;
1019 
1020 	wakeup = device_may_wakeup(dev) && nhi_wake_supported(pdev);
1021 	return __nhi_suspend_noirq(dev, wakeup);
1022 }
1023 
1024 static void nhi_enable_int_throttling(struct tb_nhi *nhi)
1025 {
1026 	/* Throttling is specified in 256ns increments */
1027 	u32 throttle = DIV_ROUND_UP(128 * NSEC_PER_USEC, 256);
1028 	unsigned int i;
1029 
1030 	/*
1031 	 * Configure interrupt throttling for all vectors even if we
1032 	 * only use few.
1033 	 */
1034 	for (i = 0; i < MSIX_MAX_VECS; i++) {
1035 		u32 reg = REG_INT_THROTTLING_RATE + i * 4;
1036 		iowrite32(throttle, nhi->iobase + reg);
1037 	}
1038 }
1039 
1040 static int nhi_resume_noirq(struct device *dev)
1041 {
1042 	struct pci_dev *pdev = to_pci_dev(dev);
1043 	struct tb *tb = pci_get_drvdata(pdev);
1044 	struct tb_nhi *nhi = tb->nhi;
1045 	int ret;
1046 
1047 	/*
1048 	 * Check that the device is still there. It may be that the user
1049 	 * unplugged last device which causes the host controller to go
1050 	 * away on PCs.
1051 	 */
1052 	if (!pci_device_is_present(pdev)) {
1053 		nhi->going_away = true;
1054 	} else {
1055 		if (nhi->ops && nhi->ops->resume_noirq) {
1056 			ret = nhi->ops->resume_noirq(nhi);
1057 			if (ret)
1058 				return ret;
1059 		}
1060 		nhi_enable_int_throttling(tb->nhi);
1061 	}
1062 
1063 	return tb_domain_resume_noirq(tb);
1064 }
1065 
1066 static int nhi_suspend(struct device *dev)
1067 {
1068 	struct pci_dev *pdev = to_pci_dev(dev);
1069 	struct tb *tb = pci_get_drvdata(pdev);
1070 
1071 	return tb_domain_suspend(tb);
1072 }
1073 
1074 static void nhi_complete(struct device *dev)
1075 {
1076 	struct pci_dev *pdev = to_pci_dev(dev);
1077 	struct tb *tb = pci_get_drvdata(pdev);
1078 
1079 	/*
1080 	 * If we were runtime suspended when system suspend started,
1081 	 * schedule runtime resume now. It should bring the domain back
1082 	 * to functional state.
1083 	 */
1084 	if (pm_runtime_suspended(&pdev->dev))
1085 		pm_runtime_resume(&pdev->dev);
1086 	else
1087 		tb_domain_complete(tb);
1088 }
1089 
1090 static int nhi_runtime_suspend(struct device *dev)
1091 {
1092 	struct pci_dev *pdev = to_pci_dev(dev);
1093 	struct tb *tb = pci_get_drvdata(pdev);
1094 	struct tb_nhi *nhi = tb->nhi;
1095 	int ret;
1096 
1097 	ret = tb_domain_runtime_suspend(tb);
1098 	if (ret)
1099 		return ret;
1100 
1101 	if (nhi->ops && nhi->ops->runtime_suspend) {
1102 		ret = nhi->ops->runtime_suspend(tb->nhi);
1103 		if (ret)
1104 			return ret;
1105 	}
1106 	return 0;
1107 }
1108 
1109 static int nhi_runtime_resume(struct device *dev)
1110 {
1111 	struct pci_dev *pdev = to_pci_dev(dev);
1112 	struct tb *tb = pci_get_drvdata(pdev);
1113 	struct tb_nhi *nhi = tb->nhi;
1114 	int ret;
1115 
1116 	if (nhi->ops && nhi->ops->runtime_resume) {
1117 		ret = nhi->ops->runtime_resume(nhi);
1118 		if (ret)
1119 			return ret;
1120 	}
1121 
1122 	nhi_enable_int_throttling(nhi);
1123 	return tb_domain_runtime_resume(tb);
1124 }
1125 
1126 static void nhi_shutdown(struct tb_nhi *nhi)
1127 {
1128 	int i;
1129 
1130 	dev_dbg(&nhi->pdev->dev, "shutdown\n");
1131 
1132 	for (i = 0; i < nhi->hop_count; i++) {
1133 		if (nhi->tx_rings[i])
1134 			dev_WARN(&nhi->pdev->dev,
1135 				 "TX ring %d is still active\n", i);
1136 		if (nhi->rx_rings[i])
1137 			dev_WARN(&nhi->pdev->dev,
1138 				 "RX ring %d is still active\n", i);
1139 	}
1140 	nhi_disable_interrupts(nhi);
1141 	/*
1142 	 * We have to release the irq before calling flush_work. Otherwise an
1143 	 * already executing IRQ handler could call schedule_work again.
1144 	 */
1145 	if (!nhi->pdev->msix_enabled) {
1146 		devm_free_irq(&nhi->pdev->dev, nhi->pdev->irq, nhi);
1147 		flush_work(&nhi->interrupt_work);
1148 	}
1149 	ida_destroy(&nhi->msix_ida);
1150 
1151 	if (nhi->ops && nhi->ops->shutdown)
1152 		nhi->ops->shutdown(nhi);
1153 }
1154 
1155 static void nhi_check_quirks(struct tb_nhi *nhi)
1156 {
1157 	if (nhi->pdev->vendor == PCI_VENDOR_ID_INTEL) {
1158 		/*
1159 		 * Intel hardware supports auto clear of the interrupt
1160 		 * status register right after interrupt is being
1161 		 * issued.
1162 		 */
1163 		nhi->quirks |= QUIRK_AUTO_CLEAR_INT;
1164 
1165 		switch (nhi->pdev->device) {
1166 		case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_NHI:
1167 		case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_NHI:
1168 			/*
1169 			 * Falcon Ridge controller needs the end-to-end
1170 			 * flow control workaround to avoid losing Rx
1171 			 * packets when RING_FLAG_E2E is set.
1172 			 */
1173 			nhi->quirks |= QUIRK_E2E;
1174 			break;
1175 		}
1176 	}
1177 }
1178 
1179 static int nhi_check_iommu_pdev(struct pci_dev *pdev, void *data)
1180 {
1181 	if (!pdev->external_facing ||
1182 	    !device_iommu_capable(&pdev->dev, IOMMU_CAP_PRE_BOOT_PROTECTION))
1183 		return 0;
1184 	*(bool *)data = true;
1185 	return 1; /* Stop walking */
1186 }
1187 
1188 static void nhi_check_iommu(struct tb_nhi *nhi)
1189 {
1190 	struct pci_bus *bus = nhi->pdev->bus;
1191 	bool port_ok = false;
1192 
1193 	/*
1194 	 * Ideally what we'd do here is grab every PCI device that
1195 	 * represents a tunnelling adapter for this NHI and check their
1196 	 * status directly, but unfortunately USB4 seems to make it
1197 	 * obnoxiously difficult to reliably make any correlation.
1198 	 *
1199 	 * So for now we'll have to bodge it... Hoping that the system
1200 	 * is at least sane enough that an adapter is in the same PCI
1201 	 * segment as its NHI, if we can find *something* on that segment
1202 	 * which meets the requirements for Kernel DMA Protection, we'll
1203 	 * take that to imply that firmware is aware and has (hopefully)
1204 	 * done the right thing in general. We need to know that the PCI
1205 	 * layer has seen the ExternalFacingPort property which will then
1206 	 * inform the IOMMU layer to enforce the complete "untrusted DMA"
1207 	 * flow, but also that the IOMMU driver itself can be trusted not
1208 	 * to have been subverted by a pre-boot DMA attack.
1209 	 */
1210 	while (bus->parent)
1211 		bus = bus->parent;
1212 
1213 	pci_walk_bus(bus, nhi_check_iommu_pdev, &port_ok);
1214 
1215 	nhi->iommu_dma_protection = port_ok;
1216 	dev_dbg(&nhi->pdev->dev, "IOMMU DMA protection is %s\n",
1217 		str_enabled_disabled(port_ok));
1218 }
1219 
1220 static int nhi_init_msi(struct tb_nhi *nhi)
1221 {
1222 	struct pci_dev *pdev = nhi->pdev;
1223 	struct device *dev = &pdev->dev;
1224 	int res, irq, nvec;
1225 
1226 	/* In case someone left them on. */
1227 	nhi_disable_interrupts(nhi);
1228 
1229 	nhi_enable_int_throttling(nhi);
1230 
1231 	ida_init(&nhi->msix_ida);
1232 
1233 	/*
1234 	 * The NHI has 16 MSI-X vectors or a single MSI. We first try to
1235 	 * get all MSI-X vectors and if we succeed, each ring will have
1236 	 * one MSI-X. If for some reason that does not work out, we
1237 	 * fallback to a single MSI.
1238 	 */
1239 	nvec = pci_alloc_irq_vectors(pdev, MSIX_MIN_VECS, MSIX_MAX_VECS,
1240 				     PCI_IRQ_MSIX);
1241 	if (nvec < 0) {
1242 		nvec = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_MSI);
1243 		if (nvec < 0)
1244 			return nvec;
1245 
1246 		INIT_WORK(&nhi->interrupt_work, nhi_interrupt_work);
1247 
1248 		irq = pci_irq_vector(nhi->pdev, 0);
1249 		if (irq < 0)
1250 			return irq;
1251 
1252 		res = devm_request_irq(&pdev->dev, irq, nhi_msi,
1253 				       IRQF_NO_SUSPEND, "thunderbolt", nhi);
1254 		if (res)
1255 			return dev_err_probe(dev, res, "request_irq failed, aborting\n");
1256 	}
1257 
1258 	return 0;
1259 }
1260 
1261 static bool nhi_imr_valid(struct pci_dev *pdev)
1262 {
1263 	u8 val;
1264 
1265 	if (!device_property_read_u8(&pdev->dev, "IMR_VALID", &val))
1266 		return !!val;
1267 
1268 	return true;
1269 }
1270 
1271 static struct tb *nhi_select_cm(struct tb_nhi *nhi)
1272 {
1273 	struct tb *tb;
1274 
1275 	/*
1276 	 * USB4 case is simple. If we got control of any of the
1277 	 * capabilities, we use software CM.
1278 	 */
1279 	if (tb_acpi_is_native())
1280 		return tb_probe(nhi);
1281 
1282 	/*
1283 	 * Either firmware based CM is running (we did not get control
1284 	 * from the firmware) or this is pre-USB4 PC so try first
1285 	 * firmware CM and then fallback to software CM.
1286 	 */
1287 	tb = icm_probe(nhi);
1288 	if (!tb)
1289 		tb = tb_probe(nhi);
1290 
1291 	return tb;
1292 }
1293 
1294 static int nhi_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1295 {
1296 	struct device *dev = &pdev->dev;
1297 	struct tb_nhi *nhi;
1298 	struct tb *tb;
1299 	int res;
1300 
1301 	if (!nhi_imr_valid(pdev))
1302 		return dev_err_probe(dev, -ENODEV, "firmware image not valid, aborting\n");
1303 
1304 	res = pcim_enable_device(pdev);
1305 	if (res)
1306 		return dev_err_probe(dev, res, "cannot enable PCI device, aborting\n");
1307 
1308 	res = pcim_iomap_regions(pdev, 1 << 0, "thunderbolt");
1309 	if (res)
1310 		return dev_err_probe(dev, res, "cannot obtain PCI resources, aborting\n");
1311 
1312 	nhi = devm_kzalloc(&pdev->dev, sizeof(*nhi), GFP_KERNEL);
1313 	if (!nhi)
1314 		return -ENOMEM;
1315 
1316 	nhi->pdev = pdev;
1317 	nhi->ops = (const struct tb_nhi_ops *)id->driver_data;
1318 	/* cannot fail - table is allocated in pcim_iomap_regions */
1319 	nhi->iobase = pcim_iomap_table(pdev)[0];
1320 	nhi->hop_count = ioread32(nhi->iobase + REG_HOP_COUNT) & 0x3ff;
1321 	dev_dbg(dev, "total paths: %d\n", nhi->hop_count);
1322 
1323 	nhi->tx_rings = devm_kcalloc(&pdev->dev, nhi->hop_count,
1324 				     sizeof(*nhi->tx_rings), GFP_KERNEL);
1325 	nhi->rx_rings = devm_kcalloc(&pdev->dev, nhi->hop_count,
1326 				     sizeof(*nhi->rx_rings), GFP_KERNEL);
1327 	if (!nhi->tx_rings || !nhi->rx_rings)
1328 		return -ENOMEM;
1329 
1330 	nhi_check_quirks(nhi);
1331 	nhi_check_iommu(nhi);
1332 
1333 	res = nhi_init_msi(nhi);
1334 	if (res)
1335 		return dev_err_probe(dev, res, "cannot enable MSI, aborting\n");
1336 
1337 	spin_lock_init(&nhi->lock);
1338 
1339 	res = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
1340 	if (res)
1341 		return dev_err_probe(dev, res, "failed to set DMA mask\n");
1342 
1343 	pci_set_master(pdev);
1344 
1345 	if (nhi->ops && nhi->ops->init) {
1346 		res = nhi->ops->init(nhi);
1347 		if (res)
1348 			return res;
1349 	}
1350 
1351 	tb = nhi_select_cm(nhi);
1352 	if (!tb)
1353 		return dev_err_probe(dev, -ENODEV,
1354 			"failed to determine connection manager, aborting\n");
1355 
1356 	dev_dbg(dev, "NHI initialized, starting thunderbolt\n");
1357 
1358 	res = tb_domain_add(tb);
1359 	if (res) {
1360 		/*
1361 		 * At this point the RX/TX rings might already have been
1362 		 * activated. Do a proper shutdown.
1363 		 */
1364 		tb_domain_put(tb);
1365 		nhi_shutdown(nhi);
1366 		return res;
1367 	}
1368 	pci_set_drvdata(pdev, tb);
1369 
1370 	device_wakeup_enable(&pdev->dev);
1371 
1372 	pm_runtime_allow(&pdev->dev);
1373 	pm_runtime_set_autosuspend_delay(&pdev->dev, TB_AUTOSUSPEND_DELAY);
1374 	pm_runtime_use_autosuspend(&pdev->dev);
1375 	pm_runtime_put_autosuspend(&pdev->dev);
1376 
1377 	return 0;
1378 }
1379 
1380 static void nhi_remove(struct pci_dev *pdev)
1381 {
1382 	struct tb *tb = pci_get_drvdata(pdev);
1383 	struct tb_nhi *nhi = tb->nhi;
1384 
1385 	pm_runtime_get_sync(&pdev->dev);
1386 	pm_runtime_dont_use_autosuspend(&pdev->dev);
1387 	pm_runtime_forbid(&pdev->dev);
1388 
1389 	tb_domain_remove(tb);
1390 	nhi_shutdown(nhi);
1391 }
1392 
1393 /*
1394  * The tunneled pci bridges are siblings of us. Use resume_noirq to reenable
1395  * the tunnels asap. A corresponding pci quirk blocks the downstream bridges
1396  * resume_noirq until we are done.
1397  */
1398 static const struct dev_pm_ops nhi_pm_ops = {
1399 	.suspend_noirq = nhi_suspend_noirq,
1400 	.resume_noirq = nhi_resume_noirq,
1401 	.freeze_noirq = nhi_freeze_noirq,  /*
1402 					    * we just disable hotplug, the
1403 					    * pci-tunnels stay alive.
1404 					    */
1405 	.thaw_noirq = nhi_thaw_noirq,
1406 	.restore_noirq = nhi_resume_noirq,
1407 	.suspend = nhi_suspend,
1408 	.poweroff_noirq = nhi_poweroff_noirq,
1409 	.poweroff = nhi_suspend,
1410 	.complete = nhi_complete,
1411 	.runtime_suspend = nhi_runtime_suspend,
1412 	.runtime_resume = nhi_runtime_resume,
1413 };
1414 
1415 static struct pci_device_id nhi_ids[] = {
1416 	/*
1417 	 * We have to specify class, the TB bridges use the same device and
1418 	 * vendor (sub)id on gen 1 and gen 2 controllers.
1419 	 */
1420 	{
1421 		.class = PCI_CLASS_SYSTEM_OTHER << 8, .class_mask = ~0,
1422 		.vendor = PCI_VENDOR_ID_INTEL,
1423 		.device = PCI_DEVICE_ID_INTEL_LIGHT_RIDGE,
1424 		.subvendor = 0x2222, .subdevice = 0x1111,
1425 	},
1426 	{
1427 		.class = PCI_CLASS_SYSTEM_OTHER << 8, .class_mask = ~0,
1428 		.vendor = PCI_VENDOR_ID_INTEL,
1429 		.device = PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C,
1430 		.subvendor = 0x2222, .subdevice = 0x1111,
1431 	},
1432 	{
1433 		.class = PCI_CLASS_SYSTEM_OTHER << 8, .class_mask = ~0,
1434 		.vendor = PCI_VENDOR_ID_INTEL,
1435 		.device = PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_NHI,
1436 		.subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID,
1437 	},
1438 	{
1439 		.class = PCI_CLASS_SYSTEM_OTHER << 8, .class_mask = ~0,
1440 		.vendor = PCI_VENDOR_ID_INTEL,
1441 		.device = PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_NHI,
1442 		.subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID,
1443 	},
1444 
1445 	/* Thunderbolt 3 */
1446 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_2C_NHI) },
1447 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_4C_NHI) },
1448 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_USBONLY_NHI) },
1449 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_LP_NHI) },
1450 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_LP_USBONLY_NHI) },
1451 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_2C_NHI) },
1452 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_4C_NHI) },
1453 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_USBONLY_NHI) },
1454 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_TITAN_RIDGE_2C_NHI) },
1455 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_TITAN_RIDGE_4C_NHI) },
1456 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ICL_NHI0),
1457 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1458 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ICL_NHI1),
1459 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1460 	/* Thunderbolt 4 */
1461 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_TGL_NHI0),
1462 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1463 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_TGL_NHI1),
1464 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1465 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_TGL_H_NHI0),
1466 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1467 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_TGL_H_NHI1),
1468 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1469 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ADL_NHI0),
1470 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1471 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_ADL_NHI1),
1472 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1473 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_RPL_NHI0),
1474 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1475 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_RPL_NHI1),
1476 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1477 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_MTL_M_NHI0),
1478 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1479 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_MTL_P_NHI0),
1480 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1481 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_MTL_P_NHI1),
1482 	  .driver_data = (kernel_ulong_t)&icl_nhi_ops },
1483 
1484 	/* Any USB4 compliant host */
1485 	{ PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_USB_USB4, ~0) },
1486 
1487 	{ 0,}
1488 };
1489 
1490 MODULE_DEVICE_TABLE(pci, nhi_ids);
1491 MODULE_LICENSE("GPL");
1492 
1493 static struct pci_driver nhi_driver = {
1494 	.name = "thunderbolt",
1495 	.id_table = nhi_ids,
1496 	.probe = nhi_probe,
1497 	.remove = nhi_remove,
1498 	.shutdown = nhi_remove,
1499 	.driver.pm = &nhi_pm_ops,
1500 };
1501 
1502 static int __init nhi_init(void)
1503 {
1504 	int ret;
1505 
1506 	ret = tb_domain_init();
1507 	if (ret)
1508 		return ret;
1509 	ret = pci_register_driver(&nhi_driver);
1510 	if (ret)
1511 		tb_domain_exit();
1512 	return ret;
1513 }
1514 
1515 static void __exit nhi_unload(void)
1516 {
1517 	pci_unregister_driver(&nhi_driver);
1518 	tb_domain_exit();
1519 }
1520 
1521 rootfs_initcall(nhi_init);
1522 module_exit(nhi_unload);
1523