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