xref: /openbmc/linux/drivers/usb/host/xhci-mem.c (revision 4ebdac060e5e24a89a7b3ec33ec46a41621e57fe)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * xHCI host controller driver
4  *
5  * Copyright (C) 2008 Intel Corp.
6  *
7  * Author: Sarah Sharp
8  * Some code borrowed from the Linux EHCI driver.
9  */
10 
11 #include <linux/usb.h>
12 #include <linux/overflow.h>
13 #include <linux/pci.h>
14 #include <linux/slab.h>
15 #include <linux/dmapool.h>
16 #include <linux/dma-mapping.h>
17 
18 #include "xhci.h"
19 #include "xhci-trace.h"
20 #include "xhci-debugfs.h"
21 
22 /*
23  * Allocates a generic ring segment from the ring pool, sets the dma address,
24  * initializes the segment to zero, and sets the private next pointer to NULL.
25  *
26  * Section 4.11.1.1:
27  * "All components of all Command and Transfer TRBs shall be initialized to '0'"
28  */
xhci_segment_alloc(struct xhci_hcd * xhci,unsigned int cycle_state,unsigned int max_packet,unsigned int num,gfp_t flags)29 static struct xhci_segment *xhci_segment_alloc(struct xhci_hcd *xhci,
30 					       unsigned int cycle_state,
31 					       unsigned int max_packet,
32 					       unsigned int num,
33 					       gfp_t flags)
34 {
35 	struct xhci_segment *seg;
36 	dma_addr_t	dma;
37 	int		i;
38 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
39 
40 	seg = kzalloc_node(sizeof(*seg), flags, dev_to_node(dev));
41 	if (!seg)
42 		return NULL;
43 
44 	seg->trbs = dma_pool_zalloc(xhci->segment_pool, flags, &dma);
45 	if (!seg->trbs) {
46 		kfree(seg);
47 		return NULL;
48 	}
49 
50 	if (max_packet) {
51 		seg->bounce_buf = kzalloc_node(max_packet, flags,
52 					dev_to_node(dev));
53 		if (!seg->bounce_buf) {
54 			dma_pool_free(xhci->segment_pool, seg->trbs, dma);
55 			kfree(seg);
56 			return NULL;
57 		}
58 	}
59 	/* If the cycle state is 0, set the cycle bit to 1 for all the TRBs */
60 	if (cycle_state == 0) {
61 		for (i = 0; i < TRBS_PER_SEGMENT; i++)
62 			seg->trbs[i].link.control = cpu_to_le32(TRB_CYCLE);
63 	}
64 	seg->num = num;
65 	seg->dma = dma;
66 	seg->next = NULL;
67 
68 	return seg;
69 }
70 
xhci_segment_free(struct xhci_hcd * xhci,struct xhci_segment * seg)71 static void xhci_segment_free(struct xhci_hcd *xhci, struct xhci_segment *seg)
72 {
73 	if (seg->trbs) {
74 		dma_pool_free(xhci->segment_pool, seg->trbs, seg->dma);
75 		seg->trbs = NULL;
76 	}
77 	kfree(seg->bounce_buf);
78 	kfree(seg);
79 }
80 
xhci_free_segments_for_ring(struct xhci_hcd * xhci,struct xhci_segment * first)81 static void xhci_free_segments_for_ring(struct xhci_hcd *xhci,
82 				struct xhci_segment *first)
83 {
84 	struct xhci_segment *seg;
85 
86 	seg = first->next;
87 	while (seg != first) {
88 		struct xhci_segment *next = seg->next;
89 		xhci_segment_free(xhci, seg);
90 		seg = next;
91 	}
92 	xhci_segment_free(xhci, first);
93 }
94 
95 /*
96  * Make the prev segment point to the next segment.
97  *
98  * Change the last TRB in the prev segment to be a Link TRB which points to the
99  * DMA address of the next segment.  The caller needs to set any Link TRB
100  * related flags, such as End TRB, Toggle Cycle, and no snoop.
101  */
xhci_link_segments(struct xhci_segment * prev,struct xhci_segment * next,enum xhci_ring_type type,bool chain_links)102 static void xhci_link_segments(struct xhci_segment *prev,
103 			       struct xhci_segment *next,
104 			       enum xhci_ring_type type, bool chain_links)
105 {
106 	u32 val;
107 
108 	if (!prev || !next)
109 		return;
110 	prev->next = next;
111 	if (type != TYPE_EVENT) {
112 		prev->trbs[TRBS_PER_SEGMENT-1].link.segment_ptr =
113 			cpu_to_le64(next->dma);
114 
115 		/* Set the last TRB in the segment to have a TRB type ID of Link TRB */
116 		val = le32_to_cpu(prev->trbs[TRBS_PER_SEGMENT-1].link.control);
117 		val &= ~TRB_TYPE_BITMASK;
118 		val |= TRB_TYPE(TRB_LINK);
119 		if (chain_links)
120 			val |= TRB_CHAIN;
121 		prev->trbs[TRBS_PER_SEGMENT-1].link.control = cpu_to_le32(val);
122 	}
123 }
124 
125 /*
126  * Link the ring to the new segments.
127  * Set Toggle Cycle for the new ring if needed.
128  */
xhci_link_rings(struct xhci_hcd * xhci,struct xhci_ring * ring,struct xhci_segment * first,struct xhci_segment * last,unsigned int num_segs)129 static void xhci_link_rings(struct xhci_hcd *xhci, struct xhci_ring *ring,
130 		struct xhci_segment *first, struct xhci_segment *last,
131 		unsigned int num_segs)
132 {
133 	struct xhci_segment *next;
134 	bool chain_links;
135 
136 	if (!ring || !first || !last)
137 		return;
138 
139 	/* Set chain bit for 0.95 hosts, and for isoc rings on AMD 0.96 host */
140 	chain_links = !!(xhci_link_trb_quirk(xhci) ||
141 			 (ring->type == TYPE_ISOC &&
142 			  (xhci->quirks & XHCI_AMD_0x96_HOST)));
143 
144 	next = ring->enq_seg->next;
145 	xhci_link_segments(ring->enq_seg, first, ring->type, chain_links);
146 	xhci_link_segments(last, next, ring->type, chain_links);
147 	ring->num_segs += num_segs;
148 
149 	if (ring->type != TYPE_EVENT && ring->enq_seg == ring->last_seg) {
150 		ring->last_seg->trbs[TRBS_PER_SEGMENT-1].link.control
151 			&= ~cpu_to_le32(LINK_TOGGLE);
152 		last->trbs[TRBS_PER_SEGMENT-1].link.control
153 			|= cpu_to_le32(LINK_TOGGLE);
154 		ring->last_seg = last;
155 	}
156 }
157 
158 /*
159  * We need a radix tree for mapping physical addresses of TRBs to which stream
160  * ID they belong to.  We need to do this because the host controller won't tell
161  * us which stream ring the TRB came from.  We could store the stream ID in an
162  * event data TRB, but that doesn't help us for the cancellation case, since the
163  * endpoint may stop before it reaches that event data TRB.
164  *
165  * The radix tree maps the upper portion of the TRB DMA address to a ring
166  * segment that has the same upper portion of DMA addresses.  For example, say I
167  * have segments of size 1KB, that are always 1KB aligned.  A segment may
168  * start at 0x10c91000 and end at 0x10c913f0.  If I use the upper 10 bits, the
169  * key to the stream ID is 0x43244.  I can use the DMA address of the TRB to
170  * pass the radix tree a key to get the right stream ID:
171  *
172  *	0x10c90fff >> 10 = 0x43243
173  *	0x10c912c0 >> 10 = 0x43244
174  *	0x10c91400 >> 10 = 0x43245
175  *
176  * Obviously, only those TRBs with DMA addresses that are within the segment
177  * will make the radix tree return the stream ID for that ring.
178  *
179  * Caveats for the radix tree:
180  *
181  * The radix tree uses an unsigned long as a key pair.  On 32-bit systems, an
182  * unsigned long will be 32-bits; on a 64-bit system an unsigned long will be
183  * 64-bits.  Since we only request 32-bit DMA addresses, we can use that as the
184  * key on 32-bit or 64-bit systems (it would also be fine if we asked for 64-bit
185  * PCI DMA addresses on a 64-bit system).  There might be a problem on 32-bit
186  * extended systems (where the DMA address can be bigger than 32-bits),
187  * if we allow the PCI dma mask to be bigger than 32-bits.  So don't do that.
188  */
xhci_insert_segment_mapping(struct radix_tree_root * trb_address_map,struct xhci_ring * ring,struct xhci_segment * seg,gfp_t mem_flags)189 static int xhci_insert_segment_mapping(struct radix_tree_root *trb_address_map,
190 		struct xhci_ring *ring,
191 		struct xhci_segment *seg,
192 		gfp_t mem_flags)
193 {
194 	unsigned long key;
195 	int ret;
196 
197 	key = (unsigned long)(seg->dma >> TRB_SEGMENT_SHIFT);
198 	/* Skip any segments that were already added. */
199 	if (radix_tree_lookup(trb_address_map, key))
200 		return 0;
201 
202 	ret = radix_tree_maybe_preload(mem_flags);
203 	if (ret)
204 		return ret;
205 	ret = radix_tree_insert(trb_address_map,
206 			key, ring);
207 	radix_tree_preload_end();
208 	return ret;
209 }
210 
xhci_remove_segment_mapping(struct radix_tree_root * trb_address_map,struct xhci_segment * seg)211 static void xhci_remove_segment_mapping(struct radix_tree_root *trb_address_map,
212 		struct xhci_segment *seg)
213 {
214 	unsigned long key;
215 
216 	key = (unsigned long)(seg->dma >> TRB_SEGMENT_SHIFT);
217 	if (radix_tree_lookup(trb_address_map, key))
218 		radix_tree_delete(trb_address_map, key);
219 }
220 
xhci_update_stream_segment_mapping(struct radix_tree_root * trb_address_map,struct xhci_ring * ring,struct xhci_segment * first_seg,struct xhci_segment * last_seg,gfp_t mem_flags)221 static int xhci_update_stream_segment_mapping(
222 		struct radix_tree_root *trb_address_map,
223 		struct xhci_ring *ring,
224 		struct xhci_segment *first_seg,
225 		struct xhci_segment *last_seg,
226 		gfp_t mem_flags)
227 {
228 	struct xhci_segment *seg;
229 	struct xhci_segment *failed_seg;
230 	int ret;
231 
232 	if (WARN_ON_ONCE(trb_address_map == NULL))
233 		return 0;
234 
235 	seg = first_seg;
236 	do {
237 		ret = xhci_insert_segment_mapping(trb_address_map,
238 				ring, seg, mem_flags);
239 		if (ret)
240 			goto remove_streams;
241 		if (seg == last_seg)
242 			return 0;
243 		seg = seg->next;
244 	} while (seg != first_seg);
245 
246 	return 0;
247 
248 remove_streams:
249 	failed_seg = seg;
250 	seg = first_seg;
251 	do {
252 		xhci_remove_segment_mapping(trb_address_map, seg);
253 		if (seg == failed_seg)
254 			return ret;
255 		seg = seg->next;
256 	} while (seg != first_seg);
257 
258 	return ret;
259 }
260 
xhci_remove_stream_mapping(struct xhci_ring * ring)261 static void xhci_remove_stream_mapping(struct xhci_ring *ring)
262 {
263 	struct xhci_segment *seg;
264 
265 	if (WARN_ON_ONCE(ring->trb_address_map == NULL))
266 		return;
267 
268 	seg = ring->first_seg;
269 	do {
270 		xhci_remove_segment_mapping(ring->trb_address_map, seg);
271 		seg = seg->next;
272 	} while (seg != ring->first_seg);
273 }
274 
xhci_update_stream_mapping(struct xhci_ring * ring,gfp_t mem_flags)275 static int xhci_update_stream_mapping(struct xhci_ring *ring, gfp_t mem_flags)
276 {
277 	return xhci_update_stream_segment_mapping(ring->trb_address_map, ring,
278 			ring->first_seg, ring->last_seg, mem_flags);
279 }
280 
281 /* XXX: Do we need the hcd structure in all these functions? */
xhci_ring_free(struct xhci_hcd * xhci,struct xhci_ring * ring)282 void xhci_ring_free(struct xhci_hcd *xhci, struct xhci_ring *ring)
283 {
284 	if (!ring)
285 		return;
286 
287 	trace_xhci_ring_free(ring);
288 
289 	if (ring->first_seg) {
290 		if (ring->type == TYPE_STREAM)
291 			xhci_remove_stream_mapping(ring);
292 		xhci_free_segments_for_ring(xhci, ring->first_seg);
293 	}
294 
295 	kfree(ring);
296 }
297 
xhci_initialize_ring_info(struct xhci_ring * ring,unsigned int cycle_state)298 void xhci_initialize_ring_info(struct xhci_ring *ring,
299 			       unsigned int cycle_state)
300 {
301 	/* The ring is empty, so the enqueue pointer == dequeue pointer */
302 	ring->enqueue = ring->first_seg->trbs;
303 	ring->enq_seg = ring->first_seg;
304 	ring->dequeue = ring->enqueue;
305 	ring->deq_seg = ring->first_seg;
306 	/* The ring is initialized to 0. The producer must write 1 to the cycle
307 	 * bit to handover ownership of the TRB, so PCS = 1.  The consumer must
308 	 * compare CCS to the cycle bit to check ownership, so CCS = 1.
309 	 *
310 	 * New rings are initialized with cycle state equal to 1; if we are
311 	 * handling ring expansion, set the cycle state equal to the old ring.
312 	 */
313 	ring->cycle_state = cycle_state;
314 
315 	/*
316 	 * Each segment has a link TRB, and leave an extra TRB for SW
317 	 * accounting purpose
318 	 */
319 	ring->num_trbs_free = ring->num_segs * (TRBS_PER_SEGMENT - 1) - 1;
320 }
321 EXPORT_SYMBOL_GPL(xhci_initialize_ring_info);
322 
323 /* Allocate segments and link them for a ring */
xhci_alloc_segments_for_ring(struct xhci_hcd * xhci,struct xhci_segment ** first,struct xhci_segment ** last,unsigned int num_segs,unsigned int cycle_state,enum xhci_ring_type type,unsigned int max_packet,gfp_t flags)324 static int xhci_alloc_segments_for_ring(struct xhci_hcd *xhci,
325 		struct xhci_segment **first, struct xhci_segment **last,
326 		unsigned int num_segs, unsigned int cycle_state,
327 		enum xhci_ring_type type, unsigned int max_packet, gfp_t flags)
328 {
329 	struct xhci_segment *prev;
330 	unsigned int num = 0;
331 	bool chain_links;
332 
333 	/* Set chain bit for 0.95 hosts, and for isoc rings on AMD 0.96 host */
334 	chain_links = !!(xhci_link_trb_quirk(xhci) ||
335 			 (type == TYPE_ISOC &&
336 			  (xhci->quirks & XHCI_AMD_0x96_HOST)));
337 
338 	prev = xhci_segment_alloc(xhci, cycle_state, max_packet, num, flags);
339 	if (!prev)
340 		return -ENOMEM;
341 	num++;
342 
343 	*first = prev;
344 	while (num < num_segs) {
345 		struct xhci_segment	*next;
346 
347 		next = xhci_segment_alloc(xhci, cycle_state, max_packet, num,
348 					  flags);
349 		if (!next) {
350 			prev = *first;
351 			while (prev) {
352 				next = prev->next;
353 				xhci_segment_free(xhci, prev);
354 				prev = next;
355 			}
356 			return -ENOMEM;
357 		}
358 		xhci_link_segments(prev, next, type, chain_links);
359 
360 		prev = next;
361 		num++;
362 	}
363 	xhci_link_segments(prev, *first, type, chain_links);
364 	*last = prev;
365 
366 	return 0;
367 }
368 
369 /*
370  * Create a new ring with zero or more segments.
371  *
372  * Link each segment together into a ring.
373  * Set the end flag and the cycle toggle bit on the last segment.
374  * See section 4.9.1 and figures 15 and 16.
375  */
xhci_ring_alloc(struct xhci_hcd * xhci,unsigned int num_segs,unsigned int cycle_state,enum xhci_ring_type type,unsigned int max_packet,gfp_t flags)376 struct xhci_ring *xhci_ring_alloc(struct xhci_hcd *xhci,
377 		unsigned int num_segs, unsigned int cycle_state,
378 		enum xhci_ring_type type, unsigned int max_packet, gfp_t flags)
379 {
380 	struct xhci_ring	*ring;
381 	int ret;
382 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
383 
384 	ring = kzalloc_node(sizeof(*ring), flags, dev_to_node(dev));
385 	if (!ring)
386 		return NULL;
387 
388 	ring->num_segs = num_segs;
389 	ring->bounce_buf_len = max_packet;
390 	INIT_LIST_HEAD(&ring->td_list);
391 	ring->type = type;
392 	if (num_segs == 0)
393 		return ring;
394 
395 	ret = xhci_alloc_segments_for_ring(xhci, &ring->first_seg,
396 			&ring->last_seg, num_segs, cycle_state, type,
397 			max_packet, flags);
398 	if (ret)
399 		goto fail;
400 
401 	/* Only event ring does not use link TRB */
402 	if (type != TYPE_EVENT) {
403 		/* See section 4.9.2.1 and 6.4.4.1 */
404 		ring->last_seg->trbs[TRBS_PER_SEGMENT - 1].link.control |=
405 			cpu_to_le32(LINK_TOGGLE);
406 	}
407 	xhci_initialize_ring_info(ring, cycle_state);
408 	trace_xhci_ring_alloc(ring);
409 	return ring;
410 
411 fail:
412 	kfree(ring);
413 	return NULL;
414 }
415 
xhci_free_endpoint_ring(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,unsigned int ep_index)416 void xhci_free_endpoint_ring(struct xhci_hcd *xhci,
417 		struct xhci_virt_device *virt_dev,
418 		unsigned int ep_index)
419 {
420 	xhci_ring_free(xhci, virt_dev->eps[ep_index].ring);
421 	virt_dev->eps[ep_index].ring = NULL;
422 }
423 
424 /*
425  * Expand an existing ring.
426  * Allocate a new ring which has same segment numbers and link the two rings.
427  */
xhci_ring_expansion(struct xhci_hcd * xhci,struct xhci_ring * ring,unsigned int num_new_segs,gfp_t flags)428 int xhci_ring_expansion(struct xhci_hcd *xhci, struct xhci_ring *ring,
429 				unsigned int num_new_segs, gfp_t flags)
430 {
431 	struct xhci_segment	*first;
432 	struct xhci_segment	*last;
433 	int			ret;
434 
435 	ret = xhci_alloc_segments_for_ring(xhci, &first, &last,
436 			num_new_segs, ring->cycle_state, ring->type,
437 			ring->bounce_buf_len, flags);
438 	if (ret)
439 		return -ENOMEM;
440 
441 	if (ring->type == TYPE_STREAM)
442 		ret = xhci_update_stream_segment_mapping(ring->trb_address_map,
443 						ring, first, last, flags);
444 	if (ret) {
445 		struct xhci_segment *next;
446 		do {
447 			next = first->next;
448 			xhci_segment_free(xhci, first);
449 			if (first == last)
450 				break;
451 			first = next;
452 		} while (true);
453 		return ret;
454 	}
455 
456 	xhci_link_rings(xhci, ring, first, last, num_new_segs);
457 	trace_xhci_ring_expansion(ring);
458 	xhci_dbg_trace(xhci, trace_xhci_dbg_ring_expansion,
459 			"ring expansion succeed, now has %d segments",
460 			ring->num_segs);
461 
462 	return 0;
463 }
464 
xhci_alloc_container_ctx(struct xhci_hcd * xhci,int type,gfp_t flags)465 struct xhci_container_ctx *xhci_alloc_container_ctx(struct xhci_hcd *xhci,
466 						    int type, gfp_t flags)
467 {
468 	struct xhci_container_ctx *ctx;
469 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
470 
471 	if ((type != XHCI_CTX_TYPE_DEVICE) && (type != XHCI_CTX_TYPE_INPUT))
472 		return NULL;
473 
474 	ctx = kzalloc_node(sizeof(*ctx), flags, dev_to_node(dev));
475 	if (!ctx)
476 		return NULL;
477 
478 	ctx->type = type;
479 	ctx->size = HCC_64BYTE_CONTEXT(xhci->hcc_params) ? 2048 : 1024;
480 	if (type == XHCI_CTX_TYPE_INPUT)
481 		ctx->size += CTX_SIZE(xhci->hcc_params);
482 
483 	ctx->bytes = dma_pool_zalloc(xhci->device_pool, flags, &ctx->dma);
484 	if (!ctx->bytes) {
485 		kfree(ctx);
486 		return NULL;
487 	}
488 	return ctx;
489 }
490 
xhci_free_container_ctx(struct xhci_hcd * xhci,struct xhci_container_ctx * ctx)491 void xhci_free_container_ctx(struct xhci_hcd *xhci,
492 			     struct xhci_container_ctx *ctx)
493 {
494 	if (!ctx)
495 		return;
496 	dma_pool_free(xhci->device_pool, ctx->bytes, ctx->dma);
497 	kfree(ctx);
498 }
499 
xhci_get_input_control_ctx(struct xhci_container_ctx * ctx)500 struct xhci_input_control_ctx *xhci_get_input_control_ctx(
501 					      struct xhci_container_ctx *ctx)
502 {
503 	if (ctx->type != XHCI_CTX_TYPE_INPUT)
504 		return NULL;
505 
506 	return (struct xhci_input_control_ctx *)ctx->bytes;
507 }
508 
xhci_get_slot_ctx(struct xhci_hcd * xhci,struct xhci_container_ctx * ctx)509 struct xhci_slot_ctx *xhci_get_slot_ctx(struct xhci_hcd *xhci,
510 					struct xhci_container_ctx *ctx)
511 {
512 	if (ctx->type == XHCI_CTX_TYPE_DEVICE)
513 		return (struct xhci_slot_ctx *)ctx->bytes;
514 
515 	return (struct xhci_slot_ctx *)
516 		(ctx->bytes + CTX_SIZE(xhci->hcc_params));
517 }
518 
xhci_get_ep_ctx(struct xhci_hcd * xhci,struct xhci_container_ctx * ctx,unsigned int ep_index)519 struct xhci_ep_ctx *xhci_get_ep_ctx(struct xhci_hcd *xhci,
520 				    struct xhci_container_ctx *ctx,
521 				    unsigned int ep_index)
522 {
523 	/* increment ep index by offset of start of ep ctx array */
524 	ep_index++;
525 	if (ctx->type == XHCI_CTX_TYPE_INPUT)
526 		ep_index++;
527 
528 	return (struct xhci_ep_ctx *)
529 		(ctx->bytes + (ep_index * CTX_SIZE(xhci->hcc_params)));
530 }
531 EXPORT_SYMBOL_GPL(xhci_get_ep_ctx);
532 
533 /***************** Streams structures manipulation *************************/
534 
xhci_free_stream_ctx(struct xhci_hcd * xhci,unsigned int num_stream_ctxs,struct xhci_stream_ctx * stream_ctx,dma_addr_t dma)535 static void xhci_free_stream_ctx(struct xhci_hcd *xhci,
536 		unsigned int num_stream_ctxs,
537 		struct xhci_stream_ctx *stream_ctx, dma_addr_t dma)
538 {
539 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
540 	size_t size = sizeof(struct xhci_stream_ctx) * num_stream_ctxs;
541 
542 	if (size > MEDIUM_STREAM_ARRAY_SIZE)
543 		dma_free_coherent(dev, size, stream_ctx, dma);
544 	else if (size > SMALL_STREAM_ARRAY_SIZE)
545 		dma_pool_free(xhci->medium_streams_pool, stream_ctx, dma);
546 	else
547 		dma_pool_free(xhci->small_streams_pool, stream_ctx, dma);
548 }
549 
550 /*
551  * The stream context array for each endpoint with bulk streams enabled can
552  * vary in size, based on:
553  *  - how many streams the endpoint supports,
554  *  - the maximum primary stream array size the host controller supports,
555  *  - and how many streams the device driver asks for.
556  *
557  * The stream context array must be a power of 2, and can be as small as
558  * 64 bytes or as large as 1MB.
559  */
xhci_alloc_stream_ctx(struct xhci_hcd * xhci,unsigned int num_stream_ctxs,dma_addr_t * dma,gfp_t mem_flags)560 static struct xhci_stream_ctx *xhci_alloc_stream_ctx(struct xhci_hcd *xhci,
561 		unsigned int num_stream_ctxs, dma_addr_t *dma,
562 		gfp_t mem_flags)
563 {
564 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
565 	size_t size = size_mul(sizeof(struct xhci_stream_ctx), num_stream_ctxs);
566 
567 	if (size > MEDIUM_STREAM_ARRAY_SIZE)
568 		return dma_alloc_coherent(dev, size, dma, mem_flags);
569 	if (size > SMALL_STREAM_ARRAY_SIZE)
570 		return dma_pool_zalloc(xhci->medium_streams_pool, mem_flags, dma);
571 	else
572 		return dma_pool_zalloc(xhci->small_streams_pool, mem_flags, dma);
573 }
574 
xhci_dma_to_transfer_ring(struct xhci_virt_ep * ep,u64 address)575 struct xhci_ring *xhci_dma_to_transfer_ring(
576 		struct xhci_virt_ep *ep,
577 		u64 address)
578 {
579 	if (ep->ep_state & EP_HAS_STREAMS)
580 		return radix_tree_lookup(&ep->stream_info->trb_address_map,
581 				address >> TRB_SEGMENT_SHIFT);
582 	return ep->ring;
583 }
584 
585 /*
586  * Change an endpoint's internal structure so it supports stream IDs.  The
587  * number of requested streams includes stream 0, which cannot be used by device
588  * drivers.
589  *
590  * The number of stream contexts in the stream context array may be bigger than
591  * the number of streams the driver wants to use.  This is because the number of
592  * stream context array entries must be a power of two.
593  */
xhci_alloc_stream_info(struct xhci_hcd * xhci,unsigned int num_stream_ctxs,unsigned int num_streams,unsigned int max_packet,gfp_t mem_flags)594 struct xhci_stream_info *xhci_alloc_stream_info(struct xhci_hcd *xhci,
595 		unsigned int num_stream_ctxs,
596 		unsigned int num_streams,
597 		unsigned int max_packet, gfp_t mem_flags)
598 {
599 	struct xhci_stream_info *stream_info;
600 	u32 cur_stream;
601 	struct xhci_ring *cur_ring;
602 	u64 addr;
603 	int ret;
604 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
605 
606 	xhci_dbg(xhci, "Allocating %u streams and %u stream context array entries.\n",
607 			num_streams, num_stream_ctxs);
608 	if (xhci->cmd_ring_reserved_trbs == MAX_RSVD_CMD_TRBS) {
609 		xhci_dbg(xhci, "Command ring has no reserved TRBs available\n");
610 		return NULL;
611 	}
612 	xhci->cmd_ring_reserved_trbs++;
613 
614 	stream_info = kzalloc_node(sizeof(*stream_info), mem_flags,
615 			dev_to_node(dev));
616 	if (!stream_info)
617 		goto cleanup_trbs;
618 
619 	stream_info->num_streams = num_streams;
620 	stream_info->num_stream_ctxs = num_stream_ctxs;
621 
622 	/* Initialize the array of virtual pointers to stream rings. */
623 	stream_info->stream_rings = kcalloc_node(
624 			num_streams, sizeof(struct xhci_ring *), mem_flags,
625 			dev_to_node(dev));
626 	if (!stream_info->stream_rings)
627 		goto cleanup_info;
628 
629 	/* Initialize the array of DMA addresses for stream rings for the HW. */
630 	stream_info->stream_ctx_array = xhci_alloc_stream_ctx(xhci,
631 			num_stream_ctxs, &stream_info->ctx_array_dma,
632 			mem_flags);
633 	if (!stream_info->stream_ctx_array)
634 		goto cleanup_ring_array;
635 
636 	/* Allocate everything needed to free the stream rings later */
637 	stream_info->free_streams_command =
638 		xhci_alloc_command_with_ctx(xhci, true, mem_flags);
639 	if (!stream_info->free_streams_command)
640 		goto cleanup_ctx;
641 
642 	INIT_RADIX_TREE(&stream_info->trb_address_map, GFP_ATOMIC);
643 
644 	/* Allocate rings for all the streams that the driver will use,
645 	 * and add their segment DMA addresses to the radix tree.
646 	 * Stream 0 is reserved.
647 	 */
648 
649 	for (cur_stream = 1; cur_stream < num_streams; cur_stream++) {
650 		stream_info->stream_rings[cur_stream] =
651 			xhci_ring_alloc(xhci, 2, 1, TYPE_STREAM, max_packet,
652 					mem_flags);
653 		cur_ring = stream_info->stream_rings[cur_stream];
654 		if (!cur_ring)
655 			goto cleanup_rings;
656 		cur_ring->stream_id = cur_stream;
657 		cur_ring->trb_address_map = &stream_info->trb_address_map;
658 		/* Set deq ptr, cycle bit, and stream context type */
659 		addr = cur_ring->first_seg->dma |
660 			SCT_FOR_CTX(SCT_PRI_TR) |
661 			cur_ring->cycle_state;
662 		stream_info->stream_ctx_array[cur_stream].stream_ring =
663 			cpu_to_le64(addr);
664 		xhci_dbg(xhci, "Setting stream %d ring ptr to 0x%08llx\n", cur_stream, addr);
665 
666 		ret = xhci_update_stream_mapping(cur_ring, mem_flags);
667 		if (ret) {
668 			xhci_ring_free(xhci, cur_ring);
669 			stream_info->stream_rings[cur_stream] = NULL;
670 			goto cleanup_rings;
671 		}
672 	}
673 	/* Leave the other unused stream ring pointers in the stream context
674 	 * array initialized to zero.  This will cause the xHC to give us an
675 	 * error if the device asks for a stream ID we don't have setup (if it
676 	 * was any other way, the host controller would assume the ring is
677 	 * "empty" and wait forever for data to be queued to that stream ID).
678 	 */
679 
680 	return stream_info;
681 
682 cleanup_rings:
683 	for (cur_stream = 1; cur_stream < num_streams; cur_stream++) {
684 		cur_ring = stream_info->stream_rings[cur_stream];
685 		if (cur_ring) {
686 			xhci_ring_free(xhci, cur_ring);
687 			stream_info->stream_rings[cur_stream] = NULL;
688 		}
689 	}
690 	xhci_free_command(xhci, stream_info->free_streams_command);
691 cleanup_ctx:
692 	xhci_free_stream_ctx(xhci,
693 		stream_info->num_stream_ctxs,
694 		stream_info->stream_ctx_array,
695 		stream_info->ctx_array_dma);
696 cleanup_ring_array:
697 	kfree(stream_info->stream_rings);
698 cleanup_info:
699 	kfree(stream_info);
700 cleanup_trbs:
701 	xhci->cmd_ring_reserved_trbs--;
702 	return NULL;
703 }
704 /*
705  * Sets the MaxPStreams field and the Linear Stream Array field.
706  * Sets the dequeue pointer to the stream context array.
707  */
xhci_setup_streams_ep_input_ctx(struct xhci_hcd * xhci,struct xhci_ep_ctx * ep_ctx,struct xhci_stream_info * stream_info)708 void xhci_setup_streams_ep_input_ctx(struct xhci_hcd *xhci,
709 		struct xhci_ep_ctx *ep_ctx,
710 		struct xhci_stream_info *stream_info)
711 {
712 	u32 max_primary_streams;
713 	/* MaxPStreams is the number of stream context array entries, not the
714 	 * number we're actually using.  Must be in 2^(MaxPstreams + 1) format.
715 	 * fls(0) = 0, fls(0x1) = 1, fls(0x10) = 2, fls(0x100) = 3, etc.
716 	 */
717 	max_primary_streams = fls(stream_info->num_stream_ctxs) - 2;
718 	xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
719 			"Setting number of stream ctx array entries to %u",
720 			1 << (max_primary_streams + 1));
721 	ep_ctx->ep_info &= cpu_to_le32(~EP_MAXPSTREAMS_MASK);
722 	ep_ctx->ep_info |= cpu_to_le32(EP_MAXPSTREAMS(max_primary_streams)
723 				       | EP_HAS_LSA);
724 	ep_ctx->deq  = cpu_to_le64(stream_info->ctx_array_dma);
725 }
726 
727 /*
728  * Sets the MaxPStreams field and the Linear Stream Array field to 0.
729  * Reinstalls the "normal" endpoint ring (at its previous dequeue mark,
730  * not at the beginning of the ring).
731  */
xhci_setup_no_streams_ep_input_ctx(struct xhci_ep_ctx * ep_ctx,struct xhci_virt_ep * ep)732 void xhci_setup_no_streams_ep_input_ctx(struct xhci_ep_ctx *ep_ctx,
733 		struct xhci_virt_ep *ep)
734 {
735 	dma_addr_t addr;
736 	ep_ctx->ep_info &= cpu_to_le32(~(EP_MAXPSTREAMS_MASK | EP_HAS_LSA));
737 	addr = xhci_trb_virt_to_dma(ep->ring->deq_seg, ep->ring->dequeue);
738 	ep_ctx->deq  = cpu_to_le64(addr | ep->ring->cycle_state);
739 }
740 
741 /* Frees all stream contexts associated with the endpoint,
742  *
743  * Caller should fix the endpoint context streams fields.
744  */
xhci_free_stream_info(struct xhci_hcd * xhci,struct xhci_stream_info * stream_info)745 void xhci_free_stream_info(struct xhci_hcd *xhci,
746 		struct xhci_stream_info *stream_info)
747 {
748 	int cur_stream;
749 	struct xhci_ring *cur_ring;
750 
751 	if (!stream_info)
752 		return;
753 
754 	for (cur_stream = 1; cur_stream < stream_info->num_streams;
755 			cur_stream++) {
756 		cur_ring = stream_info->stream_rings[cur_stream];
757 		if (cur_ring) {
758 			xhci_ring_free(xhci, cur_ring);
759 			stream_info->stream_rings[cur_stream] = NULL;
760 		}
761 	}
762 	xhci_free_command(xhci, stream_info->free_streams_command);
763 	xhci->cmd_ring_reserved_trbs--;
764 	if (stream_info->stream_ctx_array)
765 		xhci_free_stream_ctx(xhci,
766 				stream_info->num_stream_ctxs,
767 				stream_info->stream_ctx_array,
768 				stream_info->ctx_array_dma);
769 
770 	kfree(stream_info->stream_rings);
771 	kfree(stream_info);
772 }
773 
774 
775 /***************** Device context manipulation *************************/
776 
xhci_free_tt_info(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,int slot_id)777 static void xhci_free_tt_info(struct xhci_hcd *xhci,
778 		struct xhci_virt_device *virt_dev,
779 		int slot_id)
780 {
781 	struct list_head *tt_list_head;
782 	struct xhci_tt_bw_info *tt_info, *next;
783 	bool slot_found = false;
784 
785 	/* If the device never made it past the Set Address stage,
786 	 * it may not have the real_port set correctly.
787 	 */
788 	if (virt_dev->real_port == 0 ||
789 			virt_dev->real_port > HCS_MAX_PORTS(xhci->hcs_params1)) {
790 		xhci_dbg(xhci, "Bad real port.\n");
791 		return;
792 	}
793 
794 	tt_list_head = &(xhci->rh_bw[virt_dev->real_port - 1].tts);
795 	list_for_each_entry_safe(tt_info, next, tt_list_head, tt_list) {
796 		/* Multi-TT hubs will have more than one entry */
797 		if (tt_info->slot_id == slot_id) {
798 			slot_found = true;
799 			list_del(&tt_info->tt_list);
800 			kfree(tt_info);
801 		} else if (slot_found) {
802 			break;
803 		}
804 	}
805 }
806 
xhci_alloc_tt_info(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,struct usb_device * hdev,struct usb_tt * tt,gfp_t mem_flags)807 int xhci_alloc_tt_info(struct xhci_hcd *xhci,
808 		struct xhci_virt_device *virt_dev,
809 		struct usb_device *hdev,
810 		struct usb_tt *tt, gfp_t mem_flags)
811 {
812 	struct xhci_tt_bw_info		*tt_info;
813 	unsigned int			num_ports;
814 	int				i, j;
815 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
816 
817 	if (!tt->multi)
818 		num_ports = 1;
819 	else
820 		num_ports = hdev->maxchild;
821 
822 	for (i = 0; i < num_ports; i++, tt_info++) {
823 		struct xhci_interval_bw_table *bw_table;
824 
825 		tt_info = kzalloc_node(sizeof(*tt_info), mem_flags,
826 				dev_to_node(dev));
827 		if (!tt_info)
828 			goto free_tts;
829 		INIT_LIST_HEAD(&tt_info->tt_list);
830 		list_add(&tt_info->tt_list,
831 				&xhci->rh_bw[virt_dev->real_port - 1].tts);
832 		tt_info->slot_id = virt_dev->udev->slot_id;
833 		if (tt->multi)
834 			tt_info->ttport = i+1;
835 		bw_table = &tt_info->bw_table;
836 		for (j = 0; j < XHCI_MAX_INTERVAL; j++)
837 			INIT_LIST_HEAD(&bw_table->interval_bw[j].endpoints);
838 	}
839 	return 0;
840 
841 free_tts:
842 	xhci_free_tt_info(xhci, virt_dev, virt_dev->udev->slot_id);
843 	return -ENOMEM;
844 }
845 
846 
847 /* All the xhci_tds in the ring's TD list should be freed at this point.
848  * Should be called with xhci->lock held if there is any chance the TT lists
849  * will be manipulated by the configure endpoint, allocate device, or update
850  * hub functions while this function is removing the TT entries from the list.
851  */
xhci_free_virt_device(struct xhci_hcd * xhci,int slot_id)852 void xhci_free_virt_device(struct xhci_hcd *xhci, int slot_id)
853 {
854 	struct xhci_virt_device *dev;
855 	int i;
856 	int old_active_eps = 0;
857 
858 	/* Slot ID 0 is reserved */
859 	if (slot_id == 0 || !xhci->devs[slot_id])
860 		return;
861 
862 	dev = xhci->devs[slot_id];
863 
864 	xhci->dcbaa->dev_context_ptrs[slot_id] = 0;
865 	if (!dev)
866 		return;
867 
868 	trace_xhci_free_virt_device(dev);
869 
870 	if (dev->tt_info)
871 		old_active_eps = dev->tt_info->active_eps;
872 
873 	for (i = 0; i < 31; i++) {
874 		if (dev->eps[i].ring)
875 			xhci_ring_free(xhci, dev->eps[i].ring);
876 		if (dev->eps[i].stream_info)
877 			xhci_free_stream_info(xhci,
878 					dev->eps[i].stream_info);
879 		/*
880 		 * Endpoints are normally deleted from the bandwidth list when
881 		 * endpoints are dropped, before device is freed.
882 		 * If host is dying or being removed then endpoints aren't
883 		 * dropped cleanly, so delete the endpoint from list here.
884 		 * Only applicable for hosts with software bandwidth checking.
885 		 */
886 
887 		if (!list_empty(&dev->eps[i].bw_endpoint_list)) {
888 			list_del_init(&dev->eps[i].bw_endpoint_list);
889 			xhci_dbg(xhci, "Slot %u endpoint %u not removed from BW list!\n",
890 				 slot_id, i);
891 		}
892 	}
893 	/* If this is a hub, free the TT(s) from the TT list */
894 	xhci_free_tt_info(xhci, dev, slot_id);
895 	/* If necessary, update the number of active TTs on this root port */
896 	xhci_update_tt_active_eps(xhci, dev, old_active_eps);
897 
898 	if (dev->in_ctx)
899 		xhci_free_container_ctx(xhci, dev->in_ctx);
900 	if (dev->out_ctx)
901 		xhci_free_container_ctx(xhci, dev->out_ctx);
902 
903 	if (dev->udev && dev->udev->slot_id)
904 		dev->udev->slot_id = 0;
905 	kfree(xhci->devs[slot_id]);
906 	xhci->devs[slot_id] = NULL;
907 }
908 
909 /*
910  * Free a virt_device structure.
911  * If the virt_device added a tt_info (a hub) and has children pointing to
912  * that tt_info, then free the child first. Recursive.
913  * We can't rely on udev at this point to find child-parent relationships.
914  */
xhci_free_virt_devices_depth_first(struct xhci_hcd * xhci,int slot_id)915 static void xhci_free_virt_devices_depth_first(struct xhci_hcd *xhci, int slot_id)
916 {
917 	struct xhci_virt_device *vdev;
918 	struct list_head *tt_list_head;
919 	struct xhci_tt_bw_info *tt_info, *next;
920 	int i;
921 
922 	vdev = xhci->devs[slot_id];
923 	if (!vdev)
924 		return;
925 
926 	if (vdev->real_port == 0 ||
927 			vdev->real_port > HCS_MAX_PORTS(xhci->hcs_params1)) {
928 		xhci_dbg(xhci, "Bad vdev->real_port.\n");
929 		goto out;
930 	}
931 
932 	tt_list_head = &(xhci->rh_bw[vdev->real_port - 1].tts);
933 	list_for_each_entry_safe(tt_info, next, tt_list_head, tt_list) {
934 		/* is this a hub device that added a tt_info to the tts list */
935 		if (tt_info->slot_id == slot_id) {
936 			/* are any devices using this tt_info? */
937 			for (i = 1; i < HCS_MAX_SLOTS(xhci->hcs_params1); i++) {
938 				vdev = xhci->devs[i];
939 				if (vdev && (vdev->tt_info == tt_info))
940 					xhci_free_virt_devices_depth_first(
941 						xhci, i);
942 			}
943 		}
944 	}
945 out:
946 	/* we are now at a leaf device */
947 	xhci_debugfs_remove_slot(xhci, slot_id);
948 	xhci_free_virt_device(xhci, slot_id);
949 }
950 
xhci_alloc_virt_device(struct xhci_hcd * xhci,int slot_id,struct usb_device * udev,gfp_t flags)951 int xhci_alloc_virt_device(struct xhci_hcd *xhci, int slot_id,
952 		struct usb_device *udev, gfp_t flags)
953 {
954 	struct xhci_virt_device *dev;
955 	int i;
956 
957 	/* Slot ID 0 is reserved */
958 	if (slot_id == 0 || xhci->devs[slot_id]) {
959 		xhci_warn(xhci, "Bad Slot ID %d\n", slot_id);
960 		return 0;
961 	}
962 
963 	dev = kzalloc(sizeof(*dev), flags);
964 	if (!dev)
965 		return 0;
966 
967 	dev->slot_id = slot_id;
968 
969 	/* Allocate the (output) device context that will be used in the HC. */
970 	dev->out_ctx = xhci_alloc_container_ctx(xhci, XHCI_CTX_TYPE_DEVICE, flags);
971 	if (!dev->out_ctx)
972 		goto fail;
973 
974 	xhci_dbg(xhci, "Slot %d output ctx = 0x%pad (dma)\n", slot_id, &dev->out_ctx->dma);
975 
976 	/* Allocate the (input) device context for address device command */
977 	dev->in_ctx = xhci_alloc_container_ctx(xhci, XHCI_CTX_TYPE_INPUT, flags);
978 	if (!dev->in_ctx)
979 		goto fail;
980 
981 	xhci_dbg(xhci, "Slot %d input ctx = 0x%pad (dma)\n", slot_id, &dev->in_ctx->dma);
982 
983 	/* Initialize the cancellation and bandwidth list for each ep */
984 	for (i = 0; i < 31; i++) {
985 		dev->eps[i].ep_index = i;
986 		dev->eps[i].vdev = dev;
987 		dev->eps[i].xhci = xhci;
988 		INIT_LIST_HEAD(&dev->eps[i].cancelled_td_list);
989 		INIT_LIST_HEAD(&dev->eps[i].bw_endpoint_list);
990 	}
991 
992 	/* Allocate endpoint 0 ring */
993 	dev->eps[0].ring = xhci_ring_alloc(xhci, 2, 1, TYPE_CTRL, 0, flags);
994 	if (!dev->eps[0].ring)
995 		goto fail;
996 
997 	dev->udev = udev;
998 
999 	/* Point to output device context in dcbaa. */
1000 	xhci->dcbaa->dev_context_ptrs[slot_id] = cpu_to_le64(dev->out_ctx->dma);
1001 	xhci_dbg(xhci, "Set slot id %d dcbaa entry %p to 0x%llx\n",
1002 		 slot_id,
1003 		 &xhci->dcbaa->dev_context_ptrs[slot_id],
1004 		 le64_to_cpu(xhci->dcbaa->dev_context_ptrs[slot_id]));
1005 
1006 	trace_xhci_alloc_virt_device(dev);
1007 
1008 	xhci->devs[slot_id] = dev;
1009 
1010 	return 1;
1011 fail:
1012 
1013 	if (dev->in_ctx)
1014 		xhci_free_container_ctx(xhci, dev->in_ctx);
1015 	if (dev->out_ctx)
1016 		xhci_free_container_ctx(xhci, dev->out_ctx);
1017 	kfree(dev);
1018 
1019 	return 0;
1020 }
1021 
xhci_copy_ep0_dequeue_into_input_ctx(struct xhci_hcd * xhci,struct usb_device * udev)1022 void xhci_copy_ep0_dequeue_into_input_ctx(struct xhci_hcd *xhci,
1023 		struct usb_device *udev)
1024 {
1025 	struct xhci_virt_device *virt_dev;
1026 	struct xhci_ep_ctx	*ep0_ctx;
1027 	struct xhci_ring	*ep_ring;
1028 
1029 	virt_dev = xhci->devs[udev->slot_id];
1030 	ep0_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, 0);
1031 	ep_ring = virt_dev->eps[0].ring;
1032 	/*
1033 	 * FIXME we don't keep track of the dequeue pointer very well after a
1034 	 * Set TR dequeue pointer, so we're setting the dequeue pointer of the
1035 	 * host to our enqueue pointer.  This should only be called after a
1036 	 * configured device has reset, so all control transfers should have
1037 	 * been completed or cancelled before the reset.
1038 	 */
1039 	ep0_ctx->deq = cpu_to_le64(xhci_trb_virt_to_dma(ep_ring->enq_seg,
1040 							ep_ring->enqueue)
1041 				   | ep_ring->cycle_state);
1042 }
1043 
1044 /*
1045  * The xHCI roothub may have ports of differing speeds in any order in the port
1046  * status registers.
1047  *
1048  * The xHCI hardware wants to know the roothub port number that the USB device
1049  * is attached to (or the roothub port its ancestor hub is attached to).  All we
1050  * know is the index of that port under either the USB 2.0 or the USB 3.0
1051  * roothub, but that doesn't give us the real index into the HW port status
1052  * registers. Call xhci_find_raw_port_number() to get real index.
1053  */
xhci_find_real_port_number(struct xhci_hcd * xhci,struct usb_device * udev)1054 static u32 xhci_find_real_port_number(struct xhci_hcd *xhci,
1055 		struct usb_device *udev)
1056 {
1057 	struct usb_device *top_dev;
1058 	struct usb_hcd *hcd;
1059 
1060 	if (udev->speed >= USB_SPEED_SUPER)
1061 		hcd = xhci_get_usb3_hcd(xhci);
1062 	else
1063 		hcd = xhci->main_hcd;
1064 
1065 	for (top_dev = udev; top_dev->parent && top_dev->parent->parent;
1066 			top_dev = top_dev->parent)
1067 		/* Found device below root hub */;
1068 
1069 	return	xhci_find_raw_port_number(hcd, top_dev->portnum);
1070 }
1071 
1072 /* Setup an xHCI virtual device for a Set Address command */
xhci_setup_addressable_virt_dev(struct xhci_hcd * xhci,struct usb_device * udev)1073 int xhci_setup_addressable_virt_dev(struct xhci_hcd *xhci, struct usb_device *udev)
1074 {
1075 	struct xhci_virt_device *dev;
1076 	struct xhci_ep_ctx	*ep0_ctx;
1077 	struct xhci_slot_ctx    *slot_ctx;
1078 	u32			port_num;
1079 	u32			max_packets;
1080 	struct usb_device *top_dev;
1081 
1082 	dev = xhci->devs[udev->slot_id];
1083 	/* Slot ID 0 is reserved */
1084 	if (udev->slot_id == 0 || !dev) {
1085 		xhci_warn(xhci, "Slot ID %d is not assigned to this device\n",
1086 				udev->slot_id);
1087 		return -EINVAL;
1088 	}
1089 	ep0_ctx = xhci_get_ep_ctx(xhci, dev->in_ctx, 0);
1090 	slot_ctx = xhci_get_slot_ctx(xhci, dev->in_ctx);
1091 
1092 	/* 3) Only the control endpoint is valid - one endpoint context */
1093 	slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1) | udev->route);
1094 	switch (udev->speed) {
1095 	case USB_SPEED_SUPER_PLUS:
1096 		slot_ctx->dev_info |= cpu_to_le32(SLOT_SPEED_SSP);
1097 		max_packets = MAX_PACKET(512);
1098 		break;
1099 	case USB_SPEED_SUPER:
1100 		slot_ctx->dev_info |= cpu_to_le32(SLOT_SPEED_SS);
1101 		max_packets = MAX_PACKET(512);
1102 		break;
1103 	case USB_SPEED_HIGH:
1104 		slot_ctx->dev_info |= cpu_to_le32(SLOT_SPEED_HS);
1105 		max_packets = MAX_PACKET(64);
1106 		break;
1107 	/* USB core guesses at a 64-byte max packet first for FS devices */
1108 	case USB_SPEED_FULL:
1109 		slot_ctx->dev_info |= cpu_to_le32(SLOT_SPEED_FS);
1110 		max_packets = MAX_PACKET(64);
1111 		break;
1112 	case USB_SPEED_LOW:
1113 		slot_ctx->dev_info |= cpu_to_le32(SLOT_SPEED_LS);
1114 		max_packets = MAX_PACKET(8);
1115 		break;
1116 	default:
1117 		/* Speed was set earlier, this shouldn't happen. */
1118 		return -EINVAL;
1119 	}
1120 	/* Find the root hub port this device is under */
1121 	port_num = xhci_find_real_port_number(xhci, udev);
1122 	if (!port_num)
1123 		return -EINVAL;
1124 	slot_ctx->dev_info2 |= cpu_to_le32(ROOT_HUB_PORT(port_num));
1125 	/* Set the port number in the virtual_device to the faked port number */
1126 	for (top_dev = udev; top_dev->parent && top_dev->parent->parent;
1127 			top_dev = top_dev->parent)
1128 		/* Found device below root hub */;
1129 	dev->fake_port = top_dev->portnum;
1130 	dev->real_port = port_num;
1131 	xhci_dbg(xhci, "Set root hub portnum to %d\n", port_num);
1132 	xhci_dbg(xhci, "Set fake root hub portnum to %d\n", dev->fake_port);
1133 
1134 	/* Find the right bandwidth table that this device will be a part of.
1135 	 * If this is a full speed device attached directly to a root port (or a
1136 	 * decendent of one), it counts as a primary bandwidth domain, not a
1137 	 * secondary bandwidth domain under a TT.  An xhci_tt_info structure
1138 	 * will never be created for the HS root hub.
1139 	 */
1140 	if (!udev->tt || !udev->tt->hub->parent) {
1141 		dev->bw_table = &xhci->rh_bw[port_num - 1].bw_table;
1142 	} else {
1143 		struct xhci_root_port_bw_info *rh_bw;
1144 		struct xhci_tt_bw_info *tt_bw;
1145 
1146 		rh_bw = &xhci->rh_bw[port_num - 1];
1147 		/* Find the right TT. */
1148 		list_for_each_entry(tt_bw, &rh_bw->tts, tt_list) {
1149 			if (tt_bw->slot_id != udev->tt->hub->slot_id)
1150 				continue;
1151 
1152 			if (!dev->udev->tt->multi ||
1153 					(udev->tt->multi &&
1154 					 tt_bw->ttport == dev->udev->ttport)) {
1155 				dev->bw_table = &tt_bw->bw_table;
1156 				dev->tt_info = tt_bw;
1157 				break;
1158 			}
1159 		}
1160 		if (!dev->tt_info)
1161 			xhci_warn(xhci, "WARN: Didn't find a matching TT\n");
1162 	}
1163 
1164 	/* Is this a LS/FS device under an external HS hub? */
1165 	if (udev->tt && udev->tt->hub->parent) {
1166 		slot_ctx->tt_info = cpu_to_le32(udev->tt->hub->slot_id |
1167 						(udev->ttport << 8));
1168 		if (udev->tt->multi)
1169 			slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
1170 	}
1171 	xhci_dbg(xhci, "udev->tt = %p\n", udev->tt);
1172 	xhci_dbg(xhci, "udev->ttport = 0x%x\n", udev->ttport);
1173 
1174 	/* Step 4 - ring already allocated */
1175 	/* Step 5 */
1176 	ep0_ctx->ep_info2 = cpu_to_le32(EP_TYPE(CTRL_EP));
1177 
1178 	/* EP 0 can handle "burst" sizes of 1, so Max Burst Size field is 0 */
1179 	ep0_ctx->ep_info2 |= cpu_to_le32(MAX_BURST(0) | ERROR_COUNT(3) |
1180 					 max_packets);
1181 
1182 	ep0_ctx->deq = cpu_to_le64(dev->eps[0].ring->first_seg->dma |
1183 				   dev->eps[0].ring->cycle_state);
1184 
1185 	trace_xhci_setup_addressable_virt_device(dev);
1186 
1187 	/* Steps 7 and 8 were done in xhci_alloc_virt_device() */
1188 
1189 	return 0;
1190 }
1191 
1192 /*
1193  * Convert interval expressed as 2^(bInterval - 1) == interval into
1194  * straight exponent value 2^n == interval.
1195  *
1196  */
xhci_parse_exponent_interval(struct usb_device * udev,struct usb_host_endpoint * ep)1197 static unsigned int xhci_parse_exponent_interval(struct usb_device *udev,
1198 		struct usb_host_endpoint *ep)
1199 {
1200 	unsigned int interval;
1201 
1202 	interval = clamp_val(ep->desc.bInterval, 1, 16) - 1;
1203 	if (interval != ep->desc.bInterval - 1)
1204 		dev_warn(&udev->dev,
1205 			 "ep %#x - rounding interval to %d %sframes\n",
1206 			 ep->desc.bEndpointAddress,
1207 			 1 << interval,
1208 			 udev->speed == USB_SPEED_FULL ? "" : "micro");
1209 
1210 	if (udev->speed == USB_SPEED_FULL) {
1211 		/*
1212 		 * Full speed isoc endpoints specify interval in frames,
1213 		 * not microframes. We are using microframes everywhere,
1214 		 * so adjust accordingly.
1215 		 */
1216 		interval += 3;	/* 1 frame = 2^3 uframes */
1217 	}
1218 
1219 	return interval;
1220 }
1221 
1222 /*
1223  * Convert bInterval expressed in microframes (in 1-255 range) to exponent of
1224  * microframes, rounded down to nearest power of 2.
1225  */
xhci_microframes_to_exponent(struct usb_device * udev,struct usb_host_endpoint * ep,unsigned int desc_interval,unsigned int min_exponent,unsigned int max_exponent)1226 static unsigned int xhci_microframes_to_exponent(struct usb_device *udev,
1227 		struct usb_host_endpoint *ep, unsigned int desc_interval,
1228 		unsigned int min_exponent, unsigned int max_exponent)
1229 {
1230 	unsigned int interval;
1231 
1232 	interval = fls(desc_interval) - 1;
1233 	interval = clamp_val(interval, min_exponent, max_exponent);
1234 	if ((1 << interval) != desc_interval)
1235 		dev_dbg(&udev->dev,
1236 			 "ep %#x - rounding interval to %d microframes, ep desc says %d microframes\n",
1237 			 ep->desc.bEndpointAddress,
1238 			 1 << interval,
1239 			 desc_interval);
1240 
1241 	return interval;
1242 }
1243 
xhci_parse_microframe_interval(struct usb_device * udev,struct usb_host_endpoint * ep)1244 static unsigned int xhci_parse_microframe_interval(struct usb_device *udev,
1245 		struct usb_host_endpoint *ep)
1246 {
1247 	if (ep->desc.bInterval == 0)
1248 		return 0;
1249 	return xhci_microframes_to_exponent(udev, ep,
1250 			ep->desc.bInterval, 0, 15);
1251 }
1252 
1253 
xhci_parse_frame_interval(struct usb_device * udev,struct usb_host_endpoint * ep)1254 static unsigned int xhci_parse_frame_interval(struct usb_device *udev,
1255 		struct usb_host_endpoint *ep)
1256 {
1257 	return xhci_microframes_to_exponent(udev, ep,
1258 			ep->desc.bInterval * 8, 3, 10);
1259 }
1260 
1261 /* Return the polling or NAK interval.
1262  *
1263  * The polling interval is expressed in "microframes".  If xHCI's Interval field
1264  * is set to N, it will service the endpoint every 2^(Interval)*125us.
1265  *
1266  * The NAK interval is one NAK per 1 to 255 microframes, or no NAKs if interval
1267  * is set to 0.
1268  */
xhci_get_endpoint_interval(struct usb_device * udev,struct usb_host_endpoint * ep)1269 static unsigned int xhci_get_endpoint_interval(struct usb_device *udev,
1270 		struct usb_host_endpoint *ep)
1271 {
1272 	unsigned int interval = 0;
1273 
1274 	switch (udev->speed) {
1275 	case USB_SPEED_HIGH:
1276 		/* Max NAK rate */
1277 		if (usb_endpoint_xfer_control(&ep->desc) ||
1278 		    usb_endpoint_xfer_bulk(&ep->desc)) {
1279 			interval = xhci_parse_microframe_interval(udev, ep);
1280 			break;
1281 		}
1282 		fallthrough;	/* SS and HS isoc/int have same decoding */
1283 
1284 	case USB_SPEED_SUPER_PLUS:
1285 	case USB_SPEED_SUPER:
1286 		if (usb_endpoint_xfer_int(&ep->desc) ||
1287 		    usb_endpoint_xfer_isoc(&ep->desc)) {
1288 			interval = xhci_parse_exponent_interval(udev, ep);
1289 		}
1290 		break;
1291 
1292 	case USB_SPEED_FULL:
1293 		if (usb_endpoint_xfer_isoc(&ep->desc)) {
1294 			interval = xhci_parse_exponent_interval(udev, ep);
1295 			break;
1296 		}
1297 		/*
1298 		 * Fall through for interrupt endpoint interval decoding
1299 		 * since it uses the same rules as low speed interrupt
1300 		 * endpoints.
1301 		 */
1302 		fallthrough;
1303 
1304 	case USB_SPEED_LOW:
1305 		if (usb_endpoint_xfer_int(&ep->desc) ||
1306 		    usb_endpoint_xfer_isoc(&ep->desc)) {
1307 
1308 			interval = xhci_parse_frame_interval(udev, ep);
1309 		}
1310 		break;
1311 
1312 	default:
1313 		BUG();
1314 	}
1315 	return interval;
1316 }
1317 
1318 /* The "Mult" field in the endpoint context is only set for SuperSpeed isoc eps.
1319  * High speed endpoint descriptors can define "the number of additional
1320  * transaction opportunities per microframe", but that goes in the Max Burst
1321  * endpoint context field.
1322  */
xhci_get_endpoint_mult(struct usb_device * udev,struct usb_host_endpoint * ep)1323 static u32 xhci_get_endpoint_mult(struct usb_device *udev,
1324 		struct usb_host_endpoint *ep)
1325 {
1326 	if (udev->speed < USB_SPEED_SUPER ||
1327 			!usb_endpoint_xfer_isoc(&ep->desc))
1328 		return 0;
1329 	return ep->ss_ep_comp.bmAttributes;
1330 }
1331 
xhci_get_endpoint_max_burst(struct usb_device * udev,struct usb_host_endpoint * ep)1332 static u32 xhci_get_endpoint_max_burst(struct usb_device *udev,
1333 				       struct usb_host_endpoint *ep)
1334 {
1335 	/* Super speed and Plus have max burst in ep companion desc */
1336 	if (udev->speed >= USB_SPEED_SUPER)
1337 		return ep->ss_ep_comp.bMaxBurst;
1338 
1339 	if (udev->speed == USB_SPEED_HIGH &&
1340 	    (usb_endpoint_xfer_isoc(&ep->desc) ||
1341 	     usb_endpoint_xfer_int(&ep->desc)))
1342 		return usb_endpoint_maxp_mult(&ep->desc) - 1;
1343 
1344 	return 0;
1345 }
1346 
xhci_get_endpoint_type(struct usb_host_endpoint * ep)1347 static u32 xhci_get_endpoint_type(struct usb_host_endpoint *ep)
1348 {
1349 	int in;
1350 
1351 	in = usb_endpoint_dir_in(&ep->desc);
1352 
1353 	switch (usb_endpoint_type(&ep->desc)) {
1354 	case USB_ENDPOINT_XFER_CONTROL:
1355 		return CTRL_EP;
1356 	case USB_ENDPOINT_XFER_BULK:
1357 		return in ? BULK_IN_EP : BULK_OUT_EP;
1358 	case USB_ENDPOINT_XFER_ISOC:
1359 		return in ? ISOC_IN_EP : ISOC_OUT_EP;
1360 	case USB_ENDPOINT_XFER_INT:
1361 		return in ? INT_IN_EP : INT_OUT_EP;
1362 	}
1363 	return 0;
1364 }
1365 
1366 /* Return the maximum endpoint service interval time (ESIT) payload.
1367  * Basically, this is the maxpacket size, multiplied by the burst size
1368  * and mult size.
1369  */
xhci_get_max_esit_payload(struct usb_device * udev,struct usb_host_endpoint * ep)1370 static u32 xhci_get_max_esit_payload(struct usb_device *udev,
1371 		struct usb_host_endpoint *ep)
1372 {
1373 	int max_burst;
1374 	int max_packet;
1375 
1376 	/* Only applies for interrupt or isochronous endpoints */
1377 	if (usb_endpoint_xfer_control(&ep->desc) ||
1378 			usb_endpoint_xfer_bulk(&ep->desc))
1379 		return 0;
1380 
1381 	/* SuperSpeedPlus Isoc ep sending over 48k per esit */
1382 	if ((udev->speed >= USB_SPEED_SUPER_PLUS) &&
1383 	    USB_SS_SSP_ISOC_COMP(ep->ss_ep_comp.bmAttributes))
1384 		return le32_to_cpu(ep->ssp_isoc_ep_comp.dwBytesPerInterval);
1385 
1386 	/* SuperSpeed or SuperSpeedPlus Isoc ep with less than 48k per esit */
1387 	if (udev->speed >= USB_SPEED_SUPER)
1388 		return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1389 
1390 	max_packet = usb_endpoint_maxp(&ep->desc);
1391 	max_burst = usb_endpoint_maxp_mult(&ep->desc);
1392 	/* A 0 in max burst means 1 transfer per ESIT */
1393 	return max_packet * max_burst;
1394 }
1395 
1396 /* Set up an endpoint with one ring segment.  Do not allocate stream rings.
1397  * Drivers will have to call usb_alloc_streams() to do that.
1398  */
xhci_endpoint_init(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,struct usb_device * udev,struct usb_host_endpoint * ep,gfp_t mem_flags)1399 int xhci_endpoint_init(struct xhci_hcd *xhci,
1400 		struct xhci_virt_device *virt_dev,
1401 		struct usb_device *udev,
1402 		struct usb_host_endpoint *ep,
1403 		gfp_t mem_flags)
1404 {
1405 	unsigned int ep_index;
1406 	struct xhci_ep_ctx *ep_ctx;
1407 	struct xhci_ring *ep_ring;
1408 	unsigned int max_packet;
1409 	enum xhci_ring_type ring_type;
1410 	u32 max_esit_payload;
1411 	u32 endpoint_type;
1412 	unsigned int max_burst;
1413 	unsigned int interval;
1414 	unsigned int mult;
1415 	unsigned int avg_trb_len;
1416 	unsigned int err_count = 0;
1417 
1418 	ep_index = xhci_get_endpoint_index(&ep->desc);
1419 	ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, ep_index);
1420 
1421 	endpoint_type = xhci_get_endpoint_type(ep);
1422 	if (!endpoint_type)
1423 		return -EINVAL;
1424 
1425 	ring_type = usb_endpoint_type(&ep->desc);
1426 
1427 	/*
1428 	 * Get values to fill the endpoint context, mostly from ep descriptor.
1429 	 * The average TRB buffer lengt for bulk endpoints is unclear as we
1430 	 * have no clue on scatter gather list entry size. For Isoc and Int,
1431 	 * set it to max available. See xHCI 1.1 spec 4.14.1.1 for details.
1432 	 */
1433 	max_esit_payload = xhci_get_max_esit_payload(udev, ep);
1434 	interval = xhci_get_endpoint_interval(udev, ep);
1435 
1436 	/* Periodic endpoint bInterval limit quirk */
1437 	if (usb_endpoint_xfer_int(&ep->desc) ||
1438 	    usb_endpoint_xfer_isoc(&ep->desc)) {
1439 		if ((xhci->quirks & XHCI_LIMIT_ENDPOINT_INTERVAL_9) &&
1440 		    interval >= 9) {
1441 			interval = 8;
1442 		}
1443 		if ((xhci->quirks & XHCI_LIMIT_ENDPOINT_INTERVAL_7) &&
1444 		    udev->speed >= USB_SPEED_HIGH &&
1445 		    interval >= 7) {
1446 			interval = 6;
1447 		}
1448 	}
1449 
1450 	mult = xhci_get_endpoint_mult(udev, ep);
1451 	max_packet = usb_endpoint_maxp(&ep->desc);
1452 	max_burst = xhci_get_endpoint_max_burst(udev, ep);
1453 	avg_trb_len = max_esit_payload;
1454 
1455 	/* FIXME dig Mult and streams info out of ep companion desc */
1456 
1457 	/* Allow 3 retries for everything but isoc, set CErr = 3 */
1458 	if (!usb_endpoint_xfer_isoc(&ep->desc))
1459 		err_count = 3;
1460 	/* HS bulk max packet should be 512, FS bulk supports 8, 16, 32 or 64 */
1461 	if (usb_endpoint_xfer_bulk(&ep->desc)) {
1462 		if (udev->speed == USB_SPEED_HIGH)
1463 			max_packet = 512;
1464 		if (udev->speed == USB_SPEED_FULL) {
1465 			max_packet = rounddown_pow_of_two(max_packet);
1466 			max_packet = clamp_val(max_packet, 8, 64);
1467 		}
1468 	}
1469 	/* xHCI 1.0 and 1.1 indicates that ctrl ep avg TRB Length should be 8 */
1470 	if (usb_endpoint_xfer_control(&ep->desc) && xhci->hci_version >= 0x100)
1471 		avg_trb_len = 8;
1472 	/* xhci 1.1 with LEC support doesn't use mult field, use RsvdZ */
1473 	if ((xhci->hci_version > 0x100) && HCC2_LEC(xhci->hcc_params2))
1474 		mult = 0;
1475 
1476 	/* Set up the endpoint ring */
1477 	virt_dev->eps[ep_index].new_ring =
1478 		xhci_ring_alloc(xhci, 2, 1, ring_type, max_packet, mem_flags);
1479 	if (!virt_dev->eps[ep_index].new_ring)
1480 		return -ENOMEM;
1481 
1482 	virt_dev->eps[ep_index].skip = false;
1483 	ep_ring = virt_dev->eps[ep_index].new_ring;
1484 
1485 	/* Fill the endpoint context */
1486 	ep_ctx->ep_info = cpu_to_le32(EP_MAX_ESIT_PAYLOAD_HI(max_esit_payload) |
1487 				      EP_INTERVAL(interval) |
1488 				      EP_MULT(mult));
1489 	ep_ctx->ep_info2 = cpu_to_le32(EP_TYPE(endpoint_type) |
1490 				       MAX_PACKET(max_packet) |
1491 				       MAX_BURST(max_burst) |
1492 				       ERROR_COUNT(err_count));
1493 	ep_ctx->deq = cpu_to_le64(ep_ring->first_seg->dma |
1494 				  ep_ring->cycle_state);
1495 
1496 	ep_ctx->tx_info = cpu_to_le32(EP_MAX_ESIT_PAYLOAD_LO(max_esit_payload) |
1497 				      EP_AVG_TRB_LENGTH(avg_trb_len));
1498 
1499 	return 0;
1500 }
1501 
xhci_endpoint_zero(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,struct usb_host_endpoint * ep)1502 void xhci_endpoint_zero(struct xhci_hcd *xhci,
1503 		struct xhci_virt_device *virt_dev,
1504 		struct usb_host_endpoint *ep)
1505 {
1506 	unsigned int ep_index;
1507 	struct xhci_ep_ctx *ep_ctx;
1508 
1509 	ep_index = xhci_get_endpoint_index(&ep->desc);
1510 	ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, ep_index);
1511 
1512 	ep_ctx->ep_info = 0;
1513 	ep_ctx->ep_info2 = 0;
1514 	ep_ctx->deq = 0;
1515 	ep_ctx->tx_info = 0;
1516 	/* Don't free the endpoint ring until the set interface or configuration
1517 	 * request succeeds.
1518 	 */
1519 }
1520 
xhci_clear_endpoint_bw_info(struct xhci_bw_info * bw_info)1521 void xhci_clear_endpoint_bw_info(struct xhci_bw_info *bw_info)
1522 {
1523 	bw_info->ep_interval = 0;
1524 	bw_info->mult = 0;
1525 	bw_info->num_packets = 0;
1526 	bw_info->max_packet_size = 0;
1527 	bw_info->type = 0;
1528 	bw_info->max_esit_payload = 0;
1529 }
1530 
xhci_update_bw_info(struct xhci_hcd * xhci,struct xhci_container_ctx * in_ctx,struct xhci_input_control_ctx * ctrl_ctx,struct xhci_virt_device * virt_dev)1531 void xhci_update_bw_info(struct xhci_hcd *xhci,
1532 		struct xhci_container_ctx *in_ctx,
1533 		struct xhci_input_control_ctx *ctrl_ctx,
1534 		struct xhci_virt_device *virt_dev)
1535 {
1536 	struct xhci_bw_info *bw_info;
1537 	struct xhci_ep_ctx *ep_ctx;
1538 	unsigned int ep_type;
1539 	int i;
1540 
1541 	for (i = 1; i < 31; i++) {
1542 		bw_info = &virt_dev->eps[i].bw_info;
1543 
1544 		/* We can't tell what endpoint type is being dropped, but
1545 		 * unconditionally clearing the bandwidth info for non-periodic
1546 		 * endpoints should be harmless because the info will never be
1547 		 * set in the first place.
1548 		 */
1549 		if (!EP_IS_ADDED(ctrl_ctx, i) && EP_IS_DROPPED(ctrl_ctx, i)) {
1550 			/* Dropped endpoint */
1551 			xhci_clear_endpoint_bw_info(bw_info);
1552 			continue;
1553 		}
1554 
1555 		if (EP_IS_ADDED(ctrl_ctx, i)) {
1556 			ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, i);
1557 			ep_type = CTX_TO_EP_TYPE(le32_to_cpu(ep_ctx->ep_info2));
1558 
1559 			/* Ignore non-periodic endpoints */
1560 			if (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
1561 					ep_type != ISOC_IN_EP &&
1562 					ep_type != INT_IN_EP)
1563 				continue;
1564 
1565 			/* Added or changed endpoint */
1566 			bw_info->ep_interval = CTX_TO_EP_INTERVAL(
1567 					le32_to_cpu(ep_ctx->ep_info));
1568 			/* Number of packets and mult are zero-based in the
1569 			 * input context, but we want one-based for the
1570 			 * interval table.
1571 			 */
1572 			bw_info->mult = CTX_TO_EP_MULT(
1573 					le32_to_cpu(ep_ctx->ep_info)) + 1;
1574 			bw_info->num_packets = CTX_TO_MAX_BURST(
1575 					le32_to_cpu(ep_ctx->ep_info2)) + 1;
1576 			bw_info->max_packet_size = MAX_PACKET_DECODED(
1577 					le32_to_cpu(ep_ctx->ep_info2));
1578 			bw_info->type = ep_type;
1579 			bw_info->max_esit_payload = CTX_TO_MAX_ESIT_PAYLOAD(
1580 					le32_to_cpu(ep_ctx->tx_info));
1581 		}
1582 	}
1583 }
1584 
1585 /* Copy output xhci_ep_ctx to the input xhci_ep_ctx copy.
1586  * Useful when you want to change one particular aspect of the endpoint and then
1587  * issue a configure endpoint command.
1588  */
xhci_endpoint_copy(struct xhci_hcd * xhci,struct xhci_container_ctx * in_ctx,struct xhci_container_ctx * out_ctx,unsigned int ep_index)1589 void xhci_endpoint_copy(struct xhci_hcd *xhci,
1590 		struct xhci_container_ctx *in_ctx,
1591 		struct xhci_container_ctx *out_ctx,
1592 		unsigned int ep_index)
1593 {
1594 	struct xhci_ep_ctx *out_ep_ctx;
1595 	struct xhci_ep_ctx *in_ep_ctx;
1596 
1597 	out_ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1598 	in_ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
1599 
1600 	in_ep_ctx->ep_info = out_ep_ctx->ep_info;
1601 	in_ep_ctx->ep_info2 = out_ep_ctx->ep_info2;
1602 	in_ep_ctx->deq = out_ep_ctx->deq;
1603 	in_ep_ctx->tx_info = out_ep_ctx->tx_info;
1604 	if (xhci->quirks & XHCI_MTK_HOST) {
1605 		in_ep_ctx->reserved[0] = out_ep_ctx->reserved[0];
1606 		in_ep_ctx->reserved[1] = out_ep_ctx->reserved[1];
1607 	}
1608 }
1609 
1610 /* Copy output xhci_slot_ctx to the input xhci_slot_ctx.
1611  * Useful when you want to change one particular aspect of the endpoint and then
1612  * issue a configure endpoint command.  Only the context entries field matters,
1613  * but we'll copy the whole thing anyway.
1614  */
xhci_slot_copy(struct xhci_hcd * xhci,struct xhci_container_ctx * in_ctx,struct xhci_container_ctx * out_ctx)1615 void xhci_slot_copy(struct xhci_hcd *xhci,
1616 		struct xhci_container_ctx *in_ctx,
1617 		struct xhci_container_ctx *out_ctx)
1618 {
1619 	struct xhci_slot_ctx *in_slot_ctx;
1620 	struct xhci_slot_ctx *out_slot_ctx;
1621 
1622 	in_slot_ctx = xhci_get_slot_ctx(xhci, in_ctx);
1623 	out_slot_ctx = xhci_get_slot_ctx(xhci, out_ctx);
1624 
1625 	in_slot_ctx->dev_info = out_slot_ctx->dev_info;
1626 	in_slot_ctx->dev_info2 = out_slot_ctx->dev_info2;
1627 	in_slot_ctx->tt_info = out_slot_ctx->tt_info;
1628 	in_slot_ctx->dev_state = out_slot_ctx->dev_state;
1629 }
1630 
1631 /* Set up the scratchpad buffer array and scratchpad buffers, if needed. */
scratchpad_alloc(struct xhci_hcd * xhci,gfp_t flags)1632 static int scratchpad_alloc(struct xhci_hcd *xhci, gfp_t flags)
1633 {
1634 	int i;
1635 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
1636 	int num_sp = HCS_MAX_SCRATCHPAD(xhci->hcs_params2);
1637 
1638 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
1639 			"Allocating %d scratchpad buffers", num_sp);
1640 
1641 	if (!num_sp)
1642 		return 0;
1643 
1644 	xhci->scratchpad = kzalloc_node(sizeof(*xhci->scratchpad), flags,
1645 				dev_to_node(dev));
1646 	if (!xhci->scratchpad)
1647 		goto fail_sp;
1648 
1649 	xhci->scratchpad->sp_array = dma_alloc_coherent(dev,
1650 				     size_mul(sizeof(u64), num_sp),
1651 				     &xhci->scratchpad->sp_dma, flags);
1652 	if (!xhci->scratchpad->sp_array)
1653 		goto fail_sp2;
1654 
1655 	xhci->scratchpad->sp_buffers = kcalloc_node(num_sp, sizeof(void *),
1656 					flags, dev_to_node(dev));
1657 	if (!xhci->scratchpad->sp_buffers)
1658 		goto fail_sp3;
1659 
1660 	xhci->dcbaa->dev_context_ptrs[0] = cpu_to_le64(xhci->scratchpad->sp_dma);
1661 	for (i = 0; i < num_sp; i++) {
1662 		dma_addr_t dma;
1663 		void *buf = dma_alloc_coherent(dev, xhci->page_size, &dma,
1664 					       flags);
1665 		if (!buf)
1666 			goto fail_sp4;
1667 
1668 		xhci->scratchpad->sp_array[i] = dma;
1669 		xhci->scratchpad->sp_buffers[i] = buf;
1670 	}
1671 
1672 	return 0;
1673 
1674  fail_sp4:
1675 	while (i--)
1676 		dma_free_coherent(dev, xhci->page_size,
1677 				    xhci->scratchpad->sp_buffers[i],
1678 				    xhci->scratchpad->sp_array[i]);
1679 
1680 	kfree(xhci->scratchpad->sp_buffers);
1681 
1682  fail_sp3:
1683 	dma_free_coherent(dev, num_sp * sizeof(u64),
1684 			    xhci->scratchpad->sp_array,
1685 			    xhci->scratchpad->sp_dma);
1686 
1687  fail_sp2:
1688 	kfree(xhci->scratchpad);
1689 	xhci->scratchpad = NULL;
1690 
1691  fail_sp:
1692 	return -ENOMEM;
1693 }
1694 
scratchpad_free(struct xhci_hcd * xhci)1695 static void scratchpad_free(struct xhci_hcd *xhci)
1696 {
1697 	int num_sp;
1698 	int i;
1699 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
1700 
1701 	if (!xhci->scratchpad)
1702 		return;
1703 
1704 	num_sp = HCS_MAX_SCRATCHPAD(xhci->hcs_params2);
1705 
1706 	for (i = 0; i < num_sp; i++) {
1707 		dma_free_coherent(dev, xhci->page_size,
1708 				    xhci->scratchpad->sp_buffers[i],
1709 				    xhci->scratchpad->sp_array[i]);
1710 	}
1711 	kfree(xhci->scratchpad->sp_buffers);
1712 	dma_free_coherent(dev, num_sp * sizeof(u64),
1713 			    xhci->scratchpad->sp_array,
1714 			    xhci->scratchpad->sp_dma);
1715 	kfree(xhci->scratchpad);
1716 	xhci->scratchpad = NULL;
1717 }
1718 
xhci_alloc_command(struct xhci_hcd * xhci,bool allocate_completion,gfp_t mem_flags)1719 struct xhci_command *xhci_alloc_command(struct xhci_hcd *xhci,
1720 		bool allocate_completion, gfp_t mem_flags)
1721 {
1722 	struct xhci_command *command;
1723 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
1724 
1725 	command = kzalloc_node(sizeof(*command), mem_flags, dev_to_node(dev));
1726 	if (!command)
1727 		return NULL;
1728 
1729 	if (allocate_completion) {
1730 		command->completion =
1731 			kzalloc_node(sizeof(struct completion), mem_flags,
1732 				dev_to_node(dev));
1733 		if (!command->completion) {
1734 			kfree(command);
1735 			return NULL;
1736 		}
1737 		init_completion(command->completion);
1738 	}
1739 
1740 	command->status = 0;
1741 	/* set default timeout to 5000 ms */
1742 	command->timeout_ms = XHCI_CMD_DEFAULT_TIMEOUT;
1743 	INIT_LIST_HEAD(&command->cmd_list);
1744 	return command;
1745 }
1746 
xhci_alloc_command_with_ctx(struct xhci_hcd * xhci,bool allocate_completion,gfp_t mem_flags)1747 struct xhci_command *xhci_alloc_command_with_ctx(struct xhci_hcd *xhci,
1748 		bool allocate_completion, gfp_t mem_flags)
1749 {
1750 	struct xhci_command *command;
1751 
1752 	command = xhci_alloc_command(xhci, allocate_completion, mem_flags);
1753 	if (!command)
1754 		return NULL;
1755 
1756 	command->in_ctx = xhci_alloc_container_ctx(xhci, XHCI_CTX_TYPE_INPUT,
1757 						   mem_flags);
1758 	if (!command->in_ctx) {
1759 		kfree(command->completion);
1760 		kfree(command);
1761 		return NULL;
1762 	}
1763 	return command;
1764 }
1765 
xhci_urb_free_priv(struct urb_priv * urb_priv)1766 void xhci_urb_free_priv(struct urb_priv *urb_priv)
1767 {
1768 	kfree(urb_priv);
1769 }
1770 
xhci_free_command(struct xhci_hcd * xhci,struct xhci_command * command)1771 void xhci_free_command(struct xhci_hcd *xhci,
1772 		struct xhci_command *command)
1773 {
1774 	xhci_free_container_ctx(xhci,
1775 			command->in_ctx);
1776 	kfree(command->completion);
1777 	kfree(command);
1778 }
1779 
xhci_alloc_erst(struct xhci_hcd * xhci,struct xhci_ring * evt_ring,struct xhci_erst * erst,gfp_t flags)1780 int xhci_alloc_erst(struct xhci_hcd *xhci,
1781 		    struct xhci_ring *evt_ring,
1782 		    struct xhci_erst *erst,
1783 		    gfp_t flags)
1784 {
1785 	size_t size;
1786 	unsigned int val;
1787 	struct xhci_segment *seg;
1788 	struct xhci_erst_entry *entry;
1789 
1790 	size = size_mul(sizeof(struct xhci_erst_entry), evt_ring->num_segs);
1791 	erst->entries = dma_alloc_coherent(xhci_to_hcd(xhci)->self.sysdev,
1792 					   size, &erst->erst_dma_addr, flags);
1793 	if (!erst->entries)
1794 		return -ENOMEM;
1795 
1796 	erst->num_entries = evt_ring->num_segs;
1797 
1798 	seg = evt_ring->first_seg;
1799 	for (val = 0; val < evt_ring->num_segs; val++) {
1800 		entry = &erst->entries[val];
1801 		entry->seg_addr = cpu_to_le64(seg->dma);
1802 		entry->seg_size = cpu_to_le32(TRBS_PER_SEGMENT);
1803 		entry->rsvd = 0;
1804 		seg = seg->next;
1805 	}
1806 
1807 	return 0;
1808 }
1809 
1810 static void
xhci_remove_interrupter(struct xhci_hcd * xhci,struct xhci_interrupter * ir)1811 xhci_remove_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
1812 {
1813 	u32 tmp;
1814 
1815 	if (!ir)
1816 		return;
1817 
1818 	/*
1819 	 * Clean out interrupter registers except ERSTBA. Clearing either the
1820 	 * low or high 32 bits of ERSTBA immediately causes the controller to
1821 	 * dereference the partially cleared 64 bit address, causing IOMMU error.
1822 	 */
1823 	if (ir->ir_set) {
1824 		tmp = readl(&ir->ir_set->erst_size);
1825 		tmp &= ERST_SIZE_MASK;
1826 		writel(tmp, &ir->ir_set->erst_size);
1827 
1828 		xhci_write_64(xhci, ERST_EHB, &ir->ir_set->erst_dequeue);
1829 	}
1830 }
1831 
1832 static void
xhci_free_interrupter(struct xhci_hcd * xhci,struct xhci_interrupter * ir)1833 xhci_free_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
1834 {
1835 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
1836 	size_t erst_size;
1837 
1838 	if (!ir)
1839 		return;
1840 
1841 	erst_size = sizeof(struct xhci_erst_entry) * ir->erst.num_entries;
1842 	if (ir->erst.entries)
1843 		dma_free_coherent(dev, erst_size,
1844 				  ir->erst.entries,
1845 				  ir->erst.erst_dma_addr);
1846 	ir->erst.entries = NULL;
1847 
1848 	/* free interrupter event ring */
1849 	if (ir->event_ring)
1850 		xhci_ring_free(xhci, ir->event_ring);
1851 
1852 	ir->event_ring = NULL;
1853 
1854 	kfree(ir);
1855 }
1856 
xhci_remove_secondary_interrupter(struct usb_hcd * hcd,struct xhci_interrupter * ir)1857 void xhci_remove_secondary_interrupter(struct usb_hcd *hcd, struct xhci_interrupter *ir)
1858 {
1859 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1860 	unsigned int intr_num;
1861 
1862 	spin_lock_irq(&xhci->lock);
1863 
1864 	/* interrupter 0 is primary interrupter, don't touch it */
1865 	if (!ir || !ir->intr_num || ir->intr_num >= xhci->max_interrupters) {
1866 		xhci_dbg(xhci, "Invalid secondary interrupter, can't remove\n");
1867 		spin_unlock_irq(&xhci->lock);
1868 		return;
1869 	}
1870 
1871 	intr_num = ir->intr_num;
1872 
1873 	xhci_remove_interrupter(xhci, ir);
1874 	xhci->interrupters[intr_num] = NULL;
1875 
1876 	spin_unlock_irq(&xhci->lock);
1877 
1878 	xhci_free_interrupter(xhci, ir);
1879 }
1880 EXPORT_SYMBOL_GPL(xhci_remove_secondary_interrupter);
1881 
xhci_mem_cleanup(struct xhci_hcd * xhci)1882 void xhci_mem_cleanup(struct xhci_hcd *xhci)
1883 {
1884 	struct device	*dev = xhci_to_hcd(xhci)->self.sysdev;
1885 	int i, j, num_ports;
1886 
1887 	cancel_delayed_work_sync(&xhci->cmd_timer);
1888 
1889 	for (i = 0; xhci->interrupters && i < xhci->max_interrupters; i++) {
1890 		if (xhci->interrupters[i]) {
1891 			xhci_remove_interrupter(xhci, xhci->interrupters[i]);
1892 			xhci_free_interrupter(xhci, xhci->interrupters[i]);
1893 			xhci->interrupters[i] = NULL;
1894 		}
1895 	}
1896 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed interrupters");
1897 
1898 	if (xhci->cmd_ring)
1899 		xhci_ring_free(xhci, xhci->cmd_ring);
1900 	xhci->cmd_ring = NULL;
1901 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed command ring");
1902 	xhci_cleanup_command_queue(xhci);
1903 
1904 	num_ports = HCS_MAX_PORTS(xhci->hcs_params1);
1905 	for (i = 0; i < num_ports && xhci->rh_bw; i++) {
1906 		struct xhci_interval_bw_table *bwt = &xhci->rh_bw[i].bw_table;
1907 		for (j = 0; j < XHCI_MAX_INTERVAL; j++) {
1908 			struct list_head *ep = &bwt->interval_bw[j].endpoints;
1909 			while (!list_empty(ep))
1910 				list_del_init(ep->next);
1911 		}
1912 	}
1913 
1914 	for (i = HCS_MAX_SLOTS(xhci->hcs_params1); i > 0; i--)
1915 		xhci_free_virt_devices_depth_first(xhci, i);
1916 
1917 	dma_pool_destroy(xhci->segment_pool);
1918 	xhci->segment_pool = NULL;
1919 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed segment pool");
1920 
1921 	dma_pool_destroy(xhci->device_pool);
1922 	xhci->device_pool = NULL;
1923 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed device context pool");
1924 
1925 	dma_pool_destroy(xhci->small_streams_pool);
1926 	xhci->small_streams_pool = NULL;
1927 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
1928 			"Freed small stream array pool");
1929 
1930 	dma_pool_destroy(xhci->medium_streams_pool);
1931 	xhci->medium_streams_pool = NULL;
1932 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
1933 			"Freed medium stream array pool");
1934 
1935 	if (xhci->dcbaa)
1936 		dma_free_coherent(dev, sizeof(*xhci->dcbaa),
1937 				xhci->dcbaa, xhci->dcbaa->dma);
1938 	xhci->dcbaa = NULL;
1939 
1940 	scratchpad_free(xhci);
1941 
1942 	if (!xhci->rh_bw)
1943 		goto no_bw;
1944 
1945 	for (i = 0; i < num_ports; i++) {
1946 		struct xhci_tt_bw_info *tt, *n;
1947 		list_for_each_entry_safe(tt, n, &xhci->rh_bw[i].tts, tt_list) {
1948 			list_del(&tt->tt_list);
1949 			kfree(tt);
1950 		}
1951 	}
1952 
1953 no_bw:
1954 	xhci->cmd_ring_reserved_trbs = 0;
1955 	xhci->usb2_rhub.num_ports = 0;
1956 	xhci->usb3_rhub.num_ports = 0;
1957 	xhci->num_active_eps = 0;
1958 	kfree(xhci->usb2_rhub.ports);
1959 	kfree(xhci->usb3_rhub.ports);
1960 	kfree(xhci->hw_ports);
1961 	kfree(xhci->rh_bw);
1962 	kfree(xhci->ext_caps);
1963 	for (i = 0; i < xhci->num_port_caps; i++)
1964 		kfree(xhci->port_caps[i].psi);
1965 	kfree(xhci->port_caps);
1966 	kfree(xhci->interrupters);
1967 	xhci->num_port_caps = 0;
1968 
1969 	xhci->usb2_rhub.ports = NULL;
1970 	xhci->usb3_rhub.ports = NULL;
1971 	xhci->hw_ports = NULL;
1972 	xhci->rh_bw = NULL;
1973 	xhci->ext_caps = NULL;
1974 	xhci->port_caps = NULL;
1975 	xhci->interrupters = NULL;
1976 
1977 	xhci->page_size = 0;
1978 	xhci->page_shift = 0;
1979 	xhci->usb2_rhub.bus_state.bus_suspended = 0;
1980 	xhci->usb3_rhub.bus_state.bus_suspended = 0;
1981 }
1982 
xhci_set_hc_event_deq(struct xhci_hcd * xhci,struct xhci_interrupter * ir)1983 static void xhci_set_hc_event_deq(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
1984 {
1985 	dma_addr_t deq;
1986 
1987 	deq = xhci_trb_virt_to_dma(ir->event_ring->deq_seg,
1988 			ir->event_ring->dequeue);
1989 	if (!deq)
1990 		xhci_warn(xhci, "WARN something wrong with SW event ring dequeue ptr.\n");
1991 	/* Update HC event ring dequeue pointer */
1992 	/* Don't clear the EHB bit (which is RW1C) because
1993 	 * there might be more events to service.
1994 	 */
1995 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
1996 		       "// Write event ring dequeue pointer, preserving EHB bit");
1997 	xhci_write_64(xhci, ((u64) deq & (u64) ~ERST_PTR_MASK),
1998 			&ir->ir_set->erst_dequeue);
1999 }
2000 
xhci_add_in_port(struct xhci_hcd * xhci,unsigned int num_ports,__le32 __iomem * addr,int max_caps)2001 static void xhci_add_in_port(struct xhci_hcd *xhci, unsigned int num_ports,
2002 		__le32 __iomem *addr, int max_caps)
2003 {
2004 	u32 temp, port_offset, port_count;
2005 	int i;
2006 	u8 major_revision, minor_revision, tmp_minor_revision;
2007 	struct xhci_hub *rhub;
2008 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
2009 	struct xhci_port_cap *port_cap;
2010 
2011 	temp = readl(addr);
2012 	major_revision = XHCI_EXT_PORT_MAJOR(temp);
2013 	minor_revision = XHCI_EXT_PORT_MINOR(temp);
2014 
2015 	if (major_revision == 0x03) {
2016 		rhub = &xhci->usb3_rhub;
2017 		/*
2018 		 * Some hosts incorrectly use sub-minor version for minor
2019 		 * version (i.e. 0x02 instead of 0x20 for bcdUSB 0x320 and 0x01
2020 		 * for bcdUSB 0x310). Since there is no USB release with sub
2021 		 * minor version 0x301 to 0x309, we can assume that they are
2022 		 * incorrect and fix it here.
2023 		 */
2024 		if (minor_revision > 0x00 && minor_revision < 0x10)
2025 			minor_revision <<= 4;
2026 		/*
2027 		 * Some zhaoxin's xHCI controller that follow usb3.1 spec
2028 		 * but only support Gen1.
2029 		 */
2030 		if (xhci->quirks & XHCI_ZHAOXIN_HOST) {
2031 			tmp_minor_revision = minor_revision;
2032 			minor_revision = 0;
2033 		}
2034 
2035 	} else if (major_revision <= 0x02) {
2036 		rhub = &xhci->usb2_rhub;
2037 	} else {
2038 		xhci_warn(xhci, "Ignoring unknown port speed, Ext Cap %p, revision = 0x%x\n",
2039 				addr, major_revision);
2040 		/* Ignoring port protocol we can't understand. FIXME */
2041 		return;
2042 	}
2043 
2044 	/* Port offset and count in the third dword, see section 7.2 */
2045 	temp = readl(addr + 2);
2046 	port_offset = XHCI_EXT_PORT_OFF(temp);
2047 	port_count = XHCI_EXT_PORT_COUNT(temp);
2048 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2049 		       "Ext Cap %p, port offset = %u, count = %u, revision = 0x%x",
2050 		       addr, port_offset, port_count, major_revision);
2051 	/* Port count includes the current port offset */
2052 	if (port_offset == 0 || (port_offset + port_count - 1) > num_ports)
2053 		/* WTF? "Valid values are ‘1’ to MaxPorts" */
2054 		return;
2055 
2056 	port_cap = &xhci->port_caps[xhci->num_port_caps++];
2057 	if (xhci->num_port_caps > max_caps)
2058 		return;
2059 
2060 	port_cap->psi_count = XHCI_EXT_PORT_PSIC(temp);
2061 
2062 	if (port_cap->psi_count) {
2063 		port_cap->psi = kcalloc_node(port_cap->psi_count,
2064 					     sizeof(*port_cap->psi),
2065 					     GFP_KERNEL, dev_to_node(dev));
2066 		if (!port_cap->psi)
2067 			port_cap->psi_count = 0;
2068 
2069 		port_cap->psi_uid_count++;
2070 		for (i = 0; i < port_cap->psi_count; i++) {
2071 			port_cap->psi[i] = readl(addr + 4 + i);
2072 
2073 			/* count unique ID values, two consecutive entries can
2074 			 * have the same ID if link is assymetric
2075 			 */
2076 			if (i && (XHCI_EXT_PORT_PSIV(port_cap->psi[i]) !=
2077 				  XHCI_EXT_PORT_PSIV(port_cap->psi[i - 1])))
2078 				port_cap->psi_uid_count++;
2079 
2080 			if (xhci->quirks & XHCI_ZHAOXIN_HOST &&
2081 			    major_revision == 0x03 &&
2082 			    XHCI_EXT_PORT_PSIV(port_cap->psi[i]) >= 5)
2083 				minor_revision = tmp_minor_revision;
2084 
2085 			xhci_dbg(xhci, "PSIV:%d PSIE:%d PLT:%d PFD:%d LP:%d PSIM:%d\n",
2086 				  XHCI_EXT_PORT_PSIV(port_cap->psi[i]),
2087 				  XHCI_EXT_PORT_PSIE(port_cap->psi[i]),
2088 				  XHCI_EXT_PORT_PLT(port_cap->psi[i]),
2089 				  XHCI_EXT_PORT_PFD(port_cap->psi[i]),
2090 				  XHCI_EXT_PORT_LP(port_cap->psi[i]),
2091 				  XHCI_EXT_PORT_PSIM(port_cap->psi[i]));
2092 		}
2093 	}
2094 
2095 	rhub->maj_rev = major_revision;
2096 
2097 	if (rhub->min_rev < minor_revision)
2098 		rhub->min_rev = minor_revision;
2099 
2100 	port_cap->maj_rev = major_revision;
2101 	port_cap->min_rev = minor_revision;
2102 
2103 	/* cache usb2 port capabilities */
2104 	if (major_revision < 0x03 && xhci->num_ext_caps < max_caps)
2105 		xhci->ext_caps[xhci->num_ext_caps++] = temp;
2106 
2107 	if ((xhci->hci_version >= 0x100) && (major_revision != 0x03) &&
2108 		 (temp & XHCI_HLC)) {
2109 		xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2110 			       "xHCI 1.0: support USB2 hardware lpm");
2111 		xhci->hw_lpm_support = 1;
2112 	}
2113 
2114 	port_offset--;
2115 	for (i = port_offset; i < (port_offset + port_count); i++) {
2116 		struct xhci_port *hw_port = &xhci->hw_ports[i];
2117 		/* Duplicate entry.  Ignore the port if the revisions differ. */
2118 		if (hw_port->rhub) {
2119 			xhci_warn(xhci, "Duplicate port entry, Ext Cap %p, port %u\n", addr, i);
2120 			xhci_warn(xhci, "Port was marked as USB %u, duplicated as USB %u\n",
2121 					hw_port->rhub->maj_rev, major_revision);
2122 			/* Only adjust the roothub port counts if we haven't
2123 			 * found a similar duplicate.
2124 			 */
2125 			if (hw_port->rhub != rhub &&
2126 				 hw_port->hcd_portnum != DUPLICATE_ENTRY) {
2127 				hw_port->rhub->num_ports--;
2128 				hw_port->hcd_portnum = DUPLICATE_ENTRY;
2129 			}
2130 			continue;
2131 		}
2132 		hw_port->rhub = rhub;
2133 		hw_port->port_cap = port_cap;
2134 		rhub->num_ports++;
2135 	}
2136 	/* FIXME: Should we disable ports not in the Extended Capabilities? */
2137 }
2138 
xhci_create_rhub_port_array(struct xhci_hcd * xhci,struct xhci_hub * rhub,gfp_t flags)2139 static void xhci_create_rhub_port_array(struct xhci_hcd *xhci,
2140 					struct xhci_hub *rhub, gfp_t flags)
2141 {
2142 	int port_index = 0;
2143 	int i;
2144 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
2145 
2146 	if (!rhub->num_ports)
2147 		return;
2148 	rhub->ports = kcalloc_node(rhub->num_ports, sizeof(*rhub->ports),
2149 			flags, dev_to_node(dev));
2150 	if (!rhub->ports)
2151 		return;
2152 
2153 	for (i = 0; i < HCS_MAX_PORTS(xhci->hcs_params1); i++) {
2154 		if (xhci->hw_ports[i].rhub != rhub ||
2155 		    xhci->hw_ports[i].hcd_portnum == DUPLICATE_ENTRY)
2156 			continue;
2157 		xhci->hw_ports[i].hcd_portnum = port_index;
2158 		rhub->ports[port_index] = &xhci->hw_ports[i];
2159 		port_index++;
2160 		if (port_index == rhub->num_ports)
2161 			break;
2162 	}
2163 }
2164 
2165 /*
2166  * Scan the Extended Capabilities for the "Supported Protocol Capabilities" that
2167  * specify what speeds each port is supposed to be.  We can't count on the port
2168  * speed bits in the PORTSC register being correct until a device is connected,
2169  * but we need to set up the two fake roothubs with the correct number of USB
2170  * 3.0 and USB 2.0 ports at host controller initialization time.
2171  */
xhci_setup_port_arrays(struct xhci_hcd * xhci,gfp_t flags)2172 static int xhci_setup_port_arrays(struct xhci_hcd *xhci, gfp_t flags)
2173 {
2174 	void __iomem *base;
2175 	u32 offset;
2176 	unsigned int num_ports;
2177 	int i, j;
2178 	int cap_count = 0;
2179 	u32 cap_start;
2180 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
2181 
2182 	num_ports = HCS_MAX_PORTS(xhci->hcs_params1);
2183 	xhci->hw_ports = kcalloc_node(num_ports, sizeof(*xhci->hw_ports),
2184 				flags, dev_to_node(dev));
2185 	if (!xhci->hw_ports)
2186 		return -ENOMEM;
2187 
2188 	for (i = 0; i < num_ports; i++) {
2189 		xhci->hw_ports[i].addr = &xhci->op_regs->port_status_base +
2190 			NUM_PORT_REGS * i;
2191 		xhci->hw_ports[i].hw_portnum = i;
2192 
2193 		init_completion(&xhci->hw_ports[i].rexit_done);
2194 		init_completion(&xhci->hw_ports[i].u3exit_done);
2195 	}
2196 
2197 	xhci->rh_bw = kcalloc_node(num_ports, sizeof(*xhci->rh_bw), flags,
2198 				   dev_to_node(dev));
2199 	if (!xhci->rh_bw)
2200 		return -ENOMEM;
2201 	for (i = 0; i < num_ports; i++) {
2202 		struct xhci_interval_bw_table *bw_table;
2203 
2204 		INIT_LIST_HEAD(&xhci->rh_bw[i].tts);
2205 		bw_table = &xhci->rh_bw[i].bw_table;
2206 		for (j = 0; j < XHCI_MAX_INTERVAL; j++)
2207 			INIT_LIST_HEAD(&bw_table->interval_bw[j].endpoints);
2208 	}
2209 	base = &xhci->cap_regs->hc_capbase;
2210 
2211 	cap_start = xhci_find_next_ext_cap(base, 0, XHCI_EXT_CAPS_PROTOCOL);
2212 	if (!cap_start) {
2213 		xhci_err(xhci, "No Extended Capability registers, unable to set up roothub\n");
2214 		return -ENODEV;
2215 	}
2216 
2217 	offset = cap_start;
2218 	/* count extended protocol capability entries for later caching */
2219 	while (offset) {
2220 		cap_count++;
2221 		offset = xhci_find_next_ext_cap(base, offset,
2222 						      XHCI_EXT_CAPS_PROTOCOL);
2223 	}
2224 
2225 	xhci->ext_caps = kcalloc_node(cap_count, sizeof(*xhci->ext_caps),
2226 				flags, dev_to_node(dev));
2227 	if (!xhci->ext_caps)
2228 		return -ENOMEM;
2229 
2230 	xhci->port_caps = kcalloc_node(cap_count, sizeof(*xhci->port_caps),
2231 				flags, dev_to_node(dev));
2232 	if (!xhci->port_caps)
2233 		return -ENOMEM;
2234 
2235 	offset = cap_start;
2236 
2237 	while (offset) {
2238 		xhci_add_in_port(xhci, num_ports, base + offset, cap_count);
2239 		if (xhci->usb2_rhub.num_ports + xhci->usb3_rhub.num_ports ==
2240 		    num_ports)
2241 			break;
2242 		offset = xhci_find_next_ext_cap(base, offset,
2243 						XHCI_EXT_CAPS_PROTOCOL);
2244 	}
2245 	if (xhci->usb2_rhub.num_ports == 0 && xhci->usb3_rhub.num_ports == 0) {
2246 		xhci_warn(xhci, "No ports on the roothubs?\n");
2247 		return -ENODEV;
2248 	}
2249 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2250 		       "Found %u USB 2.0 ports and %u USB 3.0 ports.",
2251 		       xhci->usb2_rhub.num_ports, xhci->usb3_rhub.num_ports);
2252 
2253 	/* Place limits on the number of roothub ports so that the hub
2254 	 * descriptors aren't longer than the USB core will allocate.
2255 	 */
2256 	if (xhci->usb3_rhub.num_ports > USB_SS_MAXPORTS) {
2257 		xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2258 				"Limiting USB 3.0 roothub ports to %u.",
2259 				USB_SS_MAXPORTS);
2260 		xhci->usb3_rhub.num_ports = USB_SS_MAXPORTS;
2261 	}
2262 	if (xhci->usb2_rhub.num_ports > USB_MAXCHILDREN) {
2263 		xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2264 				"Limiting USB 2.0 roothub ports to %u.",
2265 				USB_MAXCHILDREN);
2266 		xhci->usb2_rhub.num_ports = USB_MAXCHILDREN;
2267 	}
2268 
2269 	if (!xhci->usb2_rhub.num_ports)
2270 		xhci_info(xhci, "USB2 root hub has no ports\n");
2271 
2272 	if (!xhci->usb3_rhub.num_ports)
2273 		xhci_info(xhci, "USB3 root hub has no ports\n");
2274 
2275 	xhci_create_rhub_port_array(xhci, &xhci->usb2_rhub, flags);
2276 	xhci_create_rhub_port_array(xhci, &xhci->usb3_rhub, flags);
2277 
2278 	return 0;
2279 }
2280 
2281 static struct xhci_interrupter *
xhci_alloc_interrupter(struct xhci_hcd * xhci,unsigned int segs,gfp_t flags)2282 xhci_alloc_interrupter(struct xhci_hcd *xhci, unsigned int segs, gfp_t flags)
2283 {
2284 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
2285 	struct xhci_interrupter *ir;
2286 	unsigned int max_segs;
2287 	int ret;
2288 
2289 	if (!segs)
2290 		segs = ERST_DEFAULT_SEGS;
2291 
2292 	max_segs = BIT(HCS_ERST_MAX(xhci->hcs_params2));
2293 	segs = min(segs, max_segs);
2294 
2295 	ir = kzalloc_node(sizeof(*ir), flags, dev_to_node(dev));
2296 	if (!ir)
2297 		return NULL;
2298 
2299 	ir->event_ring = xhci_ring_alloc(xhci, segs, 1, TYPE_EVENT, 0, flags);
2300 	if (!ir->event_ring) {
2301 		xhci_warn(xhci, "Failed to allocate interrupter event ring\n");
2302 		kfree(ir);
2303 		return NULL;
2304 	}
2305 
2306 	ret = xhci_alloc_erst(xhci, ir->event_ring, &ir->erst, flags);
2307 	if (ret) {
2308 		xhci_warn(xhci, "Failed to allocate interrupter erst\n");
2309 		xhci_ring_free(xhci, ir->event_ring);
2310 		kfree(ir);
2311 		return NULL;
2312 	}
2313 
2314 	return ir;
2315 }
2316 
2317 static int
xhci_add_interrupter(struct xhci_hcd * xhci,struct xhci_interrupter * ir,unsigned int intr_num)2318 xhci_add_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir,
2319 		     unsigned int intr_num)
2320 {
2321 	u64 erst_base;
2322 	u32 erst_size;
2323 
2324 	if (intr_num > xhci->max_interrupters) {
2325 		xhci_warn(xhci, "Can't add interrupter %d, max interrupters %d\n",
2326 			  intr_num, xhci->max_interrupters);
2327 		return -EINVAL;
2328 	}
2329 
2330 	if (xhci->interrupters[intr_num]) {
2331 		xhci_warn(xhci, "Interrupter %d\n already set up", intr_num);
2332 		return -EINVAL;
2333 	}
2334 
2335 	xhci->interrupters[intr_num] = ir;
2336 	ir->intr_num = intr_num;
2337 	ir->ir_set = &xhci->run_regs->ir_set[intr_num];
2338 
2339 	/* set ERST count with the number of entries in the segment table */
2340 	erst_size = readl(&ir->ir_set->erst_size);
2341 	erst_size &= ERST_SIZE_MASK;
2342 	erst_size |= ir->event_ring->num_segs;
2343 	writel(erst_size, &ir->ir_set->erst_size);
2344 
2345 	erst_base = xhci_read_64(xhci, &ir->ir_set->erst_base);
2346 	erst_base &= ERST_BASE_RSVDP;
2347 	erst_base |= ir->erst.erst_dma_addr & ~ERST_BASE_RSVDP;
2348 	if (xhci->quirks & XHCI_WRITE_64_HI_LO)
2349 		hi_lo_writeq(erst_base, &ir->ir_set->erst_base);
2350 	else
2351 		xhci_write_64(xhci, erst_base, &ir->ir_set->erst_base);
2352 
2353 	/* Set the event ring dequeue address of this interrupter */
2354 	xhci_set_hc_event_deq(xhci, ir);
2355 
2356 	return 0;
2357 }
2358 
2359 struct xhci_interrupter *
xhci_create_secondary_interrupter(struct usb_hcd * hcd,unsigned int segs,u32 imod_interval)2360 xhci_create_secondary_interrupter(struct usb_hcd *hcd, unsigned int segs,
2361 				  u32 imod_interval)
2362 {
2363 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
2364 	struct xhci_interrupter *ir;
2365 	unsigned int i;
2366 	int err = -ENOSPC;
2367 
2368 	if (!xhci->interrupters || xhci->max_interrupters <= 1)
2369 		return NULL;
2370 
2371 	ir = xhci_alloc_interrupter(xhci, segs, GFP_KERNEL);
2372 	if (!ir)
2373 		return NULL;
2374 
2375 	spin_lock_irq(&xhci->lock);
2376 
2377 	/* Find available secondary interrupter, interrupter 0 is reserved for primary */
2378 	for (i = 1; i < xhci->max_interrupters; i++) {
2379 		if (xhci->interrupters[i] == NULL) {
2380 			err = xhci_add_interrupter(xhci, ir, i);
2381 			break;
2382 		}
2383 	}
2384 
2385 	spin_unlock_irq(&xhci->lock);
2386 
2387 	if (err) {
2388 		xhci_warn(xhci, "Failed to add secondary interrupter, max interrupters %d\n",
2389 			  xhci->max_interrupters);
2390 		xhci_free_interrupter(xhci, ir);
2391 		return NULL;
2392 	}
2393 
2394 	err = xhci_set_interrupter_moderation(ir, imod_interval);
2395 	if (err)
2396 		xhci_warn(xhci, "Failed to set interrupter %d moderation to %uns\n",
2397 			  i, imod_interval);
2398 
2399 	xhci_dbg(xhci, "Add secondary interrupter %d, max interrupters %d\n",
2400 		 i, xhci->max_interrupters);
2401 
2402 	return ir;
2403 }
2404 EXPORT_SYMBOL_GPL(xhci_create_secondary_interrupter);
2405 
xhci_mem_init(struct xhci_hcd * xhci,gfp_t flags)2406 int xhci_mem_init(struct xhci_hcd *xhci, gfp_t flags)
2407 {
2408 	struct xhci_interrupter *ir;
2409 	struct device	*dev = xhci_to_hcd(xhci)->self.sysdev;
2410 	dma_addr_t	dma;
2411 	unsigned int	val, val2;
2412 	u64		val_64;
2413 	u32		page_size, temp;
2414 	int		i;
2415 
2416 	INIT_LIST_HEAD(&xhci->cmd_list);
2417 
2418 	/* init command timeout work */
2419 	INIT_DELAYED_WORK(&xhci->cmd_timer, xhci_handle_command_timeout);
2420 	init_completion(&xhci->cmd_ring_stop_completion);
2421 
2422 	page_size = readl(&xhci->op_regs->page_size);
2423 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2424 			"Supported page size register = 0x%x", page_size);
2425 	val = ffs(page_size) - 1;
2426 	if (val < 16)
2427 		xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2428 			"Supported page size of %iK", (1 << (val + 12)) / 1024);
2429 	else
2430 		xhci_warn(xhci, "WARN: no supported page size\n");
2431 	/* Use 4K pages, since that's common and the minimum the HC supports */
2432 	xhci->page_shift = 12;
2433 	xhci->page_size = 1 << xhci->page_shift;
2434 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2435 			"HCD page size set to %iK", xhci->page_size / 1024);
2436 
2437 	/*
2438 	 * Program the Number of Device Slots Enabled field in the CONFIG
2439 	 * register with the max value of slots the HC can handle.
2440 	 */
2441 	val = HCS_MAX_SLOTS(readl(&xhci->cap_regs->hcs_params1));
2442 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2443 			"// xHC can handle at most %d device slots.", val);
2444 	val2 = readl(&xhci->op_regs->config_reg);
2445 	val |= (val2 & ~HCS_SLOTS_MASK);
2446 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2447 			"// Setting Max device slots reg = 0x%x.", val);
2448 	writel(val, &xhci->op_regs->config_reg);
2449 
2450 	/*
2451 	 * xHCI section 5.4.6 - Device Context array must be
2452 	 * "physically contiguous and 64-byte (cache line) aligned".
2453 	 */
2454 	xhci->dcbaa = dma_alloc_coherent(dev, sizeof(*xhci->dcbaa), &dma,
2455 			flags);
2456 	if (!xhci->dcbaa)
2457 		goto fail;
2458 	xhci->dcbaa->dma = dma;
2459 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2460 			"// Device context base array address = 0x%pad (DMA), %p (virt)",
2461 			&xhci->dcbaa->dma, xhci->dcbaa);
2462 	xhci_write_64(xhci, dma, &xhci->op_regs->dcbaa_ptr);
2463 
2464 	/*
2465 	 * Initialize the ring segment pool.  The ring must be a contiguous
2466 	 * structure comprised of TRBs.  The TRBs must be 16 byte aligned,
2467 	 * however, the command ring segment needs 64-byte aligned segments
2468 	 * and our use of dma addresses in the trb_address_map radix tree needs
2469 	 * TRB_SEGMENT_SIZE alignment, so we pick the greater alignment need.
2470 	 */
2471 	if (xhci->quirks & XHCI_TRB_OVERFETCH)
2472 		/* Buggy HC prefetches beyond segment bounds - allocate dummy space at the end */
2473 		xhci->segment_pool = dma_pool_create("xHCI ring segments", dev,
2474 				TRB_SEGMENT_SIZE * 2, TRB_SEGMENT_SIZE * 2, xhci->page_size * 2);
2475 	else
2476 		xhci->segment_pool = dma_pool_create("xHCI ring segments", dev,
2477 				TRB_SEGMENT_SIZE, TRB_SEGMENT_SIZE, xhci->page_size);
2478 
2479 	/* See Table 46 and Note on Figure 55 */
2480 	xhci->device_pool = dma_pool_create("xHCI input/output contexts", dev,
2481 			2112, 64, xhci->page_size);
2482 	if (!xhci->segment_pool || !xhci->device_pool)
2483 		goto fail;
2484 
2485 	/* Linear stream context arrays don't have any boundary restrictions,
2486 	 * and only need to be 16-byte aligned.
2487 	 */
2488 	xhci->small_streams_pool =
2489 		dma_pool_create("xHCI 256 byte stream ctx arrays",
2490 			dev, SMALL_STREAM_ARRAY_SIZE, 16, 0);
2491 	xhci->medium_streams_pool =
2492 		dma_pool_create("xHCI 1KB stream ctx arrays",
2493 			dev, MEDIUM_STREAM_ARRAY_SIZE, 16, 0);
2494 	/* Any stream context array bigger than MEDIUM_STREAM_ARRAY_SIZE
2495 	 * will be allocated with dma_alloc_coherent()
2496 	 */
2497 
2498 	if (!xhci->small_streams_pool || !xhci->medium_streams_pool)
2499 		goto fail;
2500 
2501 	/* Set up the command ring to have one segments for now. */
2502 	xhci->cmd_ring = xhci_ring_alloc(xhci, 1, 1, TYPE_COMMAND, 0, flags);
2503 	if (!xhci->cmd_ring)
2504 		goto fail;
2505 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2506 			"Allocated command ring at %p", xhci->cmd_ring);
2507 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "First segment DMA is 0x%pad",
2508 			&xhci->cmd_ring->first_seg->dma);
2509 
2510 	/* Set the address in the Command Ring Control register */
2511 	val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
2512 	val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
2513 		(xhci->cmd_ring->first_seg->dma & (u64) ~CMD_RING_RSVD_BITS) |
2514 		xhci->cmd_ring->cycle_state;
2515 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2516 			"// Setting command ring address to 0x%016llx", val_64);
2517 	xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
2518 
2519 	/* Reserve one command ring TRB for disabling LPM.
2520 	 * Since the USB core grabs the shared usb_bus bandwidth mutex before
2521 	 * disabling LPM, we only need to reserve one TRB for all devices.
2522 	 */
2523 	xhci->cmd_ring_reserved_trbs++;
2524 
2525 	val = readl(&xhci->cap_regs->db_off);
2526 	val &= DBOFF_MASK;
2527 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2528 		       "// Doorbell array is located at offset 0x%x from cap regs base addr",
2529 		       val);
2530 	xhci->dba = (void __iomem *) xhci->cap_regs + val;
2531 
2532 	/* Allocate and set up primary interrupter 0 with an event ring. */
2533 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2534 		       "Allocating primary event ring");
2535 	xhci->interrupters = kcalloc_node(xhci->max_interrupters, sizeof(*xhci->interrupters),
2536 					  flags, dev_to_node(dev));
2537 
2538 	ir = xhci_alloc_interrupter(xhci, 0, flags);
2539 	if (!ir)
2540 		goto fail;
2541 
2542 	if (xhci_add_interrupter(xhci, ir, 0))
2543 		goto fail;
2544 
2545 	xhci->isoc_bei_interval = AVOID_BEI_INTERVAL_MAX;
2546 
2547 	/*
2548 	 * XXX: Might need to set the Interrupter Moderation Register to
2549 	 * something other than the default (~1ms minimum between interrupts).
2550 	 * See section 5.5.1.2.
2551 	 */
2552 	for (i = 0; i < MAX_HC_SLOTS; i++)
2553 		xhci->devs[i] = NULL;
2554 
2555 	if (scratchpad_alloc(xhci, flags))
2556 		goto fail;
2557 	if (xhci_setup_port_arrays(xhci, flags))
2558 		goto fail;
2559 
2560 	/* Enable USB 3.0 device notifications for function remote wake, which
2561 	 * is necessary for allowing USB 3.0 devices to do remote wakeup from
2562 	 * U3 (device suspend).
2563 	 */
2564 	temp = readl(&xhci->op_regs->dev_notification);
2565 	temp &= ~DEV_NOTE_MASK;
2566 	temp |= DEV_NOTE_FWAKE;
2567 	writel(temp, &xhci->op_regs->dev_notification);
2568 
2569 	return 0;
2570 
2571 fail:
2572 	xhci_halt(xhci);
2573 	xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
2574 	xhci_mem_cleanup(xhci);
2575 	return -ENOMEM;
2576 }
2577