xref: /linux/drivers/pci/setup-bus.c (revision 8cb081667377709f4924ab6b3a88a0d7a761fe91)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Support routines for initializing a PCI subsystem
4  *
5  * Extruded from code written by
6  *      Dave Rusling (david.rusling@reo.mts.dec.com)
7  *      David Mosberger (davidm@cs.arizona.edu)
8  *	David Miller (davem@redhat.com)
9  *
10  * Nov 2000, Ivan Kokshaysky <ink@jurassic.park.msu.ru>
11  *	     PCI-PCI bridges cleanup, sorted resource allocation.
12  * Feb 2002, Ivan Kokshaysky <ink@jurassic.park.msu.ru>
13  *	     Converted to allocation in 3 passes, which gives
14  *	     tighter packing. Prefetchable range support.
15  */
16 
17 #include <linux/align.h>
18 #include <linux/bitops.h>
19 #include <linux/bug.h>
20 #include <linux/init.h>
21 #include <linux/kernel.h>
22 #include <linux/minmax.h>
23 #include <linux/module.h>
24 #include <linux/pci.h>
25 #include <linux/errno.h>
26 #include <linux/ioport.h>
27 #include <linux/cache.h>
28 #include <linux/limits.h>
29 #include <linux/sizes.h>
30 #include <linux/slab.h>
31 #include <linux/acpi.h>
32 #include "pci.h"
33 
34 #define PCI_RES_TYPE_MASK \
35 	(IORESOURCE_IO | IORESOURCE_MEM | IORESOURCE_PREFETCH |\
36 	 IORESOURCE_MEM_64)
37 
38 unsigned int pci_flags;
39 EXPORT_SYMBOL_GPL(pci_flags);
40 
41 struct pci_dev_resource {
42 	struct list_head list;
43 	struct resource *res;
44 	struct pci_dev *dev;
45 	resource_size_t start;
46 	resource_size_t end;
47 	resource_size_t add_size;
48 	resource_size_t min_align;
49 	unsigned long flags;
50 };
51 
52 static void pci_dev_res_free_list(struct list_head *head)
53 {
54 	struct pci_dev_resource *dev_res, *tmp;
55 
56 	list_for_each_entry_safe(dev_res, tmp, head, list) {
57 		list_del(&dev_res->list);
58 		kfree(dev_res);
59 	}
60 }
61 
62 /**
63  * pci_dev_res_add_to_list() - Add a new resource tracker to the list
64  * @head:	Head of the list
65  * @dev:	Device to which the resource belongs
66  * @res:	Resource to be tracked
67  * @add_size:	Additional size to be optionally added to the resource
68  * @min_align:	Minimum memory window alignment
69  */
70 int pci_dev_res_add_to_list(struct list_head *head, struct pci_dev *dev,
71 			    struct resource *res, resource_size_t add_size,
72 			    resource_size_t min_align)
73 {
74 	struct pci_dev_resource *tmp;
75 
76 	tmp = kzalloc_obj(*tmp);
77 	if (!tmp)
78 		return -ENOMEM;
79 
80 	tmp->res = res;
81 	tmp->dev = dev;
82 	tmp->start = res->start;
83 	tmp->end = res->end;
84 	tmp->flags = res->flags;
85 	tmp->add_size = add_size;
86 	tmp->min_align = min_align;
87 
88 	list_add(&tmp->list, head);
89 
90 	return 0;
91 }
92 
93 static void pci_dev_res_remove_from_list(struct list_head *head,
94 					 struct resource *res)
95 {
96 	struct pci_dev_resource *dev_res, *tmp;
97 
98 	list_for_each_entry_safe(dev_res, tmp, head, list) {
99 		if (dev_res->res == res) {
100 			list_del(&dev_res->list);
101 			kfree(dev_res);
102 			break;
103 		}
104 	}
105 }
106 
107 static struct pci_dev_resource *res_to_dev_res(struct list_head *head,
108 					       struct resource *res)
109 {
110 	struct pci_dev_resource *dev_res;
111 
112 	list_for_each_entry(dev_res, head, list) {
113 		if (dev_res->res == res)
114 			return dev_res;
115 	}
116 
117 	return NULL;
118 }
119 
120 static resource_size_t get_res_add_size(struct list_head *head,
121 					struct resource *res)
122 {
123 	struct pci_dev_resource *dev_res;
124 
125 	dev_res = res_to_dev_res(head, res);
126 	return dev_res ? dev_res->add_size : 0;
127 }
128 
129 static void pci_dev_res_restore(struct pci_dev_resource *dev_res)
130 {
131 	struct resource *res = dev_res->res;
132 	struct pci_dev *dev = dev_res->dev;
133 	int idx = pci_resource_num(dev, res);
134 	const char *res_name = pci_resource_name(dev, idx);
135 
136 	if (WARN_ON_ONCE(resource_assigned(res)))
137 		return;
138 
139 	res->start = dev_res->start;
140 	res->end = dev_res->end;
141 	res->flags = dev_res->flags;
142 
143 	pci_dbg(dev, "%s %pR: resource restored\n", res_name, res);
144 }
145 
146 /*
147  * Helper function for sizing routines.  Assigned resources have non-NULL
148  * parent resource.
149  *
150  * Return first unassigned resource of the correct type.  If there is none,
151  * return first assigned resource of the correct type.  If none of the
152  * above, return NULL.
153  *
154  * Returning an assigned resource of the correct type allows the caller to
155  * distinguish between already assigned and no resource of the correct type.
156  */
157 static struct resource *find_bus_resource_of_type(struct pci_bus *bus,
158 						  unsigned long type_mask,
159 						  unsigned long type)
160 {
161 	struct resource *r, *r_assigned = NULL;
162 
163 	pci_bus_for_each_resource(bus, r) {
164 		if (!r || r == &ioport_resource || r == &iomem_resource)
165 			continue;
166 
167 		if ((r->flags & type_mask) != type)
168 			continue;
169 
170 		if (!resource_assigned(r))
171 			return r;
172 		if (!r_assigned)
173 			r_assigned = r;
174 	}
175 	return r_assigned;
176 }
177 
178 /**
179  * pbus_select_window_for_type - Select bridge window for a resource type
180  * @bus: PCI bus
181  * @type: Resource type (resource flags can be passed as is)
182  *
183  * Select the bridge window based on a resource @type.
184  *
185  * For memory resources, the selection is done as follows:
186  *
187  * Any non-prefetchable resource is put into the non-prefetchable window.
188  *
189  * If there is no prefetchable MMIO window, put all memory resources into the
190  * non-prefetchable window.
191  *
192  * If there's a 64-bit prefetchable MMIO window, put all 64-bit prefetchable
193  * resources into it and place 32-bit prefetchable memory into the
194  * non-prefetchable window.
195  *
196  * Otherwise, put all prefetchable resources into the prefetchable window.
197  *
198  * Return: the bridge window resource or NULL if no bridge window is found.
199  */
200 static struct resource *pbus_select_window_for_type(struct pci_bus *bus,
201 						    unsigned long type)
202 {
203 	int iores_type = type & IORESOURCE_TYPE_BITS;	/* w/o 64bit & pref */
204 	struct resource *mmio, *mmio_pref, *win;
205 
206 	type &= PCI_RES_TYPE_MASK;			/* with 64bit & pref */
207 
208 	if ((iores_type != IORESOURCE_IO) && (iores_type != IORESOURCE_MEM))
209 		return NULL;
210 
211 	if (pci_is_root_bus(bus)) {
212 		win = find_bus_resource_of_type(bus, type, type);
213 		if (win)
214 			return win;
215 
216 		type &= ~IORESOURCE_MEM_64;
217 		win = find_bus_resource_of_type(bus, type, type);
218 		if (win)
219 			return win;
220 
221 		type &= ~IORESOURCE_PREFETCH;
222 		return find_bus_resource_of_type(bus, type, type);
223 	}
224 
225 	switch (iores_type) {
226 	case IORESOURCE_IO:
227 		win = pci_bus_resource_n(bus, PCI_BUS_BRIDGE_IO_WINDOW);
228 		if (win && (win->flags & IORESOURCE_IO))
229 			return win;
230 		return NULL;
231 
232 	case IORESOURCE_MEM:
233 		mmio = pci_bus_resource_n(bus, PCI_BUS_BRIDGE_MEM_WINDOW);
234 		mmio_pref = pci_bus_resource_n(bus, PCI_BUS_BRIDGE_PREF_MEM_WINDOW);
235 
236 		if (mmio && !(mmio->flags & IORESOURCE_MEM))
237 			mmio = NULL;
238 		if (mmio_pref && !(mmio_pref->flags & IORESOURCE_MEM))
239 			mmio_pref = NULL;
240 
241 		if (!(type & IORESOURCE_PREFETCH) || !mmio_pref)
242 			return mmio;
243 
244 		if ((type & IORESOURCE_MEM_64) ||
245 		    !(mmio_pref->flags & IORESOURCE_MEM_64))
246 			return mmio_pref;
247 
248 		return mmio;
249 	default:
250 		return NULL;
251 	}
252 }
253 
254 /**
255  * pbus_select_window - Select bridge window for a resource
256  * @bus: PCI bus
257  * @res: Resource
258  *
259  * Select the bridge window for @res. If the resource is already assigned,
260  * return the current bridge window.
261  *
262  * For memory resources, the selection is done as follows:
263  *
264  * Any non-prefetchable resource is put into the non-prefetchable window.
265  *
266  * If there is no prefetchable MMIO window, put all memory resources into the
267  * non-prefetchable window.
268  *
269  * If there's a 64-bit prefetchable MMIO window, put all 64-bit prefetchable
270  * resources into it and place 32-bit prefetchable memory into the
271  * non-prefetchable window.
272  *
273  * Otherwise, put all prefetchable resources into the prefetchable window.
274  *
275  * Return: the bridge window resource or NULL if no bridge window is found.
276  */
277 struct resource *pbus_select_window(struct pci_bus *bus,
278 				    const struct resource *res)
279 {
280 	if (resource_assigned(res))
281 		return res->parent;
282 
283 	return pbus_select_window_for_type(bus, res->flags);
284 }
285 
286 static bool pdev_resources_assignable(struct pci_dev *dev)
287 {
288 	u16 class = dev->class >> 8, command;
289 
290 	/* Don't touch classless devices or host bridges or IOAPICs */
291 	if (class == PCI_CLASS_NOT_DEFINED || class == PCI_CLASS_BRIDGE_HOST)
292 		return false;
293 
294 	/* Don't touch IOAPIC devices already enabled by firmware */
295 	if (class == PCI_CLASS_SYSTEM_PIC) {
296 		pci_read_config_word(dev, PCI_COMMAND, &command);
297 		if (command & (PCI_COMMAND_IO | PCI_COMMAND_MEMORY))
298 			return false;
299 	}
300 
301 	return true;
302 }
303 
304 static bool pdev_resource_assignable(struct pci_dev *dev, struct resource *res)
305 {
306 	int idx = pci_resource_num(dev, res);
307 
308 	if (!res->flags)
309 		return false;
310 
311 	if (pci_resource_is_bridge_win(idx) && res->flags & IORESOURCE_DISABLED)
312 		return false;
313 
314 	return true;
315 }
316 
317 static bool pdev_resource_should_fit(struct pci_dev *dev, struct resource *res)
318 {
319 	if (resource_assigned(res))
320 		return false;
321 
322 	if (res->flags & IORESOURCE_PCI_FIXED)
323 		return false;
324 
325 	return pdev_resource_assignable(dev, res);
326 }
327 
328 /* Sort resources by alignment */
329 static void pdev_sort_resources(struct pci_dev *dev, struct list_head *head)
330 {
331 	struct resource *r;
332 	int i;
333 
334 	if (!pdev_resources_assignable(dev))
335 		return;
336 
337 	pci_dev_for_each_resource(dev, r, i) {
338 		const char *r_name = pci_resource_name(dev, i);
339 		struct pci_dev_resource *dev_res, *tmp;
340 		resource_size_t r_align;
341 		struct list_head *n;
342 
343 		if (!pdev_resource_should_fit(dev, r))
344 			continue;
345 
346 		r_align = pci_resource_alignment(dev, r);
347 		if (!r_align) {
348 			pci_warn(dev, "%s %pR: alignment must not be zero\n",
349 				 r_name, r);
350 			continue;
351 		}
352 
353 		tmp = kzalloc_obj(*tmp);
354 		if (!tmp)
355 			panic("%s: kzalloc() failed!\n", __func__);
356 		tmp->res = r;
357 		tmp->dev = dev;
358 		tmp->start = r->start;
359 		tmp->end = r->end;
360 		tmp->flags = r->flags;
361 
362 		/* Fallback is smallest one or list is empty */
363 		n = head;
364 		list_for_each_entry(dev_res, head, list) {
365 			resource_size_t align;
366 
367 			align = pci_resource_alignment(dev_res->dev,
368 							 dev_res->res);
369 
370 			if (r_align > align) {
371 				n = &dev_res->list;
372 				break;
373 			}
374 		}
375 		/* Insert it just before n */
376 		list_add_tail(&tmp->list, n);
377 	}
378 }
379 
380 bool pci_resource_is_optional(const struct pci_dev *dev, int resno)
381 {
382 	const struct resource *res = pci_resource_n(dev, resno);
383 
384 	if (pci_resource_is_iov(resno))
385 		return true;
386 	if (resno == PCI_ROM_RESOURCE && !(res->flags & IORESOURCE_ROM_ENABLE))
387 		return true;
388 	if (pci_resource_is_bridge_win(resno) && !resource_size(res))
389 		return true;
390 
391 	return false;
392 }
393 
394 static void reset_resource(struct pci_dev *dev, struct resource *res)
395 {
396 	int idx = pci_resource_num(dev, res);
397 	const char *res_name = pci_resource_name(dev, idx);
398 
399 	if (pci_resource_is_bridge_win(idx)) {
400 		res->flags |= IORESOURCE_UNSET;
401 		return;
402 	}
403 
404 	pci_dbg(dev, "%s %pR: resetting resource\n", res_name, res);
405 
406 	res->start = 0;
407 	res->end = 0;
408 	res->flags = 0;
409 }
410 
411 /**
412  * reassign_resources_sorted() - Satisfy any additional resource requests
413  *
414  * @realloc_head:	Head of the list tracking requests requiring
415  *			additional resources
416  * @head:		Head of the list tracking requests with allocated
417  *			resources
418  *
419  * Walk through each element of the realloc_head and try to procure additional
420  * resources for the element, provided the element is in the head list.
421  */
422 static void reassign_resources_sorted(struct list_head *realloc_head,
423 				      struct list_head *head)
424 {
425 	struct pci_dev_resource *add_res, *tmp;
426 	struct pci_dev *dev;
427 	struct resource *res;
428 	const char *res_name;
429 	resource_size_t add_size, align;
430 	int idx;
431 
432 	list_for_each_entry_safe(add_res, tmp, realloc_head, list) {
433 		res = add_res->res;
434 		dev = add_res->dev;
435 		idx = pci_resource_num(dev, res);
436 
437 		/* Skip this resource if not found in head list */
438 		if (!res_to_dev_res(head, res))
439 			continue;
440 
441 		/*
442 		 * Skip resource that failed the earlier assignment and is
443 		 * not optional as it would just fail again.
444 		 */
445 		if (!resource_assigned(res) && resource_size(res) &&
446 		    !pci_resource_is_optional(dev, idx))
447 			goto out;
448 
449 		res_name = pci_resource_name(dev, idx);
450 		add_size = add_res->add_size;
451 		align = add_res->min_align;
452 		if (!resource_assigned(res)) {
453 			resource_set_range(res, align,
454 					   resource_size(res) + add_size);
455 			if (pci_assign_resource(dev, idx)) {
456 				pci_dbg(dev,
457 					"%s %pR: ignoring failure in optional allocation\n",
458 					res_name, res);
459 			}
460 		} else if (add_size > 0 || !IS_ALIGNED(res->start, align)) {
461 			res->flags |= add_res->flags &
462 				 (IORESOURCE_STARTALIGN|IORESOURCE_SIZEALIGN);
463 			if (pci_reassign_resource(dev, idx, add_size, align))
464 				pci_info(dev, "%s %pR: failed to add optional %llx\n",
465 					 res_name, res,
466 					 (unsigned long long) add_size);
467 		}
468 out:
469 		list_del(&add_res->list);
470 		kfree(add_res);
471 	}
472 }
473 
474 /**
475  * assign_requested_resources_sorted() - Satisfy resource requests
476  *
477  * @head:	Head of the list tracking requests for resources
478  * @fail_head:	Head of the list tracking requests that could not be
479  *		allocated
480  * @optional:	Assign also optional resources
481  *
482  * Satisfy resource requests of each element in the list.  Add requests that
483  * could not be satisfied to the failed_list.
484  */
485 static void assign_requested_resources_sorted(struct list_head *head,
486 					      struct list_head *fail_head,
487 					      bool optional)
488 {
489 	struct pci_dev_resource *dev_res;
490 	struct resource *res;
491 	struct pci_dev *dev;
492 	bool optional_res;
493 	int idx;
494 
495 	list_for_each_entry(dev_res, head, list) {
496 		res = dev_res->res;
497 		dev = dev_res->dev;
498 		idx = pci_resource_num(dev, res);
499 		optional_res = pci_resource_is_optional(dev, idx);
500 
501 		if (!resource_size(res))
502 			continue;
503 
504 		if (!optional && optional_res)
505 			continue;
506 
507 		if (pci_assign_resource(dev, idx)) {
508 			if (fail_head) {
509 				pci_dev_res_add_to_list(fail_head, dev, res,
510 							0 /* don't care */,
511 							0 /* don't care */);
512 			}
513 		}
514 	}
515 }
516 
517 static unsigned long pci_fail_res_type_mask(struct list_head *fail_head)
518 {
519 	struct pci_dev_resource *fail_res;
520 	unsigned long mask = 0;
521 
522 	/* Check failed type */
523 	list_for_each_entry(fail_res, fail_head, list)
524 		mask |= fail_res->flags;
525 
526 	/*
527 	 * One pref failed resource will set IORESOURCE_MEM, as we can
528 	 * allocate pref in non-pref range.  Will release all assigned
529 	 * non-pref sibling resources according to that bit.
530 	 */
531 	return mask & (IORESOURCE_IO | IORESOURCE_MEM | IORESOURCE_PREFETCH);
532 }
533 
534 static bool pci_need_to_release(unsigned long mask, struct resource *res)
535 {
536 	if (res->flags & IORESOURCE_IO)
537 		return !!(mask & IORESOURCE_IO);
538 
539 	/* Check pref at first */
540 	if (res->flags & IORESOURCE_PREFETCH) {
541 		if (mask & IORESOURCE_PREFETCH)
542 			return true;
543 		/* Count pref if its parent is non-pref */
544 		else if ((mask & IORESOURCE_MEM) &&
545 			 !(res->parent->flags & IORESOURCE_PREFETCH))
546 			return true;
547 		else
548 			return false;
549 	}
550 
551 	if (res->flags & IORESOURCE_MEM)
552 		return !!(mask & IORESOURCE_MEM);
553 
554 	return false;	/* Should not get here */
555 }
556 
557 /* Return: @true if assignment of a required resource failed. */
558 static bool pci_required_resource_failed(struct list_head *fail_head,
559 					 unsigned long type)
560 {
561 	struct pci_dev_resource *fail_res;
562 
563 	type &= PCI_RES_TYPE_MASK;
564 
565 	list_for_each_entry(fail_res, fail_head, list) {
566 		int idx = pci_resource_num(fail_res->dev, fail_res->res);
567 
568 		if (type && (fail_res->flags & PCI_RES_TYPE_MASK) != type)
569 			continue;
570 
571 		if (!pci_resource_is_optional(fail_res->dev, idx))
572 			return true;
573 	}
574 	return false;
575 }
576 
577 static void __assign_resources_sorted(struct list_head *head,
578 				      struct list_head *realloc_head,
579 				      struct list_head *fail_head)
580 {
581 	/*
582 	 * Should not assign requested resources at first.  They could be
583 	 * adjacent, so later reassign can not reallocate them one by one in
584 	 * parent resource window.
585 	 *
586 	 * Try to assign required and any optional resources at beginning
587 	 * (add_size included). If all required resources were successfully
588 	 * assigned, get out early. If could not do that, we still try to
589 	 * assign required at first, then try to reassign some optional
590 	 * resources.
591 	 *
592 	 * Separate three resource type checking if we need to release
593 	 * assigned resource after requested + add_size try.
594 	 *
595 	 *	1. If IO port assignment fails, will release assigned IO
596 	 *	   port.
597 	 *	2. If pref MMIO assignment fails, release assigned pref
598 	 *	   MMIO.  If assigned pref MMIO's parent is non-pref MMIO
599 	 *	   and non-pref MMIO assignment fails, will release that
600 	 *	   assigned pref MMIO.
601 	 *	3. If non-pref MMIO assignment fails or pref MMIO
602 	 *	   assignment fails, will release assigned non-pref MMIO.
603 	 */
604 	LIST_HEAD(save_head);
605 	LIST_HEAD(local_fail_head);
606 	LIST_HEAD(dummy_head);
607 	struct pci_dev_resource *save_res;
608 	struct pci_dev_resource *dev_res, *tmp_res, *dev_res2, *addsize_res;
609 	struct resource *res;
610 	struct pci_dev *dev;
611 	unsigned long fail_type;
612 	resource_size_t align;
613 
614 	if (!realloc_head)
615 		realloc_head = &dummy_head;
616 
617 	/* Check if optional add_size is there */
618 	if (list_empty(realloc_head))
619 		goto assign;
620 
621 	/* Save original start, end, flags etc at first */
622 	list_for_each_entry(dev_res, head, list) {
623 		if (pci_dev_res_add_to_list(&save_head, dev_res->dev,
624 					    dev_res->res, 0, 0)) {
625 			pci_dev_res_free_list(&save_head);
626 			goto assign;
627 		}
628 	}
629 
630 	/* Update res in head list with add_size in realloc_head list */
631 	list_for_each_entry_safe(dev_res, tmp_res, head, list) {
632 		res = dev_res->res;
633 
634 		addsize_res = res_to_dev_res(realloc_head, res);
635 		if (!addsize_res)
636 			continue;
637 
638 		res->end += addsize_res->add_size;
639 		/*
640 		 * There are two kinds of additional resources in the list:
641 		 * 1. bridge resource  -- IORESOURCE_STARTALIGN
642 		 * 2. SR-IOV resource  -- IORESOURCE_SIZEALIGN
643 		 * Here just fix the additional alignment for bridge
644 		 */
645 		if (!(res->flags & IORESOURCE_STARTALIGN))
646 			continue;
647 
648 		if (addsize_res->min_align <= res->start)
649 			continue;
650 		/*
651 		 * The "head" list is sorted by alignment so resources with
652 		 * bigger alignment will be assigned first.  After we
653 		 * change the alignment of a dev_res in "head" list, we
654 		 * need to reorder the list by alignment to make it
655 		 * consistent.
656 		 */
657 		resource_set_range(res, addsize_res->min_align,
658 				   resource_size(res));
659 
660 		list_for_each_entry(dev_res2, head, list) {
661 			align = pci_resource_alignment(dev_res2->dev,
662 						       dev_res2->res);
663 			if (addsize_res->min_align > align) {
664 				list_move_tail(&dev_res->list, &dev_res2->list);
665 				break;
666 			}
667 		}
668 
669 	}
670 
671 assign:
672 	assign_requested_resources_sorted(head, &local_fail_head, true);
673 
674 	/* All non-optional resources assigned? */
675 	if (list_empty(&local_fail_head)) {
676 		/* Remove head list from realloc_head list */
677 		list_for_each_entry(dev_res, head, list)
678 			pci_dev_res_remove_from_list(realloc_head,
679 						     dev_res->res);
680 		pci_dev_res_free_list(&save_head);
681 		goto out;
682 	}
683 
684 	/* Without realloc_head and only optional fails, nothing more to do. */
685 	if (!pci_required_resource_failed(&local_fail_head, 0) &&
686 	    list_empty(realloc_head)) {
687 		list_for_each_entry(save_res, &save_head, list) {
688 			struct resource *res = save_res->res;
689 
690 			if (resource_assigned(res))
691 				continue;
692 
693 			pci_dev_res_restore(save_res);
694 		}
695 		pci_dev_res_free_list(&local_fail_head);
696 		pci_dev_res_free_list(&save_head);
697 		goto out;
698 	}
699 
700 	/* Check failed type */
701 	fail_type = pci_fail_res_type_mask(&local_fail_head);
702 	/* Remove not need to be released assigned res from head list etc */
703 	list_for_each_entry_safe(dev_res, tmp_res, head, list) {
704 		res = dev_res->res;
705 
706 		if (resource_assigned(res) &&
707 		    !pci_need_to_release(fail_type, res)) {
708 			/* Remove it from realloc_head list */
709 			pci_dev_res_remove_from_list(realloc_head, res);
710 			pci_dev_res_remove_from_list(&save_head, res);
711 			list_del(&dev_res->list);
712 			kfree(dev_res);
713 		}
714 	}
715 
716 	pci_dev_res_free_list(&local_fail_head);
717 	/* Release assigned resource */
718 	list_for_each_entry(dev_res, head, list) {
719 		res = dev_res->res;
720 		dev = dev_res->dev;
721 
722 		pci_release_resource(dev, pci_resource_num(dev, res));
723 		pci_dev_res_restore(dev_res);
724 	}
725 	/* Restore start/end/flags from saved list */
726 	list_for_each_entry(save_res, &save_head, list)
727 		pci_dev_res_restore(save_res);
728 	pci_dev_res_free_list(&save_head);
729 
730 	/* Satisfy the must-have resource requests */
731 	assign_requested_resources_sorted(head, NULL, false);
732 
733 	/* Try to satisfy any additional optional resource requests */
734 	if (!list_empty(realloc_head))
735 		reassign_resources_sorted(realloc_head, head);
736 
737 out:
738 	/* Reset any failed resource, cannot use fail_head as it can be NULL. */
739 	list_for_each_entry(dev_res, head, list) {
740 		res = dev_res->res;
741 		dev = dev_res->dev;
742 
743 		if (resource_assigned(res))
744 			continue;
745 
746 		if (fail_head) {
747 			pci_dev_res_add_to_list(fail_head, dev, res,
748 						0 /* don't care */,
749 						0 /* don't care */);
750 		}
751 
752 		reset_resource(dev, res);
753 	}
754 
755 	pci_dev_res_free_list(head);
756 }
757 
758 static void pdev_assign_resources_sorted(struct pci_dev *dev,
759 					 struct list_head *add_head,
760 					 struct list_head *fail_head)
761 {
762 	LIST_HEAD(head);
763 
764 	pdev_sort_resources(dev, &head);
765 	__assign_resources_sorted(&head, add_head, fail_head);
766 
767 }
768 
769 static void pbus_assign_resources_sorted(const struct pci_bus *bus,
770 					 struct list_head *realloc_head,
771 					 struct list_head *fail_head)
772 {
773 	struct pci_dev *dev;
774 	LIST_HEAD(head);
775 
776 	list_for_each_entry(dev, &bus->devices, bus_list)
777 		pdev_sort_resources(dev, &head);
778 
779 	__assign_resources_sorted(&head, realloc_head, fail_head);
780 }
781 
782 /*
783  * Initialize bridges with base/limit values we have collected.  PCI-to-PCI
784  * Bridge Architecture Specification rev. 1.1 (1998) requires that if there
785  * are no I/O ports or memory behind the bridge, the corresponding range
786  * must be turned off by writing base value greater than limit to the
787  * bridge's base/limit registers.
788  *
789  * Note: care must be taken when updating I/O base/limit registers of
790  * bridges which support 32-bit I/O.  This update requires two config space
791  * writes, so it's quite possible that an I/O window of the bridge will
792  * have some undesirable address (e.g. 0) after the first write.  Ditto
793  * 64-bit prefetchable MMIO.
794  */
795 static void pci_setup_bridge_io(struct pci_dev *bridge)
796 {
797 	struct resource *res;
798 	const char *res_name;
799 	struct pci_bus_region region;
800 	unsigned long io_mask;
801 	u8 io_base_lo, io_limit_lo;
802 	u16 l;
803 	u32 io_upper16;
804 
805 	io_mask = PCI_IO_RANGE_MASK;
806 	if (bridge->io_window_1k)
807 		io_mask = PCI_IO_1K_RANGE_MASK;
808 
809 	/* Set up the top and bottom of the PCI I/O segment for this bus */
810 	res = &bridge->resource[PCI_BRIDGE_IO_WINDOW];
811 	res_name = pci_resource_name(bridge, PCI_BRIDGE_IO_WINDOW);
812 	pcibios_resource_to_bus(bridge->bus, &region, res);
813 	if (resource_assigned(res) && res->flags & IORESOURCE_IO) {
814 		pci_read_config_word(bridge, PCI_IO_BASE, &l);
815 		io_base_lo = (region.start >> 8) & io_mask;
816 		io_limit_lo = (region.end >> 8) & io_mask;
817 		l = ((u16) io_limit_lo << 8) | io_base_lo;
818 		/* Set up upper 16 bits of I/O base/limit */
819 		io_upper16 = (region.end & 0xffff0000) | (region.start >> 16);
820 		pci_info(bridge, "  %s %pR\n", res_name, res);
821 	} else {
822 		/* Clear upper 16 bits of I/O base/limit */
823 		io_upper16 = 0;
824 		l = 0x00f0;
825 	}
826 	/* Temporarily disable the I/O range before updating PCI_IO_BASE */
827 	pci_write_config_dword(bridge, PCI_IO_BASE_UPPER16, 0x0000ffff);
828 	/* Update lower 16 bits of I/O base/limit */
829 	pci_write_config_word(bridge, PCI_IO_BASE, l);
830 	/* Update upper 16 bits of I/O base/limit */
831 	pci_write_config_dword(bridge, PCI_IO_BASE_UPPER16, io_upper16);
832 }
833 
834 static void pci_setup_bridge_mmio(struct pci_dev *bridge)
835 {
836 	struct resource *res;
837 	const char *res_name;
838 	struct pci_bus_region region;
839 	u32 l;
840 
841 	/* Set up the top and bottom of the PCI Memory segment for this bus */
842 	res = &bridge->resource[PCI_BRIDGE_MEM_WINDOW];
843 	res_name = pci_resource_name(bridge, PCI_BRIDGE_MEM_WINDOW);
844 	pcibios_resource_to_bus(bridge->bus, &region, res);
845 	if (resource_assigned(res) && res->flags & IORESOURCE_MEM) {
846 		l = (region.start >> 16) & 0xfff0;
847 		l |= region.end & 0xfff00000;
848 		pci_info(bridge, "  %s %pR\n", res_name, res);
849 	} else {
850 		l = 0x0000fff0;
851 	}
852 	pci_write_config_dword(bridge, PCI_MEMORY_BASE, l);
853 }
854 
855 static void pci_setup_bridge_mmio_pref(struct pci_dev *bridge)
856 {
857 	struct resource *res;
858 	const char *res_name;
859 	struct pci_bus_region region;
860 	u32 l, bu, lu;
861 
862 	/*
863 	 * Clear out the upper 32 bits of PREF limit.  If
864 	 * PCI_PREF_BASE_UPPER32 was non-zero, this temporarily disables
865 	 * PREF range, which is ok.
866 	 */
867 	pci_write_config_dword(bridge, PCI_PREF_LIMIT_UPPER32, 0);
868 
869 	/* Set up PREF base/limit */
870 	bu = lu = 0;
871 	res = &bridge->resource[PCI_BRIDGE_PREF_MEM_WINDOW];
872 	res_name = pci_resource_name(bridge, PCI_BRIDGE_PREF_MEM_WINDOW);
873 	pcibios_resource_to_bus(bridge->bus, &region, res);
874 	if (resource_assigned(res) && res->flags & IORESOURCE_PREFETCH) {
875 		l = (region.start >> 16) & 0xfff0;
876 		l |= region.end & 0xfff00000;
877 		if (res->flags & IORESOURCE_MEM_64) {
878 			bu = upper_32_bits(region.start);
879 			lu = upper_32_bits(region.end);
880 		}
881 		pci_info(bridge, "  %s %pR\n", res_name, res);
882 	} else {
883 		l = 0x0000fff0;
884 	}
885 	pci_write_config_dword(bridge, PCI_PREF_MEMORY_BASE, l);
886 
887 	/* Set the upper 32 bits of PREF base & limit */
888 	pci_write_config_dword(bridge, PCI_PREF_BASE_UPPER32, bu);
889 	pci_write_config_dword(bridge, PCI_PREF_LIMIT_UPPER32, lu);
890 }
891 
892 static void __pci_setup_bridge(struct pci_bus *bus, unsigned long type)
893 {
894 	struct pci_dev *bridge = bus->self;
895 
896 	pci_info(bridge, "PCI bridge to %pR\n", &bus->busn_res);
897 
898 	if (type & IORESOURCE_IO)
899 		pci_setup_bridge_io(bridge);
900 
901 	if (type & IORESOURCE_MEM)
902 		pci_setup_bridge_mmio(bridge);
903 
904 	if (type & IORESOURCE_PREFETCH)
905 		pci_setup_bridge_mmio_pref(bridge);
906 
907 	pci_write_config_word(bridge, PCI_BRIDGE_CONTROL, bus->bridge_ctl);
908 }
909 
910 static void pci_setup_one_bridge_window(struct pci_dev *bridge, int resno)
911 {
912 	switch (resno) {
913 	case PCI_BRIDGE_IO_WINDOW:
914 		pci_setup_bridge_io(bridge);
915 		break;
916 	case PCI_BRIDGE_MEM_WINDOW:
917 		pci_setup_bridge_mmio(bridge);
918 		break;
919 	case PCI_BRIDGE_PREF_MEM_WINDOW:
920 		pci_setup_bridge_mmio_pref(bridge);
921 		break;
922 	default:
923 		return;
924 	}
925 }
926 
927 void __weak pcibios_setup_bridge(struct pci_bus *bus, unsigned long type)
928 {
929 }
930 
931 static void pci_setup_bridge(struct pci_bus *bus)
932 {
933 	unsigned long type = IORESOURCE_IO | IORESOURCE_MEM |
934 				  IORESOURCE_PREFETCH;
935 
936 	pcibios_setup_bridge(bus, type);
937 	__pci_setup_bridge(bus, type);
938 }
939 
940 
941 int pci_claim_bridge_resource(struct pci_dev *bridge, int i)
942 {
943 	int ret = -EINVAL;
944 
945 	if (!pci_resource_is_bridge_win(i))
946 		return 0;
947 
948 	if (pci_claim_resource(bridge, i) == 0)
949 		return 0;	/* Claimed the window */
950 
951 	if ((bridge->class >> 8) != PCI_CLASS_BRIDGE_PCI)
952 		return 0;
953 
954 	if (i > PCI_BRIDGE_PREF_MEM_WINDOW)
955 		return -EINVAL;
956 
957 	/* Try to clip the resource and claim the smaller window */
958 	if (pci_bus_clip_resource(bridge, i))
959 		ret = pci_claim_resource(bridge, i);
960 
961 	pci_setup_one_bridge_window(bridge, i);
962 
963 	return ret;
964 }
965 
966 /*
967  * Check whether the bridge supports optional I/O and prefetchable memory
968  * ranges.  If not, the respective base/limit registers must be read-only
969  * and read as 0.
970  */
971 static void pci_bridge_check_ranges(struct pci_bus *bus)
972 {
973 	struct pci_dev *bridge = bus->self;
974 	struct resource *b_res;
975 
976 	b_res = &bridge->resource[PCI_BRIDGE_MEM_WINDOW];
977 	b_res->flags |= IORESOURCE_MEM;
978 
979 	if (bridge->io_window) {
980 		b_res = &bridge->resource[PCI_BRIDGE_IO_WINDOW];
981 		b_res->flags |= IORESOURCE_IO;
982 	}
983 
984 	if (bridge->pref_window) {
985 		b_res = &bridge->resource[PCI_BRIDGE_PREF_MEM_WINDOW];
986 		b_res->flags |= IORESOURCE_MEM | IORESOURCE_PREFETCH;
987 		if (bridge->pref_64_window) {
988 			b_res->flags |= IORESOURCE_MEM_64 |
989 					PCI_PREF_RANGE_TYPE_64;
990 		}
991 	}
992 }
993 
994 static resource_size_t calculate_iosize(resource_size_t size,
995 					resource_size_t min_size,
996 					resource_size_t size1,
997 					resource_size_t add_size,
998 					resource_size_t children_add_size,
999 					resource_size_t old_size,
1000 					resource_size_t align)
1001 {
1002 	if (size < min_size)
1003 		size = min_size;
1004 	if (old_size == 1)
1005 		old_size = 0;
1006 	/*
1007 	 * To be fixed in 2.5: we should have sort of HAVE_ISA flag in the
1008 	 * struct pci_bus.
1009 	 */
1010 #if defined(CONFIG_ISA) || defined(CONFIG_EISA)
1011 	size = (size & 0xff) + ((size & ~0xffUL) << 2);
1012 #endif
1013 	size = size + size1;
1014 
1015 	size = max(size, add_size) + children_add_size;
1016 	return ALIGN(max(size, old_size), align);
1017 }
1018 
1019 static resource_size_t calculate_memsize(resource_size_t size,
1020 					 resource_size_t min_size,
1021 					 resource_size_t children_add_size,
1022 					 resource_size_t align)
1023 {
1024 	size = max(size, min_size) + children_add_size;
1025 	return ALIGN(size, align);
1026 }
1027 
1028 resource_size_t __weak pcibios_window_alignment(struct pci_bus *bus,
1029 						unsigned long type)
1030 {
1031 	return 1;
1032 }
1033 
1034 #define PCI_P2P_DEFAULT_MEM_ALIGN	SZ_1M
1035 #define PCI_P2P_DEFAULT_IO_ALIGN	SZ_4K
1036 #define PCI_P2P_DEFAULT_IO_ALIGN_1K	SZ_1K
1037 
1038 resource_size_t pci_min_window_alignment(struct pci_bus *bus, unsigned long type)
1039 {
1040 	resource_size_t align = 1, arch_align;
1041 
1042 	if (type & IORESOURCE_MEM)
1043 		align = PCI_P2P_DEFAULT_MEM_ALIGN;
1044 	else if (type & IORESOURCE_IO) {
1045 		/*
1046 		 * Per spec, I/O windows are 4K-aligned, but some bridges have
1047 		 * an extension to support 1K alignment.
1048 		 */
1049 		if (bus->self && bus->self->io_window_1k)
1050 			align = PCI_P2P_DEFAULT_IO_ALIGN_1K;
1051 		else
1052 			align = PCI_P2P_DEFAULT_IO_ALIGN;
1053 	}
1054 
1055 	arch_align = pcibios_window_alignment(bus, type);
1056 	return max(align, arch_align);
1057 }
1058 
1059 /**
1060  * pbus_size_io() - Size the I/O window of a given bus
1061  *
1062  * @bus:		The bus
1063  * @add_size:		Additional I/O window
1064  * @realloc_head:	Track the additional I/O window on this list
1065  *
1066  * Sizing the I/O windows of the PCI-PCI bridge is trivial, since these
1067  * windows have 1K or 4K granularity and the I/O ranges of non-bridge PCI
1068  * devices are limited to 256 bytes.  We must be careful with the ISA
1069  * aliasing though.
1070  */
1071 static void pbus_size_io(struct pci_bus *bus, resource_size_t add_size,
1072 			 struct list_head *realloc_head)
1073 {
1074 	struct pci_dev *dev;
1075 	struct resource *b_res = pbus_select_window_for_type(bus, IORESOURCE_IO);
1076 	resource_size_t size = 0, size0 = 0, size1 = 0;
1077 	resource_size_t children_add_size = 0;
1078 	resource_size_t min_align, align;
1079 
1080 	if (!b_res)
1081 		return;
1082 
1083 	/* If resource is already assigned, nothing more to do */
1084 	if (resource_assigned(b_res))
1085 		return;
1086 
1087 	min_align = pci_min_window_alignment(bus, IORESOURCE_IO);
1088 	list_for_each_entry(dev, &bus->devices, bus_list) {
1089 		struct resource *r;
1090 
1091 		pci_dev_for_each_resource(dev, r) {
1092 			unsigned long r_size;
1093 
1094 			if (resource_assigned(r) || !(r->flags & IORESOURCE_IO))
1095 				continue;
1096 
1097 			if (!pdev_resource_assignable(dev, r))
1098 				continue;
1099 
1100 			r_size = resource_size(r);
1101 			if (r_size < SZ_1K)
1102 				/* Might be re-aligned for ISA */
1103 				size += r_size;
1104 			else
1105 				size1 += r_size;
1106 
1107 			align = pci_resource_alignment(dev, r);
1108 			if (align > min_align)
1109 				min_align = align;
1110 
1111 			if (realloc_head)
1112 				children_add_size += get_res_add_size(realloc_head, r);
1113 		}
1114 	}
1115 
1116 	size0 = calculate_iosize(size, realloc_head ? 0 : add_size, size1, 0, 0,
1117 			resource_size(b_res), min_align);
1118 
1119 	if (size0)
1120 		b_res->flags &= ~IORESOURCE_DISABLED;
1121 
1122 	size1 = size0;
1123 	if (realloc_head && (add_size > 0 || children_add_size > 0)) {
1124 		size1 = calculate_iosize(size, 0, size1, add_size,
1125 					 children_add_size, resource_size(b_res),
1126 					 min_align);
1127 	}
1128 
1129 	if (!size0 && !size1) {
1130 		if (bus->self && (b_res->start || b_res->end))
1131 			pci_info(bus->self, "disabling bridge window %pR to %pR (unused)\n",
1132 				 b_res, &bus->busn_res);
1133 		b_res->flags |= IORESOURCE_DISABLED;
1134 		return;
1135 	}
1136 
1137 	resource_set_range(b_res, min_align, size0);
1138 	b_res->flags |= IORESOURCE_STARTALIGN;
1139 	if (bus->self && size1 > size0 && realloc_head) {
1140 		b_res->flags &= ~IORESOURCE_DISABLED;
1141 		pci_dev_res_add_to_list(realloc_head, bus->self, b_res,
1142 					size1 - size0, min_align);
1143 		pci_info(bus->self, "bridge window %pR to %pR add_size %llx\n",
1144 			 b_res, &bus->busn_res,
1145 			 (unsigned long long) size1 - size0);
1146 	}
1147 }
1148 
1149 static inline resource_size_t calculate_mem_align(resource_size_t *aligns,
1150 						  int max_order)
1151 {
1152 	resource_size_t align = 0;
1153 	resource_size_t min_align = 0;
1154 	int order;
1155 
1156 	for (order = 0; order <= max_order; order++) {
1157 		resource_size_t align1 = 1;
1158 
1159 		align1 <<= order + __ffs(SZ_1M);
1160 
1161 		if (!align)
1162 			min_align = align1;
1163 		else if (ALIGN(align + min_align, min_align) < align1)
1164 			min_align = align1 >> 1;
1165 		align += aligns[order];
1166 	}
1167 
1168 	return min_align;
1169 }
1170 
1171 /*
1172  * Calculate bridge window head alignment that leaves no gaps in between
1173  * resources.
1174  */
1175 static resource_size_t calculate_head_align(resource_size_t *aligns,
1176 					    int max_order)
1177 {
1178 	resource_size_t head_align = 1;
1179 	resource_size_t remainder = 0;
1180 	int order;
1181 
1182 	/* Take the largest alignment as the starting point. */
1183 	head_align <<= max_order + __ffs(SZ_1M);
1184 
1185 	for (order = max_order - 1; order >= 0; order--) {
1186 		resource_size_t align1 = 1;
1187 
1188 		align1 <<= order + __ffs(SZ_1M);
1189 
1190 		/*
1191 		 * Account smaller resources with alignment < max_order that
1192 		 * could be used to fill head room if alignment less than
1193 		 * max_order is used.
1194 		 */
1195 		remainder += aligns[order];
1196 
1197 		/*
1198 		 * Test if head fill is enough to satisfy the alignment of
1199 		 * the larger resources after reducing the alignment.
1200 		 */
1201 		while ((head_align > align1) && (remainder >= head_align / 2)) {
1202 			head_align /= 2;
1203 			remainder -= head_align;
1204 		}
1205 	}
1206 
1207 	return head_align;
1208 }
1209 
1210 /*
1211  * pbus_size_mem_optional - Account optional resources in bridge window
1212  *
1213  * Account an optional resource or the optional part of the resource in bridge
1214  * window size.
1215  *
1216  * Return: %true if the resource is entirely optional.
1217  */
1218 static bool pbus_size_mem_optional(struct pci_dev *dev, int resno,
1219 				   resource_size_t align,
1220 				   struct list_head *realloc_head,
1221 				   resource_size_t *add_align,
1222 				   resource_size_t *children_add_size)
1223 {
1224 	struct resource *res = pci_resource_n(dev, resno);
1225 	bool optional = pci_resource_is_optional(dev, resno);
1226 	resource_size_t r_size = resource_size(res);
1227 	struct pci_dev_resource *dev_res = NULL;
1228 
1229 	if (!realloc_head)
1230 		return false;
1231 
1232 	/*
1233 	 * Only bridges have optional sizes in realloc_head at this
1234 	 * point. As res_to_dev_res() walks the entire realloc_head
1235 	 * list, skip calling it when known unnecessary.
1236 	 */
1237 	if (pci_resource_is_bridge_win(resno)) {
1238 		dev_res = res_to_dev_res(realloc_head, res);
1239 		if (dev_res) {
1240 			*children_add_size += dev_res->add_size;
1241 			*add_align = max(*add_align, dev_res->min_align);
1242 		}
1243 	}
1244 
1245 	if (!optional)
1246 		return false;
1247 
1248 	/*
1249 	 * Put requested res to the optional list if not there yet (SR-IOV,
1250 	 * disabled ROM). Bridge windows with an optional part are already
1251 	 * on the list.
1252 	 */
1253 	if (!dev_res)
1254 		pci_dev_res_add_to_list(realloc_head, dev, res, 0, align);
1255 	*children_add_size += r_size;
1256 	*add_align = max(align, *add_align);
1257 
1258 	return true;
1259 }
1260 
1261 /**
1262  * pbus_size_mem() - Size the memory window of a given bus
1263  *
1264  * @bus:		The bus
1265  * @b_res:		The bridge window resource
1266  * @add_size:		Additional memory window
1267  * @realloc_head:	Track the additional memory window on this list
1268  *
1269  * Calculate the size of the bridge window @b_res and minimal alignment
1270  * which guarantees that all child resources fit in this size.
1271  *
1272  * Set the bus resource start/end to indicate the required size if there an
1273  * available unassigned bus resource of the desired @type.
1274  *
1275  * Add optional resource requests to the @realloc_head list if it is
1276  * supplied.
1277  */
1278 static void pbus_size_mem(struct pci_bus *bus, struct resource *b_res,
1279 			  resource_size_t add_size,
1280 			  struct list_head *realloc_head)
1281 {
1282 	struct pci_dev *dev;
1283 	resource_size_t min_align, win_align, align, size, size0, size1 = 0;
1284 	resource_size_t aligns[28] = {}; /* Alignments from 1MB to 128TB */
1285 	int order, max_order;
1286 	resource_size_t children_add_size = 0;
1287 	resource_size_t add_align = 0;
1288 
1289 	if (!b_res)
1290 		return;
1291 
1292 	/* If resource is already assigned, nothing more to do */
1293 	if (resource_assigned(b_res))
1294 		return;
1295 
1296 	max_order = 0;
1297 	size = 0;
1298 
1299 	list_for_each_entry(dev, &bus->devices, bus_list) {
1300 		struct resource *r;
1301 		int i;
1302 
1303 		pci_dev_for_each_resource(dev, r, i) {
1304 			const char *r_name = pci_resource_name(dev, i);
1305 			resource_size_t r_size;
1306 
1307 			if (!pdev_resources_assignable(dev) ||
1308 			    !pdev_resource_should_fit(dev, r))
1309 				continue;
1310 			if (b_res != pbus_select_window(bus, r))
1311 				continue;
1312 
1313 			align = pci_resource_alignment(dev, r);
1314 			/*
1315 			 * aligns[0] is for 1MB (since bridge memory
1316 			 * windows are always at least 1MB aligned), so
1317 			 * keep "order" from being negative for smaller
1318 			 * resources.
1319 			 */
1320 			order = max_t(int, __ffs(align) - __ffs(SZ_1M), 0);
1321 			if (order >= ARRAY_SIZE(aligns)) {
1322 				pci_warn(dev, "%s %pR: disabling; bad alignment %#llx\n",
1323 					 r_name, r, (unsigned long long) align);
1324 				r->flags = 0;
1325 				continue;
1326 			}
1327 
1328 			if (pbus_size_mem_optional(dev, i, align,
1329 						   realloc_head, &add_align,
1330 						   &children_add_size))
1331 				continue;
1332 
1333 			r_size = resource_size(r);
1334 			size += max(r_size, align);
1335 
1336 			/*
1337 			 * If resource's size is larger than its alignment,
1338 			 * some configurations result in an unwanted gap in
1339 			 * the head space that the larger resource cannot
1340 			 * fill.
1341 			 */
1342 			if (r_size <= align)
1343 				aligns[order] += align;
1344 			if (order > max_order)
1345 				max_order = order;
1346 		}
1347 	}
1348 
1349 	win_align = pci_min_window_alignment(bus, b_res->flags);
1350 	min_align = calculate_head_align(aligns, max_order);
1351 	min_align = max(min_align, win_align);
1352 	size0 = calculate_memsize(size, realloc_head ? 0 : add_size,
1353 				  0, win_align);
1354 
1355 	if (size0) {
1356 		resource_set_range(b_res, min_align, size0);
1357 		b_res->flags &= ~IORESOURCE_DISABLED;
1358 	}
1359 
1360 	if (realloc_head && (add_size > 0 || children_add_size > 0)) {
1361 		add_align = max(min_align, add_align);
1362 		size1 = calculate_memsize(size, add_size, children_add_size,
1363 					  win_align);
1364 	}
1365 
1366 	if (!size0 && !size1) {
1367 		if (bus->self && (b_res->start || b_res->end))
1368 			pci_info(bus->self, "disabling bridge window %pR to %pR (unused)\n",
1369 				 b_res, &bus->busn_res);
1370 		b_res->flags |= IORESOURCE_DISABLED;
1371 		return;
1372 	}
1373 
1374 	resource_set_range(b_res, min_align, size0);
1375 	b_res->flags |= IORESOURCE_STARTALIGN;
1376 	if (bus->self && realloc_head && (size1 > size0 || add_align > min_align)) {
1377 		b_res->flags &= ~IORESOURCE_DISABLED;
1378 		add_size = size1 > size0 ? size1 - size0 : 0;
1379 		pci_dev_res_add_to_list(realloc_head, bus->self, b_res,
1380 					add_size, add_align);
1381 		pci_info(bus->self, "bridge window %pR to %pR add_size %llx add_align %llx\n",
1382 			   b_res, &bus->busn_res,
1383 			   (unsigned long long) add_size,
1384 			   (unsigned long long) add_align);
1385 	}
1386 }
1387 
1388 void __pci_bus_size_bridges(struct pci_bus *bus, struct list_head *realloc_head)
1389 {
1390 	struct pci_dev *dev;
1391 	resource_size_t additional_io_size = 0, additional_mmio_size = 0,
1392 			additional_mmio_pref_size = 0;
1393 	struct resource *b_res;
1394 	struct pci_host_bridge *host;
1395 	int hdr_type;
1396 
1397 	list_for_each_entry(dev, &bus->devices, bus_list) {
1398 		struct pci_bus *b = dev->subordinate;
1399 		if (!b)
1400 			continue;
1401 
1402 		switch (dev->hdr_type) {
1403 		case PCI_HEADER_TYPE_CARDBUS:
1404 			if (pci_bus_size_cardbus_bridge(b, realloc_head))
1405 				continue;
1406 			break;
1407 
1408 		case PCI_HEADER_TYPE_BRIDGE:
1409 		default:
1410 			__pci_bus_size_bridges(b, realloc_head);
1411 			break;
1412 		}
1413 	}
1414 
1415 	/* The root bus? */
1416 	if (pci_is_root_bus(bus)) {
1417 		host = to_pci_host_bridge(bus->bridge);
1418 		if (!host->size_windows)
1419 			return;
1420 		hdr_type = -1;	/* Intentionally invalid - not a PCI device. */
1421 	} else {
1422 		hdr_type = bus->self->hdr_type;
1423 	}
1424 
1425 	switch (hdr_type) {
1426 	case PCI_HEADER_TYPE_CARDBUS:
1427 		/* Don't size CardBuses yet */
1428 		break;
1429 
1430 	case PCI_HEADER_TYPE_BRIDGE:
1431 		pci_bridge_check_ranges(bus);
1432 		if (bus->self->is_hotplug_bridge) {
1433 			additional_io_size  = pci_hotplug_io_size;
1434 			additional_mmio_size = pci_hotplug_mmio_size;
1435 			additional_mmio_pref_size = pci_hotplug_mmio_pref_size;
1436 		}
1437 		fallthrough;
1438 	default:
1439 		pbus_size_io(bus, additional_io_size, realloc_head);
1440 
1441 		b_res = pbus_select_window_for_type(bus, IORESOURCE_MEM |
1442 							 IORESOURCE_PREFETCH |
1443 							 IORESOURCE_MEM_64);
1444 		if (b_res && (b_res->flags & IORESOURCE_PREFETCH)) {
1445 			pbus_size_mem(bus, b_res, additional_mmio_pref_size,
1446 				      realloc_head);
1447 		}
1448 
1449 		b_res = pbus_select_window_for_type(bus, IORESOURCE_MEM);
1450 		if (b_res) {
1451 			pbus_size_mem(bus, b_res, additional_mmio_size,
1452 				      realloc_head);
1453 		}
1454 		break;
1455 	}
1456 }
1457 
1458 void pci_bus_size_bridges(struct pci_bus *bus)
1459 {
1460 	__pci_bus_size_bridges(bus, NULL);
1461 }
1462 EXPORT_SYMBOL(pci_bus_size_bridges);
1463 
1464 static void assign_fixed_resource_on_bus(struct pci_bus *b, struct resource *r)
1465 {
1466 	struct resource *parent_r;
1467 	unsigned long mask = IORESOURCE_IO | IORESOURCE_MEM |
1468 			     IORESOURCE_PREFETCH;
1469 
1470 	pci_bus_for_each_resource(b, parent_r) {
1471 		if (!parent_r)
1472 			continue;
1473 
1474 		if ((r->flags & mask) == (parent_r->flags & mask) &&
1475 		    resource_contains(parent_r, r))
1476 			request_resource(parent_r, r);
1477 	}
1478 }
1479 
1480 /*
1481  * Try to assign any resources marked as IORESOURCE_PCI_FIXED, as they are
1482  * skipped by pbus_assign_resources_sorted().
1483  */
1484 static void pdev_assign_fixed_resources(struct pci_dev *dev)
1485 {
1486 	struct resource *r;
1487 
1488 	pci_dev_for_each_resource(dev, r) {
1489 		struct pci_bus *b;
1490 
1491 		if (resource_assigned(r) ||
1492 		    !(r->flags & IORESOURCE_PCI_FIXED) ||
1493 		    !(r->flags & (IORESOURCE_IO | IORESOURCE_MEM)))
1494 			continue;
1495 
1496 		b = dev->bus;
1497 		while (b && !resource_assigned(r)) {
1498 			assign_fixed_resource_on_bus(b, r);
1499 			b = b->parent;
1500 		}
1501 	}
1502 }
1503 
1504 void __pci_bus_assign_resources(const struct pci_bus *bus,
1505 				struct list_head *realloc_head,
1506 				struct list_head *fail_head)
1507 {
1508 	struct pci_bus *b;
1509 	struct pci_dev *dev;
1510 
1511 	pbus_assign_resources_sorted(bus, realloc_head, fail_head);
1512 
1513 	list_for_each_entry(dev, &bus->devices, bus_list) {
1514 		pdev_assign_fixed_resources(dev);
1515 
1516 		b = dev->subordinate;
1517 		if (!b)
1518 			continue;
1519 
1520 		__pci_bus_assign_resources(b, realloc_head, fail_head);
1521 
1522 		switch (dev->hdr_type) {
1523 		case PCI_HEADER_TYPE_BRIDGE:
1524 			if (!pci_is_enabled(dev))
1525 				pci_setup_bridge(b);
1526 			break;
1527 
1528 		case PCI_HEADER_TYPE_CARDBUS:
1529 			pci_setup_cardbus_bridge(b);
1530 			break;
1531 
1532 		default:
1533 			pci_info(dev, "not setting up bridge for bus %04x:%02x\n",
1534 				 pci_domain_nr(b), b->number);
1535 			break;
1536 		}
1537 	}
1538 }
1539 
1540 void pci_bus_assign_resources(const struct pci_bus *bus)
1541 {
1542 	__pci_bus_assign_resources(bus, NULL, NULL);
1543 }
1544 EXPORT_SYMBOL(pci_bus_assign_resources);
1545 
1546 static void pci_claim_device_resources(struct pci_dev *dev)
1547 {
1548 	int i;
1549 
1550 	for (i = 0; i < PCI_BRIDGE_RESOURCES; i++) {
1551 		struct resource *r = &dev->resource[i];
1552 
1553 		if (!r->flags || resource_assigned(r))
1554 			continue;
1555 
1556 		pci_claim_resource(dev, i);
1557 	}
1558 }
1559 
1560 static void pci_claim_bridge_resources(struct pci_dev *dev)
1561 {
1562 	int i;
1563 
1564 	for (i = PCI_BRIDGE_RESOURCES; i < PCI_NUM_RESOURCES; i++) {
1565 		struct resource *r = &dev->resource[i];
1566 
1567 		if (!r->flags || resource_assigned(r))
1568 			continue;
1569 		if (r->flags & IORESOURCE_DISABLED)
1570 			continue;
1571 
1572 		pci_claim_bridge_resource(dev, i);
1573 	}
1574 }
1575 
1576 static void pci_bus_allocate_dev_resources(struct pci_bus *b)
1577 {
1578 	struct pci_dev *dev;
1579 	struct pci_bus *child;
1580 
1581 	list_for_each_entry(dev, &b->devices, bus_list) {
1582 		pci_claim_device_resources(dev);
1583 
1584 		child = dev->subordinate;
1585 		if (child)
1586 			pci_bus_allocate_dev_resources(child);
1587 	}
1588 }
1589 
1590 static void pci_bus_allocate_resources(struct pci_bus *b)
1591 {
1592 	struct pci_bus *child;
1593 
1594 	/*
1595 	 * Carry out a depth-first search on the PCI bus tree to allocate
1596 	 * bridge apertures.  Read the programmed bridge bases and
1597 	 * recursively claim the respective bridge resources.
1598 	 */
1599 	if (b->self) {
1600 		pci_read_bridge_bases(b);
1601 		pci_claim_bridge_resources(b->self);
1602 	}
1603 
1604 	list_for_each_entry(child, &b->children, node)
1605 		pci_bus_allocate_resources(child);
1606 }
1607 
1608 void pci_bus_claim_resources(struct pci_bus *b)
1609 {
1610 	pci_bus_allocate_resources(b);
1611 	pci_bus_allocate_dev_resources(b);
1612 }
1613 EXPORT_SYMBOL(pci_bus_claim_resources);
1614 
1615 static void __pci_bridge_assign_resources(const struct pci_dev *bridge,
1616 					  struct list_head *add_head,
1617 					  struct list_head *fail_head)
1618 {
1619 	struct pci_bus *b;
1620 
1621 	pdev_assign_resources_sorted((struct pci_dev *)bridge,
1622 					 add_head, fail_head);
1623 
1624 	b = bridge->subordinate;
1625 	if (!b)
1626 		return;
1627 
1628 	__pci_bus_assign_resources(b, add_head, fail_head);
1629 
1630 	switch (bridge->class >> 8) {
1631 	case PCI_CLASS_BRIDGE_PCI:
1632 		pci_setup_bridge(b);
1633 		break;
1634 
1635 	case PCI_CLASS_BRIDGE_CARDBUS:
1636 		pci_setup_cardbus_bridge(b);
1637 		break;
1638 
1639 	default:
1640 		pci_info(bridge, "not setting up bridge for bus %04x:%02x\n",
1641 			 pci_domain_nr(b), b->number);
1642 		break;
1643 	}
1644 }
1645 
1646 static void pci_bridge_release_resources(struct pci_bus *bus,
1647 					 struct resource *b_win)
1648 {
1649 	struct pci_dev *dev = bus->self;
1650 	int idx, ret;
1651 
1652 	if (!resource_assigned(b_win))
1653 		return;
1654 
1655 	idx = pci_resource_num(dev, b_win);
1656 
1657 	/* If there are children, release them all */
1658 	release_child_resources(b_win);
1659 
1660 	ret = pci_release_resource(dev, idx);
1661 	if (ret)
1662 		return;
1663 
1664 	pci_setup_one_bridge_window(dev, idx);
1665 }
1666 
1667 enum release_type {
1668 	leaf_only,
1669 	whole_subtree,
1670 };
1671 
1672 /*
1673  * Try to release PCI bridge resources from leaf bridge, so we can allocate
1674  * a larger window later.
1675  */
1676 static void pci_bus_release_bridge_resources(struct pci_bus *bus,
1677 					     struct resource *b_win,
1678 					     enum release_type rel_type)
1679 {
1680 	struct pci_dev *dev;
1681 	bool is_leaf_bridge = true;
1682 
1683 	list_for_each_entry(dev, &bus->devices, bus_list) {
1684 		struct pci_bus *b = dev->subordinate;
1685 		struct resource *res;
1686 
1687 		if (!b)
1688 			continue;
1689 
1690 		is_leaf_bridge = false;
1691 
1692 		if ((dev->class >> 8) != PCI_CLASS_BRIDGE_PCI)
1693 			continue;
1694 
1695 		if (rel_type != whole_subtree)
1696 			continue;
1697 
1698 		pci_bus_for_each_resource(b, res) {
1699 			if (res->parent != b_win)
1700 				continue;
1701 
1702 			pci_bus_release_bridge_resources(b, res, rel_type);
1703 		}
1704 	}
1705 
1706 	if (pci_is_root_bus(bus))
1707 		return;
1708 
1709 	if ((bus->self->class >> 8) != PCI_CLASS_BRIDGE_PCI)
1710 		return;
1711 
1712 	if ((rel_type == whole_subtree) || is_leaf_bridge)
1713 		pci_bridge_release_resources(bus, b_win);
1714 }
1715 
1716 static void pci_bus_dump_res(struct pci_bus *bus)
1717 {
1718 	struct resource *res;
1719 	int i;
1720 
1721 	pci_bus_for_each_resource(bus, res, i) {
1722 		if (!res || !res->end || !res->flags)
1723 			continue;
1724 
1725 		dev_info(&bus->dev, "resource %d %pR\n", i, res);
1726 	}
1727 }
1728 
1729 static void pci_bus_dump_resources(struct pci_bus *bus)
1730 {
1731 	struct pci_bus *b;
1732 	struct pci_dev *dev;
1733 
1734 
1735 	pci_bus_dump_res(bus);
1736 
1737 	list_for_each_entry(dev, &bus->devices, bus_list) {
1738 		b = dev->subordinate;
1739 		if (!b)
1740 			continue;
1741 
1742 		pci_bus_dump_resources(b);
1743 	}
1744 }
1745 
1746 static int pci_bus_get_depth(struct pci_bus *bus)
1747 {
1748 	int depth = 0;
1749 	struct pci_bus *child_bus;
1750 
1751 	list_for_each_entry(child_bus, &bus->children, node) {
1752 		int ret;
1753 
1754 		ret = pci_bus_get_depth(child_bus);
1755 		if (ret + 1 > depth)
1756 			depth = ret + 1;
1757 	}
1758 
1759 	return depth;
1760 }
1761 
1762 /*
1763  * -1: undefined, will auto detect later
1764  *  0: disabled by user
1765  *  1: disabled by auto detect
1766  *  2: enabled by user
1767  *  3: enabled by auto detect
1768  */
1769 enum enable_type {
1770 	undefined = -1,
1771 	user_disabled,
1772 	auto_disabled,
1773 	user_enabled,
1774 	auto_enabled,
1775 };
1776 
1777 static enum enable_type pci_realloc_enable = undefined;
1778 void __init pci_realloc_get_opt(char *str)
1779 {
1780 	if (!strncmp(str, "off", 3))
1781 		pci_realloc_enable = user_disabled;
1782 	else if (!strncmp(str, "on", 2))
1783 		pci_realloc_enable = user_enabled;
1784 }
1785 static bool pci_realloc_enabled(enum enable_type enable)
1786 {
1787 	return enable >= user_enabled;
1788 }
1789 
1790 #if defined(CONFIG_PCI_IOV) && defined(CONFIG_PCI_REALLOC_ENABLE_AUTO)
1791 static int iov_resources_unassigned(struct pci_dev *dev, void *data)
1792 {
1793 	int i;
1794 	bool *unassigned = data;
1795 
1796 	for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
1797 		int idx = pci_resource_num_from_vf_bar(i);
1798 		struct resource *r = &dev->resource[idx];
1799 		struct pci_bus_region region;
1800 
1801 		/* Not assigned or rejected by kernel? */
1802 		if (!r->flags)
1803 			continue;
1804 
1805 		pcibios_resource_to_bus(dev->bus, &region, r);
1806 		if (!region.start) {
1807 			*unassigned = true;
1808 			return 1; /* Return early from pci_walk_bus() */
1809 		}
1810 	}
1811 
1812 	return 0;
1813 }
1814 
1815 static enum enable_type pci_realloc_detect(struct pci_bus *bus,
1816 					   enum enable_type enable_local)
1817 {
1818 	bool unassigned = false;
1819 	struct pci_host_bridge *host;
1820 
1821 	if (enable_local != undefined)
1822 		return enable_local;
1823 
1824 	host = pci_find_host_bridge(bus);
1825 	if (host->preserve_config)
1826 		return auto_disabled;
1827 
1828 	pci_walk_bus(bus, iov_resources_unassigned, &unassigned);
1829 	if (unassigned)
1830 		return auto_enabled;
1831 
1832 	return enable_local;
1833 }
1834 #else
1835 static enum enable_type pci_realloc_detect(struct pci_bus *bus,
1836 					   enum enable_type enable_local)
1837 {
1838 	return enable_local;
1839 }
1840 #endif
1841 
1842 static void adjust_bridge_window(struct pci_dev *bridge, struct resource *res,
1843 				 struct list_head *add_list,
1844 				 resource_size_t new_size)
1845 {
1846 	resource_size_t add_size, size = resource_size(res);
1847 	struct pci_dev_resource *dev_res;
1848 
1849 	if (resource_assigned(res))
1850 		return;
1851 
1852 	if (!new_size)
1853 		return;
1854 
1855 	if (new_size > size) {
1856 		add_size = new_size - size;
1857 		pci_dbg(bridge, "bridge window %pR extended by %pa\n", res,
1858 			&add_size);
1859 	} else if (new_size < size) {
1860 		int idx = pci_resource_num(bridge, res);
1861 
1862 		/*
1863 		 * hpio/mmio/mmioprefsize hasn't been included at all? See the
1864 		 * add_size param at the callsites of calculate_memsize().
1865 		 */
1866 		if (!add_list)
1867 			return;
1868 
1869 		/* Only shrink if the hotplug extra relates to window size. */
1870 		switch (idx) {
1871 			case PCI_BRIDGE_IO_WINDOW:
1872 				if (size > pci_hotplug_io_size)
1873 					return;
1874 				break;
1875 			case PCI_BRIDGE_MEM_WINDOW:
1876 				if (size > pci_hotplug_mmio_size)
1877 					return;
1878 				break;
1879 			case PCI_BRIDGE_PREF_MEM_WINDOW:
1880 				if (size > pci_hotplug_mmio_pref_size)
1881 					return;
1882 				break;
1883 			default:
1884 				break;
1885 		}
1886 
1887 		dev_res = res_to_dev_res(add_list, res);
1888 		add_size = size - new_size;
1889 		if (add_size < dev_res->add_size) {
1890 			dev_res->add_size -= add_size;
1891 			pci_dbg(bridge, "bridge window %pR optional size shrunken by %pa\n",
1892 				res, &add_size);
1893 		} else {
1894 			pci_dbg(bridge, "bridge window %pR optional size removed\n",
1895 				res);
1896 			pci_dev_res_remove_from_list(add_list, res);
1897 		}
1898 		return;
1899 
1900 	} else {
1901 		return;
1902 	}
1903 
1904 	resource_set_size(res, new_size);
1905 
1906 	/* If the resource is part of the add_list, remove it now */
1907 	if (add_list)
1908 		pci_dev_res_remove_from_list(add_list, res);
1909 }
1910 
1911 static void remove_dev_resource(struct resource *avail, struct pci_dev *dev,
1912 				struct resource *res)
1913 {
1914 	resource_size_t size, align, tmp;
1915 
1916 	size = resource_size(res);
1917 	if (!size)
1918 		return;
1919 
1920 	align = pci_resource_alignment(dev, res);
1921 	align = align ? ALIGN(avail->start, align) - avail->start : 0;
1922 	tmp = align + size;
1923 	avail->start = min(avail->start + tmp, avail->end + 1);
1924 }
1925 
1926 static void remove_dev_resources(struct pci_dev *dev,
1927 				 struct resource available[PCI_P2P_BRIDGE_RESOURCE_NUM])
1928 {
1929 	struct resource *res, *b_win;
1930 	int idx;
1931 
1932 	pci_dev_for_each_resource(dev, res) {
1933 		b_win = pbus_select_window(dev->bus, res);
1934 		if (!b_win)
1935 			continue;
1936 
1937 		idx = pci_resource_num(dev->bus->self, b_win);
1938 		idx -= PCI_BRIDGE_RESOURCES;
1939 
1940 		remove_dev_resource(&available[idx], dev, res);
1941 	}
1942 }
1943 
1944 #define ALIGN_DOWN_IF_NONZERO(addr, align) \
1945 			((align) ? ALIGN_DOWN((addr), (align)) : (addr))
1946 
1947 /*
1948  * io, mmio and mmio_pref contain the total amount of bridge window space
1949  * available. This includes the minimal space needed to cover all the
1950  * existing devices on the bus and the possible extra space that can be
1951  * shared with the bridges.
1952  */
1953 static void pci_bus_distribute_available_resources(struct pci_bus *bus,
1954 		    struct list_head *add_list,
1955 		    struct resource available_in[PCI_P2P_BRIDGE_RESOURCE_NUM])
1956 {
1957 	struct resource available[PCI_P2P_BRIDGE_RESOURCE_NUM];
1958 	unsigned int normal_bridges = 0, hotplug_bridges = 0;
1959 	struct pci_dev *dev, *bridge = bus->self;
1960 	resource_size_t per_bridge[PCI_P2P_BRIDGE_RESOURCE_NUM];
1961 	resource_size_t align;
1962 	int i;
1963 
1964 	for (i = 0; i < PCI_P2P_BRIDGE_RESOURCE_NUM; i++) {
1965 		struct resource *res =
1966 			pci_resource_n(bridge, PCI_BRIDGE_RESOURCES + i);
1967 
1968 		available[i] = available_in[i];
1969 
1970 		/*
1971 		 * The alignment of this bridge is yet to be considered,
1972 		 * hence it must be done now before extending its bridge
1973 		 * window.
1974 		 */
1975 		align = pci_resource_alignment(bridge, res);
1976 		if (!resource_assigned(res) && align)
1977 			available[i].start = min(ALIGN(available[i].start, align),
1978 						 available[i].end + 1);
1979 
1980 		/*
1981 		 * Now that we have adjusted for alignment, update the
1982 		 * bridge window resources to fill as much remaining
1983 		 * resource space as possible.
1984 		 */
1985 		adjust_bridge_window(bridge, res, add_list,
1986 				     resource_size(&available[i]));
1987 	}
1988 
1989 	/*
1990 	 * Calculate how many hotplug bridges and normal bridges there
1991 	 * are on this bus.  We will distribute the additional available
1992 	 * resources between hotplug bridges.
1993 	 */
1994 	for_each_pci_bridge(dev, bus) {
1995 		if (dev->is_hotplug_bridge)
1996 			hotplug_bridges++;
1997 		else
1998 			normal_bridges++;
1999 	}
2000 
2001 	if (!(hotplug_bridges + normal_bridges))
2002 		return;
2003 
2004 	/*
2005 	 * Calculate the amount of space we can forward from "bus" to any
2006 	 * downstream buses, i.e., the space left over after assigning the
2007 	 * BARs and windows on "bus".
2008 	 */
2009 	list_for_each_entry(dev, &bus->devices, bus_list) {
2010 		if (!dev->is_virtfn)
2011 			remove_dev_resources(dev, available);
2012 	}
2013 
2014 	/*
2015 	 * If there is at least one hotplug bridge on this bus it gets all
2016 	 * the extra resource space that was left after the reductions
2017 	 * above.
2018 	 *
2019 	 * If there are no hotplug bridges the extra resource space is
2020 	 * split between non-hotplug bridges. This is to allow possible
2021 	 * hotplug bridges below them to get the extra space as well.
2022 	 */
2023 	for (i = 0; i < PCI_P2P_BRIDGE_RESOURCE_NUM; i++) {
2024 		per_bridge[i] = div64_ul(resource_size(&available[i]),
2025 					 hotplug_bridges ?: normal_bridges);
2026 	}
2027 
2028 	for_each_pci_bridge(dev, bus) {
2029 		struct resource *res;
2030 		struct pci_bus *b;
2031 
2032 		b = dev->subordinate;
2033 		if (!b)
2034 			continue;
2035 		if (hotplug_bridges && !dev->is_hotplug_bridge)
2036 			continue;
2037 
2038 		for (i = 0; i < PCI_P2P_BRIDGE_RESOURCE_NUM; i++) {
2039 			res = pci_resource_n(dev, PCI_BRIDGE_RESOURCES + i);
2040 
2041 			/*
2042 			 * Make sure the split resource space is properly
2043 			 * aligned for bridge windows (align it down to
2044 			 * avoid going above what is available).
2045 			 */
2046 			align = pci_resource_alignment(dev, res);
2047 			resource_set_size(&available[i],
2048 					  ALIGN_DOWN_IF_NONZERO(per_bridge[i],
2049 								align));
2050 
2051 			/*
2052 			 * The per_bridge holds the extra resource space
2053 			 * that can be added for each bridge but there is
2054 			 * the minimal already reserved as well so adjust
2055 			 * x.start down accordingly to cover the whole
2056 			 * space.
2057 			 */
2058 			available[i].start -= resource_size(res);
2059 		}
2060 
2061 		pci_bus_distribute_available_resources(b, add_list, available);
2062 
2063 		for (i = 0; i < PCI_P2P_BRIDGE_RESOURCE_NUM; i++)
2064 			available[i].start += available[i].end + 1;
2065 	}
2066 }
2067 
2068 static void pci_bridge_distribute_available_resources(struct pci_dev *bridge,
2069 						      struct list_head *add_list)
2070 {
2071 	struct resource *res, available[PCI_P2P_BRIDGE_RESOURCE_NUM];
2072 	unsigned int i;
2073 
2074 	if (!bridge->is_hotplug_bridge)
2075 		return;
2076 
2077 	pci_dbg(bridge, "distributing available resources\n");
2078 
2079 	/* Take the initial extra resources from the hotplug port */
2080 	for (i = 0; i < PCI_P2P_BRIDGE_RESOURCE_NUM; i++) {
2081 		res = pci_resource_n(bridge, PCI_BRIDGE_RESOURCES + i);
2082 		available[i] = *res;
2083 	}
2084 
2085 	pci_bus_distribute_available_resources(bridge->subordinate,
2086 					       add_list, available);
2087 }
2088 
2089 static bool pci_bridge_resources_not_assigned(struct pci_dev *dev)
2090 {
2091 	const struct resource *r;
2092 
2093 	/*
2094 	 * If the child device's resources are not yet assigned it means we
2095 	 * are configuring them (not the boot firmware), so we should be
2096 	 * able to extend the upstream bridge resources in the same way we
2097 	 * do with the normal hotplug case.
2098 	 */
2099 	r = &dev->resource[PCI_BRIDGE_IO_WINDOW];
2100 	if (r->flags && !(r->flags & IORESOURCE_STARTALIGN))
2101 		return false;
2102 	r = &dev->resource[PCI_BRIDGE_MEM_WINDOW];
2103 	if (r->flags && !(r->flags & IORESOURCE_STARTALIGN))
2104 		return false;
2105 	r = &dev->resource[PCI_BRIDGE_PREF_MEM_WINDOW];
2106 	if (r->flags && !(r->flags & IORESOURCE_STARTALIGN))
2107 		return false;
2108 
2109 	return true;
2110 }
2111 
2112 static void
2113 pci_root_bus_distribute_available_resources(struct pci_bus *bus,
2114 					    struct list_head *add_list)
2115 {
2116 	struct pci_dev *dev, *bridge = bus->self;
2117 
2118 	for_each_pci_bridge(dev, bus) {
2119 		struct pci_bus *b;
2120 
2121 		b = dev->subordinate;
2122 		if (!b)
2123 			continue;
2124 
2125 		/*
2126 		 * Need to check "bridge" here too because it is NULL
2127 		 * in case of root bus.
2128 		 */
2129 		if (bridge && pci_bridge_resources_not_assigned(dev))
2130 			pci_bridge_distribute_available_resources(dev, add_list);
2131 		else
2132 			pci_root_bus_distribute_available_resources(b, add_list);
2133 	}
2134 }
2135 
2136 static void pci_prepare_next_assign_round(struct list_head *fail_head,
2137 					  int tried_times,
2138 					  enum release_type rel_type)
2139 {
2140 	struct pci_dev_resource *fail_res;
2141 
2142 	pr_info("PCI: No. %d try to assign unassigned res\n", tried_times + 1);
2143 
2144 	/*
2145 	 * Try to release leaf bridge's resources that aren't big
2146 	 * enough to contain child device resources.
2147 	 */
2148 	list_for_each_entry(fail_res, fail_head, list) {
2149 		struct pci_bus *bus = fail_res->dev->bus;
2150 		struct resource *b_win;
2151 
2152 		b_win = pbus_select_window_for_type(bus, fail_res->flags);
2153 		if (!b_win)
2154 			continue;
2155 		pci_bus_release_bridge_resources(bus, b_win, rel_type);
2156 	}
2157 
2158 	/* Restore size and flags */
2159 	list_for_each_entry(fail_res, fail_head, list)
2160 		pci_dev_res_restore(fail_res);
2161 
2162 	pci_dev_res_free_list(fail_head);
2163 }
2164 
2165 /*
2166  * First try will not touch PCI bridge res.
2167  * Second and later try will clear small leaf bridge res.
2168  * Will stop till to the max depth if can not find good one.
2169  */
2170 void pci_assign_unassigned_root_bus_resources(struct pci_bus *bus)
2171 {
2172 	LIST_HEAD(realloc_head);
2173 	/* List of resources that want additional resources */
2174 	struct list_head *add_list = NULL;
2175 	int tried_times = 0;
2176 	enum release_type rel_type = leaf_only;
2177 	LIST_HEAD(fail_head);
2178 	int pci_try_num = 1;
2179 	enum enable_type enable_local;
2180 
2181 	/* Don't realloc if asked to do so */
2182 	enable_local = pci_realloc_detect(bus, pci_realloc_enable);
2183 	if (pci_realloc_enabled(enable_local)) {
2184 		int max_depth = pci_bus_get_depth(bus);
2185 
2186 		pci_try_num = max_depth + 1;
2187 		dev_info(&bus->dev, "max bus depth: %d pci_try_num: %d\n",
2188 			 max_depth, pci_try_num);
2189 	}
2190 
2191 	while (1) {
2192 		/*
2193 		 * Last try will use add_list, otherwise will try good to
2194 		 * have as must have, so can realloc parent bridge resource
2195 		 */
2196 		if (tried_times + 1 == pci_try_num)
2197 			add_list = &realloc_head;
2198 		/*
2199 		 * Depth first, calculate sizes and alignments of all
2200 		 * subordinate buses.
2201 		 */
2202 		__pci_bus_size_bridges(bus, add_list);
2203 
2204 		pci_root_bus_distribute_available_resources(bus, add_list);
2205 
2206 		/* Depth last, allocate resources and update the hardware. */
2207 		__pci_bus_assign_resources(bus, add_list, &fail_head);
2208 		if (WARN_ON_ONCE(add_list && !list_empty(add_list)))
2209 			pci_dev_res_free_list(add_list);
2210 		tried_times++;
2211 
2212 		/* Any device complain? */
2213 		if (list_empty(&fail_head))
2214 			break;
2215 
2216 		if (tried_times >= pci_try_num) {
2217 			if (enable_local == undefined) {
2218 				dev_info(&bus->dev,
2219 					 "Some PCI device resources are unassigned, try booting with pci=realloc\n");
2220 			} else if (enable_local == auto_enabled) {
2221 				dev_info(&bus->dev,
2222 					 "Automatically enabled pci realloc, if you have problem, try booting with pci=realloc=off\n");
2223 			}
2224 			pci_dev_res_free_list(&fail_head);
2225 			break;
2226 		}
2227 
2228 		/* Third times and later will not check if it is leaf */
2229 		if (tried_times + 1 > 2)
2230 			rel_type = whole_subtree;
2231 
2232 		pci_prepare_next_assign_round(&fail_head, tried_times, rel_type);
2233 	}
2234 
2235 	pci_bus_dump_resources(bus);
2236 }
2237 
2238 void pci_assign_unassigned_resources(void)
2239 {
2240 	struct pci_bus *root_bus;
2241 
2242 	list_for_each_entry(root_bus, &pci_root_buses, node) {
2243 		pci_assign_unassigned_root_bus_resources(root_bus);
2244 
2245 		/* Make sure the root bridge has a companion ACPI device */
2246 		if (ACPI_HANDLE(root_bus->bridge))
2247 			acpi_ioapic_add(ACPI_HANDLE(root_bus->bridge));
2248 	}
2249 }
2250 
2251 void pci_assign_unassigned_bridge_resources(struct pci_dev *bridge)
2252 {
2253 	struct pci_bus *parent = bridge->subordinate;
2254 	/* List of resources that want additional resources */
2255 	LIST_HEAD(add_list);
2256 	int tried_times = 0;
2257 	LIST_HEAD(fail_head);
2258 	int ret;
2259 
2260 	while (1) {
2261 		__pci_bus_size_bridges(parent, &add_list);
2262 
2263 		/*
2264 		 * Distribute remaining resources (if any) equally between
2265 		 * hotplug bridges below. This makes it possible to extend
2266 		 * the hierarchy later without running out of resources.
2267 		 */
2268 		pci_bridge_distribute_available_resources(bridge, &add_list);
2269 
2270 		__pci_bridge_assign_resources(bridge, &add_list, &fail_head);
2271 		if (WARN_ON_ONCE(!list_empty(&add_list)))
2272 			pci_dev_res_free_list(&add_list);
2273 		tried_times++;
2274 
2275 		if (list_empty(&fail_head))
2276 			break;
2277 
2278 		if (tried_times >= 2) {
2279 			/* Still fail, don't need to try more */
2280 			pci_dev_res_free_list(&fail_head);
2281 			break;
2282 		}
2283 
2284 		pci_prepare_next_assign_round(&fail_head, tried_times,
2285 					      whole_subtree);
2286 	}
2287 
2288 	ret = pci_reenable_device(bridge);
2289 	if (ret)
2290 		pci_err(bridge, "Error reenabling bridge (%d)\n", ret);
2291 	pci_set_master(bridge);
2292 }
2293 EXPORT_SYMBOL_GPL(pci_assign_unassigned_bridge_resources);
2294 
2295 /*
2296  * Walk to the root bus, find the bridge window relevant for @res and
2297  * release it when possible. If the bridge window contains assigned
2298  * resources, it cannot be released.
2299  */
2300 static int pbus_reassign_bridge_resources(struct pci_bus *bus, struct resource *res,
2301 					  struct list_head *saved)
2302 {
2303 	unsigned long type = res->flags;
2304 	struct pci_dev_resource *dev_res;
2305 	struct pci_dev *bridge = NULL;
2306 	LIST_HEAD(added);
2307 	LIST_HEAD(failed);
2308 	unsigned int i;
2309 	int ret = 0;
2310 
2311 	while (!pci_is_root_bus(bus)) {
2312 		bridge = bus->self;
2313 		res = pbus_select_window(bus, res);
2314 		if (!res)
2315 			break;
2316 
2317 		i = pci_resource_num(bridge, res);
2318 
2319 		/* Ignore BARs which are still in use */
2320 		if (!res->child) {
2321 			ret = pci_dev_res_add_to_list(saved, bridge, res, 0, 0);
2322 			if (ret)
2323 				return ret;
2324 
2325 			pci_release_resource(bridge, i);
2326 		} else {
2327 			const char *res_name = pci_resource_name(bridge, i);
2328 
2329 			pci_warn(bridge,
2330 				 "%s %pR: was not released (still contains assigned resources)\n",
2331 				 res_name, res);
2332 		}
2333 
2334 		bus = bus->parent;
2335 	}
2336 
2337 	if (!bridge)
2338 		return -ENOENT;
2339 
2340 	__pci_bus_size_bridges(bridge->subordinate, &added);
2341 	__pci_bridge_assign_resources(bridge, &added, &failed);
2342 	if (WARN_ON_ONCE(!list_empty(&added)))
2343 		pci_dev_res_free_list(&added);
2344 
2345 	if (!list_empty(&failed)) {
2346 		if (pci_required_resource_failed(&failed, type))
2347 			ret = -ENOSPC;
2348 		pci_dev_res_free_list(&failed);
2349 		if (ret)
2350 			return ret;
2351 
2352 		/* Only resources with unrelated types failed (again) */
2353 	}
2354 
2355 	list_for_each_entry(dev_res, saved, list) {
2356 		struct pci_dev *dev = dev_res->dev;
2357 
2358 		/* Skip the bridge we just assigned resources for */
2359 		if (bridge == dev)
2360 			continue;
2361 
2362 		if (!dev->subordinate)
2363 			continue;
2364 
2365 		pci_setup_bridge(dev->subordinate);
2366 	}
2367 
2368 	return 0;
2369 }
2370 
2371 int pci_do_resource_release_and_resize(struct pci_dev *pdev, int resno, int size,
2372 				       int exclude_bars)
2373 {
2374 	struct resource *res = pci_resource_n(pdev, resno);
2375 	struct pci_dev_resource *dev_res;
2376 	struct pci_bus *bus = pdev->bus;
2377 	struct resource *b_win, *r;
2378 	LIST_HEAD(saved);
2379 	unsigned int i;
2380 	int old, ret;
2381 
2382 	b_win = pbus_select_window(bus, res);
2383 	if (!b_win)
2384 		return -EINVAL;
2385 
2386 	old = pci_rebar_get_current_size(pdev, resno);
2387 	if (old < 0)
2388 		return old;
2389 
2390 	ret = pci_rebar_set_size(pdev, resno, size);
2391 	if (ret)
2392 		return ret;
2393 
2394 	pci_dev_for_each_resource(pdev, r, i) {
2395 		if (i >= PCI_BRIDGE_RESOURCES)
2396 			break;
2397 
2398 		if (exclude_bars & BIT(i))
2399 			continue;
2400 
2401 		if (b_win != pbus_select_window(bus, r))
2402 			continue;
2403 
2404 		ret = pci_dev_res_add_to_list(&saved, pdev, r, 0, 0);
2405 		if (ret)
2406 			goto restore;
2407 		pci_release_resource(pdev, i);
2408 	}
2409 
2410 	pci_resize_resource_set_size(pdev, resno, size);
2411 
2412 	if (!bus->self)
2413 		goto out;
2414 
2415 	down_read(&pci_bus_sem);
2416 	ret = pbus_reassign_bridge_resources(bus, res, &saved);
2417 	if (ret)
2418 		goto restore;
2419 
2420 out:
2421 	up_read(&pci_bus_sem);
2422 	pci_dev_res_free_list(&saved);
2423 	return ret;
2424 
2425 restore:
2426 	/*
2427 	 * Revert to the old configuration.
2428 	 *
2429 	 * BAR Size must be restored first because it affects the read-only
2430 	 * bits in BAR (the old address might not be restorable otherwise
2431 	 * due to low address bits).
2432 	 */
2433 	pci_rebar_set_size(pdev, resno, old);
2434 
2435 	list_for_each_entry(dev_res, &saved, list) {
2436 		struct resource *res = dev_res->res;
2437 		struct pci_dev *dev = dev_res->dev;
2438 
2439 		i = pci_resource_num(dev, res);
2440 
2441 		if (resource_assigned(res)) {
2442 			release_child_resources(res);
2443 			pci_release_resource(dev, i);
2444 		}
2445 
2446 		pci_dev_res_restore(dev_res);
2447 
2448 		if (pci_claim_resource(dev, i))
2449 			continue;
2450 
2451 		if (i < PCI_BRIDGE_RESOURCES) {
2452 			const char *res_name = pci_resource_name(dev, i);
2453 
2454 			pci_update_resource(dev, i);
2455 			pci_info(dev, "%s %pR: old value restored\n",
2456 				 res_name, res);
2457 		}
2458 		if (dev->subordinate)
2459 			pci_setup_bridge(dev->subordinate);
2460 	}
2461 	goto out;
2462 }
2463 
2464 void pci_assign_unassigned_bus_resources(struct pci_bus *bus)
2465 {
2466 	struct pci_dev *dev;
2467 	/* List of resources that want additional resources */
2468 	LIST_HEAD(add_list);
2469 
2470 	down_read(&pci_bus_sem);
2471 	for_each_pci_bridge(dev, bus)
2472 		if (pci_has_subordinate(dev))
2473 			__pci_bus_size_bridges(dev->subordinate, &add_list);
2474 	up_read(&pci_bus_sem);
2475 	__pci_bus_assign_resources(bus, &add_list, NULL);
2476 	if (WARN_ON_ONCE(!list_empty(&add_list)))
2477 		pci_dev_res_free_list(&add_list);
2478 }
2479 EXPORT_SYMBOL_GPL(pci_assign_unassigned_bus_resources);
2480