• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * PCI Bus Services, see include/linux/pci.h for further explanation.
4  *
5  * Copyright 1993 -- 1997 Drew Eckhardt, Frederic Potter,
6  * David Mosberger-Tang
7  *
8  * Copyright 1997 -- 2000 Martin Mares <mj@ucw.cz>
9  */
10 
11 #include <linux/acpi.h>
12 #include <linux/kernel.h>
13 #include <linux/delay.h>
14 #include <linux/dmi.h>
15 #include <linux/init.h>
16 #include <linux/msi.h>
17 #include <linux/of.h>
18 #include <linux/pci.h>
19 #include <linux/pm.h>
20 #include <linux/slab.h>
21 #include <linux/module.h>
22 #include <linux/spinlock.h>
23 #include <linux/string.h>
24 #include <linux/log2.h>
25 #include <linux/logic_pio.h>
26 #include <linux/pm_wakeup.h>
27 #include <linux/interrupt.h>
28 #include <linux/device.h>
29 #include <linux/pm_runtime.h>
30 #include <linux/pci_hotplug.h>
31 #include <linux/vmalloc.h>
32 #include <asm/dma.h>
33 #include <linux/aer.h>
34 #ifndef  __GENKSYMS__
35 #include <trace/hooks/pci.h>
36 #endif
37 #include "pci.h"
38 
39 DEFINE_MUTEX(pci_slot_mutex);
40 
41 const char *pci_power_names[] = {
42 	"error", "D0", "D1", "D2", "D3hot", "D3cold", "unknown",
43 };
44 EXPORT_SYMBOL_GPL(pci_power_names);
45 
46 int isa_dma_bridge_buggy;
47 EXPORT_SYMBOL(isa_dma_bridge_buggy);
48 
49 int pci_pci_problems;
50 EXPORT_SYMBOL(pci_pci_problems);
51 
52 unsigned int pci_pm_d3hot_delay;
53 
54 static void pci_pme_list_scan(struct work_struct *work);
55 
56 static LIST_HEAD(pci_pme_list);
57 static DEFINE_MUTEX(pci_pme_list_mutex);
58 static DECLARE_DELAYED_WORK(pci_pme_work, pci_pme_list_scan);
59 
60 struct pci_pme_device {
61 	struct list_head list;
62 	struct pci_dev *dev;
63 };
64 
65 #define PME_TIMEOUT 1000 /* How long between PME checks */
66 
pci_dev_d3_sleep(struct pci_dev * dev)67 static void pci_dev_d3_sleep(struct pci_dev *dev)
68 {
69 	unsigned int delay = dev->d3hot_delay;
70 	int err = -EOPNOTSUPP;
71 
72 	if (delay < pci_pm_d3hot_delay)
73 		delay = pci_pm_d3hot_delay;
74 
75 	if (delay) {
76 		trace_android_rvh_pci_d3_sleep(dev, delay, &err);
77 		if (err == -EOPNOTSUPP)
78 			msleep(delay);
79 	}
80 }
81 
82 #ifdef CONFIG_PCI_DOMAINS
83 int pci_domains_supported = 1;
84 #endif
85 
86 #define DEFAULT_CARDBUS_IO_SIZE		(256)
87 #define DEFAULT_CARDBUS_MEM_SIZE	(64*1024*1024)
88 /* pci=cbmemsize=nnM,cbiosize=nn can override this */
89 unsigned long pci_cardbus_io_size = DEFAULT_CARDBUS_IO_SIZE;
90 unsigned long pci_cardbus_mem_size = DEFAULT_CARDBUS_MEM_SIZE;
91 
92 #define DEFAULT_HOTPLUG_IO_SIZE		(256)
93 #define DEFAULT_HOTPLUG_MMIO_SIZE	(2*1024*1024)
94 #define DEFAULT_HOTPLUG_MMIO_PREF_SIZE	(2*1024*1024)
95 /* hpiosize=nn can override this */
96 unsigned long pci_hotplug_io_size  = DEFAULT_HOTPLUG_IO_SIZE;
97 /*
98  * pci=hpmmiosize=nnM overrides non-prefetchable MMIO size,
99  * pci=hpmmioprefsize=nnM overrides prefetchable MMIO size;
100  * pci=hpmemsize=nnM overrides both
101  */
102 unsigned long pci_hotplug_mmio_size = DEFAULT_HOTPLUG_MMIO_SIZE;
103 unsigned long pci_hotplug_mmio_pref_size = DEFAULT_HOTPLUG_MMIO_PREF_SIZE;
104 
105 #define DEFAULT_HOTPLUG_BUS_SIZE	1
106 unsigned long pci_hotplug_bus_size = DEFAULT_HOTPLUG_BUS_SIZE;
107 
108 
109 /* PCIe MPS/MRRS strategy; can be overridden by kernel command-line param */
110 #ifdef CONFIG_PCIE_BUS_TUNE_OFF
111 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_TUNE_OFF;
112 #elif defined CONFIG_PCIE_BUS_SAFE
113 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_SAFE;
114 #elif defined CONFIG_PCIE_BUS_PERFORMANCE
115 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_PERFORMANCE;
116 #elif defined CONFIG_PCIE_BUS_PEER2PEER
117 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_PEER2PEER;
118 #else
119 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_DEFAULT;
120 #endif
121 
122 /*
123  * The default CLS is used if arch didn't set CLS explicitly and not
124  * all pci devices agree on the same value.  Arch can override either
125  * the dfl or actual value as it sees fit.  Don't forget this is
126  * measured in 32-bit words, not bytes.
127  */
128 u8 pci_dfl_cache_line_size = L1_CACHE_BYTES >> 2;
129 u8 pci_cache_line_size;
130 
131 /*
132  * If we set up a device for bus mastering, we need to check the latency
133  * timer as certain BIOSes forget to set it properly.
134  */
135 unsigned int pcibios_max_latency = 255;
136 
137 /* If set, the PCIe ARI capability will not be used. */
138 static bool pcie_ari_disabled;
139 
140 /* If set, the PCIe ATS capability will not be used. */
141 static bool pcie_ats_disabled;
142 
143 /* If set, the PCI config space of each device is printed during boot. */
144 bool pci_early_dump;
145 
pci_ats_disabled(void)146 bool pci_ats_disabled(void)
147 {
148 	return pcie_ats_disabled;
149 }
150 EXPORT_SYMBOL_GPL(pci_ats_disabled);
151 
152 /* Disable bridge_d3 for all PCIe ports */
153 static bool pci_bridge_d3_disable;
154 /* Force bridge_d3 for all PCIe ports */
155 static bool pci_bridge_d3_force;
156 
pcie_port_pm_setup(char * str)157 static int __init pcie_port_pm_setup(char *str)
158 {
159 	if (!strcmp(str, "off"))
160 		pci_bridge_d3_disable = true;
161 	else if (!strcmp(str, "force"))
162 		pci_bridge_d3_force = true;
163 	return 1;
164 }
165 __setup("pcie_port_pm=", pcie_port_pm_setup);
166 
167 /**
168  * pci_bus_max_busnr - returns maximum PCI bus number of given bus' children
169  * @bus: pointer to PCI bus structure to search
170  *
171  * Given a PCI bus, returns the highest PCI bus number present in the set
172  * including the given PCI bus and its list of child PCI buses.
173  */
pci_bus_max_busnr(struct pci_bus * bus)174 unsigned char pci_bus_max_busnr(struct pci_bus *bus)
175 {
176 	struct pci_bus *tmp;
177 	unsigned char max, n;
178 
179 	max = bus->busn_res.end;
180 	list_for_each_entry(tmp, &bus->children, node) {
181 		n = pci_bus_max_busnr(tmp);
182 		if (n > max)
183 			max = n;
184 	}
185 	return max;
186 }
187 EXPORT_SYMBOL_GPL(pci_bus_max_busnr);
188 
189 /**
190  * pci_status_get_and_clear_errors - return and clear error bits in PCI_STATUS
191  * @pdev: the PCI device
192  *
193  * Returns error bits set in PCI_STATUS and clears them.
194  */
pci_status_get_and_clear_errors(struct pci_dev * pdev)195 int pci_status_get_and_clear_errors(struct pci_dev *pdev)
196 {
197 	u16 status;
198 	int ret;
199 
200 	ret = pci_read_config_word(pdev, PCI_STATUS, &status);
201 	if (ret != PCIBIOS_SUCCESSFUL)
202 		return -EIO;
203 
204 	status &= PCI_STATUS_ERROR_BITS;
205 	if (status)
206 		pci_write_config_word(pdev, PCI_STATUS, status);
207 
208 	return status;
209 }
210 EXPORT_SYMBOL_GPL(pci_status_get_and_clear_errors);
211 
212 #ifdef CONFIG_HAS_IOMEM
pci_ioremap_bar(struct pci_dev * pdev,int bar)213 void __iomem *pci_ioremap_bar(struct pci_dev *pdev, int bar)
214 {
215 	struct resource *res = &pdev->resource[bar];
216 
217 	/*
218 	 * Make sure the BAR is actually a memory resource, not an IO resource
219 	 */
220 	if (res->flags & IORESOURCE_UNSET || !(res->flags & IORESOURCE_MEM)) {
221 		pci_warn(pdev, "can't ioremap BAR %d: %pR\n", bar, res);
222 		return NULL;
223 	}
224 	return ioremap(res->start, resource_size(res));
225 }
226 EXPORT_SYMBOL_GPL(pci_ioremap_bar);
227 
pci_ioremap_wc_bar(struct pci_dev * pdev,int bar)228 void __iomem *pci_ioremap_wc_bar(struct pci_dev *pdev, int bar)
229 {
230 	/*
231 	 * Make sure the BAR is actually a memory resource, not an IO resource
232 	 */
233 	if (!(pci_resource_flags(pdev, bar) & IORESOURCE_MEM)) {
234 		WARN_ON(1);
235 		return NULL;
236 	}
237 	return ioremap_wc(pci_resource_start(pdev, bar),
238 			  pci_resource_len(pdev, bar));
239 }
240 EXPORT_SYMBOL_GPL(pci_ioremap_wc_bar);
241 #endif
242 
243 /**
244  * pci_dev_str_match_path - test if a path string matches a device
245  * @dev: the PCI device to test
246  * @path: string to match the device against
247  * @endptr: pointer to the string after the match
248  *
249  * Test if a string (typically from a kernel parameter) formatted as a
250  * path of device/function addresses matches a PCI device. The string must
251  * be of the form:
252  *
253  *   [<domain>:]<bus>:<device>.<func>[/<device>.<func>]*
254  *
255  * A path for a device can be obtained using 'lspci -t'.  Using a path
256  * is more robust against bus renumbering than using only a single bus,
257  * device and function address.
258  *
259  * Returns 1 if the string matches the device, 0 if it does not and
260  * a negative error code if it fails to parse the string.
261  */
pci_dev_str_match_path(struct pci_dev * dev,const char * path,const char ** endptr)262 static int pci_dev_str_match_path(struct pci_dev *dev, const char *path,
263 				  const char **endptr)
264 {
265 	int ret;
266 	int seg, bus, slot, func;
267 	char *wpath, *p;
268 	char end;
269 
270 	*endptr = strchrnul(path, ';');
271 
272 	wpath = kmemdup_nul(path, *endptr - path, GFP_ATOMIC);
273 	if (!wpath)
274 		return -ENOMEM;
275 
276 	while (1) {
277 		p = strrchr(wpath, '/');
278 		if (!p)
279 			break;
280 		ret = sscanf(p, "/%x.%x%c", &slot, &func, &end);
281 		if (ret != 2) {
282 			ret = -EINVAL;
283 			goto free_and_exit;
284 		}
285 
286 		if (dev->devfn != PCI_DEVFN(slot, func)) {
287 			ret = 0;
288 			goto free_and_exit;
289 		}
290 
291 		/*
292 		 * Note: we don't need to get a reference to the upstream
293 		 * bridge because we hold a reference to the top level
294 		 * device which should hold a reference to the bridge,
295 		 * and so on.
296 		 */
297 		dev = pci_upstream_bridge(dev);
298 		if (!dev) {
299 			ret = 0;
300 			goto free_and_exit;
301 		}
302 
303 		*p = 0;
304 	}
305 
306 	ret = sscanf(wpath, "%x:%x:%x.%x%c", &seg, &bus, &slot,
307 		     &func, &end);
308 	if (ret != 4) {
309 		seg = 0;
310 		ret = sscanf(wpath, "%x:%x.%x%c", &bus, &slot, &func, &end);
311 		if (ret != 3) {
312 			ret = -EINVAL;
313 			goto free_and_exit;
314 		}
315 	}
316 
317 	ret = (seg == pci_domain_nr(dev->bus) &&
318 	       bus == dev->bus->number &&
319 	       dev->devfn == PCI_DEVFN(slot, func));
320 
321 free_and_exit:
322 	kfree(wpath);
323 	return ret;
324 }
325 
326 /**
327  * pci_dev_str_match - test if a string matches a device
328  * @dev: the PCI device to test
329  * @p: string to match the device against
330  * @endptr: pointer to the string after the match
331  *
332  * Test if a string (typically from a kernel parameter) matches a specified
333  * PCI device. The string may be of one of the following formats:
334  *
335  *   [<domain>:]<bus>:<device>.<func>[/<device>.<func>]*
336  *   pci:<vendor>:<device>[:<subvendor>:<subdevice>]
337  *
338  * The first format specifies a PCI bus/device/function address which
339  * may change if new hardware is inserted, if motherboard firmware changes,
340  * or due to changes caused in kernel parameters. If the domain is
341  * left unspecified, it is taken to be 0.  In order to be robust against
342  * bus renumbering issues, a path of PCI device/function numbers may be used
343  * to address the specific device.  The path for a device can be determined
344  * through the use of 'lspci -t'.
345  *
346  * The second format matches devices using IDs in the configuration
347  * space which may match multiple devices in the system. A value of 0
348  * for any field will match all devices. (Note: this differs from
349  * in-kernel code that uses PCI_ANY_ID which is ~0; this is for
350  * legacy reasons and convenience so users don't have to specify
351  * FFFFFFFFs on the command line.)
352  *
353  * Returns 1 if the string matches the device, 0 if it does not and
354  * a negative error code if the string cannot be parsed.
355  */
pci_dev_str_match(struct pci_dev * dev,const char * p,const char ** endptr)356 static int pci_dev_str_match(struct pci_dev *dev, const char *p,
357 			     const char **endptr)
358 {
359 	int ret;
360 	int count;
361 	unsigned short vendor, device, subsystem_vendor, subsystem_device;
362 
363 	if (strncmp(p, "pci:", 4) == 0) {
364 		/* PCI vendor/device (subvendor/subdevice) IDs are specified */
365 		p += 4;
366 		ret = sscanf(p, "%hx:%hx:%hx:%hx%n", &vendor, &device,
367 			     &subsystem_vendor, &subsystem_device, &count);
368 		if (ret != 4) {
369 			ret = sscanf(p, "%hx:%hx%n", &vendor, &device, &count);
370 			if (ret != 2)
371 				return -EINVAL;
372 
373 			subsystem_vendor = 0;
374 			subsystem_device = 0;
375 		}
376 
377 		p += count;
378 
379 		if ((!vendor || vendor == dev->vendor) &&
380 		    (!device || device == dev->device) &&
381 		    (!subsystem_vendor ||
382 			    subsystem_vendor == dev->subsystem_vendor) &&
383 		    (!subsystem_device ||
384 			    subsystem_device == dev->subsystem_device))
385 			goto found;
386 	} else {
387 		/*
388 		 * PCI Bus, Device, Function IDs are specified
389 		 * (optionally, may include a path of devfns following it)
390 		 */
391 		ret = pci_dev_str_match_path(dev, p, &p);
392 		if (ret < 0)
393 			return ret;
394 		else if (ret)
395 			goto found;
396 	}
397 
398 	*endptr = p;
399 	return 0;
400 
401 found:
402 	*endptr = p;
403 	return 1;
404 }
405 
__pci_find_next_cap_ttl(struct pci_bus * bus,unsigned int devfn,u8 pos,int cap,int * ttl)406 static int __pci_find_next_cap_ttl(struct pci_bus *bus, unsigned int devfn,
407 				   u8 pos, int cap, int *ttl)
408 {
409 	u8 id;
410 	u16 ent;
411 
412 	pci_bus_read_config_byte(bus, devfn, pos, &pos);
413 
414 	while ((*ttl)--) {
415 		if (pos < 0x40)
416 			break;
417 		pos &= ~3;
418 		pci_bus_read_config_word(bus, devfn, pos, &ent);
419 
420 		id = ent & 0xff;
421 		if (id == 0xff)
422 			break;
423 		if (id == cap)
424 			return pos;
425 		pos = (ent >> 8);
426 	}
427 	return 0;
428 }
429 
__pci_find_next_cap(struct pci_bus * bus,unsigned int devfn,u8 pos,int cap)430 static int __pci_find_next_cap(struct pci_bus *bus, unsigned int devfn,
431 			       u8 pos, int cap)
432 {
433 	int ttl = PCI_FIND_CAP_TTL;
434 
435 	return __pci_find_next_cap_ttl(bus, devfn, pos, cap, &ttl);
436 }
437 
pci_find_next_capability(struct pci_dev * dev,u8 pos,int cap)438 int pci_find_next_capability(struct pci_dev *dev, u8 pos, int cap)
439 {
440 	return __pci_find_next_cap(dev->bus, dev->devfn,
441 				   pos + PCI_CAP_LIST_NEXT, cap);
442 }
443 EXPORT_SYMBOL_GPL(pci_find_next_capability);
444 
__pci_bus_find_cap_start(struct pci_bus * bus,unsigned int devfn,u8 hdr_type)445 static int __pci_bus_find_cap_start(struct pci_bus *bus,
446 				    unsigned int devfn, u8 hdr_type)
447 {
448 	u16 status;
449 
450 	pci_bus_read_config_word(bus, devfn, PCI_STATUS, &status);
451 	if (!(status & PCI_STATUS_CAP_LIST))
452 		return 0;
453 
454 	switch (hdr_type) {
455 	case PCI_HEADER_TYPE_NORMAL:
456 	case PCI_HEADER_TYPE_BRIDGE:
457 		return PCI_CAPABILITY_LIST;
458 	case PCI_HEADER_TYPE_CARDBUS:
459 		return PCI_CB_CAPABILITY_LIST;
460 	}
461 
462 	return 0;
463 }
464 
465 /**
466  * pci_find_capability - query for devices' capabilities
467  * @dev: PCI device to query
468  * @cap: capability code
469  *
470  * Tell if a device supports a given PCI capability.
471  * Returns the address of the requested capability structure within the
472  * device's PCI configuration space or 0 in case the device does not
473  * support it.  Possible values for @cap include:
474  *
475  *  %PCI_CAP_ID_PM           Power Management
476  *  %PCI_CAP_ID_AGP          Accelerated Graphics Port
477  *  %PCI_CAP_ID_VPD          Vital Product Data
478  *  %PCI_CAP_ID_SLOTID       Slot Identification
479  *  %PCI_CAP_ID_MSI          Message Signalled Interrupts
480  *  %PCI_CAP_ID_CHSWP        CompactPCI HotSwap
481  *  %PCI_CAP_ID_PCIX         PCI-X
482  *  %PCI_CAP_ID_EXP          PCI Express
483  */
pci_find_capability(struct pci_dev * dev,int cap)484 int pci_find_capability(struct pci_dev *dev, int cap)
485 {
486 	int pos;
487 
488 	pos = __pci_bus_find_cap_start(dev->bus, dev->devfn, dev->hdr_type);
489 	if (pos)
490 		pos = __pci_find_next_cap(dev->bus, dev->devfn, pos, cap);
491 
492 	return pos;
493 }
494 EXPORT_SYMBOL(pci_find_capability);
495 
496 /**
497  * pci_bus_find_capability - query for devices' capabilities
498  * @bus: the PCI bus to query
499  * @devfn: PCI device to query
500  * @cap: capability code
501  *
502  * Like pci_find_capability() but works for PCI devices that do not have a
503  * pci_dev structure set up yet.
504  *
505  * Returns the address of the requested capability structure within the
506  * device's PCI configuration space or 0 in case the device does not
507  * support it.
508  */
pci_bus_find_capability(struct pci_bus * bus,unsigned int devfn,int cap)509 int pci_bus_find_capability(struct pci_bus *bus, unsigned int devfn, int cap)
510 {
511 	int pos;
512 	u8 hdr_type;
513 
514 	pci_bus_read_config_byte(bus, devfn, PCI_HEADER_TYPE, &hdr_type);
515 
516 	pos = __pci_bus_find_cap_start(bus, devfn, hdr_type & 0x7f);
517 	if (pos)
518 		pos = __pci_find_next_cap(bus, devfn, pos, cap);
519 
520 	return pos;
521 }
522 EXPORT_SYMBOL(pci_bus_find_capability);
523 
524 /**
525  * pci_find_next_ext_capability - Find an extended capability
526  * @dev: PCI device to query
527  * @start: address at which to start looking (0 to start at beginning of list)
528  * @cap: capability code
529  *
530  * Returns the address of the next matching extended capability structure
531  * within the device's PCI configuration space or 0 if the device does
532  * not support it.  Some capabilities can occur several times, e.g., the
533  * vendor-specific capability, and this provides a way to find them all.
534  */
pci_find_next_ext_capability(struct pci_dev * dev,int start,int cap)535 int pci_find_next_ext_capability(struct pci_dev *dev, int start, int cap)
536 {
537 	u32 header;
538 	int ttl;
539 	int pos = PCI_CFG_SPACE_SIZE;
540 
541 	/* minimum 8 bytes per capability */
542 	ttl = (PCI_CFG_SPACE_EXP_SIZE - PCI_CFG_SPACE_SIZE) / 8;
543 
544 	if (dev->cfg_size <= PCI_CFG_SPACE_SIZE)
545 		return 0;
546 
547 	if (start)
548 		pos = start;
549 
550 	if (pci_read_config_dword(dev, pos, &header) != PCIBIOS_SUCCESSFUL)
551 		return 0;
552 
553 	/*
554 	 * If we have no capabilities, this is indicated by cap ID,
555 	 * cap version and next pointer all being 0.
556 	 */
557 	if (header == 0)
558 		return 0;
559 
560 	while (ttl-- > 0) {
561 		if (PCI_EXT_CAP_ID(header) == cap && pos != start)
562 			return pos;
563 
564 		pos = PCI_EXT_CAP_NEXT(header);
565 		if (pos < PCI_CFG_SPACE_SIZE)
566 			break;
567 
568 		if (pci_read_config_dword(dev, pos, &header) != PCIBIOS_SUCCESSFUL)
569 			break;
570 	}
571 
572 	return 0;
573 }
574 EXPORT_SYMBOL_GPL(pci_find_next_ext_capability);
575 
576 /**
577  * pci_find_ext_capability - Find an extended capability
578  * @dev: PCI device to query
579  * @cap: capability code
580  *
581  * Returns the address of the requested extended capability structure
582  * within the device's PCI configuration space or 0 if the device does
583  * not support it.  Possible values for @cap include:
584  *
585  *  %PCI_EXT_CAP_ID_ERR		Advanced Error Reporting
586  *  %PCI_EXT_CAP_ID_VC		Virtual Channel
587  *  %PCI_EXT_CAP_ID_DSN		Device Serial Number
588  *  %PCI_EXT_CAP_ID_PWR		Power Budgeting
589  */
pci_find_ext_capability(struct pci_dev * dev,int cap)590 int pci_find_ext_capability(struct pci_dev *dev, int cap)
591 {
592 	return pci_find_next_ext_capability(dev, 0, cap);
593 }
594 EXPORT_SYMBOL_GPL(pci_find_ext_capability);
595 
596 /**
597  * pci_get_dsn - Read and return the 8-byte Device Serial Number
598  * @dev: PCI device to query
599  *
600  * Looks up the PCI_EXT_CAP_ID_DSN and reads the 8 bytes of the Device Serial
601  * Number.
602  *
603  * Returns the DSN, or zero if the capability does not exist.
604  */
pci_get_dsn(struct pci_dev * dev)605 u64 pci_get_dsn(struct pci_dev *dev)
606 {
607 	u32 dword;
608 	u64 dsn;
609 	int pos;
610 
611 	pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_DSN);
612 	if (!pos)
613 		return 0;
614 
615 	/*
616 	 * The Device Serial Number is two dwords offset 4 bytes from the
617 	 * capability position. The specification says that the first dword is
618 	 * the lower half, and the second dword is the upper half.
619 	 */
620 	pos += 4;
621 	pci_read_config_dword(dev, pos, &dword);
622 	dsn = (u64)dword;
623 	pci_read_config_dword(dev, pos + 4, &dword);
624 	dsn |= ((u64)dword) << 32;
625 
626 	return dsn;
627 }
628 EXPORT_SYMBOL_GPL(pci_get_dsn);
629 
__pci_find_next_ht_cap(struct pci_dev * dev,int pos,int ht_cap)630 static int __pci_find_next_ht_cap(struct pci_dev *dev, int pos, int ht_cap)
631 {
632 	int rc, ttl = PCI_FIND_CAP_TTL;
633 	u8 cap, mask;
634 
635 	if (ht_cap == HT_CAPTYPE_SLAVE || ht_cap == HT_CAPTYPE_HOST)
636 		mask = HT_3BIT_CAP_MASK;
637 	else
638 		mask = HT_5BIT_CAP_MASK;
639 
640 	pos = __pci_find_next_cap_ttl(dev->bus, dev->devfn, pos,
641 				      PCI_CAP_ID_HT, &ttl);
642 	while (pos) {
643 		rc = pci_read_config_byte(dev, pos + 3, &cap);
644 		if (rc != PCIBIOS_SUCCESSFUL)
645 			return 0;
646 
647 		if ((cap & mask) == ht_cap)
648 			return pos;
649 
650 		pos = __pci_find_next_cap_ttl(dev->bus, dev->devfn,
651 					      pos + PCI_CAP_LIST_NEXT,
652 					      PCI_CAP_ID_HT, &ttl);
653 	}
654 
655 	return 0;
656 }
657 /**
658  * pci_find_next_ht_capability - query a device's Hypertransport capabilities
659  * @dev: PCI device to query
660  * @pos: Position from which to continue searching
661  * @ht_cap: Hypertransport capability code
662  *
663  * To be used in conjunction with pci_find_ht_capability() to search for
664  * all capabilities matching @ht_cap. @pos should always be a value returned
665  * from pci_find_ht_capability().
666  *
667  * NB. To be 100% safe against broken PCI devices, the caller should take
668  * steps to avoid an infinite loop.
669  */
pci_find_next_ht_capability(struct pci_dev * dev,int pos,int ht_cap)670 int pci_find_next_ht_capability(struct pci_dev *dev, int pos, int ht_cap)
671 {
672 	return __pci_find_next_ht_cap(dev, pos + PCI_CAP_LIST_NEXT, ht_cap);
673 }
674 EXPORT_SYMBOL_GPL(pci_find_next_ht_capability);
675 
676 /**
677  * pci_find_ht_capability - query a device's Hypertransport capabilities
678  * @dev: PCI device to query
679  * @ht_cap: Hypertransport capability code
680  *
681  * Tell if a device supports a given Hypertransport capability.
682  * Returns an address within the device's PCI configuration space
683  * or 0 in case the device does not support the request capability.
684  * The address points to the PCI capability, of type PCI_CAP_ID_HT,
685  * which has a Hypertransport capability matching @ht_cap.
686  */
pci_find_ht_capability(struct pci_dev * dev,int ht_cap)687 int pci_find_ht_capability(struct pci_dev *dev, int ht_cap)
688 {
689 	int pos;
690 
691 	pos = __pci_bus_find_cap_start(dev->bus, dev->devfn, dev->hdr_type);
692 	if (pos)
693 		pos = __pci_find_next_ht_cap(dev, pos, ht_cap);
694 
695 	return pos;
696 }
697 EXPORT_SYMBOL_GPL(pci_find_ht_capability);
698 
699 /**
700  * pci_find_parent_resource - return resource region of parent bus of given
701  *			      region
702  * @dev: PCI device structure contains resources to be searched
703  * @res: child resource record for which parent is sought
704  *
705  * For given resource region of given device, return the resource region of
706  * parent bus the given region is contained in.
707  */
pci_find_parent_resource(const struct pci_dev * dev,struct resource * res)708 struct resource *pci_find_parent_resource(const struct pci_dev *dev,
709 					  struct resource *res)
710 {
711 	const struct pci_bus *bus = dev->bus;
712 	struct resource *r;
713 	int i;
714 
715 	pci_bus_for_each_resource(bus, r, i) {
716 		if (!r)
717 			continue;
718 		if (resource_contains(r, res)) {
719 
720 			/*
721 			 * If the window is prefetchable but the BAR is
722 			 * not, the allocator made a mistake.
723 			 */
724 			if (r->flags & IORESOURCE_PREFETCH &&
725 			    !(res->flags & IORESOURCE_PREFETCH))
726 				return NULL;
727 
728 			/*
729 			 * If we're below a transparent bridge, there may
730 			 * be both a positively-decoded aperture and a
731 			 * subtractively-decoded region that contain the BAR.
732 			 * We want the positively-decoded one, so this depends
733 			 * on pci_bus_for_each_resource() giving us those
734 			 * first.
735 			 */
736 			return r;
737 		}
738 	}
739 	return NULL;
740 }
741 EXPORT_SYMBOL(pci_find_parent_resource);
742 
743 /**
744  * pci_find_resource - Return matching PCI device resource
745  * @dev: PCI device to query
746  * @res: Resource to look for
747  *
748  * Goes over standard PCI resources (BARs) and checks if the given resource
749  * is partially or fully contained in any of them. In that case the
750  * matching resource is returned, %NULL otherwise.
751  */
pci_find_resource(struct pci_dev * dev,struct resource * res)752 struct resource *pci_find_resource(struct pci_dev *dev, struct resource *res)
753 {
754 	int i;
755 
756 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
757 		struct resource *r = &dev->resource[i];
758 
759 		if (r->start && resource_contains(r, res))
760 			return r;
761 	}
762 
763 	return NULL;
764 }
765 EXPORT_SYMBOL(pci_find_resource);
766 
767 /**
768  * pci_wait_for_pending - wait for @mask bit(s) to clear in status word @pos
769  * @dev: the PCI device to operate on
770  * @pos: config space offset of status word
771  * @mask: mask of bit(s) to care about in status word
772  *
773  * Return 1 when mask bit(s) in status word clear, 0 otherwise.
774  */
pci_wait_for_pending(struct pci_dev * dev,int pos,u16 mask)775 int pci_wait_for_pending(struct pci_dev *dev, int pos, u16 mask)
776 {
777 	int i;
778 
779 	/* Wait for Transaction Pending bit clean */
780 	for (i = 0; i < 4; i++) {
781 		u16 status;
782 		if (i)
783 			msleep((1 << (i - 1)) * 100);
784 
785 		pci_read_config_word(dev, pos, &status);
786 		if (!(status & mask))
787 			return 1;
788 	}
789 
790 	return 0;
791 }
792 
793 static int pci_acs_enable;
794 
795 /**
796  * pci_request_acs - ask for ACS to be enabled if supported
797  */
pci_request_acs(void)798 void pci_request_acs(void)
799 {
800 	pci_acs_enable = 1;
801 }
802 
803 static const char *disable_acs_redir_param;
804 
805 /**
806  * pci_disable_acs_redir - disable ACS redirect capabilities
807  * @dev: the PCI device
808  *
809  * For only devices specified in the disable_acs_redir parameter.
810  */
pci_disable_acs_redir(struct pci_dev * dev)811 static void pci_disable_acs_redir(struct pci_dev *dev)
812 {
813 	int ret = 0;
814 	const char *p;
815 	int pos;
816 	u16 ctrl;
817 
818 	if (!disable_acs_redir_param)
819 		return;
820 
821 	p = disable_acs_redir_param;
822 	while (*p) {
823 		ret = pci_dev_str_match(dev, p, &p);
824 		if (ret < 0) {
825 			pr_info_once("PCI: Can't parse disable_acs_redir parameter: %s\n",
826 				     disable_acs_redir_param);
827 
828 			break;
829 		} else if (ret == 1) {
830 			/* Found a match */
831 			break;
832 		}
833 
834 		if (*p != ';' && *p != ',') {
835 			/* End of param or invalid format */
836 			break;
837 		}
838 		p++;
839 	}
840 
841 	if (ret != 1)
842 		return;
843 
844 	if (!pci_dev_specific_disable_acs_redir(dev))
845 		return;
846 
847 	pos = dev->acs_cap;
848 	if (!pos) {
849 		pci_warn(dev, "cannot disable ACS redirect for this hardware as it does not have ACS capabilities\n");
850 		return;
851 	}
852 
853 	pci_read_config_word(dev, pos + PCI_ACS_CTRL, &ctrl);
854 
855 	/* P2P Request & Completion Redirect */
856 	ctrl &= ~(PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_EC);
857 
858 	pci_write_config_word(dev, pos + PCI_ACS_CTRL, ctrl);
859 
860 	pci_info(dev, "disabled ACS redirect\n");
861 }
862 
863 /**
864  * pci_std_enable_acs - enable ACS on devices using standard ACS capabilities
865  * @dev: the PCI device
866  */
pci_std_enable_acs(struct pci_dev * dev)867 static void pci_std_enable_acs(struct pci_dev *dev)
868 {
869 	int pos;
870 	u16 cap;
871 	u16 ctrl;
872 
873 	pos = dev->acs_cap;
874 	if (!pos)
875 		return;
876 
877 	pci_read_config_word(dev, pos + PCI_ACS_CAP, &cap);
878 	pci_read_config_word(dev, pos + PCI_ACS_CTRL, &ctrl);
879 
880 	/* Source Validation */
881 	ctrl |= (cap & PCI_ACS_SV);
882 
883 	/* P2P Request Redirect */
884 	ctrl |= (cap & PCI_ACS_RR);
885 
886 	/* P2P Completion Redirect */
887 	ctrl |= (cap & PCI_ACS_CR);
888 
889 	/* Upstream Forwarding */
890 	ctrl |= (cap & PCI_ACS_UF);
891 
892 	/* Enable Translation Blocking for external devices */
893 	if (dev->external_facing || dev->untrusted)
894 		ctrl |= (cap & PCI_ACS_TB);
895 
896 	pci_write_config_word(dev, pos + PCI_ACS_CTRL, ctrl);
897 }
898 
899 /**
900  * pci_enable_acs - enable ACS if hardware support it
901  * @dev: the PCI device
902  */
pci_enable_acs(struct pci_dev * dev)903 static void pci_enable_acs(struct pci_dev *dev)
904 {
905 	if (!pci_acs_enable)
906 		goto disable_acs_redir;
907 
908 	if (!pci_dev_specific_enable_acs(dev))
909 		goto disable_acs_redir;
910 
911 	pci_std_enable_acs(dev);
912 
913 disable_acs_redir:
914 	/*
915 	 * Note: pci_disable_acs_redir() must be called even if ACS was not
916 	 * enabled by the kernel because it may have been enabled by
917 	 * platform firmware.  So if we are told to disable it, we should
918 	 * always disable it after setting the kernel's default
919 	 * preferences.
920 	 */
921 	pci_disable_acs_redir(dev);
922 }
923 
924 /**
925  * pci_restore_bars - restore a device's BAR values (e.g. after wake-up)
926  * @dev: PCI device to have its BARs restored
927  *
928  * Restore the BAR values for a given device, so as to make it
929  * accessible by its driver.
930  */
pci_restore_bars(struct pci_dev * dev)931 static void pci_restore_bars(struct pci_dev *dev)
932 {
933 	int i;
934 
935 	for (i = 0; i < PCI_BRIDGE_RESOURCES; i++)
936 		pci_update_resource(dev, i);
937 }
938 
939 static const struct pci_platform_pm_ops *pci_platform_pm;
940 
pci_set_platform_pm(const struct pci_platform_pm_ops * ops)941 int pci_set_platform_pm(const struct pci_platform_pm_ops *ops)
942 {
943 	if (!ops->is_manageable || !ops->set_state  || !ops->get_state ||
944 	    !ops->choose_state  || !ops->set_wakeup || !ops->need_resume)
945 		return -EINVAL;
946 	pci_platform_pm = ops;
947 	return 0;
948 }
949 
platform_pci_power_manageable(struct pci_dev * dev)950 static inline bool platform_pci_power_manageable(struct pci_dev *dev)
951 {
952 	return pci_platform_pm ? pci_platform_pm->is_manageable(dev) : false;
953 }
954 
platform_pci_set_power_state(struct pci_dev * dev,pci_power_t t)955 static inline int platform_pci_set_power_state(struct pci_dev *dev,
956 					       pci_power_t t)
957 {
958 	return pci_platform_pm ? pci_platform_pm->set_state(dev, t) : -ENOSYS;
959 }
960 
platform_pci_get_power_state(struct pci_dev * dev)961 static inline pci_power_t platform_pci_get_power_state(struct pci_dev *dev)
962 {
963 	return pci_platform_pm ? pci_platform_pm->get_state(dev) : PCI_UNKNOWN;
964 }
965 
platform_pci_refresh_power_state(struct pci_dev * dev)966 static inline void platform_pci_refresh_power_state(struct pci_dev *dev)
967 {
968 	if (pci_platform_pm && pci_platform_pm->refresh_state)
969 		pci_platform_pm->refresh_state(dev);
970 }
971 
platform_pci_choose_state(struct pci_dev * dev)972 static inline pci_power_t platform_pci_choose_state(struct pci_dev *dev)
973 {
974 	return pci_platform_pm ?
975 			pci_platform_pm->choose_state(dev) : PCI_POWER_ERROR;
976 }
977 
platform_pci_set_wakeup(struct pci_dev * dev,bool enable)978 static inline int platform_pci_set_wakeup(struct pci_dev *dev, bool enable)
979 {
980 	return pci_platform_pm ?
981 			pci_platform_pm->set_wakeup(dev, enable) : -ENODEV;
982 }
983 
platform_pci_need_resume(struct pci_dev * dev)984 static inline bool platform_pci_need_resume(struct pci_dev *dev)
985 {
986 	return pci_platform_pm ? pci_platform_pm->need_resume(dev) : false;
987 }
988 
platform_pci_bridge_d3(struct pci_dev * dev)989 static inline bool platform_pci_bridge_d3(struct pci_dev *dev)
990 {
991 	if (pci_platform_pm && pci_platform_pm->bridge_d3)
992 		return pci_platform_pm->bridge_d3(dev);
993 	return false;
994 }
995 
996 /**
997  * pci_raw_set_power_state - Use PCI PM registers to set the power state of
998  *			     given PCI device
999  * @dev: PCI device to handle.
1000  * @state: PCI power state (D0, D1, D2, D3hot) to put the device into.
1001  *
1002  * RETURN VALUE:
1003  * -EINVAL if the requested state is invalid.
1004  * -EIO if device does not support PCI PM or its PM capabilities register has a
1005  * wrong version, or device doesn't support the requested state.
1006  * 0 if device already is in the requested state.
1007  * 0 if device's power state has been successfully changed.
1008  */
pci_raw_set_power_state(struct pci_dev * dev,pci_power_t state)1009 static int pci_raw_set_power_state(struct pci_dev *dev, pci_power_t state)
1010 {
1011 	u16 pmcsr;
1012 	bool need_restore = false;
1013 
1014 	/* Check if we're already there */
1015 	if (dev->current_state == state)
1016 		return 0;
1017 
1018 	if (!dev->pm_cap)
1019 		return -EIO;
1020 
1021 	if (state < PCI_D0 || state > PCI_D3hot)
1022 		return -EINVAL;
1023 
1024 	/*
1025 	 * Validate transition: We can enter D0 from any state, but if
1026 	 * we're already in a low-power state, we can only go deeper.  E.g.,
1027 	 * we can go from D1 to D3, but we can't go directly from D3 to D1;
1028 	 * we'd have to go from D3 to D0, then to D1.
1029 	 */
1030 	if (state != PCI_D0 && dev->current_state <= PCI_D3cold
1031 	    && dev->current_state > state) {
1032 		pci_err(dev, "invalid power transition (from %s to %s)\n",
1033 			pci_power_name(dev->current_state),
1034 			pci_power_name(state));
1035 		return -EINVAL;
1036 	}
1037 
1038 	/* Check if this device supports the desired state */
1039 	if ((state == PCI_D1 && !dev->d1_support)
1040 	   || (state == PCI_D2 && !dev->d2_support))
1041 		return -EIO;
1042 
1043 	pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
1044 	if (pmcsr == (u16) ~0) {
1045 		pci_err(dev, "can't change power state from %s to %s (config space inaccessible)\n",
1046 			pci_power_name(dev->current_state),
1047 			pci_power_name(state));
1048 		return -EIO;
1049 	}
1050 
1051 	/*
1052 	 * If we're (effectively) in D3, force entire word to 0.
1053 	 * This doesn't affect PME_Status, disables PME_En, and
1054 	 * sets PowerState to 0.
1055 	 */
1056 	switch (dev->current_state) {
1057 	case PCI_D0:
1058 	case PCI_D1:
1059 	case PCI_D2:
1060 		pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
1061 		pmcsr |= state;
1062 		break;
1063 	case PCI_D3hot:
1064 	case PCI_D3cold:
1065 	case PCI_UNKNOWN: /* Boot-up */
1066 		if ((pmcsr & PCI_PM_CTRL_STATE_MASK) == PCI_D3hot
1067 		 && !(pmcsr & PCI_PM_CTRL_NO_SOFT_RESET))
1068 			need_restore = true;
1069 		fallthrough;	/* force to D0 */
1070 	default:
1071 		pmcsr = 0;
1072 		break;
1073 	}
1074 
1075 	/* Enter specified state */
1076 	pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, pmcsr);
1077 
1078 	/*
1079 	 * Mandatory power management transition delays; see PCI PM 1.1
1080 	 * 5.6.1 table 18
1081 	 */
1082 	if (state == PCI_D3hot || dev->current_state == PCI_D3hot)
1083 		pci_dev_d3_sleep(dev);
1084 	else if (state == PCI_D2 || dev->current_state == PCI_D2)
1085 		udelay(PCI_PM_D2_DELAY);
1086 
1087 	pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
1088 	dev->current_state = (pmcsr & PCI_PM_CTRL_STATE_MASK);
1089 	if (dev->current_state != state)
1090 		pci_info_ratelimited(dev, "refused to change power state from %s to %s\n",
1091 			 pci_power_name(dev->current_state),
1092 			 pci_power_name(state));
1093 
1094 	/*
1095 	 * According to section 5.4.1 of the "PCI BUS POWER MANAGEMENT
1096 	 * INTERFACE SPECIFICATION, REV. 1.2", a device transitioning
1097 	 * from D3hot to D0 _may_ perform an internal reset, thereby
1098 	 * going to "D0 Uninitialized" rather than "D0 Initialized".
1099 	 * For example, at least some versions of the 3c905B and the
1100 	 * 3c556B exhibit this behaviour.
1101 	 *
1102 	 * At least some laptop BIOSen (e.g. the Thinkpad T21) leave
1103 	 * devices in a D3hot state at boot.  Consequently, we need to
1104 	 * restore at least the BARs so that the device will be
1105 	 * accessible to its driver.
1106 	 */
1107 	if (need_restore)
1108 		pci_restore_bars(dev);
1109 
1110 	if (dev->bus->self)
1111 		pcie_aspm_pm_state_change(dev->bus->self);
1112 
1113 	return 0;
1114 }
1115 
1116 /**
1117  * pci_update_current_state - Read power state of given device and cache it
1118  * @dev: PCI device to handle.
1119  * @state: State to cache in case the device doesn't have the PM capability
1120  *
1121  * The power state is read from the PMCSR register, which however is
1122  * inaccessible in D3cold.  The platform firmware is therefore queried first
1123  * to detect accessibility of the register.  In case the platform firmware
1124  * reports an incorrect state or the device isn't power manageable by the
1125  * platform at all, we try to detect D3cold by testing accessibility of the
1126  * vendor ID in config space.
1127  */
pci_update_current_state(struct pci_dev * dev,pci_power_t state)1128 void pci_update_current_state(struct pci_dev *dev, pci_power_t state)
1129 {
1130 	if (platform_pci_get_power_state(dev) == PCI_D3cold ||
1131 	    !pci_device_is_present(dev)) {
1132 		dev->current_state = PCI_D3cold;
1133 	} else if (dev->pm_cap) {
1134 		u16 pmcsr;
1135 
1136 		pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
1137 		dev->current_state = (pmcsr & PCI_PM_CTRL_STATE_MASK);
1138 	} else {
1139 		dev->current_state = state;
1140 	}
1141 }
1142 
1143 /**
1144  * pci_refresh_power_state - Refresh the given device's power state data
1145  * @dev: Target PCI device.
1146  *
1147  * Ask the platform to refresh the devices power state information and invoke
1148  * pci_update_current_state() to update its current PCI power state.
1149  */
pci_refresh_power_state(struct pci_dev * dev)1150 void pci_refresh_power_state(struct pci_dev *dev)
1151 {
1152 	if (platform_pci_power_manageable(dev))
1153 		platform_pci_refresh_power_state(dev);
1154 
1155 	pci_update_current_state(dev, dev->current_state);
1156 }
1157 
1158 /**
1159  * pci_platform_power_transition - Use platform to change device power state
1160  * @dev: PCI device to handle.
1161  * @state: State to put the device into.
1162  */
pci_platform_power_transition(struct pci_dev * dev,pci_power_t state)1163 int pci_platform_power_transition(struct pci_dev *dev, pci_power_t state)
1164 {
1165 	int error;
1166 
1167 	if (platform_pci_power_manageable(dev)) {
1168 		error = platform_pci_set_power_state(dev, state);
1169 		if (!error)
1170 			pci_update_current_state(dev, state);
1171 	} else
1172 		error = -ENODEV;
1173 
1174 	if (error && !dev->pm_cap) /* Fall back to PCI_D0 */
1175 		dev->current_state = PCI_D0;
1176 
1177 	return error;
1178 }
1179 EXPORT_SYMBOL_GPL(pci_platform_power_transition);
1180 
1181 /**
1182  * pci_wakeup - Wake up a PCI device
1183  * @pci_dev: Device to handle.
1184  * @ign: ignored parameter
1185  */
pci_wakeup(struct pci_dev * pci_dev,void * ign)1186 static int pci_wakeup(struct pci_dev *pci_dev, void *ign)
1187 {
1188 	pci_wakeup_event(pci_dev);
1189 	pm_request_resume(&pci_dev->dev);
1190 	return 0;
1191 }
1192 
1193 /**
1194  * pci_wakeup_bus - Walk given bus and wake up devices on it
1195  * @bus: Top bus of the subtree to walk.
1196  */
pci_wakeup_bus(struct pci_bus * bus)1197 void pci_wakeup_bus(struct pci_bus *bus)
1198 {
1199 	if (bus)
1200 		pci_walk_bus(bus, pci_wakeup, NULL);
1201 }
1202 
pci_dev_wait(struct pci_dev * dev,char * reset_type,int timeout)1203 static int pci_dev_wait(struct pci_dev *dev, char *reset_type, int timeout)
1204 {
1205 	int delay = 1;
1206 	u32 id;
1207 
1208 	/*
1209 	 * After reset, the device should not silently discard config
1210 	 * requests, but it may still indicate that it needs more time by
1211 	 * responding to them with CRS completions.  The Root Port will
1212 	 * generally synthesize ~0 data to complete the read (except when
1213 	 * CRS SV is enabled and the read was for the Vendor ID; in that
1214 	 * case it synthesizes 0x0001 data).
1215 	 *
1216 	 * Wait for the device to return a non-CRS completion.  Read the
1217 	 * Command register instead of Vendor ID so we don't have to
1218 	 * contend with the CRS SV value.
1219 	 */
1220 	pci_read_config_dword(dev, PCI_COMMAND, &id);
1221 	while (id == ~0) {
1222 		if (delay > timeout) {
1223 			pci_warn(dev, "not ready %dms after %s; giving up\n",
1224 				 delay - 1, reset_type);
1225 			return -ENOTTY;
1226 		}
1227 
1228 		if (delay > PCI_RESET_WAIT)
1229 			pci_info(dev, "not ready %dms after %s; waiting\n",
1230 				 delay - 1, reset_type);
1231 
1232 		msleep(delay);
1233 		delay *= 2;
1234 		pci_read_config_dword(dev, PCI_COMMAND, &id);
1235 	}
1236 
1237 	if (delay > PCI_RESET_WAIT)
1238 		pci_info(dev, "ready %dms after %s\n", delay - 1,
1239 			 reset_type);
1240 
1241 	return 0;
1242 }
1243 
1244 /**
1245  * pci_power_up - Put the given device into D0
1246  * @dev: PCI device to power up
1247  */
pci_power_up(struct pci_dev * dev)1248 int pci_power_up(struct pci_dev *dev)
1249 {
1250 	pci_platform_power_transition(dev, PCI_D0);
1251 
1252 	/*
1253 	 * Mandatory power management transition delays are handled in
1254 	 * pci_pm_resume_noirq() and pci_pm_runtime_resume() of the
1255 	 * corresponding bridge.
1256 	 */
1257 	if (dev->runtime_d3cold) {
1258 		/*
1259 		 * When powering on a bridge from D3cold, the whole hierarchy
1260 		 * may be powered on into D0uninitialized state, resume them to
1261 		 * give them a chance to suspend again
1262 		 */
1263 		pci_wakeup_bus(dev->subordinate);
1264 	}
1265 
1266 	return pci_raw_set_power_state(dev, PCI_D0);
1267 }
1268 
1269 /**
1270  * __pci_dev_set_current_state - Set current state of a PCI device
1271  * @dev: Device to handle
1272  * @data: pointer to state to be set
1273  */
__pci_dev_set_current_state(struct pci_dev * dev,void * data)1274 static int __pci_dev_set_current_state(struct pci_dev *dev, void *data)
1275 {
1276 	pci_power_t state = *(pci_power_t *)data;
1277 
1278 	dev->current_state = state;
1279 	return 0;
1280 }
1281 
1282 /**
1283  * pci_bus_set_current_state - Walk given bus and set current state of devices
1284  * @bus: Top bus of the subtree to walk.
1285  * @state: state to be set
1286  */
pci_bus_set_current_state(struct pci_bus * bus,pci_power_t state)1287 void pci_bus_set_current_state(struct pci_bus *bus, pci_power_t state)
1288 {
1289 	if (bus)
1290 		pci_walk_bus(bus, __pci_dev_set_current_state, &state);
1291 }
1292 
1293 /**
1294  * pci_set_power_state - Set the power state of a PCI device
1295  * @dev: PCI device to handle.
1296  * @state: PCI power state (D0, D1, D2, D3hot) to put the device into.
1297  *
1298  * Transition a device to a new power state, using the platform firmware and/or
1299  * the device's PCI PM registers.
1300  *
1301  * RETURN VALUE:
1302  * -EINVAL if the requested state is invalid.
1303  * -EIO if device does not support PCI PM or its PM capabilities register has a
1304  * wrong version, or device doesn't support the requested state.
1305  * 0 if the transition is to D1 or D2 but D1 and D2 are not supported.
1306  * 0 if device already is in the requested state.
1307  * 0 if the transition is to D3 but D3 is not supported.
1308  * 0 if device's power state has been successfully changed.
1309  */
pci_set_power_state(struct pci_dev * dev,pci_power_t state)1310 int pci_set_power_state(struct pci_dev *dev, pci_power_t state)
1311 {
1312 	int error;
1313 
1314 	/* Bound the state we're entering */
1315 	if (state > PCI_D3cold)
1316 		state = PCI_D3cold;
1317 	else if (state < PCI_D0)
1318 		state = PCI_D0;
1319 	else if ((state == PCI_D1 || state == PCI_D2) && pci_no_d1d2(dev))
1320 
1321 		/*
1322 		 * If the device or the parent bridge do not support PCI
1323 		 * PM, ignore the request if we're doing anything other
1324 		 * than putting it into D0 (which would only happen on
1325 		 * boot).
1326 		 */
1327 		return 0;
1328 
1329 	/* Check if we're already there */
1330 	if (dev->current_state == state)
1331 		return 0;
1332 
1333 	if (state == PCI_D0)
1334 		return pci_power_up(dev);
1335 
1336 	/*
1337 	 * This device is quirked not to be put into D3, so don't put it in
1338 	 * D3
1339 	 */
1340 	if (state >= PCI_D3hot && (dev->dev_flags & PCI_DEV_FLAGS_NO_D3))
1341 		return 0;
1342 
1343 	/*
1344 	 * To put device in D3cold, we put device into D3hot in native
1345 	 * way, then put device into D3cold with platform ops
1346 	 */
1347 	error = pci_raw_set_power_state(dev, state > PCI_D3hot ?
1348 					PCI_D3hot : state);
1349 
1350 	if (pci_platform_power_transition(dev, state))
1351 		return error;
1352 
1353 	/* Powering off a bridge may power off the whole hierarchy */
1354 	if (state == PCI_D3cold)
1355 		pci_bus_set_current_state(dev->subordinate, PCI_D3cold);
1356 
1357 	return 0;
1358 }
1359 EXPORT_SYMBOL(pci_set_power_state);
1360 
1361 /**
1362  * pci_choose_state - Choose the power state of a PCI device
1363  * @dev: PCI device to be suspended
1364  * @state: target sleep state for the whole system. This is the value
1365  *	   that is passed to suspend() function.
1366  *
1367  * Returns PCI power state suitable for given device and given system
1368  * message.
1369  */
pci_choose_state(struct pci_dev * dev,pm_message_t state)1370 pci_power_t pci_choose_state(struct pci_dev *dev, pm_message_t state)
1371 {
1372 	pci_power_t ret;
1373 
1374 	if (!dev->pm_cap)
1375 		return PCI_D0;
1376 
1377 	ret = platform_pci_choose_state(dev);
1378 	if (ret != PCI_POWER_ERROR)
1379 		return ret;
1380 
1381 	switch (state.event) {
1382 	case PM_EVENT_ON:
1383 		return PCI_D0;
1384 	case PM_EVENT_FREEZE:
1385 	case PM_EVENT_PRETHAW:
1386 		/* REVISIT both freeze and pre-thaw "should" use D0 */
1387 	case PM_EVENT_SUSPEND:
1388 	case PM_EVENT_HIBERNATE:
1389 		return PCI_D3hot;
1390 	default:
1391 		pci_info(dev, "unrecognized suspend event %d\n",
1392 			 state.event);
1393 		BUG();
1394 	}
1395 	return PCI_D0;
1396 }
1397 EXPORT_SYMBOL(pci_choose_state);
1398 
1399 #define PCI_EXP_SAVE_REGS	7
1400 
_pci_find_saved_cap(struct pci_dev * pci_dev,u16 cap,bool extended)1401 static struct pci_cap_saved_state *_pci_find_saved_cap(struct pci_dev *pci_dev,
1402 						       u16 cap, bool extended)
1403 {
1404 	struct pci_cap_saved_state *tmp;
1405 
1406 	hlist_for_each_entry(tmp, &pci_dev->saved_cap_space, next) {
1407 		if (tmp->cap.cap_extended == extended && tmp->cap.cap_nr == cap)
1408 			return tmp;
1409 	}
1410 	return NULL;
1411 }
1412 
pci_find_saved_cap(struct pci_dev * dev,char cap)1413 struct pci_cap_saved_state *pci_find_saved_cap(struct pci_dev *dev, char cap)
1414 {
1415 	return _pci_find_saved_cap(dev, cap, false);
1416 }
1417 
pci_find_saved_ext_cap(struct pci_dev * dev,u16 cap)1418 struct pci_cap_saved_state *pci_find_saved_ext_cap(struct pci_dev *dev, u16 cap)
1419 {
1420 	return _pci_find_saved_cap(dev, cap, true);
1421 }
1422 
pci_save_pcie_state(struct pci_dev * dev)1423 static int pci_save_pcie_state(struct pci_dev *dev)
1424 {
1425 	int i = 0;
1426 	struct pci_cap_saved_state *save_state;
1427 	u16 *cap;
1428 
1429 	if (!pci_is_pcie(dev))
1430 		return 0;
1431 
1432 	save_state = pci_find_saved_cap(dev, PCI_CAP_ID_EXP);
1433 	if (!save_state) {
1434 		pci_err(dev, "buffer not found in %s\n", __func__);
1435 		return -ENOMEM;
1436 	}
1437 
1438 	cap = (u16 *)&save_state->cap.data[0];
1439 	pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &cap[i++]);
1440 	pcie_capability_read_word(dev, PCI_EXP_LNKCTL, &cap[i++]);
1441 	pcie_capability_read_word(dev, PCI_EXP_SLTCTL, &cap[i++]);
1442 	pcie_capability_read_word(dev, PCI_EXP_RTCTL,  &cap[i++]);
1443 	pcie_capability_read_word(dev, PCI_EXP_DEVCTL2, &cap[i++]);
1444 	pcie_capability_read_word(dev, PCI_EXP_LNKCTL2, &cap[i++]);
1445 	pcie_capability_read_word(dev, PCI_EXP_SLTCTL2, &cap[i++]);
1446 
1447 	return 0;
1448 }
1449 
pci_restore_pcie_state(struct pci_dev * dev)1450 static void pci_restore_pcie_state(struct pci_dev *dev)
1451 {
1452 	int i = 0;
1453 	struct pci_cap_saved_state *save_state;
1454 	u16 *cap;
1455 
1456 	save_state = pci_find_saved_cap(dev, PCI_CAP_ID_EXP);
1457 	if (!save_state)
1458 		return;
1459 
1460 	cap = (u16 *)&save_state->cap.data[0];
1461 	pcie_capability_write_word(dev, PCI_EXP_DEVCTL, cap[i++]);
1462 	pcie_capability_write_word(dev, PCI_EXP_LNKCTL, cap[i++]);
1463 	pcie_capability_write_word(dev, PCI_EXP_SLTCTL, cap[i++]);
1464 	pcie_capability_write_word(dev, PCI_EXP_RTCTL, cap[i++]);
1465 	pcie_capability_write_word(dev, PCI_EXP_DEVCTL2, cap[i++]);
1466 	pcie_capability_write_word(dev, PCI_EXP_LNKCTL2, cap[i++]);
1467 	pcie_capability_write_word(dev, PCI_EXP_SLTCTL2, cap[i++]);
1468 }
1469 
pci_save_pcix_state(struct pci_dev * dev)1470 static int pci_save_pcix_state(struct pci_dev *dev)
1471 {
1472 	int pos;
1473 	struct pci_cap_saved_state *save_state;
1474 
1475 	pos = pci_find_capability(dev, PCI_CAP_ID_PCIX);
1476 	if (!pos)
1477 		return 0;
1478 
1479 	save_state = pci_find_saved_cap(dev, PCI_CAP_ID_PCIX);
1480 	if (!save_state) {
1481 		pci_err(dev, "buffer not found in %s\n", __func__);
1482 		return -ENOMEM;
1483 	}
1484 
1485 	pci_read_config_word(dev, pos + PCI_X_CMD,
1486 			     (u16 *)save_state->cap.data);
1487 
1488 	return 0;
1489 }
1490 
pci_restore_pcix_state(struct pci_dev * dev)1491 static void pci_restore_pcix_state(struct pci_dev *dev)
1492 {
1493 	int i = 0, pos;
1494 	struct pci_cap_saved_state *save_state;
1495 	u16 *cap;
1496 
1497 	save_state = pci_find_saved_cap(dev, PCI_CAP_ID_PCIX);
1498 	pos = pci_find_capability(dev, PCI_CAP_ID_PCIX);
1499 	if (!save_state || !pos)
1500 		return;
1501 	cap = (u16 *)&save_state->cap.data[0];
1502 
1503 	pci_write_config_word(dev, pos + PCI_X_CMD, cap[i++]);
1504 }
1505 
pci_save_ltr_state(struct pci_dev * dev)1506 static void pci_save_ltr_state(struct pci_dev *dev)
1507 {
1508 	int ltr;
1509 	struct pci_cap_saved_state *save_state;
1510 	u16 *cap;
1511 
1512 	if (!pci_is_pcie(dev))
1513 		return;
1514 
1515 	ltr = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_LTR);
1516 	if (!ltr)
1517 		return;
1518 
1519 	save_state = pci_find_saved_ext_cap(dev, PCI_EXT_CAP_ID_LTR);
1520 	if (!save_state) {
1521 		pci_err(dev, "no suspend buffer for LTR; ASPM issues possible after resume\n");
1522 		return;
1523 	}
1524 
1525 	cap = (u16 *)&save_state->cap.data[0];
1526 	pci_read_config_word(dev, ltr + PCI_LTR_MAX_SNOOP_LAT, cap++);
1527 	pci_read_config_word(dev, ltr + PCI_LTR_MAX_NOSNOOP_LAT, cap++);
1528 }
1529 
pci_restore_ltr_state(struct pci_dev * dev)1530 static void pci_restore_ltr_state(struct pci_dev *dev)
1531 {
1532 	struct pci_cap_saved_state *save_state;
1533 	int ltr;
1534 	u16 *cap;
1535 
1536 	save_state = pci_find_saved_ext_cap(dev, PCI_EXT_CAP_ID_LTR);
1537 	ltr = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_LTR);
1538 	if (!save_state || !ltr)
1539 		return;
1540 
1541 	cap = (u16 *)&save_state->cap.data[0];
1542 	pci_write_config_word(dev, ltr + PCI_LTR_MAX_SNOOP_LAT, *cap++);
1543 	pci_write_config_word(dev, ltr + PCI_LTR_MAX_NOSNOOP_LAT, *cap++);
1544 }
1545 
1546 /**
1547  * pci_save_state - save the PCI configuration space of a device before
1548  *		    suspending
1549  * @dev: PCI device that we're dealing with
1550  */
pci_save_state(struct pci_dev * dev)1551 int pci_save_state(struct pci_dev *dev)
1552 {
1553 	int i;
1554 	/* XXX: 100% dword access ok here? */
1555 	for (i = 0; i < 16; i++) {
1556 		pci_read_config_dword(dev, i * 4, &dev->saved_config_space[i]);
1557 		pci_dbg(dev, "saving config space at offset %#x (reading %#x)\n",
1558 			i * 4, dev->saved_config_space[i]);
1559 	}
1560 	dev->state_saved = true;
1561 
1562 	i = pci_save_pcie_state(dev);
1563 	if (i != 0)
1564 		return i;
1565 
1566 	i = pci_save_pcix_state(dev);
1567 	if (i != 0)
1568 		return i;
1569 
1570 	pci_save_ltr_state(dev);
1571 	pci_save_dpc_state(dev);
1572 	pci_save_aer_state(dev);
1573 	return pci_save_vc_state(dev);
1574 }
1575 EXPORT_SYMBOL(pci_save_state);
1576 
pci_restore_config_dword(struct pci_dev * pdev,int offset,u32 saved_val,int retry,bool force)1577 static void pci_restore_config_dword(struct pci_dev *pdev, int offset,
1578 				     u32 saved_val, int retry, bool force)
1579 {
1580 	u32 val;
1581 
1582 	pci_read_config_dword(pdev, offset, &val);
1583 	if (!force && val == saved_val)
1584 		return;
1585 
1586 	for (;;) {
1587 		pci_dbg(pdev, "restoring config space at offset %#x (was %#x, writing %#x)\n",
1588 			offset, val, saved_val);
1589 		pci_write_config_dword(pdev, offset, saved_val);
1590 		if (retry-- <= 0)
1591 			return;
1592 
1593 		pci_read_config_dword(pdev, offset, &val);
1594 		if (val == saved_val)
1595 			return;
1596 
1597 		mdelay(1);
1598 	}
1599 }
1600 
pci_restore_config_space_range(struct pci_dev * pdev,int start,int end,int retry,bool force)1601 static void pci_restore_config_space_range(struct pci_dev *pdev,
1602 					   int start, int end, int retry,
1603 					   bool force)
1604 {
1605 	int index;
1606 
1607 	for (index = end; index >= start; index--)
1608 		pci_restore_config_dword(pdev, 4 * index,
1609 					 pdev->saved_config_space[index],
1610 					 retry, force);
1611 }
1612 
pci_restore_config_space(struct pci_dev * pdev)1613 static void pci_restore_config_space(struct pci_dev *pdev)
1614 {
1615 	if (pdev->hdr_type == PCI_HEADER_TYPE_NORMAL) {
1616 		pci_restore_config_space_range(pdev, 10, 15, 0, false);
1617 		/* Restore BARs before the command register. */
1618 		pci_restore_config_space_range(pdev, 4, 9, 10, false);
1619 		pci_restore_config_space_range(pdev, 0, 3, 0, false);
1620 	} else if (pdev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
1621 		pci_restore_config_space_range(pdev, 12, 15, 0, false);
1622 
1623 		/*
1624 		 * Force rewriting of prefetch registers to avoid S3 resume
1625 		 * issues on Intel PCI bridges that occur when these
1626 		 * registers are not explicitly written.
1627 		 */
1628 		pci_restore_config_space_range(pdev, 9, 11, 0, true);
1629 		pci_restore_config_space_range(pdev, 0, 8, 0, false);
1630 	} else {
1631 		pci_restore_config_space_range(pdev, 0, 15, 0, false);
1632 	}
1633 }
1634 
pci_restore_rebar_state(struct pci_dev * pdev)1635 static void pci_restore_rebar_state(struct pci_dev *pdev)
1636 {
1637 	unsigned int pos, nbars, i;
1638 	u32 ctrl;
1639 
1640 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_REBAR);
1641 	if (!pos)
1642 		return;
1643 
1644 	pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
1645 	nbars = (ctrl & PCI_REBAR_CTRL_NBAR_MASK) >>
1646 		    PCI_REBAR_CTRL_NBAR_SHIFT;
1647 
1648 	for (i = 0; i < nbars; i++, pos += 8) {
1649 		struct resource *res;
1650 		int bar_idx, size;
1651 
1652 		pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
1653 		bar_idx = ctrl & PCI_REBAR_CTRL_BAR_IDX;
1654 		res = pdev->resource + bar_idx;
1655 		size = ilog2(resource_size(res)) - 20;
1656 		ctrl &= ~PCI_REBAR_CTRL_BAR_SIZE;
1657 		ctrl |= size << PCI_REBAR_CTRL_BAR_SHIFT;
1658 		pci_write_config_dword(pdev, pos + PCI_REBAR_CTRL, ctrl);
1659 	}
1660 }
1661 
1662 /**
1663  * pci_restore_state - Restore the saved state of a PCI device
1664  * @dev: PCI device that we're dealing with
1665  */
pci_restore_state(struct pci_dev * dev)1666 void pci_restore_state(struct pci_dev *dev)
1667 {
1668 	if (!dev->state_saved)
1669 		return;
1670 
1671 	/*
1672 	 * Restore max latencies (in the LTR capability) before enabling
1673 	 * LTR itself (in the PCIe capability).
1674 	 */
1675 	pci_restore_ltr_state(dev);
1676 
1677 	pci_restore_pcie_state(dev);
1678 	pci_restore_pasid_state(dev);
1679 	pci_restore_pri_state(dev);
1680 	pci_restore_ats_state(dev);
1681 	pci_restore_vc_state(dev);
1682 	pci_restore_rebar_state(dev);
1683 	pci_restore_dpc_state(dev);
1684 
1685 	pci_aer_clear_status(dev);
1686 	pci_restore_aer_state(dev);
1687 
1688 	pci_restore_config_space(dev);
1689 
1690 	pci_restore_pcix_state(dev);
1691 	pci_restore_msi_state(dev);
1692 
1693 	/* Restore ACS and IOV configuration state */
1694 	pci_enable_acs(dev);
1695 	pci_restore_iov_state(dev);
1696 
1697 	dev->state_saved = false;
1698 }
1699 EXPORT_SYMBOL(pci_restore_state);
1700 
1701 struct pci_saved_state {
1702 	u32 config_space[16];
1703 	struct pci_cap_saved_data cap[];
1704 };
1705 
1706 /**
1707  * pci_store_saved_state - Allocate and return an opaque struct containing
1708  *			   the device saved state.
1709  * @dev: PCI device that we're dealing with
1710  *
1711  * Return NULL if no state or error.
1712  */
pci_store_saved_state(struct pci_dev * dev)1713 struct pci_saved_state *pci_store_saved_state(struct pci_dev *dev)
1714 {
1715 	struct pci_saved_state *state;
1716 	struct pci_cap_saved_state *tmp;
1717 	struct pci_cap_saved_data *cap;
1718 	size_t size;
1719 
1720 	if (!dev->state_saved)
1721 		return NULL;
1722 
1723 	size = sizeof(*state) + sizeof(struct pci_cap_saved_data);
1724 
1725 	hlist_for_each_entry(tmp, &dev->saved_cap_space, next)
1726 		size += sizeof(struct pci_cap_saved_data) + tmp->cap.size;
1727 
1728 	state = kzalloc(size, GFP_KERNEL);
1729 	if (!state)
1730 		return NULL;
1731 
1732 	memcpy(state->config_space, dev->saved_config_space,
1733 	       sizeof(state->config_space));
1734 
1735 	cap = state->cap;
1736 	hlist_for_each_entry(tmp, &dev->saved_cap_space, next) {
1737 		size_t len = sizeof(struct pci_cap_saved_data) + tmp->cap.size;
1738 		memcpy(cap, &tmp->cap, len);
1739 		cap = (struct pci_cap_saved_data *)((u8 *)cap + len);
1740 	}
1741 	/* Empty cap_save terminates list */
1742 
1743 	return state;
1744 }
1745 EXPORT_SYMBOL_GPL(pci_store_saved_state);
1746 
1747 /**
1748  * pci_load_saved_state - Reload the provided save state into struct pci_dev.
1749  * @dev: PCI device that we're dealing with
1750  * @state: Saved state returned from pci_store_saved_state()
1751  */
pci_load_saved_state(struct pci_dev * dev,struct pci_saved_state * state)1752 int pci_load_saved_state(struct pci_dev *dev,
1753 			 struct pci_saved_state *state)
1754 {
1755 	struct pci_cap_saved_data *cap;
1756 
1757 	dev->state_saved = false;
1758 
1759 	if (!state)
1760 		return 0;
1761 
1762 	memcpy(dev->saved_config_space, state->config_space,
1763 	       sizeof(state->config_space));
1764 
1765 	cap = state->cap;
1766 	while (cap->size) {
1767 		struct pci_cap_saved_state *tmp;
1768 
1769 		tmp = _pci_find_saved_cap(dev, cap->cap_nr, cap->cap_extended);
1770 		if (!tmp || tmp->cap.size != cap->size)
1771 			return -EINVAL;
1772 
1773 		memcpy(tmp->cap.data, cap->data, tmp->cap.size);
1774 		cap = (struct pci_cap_saved_data *)((u8 *)cap +
1775 		       sizeof(struct pci_cap_saved_data) + cap->size);
1776 	}
1777 
1778 	dev->state_saved = true;
1779 	return 0;
1780 }
1781 EXPORT_SYMBOL_GPL(pci_load_saved_state);
1782 
1783 /**
1784  * pci_load_and_free_saved_state - Reload the save state pointed to by state,
1785  *				   and free the memory allocated for it.
1786  * @dev: PCI device that we're dealing with
1787  * @state: Pointer to saved state returned from pci_store_saved_state()
1788  */
pci_load_and_free_saved_state(struct pci_dev * dev,struct pci_saved_state ** state)1789 int pci_load_and_free_saved_state(struct pci_dev *dev,
1790 				  struct pci_saved_state **state)
1791 {
1792 	int ret = pci_load_saved_state(dev, *state);
1793 	kfree(*state);
1794 	*state = NULL;
1795 	return ret;
1796 }
1797 EXPORT_SYMBOL_GPL(pci_load_and_free_saved_state);
1798 
pcibios_enable_device(struct pci_dev * dev,int bars)1799 int __weak pcibios_enable_device(struct pci_dev *dev, int bars)
1800 {
1801 	return pci_enable_resources(dev, bars);
1802 }
1803 
do_pci_enable_device(struct pci_dev * dev,int bars)1804 static int do_pci_enable_device(struct pci_dev *dev, int bars)
1805 {
1806 	int err;
1807 	struct pci_dev *bridge;
1808 	u16 cmd;
1809 	u8 pin;
1810 
1811 	err = pci_set_power_state(dev, PCI_D0);
1812 	if (err < 0 && err != -EIO)
1813 		return err;
1814 
1815 	bridge = pci_upstream_bridge(dev);
1816 	if (bridge)
1817 		pcie_aspm_powersave_config_link(bridge);
1818 
1819 	err = pcibios_enable_device(dev, bars);
1820 	if (err < 0)
1821 		return err;
1822 	pci_fixup_device(pci_fixup_enable, dev);
1823 
1824 	if (dev->msi_enabled || dev->msix_enabled)
1825 		return 0;
1826 
1827 	pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &pin);
1828 	if (pin) {
1829 		pci_read_config_word(dev, PCI_COMMAND, &cmd);
1830 		if (cmd & PCI_COMMAND_INTX_DISABLE)
1831 			pci_write_config_word(dev, PCI_COMMAND,
1832 					      cmd & ~PCI_COMMAND_INTX_DISABLE);
1833 	}
1834 
1835 	return 0;
1836 }
1837 
1838 /**
1839  * pci_reenable_device - Resume abandoned device
1840  * @dev: PCI device to be resumed
1841  *
1842  * NOTE: This function is a backend of pci_default_resume() and is not supposed
1843  * to be called by normal code, write proper resume handler and use it instead.
1844  */
pci_reenable_device(struct pci_dev * dev)1845 int pci_reenable_device(struct pci_dev *dev)
1846 {
1847 	if (pci_is_enabled(dev))
1848 		return do_pci_enable_device(dev, (1 << PCI_NUM_RESOURCES) - 1);
1849 	return 0;
1850 }
1851 EXPORT_SYMBOL(pci_reenable_device);
1852 
pci_enable_bridge(struct pci_dev * dev)1853 static void pci_enable_bridge(struct pci_dev *dev)
1854 {
1855 	struct pci_dev *bridge;
1856 	int retval;
1857 
1858 	bridge = pci_upstream_bridge(dev);
1859 	if (bridge)
1860 		pci_enable_bridge(bridge);
1861 
1862 	if (pci_is_enabled(dev)) {
1863 		if (!dev->is_busmaster)
1864 			pci_set_master(dev);
1865 		return;
1866 	}
1867 
1868 	retval = pci_enable_device(dev);
1869 	if (retval)
1870 		pci_err(dev, "Error enabling bridge (%d), continuing\n",
1871 			retval);
1872 	pci_set_master(dev);
1873 }
1874 
pci_enable_device_flags(struct pci_dev * dev,unsigned long flags)1875 static int pci_enable_device_flags(struct pci_dev *dev, unsigned long flags)
1876 {
1877 	struct pci_dev *bridge;
1878 	int err;
1879 	int i, bars = 0;
1880 
1881 	/*
1882 	 * Power state could be unknown at this point, either due to a fresh
1883 	 * boot or a device removal call.  So get the current power state
1884 	 * so that things like MSI message writing will behave as expected
1885 	 * (e.g. if the device really is in D0 at enable time).
1886 	 */
1887 	pci_update_current_state(dev, dev->current_state);
1888 
1889 	if (atomic_inc_return(&dev->enable_cnt) > 1)
1890 		return 0;		/* already enabled */
1891 
1892 	bridge = pci_upstream_bridge(dev);
1893 	if (bridge)
1894 		pci_enable_bridge(bridge);
1895 
1896 	/* only skip sriov related */
1897 	for (i = 0; i <= PCI_ROM_RESOURCE; i++)
1898 		if (dev->resource[i].flags & flags)
1899 			bars |= (1 << i);
1900 	for (i = PCI_BRIDGE_RESOURCES; i < DEVICE_COUNT_RESOURCE; i++)
1901 		if (dev->resource[i].flags & flags)
1902 			bars |= (1 << i);
1903 
1904 	err = do_pci_enable_device(dev, bars);
1905 	if (err < 0)
1906 		atomic_dec(&dev->enable_cnt);
1907 	return err;
1908 }
1909 
1910 /**
1911  * pci_enable_device_io - Initialize a device for use with IO space
1912  * @dev: PCI device to be initialized
1913  *
1914  * Initialize device before it's used by a driver. Ask low-level code
1915  * to enable I/O resources. Wake up the device if it was suspended.
1916  * Beware, this function can fail.
1917  */
pci_enable_device_io(struct pci_dev * dev)1918 int pci_enable_device_io(struct pci_dev *dev)
1919 {
1920 	return pci_enable_device_flags(dev, IORESOURCE_IO);
1921 }
1922 EXPORT_SYMBOL(pci_enable_device_io);
1923 
1924 /**
1925  * pci_enable_device_mem - Initialize a device for use with Memory space
1926  * @dev: PCI device to be initialized
1927  *
1928  * Initialize device before it's used by a driver. Ask low-level code
1929  * to enable Memory resources. Wake up the device if it was suspended.
1930  * Beware, this function can fail.
1931  */
pci_enable_device_mem(struct pci_dev * dev)1932 int pci_enable_device_mem(struct pci_dev *dev)
1933 {
1934 	return pci_enable_device_flags(dev, IORESOURCE_MEM);
1935 }
1936 EXPORT_SYMBOL(pci_enable_device_mem);
1937 
1938 /**
1939  * pci_enable_device - Initialize device before it's used by a driver.
1940  * @dev: PCI device to be initialized
1941  *
1942  * Initialize device before it's used by a driver. Ask low-level code
1943  * to enable I/O and memory. Wake up the device if it was suspended.
1944  * Beware, this function can fail.
1945  *
1946  * Note we don't actually enable the device many times if we call
1947  * this function repeatedly (we just increment the count).
1948  */
pci_enable_device(struct pci_dev * dev)1949 int pci_enable_device(struct pci_dev *dev)
1950 {
1951 	return pci_enable_device_flags(dev, IORESOURCE_MEM | IORESOURCE_IO);
1952 }
1953 EXPORT_SYMBOL(pci_enable_device);
1954 
1955 /*
1956  * Managed PCI resources.  This manages device on/off, INTx/MSI/MSI-X
1957  * on/off and BAR regions.  pci_dev itself records MSI/MSI-X status, so
1958  * there's no need to track it separately.  pci_devres is initialized
1959  * when a device is enabled using managed PCI device enable interface.
1960  */
1961 struct pci_devres {
1962 	unsigned int enabled:1;
1963 	unsigned int pinned:1;
1964 	unsigned int orig_intx:1;
1965 	unsigned int restore_intx:1;
1966 	unsigned int mwi:1;
1967 	u32 region_mask;
1968 };
1969 
pcim_release(struct device * gendev,void * res)1970 static void pcim_release(struct device *gendev, void *res)
1971 {
1972 	struct pci_dev *dev = to_pci_dev(gendev);
1973 	struct pci_devres *this = res;
1974 	int i;
1975 
1976 	if (dev->msi_enabled)
1977 		pci_disable_msi(dev);
1978 	if (dev->msix_enabled)
1979 		pci_disable_msix(dev);
1980 
1981 	for (i = 0; i < DEVICE_COUNT_RESOURCE; i++)
1982 		if (this->region_mask & (1 << i))
1983 			pci_release_region(dev, i);
1984 
1985 	if (this->mwi)
1986 		pci_clear_mwi(dev);
1987 
1988 	if (this->restore_intx)
1989 		pci_intx(dev, this->orig_intx);
1990 
1991 	if (this->enabled && !this->pinned)
1992 		pci_disable_device(dev);
1993 }
1994 
get_pci_dr(struct pci_dev * pdev)1995 static struct pci_devres *get_pci_dr(struct pci_dev *pdev)
1996 {
1997 	struct pci_devres *dr, *new_dr;
1998 
1999 	dr = devres_find(&pdev->dev, pcim_release, NULL, NULL);
2000 	if (dr)
2001 		return dr;
2002 
2003 	new_dr = devres_alloc(pcim_release, sizeof(*new_dr), GFP_KERNEL);
2004 	if (!new_dr)
2005 		return NULL;
2006 	return devres_get(&pdev->dev, new_dr, NULL, NULL);
2007 }
2008 
find_pci_dr(struct pci_dev * pdev)2009 static struct pci_devres *find_pci_dr(struct pci_dev *pdev)
2010 {
2011 	if (pci_is_managed(pdev))
2012 		return devres_find(&pdev->dev, pcim_release, NULL, NULL);
2013 	return NULL;
2014 }
2015 
2016 /**
2017  * pcim_enable_device - Managed pci_enable_device()
2018  * @pdev: PCI device to be initialized
2019  *
2020  * Managed pci_enable_device().
2021  */
pcim_enable_device(struct pci_dev * pdev)2022 int pcim_enable_device(struct pci_dev *pdev)
2023 {
2024 	struct pci_devres *dr;
2025 	int rc;
2026 
2027 	dr = get_pci_dr(pdev);
2028 	if (unlikely(!dr))
2029 		return -ENOMEM;
2030 	if (dr->enabled)
2031 		return 0;
2032 
2033 	rc = pci_enable_device(pdev);
2034 	if (!rc) {
2035 		pdev->is_managed = 1;
2036 		dr->enabled = 1;
2037 	}
2038 	return rc;
2039 }
2040 EXPORT_SYMBOL(pcim_enable_device);
2041 
2042 /**
2043  * pcim_pin_device - Pin managed PCI device
2044  * @pdev: PCI device to pin
2045  *
2046  * Pin managed PCI device @pdev.  Pinned device won't be disabled on
2047  * driver detach.  @pdev must have been enabled with
2048  * pcim_enable_device().
2049  */
pcim_pin_device(struct pci_dev * pdev)2050 void pcim_pin_device(struct pci_dev *pdev)
2051 {
2052 	struct pci_devres *dr;
2053 
2054 	dr = find_pci_dr(pdev);
2055 	WARN_ON(!dr || !dr->enabled);
2056 	if (dr)
2057 		dr->pinned = 1;
2058 }
2059 EXPORT_SYMBOL(pcim_pin_device);
2060 
2061 /*
2062  * pcibios_add_device - provide arch specific hooks when adding device dev
2063  * @dev: the PCI device being added
2064  *
2065  * Permits the platform to provide architecture specific functionality when
2066  * devices are added. This is the default implementation. Architecture
2067  * implementations can override this.
2068  */
pcibios_add_device(struct pci_dev * dev)2069 int __weak pcibios_add_device(struct pci_dev *dev)
2070 {
2071 	return 0;
2072 }
2073 
2074 /**
2075  * pcibios_release_device - provide arch specific hooks when releasing
2076  *			    device dev
2077  * @dev: the PCI device being released
2078  *
2079  * Permits the platform to provide architecture specific functionality when
2080  * devices are released. This is the default implementation. Architecture
2081  * implementations can override this.
2082  */
pcibios_release_device(struct pci_dev * dev)2083 void __weak pcibios_release_device(struct pci_dev *dev) {}
2084 
2085 /**
2086  * pcibios_disable_device - disable arch specific PCI resources for device dev
2087  * @dev: the PCI device to disable
2088  *
2089  * Disables architecture specific PCI resources for the device. This
2090  * is the default implementation. Architecture implementations can
2091  * override this.
2092  */
pcibios_disable_device(struct pci_dev * dev)2093 void __weak pcibios_disable_device(struct pci_dev *dev) {}
2094 
2095 /**
2096  * pcibios_penalize_isa_irq - penalize an ISA IRQ
2097  * @irq: ISA IRQ to penalize
2098  * @active: IRQ active or not
2099  *
2100  * Permits the platform to provide architecture-specific functionality when
2101  * penalizing ISA IRQs. This is the default implementation. Architecture
2102  * implementations can override this.
2103  */
pcibios_penalize_isa_irq(int irq,int active)2104 void __weak pcibios_penalize_isa_irq(int irq, int active) {}
2105 
do_pci_disable_device(struct pci_dev * dev)2106 static void do_pci_disable_device(struct pci_dev *dev)
2107 {
2108 	u16 pci_command;
2109 
2110 	pci_read_config_word(dev, PCI_COMMAND, &pci_command);
2111 	if (pci_command & PCI_COMMAND_MASTER) {
2112 		pci_command &= ~PCI_COMMAND_MASTER;
2113 		pci_write_config_word(dev, PCI_COMMAND, pci_command);
2114 	}
2115 
2116 	pcibios_disable_device(dev);
2117 }
2118 
2119 /**
2120  * pci_disable_enabled_device - Disable device without updating enable_cnt
2121  * @dev: PCI device to disable
2122  *
2123  * NOTE: This function is a backend of PCI power management routines and is
2124  * not supposed to be called drivers.
2125  */
pci_disable_enabled_device(struct pci_dev * dev)2126 void pci_disable_enabled_device(struct pci_dev *dev)
2127 {
2128 	if (pci_is_enabled(dev))
2129 		do_pci_disable_device(dev);
2130 }
2131 
2132 /**
2133  * pci_disable_device - Disable PCI device after use
2134  * @dev: PCI device to be disabled
2135  *
2136  * Signal to the system that the PCI device is not in use by the system
2137  * anymore.  This only involves disabling PCI bus-mastering, if active.
2138  *
2139  * Note we don't actually disable the device until all callers of
2140  * pci_enable_device() have called pci_disable_device().
2141  */
pci_disable_device(struct pci_dev * dev)2142 void pci_disable_device(struct pci_dev *dev)
2143 {
2144 	struct pci_devres *dr;
2145 
2146 	dr = find_pci_dr(dev);
2147 	if (dr)
2148 		dr->enabled = 0;
2149 
2150 	dev_WARN_ONCE(&dev->dev, atomic_read(&dev->enable_cnt) <= 0,
2151 		      "disabling already-disabled device");
2152 
2153 	if (atomic_dec_return(&dev->enable_cnt) != 0)
2154 		return;
2155 
2156 	do_pci_disable_device(dev);
2157 
2158 	dev->is_busmaster = 0;
2159 }
2160 EXPORT_SYMBOL(pci_disable_device);
2161 
2162 /**
2163  * pcibios_set_pcie_reset_state - set reset state for device dev
2164  * @dev: the PCIe device reset
2165  * @state: Reset state to enter into
2166  *
2167  * Set the PCIe reset state for the device. This is the default
2168  * implementation. Architecture implementations can override this.
2169  */
pcibios_set_pcie_reset_state(struct pci_dev * dev,enum pcie_reset_state state)2170 int __weak pcibios_set_pcie_reset_state(struct pci_dev *dev,
2171 					enum pcie_reset_state state)
2172 {
2173 	return -EINVAL;
2174 }
2175 
2176 /**
2177  * pci_set_pcie_reset_state - set reset state for device dev
2178  * @dev: the PCIe device reset
2179  * @state: Reset state to enter into
2180  *
2181  * Sets the PCI reset state for the device.
2182  */
pci_set_pcie_reset_state(struct pci_dev * dev,enum pcie_reset_state state)2183 int pci_set_pcie_reset_state(struct pci_dev *dev, enum pcie_reset_state state)
2184 {
2185 	return pcibios_set_pcie_reset_state(dev, state);
2186 }
2187 EXPORT_SYMBOL_GPL(pci_set_pcie_reset_state);
2188 
pcie_clear_device_status(struct pci_dev * dev)2189 void pcie_clear_device_status(struct pci_dev *dev)
2190 {
2191 	u16 sta;
2192 
2193 	pcie_capability_read_word(dev, PCI_EXP_DEVSTA, &sta);
2194 	pcie_capability_write_word(dev, PCI_EXP_DEVSTA, sta);
2195 }
2196 
2197 /**
2198  * pcie_clear_root_pme_status - Clear root port PME interrupt status.
2199  * @dev: PCIe root port or event collector.
2200  */
pcie_clear_root_pme_status(struct pci_dev * dev)2201 void pcie_clear_root_pme_status(struct pci_dev *dev)
2202 {
2203 	pcie_capability_set_dword(dev, PCI_EXP_RTSTA, PCI_EXP_RTSTA_PME);
2204 }
2205 
2206 /**
2207  * pci_check_pme_status - Check if given device has generated PME.
2208  * @dev: Device to check.
2209  *
2210  * Check the PME status of the device and if set, clear it and clear PME enable
2211  * (if set).  Return 'true' if PME status and PME enable were both set or
2212  * 'false' otherwise.
2213  */
pci_check_pme_status(struct pci_dev * dev)2214 bool pci_check_pme_status(struct pci_dev *dev)
2215 {
2216 	int pmcsr_pos;
2217 	u16 pmcsr;
2218 	bool ret = false;
2219 
2220 	if (!dev->pm_cap)
2221 		return false;
2222 
2223 	pmcsr_pos = dev->pm_cap + PCI_PM_CTRL;
2224 	pci_read_config_word(dev, pmcsr_pos, &pmcsr);
2225 	if (!(pmcsr & PCI_PM_CTRL_PME_STATUS))
2226 		return false;
2227 
2228 	/* Clear PME status. */
2229 	pmcsr |= PCI_PM_CTRL_PME_STATUS;
2230 	if (pmcsr & PCI_PM_CTRL_PME_ENABLE) {
2231 		/* Disable PME to avoid interrupt flood. */
2232 		pmcsr &= ~PCI_PM_CTRL_PME_ENABLE;
2233 		ret = true;
2234 	}
2235 
2236 	pci_write_config_word(dev, pmcsr_pos, pmcsr);
2237 
2238 	return ret;
2239 }
2240 
2241 /**
2242  * pci_pme_wakeup - Wake up a PCI device if its PME Status bit is set.
2243  * @dev: Device to handle.
2244  * @pme_poll_reset: Whether or not to reset the device's pme_poll flag.
2245  *
2246  * Check if @dev has generated PME and queue a resume request for it in that
2247  * case.
2248  */
pci_pme_wakeup(struct pci_dev * dev,void * pme_poll_reset)2249 static int pci_pme_wakeup(struct pci_dev *dev, void *pme_poll_reset)
2250 {
2251 	if (pme_poll_reset && dev->pme_poll)
2252 		dev->pme_poll = false;
2253 
2254 	if (pci_check_pme_status(dev)) {
2255 		pci_wakeup_event(dev);
2256 		pm_request_resume(&dev->dev);
2257 	}
2258 	return 0;
2259 }
2260 
2261 /**
2262  * pci_pme_wakeup_bus - Walk given bus and wake up devices on it, if necessary.
2263  * @bus: Top bus of the subtree to walk.
2264  */
pci_pme_wakeup_bus(struct pci_bus * bus)2265 void pci_pme_wakeup_bus(struct pci_bus *bus)
2266 {
2267 	if (bus)
2268 		pci_walk_bus(bus, pci_pme_wakeup, (void *)true);
2269 }
2270 
2271 
2272 /**
2273  * pci_pme_capable - check the capability of PCI device to generate PME#
2274  * @dev: PCI device to handle.
2275  * @state: PCI state from which device will issue PME#.
2276  */
pci_pme_capable(struct pci_dev * dev,pci_power_t state)2277 bool pci_pme_capable(struct pci_dev *dev, pci_power_t state)
2278 {
2279 	if (!dev->pm_cap)
2280 		return false;
2281 
2282 	return !!(dev->pme_support & (1 << state));
2283 }
2284 EXPORT_SYMBOL(pci_pme_capable);
2285 
pci_pme_list_scan(struct work_struct * work)2286 static void pci_pme_list_scan(struct work_struct *work)
2287 {
2288 	struct pci_pme_device *pme_dev, *n;
2289 
2290 	mutex_lock(&pci_pme_list_mutex);
2291 	list_for_each_entry_safe(pme_dev, n, &pci_pme_list, list) {
2292 		if (pme_dev->dev->pme_poll) {
2293 			struct pci_dev *bridge;
2294 
2295 			bridge = pme_dev->dev->bus->self;
2296 			/*
2297 			 * If bridge is in low power state, the
2298 			 * configuration space of subordinate devices
2299 			 * may be not accessible
2300 			 */
2301 			if (bridge && bridge->current_state != PCI_D0)
2302 				continue;
2303 			/*
2304 			 * If the device is in D3cold it should not be
2305 			 * polled either.
2306 			 */
2307 			if (pme_dev->dev->current_state == PCI_D3cold)
2308 				continue;
2309 
2310 			pci_pme_wakeup(pme_dev->dev, NULL);
2311 		} else {
2312 			list_del(&pme_dev->list);
2313 			kfree(pme_dev);
2314 		}
2315 	}
2316 	if (!list_empty(&pci_pme_list))
2317 		queue_delayed_work(system_freezable_wq, &pci_pme_work,
2318 				   msecs_to_jiffies(PME_TIMEOUT));
2319 	mutex_unlock(&pci_pme_list_mutex);
2320 }
2321 
__pci_pme_active(struct pci_dev * dev,bool enable)2322 static void __pci_pme_active(struct pci_dev *dev, bool enable)
2323 {
2324 	u16 pmcsr;
2325 
2326 	if (!dev->pme_support)
2327 		return;
2328 
2329 	pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
2330 	/* Clear PME_Status by writing 1 to it and enable PME# */
2331 	pmcsr |= PCI_PM_CTRL_PME_STATUS | PCI_PM_CTRL_PME_ENABLE;
2332 	if (!enable)
2333 		pmcsr &= ~PCI_PM_CTRL_PME_ENABLE;
2334 
2335 	pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, pmcsr);
2336 }
2337 
2338 /**
2339  * pci_pme_restore - Restore PME configuration after config space restore.
2340  * @dev: PCI device to update.
2341  */
pci_pme_restore(struct pci_dev * dev)2342 void pci_pme_restore(struct pci_dev *dev)
2343 {
2344 	u16 pmcsr;
2345 
2346 	if (!dev->pme_support)
2347 		return;
2348 
2349 	pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
2350 	if (dev->wakeup_prepared) {
2351 		pmcsr |= PCI_PM_CTRL_PME_ENABLE;
2352 		pmcsr &= ~PCI_PM_CTRL_PME_STATUS;
2353 	} else {
2354 		pmcsr &= ~PCI_PM_CTRL_PME_ENABLE;
2355 		pmcsr |= PCI_PM_CTRL_PME_STATUS;
2356 	}
2357 	pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, pmcsr);
2358 }
2359 
2360 /**
2361  * pci_pme_active - enable or disable PCI device's PME# function
2362  * @dev: PCI device to handle.
2363  * @enable: 'true' to enable PME# generation; 'false' to disable it.
2364  *
2365  * The caller must verify that the device is capable of generating PME# before
2366  * calling this function with @enable equal to 'true'.
2367  */
pci_pme_active(struct pci_dev * dev,bool enable)2368 void pci_pme_active(struct pci_dev *dev, bool enable)
2369 {
2370 	__pci_pme_active(dev, enable);
2371 
2372 	/*
2373 	 * PCI (as opposed to PCIe) PME requires that the device have
2374 	 * its PME# line hooked up correctly. Not all hardware vendors
2375 	 * do this, so the PME never gets delivered and the device
2376 	 * remains asleep. The easiest way around this is to
2377 	 * periodically walk the list of suspended devices and check
2378 	 * whether any have their PME flag set. The assumption is that
2379 	 * we'll wake up often enough anyway that this won't be a huge
2380 	 * hit, and the power savings from the devices will still be a
2381 	 * win.
2382 	 *
2383 	 * Although PCIe uses in-band PME message instead of PME# line
2384 	 * to report PME, PME does not work for some PCIe devices in
2385 	 * reality.  For example, there are devices that set their PME
2386 	 * status bits, but don't really bother to send a PME message;
2387 	 * there are PCI Express Root Ports that don't bother to
2388 	 * trigger interrupts when they receive PME messages from the
2389 	 * devices below.  So PME poll is used for PCIe devices too.
2390 	 */
2391 
2392 	if (dev->pme_poll) {
2393 		struct pci_pme_device *pme_dev;
2394 		if (enable) {
2395 			pme_dev = kmalloc(sizeof(struct pci_pme_device),
2396 					  GFP_KERNEL);
2397 			if (!pme_dev) {
2398 				pci_warn(dev, "can't enable PME#\n");
2399 				return;
2400 			}
2401 			pme_dev->dev = dev;
2402 			mutex_lock(&pci_pme_list_mutex);
2403 			list_add(&pme_dev->list, &pci_pme_list);
2404 			if (list_is_singular(&pci_pme_list))
2405 				queue_delayed_work(system_freezable_wq,
2406 						   &pci_pme_work,
2407 						   msecs_to_jiffies(PME_TIMEOUT));
2408 			mutex_unlock(&pci_pme_list_mutex);
2409 		} else {
2410 			mutex_lock(&pci_pme_list_mutex);
2411 			list_for_each_entry(pme_dev, &pci_pme_list, list) {
2412 				if (pme_dev->dev == dev) {
2413 					list_del(&pme_dev->list);
2414 					kfree(pme_dev);
2415 					break;
2416 				}
2417 			}
2418 			mutex_unlock(&pci_pme_list_mutex);
2419 		}
2420 	}
2421 
2422 	pci_dbg(dev, "PME# %s\n", enable ? "enabled" : "disabled");
2423 }
2424 EXPORT_SYMBOL(pci_pme_active);
2425 
2426 /**
2427  * __pci_enable_wake - enable PCI device as wakeup event source
2428  * @dev: PCI device affected
2429  * @state: PCI state from which device will issue wakeup events
2430  * @enable: True to enable event generation; false to disable
2431  *
2432  * This enables the device as a wakeup event source, or disables it.
2433  * When such events involves platform-specific hooks, those hooks are
2434  * called automatically by this routine.
2435  *
2436  * Devices with legacy power management (no standard PCI PM capabilities)
2437  * always require such platform hooks.
2438  *
2439  * RETURN VALUE:
2440  * 0 is returned on success
2441  * -EINVAL is returned if device is not supposed to wake up the system
2442  * Error code depending on the platform is returned if both the platform and
2443  * the native mechanism fail to enable the generation of wake-up events
2444  */
__pci_enable_wake(struct pci_dev * dev,pci_power_t state,bool enable)2445 static int __pci_enable_wake(struct pci_dev *dev, pci_power_t state, bool enable)
2446 {
2447 	int ret = 0;
2448 
2449 	/*
2450 	 * Bridges that are not power-manageable directly only signal
2451 	 * wakeup on behalf of subordinate devices which is set up
2452 	 * elsewhere, so skip them. However, bridges that are
2453 	 * power-manageable may signal wakeup for themselves (for example,
2454 	 * on a hotplug event) and they need to be covered here.
2455 	 */
2456 	if (!pci_power_manageable(dev))
2457 		return 0;
2458 
2459 	/* Don't do the same thing twice in a row for one device. */
2460 	if (!!enable == !!dev->wakeup_prepared)
2461 		return 0;
2462 
2463 	/*
2464 	 * According to "PCI System Architecture" 4th ed. by Tom Shanley & Don
2465 	 * Anderson we should be doing PME# wake enable followed by ACPI wake
2466 	 * enable.  To disable wake-up we call the platform first, for symmetry.
2467 	 */
2468 
2469 	if (enable) {
2470 		int error;
2471 
2472 		/*
2473 		 * Enable PME signaling if the device can signal PME from
2474 		 * D3cold regardless of whether or not it can signal PME from
2475 		 * the current target state, because that will allow it to
2476 		 * signal PME when the hierarchy above it goes into D3cold and
2477 		 * the device itself ends up in D3cold as a result of that.
2478 		 */
2479 		if (pci_pme_capable(dev, state) || pci_pme_capable(dev, PCI_D3cold))
2480 			pci_pme_active(dev, true);
2481 		else
2482 			ret = 1;
2483 		error = platform_pci_set_wakeup(dev, true);
2484 		if (ret)
2485 			ret = error;
2486 		if (!ret)
2487 			dev->wakeup_prepared = true;
2488 	} else {
2489 		platform_pci_set_wakeup(dev, false);
2490 		pci_pme_active(dev, false);
2491 		dev->wakeup_prepared = false;
2492 	}
2493 
2494 	return ret;
2495 }
2496 
2497 /**
2498  * pci_enable_wake - change wakeup settings for a PCI device
2499  * @pci_dev: Target device
2500  * @state: PCI state from which device will issue wakeup events
2501  * @enable: Whether or not to enable event generation
2502  *
2503  * If @enable is set, check device_may_wakeup() for the device before calling
2504  * __pci_enable_wake() for it.
2505  */
pci_enable_wake(struct pci_dev * pci_dev,pci_power_t state,bool enable)2506 int pci_enable_wake(struct pci_dev *pci_dev, pci_power_t state, bool enable)
2507 {
2508 	if (enable && !device_may_wakeup(&pci_dev->dev))
2509 		return -EINVAL;
2510 
2511 	return __pci_enable_wake(pci_dev, state, enable);
2512 }
2513 EXPORT_SYMBOL(pci_enable_wake);
2514 
2515 /**
2516  * pci_wake_from_d3 - enable/disable device to wake up from D3_hot or D3_cold
2517  * @dev: PCI device to prepare
2518  * @enable: True to enable wake-up event generation; false to disable
2519  *
2520  * Many drivers want the device to wake up the system from D3_hot or D3_cold
2521  * and this function allows them to set that up cleanly - pci_enable_wake()
2522  * should not be called twice in a row to enable wake-up due to PCI PM vs ACPI
2523  * ordering constraints.
2524  *
2525  * This function only returns error code if the device is not allowed to wake
2526  * up the system from sleep or it is not capable of generating PME# from both
2527  * D3_hot and D3_cold and the platform is unable to enable wake-up power for it.
2528  */
pci_wake_from_d3(struct pci_dev * dev,bool enable)2529 int pci_wake_from_d3(struct pci_dev *dev, bool enable)
2530 {
2531 	return pci_pme_capable(dev, PCI_D3cold) ?
2532 			pci_enable_wake(dev, PCI_D3cold, enable) :
2533 			pci_enable_wake(dev, PCI_D3hot, enable);
2534 }
2535 EXPORT_SYMBOL(pci_wake_from_d3);
2536 
2537 /**
2538  * pci_target_state - find an appropriate low power state for a given PCI dev
2539  * @dev: PCI device
2540  * @wakeup: Whether or not wakeup functionality will be enabled for the device.
2541  *
2542  * Use underlying platform code to find a supported low power state for @dev.
2543  * If the platform can't manage @dev, return the deepest state from which it
2544  * can generate wake events, based on any available PME info.
2545  */
pci_target_state(struct pci_dev * dev,bool wakeup)2546 static pci_power_t pci_target_state(struct pci_dev *dev, bool wakeup)
2547 {
2548 	pci_power_t target_state = PCI_D3hot;
2549 
2550 	if (platform_pci_power_manageable(dev)) {
2551 		/*
2552 		 * Call the platform to find the target state for the device.
2553 		 */
2554 		pci_power_t state = platform_pci_choose_state(dev);
2555 
2556 		switch (state) {
2557 		case PCI_POWER_ERROR:
2558 		case PCI_UNKNOWN:
2559 			break;
2560 		case PCI_D1:
2561 		case PCI_D2:
2562 			if (pci_no_d1d2(dev))
2563 				break;
2564 			fallthrough;
2565 		default:
2566 			target_state = state;
2567 		}
2568 
2569 		return target_state;
2570 	}
2571 
2572 	if (!dev->pm_cap)
2573 		target_state = PCI_D0;
2574 
2575 	/*
2576 	 * If the device is in D3cold even though it's not power-manageable by
2577 	 * the platform, it may have been powered down by non-standard means.
2578 	 * Best to let it slumber.
2579 	 */
2580 	if (dev->current_state == PCI_D3cold)
2581 		target_state = PCI_D3cold;
2582 
2583 	if (wakeup && dev->pme_support) {
2584 		pci_power_t state = target_state;
2585 
2586 		/*
2587 		 * Find the deepest state from which the device can generate
2588 		 * PME#.
2589 		 */
2590 		while (state && !(dev->pme_support & (1 << state)))
2591 			state--;
2592 
2593 		if (state)
2594 			return state;
2595 		else if (dev->pme_support & 1)
2596 			return PCI_D0;
2597 	}
2598 
2599 	return target_state;
2600 }
2601 
2602 /**
2603  * pci_prepare_to_sleep - prepare PCI device for system-wide transition
2604  *			  into a sleep state
2605  * @dev: Device to handle.
2606  *
2607  * Choose the power state appropriate for the device depending on whether
2608  * it can wake up the system and/or is power manageable by the platform
2609  * (PCI_D3hot is the default) and put the device into that state.
2610  */
pci_prepare_to_sleep(struct pci_dev * dev)2611 int pci_prepare_to_sleep(struct pci_dev *dev)
2612 {
2613 	bool wakeup = device_may_wakeup(&dev->dev);
2614 	pci_power_t target_state = pci_target_state(dev, wakeup);
2615 	int error;
2616 
2617 	if (target_state == PCI_POWER_ERROR)
2618 		return -EIO;
2619 
2620 	pci_enable_wake(dev, target_state, wakeup);
2621 
2622 	error = pci_set_power_state(dev, target_state);
2623 
2624 	if (error)
2625 		pci_enable_wake(dev, target_state, false);
2626 
2627 	return error;
2628 }
2629 EXPORT_SYMBOL(pci_prepare_to_sleep);
2630 
2631 /**
2632  * pci_back_from_sleep - turn PCI device on during system-wide transition
2633  *			 into working state
2634  * @dev: Device to handle.
2635  *
2636  * Disable device's system wake-up capability and put it into D0.
2637  */
pci_back_from_sleep(struct pci_dev * dev)2638 int pci_back_from_sleep(struct pci_dev *dev)
2639 {
2640 	pci_enable_wake(dev, PCI_D0, false);
2641 	return pci_set_power_state(dev, PCI_D0);
2642 }
2643 EXPORT_SYMBOL(pci_back_from_sleep);
2644 
2645 /**
2646  * pci_finish_runtime_suspend - Carry out PCI-specific part of runtime suspend.
2647  * @dev: PCI device being suspended.
2648  *
2649  * Prepare @dev to generate wake-up events at run time and put it into a low
2650  * power state.
2651  */
pci_finish_runtime_suspend(struct pci_dev * dev)2652 int pci_finish_runtime_suspend(struct pci_dev *dev)
2653 {
2654 	pci_power_t target_state;
2655 	int error;
2656 
2657 	target_state = pci_target_state(dev, device_can_wakeup(&dev->dev));
2658 	if (target_state == PCI_POWER_ERROR)
2659 		return -EIO;
2660 
2661 	dev->runtime_d3cold = target_state == PCI_D3cold;
2662 
2663 	__pci_enable_wake(dev, target_state, pci_dev_run_wake(dev));
2664 
2665 	error = pci_set_power_state(dev, target_state);
2666 
2667 	if (error) {
2668 		pci_enable_wake(dev, target_state, false);
2669 		dev->runtime_d3cold = false;
2670 	}
2671 
2672 	return error;
2673 }
2674 
2675 /**
2676  * pci_dev_run_wake - Check if device can generate run-time wake-up events.
2677  * @dev: Device to check.
2678  *
2679  * Return true if the device itself is capable of generating wake-up events
2680  * (through the platform or using the native PCIe PME) or if the device supports
2681  * PME and one of its upstream bridges can generate wake-up events.
2682  */
pci_dev_run_wake(struct pci_dev * dev)2683 bool pci_dev_run_wake(struct pci_dev *dev)
2684 {
2685 	struct pci_bus *bus = dev->bus;
2686 
2687 	if (!dev->pme_support)
2688 		return false;
2689 
2690 	/* PME-capable in principle, but not from the target power state */
2691 	if (!pci_pme_capable(dev, pci_target_state(dev, true)))
2692 		return false;
2693 
2694 	if (device_can_wakeup(&dev->dev))
2695 		return true;
2696 
2697 	while (bus->parent) {
2698 		struct pci_dev *bridge = bus->self;
2699 
2700 		if (device_can_wakeup(&bridge->dev))
2701 			return true;
2702 
2703 		bus = bus->parent;
2704 	}
2705 
2706 	/* We have reached the root bus. */
2707 	if (bus->bridge)
2708 		return device_can_wakeup(bus->bridge);
2709 
2710 	return false;
2711 }
2712 EXPORT_SYMBOL_GPL(pci_dev_run_wake);
2713 
2714 /**
2715  * pci_dev_need_resume - Check if it is necessary to resume the device.
2716  * @pci_dev: Device to check.
2717  *
2718  * Return 'true' if the device is not runtime-suspended or it has to be
2719  * reconfigured due to wakeup settings difference between system and runtime
2720  * suspend, or the current power state of it is not suitable for the upcoming
2721  * (system-wide) transition.
2722  */
pci_dev_need_resume(struct pci_dev * pci_dev)2723 bool pci_dev_need_resume(struct pci_dev *pci_dev)
2724 {
2725 	struct device *dev = &pci_dev->dev;
2726 	pci_power_t target_state;
2727 
2728 	if (!pm_runtime_suspended(dev) || platform_pci_need_resume(pci_dev))
2729 		return true;
2730 
2731 	target_state = pci_target_state(pci_dev, device_may_wakeup(dev));
2732 
2733 	/*
2734 	 * If the earlier platform check has not triggered, D3cold is just power
2735 	 * removal on top of D3hot, so no need to resume the device in that
2736 	 * case.
2737 	 */
2738 	return target_state != pci_dev->current_state &&
2739 		target_state != PCI_D3cold &&
2740 		pci_dev->current_state != PCI_D3hot;
2741 }
2742 
2743 /**
2744  * pci_dev_adjust_pme - Adjust PME setting for a suspended device.
2745  * @pci_dev: Device to check.
2746  *
2747  * If the device is suspended and it is not configured for system wakeup,
2748  * disable PME for it to prevent it from waking up the system unnecessarily.
2749  *
2750  * Note that if the device's power state is D3cold and the platform check in
2751  * pci_dev_need_resume() has not triggered, the device's configuration need not
2752  * be changed.
2753  */
pci_dev_adjust_pme(struct pci_dev * pci_dev)2754 void pci_dev_adjust_pme(struct pci_dev *pci_dev)
2755 {
2756 	struct device *dev = &pci_dev->dev;
2757 
2758 	spin_lock_irq(&dev->power.lock);
2759 
2760 	if (pm_runtime_suspended(dev) && !device_may_wakeup(dev) &&
2761 	    pci_dev->current_state < PCI_D3cold)
2762 		__pci_pme_active(pci_dev, false);
2763 
2764 	spin_unlock_irq(&dev->power.lock);
2765 }
2766 
2767 /**
2768  * pci_dev_complete_resume - Finalize resume from system sleep for a device.
2769  * @pci_dev: Device to handle.
2770  *
2771  * If the device is runtime suspended and wakeup-capable, enable PME for it as
2772  * it might have been disabled during the prepare phase of system suspend if
2773  * the device was not configured for system wakeup.
2774  */
pci_dev_complete_resume(struct pci_dev * pci_dev)2775 void pci_dev_complete_resume(struct pci_dev *pci_dev)
2776 {
2777 	struct device *dev = &pci_dev->dev;
2778 
2779 	if (!pci_dev_run_wake(pci_dev))
2780 		return;
2781 
2782 	spin_lock_irq(&dev->power.lock);
2783 
2784 	if (pm_runtime_suspended(dev) && pci_dev->current_state < PCI_D3cold)
2785 		__pci_pme_active(pci_dev, true);
2786 
2787 	spin_unlock_irq(&dev->power.lock);
2788 }
2789 
pci_config_pm_runtime_get(struct pci_dev * pdev)2790 void pci_config_pm_runtime_get(struct pci_dev *pdev)
2791 {
2792 	struct device *dev = &pdev->dev;
2793 	struct device *parent = dev->parent;
2794 
2795 	if (parent)
2796 		pm_runtime_get_sync(parent);
2797 	pm_runtime_get_noresume(dev);
2798 	/*
2799 	 * pdev->current_state is set to PCI_D3cold during suspending,
2800 	 * so wait until suspending completes
2801 	 */
2802 	pm_runtime_barrier(dev);
2803 	/*
2804 	 * Only need to resume devices in D3cold, because config
2805 	 * registers are still accessible for devices suspended but
2806 	 * not in D3cold.
2807 	 */
2808 	if (pdev->current_state == PCI_D3cold)
2809 		pm_runtime_resume(dev);
2810 }
2811 
pci_config_pm_runtime_put(struct pci_dev * pdev)2812 void pci_config_pm_runtime_put(struct pci_dev *pdev)
2813 {
2814 	struct device *dev = &pdev->dev;
2815 	struct device *parent = dev->parent;
2816 
2817 	pm_runtime_put(dev);
2818 	if (parent)
2819 		pm_runtime_put_sync(parent);
2820 }
2821 
2822 static const struct dmi_system_id bridge_d3_blacklist[] = {
2823 #ifdef CONFIG_X86
2824 	{
2825 		/*
2826 		 * Gigabyte X299 root port is not marked as hotplug capable
2827 		 * which allows Linux to power manage it.  However, this
2828 		 * confuses the BIOS SMI handler so don't power manage root
2829 		 * ports on that system.
2830 		 */
2831 		.ident = "X299 DESIGNARE EX-CF",
2832 		.matches = {
2833 			DMI_MATCH(DMI_BOARD_VENDOR, "Gigabyte Technology Co., Ltd."),
2834 			DMI_MATCH(DMI_BOARD_NAME, "X299 DESIGNARE EX-CF"),
2835 		},
2836 	},
2837 	{
2838 		/*
2839 		 * Downstream device is not accessible after putting a root port
2840 		 * into D3cold and back into D0 on Elo Continental Z2 board
2841 		 */
2842 		.ident = "Elo Continental Z2",
2843 		.matches = {
2844 			DMI_MATCH(DMI_BOARD_VENDOR, "Elo Touch Solutions"),
2845 			DMI_MATCH(DMI_BOARD_NAME, "Geminilake"),
2846 			DMI_MATCH(DMI_BOARD_VERSION, "Continental Z2"),
2847 		},
2848 	},
2849 #endif
2850 	{ }
2851 };
2852 
2853 /**
2854  * pci_bridge_d3_possible - Is it possible to put the bridge into D3
2855  * @bridge: Bridge to check
2856  *
2857  * This function checks if it is possible to move the bridge to D3.
2858  * Currently we only allow D3 for recent enough PCIe ports and Thunderbolt.
2859  */
pci_bridge_d3_possible(struct pci_dev * bridge)2860 bool pci_bridge_d3_possible(struct pci_dev *bridge)
2861 {
2862 	if (!pci_is_pcie(bridge))
2863 		return false;
2864 
2865 	switch (pci_pcie_type(bridge)) {
2866 	case PCI_EXP_TYPE_ROOT_PORT:
2867 	case PCI_EXP_TYPE_UPSTREAM:
2868 	case PCI_EXP_TYPE_DOWNSTREAM:
2869 		if (pci_bridge_d3_disable)
2870 			return false;
2871 
2872 		/*
2873 		 * Hotplug ports handled by firmware in System Management Mode
2874 		 * may not be put into D3 by the OS (Thunderbolt on non-Macs).
2875 		 */
2876 		if (bridge->is_hotplug_bridge && !pciehp_is_native(bridge))
2877 			return false;
2878 
2879 		if (pci_bridge_d3_force)
2880 			return true;
2881 
2882 		/* Even the oldest 2010 Thunderbolt controller supports D3. */
2883 		if (bridge->is_thunderbolt)
2884 			return true;
2885 
2886 		/* Platform might know better if the bridge supports D3 */
2887 		if (platform_pci_bridge_d3(bridge))
2888 			return true;
2889 
2890 		/*
2891 		 * Hotplug ports handled natively by the OS were not validated
2892 		 * by vendors for runtime D3 at least until 2018 because there
2893 		 * was no OS support.
2894 		 */
2895 		if (bridge->is_hotplug_bridge)
2896 			return false;
2897 
2898 		if (dmi_check_system(bridge_d3_blacklist))
2899 			return false;
2900 
2901 		/*
2902 		 * It should be safe to put PCIe ports from 2015 or newer
2903 		 * to D3.
2904 		 */
2905 		if (dmi_get_bios_year() >= 2015)
2906 			return true;
2907 		break;
2908 	}
2909 
2910 	return false;
2911 }
2912 
pci_dev_check_d3cold(struct pci_dev * dev,void * data)2913 static int pci_dev_check_d3cold(struct pci_dev *dev, void *data)
2914 {
2915 	bool *d3cold_ok = data;
2916 
2917 	if (/* The device needs to be allowed to go D3cold ... */
2918 	    dev->no_d3cold || !dev->d3cold_allowed ||
2919 
2920 	    /* ... and if it is wakeup capable to do so from D3cold. */
2921 	    (device_may_wakeup(&dev->dev) &&
2922 	     !pci_pme_capable(dev, PCI_D3cold)) ||
2923 
2924 	    /* If it is a bridge it must be allowed to go to D3. */
2925 	    !pci_power_manageable(dev))
2926 
2927 		*d3cold_ok = false;
2928 
2929 	return !*d3cold_ok;
2930 }
2931 
2932 /*
2933  * pci_bridge_d3_update - Update bridge D3 capabilities
2934  * @dev: PCI device which is changed
2935  *
2936  * Update upstream bridge PM capabilities accordingly depending on if the
2937  * device PM configuration was changed or the device is being removed.  The
2938  * change is also propagated upstream.
2939  */
pci_bridge_d3_update(struct pci_dev * dev)2940 void pci_bridge_d3_update(struct pci_dev *dev)
2941 {
2942 	bool remove = !device_is_registered(&dev->dev);
2943 	struct pci_dev *bridge;
2944 	bool d3cold_ok = true;
2945 
2946 	bridge = pci_upstream_bridge(dev);
2947 	if (!bridge || !pci_bridge_d3_possible(bridge))
2948 		return;
2949 
2950 	/*
2951 	 * If D3 is currently allowed for the bridge, removing one of its
2952 	 * children won't change that.
2953 	 */
2954 	if (remove && bridge->bridge_d3)
2955 		return;
2956 
2957 	/*
2958 	 * If D3 is currently allowed for the bridge and a child is added or
2959 	 * changed, disallowance of D3 can only be caused by that child, so
2960 	 * we only need to check that single device, not any of its siblings.
2961 	 *
2962 	 * If D3 is currently not allowed for the bridge, checking the device
2963 	 * first may allow us to skip checking its siblings.
2964 	 */
2965 	if (!remove)
2966 		pci_dev_check_d3cold(dev, &d3cold_ok);
2967 
2968 	/*
2969 	 * If D3 is currently not allowed for the bridge, this may be caused
2970 	 * either by the device being changed/removed or any of its siblings,
2971 	 * so we need to go through all children to find out if one of them
2972 	 * continues to block D3.
2973 	 */
2974 	if (d3cold_ok && !bridge->bridge_d3)
2975 		pci_walk_bus(bridge->subordinate, pci_dev_check_d3cold,
2976 			     &d3cold_ok);
2977 
2978 	if (bridge->bridge_d3 != d3cold_ok) {
2979 		bridge->bridge_d3 = d3cold_ok;
2980 		/* Propagate change to upstream bridges */
2981 		pci_bridge_d3_update(bridge);
2982 	}
2983 }
2984 
2985 /**
2986  * pci_d3cold_enable - Enable D3cold for device
2987  * @dev: PCI device to handle
2988  *
2989  * This function can be used in drivers to enable D3cold from the device
2990  * they handle.  It also updates upstream PCI bridge PM capabilities
2991  * accordingly.
2992  */
pci_d3cold_enable(struct pci_dev * dev)2993 void pci_d3cold_enable(struct pci_dev *dev)
2994 {
2995 	if (dev->no_d3cold) {
2996 		dev->no_d3cold = false;
2997 		pci_bridge_d3_update(dev);
2998 	}
2999 }
3000 EXPORT_SYMBOL_GPL(pci_d3cold_enable);
3001 
3002 /**
3003  * pci_d3cold_disable - Disable D3cold for device
3004  * @dev: PCI device to handle
3005  *
3006  * This function can be used in drivers to disable D3cold from the device
3007  * they handle.  It also updates upstream PCI bridge PM capabilities
3008  * accordingly.
3009  */
pci_d3cold_disable(struct pci_dev * dev)3010 void pci_d3cold_disable(struct pci_dev *dev)
3011 {
3012 	if (!dev->no_d3cold) {
3013 		dev->no_d3cold = true;
3014 		pci_bridge_d3_update(dev);
3015 	}
3016 }
3017 EXPORT_SYMBOL_GPL(pci_d3cold_disable);
3018 
3019 /**
3020  * pci_pm_init - Initialize PM functions of given PCI device
3021  * @dev: PCI device to handle.
3022  */
pci_pm_init(struct pci_dev * dev)3023 void pci_pm_init(struct pci_dev *dev)
3024 {
3025 	int pm;
3026 	u16 status;
3027 	u16 pmc;
3028 
3029 	pm_runtime_forbid(&dev->dev);
3030 	pm_runtime_set_active(&dev->dev);
3031 	pm_runtime_enable(&dev->dev);
3032 	device_enable_async_suspend(&dev->dev);
3033 	dev->wakeup_prepared = false;
3034 
3035 	dev->pm_cap = 0;
3036 	dev->pme_support = 0;
3037 
3038 	/* find PCI PM capability in list */
3039 	pm = pci_find_capability(dev, PCI_CAP_ID_PM);
3040 	if (!pm)
3041 		return;
3042 	/* Check device's ability to generate PME# */
3043 	pci_read_config_word(dev, pm + PCI_PM_PMC, &pmc);
3044 
3045 	if ((pmc & PCI_PM_CAP_VER_MASK) > 3) {
3046 		pci_err(dev, "unsupported PM cap regs version (%u)\n",
3047 			pmc & PCI_PM_CAP_VER_MASK);
3048 		return;
3049 	}
3050 
3051 	dev->pm_cap = pm;
3052 	dev->d3hot_delay = PCI_PM_D3HOT_WAIT;
3053 	dev->d3cold_delay = PCI_PM_D3COLD_WAIT;
3054 	dev->bridge_d3 = pci_bridge_d3_possible(dev);
3055 	dev->d3cold_allowed = true;
3056 
3057 	dev->d1_support = false;
3058 	dev->d2_support = false;
3059 	if (!pci_no_d1d2(dev)) {
3060 		if (pmc & PCI_PM_CAP_D1)
3061 			dev->d1_support = true;
3062 		if (pmc & PCI_PM_CAP_D2)
3063 			dev->d2_support = true;
3064 
3065 		if (dev->d1_support || dev->d2_support)
3066 			pci_info(dev, "supports%s%s\n",
3067 				   dev->d1_support ? " D1" : "",
3068 				   dev->d2_support ? " D2" : "");
3069 	}
3070 
3071 	pmc &= PCI_PM_CAP_PME_MASK;
3072 	if (pmc) {
3073 		pci_info(dev, "PME# supported from%s%s%s%s%s\n",
3074 			 (pmc & PCI_PM_CAP_PME_D0) ? " D0" : "",
3075 			 (pmc & PCI_PM_CAP_PME_D1) ? " D1" : "",
3076 			 (pmc & PCI_PM_CAP_PME_D2) ? " D2" : "",
3077 			 (pmc & PCI_PM_CAP_PME_D3hot) ? " D3hot" : "",
3078 			 (pmc & PCI_PM_CAP_PME_D3cold) ? " D3cold" : "");
3079 		dev->pme_support = pmc >> PCI_PM_CAP_PME_SHIFT;
3080 		dev->pme_poll = true;
3081 		/*
3082 		 * Make device's PM flags reflect the wake-up capability, but
3083 		 * let the user space enable it to wake up the system as needed.
3084 		 */
3085 		device_set_wakeup_capable(&dev->dev, true);
3086 		/* Disable the PME# generation functionality */
3087 		pci_pme_active(dev, false);
3088 	}
3089 
3090 	pci_read_config_word(dev, PCI_STATUS, &status);
3091 	if (status & PCI_STATUS_IMM_READY)
3092 		dev->imm_ready = 1;
3093 }
3094 
pci_ea_flags(struct pci_dev * dev,u8 prop)3095 static unsigned long pci_ea_flags(struct pci_dev *dev, u8 prop)
3096 {
3097 	unsigned long flags = IORESOURCE_PCI_FIXED | IORESOURCE_PCI_EA_BEI;
3098 
3099 	switch (prop) {
3100 	case PCI_EA_P_MEM:
3101 	case PCI_EA_P_VF_MEM:
3102 		flags |= IORESOURCE_MEM;
3103 		break;
3104 	case PCI_EA_P_MEM_PREFETCH:
3105 	case PCI_EA_P_VF_MEM_PREFETCH:
3106 		flags |= IORESOURCE_MEM | IORESOURCE_PREFETCH;
3107 		break;
3108 	case PCI_EA_P_IO:
3109 		flags |= IORESOURCE_IO;
3110 		break;
3111 	default:
3112 		return 0;
3113 	}
3114 
3115 	return flags;
3116 }
3117 
pci_ea_get_resource(struct pci_dev * dev,u8 bei,u8 prop)3118 static struct resource *pci_ea_get_resource(struct pci_dev *dev, u8 bei,
3119 					    u8 prop)
3120 {
3121 	if (bei <= PCI_EA_BEI_BAR5 && prop <= PCI_EA_P_IO)
3122 		return &dev->resource[bei];
3123 #ifdef CONFIG_PCI_IOV
3124 	else if (bei >= PCI_EA_BEI_VF_BAR0 && bei <= PCI_EA_BEI_VF_BAR5 &&
3125 		 (prop == PCI_EA_P_VF_MEM || prop == PCI_EA_P_VF_MEM_PREFETCH))
3126 		return &dev->resource[PCI_IOV_RESOURCES +
3127 				      bei - PCI_EA_BEI_VF_BAR0];
3128 #endif
3129 	else if (bei == PCI_EA_BEI_ROM)
3130 		return &dev->resource[PCI_ROM_RESOURCE];
3131 	else
3132 		return NULL;
3133 }
3134 
3135 /* Read an Enhanced Allocation (EA) entry */
pci_ea_read(struct pci_dev * dev,int offset)3136 static int pci_ea_read(struct pci_dev *dev, int offset)
3137 {
3138 	struct resource *res;
3139 	int ent_size, ent_offset = offset;
3140 	resource_size_t start, end;
3141 	unsigned long flags;
3142 	u32 dw0, bei, base, max_offset;
3143 	u8 prop;
3144 	bool support_64 = (sizeof(resource_size_t) >= 8);
3145 
3146 	pci_read_config_dword(dev, ent_offset, &dw0);
3147 	ent_offset += 4;
3148 
3149 	/* Entry size field indicates DWORDs after 1st */
3150 	ent_size = ((dw0 & PCI_EA_ES) + 1) << 2;
3151 
3152 	if (!(dw0 & PCI_EA_ENABLE)) /* Entry not enabled */
3153 		goto out;
3154 
3155 	bei = (dw0 & PCI_EA_BEI) >> 4;
3156 	prop = (dw0 & PCI_EA_PP) >> 8;
3157 
3158 	/*
3159 	 * If the Property is in the reserved range, try the Secondary
3160 	 * Property instead.
3161 	 */
3162 	if (prop > PCI_EA_P_BRIDGE_IO && prop < PCI_EA_P_MEM_RESERVED)
3163 		prop = (dw0 & PCI_EA_SP) >> 16;
3164 	if (prop > PCI_EA_P_BRIDGE_IO)
3165 		goto out;
3166 
3167 	res = pci_ea_get_resource(dev, bei, prop);
3168 	if (!res) {
3169 		pci_err(dev, "Unsupported EA entry BEI: %u\n", bei);
3170 		goto out;
3171 	}
3172 
3173 	flags = pci_ea_flags(dev, prop);
3174 	if (!flags) {
3175 		pci_err(dev, "Unsupported EA properties: %#x\n", prop);
3176 		goto out;
3177 	}
3178 
3179 	/* Read Base */
3180 	pci_read_config_dword(dev, ent_offset, &base);
3181 	start = (base & PCI_EA_FIELD_MASK);
3182 	ent_offset += 4;
3183 
3184 	/* Read MaxOffset */
3185 	pci_read_config_dword(dev, ent_offset, &max_offset);
3186 	ent_offset += 4;
3187 
3188 	/* Read Base MSBs (if 64-bit entry) */
3189 	if (base & PCI_EA_IS_64) {
3190 		u32 base_upper;
3191 
3192 		pci_read_config_dword(dev, ent_offset, &base_upper);
3193 		ent_offset += 4;
3194 
3195 		flags |= IORESOURCE_MEM_64;
3196 
3197 		/* entry starts above 32-bit boundary, can't use */
3198 		if (!support_64 && base_upper)
3199 			goto out;
3200 
3201 		if (support_64)
3202 			start |= ((u64)base_upper << 32);
3203 	}
3204 
3205 	end = start + (max_offset | 0x03);
3206 
3207 	/* Read MaxOffset MSBs (if 64-bit entry) */
3208 	if (max_offset & PCI_EA_IS_64) {
3209 		u32 max_offset_upper;
3210 
3211 		pci_read_config_dword(dev, ent_offset, &max_offset_upper);
3212 		ent_offset += 4;
3213 
3214 		flags |= IORESOURCE_MEM_64;
3215 
3216 		/* entry too big, can't use */
3217 		if (!support_64 && max_offset_upper)
3218 			goto out;
3219 
3220 		if (support_64)
3221 			end += ((u64)max_offset_upper << 32);
3222 	}
3223 
3224 	if (end < start) {
3225 		pci_err(dev, "EA Entry crosses address boundary\n");
3226 		goto out;
3227 	}
3228 
3229 	if (ent_size != ent_offset - offset) {
3230 		pci_err(dev, "EA Entry Size (%d) does not match length read (%d)\n",
3231 			ent_size, ent_offset - offset);
3232 		goto out;
3233 	}
3234 
3235 	res->name = pci_name(dev);
3236 	res->start = start;
3237 	res->end = end;
3238 	res->flags = flags;
3239 
3240 	if (bei <= PCI_EA_BEI_BAR5)
3241 		pci_info(dev, "BAR %d: %pR (from Enhanced Allocation, properties %#02x)\n",
3242 			   bei, res, prop);
3243 	else if (bei == PCI_EA_BEI_ROM)
3244 		pci_info(dev, "ROM: %pR (from Enhanced Allocation, properties %#02x)\n",
3245 			   res, prop);
3246 	else if (bei >= PCI_EA_BEI_VF_BAR0 && bei <= PCI_EA_BEI_VF_BAR5)
3247 		pci_info(dev, "VF BAR %d: %pR (from Enhanced Allocation, properties %#02x)\n",
3248 			   bei - PCI_EA_BEI_VF_BAR0, res, prop);
3249 	else
3250 		pci_info(dev, "BEI %d res: %pR (from Enhanced Allocation, properties %#02x)\n",
3251 			   bei, res, prop);
3252 
3253 out:
3254 	return offset + ent_size;
3255 }
3256 
3257 /* Enhanced Allocation Initialization */
pci_ea_init(struct pci_dev * dev)3258 void pci_ea_init(struct pci_dev *dev)
3259 {
3260 	int ea;
3261 	u8 num_ent;
3262 	int offset;
3263 	int i;
3264 
3265 	/* find PCI EA capability in list */
3266 	ea = pci_find_capability(dev, PCI_CAP_ID_EA);
3267 	if (!ea)
3268 		return;
3269 
3270 	/* determine the number of entries */
3271 	pci_bus_read_config_byte(dev->bus, dev->devfn, ea + PCI_EA_NUM_ENT,
3272 					&num_ent);
3273 	num_ent &= PCI_EA_NUM_ENT_MASK;
3274 
3275 	offset = ea + PCI_EA_FIRST_ENT;
3276 
3277 	/* Skip DWORD 2 for type 1 functions */
3278 	if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE)
3279 		offset += 4;
3280 
3281 	/* parse each EA entry */
3282 	for (i = 0; i < num_ent; ++i)
3283 		offset = pci_ea_read(dev, offset);
3284 }
3285 
pci_add_saved_cap(struct pci_dev * pci_dev,struct pci_cap_saved_state * new_cap)3286 static void pci_add_saved_cap(struct pci_dev *pci_dev,
3287 	struct pci_cap_saved_state *new_cap)
3288 {
3289 	hlist_add_head(&new_cap->next, &pci_dev->saved_cap_space);
3290 }
3291 
3292 /**
3293  * _pci_add_cap_save_buffer - allocate buffer for saving given
3294  *			      capability registers
3295  * @dev: the PCI device
3296  * @cap: the capability to allocate the buffer for
3297  * @extended: Standard or Extended capability ID
3298  * @size: requested size of the buffer
3299  */
_pci_add_cap_save_buffer(struct pci_dev * dev,u16 cap,bool extended,unsigned int size)3300 static int _pci_add_cap_save_buffer(struct pci_dev *dev, u16 cap,
3301 				    bool extended, unsigned int size)
3302 {
3303 	int pos;
3304 	struct pci_cap_saved_state *save_state;
3305 
3306 	if (extended)
3307 		pos = pci_find_ext_capability(dev, cap);
3308 	else
3309 		pos = pci_find_capability(dev, cap);
3310 
3311 	if (!pos)
3312 		return 0;
3313 
3314 	save_state = kzalloc(sizeof(*save_state) + size, GFP_KERNEL);
3315 	if (!save_state)
3316 		return -ENOMEM;
3317 
3318 	save_state->cap.cap_nr = cap;
3319 	save_state->cap.cap_extended = extended;
3320 	save_state->cap.size = size;
3321 	pci_add_saved_cap(dev, save_state);
3322 
3323 	return 0;
3324 }
3325 
pci_add_cap_save_buffer(struct pci_dev * dev,char cap,unsigned int size)3326 int pci_add_cap_save_buffer(struct pci_dev *dev, char cap, unsigned int size)
3327 {
3328 	return _pci_add_cap_save_buffer(dev, cap, false, size);
3329 }
3330 
pci_add_ext_cap_save_buffer(struct pci_dev * dev,u16 cap,unsigned int size)3331 int pci_add_ext_cap_save_buffer(struct pci_dev *dev, u16 cap, unsigned int size)
3332 {
3333 	return _pci_add_cap_save_buffer(dev, cap, true, size);
3334 }
3335 
3336 /**
3337  * pci_allocate_cap_save_buffers - allocate buffers for saving capabilities
3338  * @dev: the PCI device
3339  */
pci_allocate_cap_save_buffers(struct pci_dev * dev)3340 void pci_allocate_cap_save_buffers(struct pci_dev *dev)
3341 {
3342 	int error;
3343 
3344 	error = pci_add_cap_save_buffer(dev, PCI_CAP_ID_EXP,
3345 					PCI_EXP_SAVE_REGS * sizeof(u16));
3346 	if (error)
3347 		pci_err(dev, "unable to preallocate PCI Express save buffer\n");
3348 
3349 	error = pci_add_cap_save_buffer(dev, PCI_CAP_ID_PCIX, sizeof(u16));
3350 	if (error)
3351 		pci_err(dev, "unable to preallocate PCI-X save buffer\n");
3352 
3353 	error = pci_add_ext_cap_save_buffer(dev, PCI_EXT_CAP_ID_LTR,
3354 					    2 * sizeof(u16));
3355 	if (error)
3356 		pci_err(dev, "unable to allocate suspend buffer for LTR\n");
3357 
3358 	pci_allocate_vc_save_buffers(dev);
3359 }
3360 
pci_free_cap_save_buffers(struct pci_dev * dev)3361 void pci_free_cap_save_buffers(struct pci_dev *dev)
3362 {
3363 	struct pci_cap_saved_state *tmp;
3364 	struct hlist_node *n;
3365 
3366 	hlist_for_each_entry_safe(tmp, n, &dev->saved_cap_space, next)
3367 		kfree(tmp);
3368 }
3369 
3370 /**
3371  * pci_configure_ari - enable or disable ARI forwarding
3372  * @dev: the PCI device
3373  *
3374  * If @dev and its upstream bridge both support ARI, enable ARI in the
3375  * bridge.  Otherwise, disable ARI in the bridge.
3376  */
pci_configure_ari(struct pci_dev * dev)3377 void pci_configure_ari(struct pci_dev *dev)
3378 {
3379 	u32 cap;
3380 	struct pci_dev *bridge;
3381 
3382 	if (pcie_ari_disabled || !pci_is_pcie(dev) || dev->devfn)
3383 		return;
3384 
3385 	bridge = dev->bus->self;
3386 	if (!bridge)
3387 		return;
3388 
3389 	pcie_capability_read_dword(bridge, PCI_EXP_DEVCAP2, &cap);
3390 	if (!(cap & PCI_EXP_DEVCAP2_ARI))
3391 		return;
3392 
3393 	if (pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ARI)) {
3394 		pcie_capability_set_word(bridge, PCI_EXP_DEVCTL2,
3395 					 PCI_EXP_DEVCTL2_ARI);
3396 		bridge->ari_enabled = 1;
3397 	} else {
3398 		pcie_capability_clear_word(bridge, PCI_EXP_DEVCTL2,
3399 					   PCI_EXP_DEVCTL2_ARI);
3400 		bridge->ari_enabled = 0;
3401 	}
3402 }
3403 
pci_acs_flags_enabled(struct pci_dev * pdev,u16 acs_flags)3404 static bool pci_acs_flags_enabled(struct pci_dev *pdev, u16 acs_flags)
3405 {
3406 	int pos;
3407 	u16 cap, ctrl;
3408 
3409 	pos = pdev->acs_cap;
3410 	if (!pos)
3411 		return false;
3412 
3413 	/*
3414 	 * Except for egress control, capabilities are either required
3415 	 * or only required if controllable.  Features missing from the
3416 	 * capability field can therefore be assumed as hard-wired enabled.
3417 	 */
3418 	pci_read_config_word(pdev, pos + PCI_ACS_CAP, &cap);
3419 	acs_flags &= (cap | PCI_ACS_EC);
3420 
3421 	pci_read_config_word(pdev, pos + PCI_ACS_CTRL, &ctrl);
3422 	return (ctrl & acs_flags) == acs_flags;
3423 }
3424 
3425 /**
3426  * pci_acs_enabled - test ACS against required flags for a given device
3427  * @pdev: device to test
3428  * @acs_flags: required PCI ACS flags
3429  *
3430  * Return true if the device supports the provided flags.  Automatically
3431  * filters out flags that are not implemented on multifunction devices.
3432  *
3433  * Note that this interface checks the effective ACS capabilities of the
3434  * device rather than the actual capabilities.  For instance, most single
3435  * function endpoints are not required to support ACS because they have no
3436  * opportunity for peer-to-peer access.  We therefore return 'true'
3437  * regardless of whether the device exposes an ACS capability.  This makes
3438  * it much easier for callers of this function to ignore the actual type
3439  * or topology of the device when testing ACS support.
3440  */
pci_acs_enabled(struct pci_dev * pdev,u16 acs_flags)3441 bool pci_acs_enabled(struct pci_dev *pdev, u16 acs_flags)
3442 {
3443 	int ret;
3444 
3445 	ret = pci_dev_specific_acs_enabled(pdev, acs_flags);
3446 	if (ret >= 0)
3447 		return ret > 0;
3448 
3449 	/*
3450 	 * Conventional PCI and PCI-X devices never support ACS, either
3451 	 * effectively or actually.  The shared bus topology implies that
3452 	 * any device on the bus can receive or snoop DMA.
3453 	 */
3454 	if (!pci_is_pcie(pdev))
3455 		return false;
3456 
3457 	switch (pci_pcie_type(pdev)) {
3458 	/*
3459 	 * PCI/X-to-PCIe bridges are not specifically mentioned by the spec,
3460 	 * but since their primary interface is PCI/X, we conservatively
3461 	 * handle them as we would a non-PCIe device.
3462 	 */
3463 	case PCI_EXP_TYPE_PCIE_BRIDGE:
3464 	/*
3465 	 * PCIe 3.0, 6.12.1 excludes ACS on these devices.  "ACS is never
3466 	 * applicable... must never implement an ACS Extended Capability...".
3467 	 * This seems arbitrary, but we take a conservative interpretation
3468 	 * of this statement.
3469 	 */
3470 	case PCI_EXP_TYPE_PCI_BRIDGE:
3471 	case PCI_EXP_TYPE_RC_EC:
3472 		return false;
3473 	/*
3474 	 * PCIe 3.0, 6.12.1.1 specifies that downstream and root ports should
3475 	 * implement ACS in order to indicate their peer-to-peer capabilities,
3476 	 * regardless of whether they are single- or multi-function devices.
3477 	 */
3478 	case PCI_EXP_TYPE_DOWNSTREAM:
3479 	case PCI_EXP_TYPE_ROOT_PORT:
3480 		return pci_acs_flags_enabled(pdev, acs_flags);
3481 	/*
3482 	 * PCIe 3.0, 6.12.1.2 specifies ACS capabilities that should be
3483 	 * implemented by the remaining PCIe types to indicate peer-to-peer
3484 	 * capabilities, but only when they are part of a multifunction
3485 	 * device.  The footnote for section 6.12 indicates the specific
3486 	 * PCIe types included here.
3487 	 */
3488 	case PCI_EXP_TYPE_ENDPOINT:
3489 	case PCI_EXP_TYPE_UPSTREAM:
3490 	case PCI_EXP_TYPE_LEG_END:
3491 	case PCI_EXP_TYPE_RC_END:
3492 		if (!pdev->multifunction)
3493 			break;
3494 
3495 		return pci_acs_flags_enabled(pdev, acs_flags);
3496 	}
3497 
3498 	/*
3499 	 * PCIe 3.0, 6.12.1.3 specifies no ACS capabilities are applicable
3500 	 * to single function devices with the exception of downstream ports.
3501 	 */
3502 	return true;
3503 }
3504 
3505 /**
3506  * pci_acs_path_enable - test ACS flags from start to end in a hierarchy
3507  * @start: starting downstream device
3508  * @end: ending upstream device or NULL to search to the root bus
3509  * @acs_flags: required flags
3510  *
3511  * Walk up a device tree from start to end testing PCI ACS support.  If
3512  * any step along the way does not support the required flags, return false.
3513  */
pci_acs_path_enabled(struct pci_dev * start,struct pci_dev * end,u16 acs_flags)3514 bool pci_acs_path_enabled(struct pci_dev *start,
3515 			  struct pci_dev *end, u16 acs_flags)
3516 {
3517 	struct pci_dev *pdev, *parent = start;
3518 
3519 	do {
3520 		pdev = parent;
3521 
3522 		if (!pci_acs_enabled(pdev, acs_flags))
3523 			return false;
3524 
3525 		if (pci_is_root_bus(pdev->bus))
3526 			return (end == NULL);
3527 
3528 		parent = pdev->bus->self;
3529 	} while (pdev != end);
3530 
3531 	return true;
3532 }
3533 
3534 /**
3535  * pci_acs_init - Initialize ACS if hardware supports it
3536  * @dev: the PCI device
3537  */
pci_acs_init(struct pci_dev * dev)3538 void pci_acs_init(struct pci_dev *dev)
3539 {
3540 	dev->acs_cap = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ACS);
3541 
3542 	/*
3543 	 * Attempt to enable ACS regardless of capability because some Root
3544 	 * Ports (e.g. those quirked with *_intel_pch_acs_*) do not have
3545 	 * the standard ACS capability but still support ACS via those
3546 	 * quirks.
3547 	 */
3548 	pci_enable_acs(dev);
3549 }
3550 
3551 /**
3552  * pci_rebar_find_pos - find position of resize ctrl reg for BAR
3553  * @pdev: PCI device
3554  * @bar: BAR to find
3555  *
3556  * Helper to find the position of the ctrl register for a BAR.
3557  * Returns -ENOTSUPP if resizable BARs are not supported at all.
3558  * Returns -ENOENT if no ctrl register for the BAR could be found.
3559  */
pci_rebar_find_pos(struct pci_dev * pdev,int bar)3560 static int pci_rebar_find_pos(struct pci_dev *pdev, int bar)
3561 {
3562 	unsigned int pos, nbars, i;
3563 	u32 ctrl;
3564 
3565 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_REBAR);
3566 	if (!pos)
3567 		return -ENOTSUPP;
3568 
3569 	pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
3570 	nbars = (ctrl & PCI_REBAR_CTRL_NBAR_MASK) >>
3571 		    PCI_REBAR_CTRL_NBAR_SHIFT;
3572 
3573 	for (i = 0; i < nbars; i++, pos += 8) {
3574 		int bar_idx;
3575 
3576 		pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
3577 		bar_idx = ctrl & PCI_REBAR_CTRL_BAR_IDX;
3578 		if (bar_idx == bar)
3579 			return pos;
3580 	}
3581 
3582 	return -ENOENT;
3583 }
3584 
3585 /**
3586  * pci_rebar_get_possible_sizes - get possible sizes for BAR
3587  * @pdev: PCI device
3588  * @bar: BAR to query
3589  *
3590  * Get the possible sizes of a resizable BAR as bitmask defined in the spec
3591  * (bit 0=1MB, bit 19=512GB). Returns 0 if BAR isn't resizable.
3592  */
pci_rebar_get_possible_sizes(struct pci_dev * pdev,int bar)3593 u32 pci_rebar_get_possible_sizes(struct pci_dev *pdev, int bar)
3594 {
3595 	int pos;
3596 	u32 cap;
3597 
3598 	pos = pci_rebar_find_pos(pdev, bar);
3599 	if (pos < 0)
3600 		return 0;
3601 
3602 	pci_read_config_dword(pdev, pos + PCI_REBAR_CAP, &cap);
3603 	cap &= PCI_REBAR_CAP_SIZES;
3604 
3605 	/* Sapphire RX 5600 XT Pulse has an invalid cap dword for BAR 0 */
3606 	if (pdev->vendor == PCI_VENDOR_ID_ATI && pdev->device == 0x731f &&
3607 	    bar == 0 && cap == 0x7000)
3608 		cap = 0x3f000;
3609 
3610 	return cap >> 4;
3611 }
3612 
3613 /**
3614  * pci_rebar_get_current_size - get the current size of a BAR
3615  * @pdev: PCI device
3616  * @bar: BAR to set size to
3617  *
3618  * Read the size of a BAR from the resizable BAR config.
3619  * Returns size if found or negative error code.
3620  */
pci_rebar_get_current_size(struct pci_dev * pdev,int bar)3621 int pci_rebar_get_current_size(struct pci_dev *pdev, int bar)
3622 {
3623 	int pos;
3624 	u32 ctrl;
3625 
3626 	pos = pci_rebar_find_pos(pdev, bar);
3627 	if (pos < 0)
3628 		return pos;
3629 
3630 	pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
3631 	return (ctrl & PCI_REBAR_CTRL_BAR_SIZE) >> PCI_REBAR_CTRL_BAR_SHIFT;
3632 }
3633 
3634 /**
3635  * pci_rebar_set_size - set a new size for a BAR
3636  * @pdev: PCI device
3637  * @bar: BAR to set size to
3638  * @size: new size as defined in the spec (0=1MB, 19=512GB)
3639  *
3640  * Set the new size of a BAR as defined in the spec.
3641  * Returns zero if resizing was successful, error code otherwise.
3642  */
pci_rebar_set_size(struct pci_dev * pdev,int bar,int size)3643 int pci_rebar_set_size(struct pci_dev *pdev, int bar, int size)
3644 {
3645 	int pos;
3646 	u32 ctrl;
3647 
3648 	pos = pci_rebar_find_pos(pdev, bar);
3649 	if (pos < 0)
3650 		return pos;
3651 
3652 	pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
3653 	ctrl &= ~PCI_REBAR_CTRL_BAR_SIZE;
3654 	ctrl |= size << PCI_REBAR_CTRL_BAR_SHIFT;
3655 	pci_write_config_dword(pdev, pos + PCI_REBAR_CTRL, ctrl);
3656 	return 0;
3657 }
3658 
3659 /**
3660  * pci_enable_atomic_ops_to_root - enable AtomicOp requests to root port
3661  * @dev: the PCI device
3662  * @cap_mask: mask of desired AtomicOp sizes, including one or more of:
3663  *	PCI_EXP_DEVCAP2_ATOMIC_COMP32
3664  *	PCI_EXP_DEVCAP2_ATOMIC_COMP64
3665  *	PCI_EXP_DEVCAP2_ATOMIC_COMP128
3666  *
3667  * Return 0 if all upstream bridges support AtomicOp routing, egress
3668  * blocking is disabled on all upstream ports, and the root port supports
3669  * the requested completion capabilities (32-bit, 64-bit and/or 128-bit
3670  * AtomicOp completion), or negative otherwise.
3671  */
pci_enable_atomic_ops_to_root(struct pci_dev * dev,u32 cap_mask)3672 int pci_enable_atomic_ops_to_root(struct pci_dev *dev, u32 cap_mask)
3673 {
3674 	struct pci_bus *bus = dev->bus;
3675 	struct pci_dev *bridge;
3676 	u32 cap, ctl2;
3677 
3678 	if (!pci_is_pcie(dev))
3679 		return -EINVAL;
3680 
3681 	/*
3682 	 * Per PCIe r4.0, sec 6.15, endpoints and root ports may be
3683 	 * AtomicOp requesters.  For now, we only support endpoints as
3684 	 * requesters and root ports as completers.  No endpoints as
3685 	 * completers, and no peer-to-peer.
3686 	 */
3687 
3688 	switch (pci_pcie_type(dev)) {
3689 	case PCI_EXP_TYPE_ENDPOINT:
3690 	case PCI_EXP_TYPE_LEG_END:
3691 	case PCI_EXP_TYPE_RC_END:
3692 		break;
3693 	default:
3694 		return -EINVAL;
3695 	}
3696 
3697 	while (bus->parent) {
3698 		bridge = bus->self;
3699 
3700 		pcie_capability_read_dword(bridge, PCI_EXP_DEVCAP2, &cap);
3701 
3702 		switch (pci_pcie_type(bridge)) {
3703 		/* Ensure switch ports support AtomicOp routing */
3704 		case PCI_EXP_TYPE_UPSTREAM:
3705 		case PCI_EXP_TYPE_DOWNSTREAM:
3706 			if (!(cap & PCI_EXP_DEVCAP2_ATOMIC_ROUTE))
3707 				return -EINVAL;
3708 			break;
3709 
3710 		/* Ensure root port supports all the sizes we care about */
3711 		case PCI_EXP_TYPE_ROOT_PORT:
3712 			if ((cap & cap_mask) != cap_mask)
3713 				return -EINVAL;
3714 			break;
3715 		}
3716 
3717 		/* Ensure upstream ports don't block AtomicOps on egress */
3718 		if (pci_pcie_type(bridge) == PCI_EXP_TYPE_UPSTREAM) {
3719 			pcie_capability_read_dword(bridge, PCI_EXP_DEVCTL2,
3720 						   &ctl2);
3721 			if (ctl2 & PCI_EXP_DEVCTL2_ATOMIC_EGRESS_BLOCK)
3722 				return -EINVAL;
3723 		}
3724 
3725 		bus = bus->parent;
3726 	}
3727 
3728 	pcie_capability_set_word(dev, PCI_EXP_DEVCTL2,
3729 				 PCI_EXP_DEVCTL2_ATOMIC_REQ);
3730 	return 0;
3731 }
3732 EXPORT_SYMBOL(pci_enable_atomic_ops_to_root);
3733 
3734 /**
3735  * pci_swizzle_interrupt_pin - swizzle INTx for device behind bridge
3736  * @dev: the PCI device
3737  * @pin: the INTx pin (1=INTA, 2=INTB, 3=INTC, 4=INTD)
3738  *
3739  * Perform INTx swizzling for a device behind one level of bridge.  This is
3740  * required by section 9.1 of the PCI-to-PCI bridge specification for devices
3741  * behind bridges on add-in cards.  For devices with ARI enabled, the slot
3742  * number is always 0 (see the Implementation Note in section 2.2.8.1 of
3743  * the PCI Express Base Specification, Revision 2.1)
3744  */
pci_swizzle_interrupt_pin(const struct pci_dev * dev,u8 pin)3745 u8 pci_swizzle_interrupt_pin(const struct pci_dev *dev, u8 pin)
3746 {
3747 	int slot;
3748 
3749 	if (pci_ari_enabled(dev->bus))
3750 		slot = 0;
3751 	else
3752 		slot = PCI_SLOT(dev->devfn);
3753 
3754 	return (((pin - 1) + slot) % 4) + 1;
3755 }
3756 
pci_get_interrupt_pin(struct pci_dev * dev,struct pci_dev ** bridge)3757 int pci_get_interrupt_pin(struct pci_dev *dev, struct pci_dev **bridge)
3758 {
3759 	u8 pin;
3760 
3761 	pin = dev->pin;
3762 	if (!pin)
3763 		return -1;
3764 
3765 	while (!pci_is_root_bus(dev->bus)) {
3766 		pin = pci_swizzle_interrupt_pin(dev, pin);
3767 		dev = dev->bus->self;
3768 	}
3769 	*bridge = dev;
3770 	return pin;
3771 }
3772 
3773 /**
3774  * pci_common_swizzle - swizzle INTx all the way to root bridge
3775  * @dev: the PCI device
3776  * @pinp: pointer to the INTx pin value (1=INTA, 2=INTB, 3=INTD, 4=INTD)
3777  *
3778  * Perform INTx swizzling for a device.  This traverses through all PCI-to-PCI
3779  * bridges all the way up to a PCI root bus.
3780  */
pci_common_swizzle(struct pci_dev * dev,u8 * pinp)3781 u8 pci_common_swizzle(struct pci_dev *dev, u8 *pinp)
3782 {
3783 	u8 pin = *pinp;
3784 
3785 	while (!pci_is_root_bus(dev->bus)) {
3786 		pin = pci_swizzle_interrupt_pin(dev, pin);
3787 		dev = dev->bus->self;
3788 	}
3789 	*pinp = pin;
3790 	return PCI_SLOT(dev->devfn);
3791 }
3792 EXPORT_SYMBOL_GPL(pci_common_swizzle);
3793 
3794 /**
3795  * pci_release_region - Release a PCI bar
3796  * @pdev: PCI device whose resources were previously reserved by
3797  *	  pci_request_region()
3798  * @bar: BAR to release
3799  *
3800  * Releases the PCI I/O and memory resources previously reserved by a
3801  * successful call to pci_request_region().  Call this function only
3802  * after all use of the PCI regions has ceased.
3803  */
pci_release_region(struct pci_dev * pdev,int bar)3804 void pci_release_region(struct pci_dev *pdev, int bar)
3805 {
3806 	struct pci_devres *dr;
3807 
3808 	if (pci_resource_len(pdev, bar) == 0)
3809 		return;
3810 	if (pci_resource_flags(pdev, bar) & IORESOURCE_IO)
3811 		release_region(pci_resource_start(pdev, bar),
3812 				pci_resource_len(pdev, bar));
3813 	else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM)
3814 		release_mem_region(pci_resource_start(pdev, bar),
3815 				pci_resource_len(pdev, bar));
3816 
3817 	dr = find_pci_dr(pdev);
3818 	if (dr)
3819 		dr->region_mask &= ~(1 << bar);
3820 }
3821 EXPORT_SYMBOL(pci_release_region);
3822 
3823 /**
3824  * __pci_request_region - Reserved PCI I/O and memory resource
3825  * @pdev: PCI device whose resources are to be reserved
3826  * @bar: BAR to be reserved
3827  * @res_name: Name to be associated with resource.
3828  * @exclusive: whether the region access is exclusive or not
3829  *
3830  * Mark the PCI region associated with PCI device @pdev BAR @bar as
3831  * being reserved by owner @res_name.  Do not access any
3832  * address inside the PCI regions unless this call returns
3833  * successfully.
3834  *
3835  * If @exclusive is set, then the region is marked so that userspace
3836  * is explicitly not allowed to map the resource via /dev/mem or
3837  * sysfs MMIO access.
3838  *
3839  * Returns 0 on success, or %EBUSY on error.  A warning
3840  * message is also printed on failure.
3841  */
__pci_request_region(struct pci_dev * pdev,int bar,const char * res_name,int exclusive)3842 static int __pci_request_region(struct pci_dev *pdev, int bar,
3843 				const char *res_name, int exclusive)
3844 {
3845 	struct pci_devres *dr;
3846 
3847 	if (pci_resource_len(pdev, bar) == 0)
3848 		return 0;
3849 
3850 	if (pci_resource_flags(pdev, bar) & IORESOURCE_IO) {
3851 		if (!request_region(pci_resource_start(pdev, bar),
3852 			    pci_resource_len(pdev, bar), res_name))
3853 			goto err_out;
3854 	} else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM) {
3855 		if (!__request_mem_region(pci_resource_start(pdev, bar),
3856 					pci_resource_len(pdev, bar), res_name,
3857 					exclusive))
3858 			goto err_out;
3859 	}
3860 
3861 	dr = find_pci_dr(pdev);
3862 	if (dr)
3863 		dr->region_mask |= 1 << bar;
3864 
3865 	return 0;
3866 
3867 err_out:
3868 	pci_warn(pdev, "BAR %d: can't reserve %pR\n", bar,
3869 		 &pdev->resource[bar]);
3870 	return -EBUSY;
3871 }
3872 
3873 /**
3874  * pci_request_region - Reserve PCI I/O and memory resource
3875  * @pdev: PCI device whose resources are to be reserved
3876  * @bar: BAR to be reserved
3877  * @res_name: Name to be associated with resource
3878  *
3879  * Mark the PCI region associated with PCI device @pdev BAR @bar as
3880  * being reserved by owner @res_name.  Do not access any
3881  * address inside the PCI regions unless this call returns
3882  * successfully.
3883  *
3884  * Returns 0 on success, or %EBUSY on error.  A warning
3885  * message is also printed on failure.
3886  */
pci_request_region(struct pci_dev * pdev,int bar,const char * res_name)3887 int pci_request_region(struct pci_dev *pdev, int bar, const char *res_name)
3888 {
3889 	return __pci_request_region(pdev, bar, res_name, 0);
3890 }
3891 EXPORT_SYMBOL(pci_request_region);
3892 
3893 /**
3894  * pci_release_selected_regions - Release selected PCI I/O and memory resources
3895  * @pdev: PCI device whose resources were previously reserved
3896  * @bars: Bitmask of BARs to be released
3897  *
3898  * Release selected PCI I/O and memory resources previously reserved.
3899  * Call this function only after all use of the PCI regions has ceased.
3900  */
pci_release_selected_regions(struct pci_dev * pdev,int bars)3901 void pci_release_selected_regions(struct pci_dev *pdev, int bars)
3902 {
3903 	int i;
3904 
3905 	for (i = 0; i < PCI_STD_NUM_BARS; i++)
3906 		if (bars & (1 << i))
3907 			pci_release_region(pdev, i);
3908 }
3909 EXPORT_SYMBOL(pci_release_selected_regions);
3910 
__pci_request_selected_regions(struct pci_dev * pdev,int bars,const char * res_name,int excl)3911 static int __pci_request_selected_regions(struct pci_dev *pdev, int bars,
3912 					  const char *res_name, int excl)
3913 {
3914 	int i;
3915 
3916 	for (i = 0; i < PCI_STD_NUM_BARS; i++)
3917 		if (bars & (1 << i))
3918 			if (__pci_request_region(pdev, i, res_name, excl))
3919 				goto err_out;
3920 	return 0;
3921 
3922 err_out:
3923 	while (--i >= 0)
3924 		if (bars & (1 << i))
3925 			pci_release_region(pdev, i);
3926 
3927 	return -EBUSY;
3928 }
3929 
3930 
3931 /**
3932  * pci_request_selected_regions - Reserve selected PCI I/O and memory resources
3933  * @pdev: PCI device whose resources are to be reserved
3934  * @bars: Bitmask of BARs to be requested
3935  * @res_name: Name to be associated with resource
3936  */
pci_request_selected_regions(struct pci_dev * pdev,int bars,const char * res_name)3937 int pci_request_selected_regions(struct pci_dev *pdev, int bars,
3938 				 const char *res_name)
3939 {
3940 	return __pci_request_selected_regions(pdev, bars, res_name, 0);
3941 }
3942 EXPORT_SYMBOL(pci_request_selected_regions);
3943 
pci_request_selected_regions_exclusive(struct pci_dev * pdev,int bars,const char * res_name)3944 int pci_request_selected_regions_exclusive(struct pci_dev *pdev, int bars,
3945 					   const char *res_name)
3946 {
3947 	return __pci_request_selected_regions(pdev, bars, res_name,
3948 			IORESOURCE_EXCLUSIVE);
3949 }
3950 EXPORT_SYMBOL(pci_request_selected_regions_exclusive);
3951 
3952 /**
3953  * pci_release_regions - Release reserved PCI I/O and memory resources
3954  * @pdev: PCI device whose resources were previously reserved by
3955  *	  pci_request_regions()
3956  *
3957  * Releases all PCI I/O and memory resources previously reserved by a
3958  * successful call to pci_request_regions().  Call this function only
3959  * after all use of the PCI regions has ceased.
3960  */
3961 
pci_release_regions(struct pci_dev * pdev)3962 void pci_release_regions(struct pci_dev *pdev)
3963 {
3964 	pci_release_selected_regions(pdev, (1 << PCI_STD_NUM_BARS) - 1);
3965 }
3966 EXPORT_SYMBOL(pci_release_regions);
3967 
3968 /**
3969  * pci_request_regions - Reserve PCI I/O and memory resources
3970  * @pdev: PCI device whose resources are to be reserved
3971  * @res_name: Name to be associated with resource.
3972  *
3973  * Mark all PCI regions associated with PCI device @pdev as
3974  * being reserved by owner @res_name.  Do not access any
3975  * address inside the PCI regions unless this call returns
3976  * successfully.
3977  *
3978  * Returns 0 on success, or %EBUSY on error.  A warning
3979  * message is also printed on failure.
3980  */
pci_request_regions(struct pci_dev * pdev,const char * res_name)3981 int pci_request_regions(struct pci_dev *pdev, const char *res_name)
3982 {
3983 	return pci_request_selected_regions(pdev,
3984 			((1 << PCI_STD_NUM_BARS) - 1), res_name);
3985 }
3986 EXPORT_SYMBOL(pci_request_regions);
3987 
3988 /**
3989  * pci_request_regions_exclusive - Reserve PCI I/O and memory resources
3990  * @pdev: PCI device whose resources are to be reserved
3991  * @res_name: Name to be associated with resource.
3992  *
3993  * Mark all PCI regions associated with PCI device @pdev as being reserved
3994  * by owner @res_name.  Do not access any address inside the PCI regions
3995  * unless this call returns successfully.
3996  *
3997  * pci_request_regions_exclusive() will mark the region so that /dev/mem
3998  * and the sysfs MMIO access will not be allowed.
3999  *
4000  * Returns 0 on success, or %EBUSY on error.  A warning message is also
4001  * printed on failure.
4002  */
pci_request_regions_exclusive(struct pci_dev * pdev,const char * res_name)4003 int pci_request_regions_exclusive(struct pci_dev *pdev, const char *res_name)
4004 {
4005 	return pci_request_selected_regions_exclusive(pdev,
4006 				((1 << PCI_STD_NUM_BARS) - 1), res_name);
4007 }
4008 EXPORT_SYMBOL(pci_request_regions_exclusive);
4009 
4010 /*
4011  * Record the PCI IO range (expressed as CPU physical address + size).
4012  * Return a negative value if an error has occurred, zero otherwise
4013  */
pci_register_io_range(struct fwnode_handle * fwnode,phys_addr_t addr,resource_size_t size)4014 int pci_register_io_range(struct fwnode_handle *fwnode, phys_addr_t addr,
4015 			resource_size_t	size)
4016 {
4017 	int ret = 0;
4018 #ifdef PCI_IOBASE
4019 	struct logic_pio_hwaddr *range;
4020 
4021 	if (!size || addr + size < addr)
4022 		return -EINVAL;
4023 
4024 	range = kzalloc(sizeof(*range), GFP_ATOMIC);
4025 	if (!range)
4026 		return -ENOMEM;
4027 
4028 	range->fwnode = fwnode;
4029 	range->size = size;
4030 	range->hw_start = addr;
4031 	range->flags = LOGIC_PIO_CPU_MMIO;
4032 
4033 	ret = logic_pio_register_range(range);
4034 	if (ret)
4035 		kfree(range);
4036 
4037 	/* Ignore duplicates due to deferred probing */
4038 	if (ret == -EEXIST)
4039 		ret = 0;
4040 #endif
4041 
4042 	return ret;
4043 }
4044 
pci_pio_to_address(unsigned long pio)4045 phys_addr_t pci_pio_to_address(unsigned long pio)
4046 {
4047 	phys_addr_t address = (phys_addr_t)OF_BAD_ADDR;
4048 
4049 #ifdef PCI_IOBASE
4050 	if (pio >= MMIO_UPPER_LIMIT)
4051 		return address;
4052 
4053 	address = logic_pio_to_hwaddr(pio);
4054 #endif
4055 
4056 	return address;
4057 }
4058 EXPORT_SYMBOL_GPL(pci_pio_to_address);
4059 
pci_address_to_pio(phys_addr_t address)4060 unsigned long __weak pci_address_to_pio(phys_addr_t address)
4061 {
4062 #ifdef PCI_IOBASE
4063 	return logic_pio_trans_cpuaddr(address);
4064 #else
4065 	if (address > IO_SPACE_LIMIT)
4066 		return (unsigned long)-1;
4067 
4068 	return (unsigned long) address;
4069 #endif
4070 }
4071 
4072 /**
4073  * pci_remap_iospace - Remap the memory mapped I/O space
4074  * @res: Resource describing the I/O space
4075  * @phys_addr: physical address of range to be mapped
4076  *
4077  * Remap the memory mapped I/O space described by the @res and the CPU
4078  * physical address @phys_addr into virtual address space.  Only
4079  * architectures that have memory mapped IO functions defined (and the
4080  * PCI_IOBASE value defined) should call this function.
4081  */
pci_remap_iospace(const struct resource * res,phys_addr_t phys_addr)4082 int pci_remap_iospace(const struct resource *res, phys_addr_t phys_addr)
4083 {
4084 #if defined(PCI_IOBASE) && defined(CONFIG_MMU)
4085 	unsigned long vaddr = (unsigned long)PCI_IOBASE + res->start;
4086 
4087 	if (!(res->flags & IORESOURCE_IO))
4088 		return -EINVAL;
4089 
4090 	if (res->end > IO_SPACE_LIMIT)
4091 		return -EINVAL;
4092 
4093 	return ioremap_page_range(vaddr, vaddr + resource_size(res), phys_addr,
4094 				  pgprot_device(PAGE_KERNEL));
4095 #else
4096 	/*
4097 	 * This architecture does not have memory mapped I/O space,
4098 	 * so this function should never be called
4099 	 */
4100 	WARN_ONCE(1, "This architecture does not support memory mapped I/O\n");
4101 	return -ENODEV;
4102 #endif
4103 }
4104 EXPORT_SYMBOL(pci_remap_iospace);
4105 
4106 /**
4107  * pci_unmap_iospace - Unmap the memory mapped I/O space
4108  * @res: resource to be unmapped
4109  *
4110  * Unmap the CPU virtual address @res from virtual address space.  Only
4111  * architectures that have memory mapped IO functions defined (and the
4112  * PCI_IOBASE value defined) should call this function.
4113  */
pci_unmap_iospace(struct resource * res)4114 void pci_unmap_iospace(struct resource *res)
4115 {
4116 #if defined(PCI_IOBASE) && defined(CONFIG_MMU)
4117 	unsigned long vaddr = (unsigned long)PCI_IOBASE + res->start;
4118 
4119 	unmap_kernel_range(vaddr, resource_size(res));
4120 #endif
4121 }
4122 EXPORT_SYMBOL(pci_unmap_iospace);
4123 
devm_pci_unmap_iospace(struct device * dev,void * ptr)4124 static void devm_pci_unmap_iospace(struct device *dev, void *ptr)
4125 {
4126 	struct resource **res = ptr;
4127 
4128 	pci_unmap_iospace(*res);
4129 }
4130 
4131 /**
4132  * devm_pci_remap_iospace - Managed pci_remap_iospace()
4133  * @dev: Generic device to remap IO address for
4134  * @res: Resource describing the I/O space
4135  * @phys_addr: physical address of range to be mapped
4136  *
4137  * Managed pci_remap_iospace().  Map is automatically unmapped on driver
4138  * detach.
4139  */
devm_pci_remap_iospace(struct device * dev,const struct resource * res,phys_addr_t phys_addr)4140 int devm_pci_remap_iospace(struct device *dev, const struct resource *res,
4141 			   phys_addr_t phys_addr)
4142 {
4143 	const struct resource **ptr;
4144 	int error;
4145 
4146 	ptr = devres_alloc(devm_pci_unmap_iospace, sizeof(*ptr), GFP_KERNEL);
4147 	if (!ptr)
4148 		return -ENOMEM;
4149 
4150 	error = pci_remap_iospace(res, phys_addr);
4151 	if (error) {
4152 		devres_free(ptr);
4153 	} else	{
4154 		*ptr = res;
4155 		devres_add(dev, ptr);
4156 	}
4157 
4158 	return error;
4159 }
4160 EXPORT_SYMBOL(devm_pci_remap_iospace);
4161 
4162 /**
4163  * devm_pci_remap_cfgspace - Managed pci_remap_cfgspace()
4164  * @dev: Generic device to remap IO address for
4165  * @offset: Resource address to map
4166  * @size: Size of map
4167  *
4168  * Managed pci_remap_cfgspace().  Map is automatically unmapped on driver
4169  * detach.
4170  */
devm_pci_remap_cfgspace(struct device * dev,resource_size_t offset,resource_size_t size)4171 void __iomem *devm_pci_remap_cfgspace(struct device *dev,
4172 				      resource_size_t offset,
4173 				      resource_size_t size)
4174 {
4175 	void __iomem **ptr, *addr;
4176 
4177 	ptr = devres_alloc(devm_ioremap_release, sizeof(*ptr), GFP_KERNEL);
4178 	if (!ptr)
4179 		return NULL;
4180 
4181 	addr = pci_remap_cfgspace(offset, size);
4182 	if (addr) {
4183 		*ptr = addr;
4184 		devres_add(dev, ptr);
4185 	} else
4186 		devres_free(ptr);
4187 
4188 	return addr;
4189 }
4190 EXPORT_SYMBOL(devm_pci_remap_cfgspace);
4191 
4192 /**
4193  * devm_pci_remap_cfg_resource - check, request region and ioremap cfg resource
4194  * @dev: generic device to handle the resource for
4195  * @res: configuration space resource to be handled
4196  *
4197  * Checks that a resource is a valid memory region, requests the memory
4198  * region and ioremaps with pci_remap_cfgspace() API that ensures the
4199  * proper PCI configuration space memory attributes are guaranteed.
4200  *
4201  * All operations are managed and will be undone on driver detach.
4202  *
4203  * Returns a pointer to the remapped memory or an ERR_PTR() encoded error code
4204  * on failure. Usage example::
4205  *
4206  *	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
4207  *	base = devm_pci_remap_cfg_resource(&pdev->dev, res);
4208  *	if (IS_ERR(base))
4209  *		return PTR_ERR(base);
4210  */
devm_pci_remap_cfg_resource(struct device * dev,struct resource * res)4211 void __iomem *devm_pci_remap_cfg_resource(struct device *dev,
4212 					  struct resource *res)
4213 {
4214 	resource_size_t size;
4215 	const char *name;
4216 	void __iomem *dest_ptr;
4217 
4218 	BUG_ON(!dev);
4219 
4220 	if (!res || resource_type(res) != IORESOURCE_MEM) {
4221 		dev_err(dev, "invalid resource\n");
4222 		return IOMEM_ERR_PTR(-EINVAL);
4223 	}
4224 
4225 	size = resource_size(res);
4226 	name = res->name ?: dev_name(dev);
4227 
4228 	if (!devm_request_mem_region(dev, res->start, size, name)) {
4229 		dev_err(dev, "can't request region for resource %pR\n", res);
4230 		return IOMEM_ERR_PTR(-EBUSY);
4231 	}
4232 
4233 	dest_ptr = devm_pci_remap_cfgspace(dev, res->start, size);
4234 	if (!dest_ptr) {
4235 		dev_err(dev, "ioremap failed for resource %pR\n", res);
4236 		devm_release_mem_region(dev, res->start, size);
4237 		dest_ptr = IOMEM_ERR_PTR(-ENOMEM);
4238 	}
4239 
4240 	return dest_ptr;
4241 }
4242 EXPORT_SYMBOL(devm_pci_remap_cfg_resource);
4243 
__pci_set_master(struct pci_dev * dev,bool enable)4244 static void __pci_set_master(struct pci_dev *dev, bool enable)
4245 {
4246 	u16 old_cmd, cmd;
4247 
4248 	pci_read_config_word(dev, PCI_COMMAND, &old_cmd);
4249 	if (enable)
4250 		cmd = old_cmd | PCI_COMMAND_MASTER;
4251 	else
4252 		cmd = old_cmd & ~PCI_COMMAND_MASTER;
4253 	if (cmd != old_cmd) {
4254 		pci_dbg(dev, "%s bus mastering\n",
4255 			enable ? "enabling" : "disabling");
4256 		pci_write_config_word(dev, PCI_COMMAND, cmd);
4257 	}
4258 	dev->is_busmaster = enable;
4259 }
4260 
4261 /**
4262  * pcibios_setup - process "pci=" kernel boot arguments
4263  * @str: string used to pass in "pci=" kernel boot arguments
4264  *
4265  * Process kernel boot arguments.  This is the default implementation.
4266  * Architecture specific implementations can override this as necessary.
4267  */
pcibios_setup(char * str)4268 char * __weak __init pcibios_setup(char *str)
4269 {
4270 	return str;
4271 }
4272 
4273 /**
4274  * pcibios_set_master - enable PCI bus-mastering for device dev
4275  * @dev: the PCI device to enable
4276  *
4277  * Enables PCI bus-mastering for the device.  This is the default
4278  * implementation.  Architecture specific implementations can override
4279  * this if necessary.
4280  */
pcibios_set_master(struct pci_dev * dev)4281 void __weak pcibios_set_master(struct pci_dev *dev)
4282 {
4283 	u8 lat;
4284 
4285 	/* The latency timer doesn't apply to PCIe (either Type 0 or Type 1) */
4286 	if (pci_is_pcie(dev))
4287 		return;
4288 
4289 	pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
4290 	if (lat < 16)
4291 		lat = (64 <= pcibios_max_latency) ? 64 : pcibios_max_latency;
4292 	else if (lat > pcibios_max_latency)
4293 		lat = pcibios_max_latency;
4294 	else
4295 		return;
4296 
4297 	pci_write_config_byte(dev, PCI_LATENCY_TIMER, lat);
4298 }
4299 
4300 /**
4301  * pci_set_master - enables bus-mastering for device dev
4302  * @dev: the PCI device to enable
4303  *
4304  * Enables bus-mastering on the device and calls pcibios_set_master()
4305  * to do the needed arch specific settings.
4306  */
pci_set_master(struct pci_dev * dev)4307 void pci_set_master(struct pci_dev *dev)
4308 {
4309 	__pci_set_master(dev, true);
4310 	pcibios_set_master(dev);
4311 }
4312 EXPORT_SYMBOL(pci_set_master);
4313 
4314 /**
4315  * pci_clear_master - disables bus-mastering for device dev
4316  * @dev: the PCI device to disable
4317  */
pci_clear_master(struct pci_dev * dev)4318 void pci_clear_master(struct pci_dev *dev)
4319 {
4320 	__pci_set_master(dev, false);
4321 }
4322 EXPORT_SYMBOL(pci_clear_master);
4323 
4324 /**
4325  * pci_set_cacheline_size - ensure the CACHE_LINE_SIZE register is programmed
4326  * @dev: the PCI device for which MWI is to be enabled
4327  *
4328  * Helper function for pci_set_mwi.
4329  * Originally copied from drivers/net/acenic.c.
4330  * Copyright 1998-2001 by Jes Sorensen, <jes@trained-monkey.org>.
4331  *
4332  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4333  */
pci_set_cacheline_size(struct pci_dev * dev)4334 int pci_set_cacheline_size(struct pci_dev *dev)
4335 {
4336 	u8 cacheline_size;
4337 
4338 	if (!pci_cache_line_size)
4339 		return -EINVAL;
4340 
4341 	/* Validate current setting: the PCI_CACHE_LINE_SIZE must be
4342 	   equal to or multiple of the right value. */
4343 	pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
4344 	if (cacheline_size >= pci_cache_line_size &&
4345 	    (cacheline_size % pci_cache_line_size) == 0)
4346 		return 0;
4347 
4348 	/* Write the correct value. */
4349 	pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, pci_cache_line_size);
4350 	/* Read it back. */
4351 	pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
4352 	if (cacheline_size == pci_cache_line_size)
4353 		return 0;
4354 
4355 	pci_info(dev, "cache line size of %d is not supported\n",
4356 		   pci_cache_line_size << 2);
4357 
4358 	return -EINVAL;
4359 }
4360 EXPORT_SYMBOL_GPL(pci_set_cacheline_size);
4361 
4362 /**
4363  * pci_set_mwi - enables memory-write-invalidate PCI transaction
4364  * @dev: the PCI device for which MWI is enabled
4365  *
4366  * Enables the Memory-Write-Invalidate transaction in %PCI_COMMAND.
4367  *
4368  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4369  */
pci_set_mwi(struct pci_dev * dev)4370 int pci_set_mwi(struct pci_dev *dev)
4371 {
4372 #ifdef PCI_DISABLE_MWI
4373 	return 0;
4374 #else
4375 	int rc;
4376 	u16 cmd;
4377 
4378 	rc = pci_set_cacheline_size(dev);
4379 	if (rc)
4380 		return rc;
4381 
4382 	pci_read_config_word(dev, PCI_COMMAND, &cmd);
4383 	if (!(cmd & PCI_COMMAND_INVALIDATE)) {
4384 		pci_dbg(dev, "enabling Mem-Wr-Inval\n");
4385 		cmd |= PCI_COMMAND_INVALIDATE;
4386 		pci_write_config_word(dev, PCI_COMMAND, cmd);
4387 	}
4388 	return 0;
4389 #endif
4390 }
4391 EXPORT_SYMBOL(pci_set_mwi);
4392 
4393 /**
4394  * pcim_set_mwi - a device-managed pci_set_mwi()
4395  * @dev: the PCI device for which MWI is enabled
4396  *
4397  * Managed pci_set_mwi().
4398  *
4399  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4400  */
pcim_set_mwi(struct pci_dev * dev)4401 int pcim_set_mwi(struct pci_dev *dev)
4402 {
4403 	struct pci_devres *dr;
4404 
4405 	dr = find_pci_dr(dev);
4406 	if (!dr)
4407 		return -ENOMEM;
4408 
4409 	dr->mwi = 1;
4410 	return pci_set_mwi(dev);
4411 }
4412 EXPORT_SYMBOL(pcim_set_mwi);
4413 
4414 /**
4415  * pci_try_set_mwi - enables memory-write-invalidate PCI transaction
4416  * @dev: the PCI device for which MWI is enabled
4417  *
4418  * Enables the Memory-Write-Invalidate transaction in %PCI_COMMAND.
4419  * Callers are not required to check the return value.
4420  *
4421  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4422  */
pci_try_set_mwi(struct pci_dev * dev)4423 int pci_try_set_mwi(struct pci_dev *dev)
4424 {
4425 #ifdef PCI_DISABLE_MWI
4426 	return 0;
4427 #else
4428 	return pci_set_mwi(dev);
4429 #endif
4430 }
4431 EXPORT_SYMBOL(pci_try_set_mwi);
4432 
4433 /**
4434  * pci_clear_mwi - disables Memory-Write-Invalidate for device dev
4435  * @dev: the PCI device to disable
4436  *
4437  * Disables PCI Memory-Write-Invalidate transaction on the device
4438  */
pci_clear_mwi(struct pci_dev * dev)4439 void pci_clear_mwi(struct pci_dev *dev)
4440 {
4441 #ifndef PCI_DISABLE_MWI
4442 	u16 cmd;
4443 
4444 	pci_read_config_word(dev, PCI_COMMAND, &cmd);
4445 	if (cmd & PCI_COMMAND_INVALIDATE) {
4446 		cmd &= ~PCI_COMMAND_INVALIDATE;
4447 		pci_write_config_word(dev, PCI_COMMAND, cmd);
4448 	}
4449 #endif
4450 }
4451 EXPORT_SYMBOL(pci_clear_mwi);
4452 
4453 /**
4454  * pci_intx - enables/disables PCI INTx for device dev
4455  * @pdev: the PCI device to operate on
4456  * @enable: boolean: whether to enable or disable PCI INTx
4457  *
4458  * Enables/disables PCI INTx for device @pdev
4459  */
pci_intx(struct pci_dev * pdev,int enable)4460 void pci_intx(struct pci_dev *pdev, int enable)
4461 {
4462 	u16 pci_command, new;
4463 
4464 	pci_read_config_word(pdev, PCI_COMMAND, &pci_command);
4465 
4466 	if (enable)
4467 		new = pci_command & ~PCI_COMMAND_INTX_DISABLE;
4468 	else
4469 		new = pci_command | PCI_COMMAND_INTX_DISABLE;
4470 
4471 	if (new != pci_command) {
4472 		struct pci_devres *dr;
4473 
4474 		pci_write_config_word(pdev, PCI_COMMAND, new);
4475 
4476 		dr = find_pci_dr(pdev);
4477 		if (dr && !dr->restore_intx) {
4478 			dr->restore_intx = 1;
4479 			dr->orig_intx = !enable;
4480 		}
4481 	}
4482 }
4483 EXPORT_SYMBOL_GPL(pci_intx);
4484 
pci_check_and_set_intx_mask(struct pci_dev * dev,bool mask)4485 static bool pci_check_and_set_intx_mask(struct pci_dev *dev, bool mask)
4486 {
4487 	struct pci_bus *bus = dev->bus;
4488 	bool mask_updated = true;
4489 	u32 cmd_status_dword;
4490 	u16 origcmd, newcmd;
4491 	unsigned long flags;
4492 	bool irq_pending;
4493 
4494 	/*
4495 	 * We do a single dword read to retrieve both command and status.
4496 	 * Document assumptions that make this possible.
4497 	 */
4498 	BUILD_BUG_ON(PCI_COMMAND % 4);
4499 	BUILD_BUG_ON(PCI_COMMAND + 2 != PCI_STATUS);
4500 
4501 	raw_spin_lock_irqsave(&pci_lock, flags);
4502 
4503 	bus->ops->read(bus, dev->devfn, PCI_COMMAND, 4, &cmd_status_dword);
4504 
4505 	irq_pending = (cmd_status_dword >> 16) & PCI_STATUS_INTERRUPT;
4506 
4507 	/*
4508 	 * Check interrupt status register to see whether our device
4509 	 * triggered the interrupt (when masking) or the next IRQ is
4510 	 * already pending (when unmasking).
4511 	 */
4512 	if (mask != irq_pending) {
4513 		mask_updated = false;
4514 		goto done;
4515 	}
4516 
4517 	origcmd = cmd_status_dword;
4518 	newcmd = origcmd & ~PCI_COMMAND_INTX_DISABLE;
4519 	if (mask)
4520 		newcmd |= PCI_COMMAND_INTX_DISABLE;
4521 	if (newcmd != origcmd)
4522 		bus->ops->write(bus, dev->devfn, PCI_COMMAND, 2, newcmd);
4523 
4524 done:
4525 	raw_spin_unlock_irqrestore(&pci_lock, flags);
4526 
4527 	return mask_updated;
4528 }
4529 
4530 /**
4531  * pci_check_and_mask_intx - mask INTx on pending interrupt
4532  * @dev: the PCI device to operate on
4533  *
4534  * Check if the device dev has its INTx line asserted, mask it and return
4535  * true in that case. False is returned if no interrupt was pending.
4536  */
pci_check_and_mask_intx(struct pci_dev * dev)4537 bool pci_check_and_mask_intx(struct pci_dev *dev)
4538 {
4539 	return pci_check_and_set_intx_mask(dev, true);
4540 }
4541 EXPORT_SYMBOL_GPL(pci_check_and_mask_intx);
4542 
4543 /**
4544  * pci_check_and_unmask_intx - unmask INTx if no interrupt is pending
4545  * @dev: the PCI device to operate on
4546  *
4547  * Check if the device dev has its INTx line asserted, unmask it if not and
4548  * return true. False is returned and the mask remains active if there was
4549  * still an interrupt pending.
4550  */
pci_check_and_unmask_intx(struct pci_dev * dev)4551 bool pci_check_and_unmask_intx(struct pci_dev *dev)
4552 {
4553 	return pci_check_and_set_intx_mask(dev, false);
4554 }
4555 EXPORT_SYMBOL_GPL(pci_check_and_unmask_intx);
4556 
4557 /**
4558  * pci_wait_for_pending_transaction - wait for pending transaction
4559  * @dev: the PCI device to operate on
4560  *
4561  * Return 0 if transaction is pending 1 otherwise.
4562  */
pci_wait_for_pending_transaction(struct pci_dev * dev)4563 int pci_wait_for_pending_transaction(struct pci_dev *dev)
4564 {
4565 	if (!pci_is_pcie(dev))
4566 		return 1;
4567 
4568 	return pci_wait_for_pending(dev, pci_pcie_cap(dev) + PCI_EXP_DEVSTA,
4569 				    PCI_EXP_DEVSTA_TRPND);
4570 }
4571 EXPORT_SYMBOL(pci_wait_for_pending_transaction);
4572 
4573 /**
4574  * pcie_has_flr - check if a device supports function level resets
4575  * @dev: device to check
4576  *
4577  * Returns true if the device advertises support for PCIe function level
4578  * resets.
4579  */
pcie_has_flr(struct pci_dev * dev)4580 bool pcie_has_flr(struct pci_dev *dev)
4581 {
4582 	u32 cap;
4583 
4584 	if (dev->dev_flags & PCI_DEV_FLAGS_NO_FLR_RESET)
4585 		return false;
4586 
4587 	pcie_capability_read_dword(dev, PCI_EXP_DEVCAP, &cap);
4588 	return cap & PCI_EXP_DEVCAP_FLR;
4589 }
4590 EXPORT_SYMBOL_GPL(pcie_has_flr);
4591 
4592 /**
4593  * pcie_flr - initiate a PCIe function level reset
4594  * @dev: device to reset
4595  *
4596  * Initiate a function level reset on @dev.  The caller should ensure the
4597  * device supports FLR before calling this function, e.g. by using the
4598  * pcie_has_flr() helper.
4599  */
pcie_flr(struct pci_dev * dev)4600 int pcie_flr(struct pci_dev *dev)
4601 {
4602 	if (!pci_wait_for_pending_transaction(dev))
4603 		pci_err(dev, "timed out waiting for pending transaction; performing function level reset anyway\n");
4604 
4605 	pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_BCR_FLR);
4606 
4607 	if (dev->imm_ready)
4608 		return 0;
4609 
4610 	/*
4611 	 * Per PCIe r4.0, sec 6.6.2, a device must complete an FLR within
4612 	 * 100ms, but may silently discard requests while the FLR is in
4613 	 * progress.  Wait 100ms before trying to access the device.
4614 	 */
4615 	msleep(100);
4616 
4617 	return pci_dev_wait(dev, "FLR", PCIE_RESET_READY_POLL_MS);
4618 }
4619 EXPORT_SYMBOL_GPL(pcie_flr);
4620 
pci_af_flr(struct pci_dev * dev,int probe)4621 static int pci_af_flr(struct pci_dev *dev, int probe)
4622 {
4623 	int pos;
4624 	u8 cap;
4625 
4626 	pos = pci_find_capability(dev, PCI_CAP_ID_AF);
4627 	if (!pos)
4628 		return -ENOTTY;
4629 
4630 	if (dev->dev_flags & PCI_DEV_FLAGS_NO_FLR_RESET)
4631 		return -ENOTTY;
4632 
4633 	pci_read_config_byte(dev, pos + PCI_AF_CAP, &cap);
4634 	if (!(cap & PCI_AF_CAP_TP) || !(cap & PCI_AF_CAP_FLR))
4635 		return -ENOTTY;
4636 
4637 	if (probe)
4638 		return 0;
4639 
4640 	/*
4641 	 * Wait for Transaction Pending bit to clear.  A word-aligned test
4642 	 * is used, so we use the control offset rather than status and shift
4643 	 * the test bit to match.
4644 	 */
4645 	if (!pci_wait_for_pending(dev, pos + PCI_AF_CTRL,
4646 				 PCI_AF_STATUS_TP << 8))
4647 		pci_err(dev, "timed out waiting for pending transaction; performing AF function level reset anyway\n");
4648 
4649 	pci_write_config_byte(dev, pos + PCI_AF_CTRL, PCI_AF_CTRL_FLR);
4650 
4651 	if (dev->imm_ready)
4652 		return 0;
4653 
4654 	/*
4655 	 * Per Advanced Capabilities for Conventional PCI ECN, 13 April 2006,
4656 	 * updated 27 July 2006; a device must complete an FLR within
4657 	 * 100ms, but may silently discard requests while the FLR is in
4658 	 * progress.  Wait 100ms before trying to access the device.
4659 	 */
4660 	msleep(100);
4661 
4662 	return pci_dev_wait(dev, "AF_FLR", PCIE_RESET_READY_POLL_MS);
4663 }
4664 
4665 /**
4666  * pci_pm_reset - Put device into PCI_D3 and back into PCI_D0.
4667  * @dev: Device to reset.
4668  * @probe: If set, only check if the device can be reset this way.
4669  *
4670  * If @dev supports native PCI PM and its PCI_PM_CTRL_NO_SOFT_RESET flag is
4671  * unset, it will be reinitialized internally when going from PCI_D3hot to
4672  * PCI_D0.  If that's the case and the device is not in a low-power state
4673  * already, force it into PCI_D3hot and back to PCI_D0, causing it to be reset.
4674  *
4675  * NOTE: This causes the caller to sleep for twice the device power transition
4676  * cooldown period, which for the D0->D3hot and D3hot->D0 transitions is 10 ms
4677  * by default (i.e. unless the @dev's d3hot_delay field has a different value).
4678  * Moreover, only devices in D0 can be reset by this function.
4679  */
pci_pm_reset(struct pci_dev * dev,int probe)4680 static int pci_pm_reset(struct pci_dev *dev, int probe)
4681 {
4682 	u16 csr;
4683 
4684 	if (!dev->pm_cap || dev->dev_flags & PCI_DEV_FLAGS_NO_PM_RESET)
4685 		return -ENOTTY;
4686 
4687 	pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &csr);
4688 	if (csr & PCI_PM_CTRL_NO_SOFT_RESET)
4689 		return -ENOTTY;
4690 
4691 	if (probe)
4692 		return 0;
4693 
4694 	if (dev->current_state != PCI_D0)
4695 		return -EINVAL;
4696 
4697 	csr &= ~PCI_PM_CTRL_STATE_MASK;
4698 	csr |= PCI_D3hot;
4699 	pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, csr);
4700 	pci_dev_d3_sleep(dev);
4701 
4702 	csr &= ~PCI_PM_CTRL_STATE_MASK;
4703 	csr |= PCI_D0;
4704 	pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, csr);
4705 	pci_dev_d3_sleep(dev);
4706 
4707 	return pci_dev_wait(dev, "PM D3hot->D0", PCIE_RESET_READY_POLL_MS);
4708 }
4709 
4710 /**
4711  * pcie_wait_for_link_delay - Wait until link is active or inactive
4712  * @pdev: Bridge device
4713  * @active: waiting for active or inactive?
4714  * @delay: Delay to wait after link has become active (in ms)
4715  *
4716  * Use this to wait till link becomes active or inactive.
4717  */
pcie_wait_for_link_delay(struct pci_dev * pdev,bool active,int delay)4718 static bool pcie_wait_for_link_delay(struct pci_dev *pdev, bool active,
4719 				     int delay)
4720 {
4721 	int timeout = 1000;
4722 	bool ret;
4723 	u16 lnk_status;
4724 
4725 	/*
4726 	 * Some controllers might not implement link active reporting. In this
4727 	 * case, we wait for 1000 ms + any delay requested by the caller.
4728 	 */
4729 	if (!pdev->link_active_reporting) {
4730 		msleep(timeout + delay);
4731 		return true;
4732 	}
4733 
4734 	/*
4735 	 * PCIe r4.0 sec 6.6.1, a component must enter LTSSM Detect within 20ms,
4736 	 * after which we should expect an link active if the reset was
4737 	 * successful. If so, software must wait a minimum 100ms before sending
4738 	 * configuration requests to devices downstream this port.
4739 	 *
4740 	 * If the link fails to activate, either the device was physically
4741 	 * removed or the link is permanently failed.
4742 	 */
4743 	if (active)
4744 		msleep(20);
4745 	for (;;) {
4746 		pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnk_status);
4747 		ret = !!(lnk_status & PCI_EXP_LNKSTA_DLLLA);
4748 		if (ret == active)
4749 			break;
4750 		if (timeout <= 0)
4751 			break;
4752 		msleep(10);
4753 		timeout -= 10;
4754 	}
4755 	if (active && ret)
4756 		msleep(delay);
4757 
4758 	return ret == active;
4759 }
4760 
4761 /**
4762  * pcie_wait_for_link - Wait until link is active or inactive
4763  * @pdev: Bridge device
4764  * @active: waiting for active or inactive?
4765  *
4766  * Use this to wait till link becomes active or inactive.
4767  */
pcie_wait_for_link(struct pci_dev * pdev,bool active)4768 bool pcie_wait_for_link(struct pci_dev *pdev, bool active)
4769 {
4770 	return pcie_wait_for_link_delay(pdev, active, 100);
4771 }
4772 
4773 /*
4774  * Find maximum D3cold delay required by all the devices on the bus.  The
4775  * spec says 100 ms, but firmware can lower it and we allow drivers to
4776  * increase it as well.
4777  *
4778  * Called with @pci_bus_sem locked for reading.
4779  */
pci_bus_max_d3cold_delay(const struct pci_bus * bus)4780 static int pci_bus_max_d3cold_delay(const struct pci_bus *bus)
4781 {
4782 	const struct pci_dev *pdev;
4783 	int min_delay = 100;
4784 	int max_delay = 0;
4785 
4786 	list_for_each_entry(pdev, &bus->devices, bus_list) {
4787 		if (pdev->d3cold_delay < min_delay)
4788 			min_delay = pdev->d3cold_delay;
4789 		if (pdev->d3cold_delay > max_delay)
4790 			max_delay = pdev->d3cold_delay;
4791 	}
4792 
4793 	return max(min_delay, max_delay);
4794 }
4795 
4796 /**
4797  * pci_bridge_wait_for_secondary_bus - Wait for secondary bus to be accessible
4798  * @dev: PCI bridge
4799  * @reset_type: reset type in human-readable form
4800  * @timeout: maximum time to wait for devices on secondary bus (milliseconds)
4801  *
4802  * Handle necessary delays before access to the devices on the secondary
4803  * side of the bridge are permitted after D3cold to D0 transition
4804  * or Conventional Reset.
4805  *
4806  * For PCIe this means the delays in PCIe 5.0 section 6.6.1. For
4807  * conventional PCI it means Tpvrh + Trhfa specified in PCI 3.0 section
4808  * 4.3.2.
4809  *
4810  * Return 0 on success or -ENOTTY if the first device on the secondary bus
4811  * failed to become accessible.
4812  */
pci_bridge_wait_for_secondary_bus(struct pci_dev * dev,char * reset_type,int timeout)4813 int pci_bridge_wait_for_secondary_bus(struct pci_dev *dev, char *reset_type,
4814 				      int timeout)
4815 {
4816 	struct pci_dev *child;
4817 	int delay;
4818 
4819 	if (pci_dev_is_disconnected(dev))
4820 		return 0;
4821 
4822 	if (!pci_is_bridge(dev))
4823 		return 0;
4824 
4825 	down_read(&pci_bus_sem);
4826 
4827 	/*
4828 	 * We only deal with devices that are present currently on the bus.
4829 	 * For any hot-added devices the access delay is handled in pciehp
4830 	 * board_added(). In case of ACPI hotplug the firmware is expected
4831 	 * to configure the devices before OS is notified.
4832 	 */
4833 	if (!dev->subordinate || list_empty(&dev->subordinate->devices)) {
4834 		up_read(&pci_bus_sem);
4835 		return 0;
4836 	}
4837 
4838 	/* Take d3cold_delay requirements into account */
4839 	delay = pci_bus_max_d3cold_delay(dev->subordinate);
4840 	if (!delay) {
4841 		up_read(&pci_bus_sem);
4842 		return 0;
4843 	}
4844 
4845 	child = list_first_entry(&dev->subordinate->devices, struct pci_dev,
4846 				 bus_list);
4847 	up_read(&pci_bus_sem);
4848 
4849 	/*
4850 	 * Conventional PCI and PCI-X we need to wait Tpvrh + Trhfa before
4851 	 * accessing the device after reset (that is 1000 ms + 100 ms).
4852 	 */
4853 	if (!pci_is_pcie(dev)) {
4854 		pci_dbg(dev, "waiting %d ms for secondary bus\n", 1000 + delay);
4855 		msleep(1000 + delay);
4856 		return 0;
4857 	}
4858 
4859 	/*
4860 	 * For PCIe downstream and root ports that do not support speeds
4861 	 * greater than 5 GT/s need to wait minimum 100 ms. For higher
4862 	 * speeds (gen3) we need to wait first for the data link layer to
4863 	 * become active.
4864 	 *
4865 	 * However, 100 ms is the minimum and the PCIe spec says the
4866 	 * software must allow at least 1s before it can determine that the
4867 	 * device that did not respond is a broken device. There is
4868 	 * evidence that 100 ms is not always enough, for example certain
4869 	 * Titan Ridge xHCI controller does not always respond to
4870 	 * configuration requests if we only wait for 100 ms (see
4871 	 * https://bugzilla.kernel.org/show_bug.cgi?id=203885).
4872 	 *
4873 	 * Therefore we wait for 100 ms and check for the device presence
4874 	 * until the timeout expires.
4875 	 */
4876 	if (!pcie_downstream_port(dev))
4877 		return 0;
4878 
4879 	if (pcie_get_speed_cap(dev) <= PCIE_SPEED_5_0GT) {
4880 		pci_dbg(dev, "waiting %d ms for downstream link\n", delay);
4881 		msleep(delay);
4882 	} else {
4883 		pci_dbg(dev, "waiting %d ms for downstream link, after activation\n",
4884 			delay);
4885 		if (!pcie_wait_for_link_delay(dev, true, delay)) {
4886 			/* Did not train, no need to wait any further */
4887 			pci_info(dev, "Data Link Layer Link Active not set in 1000 msec\n");
4888 			return -ENOTTY;
4889 		}
4890 	}
4891 
4892 	return pci_dev_wait(child, reset_type, timeout - delay);
4893 }
4894 
pci_reset_secondary_bus(struct pci_dev * dev)4895 void pci_reset_secondary_bus(struct pci_dev *dev)
4896 {
4897 	u16 ctrl;
4898 
4899 	pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &ctrl);
4900 	ctrl |= PCI_BRIDGE_CTL_BUS_RESET;
4901 	pci_write_config_word(dev, PCI_BRIDGE_CONTROL, ctrl);
4902 
4903 	/*
4904 	 * PCI spec v3.0 7.6.4.2 requires minimum Trst of 1ms.  Double
4905 	 * this to 2ms to ensure that we meet the minimum requirement.
4906 	 */
4907 	msleep(2);
4908 
4909 	ctrl &= ~PCI_BRIDGE_CTL_BUS_RESET;
4910 	pci_write_config_word(dev, PCI_BRIDGE_CONTROL, ctrl);
4911 }
4912 
pcibios_reset_secondary_bus(struct pci_dev * dev)4913 void __weak pcibios_reset_secondary_bus(struct pci_dev *dev)
4914 {
4915 	pci_reset_secondary_bus(dev);
4916 }
4917 
4918 /**
4919  * pci_bridge_secondary_bus_reset - Reset the secondary bus on a PCI bridge.
4920  * @dev: Bridge device
4921  *
4922  * Use the bridge control register to assert reset on the secondary bus.
4923  * Devices on the secondary bus are left in power-on state.
4924  */
pci_bridge_secondary_bus_reset(struct pci_dev * dev)4925 int pci_bridge_secondary_bus_reset(struct pci_dev *dev)
4926 {
4927 	pcibios_reset_secondary_bus(dev);
4928 
4929 	return pci_bridge_wait_for_secondary_bus(dev, "bus reset",
4930 						 PCIE_RESET_READY_POLL_MS);
4931 }
4932 EXPORT_SYMBOL_GPL(pci_bridge_secondary_bus_reset);
4933 
pci_parent_bus_reset(struct pci_dev * dev,int probe)4934 static int pci_parent_bus_reset(struct pci_dev *dev, int probe)
4935 {
4936 	struct pci_dev *pdev;
4937 
4938 	if (pci_is_root_bus(dev->bus) || dev->subordinate ||
4939 	    !dev->bus->self || dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET)
4940 		return -ENOTTY;
4941 
4942 	list_for_each_entry(pdev, &dev->bus->devices, bus_list)
4943 		if (pdev != dev)
4944 			return -ENOTTY;
4945 
4946 	if (probe)
4947 		return 0;
4948 
4949 	return pci_bridge_secondary_bus_reset(dev->bus->self);
4950 }
4951 
pci_reset_hotplug_slot(struct hotplug_slot * hotplug,int probe)4952 static int pci_reset_hotplug_slot(struct hotplug_slot *hotplug, int probe)
4953 {
4954 	int rc = -ENOTTY;
4955 
4956 	if (!hotplug || !try_module_get(hotplug->owner))
4957 		return rc;
4958 
4959 	if (hotplug->ops->reset_slot)
4960 		rc = hotplug->ops->reset_slot(hotplug, probe);
4961 
4962 	module_put(hotplug->owner);
4963 
4964 	return rc;
4965 }
4966 
pci_dev_reset_slot_function(struct pci_dev * dev,int probe)4967 static int pci_dev_reset_slot_function(struct pci_dev *dev, int probe)
4968 {
4969 	if (dev->multifunction || dev->subordinate || !dev->slot ||
4970 	    dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET)
4971 		return -ENOTTY;
4972 
4973 	return pci_reset_hotplug_slot(dev->slot->hotplug, probe);
4974 }
4975 
pci_dev_lock(struct pci_dev * dev)4976 static void pci_dev_lock(struct pci_dev *dev)
4977 {
4978 	/* block PM suspend, driver probe, etc. */
4979 	device_lock(&dev->dev);
4980 	pci_cfg_access_lock(dev);
4981 }
4982 
4983 /* Return 1 on successful lock, 0 on contention */
pci_dev_trylock(struct pci_dev * dev)4984 static int pci_dev_trylock(struct pci_dev *dev)
4985 {
4986 	if (device_trylock(&dev->dev)) {
4987 		if (pci_cfg_access_trylock(dev))
4988 			return 1;
4989 		device_unlock(&dev->dev);
4990 	}
4991 
4992 	return 0;
4993 }
4994 
pci_dev_unlock(struct pci_dev * dev)4995 static void pci_dev_unlock(struct pci_dev *dev)
4996 {
4997 	pci_cfg_access_unlock(dev);
4998 	device_unlock(&dev->dev);
4999 }
5000 
pci_dev_save_and_disable(struct pci_dev * dev)5001 static void pci_dev_save_and_disable(struct pci_dev *dev)
5002 {
5003 	const struct pci_error_handlers *err_handler =
5004 			dev->driver ? dev->driver->err_handler : NULL;
5005 
5006 	/*
5007 	 * dev->driver->err_handler->reset_prepare() is protected against
5008 	 * races with ->remove() by the device lock, which must be held by
5009 	 * the caller.
5010 	 */
5011 	if (err_handler && err_handler->reset_prepare)
5012 		err_handler->reset_prepare(dev);
5013 
5014 	/*
5015 	 * Wake-up device prior to save.  PM registers default to D0 after
5016 	 * reset and a simple register restore doesn't reliably return
5017 	 * to a non-D0 state anyway.
5018 	 */
5019 	pci_set_power_state(dev, PCI_D0);
5020 
5021 	pci_save_state(dev);
5022 	/*
5023 	 * Disable the device by clearing the Command register, except for
5024 	 * INTx-disable which is set.  This not only disables MMIO and I/O port
5025 	 * BARs, but also prevents the device from being Bus Master, preventing
5026 	 * DMA from the device including MSI/MSI-X interrupts.  For PCI 2.3
5027 	 * compliant devices, INTx-disable prevents legacy interrupts.
5028 	 */
5029 	pci_write_config_word(dev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
5030 }
5031 
pci_dev_restore(struct pci_dev * dev)5032 static void pci_dev_restore(struct pci_dev *dev)
5033 {
5034 	const struct pci_error_handlers *err_handler =
5035 			dev->driver ? dev->driver->err_handler : NULL;
5036 
5037 	pci_restore_state(dev);
5038 
5039 	/*
5040 	 * dev->driver->err_handler->reset_done() is protected against
5041 	 * races with ->remove() by the device lock, which must be held by
5042 	 * the caller.
5043 	 */
5044 	if (err_handler && err_handler->reset_done)
5045 		err_handler->reset_done(dev);
5046 }
5047 
5048 /**
5049  * __pci_reset_function_locked - reset a PCI device function while holding
5050  * the @dev mutex lock.
5051  * @dev: PCI device to reset
5052  *
5053  * Some devices allow an individual function to be reset without affecting
5054  * other functions in the same device.  The PCI device must be responsive
5055  * to PCI config space in order to use this function.
5056  *
5057  * The device function is presumed to be unused and the caller is holding
5058  * the device mutex lock when this function is called.
5059  *
5060  * Resetting the device will make the contents of PCI configuration space
5061  * random, so any caller of this must be prepared to reinitialise the
5062  * device including MSI, bus mastering, BARs, decoding IO and memory spaces,
5063  * etc.
5064  *
5065  * Returns 0 if the device function was successfully reset or negative if the
5066  * device doesn't support resetting a single function.
5067  */
__pci_reset_function_locked(struct pci_dev * dev)5068 int __pci_reset_function_locked(struct pci_dev *dev)
5069 {
5070 	int rc;
5071 
5072 	might_sleep();
5073 
5074 	/*
5075 	 * A reset method returns -ENOTTY if it doesn't support this device
5076 	 * and we should try the next method.
5077 	 *
5078 	 * If it returns 0 (success), we're finished.  If it returns any
5079 	 * other error, we're also finished: this indicates that further
5080 	 * reset mechanisms might be broken on the device.
5081 	 */
5082 	rc = pci_dev_specific_reset(dev, 0);
5083 	if (rc != -ENOTTY)
5084 		return rc;
5085 	if (pcie_has_flr(dev)) {
5086 		rc = pcie_flr(dev);
5087 		if (rc != -ENOTTY)
5088 			return rc;
5089 	}
5090 	rc = pci_af_flr(dev, 0);
5091 	if (rc != -ENOTTY)
5092 		return rc;
5093 	rc = pci_pm_reset(dev, 0);
5094 	if (rc != -ENOTTY)
5095 		return rc;
5096 	rc = pci_dev_reset_slot_function(dev, 0);
5097 	if (rc != -ENOTTY)
5098 		return rc;
5099 	return pci_parent_bus_reset(dev, 0);
5100 }
5101 EXPORT_SYMBOL_GPL(__pci_reset_function_locked);
5102 
5103 /**
5104  * pci_probe_reset_function - check whether the device can be safely reset
5105  * @dev: PCI device to reset
5106  *
5107  * Some devices allow an individual function to be reset without affecting
5108  * other functions in the same device.  The PCI device must be responsive
5109  * to PCI config space in order to use this function.
5110  *
5111  * Returns 0 if the device function can be reset or negative if the
5112  * device doesn't support resetting a single function.
5113  */
pci_probe_reset_function(struct pci_dev * dev)5114 int pci_probe_reset_function(struct pci_dev *dev)
5115 {
5116 	int rc;
5117 
5118 	might_sleep();
5119 
5120 	rc = pci_dev_specific_reset(dev, 1);
5121 	if (rc != -ENOTTY)
5122 		return rc;
5123 	if (pcie_has_flr(dev))
5124 		return 0;
5125 	rc = pci_af_flr(dev, 1);
5126 	if (rc != -ENOTTY)
5127 		return rc;
5128 	rc = pci_pm_reset(dev, 1);
5129 	if (rc != -ENOTTY)
5130 		return rc;
5131 	rc = pci_dev_reset_slot_function(dev, 1);
5132 	if (rc != -ENOTTY)
5133 		return rc;
5134 
5135 	return pci_parent_bus_reset(dev, 1);
5136 }
5137 
5138 /**
5139  * pci_reset_function - quiesce and reset a PCI device function
5140  * @dev: PCI device to reset
5141  *
5142  * Some devices allow an individual function to be reset without affecting
5143  * other functions in the same device.  The PCI device must be responsive
5144  * to PCI config space in order to use this function.
5145  *
5146  * This function does not just reset the PCI portion of a device, but
5147  * clears all the state associated with the device.  This function differs
5148  * from __pci_reset_function_locked() in that it saves and restores device state
5149  * over the reset and takes the PCI device lock.
5150  *
5151  * Returns 0 if the device function was successfully reset or negative if the
5152  * device doesn't support resetting a single function.
5153  */
pci_reset_function(struct pci_dev * dev)5154 int pci_reset_function(struct pci_dev *dev)
5155 {
5156 	int rc;
5157 
5158 	if (!dev->reset_fn)
5159 		return -ENOTTY;
5160 
5161 	pci_dev_lock(dev);
5162 	pci_dev_save_and_disable(dev);
5163 
5164 	rc = __pci_reset_function_locked(dev);
5165 
5166 	pci_dev_restore(dev);
5167 	pci_dev_unlock(dev);
5168 
5169 	return rc;
5170 }
5171 EXPORT_SYMBOL_GPL(pci_reset_function);
5172 
5173 /**
5174  * pci_reset_function_locked - quiesce and reset a PCI device function
5175  * @dev: PCI device to reset
5176  *
5177  * Some devices allow an individual function to be reset without affecting
5178  * other functions in the same device.  The PCI device must be responsive
5179  * to PCI config space in order to use this function.
5180  *
5181  * This function does not just reset the PCI portion of a device, but
5182  * clears all the state associated with the device.  This function differs
5183  * from __pci_reset_function_locked() in that it saves and restores device state
5184  * over the reset.  It also differs from pci_reset_function() in that it
5185  * requires the PCI device lock to be held.
5186  *
5187  * Returns 0 if the device function was successfully reset or negative if the
5188  * device doesn't support resetting a single function.
5189  */
pci_reset_function_locked(struct pci_dev * dev)5190 int pci_reset_function_locked(struct pci_dev *dev)
5191 {
5192 	int rc;
5193 
5194 	if (!dev->reset_fn)
5195 		return -ENOTTY;
5196 
5197 	pci_dev_save_and_disable(dev);
5198 
5199 	rc = __pci_reset_function_locked(dev);
5200 
5201 	pci_dev_restore(dev);
5202 
5203 	return rc;
5204 }
5205 EXPORT_SYMBOL_GPL(pci_reset_function_locked);
5206 
5207 /**
5208  * pci_try_reset_function - quiesce and reset a PCI device function
5209  * @dev: PCI device to reset
5210  *
5211  * Same as above, except return -EAGAIN if unable to lock device.
5212  */
pci_try_reset_function(struct pci_dev * dev)5213 int pci_try_reset_function(struct pci_dev *dev)
5214 {
5215 	int rc;
5216 
5217 	if (!dev->reset_fn)
5218 		return -ENOTTY;
5219 
5220 	if (!pci_dev_trylock(dev))
5221 		return -EAGAIN;
5222 
5223 	pci_dev_save_and_disable(dev);
5224 	rc = __pci_reset_function_locked(dev);
5225 	pci_dev_restore(dev);
5226 	pci_dev_unlock(dev);
5227 
5228 	return rc;
5229 }
5230 EXPORT_SYMBOL_GPL(pci_try_reset_function);
5231 
5232 /* Do any devices on or below this bus prevent a bus reset? */
pci_bus_resetable(struct pci_bus * bus)5233 static bool pci_bus_resetable(struct pci_bus *bus)
5234 {
5235 	struct pci_dev *dev;
5236 
5237 
5238 	if (bus->self && (bus->self->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET))
5239 		return false;
5240 
5241 	list_for_each_entry(dev, &bus->devices, bus_list) {
5242 		if (dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET ||
5243 		    (dev->subordinate && !pci_bus_resetable(dev->subordinate)))
5244 			return false;
5245 	}
5246 
5247 	return true;
5248 }
5249 
5250 /* Lock devices from the top of the tree down */
pci_bus_lock(struct pci_bus * bus)5251 static void pci_bus_lock(struct pci_bus *bus)
5252 {
5253 	struct pci_dev *dev;
5254 
5255 	list_for_each_entry(dev, &bus->devices, bus_list) {
5256 		pci_dev_lock(dev);
5257 		if (dev->subordinate)
5258 			pci_bus_lock(dev->subordinate);
5259 	}
5260 }
5261 
5262 /* Unlock devices from the bottom of the tree up */
pci_bus_unlock(struct pci_bus * bus)5263 static void pci_bus_unlock(struct pci_bus *bus)
5264 {
5265 	struct pci_dev *dev;
5266 
5267 	list_for_each_entry(dev, &bus->devices, bus_list) {
5268 		if (dev->subordinate)
5269 			pci_bus_unlock(dev->subordinate);
5270 		pci_dev_unlock(dev);
5271 	}
5272 }
5273 
5274 /* Return 1 on successful lock, 0 on contention */
pci_bus_trylock(struct pci_bus * bus)5275 static int pci_bus_trylock(struct pci_bus *bus)
5276 {
5277 	struct pci_dev *dev;
5278 
5279 	list_for_each_entry(dev, &bus->devices, bus_list) {
5280 		if (!pci_dev_trylock(dev))
5281 			goto unlock;
5282 		if (dev->subordinate) {
5283 			if (!pci_bus_trylock(dev->subordinate)) {
5284 				pci_dev_unlock(dev);
5285 				goto unlock;
5286 			}
5287 		}
5288 	}
5289 	return 1;
5290 
5291 unlock:
5292 	list_for_each_entry_continue_reverse(dev, &bus->devices, bus_list) {
5293 		if (dev->subordinate)
5294 			pci_bus_unlock(dev->subordinate);
5295 		pci_dev_unlock(dev);
5296 	}
5297 	return 0;
5298 }
5299 
5300 /* Do any devices on or below this slot prevent a bus reset? */
pci_slot_resetable(struct pci_slot * slot)5301 static bool pci_slot_resetable(struct pci_slot *slot)
5302 {
5303 	struct pci_dev *dev;
5304 
5305 	if (slot->bus->self &&
5306 	    (slot->bus->self->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET))
5307 		return false;
5308 
5309 	list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5310 		if (!dev->slot || dev->slot != slot)
5311 			continue;
5312 		if (dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET ||
5313 		    (dev->subordinate && !pci_bus_resetable(dev->subordinate)))
5314 			return false;
5315 	}
5316 
5317 	return true;
5318 }
5319 
5320 /* Lock devices from the top of the tree down */
pci_slot_lock(struct pci_slot * slot)5321 static void pci_slot_lock(struct pci_slot *slot)
5322 {
5323 	struct pci_dev *dev;
5324 
5325 	list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5326 		if (!dev->slot || dev->slot != slot)
5327 			continue;
5328 		pci_dev_lock(dev);
5329 		if (dev->subordinate)
5330 			pci_bus_lock(dev->subordinate);
5331 	}
5332 }
5333 
5334 /* Unlock devices from the bottom of the tree up */
pci_slot_unlock(struct pci_slot * slot)5335 static void pci_slot_unlock(struct pci_slot *slot)
5336 {
5337 	struct pci_dev *dev;
5338 
5339 	list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5340 		if (!dev->slot || dev->slot != slot)
5341 			continue;
5342 		if (dev->subordinate)
5343 			pci_bus_unlock(dev->subordinate);
5344 		pci_dev_unlock(dev);
5345 	}
5346 }
5347 
5348 /* Return 1 on successful lock, 0 on contention */
pci_slot_trylock(struct pci_slot * slot)5349 static int pci_slot_trylock(struct pci_slot *slot)
5350 {
5351 	struct pci_dev *dev;
5352 
5353 	list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5354 		if (!dev->slot || dev->slot != slot)
5355 			continue;
5356 		if (!pci_dev_trylock(dev))
5357 			goto unlock;
5358 		if (dev->subordinate) {
5359 			if (!pci_bus_trylock(dev->subordinate)) {
5360 				pci_dev_unlock(dev);
5361 				goto unlock;
5362 			}
5363 		}
5364 	}
5365 	return 1;
5366 
5367 unlock:
5368 	list_for_each_entry_continue_reverse(dev,
5369 					     &slot->bus->devices, bus_list) {
5370 		if (!dev->slot || dev->slot != slot)
5371 			continue;
5372 		if (dev->subordinate)
5373 			pci_bus_unlock(dev->subordinate);
5374 		pci_dev_unlock(dev);
5375 	}
5376 	return 0;
5377 }
5378 
5379 /*
5380  * Save and disable devices from the top of the tree down while holding
5381  * the @dev mutex lock for the entire tree.
5382  */
pci_bus_save_and_disable_locked(struct pci_bus * bus)5383 static void pci_bus_save_and_disable_locked(struct pci_bus *bus)
5384 {
5385 	struct pci_dev *dev;
5386 
5387 	list_for_each_entry(dev, &bus->devices, bus_list) {
5388 		pci_dev_save_and_disable(dev);
5389 		if (dev->subordinate)
5390 			pci_bus_save_and_disable_locked(dev->subordinate);
5391 	}
5392 }
5393 
5394 /*
5395  * Restore devices from top of the tree down while holding @dev mutex lock
5396  * for the entire tree.  Parent bridges need to be restored before we can
5397  * get to subordinate devices.
5398  */
pci_bus_restore_locked(struct pci_bus * bus)5399 static void pci_bus_restore_locked(struct pci_bus *bus)
5400 {
5401 	struct pci_dev *dev;
5402 
5403 	list_for_each_entry(dev, &bus->devices, bus_list) {
5404 		pci_dev_restore(dev);
5405 		if (dev->subordinate)
5406 			pci_bus_restore_locked(dev->subordinate);
5407 	}
5408 }
5409 
5410 /*
5411  * Save and disable devices from the top of the tree down while holding
5412  * the @dev mutex lock for the entire tree.
5413  */
pci_slot_save_and_disable_locked(struct pci_slot * slot)5414 static void pci_slot_save_and_disable_locked(struct pci_slot *slot)
5415 {
5416 	struct pci_dev *dev;
5417 
5418 	list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5419 		if (!dev->slot || dev->slot != slot)
5420 			continue;
5421 		pci_dev_save_and_disable(dev);
5422 		if (dev->subordinate)
5423 			pci_bus_save_and_disable_locked(dev->subordinate);
5424 	}
5425 }
5426 
5427 /*
5428  * Restore devices from top of the tree down while holding @dev mutex lock
5429  * for the entire tree.  Parent bridges need to be restored before we can
5430  * get to subordinate devices.
5431  */
pci_slot_restore_locked(struct pci_slot * slot)5432 static void pci_slot_restore_locked(struct pci_slot *slot)
5433 {
5434 	struct pci_dev *dev;
5435 
5436 	list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5437 		if (!dev->slot || dev->slot != slot)
5438 			continue;
5439 		pci_dev_restore(dev);
5440 		if (dev->subordinate)
5441 			pci_bus_restore_locked(dev->subordinate);
5442 	}
5443 }
5444 
pci_slot_reset(struct pci_slot * slot,int probe)5445 static int pci_slot_reset(struct pci_slot *slot, int probe)
5446 {
5447 	int rc;
5448 
5449 	if (!slot || !pci_slot_resetable(slot))
5450 		return -ENOTTY;
5451 
5452 	if (!probe)
5453 		pci_slot_lock(slot);
5454 
5455 	might_sleep();
5456 
5457 	rc = pci_reset_hotplug_slot(slot->hotplug, probe);
5458 
5459 	if (!probe)
5460 		pci_slot_unlock(slot);
5461 
5462 	return rc;
5463 }
5464 
5465 /**
5466  * pci_probe_reset_slot - probe whether a PCI slot can be reset
5467  * @slot: PCI slot to probe
5468  *
5469  * Return 0 if slot can be reset, negative if a slot reset is not supported.
5470  */
pci_probe_reset_slot(struct pci_slot * slot)5471 int pci_probe_reset_slot(struct pci_slot *slot)
5472 {
5473 	return pci_slot_reset(slot, 1);
5474 }
5475 EXPORT_SYMBOL_GPL(pci_probe_reset_slot);
5476 
5477 /**
5478  * __pci_reset_slot - Try to reset a PCI slot
5479  * @slot: PCI slot to reset
5480  *
5481  * A PCI bus may host multiple slots, each slot may support a reset mechanism
5482  * independent of other slots.  For instance, some slots may support slot power
5483  * control.  In the case of a 1:1 bus to slot architecture, this function may
5484  * wrap the bus reset to avoid spurious slot related events such as hotplug.
5485  * Generally a slot reset should be attempted before a bus reset.  All of the
5486  * function of the slot and any subordinate buses behind the slot are reset
5487  * through this function.  PCI config space of all devices in the slot and
5488  * behind the slot is saved before and restored after reset.
5489  *
5490  * Same as above except return -EAGAIN if the slot cannot be locked
5491  */
__pci_reset_slot(struct pci_slot * slot)5492 static int __pci_reset_slot(struct pci_slot *slot)
5493 {
5494 	int rc;
5495 
5496 	rc = pci_slot_reset(slot, 1);
5497 	if (rc)
5498 		return rc;
5499 
5500 	if (pci_slot_trylock(slot)) {
5501 		pci_slot_save_and_disable_locked(slot);
5502 		might_sleep();
5503 		rc = pci_reset_hotplug_slot(slot->hotplug, 0);
5504 		pci_slot_restore_locked(slot);
5505 		pci_slot_unlock(slot);
5506 	} else
5507 		rc = -EAGAIN;
5508 
5509 	return rc;
5510 }
5511 
pci_bus_reset(struct pci_bus * bus,int probe)5512 static int pci_bus_reset(struct pci_bus *bus, int probe)
5513 {
5514 	int ret;
5515 
5516 	if (!bus->self || !pci_bus_resetable(bus))
5517 		return -ENOTTY;
5518 
5519 	if (probe)
5520 		return 0;
5521 
5522 	pci_bus_lock(bus);
5523 
5524 	might_sleep();
5525 
5526 	ret = pci_bridge_secondary_bus_reset(bus->self);
5527 
5528 	pci_bus_unlock(bus);
5529 
5530 	return ret;
5531 }
5532 
5533 /**
5534  * pci_bus_error_reset - reset the bridge's subordinate bus
5535  * @bridge: The parent device that connects to the bus to reset
5536  *
5537  * This function will first try to reset the slots on this bus if the method is
5538  * available. If slot reset fails or is not available, this will fall back to a
5539  * secondary bus reset.
5540  */
pci_bus_error_reset(struct pci_dev * bridge)5541 int pci_bus_error_reset(struct pci_dev *bridge)
5542 {
5543 	struct pci_bus *bus = bridge->subordinate;
5544 	struct pci_slot *slot;
5545 
5546 	if (!bus)
5547 		return -ENOTTY;
5548 
5549 	mutex_lock(&pci_slot_mutex);
5550 	if (list_empty(&bus->slots))
5551 		goto bus_reset;
5552 
5553 	list_for_each_entry(slot, &bus->slots, list)
5554 		if (pci_probe_reset_slot(slot))
5555 			goto bus_reset;
5556 
5557 	list_for_each_entry(slot, &bus->slots, list)
5558 		if (pci_slot_reset(slot, 0))
5559 			goto bus_reset;
5560 
5561 	mutex_unlock(&pci_slot_mutex);
5562 	return 0;
5563 bus_reset:
5564 	mutex_unlock(&pci_slot_mutex);
5565 	return pci_bus_reset(bridge->subordinate, 0);
5566 }
5567 
5568 /**
5569  * pci_probe_reset_bus - probe whether a PCI bus can be reset
5570  * @bus: PCI bus to probe
5571  *
5572  * Return 0 if bus can be reset, negative if a bus reset is not supported.
5573  */
pci_probe_reset_bus(struct pci_bus * bus)5574 int pci_probe_reset_bus(struct pci_bus *bus)
5575 {
5576 	return pci_bus_reset(bus, 1);
5577 }
5578 EXPORT_SYMBOL_GPL(pci_probe_reset_bus);
5579 
5580 /**
5581  * __pci_reset_bus - Try to reset a PCI bus
5582  * @bus: top level PCI bus to reset
5583  *
5584  * Same as above except return -EAGAIN if the bus cannot be locked
5585  */
__pci_reset_bus(struct pci_bus * bus)5586 static int __pci_reset_bus(struct pci_bus *bus)
5587 {
5588 	int rc;
5589 
5590 	rc = pci_bus_reset(bus, 1);
5591 	if (rc)
5592 		return rc;
5593 
5594 	if (pci_bus_trylock(bus)) {
5595 		pci_bus_save_and_disable_locked(bus);
5596 		might_sleep();
5597 		rc = pci_bridge_secondary_bus_reset(bus->self);
5598 		pci_bus_restore_locked(bus);
5599 		pci_bus_unlock(bus);
5600 	} else
5601 		rc = -EAGAIN;
5602 
5603 	return rc;
5604 }
5605 
5606 /**
5607  * pci_reset_bus - Try to reset a PCI bus
5608  * @pdev: top level PCI device to reset via slot/bus
5609  *
5610  * Same as above except return -EAGAIN if the bus cannot be locked
5611  */
pci_reset_bus(struct pci_dev * pdev)5612 int pci_reset_bus(struct pci_dev *pdev)
5613 {
5614 	return (!pci_probe_reset_slot(pdev->slot)) ?
5615 	    __pci_reset_slot(pdev->slot) : __pci_reset_bus(pdev->bus);
5616 }
5617 EXPORT_SYMBOL_GPL(pci_reset_bus);
5618 
5619 /**
5620  * pcix_get_max_mmrbc - get PCI-X maximum designed memory read byte count
5621  * @dev: PCI device to query
5622  *
5623  * Returns mmrbc: maximum designed memory read count in bytes or
5624  * appropriate error value.
5625  */
pcix_get_max_mmrbc(struct pci_dev * dev)5626 int pcix_get_max_mmrbc(struct pci_dev *dev)
5627 {
5628 	int cap;
5629 	u32 stat;
5630 
5631 	cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
5632 	if (!cap)
5633 		return -EINVAL;
5634 
5635 	if (pci_read_config_dword(dev, cap + PCI_X_STATUS, &stat))
5636 		return -EINVAL;
5637 
5638 	return 512 << ((stat & PCI_X_STATUS_MAX_READ) >> 21);
5639 }
5640 EXPORT_SYMBOL(pcix_get_max_mmrbc);
5641 
5642 /**
5643  * pcix_get_mmrbc - get PCI-X maximum memory read byte count
5644  * @dev: PCI device to query
5645  *
5646  * Returns mmrbc: maximum memory read count in bytes or appropriate error
5647  * value.
5648  */
pcix_get_mmrbc(struct pci_dev * dev)5649 int pcix_get_mmrbc(struct pci_dev *dev)
5650 {
5651 	int cap;
5652 	u16 cmd;
5653 
5654 	cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
5655 	if (!cap)
5656 		return -EINVAL;
5657 
5658 	if (pci_read_config_word(dev, cap + PCI_X_CMD, &cmd))
5659 		return -EINVAL;
5660 
5661 	return 512 << ((cmd & PCI_X_CMD_MAX_READ) >> 2);
5662 }
5663 EXPORT_SYMBOL(pcix_get_mmrbc);
5664 
5665 /**
5666  * pcix_set_mmrbc - set PCI-X maximum memory read byte count
5667  * @dev: PCI device to query
5668  * @mmrbc: maximum memory read count in bytes
5669  *    valid values are 512, 1024, 2048, 4096
5670  *
5671  * If possible sets maximum memory read byte count, some bridges have errata
5672  * that prevent this.
5673  */
pcix_set_mmrbc(struct pci_dev * dev,int mmrbc)5674 int pcix_set_mmrbc(struct pci_dev *dev, int mmrbc)
5675 {
5676 	int cap;
5677 	u32 stat, v, o;
5678 	u16 cmd;
5679 
5680 	if (mmrbc < 512 || mmrbc > 4096 || !is_power_of_2(mmrbc))
5681 		return -EINVAL;
5682 
5683 	v = ffs(mmrbc) - 10;
5684 
5685 	cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
5686 	if (!cap)
5687 		return -EINVAL;
5688 
5689 	if (pci_read_config_dword(dev, cap + PCI_X_STATUS, &stat))
5690 		return -EINVAL;
5691 
5692 	if (v > (stat & PCI_X_STATUS_MAX_READ) >> 21)
5693 		return -E2BIG;
5694 
5695 	if (pci_read_config_word(dev, cap + PCI_X_CMD, &cmd))
5696 		return -EINVAL;
5697 
5698 	o = (cmd & PCI_X_CMD_MAX_READ) >> 2;
5699 	if (o != v) {
5700 		if (v > o && (dev->bus->bus_flags & PCI_BUS_FLAGS_NO_MMRBC))
5701 			return -EIO;
5702 
5703 		cmd &= ~PCI_X_CMD_MAX_READ;
5704 		cmd |= v << 2;
5705 		if (pci_write_config_word(dev, cap + PCI_X_CMD, cmd))
5706 			return -EIO;
5707 	}
5708 	return 0;
5709 }
5710 EXPORT_SYMBOL(pcix_set_mmrbc);
5711 
5712 /**
5713  * pcie_get_readrq - get PCI Express read request size
5714  * @dev: PCI device to query
5715  *
5716  * Returns maximum memory read request in bytes or appropriate error value.
5717  */
pcie_get_readrq(struct pci_dev * dev)5718 int pcie_get_readrq(struct pci_dev *dev)
5719 {
5720 	u16 ctl;
5721 
5722 	pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &ctl);
5723 
5724 	return 128 << ((ctl & PCI_EXP_DEVCTL_READRQ) >> 12);
5725 }
5726 EXPORT_SYMBOL(pcie_get_readrq);
5727 
5728 /**
5729  * pcie_set_readrq - set PCI Express maximum memory read request
5730  * @dev: PCI device to query
5731  * @rq: maximum memory read count in bytes
5732  *    valid values are 128, 256, 512, 1024, 2048, 4096
5733  *
5734  * If possible sets maximum memory read request in bytes
5735  */
pcie_set_readrq(struct pci_dev * dev,int rq)5736 int pcie_set_readrq(struct pci_dev *dev, int rq)
5737 {
5738 	u16 v;
5739 	int ret;
5740 
5741 	if (rq < 128 || rq > 4096 || !is_power_of_2(rq))
5742 		return -EINVAL;
5743 
5744 	/*
5745 	 * If using the "performance" PCIe config, we clamp the read rq
5746 	 * size to the max packet size to keep the host bridge from
5747 	 * generating requests larger than we can cope with.
5748 	 */
5749 	if (pcie_bus_config == PCIE_BUS_PERFORMANCE) {
5750 		int mps = pcie_get_mps(dev);
5751 
5752 		if (mps < rq)
5753 			rq = mps;
5754 	}
5755 
5756 	v = (ffs(rq) - 8) << 12;
5757 
5758 	ret = pcie_capability_clear_and_set_word(dev, PCI_EXP_DEVCTL,
5759 						  PCI_EXP_DEVCTL_READRQ, v);
5760 
5761 	return pcibios_err_to_errno(ret);
5762 }
5763 EXPORT_SYMBOL(pcie_set_readrq);
5764 
5765 /**
5766  * pcie_get_mps - get PCI Express maximum payload size
5767  * @dev: PCI device to query
5768  *
5769  * Returns maximum payload size in bytes
5770  */
pcie_get_mps(struct pci_dev * dev)5771 int pcie_get_mps(struct pci_dev *dev)
5772 {
5773 	u16 ctl;
5774 
5775 	pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &ctl);
5776 
5777 	return 128 << ((ctl & PCI_EXP_DEVCTL_PAYLOAD) >> 5);
5778 }
5779 EXPORT_SYMBOL(pcie_get_mps);
5780 
5781 /**
5782  * pcie_set_mps - set PCI Express maximum payload size
5783  * @dev: PCI device to query
5784  * @mps: maximum payload size in bytes
5785  *    valid values are 128, 256, 512, 1024, 2048, 4096
5786  *
5787  * If possible sets maximum payload size
5788  */
pcie_set_mps(struct pci_dev * dev,int mps)5789 int pcie_set_mps(struct pci_dev *dev, int mps)
5790 {
5791 	u16 v;
5792 	int ret;
5793 
5794 	if (mps < 128 || mps > 4096 || !is_power_of_2(mps))
5795 		return -EINVAL;
5796 
5797 	v = ffs(mps) - 8;
5798 	if (v > dev->pcie_mpss)
5799 		return -EINVAL;
5800 	v <<= 5;
5801 
5802 	ret = pcie_capability_clear_and_set_word(dev, PCI_EXP_DEVCTL,
5803 						  PCI_EXP_DEVCTL_PAYLOAD, v);
5804 
5805 	return pcibios_err_to_errno(ret);
5806 }
5807 EXPORT_SYMBOL(pcie_set_mps);
5808 
5809 /**
5810  * pcie_bandwidth_available - determine minimum link settings of a PCIe
5811  *			      device and its bandwidth limitation
5812  * @dev: PCI device to query
5813  * @limiting_dev: storage for device causing the bandwidth limitation
5814  * @speed: storage for speed of limiting device
5815  * @width: storage for width of limiting device
5816  *
5817  * Walk up the PCI device chain and find the point where the minimum
5818  * bandwidth is available.  Return the bandwidth available there and (if
5819  * limiting_dev, speed, and width pointers are supplied) information about
5820  * that point.  The bandwidth returned is in Mb/s, i.e., megabits/second of
5821  * raw bandwidth.
5822  */
pcie_bandwidth_available(struct pci_dev * dev,struct pci_dev ** limiting_dev,enum pci_bus_speed * speed,enum pcie_link_width * width)5823 u32 pcie_bandwidth_available(struct pci_dev *dev, struct pci_dev **limiting_dev,
5824 			     enum pci_bus_speed *speed,
5825 			     enum pcie_link_width *width)
5826 {
5827 	u16 lnksta;
5828 	enum pci_bus_speed next_speed;
5829 	enum pcie_link_width next_width;
5830 	u32 bw, next_bw;
5831 
5832 	if (speed)
5833 		*speed = PCI_SPEED_UNKNOWN;
5834 	if (width)
5835 		*width = PCIE_LNK_WIDTH_UNKNOWN;
5836 
5837 	bw = 0;
5838 
5839 	while (dev) {
5840 		pcie_capability_read_word(dev, PCI_EXP_LNKSTA, &lnksta);
5841 
5842 		next_speed = pcie_link_speed[lnksta & PCI_EXP_LNKSTA_CLS];
5843 		next_width = (lnksta & PCI_EXP_LNKSTA_NLW) >>
5844 			PCI_EXP_LNKSTA_NLW_SHIFT;
5845 
5846 		next_bw = next_width * PCIE_SPEED2MBS_ENC(next_speed);
5847 
5848 		/* Check if current device limits the total bandwidth */
5849 		if (!bw || next_bw <= bw) {
5850 			bw = next_bw;
5851 
5852 			if (limiting_dev)
5853 				*limiting_dev = dev;
5854 			if (speed)
5855 				*speed = next_speed;
5856 			if (width)
5857 				*width = next_width;
5858 		}
5859 
5860 		dev = pci_upstream_bridge(dev);
5861 	}
5862 
5863 	return bw;
5864 }
5865 EXPORT_SYMBOL(pcie_bandwidth_available);
5866 
5867 /**
5868  * pcie_get_speed_cap - query for the PCI device's link speed capability
5869  * @dev: PCI device to query
5870  *
5871  * Query the PCI device speed capability.  Return the maximum link speed
5872  * supported by the device.
5873  */
pcie_get_speed_cap(struct pci_dev * dev)5874 enum pci_bus_speed pcie_get_speed_cap(struct pci_dev *dev)
5875 {
5876 	u32 lnkcap2, lnkcap;
5877 
5878 	/*
5879 	 * Link Capabilities 2 was added in PCIe r3.0, sec 7.8.18.  The
5880 	 * implementation note there recommends using the Supported Link
5881 	 * Speeds Vector in Link Capabilities 2 when supported.
5882 	 *
5883 	 * Without Link Capabilities 2, i.e., prior to PCIe r3.0, software
5884 	 * should use the Supported Link Speeds field in Link Capabilities,
5885 	 * where only 2.5 GT/s and 5.0 GT/s speeds were defined.
5886 	 */
5887 	pcie_capability_read_dword(dev, PCI_EXP_LNKCAP2, &lnkcap2);
5888 
5889 	/* PCIe r3.0-compliant */
5890 	if (lnkcap2)
5891 		return PCIE_LNKCAP2_SLS2SPEED(lnkcap2);
5892 
5893 	pcie_capability_read_dword(dev, PCI_EXP_LNKCAP, &lnkcap);
5894 	if ((lnkcap & PCI_EXP_LNKCAP_SLS) == PCI_EXP_LNKCAP_SLS_5_0GB)
5895 		return PCIE_SPEED_5_0GT;
5896 	else if ((lnkcap & PCI_EXP_LNKCAP_SLS) == PCI_EXP_LNKCAP_SLS_2_5GB)
5897 		return PCIE_SPEED_2_5GT;
5898 
5899 	return PCI_SPEED_UNKNOWN;
5900 }
5901 EXPORT_SYMBOL(pcie_get_speed_cap);
5902 
5903 /**
5904  * pcie_get_width_cap - query for the PCI device's link width capability
5905  * @dev: PCI device to query
5906  *
5907  * Query the PCI device width capability.  Return the maximum link width
5908  * supported by the device.
5909  */
pcie_get_width_cap(struct pci_dev * dev)5910 enum pcie_link_width pcie_get_width_cap(struct pci_dev *dev)
5911 {
5912 	u32 lnkcap;
5913 
5914 	pcie_capability_read_dword(dev, PCI_EXP_LNKCAP, &lnkcap);
5915 	if (lnkcap)
5916 		return (lnkcap & PCI_EXP_LNKCAP_MLW) >> 4;
5917 
5918 	return PCIE_LNK_WIDTH_UNKNOWN;
5919 }
5920 EXPORT_SYMBOL(pcie_get_width_cap);
5921 
5922 /**
5923  * pcie_bandwidth_capable - calculate a PCI device's link bandwidth capability
5924  * @dev: PCI device
5925  * @speed: storage for link speed
5926  * @width: storage for link width
5927  *
5928  * Calculate a PCI device's link bandwidth by querying for its link speed
5929  * and width, multiplying them, and applying encoding overhead.  The result
5930  * is in Mb/s, i.e., megabits/second of raw bandwidth.
5931  */
pcie_bandwidth_capable(struct pci_dev * dev,enum pci_bus_speed * speed,enum pcie_link_width * width)5932 u32 pcie_bandwidth_capable(struct pci_dev *dev, enum pci_bus_speed *speed,
5933 			   enum pcie_link_width *width)
5934 {
5935 	*speed = pcie_get_speed_cap(dev);
5936 	*width = pcie_get_width_cap(dev);
5937 
5938 	if (*speed == PCI_SPEED_UNKNOWN || *width == PCIE_LNK_WIDTH_UNKNOWN)
5939 		return 0;
5940 
5941 	return *width * PCIE_SPEED2MBS_ENC(*speed);
5942 }
5943 
5944 /**
5945  * __pcie_print_link_status - Report the PCI device's link speed and width
5946  * @dev: PCI device to query
5947  * @verbose: Print info even when enough bandwidth is available
5948  *
5949  * If the available bandwidth at the device is less than the device is
5950  * capable of, report the device's maximum possible bandwidth and the
5951  * upstream link that limits its performance.  If @verbose, always print
5952  * the available bandwidth, even if the device isn't constrained.
5953  */
__pcie_print_link_status(struct pci_dev * dev,bool verbose)5954 void __pcie_print_link_status(struct pci_dev *dev, bool verbose)
5955 {
5956 	enum pcie_link_width width, width_cap;
5957 	enum pci_bus_speed speed, speed_cap;
5958 	struct pci_dev *limiting_dev = NULL;
5959 	u32 bw_avail, bw_cap;
5960 
5961 	bw_cap = pcie_bandwidth_capable(dev, &speed_cap, &width_cap);
5962 	bw_avail = pcie_bandwidth_available(dev, &limiting_dev, &speed, &width);
5963 
5964 	if (bw_avail >= bw_cap && verbose)
5965 		pci_info(dev, "%u.%03u Gb/s available PCIe bandwidth (%s x%d link)\n",
5966 			 bw_cap / 1000, bw_cap % 1000,
5967 			 pci_speed_string(speed_cap), width_cap);
5968 	else if (bw_avail < bw_cap)
5969 		pci_info(dev, "%u.%03u Gb/s available PCIe bandwidth, limited by %s x%d link at %s (capable of %u.%03u Gb/s with %s x%d link)\n",
5970 			 bw_avail / 1000, bw_avail % 1000,
5971 			 pci_speed_string(speed), width,
5972 			 limiting_dev ? pci_name(limiting_dev) : "<unknown>",
5973 			 bw_cap / 1000, bw_cap % 1000,
5974 			 pci_speed_string(speed_cap), width_cap);
5975 }
5976 
5977 /**
5978  * pcie_print_link_status - Report the PCI device's link speed and width
5979  * @dev: PCI device to query
5980  *
5981  * Report the available bandwidth at the device.
5982  */
pcie_print_link_status(struct pci_dev * dev)5983 void pcie_print_link_status(struct pci_dev *dev)
5984 {
5985 	__pcie_print_link_status(dev, true);
5986 }
5987 EXPORT_SYMBOL(pcie_print_link_status);
5988 
5989 /**
5990  * pci_select_bars - Make BAR mask from the type of resource
5991  * @dev: the PCI device for which BAR mask is made
5992  * @flags: resource type mask to be selected
5993  *
5994  * This helper routine makes bar mask from the type of resource.
5995  */
pci_select_bars(struct pci_dev * dev,unsigned long flags)5996 int pci_select_bars(struct pci_dev *dev, unsigned long flags)
5997 {
5998 	int i, bars = 0;
5999 	for (i = 0; i < PCI_NUM_RESOURCES; i++)
6000 		if (pci_resource_flags(dev, i) & flags)
6001 			bars |= (1 << i);
6002 	return bars;
6003 }
6004 EXPORT_SYMBOL(pci_select_bars);
6005 
6006 /* Some architectures require additional programming to enable VGA */
6007 static arch_set_vga_state_t arch_set_vga_state;
6008 
pci_register_set_vga_state(arch_set_vga_state_t func)6009 void __init pci_register_set_vga_state(arch_set_vga_state_t func)
6010 {
6011 	arch_set_vga_state = func;	/* NULL disables */
6012 }
6013 
pci_set_vga_state_arch(struct pci_dev * dev,bool decode,unsigned int command_bits,u32 flags)6014 static int pci_set_vga_state_arch(struct pci_dev *dev, bool decode,
6015 				  unsigned int command_bits, u32 flags)
6016 {
6017 	if (arch_set_vga_state)
6018 		return arch_set_vga_state(dev, decode, command_bits,
6019 						flags);
6020 	return 0;
6021 }
6022 
6023 /**
6024  * pci_set_vga_state - set VGA decode state on device and parents if requested
6025  * @dev: the PCI device
6026  * @decode: true = enable decoding, false = disable decoding
6027  * @command_bits: PCI_COMMAND_IO and/or PCI_COMMAND_MEMORY
6028  * @flags: traverse ancestors and change bridges
6029  * CHANGE_BRIDGE_ONLY / CHANGE_BRIDGE
6030  */
pci_set_vga_state(struct pci_dev * dev,bool decode,unsigned int command_bits,u32 flags)6031 int pci_set_vga_state(struct pci_dev *dev, bool decode,
6032 		      unsigned int command_bits, u32 flags)
6033 {
6034 	struct pci_bus *bus;
6035 	struct pci_dev *bridge;
6036 	u16 cmd;
6037 	int rc;
6038 
6039 	WARN_ON((flags & PCI_VGA_STATE_CHANGE_DECODES) && (command_bits & ~(PCI_COMMAND_IO|PCI_COMMAND_MEMORY)));
6040 
6041 	/* ARCH specific VGA enables */
6042 	rc = pci_set_vga_state_arch(dev, decode, command_bits, flags);
6043 	if (rc)
6044 		return rc;
6045 
6046 	if (flags & PCI_VGA_STATE_CHANGE_DECODES) {
6047 		pci_read_config_word(dev, PCI_COMMAND, &cmd);
6048 		if (decode)
6049 			cmd |= command_bits;
6050 		else
6051 			cmd &= ~command_bits;
6052 		pci_write_config_word(dev, PCI_COMMAND, cmd);
6053 	}
6054 
6055 	if (!(flags & PCI_VGA_STATE_CHANGE_BRIDGE))
6056 		return 0;
6057 
6058 	bus = dev->bus;
6059 	while (bus) {
6060 		bridge = bus->self;
6061 		if (bridge) {
6062 			pci_read_config_word(bridge, PCI_BRIDGE_CONTROL,
6063 					     &cmd);
6064 			if (decode)
6065 				cmd |= PCI_BRIDGE_CTL_VGA;
6066 			else
6067 				cmd &= ~PCI_BRIDGE_CTL_VGA;
6068 			pci_write_config_word(bridge, PCI_BRIDGE_CONTROL,
6069 					      cmd);
6070 		}
6071 		bus = bus->parent;
6072 	}
6073 	return 0;
6074 }
6075 
6076 #ifdef CONFIG_ACPI
pci_pr3_present(struct pci_dev * pdev)6077 bool pci_pr3_present(struct pci_dev *pdev)
6078 {
6079 	struct acpi_device *adev;
6080 
6081 	if (acpi_disabled)
6082 		return false;
6083 
6084 	adev = ACPI_COMPANION(&pdev->dev);
6085 	if (!adev)
6086 		return false;
6087 
6088 	return adev->power.flags.power_resources &&
6089 		acpi_has_method(adev->handle, "_PR3");
6090 }
6091 EXPORT_SYMBOL_GPL(pci_pr3_present);
6092 #endif
6093 
6094 /**
6095  * pci_add_dma_alias - Add a DMA devfn alias for a device
6096  * @dev: the PCI device for which alias is added
6097  * @devfn_from: alias slot and function
6098  * @nr_devfns: number of subsequent devfns to alias
6099  *
6100  * This helper encodes an 8-bit devfn as a bit number in dma_alias_mask
6101  * which is used to program permissible bus-devfn source addresses for DMA
6102  * requests in an IOMMU.  These aliases factor into IOMMU group creation
6103  * and are useful for devices generating DMA requests beyond or different
6104  * from their logical bus-devfn.  Examples include device quirks where the
6105  * device simply uses the wrong devfn, as well as non-transparent bridges
6106  * where the alias may be a proxy for devices in another domain.
6107  *
6108  * IOMMU group creation is performed during device discovery or addition,
6109  * prior to any potential DMA mapping and therefore prior to driver probing
6110  * (especially for userspace assigned devices where IOMMU group definition
6111  * cannot be left as a userspace activity).  DMA aliases should therefore
6112  * be configured via quirks, such as the PCI fixup header quirk.
6113  */
pci_add_dma_alias(struct pci_dev * dev,u8 devfn_from,unsigned nr_devfns)6114 void pci_add_dma_alias(struct pci_dev *dev, u8 devfn_from, unsigned nr_devfns)
6115 {
6116 	int devfn_to;
6117 
6118 	nr_devfns = min(nr_devfns, (unsigned) MAX_NR_DEVFNS - devfn_from);
6119 	devfn_to = devfn_from + nr_devfns - 1;
6120 
6121 	if (!dev->dma_alias_mask)
6122 		dev->dma_alias_mask = bitmap_zalloc(MAX_NR_DEVFNS, GFP_KERNEL);
6123 	if (!dev->dma_alias_mask) {
6124 		pci_warn(dev, "Unable to allocate DMA alias mask\n");
6125 		return;
6126 	}
6127 
6128 	bitmap_set(dev->dma_alias_mask, devfn_from, nr_devfns);
6129 
6130 	if (nr_devfns == 1)
6131 		pci_info(dev, "Enabling fixed DMA alias to %02x.%d\n",
6132 				PCI_SLOT(devfn_from), PCI_FUNC(devfn_from));
6133 	else if (nr_devfns > 1)
6134 		pci_info(dev, "Enabling fixed DMA alias for devfn range from %02x.%d to %02x.%d\n",
6135 				PCI_SLOT(devfn_from), PCI_FUNC(devfn_from),
6136 				PCI_SLOT(devfn_to), PCI_FUNC(devfn_to));
6137 }
6138 
pci_devs_are_dma_aliases(struct pci_dev * dev1,struct pci_dev * dev2)6139 bool pci_devs_are_dma_aliases(struct pci_dev *dev1, struct pci_dev *dev2)
6140 {
6141 	return (dev1->dma_alias_mask &&
6142 		test_bit(dev2->devfn, dev1->dma_alias_mask)) ||
6143 	       (dev2->dma_alias_mask &&
6144 		test_bit(dev1->devfn, dev2->dma_alias_mask)) ||
6145 	       pci_real_dma_dev(dev1) == dev2 ||
6146 	       pci_real_dma_dev(dev2) == dev1;
6147 }
6148 
pci_device_is_present(struct pci_dev * pdev)6149 bool pci_device_is_present(struct pci_dev *pdev)
6150 {
6151 	u32 v;
6152 
6153 	/* Check PF if pdev is a VF, since VF Vendor/Device IDs are 0xffff */
6154 	pdev = pci_physfn(pdev);
6155 	if (pci_dev_is_disconnected(pdev))
6156 		return false;
6157 	return pci_bus_read_dev_vendor_id(pdev->bus, pdev->devfn, &v, 0);
6158 }
6159 EXPORT_SYMBOL_GPL(pci_device_is_present);
6160 
pci_ignore_hotplug(struct pci_dev * dev)6161 void pci_ignore_hotplug(struct pci_dev *dev)
6162 {
6163 	struct pci_dev *bridge = dev->bus->self;
6164 
6165 	dev->ignore_hotplug = 1;
6166 	/* Propagate the "ignore hotplug" setting to the parent bridge. */
6167 	if (bridge)
6168 		bridge->ignore_hotplug = 1;
6169 }
6170 EXPORT_SYMBOL_GPL(pci_ignore_hotplug);
6171 
6172 /**
6173  * pci_real_dma_dev - Get PCI DMA device for PCI device
6174  * @dev: the PCI device that may have a PCI DMA alias
6175  *
6176  * Permits the platform to provide architecture-specific functionality to
6177  * devices needing to alias DMA to another PCI device on another PCI bus. If
6178  * the PCI device is on the same bus, it is recommended to use
6179  * pci_add_dma_alias(). This is the default implementation. Architecture
6180  * implementations can override this.
6181  */
pci_real_dma_dev(struct pci_dev * dev)6182 struct pci_dev __weak *pci_real_dma_dev(struct pci_dev *dev)
6183 {
6184 	return dev;
6185 }
6186 
pcibios_default_alignment(void)6187 resource_size_t __weak pcibios_default_alignment(void)
6188 {
6189 	return 0;
6190 }
6191 
6192 /*
6193  * Arches that don't want to expose struct resource to userland as-is in
6194  * sysfs and /proc can implement their own pci_resource_to_user().
6195  */
pci_resource_to_user(const struct pci_dev * dev,int bar,const struct resource * rsrc,resource_size_t * start,resource_size_t * end)6196 void __weak pci_resource_to_user(const struct pci_dev *dev, int bar,
6197 				 const struct resource *rsrc,
6198 				 resource_size_t *start, resource_size_t *end)
6199 {
6200 	*start = rsrc->start;
6201 	*end = rsrc->end;
6202 }
6203 
6204 static char *resource_alignment_param;
6205 static DEFINE_SPINLOCK(resource_alignment_lock);
6206 
6207 /**
6208  * pci_specified_resource_alignment - get resource alignment specified by user.
6209  * @dev: the PCI device to get
6210  * @resize: whether or not to change resources' size when reassigning alignment
6211  *
6212  * RETURNS: Resource alignment if it is specified.
6213  *          Zero if it is not specified.
6214  */
pci_specified_resource_alignment(struct pci_dev * dev,bool * resize)6215 static resource_size_t pci_specified_resource_alignment(struct pci_dev *dev,
6216 							bool *resize)
6217 {
6218 	int align_order, count;
6219 	resource_size_t align = pcibios_default_alignment();
6220 	const char *p;
6221 	int ret;
6222 
6223 	spin_lock(&resource_alignment_lock);
6224 	p = resource_alignment_param;
6225 	if (!p || !*p)
6226 		goto out;
6227 	if (pci_has_flag(PCI_PROBE_ONLY)) {
6228 		align = 0;
6229 		pr_info_once("PCI: Ignoring requested alignments (PCI_PROBE_ONLY)\n");
6230 		goto out;
6231 	}
6232 
6233 	while (*p) {
6234 		count = 0;
6235 		if (sscanf(p, "%d%n", &align_order, &count) == 1 &&
6236 		    p[count] == '@') {
6237 			p += count + 1;
6238 			if (align_order > 63) {
6239 				pr_err("PCI: Invalid requested alignment (order %d)\n",
6240 				       align_order);
6241 				align_order = PAGE_SHIFT;
6242 			}
6243 		} else {
6244 			align_order = PAGE_SHIFT;
6245 		}
6246 
6247 		ret = pci_dev_str_match(dev, p, &p);
6248 		if (ret == 1) {
6249 			*resize = true;
6250 			align = 1ULL << align_order;
6251 			break;
6252 		} else if (ret < 0) {
6253 			pr_err("PCI: Can't parse resource_alignment parameter: %s\n",
6254 			       p);
6255 			break;
6256 		}
6257 
6258 		if (*p != ';' && *p != ',') {
6259 			/* End of param or invalid format */
6260 			break;
6261 		}
6262 		p++;
6263 	}
6264 out:
6265 	spin_unlock(&resource_alignment_lock);
6266 	return align;
6267 }
6268 
pci_request_resource_alignment(struct pci_dev * dev,int bar,resource_size_t align,bool resize)6269 static void pci_request_resource_alignment(struct pci_dev *dev, int bar,
6270 					   resource_size_t align, bool resize)
6271 {
6272 	struct resource *r = &dev->resource[bar];
6273 	resource_size_t size;
6274 
6275 	if (!(r->flags & IORESOURCE_MEM))
6276 		return;
6277 
6278 	if (r->flags & IORESOURCE_PCI_FIXED) {
6279 		pci_info(dev, "BAR%d %pR: ignoring requested alignment %#llx\n",
6280 			 bar, r, (unsigned long long)align);
6281 		return;
6282 	}
6283 
6284 	size = resource_size(r);
6285 	if (size >= align)
6286 		return;
6287 
6288 	/*
6289 	 * Increase the alignment of the resource.  There are two ways we
6290 	 * can do this:
6291 	 *
6292 	 * 1) Increase the size of the resource.  BARs are aligned on their
6293 	 *    size, so when we reallocate space for this resource, we'll
6294 	 *    allocate it with the larger alignment.  This also prevents
6295 	 *    assignment of any other BARs inside the alignment region, so
6296 	 *    if we're requesting page alignment, this means no other BARs
6297 	 *    will share the page.
6298 	 *
6299 	 *    The disadvantage is that this makes the resource larger than
6300 	 *    the hardware BAR, which may break drivers that compute things
6301 	 *    based on the resource size, e.g., to find registers at a
6302 	 *    fixed offset before the end of the BAR.
6303 	 *
6304 	 * 2) Retain the resource size, but use IORESOURCE_STARTALIGN and
6305 	 *    set r->start to the desired alignment.  By itself this
6306 	 *    doesn't prevent other BARs being put inside the alignment
6307 	 *    region, but if we realign *every* resource of every device in
6308 	 *    the system, none of them will share an alignment region.
6309 	 *
6310 	 * When the user has requested alignment for only some devices via
6311 	 * the "pci=resource_alignment" argument, "resize" is true and we
6312 	 * use the first method.  Otherwise we assume we're aligning all
6313 	 * devices and we use the second.
6314 	 */
6315 
6316 	pci_info(dev, "BAR%d %pR: requesting alignment to %#llx\n",
6317 		 bar, r, (unsigned long long)align);
6318 
6319 	if (resize) {
6320 		r->start = 0;
6321 		r->end = align - 1;
6322 	} else {
6323 		r->flags &= ~IORESOURCE_SIZEALIGN;
6324 		r->flags |= IORESOURCE_STARTALIGN;
6325 		r->start = align;
6326 		r->end = r->start + size - 1;
6327 	}
6328 	r->flags |= IORESOURCE_UNSET;
6329 }
6330 
6331 /*
6332  * This function disables memory decoding and releases memory resources
6333  * of the device specified by kernel's boot parameter 'pci=resource_alignment='.
6334  * It also rounds up size to specified alignment.
6335  * Later on, the kernel will assign page-aligned memory resource back
6336  * to the device.
6337  */
pci_reassigndev_resource_alignment(struct pci_dev * dev)6338 void pci_reassigndev_resource_alignment(struct pci_dev *dev)
6339 {
6340 	int i;
6341 	struct resource *r;
6342 	resource_size_t align;
6343 	u16 command;
6344 	bool resize = false;
6345 
6346 	/*
6347 	 * VF BARs are read-only zero according to SR-IOV spec r1.1, sec
6348 	 * 3.4.1.11.  Their resources are allocated from the space
6349 	 * described by the VF BARx register in the PF's SR-IOV capability.
6350 	 * We can't influence their alignment here.
6351 	 */
6352 	if (dev->is_virtfn)
6353 		return;
6354 
6355 	/* check if specified PCI is target device to reassign */
6356 	align = pci_specified_resource_alignment(dev, &resize);
6357 	if (!align)
6358 		return;
6359 
6360 	if (dev->hdr_type == PCI_HEADER_TYPE_NORMAL &&
6361 	    (dev->class >> 8) == PCI_CLASS_BRIDGE_HOST) {
6362 		pci_warn(dev, "Can't reassign resources to host bridge\n");
6363 		return;
6364 	}
6365 
6366 	pci_read_config_word(dev, PCI_COMMAND, &command);
6367 	command &= ~PCI_COMMAND_MEMORY;
6368 	pci_write_config_word(dev, PCI_COMMAND, command);
6369 
6370 	for (i = 0; i <= PCI_ROM_RESOURCE; i++)
6371 		pci_request_resource_alignment(dev, i, align, resize);
6372 
6373 	/*
6374 	 * Need to disable bridge's resource window,
6375 	 * to enable the kernel to reassign new resource
6376 	 * window later on.
6377 	 */
6378 	if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
6379 		for (i = PCI_BRIDGE_RESOURCES; i < PCI_NUM_RESOURCES; i++) {
6380 			r = &dev->resource[i];
6381 			if (!(r->flags & IORESOURCE_MEM))
6382 				continue;
6383 			r->flags |= IORESOURCE_UNSET;
6384 			r->end = resource_size(r) - 1;
6385 			r->start = 0;
6386 		}
6387 		pci_disable_bridge_window(dev);
6388 	}
6389 }
6390 
resource_alignment_show(struct bus_type * bus,char * buf)6391 static ssize_t resource_alignment_show(struct bus_type *bus, char *buf)
6392 {
6393 	size_t count = 0;
6394 
6395 	spin_lock(&resource_alignment_lock);
6396 	if (resource_alignment_param)
6397 		count = scnprintf(buf, PAGE_SIZE, "%s", resource_alignment_param);
6398 	spin_unlock(&resource_alignment_lock);
6399 
6400 	/*
6401 	 * When set by the command line, resource_alignment_param will not
6402 	 * have a trailing line feed, which is ugly. So conditionally add
6403 	 * it here.
6404 	 */
6405 	if (count >= 2 && buf[count - 2] != '\n' && count < PAGE_SIZE - 1) {
6406 		buf[count - 1] = '\n';
6407 		buf[count++] = 0;
6408 	}
6409 
6410 	return count;
6411 }
6412 
resource_alignment_store(struct bus_type * bus,const char * buf,size_t count)6413 static ssize_t resource_alignment_store(struct bus_type *bus,
6414 					const char *buf, size_t count)
6415 {
6416 	char *param = kstrndup(buf, count, GFP_KERNEL);
6417 
6418 	if (!param)
6419 		return -ENOMEM;
6420 
6421 	spin_lock(&resource_alignment_lock);
6422 	kfree(resource_alignment_param);
6423 	resource_alignment_param = param;
6424 	spin_unlock(&resource_alignment_lock);
6425 	return count;
6426 }
6427 
6428 static BUS_ATTR_RW(resource_alignment);
6429 
pci_resource_alignment_sysfs_init(void)6430 static int __init pci_resource_alignment_sysfs_init(void)
6431 {
6432 	return bus_create_file(&pci_bus_type,
6433 					&bus_attr_resource_alignment);
6434 }
6435 late_initcall(pci_resource_alignment_sysfs_init);
6436 
pci_no_domains(void)6437 static void pci_no_domains(void)
6438 {
6439 #ifdef CONFIG_PCI_DOMAINS
6440 	pci_domains_supported = 0;
6441 #endif
6442 }
6443 
6444 #ifdef CONFIG_PCI_DOMAINS_GENERIC
6445 static atomic_t __domain_nr = ATOMIC_INIT(-1);
6446 
pci_get_new_domain_nr(void)6447 static int pci_get_new_domain_nr(void)
6448 {
6449 	return atomic_inc_return(&__domain_nr);
6450 }
6451 
of_pci_bus_find_domain_nr(struct device * parent)6452 static int of_pci_bus_find_domain_nr(struct device *parent)
6453 {
6454 	static int use_dt_domains = -1;
6455 	int domain = -1;
6456 
6457 	if (parent)
6458 		domain = of_get_pci_domain_nr(parent->of_node);
6459 
6460 	/*
6461 	 * Check DT domain and use_dt_domains values.
6462 	 *
6463 	 * If DT domain property is valid (domain >= 0) and
6464 	 * use_dt_domains != 0, the DT assignment is valid since this means
6465 	 * we have not previously allocated a domain number by using
6466 	 * pci_get_new_domain_nr(); we should also update use_dt_domains to
6467 	 * 1, to indicate that we have just assigned a domain number from
6468 	 * DT.
6469 	 *
6470 	 * If DT domain property value is not valid (ie domain < 0), and we
6471 	 * have not previously assigned a domain number from DT
6472 	 * (use_dt_domains != 1) we should assign a domain number by
6473 	 * using the:
6474 	 *
6475 	 * pci_get_new_domain_nr()
6476 	 *
6477 	 * API and update the use_dt_domains value to keep track of method we
6478 	 * are using to assign domain numbers (use_dt_domains = 0).
6479 	 *
6480 	 * All other combinations imply we have a platform that is trying
6481 	 * to mix domain numbers obtained from DT and pci_get_new_domain_nr(),
6482 	 * which is a recipe for domain mishandling and it is prevented by
6483 	 * invalidating the domain value (domain = -1) and printing a
6484 	 * corresponding error.
6485 	 */
6486 	if (domain >= 0 && use_dt_domains) {
6487 		use_dt_domains = 1;
6488 	} else if (domain < 0 && use_dt_domains != 1) {
6489 		use_dt_domains = 0;
6490 		domain = pci_get_new_domain_nr();
6491 	} else {
6492 		if (parent)
6493 			pr_err("Node %pOF has ", parent->of_node);
6494 		pr_err("Inconsistent \"linux,pci-domain\" property in DT\n");
6495 		domain = -1;
6496 	}
6497 
6498 	return domain;
6499 }
6500 
pci_bus_find_domain_nr(struct pci_bus * bus,struct device * parent)6501 int pci_bus_find_domain_nr(struct pci_bus *bus, struct device *parent)
6502 {
6503 	return acpi_disabled ? of_pci_bus_find_domain_nr(parent) :
6504 			       acpi_pci_bus_find_domain_nr(bus);
6505 }
6506 #endif
6507 
6508 /**
6509  * pci_ext_cfg_avail - can we access extended PCI config space?
6510  *
6511  * Returns 1 if we can access PCI extended config space (offsets
6512  * greater than 0xff). This is the default implementation. Architecture
6513  * implementations can override this.
6514  */
pci_ext_cfg_avail(void)6515 int __weak pci_ext_cfg_avail(void)
6516 {
6517 	return 1;
6518 }
6519 
pci_fixup_cardbus(struct pci_bus * bus)6520 void __weak pci_fixup_cardbus(struct pci_bus *bus)
6521 {
6522 }
6523 EXPORT_SYMBOL(pci_fixup_cardbus);
6524 
pci_setup(char * str)6525 static int __init pci_setup(char *str)
6526 {
6527 	while (str) {
6528 		char *k = strchr(str, ',');
6529 		if (k)
6530 			*k++ = 0;
6531 		if (*str && (str = pcibios_setup(str)) && *str) {
6532 			if (!strcmp(str, "nomsi")) {
6533 				pci_no_msi();
6534 			} else if (!strncmp(str, "noats", 5)) {
6535 				pr_info("PCIe: ATS is disabled\n");
6536 				pcie_ats_disabled = true;
6537 			} else if (!strcmp(str, "noaer")) {
6538 				pci_no_aer();
6539 			} else if (!strcmp(str, "earlydump")) {
6540 				pci_early_dump = true;
6541 			} else if (!strncmp(str, "realloc=", 8)) {
6542 				pci_realloc_get_opt(str + 8);
6543 			} else if (!strncmp(str, "realloc", 7)) {
6544 				pci_realloc_get_opt("on");
6545 			} else if (!strcmp(str, "nodomains")) {
6546 				pci_no_domains();
6547 			} else if (!strncmp(str, "noari", 5)) {
6548 				pcie_ari_disabled = true;
6549 			} else if (!strncmp(str, "cbiosize=", 9)) {
6550 				pci_cardbus_io_size = memparse(str + 9, &str);
6551 			} else if (!strncmp(str, "cbmemsize=", 10)) {
6552 				pci_cardbus_mem_size = memparse(str + 10, &str);
6553 			} else if (!strncmp(str, "resource_alignment=", 19)) {
6554 				resource_alignment_param = str + 19;
6555 			} else if (!strncmp(str, "ecrc=", 5)) {
6556 				pcie_ecrc_get_policy(str + 5);
6557 			} else if (!strncmp(str, "hpiosize=", 9)) {
6558 				pci_hotplug_io_size = memparse(str + 9, &str);
6559 			} else if (!strncmp(str, "hpmmiosize=", 11)) {
6560 				pci_hotplug_mmio_size = memparse(str + 11, &str);
6561 			} else if (!strncmp(str, "hpmmioprefsize=", 15)) {
6562 				pci_hotplug_mmio_pref_size = memparse(str + 15, &str);
6563 			} else if (!strncmp(str, "hpmemsize=", 10)) {
6564 				pci_hotplug_mmio_size = memparse(str + 10, &str);
6565 				pci_hotplug_mmio_pref_size = pci_hotplug_mmio_size;
6566 			} else if (!strncmp(str, "hpbussize=", 10)) {
6567 				pci_hotplug_bus_size =
6568 					simple_strtoul(str + 10, &str, 0);
6569 				if (pci_hotplug_bus_size > 0xff)
6570 					pci_hotplug_bus_size = DEFAULT_HOTPLUG_BUS_SIZE;
6571 			} else if (!strncmp(str, "pcie_bus_tune_off", 17)) {
6572 				pcie_bus_config = PCIE_BUS_TUNE_OFF;
6573 			} else if (!strncmp(str, "pcie_bus_safe", 13)) {
6574 				pcie_bus_config = PCIE_BUS_SAFE;
6575 			} else if (!strncmp(str, "pcie_bus_perf", 13)) {
6576 				pcie_bus_config = PCIE_BUS_PERFORMANCE;
6577 			} else if (!strncmp(str, "pcie_bus_peer2peer", 18)) {
6578 				pcie_bus_config = PCIE_BUS_PEER2PEER;
6579 			} else if (!strncmp(str, "pcie_scan_all", 13)) {
6580 				pci_add_flags(PCI_SCAN_ALL_PCIE_DEVS);
6581 			} else if (!strncmp(str, "disable_acs_redir=", 18)) {
6582 				disable_acs_redir_param = str + 18;
6583 			} else {
6584 				pr_err("PCI: Unknown option `%s'\n", str);
6585 			}
6586 		}
6587 		str = k;
6588 	}
6589 	return 0;
6590 }
6591 early_param("pci", pci_setup);
6592 
6593 /*
6594  * 'resource_alignment_param' and 'disable_acs_redir_param' are initialized
6595  * in pci_setup(), above, to point to data in the __initdata section which
6596  * will be freed after the init sequence is complete. We can't allocate memory
6597  * in pci_setup() because some architectures do not have any memory allocation
6598  * service available during an early_param() call. So we allocate memory and
6599  * copy the variable here before the init section is freed.
6600  *
6601  */
pci_realloc_setup_params(void)6602 static int __init pci_realloc_setup_params(void)
6603 {
6604 	resource_alignment_param = kstrdup(resource_alignment_param,
6605 					   GFP_KERNEL);
6606 	disable_acs_redir_param = kstrdup(disable_acs_redir_param, GFP_KERNEL);
6607 
6608 	return 0;
6609 }
6610 pure_initcall(pci_realloc_setup_params);
6611