1 // SPDX-License-Identifier: GPL-2.0
3 * PCI Bus Services, see include/linux/pci.h for further explanation.
5 * Copyright 1993 -- 1997 Drew Eckhardt, Frederic Potter,
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>
18 #include <linux/pci.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/device.h>
27 #include <linux/pm_runtime.h>
28 #include <linux/pci_hotplug.h>
29 #include <linux/vmalloc.h>
31 #include <linux/aer.h>
32 #include <linux/bitfield.h>
35 DEFINE_MUTEX(pci_slot_mutex);
37 const char *pci_power_names[] = {
38 "error", "D0", "D1", "D2", "D3hot", "D3cold", "unknown",
40 EXPORT_SYMBOL_GPL(pci_power_names);
43 int isa_dma_bridge_buggy;
44 EXPORT_SYMBOL(isa_dma_bridge_buggy);
48 EXPORT_SYMBOL(pci_pci_problems);
50 unsigned int pci_pm_d3hot_delay;
52 static void pci_pme_list_scan(struct work_struct *work);
54 static LIST_HEAD(pci_pme_list);
55 static DEFINE_MUTEX(pci_pme_list_mutex);
56 static DECLARE_DELAYED_WORK(pci_pme_work, pci_pme_list_scan);
58 struct pci_pme_device {
59 struct list_head list;
63 #define PME_TIMEOUT 1000 /* How long between PME checks */
66 * Following exit from Conventional Reset, devices must be ready within 1 sec
67 * (PCIe r6.0 sec 6.6.1). A D3cold to D0 transition implies a Conventional
68 * Reset (PCIe r6.0 sec 5.8).
70 #define PCI_RESET_WAIT 1000 /* msec */
73 * Devices may extend the 1 sec period through Request Retry Status
74 * completions (PCIe r6.0 sec 2.3.1). The spec does not provide an upper
75 * limit, but 60 sec ought to be enough for any device to become
78 #define PCIE_RESET_READY_POLL_MS 60000 /* msec */
80 static void pci_dev_d3_sleep(struct pci_dev *dev)
82 unsigned int delay_ms = max(dev->d3hot_delay, pci_pm_d3hot_delay);
86 /* Use a 20% upper bound, 1ms minimum */
87 upper = max(DIV_ROUND_CLOSEST(delay_ms, 5), 1U);
88 usleep_range(delay_ms * USEC_PER_MSEC,
89 (delay_ms + upper) * USEC_PER_MSEC);
93 bool pci_reset_supported(struct pci_dev *dev)
95 return dev->reset_methods[0] != 0;
98 #ifdef CONFIG_PCI_DOMAINS
99 int pci_domains_supported = 1;
102 #define DEFAULT_CARDBUS_IO_SIZE (256)
103 #define DEFAULT_CARDBUS_MEM_SIZE (64*1024*1024)
104 /* pci=cbmemsize=nnM,cbiosize=nn can override this */
105 unsigned long pci_cardbus_io_size = DEFAULT_CARDBUS_IO_SIZE;
106 unsigned long pci_cardbus_mem_size = DEFAULT_CARDBUS_MEM_SIZE;
108 #define DEFAULT_HOTPLUG_IO_SIZE (256)
109 #define DEFAULT_HOTPLUG_MMIO_SIZE (2*1024*1024)
110 #define DEFAULT_HOTPLUG_MMIO_PREF_SIZE (2*1024*1024)
111 /* hpiosize=nn can override this */
112 unsigned long pci_hotplug_io_size = DEFAULT_HOTPLUG_IO_SIZE;
114 * pci=hpmmiosize=nnM overrides non-prefetchable MMIO size,
115 * pci=hpmmioprefsize=nnM overrides prefetchable MMIO size;
116 * pci=hpmemsize=nnM overrides both
118 unsigned long pci_hotplug_mmio_size = DEFAULT_HOTPLUG_MMIO_SIZE;
119 unsigned long pci_hotplug_mmio_pref_size = DEFAULT_HOTPLUG_MMIO_PREF_SIZE;
121 #define DEFAULT_HOTPLUG_BUS_SIZE 1
122 unsigned long pci_hotplug_bus_size = DEFAULT_HOTPLUG_BUS_SIZE;
125 /* PCIe MPS/MRRS strategy; can be overridden by kernel command-line param */
126 #ifdef CONFIG_PCIE_BUS_TUNE_OFF
127 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_TUNE_OFF;
128 #elif defined CONFIG_PCIE_BUS_SAFE
129 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_SAFE;
130 #elif defined CONFIG_PCIE_BUS_PERFORMANCE
131 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_PERFORMANCE;
132 #elif defined CONFIG_PCIE_BUS_PEER2PEER
133 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_PEER2PEER;
135 enum pcie_bus_config_types pcie_bus_config = PCIE_BUS_DEFAULT;
139 * The default CLS is used if arch didn't set CLS explicitly and not
140 * all pci devices agree on the same value. Arch can override either
141 * the dfl or actual value as it sees fit. Don't forget this is
142 * measured in 32-bit words, not bytes.
144 u8 pci_dfl_cache_line_size __ro_after_init = L1_CACHE_BYTES >> 2;
145 u8 pci_cache_line_size __ro_after_init ;
148 * If we set up a device for bus mastering, we need to check the latency
149 * timer as certain BIOSes forget to set it properly.
151 unsigned int pcibios_max_latency = 255;
153 /* If set, the PCIe ARI capability will not be used. */
154 static bool pcie_ari_disabled;
156 /* If set, the PCIe ATS capability will not be used. */
157 static bool pcie_ats_disabled;
159 /* If set, the PCI config space of each device is printed during boot. */
162 bool pci_ats_disabled(void)
164 return pcie_ats_disabled;
166 EXPORT_SYMBOL_GPL(pci_ats_disabled);
168 /* Disable bridge_d3 for all PCIe ports */
169 static bool pci_bridge_d3_disable;
170 /* Force bridge_d3 for all PCIe ports */
171 static bool pci_bridge_d3_force;
173 static int __init pcie_port_pm_setup(char *str)
175 if (!strcmp(str, "off"))
176 pci_bridge_d3_disable = true;
177 else if (!strcmp(str, "force"))
178 pci_bridge_d3_force = true;
181 __setup("pcie_port_pm=", pcie_port_pm_setup);
184 * pci_bus_max_busnr - returns maximum PCI bus number of given bus' children
185 * @bus: pointer to PCI bus structure to search
187 * Given a PCI bus, returns the highest PCI bus number present in the set
188 * including the given PCI bus and its list of child PCI buses.
190 unsigned char pci_bus_max_busnr(struct pci_bus *bus)
193 unsigned char max, n;
195 max = bus->busn_res.end;
196 list_for_each_entry(tmp, &bus->children, node) {
197 n = pci_bus_max_busnr(tmp);
203 EXPORT_SYMBOL_GPL(pci_bus_max_busnr);
206 * pci_status_get_and_clear_errors - return and clear error bits in PCI_STATUS
207 * @pdev: the PCI device
209 * Returns error bits set in PCI_STATUS and clears them.
211 int pci_status_get_and_clear_errors(struct pci_dev *pdev)
216 ret = pci_read_config_word(pdev, PCI_STATUS, &status);
217 if (ret != PCIBIOS_SUCCESSFUL)
220 status &= PCI_STATUS_ERROR_BITS;
222 pci_write_config_word(pdev, PCI_STATUS, status);
226 EXPORT_SYMBOL_GPL(pci_status_get_and_clear_errors);
228 #ifdef CONFIG_HAS_IOMEM
229 static void __iomem *__pci_ioremap_resource(struct pci_dev *pdev, int bar,
232 struct resource *res = &pdev->resource[bar];
233 resource_size_t start = res->start;
234 resource_size_t size = resource_size(res);
237 * Make sure the BAR is actually a memory resource, not an IO resource
239 if (res->flags & IORESOURCE_UNSET || !(res->flags & IORESOURCE_MEM)) {
240 pci_err(pdev, "can't ioremap BAR %d: %pR\n", bar, res);
245 return ioremap_wc(start, size);
247 return ioremap(start, size);
250 void __iomem *pci_ioremap_bar(struct pci_dev *pdev, int bar)
252 return __pci_ioremap_resource(pdev, bar, false);
254 EXPORT_SYMBOL_GPL(pci_ioremap_bar);
256 void __iomem *pci_ioremap_wc_bar(struct pci_dev *pdev, int bar)
258 return __pci_ioremap_resource(pdev, bar, true);
260 EXPORT_SYMBOL_GPL(pci_ioremap_wc_bar);
264 * pci_dev_str_match_path - test if a path string matches a device
265 * @dev: the PCI device to test
266 * @path: string to match the device against
267 * @endptr: pointer to the string after the match
269 * Test if a string (typically from a kernel parameter) formatted as a
270 * path of device/function addresses matches a PCI device. The string must
273 * [<domain>:]<bus>:<device>.<func>[/<device>.<func>]*
275 * A path for a device can be obtained using 'lspci -t'. Using a path
276 * is more robust against bus renumbering than using only a single bus,
277 * device and function address.
279 * Returns 1 if the string matches the device, 0 if it does not and
280 * a negative error code if it fails to parse the string.
282 static int pci_dev_str_match_path(struct pci_dev *dev, const char *path,
286 unsigned int seg, bus, slot, func;
290 *endptr = strchrnul(path, ';');
292 wpath = kmemdup_nul(path, *endptr - path, GFP_ATOMIC);
297 p = strrchr(wpath, '/');
300 ret = sscanf(p, "/%x.%x%c", &slot, &func, &end);
306 if (dev->devfn != PCI_DEVFN(slot, func)) {
312 * Note: we don't need to get a reference to the upstream
313 * bridge because we hold a reference to the top level
314 * device which should hold a reference to the bridge,
317 dev = pci_upstream_bridge(dev);
326 ret = sscanf(wpath, "%x:%x:%x.%x%c", &seg, &bus, &slot,
330 ret = sscanf(wpath, "%x:%x.%x%c", &bus, &slot, &func, &end);
337 ret = (seg == pci_domain_nr(dev->bus) &&
338 bus == dev->bus->number &&
339 dev->devfn == PCI_DEVFN(slot, func));
347 * pci_dev_str_match - test if a string matches a device
348 * @dev: the PCI device to test
349 * @p: string to match the device against
350 * @endptr: pointer to the string after the match
352 * Test if a string (typically from a kernel parameter) matches a specified
353 * PCI device. The string may be of one of the following formats:
355 * [<domain>:]<bus>:<device>.<func>[/<device>.<func>]*
356 * pci:<vendor>:<device>[:<subvendor>:<subdevice>]
358 * The first format specifies a PCI bus/device/function address which
359 * may change if new hardware is inserted, if motherboard firmware changes,
360 * or due to changes caused in kernel parameters. If the domain is
361 * left unspecified, it is taken to be 0. In order to be robust against
362 * bus renumbering issues, a path of PCI device/function numbers may be used
363 * to address the specific device. The path for a device can be determined
364 * through the use of 'lspci -t'.
366 * The second format matches devices using IDs in the configuration
367 * space which may match multiple devices in the system. A value of 0
368 * for any field will match all devices. (Note: this differs from
369 * in-kernel code that uses PCI_ANY_ID which is ~0; this is for
370 * legacy reasons and convenience so users don't have to specify
371 * FFFFFFFFs on the command line.)
373 * Returns 1 if the string matches the device, 0 if it does not and
374 * a negative error code if the string cannot be parsed.
376 static int pci_dev_str_match(struct pci_dev *dev, const char *p,
381 unsigned short vendor, device, subsystem_vendor, subsystem_device;
383 if (strncmp(p, "pci:", 4) == 0) {
384 /* PCI vendor/device (subvendor/subdevice) IDs are specified */
386 ret = sscanf(p, "%hx:%hx:%hx:%hx%n", &vendor, &device,
387 &subsystem_vendor, &subsystem_device, &count);
389 ret = sscanf(p, "%hx:%hx%n", &vendor, &device, &count);
393 subsystem_vendor = 0;
394 subsystem_device = 0;
399 if ((!vendor || vendor == dev->vendor) &&
400 (!device || device == dev->device) &&
401 (!subsystem_vendor ||
402 subsystem_vendor == dev->subsystem_vendor) &&
403 (!subsystem_device ||
404 subsystem_device == dev->subsystem_device))
408 * PCI Bus, Device, Function IDs are specified
409 * (optionally, may include a path of devfns following it)
411 ret = pci_dev_str_match_path(dev, p, &p);
426 static u8 __pci_find_next_cap_ttl(struct pci_bus *bus, unsigned int devfn,
427 u8 pos, int cap, int *ttl)
432 pci_bus_read_config_byte(bus, devfn, pos, &pos);
438 pci_bus_read_config_word(bus, devfn, pos, &ent);
450 static u8 __pci_find_next_cap(struct pci_bus *bus, unsigned int devfn,
453 int ttl = PCI_FIND_CAP_TTL;
455 return __pci_find_next_cap_ttl(bus, devfn, pos, cap, &ttl);
458 u8 pci_find_next_capability(struct pci_dev *dev, u8 pos, int cap)
460 return __pci_find_next_cap(dev->bus, dev->devfn,
461 pos + PCI_CAP_LIST_NEXT, cap);
463 EXPORT_SYMBOL_GPL(pci_find_next_capability);
465 static u8 __pci_bus_find_cap_start(struct pci_bus *bus,
466 unsigned int devfn, u8 hdr_type)
470 pci_bus_read_config_word(bus, devfn, PCI_STATUS, &status);
471 if (!(status & PCI_STATUS_CAP_LIST))
475 case PCI_HEADER_TYPE_NORMAL:
476 case PCI_HEADER_TYPE_BRIDGE:
477 return PCI_CAPABILITY_LIST;
478 case PCI_HEADER_TYPE_CARDBUS:
479 return PCI_CB_CAPABILITY_LIST;
486 * pci_find_capability - query for devices' capabilities
487 * @dev: PCI device to query
488 * @cap: capability code
490 * Tell if a device supports a given PCI capability.
491 * Returns the address of the requested capability structure within the
492 * device's PCI configuration space or 0 in case the device does not
493 * support it. Possible values for @cap include:
495 * %PCI_CAP_ID_PM Power Management
496 * %PCI_CAP_ID_AGP Accelerated Graphics Port
497 * %PCI_CAP_ID_VPD Vital Product Data
498 * %PCI_CAP_ID_SLOTID Slot Identification
499 * %PCI_CAP_ID_MSI Message Signalled Interrupts
500 * %PCI_CAP_ID_CHSWP CompactPCI HotSwap
501 * %PCI_CAP_ID_PCIX PCI-X
502 * %PCI_CAP_ID_EXP PCI Express
504 u8 pci_find_capability(struct pci_dev *dev, int cap)
508 pos = __pci_bus_find_cap_start(dev->bus, dev->devfn, dev->hdr_type);
510 pos = __pci_find_next_cap(dev->bus, dev->devfn, pos, cap);
514 EXPORT_SYMBOL(pci_find_capability);
517 * pci_bus_find_capability - query for devices' capabilities
518 * @bus: the PCI bus to query
519 * @devfn: PCI device to query
520 * @cap: capability code
522 * Like pci_find_capability() but works for PCI devices that do not have a
523 * pci_dev structure set up yet.
525 * Returns the address of the requested capability structure within the
526 * device's PCI configuration space or 0 in case the device does not
529 u8 pci_bus_find_capability(struct pci_bus *bus, unsigned int devfn, int cap)
533 pci_bus_read_config_byte(bus, devfn, PCI_HEADER_TYPE, &hdr_type);
535 pos = __pci_bus_find_cap_start(bus, devfn, hdr_type & PCI_HEADER_TYPE_MASK);
537 pos = __pci_find_next_cap(bus, devfn, pos, cap);
541 EXPORT_SYMBOL(pci_bus_find_capability);
544 * pci_find_next_ext_capability - Find an extended capability
545 * @dev: PCI device to query
546 * @start: address at which to start looking (0 to start at beginning of list)
547 * @cap: capability code
549 * Returns the address of the next matching extended capability structure
550 * within the device's PCI configuration space or 0 if the device does
551 * not support it. Some capabilities can occur several times, e.g., the
552 * vendor-specific capability, and this provides a way to find them all.
554 u16 pci_find_next_ext_capability(struct pci_dev *dev, u16 start, int cap)
558 u16 pos = PCI_CFG_SPACE_SIZE;
560 /* minimum 8 bytes per capability */
561 ttl = (PCI_CFG_SPACE_EXP_SIZE - PCI_CFG_SPACE_SIZE) / 8;
563 if (dev->cfg_size <= PCI_CFG_SPACE_SIZE)
569 if (pci_read_config_dword(dev, pos, &header) != PCIBIOS_SUCCESSFUL)
573 * If we have no capabilities, this is indicated by cap ID,
574 * cap version and next pointer all being 0.
580 if (PCI_EXT_CAP_ID(header) == cap && pos != start)
583 pos = PCI_EXT_CAP_NEXT(header);
584 if (pos < PCI_CFG_SPACE_SIZE)
587 if (pci_read_config_dword(dev, pos, &header) != PCIBIOS_SUCCESSFUL)
593 EXPORT_SYMBOL_GPL(pci_find_next_ext_capability);
596 * pci_find_ext_capability - Find an extended capability
597 * @dev: PCI device to query
598 * @cap: capability code
600 * Returns the address of the requested extended capability structure
601 * within the device's PCI configuration space or 0 if the device does
602 * not support it. Possible values for @cap include:
604 * %PCI_EXT_CAP_ID_ERR Advanced Error Reporting
605 * %PCI_EXT_CAP_ID_VC Virtual Channel
606 * %PCI_EXT_CAP_ID_DSN Device Serial Number
607 * %PCI_EXT_CAP_ID_PWR Power Budgeting
609 u16 pci_find_ext_capability(struct pci_dev *dev, int cap)
611 return pci_find_next_ext_capability(dev, 0, cap);
613 EXPORT_SYMBOL_GPL(pci_find_ext_capability);
616 * pci_get_dsn - Read and return the 8-byte Device Serial Number
617 * @dev: PCI device to query
619 * Looks up the PCI_EXT_CAP_ID_DSN and reads the 8 bytes of the Device Serial
622 * Returns the DSN, or zero if the capability does not exist.
624 u64 pci_get_dsn(struct pci_dev *dev)
630 pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_DSN);
635 * The Device Serial Number is two dwords offset 4 bytes from the
636 * capability position. The specification says that the first dword is
637 * the lower half, and the second dword is the upper half.
640 pci_read_config_dword(dev, pos, &dword);
642 pci_read_config_dword(dev, pos + 4, &dword);
643 dsn |= ((u64)dword) << 32;
647 EXPORT_SYMBOL_GPL(pci_get_dsn);
649 static u8 __pci_find_next_ht_cap(struct pci_dev *dev, u8 pos, int ht_cap)
651 int rc, ttl = PCI_FIND_CAP_TTL;
654 if (ht_cap == HT_CAPTYPE_SLAVE || ht_cap == HT_CAPTYPE_HOST)
655 mask = HT_3BIT_CAP_MASK;
657 mask = HT_5BIT_CAP_MASK;
659 pos = __pci_find_next_cap_ttl(dev->bus, dev->devfn, pos,
660 PCI_CAP_ID_HT, &ttl);
662 rc = pci_read_config_byte(dev, pos + 3, &cap);
663 if (rc != PCIBIOS_SUCCESSFUL)
666 if ((cap & mask) == ht_cap)
669 pos = __pci_find_next_cap_ttl(dev->bus, dev->devfn,
670 pos + PCI_CAP_LIST_NEXT,
671 PCI_CAP_ID_HT, &ttl);
678 * pci_find_next_ht_capability - query a device's HyperTransport capabilities
679 * @dev: PCI device to query
680 * @pos: Position from which to continue searching
681 * @ht_cap: HyperTransport capability code
683 * To be used in conjunction with pci_find_ht_capability() to search for
684 * all capabilities matching @ht_cap. @pos should always be a value returned
685 * from pci_find_ht_capability().
687 * NB. To be 100% safe against broken PCI devices, the caller should take
688 * steps to avoid an infinite loop.
690 u8 pci_find_next_ht_capability(struct pci_dev *dev, u8 pos, int ht_cap)
692 return __pci_find_next_ht_cap(dev, pos + PCI_CAP_LIST_NEXT, ht_cap);
694 EXPORT_SYMBOL_GPL(pci_find_next_ht_capability);
697 * pci_find_ht_capability - query a device's HyperTransport capabilities
698 * @dev: PCI device to query
699 * @ht_cap: HyperTransport capability code
701 * Tell if a device supports a given HyperTransport capability.
702 * Returns an address within the device's PCI configuration space
703 * or 0 in case the device does not support the request capability.
704 * The address points to the PCI capability, of type PCI_CAP_ID_HT,
705 * which has a HyperTransport capability matching @ht_cap.
707 u8 pci_find_ht_capability(struct pci_dev *dev, int ht_cap)
711 pos = __pci_bus_find_cap_start(dev->bus, dev->devfn, dev->hdr_type);
713 pos = __pci_find_next_ht_cap(dev, pos, ht_cap);
717 EXPORT_SYMBOL_GPL(pci_find_ht_capability);
720 * pci_find_vsec_capability - Find a vendor-specific extended capability
721 * @dev: PCI device to query
722 * @vendor: Vendor ID for which capability is defined
723 * @cap: Vendor-specific capability ID
725 * If @dev has Vendor ID @vendor, search for a VSEC capability with
726 * VSEC ID @cap. If found, return the capability offset in
727 * config space; otherwise return 0.
729 u16 pci_find_vsec_capability(struct pci_dev *dev, u16 vendor, int cap)
735 if (vendor != dev->vendor)
738 while ((vsec = pci_find_next_ext_capability(dev, vsec,
739 PCI_EXT_CAP_ID_VNDR))) {
740 ret = pci_read_config_dword(dev, vsec + PCI_VNDR_HEADER, &header);
741 if (ret != PCIBIOS_SUCCESSFUL)
744 if (PCI_VNDR_HEADER_ID(header) == cap)
750 EXPORT_SYMBOL_GPL(pci_find_vsec_capability);
753 * pci_find_dvsec_capability - Find DVSEC for vendor
754 * @dev: PCI device to query
755 * @vendor: Vendor ID to match for the DVSEC
756 * @dvsec: Designated Vendor-specific capability ID
758 * If DVSEC has Vendor ID @vendor and DVSEC ID @dvsec return the capability
759 * offset in config space; otherwise return 0.
761 u16 pci_find_dvsec_capability(struct pci_dev *dev, u16 vendor, u16 dvsec)
765 pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_DVSEC);
772 pci_read_config_word(dev, pos + PCI_DVSEC_HEADER1, &v);
773 pci_read_config_word(dev, pos + PCI_DVSEC_HEADER2, &id);
774 if (vendor == v && dvsec == id)
777 pos = pci_find_next_ext_capability(dev, pos, PCI_EXT_CAP_ID_DVSEC);
782 EXPORT_SYMBOL_GPL(pci_find_dvsec_capability);
785 * pci_find_parent_resource - return resource region of parent bus of given
787 * @dev: PCI device structure contains resources to be searched
788 * @res: child resource record for which parent is sought
790 * For given resource region of given device, return the resource region of
791 * parent bus the given region is contained in.
793 struct resource *pci_find_parent_resource(const struct pci_dev *dev,
794 struct resource *res)
796 const struct pci_bus *bus = dev->bus;
799 pci_bus_for_each_resource(bus, r) {
802 if (resource_contains(r, res)) {
805 * If the window is prefetchable but the BAR is
806 * not, the allocator made a mistake.
808 if (r->flags & IORESOURCE_PREFETCH &&
809 !(res->flags & IORESOURCE_PREFETCH))
813 * If we're below a transparent bridge, there may
814 * be both a positively-decoded aperture and a
815 * subtractively-decoded region that contain the BAR.
816 * We want the positively-decoded one, so this depends
817 * on pci_bus_for_each_resource() giving us those
825 EXPORT_SYMBOL(pci_find_parent_resource);
828 * pci_find_resource - Return matching PCI device resource
829 * @dev: PCI device to query
830 * @res: Resource to look for
832 * Goes over standard PCI resources (BARs) and checks if the given resource
833 * is partially or fully contained in any of them. In that case the
834 * matching resource is returned, %NULL otherwise.
836 struct resource *pci_find_resource(struct pci_dev *dev, struct resource *res)
840 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
841 struct resource *r = &dev->resource[i];
843 if (r->start && resource_contains(r, res))
849 EXPORT_SYMBOL(pci_find_resource);
852 * pci_resource_name - Return the name of the PCI resource
853 * @dev: PCI device to query
854 * @i: index of the resource
856 * Return the standard PCI resource (BAR) name according to their index.
858 const char *pci_resource_name(struct pci_dev *dev, unsigned int i)
860 static const char * const bar_name[] = {
868 #ifdef CONFIG_PCI_IOV
876 "bridge window", /* "io" included in %pR */
877 "bridge window", /* "mem" included in %pR */
878 "bridge window", /* "mem pref" included in %pR */
880 static const char * const cardbus_name[] = {
887 #ifdef CONFIG_PCI_IOV
895 "CardBus bridge window 0", /* I/O */
896 "CardBus bridge window 1", /* I/O */
897 "CardBus bridge window 0", /* mem */
898 "CardBus bridge window 1", /* mem */
901 if (dev->hdr_type == PCI_HEADER_TYPE_CARDBUS &&
902 i < ARRAY_SIZE(cardbus_name))
903 return cardbus_name[i];
905 if (i < ARRAY_SIZE(bar_name))
912 * pci_wait_for_pending - wait for @mask bit(s) to clear in status word @pos
913 * @dev: the PCI device to operate on
914 * @pos: config space offset of status word
915 * @mask: mask of bit(s) to care about in status word
917 * Return 1 when mask bit(s) in status word clear, 0 otherwise.
919 int pci_wait_for_pending(struct pci_dev *dev, int pos, u16 mask)
923 /* Wait for Transaction Pending bit clean */
924 for (i = 0; i < 4; i++) {
927 msleep((1 << (i - 1)) * 100);
929 pci_read_config_word(dev, pos, &status);
930 if (!(status & mask))
937 static int pci_acs_enable;
940 * pci_request_acs - ask for ACS to be enabled if supported
942 void pci_request_acs(void)
947 static const char *disable_acs_redir_param;
948 static const char *config_acs_param;
956 static void __pci_config_acs(struct pci_dev *dev, struct pci_acs *caps,
957 const char *p, u16 mask, u16 flags)
967 /* Check for ACS flags */
968 delimit = strstr(p, "@");
973 end = delimit - p - 1;
976 if (*(p + end) == '0') {
980 } else if (*(p + end) == '1') {
985 } else if ((*(p + end) == 'x') || (*(p + end) == 'X')) {
989 pci_err(dev, "Invalid ACS flags... Ignoring\n");
995 pci_err(dev, "ACS Flags missing\n");
1000 if (mask & ~(PCI_ACS_SV | PCI_ACS_TB | PCI_ACS_RR | PCI_ACS_CR |
1001 PCI_ACS_UF | PCI_ACS_EC | PCI_ACS_DT)) {
1002 pci_err(dev, "Invalid ACS flags specified\n");
1006 ret = pci_dev_str_match(dev, p, &p);
1008 pr_info_once("PCI: Can't parse ACS command line parameter\n");
1010 } else if (ret == 1) {
1015 if (*p != ';' && *p != ',') {
1016 /* End of param or invalid format */
1025 if (!pci_dev_specific_disable_acs_redir(dev))
1028 pci_dbg(dev, "ACS mask = %#06x\n", mask);
1029 pci_dbg(dev, "ACS flags = %#06x\n", flags);
1031 /* If mask is 0 then we copy the bit from the firmware setting. */
1032 caps->ctrl = (caps->ctrl & ~mask) | (caps->fw_ctrl & mask);
1033 caps->ctrl |= flags;
1035 pci_info(dev, "Configured ACS to %#06x\n", caps->ctrl);
1039 * pci_std_enable_acs - enable ACS on devices using standard ACS capabilities
1040 * @dev: the PCI device
1041 * @caps: default ACS controls
1043 static void pci_std_enable_acs(struct pci_dev *dev, struct pci_acs *caps)
1045 /* Source Validation */
1046 caps->ctrl |= (caps->cap & PCI_ACS_SV);
1048 /* P2P Request Redirect */
1049 caps->ctrl |= (caps->cap & PCI_ACS_RR);
1051 /* P2P Completion Redirect */
1052 caps->ctrl |= (caps->cap & PCI_ACS_CR);
1054 /* Upstream Forwarding */
1055 caps->ctrl |= (caps->cap & PCI_ACS_UF);
1057 /* Enable Translation Blocking for external devices and noats */
1058 if (pci_ats_disabled() || dev->external_facing || dev->untrusted)
1059 caps->ctrl |= (caps->cap & PCI_ACS_TB);
1063 * pci_enable_acs - enable ACS if hardware support it
1064 * @dev: the PCI device
1066 static void pci_enable_acs(struct pci_dev *dev)
1068 struct pci_acs caps;
1069 bool enable_acs = false;
1072 /* If an iommu is present we start with kernel default caps */
1073 if (pci_acs_enable) {
1074 if (pci_dev_specific_enable_acs(dev))
1082 pci_read_config_word(dev, pos + PCI_ACS_CAP, &caps.cap);
1083 pci_read_config_word(dev, pos + PCI_ACS_CTRL, &caps.ctrl);
1084 caps.fw_ctrl = caps.ctrl;
1087 pci_std_enable_acs(dev, &caps);
1090 * Always apply caps from the command line, even if there is no iommu.
1091 * Trust that the admin has a reason to change the ACS settings.
1093 __pci_config_acs(dev, &caps, disable_acs_redir_param,
1094 PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_EC,
1095 ~(PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_EC));
1096 __pci_config_acs(dev, &caps, config_acs_param, 0, 0);
1098 pci_write_config_word(dev, pos + PCI_ACS_CTRL, caps.ctrl);
1102 * pci_restore_bars - restore a device's BAR values (e.g. after wake-up)
1103 * @dev: PCI device to have its BARs restored
1105 * Restore the BAR values for a given device, so as to make it
1106 * accessible by its driver.
1108 static void pci_restore_bars(struct pci_dev *dev)
1112 for (i = 0; i < PCI_BRIDGE_RESOURCES; i++)
1113 pci_update_resource(dev, i);
1116 static inline bool platform_pci_power_manageable(struct pci_dev *dev)
1118 if (pci_use_mid_pm())
1121 return acpi_pci_power_manageable(dev);
1124 static inline int platform_pci_set_power_state(struct pci_dev *dev,
1127 if (pci_use_mid_pm())
1128 return mid_pci_set_power_state(dev, t);
1130 return acpi_pci_set_power_state(dev, t);
1133 static inline pci_power_t platform_pci_get_power_state(struct pci_dev *dev)
1135 if (pci_use_mid_pm())
1136 return mid_pci_get_power_state(dev);
1138 return acpi_pci_get_power_state(dev);
1141 static inline void platform_pci_refresh_power_state(struct pci_dev *dev)
1143 if (!pci_use_mid_pm())
1144 acpi_pci_refresh_power_state(dev);
1147 static inline pci_power_t platform_pci_choose_state(struct pci_dev *dev)
1149 if (pci_use_mid_pm())
1150 return PCI_POWER_ERROR;
1152 return acpi_pci_choose_state(dev);
1155 static inline int platform_pci_set_wakeup(struct pci_dev *dev, bool enable)
1157 if (pci_use_mid_pm())
1158 return PCI_POWER_ERROR;
1160 return acpi_pci_wakeup(dev, enable);
1163 static inline bool platform_pci_need_resume(struct pci_dev *dev)
1165 if (pci_use_mid_pm())
1168 return acpi_pci_need_resume(dev);
1171 static inline bool platform_pci_bridge_d3(struct pci_dev *dev)
1173 if (pci_use_mid_pm())
1176 return acpi_pci_bridge_d3(dev);
1180 * pci_update_current_state - Read power state of given device and cache it
1181 * @dev: PCI device to handle.
1182 * @state: State to cache in case the device doesn't have the PM capability
1184 * The power state is read from the PMCSR register, which however is
1185 * inaccessible in D3cold. The platform firmware is therefore queried first
1186 * to detect accessibility of the register. In case the platform firmware
1187 * reports an incorrect state or the device isn't power manageable by the
1188 * platform at all, we try to detect D3cold by testing accessibility of the
1189 * vendor ID in config space.
1191 void pci_update_current_state(struct pci_dev *dev, pci_power_t state)
1193 if (platform_pci_get_power_state(dev) == PCI_D3cold) {
1194 dev->current_state = PCI_D3cold;
1195 } else if (dev->pm_cap) {
1198 pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
1199 if (PCI_POSSIBLE_ERROR(pmcsr)) {
1200 dev->current_state = PCI_D3cold;
1203 dev->current_state = pmcsr & PCI_PM_CTRL_STATE_MASK;
1205 dev->current_state = state;
1210 * pci_refresh_power_state - Refresh the given device's power state data
1211 * @dev: Target PCI device.
1213 * Ask the platform to refresh the devices power state information and invoke
1214 * pci_update_current_state() to update its current PCI power state.
1216 void pci_refresh_power_state(struct pci_dev *dev)
1218 platform_pci_refresh_power_state(dev);
1219 pci_update_current_state(dev, dev->current_state);
1223 * pci_platform_power_transition - Use platform to change device power state
1224 * @dev: PCI device to handle.
1225 * @state: State to put the device into.
1227 int pci_platform_power_transition(struct pci_dev *dev, pci_power_t state)
1231 error = platform_pci_set_power_state(dev, state);
1233 pci_update_current_state(dev, state);
1234 else if (!dev->pm_cap) /* Fall back to PCI_D0 */
1235 dev->current_state = PCI_D0;
1239 EXPORT_SYMBOL_GPL(pci_platform_power_transition);
1241 static int pci_resume_one(struct pci_dev *pci_dev, void *ign)
1243 pm_request_resume(&pci_dev->dev);
1248 * pci_resume_bus - Walk given bus and runtime resume devices on it
1249 * @bus: Top bus of the subtree to walk.
1251 void pci_resume_bus(struct pci_bus *bus)
1254 pci_walk_bus(bus, pci_resume_one, NULL);
1257 static int pci_dev_wait(struct pci_dev *dev, char *reset_type, int timeout)
1260 bool retrain = false;
1261 struct pci_dev *root, *bridge;
1263 root = pcie_find_root_port(dev);
1265 if (pci_is_pcie(dev)) {
1266 bridge = pci_upstream_bridge(dev);
1272 * The caller has already waited long enough after a reset that the
1273 * device should respond to config requests, but it may respond
1274 * with Request Retry Status (RRS) if it needs more time to
1277 * If the device is below a Root Port with Configuration RRS
1278 * Software Visibility enabled, reading the Vendor ID returns a
1279 * special data value if the device responded with RRS. Read the
1280 * Vendor ID until we get non-RRS status.
1282 * If there's no Root Port or Configuration RRS Software Visibility
1283 * is not enabled, the device may still respond with RRS, but
1284 * hardware may retry the config request. If no retries receive
1285 * Successful Completion, hardware generally synthesizes ~0
1286 * (PCI_ERROR_RESPONSE) data to complete the read. Reading Vendor
1287 * ID for VFs and non-existent devices also returns ~0, so read the
1288 * Command register until it returns something other than ~0.
1293 if (pci_dev_is_disconnected(dev)) {
1294 pci_dbg(dev, "disconnected; not waiting\n");
1298 if (root && root->config_rrs_sv) {
1299 pci_read_config_dword(dev, PCI_VENDOR_ID, &id);
1300 if (!pci_bus_rrs_vendor_id(id))
1303 pci_read_config_dword(dev, PCI_COMMAND, &id);
1304 if (!PCI_POSSIBLE_ERROR(id))
1308 if (delay > timeout) {
1309 pci_warn(dev, "not ready %dms after %s; giving up\n",
1310 delay - 1, reset_type);
1314 if (delay > PCI_RESET_WAIT) {
1317 if (pcie_failed_link_retrain(bridge) == 0) {
1322 pci_info(dev, "not ready %dms after %s; waiting\n",
1323 delay - 1, reset_type);
1330 if (delay > PCI_RESET_WAIT)
1331 pci_info(dev, "ready %dms after %s\n", delay - 1,
1334 pci_dbg(dev, "ready %dms after %s\n", delay - 1,
1341 * pci_power_up - Put the given device into D0
1342 * @dev: PCI device to power up
1344 * On success, return 0 or 1, depending on whether or not it is necessary to
1345 * restore the device's BARs subsequently (1 is returned in that case).
1347 * On failure, return a negative error code. Always return failure if @dev
1348 * lacks a Power Management Capability, even if the platform was able to
1349 * put the device in D0 via non-PCI means.
1351 int pci_power_up(struct pci_dev *dev)
1357 platform_pci_set_power_state(dev, PCI_D0);
1360 state = platform_pci_get_power_state(dev);
1361 if (state == PCI_UNKNOWN)
1362 dev->current_state = PCI_D0;
1364 dev->current_state = state;
1369 pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
1370 if (PCI_POSSIBLE_ERROR(pmcsr)) {
1371 pci_err(dev, "Unable to change power state from %s to D0, device inaccessible\n",
1372 pci_power_name(dev->current_state));
1373 dev->current_state = PCI_D3cold;
1377 state = pmcsr & PCI_PM_CTRL_STATE_MASK;
1379 need_restore = (state == PCI_D3hot || dev->current_state >= PCI_D3hot) &&
1380 !(pmcsr & PCI_PM_CTRL_NO_SOFT_RESET);
1382 if (state == PCI_D0)
1386 * Force the entire word to 0. This doesn't affect PME_Status, disables
1387 * PME_En, and sets PowerState to 0.
1389 pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, 0);
1391 /* Mandatory transition delays; see PCI PM 1.2. */
1392 if (state == PCI_D3hot)
1393 pci_dev_d3_sleep(dev);
1394 else if (state == PCI_D2)
1395 udelay(PCI_PM_D2_DELAY);
1398 dev->current_state = PCI_D0;
1406 * pci_set_full_power_state - Put a PCI device into D0 and update its state
1407 * @dev: PCI device to power up
1408 * @locked: whether pci_bus_sem is held
1410 * Call pci_power_up() to put @dev into D0, read from its PCI_PM_CTRL register
1411 * to confirm the state change, restore its BARs if they might be lost and
1412 * reconfigure ASPM in accordance with the new power state.
1414 * If pci_restore_state() is going to be called right after a power state change
1415 * to D0, it is more efficient to use pci_power_up() directly instead of this
1418 static int pci_set_full_power_state(struct pci_dev *dev, bool locked)
1423 ret = pci_power_up(dev);
1425 if (dev->current_state == PCI_D0)
1431 pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
1432 dev->current_state = pmcsr & PCI_PM_CTRL_STATE_MASK;
1433 if (dev->current_state != PCI_D0) {
1434 pci_info_ratelimited(dev, "Refused to change power state from %s to D0\n",
1435 pci_power_name(dev->current_state));
1436 } else if (ret > 0) {
1438 * According to section 5.4.1 of the "PCI BUS POWER MANAGEMENT
1439 * INTERFACE SPECIFICATION, REV. 1.2", a device transitioning
1440 * from D3hot to D0 _may_ perform an internal reset, thereby
1441 * going to "D0 Uninitialized" rather than "D0 Initialized".
1442 * For example, at least some versions of the 3c905B and the
1443 * 3c556B exhibit this behaviour.
1445 * At least some laptop BIOSen (e.g. the Thinkpad T21) leave
1446 * devices in a D3hot state at boot. Consequently, we need to
1447 * restore at least the BARs so that the device will be
1448 * accessible to its driver.
1450 pci_restore_bars(dev);
1454 pcie_aspm_pm_state_change(dev->bus->self, locked);
1460 * __pci_dev_set_current_state - Set current state of a PCI device
1461 * @dev: Device to handle
1462 * @data: pointer to state to be set
1464 static int __pci_dev_set_current_state(struct pci_dev *dev, void *data)
1466 pci_power_t state = *(pci_power_t *)data;
1468 dev->current_state = state;
1473 * pci_bus_set_current_state - Walk given bus and set current state of devices
1474 * @bus: Top bus of the subtree to walk.
1475 * @state: state to be set
1477 void pci_bus_set_current_state(struct pci_bus *bus, pci_power_t state)
1480 pci_walk_bus(bus, __pci_dev_set_current_state, &state);
1483 static void __pci_bus_set_current_state(struct pci_bus *bus, pci_power_t state, bool locked)
1489 pci_walk_bus_locked(bus, __pci_dev_set_current_state, &state);
1491 pci_walk_bus(bus, __pci_dev_set_current_state, &state);
1495 * pci_set_low_power_state - Put a PCI device into a low-power state.
1496 * @dev: PCI device to handle.
1497 * @state: PCI power state (D1, D2, D3hot) to put the device into.
1498 * @locked: whether pci_bus_sem is held
1500 * Use the device's PCI_PM_CTRL register to put it into a low-power state.
1503 * -EINVAL if the requested state is invalid.
1504 * -EIO if device does not support PCI PM or its PM capabilities register has a
1505 * wrong version, or device doesn't support the requested state.
1506 * 0 if device already is in the requested state.
1507 * 0 if device's power state has been successfully changed.
1509 static int pci_set_low_power_state(struct pci_dev *dev, pci_power_t state, bool locked)
1517 * Validate transition: We can enter D0 from any state, but if
1518 * we're already in a low-power state, we can only go deeper. E.g.,
1519 * we can go from D1 to D3, but we can't go directly from D3 to D1;
1520 * we'd have to go from D3 to D0, then to D1.
1522 if (dev->current_state <= PCI_D3cold && dev->current_state > state) {
1523 pci_dbg(dev, "Invalid power transition (from %s to %s)\n",
1524 pci_power_name(dev->current_state),
1525 pci_power_name(state));
1529 /* Check if this device supports the desired state */
1530 if ((state == PCI_D1 && !dev->d1_support)
1531 || (state == PCI_D2 && !dev->d2_support))
1534 pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
1535 if (PCI_POSSIBLE_ERROR(pmcsr)) {
1536 pci_err(dev, "Unable to change power state from %s to %s, device inaccessible\n",
1537 pci_power_name(dev->current_state),
1538 pci_power_name(state));
1539 dev->current_state = PCI_D3cold;
1543 pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
1546 /* Enter specified state */
1547 pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, pmcsr);
1549 /* Mandatory power management transition delays; see PCI PM 1.2. */
1550 if (state == PCI_D3hot)
1551 pci_dev_d3_sleep(dev);
1552 else if (state == PCI_D2)
1553 udelay(PCI_PM_D2_DELAY);
1555 pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
1556 dev->current_state = pmcsr & PCI_PM_CTRL_STATE_MASK;
1557 if (dev->current_state != state)
1558 pci_info_ratelimited(dev, "Refused to change power state from %s to %s\n",
1559 pci_power_name(dev->current_state),
1560 pci_power_name(state));
1563 pcie_aspm_pm_state_change(dev->bus->self, locked);
1568 static int __pci_set_power_state(struct pci_dev *dev, pci_power_t state, bool locked)
1572 /* Bound the state we're entering */
1573 if (state > PCI_D3cold)
1575 else if (state < PCI_D0)
1577 else if ((state == PCI_D1 || state == PCI_D2) && pci_no_d1d2(dev))
1580 * If the device or the parent bridge do not support PCI
1581 * PM, ignore the request if we're doing anything other
1582 * than putting it into D0 (which would only happen on
1587 /* Check if we're already there */
1588 if (dev->current_state == state)
1591 if (state == PCI_D0)
1592 return pci_set_full_power_state(dev, locked);
1595 * This device is quirked not to be put into D3, so don't put it in
1598 if (state >= PCI_D3hot && (dev->dev_flags & PCI_DEV_FLAGS_NO_D3))
1601 if (state == PCI_D3cold) {
1603 * To put the device in D3cold, put it into D3hot in the native
1604 * way, then put it into D3cold using platform ops.
1606 error = pci_set_low_power_state(dev, PCI_D3hot, locked);
1608 if (pci_platform_power_transition(dev, PCI_D3cold))
1611 /* Powering off a bridge may power off the whole hierarchy */
1612 if (dev->current_state == PCI_D3cold)
1613 __pci_bus_set_current_state(dev->subordinate, PCI_D3cold, locked);
1615 error = pci_set_low_power_state(dev, state, locked);
1617 if (pci_platform_power_transition(dev, state))
1625 * pci_set_power_state - Set the power state of a PCI device
1626 * @dev: PCI device to handle.
1627 * @state: PCI power state (D0, D1, D2, D3hot) to put the device into.
1629 * Transition a device to a new power state, using the platform firmware and/or
1630 * the device's PCI PM registers.
1633 * -EINVAL if the requested state is invalid.
1634 * -EIO if device does not support PCI PM or its PM capabilities register has a
1635 * wrong version, or device doesn't support the requested state.
1636 * 0 if the transition is to D1 or D2 but D1 and D2 are not supported.
1637 * 0 if device already is in the requested state.
1638 * 0 if the transition is to D3 but D3 is not supported.
1639 * 0 if device's power state has been successfully changed.
1641 int pci_set_power_state(struct pci_dev *dev, pci_power_t state)
1643 return __pci_set_power_state(dev, state, false);
1645 EXPORT_SYMBOL(pci_set_power_state);
1647 int pci_set_power_state_locked(struct pci_dev *dev, pci_power_t state)
1649 lockdep_assert_held(&pci_bus_sem);
1651 return __pci_set_power_state(dev, state, true);
1653 EXPORT_SYMBOL(pci_set_power_state_locked);
1655 #define PCI_EXP_SAVE_REGS 7
1657 static struct pci_cap_saved_state *_pci_find_saved_cap(struct pci_dev *pci_dev,
1658 u16 cap, bool extended)
1660 struct pci_cap_saved_state *tmp;
1662 hlist_for_each_entry(tmp, &pci_dev->saved_cap_space, next) {
1663 if (tmp->cap.cap_extended == extended && tmp->cap.cap_nr == cap)
1669 struct pci_cap_saved_state *pci_find_saved_cap(struct pci_dev *dev, char cap)
1671 return _pci_find_saved_cap(dev, cap, false);
1674 struct pci_cap_saved_state *pci_find_saved_ext_cap(struct pci_dev *dev, u16 cap)
1676 return _pci_find_saved_cap(dev, cap, true);
1679 static int pci_save_pcie_state(struct pci_dev *dev)
1682 struct pci_cap_saved_state *save_state;
1685 if (!pci_is_pcie(dev))
1688 save_state = pci_find_saved_cap(dev, PCI_CAP_ID_EXP);
1690 pci_err(dev, "buffer not found in %s\n", __func__);
1694 cap = (u16 *)&save_state->cap.data[0];
1695 pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &cap[i++]);
1696 pcie_capability_read_word(dev, PCI_EXP_LNKCTL, &cap[i++]);
1697 pcie_capability_read_word(dev, PCI_EXP_SLTCTL, &cap[i++]);
1698 pcie_capability_read_word(dev, PCI_EXP_RTCTL, &cap[i++]);
1699 pcie_capability_read_word(dev, PCI_EXP_DEVCTL2, &cap[i++]);
1700 pcie_capability_read_word(dev, PCI_EXP_LNKCTL2, &cap[i++]);
1701 pcie_capability_read_word(dev, PCI_EXP_SLTCTL2, &cap[i++]);
1703 pci_save_aspm_l1ss_state(dev);
1704 pci_save_ltr_state(dev);
1709 static void pci_restore_pcie_state(struct pci_dev *dev)
1712 struct pci_cap_saved_state *save_state;
1716 * Restore max latencies (in the LTR capability) before enabling
1717 * LTR itself in PCI_EXP_DEVCTL2.
1719 pci_restore_ltr_state(dev);
1720 pci_restore_aspm_l1ss_state(dev);
1722 save_state = pci_find_saved_cap(dev, PCI_CAP_ID_EXP);
1727 * Downstream ports reset the LTR enable bit when link goes down.
1728 * Check and re-configure the bit here before restoring device.
1729 * PCIe r5.0, sec 7.5.3.16.
1731 pci_bridge_reconfigure_ltr(dev);
1733 cap = (u16 *)&save_state->cap.data[0];
1734 pcie_capability_write_word(dev, PCI_EXP_DEVCTL, cap[i++]);
1735 pcie_capability_write_word(dev, PCI_EXP_LNKCTL, cap[i++]);
1736 pcie_capability_write_word(dev, PCI_EXP_SLTCTL, cap[i++]);
1737 pcie_capability_write_word(dev, PCI_EXP_RTCTL, cap[i++]);
1738 pcie_capability_write_word(dev, PCI_EXP_DEVCTL2, cap[i++]);
1739 pcie_capability_write_word(dev, PCI_EXP_LNKCTL2, cap[i++]);
1740 pcie_capability_write_word(dev, PCI_EXP_SLTCTL2, cap[i++]);
1743 static int pci_save_pcix_state(struct pci_dev *dev)
1746 struct pci_cap_saved_state *save_state;
1748 pos = pci_find_capability(dev, PCI_CAP_ID_PCIX);
1752 save_state = pci_find_saved_cap(dev, PCI_CAP_ID_PCIX);
1754 pci_err(dev, "buffer not found in %s\n", __func__);
1758 pci_read_config_word(dev, pos + PCI_X_CMD,
1759 (u16 *)save_state->cap.data);
1764 static void pci_restore_pcix_state(struct pci_dev *dev)
1767 struct pci_cap_saved_state *save_state;
1770 save_state = pci_find_saved_cap(dev, PCI_CAP_ID_PCIX);
1771 pos = pci_find_capability(dev, PCI_CAP_ID_PCIX);
1772 if (!save_state || !pos)
1774 cap = (u16 *)&save_state->cap.data[0];
1776 pci_write_config_word(dev, pos + PCI_X_CMD, cap[i++]);
1780 * pci_save_state - save the PCI configuration space of a device before
1782 * @dev: PCI device that we're dealing with
1784 int pci_save_state(struct pci_dev *dev)
1787 /* XXX: 100% dword access ok here? */
1788 for (i = 0; i < 16; i++) {
1789 pci_read_config_dword(dev, i * 4, &dev->saved_config_space[i]);
1790 pci_dbg(dev, "save config %#04x: %#010x\n",
1791 i * 4, dev->saved_config_space[i]);
1793 dev->state_saved = true;
1795 i = pci_save_pcie_state(dev);
1799 i = pci_save_pcix_state(dev);
1803 pci_save_dpc_state(dev);
1804 pci_save_aer_state(dev);
1805 pci_save_ptm_state(dev);
1806 pci_save_tph_state(dev);
1807 return pci_save_vc_state(dev);
1809 EXPORT_SYMBOL(pci_save_state);
1811 static void pci_restore_config_dword(struct pci_dev *pdev, int offset,
1812 u32 saved_val, int retry, bool force)
1816 pci_read_config_dword(pdev, offset, &val);
1817 if (!force && val == saved_val)
1821 pci_dbg(pdev, "restore config %#04x: %#010x -> %#010x\n",
1822 offset, val, saved_val);
1823 pci_write_config_dword(pdev, offset, saved_val);
1827 pci_read_config_dword(pdev, offset, &val);
1828 if (val == saved_val)
1835 static void pci_restore_config_space_range(struct pci_dev *pdev,
1836 int start, int end, int retry,
1841 for (index = end; index >= start; index--)
1842 pci_restore_config_dword(pdev, 4 * index,
1843 pdev->saved_config_space[index],
1847 static void pci_restore_config_space(struct pci_dev *pdev)
1849 if (pdev->hdr_type == PCI_HEADER_TYPE_NORMAL) {
1850 pci_restore_config_space_range(pdev, 10, 15, 0, false);
1851 /* Restore BARs before the command register. */
1852 pci_restore_config_space_range(pdev, 4, 9, 10, false);
1853 pci_restore_config_space_range(pdev, 0, 3, 0, false);
1854 } else if (pdev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
1855 pci_restore_config_space_range(pdev, 12, 15, 0, false);
1858 * Force rewriting of prefetch registers to avoid S3 resume
1859 * issues on Intel PCI bridges that occur when these
1860 * registers are not explicitly written.
1862 pci_restore_config_space_range(pdev, 9, 11, 0, true);
1863 pci_restore_config_space_range(pdev, 0, 8, 0, false);
1865 pci_restore_config_space_range(pdev, 0, 15, 0, false);
1869 static void pci_restore_rebar_state(struct pci_dev *pdev)
1871 unsigned int pos, nbars, i;
1874 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_REBAR);
1878 pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
1879 nbars = FIELD_GET(PCI_REBAR_CTRL_NBAR_MASK, ctrl);
1881 for (i = 0; i < nbars; i++, pos += 8) {
1882 struct resource *res;
1885 pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
1886 bar_idx = ctrl & PCI_REBAR_CTRL_BAR_IDX;
1887 res = pdev->resource + bar_idx;
1888 size = pci_rebar_bytes_to_size(resource_size(res));
1889 ctrl &= ~PCI_REBAR_CTRL_BAR_SIZE;
1890 ctrl |= FIELD_PREP(PCI_REBAR_CTRL_BAR_SIZE, size);
1891 pci_write_config_dword(pdev, pos + PCI_REBAR_CTRL, ctrl);
1896 * pci_restore_state - Restore the saved state of a PCI device
1897 * @dev: PCI device that we're dealing with
1899 void pci_restore_state(struct pci_dev *dev)
1901 if (!dev->state_saved)
1904 pci_restore_pcie_state(dev);
1905 pci_restore_pasid_state(dev);
1906 pci_restore_pri_state(dev);
1907 pci_restore_ats_state(dev);
1908 pci_restore_vc_state(dev);
1909 pci_restore_rebar_state(dev);
1910 pci_restore_dpc_state(dev);
1911 pci_restore_ptm_state(dev);
1912 pci_restore_tph_state(dev);
1914 pci_aer_clear_status(dev);
1915 pci_restore_aer_state(dev);
1917 pci_restore_config_space(dev);
1919 pci_restore_pcix_state(dev);
1920 pci_restore_msi_state(dev);
1922 /* Restore ACS and IOV configuration state */
1923 pci_enable_acs(dev);
1924 pci_restore_iov_state(dev);
1926 dev->state_saved = false;
1928 EXPORT_SYMBOL(pci_restore_state);
1930 struct pci_saved_state {
1931 u32 config_space[16];
1932 struct pci_cap_saved_data cap[];
1936 * pci_store_saved_state - Allocate and return an opaque struct containing
1937 * the device saved state.
1938 * @dev: PCI device that we're dealing with
1940 * Return NULL if no state or error.
1942 struct pci_saved_state *pci_store_saved_state(struct pci_dev *dev)
1944 struct pci_saved_state *state;
1945 struct pci_cap_saved_state *tmp;
1946 struct pci_cap_saved_data *cap;
1949 if (!dev->state_saved)
1952 size = sizeof(*state) + sizeof(struct pci_cap_saved_data);
1954 hlist_for_each_entry(tmp, &dev->saved_cap_space, next)
1955 size += sizeof(struct pci_cap_saved_data) + tmp->cap.size;
1957 state = kzalloc(size, GFP_KERNEL);
1961 memcpy(state->config_space, dev->saved_config_space,
1962 sizeof(state->config_space));
1965 hlist_for_each_entry(tmp, &dev->saved_cap_space, next) {
1966 size_t len = sizeof(struct pci_cap_saved_data) + tmp->cap.size;
1967 memcpy(cap, &tmp->cap, len);
1968 cap = (struct pci_cap_saved_data *)((u8 *)cap + len);
1970 /* Empty cap_save terminates list */
1974 EXPORT_SYMBOL_GPL(pci_store_saved_state);
1977 * pci_load_saved_state - Reload the provided save state into struct pci_dev.
1978 * @dev: PCI device that we're dealing with
1979 * @state: Saved state returned from pci_store_saved_state()
1981 int pci_load_saved_state(struct pci_dev *dev,
1982 struct pci_saved_state *state)
1984 struct pci_cap_saved_data *cap;
1986 dev->state_saved = false;
1991 memcpy(dev->saved_config_space, state->config_space,
1992 sizeof(state->config_space));
1996 struct pci_cap_saved_state *tmp;
1998 tmp = _pci_find_saved_cap(dev, cap->cap_nr, cap->cap_extended);
1999 if (!tmp || tmp->cap.size != cap->size)
2002 memcpy(tmp->cap.data, cap->data, tmp->cap.size);
2003 cap = (struct pci_cap_saved_data *)((u8 *)cap +
2004 sizeof(struct pci_cap_saved_data) + cap->size);
2007 dev->state_saved = true;
2010 EXPORT_SYMBOL_GPL(pci_load_saved_state);
2013 * pci_load_and_free_saved_state - Reload the save state pointed to by state,
2014 * and free the memory allocated for it.
2015 * @dev: PCI device that we're dealing with
2016 * @state: Pointer to saved state returned from pci_store_saved_state()
2018 int pci_load_and_free_saved_state(struct pci_dev *dev,
2019 struct pci_saved_state **state)
2021 int ret = pci_load_saved_state(dev, *state);
2026 EXPORT_SYMBOL_GPL(pci_load_and_free_saved_state);
2028 int __weak pcibios_enable_device(struct pci_dev *dev, int bars)
2030 return pci_enable_resources(dev, bars);
2033 static int pci_host_bridge_enable_device(struct pci_dev *dev)
2035 struct pci_host_bridge *host_bridge = pci_find_host_bridge(dev->bus);
2038 if (host_bridge && host_bridge->enable_device) {
2039 err = host_bridge->enable_device(host_bridge, dev);
2047 static void pci_host_bridge_disable_device(struct pci_dev *dev)
2049 struct pci_host_bridge *host_bridge = pci_find_host_bridge(dev->bus);
2051 if (host_bridge && host_bridge->disable_device)
2052 host_bridge->disable_device(host_bridge, dev);
2055 static int do_pci_enable_device(struct pci_dev *dev, int bars)
2058 struct pci_dev *bridge;
2062 err = pci_set_power_state(dev, PCI_D0);
2063 if (err < 0 && err != -EIO)
2066 bridge = pci_upstream_bridge(dev);
2068 pcie_aspm_powersave_config_link(bridge);
2070 err = pci_host_bridge_enable_device(dev);
2074 err = pcibios_enable_device(dev, bars);
2077 pci_fixup_device(pci_fixup_enable, dev);
2079 if (dev->msi_enabled || dev->msix_enabled)
2082 pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &pin);
2084 pci_read_config_word(dev, PCI_COMMAND, &cmd);
2085 if (cmd & PCI_COMMAND_INTX_DISABLE)
2086 pci_write_config_word(dev, PCI_COMMAND,
2087 cmd & ~PCI_COMMAND_INTX_DISABLE);
2093 pci_host_bridge_disable_device(dev);
2100 * pci_reenable_device - Resume abandoned device
2101 * @dev: PCI device to be resumed
2103 * NOTE: This function is a backend of pci_default_resume() and is not supposed
2104 * to be called by normal code, write proper resume handler and use it instead.
2106 int pci_reenable_device(struct pci_dev *dev)
2108 if (pci_is_enabled(dev))
2109 return do_pci_enable_device(dev, (1 << PCI_NUM_RESOURCES) - 1);
2112 EXPORT_SYMBOL(pci_reenable_device);
2114 static void pci_enable_bridge(struct pci_dev *dev)
2116 struct pci_dev *bridge;
2119 bridge = pci_upstream_bridge(dev);
2121 pci_enable_bridge(bridge);
2123 if (pci_is_enabled(dev)) {
2124 if (!dev->is_busmaster)
2125 pci_set_master(dev);
2129 retval = pci_enable_device(dev);
2131 pci_err(dev, "Error enabling bridge (%d), continuing\n",
2133 pci_set_master(dev);
2136 static int pci_enable_device_flags(struct pci_dev *dev, unsigned long flags)
2138 struct pci_dev *bridge;
2143 * Power state could be unknown at this point, either due to a fresh
2144 * boot or a device removal call. So get the current power state
2145 * so that things like MSI message writing will behave as expected
2146 * (e.g. if the device really is in D0 at enable time).
2148 pci_update_current_state(dev, dev->current_state);
2150 if (atomic_inc_return(&dev->enable_cnt) > 1)
2151 return 0; /* already enabled */
2153 bridge = pci_upstream_bridge(dev);
2155 pci_enable_bridge(bridge);
2157 /* only skip sriov related */
2158 for (i = 0; i <= PCI_ROM_RESOURCE; i++)
2159 if (dev->resource[i].flags & flags)
2161 for (i = PCI_BRIDGE_RESOURCES; i < DEVICE_COUNT_RESOURCE; i++)
2162 if (dev->resource[i].flags & flags)
2165 err = do_pci_enable_device(dev, bars);
2167 atomic_dec(&dev->enable_cnt);
2172 * pci_enable_device_mem - Initialize a device for use with Memory space
2173 * @dev: PCI device to be initialized
2175 * Initialize device before it's used by a driver. Ask low-level code
2176 * to enable Memory resources. Wake up the device if it was suspended.
2177 * Beware, this function can fail.
2179 int pci_enable_device_mem(struct pci_dev *dev)
2181 return pci_enable_device_flags(dev, IORESOURCE_MEM);
2183 EXPORT_SYMBOL(pci_enable_device_mem);
2186 * pci_enable_device - Initialize device before it's used by a driver.
2187 * @dev: PCI device to be initialized
2189 * Initialize device before it's used by a driver. Ask low-level code
2190 * to enable I/O and memory. Wake up the device if it was suspended.
2191 * Beware, this function can fail.
2193 * Note we don't actually enable the device many times if we call
2194 * this function repeatedly (we just increment the count).
2196 int pci_enable_device(struct pci_dev *dev)
2198 return pci_enable_device_flags(dev, IORESOURCE_MEM | IORESOURCE_IO);
2200 EXPORT_SYMBOL(pci_enable_device);
2203 * pcibios_device_add - provide arch specific hooks when adding device dev
2204 * @dev: the PCI device being added
2206 * Permits the platform to provide architecture specific functionality when
2207 * devices are added. This is the default implementation. Architecture
2208 * implementations can override this.
2210 int __weak pcibios_device_add(struct pci_dev *dev)
2216 * pcibios_release_device - provide arch specific hooks when releasing
2218 * @dev: the PCI device being released
2220 * Permits the platform to provide architecture specific functionality when
2221 * devices are released. This is the default implementation. Architecture
2222 * implementations can override this.
2224 void __weak pcibios_release_device(struct pci_dev *dev) {}
2227 * pcibios_disable_device - disable arch specific PCI resources for device dev
2228 * @dev: the PCI device to disable
2230 * Disables architecture specific PCI resources for the device. This
2231 * is the default implementation. Architecture implementations can
2234 void __weak pcibios_disable_device(struct pci_dev *dev) {}
2236 static void do_pci_disable_device(struct pci_dev *dev)
2240 pci_read_config_word(dev, PCI_COMMAND, &pci_command);
2241 if (pci_command & PCI_COMMAND_MASTER) {
2242 pci_command &= ~PCI_COMMAND_MASTER;
2243 pci_write_config_word(dev, PCI_COMMAND, pci_command);
2246 pcibios_disable_device(dev);
2250 * pci_disable_enabled_device - Disable device without updating enable_cnt
2251 * @dev: PCI device to disable
2253 * NOTE: This function is a backend of PCI power management routines and is
2254 * not supposed to be called drivers.
2256 void pci_disable_enabled_device(struct pci_dev *dev)
2258 if (pci_is_enabled(dev))
2259 do_pci_disable_device(dev);
2263 * pci_disable_device - Disable PCI device after use
2264 * @dev: PCI device to be disabled
2266 * Signal to the system that the PCI device is not in use by the system
2267 * anymore. This only involves disabling PCI bus-mastering, if active.
2269 * Note we don't actually disable the device until all callers of
2270 * pci_enable_device() have called pci_disable_device().
2272 void pci_disable_device(struct pci_dev *dev)
2274 dev_WARN_ONCE(&dev->dev, atomic_read(&dev->enable_cnt) <= 0,
2275 "disabling already-disabled device");
2277 if (atomic_dec_return(&dev->enable_cnt) != 0)
2280 pci_host_bridge_disable_device(dev);
2282 do_pci_disable_device(dev);
2284 dev->is_busmaster = 0;
2286 EXPORT_SYMBOL(pci_disable_device);
2289 * pcibios_set_pcie_reset_state - set reset state for device dev
2290 * @dev: the PCIe device reset
2291 * @state: Reset state to enter into
2293 * Set the PCIe reset state for the device. This is the default
2294 * implementation. Architecture implementations can override this.
2296 int __weak pcibios_set_pcie_reset_state(struct pci_dev *dev,
2297 enum pcie_reset_state state)
2303 * pci_set_pcie_reset_state - set reset state for device dev
2304 * @dev: the PCIe device reset
2305 * @state: Reset state to enter into
2307 * Sets the PCI reset state for the device.
2309 int pci_set_pcie_reset_state(struct pci_dev *dev, enum pcie_reset_state state)
2311 return pcibios_set_pcie_reset_state(dev, state);
2313 EXPORT_SYMBOL_GPL(pci_set_pcie_reset_state);
2315 #ifdef CONFIG_PCIEAER
2316 void pcie_clear_device_status(struct pci_dev *dev)
2320 pcie_capability_read_word(dev, PCI_EXP_DEVSTA, &sta);
2321 pcie_capability_write_word(dev, PCI_EXP_DEVSTA, sta);
2326 * pcie_clear_root_pme_status - Clear root port PME interrupt status.
2327 * @dev: PCIe root port or event collector.
2329 void pcie_clear_root_pme_status(struct pci_dev *dev)
2331 pcie_capability_set_dword(dev, PCI_EXP_RTSTA, PCI_EXP_RTSTA_PME);
2335 * pci_check_pme_status - Check if given device has generated PME.
2336 * @dev: Device to check.
2338 * Check the PME status of the device and if set, clear it and clear PME enable
2339 * (if set). Return 'true' if PME status and PME enable were both set or
2340 * 'false' otherwise.
2342 bool pci_check_pme_status(struct pci_dev *dev)
2351 pmcsr_pos = dev->pm_cap + PCI_PM_CTRL;
2352 pci_read_config_word(dev, pmcsr_pos, &pmcsr);
2353 if (!(pmcsr & PCI_PM_CTRL_PME_STATUS))
2356 /* Clear PME status. */
2357 pmcsr |= PCI_PM_CTRL_PME_STATUS;
2358 if (pmcsr & PCI_PM_CTRL_PME_ENABLE) {
2359 /* Disable PME to avoid interrupt flood. */
2360 pmcsr &= ~PCI_PM_CTRL_PME_ENABLE;
2364 pci_write_config_word(dev, pmcsr_pos, pmcsr);
2370 * pci_pme_wakeup - Wake up a PCI device if its PME Status bit is set.
2371 * @dev: Device to handle.
2372 * @pme_poll_reset: Whether or not to reset the device's pme_poll flag.
2374 * Check if @dev has generated PME and queue a resume request for it in that
2377 static int pci_pme_wakeup(struct pci_dev *dev, void *pme_poll_reset)
2379 if (pme_poll_reset && dev->pme_poll)
2380 dev->pme_poll = false;
2382 if (pci_check_pme_status(dev)) {
2383 pci_wakeup_event(dev);
2384 pm_request_resume(&dev->dev);
2390 * pci_pme_wakeup_bus - Walk given bus and wake up devices on it, if necessary.
2391 * @bus: Top bus of the subtree to walk.
2393 void pci_pme_wakeup_bus(struct pci_bus *bus)
2396 pci_walk_bus(bus, pci_pme_wakeup, (void *)true);
2401 * pci_pme_capable - check the capability of PCI device to generate PME#
2402 * @dev: PCI device to handle.
2403 * @state: PCI state from which device will issue PME#.
2405 bool pci_pme_capable(struct pci_dev *dev, pci_power_t state)
2410 return !!(dev->pme_support & (1 << state));
2412 EXPORT_SYMBOL(pci_pme_capable);
2414 static void pci_pme_list_scan(struct work_struct *work)
2416 struct pci_pme_device *pme_dev, *n;
2418 mutex_lock(&pci_pme_list_mutex);
2419 list_for_each_entry_safe(pme_dev, n, &pci_pme_list, list) {
2420 struct pci_dev *pdev = pme_dev->dev;
2422 if (pdev->pme_poll) {
2423 struct pci_dev *bridge = pdev->bus->self;
2424 struct device *dev = &pdev->dev;
2425 struct device *bdev = bridge ? &bridge->dev : NULL;
2429 * If we have a bridge, it should be in an active/D0
2430 * state or the configuration space of subordinate
2431 * devices may not be accessible or stable over the
2432 * course of the call.
2435 bref = pm_runtime_get_if_active(bdev);
2439 if (bridge->current_state != PCI_D0)
2444 * The device itself should be suspended but config
2445 * space must be accessible, therefore it cannot be in
2448 if (pm_runtime_suspended(dev) &&
2449 pdev->current_state != PCI_D3cold)
2450 pci_pme_wakeup(pdev, NULL);
2454 pm_runtime_put(bdev);
2456 list_del(&pme_dev->list);
2460 if (!list_empty(&pci_pme_list))
2461 queue_delayed_work(system_freezable_wq, &pci_pme_work,
2462 msecs_to_jiffies(PME_TIMEOUT));
2463 mutex_unlock(&pci_pme_list_mutex);
2466 static void __pci_pme_active(struct pci_dev *dev, bool enable)
2470 if (!dev->pme_support)
2473 pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
2474 /* Clear PME_Status by writing 1 to it and enable PME# */
2475 pmcsr |= PCI_PM_CTRL_PME_STATUS | PCI_PM_CTRL_PME_ENABLE;
2477 pmcsr &= ~PCI_PM_CTRL_PME_ENABLE;
2479 pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, pmcsr);
2483 * pci_pme_restore - Restore PME configuration after config space restore.
2484 * @dev: PCI device to update.
2486 void pci_pme_restore(struct pci_dev *dev)
2490 if (!dev->pme_support)
2493 pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
2494 if (dev->wakeup_prepared) {
2495 pmcsr |= PCI_PM_CTRL_PME_ENABLE;
2496 pmcsr &= ~PCI_PM_CTRL_PME_STATUS;
2498 pmcsr &= ~PCI_PM_CTRL_PME_ENABLE;
2499 pmcsr |= PCI_PM_CTRL_PME_STATUS;
2501 pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, pmcsr);
2505 * pci_pme_active - enable or disable PCI device's PME# function
2506 * @dev: PCI device to handle.
2507 * @enable: 'true' to enable PME# generation; 'false' to disable it.
2509 * The caller must verify that the device is capable of generating PME# before
2510 * calling this function with @enable equal to 'true'.
2512 void pci_pme_active(struct pci_dev *dev, bool enable)
2514 __pci_pme_active(dev, enable);
2517 * PCI (as opposed to PCIe) PME requires that the device have
2518 * its PME# line hooked up correctly. Not all hardware vendors
2519 * do this, so the PME never gets delivered and the device
2520 * remains asleep. The easiest way around this is to
2521 * periodically walk the list of suspended devices and check
2522 * whether any have their PME flag set. The assumption is that
2523 * we'll wake up often enough anyway that this won't be a huge
2524 * hit, and the power savings from the devices will still be a
2527 * Although PCIe uses in-band PME message instead of PME# line
2528 * to report PME, PME does not work for some PCIe devices in
2529 * reality. For example, there are devices that set their PME
2530 * status bits, but don't really bother to send a PME message;
2531 * there are PCI Express Root Ports that don't bother to
2532 * trigger interrupts when they receive PME messages from the
2533 * devices below. So PME poll is used for PCIe devices too.
2536 if (dev->pme_poll) {
2537 struct pci_pme_device *pme_dev;
2539 pme_dev = kmalloc(sizeof(struct pci_pme_device),
2542 pci_warn(dev, "can't enable PME#\n");
2546 mutex_lock(&pci_pme_list_mutex);
2547 list_add(&pme_dev->list, &pci_pme_list);
2548 if (list_is_singular(&pci_pme_list))
2549 queue_delayed_work(system_freezable_wq,
2551 msecs_to_jiffies(PME_TIMEOUT));
2552 mutex_unlock(&pci_pme_list_mutex);
2554 mutex_lock(&pci_pme_list_mutex);
2555 list_for_each_entry(pme_dev, &pci_pme_list, list) {
2556 if (pme_dev->dev == dev) {
2557 list_del(&pme_dev->list);
2562 mutex_unlock(&pci_pme_list_mutex);
2566 pci_dbg(dev, "PME# %s\n", enable ? "enabled" : "disabled");
2568 EXPORT_SYMBOL(pci_pme_active);
2571 * __pci_enable_wake - enable PCI device as wakeup event source
2572 * @dev: PCI device affected
2573 * @state: PCI state from which device will issue wakeup events
2574 * @enable: True to enable event generation; false to disable
2576 * This enables the device as a wakeup event source, or disables it.
2577 * When such events involves platform-specific hooks, those hooks are
2578 * called automatically by this routine.
2580 * Devices with legacy power management (no standard PCI PM capabilities)
2581 * always require such platform hooks.
2584 * 0 is returned on success
2585 * -EINVAL is returned if device is not supposed to wake up the system
2586 * Error code depending on the platform is returned if both the platform and
2587 * the native mechanism fail to enable the generation of wake-up events
2589 static int __pci_enable_wake(struct pci_dev *dev, pci_power_t state, bool enable)
2594 * Bridges that are not power-manageable directly only signal
2595 * wakeup on behalf of subordinate devices which is set up
2596 * elsewhere, so skip them. However, bridges that are
2597 * power-manageable may signal wakeup for themselves (for example,
2598 * on a hotplug event) and they need to be covered here.
2600 if (!pci_power_manageable(dev))
2603 /* Don't do the same thing twice in a row for one device. */
2604 if (!!enable == !!dev->wakeup_prepared)
2608 * According to "PCI System Architecture" 4th ed. by Tom Shanley & Don
2609 * Anderson we should be doing PME# wake enable followed by ACPI wake
2610 * enable. To disable wake-up we call the platform first, for symmetry.
2617 * Enable PME signaling if the device can signal PME from
2618 * D3cold regardless of whether or not it can signal PME from
2619 * the current target state, because that will allow it to
2620 * signal PME when the hierarchy above it goes into D3cold and
2621 * the device itself ends up in D3cold as a result of that.
2623 if (pci_pme_capable(dev, state) || pci_pme_capable(dev, PCI_D3cold))
2624 pci_pme_active(dev, true);
2627 error = platform_pci_set_wakeup(dev, true);
2631 dev->wakeup_prepared = true;
2633 platform_pci_set_wakeup(dev, false);
2634 pci_pme_active(dev, false);
2635 dev->wakeup_prepared = false;
2642 * pci_enable_wake - change wakeup settings for a PCI device
2643 * @pci_dev: Target device
2644 * @state: PCI state from which device will issue wakeup events
2645 * @enable: Whether or not to enable event generation
2647 * If @enable is set, check device_may_wakeup() for the device before calling
2648 * __pci_enable_wake() for it.
2650 int pci_enable_wake(struct pci_dev *pci_dev, pci_power_t state, bool enable)
2652 if (enable && !device_may_wakeup(&pci_dev->dev))
2655 return __pci_enable_wake(pci_dev, state, enable);
2657 EXPORT_SYMBOL(pci_enable_wake);
2660 * pci_wake_from_d3 - enable/disable device to wake up from D3_hot or D3_cold
2661 * @dev: PCI device to prepare
2662 * @enable: True to enable wake-up event generation; false to disable
2664 * Many drivers want the device to wake up the system from D3_hot or D3_cold
2665 * and this function allows them to set that up cleanly - pci_enable_wake()
2666 * should not be called twice in a row to enable wake-up due to PCI PM vs ACPI
2667 * ordering constraints.
2669 * This function only returns error code if the device is not allowed to wake
2670 * up the system from sleep or it is not capable of generating PME# from both
2671 * D3_hot and D3_cold and the platform is unable to enable wake-up power for it.
2673 int pci_wake_from_d3(struct pci_dev *dev, bool enable)
2675 return pci_pme_capable(dev, PCI_D3cold) ?
2676 pci_enable_wake(dev, PCI_D3cold, enable) :
2677 pci_enable_wake(dev, PCI_D3hot, enable);
2679 EXPORT_SYMBOL(pci_wake_from_d3);
2682 * pci_target_state - find an appropriate low power state for a given PCI dev
2684 * @wakeup: Whether or not wakeup functionality will be enabled for the device.
2686 * Use underlying platform code to find a supported low power state for @dev.
2687 * If the platform can't manage @dev, return the deepest state from which it
2688 * can generate wake events, based on any available PME info.
2690 static pci_power_t pci_target_state(struct pci_dev *dev, bool wakeup)
2692 if (platform_pci_power_manageable(dev)) {
2694 * Call the platform to find the target state for the device.
2696 pci_power_t state = platform_pci_choose_state(dev);
2699 case PCI_POWER_ERROR:
2705 if (pci_no_d1d2(dev))
2713 * If the device is in D3cold even though it's not power-manageable by
2714 * the platform, it may have been powered down by non-standard means.
2715 * Best to let it slumber.
2717 if (dev->current_state == PCI_D3cold)
2719 else if (!dev->pm_cap)
2722 if (wakeup && dev->pme_support) {
2723 pci_power_t state = PCI_D3hot;
2726 * Find the deepest state from which the device can generate
2729 while (state && !(dev->pme_support & (1 << state)))
2734 else if (dev->pme_support & 1)
2742 * pci_prepare_to_sleep - prepare PCI device for system-wide transition
2743 * into a sleep state
2744 * @dev: Device to handle.
2746 * Choose the power state appropriate for the device depending on whether
2747 * it can wake up the system and/or is power manageable by the platform
2748 * (PCI_D3hot is the default) and put the device into that state.
2750 int pci_prepare_to_sleep(struct pci_dev *dev)
2752 bool wakeup = device_may_wakeup(&dev->dev);
2753 pci_power_t target_state = pci_target_state(dev, wakeup);
2756 if (target_state == PCI_POWER_ERROR)
2759 pci_enable_wake(dev, target_state, wakeup);
2761 error = pci_set_power_state(dev, target_state);
2764 pci_enable_wake(dev, target_state, false);
2768 EXPORT_SYMBOL(pci_prepare_to_sleep);
2771 * pci_back_from_sleep - turn PCI device on during system-wide transition
2772 * into working state
2773 * @dev: Device to handle.
2775 * Disable device's system wake-up capability and put it into D0.
2777 int pci_back_from_sleep(struct pci_dev *dev)
2779 int ret = pci_set_power_state(dev, PCI_D0);
2784 pci_enable_wake(dev, PCI_D0, false);
2787 EXPORT_SYMBOL(pci_back_from_sleep);
2790 * pci_finish_runtime_suspend - Carry out PCI-specific part of runtime suspend.
2791 * @dev: PCI device being suspended.
2793 * Prepare @dev to generate wake-up events at run time and put it into a low
2796 int pci_finish_runtime_suspend(struct pci_dev *dev)
2798 pci_power_t target_state;
2801 target_state = pci_target_state(dev, device_can_wakeup(&dev->dev));
2802 if (target_state == PCI_POWER_ERROR)
2805 __pci_enable_wake(dev, target_state, pci_dev_run_wake(dev));
2807 error = pci_set_power_state(dev, target_state);
2810 pci_enable_wake(dev, target_state, false);
2816 * pci_dev_run_wake - Check if device can generate run-time wake-up events.
2817 * @dev: Device to check.
2819 * Return true if the device itself is capable of generating wake-up events
2820 * (through the platform or using the native PCIe PME) or if the device supports
2821 * PME and one of its upstream bridges can generate wake-up events.
2823 bool pci_dev_run_wake(struct pci_dev *dev)
2825 struct pci_bus *bus = dev->bus;
2827 if (!dev->pme_support)
2830 /* PME-capable in principle, but not from the target power state */
2831 if (!pci_pme_capable(dev, pci_target_state(dev, true)))
2834 if (device_can_wakeup(&dev->dev))
2837 while (bus->parent) {
2838 struct pci_dev *bridge = bus->self;
2840 if (device_can_wakeup(&bridge->dev))
2846 /* We have reached the root bus. */
2848 return device_can_wakeup(bus->bridge);
2852 EXPORT_SYMBOL_GPL(pci_dev_run_wake);
2855 * pci_dev_need_resume - Check if it is necessary to resume the device.
2856 * @pci_dev: Device to check.
2858 * Return 'true' if the device is not runtime-suspended or it has to be
2859 * reconfigured due to wakeup settings difference between system and runtime
2860 * suspend, or the current power state of it is not suitable for the upcoming
2861 * (system-wide) transition.
2863 bool pci_dev_need_resume(struct pci_dev *pci_dev)
2865 struct device *dev = &pci_dev->dev;
2866 pci_power_t target_state;
2868 if (!pm_runtime_suspended(dev) || platform_pci_need_resume(pci_dev))
2871 target_state = pci_target_state(pci_dev, device_may_wakeup(dev));
2874 * If the earlier platform check has not triggered, D3cold is just power
2875 * removal on top of D3hot, so no need to resume the device in that
2878 return target_state != pci_dev->current_state &&
2879 target_state != PCI_D3cold &&
2880 pci_dev->current_state != PCI_D3hot;
2884 * pci_dev_adjust_pme - Adjust PME setting for a suspended device.
2885 * @pci_dev: Device to check.
2887 * If the device is suspended and it is not configured for system wakeup,
2888 * disable PME for it to prevent it from waking up the system unnecessarily.
2890 * Note that if the device's power state is D3cold and the platform check in
2891 * pci_dev_need_resume() has not triggered, the device's configuration need not
2894 void pci_dev_adjust_pme(struct pci_dev *pci_dev)
2896 struct device *dev = &pci_dev->dev;
2898 spin_lock_irq(&dev->power.lock);
2900 if (pm_runtime_suspended(dev) && !device_may_wakeup(dev) &&
2901 pci_dev->current_state < PCI_D3cold)
2902 __pci_pme_active(pci_dev, false);
2904 spin_unlock_irq(&dev->power.lock);
2908 * pci_dev_complete_resume - Finalize resume from system sleep for a device.
2909 * @pci_dev: Device to handle.
2911 * If the device is runtime suspended and wakeup-capable, enable PME for it as
2912 * it might have been disabled during the prepare phase of system suspend if
2913 * the device was not configured for system wakeup.
2915 void pci_dev_complete_resume(struct pci_dev *pci_dev)
2917 struct device *dev = &pci_dev->dev;
2919 if (!pci_dev_run_wake(pci_dev))
2922 spin_lock_irq(&dev->power.lock);
2924 if (pm_runtime_suspended(dev) && pci_dev->current_state < PCI_D3cold)
2925 __pci_pme_active(pci_dev, true);
2927 spin_unlock_irq(&dev->power.lock);
2931 * pci_choose_state - Choose the power state of a PCI device.
2932 * @dev: Target PCI device.
2933 * @state: Target state for the whole system.
2935 * Returns PCI power state suitable for @dev and @state.
2937 pci_power_t pci_choose_state(struct pci_dev *dev, pm_message_t state)
2939 if (state.event == PM_EVENT_ON)
2942 return pci_target_state(dev, false);
2944 EXPORT_SYMBOL(pci_choose_state);
2946 void pci_config_pm_runtime_get(struct pci_dev *pdev)
2948 struct device *dev = &pdev->dev;
2949 struct device *parent = dev->parent;
2952 pm_runtime_get_sync(parent);
2953 pm_runtime_get_noresume(dev);
2955 * pdev->current_state is set to PCI_D3cold during suspending,
2956 * so wait until suspending completes
2958 pm_runtime_barrier(dev);
2960 * Only need to resume devices in D3cold, because config
2961 * registers are still accessible for devices suspended but
2964 if (pdev->current_state == PCI_D3cold)
2965 pm_runtime_resume(dev);
2968 void pci_config_pm_runtime_put(struct pci_dev *pdev)
2970 struct device *dev = &pdev->dev;
2971 struct device *parent = dev->parent;
2973 pm_runtime_put(dev);
2975 pm_runtime_put_sync(parent);
2978 static const struct dmi_system_id bridge_d3_blacklist[] = {
2982 * Gigabyte X299 root port is not marked as hotplug capable
2983 * which allows Linux to power manage it. However, this
2984 * confuses the BIOS SMI handler so don't power manage root
2985 * ports on that system.
2987 .ident = "X299 DESIGNARE EX-CF",
2989 DMI_MATCH(DMI_BOARD_VENDOR, "Gigabyte Technology Co., Ltd."),
2990 DMI_MATCH(DMI_BOARD_NAME, "X299 DESIGNARE EX-CF"),
2995 * Downstream device is not accessible after putting a root port
2996 * into D3cold and back into D0 on Elo Continental Z2 board
2998 .ident = "Elo Continental Z2",
3000 DMI_MATCH(DMI_BOARD_VENDOR, "Elo Touch Solutions"),
3001 DMI_MATCH(DMI_BOARD_NAME, "Geminilake"),
3002 DMI_MATCH(DMI_BOARD_VERSION, "Continental Z2"),
3007 * Changing power state of root port dGPU is connected fails
3008 * https://gitlab.freedesktop.org/drm/amd/-/issues/3229
3010 .ident = "Hewlett-Packard HP Pavilion 17 Notebook PC/1972",
3012 DMI_MATCH(DMI_BOARD_VENDOR, "Hewlett-Packard"),
3013 DMI_MATCH(DMI_BOARD_NAME, "1972"),
3014 DMI_MATCH(DMI_BOARD_VERSION, "95.33"),
3022 * pci_bridge_d3_possible - Is it possible to put the bridge into D3
3023 * @bridge: Bridge to check
3025 * This function checks if it is possible to move the bridge to D3.
3026 * Currently we only allow D3 for recent enough PCIe ports and Thunderbolt.
3028 bool pci_bridge_d3_possible(struct pci_dev *bridge)
3030 if (!pci_is_pcie(bridge))
3033 switch (pci_pcie_type(bridge)) {
3034 case PCI_EXP_TYPE_ROOT_PORT:
3035 case PCI_EXP_TYPE_UPSTREAM:
3036 case PCI_EXP_TYPE_DOWNSTREAM:
3037 if (pci_bridge_d3_disable)
3041 * Hotplug ports handled by firmware in System Management Mode
3042 * may not be put into D3 by the OS (Thunderbolt on non-Macs).
3044 if (bridge->is_hotplug_bridge && !pciehp_is_native(bridge))
3047 if (pci_bridge_d3_force)
3050 /* Even the oldest 2010 Thunderbolt controller supports D3. */
3051 if (bridge->is_thunderbolt)
3054 /* Platform might know better if the bridge supports D3 */
3055 if (platform_pci_bridge_d3(bridge))
3059 * Hotplug ports handled natively by the OS were not validated
3060 * by vendors for runtime D3 at least until 2018 because there
3061 * was no OS support.
3063 if (bridge->is_hotplug_bridge)
3066 if (dmi_check_system(bridge_d3_blacklist))
3070 * It should be safe to put PCIe ports from 2015 or newer
3073 if (dmi_get_bios_year() >= 2015)
3081 static int pci_dev_check_d3cold(struct pci_dev *dev, void *data)
3083 bool *d3cold_ok = data;
3085 if (/* The device needs to be allowed to go D3cold ... */
3086 dev->no_d3cold || !dev->d3cold_allowed ||
3088 /* ... and if it is wakeup capable to do so from D3cold. */
3089 (device_may_wakeup(&dev->dev) &&
3090 !pci_pme_capable(dev, PCI_D3cold)) ||
3092 /* If it is a bridge it must be allowed to go to D3. */
3093 !pci_power_manageable(dev))
3101 * pci_bridge_d3_update - Update bridge D3 capabilities
3102 * @dev: PCI device which is changed
3104 * Update upstream bridge PM capabilities accordingly depending on if the
3105 * device PM configuration was changed or the device is being removed. The
3106 * change is also propagated upstream.
3108 void pci_bridge_d3_update(struct pci_dev *dev)
3110 bool remove = !device_is_registered(&dev->dev);
3111 struct pci_dev *bridge;
3112 bool d3cold_ok = true;
3114 bridge = pci_upstream_bridge(dev);
3115 if (!bridge || !pci_bridge_d3_possible(bridge))
3119 * If D3 is currently allowed for the bridge, removing one of its
3120 * children won't change that.
3122 if (remove && bridge->bridge_d3)
3126 * If D3 is currently allowed for the bridge and a child is added or
3127 * changed, disallowance of D3 can only be caused by that child, so
3128 * we only need to check that single device, not any of its siblings.
3130 * If D3 is currently not allowed for the bridge, checking the device
3131 * first may allow us to skip checking its siblings.
3134 pci_dev_check_d3cold(dev, &d3cold_ok);
3137 * If D3 is currently not allowed for the bridge, this may be caused
3138 * either by the device being changed/removed or any of its siblings,
3139 * so we need to go through all children to find out if one of them
3140 * continues to block D3.
3142 if (d3cold_ok && !bridge->bridge_d3)
3143 pci_walk_bus(bridge->subordinate, pci_dev_check_d3cold,
3146 if (bridge->bridge_d3 != d3cold_ok) {
3147 bridge->bridge_d3 = d3cold_ok;
3148 /* Propagate change to upstream bridges */
3149 pci_bridge_d3_update(bridge);
3154 * pci_d3cold_enable - Enable D3cold for device
3155 * @dev: PCI device to handle
3157 * This function can be used in drivers to enable D3cold from the device
3158 * they handle. It also updates upstream PCI bridge PM capabilities
3161 void pci_d3cold_enable(struct pci_dev *dev)
3163 if (dev->no_d3cold) {
3164 dev->no_d3cold = false;
3165 pci_bridge_d3_update(dev);
3168 EXPORT_SYMBOL_GPL(pci_d3cold_enable);
3171 * pci_d3cold_disable - Disable D3cold for device
3172 * @dev: PCI device to handle
3174 * This function can be used in drivers to disable D3cold from the device
3175 * they handle. It also updates upstream PCI bridge PM capabilities
3178 void pci_d3cold_disable(struct pci_dev *dev)
3180 if (!dev->no_d3cold) {
3181 dev->no_d3cold = true;
3182 pci_bridge_d3_update(dev);
3185 EXPORT_SYMBOL_GPL(pci_d3cold_disable);
3188 * pci_pm_init - Initialize PM functions of given PCI device
3189 * @dev: PCI device to handle.
3191 void pci_pm_init(struct pci_dev *dev)
3197 pm_runtime_forbid(&dev->dev);
3198 pm_runtime_set_active(&dev->dev);
3199 pm_runtime_enable(&dev->dev);
3200 device_enable_async_suspend(&dev->dev);
3201 dev->wakeup_prepared = false;
3204 dev->pme_support = 0;
3206 /* find PCI PM capability in list */
3207 pm = pci_find_capability(dev, PCI_CAP_ID_PM);
3210 /* Check device's ability to generate PME# */
3211 pci_read_config_word(dev, pm + PCI_PM_PMC, &pmc);
3213 if ((pmc & PCI_PM_CAP_VER_MASK) > 3) {
3214 pci_err(dev, "unsupported PM cap regs version (%u)\n",
3215 pmc & PCI_PM_CAP_VER_MASK);
3220 dev->d3hot_delay = PCI_PM_D3HOT_WAIT;
3221 dev->d3cold_delay = PCI_PM_D3COLD_WAIT;
3222 dev->bridge_d3 = pci_bridge_d3_possible(dev);
3223 dev->d3cold_allowed = true;
3225 dev->d1_support = false;
3226 dev->d2_support = false;
3227 if (!pci_no_d1d2(dev)) {
3228 if (pmc & PCI_PM_CAP_D1)
3229 dev->d1_support = true;
3230 if (pmc & PCI_PM_CAP_D2)
3231 dev->d2_support = true;
3233 if (dev->d1_support || dev->d2_support)
3234 pci_info(dev, "supports%s%s\n",
3235 dev->d1_support ? " D1" : "",
3236 dev->d2_support ? " D2" : "");
3239 pmc &= PCI_PM_CAP_PME_MASK;
3241 pci_info(dev, "PME# supported from%s%s%s%s%s\n",
3242 (pmc & PCI_PM_CAP_PME_D0) ? " D0" : "",
3243 (pmc & PCI_PM_CAP_PME_D1) ? " D1" : "",
3244 (pmc & PCI_PM_CAP_PME_D2) ? " D2" : "",
3245 (pmc & PCI_PM_CAP_PME_D3hot) ? " D3hot" : "",
3246 (pmc & PCI_PM_CAP_PME_D3cold) ? " D3cold" : "");
3247 dev->pme_support = FIELD_GET(PCI_PM_CAP_PME_MASK, pmc);
3248 dev->pme_poll = true;
3250 * Make device's PM flags reflect the wake-up capability, but
3251 * let the user space enable it to wake up the system as needed.
3253 device_set_wakeup_capable(&dev->dev, true);
3254 /* Disable the PME# generation functionality */
3255 pci_pme_active(dev, false);
3258 pci_read_config_word(dev, PCI_STATUS, &status);
3259 if (status & PCI_STATUS_IMM_READY)
3263 static unsigned long pci_ea_flags(struct pci_dev *dev, u8 prop)
3265 unsigned long flags = IORESOURCE_PCI_FIXED | IORESOURCE_PCI_EA_BEI;
3269 case PCI_EA_P_VF_MEM:
3270 flags |= IORESOURCE_MEM;
3272 case PCI_EA_P_MEM_PREFETCH:
3273 case PCI_EA_P_VF_MEM_PREFETCH:
3274 flags |= IORESOURCE_MEM | IORESOURCE_PREFETCH;
3277 flags |= IORESOURCE_IO;
3286 static struct resource *pci_ea_get_resource(struct pci_dev *dev, u8 bei,
3289 if (bei <= PCI_EA_BEI_BAR5 && prop <= PCI_EA_P_IO)
3290 return &dev->resource[bei];
3291 #ifdef CONFIG_PCI_IOV
3292 else if (bei >= PCI_EA_BEI_VF_BAR0 && bei <= PCI_EA_BEI_VF_BAR5 &&
3293 (prop == PCI_EA_P_VF_MEM || prop == PCI_EA_P_VF_MEM_PREFETCH))
3294 return &dev->resource[PCI_IOV_RESOURCES +
3295 bei - PCI_EA_BEI_VF_BAR0];
3297 else if (bei == PCI_EA_BEI_ROM)
3298 return &dev->resource[PCI_ROM_RESOURCE];
3303 /* Read an Enhanced Allocation (EA) entry */
3304 static int pci_ea_read(struct pci_dev *dev, int offset)
3306 struct resource *res;
3307 const char *res_name;
3308 int ent_size, ent_offset = offset;
3309 resource_size_t start, end;
3310 unsigned long flags;
3311 u32 dw0, bei, base, max_offset;
3313 bool support_64 = (sizeof(resource_size_t) >= 8);
3315 pci_read_config_dword(dev, ent_offset, &dw0);
3318 /* Entry size field indicates DWORDs after 1st */
3319 ent_size = (FIELD_GET(PCI_EA_ES, dw0) + 1) << 2;
3321 if (!(dw0 & PCI_EA_ENABLE)) /* Entry not enabled */
3324 bei = FIELD_GET(PCI_EA_BEI, dw0);
3325 prop = FIELD_GET(PCI_EA_PP, dw0);
3328 * If the Property is in the reserved range, try the Secondary
3331 if (prop > PCI_EA_P_BRIDGE_IO && prop < PCI_EA_P_MEM_RESERVED)
3332 prop = FIELD_GET(PCI_EA_SP, dw0);
3333 if (prop > PCI_EA_P_BRIDGE_IO)
3336 res = pci_ea_get_resource(dev, bei, prop);
3337 res_name = pci_resource_name(dev, bei);
3339 pci_err(dev, "Unsupported EA entry BEI: %u\n", bei);
3343 flags = pci_ea_flags(dev, prop);
3345 pci_err(dev, "Unsupported EA properties: %#x\n", prop);
3350 pci_read_config_dword(dev, ent_offset, &base);
3351 start = (base & PCI_EA_FIELD_MASK);
3354 /* Read MaxOffset */
3355 pci_read_config_dword(dev, ent_offset, &max_offset);
3358 /* Read Base MSBs (if 64-bit entry) */
3359 if (base & PCI_EA_IS_64) {
3362 pci_read_config_dword(dev, ent_offset, &base_upper);
3365 flags |= IORESOURCE_MEM_64;
3367 /* entry starts above 32-bit boundary, can't use */
3368 if (!support_64 && base_upper)
3372 start |= ((u64)base_upper << 32);
3375 end = start + (max_offset | 0x03);
3377 /* Read MaxOffset MSBs (if 64-bit entry) */
3378 if (max_offset & PCI_EA_IS_64) {
3379 u32 max_offset_upper;
3381 pci_read_config_dword(dev, ent_offset, &max_offset_upper);
3384 flags |= IORESOURCE_MEM_64;
3386 /* entry too big, can't use */
3387 if (!support_64 && max_offset_upper)
3391 end += ((u64)max_offset_upper << 32);
3395 pci_err(dev, "EA Entry crosses address boundary\n");
3399 if (ent_size != ent_offset - offset) {
3400 pci_err(dev, "EA Entry Size (%d) does not match length read (%d)\n",
3401 ent_size, ent_offset - offset);
3405 res->name = pci_name(dev);
3410 if (bei <= PCI_EA_BEI_BAR5)
3411 pci_info(dev, "%s %pR: from Enhanced Allocation, properties %#02x\n",
3412 res_name, res, prop);
3413 else if (bei == PCI_EA_BEI_ROM)
3414 pci_info(dev, "%s %pR: from Enhanced Allocation, properties %#02x\n",
3415 res_name, res, prop);
3416 else if (bei >= PCI_EA_BEI_VF_BAR0 && bei <= PCI_EA_BEI_VF_BAR5)
3417 pci_info(dev, "%s %pR: from Enhanced Allocation, properties %#02x\n",
3418 res_name, res, prop);
3420 pci_info(dev, "BEI %d %pR: from Enhanced Allocation, properties %#02x\n",
3424 return offset + ent_size;
3427 /* Enhanced Allocation Initialization */
3428 void pci_ea_init(struct pci_dev *dev)
3435 /* find PCI EA capability in list */
3436 ea = pci_find_capability(dev, PCI_CAP_ID_EA);
3440 /* determine the number of entries */
3441 pci_bus_read_config_byte(dev->bus, dev->devfn, ea + PCI_EA_NUM_ENT,
3443 num_ent &= PCI_EA_NUM_ENT_MASK;
3445 offset = ea + PCI_EA_FIRST_ENT;
3447 /* Skip DWORD 2 for type 1 functions */
3448 if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE)
3451 /* parse each EA entry */
3452 for (i = 0; i < num_ent; ++i)
3453 offset = pci_ea_read(dev, offset);
3456 static void pci_add_saved_cap(struct pci_dev *pci_dev,
3457 struct pci_cap_saved_state *new_cap)
3459 hlist_add_head(&new_cap->next, &pci_dev->saved_cap_space);
3463 * _pci_add_cap_save_buffer - allocate buffer for saving given
3464 * capability registers
3465 * @dev: the PCI device
3466 * @cap: the capability to allocate the buffer for
3467 * @extended: Standard or Extended capability ID
3468 * @size: requested size of the buffer
3470 static int _pci_add_cap_save_buffer(struct pci_dev *dev, u16 cap,
3471 bool extended, unsigned int size)
3474 struct pci_cap_saved_state *save_state;
3477 pos = pci_find_ext_capability(dev, cap);
3479 pos = pci_find_capability(dev, cap);
3484 save_state = kzalloc(sizeof(*save_state) + size, GFP_KERNEL);
3488 save_state->cap.cap_nr = cap;
3489 save_state->cap.cap_extended = extended;
3490 save_state->cap.size = size;
3491 pci_add_saved_cap(dev, save_state);
3496 int pci_add_cap_save_buffer(struct pci_dev *dev, char cap, unsigned int size)
3498 return _pci_add_cap_save_buffer(dev, cap, false, size);
3501 int pci_add_ext_cap_save_buffer(struct pci_dev *dev, u16 cap, unsigned int size)
3503 return _pci_add_cap_save_buffer(dev, cap, true, size);
3507 * pci_allocate_cap_save_buffers - allocate buffers for saving capabilities
3508 * @dev: the PCI device
3510 void pci_allocate_cap_save_buffers(struct pci_dev *dev)
3514 error = pci_add_cap_save_buffer(dev, PCI_CAP_ID_EXP,
3515 PCI_EXP_SAVE_REGS * sizeof(u16));
3517 pci_err(dev, "unable to preallocate PCI Express save buffer\n");
3519 error = pci_add_cap_save_buffer(dev, PCI_CAP_ID_PCIX, sizeof(u16));
3521 pci_err(dev, "unable to preallocate PCI-X save buffer\n");
3523 error = pci_add_ext_cap_save_buffer(dev, PCI_EXT_CAP_ID_LTR,
3526 pci_err(dev, "unable to allocate suspend buffer for LTR\n");
3528 pci_allocate_vc_save_buffers(dev);
3531 void pci_free_cap_save_buffers(struct pci_dev *dev)
3533 struct pci_cap_saved_state *tmp;
3534 struct hlist_node *n;
3536 hlist_for_each_entry_safe(tmp, n, &dev->saved_cap_space, next)
3541 * pci_configure_ari - enable or disable ARI forwarding
3542 * @dev: the PCI device
3544 * If @dev and its upstream bridge both support ARI, enable ARI in the
3545 * bridge. Otherwise, disable ARI in the bridge.
3547 void pci_configure_ari(struct pci_dev *dev)
3550 struct pci_dev *bridge;
3552 if (pcie_ari_disabled || !pci_is_pcie(dev) || dev->devfn)
3555 bridge = dev->bus->self;
3559 pcie_capability_read_dword(bridge, PCI_EXP_DEVCAP2, &cap);
3560 if (!(cap & PCI_EXP_DEVCAP2_ARI))
3563 if (pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ARI)) {
3564 pcie_capability_set_word(bridge, PCI_EXP_DEVCTL2,
3565 PCI_EXP_DEVCTL2_ARI);
3566 bridge->ari_enabled = 1;
3568 pcie_capability_clear_word(bridge, PCI_EXP_DEVCTL2,
3569 PCI_EXP_DEVCTL2_ARI);
3570 bridge->ari_enabled = 0;
3574 static bool pci_acs_flags_enabled(struct pci_dev *pdev, u16 acs_flags)
3579 pos = pdev->acs_cap;
3584 * Except for egress control, capabilities are either required
3585 * or only required if controllable. Features missing from the
3586 * capability field can therefore be assumed as hard-wired enabled.
3588 pci_read_config_word(pdev, pos + PCI_ACS_CAP, &cap);
3589 acs_flags &= (cap | PCI_ACS_EC);
3591 pci_read_config_word(pdev, pos + PCI_ACS_CTRL, &ctrl);
3592 return (ctrl & acs_flags) == acs_flags;
3596 * pci_acs_enabled - test ACS against required flags for a given device
3597 * @pdev: device to test
3598 * @acs_flags: required PCI ACS flags
3600 * Return true if the device supports the provided flags. Automatically
3601 * filters out flags that are not implemented on multifunction devices.
3603 * Note that this interface checks the effective ACS capabilities of the
3604 * device rather than the actual capabilities. For instance, most single
3605 * function endpoints are not required to support ACS because they have no
3606 * opportunity for peer-to-peer access. We therefore return 'true'
3607 * regardless of whether the device exposes an ACS capability. This makes
3608 * it much easier for callers of this function to ignore the actual type
3609 * or topology of the device when testing ACS support.
3611 bool pci_acs_enabled(struct pci_dev *pdev, u16 acs_flags)
3615 ret = pci_dev_specific_acs_enabled(pdev, acs_flags);
3620 * Conventional PCI and PCI-X devices never support ACS, either
3621 * effectively or actually. The shared bus topology implies that
3622 * any device on the bus can receive or snoop DMA.
3624 if (!pci_is_pcie(pdev))
3627 switch (pci_pcie_type(pdev)) {
3629 * PCI/X-to-PCIe bridges are not specifically mentioned by the spec,
3630 * but since their primary interface is PCI/X, we conservatively
3631 * handle them as we would a non-PCIe device.
3633 case PCI_EXP_TYPE_PCIE_BRIDGE:
3635 * PCIe 3.0, 6.12.1 excludes ACS on these devices. "ACS is never
3636 * applicable... must never implement an ACS Extended Capability...".
3637 * This seems arbitrary, but we take a conservative interpretation
3638 * of this statement.
3640 case PCI_EXP_TYPE_PCI_BRIDGE:
3641 case PCI_EXP_TYPE_RC_EC:
3644 * PCIe 3.0, 6.12.1.1 specifies that downstream and root ports should
3645 * implement ACS in order to indicate their peer-to-peer capabilities,
3646 * regardless of whether they are single- or multi-function devices.
3648 case PCI_EXP_TYPE_DOWNSTREAM:
3649 case PCI_EXP_TYPE_ROOT_PORT:
3650 return pci_acs_flags_enabled(pdev, acs_flags);
3652 * PCIe 3.0, 6.12.1.2 specifies ACS capabilities that should be
3653 * implemented by the remaining PCIe types to indicate peer-to-peer
3654 * capabilities, but only when they are part of a multifunction
3655 * device. The footnote for section 6.12 indicates the specific
3656 * PCIe types included here.
3658 case PCI_EXP_TYPE_ENDPOINT:
3659 case PCI_EXP_TYPE_UPSTREAM:
3660 case PCI_EXP_TYPE_LEG_END:
3661 case PCI_EXP_TYPE_RC_END:
3662 if (!pdev->multifunction)
3665 return pci_acs_flags_enabled(pdev, acs_flags);
3669 * PCIe 3.0, 6.12.1.3 specifies no ACS capabilities are applicable
3670 * to single function devices with the exception of downstream ports.
3676 * pci_acs_path_enabled - test ACS flags from start to end in a hierarchy
3677 * @start: starting downstream device
3678 * @end: ending upstream device or NULL to search to the root bus
3679 * @acs_flags: required flags
3681 * Walk up a device tree from start to end testing PCI ACS support. If
3682 * any step along the way does not support the required flags, return false.
3684 bool pci_acs_path_enabled(struct pci_dev *start,
3685 struct pci_dev *end, u16 acs_flags)
3687 struct pci_dev *pdev, *parent = start;
3692 if (!pci_acs_enabled(pdev, acs_flags))
3695 if (pci_is_root_bus(pdev->bus))
3696 return (end == NULL);
3698 parent = pdev->bus->self;
3699 } while (pdev != end);
3705 * pci_acs_init - Initialize ACS if hardware supports it
3706 * @dev: the PCI device
3708 void pci_acs_init(struct pci_dev *dev)
3710 dev->acs_cap = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ACS);
3713 * Attempt to enable ACS regardless of capability because some Root
3714 * Ports (e.g. those quirked with *_intel_pch_acs_*) do not have
3715 * the standard ACS capability but still support ACS via those
3718 pci_enable_acs(dev);
3722 * pci_rebar_find_pos - find position of resize ctrl reg for BAR
3726 * Helper to find the position of the ctrl register for a BAR.
3727 * Returns -ENOTSUPP if resizable BARs are not supported at all.
3728 * Returns -ENOENT if no ctrl register for the BAR could be found.
3730 static int pci_rebar_find_pos(struct pci_dev *pdev, int bar)
3732 unsigned int pos, nbars, i;
3735 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_REBAR);
3739 pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
3740 nbars = FIELD_GET(PCI_REBAR_CTRL_NBAR_MASK, ctrl);
3742 for (i = 0; i < nbars; i++, pos += 8) {
3745 pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
3746 bar_idx = FIELD_GET(PCI_REBAR_CTRL_BAR_IDX, ctrl);
3755 * pci_rebar_get_possible_sizes - get possible sizes for BAR
3757 * @bar: BAR to query
3759 * Get the possible sizes of a resizable BAR as bitmask defined in the spec
3760 * (bit 0=1MB, bit 19=512GB). Returns 0 if BAR isn't resizable.
3762 u32 pci_rebar_get_possible_sizes(struct pci_dev *pdev, int bar)
3767 pos = pci_rebar_find_pos(pdev, bar);
3771 pci_read_config_dword(pdev, pos + PCI_REBAR_CAP, &cap);
3772 cap = FIELD_GET(PCI_REBAR_CAP_SIZES, cap);
3774 /* Sapphire RX 5600 XT Pulse has an invalid cap dword for BAR 0 */
3775 if (pdev->vendor == PCI_VENDOR_ID_ATI && pdev->device == 0x731f &&
3776 bar == 0 && cap == 0x700)
3781 EXPORT_SYMBOL(pci_rebar_get_possible_sizes);
3784 * pci_rebar_get_current_size - get the current size of a BAR
3786 * @bar: BAR to set size to
3788 * Read the size of a BAR from the resizable BAR config.
3789 * Returns size if found or negative error code.
3791 int pci_rebar_get_current_size(struct pci_dev *pdev, int bar)
3796 pos = pci_rebar_find_pos(pdev, bar);
3800 pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
3801 return FIELD_GET(PCI_REBAR_CTRL_BAR_SIZE, ctrl);
3805 * pci_rebar_set_size - set a new size for a BAR
3807 * @bar: BAR to set size to
3808 * @size: new size as defined in the spec (0=1MB, 19=512GB)
3810 * Set the new size of a BAR as defined in the spec.
3811 * Returns zero if resizing was successful, error code otherwise.
3813 int pci_rebar_set_size(struct pci_dev *pdev, int bar, int size)
3818 pos = pci_rebar_find_pos(pdev, bar);
3822 pci_read_config_dword(pdev, pos + PCI_REBAR_CTRL, &ctrl);
3823 ctrl &= ~PCI_REBAR_CTRL_BAR_SIZE;
3824 ctrl |= FIELD_PREP(PCI_REBAR_CTRL_BAR_SIZE, size);
3825 pci_write_config_dword(pdev, pos + PCI_REBAR_CTRL, ctrl);
3830 * pci_enable_atomic_ops_to_root - enable AtomicOp requests to root port
3831 * @dev: the PCI device
3832 * @cap_mask: mask of desired AtomicOp sizes, including one or more of:
3833 * PCI_EXP_DEVCAP2_ATOMIC_COMP32
3834 * PCI_EXP_DEVCAP2_ATOMIC_COMP64
3835 * PCI_EXP_DEVCAP2_ATOMIC_COMP128
3837 * Return 0 if all upstream bridges support AtomicOp routing, egress
3838 * blocking is disabled on all upstream ports, and the root port supports
3839 * the requested completion capabilities (32-bit, 64-bit and/or 128-bit
3840 * AtomicOp completion), or negative otherwise.
3842 int pci_enable_atomic_ops_to_root(struct pci_dev *dev, u32 cap_mask)
3844 struct pci_bus *bus = dev->bus;
3845 struct pci_dev *bridge;
3849 * Per PCIe r5.0, sec 9.3.5.10, the AtomicOp Requester Enable bit
3850 * in Device Control 2 is reserved in VFs and the PF value applies
3851 * to all associated VFs.
3856 if (!pci_is_pcie(dev))
3860 * Per PCIe r4.0, sec 6.15, endpoints and root ports may be
3861 * AtomicOp requesters. For now, we only support endpoints as
3862 * requesters and root ports as completers. No endpoints as
3863 * completers, and no peer-to-peer.
3866 switch (pci_pcie_type(dev)) {
3867 case PCI_EXP_TYPE_ENDPOINT:
3868 case PCI_EXP_TYPE_LEG_END:
3869 case PCI_EXP_TYPE_RC_END:
3875 while (bus->parent) {
3878 pcie_capability_read_dword(bridge, PCI_EXP_DEVCAP2, &cap);
3880 switch (pci_pcie_type(bridge)) {
3881 /* Ensure switch ports support AtomicOp routing */
3882 case PCI_EXP_TYPE_UPSTREAM:
3883 case PCI_EXP_TYPE_DOWNSTREAM:
3884 if (!(cap & PCI_EXP_DEVCAP2_ATOMIC_ROUTE))
3888 /* Ensure root port supports all the sizes we care about */
3889 case PCI_EXP_TYPE_ROOT_PORT:
3890 if ((cap & cap_mask) != cap_mask)
3895 /* Ensure upstream ports don't block AtomicOps on egress */
3896 if (pci_pcie_type(bridge) == PCI_EXP_TYPE_UPSTREAM) {
3897 pcie_capability_read_dword(bridge, PCI_EXP_DEVCTL2,
3899 if (ctl2 & PCI_EXP_DEVCTL2_ATOMIC_EGRESS_BLOCK)
3906 pcie_capability_set_word(dev, PCI_EXP_DEVCTL2,
3907 PCI_EXP_DEVCTL2_ATOMIC_REQ);
3910 EXPORT_SYMBOL(pci_enable_atomic_ops_to_root);
3913 * pci_release_region - Release a PCI bar
3914 * @pdev: PCI device whose resources were previously reserved by
3915 * pci_request_region()
3916 * @bar: BAR to release
3918 * Releases the PCI I/O and memory resources previously reserved by a
3919 * successful call to pci_request_region(). Call this function only
3920 * after all use of the PCI regions has ceased.
3922 void pci_release_region(struct pci_dev *pdev, int bar)
3925 * This is done for backwards compatibility, because the old PCI devres
3926 * API had a mode in which the function became managed if it had been
3927 * enabled with pcim_enable_device() instead of pci_enable_device().
3929 if (pci_is_managed(pdev)) {
3930 pcim_release_region(pdev, bar);
3934 if (pci_resource_len(pdev, bar) == 0)
3936 if (pci_resource_flags(pdev, bar) & IORESOURCE_IO)
3937 release_region(pci_resource_start(pdev, bar),
3938 pci_resource_len(pdev, bar));
3939 else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM)
3940 release_mem_region(pci_resource_start(pdev, bar),
3941 pci_resource_len(pdev, bar));
3943 EXPORT_SYMBOL(pci_release_region);
3946 * __pci_request_region - Reserved PCI I/O and memory resource
3947 * @pdev: PCI device whose resources are to be reserved
3948 * @bar: BAR to be reserved
3949 * @name: name of the driver requesting the resource
3950 * @exclusive: whether the region access is exclusive or not
3952 * Returns: 0 on success, negative error code on failure.
3954 * Mark the PCI region associated with PCI device @pdev BAR @bar as being
3955 * reserved by owner @name. Do not access any address inside the PCI regions
3956 * unless this call returns successfully.
3958 * If @exclusive is set, then the region is marked so that userspace
3959 * is explicitly not allowed to map the resource via /dev/mem or
3960 * sysfs MMIO access.
3962 * Returns 0 on success, or %EBUSY on error. A warning
3963 * message is also printed on failure.
3965 static int __pci_request_region(struct pci_dev *pdev, int bar,
3966 const char *name, int exclusive)
3968 if (pci_is_managed(pdev)) {
3969 if (exclusive == IORESOURCE_EXCLUSIVE)
3970 return pcim_request_region_exclusive(pdev, bar, name);
3972 return pcim_request_region(pdev, bar, name);
3975 if (pci_resource_len(pdev, bar) == 0)
3978 if (pci_resource_flags(pdev, bar) & IORESOURCE_IO) {
3979 if (!request_region(pci_resource_start(pdev, bar),
3980 pci_resource_len(pdev, bar), name))
3982 } else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM) {
3983 if (!__request_mem_region(pci_resource_start(pdev, bar),
3984 pci_resource_len(pdev, bar), name,
3992 pci_warn(pdev, "BAR %d: can't reserve %pR\n", bar,
3993 &pdev->resource[bar]);
3998 * pci_request_region - Reserve PCI I/O and memory resource
3999 * @pdev: PCI device whose resources are to be reserved
4000 * @bar: BAR to be reserved
4001 * @name: name of the driver requesting the resource
4003 * Returns: 0 on success, negative error code on failure.
4005 * Mark the PCI region associated with PCI device @pdev BAR @bar as being
4006 * reserved by owner @name. Do not access any address inside the PCI regions
4007 * unless this call returns successfully.
4009 * Returns 0 on success, or %EBUSY on error. A warning
4010 * message is also printed on failure.
4013 * This is a "hybrid" function: It's normally unmanaged, but becomes managed
4014 * when pcim_enable_device() has been called in advance. This hybrid feature is
4015 * DEPRECATED! If you want managed cleanup, use the pcim_* functions instead.
4017 int pci_request_region(struct pci_dev *pdev, int bar, const char *name)
4019 return __pci_request_region(pdev, bar, name, 0);
4021 EXPORT_SYMBOL(pci_request_region);
4024 * pci_release_selected_regions - Release selected PCI I/O and memory resources
4025 * @pdev: PCI device whose resources were previously reserved
4026 * @bars: Bitmask of BARs to be released
4028 * Release selected PCI I/O and memory resources previously reserved.
4029 * Call this function only after all use of the PCI regions has ceased.
4031 void pci_release_selected_regions(struct pci_dev *pdev, int bars)
4035 for (i = 0; i < PCI_STD_NUM_BARS; i++)
4036 if (bars & (1 << i))
4037 pci_release_region(pdev, i);
4039 EXPORT_SYMBOL(pci_release_selected_regions);
4041 static int __pci_request_selected_regions(struct pci_dev *pdev, int bars,
4042 const char *name, int excl)
4046 for (i = 0; i < PCI_STD_NUM_BARS; i++)
4047 if (bars & (1 << i))
4048 if (__pci_request_region(pdev, i, name, excl))
4054 if (bars & (1 << i))
4055 pci_release_region(pdev, i);
4062 * pci_request_selected_regions - Reserve selected PCI I/O and memory resources
4063 * @pdev: PCI device whose resources are to be reserved
4064 * @bars: Bitmask of BARs to be requested
4065 * @name: Name of the driver requesting the resources
4067 * Returns: 0 on success, negative error code on failure.
4070 * This is a "hybrid" function: It's normally unmanaged, but becomes managed
4071 * when pcim_enable_device() has been called in advance. This hybrid feature is
4072 * DEPRECATED! If you want managed cleanup, use the pcim_* functions instead.
4074 int pci_request_selected_regions(struct pci_dev *pdev, int bars,
4077 return __pci_request_selected_regions(pdev, bars, name, 0);
4079 EXPORT_SYMBOL(pci_request_selected_regions);
4082 * pci_request_selected_regions_exclusive - Request regions exclusively
4083 * @pdev: PCI device to request regions from
4084 * @bars: bit mask of BARs to request
4085 * @name: name of the driver requesting the resources
4087 * Returns: 0 on success, negative error code on failure.
4090 * This is a "hybrid" function: It's normally unmanaged, but becomes managed
4091 * when pcim_enable_device() has been called in advance. This hybrid feature is
4092 * DEPRECATED! If you want managed cleanup, use the pcim_* functions instead.
4094 int pci_request_selected_regions_exclusive(struct pci_dev *pdev, int bars,
4097 return __pci_request_selected_regions(pdev, bars, name,
4098 IORESOURCE_EXCLUSIVE);
4100 EXPORT_SYMBOL(pci_request_selected_regions_exclusive);
4103 * pci_release_regions - Release reserved PCI I/O and memory resources
4104 * @pdev: PCI device whose resources were previously reserved by
4105 * pci_request_regions()
4107 * Releases all PCI I/O and memory resources previously reserved by a
4108 * successful call to pci_request_regions(). Call this function only
4109 * after all use of the PCI regions has ceased.
4111 void pci_release_regions(struct pci_dev *pdev)
4113 pci_release_selected_regions(pdev, (1 << PCI_STD_NUM_BARS) - 1);
4115 EXPORT_SYMBOL(pci_release_regions);
4118 * pci_request_regions - Reserve PCI I/O and memory resources
4119 * @pdev: PCI device whose resources are to be reserved
4120 * @name: name of the driver requesting the resources
4122 * Mark all PCI regions associated with PCI device @pdev as being reserved by
4123 * owner @name. Do not access any address inside the PCI regions unless this
4124 * call returns successfully.
4126 * Returns 0 on success, or %EBUSY on error. A warning
4127 * message is also printed on failure.
4130 * This is a "hybrid" function: It's normally unmanaged, but becomes managed
4131 * when pcim_enable_device() has been called in advance. This hybrid feature is
4132 * DEPRECATED! If you want managed cleanup, use the pcim_* functions instead.
4134 int pci_request_regions(struct pci_dev *pdev, const char *name)
4136 return pci_request_selected_regions(pdev,
4137 ((1 << PCI_STD_NUM_BARS) - 1), name);
4139 EXPORT_SYMBOL(pci_request_regions);
4142 * pci_request_regions_exclusive - Reserve PCI I/O and memory resources
4143 * @pdev: PCI device whose resources are to be reserved
4144 * @name: name of the driver requesting the resources
4146 * Returns: 0 on success, negative error code on failure.
4148 * Mark all PCI regions associated with PCI device @pdev as being reserved
4149 * by owner @name. Do not access any address inside the PCI regions
4150 * unless this call returns successfully.
4152 * pci_request_regions_exclusive() will mark the region so that /dev/mem
4153 * and the sysfs MMIO access will not be allowed.
4155 * Returns 0 on success, or %EBUSY on error. A warning message is also
4156 * printed on failure.
4159 * This is a "hybrid" function: It's normally unmanaged, but becomes managed
4160 * when pcim_enable_device() has been called in advance. This hybrid feature is
4161 * DEPRECATED! If you want managed cleanup, use the pcim_* functions instead.
4163 int pci_request_regions_exclusive(struct pci_dev *pdev, const char *name)
4165 return pci_request_selected_regions_exclusive(pdev,
4166 ((1 << PCI_STD_NUM_BARS) - 1), name);
4168 EXPORT_SYMBOL(pci_request_regions_exclusive);
4171 * Record the PCI IO range (expressed as CPU physical address + size).
4172 * Return a negative value if an error has occurred, zero otherwise
4174 int pci_register_io_range(const struct fwnode_handle *fwnode, phys_addr_t addr,
4175 resource_size_t size)
4179 struct logic_pio_hwaddr *range;
4181 if (!size || addr + size < addr)
4184 range = kzalloc(sizeof(*range), GFP_ATOMIC);
4188 range->fwnode = fwnode;
4190 range->hw_start = addr;
4191 range->flags = LOGIC_PIO_CPU_MMIO;
4193 ret = logic_pio_register_range(range);
4197 /* Ignore duplicates due to deferred probing */
4205 phys_addr_t pci_pio_to_address(unsigned long pio)
4208 if (pio < MMIO_UPPER_LIMIT)
4209 return logic_pio_to_hwaddr(pio);
4212 return (phys_addr_t) OF_BAD_ADDR;
4214 EXPORT_SYMBOL_GPL(pci_pio_to_address);
4216 unsigned long __weak pci_address_to_pio(phys_addr_t address)
4219 return logic_pio_trans_cpuaddr(address);
4221 if (address > IO_SPACE_LIMIT)
4222 return (unsigned long)-1;
4224 return (unsigned long) address;
4229 * pci_remap_iospace - Remap the memory mapped I/O space
4230 * @res: Resource describing the I/O space
4231 * @phys_addr: physical address of range to be mapped
4233 * Remap the memory mapped I/O space described by the @res and the CPU
4234 * physical address @phys_addr into virtual address space. Only
4235 * architectures that have memory mapped IO functions defined (and the
4236 * PCI_IOBASE value defined) should call this function.
4238 #ifndef pci_remap_iospace
4239 int pci_remap_iospace(const struct resource *res, phys_addr_t phys_addr)
4241 #if defined(PCI_IOBASE) && defined(CONFIG_MMU)
4242 unsigned long vaddr = (unsigned long)PCI_IOBASE + res->start;
4244 if (!(res->flags & IORESOURCE_IO))
4247 if (res->end > IO_SPACE_LIMIT)
4250 return vmap_page_range(vaddr, vaddr + resource_size(res), phys_addr,
4251 pgprot_device(PAGE_KERNEL));
4254 * This architecture does not have memory mapped I/O space,
4255 * so this function should never be called
4257 WARN_ONCE(1, "This architecture does not support memory mapped I/O\n");
4261 EXPORT_SYMBOL(pci_remap_iospace);
4265 * pci_unmap_iospace - Unmap the memory mapped I/O space
4266 * @res: resource to be unmapped
4268 * Unmap the CPU virtual address @res from virtual address space. Only
4269 * architectures that have memory mapped IO functions defined (and the
4270 * PCI_IOBASE value defined) should call this function.
4272 void pci_unmap_iospace(struct resource *res)
4274 #if defined(PCI_IOBASE) && defined(CONFIG_MMU)
4275 unsigned long vaddr = (unsigned long)PCI_IOBASE + res->start;
4277 vunmap_range(vaddr, vaddr + resource_size(res));
4280 EXPORT_SYMBOL(pci_unmap_iospace);
4282 static void __pci_set_master(struct pci_dev *dev, bool enable)
4286 pci_read_config_word(dev, PCI_COMMAND, &old_cmd);
4288 cmd = old_cmd | PCI_COMMAND_MASTER;
4290 cmd = old_cmd & ~PCI_COMMAND_MASTER;
4291 if (cmd != old_cmd) {
4292 pci_dbg(dev, "%s bus mastering\n",
4293 enable ? "enabling" : "disabling");
4294 pci_write_config_word(dev, PCI_COMMAND, cmd);
4296 dev->is_busmaster = enable;
4300 * pcibios_setup - process "pci=" kernel boot arguments
4301 * @str: string used to pass in "pci=" kernel boot arguments
4303 * Process kernel boot arguments. This is the default implementation.
4304 * Architecture specific implementations can override this as necessary.
4306 char * __weak __init pcibios_setup(char *str)
4312 * pcibios_set_master - enable PCI bus-mastering for device dev
4313 * @dev: the PCI device to enable
4315 * Enables PCI bus-mastering for the device. This is the default
4316 * implementation. Architecture specific implementations can override
4317 * this if necessary.
4319 void __weak pcibios_set_master(struct pci_dev *dev)
4323 /* The latency timer doesn't apply to PCIe (either Type 0 or Type 1) */
4324 if (pci_is_pcie(dev))
4327 pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
4329 lat = (64 <= pcibios_max_latency) ? 64 : pcibios_max_latency;
4330 else if (lat > pcibios_max_latency)
4331 lat = pcibios_max_latency;
4335 pci_write_config_byte(dev, PCI_LATENCY_TIMER, lat);
4339 * pci_set_master - enables bus-mastering for device dev
4340 * @dev: the PCI device to enable
4342 * Enables bus-mastering on the device and calls pcibios_set_master()
4343 * to do the needed arch specific settings.
4345 void pci_set_master(struct pci_dev *dev)
4347 __pci_set_master(dev, true);
4348 pcibios_set_master(dev);
4350 EXPORT_SYMBOL(pci_set_master);
4353 * pci_clear_master - disables bus-mastering for device dev
4354 * @dev: the PCI device to disable
4356 void pci_clear_master(struct pci_dev *dev)
4358 __pci_set_master(dev, false);
4360 EXPORT_SYMBOL(pci_clear_master);
4363 * pci_set_cacheline_size - ensure the CACHE_LINE_SIZE register is programmed
4364 * @dev: the PCI device for which MWI is to be enabled
4366 * Helper function for pci_set_mwi.
4367 * Originally copied from drivers/net/acenic.c.
4370 * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4372 int pci_set_cacheline_size(struct pci_dev *dev)
4376 if (!pci_cache_line_size)
4379 /* Validate current setting: the PCI_CACHE_LINE_SIZE must be
4380 equal to or multiple of the right value. */
4381 pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
4382 if (cacheline_size >= pci_cache_line_size &&
4383 (cacheline_size % pci_cache_line_size) == 0)
4386 /* Write the correct value. */
4387 pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, pci_cache_line_size);
4389 pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
4390 if (cacheline_size == pci_cache_line_size)
4393 pci_dbg(dev, "cache line size of %d is not supported\n",
4394 pci_cache_line_size << 2);
4398 EXPORT_SYMBOL_GPL(pci_set_cacheline_size);
4401 * pci_set_mwi - enables memory-write-invalidate PCI transaction
4402 * @dev: the PCI device for which MWI is enabled
4404 * Enables the Memory-Write-Invalidate transaction in %PCI_COMMAND.
4406 * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4408 int pci_set_mwi(struct pci_dev *dev)
4410 #ifdef PCI_DISABLE_MWI
4416 rc = pci_set_cacheline_size(dev);
4420 pci_read_config_word(dev, PCI_COMMAND, &cmd);
4421 if (!(cmd & PCI_COMMAND_INVALIDATE)) {
4422 pci_dbg(dev, "enabling Mem-Wr-Inval\n");
4423 cmd |= PCI_COMMAND_INVALIDATE;
4424 pci_write_config_word(dev, PCI_COMMAND, cmd);
4429 EXPORT_SYMBOL(pci_set_mwi);
4432 * pci_try_set_mwi - enables memory-write-invalidate PCI transaction
4433 * @dev: the PCI device for which MWI is enabled
4435 * Enables the Memory-Write-Invalidate transaction in %PCI_COMMAND.
4436 * Callers are not required to check the return value.
4438 * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4440 int pci_try_set_mwi(struct pci_dev *dev)
4442 #ifdef PCI_DISABLE_MWI
4445 return pci_set_mwi(dev);
4448 EXPORT_SYMBOL(pci_try_set_mwi);
4451 * pci_clear_mwi - disables Memory-Write-Invalidate for device dev
4452 * @dev: the PCI device to disable
4454 * Disables PCI Memory-Write-Invalidate transaction on the device
4456 void pci_clear_mwi(struct pci_dev *dev)
4458 #ifndef PCI_DISABLE_MWI
4461 pci_read_config_word(dev, PCI_COMMAND, &cmd);
4462 if (cmd & PCI_COMMAND_INVALIDATE) {
4463 cmd &= ~PCI_COMMAND_INVALIDATE;
4464 pci_write_config_word(dev, PCI_COMMAND, cmd);
4468 EXPORT_SYMBOL(pci_clear_mwi);
4471 * pci_disable_parity - disable parity checking for device
4472 * @dev: the PCI device to operate on
4474 * Disable parity checking for device @dev
4476 void pci_disable_parity(struct pci_dev *dev)
4480 pci_read_config_word(dev, PCI_COMMAND, &cmd);
4481 if (cmd & PCI_COMMAND_PARITY) {
4482 cmd &= ~PCI_COMMAND_PARITY;
4483 pci_write_config_word(dev, PCI_COMMAND, cmd);
4488 * pci_intx - enables/disables PCI INTx for device dev
4489 * @pdev: the PCI device to operate on
4490 * @enable: boolean: whether to enable or disable PCI INTx
4492 * Enables/disables PCI INTx for device @pdev
4494 void pci_intx(struct pci_dev *pdev, int enable)
4496 u16 pci_command, new;
4498 pci_read_config_word(pdev, PCI_COMMAND, &pci_command);
4501 new = pci_command & ~PCI_COMMAND_INTX_DISABLE;
4503 new = pci_command | PCI_COMMAND_INTX_DISABLE;
4505 if (new == pci_command)
4508 pci_write_config_word(pdev, PCI_COMMAND, new);
4510 EXPORT_SYMBOL_GPL(pci_intx);
4513 * pci_wait_for_pending_transaction - wait for pending transaction
4514 * @dev: the PCI device to operate on
4516 * Return 0 if transaction is pending 1 otherwise.
4518 int pci_wait_for_pending_transaction(struct pci_dev *dev)
4520 if (!pci_is_pcie(dev))
4523 return pci_wait_for_pending(dev, pci_pcie_cap(dev) + PCI_EXP_DEVSTA,
4524 PCI_EXP_DEVSTA_TRPND);
4526 EXPORT_SYMBOL(pci_wait_for_pending_transaction);
4529 * pcie_flr - initiate a PCIe function level reset
4530 * @dev: device to reset
4532 * Initiate a function level reset unconditionally on @dev without
4533 * checking any flags and DEVCAP
4535 int pcie_flr(struct pci_dev *dev)
4537 if (!pci_wait_for_pending_transaction(dev))
4538 pci_err(dev, "timed out waiting for pending transaction; performing function level reset anyway\n");
4540 pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_BCR_FLR);
4546 * Per PCIe r4.0, sec 6.6.2, a device must complete an FLR within
4547 * 100ms, but may silently discard requests while the FLR is in
4548 * progress. Wait 100ms before trying to access the device.
4552 return pci_dev_wait(dev, "FLR", PCIE_RESET_READY_POLL_MS);
4554 EXPORT_SYMBOL_GPL(pcie_flr);
4557 * pcie_reset_flr - initiate a PCIe function level reset
4558 * @dev: device to reset
4559 * @probe: if true, return 0 if device can be reset this way
4561 * Initiate a function level reset on @dev.
4563 int pcie_reset_flr(struct pci_dev *dev, bool probe)
4565 if (dev->dev_flags & PCI_DEV_FLAGS_NO_FLR_RESET)
4568 if (!(dev->devcap & PCI_EXP_DEVCAP_FLR))
4574 return pcie_flr(dev);
4576 EXPORT_SYMBOL_GPL(pcie_reset_flr);
4578 static int pci_af_flr(struct pci_dev *dev, bool probe)
4583 pos = pci_find_capability(dev, PCI_CAP_ID_AF);
4587 if (dev->dev_flags & PCI_DEV_FLAGS_NO_FLR_RESET)
4590 pci_read_config_byte(dev, pos + PCI_AF_CAP, &cap);
4591 if (!(cap & PCI_AF_CAP_TP) || !(cap & PCI_AF_CAP_FLR))
4598 * Wait for Transaction Pending bit to clear. A word-aligned test
4599 * is used, so we use the control offset rather than status and shift
4600 * the test bit to match.
4602 if (!pci_wait_for_pending(dev, pos + PCI_AF_CTRL,
4603 PCI_AF_STATUS_TP << 8))
4604 pci_err(dev, "timed out waiting for pending transaction; performing AF function level reset anyway\n");
4606 pci_write_config_byte(dev, pos + PCI_AF_CTRL, PCI_AF_CTRL_FLR);
4612 * Per Advanced Capabilities for Conventional PCI ECN, 13 April 2006,
4613 * updated 27 July 2006; a device must complete an FLR within
4614 * 100ms, but may silently discard requests while the FLR is in
4615 * progress. Wait 100ms before trying to access the device.
4619 return pci_dev_wait(dev, "AF_FLR", PCIE_RESET_READY_POLL_MS);
4623 * pci_pm_reset - Put device into PCI_D3 and back into PCI_D0.
4624 * @dev: Device to reset.
4625 * @probe: if true, return 0 if the device can be reset this way.
4627 * If @dev supports native PCI PM and its PCI_PM_CTRL_NO_SOFT_RESET flag is
4628 * unset, it will be reinitialized internally when going from PCI_D3hot to
4629 * PCI_D0. If that's the case and the device is not in a low-power state
4630 * already, force it into PCI_D3hot and back to PCI_D0, causing it to be reset.
4632 * NOTE: This causes the caller to sleep for twice the device power transition
4633 * cooldown period, which for the D0->D3hot and D3hot->D0 transitions is 10 ms
4634 * by default (i.e. unless the @dev's d3hot_delay field has a different value).
4635 * Moreover, only devices in D0 can be reset by this function.
4637 static int pci_pm_reset(struct pci_dev *dev, bool probe)
4641 if (!dev->pm_cap || dev->dev_flags & PCI_DEV_FLAGS_NO_PM_RESET)
4644 pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &csr);
4645 if (csr & PCI_PM_CTRL_NO_SOFT_RESET)
4651 if (dev->current_state != PCI_D0)
4654 csr &= ~PCI_PM_CTRL_STATE_MASK;
4656 pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, csr);
4657 pci_dev_d3_sleep(dev);
4659 csr &= ~PCI_PM_CTRL_STATE_MASK;
4661 pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, csr);
4662 pci_dev_d3_sleep(dev);
4664 return pci_dev_wait(dev, "PM D3hot->D0", PCIE_RESET_READY_POLL_MS);
4668 * pcie_wait_for_link_status - Wait for link status change
4669 * @pdev: Device whose link to wait for.
4670 * @use_lt: Use the LT bit if TRUE, or the DLLLA bit if FALSE.
4671 * @active: Waiting for active or inactive?
4673 * Return 0 if successful, or -ETIMEDOUT if status has not changed within
4674 * PCIE_LINK_RETRAIN_TIMEOUT_MS milliseconds.
4676 static int pcie_wait_for_link_status(struct pci_dev *pdev,
4677 bool use_lt, bool active)
4679 u16 lnksta_mask, lnksta_match;
4680 unsigned long end_jiffies;
4683 lnksta_mask = use_lt ? PCI_EXP_LNKSTA_LT : PCI_EXP_LNKSTA_DLLLA;
4684 lnksta_match = active ? lnksta_mask : 0;
4686 end_jiffies = jiffies + msecs_to_jiffies(PCIE_LINK_RETRAIN_TIMEOUT_MS);
4688 pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnksta);
4689 if ((lnksta & lnksta_mask) == lnksta_match)
4692 } while (time_before(jiffies, end_jiffies));
4698 * pcie_retrain_link - Request a link retrain and wait for it to complete
4699 * @pdev: Device whose link to retrain.
4700 * @use_lt: Use the LT bit if TRUE, or the DLLLA bit if FALSE, for status.
4702 * Retrain completion status is retrieved from the Link Status Register
4703 * according to @use_lt. It is not verified whether the use of the DLLLA
4706 * Return 0 if successful, or -ETIMEDOUT if training has not completed
4707 * within PCIE_LINK_RETRAIN_TIMEOUT_MS milliseconds.
4709 int pcie_retrain_link(struct pci_dev *pdev, bool use_lt)
4714 * Ensure the updated LNKCTL parameters are used during link
4715 * training by checking that there is no ongoing link training that
4716 * may have started before link parameters were changed, so as to
4717 * avoid LTSSM race as recommended in Implementation Note at the end
4718 * of PCIe r6.1 sec 7.5.3.7.
4720 rc = pcie_wait_for_link_status(pdev, true, false);
4724 pcie_capability_set_word(pdev, PCI_EXP_LNKCTL, PCI_EXP_LNKCTL_RL);
4725 if (pdev->clear_retrain_link) {
4727 * Due to an erratum in some devices the Retrain Link bit
4728 * needs to be cleared again manually to allow the link
4729 * training to succeed.
4731 pcie_capability_clear_word(pdev, PCI_EXP_LNKCTL, PCI_EXP_LNKCTL_RL);
4734 rc = pcie_wait_for_link_status(pdev, use_lt, !use_lt);
4737 * Clear LBMS after a manual retrain so that the bit can be used
4738 * to track link speed or width changes made by hardware itself
4739 * in attempt to correct unreliable link operation.
4741 pcie_reset_lbms_count(pdev);
4746 * pcie_wait_for_link_delay - Wait until link is active or inactive
4747 * @pdev: Bridge device
4748 * @active: waiting for active or inactive?
4749 * @delay: Delay to wait after link has become active (in ms)
4751 * Use this to wait till link becomes active or inactive.
4753 static bool pcie_wait_for_link_delay(struct pci_dev *pdev, bool active,
4759 * Some controllers might not implement link active reporting. In this
4760 * case, we wait for 1000 ms + any delay requested by the caller.
4762 if (!pdev->link_active_reporting) {
4763 msleep(PCIE_LINK_RETRAIN_TIMEOUT_MS + delay);
4768 * PCIe r4.0 sec 6.6.1, a component must enter LTSSM Detect within 20ms,
4769 * after which we should expect an link active if the reset was
4770 * successful. If so, software must wait a minimum 100ms before sending
4771 * configuration requests to devices downstream this port.
4773 * If the link fails to activate, either the device was physically
4774 * removed or the link is permanently failed.
4778 rc = pcie_wait_for_link_status(pdev, false, active);
4781 rc = pcie_failed_link_retrain(pdev);
4796 * pcie_wait_for_link - Wait until link is active or inactive
4797 * @pdev: Bridge device
4798 * @active: waiting for active or inactive?
4800 * Use this to wait till link becomes active or inactive.
4802 bool pcie_wait_for_link(struct pci_dev *pdev, bool active)
4804 return pcie_wait_for_link_delay(pdev, active, 100);
4808 * Find maximum D3cold delay required by all the devices on the bus. The
4809 * spec says 100 ms, but firmware can lower it and we allow drivers to
4810 * increase it as well.
4812 * Called with @pci_bus_sem locked for reading.
4814 static int pci_bus_max_d3cold_delay(const struct pci_bus *bus)
4816 const struct pci_dev *pdev;
4817 int min_delay = 100;
4820 list_for_each_entry(pdev, &bus->devices, bus_list) {
4821 if (pdev->d3cold_delay < min_delay)
4822 min_delay = pdev->d3cold_delay;
4823 if (pdev->d3cold_delay > max_delay)
4824 max_delay = pdev->d3cold_delay;
4827 return max(min_delay, max_delay);
4831 * pci_bridge_wait_for_secondary_bus - Wait for secondary bus to be accessible
4833 * @reset_type: reset type in human-readable form
4835 * Handle necessary delays before access to the devices on the secondary
4836 * side of the bridge are permitted after D3cold to D0 transition
4837 * or Conventional Reset.
4839 * For PCIe this means the delays in PCIe 5.0 section 6.6.1. For
4840 * conventional PCI it means Tpvrh + Trhfa specified in PCI 3.0 section
4843 * Return 0 on success or -ENOTTY if the first device on the secondary bus
4844 * failed to become accessible.
4846 int pci_bridge_wait_for_secondary_bus(struct pci_dev *dev, char *reset_type)
4848 struct pci_dev *child __free(pci_dev_put) = NULL;
4851 if (pci_dev_is_disconnected(dev))
4854 if (!pci_is_bridge(dev))
4857 down_read(&pci_bus_sem);
4860 * We only deal with devices that are present currently on the bus.
4861 * For any hot-added devices the access delay is handled in pciehp
4862 * board_added(). In case of ACPI hotplug the firmware is expected
4863 * to configure the devices before OS is notified.
4865 if (!dev->subordinate || list_empty(&dev->subordinate->devices)) {
4866 up_read(&pci_bus_sem);
4870 /* Take d3cold_delay requirements into account */
4871 delay = pci_bus_max_d3cold_delay(dev->subordinate);
4873 up_read(&pci_bus_sem);
4877 child = pci_dev_get(list_first_entry(&dev->subordinate->devices,
4878 struct pci_dev, bus_list));
4879 up_read(&pci_bus_sem);
4882 * Conventional PCI and PCI-X we need to wait Tpvrh + Trhfa before
4883 * accessing the device after reset (that is 1000 ms + 100 ms).
4885 if (!pci_is_pcie(dev)) {
4886 pci_dbg(dev, "waiting %d ms for secondary bus\n", 1000 + delay);
4887 msleep(1000 + delay);
4892 * For PCIe downstream and root ports that do not support speeds
4893 * greater than 5 GT/s need to wait minimum 100 ms. For higher
4894 * speeds (gen3) we need to wait first for the data link layer to
4897 * However, 100 ms is the minimum and the PCIe spec says the
4898 * software must allow at least 1s before it can determine that the
4899 * device that did not respond is a broken device. Also device can
4900 * take longer than that to respond if it indicates so through Request
4901 * Retry Status completions.
4903 * Therefore we wait for 100 ms and check for the device presence
4904 * until the timeout expires.
4906 if (!pcie_downstream_port(dev))
4909 if (pcie_get_speed_cap(dev) <= PCIE_SPEED_5_0GT) {
4912 pci_dbg(dev, "waiting %d ms for downstream link\n", delay);
4915 if (!pci_dev_wait(child, reset_type, PCI_RESET_WAIT - delay))
4919 * If the port supports active link reporting we now check
4920 * whether the link is active and if not bail out early with
4921 * the assumption that the device is not present anymore.
4923 if (!dev->link_active_reporting)
4926 pcie_capability_read_word(dev, PCI_EXP_LNKSTA, &status);
4927 if (!(status & PCI_EXP_LNKSTA_DLLLA))
4930 return pci_dev_wait(child, reset_type,
4931 PCIE_RESET_READY_POLL_MS - PCI_RESET_WAIT);
4934 pci_dbg(dev, "waiting %d ms for downstream link, after activation\n",
4936 if (!pcie_wait_for_link_delay(dev, true, delay)) {
4937 /* Did not train, no need to wait any further */
4938 pci_info(dev, "Data Link Layer Link Active not set in 1000 msec\n");
4942 return pci_dev_wait(child, reset_type,
4943 PCIE_RESET_READY_POLL_MS - delay);
4946 void pci_reset_secondary_bus(struct pci_dev *dev)
4950 pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &ctrl);
4951 ctrl |= PCI_BRIDGE_CTL_BUS_RESET;
4952 pci_write_config_word(dev, PCI_BRIDGE_CONTROL, ctrl);
4955 * PCI spec v3.0 7.6.4.2 requires minimum Trst of 1ms. Double
4956 * this to 2ms to ensure that we meet the minimum requirement.
4960 ctrl &= ~PCI_BRIDGE_CTL_BUS_RESET;
4961 pci_write_config_word(dev, PCI_BRIDGE_CONTROL, ctrl);
4964 void __weak pcibios_reset_secondary_bus(struct pci_dev *dev)
4966 pci_reset_secondary_bus(dev);
4970 * pci_bridge_secondary_bus_reset - Reset the secondary bus on a PCI bridge.
4971 * @dev: Bridge device
4973 * Use the bridge control register to assert reset on the secondary bus.
4974 * Devices on the secondary bus are left in power-on state.
4976 int pci_bridge_secondary_bus_reset(struct pci_dev *dev)
4978 if (!dev->block_cfg_access)
4979 pci_warn_once(dev, "unlocked secondary bus reset via: %pS\n",
4980 __builtin_return_address(0));
4981 pcibios_reset_secondary_bus(dev);
4983 return pci_bridge_wait_for_secondary_bus(dev, "bus reset");
4985 EXPORT_SYMBOL_GPL(pci_bridge_secondary_bus_reset);
4987 static int pci_parent_bus_reset(struct pci_dev *dev, bool probe)
4989 struct pci_dev *pdev;
4991 if (pci_is_root_bus(dev->bus) || dev->subordinate ||
4992 !dev->bus->self || dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET)
4995 list_for_each_entry(pdev, &dev->bus->devices, bus_list)
5002 return pci_bridge_secondary_bus_reset(dev->bus->self);
5005 static int pci_reset_hotplug_slot(struct hotplug_slot *hotplug, bool probe)
5009 if (!hotplug || !try_module_get(hotplug->owner))
5012 if (hotplug->ops->reset_slot)
5013 rc = hotplug->ops->reset_slot(hotplug, probe);
5015 module_put(hotplug->owner);
5020 static int pci_dev_reset_slot_function(struct pci_dev *dev, bool probe)
5022 if (dev->multifunction || dev->subordinate || !dev->slot ||
5023 dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET)
5026 return pci_reset_hotplug_slot(dev->slot->hotplug, probe);
5029 static u16 cxl_port_dvsec(struct pci_dev *dev)
5031 return pci_find_dvsec_capability(dev, PCI_VENDOR_ID_CXL,
5032 PCI_DVSEC_CXL_PORT);
5035 static bool cxl_sbr_masked(struct pci_dev *dev)
5040 dvsec = cxl_port_dvsec(dev);
5044 rc = pci_read_config_word(dev, dvsec + PCI_DVSEC_CXL_PORT_CTL, ®);
5045 if (rc || PCI_POSSIBLE_ERROR(reg))
5049 * Per CXL spec r3.1, sec 8.1.5.2, when "Unmask SBR" is 0, the SBR
5050 * bit in Bridge Control has no effect. When 1, the Port generates
5051 * hot reset when the SBR bit is set to 1.
5053 if (reg & PCI_DVSEC_CXL_PORT_CTL_UNMASK_SBR)
5059 static int pci_reset_bus_function(struct pci_dev *dev, bool probe)
5061 struct pci_dev *bridge = pci_upstream_bridge(dev);
5065 * If "dev" is below a CXL port that has SBR control masked, SBR
5066 * won't do anything, so return error.
5068 if (bridge && cxl_sbr_masked(bridge)) {
5075 rc = pci_dev_reset_slot_function(dev, probe);
5078 return pci_parent_bus_reset(dev, probe);
5081 static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
5083 struct pci_dev *bridge;
5084 u16 dvsec, reg, val;
5087 bridge = pci_upstream_bridge(dev);
5091 dvsec = cxl_port_dvsec(bridge);
5098 rc = pci_read_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL, ®);
5102 if (reg & PCI_DVSEC_CXL_PORT_CTL_UNMASK_SBR) {
5105 val = reg | PCI_DVSEC_CXL_PORT_CTL_UNMASK_SBR;
5106 pci_write_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL,
5110 rc = pci_reset_bus_function(dev, probe);
5113 pci_write_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL,
5119 void pci_dev_lock(struct pci_dev *dev)
5121 /* block PM suspend, driver probe, etc. */
5122 device_lock(&dev->dev);
5123 pci_cfg_access_lock(dev);
5125 EXPORT_SYMBOL_GPL(pci_dev_lock);
5127 /* Return 1 on successful lock, 0 on contention */
5128 int pci_dev_trylock(struct pci_dev *dev)
5130 if (device_trylock(&dev->dev)) {
5131 if (pci_cfg_access_trylock(dev))
5133 device_unlock(&dev->dev);
5138 EXPORT_SYMBOL_GPL(pci_dev_trylock);
5140 void pci_dev_unlock(struct pci_dev *dev)
5142 pci_cfg_access_unlock(dev);
5143 device_unlock(&dev->dev);
5145 EXPORT_SYMBOL_GPL(pci_dev_unlock);
5147 static void pci_dev_save_and_disable(struct pci_dev *dev)
5149 const struct pci_error_handlers *err_handler =
5150 dev->driver ? dev->driver->err_handler : NULL;
5153 * dev->driver->err_handler->reset_prepare() is protected against
5154 * races with ->remove() by the device lock, which must be held by
5157 if (err_handler && err_handler->reset_prepare)
5158 err_handler->reset_prepare(dev);
5159 else if (dev->driver)
5160 pci_warn(dev, "resetting");
5163 * Wake-up device prior to save. PM registers default to D0 after
5164 * reset and a simple register restore doesn't reliably return
5165 * to a non-D0 state anyway.
5167 pci_set_power_state(dev, PCI_D0);
5169 pci_save_state(dev);
5171 * Disable the device by clearing the Command register, except for
5172 * INTx-disable which is set. This not only disables MMIO and I/O port
5173 * BARs, but also prevents the device from being Bus Master, preventing
5174 * DMA from the device including MSI/MSI-X interrupts. For PCI 2.3
5175 * compliant devices, INTx-disable prevents legacy interrupts.
5177 pci_write_config_word(dev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
5180 static void pci_dev_restore(struct pci_dev *dev)
5182 const struct pci_error_handlers *err_handler =
5183 dev->driver ? dev->driver->err_handler : NULL;
5185 pci_restore_state(dev);
5188 * dev->driver->err_handler->reset_done() is protected against
5189 * races with ->remove() by the device lock, which must be held by
5192 if (err_handler && err_handler->reset_done)
5193 err_handler->reset_done(dev);
5194 else if (dev->driver)
5195 pci_warn(dev, "reset done");
5198 /* dev->reset_methods[] is a 0-terminated list of indices into this array */
5199 const struct pci_reset_fn_method pci_reset_fn_methods[] = {
5201 { pci_dev_specific_reset, .name = "device_specific" },
5202 { pci_dev_acpi_reset, .name = "acpi" },
5203 { pcie_reset_flr, .name = "flr" },
5204 { pci_af_flr, .name = "af_flr" },
5205 { pci_pm_reset, .name = "pm" },
5206 { pci_reset_bus_function, .name = "bus" },
5207 { cxl_reset_bus_function, .name = "cxl_bus" },
5211 * __pci_reset_function_locked - reset a PCI device function while holding
5212 * the @dev mutex lock.
5213 * @dev: PCI device to reset
5215 * Some devices allow an individual function to be reset without affecting
5216 * other functions in the same device. The PCI device must be responsive
5217 * to PCI config space in order to use this function.
5219 * The device function is presumed to be unused and the caller is holding
5220 * the device mutex lock when this function is called.
5222 * Resetting the device will make the contents of PCI configuration space
5223 * random, so any caller of this must be prepared to reinitialise the
5224 * device including MSI, bus mastering, BARs, decoding IO and memory spaces,
5227 * Returns 0 if the device function was successfully reset or negative if the
5228 * device doesn't support resetting a single function.
5230 int __pci_reset_function_locked(struct pci_dev *dev)
5237 * A reset method returns -ENOTTY if it doesn't support this device and
5238 * we should try the next method.
5240 * If it returns 0 (success), we're finished. If it returns any other
5241 * error, we're also finished: this indicates that further reset
5242 * mechanisms might be broken on the device.
5244 for (i = 0; i < PCI_NUM_RESET_METHODS; i++) {
5245 m = dev->reset_methods[i];
5249 rc = pci_reset_fn_methods[m].reset_fn(dev, PCI_RESET_DO_RESET);
5258 EXPORT_SYMBOL_GPL(__pci_reset_function_locked);
5261 * pci_init_reset_methods - check whether device can be safely reset
5262 * and store supported reset mechanisms.
5263 * @dev: PCI device to check for reset mechanisms
5265 * Some devices allow an individual function to be reset without affecting
5266 * other functions in the same device. The PCI device must be in D0-D3hot
5269 * Stores reset mechanisms supported by device in reset_methods byte array
5270 * which is a member of struct pci_dev.
5272 void pci_init_reset_methods(struct pci_dev *dev)
5276 BUILD_BUG_ON(ARRAY_SIZE(pci_reset_fn_methods) != PCI_NUM_RESET_METHODS);
5281 for (m = 1; m < PCI_NUM_RESET_METHODS; m++) {
5282 rc = pci_reset_fn_methods[m].reset_fn(dev, PCI_RESET_PROBE);
5284 dev->reset_methods[i++] = m;
5285 else if (rc != -ENOTTY)
5289 dev->reset_methods[i] = 0;
5293 * pci_reset_function - quiesce and reset a PCI device function
5294 * @dev: PCI device to reset
5296 * Some devices allow an individual function to be reset without affecting
5297 * other functions in the same device. The PCI device must be responsive
5298 * to PCI config space in order to use this function.
5300 * This function does not just reset the PCI portion of a device, but
5301 * clears all the state associated with the device. This function differs
5302 * from __pci_reset_function_locked() in that it saves and restores device state
5303 * over the reset and takes the PCI device lock.
5305 * Returns 0 if the device function was successfully reset or negative if the
5306 * device doesn't support resetting a single function.
5308 int pci_reset_function(struct pci_dev *dev)
5310 struct pci_dev *bridge;
5313 if (!pci_reset_supported(dev))
5317 * If there's no upstream bridge, no locking is needed since there is
5318 * no upstream bridge configuration to hold consistent.
5320 bridge = pci_upstream_bridge(dev);
5322 pci_dev_lock(bridge);
5325 pci_dev_save_and_disable(dev);
5327 rc = __pci_reset_function_locked(dev);
5329 pci_dev_restore(dev);
5330 pci_dev_unlock(dev);
5333 pci_dev_unlock(bridge);
5337 EXPORT_SYMBOL_GPL(pci_reset_function);
5340 * pci_reset_function_locked - quiesce and reset a PCI device function
5341 * @dev: PCI device to reset
5343 * Some devices allow an individual function to be reset without affecting
5344 * other functions in the same device. The PCI device must be responsive
5345 * to PCI config space in order to use this function.
5347 * This function does not just reset the PCI portion of a device, but
5348 * clears all the state associated with the device. This function differs
5349 * from __pci_reset_function_locked() in that it saves and restores device state
5350 * over the reset. It also differs from pci_reset_function() in that it
5351 * requires the PCI device lock to be held.
5353 * Returns 0 if the device function was successfully reset or negative if the
5354 * device doesn't support resetting a single function.
5356 int pci_reset_function_locked(struct pci_dev *dev)
5360 if (!pci_reset_supported(dev))
5363 pci_dev_save_and_disable(dev);
5365 rc = __pci_reset_function_locked(dev);
5367 pci_dev_restore(dev);
5371 EXPORT_SYMBOL_GPL(pci_reset_function_locked);
5374 * pci_try_reset_function - quiesce and reset a PCI device function
5375 * @dev: PCI device to reset
5377 * Same as above, except return -EAGAIN if unable to lock device.
5379 int pci_try_reset_function(struct pci_dev *dev)
5383 if (!pci_reset_supported(dev))
5386 if (!pci_dev_trylock(dev))
5389 pci_dev_save_and_disable(dev);
5390 rc = __pci_reset_function_locked(dev);
5391 pci_dev_restore(dev);
5392 pci_dev_unlock(dev);
5396 EXPORT_SYMBOL_GPL(pci_try_reset_function);
5398 /* Do any devices on or below this bus prevent a bus reset? */
5399 static bool pci_bus_resettable(struct pci_bus *bus)
5401 struct pci_dev *dev;
5404 if (bus->self && (bus->self->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET))
5407 list_for_each_entry(dev, &bus->devices, bus_list) {
5408 if (dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET ||
5409 (dev->subordinate && !pci_bus_resettable(dev->subordinate)))
5416 /* Lock devices from the top of the tree down */
5417 static void pci_bus_lock(struct pci_bus *bus)
5419 struct pci_dev *dev;
5421 pci_dev_lock(bus->self);
5422 list_for_each_entry(dev, &bus->devices, bus_list) {
5423 if (dev->subordinate)
5424 pci_bus_lock(dev->subordinate);
5430 /* Unlock devices from the bottom of the tree up */
5431 static void pci_bus_unlock(struct pci_bus *bus)
5433 struct pci_dev *dev;
5435 list_for_each_entry(dev, &bus->devices, bus_list) {
5436 if (dev->subordinate)
5437 pci_bus_unlock(dev->subordinate);
5439 pci_dev_unlock(dev);
5441 pci_dev_unlock(bus->self);
5444 /* Return 1 on successful lock, 0 on contention */
5445 static int pci_bus_trylock(struct pci_bus *bus)
5447 struct pci_dev *dev;
5449 if (!pci_dev_trylock(bus->self))
5452 list_for_each_entry(dev, &bus->devices, bus_list) {
5453 if (dev->subordinate) {
5454 if (!pci_bus_trylock(dev->subordinate))
5456 } else if (!pci_dev_trylock(dev))
5462 list_for_each_entry_continue_reverse(dev, &bus->devices, bus_list) {
5463 if (dev->subordinate)
5464 pci_bus_unlock(dev->subordinate);
5466 pci_dev_unlock(dev);
5468 pci_dev_unlock(bus->self);
5472 /* Do any devices on or below this slot prevent a bus reset? */
5473 static bool pci_slot_resettable(struct pci_slot *slot)
5475 struct pci_dev *dev;
5477 if (slot->bus->self &&
5478 (slot->bus->self->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET))
5481 list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5482 if (!dev->slot || dev->slot != slot)
5484 if (dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET ||
5485 (dev->subordinate && !pci_bus_resettable(dev->subordinate)))
5492 /* Lock devices from the top of the tree down */
5493 static void pci_slot_lock(struct pci_slot *slot)
5495 struct pci_dev *dev;
5497 list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5498 if (!dev->slot || dev->slot != slot)
5500 if (dev->subordinate)
5501 pci_bus_lock(dev->subordinate);
5507 /* Unlock devices from the bottom of the tree up */
5508 static void pci_slot_unlock(struct pci_slot *slot)
5510 struct pci_dev *dev;
5512 list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5513 if (!dev->slot || dev->slot != slot)
5515 if (dev->subordinate)
5516 pci_bus_unlock(dev->subordinate);
5517 pci_dev_unlock(dev);
5521 /* Return 1 on successful lock, 0 on contention */
5522 static int pci_slot_trylock(struct pci_slot *slot)
5524 struct pci_dev *dev;
5526 list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5527 if (!dev->slot || dev->slot != slot)
5529 if (dev->subordinate) {
5530 if (!pci_bus_trylock(dev->subordinate)) {
5531 pci_dev_unlock(dev);
5534 } else if (!pci_dev_trylock(dev))
5540 list_for_each_entry_continue_reverse(dev,
5541 &slot->bus->devices, bus_list) {
5542 if (!dev->slot || dev->slot != slot)
5544 if (dev->subordinate)
5545 pci_bus_unlock(dev->subordinate);
5547 pci_dev_unlock(dev);
5553 * Save and disable devices from the top of the tree down while holding
5554 * the @dev mutex lock for the entire tree.
5556 static void pci_bus_save_and_disable_locked(struct pci_bus *bus)
5558 struct pci_dev *dev;
5560 list_for_each_entry(dev, &bus->devices, bus_list) {
5561 pci_dev_save_and_disable(dev);
5562 if (dev->subordinate)
5563 pci_bus_save_and_disable_locked(dev->subordinate);
5568 * Restore devices from top of the tree down while holding @dev mutex lock
5569 * for the entire tree. Parent bridges need to be restored before we can
5570 * get to subordinate devices.
5572 static void pci_bus_restore_locked(struct pci_bus *bus)
5574 struct pci_dev *dev;
5576 list_for_each_entry(dev, &bus->devices, bus_list) {
5577 pci_dev_restore(dev);
5578 if (dev->subordinate) {
5579 pci_bridge_wait_for_secondary_bus(dev, "bus reset");
5580 pci_bus_restore_locked(dev->subordinate);
5586 * Save and disable devices from the top of the tree down while holding
5587 * the @dev mutex lock for the entire tree.
5589 static void pci_slot_save_and_disable_locked(struct pci_slot *slot)
5591 struct pci_dev *dev;
5593 list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5594 if (!dev->slot || dev->slot != slot)
5596 pci_dev_save_and_disable(dev);
5597 if (dev->subordinate)
5598 pci_bus_save_and_disable_locked(dev->subordinate);
5603 * Restore devices from top of the tree down while holding @dev mutex lock
5604 * for the entire tree. Parent bridges need to be restored before we can
5605 * get to subordinate devices.
5607 static void pci_slot_restore_locked(struct pci_slot *slot)
5609 struct pci_dev *dev;
5611 list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5612 if (!dev->slot || dev->slot != slot)
5614 pci_dev_restore(dev);
5615 if (dev->subordinate) {
5616 pci_bridge_wait_for_secondary_bus(dev, "slot reset");
5617 pci_bus_restore_locked(dev->subordinate);
5622 static int pci_slot_reset(struct pci_slot *slot, bool probe)
5626 if (!slot || !pci_slot_resettable(slot))
5630 pci_slot_lock(slot);
5634 rc = pci_reset_hotplug_slot(slot->hotplug, probe);
5637 pci_slot_unlock(slot);
5643 * pci_probe_reset_slot - probe whether a PCI slot can be reset
5644 * @slot: PCI slot to probe
5646 * Return 0 if slot can be reset, negative if a slot reset is not supported.
5648 int pci_probe_reset_slot(struct pci_slot *slot)
5650 return pci_slot_reset(slot, PCI_RESET_PROBE);
5652 EXPORT_SYMBOL_GPL(pci_probe_reset_slot);
5655 * __pci_reset_slot - Try to reset a PCI slot
5656 * @slot: PCI slot to reset
5658 * A PCI bus may host multiple slots, each slot may support a reset mechanism
5659 * independent of other slots. For instance, some slots may support slot power
5660 * control. In the case of a 1:1 bus to slot architecture, this function may
5661 * wrap the bus reset to avoid spurious slot related events such as hotplug.
5662 * Generally a slot reset should be attempted before a bus reset. All of the
5663 * function of the slot and any subordinate buses behind the slot are reset
5664 * through this function. PCI config space of all devices in the slot and
5665 * behind the slot is saved before and restored after reset.
5667 * Same as above except return -EAGAIN if the slot cannot be locked
5669 static int __pci_reset_slot(struct pci_slot *slot)
5673 rc = pci_slot_reset(slot, PCI_RESET_PROBE);
5677 if (pci_slot_trylock(slot)) {
5678 pci_slot_save_and_disable_locked(slot);
5680 rc = pci_reset_hotplug_slot(slot->hotplug, PCI_RESET_DO_RESET);
5681 pci_slot_restore_locked(slot);
5682 pci_slot_unlock(slot);
5689 static int pci_bus_reset(struct pci_bus *bus, bool probe)
5693 if (!bus->self || !pci_bus_resettable(bus))
5703 ret = pci_bridge_secondary_bus_reset(bus->self);
5705 pci_bus_unlock(bus);
5711 * pci_bus_error_reset - reset the bridge's subordinate bus
5712 * @bridge: The parent device that connects to the bus to reset
5714 * This function will first try to reset the slots on this bus if the method is
5715 * available. If slot reset fails or is not available, this will fall back to a
5716 * secondary bus reset.
5718 int pci_bus_error_reset(struct pci_dev *bridge)
5720 struct pci_bus *bus = bridge->subordinate;
5721 struct pci_slot *slot;
5726 mutex_lock(&pci_slot_mutex);
5727 if (list_empty(&bus->slots))
5730 list_for_each_entry(slot, &bus->slots, list)
5731 if (pci_probe_reset_slot(slot))
5734 list_for_each_entry(slot, &bus->slots, list)
5735 if (pci_slot_reset(slot, PCI_RESET_DO_RESET))
5738 mutex_unlock(&pci_slot_mutex);
5741 mutex_unlock(&pci_slot_mutex);
5742 return pci_bus_reset(bridge->subordinate, PCI_RESET_DO_RESET);
5746 * pci_probe_reset_bus - probe whether a PCI bus can be reset
5747 * @bus: PCI bus to probe
5749 * Return 0 if bus can be reset, negative if a bus reset is not supported.
5751 int pci_probe_reset_bus(struct pci_bus *bus)
5753 return pci_bus_reset(bus, PCI_RESET_PROBE);
5755 EXPORT_SYMBOL_GPL(pci_probe_reset_bus);
5758 * __pci_reset_bus - Try to reset a PCI bus
5759 * @bus: top level PCI bus to reset
5761 * Same as above except return -EAGAIN if the bus cannot be locked
5763 int __pci_reset_bus(struct pci_bus *bus)
5767 rc = pci_bus_reset(bus, PCI_RESET_PROBE);
5771 if (pci_bus_trylock(bus)) {
5772 pci_bus_save_and_disable_locked(bus);
5774 rc = pci_bridge_secondary_bus_reset(bus->self);
5775 pci_bus_restore_locked(bus);
5776 pci_bus_unlock(bus);
5784 * pci_reset_bus - Try to reset a PCI bus
5785 * @pdev: top level PCI device to reset via slot/bus
5787 * Same as above except return -EAGAIN if the bus cannot be locked
5789 int pci_reset_bus(struct pci_dev *pdev)
5791 return (!pci_probe_reset_slot(pdev->slot)) ?
5792 __pci_reset_slot(pdev->slot) : __pci_reset_bus(pdev->bus);
5794 EXPORT_SYMBOL_GPL(pci_reset_bus);
5797 * pcix_get_max_mmrbc - get PCI-X maximum designed memory read byte count
5798 * @dev: PCI device to query
5800 * Returns mmrbc: maximum designed memory read count in bytes or
5801 * appropriate error value.
5803 int pcix_get_max_mmrbc(struct pci_dev *dev)
5808 cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
5812 if (pci_read_config_dword(dev, cap + PCI_X_STATUS, &stat))
5815 return 512 << FIELD_GET(PCI_X_STATUS_MAX_READ, stat);
5817 EXPORT_SYMBOL(pcix_get_max_mmrbc);
5820 * pcix_get_mmrbc - get PCI-X maximum memory read byte count
5821 * @dev: PCI device to query
5823 * Returns mmrbc: maximum memory read count in bytes or appropriate error
5826 int pcix_get_mmrbc(struct pci_dev *dev)
5831 cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
5835 if (pci_read_config_word(dev, cap + PCI_X_CMD, &cmd))
5838 return 512 << FIELD_GET(PCI_X_CMD_MAX_READ, cmd);
5840 EXPORT_SYMBOL(pcix_get_mmrbc);
5843 * pcix_set_mmrbc - set PCI-X maximum memory read byte count
5844 * @dev: PCI device to query
5845 * @mmrbc: maximum memory read count in bytes
5846 * valid values are 512, 1024, 2048, 4096
5848 * If possible sets maximum memory read byte count, some bridges have errata
5849 * that prevent this.
5851 int pcix_set_mmrbc(struct pci_dev *dev, int mmrbc)
5857 if (mmrbc < 512 || mmrbc > 4096 || !is_power_of_2(mmrbc))
5860 v = ffs(mmrbc) - 10;
5862 cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
5866 if (pci_read_config_dword(dev, cap + PCI_X_STATUS, &stat))
5869 if (v > FIELD_GET(PCI_X_STATUS_MAX_READ, stat))
5872 if (pci_read_config_word(dev, cap + PCI_X_CMD, &cmd))
5875 o = FIELD_GET(PCI_X_CMD_MAX_READ, cmd);
5877 if (v > o && (dev->bus->bus_flags & PCI_BUS_FLAGS_NO_MMRBC))
5880 cmd &= ~PCI_X_CMD_MAX_READ;
5881 cmd |= FIELD_PREP(PCI_X_CMD_MAX_READ, v);
5882 if (pci_write_config_word(dev, cap + PCI_X_CMD, cmd))
5887 EXPORT_SYMBOL(pcix_set_mmrbc);
5890 * pcie_get_readrq - get PCI Express read request size
5891 * @dev: PCI device to query
5893 * Returns maximum memory read request in bytes or appropriate error value.
5895 int pcie_get_readrq(struct pci_dev *dev)
5899 pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &ctl);
5901 return 128 << FIELD_GET(PCI_EXP_DEVCTL_READRQ, ctl);
5903 EXPORT_SYMBOL(pcie_get_readrq);
5906 * pcie_set_readrq - set PCI Express maximum memory read request
5907 * @dev: PCI device to query
5908 * @rq: maximum memory read count in bytes
5909 * valid values are 128, 256, 512, 1024, 2048, 4096
5911 * If possible sets maximum memory read request in bytes
5913 int pcie_set_readrq(struct pci_dev *dev, int rq)
5917 struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus);
5919 if (rq < 128 || rq > 4096 || !is_power_of_2(rq))
5923 * If using the "performance" PCIe config, we clamp the read rq
5924 * size to the max packet size to keep the host bridge from
5925 * generating requests larger than we can cope with.
5927 if (pcie_bus_config == PCIE_BUS_PERFORMANCE) {
5928 int mps = pcie_get_mps(dev);
5934 v = FIELD_PREP(PCI_EXP_DEVCTL_READRQ, ffs(rq) - 8);
5936 if (bridge->no_inc_mrrs) {
5937 int max_mrrs = pcie_get_readrq(dev);
5939 if (rq > max_mrrs) {
5940 pci_info(dev, "can't set Max_Read_Request_Size to %d; max is %d\n", rq, max_mrrs);
5945 ret = pcie_capability_clear_and_set_word(dev, PCI_EXP_DEVCTL,
5946 PCI_EXP_DEVCTL_READRQ, v);
5948 return pcibios_err_to_errno(ret);
5950 EXPORT_SYMBOL(pcie_set_readrq);
5953 * pcie_get_mps - get PCI Express maximum payload size
5954 * @dev: PCI device to query
5956 * Returns maximum payload size in bytes
5958 int pcie_get_mps(struct pci_dev *dev)
5962 pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &ctl);
5964 return 128 << FIELD_GET(PCI_EXP_DEVCTL_PAYLOAD, ctl);
5966 EXPORT_SYMBOL(pcie_get_mps);
5969 * pcie_set_mps - set PCI Express maximum payload size
5970 * @dev: PCI device to query
5971 * @mps: maximum payload size in bytes
5972 * valid values are 128, 256, 512, 1024, 2048, 4096
5974 * If possible sets maximum payload size
5976 int pcie_set_mps(struct pci_dev *dev, int mps)
5981 if (mps < 128 || mps > 4096 || !is_power_of_2(mps))
5985 if (v > dev->pcie_mpss)
5987 v = FIELD_PREP(PCI_EXP_DEVCTL_PAYLOAD, v);
5989 ret = pcie_capability_clear_and_set_word(dev, PCI_EXP_DEVCTL,
5990 PCI_EXP_DEVCTL_PAYLOAD, v);
5992 return pcibios_err_to_errno(ret);
5994 EXPORT_SYMBOL(pcie_set_mps);
5996 static enum pci_bus_speed to_pcie_link_speed(u16 lnksta)
5998 return pcie_link_speed[FIELD_GET(PCI_EXP_LNKSTA_CLS, lnksta)];
6001 int pcie_link_speed_mbps(struct pci_dev *pdev)
6006 err = pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnksta);
6010 return pcie_dev_speed_mbps(to_pcie_link_speed(lnksta));
6012 EXPORT_SYMBOL(pcie_link_speed_mbps);
6015 * pcie_bandwidth_available - determine minimum link settings of a PCIe
6016 * device and its bandwidth limitation
6017 * @dev: PCI device to query
6018 * @limiting_dev: storage for device causing the bandwidth limitation
6019 * @speed: storage for speed of limiting device
6020 * @width: storage for width of limiting device
6022 * Walk up the PCI device chain and find the point where the minimum
6023 * bandwidth is available. Return the bandwidth available there and (if
6024 * limiting_dev, speed, and width pointers are supplied) information about
6025 * that point. The bandwidth returned is in Mb/s, i.e., megabits/second of
6028 u32 pcie_bandwidth_available(struct pci_dev *dev, struct pci_dev **limiting_dev,
6029 enum pci_bus_speed *speed,
6030 enum pcie_link_width *width)
6033 enum pci_bus_speed next_speed;
6034 enum pcie_link_width next_width;
6038 *speed = PCI_SPEED_UNKNOWN;
6040 *width = PCIE_LNK_WIDTH_UNKNOWN;
6045 pcie_capability_read_word(dev, PCI_EXP_LNKSTA, &lnksta);
6047 next_speed = to_pcie_link_speed(lnksta);
6048 next_width = FIELD_GET(PCI_EXP_LNKSTA_NLW, lnksta);
6050 next_bw = next_width * PCIE_SPEED2MBS_ENC(next_speed);
6052 /* Check if current device limits the total bandwidth */
6053 if (!bw || next_bw <= bw) {
6057 *limiting_dev = dev;
6059 *speed = next_speed;
6061 *width = next_width;
6064 dev = pci_upstream_bridge(dev);
6069 EXPORT_SYMBOL(pcie_bandwidth_available);
6072 * pcie_get_supported_speeds - query Supported Link Speed Vector
6073 * @dev: PCI device to query
6075 * Query @dev supported link speeds.
6077 * Implementation Note in PCIe r6.0 sec 7.5.3.18 recommends determining
6078 * supported link speeds using the Supported Link Speeds Vector in the Link
6079 * Capabilities 2 Register (when available).
6081 * Link Capabilities 2 was added in PCIe r3.0, sec 7.8.18.
6083 * Without Link Capabilities 2, i.e., prior to PCIe r3.0, Supported Link
6084 * Speeds field in Link Capabilities is used and only 2.5 GT/s and 5.0 GT/s
6085 * speeds were defined.
6087 * For @dev without Supported Link Speed Vector, the field is synthesized
6088 * from the Max Link Speed field in the Link Capabilities Register.
6090 * Return: Supported Link Speeds Vector (+ reserved 0 at LSB).
6092 u8 pcie_get_supported_speeds(struct pci_dev *dev)
6094 u32 lnkcap2, lnkcap;
6098 * Speeds retain the reserved 0 at LSB before PCIe Supported Link
6099 * Speeds Vector to allow using SLS Vector bit defines directly.
6101 pcie_capability_read_dword(dev, PCI_EXP_LNKCAP2, &lnkcap2);
6102 speeds = lnkcap2 & PCI_EXP_LNKCAP2_SLS;
6104 /* Ignore speeds higher than Max Link Speed */
6105 pcie_capability_read_dword(dev, PCI_EXP_LNKCAP, &lnkcap);
6106 speeds &= GENMASK(lnkcap & PCI_EXP_LNKCAP_SLS, 0);
6108 /* PCIe r3.0-compliant */
6112 /* Synthesize from the Max Link Speed field */
6113 if ((lnkcap & PCI_EXP_LNKCAP_SLS) == PCI_EXP_LNKCAP_SLS_5_0GB)
6114 speeds = PCI_EXP_LNKCAP2_SLS_5_0GB | PCI_EXP_LNKCAP2_SLS_2_5GB;
6115 else if ((lnkcap & PCI_EXP_LNKCAP_SLS) == PCI_EXP_LNKCAP_SLS_2_5GB)
6116 speeds = PCI_EXP_LNKCAP2_SLS_2_5GB;
6122 * pcie_get_speed_cap - query for the PCI device's link speed capability
6123 * @dev: PCI device to query
6125 * Query the PCI device speed capability.
6127 * Return: the maximum link speed supported by the device.
6129 enum pci_bus_speed pcie_get_speed_cap(struct pci_dev *dev)
6131 return PCIE_LNKCAP2_SLS2SPEED(dev->supported_speeds);
6133 EXPORT_SYMBOL(pcie_get_speed_cap);
6136 * pcie_get_width_cap - query for the PCI device's link width capability
6137 * @dev: PCI device to query
6139 * Query the PCI device width capability. Return the maximum link width
6140 * supported by the device.
6142 enum pcie_link_width pcie_get_width_cap(struct pci_dev *dev)
6146 pcie_capability_read_dword(dev, PCI_EXP_LNKCAP, &lnkcap);
6148 return FIELD_GET(PCI_EXP_LNKCAP_MLW, lnkcap);
6150 return PCIE_LNK_WIDTH_UNKNOWN;
6152 EXPORT_SYMBOL(pcie_get_width_cap);
6155 * pcie_bandwidth_capable - calculate a PCI device's link bandwidth capability
6157 * @speed: storage for link speed
6158 * @width: storage for link width
6160 * Calculate a PCI device's link bandwidth by querying for its link speed
6161 * and width, multiplying them, and applying encoding overhead. The result
6162 * is in Mb/s, i.e., megabits/second of raw bandwidth.
6164 static u32 pcie_bandwidth_capable(struct pci_dev *dev,
6165 enum pci_bus_speed *speed,
6166 enum pcie_link_width *width)
6168 *speed = pcie_get_speed_cap(dev);
6169 *width = pcie_get_width_cap(dev);
6171 if (*speed == PCI_SPEED_UNKNOWN || *width == PCIE_LNK_WIDTH_UNKNOWN)
6174 return *width * PCIE_SPEED2MBS_ENC(*speed);
6178 * __pcie_print_link_status - Report the PCI device's link speed and width
6179 * @dev: PCI device to query
6180 * @verbose: Print info even when enough bandwidth is available
6182 * If the available bandwidth at the device is less than the device is
6183 * capable of, report the device's maximum possible bandwidth and the
6184 * upstream link that limits its performance. If @verbose, always print
6185 * the available bandwidth, even if the device isn't constrained.
6187 void __pcie_print_link_status(struct pci_dev *dev, bool verbose)
6189 enum pcie_link_width width, width_cap;
6190 enum pci_bus_speed speed, speed_cap;
6191 struct pci_dev *limiting_dev = NULL;
6192 u32 bw_avail, bw_cap;
6194 bw_cap = pcie_bandwidth_capable(dev, &speed_cap, &width_cap);
6195 bw_avail = pcie_bandwidth_available(dev, &limiting_dev, &speed, &width);
6197 if (bw_avail >= bw_cap && verbose)
6198 pci_info(dev, "%u.%03u Gb/s available PCIe bandwidth (%s x%d link)\n",
6199 bw_cap / 1000, bw_cap % 1000,
6200 pci_speed_string(speed_cap), width_cap);
6201 else if (bw_avail < bw_cap)
6202 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",
6203 bw_avail / 1000, bw_avail % 1000,
6204 pci_speed_string(speed), width,
6205 limiting_dev ? pci_name(limiting_dev) : "<unknown>",
6206 bw_cap / 1000, bw_cap % 1000,
6207 pci_speed_string(speed_cap), width_cap);
6211 * pcie_print_link_status - Report the PCI device's link speed and width
6212 * @dev: PCI device to query
6214 * Report the available bandwidth at the device.
6216 void pcie_print_link_status(struct pci_dev *dev)
6218 __pcie_print_link_status(dev, true);
6220 EXPORT_SYMBOL(pcie_print_link_status);
6223 * pci_select_bars - Make BAR mask from the type of resource
6224 * @dev: the PCI device for which BAR mask is made
6225 * @flags: resource type mask to be selected
6227 * This helper routine makes bar mask from the type of resource.
6229 int pci_select_bars(struct pci_dev *dev, unsigned long flags)
6232 for (i = 0; i < PCI_NUM_RESOURCES; i++)
6233 if (pci_resource_flags(dev, i) & flags)
6237 EXPORT_SYMBOL(pci_select_bars);
6239 /* Some architectures require additional programming to enable VGA */
6240 static arch_set_vga_state_t arch_set_vga_state;
6242 void __init pci_register_set_vga_state(arch_set_vga_state_t func)
6244 arch_set_vga_state = func; /* NULL disables */
6247 static int pci_set_vga_state_arch(struct pci_dev *dev, bool decode,
6248 unsigned int command_bits, u32 flags)
6250 if (arch_set_vga_state)
6251 return arch_set_vga_state(dev, decode, command_bits,
6257 * pci_set_vga_state - set VGA decode state on device and parents if requested
6258 * @dev: the PCI device
6259 * @decode: true = enable decoding, false = disable decoding
6260 * @command_bits: PCI_COMMAND_IO and/or PCI_COMMAND_MEMORY
6261 * @flags: traverse ancestors and change bridges
6262 * CHANGE_BRIDGE_ONLY / CHANGE_BRIDGE
6264 int pci_set_vga_state(struct pci_dev *dev, bool decode,
6265 unsigned int command_bits, u32 flags)
6267 struct pci_bus *bus;
6268 struct pci_dev *bridge;
6272 WARN_ON((flags & PCI_VGA_STATE_CHANGE_DECODES) && (command_bits & ~(PCI_COMMAND_IO|PCI_COMMAND_MEMORY)));
6274 /* ARCH specific VGA enables */
6275 rc = pci_set_vga_state_arch(dev, decode, command_bits, flags);
6279 if (flags & PCI_VGA_STATE_CHANGE_DECODES) {
6280 pci_read_config_word(dev, PCI_COMMAND, &cmd);
6282 cmd |= command_bits;
6284 cmd &= ~command_bits;
6285 pci_write_config_word(dev, PCI_COMMAND, cmd);
6288 if (!(flags & PCI_VGA_STATE_CHANGE_BRIDGE))
6295 pci_read_config_word(bridge, PCI_BRIDGE_CONTROL,
6298 cmd |= PCI_BRIDGE_CTL_VGA;
6300 cmd &= ~PCI_BRIDGE_CTL_VGA;
6301 pci_write_config_word(bridge, PCI_BRIDGE_CONTROL,
6310 bool pci_pr3_present(struct pci_dev *pdev)
6312 struct acpi_device *adev;
6317 adev = ACPI_COMPANION(&pdev->dev);
6321 return adev->power.flags.power_resources &&
6322 acpi_has_method(adev->handle, "_PR3");
6324 EXPORT_SYMBOL_GPL(pci_pr3_present);
6328 * pci_add_dma_alias - Add a DMA devfn alias for a device
6329 * @dev: the PCI device for which alias is added
6330 * @devfn_from: alias slot and function
6331 * @nr_devfns: number of subsequent devfns to alias
6333 * This helper encodes an 8-bit devfn as a bit number in dma_alias_mask
6334 * which is used to program permissible bus-devfn source addresses for DMA
6335 * requests in an IOMMU. These aliases factor into IOMMU group creation
6336 * and are useful for devices generating DMA requests beyond or different
6337 * from their logical bus-devfn. Examples include device quirks where the
6338 * device simply uses the wrong devfn, as well as non-transparent bridges
6339 * where the alias may be a proxy for devices in another domain.
6341 * IOMMU group creation is performed during device discovery or addition,
6342 * prior to any potential DMA mapping and therefore prior to driver probing
6343 * (especially for userspace assigned devices where IOMMU group definition
6344 * cannot be left as a userspace activity). DMA aliases should therefore
6345 * be configured via quirks, such as the PCI fixup header quirk.
6347 void pci_add_dma_alias(struct pci_dev *dev, u8 devfn_from,
6348 unsigned int nr_devfns)
6352 nr_devfns = min(nr_devfns, (unsigned int)MAX_NR_DEVFNS - devfn_from);
6353 devfn_to = devfn_from + nr_devfns - 1;
6355 if (!dev->dma_alias_mask)
6356 dev->dma_alias_mask = bitmap_zalloc(MAX_NR_DEVFNS, GFP_KERNEL);
6357 if (!dev->dma_alias_mask) {
6358 pci_warn(dev, "Unable to allocate DMA alias mask\n");
6362 bitmap_set(dev->dma_alias_mask, devfn_from, nr_devfns);
6365 pci_info(dev, "Enabling fixed DMA alias to %02x.%d\n",
6366 PCI_SLOT(devfn_from), PCI_FUNC(devfn_from));
6367 else if (nr_devfns > 1)
6368 pci_info(dev, "Enabling fixed DMA alias for devfn range from %02x.%d to %02x.%d\n",
6369 PCI_SLOT(devfn_from), PCI_FUNC(devfn_from),
6370 PCI_SLOT(devfn_to), PCI_FUNC(devfn_to));
6373 bool pci_devs_are_dma_aliases(struct pci_dev *dev1, struct pci_dev *dev2)
6375 return (dev1->dma_alias_mask &&
6376 test_bit(dev2->devfn, dev1->dma_alias_mask)) ||
6377 (dev2->dma_alias_mask &&
6378 test_bit(dev1->devfn, dev2->dma_alias_mask)) ||
6379 pci_real_dma_dev(dev1) == dev2 ||
6380 pci_real_dma_dev(dev2) == dev1;
6383 bool pci_device_is_present(struct pci_dev *pdev)
6387 /* Check PF if pdev is a VF, since VF Vendor/Device IDs are 0xffff */
6388 pdev = pci_physfn(pdev);
6389 if (pci_dev_is_disconnected(pdev))
6391 return pci_bus_read_dev_vendor_id(pdev->bus, pdev->devfn, &v, 0);
6393 EXPORT_SYMBOL_GPL(pci_device_is_present);
6395 void pci_ignore_hotplug(struct pci_dev *dev)
6397 struct pci_dev *bridge = dev->bus->self;
6399 dev->ignore_hotplug = 1;
6400 /* Propagate the "ignore hotplug" setting to the parent bridge. */
6402 bridge->ignore_hotplug = 1;
6404 EXPORT_SYMBOL_GPL(pci_ignore_hotplug);
6407 * pci_real_dma_dev - Get PCI DMA device for PCI device
6408 * @dev: the PCI device that may have a PCI DMA alias
6410 * Permits the platform to provide architecture-specific functionality to
6411 * devices needing to alias DMA to another PCI device on another PCI bus. If
6412 * the PCI device is on the same bus, it is recommended to use
6413 * pci_add_dma_alias(). This is the default implementation. Architecture
6414 * implementations can override this.
6416 struct pci_dev __weak *pci_real_dma_dev(struct pci_dev *dev)
6421 resource_size_t __weak pcibios_default_alignment(void)
6427 * Arches that don't want to expose struct resource to userland as-is in
6428 * sysfs and /proc can implement their own pci_resource_to_user().
6430 void __weak pci_resource_to_user(const struct pci_dev *dev, int bar,
6431 const struct resource *rsrc,
6432 resource_size_t *start, resource_size_t *end)
6434 *start = rsrc->start;
6438 static char *resource_alignment_param;
6439 static DEFINE_SPINLOCK(resource_alignment_lock);
6442 * pci_specified_resource_alignment - get resource alignment specified by user.
6443 * @dev: the PCI device to get
6444 * @resize: whether or not to change resources' size when reassigning alignment
6446 * RETURNS: Resource alignment if it is specified.
6447 * Zero if it is not specified.
6449 static resource_size_t pci_specified_resource_alignment(struct pci_dev *dev,
6452 int align_order, count;
6453 resource_size_t align = pcibios_default_alignment();
6457 spin_lock(&resource_alignment_lock);
6458 p = resource_alignment_param;
6461 if (pci_has_flag(PCI_PROBE_ONLY)) {
6463 pr_info_once("PCI: Ignoring requested alignments (PCI_PROBE_ONLY)\n");
6469 if (sscanf(p, "%d%n", &align_order, &count) == 1 &&
6472 if (align_order > 63) {
6473 pr_err("PCI: Invalid requested alignment (order %d)\n",
6475 align_order = PAGE_SHIFT;
6478 align_order = PAGE_SHIFT;
6481 ret = pci_dev_str_match(dev, p, &p);
6484 align = 1ULL << align_order;
6486 } else if (ret < 0) {
6487 pr_err("PCI: Can't parse resource_alignment parameter: %s\n",
6492 if (*p != ';' && *p != ',') {
6493 /* End of param or invalid format */
6499 spin_unlock(&resource_alignment_lock);
6503 static void pci_request_resource_alignment(struct pci_dev *dev, int bar,
6504 resource_size_t align, bool resize)
6506 struct resource *r = &dev->resource[bar];
6507 const char *r_name = pci_resource_name(dev, bar);
6508 resource_size_t size;
6510 if (!(r->flags & IORESOURCE_MEM))
6513 if (r->flags & IORESOURCE_PCI_FIXED) {
6514 pci_info(dev, "%s %pR: ignoring requested alignment %#llx\n",
6515 r_name, r, (unsigned long long)align);
6519 size = resource_size(r);
6524 * Increase the alignment of the resource. There are two ways we
6527 * 1) Increase the size of the resource. BARs are aligned on their
6528 * size, so when we reallocate space for this resource, we'll
6529 * allocate it with the larger alignment. This also prevents
6530 * assignment of any other BARs inside the alignment region, so
6531 * if we're requesting page alignment, this means no other BARs
6532 * will share the page.
6534 * The disadvantage is that this makes the resource larger than
6535 * the hardware BAR, which may break drivers that compute things
6536 * based on the resource size, e.g., to find registers at a
6537 * fixed offset before the end of the BAR.
6539 * 2) Retain the resource size, but use IORESOURCE_STARTALIGN and
6540 * set r->start to the desired alignment. By itself this
6541 * doesn't prevent other BARs being put inside the alignment
6542 * region, but if we realign *every* resource of every device in
6543 * the system, none of them will share an alignment region.
6545 * When the user has requested alignment for only some devices via
6546 * the "pci=resource_alignment" argument, "resize" is true and we
6547 * use the first method. Otherwise we assume we're aligning all
6548 * devices and we use the second.
6551 pci_info(dev, "%s %pR: requesting alignment to %#llx\n",
6552 r_name, r, (unsigned long long)align);
6558 r->flags &= ~IORESOURCE_SIZEALIGN;
6559 r->flags |= IORESOURCE_STARTALIGN;
6560 resource_set_range(r, align, size);
6562 r->flags |= IORESOURCE_UNSET;
6566 * This function disables memory decoding and releases memory resources
6567 * of the device specified by kernel's boot parameter 'pci=resource_alignment='.
6568 * It also rounds up size to specified alignment.
6569 * Later on, the kernel will assign page-aligned memory resource back
6572 void pci_reassigndev_resource_alignment(struct pci_dev *dev)
6576 resource_size_t align;
6578 bool resize = false;
6581 * VF BARs are read-only zero according to SR-IOV spec r1.1, sec
6582 * 3.4.1.11. Their resources are allocated from the space
6583 * described by the VF BARx register in the PF's SR-IOV capability.
6584 * We can't influence their alignment here.
6589 /* check if specified PCI is target device to reassign */
6590 align = pci_specified_resource_alignment(dev, &resize);
6594 if (dev->hdr_type == PCI_HEADER_TYPE_NORMAL &&
6595 (dev->class >> 8) == PCI_CLASS_BRIDGE_HOST) {
6596 pci_warn(dev, "Can't reassign resources to host bridge\n");
6600 pci_read_config_word(dev, PCI_COMMAND, &command);
6601 command &= ~PCI_COMMAND_MEMORY;
6602 pci_write_config_word(dev, PCI_COMMAND, command);
6604 for (i = 0; i <= PCI_ROM_RESOURCE; i++)
6605 pci_request_resource_alignment(dev, i, align, resize);
6608 * Need to disable bridge's resource window,
6609 * to enable the kernel to reassign new resource
6612 if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
6613 for (i = PCI_BRIDGE_RESOURCES; i < PCI_NUM_RESOURCES; i++) {
6614 r = &dev->resource[i];
6615 if (!(r->flags & IORESOURCE_MEM))
6617 r->flags |= IORESOURCE_UNSET;
6618 r->end = resource_size(r) - 1;
6621 pci_disable_bridge_window(dev);
6625 static ssize_t resource_alignment_show(const struct bus_type *bus, char *buf)
6629 spin_lock(&resource_alignment_lock);
6630 if (resource_alignment_param)
6631 count = sysfs_emit(buf, "%s\n", resource_alignment_param);
6632 spin_unlock(&resource_alignment_lock);
6637 static ssize_t resource_alignment_store(const struct bus_type *bus,
6638 const char *buf, size_t count)
6640 char *param, *old, *end;
6642 if (count >= (PAGE_SIZE - 1))
6645 param = kstrndup(buf, count, GFP_KERNEL);
6649 end = strchr(param, '\n');
6653 spin_lock(&resource_alignment_lock);
6654 old = resource_alignment_param;
6655 if (strlen(param)) {
6656 resource_alignment_param = param;
6659 resource_alignment_param = NULL;
6661 spin_unlock(&resource_alignment_lock);
6668 static BUS_ATTR_RW(resource_alignment);
6670 static int __init pci_resource_alignment_sysfs_init(void)
6672 return bus_create_file(&pci_bus_type,
6673 &bus_attr_resource_alignment);
6675 late_initcall(pci_resource_alignment_sysfs_init);
6677 static void pci_no_domains(void)
6679 #ifdef CONFIG_PCI_DOMAINS
6680 pci_domains_supported = 0;
6684 #ifdef CONFIG_PCI_DOMAINS_GENERIC
6685 static DEFINE_IDA(pci_domain_nr_static_ida);
6686 static DEFINE_IDA(pci_domain_nr_dynamic_ida);
6688 static void of_pci_reserve_static_domain_nr(void)
6690 struct device_node *np;
6693 for_each_node_by_type(np, "pci") {
6694 domain_nr = of_get_pci_domain_nr(np);
6698 * Permanently allocate domain_nr in dynamic_ida
6699 * to prevent it from dynamic allocation.
6701 ida_alloc_range(&pci_domain_nr_dynamic_ida,
6702 domain_nr, domain_nr, GFP_KERNEL);
6706 static int of_pci_bus_find_domain_nr(struct device *parent)
6708 static bool static_domains_reserved = false;
6711 /* On the first call scan device tree for static allocations. */
6712 if (!static_domains_reserved) {
6713 of_pci_reserve_static_domain_nr();
6714 static_domains_reserved = true;
6719 * If domain is in DT, allocate it in static IDA. This
6720 * prevents duplicate static allocations in case of errors
6723 domain_nr = of_get_pci_domain_nr(parent->of_node);
6725 return ida_alloc_range(&pci_domain_nr_static_ida,
6726 domain_nr, domain_nr,
6731 * If domain was not specified in DT, choose a free ID from dynamic
6732 * allocations. All domain numbers from DT are permanently in
6733 * dynamic allocations to prevent assigning them to other DT nodes
6734 * without static domain.
6736 return ida_alloc(&pci_domain_nr_dynamic_ida, GFP_KERNEL);
6739 static void of_pci_bus_release_domain_nr(struct device *parent, int domain_nr)
6744 /* Release domain from IDA where it was allocated. */
6745 if (of_get_pci_domain_nr(parent->of_node) == domain_nr)
6746 ida_free(&pci_domain_nr_static_ida, domain_nr);
6748 ida_free(&pci_domain_nr_dynamic_ida, domain_nr);
6751 int pci_bus_find_domain_nr(struct pci_bus *bus, struct device *parent)
6753 return acpi_disabled ? of_pci_bus_find_domain_nr(parent) :
6754 acpi_pci_bus_find_domain_nr(bus);
6757 void pci_bus_release_domain_nr(struct device *parent, int domain_nr)
6761 of_pci_bus_release_domain_nr(parent, domain_nr);
6766 * pci_ext_cfg_avail - can we access extended PCI config space?
6768 * Returns 1 if we can access PCI extended config space (offsets
6769 * greater than 0xff). This is the default implementation. Architecture
6770 * implementations can override this.
6772 int __weak pci_ext_cfg_avail(void)
6777 void __weak pci_fixup_cardbus(struct pci_bus *bus)
6780 EXPORT_SYMBOL(pci_fixup_cardbus);
6782 static int __init pci_setup(char *str)
6785 char *k = strchr(str, ',');
6788 if (*str && (str = pcibios_setup(str)) && *str) {
6789 if (!strcmp(str, "nomsi")) {
6791 } else if (!strncmp(str, "noats", 5)) {
6792 pr_info("PCIe: ATS is disabled\n");
6793 pcie_ats_disabled = true;
6794 } else if (!strcmp(str, "noaer")) {
6796 } else if (!strcmp(str, "earlydump")) {
6797 pci_early_dump = true;
6798 } else if (!strncmp(str, "realloc=", 8)) {
6799 pci_realloc_get_opt(str + 8);
6800 } else if (!strncmp(str, "realloc", 7)) {
6801 pci_realloc_get_opt("on");
6802 } else if (!strcmp(str, "nodomains")) {
6804 } else if (!strncmp(str, "noari", 5)) {
6805 pcie_ari_disabled = true;
6806 } else if (!strncmp(str, "notph", 5)) {
6808 } else if (!strncmp(str, "cbiosize=", 9)) {
6809 pci_cardbus_io_size = memparse(str + 9, &str);
6810 } else if (!strncmp(str, "cbmemsize=", 10)) {
6811 pci_cardbus_mem_size = memparse(str + 10, &str);
6812 } else if (!strncmp(str, "resource_alignment=", 19)) {
6813 resource_alignment_param = str + 19;
6814 } else if (!strncmp(str, "ecrc=", 5)) {
6815 pcie_ecrc_get_policy(str + 5);
6816 } else if (!strncmp(str, "hpiosize=", 9)) {
6817 pci_hotplug_io_size = memparse(str + 9, &str);
6818 } else if (!strncmp(str, "hpmmiosize=", 11)) {
6819 pci_hotplug_mmio_size = memparse(str + 11, &str);
6820 } else if (!strncmp(str, "hpmmioprefsize=", 15)) {
6821 pci_hotplug_mmio_pref_size = memparse(str + 15, &str);
6822 } else if (!strncmp(str, "hpmemsize=", 10)) {
6823 pci_hotplug_mmio_size = memparse(str + 10, &str);
6824 pci_hotplug_mmio_pref_size = pci_hotplug_mmio_size;
6825 } else if (!strncmp(str, "hpbussize=", 10)) {
6826 pci_hotplug_bus_size =
6827 simple_strtoul(str + 10, &str, 0);
6828 if (pci_hotplug_bus_size > 0xff)
6829 pci_hotplug_bus_size = DEFAULT_HOTPLUG_BUS_SIZE;
6830 } else if (!strncmp(str, "pcie_bus_tune_off", 17)) {
6831 pcie_bus_config = PCIE_BUS_TUNE_OFF;
6832 } else if (!strncmp(str, "pcie_bus_safe", 13)) {
6833 pcie_bus_config = PCIE_BUS_SAFE;
6834 } else if (!strncmp(str, "pcie_bus_perf", 13)) {
6835 pcie_bus_config = PCIE_BUS_PERFORMANCE;
6836 } else if (!strncmp(str, "pcie_bus_peer2peer", 18)) {
6837 pcie_bus_config = PCIE_BUS_PEER2PEER;
6838 } else if (!strncmp(str, "pcie_scan_all", 13)) {
6839 pci_add_flags(PCI_SCAN_ALL_PCIE_DEVS);
6840 } else if (!strncmp(str, "disable_acs_redir=", 18)) {
6841 disable_acs_redir_param = str + 18;
6842 } else if (!strncmp(str, "config_acs=", 11)) {
6843 config_acs_param = str + 11;
6845 pr_err("PCI: Unknown option `%s'\n", str);
6852 early_param("pci", pci_setup);
6855 * 'resource_alignment_param' and 'disable_acs_redir_param' are initialized
6856 * in pci_setup(), above, to point to data in the __initdata section which
6857 * will be freed after the init sequence is complete. We can't allocate memory
6858 * in pci_setup() because some architectures do not have any memory allocation
6859 * service available during an early_param() call. So we allocate memory and
6860 * copy the variable here before the init section is freed.
6863 static int __init pci_realloc_setup_params(void)
6865 resource_alignment_param = kstrdup(resource_alignment_param,
6867 disable_acs_redir_param = kstrdup(disable_acs_redir_param, GFP_KERNEL);
6868 config_acs_param = kstrdup(config_acs_param, GFP_KERNEL);
6872 pure_initcall(pci_realloc_setup_params);