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