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