xref: /openbmc/linux/drivers/usb/host/xhci-mem.c (revision 5a4c98323b01d52382575a7a4d6bf7bf5f326047)
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_7) &&
1440 		    udev->speed >= USB_SPEED_HIGH &&
1441 		    interval >= 7) {
1442 			interval = 6;
1443 		}
1444 	}
1445 
1446 	mult = xhci_get_endpoint_mult(udev, ep);
1447 	max_packet = usb_endpoint_maxp(&ep->desc);
1448 	max_burst = xhci_get_endpoint_max_burst(udev, ep);
1449 	avg_trb_len = max_esit_payload;
1450 
1451 	/* FIXME dig Mult and streams info out of ep companion desc */
1452 
1453 	/* Allow 3 retries for everything but isoc, set CErr = 3 */
1454 	if (!usb_endpoint_xfer_isoc(&ep->desc))
1455 		err_count = 3;
1456 	/* HS bulk max packet should be 512, FS bulk supports 8, 16, 32 or 64 */
1457 	if (usb_endpoint_xfer_bulk(&ep->desc)) {
1458 		if (udev->speed == USB_SPEED_HIGH)
1459 			max_packet = 512;
1460 		if (udev->speed == USB_SPEED_FULL) {
1461 			max_packet = rounddown_pow_of_two(max_packet);
1462 			max_packet = clamp_val(max_packet, 8, 64);
1463 		}
1464 	}
1465 	/* xHCI 1.0 and 1.1 indicates that ctrl ep avg TRB Length should be 8 */
1466 	if (usb_endpoint_xfer_control(&ep->desc) && xhci->hci_version >= 0x100)
1467 		avg_trb_len = 8;
1468 	/* xhci 1.1 with LEC support doesn't use mult field, use RsvdZ */
1469 	if ((xhci->hci_version > 0x100) && HCC2_LEC(xhci->hcc_params2))
1470 		mult = 0;
1471 
1472 	/* Set up the endpoint ring */
1473 	virt_dev->eps[ep_index].new_ring =
1474 		xhci_ring_alloc(xhci, 2, 1, ring_type, max_packet, mem_flags);
1475 	if (!virt_dev->eps[ep_index].new_ring)
1476 		return -ENOMEM;
1477 
1478 	virt_dev->eps[ep_index].skip = false;
1479 	ep_ring = virt_dev->eps[ep_index].new_ring;
1480 
1481 	/* Fill the endpoint context */
1482 	ep_ctx->ep_info = cpu_to_le32(EP_MAX_ESIT_PAYLOAD_HI(max_esit_payload) |
1483 				      EP_INTERVAL(interval) |
1484 				      EP_MULT(mult));
1485 	ep_ctx->ep_info2 = cpu_to_le32(EP_TYPE(endpoint_type) |
1486 				       MAX_PACKET(max_packet) |
1487 				       MAX_BURST(max_burst) |
1488 				       ERROR_COUNT(err_count));
1489 	ep_ctx->deq = cpu_to_le64(ep_ring->first_seg->dma |
1490 				  ep_ring->cycle_state);
1491 
1492 	ep_ctx->tx_info = cpu_to_le32(EP_MAX_ESIT_PAYLOAD_LO(max_esit_payload) |
1493 				      EP_AVG_TRB_LENGTH(avg_trb_len));
1494 
1495 	return 0;
1496 }
1497 
xhci_endpoint_zero(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,struct usb_host_endpoint * ep)1498 void xhci_endpoint_zero(struct xhci_hcd *xhci,
1499 		struct xhci_virt_device *virt_dev,
1500 		struct usb_host_endpoint *ep)
1501 {
1502 	unsigned int ep_index;
1503 	struct xhci_ep_ctx *ep_ctx;
1504 
1505 	ep_index = xhci_get_endpoint_index(&ep->desc);
1506 	ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, ep_index);
1507 
1508 	ep_ctx->ep_info = 0;
1509 	ep_ctx->ep_info2 = 0;
1510 	ep_ctx->deq = 0;
1511 	ep_ctx->tx_info = 0;
1512 	/* Don't free the endpoint ring until the set interface or configuration
1513 	 * request succeeds.
1514 	 */
1515 }
1516 
xhci_clear_endpoint_bw_info(struct xhci_bw_info * bw_info)1517 void xhci_clear_endpoint_bw_info(struct xhci_bw_info *bw_info)
1518 {
1519 	bw_info->ep_interval = 0;
1520 	bw_info->mult = 0;
1521 	bw_info->num_packets = 0;
1522 	bw_info->max_packet_size = 0;
1523 	bw_info->type = 0;
1524 	bw_info->max_esit_payload = 0;
1525 }
1526 
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)1527 void xhci_update_bw_info(struct xhci_hcd *xhci,
1528 		struct xhci_container_ctx *in_ctx,
1529 		struct xhci_input_control_ctx *ctrl_ctx,
1530 		struct xhci_virt_device *virt_dev)
1531 {
1532 	struct xhci_bw_info *bw_info;
1533 	struct xhci_ep_ctx *ep_ctx;
1534 	unsigned int ep_type;
1535 	int i;
1536 
1537 	for (i = 1; i < 31; i++) {
1538 		bw_info = &virt_dev->eps[i].bw_info;
1539 
1540 		/* We can't tell what endpoint type is being dropped, but
1541 		 * unconditionally clearing the bandwidth info for non-periodic
1542 		 * endpoints should be harmless because the info will never be
1543 		 * set in the first place.
1544 		 */
1545 		if (!EP_IS_ADDED(ctrl_ctx, i) && EP_IS_DROPPED(ctrl_ctx, i)) {
1546 			/* Dropped endpoint */
1547 			xhci_clear_endpoint_bw_info(bw_info);
1548 			continue;
1549 		}
1550 
1551 		if (EP_IS_ADDED(ctrl_ctx, i)) {
1552 			ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, i);
1553 			ep_type = CTX_TO_EP_TYPE(le32_to_cpu(ep_ctx->ep_info2));
1554 
1555 			/* Ignore non-periodic endpoints */
1556 			if (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
1557 					ep_type != ISOC_IN_EP &&
1558 					ep_type != INT_IN_EP)
1559 				continue;
1560 
1561 			/* Added or changed endpoint */
1562 			bw_info->ep_interval = CTX_TO_EP_INTERVAL(
1563 					le32_to_cpu(ep_ctx->ep_info));
1564 			/* Number of packets and mult are zero-based in the
1565 			 * input context, but we want one-based for the
1566 			 * interval table.
1567 			 */
1568 			bw_info->mult = CTX_TO_EP_MULT(
1569 					le32_to_cpu(ep_ctx->ep_info)) + 1;
1570 			bw_info->num_packets = CTX_TO_MAX_BURST(
1571 					le32_to_cpu(ep_ctx->ep_info2)) + 1;
1572 			bw_info->max_packet_size = MAX_PACKET_DECODED(
1573 					le32_to_cpu(ep_ctx->ep_info2));
1574 			bw_info->type = ep_type;
1575 			bw_info->max_esit_payload = CTX_TO_MAX_ESIT_PAYLOAD(
1576 					le32_to_cpu(ep_ctx->tx_info));
1577 		}
1578 	}
1579 }
1580 
1581 /* Copy output xhci_ep_ctx to the input xhci_ep_ctx copy.
1582  * Useful when you want to change one particular aspect of the endpoint and then
1583  * issue a configure endpoint command.
1584  */
xhci_endpoint_copy(struct xhci_hcd * xhci,struct xhci_container_ctx * in_ctx,struct xhci_container_ctx * out_ctx,unsigned int ep_index)1585 void xhci_endpoint_copy(struct xhci_hcd *xhci,
1586 		struct xhci_container_ctx *in_ctx,
1587 		struct xhci_container_ctx *out_ctx,
1588 		unsigned int ep_index)
1589 {
1590 	struct xhci_ep_ctx *out_ep_ctx;
1591 	struct xhci_ep_ctx *in_ep_ctx;
1592 
1593 	out_ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1594 	in_ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
1595 
1596 	in_ep_ctx->ep_info = out_ep_ctx->ep_info;
1597 	in_ep_ctx->ep_info2 = out_ep_ctx->ep_info2;
1598 	in_ep_ctx->deq = out_ep_ctx->deq;
1599 	in_ep_ctx->tx_info = out_ep_ctx->tx_info;
1600 	if (xhci->quirks & XHCI_MTK_HOST) {
1601 		in_ep_ctx->reserved[0] = out_ep_ctx->reserved[0];
1602 		in_ep_ctx->reserved[1] = out_ep_ctx->reserved[1];
1603 	}
1604 }
1605 
1606 /* Copy output xhci_slot_ctx to the input xhci_slot_ctx.
1607  * Useful when you want to change one particular aspect of the endpoint and then
1608  * issue a configure endpoint command.  Only the context entries field matters,
1609  * but we'll copy the whole thing anyway.
1610  */
xhci_slot_copy(struct xhci_hcd * xhci,struct xhci_container_ctx * in_ctx,struct xhci_container_ctx * out_ctx)1611 void xhci_slot_copy(struct xhci_hcd *xhci,
1612 		struct xhci_container_ctx *in_ctx,
1613 		struct xhci_container_ctx *out_ctx)
1614 {
1615 	struct xhci_slot_ctx *in_slot_ctx;
1616 	struct xhci_slot_ctx *out_slot_ctx;
1617 
1618 	in_slot_ctx = xhci_get_slot_ctx(xhci, in_ctx);
1619 	out_slot_ctx = xhci_get_slot_ctx(xhci, out_ctx);
1620 
1621 	in_slot_ctx->dev_info = out_slot_ctx->dev_info;
1622 	in_slot_ctx->dev_info2 = out_slot_ctx->dev_info2;
1623 	in_slot_ctx->tt_info = out_slot_ctx->tt_info;
1624 	in_slot_ctx->dev_state = out_slot_ctx->dev_state;
1625 }
1626 
1627 /* Set up the scratchpad buffer array and scratchpad buffers, if needed. */
scratchpad_alloc(struct xhci_hcd * xhci,gfp_t flags)1628 static int scratchpad_alloc(struct xhci_hcd *xhci, gfp_t flags)
1629 {
1630 	int i;
1631 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
1632 	int num_sp = HCS_MAX_SCRATCHPAD(xhci->hcs_params2);
1633 
1634 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
1635 			"Allocating %d scratchpad buffers", num_sp);
1636 
1637 	if (!num_sp)
1638 		return 0;
1639 
1640 	xhci->scratchpad = kzalloc_node(sizeof(*xhci->scratchpad), flags,
1641 				dev_to_node(dev));
1642 	if (!xhci->scratchpad)
1643 		goto fail_sp;
1644 
1645 	xhci->scratchpad->sp_array = dma_alloc_coherent(dev,
1646 				     size_mul(sizeof(u64), num_sp),
1647 				     &xhci->scratchpad->sp_dma, flags);
1648 	if (!xhci->scratchpad->sp_array)
1649 		goto fail_sp2;
1650 
1651 	xhci->scratchpad->sp_buffers = kcalloc_node(num_sp, sizeof(void *),
1652 					flags, dev_to_node(dev));
1653 	if (!xhci->scratchpad->sp_buffers)
1654 		goto fail_sp3;
1655 
1656 	xhci->dcbaa->dev_context_ptrs[0] = cpu_to_le64(xhci->scratchpad->sp_dma);
1657 	for (i = 0; i < num_sp; i++) {
1658 		dma_addr_t dma;
1659 		void *buf = dma_alloc_coherent(dev, xhci->page_size, &dma,
1660 					       flags);
1661 		if (!buf)
1662 			goto fail_sp4;
1663 
1664 		xhci->scratchpad->sp_array[i] = dma;
1665 		xhci->scratchpad->sp_buffers[i] = buf;
1666 	}
1667 
1668 	return 0;
1669 
1670  fail_sp4:
1671 	while (i--)
1672 		dma_free_coherent(dev, xhci->page_size,
1673 				    xhci->scratchpad->sp_buffers[i],
1674 				    xhci->scratchpad->sp_array[i]);
1675 
1676 	kfree(xhci->scratchpad->sp_buffers);
1677 
1678  fail_sp3:
1679 	dma_free_coherent(dev, num_sp * sizeof(u64),
1680 			    xhci->scratchpad->sp_array,
1681 			    xhci->scratchpad->sp_dma);
1682 
1683  fail_sp2:
1684 	kfree(xhci->scratchpad);
1685 	xhci->scratchpad = NULL;
1686 
1687  fail_sp:
1688 	return -ENOMEM;
1689 }
1690 
scratchpad_free(struct xhci_hcd * xhci)1691 static void scratchpad_free(struct xhci_hcd *xhci)
1692 {
1693 	int num_sp;
1694 	int i;
1695 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
1696 
1697 	if (!xhci->scratchpad)
1698 		return;
1699 
1700 	num_sp = HCS_MAX_SCRATCHPAD(xhci->hcs_params2);
1701 
1702 	for (i = 0; i < num_sp; i++) {
1703 		dma_free_coherent(dev, xhci->page_size,
1704 				    xhci->scratchpad->sp_buffers[i],
1705 				    xhci->scratchpad->sp_array[i]);
1706 	}
1707 	kfree(xhci->scratchpad->sp_buffers);
1708 	dma_free_coherent(dev, num_sp * sizeof(u64),
1709 			    xhci->scratchpad->sp_array,
1710 			    xhci->scratchpad->sp_dma);
1711 	kfree(xhci->scratchpad);
1712 	xhci->scratchpad = NULL;
1713 }
1714 
xhci_alloc_command(struct xhci_hcd * xhci,bool allocate_completion,gfp_t mem_flags)1715 struct xhci_command *xhci_alloc_command(struct xhci_hcd *xhci,
1716 		bool allocate_completion, gfp_t mem_flags)
1717 {
1718 	struct xhci_command *command;
1719 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
1720 
1721 	command = kzalloc_node(sizeof(*command), mem_flags, dev_to_node(dev));
1722 	if (!command)
1723 		return NULL;
1724 
1725 	if (allocate_completion) {
1726 		command->completion =
1727 			kzalloc_node(sizeof(struct completion), mem_flags,
1728 				dev_to_node(dev));
1729 		if (!command->completion) {
1730 			kfree(command);
1731 			return NULL;
1732 		}
1733 		init_completion(command->completion);
1734 	}
1735 
1736 	command->status = 0;
1737 	/* set default timeout to 5000 ms */
1738 	command->timeout_ms = XHCI_CMD_DEFAULT_TIMEOUT;
1739 	INIT_LIST_HEAD(&command->cmd_list);
1740 	return command;
1741 }
1742 
xhci_alloc_command_with_ctx(struct xhci_hcd * xhci,bool allocate_completion,gfp_t mem_flags)1743 struct xhci_command *xhci_alloc_command_with_ctx(struct xhci_hcd *xhci,
1744 		bool allocate_completion, gfp_t mem_flags)
1745 {
1746 	struct xhci_command *command;
1747 
1748 	command = xhci_alloc_command(xhci, allocate_completion, mem_flags);
1749 	if (!command)
1750 		return NULL;
1751 
1752 	command->in_ctx = xhci_alloc_container_ctx(xhci, XHCI_CTX_TYPE_INPUT,
1753 						   mem_flags);
1754 	if (!command->in_ctx) {
1755 		kfree(command->completion);
1756 		kfree(command);
1757 		return NULL;
1758 	}
1759 	return command;
1760 }
1761 
xhci_urb_free_priv(struct urb_priv * urb_priv)1762 void xhci_urb_free_priv(struct urb_priv *urb_priv)
1763 {
1764 	kfree(urb_priv);
1765 }
1766 
xhci_free_command(struct xhci_hcd * xhci,struct xhci_command * command)1767 void xhci_free_command(struct xhci_hcd *xhci,
1768 		struct xhci_command *command)
1769 {
1770 	xhci_free_container_ctx(xhci,
1771 			command->in_ctx);
1772 	kfree(command->completion);
1773 	kfree(command);
1774 }
1775 
xhci_alloc_erst(struct xhci_hcd * xhci,struct xhci_ring * evt_ring,struct xhci_erst * erst,gfp_t flags)1776 int xhci_alloc_erst(struct xhci_hcd *xhci,
1777 		    struct xhci_ring *evt_ring,
1778 		    struct xhci_erst *erst,
1779 		    gfp_t flags)
1780 {
1781 	size_t size;
1782 	unsigned int val;
1783 	struct xhci_segment *seg;
1784 	struct xhci_erst_entry *entry;
1785 
1786 	size = size_mul(sizeof(struct xhci_erst_entry), evt_ring->num_segs);
1787 	erst->entries = dma_alloc_coherent(xhci_to_hcd(xhci)->self.sysdev,
1788 					   size, &erst->erst_dma_addr, flags);
1789 	if (!erst->entries)
1790 		return -ENOMEM;
1791 
1792 	erst->num_entries = evt_ring->num_segs;
1793 
1794 	seg = evt_ring->first_seg;
1795 	for (val = 0; val < evt_ring->num_segs; val++) {
1796 		entry = &erst->entries[val];
1797 		entry->seg_addr = cpu_to_le64(seg->dma);
1798 		entry->seg_size = cpu_to_le32(TRBS_PER_SEGMENT);
1799 		entry->rsvd = 0;
1800 		seg = seg->next;
1801 	}
1802 
1803 	return 0;
1804 }
1805 
1806 static void
xhci_remove_interrupter(struct xhci_hcd * xhci,struct xhci_interrupter * ir)1807 xhci_remove_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
1808 {
1809 	u32 tmp;
1810 
1811 	if (!ir)
1812 		return;
1813 
1814 	/*
1815 	 * Clean out interrupter registers except ERSTBA. Clearing either the
1816 	 * low or high 32 bits of ERSTBA immediately causes the controller to
1817 	 * dereference the partially cleared 64 bit address, causing IOMMU error.
1818 	 */
1819 	if (ir->ir_set) {
1820 		tmp = readl(&ir->ir_set->erst_size);
1821 		tmp &= ERST_SIZE_MASK;
1822 		writel(tmp, &ir->ir_set->erst_size);
1823 
1824 		xhci_write_64(xhci, ERST_EHB, &ir->ir_set->erst_dequeue);
1825 	}
1826 }
1827 
1828 static void
xhci_free_interrupter(struct xhci_hcd * xhci,struct xhci_interrupter * ir)1829 xhci_free_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
1830 {
1831 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
1832 	size_t erst_size;
1833 
1834 	if (!ir)
1835 		return;
1836 
1837 	erst_size = sizeof(struct xhci_erst_entry) * ir->erst.num_entries;
1838 	if (ir->erst.entries)
1839 		dma_free_coherent(dev, erst_size,
1840 				  ir->erst.entries,
1841 				  ir->erst.erst_dma_addr);
1842 	ir->erst.entries = NULL;
1843 
1844 	/* free interrupter event ring */
1845 	if (ir->event_ring)
1846 		xhci_ring_free(xhci, ir->event_ring);
1847 
1848 	ir->event_ring = NULL;
1849 
1850 	kfree(ir);
1851 }
1852 
xhci_remove_secondary_interrupter(struct usb_hcd * hcd,struct xhci_interrupter * ir)1853 void xhci_remove_secondary_interrupter(struct usb_hcd *hcd, struct xhci_interrupter *ir)
1854 {
1855 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1856 	unsigned int intr_num;
1857 
1858 	spin_lock_irq(&xhci->lock);
1859 
1860 	/* interrupter 0 is primary interrupter, don't touch it */
1861 	if (!ir || !ir->intr_num || ir->intr_num >= xhci->max_interrupters) {
1862 		xhci_dbg(xhci, "Invalid secondary interrupter, can't remove\n");
1863 		spin_unlock_irq(&xhci->lock);
1864 		return;
1865 	}
1866 
1867 	intr_num = ir->intr_num;
1868 
1869 	xhci_remove_interrupter(xhci, ir);
1870 	xhci->interrupters[intr_num] = NULL;
1871 
1872 	spin_unlock_irq(&xhci->lock);
1873 
1874 	xhci_free_interrupter(xhci, ir);
1875 }
1876 EXPORT_SYMBOL_GPL(xhci_remove_secondary_interrupter);
1877 
xhci_mem_cleanup(struct xhci_hcd * xhci)1878 void xhci_mem_cleanup(struct xhci_hcd *xhci)
1879 {
1880 	struct device	*dev = xhci_to_hcd(xhci)->self.sysdev;
1881 	int i, j, num_ports;
1882 
1883 	cancel_delayed_work_sync(&xhci->cmd_timer);
1884 
1885 	for (i = 0; xhci->interrupters && i < xhci->max_interrupters; i++) {
1886 		if (xhci->interrupters[i]) {
1887 			xhci_remove_interrupter(xhci, xhci->interrupters[i]);
1888 			xhci_free_interrupter(xhci, xhci->interrupters[i]);
1889 			xhci->interrupters[i] = NULL;
1890 		}
1891 	}
1892 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed interrupters");
1893 
1894 	if (xhci->cmd_ring)
1895 		xhci_ring_free(xhci, xhci->cmd_ring);
1896 	xhci->cmd_ring = NULL;
1897 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed command ring");
1898 	xhci_cleanup_command_queue(xhci);
1899 
1900 	num_ports = HCS_MAX_PORTS(xhci->hcs_params1);
1901 	for (i = 0; i < num_ports && xhci->rh_bw; i++) {
1902 		struct xhci_interval_bw_table *bwt = &xhci->rh_bw[i].bw_table;
1903 		for (j = 0; j < XHCI_MAX_INTERVAL; j++) {
1904 			struct list_head *ep = &bwt->interval_bw[j].endpoints;
1905 			while (!list_empty(ep))
1906 				list_del_init(ep->next);
1907 		}
1908 	}
1909 
1910 	for (i = HCS_MAX_SLOTS(xhci->hcs_params1); i > 0; i--)
1911 		xhci_free_virt_devices_depth_first(xhci, i);
1912 
1913 	dma_pool_destroy(xhci->segment_pool);
1914 	xhci->segment_pool = NULL;
1915 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed segment pool");
1916 
1917 	dma_pool_destroy(xhci->device_pool);
1918 	xhci->device_pool = NULL;
1919 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed device context pool");
1920 
1921 	dma_pool_destroy(xhci->small_streams_pool);
1922 	xhci->small_streams_pool = NULL;
1923 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
1924 			"Freed small stream array pool");
1925 
1926 	dma_pool_destroy(xhci->medium_streams_pool);
1927 	xhci->medium_streams_pool = NULL;
1928 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
1929 			"Freed medium stream array pool");
1930 
1931 	if (xhci->dcbaa)
1932 		dma_free_coherent(dev, sizeof(*xhci->dcbaa),
1933 				xhci->dcbaa, xhci->dcbaa->dma);
1934 	xhci->dcbaa = NULL;
1935 
1936 	scratchpad_free(xhci);
1937 
1938 	if (!xhci->rh_bw)
1939 		goto no_bw;
1940 
1941 	for (i = 0; i < num_ports; i++) {
1942 		struct xhci_tt_bw_info *tt, *n;
1943 		list_for_each_entry_safe(tt, n, &xhci->rh_bw[i].tts, tt_list) {
1944 			list_del(&tt->tt_list);
1945 			kfree(tt);
1946 		}
1947 	}
1948 
1949 no_bw:
1950 	xhci->cmd_ring_reserved_trbs = 0;
1951 	xhci->usb2_rhub.num_ports = 0;
1952 	xhci->usb3_rhub.num_ports = 0;
1953 	xhci->num_active_eps = 0;
1954 	kfree(xhci->usb2_rhub.ports);
1955 	kfree(xhci->usb3_rhub.ports);
1956 	kfree(xhci->hw_ports);
1957 	kfree(xhci->rh_bw);
1958 	kfree(xhci->ext_caps);
1959 	for (i = 0; i < xhci->num_port_caps; i++)
1960 		kfree(xhci->port_caps[i].psi);
1961 	kfree(xhci->port_caps);
1962 	kfree(xhci->interrupters);
1963 	xhci->num_port_caps = 0;
1964 
1965 	xhci->usb2_rhub.ports = NULL;
1966 	xhci->usb3_rhub.ports = NULL;
1967 	xhci->hw_ports = NULL;
1968 	xhci->rh_bw = NULL;
1969 	xhci->ext_caps = NULL;
1970 	xhci->port_caps = NULL;
1971 	xhci->interrupters = NULL;
1972 
1973 	xhci->page_size = 0;
1974 	xhci->page_shift = 0;
1975 	xhci->usb2_rhub.bus_state.bus_suspended = 0;
1976 	xhci->usb3_rhub.bus_state.bus_suspended = 0;
1977 }
1978 
xhci_set_hc_event_deq(struct xhci_hcd * xhci,struct xhci_interrupter * ir)1979 static void xhci_set_hc_event_deq(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
1980 {
1981 	dma_addr_t deq;
1982 
1983 	deq = xhci_trb_virt_to_dma(ir->event_ring->deq_seg,
1984 			ir->event_ring->dequeue);
1985 	if (!deq)
1986 		xhci_warn(xhci, "WARN something wrong with SW event ring dequeue ptr.\n");
1987 	/* Update HC event ring dequeue pointer */
1988 	/* Don't clear the EHB bit (which is RW1C) because
1989 	 * there might be more events to service.
1990 	 */
1991 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
1992 		       "// Write event ring dequeue pointer, preserving EHB bit");
1993 	xhci_write_64(xhci, ((u64) deq & (u64) ~ERST_PTR_MASK),
1994 			&ir->ir_set->erst_dequeue);
1995 }
1996 
xhci_add_in_port(struct xhci_hcd * xhci,unsigned int num_ports,__le32 __iomem * addr,int max_caps)1997 static void xhci_add_in_port(struct xhci_hcd *xhci, unsigned int num_ports,
1998 		__le32 __iomem *addr, int max_caps)
1999 {
2000 	u32 temp, port_offset, port_count;
2001 	int i;
2002 	u8 major_revision, minor_revision, tmp_minor_revision;
2003 	struct xhci_hub *rhub;
2004 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
2005 	struct xhci_port_cap *port_cap;
2006 
2007 	temp = readl(addr);
2008 	major_revision = XHCI_EXT_PORT_MAJOR(temp);
2009 	minor_revision = XHCI_EXT_PORT_MINOR(temp);
2010 
2011 	if (major_revision == 0x03) {
2012 		rhub = &xhci->usb3_rhub;
2013 		/*
2014 		 * Some hosts incorrectly use sub-minor version for minor
2015 		 * version (i.e. 0x02 instead of 0x20 for bcdUSB 0x320 and 0x01
2016 		 * for bcdUSB 0x310). Since there is no USB release with sub
2017 		 * minor version 0x301 to 0x309, we can assume that they are
2018 		 * incorrect and fix it here.
2019 		 */
2020 		if (minor_revision > 0x00 && minor_revision < 0x10)
2021 			minor_revision <<= 4;
2022 		/*
2023 		 * Some zhaoxin's xHCI controller that follow usb3.1 spec
2024 		 * but only support Gen1.
2025 		 */
2026 		if (xhci->quirks & XHCI_ZHAOXIN_HOST) {
2027 			tmp_minor_revision = minor_revision;
2028 			minor_revision = 0;
2029 		}
2030 
2031 	} else if (major_revision <= 0x02) {
2032 		rhub = &xhci->usb2_rhub;
2033 	} else {
2034 		xhci_warn(xhci, "Ignoring unknown port speed, Ext Cap %p, revision = 0x%x\n",
2035 				addr, major_revision);
2036 		/* Ignoring port protocol we can't understand. FIXME */
2037 		return;
2038 	}
2039 
2040 	/* Port offset and count in the third dword, see section 7.2 */
2041 	temp = readl(addr + 2);
2042 	port_offset = XHCI_EXT_PORT_OFF(temp);
2043 	port_count = XHCI_EXT_PORT_COUNT(temp);
2044 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2045 		       "Ext Cap %p, port offset = %u, count = %u, revision = 0x%x",
2046 		       addr, port_offset, port_count, major_revision);
2047 	/* Port count includes the current port offset */
2048 	if (port_offset == 0 || (port_offset + port_count - 1) > num_ports)
2049 		/* WTF? "Valid values are ‘1’ to MaxPorts" */
2050 		return;
2051 
2052 	port_cap = &xhci->port_caps[xhci->num_port_caps++];
2053 	if (xhci->num_port_caps > max_caps)
2054 		return;
2055 
2056 	port_cap->psi_count = XHCI_EXT_PORT_PSIC(temp);
2057 
2058 	if (port_cap->psi_count) {
2059 		port_cap->psi = kcalloc_node(port_cap->psi_count,
2060 					     sizeof(*port_cap->psi),
2061 					     GFP_KERNEL, dev_to_node(dev));
2062 		if (!port_cap->psi)
2063 			port_cap->psi_count = 0;
2064 
2065 		port_cap->psi_uid_count++;
2066 		for (i = 0; i < port_cap->psi_count; i++) {
2067 			port_cap->psi[i] = readl(addr + 4 + i);
2068 
2069 			/* count unique ID values, two consecutive entries can
2070 			 * have the same ID if link is assymetric
2071 			 */
2072 			if (i && (XHCI_EXT_PORT_PSIV(port_cap->psi[i]) !=
2073 				  XHCI_EXT_PORT_PSIV(port_cap->psi[i - 1])))
2074 				port_cap->psi_uid_count++;
2075 
2076 			if (xhci->quirks & XHCI_ZHAOXIN_HOST &&
2077 			    major_revision == 0x03 &&
2078 			    XHCI_EXT_PORT_PSIV(port_cap->psi[i]) >= 5)
2079 				minor_revision = tmp_minor_revision;
2080 
2081 			xhci_dbg(xhci, "PSIV:%d PSIE:%d PLT:%d PFD:%d LP:%d PSIM:%d\n",
2082 				  XHCI_EXT_PORT_PSIV(port_cap->psi[i]),
2083 				  XHCI_EXT_PORT_PSIE(port_cap->psi[i]),
2084 				  XHCI_EXT_PORT_PLT(port_cap->psi[i]),
2085 				  XHCI_EXT_PORT_PFD(port_cap->psi[i]),
2086 				  XHCI_EXT_PORT_LP(port_cap->psi[i]),
2087 				  XHCI_EXT_PORT_PSIM(port_cap->psi[i]));
2088 		}
2089 	}
2090 
2091 	rhub->maj_rev = major_revision;
2092 
2093 	if (rhub->min_rev < minor_revision)
2094 		rhub->min_rev = minor_revision;
2095 
2096 	port_cap->maj_rev = major_revision;
2097 	port_cap->min_rev = minor_revision;
2098 
2099 	/* cache usb2 port capabilities */
2100 	if (major_revision < 0x03 && xhci->num_ext_caps < max_caps)
2101 		xhci->ext_caps[xhci->num_ext_caps++] = temp;
2102 
2103 	if ((xhci->hci_version >= 0x100) && (major_revision != 0x03) &&
2104 		 (temp & XHCI_HLC)) {
2105 		xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2106 			       "xHCI 1.0: support USB2 hardware lpm");
2107 		xhci->hw_lpm_support = 1;
2108 	}
2109 
2110 	port_offset--;
2111 	for (i = port_offset; i < (port_offset + port_count); i++) {
2112 		struct xhci_port *hw_port = &xhci->hw_ports[i];
2113 		/* Duplicate entry.  Ignore the port if the revisions differ. */
2114 		if (hw_port->rhub) {
2115 			xhci_warn(xhci, "Duplicate port entry, Ext Cap %p, port %u\n", addr, i);
2116 			xhci_warn(xhci, "Port was marked as USB %u, duplicated as USB %u\n",
2117 					hw_port->rhub->maj_rev, major_revision);
2118 			/* Only adjust the roothub port counts if we haven't
2119 			 * found a similar duplicate.
2120 			 */
2121 			if (hw_port->rhub != rhub &&
2122 				 hw_port->hcd_portnum != DUPLICATE_ENTRY) {
2123 				hw_port->rhub->num_ports--;
2124 				hw_port->hcd_portnum = DUPLICATE_ENTRY;
2125 			}
2126 			continue;
2127 		}
2128 		hw_port->rhub = rhub;
2129 		hw_port->port_cap = port_cap;
2130 		rhub->num_ports++;
2131 	}
2132 	/* FIXME: Should we disable ports not in the Extended Capabilities? */
2133 }
2134 
xhci_create_rhub_port_array(struct xhci_hcd * xhci,struct xhci_hub * rhub,gfp_t flags)2135 static void xhci_create_rhub_port_array(struct xhci_hcd *xhci,
2136 					struct xhci_hub *rhub, gfp_t flags)
2137 {
2138 	int port_index = 0;
2139 	int i;
2140 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
2141 
2142 	if (!rhub->num_ports)
2143 		return;
2144 	rhub->ports = kcalloc_node(rhub->num_ports, sizeof(*rhub->ports),
2145 			flags, dev_to_node(dev));
2146 	if (!rhub->ports)
2147 		return;
2148 
2149 	for (i = 0; i < HCS_MAX_PORTS(xhci->hcs_params1); i++) {
2150 		if (xhci->hw_ports[i].rhub != rhub ||
2151 		    xhci->hw_ports[i].hcd_portnum == DUPLICATE_ENTRY)
2152 			continue;
2153 		xhci->hw_ports[i].hcd_portnum = port_index;
2154 		rhub->ports[port_index] = &xhci->hw_ports[i];
2155 		port_index++;
2156 		if (port_index == rhub->num_ports)
2157 			break;
2158 	}
2159 }
2160 
2161 /*
2162  * Scan the Extended Capabilities for the "Supported Protocol Capabilities" that
2163  * specify what speeds each port is supposed to be.  We can't count on the port
2164  * speed bits in the PORTSC register being correct until a device is connected,
2165  * but we need to set up the two fake roothubs with the correct number of USB
2166  * 3.0 and USB 2.0 ports at host controller initialization time.
2167  */
xhci_setup_port_arrays(struct xhci_hcd * xhci,gfp_t flags)2168 static int xhci_setup_port_arrays(struct xhci_hcd *xhci, gfp_t flags)
2169 {
2170 	void __iomem *base;
2171 	u32 offset;
2172 	unsigned int num_ports;
2173 	int i, j;
2174 	int cap_count = 0;
2175 	u32 cap_start;
2176 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
2177 
2178 	num_ports = HCS_MAX_PORTS(xhci->hcs_params1);
2179 	xhci->hw_ports = kcalloc_node(num_ports, sizeof(*xhci->hw_ports),
2180 				flags, dev_to_node(dev));
2181 	if (!xhci->hw_ports)
2182 		return -ENOMEM;
2183 
2184 	for (i = 0; i < num_ports; i++) {
2185 		xhci->hw_ports[i].addr = &xhci->op_regs->port_status_base +
2186 			NUM_PORT_REGS * i;
2187 		xhci->hw_ports[i].hw_portnum = i;
2188 
2189 		init_completion(&xhci->hw_ports[i].rexit_done);
2190 		init_completion(&xhci->hw_ports[i].u3exit_done);
2191 	}
2192 
2193 	xhci->rh_bw = kcalloc_node(num_ports, sizeof(*xhci->rh_bw), flags,
2194 				   dev_to_node(dev));
2195 	if (!xhci->rh_bw)
2196 		return -ENOMEM;
2197 	for (i = 0; i < num_ports; i++) {
2198 		struct xhci_interval_bw_table *bw_table;
2199 
2200 		INIT_LIST_HEAD(&xhci->rh_bw[i].tts);
2201 		bw_table = &xhci->rh_bw[i].bw_table;
2202 		for (j = 0; j < XHCI_MAX_INTERVAL; j++)
2203 			INIT_LIST_HEAD(&bw_table->interval_bw[j].endpoints);
2204 	}
2205 	base = &xhci->cap_regs->hc_capbase;
2206 
2207 	cap_start = xhci_find_next_ext_cap(base, 0, XHCI_EXT_CAPS_PROTOCOL);
2208 	if (!cap_start) {
2209 		xhci_err(xhci, "No Extended Capability registers, unable to set up roothub\n");
2210 		return -ENODEV;
2211 	}
2212 
2213 	offset = cap_start;
2214 	/* count extended protocol capability entries for later caching */
2215 	while (offset) {
2216 		cap_count++;
2217 		offset = xhci_find_next_ext_cap(base, offset,
2218 						      XHCI_EXT_CAPS_PROTOCOL);
2219 	}
2220 
2221 	xhci->ext_caps = kcalloc_node(cap_count, sizeof(*xhci->ext_caps),
2222 				flags, dev_to_node(dev));
2223 	if (!xhci->ext_caps)
2224 		return -ENOMEM;
2225 
2226 	xhci->port_caps = kcalloc_node(cap_count, sizeof(*xhci->port_caps),
2227 				flags, dev_to_node(dev));
2228 	if (!xhci->port_caps)
2229 		return -ENOMEM;
2230 
2231 	offset = cap_start;
2232 
2233 	while (offset) {
2234 		xhci_add_in_port(xhci, num_ports, base + offset, cap_count);
2235 		if (xhci->usb2_rhub.num_ports + xhci->usb3_rhub.num_ports ==
2236 		    num_ports)
2237 			break;
2238 		offset = xhci_find_next_ext_cap(base, offset,
2239 						XHCI_EXT_CAPS_PROTOCOL);
2240 	}
2241 	if (xhci->usb2_rhub.num_ports == 0 && xhci->usb3_rhub.num_ports == 0) {
2242 		xhci_warn(xhci, "No ports on the roothubs?\n");
2243 		return -ENODEV;
2244 	}
2245 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2246 		       "Found %u USB 2.0 ports and %u USB 3.0 ports.",
2247 		       xhci->usb2_rhub.num_ports, xhci->usb3_rhub.num_ports);
2248 
2249 	/* Place limits on the number of roothub ports so that the hub
2250 	 * descriptors aren't longer than the USB core will allocate.
2251 	 */
2252 	if (xhci->usb3_rhub.num_ports > USB_SS_MAXPORTS) {
2253 		xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2254 				"Limiting USB 3.0 roothub ports to %u.",
2255 				USB_SS_MAXPORTS);
2256 		xhci->usb3_rhub.num_ports = USB_SS_MAXPORTS;
2257 	}
2258 	if (xhci->usb2_rhub.num_ports > USB_MAXCHILDREN) {
2259 		xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2260 				"Limiting USB 2.0 roothub ports to %u.",
2261 				USB_MAXCHILDREN);
2262 		xhci->usb2_rhub.num_ports = USB_MAXCHILDREN;
2263 	}
2264 
2265 	if (!xhci->usb2_rhub.num_ports)
2266 		xhci_info(xhci, "USB2 root hub has no ports\n");
2267 
2268 	if (!xhci->usb3_rhub.num_ports)
2269 		xhci_info(xhci, "USB3 root hub has no ports\n");
2270 
2271 	xhci_create_rhub_port_array(xhci, &xhci->usb2_rhub, flags);
2272 	xhci_create_rhub_port_array(xhci, &xhci->usb3_rhub, flags);
2273 
2274 	return 0;
2275 }
2276 
2277 static struct xhci_interrupter *
xhci_alloc_interrupter(struct xhci_hcd * xhci,unsigned int segs,gfp_t flags)2278 xhci_alloc_interrupter(struct xhci_hcd *xhci, unsigned int segs, gfp_t flags)
2279 {
2280 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
2281 	struct xhci_interrupter *ir;
2282 	unsigned int max_segs;
2283 	int ret;
2284 
2285 	if (!segs)
2286 		segs = ERST_DEFAULT_SEGS;
2287 
2288 	max_segs = BIT(HCS_ERST_MAX(xhci->hcs_params2));
2289 	segs = min(segs, max_segs);
2290 
2291 	ir = kzalloc_node(sizeof(*ir), flags, dev_to_node(dev));
2292 	if (!ir)
2293 		return NULL;
2294 
2295 	ir->event_ring = xhci_ring_alloc(xhci, segs, 1, TYPE_EVENT, 0, flags);
2296 	if (!ir->event_ring) {
2297 		xhci_warn(xhci, "Failed to allocate interrupter event ring\n");
2298 		kfree(ir);
2299 		return NULL;
2300 	}
2301 
2302 	ret = xhci_alloc_erst(xhci, ir->event_ring, &ir->erst, flags);
2303 	if (ret) {
2304 		xhci_warn(xhci, "Failed to allocate interrupter erst\n");
2305 		xhci_ring_free(xhci, ir->event_ring);
2306 		kfree(ir);
2307 		return NULL;
2308 	}
2309 
2310 	return ir;
2311 }
2312 
2313 static int
xhci_add_interrupter(struct xhci_hcd * xhci,struct xhci_interrupter * ir,unsigned int intr_num)2314 xhci_add_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir,
2315 		     unsigned int intr_num)
2316 {
2317 	u64 erst_base;
2318 	u32 erst_size;
2319 
2320 	if (intr_num > xhci->max_interrupters) {
2321 		xhci_warn(xhci, "Can't add interrupter %d, max interrupters %d\n",
2322 			  intr_num, xhci->max_interrupters);
2323 		return -EINVAL;
2324 	}
2325 
2326 	if (xhci->interrupters[intr_num]) {
2327 		xhci_warn(xhci, "Interrupter %d\n already set up", intr_num);
2328 		return -EINVAL;
2329 	}
2330 
2331 	xhci->interrupters[intr_num] = ir;
2332 	ir->intr_num = intr_num;
2333 	ir->ir_set = &xhci->run_regs->ir_set[intr_num];
2334 
2335 	/* set ERST count with the number of entries in the segment table */
2336 	erst_size = readl(&ir->ir_set->erst_size);
2337 	erst_size &= ERST_SIZE_MASK;
2338 	erst_size |= ir->event_ring->num_segs;
2339 	writel(erst_size, &ir->ir_set->erst_size);
2340 
2341 	erst_base = xhci_read_64(xhci, &ir->ir_set->erst_base);
2342 	erst_base &= ERST_BASE_RSVDP;
2343 	erst_base |= ir->erst.erst_dma_addr & ~ERST_BASE_RSVDP;
2344 	if (xhci->quirks & XHCI_WRITE_64_HI_LO)
2345 		hi_lo_writeq(erst_base, &ir->ir_set->erst_base);
2346 	else
2347 		xhci_write_64(xhci, erst_base, &ir->ir_set->erst_base);
2348 
2349 	/* Set the event ring dequeue address of this interrupter */
2350 	xhci_set_hc_event_deq(xhci, ir);
2351 
2352 	return 0;
2353 }
2354 
2355 struct xhci_interrupter *
xhci_create_secondary_interrupter(struct usb_hcd * hcd,unsigned int segs,u32 imod_interval)2356 xhci_create_secondary_interrupter(struct usb_hcd *hcd, unsigned int segs,
2357 				  u32 imod_interval)
2358 {
2359 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
2360 	struct xhci_interrupter *ir;
2361 	unsigned int i;
2362 	int err = -ENOSPC;
2363 
2364 	if (!xhci->interrupters || xhci->max_interrupters <= 1)
2365 		return NULL;
2366 
2367 	ir = xhci_alloc_interrupter(xhci, segs, GFP_KERNEL);
2368 	if (!ir)
2369 		return NULL;
2370 
2371 	spin_lock_irq(&xhci->lock);
2372 
2373 	/* Find available secondary interrupter, interrupter 0 is reserved for primary */
2374 	for (i = 1; i < xhci->max_interrupters; i++) {
2375 		if (xhci->interrupters[i] == NULL) {
2376 			err = xhci_add_interrupter(xhci, ir, i);
2377 			break;
2378 		}
2379 	}
2380 
2381 	spin_unlock_irq(&xhci->lock);
2382 
2383 	if (err) {
2384 		xhci_warn(xhci, "Failed to add secondary interrupter, max interrupters %d\n",
2385 			  xhci->max_interrupters);
2386 		xhci_free_interrupter(xhci, ir);
2387 		return NULL;
2388 	}
2389 
2390 	err = xhci_set_interrupter_moderation(ir, imod_interval);
2391 	if (err)
2392 		xhci_warn(xhci, "Failed to set interrupter %d moderation to %uns\n",
2393 			  i, imod_interval);
2394 
2395 	xhci_dbg(xhci, "Add secondary interrupter %d, max interrupters %d\n",
2396 		 i, xhci->max_interrupters);
2397 
2398 	return ir;
2399 }
2400 EXPORT_SYMBOL_GPL(xhci_create_secondary_interrupter);
2401 
xhci_mem_init(struct xhci_hcd * xhci,gfp_t flags)2402 int xhci_mem_init(struct xhci_hcd *xhci, gfp_t flags)
2403 {
2404 	struct xhci_interrupter *ir;
2405 	struct device	*dev = xhci_to_hcd(xhci)->self.sysdev;
2406 	dma_addr_t	dma;
2407 	unsigned int	val, val2;
2408 	u64		val_64;
2409 	u32		page_size, temp;
2410 	int		i;
2411 
2412 	INIT_LIST_HEAD(&xhci->cmd_list);
2413 
2414 	/* init command timeout work */
2415 	INIT_DELAYED_WORK(&xhci->cmd_timer, xhci_handle_command_timeout);
2416 	init_completion(&xhci->cmd_ring_stop_completion);
2417 
2418 	page_size = readl(&xhci->op_regs->page_size);
2419 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2420 			"Supported page size register = 0x%x", page_size);
2421 	val = ffs(page_size) - 1;
2422 	if (val < 16)
2423 		xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2424 			"Supported page size of %iK", (1 << (val + 12)) / 1024);
2425 	else
2426 		xhci_warn(xhci, "WARN: no supported page size\n");
2427 	/* Use 4K pages, since that's common and the minimum the HC supports */
2428 	xhci->page_shift = 12;
2429 	xhci->page_size = 1 << xhci->page_shift;
2430 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2431 			"HCD page size set to %iK", xhci->page_size / 1024);
2432 
2433 	/*
2434 	 * Program the Number of Device Slots Enabled field in the CONFIG
2435 	 * register with the max value of slots the HC can handle.
2436 	 */
2437 	val = HCS_MAX_SLOTS(readl(&xhci->cap_regs->hcs_params1));
2438 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2439 			"// xHC can handle at most %d device slots.", val);
2440 	val2 = readl(&xhci->op_regs->config_reg);
2441 	val |= (val2 & ~HCS_SLOTS_MASK);
2442 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2443 			"// Setting Max device slots reg = 0x%x.", val);
2444 	writel(val, &xhci->op_regs->config_reg);
2445 
2446 	/*
2447 	 * xHCI section 5.4.6 - Device Context array must be
2448 	 * "physically contiguous and 64-byte (cache line) aligned".
2449 	 */
2450 	xhci->dcbaa = dma_alloc_coherent(dev, sizeof(*xhci->dcbaa), &dma,
2451 			flags);
2452 	if (!xhci->dcbaa)
2453 		goto fail;
2454 	xhci->dcbaa->dma = dma;
2455 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2456 			"// Device context base array address = 0x%pad (DMA), %p (virt)",
2457 			&xhci->dcbaa->dma, xhci->dcbaa);
2458 	xhci_write_64(xhci, dma, &xhci->op_regs->dcbaa_ptr);
2459 
2460 	/*
2461 	 * Initialize the ring segment pool.  The ring must be a contiguous
2462 	 * structure comprised of TRBs.  The TRBs must be 16 byte aligned,
2463 	 * however, the command ring segment needs 64-byte aligned segments
2464 	 * and our use of dma addresses in the trb_address_map radix tree needs
2465 	 * TRB_SEGMENT_SIZE alignment, so we pick the greater alignment need.
2466 	 */
2467 	if (xhci->quirks & XHCI_TRB_OVERFETCH)
2468 		/* Buggy HC prefetches beyond segment bounds - allocate dummy space at the end */
2469 		xhci->segment_pool = dma_pool_create("xHCI ring segments", dev,
2470 				TRB_SEGMENT_SIZE * 2, TRB_SEGMENT_SIZE * 2, xhci->page_size * 2);
2471 	else
2472 		xhci->segment_pool = dma_pool_create("xHCI ring segments", dev,
2473 				TRB_SEGMENT_SIZE, TRB_SEGMENT_SIZE, xhci->page_size);
2474 
2475 	/* See Table 46 and Note on Figure 55 */
2476 	xhci->device_pool = dma_pool_create("xHCI input/output contexts", dev,
2477 			2112, 64, xhci->page_size);
2478 	if (!xhci->segment_pool || !xhci->device_pool)
2479 		goto fail;
2480 
2481 	/* Linear stream context arrays don't have any boundary restrictions,
2482 	 * and only need to be 16-byte aligned.
2483 	 */
2484 	xhci->small_streams_pool =
2485 		dma_pool_create("xHCI 256 byte stream ctx arrays",
2486 			dev, SMALL_STREAM_ARRAY_SIZE, 16, 0);
2487 	xhci->medium_streams_pool =
2488 		dma_pool_create("xHCI 1KB stream ctx arrays",
2489 			dev, MEDIUM_STREAM_ARRAY_SIZE, 16, 0);
2490 	/* Any stream context array bigger than MEDIUM_STREAM_ARRAY_SIZE
2491 	 * will be allocated with dma_alloc_coherent()
2492 	 */
2493 
2494 	if (!xhci->small_streams_pool || !xhci->medium_streams_pool)
2495 		goto fail;
2496 
2497 	/* Set up the command ring to have one segments for now. */
2498 	xhci->cmd_ring = xhci_ring_alloc(xhci, 1, 1, TYPE_COMMAND, 0, flags);
2499 	if (!xhci->cmd_ring)
2500 		goto fail;
2501 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2502 			"Allocated command ring at %p", xhci->cmd_ring);
2503 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "First segment DMA is 0x%pad",
2504 			&xhci->cmd_ring->first_seg->dma);
2505 
2506 	/* Set the address in the Command Ring Control register */
2507 	val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
2508 	val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
2509 		(xhci->cmd_ring->first_seg->dma & (u64) ~CMD_RING_RSVD_BITS) |
2510 		xhci->cmd_ring->cycle_state;
2511 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2512 			"// Setting command ring address to 0x%016llx", val_64);
2513 	xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
2514 
2515 	/* Reserve one command ring TRB for disabling LPM.
2516 	 * Since the USB core grabs the shared usb_bus bandwidth mutex before
2517 	 * disabling LPM, we only need to reserve one TRB for all devices.
2518 	 */
2519 	xhci->cmd_ring_reserved_trbs++;
2520 
2521 	val = readl(&xhci->cap_regs->db_off);
2522 	val &= DBOFF_MASK;
2523 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2524 		       "// Doorbell array is located at offset 0x%x from cap regs base addr",
2525 		       val);
2526 	xhci->dba = (void __iomem *) xhci->cap_regs + val;
2527 
2528 	/* Allocate and set up primary interrupter 0 with an event ring. */
2529 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
2530 		       "Allocating primary event ring");
2531 	xhci->interrupters = kcalloc_node(xhci->max_interrupters, sizeof(*xhci->interrupters),
2532 					  flags, dev_to_node(dev));
2533 
2534 	ir = xhci_alloc_interrupter(xhci, 0, flags);
2535 	if (!ir)
2536 		goto fail;
2537 
2538 	if (xhci_add_interrupter(xhci, ir, 0))
2539 		goto fail;
2540 
2541 	xhci->isoc_bei_interval = AVOID_BEI_INTERVAL_MAX;
2542 
2543 	/*
2544 	 * XXX: Might need to set the Interrupter Moderation Register to
2545 	 * something other than the default (~1ms minimum between interrupts).
2546 	 * See section 5.5.1.2.
2547 	 */
2548 	for (i = 0; i < MAX_HC_SLOTS; i++)
2549 		xhci->devs[i] = NULL;
2550 
2551 	if (scratchpad_alloc(xhci, flags))
2552 		goto fail;
2553 	if (xhci_setup_port_arrays(xhci, flags))
2554 		goto fail;
2555 
2556 	/* Enable USB 3.0 device notifications for function remote wake, which
2557 	 * is necessary for allowing USB 3.0 devices to do remote wakeup from
2558 	 * U3 (device suspend).
2559 	 */
2560 	temp = readl(&xhci->op_regs->dev_notification);
2561 	temp &= ~DEV_NOTE_MASK;
2562 	temp |= DEV_NOTE_FWAKE;
2563 	writel(temp, &xhci->op_regs->dev_notification);
2564 
2565 	return 0;
2566 
2567 fail:
2568 	xhci_halt(xhci);
2569 	xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
2570 	xhci_mem_cleanup(xhci);
2571 	return -ENOMEM;
2572 }
2573