1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * PCI detection and setup code
4  */
5 
6 #include <linux/kernel.h>
7 #include <linux/delay.h>
8 #include <linux/init.h>
9 #include <linux/pci.h>
10 #include <linux/of_device.h>
11 #include <linux/of_pci.h>
12 #include <linux/pci_hotplug.h>
13 #include <linux/slab.h>
14 #include <linux/module.h>
15 #include <linux/cpumask.h>
16 #include <linux/aer.h>
17 #include <linux/acpi.h>
18 #include <linux/hypervisor.h>
19 #include <linux/irqdomain.h>
20 #include <linux/pm_runtime.h>
21 #include "pci.h"
22 
23 #define CARDBUS_LATENCY_TIMER	176	/* secondary latency timer */
24 #define CARDBUS_RESERVE_BUSNR	3
25 
26 static struct resource busn_resource = {
27 	.name	= "PCI busn",
28 	.start	= 0,
29 	.end	= 255,
30 	.flags	= IORESOURCE_BUS,
31 };
32 
33 /* Ugh.  Need to stop exporting this to modules. */
34 LIST_HEAD(pci_root_buses);
35 EXPORT_SYMBOL(pci_root_buses);
36 
37 static LIST_HEAD(pci_domain_busn_res_list);
38 
39 struct pci_domain_busn_res {
40 	struct list_head list;
41 	struct resource res;
42 	int domain_nr;
43 };
44 
get_pci_domain_busn_res(int domain_nr)45 static struct resource *get_pci_domain_busn_res(int domain_nr)
46 {
47 	struct pci_domain_busn_res *r;
48 
49 	list_for_each_entry(r, &pci_domain_busn_res_list, list)
50 		if (r->domain_nr == domain_nr)
51 			return &r->res;
52 
53 	r = kzalloc(sizeof(*r), GFP_KERNEL);
54 	if (!r)
55 		return NULL;
56 
57 	r->domain_nr = domain_nr;
58 	r->res.start = 0;
59 	r->res.end = 0xff;
60 	r->res.flags = IORESOURCE_BUS | IORESOURCE_PCI_FIXED;
61 
62 	list_add_tail(&r->list, &pci_domain_busn_res_list);
63 
64 	return &r->res;
65 }
66 
find_anything(struct device * dev,void * data)67 static int find_anything(struct device *dev, void *data)
68 {
69 	return 1;
70 }
71 
72 /*
73  * Some device drivers need know if PCI is initiated.
74  * Basically, we think PCI is not initiated when there
75  * is no device to be found on the pci_bus_type.
76  */
no_pci_devices(void)77 int no_pci_devices(void)
78 {
79 	struct device *dev;
80 	int no_devices;
81 
82 	dev = bus_find_device(&pci_bus_type, NULL, NULL, find_anything);
83 	no_devices = (dev == NULL);
84 	put_device(dev);
85 	return no_devices;
86 }
87 EXPORT_SYMBOL(no_pci_devices);
88 
89 /*
90  * PCI Bus Class
91  */
release_pcibus_dev(struct device * dev)92 static void release_pcibus_dev(struct device *dev)
93 {
94 	struct pci_bus *pci_bus = to_pci_bus(dev);
95 
96 	put_device(pci_bus->bridge);
97 	pci_bus_remove_resources(pci_bus);
98 	pci_release_bus_of_node(pci_bus);
99 	kfree(pci_bus);
100 }
101 
102 static struct class pcibus_class = {
103 	.name		= "pci_bus",
104 	.dev_release	= &release_pcibus_dev,
105 	.dev_groups	= pcibus_groups,
106 };
107 
pcibus_class_init(void)108 static int __init pcibus_class_init(void)
109 {
110 	return class_register(&pcibus_class);
111 }
112 postcore_initcall(pcibus_class_init);
113 
pci_size(u64 base,u64 maxbase,u64 mask)114 static u64 pci_size(u64 base, u64 maxbase, u64 mask)
115 {
116 	u64 size = mask & maxbase;	/* Find the significant bits */
117 	if (!size)
118 		return 0;
119 
120 	/*
121 	 * Get the lowest of them to find the decode size, and from that
122 	 * the extent.
123 	 */
124 	size = (size & ~(size-1)) - 1;
125 
126 	/*
127 	 * base == maxbase can be valid only if the BAR has already been
128 	 * programmed with all 1s.
129 	 */
130 	if (base == maxbase && ((base | size) & mask) != mask)
131 		return 0;
132 
133 	return size;
134 }
135 
decode_bar(struct pci_dev * dev,u32 bar)136 static inline unsigned long decode_bar(struct pci_dev *dev, u32 bar)
137 {
138 	u32 mem_type;
139 	unsigned long flags;
140 
141 	if ((bar & PCI_BASE_ADDRESS_SPACE) == PCI_BASE_ADDRESS_SPACE_IO) {
142 		flags = bar & ~PCI_BASE_ADDRESS_IO_MASK;
143 		flags |= IORESOURCE_IO;
144 		return flags;
145 	}
146 
147 	flags = bar & ~PCI_BASE_ADDRESS_MEM_MASK;
148 	flags |= IORESOURCE_MEM;
149 	if (flags & PCI_BASE_ADDRESS_MEM_PREFETCH)
150 		flags |= IORESOURCE_PREFETCH;
151 
152 	mem_type = bar & PCI_BASE_ADDRESS_MEM_TYPE_MASK;
153 	switch (mem_type) {
154 	case PCI_BASE_ADDRESS_MEM_TYPE_32:
155 		break;
156 	case PCI_BASE_ADDRESS_MEM_TYPE_1M:
157 		/* 1M mem BAR treated as 32-bit BAR */
158 		break;
159 	case PCI_BASE_ADDRESS_MEM_TYPE_64:
160 		flags |= IORESOURCE_MEM_64;
161 		break;
162 	default:
163 		/* mem unknown type treated as 32-bit BAR */
164 		break;
165 	}
166 	return flags;
167 }
168 
169 #define PCI_COMMAND_DECODE_ENABLE	(PCI_COMMAND_MEMORY | PCI_COMMAND_IO)
170 
171 /**
172  * pci_read_base - Read a PCI BAR
173  * @dev: the PCI device
174  * @type: type of the BAR
175  * @res: resource buffer to be filled in
176  * @pos: BAR position in the config space
177  *
178  * Returns 1 if the BAR is 64-bit, or 0 if 32-bit.
179  */
__pci_read_base(struct pci_dev * dev,enum pci_bar_type type,struct resource * res,unsigned int pos)180 int __pci_read_base(struct pci_dev *dev, enum pci_bar_type type,
181 		    struct resource *res, unsigned int pos)
182 {
183 	u32 l = 0, sz = 0, mask;
184 	u64 l64, sz64, mask64;
185 	u16 orig_cmd;
186 	struct pci_bus_region region, inverted_region;
187 
188 	mask = type ? PCI_ROM_ADDRESS_MASK : ~0;
189 
190 	/* No printks while decoding is disabled! */
191 	if (!dev->mmio_always_on) {
192 		pci_read_config_word(dev, PCI_COMMAND, &orig_cmd);
193 		if (orig_cmd & PCI_COMMAND_DECODE_ENABLE) {
194 			pci_write_config_word(dev, PCI_COMMAND,
195 				orig_cmd & ~PCI_COMMAND_DECODE_ENABLE);
196 		}
197 	}
198 
199 	res->name = pci_name(dev);
200 
201 	pci_read_config_dword(dev, pos, &l);
202 	pci_write_config_dword(dev, pos, l | mask);
203 	pci_read_config_dword(dev, pos, &sz);
204 	pci_write_config_dword(dev, pos, l);
205 
206 	/*
207 	 * All bits set in sz means the device isn't working properly.
208 	 * If the BAR isn't implemented, all bits must be 0.  If it's a
209 	 * memory BAR or a ROM, bit 0 must be clear; if it's an io BAR, bit
210 	 * 1 must be clear.
211 	 */
212 	if (sz == 0xffffffff)
213 		sz = 0;
214 
215 	/*
216 	 * I don't know how l can have all bits set.  Copied from old code.
217 	 * Maybe it fixes a bug on some ancient platform.
218 	 */
219 	if (l == 0xffffffff)
220 		l = 0;
221 
222 	if (type == pci_bar_unknown) {
223 		res->flags = decode_bar(dev, l);
224 		res->flags |= IORESOURCE_SIZEALIGN;
225 		if (res->flags & IORESOURCE_IO) {
226 			l64 = l & PCI_BASE_ADDRESS_IO_MASK;
227 			sz64 = sz & PCI_BASE_ADDRESS_IO_MASK;
228 			mask64 = PCI_BASE_ADDRESS_IO_MASK & (u32)IO_SPACE_LIMIT;
229 		} else {
230 			l64 = l & PCI_BASE_ADDRESS_MEM_MASK;
231 			sz64 = sz & PCI_BASE_ADDRESS_MEM_MASK;
232 			mask64 = (u32)PCI_BASE_ADDRESS_MEM_MASK;
233 		}
234 	} else {
235 		if (l & PCI_ROM_ADDRESS_ENABLE)
236 			res->flags |= IORESOURCE_ROM_ENABLE;
237 		l64 = l & PCI_ROM_ADDRESS_MASK;
238 		sz64 = sz & PCI_ROM_ADDRESS_MASK;
239 		mask64 = PCI_ROM_ADDRESS_MASK;
240 	}
241 
242 	if (res->flags & IORESOURCE_MEM_64) {
243 		pci_read_config_dword(dev, pos + 4, &l);
244 		pci_write_config_dword(dev, pos + 4, ~0);
245 		pci_read_config_dword(dev, pos + 4, &sz);
246 		pci_write_config_dword(dev, pos + 4, l);
247 
248 		l64 |= ((u64)l << 32);
249 		sz64 |= ((u64)sz << 32);
250 		mask64 |= ((u64)~0 << 32);
251 	}
252 
253 	if (!dev->mmio_always_on && (orig_cmd & PCI_COMMAND_DECODE_ENABLE))
254 		pci_write_config_word(dev, PCI_COMMAND, orig_cmd);
255 
256 	if (!sz64)
257 		goto fail;
258 
259 	sz64 = pci_size(l64, sz64, mask64);
260 	if (!sz64) {
261 		pci_info(dev, FW_BUG "reg 0x%x: invalid BAR (can't size)\n",
262 			 pos);
263 		goto fail;
264 	}
265 
266 	if (res->flags & IORESOURCE_MEM_64) {
267 		if ((sizeof(pci_bus_addr_t) < 8 || sizeof(resource_size_t) < 8)
268 		    && sz64 > 0x100000000ULL) {
269 			res->flags |= IORESOURCE_UNSET | IORESOURCE_DISABLED;
270 			res->start = 0;
271 			res->end = 0;
272 			pci_err(dev, "reg 0x%x: can't handle BAR larger than 4GB (size %#010llx)\n",
273 				pos, (unsigned long long)sz64);
274 			goto out;
275 		}
276 
277 		if ((sizeof(pci_bus_addr_t) < 8) && l) {
278 			/* Above 32-bit boundary; try to reallocate */
279 			res->flags |= IORESOURCE_UNSET;
280 			res->start = 0;
281 			res->end = sz64;
282 			pci_info(dev, "reg 0x%x: can't handle BAR above 4GB (bus address %#010llx)\n",
283 				 pos, (unsigned long long)l64);
284 			goto out;
285 		}
286 	}
287 
288 	region.start = l64;
289 	region.end = l64 + sz64;
290 
291 	pcibios_bus_to_resource(dev->bus, res, &region);
292 	pcibios_resource_to_bus(dev->bus, &inverted_region, res);
293 
294 	/*
295 	 * If "A" is a BAR value (a bus address), "bus_to_resource(A)" is
296 	 * the corresponding resource address (the physical address used by
297 	 * the CPU.  Converting that resource address back to a bus address
298 	 * should yield the original BAR value:
299 	 *
300 	 *     resource_to_bus(bus_to_resource(A)) == A
301 	 *
302 	 * If it doesn't, CPU accesses to "bus_to_resource(A)" will not
303 	 * be claimed by the device.
304 	 */
305 	if (inverted_region.start != region.start) {
306 		res->flags |= IORESOURCE_UNSET;
307 		res->start = 0;
308 		res->end = region.end - region.start;
309 		pci_info(dev, "reg 0x%x: initial BAR value %#010llx invalid\n",
310 			 pos, (unsigned long long)region.start);
311 	}
312 
313 	goto out;
314 
315 
316 fail:
317 	res->flags = 0;
318 out:
319 	if (res->flags)
320 		pci_printk(KERN_DEBUG, dev, "reg 0x%x: %pR\n", pos, res);
321 
322 	return (res->flags & IORESOURCE_MEM_64) ? 1 : 0;
323 }
324 
pci_read_bases(struct pci_dev * dev,unsigned int howmany,int rom)325 static void pci_read_bases(struct pci_dev *dev, unsigned int howmany, int rom)
326 {
327 	unsigned int pos, reg;
328 
329 	if (dev->non_compliant_bars)
330 		return;
331 
332 	/* Per PCIe r4.0, sec 9.3.4.1.11, the VF BARs are all RO Zero */
333 	if (dev->is_virtfn)
334 		return;
335 
336 	for (pos = 0; pos < howmany; pos++) {
337 		struct resource *res = &dev->resource[pos];
338 		reg = PCI_BASE_ADDRESS_0 + (pos << 2);
339 		pos += __pci_read_base(dev, pci_bar_unknown, res, reg);
340 	}
341 
342 	if (rom) {
343 		struct resource *res = &dev->resource[PCI_ROM_RESOURCE];
344 		dev->rom_base_reg = rom;
345 		res->flags = IORESOURCE_MEM | IORESOURCE_PREFETCH |
346 				IORESOURCE_READONLY | IORESOURCE_SIZEALIGN;
347 		__pci_read_base(dev, pci_bar_mem32, res, rom);
348 	}
349 }
350 
pci_read_bridge_windows(struct pci_dev * bridge)351 static void pci_read_bridge_windows(struct pci_dev *bridge)
352 {
353 	u16 io;
354 	u32 pmem, tmp;
355 
356 	pci_read_config_word(bridge, PCI_IO_BASE, &io);
357 	if (!io) {
358 		pci_write_config_word(bridge, PCI_IO_BASE, 0xe0f0);
359 		pci_read_config_word(bridge, PCI_IO_BASE, &io);
360 		pci_write_config_word(bridge, PCI_IO_BASE, 0x0);
361 	}
362 	if (io)
363 		bridge->io_window = 1;
364 
365 	/*
366 	 * DECchip 21050 pass 2 errata: the bridge may miss an address
367 	 * disconnect boundary by one PCI data phase.  Workaround: do not
368 	 * use prefetching on this device.
369 	 */
370 	if (bridge->vendor == PCI_VENDOR_ID_DEC && bridge->device == 0x0001)
371 		return;
372 
373 	pci_read_config_dword(bridge, PCI_PREF_MEMORY_BASE, &pmem);
374 	if (!pmem) {
375 		pci_write_config_dword(bridge, PCI_PREF_MEMORY_BASE,
376 					       0xffe0fff0);
377 		pci_read_config_dword(bridge, PCI_PREF_MEMORY_BASE, &pmem);
378 		pci_write_config_dword(bridge, PCI_PREF_MEMORY_BASE, 0x0);
379 	}
380 	if (!pmem)
381 		return;
382 
383 	bridge->pref_window = 1;
384 
385 	if ((pmem & PCI_PREF_RANGE_TYPE_MASK) == PCI_PREF_RANGE_TYPE_64) {
386 
387 		/*
388 		 * Bridge claims to have a 64-bit prefetchable memory
389 		 * window; verify that the upper bits are actually
390 		 * writable.
391 		 */
392 		pci_read_config_dword(bridge, PCI_PREF_BASE_UPPER32, &pmem);
393 		pci_write_config_dword(bridge, PCI_PREF_BASE_UPPER32,
394 				       0xffffffff);
395 		pci_read_config_dword(bridge, PCI_PREF_BASE_UPPER32, &tmp);
396 		pci_write_config_dword(bridge, PCI_PREF_BASE_UPPER32, pmem);
397 		if (tmp)
398 			bridge->pref_64_window = 1;
399 	}
400 }
401 
pci_read_bridge_io(struct pci_bus * child)402 static void pci_read_bridge_io(struct pci_bus *child)
403 {
404 	struct pci_dev *dev = child->self;
405 	u8 io_base_lo, io_limit_lo;
406 	unsigned long io_mask, io_granularity, base, limit;
407 	struct pci_bus_region region;
408 	struct resource *res;
409 
410 	io_mask = PCI_IO_RANGE_MASK;
411 	io_granularity = 0x1000;
412 	if (dev->io_window_1k) {
413 		/* Support 1K I/O space granularity */
414 		io_mask = PCI_IO_1K_RANGE_MASK;
415 		io_granularity = 0x400;
416 	}
417 
418 	res = child->resource[0];
419 	pci_read_config_byte(dev, PCI_IO_BASE, &io_base_lo);
420 	pci_read_config_byte(dev, PCI_IO_LIMIT, &io_limit_lo);
421 	base = (io_base_lo & io_mask) << 8;
422 	limit = (io_limit_lo & io_mask) << 8;
423 
424 	if ((io_base_lo & PCI_IO_RANGE_TYPE_MASK) == PCI_IO_RANGE_TYPE_32) {
425 		u16 io_base_hi, io_limit_hi;
426 
427 		pci_read_config_word(dev, PCI_IO_BASE_UPPER16, &io_base_hi);
428 		pci_read_config_word(dev, PCI_IO_LIMIT_UPPER16, &io_limit_hi);
429 		base |= ((unsigned long) io_base_hi << 16);
430 		limit |= ((unsigned long) io_limit_hi << 16);
431 	}
432 
433 	if (base <= limit) {
434 		res->flags = (io_base_lo & PCI_IO_RANGE_TYPE_MASK) | IORESOURCE_IO;
435 		region.start = base;
436 		region.end = limit + io_granularity - 1;
437 		pcibios_bus_to_resource(dev->bus, res, &region);
438 		pci_printk(KERN_DEBUG, dev, "  bridge window %pR\n", res);
439 	}
440 }
441 
pci_read_bridge_mmio(struct pci_bus * child)442 static void pci_read_bridge_mmio(struct pci_bus *child)
443 {
444 	struct pci_dev *dev = child->self;
445 	u16 mem_base_lo, mem_limit_lo;
446 	unsigned long base, limit;
447 	struct pci_bus_region region;
448 	struct resource *res;
449 
450 	res = child->resource[1];
451 	pci_read_config_word(dev, PCI_MEMORY_BASE, &mem_base_lo);
452 	pci_read_config_word(dev, PCI_MEMORY_LIMIT, &mem_limit_lo);
453 	base = ((unsigned long) mem_base_lo & PCI_MEMORY_RANGE_MASK) << 16;
454 	limit = ((unsigned long) mem_limit_lo & PCI_MEMORY_RANGE_MASK) << 16;
455 	if (base <= limit) {
456 		res->flags = (mem_base_lo & PCI_MEMORY_RANGE_TYPE_MASK) | IORESOURCE_MEM;
457 		region.start = base;
458 		region.end = limit + 0xfffff;
459 		pcibios_bus_to_resource(dev->bus, res, &region);
460 		pci_printk(KERN_DEBUG, dev, "  bridge window %pR\n", res);
461 	}
462 }
463 
pci_read_bridge_mmio_pref(struct pci_bus * child)464 static void pci_read_bridge_mmio_pref(struct pci_bus *child)
465 {
466 	struct pci_dev *dev = child->self;
467 	u16 mem_base_lo, mem_limit_lo;
468 	u64 base64, limit64;
469 	pci_bus_addr_t base, limit;
470 	struct pci_bus_region region;
471 	struct resource *res;
472 
473 	res = child->resource[2];
474 	pci_read_config_word(dev, PCI_PREF_MEMORY_BASE, &mem_base_lo);
475 	pci_read_config_word(dev, PCI_PREF_MEMORY_LIMIT, &mem_limit_lo);
476 	base64 = (mem_base_lo & PCI_PREF_RANGE_MASK) << 16;
477 	limit64 = (mem_limit_lo & PCI_PREF_RANGE_MASK) << 16;
478 
479 	if ((mem_base_lo & PCI_PREF_RANGE_TYPE_MASK) == PCI_PREF_RANGE_TYPE_64) {
480 		u32 mem_base_hi, mem_limit_hi;
481 
482 		pci_read_config_dword(dev, PCI_PREF_BASE_UPPER32, &mem_base_hi);
483 		pci_read_config_dword(dev, PCI_PREF_LIMIT_UPPER32, &mem_limit_hi);
484 
485 		/*
486 		 * Some bridges set the base > limit by default, and some
487 		 * (broken) BIOSes do not initialize them.  If we find
488 		 * this, just assume they are not being used.
489 		 */
490 		if (mem_base_hi <= mem_limit_hi) {
491 			base64 |= (u64) mem_base_hi << 32;
492 			limit64 |= (u64) mem_limit_hi << 32;
493 		}
494 	}
495 
496 	base = (pci_bus_addr_t) base64;
497 	limit = (pci_bus_addr_t) limit64;
498 
499 	if (base != base64) {
500 		pci_err(dev, "can't handle bridge window above 4GB (bus address %#010llx)\n",
501 			(unsigned long long) base64);
502 		return;
503 	}
504 
505 	if (base <= limit) {
506 		res->flags = (mem_base_lo & PCI_PREF_RANGE_TYPE_MASK) |
507 					 IORESOURCE_MEM | IORESOURCE_PREFETCH;
508 		if (res->flags & PCI_PREF_RANGE_TYPE_64)
509 			res->flags |= IORESOURCE_MEM_64;
510 		region.start = base;
511 		region.end = limit + 0xfffff;
512 		pcibios_bus_to_resource(dev->bus, res, &region);
513 		pci_printk(KERN_DEBUG, dev, "  bridge window %pR\n", res);
514 	}
515 }
516 
pci_read_bridge_bases(struct pci_bus * child)517 void pci_read_bridge_bases(struct pci_bus *child)
518 {
519 	struct pci_dev *dev = child->self;
520 	struct resource *res;
521 	int i;
522 
523 	if (pci_is_root_bus(child))	/* It's a host bus, nothing to read */
524 		return;
525 
526 	pci_info(dev, "PCI bridge to %pR%s\n",
527 		 &child->busn_res,
528 		 dev->transparent ? " (subtractive decode)" : "");
529 
530 	pci_bus_remove_resources(child);
531 	for (i = 0; i < PCI_BRIDGE_RESOURCE_NUM; i++)
532 		child->resource[i] = &dev->resource[PCI_BRIDGE_RESOURCES+i];
533 
534 	pci_read_bridge_io(child);
535 	pci_read_bridge_mmio(child);
536 	pci_read_bridge_mmio_pref(child);
537 
538 	if (dev->transparent) {
539 		pci_bus_for_each_resource(child->parent, res, i) {
540 			if (res && res->flags) {
541 				pci_bus_add_resource(child, res,
542 						     PCI_SUBTRACTIVE_DECODE);
543 				pci_printk(KERN_DEBUG, dev,
544 					   "  bridge window %pR (subtractive decode)\n",
545 					   res);
546 			}
547 		}
548 	}
549 }
550 
pci_alloc_bus(struct pci_bus * parent)551 static struct pci_bus *pci_alloc_bus(struct pci_bus *parent)
552 {
553 	struct pci_bus *b;
554 
555 	b = kzalloc(sizeof(*b), GFP_KERNEL);
556 	if (!b)
557 		return NULL;
558 
559 	INIT_LIST_HEAD(&b->node);
560 	INIT_LIST_HEAD(&b->children);
561 	INIT_LIST_HEAD(&b->devices);
562 	INIT_LIST_HEAD(&b->slots);
563 	INIT_LIST_HEAD(&b->resources);
564 	b->max_bus_speed = PCI_SPEED_UNKNOWN;
565 	b->cur_bus_speed = PCI_SPEED_UNKNOWN;
566 #ifdef CONFIG_PCI_DOMAINS_GENERIC
567 	if (parent)
568 		b->domain_nr = parent->domain_nr;
569 #endif
570 	return b;
571 }
572 
devm_pci_release_host_bridge_dev(struct device * dev)573 static void devm_pci_release_host_bridge_dev(struct device *dev)
574 {
575 	struct pci_host_bridge *bridge = to_pci_host_bridge(dev);
576 
577 	if (bridge->release_fn)
578 		bridge->release_fn(bridge);
579 
580 	pci_free_resource_list(&bridge->windows);
581 }
582 
pci_release_host_bridge_dev(struct device * dev)583 static void pci_release_host_bridge_dev(struct device *dev)
584 {
585 	devm_pci_release_host_bridge_dev(dev);
586 	kfree(to_pci_host_bridge(dev));
587 }
588 
pci_init_host_bridge(struct pci_host_bridge * bridge)589 static void pci_init_host_bridge(struct pci_host_bridge *bridge)
590 {
591 	INIT_LIST_HEAD(&bridge->windows);
592 
593 	/*
594 	 * We assume we can manage these PCIe features.  Some systems may
595 	 * reserve these for use by the platform itself, e.g., an ACPI BIOS
596 	 * may implement its own AER handling and use _OSC to prevent the
597 	 * OS from interfering.
598 	 */
599 	bridge->native_aer = 1;
600 	bridge->native_pcie_hotplug = 1;
601 	bridge->native_shpc_hotplug = 1;
602 	bridge->native_pme = 1;
603 	bridge->native_ltr = 1;
604 }
605 
pci_alloc_host_bridge(size_t priv)606 struct pci_host_bridge *pci_alloc_host_bridge(size_t priv)
607 {
608 	struct pci_host_bridge *bridge;
609 
610 	bridge = kzalloc(sizeof(*bridge) + priv, GFP_KERNEL);
611 	if (!bridge)
612 		return NULL;
613 
614 	pci_init_host_bridge(bridge);
615 	bridge->dev.release = pci_release_host_bridge_dev;
616 
617 	return bridge;
618 }
619 EXPORT_SYMBOL(pci_alloc_host_bridge);
620 
devm_pci_alloc_host_bridge(struct device * dev,size_t priv)621 struct pci_host_bridge *devm_pci_alloc_host_bridge(struct device *dev,
622 						   size_t priv)
623 {
624 	struct pci_host_bridge *bridge;
625 
626 	bridge = devm_kzalloc(dev, sizeof(*bridge) + priv, GFP_KERNEL);
627 	if (!bridge)
628 		return NULL;
629 
630 	pci_init_host_bridge(bridge);
631 	bridge->dev.release = devm_pci_release_host_bridge_dev;
632 
633 	return bridge;
634 }
635 EXPORT_SYMBOL(devm_pci_alloc_host_bridge);
636 
pci_free_host_bridge(struct pci_host_bridge * bridge)637 void pci_free_host_bridge(struct pci_host_bridge *bridge)
638 {
639 	pci_free_resource_list(&bridge->windows);
640 
641 	kfree(bridge);
642 }
643 EXPORT_SYMBOL(pci_free_host_bridge);
644 
645 static const unsigned char pcix_bus_speed[] = {
646 	PCI_SPEED_UNKNOWN,		/* 0 */
647 	PCI_SPEED_66MHz_PCIX,		/* 1 */
648 	PCI_SPEED_100MHz_PCIX,		/* 2 */
649 	PCI_SPEED_133MHz_PCIX,		/* 3 */
650 	PCI_SPEED_UNKNOWN,		/* 4 */
651 	PCI_SPEED_66MHz_PCIX_ECC,	/* 5 */
652 	PCI_SPEED_100MHz_PCIX_ECC,	/* 6 */
653 	PCI_SPEED_133MHz_PCIX_ECC,	/* 7 */
654 	PCI_SPEED_UNKNOWN,		/* 8 */
655 	PCI_SPEED_66MHz_PCIX_266,	/* 9 */
656 	PCI_SPEED_100MHz_PCIX_266,	/* A */
657 	PCI_SPEED_133MHz_PCIX_266,	/* B */
658 	PCI_SPEED_UNKNOWN,		/* C */
659 	PCI_SPEED_66MHz_PCIX_533,	/* D */
660 	PCI_SPEED_100MHz_PCIX_533,	/* E */
661 	PCI_SPEED_133MHz_PCIX_533	/* F */
662 };
663 
664 const unsigned char pcie_link_speed[] = {
665 	PCI_SPEED_UNKNOWN,		/* 0 */
666 	PCIE_SPEED_2_5GT,		/* 1 */
667 	PCIE_SPEED_5_0GT,		/* 2 */
668 	PCIE_SPEED_8_0GT,		/* 3 */
669 	PCIE_SPEED_16_0GT,		/* 4 */
670 	PCIE_SPEED_32_0GT,		/* 5 */
671 	PCI_SPEED_UNKNOWN,		/* 6 */
672 	PCI_SPEED_UNKNOWN,		/* 7 */
673 	PCI_SPEED_UNKNOWN,		/* 8 */
674 	PCI_SPEED_UNKNOWN,		/* 9 */
675 	PCI_SPEED_UNKNOWN,		/* A */
676 	PCI_SPEED_UNKNOWN,		/* B */
677 	PCI_SPEED_UNKNOWN,		/* C */
678 	PCI_SPEED_UNKNOWN,		/* D */
679 	PCI_SPEED_UNKNOWN,		/* E */
680 	PCI_SPEED_UNKNOWN		/* F */
681 };
682 
pcie_update_link_speed(struct pci_bus * bus,u16 linksta)683 void pcie_update_link_speed(struct pci_bus *bus, u16 linksta)
684 {
685 	bus->cur_bus_speed = pcie_link_speed[linksta & PCI_EXP_LNKSTA_CLS];
686 }
687 EXPORT_SYMBOL_GPL(pcie_update_link_speed);
688 
689 static unsigned char agp_speeds[] = {
690 	AGP_UNKNOWN,
691 	AGP_1X,
692 	AGP_2X,
693 	AGP_4X,
694 	AGP_8X
695 };
696 
agp_speed(int agp3,int agpstat)697 static enum pci_bus_speed agp_speed(int agp3, int agpstat)
698 {
699 	int index = 0;
700 
701 	if (agpstat & 4)
702 		index = 3;
703 	else if (agpstat & 2)
704 		index = 2;
705 	else if (agpstat & 1)
706 		index = 1;
707 	else
708 		goto out;
709 
710 	if (agp3) {
711 		index += 2;
712 		if (index == 5)
713 			index = 0;
714 	}
715 
716  out:
717 	return agp_speeds[index];
718 }
719 
pci_set_bus_speed(struct pci_bus * bus)720 static void pci_set_bus_speed(struct pci_bus *bus)
721 {
722 	struct pci_dev *bridge = bus->self;
723 	int pos;
724 
725 	pos = pci_find_capability(bridge, PCI_CAP_ID_AGP);
726 	if (!pos)
727 		pos = pci_find_capability(bridge, PCI_CAP_ID_AGP3);
728 	if (pos) {
729 		u32 agpstat, agpcmd;
730 
731 		pci_read_config_dword(bridge, pos + PCI_AGP_STATUS, &agpstat);
732 		bus->max_bus_speed = agp_speed(agpstat & 8, agpstat & 7);
733 
734 		pci_read_config_dword(bridge, pos + PCI_AGP_COMMAND, &agpcmd);
735 		bus->cur_bus_speed = agp_speed(agpstat & 8, agpcmd & 7);
736 	}
737 
738 	pos = pci_find_capability(bridge, PCI_CAP_ID_PCIX);
739 	if (pos) {
740 		u16 status;
741 		enum pci_bus_speed max;
742 
743 		pci_read_config_word(bridge, pos + PCI_X_BRIDGE_SSTATUS,
744 				     &status);
745 
746 		if (status & PCI_X_SSTATUS_533MHZ) {
747 			max = PCI_SPEED_133MHz_PCIX_533;
748 		} else if (status & PCI_X_SSTATUS_266MHZ) {
749 			max = PCI_SPEED_133MHz_PCIX_266;
750 		} else if (status & PCI_X_SSTATUS_133MHZ) {
751 			if ((status & PCI_X_SSTATUS_VERS) == PCI_X_SSTATUS_V2)
752 				max = PCI_SPEED_133MHz_PCIX_ECC;
753 			else
754 				max = PCI_SPEED_133MHz_PCIX;
755 		} else {
756 			max = PCI_SPEED_66MHz_PCIX;
757 		}
758 
759 		bus->max_bus_speed = max;
760 		bus->cur_bus_speed = pcix_bus_speed[
761 			(status & PCI_X_SSTATUS_FREQ) >> 6];
762 
763 		return;
764 	}
765 
766 	if (pci_is_pcie(bridge)) {
767 		u32 linkcap;
768 		u16 linksta;
769 
770 		pcie_capability_read_dword(bridge, PCI_EXP_LNKCAP, &linkcap);
771 		bus->max_bus_speed = pcie_link_speed[linkcap & PCI_EXP_LNKCAP_SLS];
772 
773 		pcie_capability_read_word(bridge, PCI_EXP_LNKSTA, &linksta);
774 		pcie_update_link_speed(bus, linksta);
775 	}
776 }
777 
pci_host_bridge_msi_domain(struct pci_bus * bus)778 static struct irq_domain *pci_host_bridge_msi_domain(struct pci_bus *bus)
779 {
780 	struct irq_domain *d;
781 
782 	/*
783 	 * Any firmware interface that can resolve the msi_domain
784 	 * should be called from here.
785 	 */
786 	d = pci_host_bridge_of_msi_domain(bus);
787 	if (!d)
788 		d = pci_host_bridge_acpi_msi_domain(bus);
789 
790 #ifdef CONFIG_PCI_MSI_IRQ_DOMAIN
791 	/*
792 	 * If no IRQ domain was found via the OF tree, try looking it up
793 	 * directly through the fwnode_handle.
794 	 */
795 	if (!d) {
796 		struct fwnode_handle *fwnode = pci_root_bus_fwnode(bus);
797 
798 		if (fwnode)
799 			d = irq_find_matching_fwnode(fwnode,
800 						     DOMAIN_BUS_PCI_MSI);
801 	}
802 #endif
803 
804 	return d;
805 }
806 
pci_set_bus_msi_domain(struct pci_bus * bus)807 static void pci_set_bus_msi_domain(struct pci_bus *bus)
808 {
809 	struct irq_domain *d;
810 	struct pci_bus *b;
811 
812 	/*
813 	 * The bus can be a root bus, a subordinate bus, or a virtual bus
814 	 * created by an SR-IOV device.  Walk up to the first bridge device
815 	 * found or derive the domain from the host bridge.
816 	 */
817 	for (b = bus, d = NULL; !d && !pci_is_root_bus(b); b = b->parent) {
818 		if (b->self)
819 			d = dev_get_msi_domain(&b->self->dev);
820 	}
821 
822 	if (!d)
823 		d = pci_host_bridge_msi_domain(b);
824 
825 	dev_set_msi_domain(&bus->dev, d);
826 }
827 
pci_register_host_bridge(struct pci_host_bridge * bridge)828 static int pci_register_host_bridge(struct pci_host_bridge *bridge)
829 {
830 	struct device *parent = bridge->dev.parent;
831 	struct resource_entry *window, *n;
832 	struct pci_bus *bus, *b;
833 	resource_size_t offset;
834 	LIST_HEAD(resources);
835 	struct resource *res;
836 	char addr[64], *fmt;
837 	const char *name;
838 	int err;
839 
840 	bus = pci_alloc_bus(NULL);
841 	if (!bus)
842 		return -ENOMEM;
843 
844 	bridge->bus = bus;
845 
846 	/* Temporarily move resources off the list */
847 	list_splice_init(&bridge->windows, &resources);
848 	bus->sysdata = bridge->sysdata;
849 	bus->msi = bridge->msi;
850 	bus->ops = bridge->ops;
851 	bus->number = bus->busn_res.start = bridge->busnr;
852 #ifdef CONFIG_PCI_DOMAINS_GENERIC
853 	bus->domain_nr = pci_bus_find_domain_nr(bus, parent);
854 #endif
855 
856 	b = pci_find_bus(pci_domain_nr(bus), bridge->busnr);
857 	if (b) {
858 		/* Ignore it if we already got here via a different bridge */
859 		dev_dbg(&b->dev, "bus already known\n");
860 		err = -EEXIST;
861 		goto free;
862 	}
863 
864 	dev_set_name(&bridge->dev, "pci%04x:%02x", pci_domain_nr(bus),
865 		     bridge->busnr);
866 
867 	err = pcibios_root_bridge_prepare(bridge);
868 	if (err)
869 		goto free;
870 
871 	err = device_register(&bridge->dev);
872 	if (err) {
873 		put_device(&bridge->dev);
874 		goto free;
875 	}
876 	bus->bridge = get_device(&bridge->dev);
877 	device_enable_async_suspend(bus->bridge);
878 	pci_set_bus_of_node(bus);
879 	pci_set_bus_msi_domain(bus);
880 
881 	if (!parent)
882 		set_dev_node(bus->bridge, pcibus_to_node(bus));
883 
884 	bus->dev.class = &pcibus_class;
885 	bus->dev.parent = bus->bridge;
886 
887 	dev_set_name(&bus->dev, "%04x:%02x", pci_domain_nr(bus), bus->number);
888 	name = dev_name(&bus->dev);
889 
890 	err = device_register(&bus->dev);
891 	if (err)
892 		goto unregister;
893 
894 	pcibios_add_bus(bus);
895 
896 	/* Create legacy_io and legacy_mem files for this bus */
897 	pci_create_legacy_files(bus);
898 
899 	if (parent)
900 		dev_info(parent, "PCI host bridge to bus %s\n", name);
901 	else
902 		pr_info("PCI host bridge to bus %s\n", name);
903 
904 	/* Add initial resources to the bus */
905 	resource_list_for_each_entry_safe(window, n, &resources) {
906 		list_move_tail(&window->node, &bridge->windows);
907 		offset = window->offset;
908 		res = window->res;
909 
910 		if (res->flags & IORESOURCE_BUS)
911 			pci_bus_insert_busn_res(bus, bus->number, res->end);
912 		else
913 			pci_bus_add_resource(bus, res, 0);
914 
915 		if (offset) {
916 			if (resource_type(res) == IORESOURCE_IO)
917 				fmt = " (bus address [%#06llx-%#06llx])";
918 			else
919 				fmt = " (bus address [%#010llx-%#010llx])";
920 
921 			snprintf(addr, sizeof(addr), fmt,
922 				 (unsigned long long)(res->start - offset),
923 				 (unsigned long long)(res->end - offset));
924 		} else
925 			addr[0] = '\0';
926 
927 		dev_info(&bus->dev, "root bus resource %pR%s\n", res, addr);
928 	}
929 
930 	down_write(&pci_bus_sem);
931 	list_add_tail(&bus->node, &pci_root_buses);
932 	up_write(&pci_bus_sem);
933 
934 	return 0;
935 
936 unregister:
937 	put_device(&bridge->dev);
938 	device_unregister(&bridge->dev);
939 
940 free:
941 	kfree(bus);
942 	return err;
943 }
944 
pci_bridge_child_ext_cfg_accessible(struct pci_dev * bridge)945 static bool pci_bridge_child_ext_cfg_accessible(struct pci_dev *bridge)
946 {
947 	int pos;
948 	u32 status;
949 
950 	/*
951 	 * If extended config space isn't accessible on a bridge's primary
952 	 * bus, we certainly can't access it on the secondary bus.
953 	 */
954 	if (bridge->bus->bus_flags & PCI_BUS_FLAGS_NO_EXTCFG)
955 		return false;
956 
957 	/*
958 	 * PCIe Root Ports and switch ports are PCIe on both sides, so if
959 	 * extended config space is accessible on the primary, it's also
960 	 * accessible on the secondary.
961 	 */
962 	if (pci_is_pcie(bridge) &&
963 	    (pci_pcie_type(bridge) == PCI_EXP_TYPE_ROOT_PORT ||
964 	     pci_pcie_type(bridge) == PCI_EXP_TYPE_UPSTREAM ||
965 	     pci_pcie_type(bridge) == PCI_EXP_TYPE_DOWNSTREAM))
966 		return true;
967 
968 	/*
969 	 * For the other bridge types:
970 	 *   - PCI-to-PCI bridges
971 	 *   - PCIe-to-PCI/PCI-X forward bridges
972 	 *   - PCI/PCI-X-to-PCIe reverse bridges
973 	 * extended config space on the secondary side is only accessible
974 	 * if the bridge supports PCI-X Mode 2.
975 	 */
976 	pos = pci_find_capability(bridge, PCI_CAP_ID_PCIX);
977 	if (!pos)
978 		return false;
979 
980 	pci_read_config_dword(bridge, pos + PCI_X_STATUS, &status);
981 	return status & (PCI_X_STATUS_266MHZ | PCI_X_STATUS_533MHZ);
982 }
983 
pci_alloc_child_bus(struct pci_bus * parent,struct pci_dev * bridge,int busnr)984 static struct pci_bus *pci_alloc_child_bus(struct pci_bus *parent,
985 					   struct pci_dev *bridge, int busnr)
986 {
987 	struct pci_bus *child;
988 	int i;
989 	int ret;
990 
991 	/* Allocate a new bus and inherit stuff from the parent */
992 	child = pci_alloc_bus(parent);
993 	if (!child)
994 		return NULL;
995 
996 	child->parent = parent;
997 	child->ops = parent->ops;
998 	child->msi = parent->msi;
999 	child->sysdata = parent->sysdata;
1000 	child->bus_flags = parent->bus_flags;
1001 
1002 	/*
1003 	 * Initialize some portions of the bus device, but don't register
1004 	 * it now as the parent is not properly set up yet.
1005 	 */
1006 	child->dev.class = &pcibus_class;
1007 	dev_set_name(&child->dev, "%04x:%02x", pci_domain_nr(child), busnr);
1008 
1009 	/* Set up the primary, secondary and subordinate bus numbers */
1010 	child->number = child->busn_res.start = busnr;
1011 	child->primary = parent->busn_res.start;
1012 	child->busn_res.end = 0xff;
1013 
1014 	if (!bridge) {
1015 		child->dev.parent = parent->bridge;
1016 		goto add_dev;
1017 	}
1018 
1019 	child->self = bridge;
1020 	child->bridge = get_device(&bridge->dev);
1021 	child->dev.parent = child->bridge;
1022 	pci_set_bus_of_node(child);
1023 	pci_set_bus_speed(child);
1024 
1025 	/*
1026 	 * Check whether extended config space is accessible on the child
1027 	 * bus.  Note that we currently assume it is always accessible on
1028 	 * the root bus.
1029 	 */
1030 	if (!pci_bridge_child_ext_cfg_accessible(bridge)) {
1031 		child->bus_flags |= PCI_BUS_FLAGS_NO_EXTCFG;
1032 		pci_info(child, "extended config space not accessible\n");
1033 	}
1034 
1035 	/* Set up default resource pointers and names */
1036 	for (i = 0; i < PCI_BRIDGE_RESOURCE_NUM; i++) {
1037 		child->resource[i] = &bridge->resource[PCI_BRIDGE_RESOURCES+i];
1038 		child->resource[i]->name = child->name;
1039 	}
1040 	bridge->subordinate = child;
1041 
1042 add_dev:
1043 	pci_set_bus_msi_domain(child);
1044 	ret = device_register(&child->dev);
1045 	WARN_ON(ret < 0);
1046 
1047 	pcibios_add_bus(child);
1048 
1049 	if (child->ops->add_bus) {
1050 		ret = child->ops->add_bus(child);
1051 		if (WARN_ON(ret < 0))
1052 			dev_err(&child->dev, "failed to add bus: %d\n", ret);
1053 	}
1054 
1055 	/* Create legacy_io and legacy_mem files for this bus */
1056 	pci_create_legacy_files(child);
1057 
1058 	return child;
1059 }
1060 
pci_add_new_bus(struct pci_bus * parent,struct pci_dev * dev,int busnr)1061 struct pci_bus *pci_add_new_bus(struct pci_bus *parent, struct pci_dev *dev,
1062 				int busnr)
1063 {
1064 	struct pci_bus *child;
1065 
1066 	child = pci_alloc_child_bus(parent, dev, busnr);
1067 	if (child) {
1068 		down_write(&pci_bus_sem);
1069 		list_add_tail(&child->node, &parent->children);
1070 		up_write(&pci_bus_sem);
1071 	}
1072 	return child;
1073 }
1074 EXPORT_SYMBOL(pci_add_new_bus);
1075 
pci_enable_crs(struct pci_dev * pdev)1076 static void pci_enable_crs(struct pci_dev *pdev)
1077 {
1078 	u16 root_cap = 0;
1079 
1080 	/* Enable CRS Software Visibility if supported */
1081 	pcie_capability_read_word(pdev, PCI_EXP_RTCAP, &root_cap);
1082 	if (root_cap & PCI_EXP_RTCAP_CRSVIS)
1083 		pcie_capability_set_word(pdev, PCI_EXP_RTCTL,
1084 					 PCI_EXP_RTCTL_CRSSVE);
1085 }
1086 
1087 static unsigned int pci_scan_child_bus_extend(struct pci_bus *bus,
1088 					      unsigned int available_buses);
1089 
1090 /*
1091  * pci_scan_bridge_extend() - Scan buses behind a bridge
1092  * @bus: Parent bus the bridge is on
1093  * @dev: Bridge itself
1094  * @max: Starting subordinate number of buses behind this bridge
1095  * @available_buses: Total number of buses available for this bridge and
1096  *		     the devices below. After the minimal bus space has
1097  *		     been allocated the remaining buses will be
1098  *		     distributed equally between hotplug-capable bridges.
1099  * @pass: Either %0 (scan already configured bridges) or %1 (scan bridges
1100  *        that need to be reconfigured.
1101  *
1102  * If it's a bridge, configure it and scan the bus behind it.
1103  * For CardBus bridges, we don't scan behind as the devices will
1104  * be handled by the bridge driver itself.
1105  *
1106  * We need to process bridges in two passes -- first we scan those
1107  * already configured by the BIOS and after we are done with all of
1108  * them, we proceed to assigning numbers to the remaining buses in
1109  * order to avoid overlaps between old and new bus numbers.
1110  *
1111  * Return: New subordinate number covering all buses behind this bridge.
1112  */
pci_scan_bridge_extend(struct pci_bus * bus,struct pci_dev * dev,int max,unsigned int available_buses,int pass)1113 static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev,
1114 				  int max, unsigned int available_buses,
1115 				  int pass)
1116 {
1117 	struct pci_bus *child;
1118 	int is_cardbus = (dev->hdr_type == PCI_HEADER_TYPE_CARDBUS);
1119 	u32 buses, i, j = 0;
1120 	u16 bctl;
1121 	u8 primary, secondary, subordinate;
1122 	int broken = 0;
1123 
1124 	/*
1125 	 * Make sure the bridge is powered on to be able to access config
1126 	 * space of devices below it.
1127 	 */
1128 	pm_runtime_get_sync(&dev->dev);
1129 
1130 	pci_read_config_dword(dev, PCI_PRIMARY_BUS, &buses);
1131 	primary = buses & 0xFF;
1132 	secondary = (buses >> 8) & 0xFF;
1133 	subordinate = (buses >> 16) & 0xFF;
1134 
1135 	pci_dbg(dev, "scanning [bus %02x-%02x] behind bridge, pass %d\n",
1136 		secondary, subordinate, pass);
1137 
1138 	if (!primary && (primary != bus->number) && secondary && subordinate) {
1139 		pci_warn(dev, "Primary bus is hard wired to 0\n");
1140 		primary = bus->number;
1141 	}
1142 
1143 	/* Check if setup is sensible at all */
1144 	if (!pass &&
1145 	    (primary != bus->number || secondary <= bus->number ||
1146 	     secondary > subordinate)) {
1147 		pci_info(dev, "bridge configuration invalid ([bus %02x-%02x]), reconfiguring\n",
1148 			 secondary, subordinate);
1149 		broken = 1;
1150 	}
1151 
1152 	/*
1153 	 * Disable Master-Abort Mode during probing to avoid reporting of
1154 	 * bus errors in some architectures.
1155 	 */
1156 	pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &bctl);
1157 	pci_write_config_word(dev, PCI_BRIDGE_CONTROL,
1158 			      bctl & ~PCI_BRIDGE_CTL_MASTER_ABORT);
1159 
1160 	pci_enable_crs(dev);
1161 
1162 	if ((secondary || subordinate) && !pcibios_assign_all_busses() &&
1163 	    !is_cardbus && !broken) {
1164 		unsigned int cmax;
1165 
1166 		/*
1167 		 * Bus already configured by firmware, process it in the
1168 		 * first pass and just note the configuration.
1169 		 */
1170 		if (pass)
1171 			goto out;
1172 
1173 		/*
1174 		 * The bus might already exist for two reasons: Either we
1175 		 * are rescanning the bus or the bus is reachable through
1176 		 * more than one bridge. The second case can happen with
1177 		 * the i450NX chipset.
1178 		 */
1179 		child = pci_find_bus(pci_domain_nr(bus), secondary);
1180 		if (!child) {
1181 			child = pci_add_new_bus(bus, dev, secondary);
1182 			if (!child)
1183 				goto out;
1184 			child->primary = primary;
1185 			pci_bus_insert_busn_res(child, secondary, subordinate);
1186 			child->bridge_ctl = bctl;
1187 		}
1188 
1189 		cmax = pci_scan_child_bus(child);
1190 		if (cmax > subordinate)
1191 			pci_warn(dev, "bridge has subordinate %02x but max busn %02x\n",
1192 				 subordinate, cmax);
1193 
1194 		/* Subordinate should equal child->busn_res.end */
1195 		if (subordinate > max)
1196 			max = subordinate;
1197 	} else {
1198 
1199 		/*
1200 		 * We need to assign a number to this bus which we always
1201 		 * do in the second pass.
1202 		 */
1203 		if (!pass) {
1204 			if (pcibios_assign_all_busses() || broken || is_cardbus)
1205 
1206 				/*
1207 				 * Temporarily disable forwarding of the
1208 				 * configuration cycles on all bridges in
1209 				 * this bus segment to avoid possible
1210 				 * conflicts in the second pass between two
1211 				 * bridges programmed with overlapping bus
1212 				 * ranges.
1213 				 */
1214 				pci_write_config_dword(dev, PCI_PRIMARY_BUS,
1215 						       buses & ~0xffffff);
1216 			goto out;
1217 		}
1218 
1219 		/* Clear errors */
1220 		pci_write_config_word(dev, PCI_STATUS, 0xffff);
1221 
1222 		/*
1223 		 * Prevent assigning a bus number that already exists.
1224 		 * This can happen when a bridge is hot-plugged, so in this
1225 		 * case we only re-scan this bus.
1226 		 */
1227 		child = pci_find_bus(pci_domain_nr(bus), max+1);
1228 		if (!child) {
1229 			child = pci_add_new_bus(bus, dev, max+1);
1230 			if (!child)
1231 				goto out;
1232 			pci_bus_insert_busn_res(child, max+1,
1233 						bus->busn_res.end);
1234 		}
1235 		max++;
1236 		if (available_buses)
1237 			available_buses--;
1238 
1239 		buses = (buses & 0xff000000)
1240 		      | ((unsigned int)(child->primary)     <<  0)
1241 		      | ((unsigned int)(child->busn_res.start)   <<  8)
1242 		      | ((unsigned int)(child->busn_res.end) << 16);
1243 
1244 		/*
1245 		 * yenta.c forces a secondary latency timer of 176.
1246 		 * Copy that behaviour here.
1247 		 */
1248 		if (is_cardbus) {
1249 			buses &= ~0xff000000;
1250 			buses |= CARDBUS_LATENCY_TIMER << 24;
1251 		}
1252 
1253 		/* We need to blast all three values with a single write */
1254 		pci_write_config_dword(dev, PCI_PRIMARY_BUS, buses);
1255 
1256 		if (!is_cardbus) {
1257 			child->bridge_ctl = bctl;
1258 			max = pci_scan_child_bus_extend(child, available_buses);
1259 		} else {
1260 
1261 			/*
1262 			 * For CardBus bridges, we leave 4 bus numbers as
1263 			 * cards with a PCI-to-PCI bridge can be inserted
1264 			 * later.
1265 			 */
1266 			for (i = 0; i < CARDBUS_RESERVE_BUSNR; i++) {
1267 				struct pci_bus *parent = bus;
1268 				if (pci_find_bus(pci_domain_nr(bus),
1269 							max+i+1))
1270 					break;
1271 				while (parent->parent) {
1272 					if ((!pcibios_assign_all_busses()) &&
1273 					    (parent->busn_res.end > max) &&
1274 					    (parent->busn_res.end <= max+i)) {
1275 						j = 1;
1276 					}
1277 					parent = parent->parent;
1278 				}
1279 				if (j) {
1280 
1281 					/*
1282 					 * Often, there are two CardBus
1283 					 * bridges -- try to leave one
1284 					 * valid bus number for each one.
1285 					 */
1286 					i /= 2;
1287 					break;
1288 				}
1289 			}
1290 			max += i;
1291 		}
1292 
1293 		/* Set subordinate bus number to its real value */
1294 		pci_bus_update_busn_res_end(child, max);
1295 		pci_write_config_byte(dev, PCI_SUBORDINATE_BUS, max);
1296 	}
1297 
1298 	sprintf(child->name,
1299 		(is_cardbus ? "PCI CardBus %04x:%02x" : "PCI Bus %04x:%02x"),
1300 		pci_domain_nr(bus), child->number);
1301 
1302 	/* Check that all devices are accessible */
1303 	while (bus->parent) {
1304 		if ((child->busn_res.end > bus->busn_res.end) ||
1305 		    (child->number > bus->busn_res.end) ||
1306 		    (child->number < bus->number) ||
1307 		    (child->busn_res.end < bus->number)) {
1308 			dev_info(&dev->dev, "devices behind bridge are unusable because %pR cannot be assigned for them\n",
1309 				 &child->busn_res);
1310 			break;
1311 		}
1312 		bus = bus->parent;
1313 	}
1314 
1315 out:
1316 	pci_write_config_word(dev, PCI_BRIDGE_CONTROL, bctl);
1317 
1318 	pm_runtime_put(&dev->dev);
1319 
1320 	return max;
1321 }
1322 
1323 /*
1324  * pci_scan_bridge() - Scan buses behind a bridge
1325  * @bus: Parent bus the bridge is on
1326  * @dev: Bridge itself
1327  * @max: Starting subordinate number of buses behind this bridge
1328  * @pass: Either %0 (scan already configured bridges) or %1 (scan bridges
1329  *        that need to be reconfigured.
1330  *
1331  * If it's a bridge, configure it and scan the bus behind it.
1332  * For CardBus bridges, we don't scan behind as the devices will
1333  * be handled by the bridge driver itself.
1334  *
1335  * We need to process bridges in two passes -- first we scan those
1336  * already configured by the BIOS and after we are done with all of
1337  * them, we proceed to assigning numbers to the remaining buses in
1338  * order to avoid overlaps between old and new bus numbers.
1339  *
1340  * Return: New subordinate number covering all buses behind this bridge.
1341  */
pci_scan_bridge(struct pci_bus * bus,struct pci_dev * dev,int max,int pass)1342 int pci_scan_bridge(struct pci_bus *bus, struct pci_dev *dev, int max, int pass)
1343 {
1344 	return pci_scan_bridge_extend(bus, dev, max, 0, pass);
1345 }
1346 EXPORT_SYMBOL(pci_scan_bridge);
1347 
1348 /*
1349  * Read interrupt line and base address registers.
1350  * The architecture-dependent code can tweak these, of course.
1351  */
pci_read_irq(struct pci_dev * dev)1352 static void pci_read_irq(struct pci_dev *dev)
1353 {
1354 	unsigned char irq;
1355 
1356 	/* VFs are not allowed to use INTx, so skip the config reads */
1357 	if (dev->is_virtfn) {
1358 		dev->pin = 0;
1359 		dev->irq = 0;
1360 		return;
1361 	}
1362 
1363 	pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &irq);
1364 	dev->pin = irq;
1365 	if (irq)
1366 		pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &irq);
1367 	dev->irq = irq;
1368 }
1369 
set_pcie_port_type(struct pci_dev * pdev)1370 void set_pcie_port_type(struct pci_dev *pdev)
1371 {
1372 	int pos;
1373 	u16 reg16;
1374 	int type;
1375 	struct pci_dev *parent;
1376 
1377 	pos = pci_find_capability(pdev, PCI_CAP_ID_EXP);
1378 	if (!pos)
1379 		return;
1380 
1381 	pdev->pcie_cap = pos;
1382 	pci_read_config_word(pdev, pos + PCI_EXP_FLAGS, &reg16);
1383 	pdev->pcie_flags_reg = reg16;
1384 	pci_read_config_word(pdev, pos + PCI_EXP_DEVCAP, &reg16);
1385 	pdev->pcie_mpss = reg16 & PCI_EXP_DEVCAP_PAYLOAD;
1386 
1387 	/*
1388 	 * A Root Port or a PCI-to-PCIe bridge is always the upstream end
1389 	 * of a Link.  No PCIe component has two Links.  Two Links are
1390 	 * connected by a Switch that has a Port on each Link and internal
1391 	 * logic to connect the two Ports.
1392 	 */
1393 	type = pci_pcie_type(pdev);
1394 	if (type == PCI_EXP_TYPE_ROOT_PORT ||
1395 	    type == PCI_EXP_TYPE_PCIE_BRIDGE)
1396 		pdev->has_secondary_link = 1;
1397 	else if (type == PCI_EXP_TYPE_UPSTREAM ||
1398 		 type == PCI_EXP_TYPE_DOWNSTREAM) {
1399 		parent = pci_upstream_bridge(pdev);
1400 
1401 		/*
1402 		 * Usually there's an upstream device (Root Port or Switch
1403 		 * Downstream Port), but we can't assume one exists.
1404 		 */
1405 		if (parent && !parent->has_secondary_link)
1406 			pdev->has_secondary_link = 1;
1407 	}
1408 }
1409 
set_pcie_hotplug_bridge(struct pci_dev * pdev)1410 void set_pcie_hotplug_bridge(struct pci_dev *pdev)
1411 {
1412 	u32 reg32;
1413 
1414 	pcie_capability_read_dword(pdev, PCI_EXP_SLTCAP, &reg32);
1415 	if (reg32 & PCI_EXP_SLTCAP_HPC)
1416 		pdev->is_hotplug_bridge = 1;
1417 }
1418 
set_pcie_thunderbolt(struct pci_dev * dev)1419 static void set_pcie_thunderbolt(struct pci_dev *dev)
1420 {
1421 	int vsec = 0;
1422 	u32 header;
1423 
1424 	while ((vsec = pci_find_next_ext_capability(dev, vsec,
1425 						    PCI_EXT_CAP_ID_VNDR))) {
1426 		pci_read_config_dword(dev, vsec + PCI_VNDR_HEADER, &header);
1427 
1428 		/* Is the device part of a Thunderbolt controller? */
1429 		if (dev->vendor == PCI_VENDOR_ID_INTEL &&
1430 		    PCI_VNDR_HEADER_ID(header) == PCI_VSEC_ID_INTEL_TBT) {
1431 			dev->is_thunderbolt = 1;
1432 			return;
1433 		}
1434 	}
1435 }
1436 
1437 /**
1438  * pci_ext_cfg_is_aliased - Is ext config space just an alias of std config?
1439  * @dev: PCI device
1440  *
1441  * PCI Express to PCI/PCI-X Bridge Specification, rev 1.0, 4.1.4 says that
1442  * when forwarding a type1 configuration request the bridge must check that
1443  * the extended register address field is zero.  The bridge is not permitted
1444  * to forward the transactions and must handle it as an Unsupported Request.
1445  * Some bridges do not follow this rule and simply drop the extended register
1446  * bits, resulting in the standard config space being aliased, every 256
1447  * bytes across the entire configuration space.  Test for this condition by
1448  * comparing the first dword of each potential alias to the vendor/device ID.
1449  * Known offenders:
1450  *   ASM1083/1085 PCIe-to-PCI Reversible Bridge (1b21:1080, rev 01 & 03)
1451  *   AMD/ATI SBx00 PCI to PCI Bridge (1002:4384, rev 40)
1452  */
pci_ext_cfg_is_aliased(struct pci_dev * dev)1453 static bool pci_ext_cfg_is_aliased(struct pci_dev *dev)
1454 {
1455 #ifdef CONFIG_PCI_QUIRKS
1456 	int pos;
1457 	u32 header, tmp;
1458 
1459 	pci_read_config_dword(dev, PCI_VENDOR_ID, &header);
1460 
1461 	for (pos = PCI_CFG_SPACE_SIZE;
1462 	     pos < PCI_CFG_SPACE_EXP_SIZE; pos += PCI_CFG_SPACE_SIZE) {
1463 		if (pci_read_config_dword(dev, pos, &tmp) != PCIBIOS_SUCCESSFUL
1464 		    || header != tmp)
1465 			return false;
1466 	}
1467 
1468 	return true;
1469 #else
1470 	return false;
1471 #endif
1472 }
1473 
1474 /**
1475  * pci_cfg_space_size - Get the configuration space size of the PCI device
1476  * @dev: PCI device
1477  *
1478  * Regular PCI devices have 256 bytes, but PCI-X 2 and PCI Express devices
1479  * have 4096 bytes.  Even if the device is capable, that doesn't mean we can
1480  * access it.  Maybe we don't have a way to generate extended config space
1481  * accesses, or the device is behind a reverse Express bridge.  So we try
1482  * reading the dword at 0x100 which must either be 0 or a valid extended
1483  * capability header.
1484  */
pci_cfg_space_size_ext(struct pci_dev * dev)1485 static int pci_cfg_space_size_ext(struct pci_dev *dev)
1486 {
1487 	u32 status;
1488 	int pos = PCI_CFG_SPACE_SIZE;
1489 
1490 	if (pci_read_config_dword(dev, pos, &status) != PCIBIOS_SUCCESSFUL)
1491 		return PCI_CFG_SPACE_SIZE;
1492 	if (status == 0xffffffff || pci_ext_cfg_is_aliased(dev))
1493 		return PCI_CFG_SPACE_SIZE;
1494 
1495 	return PCI_CFG_SPACE_EXP_SIZE;
1496 }
1497 
pci_cfg_space_size(struct pci_dev * dev)1498 int pci_cfg_space_size(struct pci_dev *dev)
1499 {
1500 	int pos;
1501 	u32 status;
1502 	u16 class;
1503 
1504 	if (dev->bus->bus_flags & PCI_BUS_FLAGS_NO_EXTCFG)
1505 		return PCI_CFG_SPACE_SIZE;
1506 
1507 	class = dev->class >> 8;
1508 	if (class == PCI_CLASS_BRIDGE_HOST)
1509 		return pci_cfg_space_size_ext(dev);
1510 
1511 	if (pci_is_pcie(dev))
1512 		return pci_cfg_space_size_ext(dev);
1513 
1514 	pos = pci_find_capability(dev, PCI_CAP_ID_PCIX);
1515 	if (!pos)
1516 		return PCI_CFG_SPACE_SIZE;
1517 
1518 	pci_read_config_dword(dev, pos + PCI_X_STATUS, &status);
1519 	if (status & (PCI_X_STATUS_266MHZ | PCI_X_STATUS_533MHZ))
1520 		return pci_cfg_space_size_ext(dev);
1521 
1522 	return PCI_CFG_SPACE_SIZE;
1523 }
1524 
pci_class(struct pci_dev * dev)1525 static u32 pci_class(struct pci_dev *dev)
1526 {
1527 	u32 class;
1528 
1529 #ifdef CONFIG_PCI_IOV
1530 	if (dev->is_virtfn)
1531 		return dev->physfn->sriov->class;
1532 #endif
1533 	pci_read_config_dword(dev, PCI_CLASS_REVISION, &class);
1534 	return class;
1535 }
1536 
pci_subsystem_ids(struct pci_dev * dev,u16 * vendor,u16 * device)1537 static void pci_subsystem_ids(struct pci_dev *dev, u16 *vendor, u16 *device)
1538 {
1539 #ifdef CONFIG_PCI_IOV
1540 	if (dev->is_virtfn) {
1541 		*vendor = dev->physfn->sriov->subsystem_vendor;
1542 		*device = dev->physfn->sriov->subsystem_device;
1543 		return;
1544 	}
1545 #endif
1546 	pci_read_config_word(dev, PCI_SUBSYSTEM_VENDOR_ID, vendor);
1547 	pci_read_config_word(dev, PCI_SUBSYSTEM_ID, device);
1548 }
1549 
pci_hdr_type(struct pci_dev * dev)1550 static u8 pci_hdr_type(struct pci_dev *dev)
1551 {
1552 	u8 hdr_type;
1553 
1554 #ifdef CONFIG_PCI_IOV
1555 	if (dev->is_virtfn)
1556 		return dev->physfn->sriov->hdr_type;
1557 #endif
1558 	pci_read_config_byte(dev, PCI_HEADER_TYPE, &hdr_type);
1559 	return hdr_type;
1560 }
1561 
1562 #define LEGACY_IO_RESOURCE	(IORESOURCE_IO | IORESOURCE_PCI_FIXED)
1563 
pci_msi_setup_pci_dev(struct pci_dev * dev)1564 static void pci_msi_setup_pci_dev(struct pci_dev *dev)
1565 {
1566 	/*
1567 	 * Disable the MSI hardware to avoid screaming interrupts
1568 	 * during boot.  This is the power on reset default so
1569 	 * usually this should be a noop.
1570 	 */
1571 	dev->msi_cap = pci_find_capability(dev, PCI_CAP_ID_MSI);
1572 	if (dev->msi_cap)
1573 		pci_msi_set_enable(dev, 0);
1574 
1575 	dev->msix_cap = pci_find_capability(dev, PCI_CAP_ID_MSIX);
1576 	if (dev->msix_cap)
1577 		pci_msix_clear_and_set_ctrl(dev, PCI_MSIX_FLAGS_ENABLE, 0);
1578 }
1579 
1580 /**
1581  * pci_intx_mask_broken - Test PCI_COMMAND_INTX_DISABLE writability
1582  * @dev: PCI device
1583  *
1584  * Test whether PCI_COMMAND_INTX_DISABLE is writable for @dev.  Check this
1585  * at enumeration-time to avoid modifying PCI_COMMAND at run-time.
1586  */
pci_intx_mask_broken(struct pci_dev * dev)1587 static int pci_intx_mask_broken(struct pci_dev *dev)
1588 {
1589 	u16 orig, toggle, new;
1590 
1591 	pci_read_config_word(dev, PCI_COMMAND, &orig);
1592 	toggle = orig ^ PCI_COMMAND_INTX_DISABLE;
1593 	pci_write_config_word(dev, PCI_COMMAND, toggle);
1594 	pci_read_config_word(dev, PCI_COMMAND, &new);
1595 
1596 	pci_write_config_word(dev, PCI_COMMAND, orig);
1597 
1598 	/*
1599 	 * PCI_COMMAND_INTX_DISABLE was reserved and read-only prior to PCI
1600 	 * r2.3, so strictly speaking, a device is not *broken* if it's not
1601 	 * writable.  But we'll live with the misnomer for now.
1602 	 */
1603 	if (new != toggle)
1604 		return 1;
1605 	return 0;
1606 }
1607 
early_dump_pci_device(struct pci_dev * pdev)1608 static void early_dump_pci_device(struct pci_dev *pdev)
1609 {
1610 	u32 value[256 / 4];
1611 	int i;
1612 
1613 	pci_info(pdev, "config space:\n");
1614 
1615 	for (i = 0; i < 256; i += 4)
1616 		pci_read_config_dword(pdev, i, &value[i / 4]);
1617 
1618 	print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET, 16, 1,
1619 		       value, 256, false);
1620 }
1621 
1622 /**
1623  * pci_setup_device - Fill in class and map information of a device
1624  * @dev: the device structure to fill
1625  *
1626  * Initialize the device structure with information about the device's
1627  * vendor,class,memory and IO-space addresses, IRQ lines etc.
1628  * Called at initialisation of the PCI subsystem and by CardBus services.
1629  * Returns 0 on success and negative if unknown type of device (not normal,
1630  * bridge or CardBus).
1631  */
pci_setup_device(struct pci_dev * dev)1632 int pci_setup_device(struct pci_dev *dev)
1633 {
1634 	u32 class;
1635 	u16 cmd;
1636 	u8 hdr_type;
1637 	int pos = 0;
1638 	struct pci_bus_region region;
1639 	struct resource *res;
1640 
1641 	hdr_type = pci_hdr_type(dev);
1642 
1643 	dev->sysdata = dev->bus->sysdata;
1644 	dev->dev.parent = dev->bus->bridge;
1645 	dev->dev.bus = &pci_bus_type;
1646 	dev->hdr_type = hdr_type & 0x7f;
1647 	dev->multifunction = !!(hdr_type & 0x80);
1648 	dev->error_state = pci_channel_io_normal;
1649 	set_pcie_port_type(dev);
1650 
1651 	pci_dev_assign_slot(dev);
1652 
1653 	/*
1654 	 * Assume 32-bit PCI; let 64-bit PCI cards (which are far rarer)
1655 	 * set this higher, assuming the system even supports it.
1656 	 */
1657 	dev->dma_mask = 0xffffffff;
1658 
1659 	dev_set_name(&dev->dev, "%04x:%02x:%02x.%d", pci_domain_nr(dev->bus),
1660 		     dev->bus->number, PCI_SLOT(dev->devfn),
1661 		     PCI_FUNC(dev->devfn));
1662 
1663 	class = pci_class(dev);
1664 
1665 	dev->revision = class & 0xff;
1666 	dev->class = class >> 8;		    /* upper 3 bytes */
1667 
1668 	pci_printk(KERN_DEBUG, dev, "[%04x:%04x] type %02x class %#08x\n",
1669 		   dev->vendor, dev->device, dev->hdr_type, dev->class);
1670 
1671 	if (pci_early_dump)
1672 		early_dump_pci_device(dev);
1673 
1674 	/* Need to have dev->class ready */
1675 	dev->cfg_size = pci_cfg_space_size(dev);
1676 
1677 	/* Need to have dev->cfg_size ready */
1678 	set_pcie_thunderbolt(dev);
1679 
1680 	/* "Unknown power state" */
1681 	dev->current_state = PCI_UNKNOWN;
1682 
1683 	/* Early fixups, before probing the BARs */
1684 	pci_fixup_device(pci_fixup_early, dev);
1685 
1686 	/* Device class may be changed after fixup */
1687 	class = dev->class >> 8;
1688 
1689 	if (dev->non_compliant_bars && !dev->mmio_always_on) {
1690 		pci_read_config_word(dev, PCI_COMMAND, &cmd);
1691 		if (cmd & (PCI_COMMAND_IO | PCI_COMMAND_MEMORY)) {
1692 			pci_info(dev, "device has non-compliant BARs; disabling IO/MEM decoding\n");
1693 			cmd &= ~PCI_COMMAND_IO;
1694 			cmd &= ~PCI_COMMAND_MEMORY;
1695 			pci_write_config_word(dev, PCI_COMMAND, cmd);
1696 		}
1697 	}
1698 
1699 	dev->broken_intx_masking = pci_intx_mask_broken(dev);
1700 
1701 	switch (dev->hdr_type) {		    /* header type */
1702 	case PCI_HEADER_TYPE_NORMAL:		    /* standard header */
1703 		if (class == PCI_CLASS_BRIDGE_PCI)
1704 			goto bad;
1705 		pci_read_irq(dev);
1706 		pci_read_bases(dev, 6, PCI_ROM_ADDRESS);
1707 
1708 		pci_subsystem_ids(dev, &dev->subsystem_vendor, &dev->subsystem_device);
1709 
1710 		/*
1711 		 * Do the ugly legacy mode stuff here rather than broken chip
1712 		 * quirk code. Legacy mode ATA controllers have fixed
1713 		 * addresses. These are not always echoed in BAR0-3, and
1714 		 * BAR0-3 in a few cases contain junk!
1715 		 */
1716 		if (class == PCI_CLASS_STORAGE_IDE) {
1717 			u8 progif;
1718 			pci_read_config_byte(dev, PCI_CLASS_PROG, &progif);
1719 			if ((progif & 1) == 0) {
1720 				region.start = 0x1F0;
1721 				region.end = 0x1F7;
1722 				res = &dev->resource[0];
1723 				res->flags = LEGACY_IO_RESOURCE;
1724 				pcibios_bus_to_resource(dev->bus, res, &region);
1725 				pci_info(dev, "legacy IDE quirk: reg 0x10: %pR\n",
1726 					 res);
1727 				region.start = 0x3F6;
1728 				region.end = 0x3F6;
1729 				res = &dev->resource[1];
1730 				res->flags = LEGACY_IO_RESOURCE;
1731 				pcibios_bus_to_resource(dev->bus, res, &region);
1732 				pci_info(dev, "legacy IDE quirk: reg 0x14: %pR\n",
1733 					 res);
1734 			}
1735 			if ((progif & 4) == 0) {
1736 				region.start = 0x170;
1737 				region.end = 0x177;
1738 				res = &dev->resource[2];
1739 				res->flags = LEGACY_IO_RESOURCE;
1740 				pcibios_bus_to_resource(dev->bus, res, &region);
1741 				pci_info(dev, "legacy IDE quirk: reg 0x18: %pR\n",
1742 					 res);
1743 				region.start = 0x376;
1744 				region.end = 0x376;
1745 				res = &dev->resource[3];
1746 				res->flags = LEGACY_IO_RESOURCE;
1747 				pcibios_bus_to_resource(dev->bus, res, &region);
1748 				pci_info(dev, "legacy IDE quirk: reg 0x1c: %pR\n",
1749 					 res);
1750 			}
1751 		}
1752 		break;
1753 
1754 	case PCI_HEADER_TYPE_BRIDGE:		    /* bridge header */
1755 		if (class != PCI_CLASS_BRIDGE_PCI)
1756 			goto bad;
1757 
1758 		/*
1759 		 * The PCI-to-PCI bridge spec requires that subtractive
1760 		 * decoding (i.e. transparent) bridge must have programming
1761 		 * interface code of 0x01.
1762 		 */
1763 		pci_read_irq(dev);
1764 		dev->transparent = ((dev->class & 0xff) == 1);
1765 		pci_read_bases(dev, 2, PCI_ROM_ADDRESS1);
1766 		pci_read_bridge_windows(dev);
1767 		set_pcie_hotplug_bridge(dev);
1768 		pos = pci_find_capability(dev, PCI_CAP_ID_SSVID);
1769 		if (pos) {
1770 			pci_read_config_word(dev, pos + PCI_SSVID_VENDOR_ID, &dev->subsystem_vendor);
1771 			pci_read_config_word(dev, pos + PCI_SSVID_DEVICE_ID, &dev->subsystem_device);
1772 		}
1773 		break;
1774 
1775 	case PCI_HEADER_TYPE_CARDBUS:		    /* CardBus bridge header */
1776 		if (class != PCI_CLASS_BRIDGE_CARDBUS)
1777 			goto bad;
1778 		pci_read_irq(dev);
1779 		pci_read_bases(dev, 1, 0);
1780 		pci_read_config_word(dev, PCI_CB_SUBSYSTEM_VENDOR_ID, &dev->subsystem_vendor);
1781 		pci_read_config_word(dev, PCI_CB_SUBSYSTEM_ID, &dev->subsystem_device);
1782 		break;
1783 
1784 	default:				    /* unknown header */
1785 		pci_err(dev, "unknown header type %02x, ignoring device\n",
1786 			dev->hdr_type);
1787 		return -EIO;
1788 
1789 	bad:
1790 		pci_err(dev, "ignoring class %#08x (doesn't match header type %02x)\n",
1791 			dev->class, dev->hdr_type);
1792 		dev->class = PCI_CLASS_NOT_DEFINED << 8;
1793 	}
1794 
1795 	/* We found a fine healthy device, go go go... */
1796 	return 0;
1797 }
1798 
pci_configure_mps(struct pci_dev * dev)1799 static void pci_configure_mps(struct pci_dev *dev)
1800 {
1801 	struct pci_dev *bridge = pci_upstream_bridge(dev);
1802 	int mps, mpss, p_mps, rc;
1803 
1804 	if (!pci_is_pcie(dev))
1805 		return;
1806 
1807 	/* MPS and MRRS fields are of type 'RsvdP' for VFs, short-circuit out */
1808 	if (dev->is_virtfn)
1809 		return;
1810 
1811 	/*
1812 	 * For Root Complex Integrated Endpoints, program the maximum
1813 	 * supported value unless limited by the PCIE_BUS_PEER2PEER case.
1814 	 */
1815 	if (pci_pcie_type(dev) == PCI_EXP_TYPE_RC_END) {
1816 		if (pcie_bus_config == PCIE_BUS_PEER2PEER)
1817 			mps = 128;
1818 		else
1819 			mps = 128 << dev->pcie_mpss;
1820 		rc = pcie_set_mps(dev, mps);
1821 		if (rc) {
1822 			pci_warn(dev, "can't set Max Payload Size to %d; if necessary, use \"pci=pcie_bus_safe\" and report a bug\n",
1823 				 mps);
1824 		}
1825 		return;
1826 	}
1827 
1828 	if (!bridge || !pci_is_pcie(bridge))
1829 		return;
1830 
1831 	mps = pcie_get_mps(dev);
1832 	p_mps = pcie_get_mps(bridge);
1833 
1834 	if (mps == p_mps)
1835 		return;
1836 
1837 	if (pcie_bus_config == PCIE_BUS_TUNE_OFF) {
1838 		pci_warn(dev, "Max Payload Size %d, but upstream %s set to %d; if necessary, use \"pci=pcie_bus_safe\" and report a bug\n",
1839 			 mps, pci_name(bridge), p_mps);
1840 		return;
1841 	}
1842 
1843 	/*
1844 	 * Fancier MPS configuration is done later by
1845 	 * pcie_bus_configure_settings()
1846 	 */
1847 	if (pcie_bus_config != PCIE_BUS_DEFAULT)
1848 		return;
1849 
1850 	mpss = 128 << dev->pcie_mpss;
1851 	if (mpss < p_mps && pci_pcie_type(bridge) == PCI_EXP_TYPE_ROOT_PORT) {
1852 		pcie_set_mps(bridge, mpss);
1853 		pci_info(dev, "Upstream bridge's Max Payload Size set to %d (was %d, max %d)\n",
1854 			 mpss, p_mps, 128 << bridge->pcie_mpss);
1855 		p_mps = pcie_get_mps(bridge);
1856 	}
1857 
1858 	rc = pcie_set_mps(dev, p_mps);
1859 	if (rc) {
1860 		pci_warn(dev, "can't set Max Payload Size to %d; if necessary, use \"pci=pcie_bus_safe\" and report a bug\n",
1861 			 p_mps);
1862 		return;
1863 	}
1864 
1865 	pci_info(dev, "Max Payload Size set to %d (was %d, max %d)\n",
1866 		 p_mps, mps, mpss);
1867 }
1868 
1869 static struct hpp_type0 pci_default_type0 = {
1870 	.revision = 1,
1871 	.cache_line_size = 8,
1872 	.latency_timer = 0x40,
1873 	.enable_serr = 0,
1874 	.enable_perr = 0,
1875 };
1876 
program_hpp_type0(struct pci_dev * dev,struct hpp_type0 * hpp)1877 static void program_hpp_type0(struct pci_dev *dev, struct hpp_type0 *hpp)
1878 {
1879 	u16 pci_cmd, pci_bctl;
1880 
1881 	if (!hpp)
1882 		hpp = &pci_default_type0;
1883 
1884 	if (hpp->revision > 1) {
1885 		pci_warn(dev, "PCI settings rev %d not supported; using defaults\n",
1886 			 hpp->revision);
1887 		hpp = &pci_default_type0;
1888 	}
1889 
1890 	pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, hpp->cache_line_size);
1891 	pci_write_config_byte(dev, PCI_LATENCY_TIMER, hpp->latency_timer);
1892 	pci_read_config_word(dev, PCI_COMMAND, &pci_cmd);
1893 	if (hpp->enable_serr)
1894 		pci_cmd |= PCI_COMMAND_SERR;
1895 	if (hpp->enable_perr)
1896 		pci_cmd |= PCI_COMMAND_PARITY;
1897 	pci_write_config_word(dev, PCI_COMMAND, pci_cmd);
1898 
1899 	/* Program bridge control value */
1900 	if ((dev->class >> 8) == PCI_CLASS_BRIDGE_PCI) {
1901 		pci_write_config_byte(dev, PCI_SEC_LATENCY_TIMER,
1902 				      hpp->latency_timer);
1903 		pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &pci_bctl);
1904 		if (hpp->enable_serr)
1905 			pci_bctl |= PCI_BRIDGE_CTL_SERR;
1906 		if (hpp->enable_perr)
1907 			pci_bctl |= PCI_BRIDGE_CTL_PARITY;
1908 		pci_write_config_word(dev, PCI_BRIDGE_CONTROL, pci_bctl);
1909 	}
1910 }
1911 
program_hpp_type1(struct pci_dev * dev,struct hpp_type1 * hpp)1912 static void program_hpp_type1(struct pci_dev *dev, struct hpp_type1 *hpp)
1913 {
1914 	int pos;
1915 
1916 	if (!hpp)
1917 		return;
1918 
1919 	pos = pci_find_capability(dev, PCI_CAP_ID_PCIX);
1920 	if (!pos)
1921 		return;
1922 
1923 	pci_warn(dev, "PCI-X settings not supported\n");
1924 }
1925 
pcie_root_rcb_set(struct pci_dev * dev)1926 static bool pcie_root_rcb_set(struct pci_dev *dev)
1927 {
1928 	struct pci_dev *rp = pcie_find_root_port(dev);
1929 	u16 lnkctl;
1930 
1931 	if (!rp)
1932 		return false;
1933 
1934 	pcie_capability_read_word(rp, PCI_EXP_LNKCTL, &lnkctl);
1935 	if (lnkctl & PCI_EXP_LNKCTL_RCB)
1936 		return true;
1937 
1938 	return false;
1939 }
1940 
program_hpp_type2(struct pci_dev * dev,struct hpp_type2 * hpp)1941 static void program_hpp_type2(struct pci_dev *dev, struct hpp_type2 *hpp)
1942 {
1943 	int pos;
1944 	u32 reg32;
1945 
1946 	if (!hpp)
1947 		return;
1948 
1949 	if (!pci_is_pcie(dev))
1950 		return;
1951 
1952 	if (hpp->revision > 1) {
1953 		pci_warn(dev, "PCIe settings rev %d not supported\n",
1954 			 hpp->revision);
1955 		return;
1956 	}
1957 
1958 	/*
1959 	 * Don't allow _HPX to change MPS or MRRS settings.  We manage
1960 	 * those to make sure they're consistent with the rest of the
1961 	 * platform.
1962 	 */
1963 	hpp->pci_exp_devctl_and |= PCI_EXP_DEVCTL_PAYLOAD |
1964 				    PCI_EXP_DEVCTL_READRQ;
1965 	hpp->pci_exp_devctl_or &= ~(PCI_EXP_DEVCTL_PAYLOAD |
1966 				    PCI_EXP_DEVCTL_READRQ);
1967 
1968 	/* Initialize Device Control Register */
1969 	pcie_capability_clear_and_set_word(dev, PCI_EXP_DEVCTL,
1970 			~hpp->pci_exp_devctl_and, hpp->pci_exp_devctl_or);
1971 
1972 	/* Initialize Link Control Register */
1973 	if (pcie_cap_has_lnkctl(dev)) {
1974 
1975 		/*
1976 		 * If the Root Port supports Read Completion Boundary of
1977 		 * 128, set RCB to 128.  Otherwise, clear it.
1978 		 */
1979 		hpp->pci_exp_lnkctl_and |= PCI_EXP_LNKCTL_RCB;
1980 		hpp->pci_exp_lnkctl_or &= ~PCI_EXP_LNKCTL_RCB;
1981 		if (pcie_root_rcb_set(dev))
1982 			hpp->pci_exp_lnkctl_or |= PCI_EXP_LNKCTL_RCB;
1983 
1984 		pcie_capability_clear_and_set_word(dev, PCI_EXP_LNKCTL,
1985 			~hpp->pci_exp_lnkctl_and, hpp->pci_exp_lnkctl_or);
1986 	}
1987 
1988 	/* Find Advanced Error Reporting Enhanced Capability */
1989 	pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
1990 	if (!pos)
1991 		return;
1992 
1993 	/* Initialize Uncorrectable Error Mask Register */
1994 	pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_MASK, &reg32);
1995 	reg32 = (reg32 & hpp->unc_err_mask_and) | hpp->unc_err_mask_or;
1996 	pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_MASK, reg32);
1997 
1998 	/* Initialize Uncorrectable Error Severity Register */
1999 	pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_SEVER, &reg32);
2000 	reg32 = (reg32 & hpp->unc_err_sever_and) | hpp->unc_err_sever_or;
2001 	pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_SEVER, reg32);
2002 
2003 	/* Initialize Correctable Error Mask Register */
2004 	pci_read_config_dword(dev, pos + PCI_ERR_COR_MASK, &reg32);
2005 	reg32 = (reg32 & hpp->cor_err_mask_and) | hpp->cor_err_mask_or;
2006 	pci_write_config_dword(dev, pos + PCI_ERR_COR_MASK, reg32);
2007 
2008 	/* Initialize Advanced Error Capabilities and Control Register */
2009 	pci_read_config_dword(dev, pos + PCI_ERR_CAP, &reg32);
2010 	reg32 = (reg32 & hpp->adv_err_cap_and) | hpp->adv_err_cap_or;
2011 
2012 	/* Don't enable ECRC generation or checking if unsupported */
2013 	if (!(reg32 & PCI_ERR_CAP_ECRC_GENC))
2014 		reg32 &= ~PCI_ERR_CAP_ECRC_GENE;
2015 	if (!(reg32 & PCI_ERR_CAP_ECRC_CHKC))
2016 		reg32 &= ~PCI_ERR_CAP_ECRC_CHKE;
2017 	pci_write_config_dword(dev, pos + PCI_ERR_CAP, reg32);
2018 
2019 	/*
2020 	 * FIXME: The following two registers are not supported yet.
2021 	 *
2022 	 *   o Secondary Uncorrectable Error Severity Register
2023 	 *   o Secondary Uncorrectable Error Mask Register
2024 	 */
2025 }
2026 
pci_configure_extended_tags(struct pci_dev * dev,void * ign)2027 int pci_configure_extended_tags(struct pci_dev *dev, void *ign)
2028 {
2029 	struct pci_host_bridge *host;
2030 	u32 cap;
2031 	u16 ctl;
2032 	int ret;
2033 
2034 	if (!pci_is_pcie(dev))
2035 		return 0;
2036 
2037 	ret = pcie_capability_read_dword(dev, PCI_EXP_DEVCAP, &cap);
2038 	if (ret)
2039 		return 0;
2040 
2041 	if (!(cap & PCI_EXP_DEVCAP_EXT_TAG))
2042 		return 0;
2043 
2044 	ret = pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &ctl);
2045 	if (ret)
2046 		return 0;
2047 
2048 	host = pci_find_host_bridge(dev->bus);
2049 	if (!host)
2050 		return 0;
2051 
2052 	/*
2053 	 * If some device in the hierarchy doesn't handle Extended Tags
2054 	 * correctly, make sure they're disabled.
2055 	 */
2056 	if (host->no_ext_tags) {
2057 		if (ctl & PCI_EXP_DEVCTL_EXT_TAG) {
2058 			pci_info(dev, "disabling Extended Tags\n");
2059 			pcie_capability_clear_word(dev, PCI_EXP_DEVCTL,
2060 						   PCI_EXP_DEVCTL_EXT_TAG);
2061 		}
2062 		return 0;
2063 	}
2064 
2065 	if (!(ctl & PCI_EXP_DEVCTL_EXT_TAG)) {
2066 		pci_info(dev, "enabling Extended Tags\n");
2067 		pcie_capability_set_word(dev, PCI_EXP_DEVCTL,
2068 					 PCI_EXP_DEVCTL_EXT_TAG);
2069 	}
2070 	return 0;
2071 }
2072 
2073 /**
2074  * pcie_relaxed_ordering_enabled - Probe for PCIe relaxed ordering enable
2075  * @dev: PCI device to query
2076  *
2077  * Returns true if the device has enabled relaxed ordering attribute.
2078  */
pcie_relaxed_ordering_enabled(struct pci_dev * dev)2079 bool pcie_relaxed_ordering_enabled(struct pci_dev *dev)
2080 {
2081 	u16 v;
2082 
2083 	pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &v);
2084 
2085 	return !!(v & PCI_EXP_DEVCTL_RELAX_EN);
2086 }
2087 EXPORT_SYMBOL(pcie_relaxed_ordering_enabled);
2088 
pci_configure_relaxed_ordering(struct pci_dev * dev)2089 static void pci_configure_relaxed_ordering(struct pci_dev *dev)
2090 {
2091 	struct pci_dev *root;
2092 
2093 	/* PCI_EXP_DEVICE_RELAX_EN is RsvdP in VFs */
2094 	if (dev->is_virtfn)
2095 		return;
2096 
2097 	if (!pcie_relaxed_ordering_enabled(dev))
2098 		return;
2099 
2100 	/*
2101 	 * For now, we only deal with Relaxed Ordering issues with Root
2102 	 * Ports. Peer-to-Peer DMA is another can of worms.
2103 	 */
2104 	root = pci_find_pcie_root_port(dev);
2105 	if (!root)
2106 		return;
2107 
2108 	if (root->dev_flags & PCI_DEV_FLAGS_NO_RELAXED_ORDERING) {
2109 		pcie_capability_clear_word(dev, PCI_EXP_DEVCTL,
2110 					   PCI_EXP_DEVCTL_RELAX_EN);
2111 		pci_info(dev, "Relaxed Ordering disabled because the Root Port didn't support it\n");
2112 	}
2113 }
2114 
pci_configure_ltr(struct pci_dev * dev)2115 static void pci_configure_ltr(struct pci_dev *dev)
2116 {
2117 #ifdef CONFIG_PCIEASPM
2118 	struct pci_host_bridge *host = pci_find_host_bridge(dev->bus);
2119 	struct pci_dev *bridge;
2120 	u32 cap, ctl;
2121 
2122 	if (!pci_is_pcie(dev))
2123 		return;
2124 
2125 	pcie_capability_read_dword(dev, PCI_EXP_DEVCAP2, &cap);
2126 	if (!(cap & PCI_EXP_DEVCAP2_LTR))
2127 		return;
2128 
2129 	pcie_capability_read_dword(dev, PCI_EXP_DEVCTL2, &ctl);
2130 	if (ctl & PCI_EXP_DEVCTL2_LTR_EN) {
2131 		if (pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT) {
2132 			dev->ltr_path = 1;
2133 			return;
2134 		}
2135 
2136 		bridge = pci_upstream_bridge(dev);
2137 		if (bridge && bridge->ltr_path)
2138 			dev->ltr_path = 1;
2139 
2140 		return;
2141 	}
2142 
2143 	if (!host->native_ltr)
2144 		return;
2145 
2146 	/*
2147 	 * Software must not enable LTR in an Endpoint unless the Root
2148 	 * Complex and all intermediate Switches indicate support for LTR.
2149 	 * PCIe r4.0, sec 6.18.
2150 	 */
2151 	if (pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT ||
2152 	    ((bridge = pci_upstream_bridge(dev)) &&
2153 	      bridge->ltr_path)) {
2154 		pcie_capability_set_word(dev, PCI_EXP_DEVCTL2,
2155 					 PCI_EXP_DEVCTL2_LTR_EN);
2156 		dev->ltr_path = 1;
2157 	}
2158 #endif
2159 }
2160 
pci_configure_eetlp_prefix(struct pci_dev * dev)2161 static void pci_configure_eetlp_prefix(struct pci_dev *dev)
2162 {
2163 #ifdef CONFIG_PCI_PASID
2164 	struct pci_dev *bridge;
2165 	int pcie_type;
2166 	u32 cap;
2167 
2168 	if (!pci_is_pcie(dev))
2169 		return;
2170 
2171 	pcie_capability_read_dword(dev, PCI_EXP_DEVCAP2, &cap);
2172 	if (!(cap & PCI_EXP_DEVCAP2_EE_PREFIX))
2173 		return;
2174 
2175 	pcie_type = pci_pcie_type(dev);
2176 	if (pcie_type == PCI_EXP_TYPE_ROOT_PORT ||
2177 	    pcie_type == PCI_EXP_TYPE_RC_END)
2178 		dev->eetlp_prefix_path = 1;
2179 	else {
2180 		bridge = pci_upstream_bridge(dev);
2181 		if (bridge && bridge->eetlp_prefix_path)
2182 			dev->eetlp_prefix_path = 1;
2183 	}
2184 #endif
2185 }
2186 
pci_configure_device(struct pci_dev * dev)2187 static void pci_configure_device(struct pci_dev *dev)
2188 {
2189 	struct hotplug_params hpp;
2190 	int ret;
2191 
2192 	pci_configure_mps(dev);
2193 	pci_configure_extended_tags(dev, NULL);
2194 	pci_configure_relaxed_ordering(dev);
2195 	pci_configure_ltr(dev);
2196 	pci_configure_eetlp_prefix(dev);
2197 
2198 	memset(&hpp, 0, sizeof(hpp));
2199 	ret = pci_get_hp_params(dev, &hpp);
2200 	if (ret)
2201 		return;
2202 
2203 	program_hpp_type2(dev, hpp.t2);
2204 	program_hpp_type1(dev, hpp.t1);
2205 	program_hpp_type0(dev, hpp.t0);
2206 }
2207 
pci_release_capabilities(struct pci_dev * dev)2208 static void pci_release_capabilities(struct pci_dev *dev)
2209 {
2210 	pci_aer_exit(dev);
2211 	pci_vpd_release(dev);
2212 	pci_iov_release(dev);
2213 	pci_free_cap_save_buffers(dev);
2214 }
2215 
2216 /**
2217  * pci_release_dev - Free a PCI device structure when all users of it are
2218  *		     finished
2219  * @dev: device that's been disconnected
2220  *
2221  * Will be called only by the device core when all users of this PCI device are
2222  * done.
2223  */
pci_release_dev(struct device * dev)2224 static void pci_release_dev(struct device *dev)
2225 {
2226 	struct pci_dev *pci_dev;
2227 
2228 	pci_dev = to_pci_dev(dev);
2229 	pci_release_capabilities(pci_dev);
2230 	pci_release_of_node(pci_dev);
2231 	pcibios_release_device(pci_dev);
2232 	pci_bus_put(pci_dev->bus);
2233 	kfree(pci_dev->driver_override);
2234 	kfree(pci_dev->dma_alias_mask);
2235 	kfree(pci_dev);
2236 }
2237 
pci_alloc_dev(struct pci_bus * bus)2238 struct pci_dev *pci_alloc_dev(struct pci_bus *bus)
2239 {
2240 	struct pci_dev *dev;
2241 
2242 	dev = kzalloc(sizeof(struct pci_dev), GFP_KERNEL);
2243 	if (!dev)
2244 		return NULL;
2245 
2246 	INIT_LIST_HEAD(&dev->bus_list);
2247 	dev->dev.type = &pci_dev_type;
2248 	dev->bus = pci_bus_get(bus);
2249 
2250 	return dev;
2251 }
2252 EXPORT_SYMBOL(pci_alloc_dev);
2253 
pci_bus_crs_vendor_id(u32 l)2254 static bool pci_bus_crs_vendor_id(u32 l)
2255 {
2256 	return (l & 0xffff) == 0x0001;
2257 }
2258 
pci_bus_wait_crs(struct pci_bus * bus,int devfn,u32 * l,int timeout)2259 static bool pci_bus_wait_crs(struct pci_bus *bus, int devfn, u32 *l,
2260 			     int timeout)
2261 {
2262 	int delay = 1;
2263 
2264 	if (!pci_bus_crs_vendor_id(*l))
2265 		return true;	/* not a CRS completion */
2266 
2267 	if (!timeout)
2268 		return false;	/* CRS, but caller doesn't want to wait */
2269 
2270 	/*
2271 	 * We got the reserved Vendor ID that indicates a completion with
2272 	 * Configuration Request Retry Status (CRS).  Retry until we get a
2273 	 * valid Vendor ID or we time out.
2274 	 */
2275 	while (pci_bus_crs_vendor_id(*l)) {
2276 		if (delay > timeout) {
2277 			pr_warn("pci %04x:%02x:%02x.%d: not ready after %dms; giving up\n",
2278 				pci_domain_nr(bus), bus->number,
2279 				PCI_SLOT(devfn), PCI_FUNC(devfn), delay - 1);
2280 
2281 			return false;
2282 		}
2283 		if (delay >= 1000)
2284 			pr_info("pci %04x:%02x:%02x.%d: not ready after %dms; waiting\n",
2285 				pci_domain_nr(bus), bus->number,
2286 				PCI_SLOT(devfn), PCI_FUNC(devfn), delay - 1);
2287 
2288 		msleep(delay);
2289 		delay *= 2;
2290 
2291 		if (pci_bus_read_config_dword(bus, devfn, PCI_VENDOR_ID, l))
2292 			return false;
2293 	}
2294 
2295 	if (delay >= 1000)
2296 		pr_info("pci %04x:%02x:%02x.%d: ready after %dms\n",
2297 			pci_domain_nr(bus), bus->number,
2298 			PCI_SLOT(devfn), PCI_FUNC(devfn), delay - 1);
2299 
2300 	return true;
2301 }
2302 
pci_bus_generic_read_dev_vendor_id(struct pci_bus * bus,int devfn,u32 * l,int timeout)2303 bool pci_bus_generic_read_dev_vendor_id(struct pci_bus *bus, int devfn, u32 *l,
2304 					int timeout)
2305 {
2306 	if (pci_bus_read_config_dword(bus, devfn, PCI_VENDOR_ID, l))
2307 		return false;
2308 
2309 	/* Some broken boards return 0 or ~0 if a slot is empty: */
2310 	if (*l == 0xffffffff || *l == 0x00000000 ||
2311 	    *l == 0x0000ffff || *l == 0xffff0000)
2312 		return false;
2313 
2314 	if (pci_bus_crs_vendor_id(*l))
2315 		return pci_bus_wait_crs(bus, devfn, l, timeout);
2316 
2317 	return true;
2318 }
2319 
pci_bus_read_dev_vendor_id(struct pci_bus * bus,int devfn,u32 * l,int timeout)2320 bool pci_bus_read_dev_vendor_id(struct pci_bus *bus, int devfn, u32 *l,
2321 				int timeout)
2322 {
2323 #ifdef CONFIG_PCI_QUIRKS
2324 	struct pci_dev *bridge = bus->self;
2325 
2326 	/*
2327 	 * Certain IDT switches have an issue where they improperly trigger
2328 	 * ACS Source Validation errors on completions for config reads.
2329 	 */
2330 	if (bridge && bridge->vendor == PCI_VENDOR_ID_IDT &&
2331 	    bridge->device == 0x80b5)
2332 		return pci_idt_bus_quirk(bus, devfn, l, timeout);
2333 #endif
2334 
2335 	return pci_bus_generic_read_dev_vendor_id(bus, devfn, l, timeout);
2336 }
2337 EXPORT_SYMBOL(pci_bus_read_dev_vendor_id);
2338 
2339 /*
2340  * Read the config data for a PCI device, sanity-check it,
2341  * and fill in the dev structure.
2342  */
pci_scan_device(struct pci_bus * bus,int devfn)2343 static struct pci_dev *pci_scan_device(struct pci_bus *bus, int devfn)
2344 {
2345 	struct pci_dev *dev;
2346 	u32 l;
2347 
2348 	if (!pci_bus_read_dev_vendor_id(bus, devfn, &l, 60*1000))
2349 		return NULL;
2350 
2351 	dev = pci_alloc_dev(bus);
2352 	if (!dev)
2353 		return NULL;
2354 
2355 	dev->devfn = devfn;
2356 	dev->vendor = l & 0xffff;
2357 	dev->device = (l >> 16) & 0xffff;
2358 
2359 	pci_set_of_node(dev);
2360 
2361 	if (pci_setup_device(dev)) {
2362 		pci_release_of_node(dev);
2363 		pci_bus_put(dev->bus);
2364 		kfree(dev);
2365 		return NULL;
2366 	}
2367 
2368 	return dev;
2369 }
2370 
pcie_report_downtraining(struct pci_dev * dev)2371 static void pcie_report_downtraining(struct pci_dev *dev)
2372 {
2373 	if (!pci_is_pcie(dev))
2374 		return;
2375 
2376 	/* Look from the device up to avoid downstream ports with no devices */
2377 	if ((pci_pcie_type(dev) != PCI_EXP_TYPE_ENDPOINT) &&
2378 	    (pci_pcie_type(dev) != PCI_EXP_TYPE_LEG_END) &&
2379 	    (pci_pcie_type(dev) != PCI_EXP_TYPE_UPSTREAM))
2380 		return;
2381 
2382 	/* Multi-function PCIe devices share the same link/status */
2383 	if (PCI_FUNC(dev->devfn) != 0 || dev->is_virtfn)
2384 		return;
2385 
2386 	/* Print link status only if the device is constrained by the fabric */
2387 	__pcie_print_link_status(dev, false);
2388 }
2389 
pci_init_capabilities(struct pci_dev * dev)2390 static void pci_init_capabilities(struct pci_dev *dev)
2391 {
2392 	/* Enhanced Allocation */
2393 	pci_ea_init(dev);
2394 
2395 	/* Setup MSI caps & disable MSI/MSI-X interrupts */
2396 	pci_msi_setup_pci_dev(dev);
2397 
2398 	/* Buffers for saving PCIe and PCI-X capabilities */
2399 	pci_allocate_cap_save_buffers(dev);
2400 
2401 	/* Power Management */
2402 	pci_pm_init(dev);
2403 
2404 	/* Vital Product Data */
2405 	pci_vpd_init(dev);
2406 
2407 	/* Alternative Routing-ID Forwarding */
2408 	pci_configure_ari(dev);
2409 
2410 	/* Single Root I/O Virtualization */
2411 	pci_iov_init(dev);
2412 
2413 	/* Address Translation Services */
2414 	pci_ats_init(dev);
2415 
2416 	/* Enable ACS P2P upstream forwarding */
2417 	pci_enable_acs(dev);
2418 
2419 	/* Precision Time Measurement */
2420 	pci_ptm_init(dev);
2421 
2422 	/* Advanced Error Reporting */
2423 	pci_aer_init(dev);
2424 
2425 	pcie_report_downtraining(dev);
2426 
2427 	if (pci_probe_reset_function(dev) == 0)
2428 		dev->reset_fn = 1;
2429 }
2430 
2431 /*
2432  * This is the equivalent of pci_host_bridge_msi_domain() that acts on
2433  * devices. Firmware interfaces that can select the MSI domain on a
2434  * per-device basis should be called from here.
2435  */
pci_dev_msi_domain(struct pci_dev * dev)2436 static struct irq_domain *pci_dev_msi_domain(struct pci_dev *dev)
2437 {
2438 	struct irq_domain *d;
2439 
2440 	/*
2441 	 * If a domain has been set through the pcibios_add_device()
2442 	 * callback, then this is the one (platform code knows best).
2443 	 */
2444 	d = dev_get_msi_domain(&dev->dev);
2445 	if (d)
2446 		return d;
2447 
2448 	/*
2449 	 * Let's see if we have a firmware interface able to provide
2450 	 * the domain.
2451 	 */
2452 	d = pci_msi_get_device_domain(dev);
2453 	if (d)
2454 		return d;
2455 
2456 	return NULL;
2457 }
2458 
pci_set_msi_domain(struct pci_dev * dev)2459 static void pci_set_msi_domain(struct pci_dev *dev)
2460 {
2461 	struct irq_domain *d;
2462 
2463 	/*
2464 	 * If the platform or firmware interfaces cannot supply a
2465 	 * device-specific MSI domain, then inherit the default domain
2466 	 * from the host bridge itself.
2467 	 */
2468 	d = pci_dev_msi_domain(dev);
2469 	if (!d)
2470 		d = dev_get_msi_domain(&dev->bus->dev);
2471 
2472 	dev_set_msi_domain(&dev->dev, d);
2473 }
2474 
pci_device_add(struct pci_dev * dev,struct pci_bus * bus)2475 void pci_device_add(struct pci_dev *dev, struct pci_bus *bus)
2476 {
2477 	int ret;
2478 
2479 	pci_configure_device(dev);
2480 
2481 	device_initialize(&dev->dev);
2482 	dev->dev.release = pci_release_dev;
2483 
2484 	set_dev_node(&dev->dev, pcibus_to_node(bus));
2485 	dev->dev.dma_mask = &dev->dma_mask;
2486 	dev->dev.dma_parms = &dev->dma_parms;
2487 	dev->dev.coherent_dma_mask = 0xffffffffull;
2488 
2489 	pci_set_dma_max_seg_size(dev, 65536);
2490 	pci_set_dma_seg_boundary(dev, 0xffffffff);
2491 
2492 	/* Fix up broken headers */
2493 	pci_fixup_device(pci_fixup_header, dev);
2494 
2495 	/* Moved out from quirk header fixup code */
2496 	pci_reassigndev_resource_alignment(dev);
2497 
2498 	/* Clear the state_saved flag */
2499 	dev->state_saved = false;
2500 
2501 	/* Initialize various capabilities */
2502 	pci_init_capabilities(dev);
2503 
2504 	/*
2505 	 * Add the device to our list of discovered devices
2506 	 * and the bus list for fixup functions, etc.
2507 	 */
2508 	down_write(&pci_bus_sem);
2509 	list_add_tail(&dev->bus_list, &bus->devices);
2510 	up_write(&pci_bus_sem);
2511 
2512 	ret = pcibios_add_device(dev);
2513 	WARN_ON(ret < 0);
2514 
2515 	/* Set up MSI IRQ domain */
2516 	pci_set_msi_domain(dev);
2517 
2518 	/* Notifier could use PCI capabilities */
2519 	dev->match_driver = false;
2520 	ret = device_add(&dev->dev);
2521 	WARN_ON(ret < 0);
2522 }
2523 
pci_scan_single_device(struct pci_bus * bus,int devfn)2524 struct pci_dev *pci_scan_single_device(struct pci_bus *bus, int devfn)
2525 {
2526 	struct pci_dev *dev;
2527 
2528 	dev = pci_get_slot(bus, devfn);
2529 	if (dev) {
2530 		pci_dev_put(dev);
2531 		return dev;
2532 	}
2533 
2534 	dev = pci_scan_device(bus, devfn);
2535 	if (!dev)
2536 		return NULL;
2537 
2538 	pci_device_add(dev, bus);
2539 
2540 	return dev;
2541 }
2542 EXPORT_SYMBOL(pci_scan_single_device);
2543 
next_fn(struct pci_bus * bus,struct pci_dev * dev,unsigned fn)2544 static unsigned next_fn(struct pci_bus *bus, struct pci_dev *dev, unsigned fn)
2545 {
2546 	int pos;
2547 	u16 cap = 0;
2548 	unsigned next_fn;
2549 
2550 	if (pci_ari_enabled(bus)) {
2551 		if (!dev)
2552 			return 0;
2553 		pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ARI);
2554 		if (!pos)
2555 			return 0;
2556 
2557 		pci_read_config_word(dev, pos + PCI_ARI_CAP, &cap);
2558 		next_fn = PCI_ARI_CAP_NFN(cap);
2559 		if (next_fn <= fn)
2560 			return 0;	/* protect against malformed list */
2561 
2562 		return next_fn;
2563 	}
2564 
2565 	/* dev may be NULL for non-contiguous multifunction devices */
2566 	if (!dev || dev->multifunction)
2567 		return (fn + 1) % 8;
2568 
2569 	return 0;
2570 }
2571 
only_one_child(struct pci_bus * bus)2572 static int only_one_child(struct pci_bus *bus)
2573 {
2574 	struct pci_dev *bridge = bus->self;
2575 
2576 	/*
2577 	 * Systems with unusual topologies set PCI_SCAN_ALL_PCIE_DEVS so
2578 	 * we scan for all possible devices, not just Device 0.
2579 	 */
2580 	if (pci_has_flag(PCI_SCAN_ALL_PCIE_DEVS))
2581 		return 0;
2582 
2583 	/*
2584 	 * A PCIe Downstream Port normally leads to a Link with only Device
2585 	 * 0 on it (PCIe spec r3.1, sec 7.3.1).  As an optimization, scan
2586 	 * only for Device 0 in that situation.
2587 	 *
2588 	 * Checking has_secondary_link is a hack to identify Downstream
2589 	 * Ports because sometimes Switches are configured such that the
2590 	 * PCIe Port Type labels are backwards.
2591 	 */
2592 	if (bridge && pci_is_pcie(bridge) && bridge->has_secondary_link)
2593 		return 1;
2594 
2595 	return 0;
2596 }
2597 
2598 /**
2599  * pci_scan_slot - Scan a PCI slot on a bus for devices
2600  * @bus: PCI bus to scan
2601  * @devfn: slot number to scan (must have zero function)
2602  *
2603  * Scan a PCI slot on the specified PCI bus for devices, adding
2604  * discovered devices to the @bus->devices list.  New devices
2605  * will not have is_added set.
2606  *
2607  * Returns the number of new devices found.
2608  */
pci_scan_slot(struct pci_bus * bus,int devfn)2609 int pci_scan_slot(struct pci_bus *bus, int devfn)
2610 {
2611 	unsigned fn, nr = 0;
2612 	struct pci_dev *dev;
2613 
2614 	if (only_one_child(bus) && (devfn > 0))
2615 		return 0; /* Already scanned the entire slot */
2616 
2617 	dev = pci_scan_single_device(bus, devfn);
2618 	if (!dev)
2619 		return 0;
2620 	if (!pci_dev_is_added(dev))
2621 		nr++;
2622 
2623 	for (fn = next_fn(bus, dev, 0); fn > 0; fn = next_fn(bus, dev, fn)) {
2624 		dev = pci_scan_single_device(bus, devfn + fn);
2625 		if (dev) {
2626 			if (!pci_dev_is_added(dev))
2627 				nr++;
2628 			dev->multifunction = 1;
2629 		}
2630 	}
2631 
2632 	/* Only one slot has PCIe device */
2633 	if (bus->self && nr)
2634 		pcie_aspm_init_link_state(bus->self);
2635 
2636 	return nr;
2637 }
2638 EXPORT_SYMBOL(pci_scan_slot);
2639 
pcie_find_smpss(struct pci_dev * dev,void * data)2640 static int pcie_find_smpss(struct pci_dev *dev, void *data)
2641 {
2642 	u8 *smpss = data;
2643 
2644 	if (!pci_is_pcie(dev))
2645 		return 0;
2646 
2647 	/*
2648 	 * We don't have a way to change MPS settings on devices that have
2649 	 * drivers attached.  A hot-added device might support only the minimum
2650 	 * MPS setting (MPS=128).  Therefore, if the fabric contains a bridge
2651 	 * where devices may be hot-added, we limit the fabric MPS to 128 so
2652 	 * hot-added devices will work correctly.
2653 	 *
2654 	 * However, if we hot-add a device to a slot directly below a Root
2655 	 * Port, it's impossible for there to be other existing devices below
2656 	 * the port.  We don't limit the MPS in this case because we can
2657 	 * reconfigure MPS on both the Root Port and the hot-added device,
2658 	 * and there are no other devices involved.
2659 	 *
2660 	 * Note that this PCIE_BUS_SAFE path assumes no peer-to-peer DMA.
2661 	 */
2662 	if (dev->is_hotplug_bridge &&
2663 	    pci_pcie_type(dev) != PCI_EXP_TYPE_ROOT_PORT)
2664 		*smpss = 0;
2665 
2666 	if (*smpss > dev->pcie_mpss)
2667 		*smpss = dev->pcie_mpss;
2668 
2669 	return 0;
2670 }
2671 
pcie_write_mps(struct pci_dev * dev,int mps)2672 static void pcie_write_mps(struct pci_dev *dev, int mps)
2673 {
2674 	int rc;
2675 
2676 	if (pcie_bus_config == PCIE_BUS_PERFORMANCE) {
2677 		mps = 128 << dev->pcie_mpss;
2678 
2679 		if (pci_pcie_type(dev) != PCI_EXP_TYPE_ROOT_PORT &&
2680 		    dev->bus->self)
2681 
2682 			/*
2683 			 * For "Performance", the assumption is made that
2684 			 * downstream communication will never be larger than
2685 			 * the MRRS.  So, the MPS only needs to be configured
2686 			 * for the upstream communication.  This being the case,
2687 			 * walk from the top down and set the MPS of the child
2688 			 * to that of the parent bus.
2689 			 *
2690 			 * Configure the device MPS with the smaller of the
2691 			 * device MPSS or the bridge MPS (which is assumed to be
2692 			 * properly configured at this point to the largest
2693 			 * allowable MPS based on its parent bus).
2694 			 */
2695 			mps = min(mps, pcie_get_mps(dev->bus->self));
2696 	}
2697 
2698 	rc = pcie_set_mps(dev, mps);
2699 	if (rc)
2700 		pci_err(dev, "Failed attempting to set the MPS\n");
2701 }
2702 
pcie_write_mrrs(struct pci_dev * dev)2703 static void pcie_write_mrrs(struct pci_dev *dev)
2704 {
2705 	int rc, mrrs;
2706 
2707 	/*
2708 	 * In the "safe" case, do not configure the MRRS.  There appear to be
2709 	 * issues with setting MRRS to 0 on a number of devices.
2710 	 */
2711 	if (pcie_bus_config != PCIE_BUS_PERFORMANCE)
2712 		return;
2713 
2714 	/*
2715 	 * For max performance, the MRRS must be set to the largest supported
2716 	 * value.  However, it cannot be configured larger than the MPS the
2717 	 * device or the bus can support.  This should already be properly
2718 	 * configured by a prior call to pcie_write_mps().
2719 	 */
2720 	mrrs = pcie_get_mps(dev);
2721 
2722 	/*
2723 	 * MRRS is a R/W register.  Invalid values can be written, but a
2724 	 * subsequent read will verify if the value is acceptable or not.
2725 	 * If the MRRS value provided is not acceptable (e.g., too large),
2726 	 * shrink the value until it is acceptable to the HW.
2727 	 */
2728 	while (mrrs != pcie_get_readrq(dev) && mrrs >= 128) {
2729 		rc = pcie_set_readrq(dev, mrrs);
2730 		if (!rc)
2731 			break;
2732 
2733 		pci_warn(dev, "Failed attempting to set the MRRS\n");
2734 		mrrs /= 2;
2735 	}
2736 
2737 	if (mrrs < 128)
2738 		pci_err(dev, "MRRS was unable to be configured with a safe value.  If problems are experienced, try running with pci=pcie_bus_safe\n");
2739 }
2740 
pcie_bus_configure_set(struct pci_dev * dev,void * data)2741 static int pcie_bus_configure_set(struct pci_dev *dev, void *data)
2742 {
2743 	int mps, orig_mps;
2744 
2745 	if (!pci_is_pcie(dev))
2746 		return 0;
2747 
2748 	if (pcie_bus_config == PCIE_BUS_TUNE_OFF ||
2749 	    pcie_bus_config == PCIE_BUS_DEFAULT)
2750 		return 0;
2751 
2752 	mps = 128 << *(u8 *)data;
2753 	orig_mps = pcie_get_mps(dev);
2754 
2755 	pcie_write_mps(dev, mps);
2756 	pcie_write_mrrs(dev);
2757 
2758 	pci_info(dev, "Max Payload Size set to %4d/%4d (was %4d), Max Read Rq %4d\n",
2759 		 pcie_get_mps(dev), 128 << dev->pcie_mpss,
2760 		 orig_mps, pcie_get_readrq(dev));
2761 
2762 	return 0;
2763 }
2764 
2765 /*
2766  * pcie_bus_configure_settings() requires that pci_walk_bus work in a top-down,
2767  * parents then children fashion.  If this changes, then this code will not
2768  * work as designed.
2769  */
pcie_bus_configure_settings(struct pci_bus * bus)2770 void pcie_bus_configure_settings(struct pci_bus *bus)
2771 {
2772 	u8 smpss = 0;
2773 
2774 	if (!bus->self)
2775 		return;
2776 
2777 	if (!pci_is_pcie(bus->self))
2778 		return;
2779 
2780 	/*
2781 	 * FIXME - Peer to peer DMA is possible, though the endpoint would need
2782 	 * to be aware of the MPS of the destination.  To work around this,
2783 	 * simply force the MPS of the entire system to the smallest possible.
2784 	 */
2785 	if (pcie_bus_config == PCIE_BUS_PEER2PEER)
2786 		smpss = 0;
2787 
2788 	if (pcie_bus_config == PCIE_BUS_SAFE) {
2789 		smpss = bus->self->pcie_mpss;
2790 
2791 		pcie_find_smpss(bus->self, &smpss);
2792 		pci_walk_bus(bus, pcie_find_smpss, &smpss);
2793 	}
2794 
2795 	pcie_bus_configure_set(bus->self, &smpss);
2796 	pci_walk_bus(bus, pcie_bus_configure_set, &smpss);
2797 }
2798 EXPORT_SYMBOL_GPL(pcie_bus_configure_settings);
2799 
2800 /*
2801  * Called after each bus is probed, but before its children are examined.  This
2802  * is marked as __weak because multiple architectures define it.
2803  */
pcibios_fixup_bus(struct pci_bus * bus)2804 void __weak pcibios_fixup_bus(struct pci_bus *bus)
2805 {
2806        /* nothing to do, expected to be removed in the future */
2807 }
2808 
2809 /**
2810  * pci_scan_child_bus_extend() - Scan devices below a bus
2811  * @bus: Bus to scan for devices
2812  * @available_buses: Total number of buses available (%0 does not try to
2813  *		     extend beyond the minimal)
2814  *
2815  * Scans devices below @bus including subordinate buses. Returns new
2816  * subordinate number including all the found devices. Passing
2817  * @available_buses causes the remaining bus space to be distributed
2818  * equally between hotplug-capable bridges to allow future extension of the
2819  * hierarchy.
2820  */
pci_scan_child_bus_extend(struct pci_bus * bus,unsigned int available_buses)2821 static unsigned int pci_scan_child_bus_extend(struct pci_bus *bus,
2822 					      unsigned int available_buses)
2823 {
2824 	unsigned int used_buses, normal_bridges = 0, hotplug_bridges = 0;
2825 	unsigned int start = bus->busn_res.start;
2826 	unsigned int devfn, fn, cmax, max = start;
2827 	struct pci_dev *dev;
2828 	int nr_devs;
2829 
2830 	dev_dbg(&bus->dev, "scanning bus\n");
2831 
2832 	/* Go find them, Rover! */
2833 	for (devfn = 0; devfn < 256; devfn += 8) {
2834 		nr_devs = pci_scan_slot(bus, devfn);
2835 
2836 		/*
2837 		 * The Jailhouse hypervisor may pass individual functions of a
2838 		 * multi-function device to a guest without passing function 0.
2839 		 * Look for them as well.
2840 		 */
2841 		if (jailhouse_paravirt() && nr_devs == 0) {
2842 			for (fn = 1; fn < 8; fn++) {
2843 				dev = pci_scan_single_device(bus, devfn + fn);
2844 				if (dev)
2845 					dev->multifunction = 1;
2846 			}
2847 		}
2848 	}
2849 
2850 	/* Reserve buses for SR-IOV capability */
2851 	used_buses = pci_iov_bus_range(bus);
2852 	max += used_buses;
2853 
2854 	/*
2855 	 * After performing arch-dependent fixup of the bus, look behind
2856 	 * all PCI-to-PCI bridges on this bus.
2857 	 */
2858 	if (!bus->is_added) {
2859 		dev_dbg(&bus->dev, "fixups for bus\n");
2860 		pcibios_fixup_bus(bus);
2861 		bus->is_added = 1;
2862 	}
2863 
2864 	/*
2865 	 * Calculate how many hotplug bridges and normal bridges there
2866 	 * are on this bus. We will distribute the additional available
2867 	 * buses between hotplug bridges.
2868 	 */
2869 	for_each_pci_bridge(dev, bus) {
2870 		if (dev->is_hotplug_bridge)
2871 			hotplug_bridges++;
2872 		else
2873 			normal_bridges++;
2874 	}
2875 
2876 	/*
2877 	 * Scan bridges that are already configured. We don't touch them
2878 	 * unless they are misconfigured (which will be done in the second
2879 	 * scan below).
2880 	 */
2881 	for_each_pci_bridge(dev, bus) {
2882 		cmax = max;
2883 		max = pci_scan_bridge_extend(bus, dev, max, 0, 0);
2884 
2885 		/*
2886 		 * Reserve one bus for each bridge now to avoid extending
2887 		 * hotplug bridges too much during the second scan below.
2888 		 */
2889 		used_buses++;
2890 		if (cmax - max > 1)
2891 			used_buses += cmax - max - 1;
2892 	}
2893 
2894 	/* Scan bridges that need to be reconfigured */
2895 	for_each_pci_bridge(dev, bus) {
2896 		unsigned int buses = 0;
2897 
2898 		if (!hotplug_bridges && normal_bridges == 1) {
2899 
2900 			/*
2901 			 * There is only one bridge on the bus (upstream
2902 			 * port) so it gets all available buses which it
2903 			 * can then distribute to the possible hotplug
2904 			 * bridges below.
2905 			 */
2906 			buses = available_buses;
2907 		} else if (dev->is_hotplug_bridge) {
2908 
2909 			/*
2910 			 * Distribute the extra buses between hotplug
2911 			 * bridges if any.
2912 			 */
2913 			buses = available_buses / hotplug_bridges;
2914 			buses = min(buses, available_buses - used_buses + 1);
2915 		}
2916 
2917 		cmax = max;
2918 		max = pci_scan_bridge_extend(bus, dev, cmax, buses, 1);
2919 		/* One bus is already accounted so don't add it again */
2920 		if (max - cmax > 1)
2921 			used_buses += max - cmax - 1;
2922 	}
2923 
2924 	/*
2925 	 * Make sure a hotplug bridge has at least the minimum requested
2926 	 * number of buses but allow it to grow up to the maximum available
2927 	 * bus number of there is room.
2928 	 */
2929 	if (bus->self && bus->self->is_hotplug_bridge) {
2930 		used_buses = max_t(unsigned int, available_buses,
2931 				   pci_hotplug_bus_size - 1);
2932 		if (max - start < used_buses) {
2933 			max = start + used_buses;
2934 
2935 			/* Do not allocate more buses than we have room left */
2936 			if (max > bus->busn_res.end)
2937 				max = bus->busn_res.end;
2938 
2939 			dev_dbg(&bus->dev, "%pR extended by %#02x\n",
2940 				&bus->busn_res, max - start);
2941 		}
2942 	}
2943 
2944 	/*
2945 	 * We've scanned the bus and so we know all about what's on
2946 	 * the other side of any bridges that may be on this bus plus
2947 	 * any devices.
2948 	 *
2949 	 * Return how far we've got finding sub-buses.
2950 	 */
2951 	dev_dbg(&bus->dev, "bus scan returning with max=%02x\n", max);
2952 	return max;
2953 }
2954 
2955 /**
2956  * pci_scan_child_bus() - Scan devices below a bus
2957  * @bus: Bus to scan for devices
2958  *
2959  * Scans devices below @bus including subordinate buses. Returns new
2960  * subordinate number including all the found devices.
2961  */
pci_scan_child_bus(struct pci_bus * bus)2962 unsigned int pci_scan_child_bus(struct pci_bus *bus)
2963 {
2964 	return pci_scan_child_bus_extend(bus, 0);
2965 }
2966 EXPORT_SYMBOL_GPL(pci_scan_child_bus);
2967 
2968 /**
2969  * pcibios_root_bridge_prepare - Platform-specific host bridge setup
2970  * @bridge: Host bridge to set up
2971  *
2972  * Default empty implementation.  Replace with an architecture-specific setup
2973  * routine, if necessary.
2974  */
pcibios_root_bridge_prepare(struct pci_host_bridge * bridge)2975 int __weak pcibios_root_bridge_prepare(struct pci_host_bridge *bridge)
2976 {
2977 	return 0;
2978 }
2979 
pcibios_add_bus(struct pci_bus * bus)2980 void __weak pcibios_add_bus(struct pci_bus *bus)
2981 {
2982 }
2983 
pcibios_remove_bus(struct pci_bus * bus)2984 void __weak pcibios_remove_bus(struct pci_bus *bus)
2985 {
2986 }
2987 
pci_create_root_bus(struct device * parent,int bus,struct pci_ops * ops,void * sysdata,struct list_head * resources)2988 struct pci_bus *pci_create_root_bus(struct device *parent, int bus,
2989 		struct pci_ops *ops, void *sysdata, struct list_head *resources)
2990 {
2991 	int error;
2992 	struct pci_host_bridge *bridge;
2993 
2994 	bridge = pci_alloc_host_bridge(0);
2995 	if (!bridge)
2996 		return NULL;
2997 
2998 	bridge->dev.parent = parent;
2999 
3000 	list_splice_init(resources, &bridge->windows);
3001 	bridge->sysdata = sysdata;
3002 	bridge->busnr = bus;
3003 	bridge->ops = ops;
3004 
3005 	error = pci_register_host_bridge(bridge);
3006 	if (error < 0)
3007 		goto err_out;
3008 
3009 	return bridge->bus;
3010 
3011 err_out:
3012 	kfree(bridge);
3013 	return NULL;
3014 }
3015 EXPORT_SYMBOL_GPL(pci_create_root_bus);
3016 
pci_host_probe(struct pci_host_bridge * bridge)3017 int pci_host_probe(struct pci_host_bridge *bridge)
3018 {
3019 	struct pci_bus *bus, *child;
3020 	int ret;
3021 
3022 	ret = pci_scan_root_bus_bridge(bridge);
3023 	if (ret < 0) {
3024 		dev_err(bridge->dev.parent, "Scanning root bridge failed");
3025 		return ret;
3026 	}
3027 
3028 	bus = bridge->bus;
3029 
3030 	/*
3031 	 * We insert PCI resources into the iomem_resource and
3032 	 * ioport_resource trees in either pci_bus_claim_resources()
3033 	 * or pci_bus_assign_resources().
3034 	 */
3035 	if (pci_has_flag(PCI_PROBE_ONLY)) {
3036 		pci_bus_claim_resources(bus);
3037 	} else {
3038 		pci_bus_size_bridges(bus);
3039 		pci_bus_assign_resources(bus);
3040 
3041 		list_for_each_entry(child, &bus->children, node)
3042 			pcie_bus_configure_settings(child);
3043 	}
3044 
3045 	pci_bus_add_devices(bus);
3046 	return 0;
3047 }
3048 EXPORT_SYMBOL_GPL(pci_host_probe);
3049 
pci_bus_insert_busn_res(struct pci_bus * b,int bus,int bus_max)3050 int pci_bus_insert_busn_res(struct pci_bus *b, int bus, int bus_max)
3051 {
3052 	struct resource *res = &b->busn_res;
3053 	struct resource *parent_res, *conflict;
3054 
3055 	res->start = bus;
3056 	res->end = bus_max;
3057 	res->flags = IORESOURCE_BUS;
3058 
3059 	if (!pci_is_root_bus(b))
3060 		parent_res = &b->parent->busn_res;
3061 	else {
3062 		parent_res = get_pci_domain_busn_res(pci_domain_nr(b));
3063 		res->flags |= IORESOURCE_PCI_FIXED;
3064 	}
3065 
3066 	conflict = request_resource_conflict(parent_res, res);
3067 
3068 	if (conflict)
3069 		dev_printk(KERN_DEBUG, &b->dev,
3070 			   "busn_res: can not insert %pR under %s%pR (conflicts with %s %pR)\n",
3071 			    res, pci_is_root_bus(b) ? "domain " : "",
3072 			    parent_res, conflict->name, conflict);
3073 
3074 	return conflict == NULL;
3075 }
3076 
pci_bus_update_busn_res_end(struct pci_bus * b,int bus_max)3077 int pci_bus_update_busn_res_end(struct pci_bus *b, int bus_max)
3078 {
3079 	struct resource *res = &b->busn_res;
3080 	struct resource old_res = *res;
3081 	resource_size_t size;
3082 	int ret;
3083 
3084 	if (res->start > bus_max)
3085 		return -EINVAL;
3086 
3087 	size = bus_max - res->start + 1;
3088 	ret = adjust_resource(res, res->start, size);
3089 	dev_printk(KERN_DEBUG, &b->dev,
3090 			"busn_res: %pR end %s updated to %02x\n",
3091 			&old_res, ret ? "can not be" : "is", bus_max);
3092 
3093 	if (!ret && !res->parent)
3094 		pci_bus_insert_busn_res(b, res->start, res->end);
3095 
3096 	return ret;
3097 }
3098 
pci_bus_release_busn_res(struct pci_bus * b)3099 void pci_bus_release_busn_res(struct pci_bus *b)
3100 {
3101 	struct resource *res = &b->busn_res;
3102 	int ret;
3103 
3104 	if (!res->flags || !res->parent)
3105 		return;
3106 
3107 	ret = release_resource(res);
3108 	dev_printk(KERN_DEBUG, &b->dev,
3109 			"busn_res: %pR %s released\n",
3110 			res, ret ? "can not be" : "is");
3111 }
3112 
pci_scan_root_bus_bridge(struct pci_host_bridge * bridge)3113 int pci_scan_root_bus_bridge(struct pci_host_bridge *bridge)
3114 {
3115 	struct resource_entry *window;
3116 	bool found = false;
3117 	struct pci_bus *b;
3118 	int max, bus, ret;
3119 
3120 	if (!bridge)
3121 		return -EINVAL;
3122 
3123 	resource_list_for_each_entry(window, &bridge->windows)
3124 		if (window->res->flags & IORESOURCE_BUS) {
3125 			found = true;
3126 			break;
3127 		}
3128 
3129 	ret = pci_register_host_bridge(bridge);
3130 	if (ret < 0)
3131 		return ret;
3132 
3133 	b = bridge->bus;
3134 	bus = bridge->busnr;
3135 
3136 	if (!found) {
3137 		dev_info(&b->dev,
3138 		 "No busn resource found for root bus, will use [bus %02x-ff]\n",
3139 			bus);
3140 		pci_bus_insert_busn_res(b, bus, 255);
3141 	}
3142 
3143 	max = pci_scan_child_bus(b);
3144 
3145 	if (!found)
3146 		pci_bus_update_busn_res_end(b, max);
3147 
3148 	return 0;
3149 }
3150 EXPORT_SYMBOL(pci_scan_root_bus_bridge);
3151 
pci_scan_root_bus(struct device * parent,int bus,struct pci_ops * ops,void * sysdata,struct list_head * resources)3152 struct pci_bus *pci_scan_root_bus(struct device *parent, int bus,
3153 		struct pci_ops *ops, void *sysdata, struct list_head *resources)
3154 {
3155 	struct resource_entry *window;
3156 	bool found = false;
3157 	struct pci_bus *b;
3158 	int max;
3159 
3160 	resource_list_for_each_entry(window, resources)
3161 		if (window->res->flags & IORESOURCE_BUS) {
3162 			found = true;
3163 			break;
3164 		}
3165 
3166 	b = pci_create_root_bus(parent, bus, ops, sysdata, resources);
3167 	if (!b)
3168 		return NULL;
3169 
3170 	if (!found) {
3171 		dev_info(&b->dev,
3172 		 "No busn resource found for root bus, will use [bus %02x-ff]\n",
3173 			bus);
3174 		pci_bus_insert_busn_res(b, bus, 255);
3175 	}
3176 
3177 	max = pci_scan_child_bus(b);
3178 
3179 	if (!found)
3180 		pci_bus_update_busn_res_end(b, max);
3181 
3182 	return b;
3183 }
3184 EXPORT_SYMBOL(pci_scan_root_bus);
3185 
pci_scan_bus(int bus,struct pci_ops * ops,void * sysdata)3186 struct pci_bus *pci_scan_bus(int bus, struct pci_ops *ops,
3187 					void *sysdata)
3188 {
3189 	LIST_HEAD(resources);
3190 	struct pci_bus *b;
3191 
3192 	pci_add_resource(&resources, &ioport_resource);
3193 	pci_add_resource(&resources, &iomem_resource);
3194 	pci_add_resource(&resources, &busn_resource);
3195 	b = pci_create_root_bus(NULL, bus, ops, sysdata, &resources);
3196 	if (b) {
3197 		pci_scan_child_bus(b);
3198 	} else {
3199 		pci_free_resource_list(&resources);
3200 	}
3201 	return b;
3202 }
3203 EXPORT_SYMBOL(pci_scan_bus);
3204 
3205 /**
3206  * pci_rescan_bus_bridge_resize - Scan a PCI bus for devices
3207  * @bridge: PCI bridge for the bus to scan
3208  *
3209  * Scan a PCI bus and child buses for new devices, add them,
3210  * and enable them, resizing bridge mmio/io resource if necessary
3211  * and possible.  The caller must ensure the child devices are already
3212  * removed for resizing to occur.
3213  *
3214  * Returns the max number of subordinate bus discovered.
3215  */
pci_rescan_bus_bridge_resize(struct pci_dev * bridge)3216 unsigned int pci_rescan_bus_bridge_resize(struct pci_dev *bridge)
3217 {
3218 	unsigned int max;
3219 	struct pci_bus *bus = bridge->subordinate;
3220 
3221 	max = pci_scan_child_bus(bus);
3222 
3223 	pci_assign_unassigned_bridge_resources(bridge);
3224 
3225 	pci_bus_add_devices(bus);
3226 
3227 	return max;
3228 }
3229 
3230 /**
3231  * pci_rescan_bus - Scan a PCI bus for devices
3232  * @bus: PCI bus to scan
3233  *
3234  * Scan a PCI bus and child buses for new devices, add them,
3235  * and enable them.
3236  *
3237  * Returns the max number of subordinate bus discovered.
3238  */
pci_rescan_bus(struct pci_bus * bus)3239 unsigned int pci_rescan_bus(struct pci_bus *bus)
3240 {
3241 	unsigned int max;
3242 
3243 	max = pci_scan_child_bus(bus);
3244 	pci_assign_unassigned_bus_resources(bus);
3245 	pci_bus_add_devices(bus);
3246 
3247 	return max;
3248 }
3249 EXPORT_SYMBOL_GPL(pci_rescan_bus);
3250 
3251 /*
3252  * pci_rescan_bus(), pci_rescan_bus_bridge_resize() and PCI device removal
3253  * routines should always be executed under this mutex.
3254  */
3255 static DEFINE_MUTEX(pci_rescan_remove_lock);
3256 
pci_lock_rescan_remove(void)3257 void pci_lock_rescan_remove(void)
3258 {
3259 	mutex_lock(&pci_rescan_remove_lock);
3260 }
3261 EXPORT_SYMBOL_GPL(pci_lock_rescan_remove);
3262 
pci_unlock_rescan_remove(void)3263 void pci_unlock_rescan_remove(void)
3264 {
3265 	mutex_unlock(&pci_rescan_remove_lock);
3266 }
3267 EXPORT_SYMBOL_GPL(pci_unlock_rescan_remove);
3268 
pci_sort_bf_cmp(const struct device * d_a,const struct device * d_b)3269 static int __init pci_sort_bf_cmp(const struct device *d_a,
3270 				  const struct device *d_b)
3271 {
3272 	const struct pci_dev *a = to_pci_dev(d_a);
3273 	const struct pci_dev *b = to_pci_dev(d_b);
3274 
3275 	if      (pci_domain_nr(a->bus) < pci_domain_nr(b->bus)) return -1;
3276 	else if (pci_domain_nr(a->bus) > pci_domain_nr(b->bus)) return  1;
3277 
3278 	if      (a->bus->number < b->bus->number) return -1;
3279 	else if (a->bus->number > b->bus->number) return  1;
3280 
3281 	if      (a->devfn < b->devfn) return -1;
3282 	else if (a->devfn > b->devfn) return  1;
3283 
3284 	return 0;
3285 }
3286 
pci_sort_breadthfirst(void)3287 void __init pci_sort_breadthfirst(void)
3288 {
3289 	bus_sort_breadthfirst(&pci_bus_type, &pci_sort_bf_cmp);
3290 }
3291 
pci_hp_add_bridge(struct pci_dev * dev)3292 int pci_hp_add_bridge(struct pci_dev *dev)
3293 {
3294 	struct pci_bus *parent = dev->bus;
3295 	int busnr, start = parent->busn_res.start;
3296 	unsigned int available_buses = 0;
3297 	int end = parent->busn_res.end;
3298 
3299 	for (busnr = start; busnr <= end; busnr++) {
3300 		if (!pci_find_bus(pci_domain_nr(parent), busnr))
3301 			break;
3302 	}
3303 	if (busnr-- > end) {
3304 		pci_err(dev, "No bus number available for hot-added bridge\n");
3305 		return -1;
3306 	}
3307 
3308 	/* Scan bridges that are already configured */
3309 	busnr = pci_scan_bridge(parent, dev, busnr, 0);
3310 
3311 	/*
3312 	 * Distribute the available bus numbers between hotplug-capable
3313 	 * bridges to make extending the chain later possible.
3314 	 */
3315 	available_buses = end - busnr;
3316 
3317 	/* Scan bridges that need to be reconfigured */
3318 	pci_scan_bridge_extend(parent, dev, busnr, available_buses, 1);
3319 
3320 	if (!dev->subordinate)
3321 		return -1;
3322 
3323 	return 0;
3324 }
3325 EXPORT_SYMBOL_GPL(pci_hp_add_bridge);
3326