xref: /linux/drivers/pci/pci.c (revision 2a31b5378c6db9c4a8d399e5d10d32cd4b732bef)
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 
3774 		/*
3775 		 * A hypervisor may expose a topology with the root port
3776 		 * not visible to the guest.  If the hypervisor has already
3777 		 * set AtomicOp Requester Enable in the endpoint, we assume
3778 		 * it has verified support in the root port, so it is safe
3779 		 * for the driver to use AtomicOps.
3780 		 */
3781 		pcie_capability_read_dword(dev, PCI_EXP_DEVCTL2, &ctl2);
3782 		if (ctl2 & PCI_EXP_DEVCTL2_ATOMIC_REQ)
3783 			return 0;
3784 
3785 		return -EINVAL;
3786 	}
3787 
3788 	pcie_capability_read_dword(root, PCI_EXP_DEVCAP2, &cap);
3789 	if ((cap & cap_mask) != cap_mask)
3790 		return -EINVAL;
3791 
3792 	bridge = pci_upstream_bridge(dev);
3793 	while (bridge != root) {
3794 		switch (pci_pcie_type(bridge)) {
3795 		case PCI_EXP_TYPE_UPSTREAM:
3796 			/* Upstream ports must not block AtomicOps on egress */
3797 			pcie_capability_read_dword(bridge, PCI_EXP_DEVCTL2,
3798 						   &ctl2);
3799 			if (ctl2 & PCI_EXP_DEVCTL2_ATOMIC_EGRESS_BLOCK)
3800 				return -EINVAL;
3801 			fallthrough;
3802 
3803 		/* All switch ports need to route AtomicOps */
3804 		case PCI_EXP_TYPE_DOWNSTREAM:
3805 			pcie_capability_read_dword(bridge, PCI_EXP_DEVCAP2,
3806 						   &cap);
3807 			if (!(cap & PCI_EXP_DEVCAP2_ATOMIC_ROUTE))
3808 				return -EINVAL;
3809 			break;
3810 		}
3811 
3812 		bridge = pci_upstream_bridge(bridge);
3813 	}
3814 
3815 	pcie_capability_set_word(dev, PCI_EXP_DEVCTL2,
3816 				 PCI_EXP_DEVCTL2_ATOMIC_REQ);
3817 	return 0;
3818 }
3819 EXPORT_SYMBOL(pci_enable_atomic_ops_to_root);
3820 
3821 /**
3822  * pci_release_region - Release a PCI bar
3823  * @pdev: PCI device whose resources were previously reserved by
3824  *	  pci_request_region()
3825  * @bar: BAR to release
3826  *
3827  * Releases the PCI I/O and memory resources previously reserved by a
3828  * successful call to pci_request_region().  Call this function only
3829  * after all use of the PCI regions has ceased.
3830  */
3831 void pci_release_region(struct pci_dev *pdev, int bar)
3832 {
3833 	if (!pci_bar_index_is_valid(bar))
3834 		return;
3835 
3836 	if (pci_resource_len(pdev, bar) == 0)
3837 		return;
3838 	if (pci_resource_flags(pdev, bar) & IORESOURCE_IO)
3839 		release_region(pci_resource_start(pdev, bar),
3840 				pci_resource_len(pdev, bar));
3841 	else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM)
3842 		release_mem_region(pci_resource_start(pdev, bar),
3843 				pci_resource_len(pdev, bar));
3844 }
3845 EXPORT_SYMBOL(pci_release_region);
3846 
3847 /**
3848  * __pci_request_region - Reserved PCI I/O and memory resource
3849  * @pdev: PCI device whose resources are to be reserved
3850  * @bar: BAR to be reserved
3851  * @name: name of the driver requesting the resource
3852  * @exclusive: whether the region access is exclusive or not
3853  *
3854  * Returns: 0 on success, negative error code on failure.
3855  *
3856  * Mark the PCI region associated with PCI device @pdev BAR @bar as being
3857  * reserved by owner @name. Do not access any address inside the PCI regions
3858  * unless this call returns successfully.
3859  *
3860  * If @exclusive is set, then the region is marked so that userspace
3861  * is explicitly not allowed to map the resource via /dev/mem or
3862  * sysfs MMIO access.
3863  *
3864  * Returns 0 on success, or %EBUSY on error.  A warning
3865  * message is also printed on failure.
3866  */
3867 static int __pci_request_region(struct pci_dev *pdev, int bar,
3868 				const char *name, int exclusive)
3869 {
3870 	if (!pci_bar_index_is_valid(bar))
3871 		return -EINVAL;
3872 
3873 	if (pci_resource_len(pdev, bar) == 0)
3874 		return 0;
3875 
3876 	if (pci_resource_flags(pdev, bar) & IORESOURCE_IO) {
3877 		if (!request_region(pci_resource_start(pdev, bar),
3878 			    pci_resource_len(pdev, bar), name))
3879 			goto err_out;
3880 	} else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM) {
3881 		if (!__request_mem_region(pci_resource_start(pdev, bar),
3882 					pci_resource_len(pdev, bar), name,
3883 					exclusive))
3884 			goto err_out;
3885 	}
3886 
3887 	return 0;
3888 
3889 err_out:
3890 	pci_warn(pdev, "BAR %d: can't reserve %pR\n", bar,
3891 		 &pdev->resource[bar]);
3892 	return -EBUSY;
3893 }
3894 
3895 /**
3896  * pci_request_region - Reserve PCI I/O and memory resource
3897  * @pdev: PCI device whose resources are to be reserved
3898  * @bar: BAR to be reserved
3899  * @name: name of the driver requesting the resource
3900  *
3901  * Returns: 0 on success, negative error code on failure.
3902  *
3903  * Mark the PCI region associated with PCI device @pdev BAR @bar as being
3904  * reserved by owner @name. Do not access any address inside the PCI regions
3905  * unless this call returns successfully.
3906  *
3907  * Returns 0 on success, or %EBUSY on error.  A warning
3908  * message is also printed on failure.
3909  */
3910 int pci_request_region(struct pci_dev *pdev, int bar, const char *name)
3911 {
3912 	return __pci_request_region(pdev, bar, name, 0);
3913 }
3914 EXPORT_SYMBOL(pci_request_region);
3915 
3916 /**
3917  * pci_release_selected_regions - Release selected PCI I/O and memory resources
3918  * @pdev: PCI device whose resources were previously reserved
3919  * @bars: Bitmask of BARs to be released
3920  *
3921  * Release selected PCI I/O and memory resources previously reserved.
3922  * Call this function only after all use of the PCI regions has ceased.
3923  */
3924 void pci_release_selected_regions(struct pci_dev *pdev, int bars)
3925 {
3926 	int i;
3927 
3928 	for (i = 0; i < PCI_STD_NUM_BARS; i++)
3929 		if (bars & (1 << i))
3930 			pci_release_region(pdev, i);
3931 }
3932 EXPORT_SYMBOL(pci_release_selected_regions);
3933 
3934 static int __pci_request_selected_regions(struct pci_dev *pdev, int bars,
3935 					  const char *name, int excl)
3936 {
3937 	int i;
3938 
3939 	for (i = 0; i < PCI_STD_NUM_BARS; i++)
3940 		if (bars & (1 << i))
3941 			if (__pci_request_region(pdev, i, name, excl))
3942 				goto err_out;
3943 	return 0;
3944 
3945 err_out:
3946 	while (--i >= 0)
3947 		if (bars & (1 << i))
3948 			pci_release_region(pdev, i);
3949 
3950 	return -EBUSY;
3951 }
3952 
3953 
3954 /**
3955  * pci_request_selected_regions - Reserve selected PCI I/O and memory resources
3956  * @pdev: PCI device whose resources are to be reserved
3957  * @bars: Bitmask of BARs to be requested
3958  * @name: Name of the driver requesting the resources
3959  *
3960  * Returns: 0 on success, negative error code on failure.
3961  */
3962 int pci_request_selected_regions(struct pci_dev *pdev, int bars,
3963 				 const char *name)
3964 {
3965 	return __pci_request_selected_regions(pdev, bars, name, 0);
3966 }
3967 EXPORT_SYMBOL(pci_request_selected_regions);
3968 
3969 /**
3970  * pci_request_selected_regions_exclusive - Request regions exclusively
3971  * @pdev: PCI device to request regions from
3972  * @bars: bit mask of BARs to request
3973  * @name: name of the driver requesting the resources
3974  *
3975  * Returns: 0 on success, negative error code on failure.
3976  */
3977 int pci_request_selected_regions_exclusive(struct pci_dev *pdev, int bars,
3978 					   const char *name)
3979 {
3980 	return __pci_request_selected_regions(pdev, bars, name,
3981 			IORESOURCE_EXCLUSIVE);
3982 }
3983 EXPORT_SYMBOL(pci_request_selected_regions_exclusive);
3984 
3985 /**
3986  * pci_release_regions - Release reserved PCI I/O and memory resources
3987  * @pdev: PCI device whose resources were previously reserved by
3988  *	  pci_request_regions()
3989  *
3990  * Releases all PCI I/O and memory resources previously reserved by a
3991  * successful call to pci_request_regions().  Call this function only
3992  * after all use of the PCI regions has ceased.
3993  */
3994 void pci_release_regions(struct pci_dev *pdev)
3995 {
3996 	pci_release_selected_regions(pdev, (1 << PCI_STD_NUM_BARS) - 1);
3997 }
3998 EXPORT_SYMBOL(pci_release_regions);
3999 
4000 /**
4001  * pci_request_regions - Reserve PCI I/O and memory resources
4002  * @pdev: PCI device whose resources are to be reserved
4003  * @name: name of the driver requesting the resources
4004  *
4005  * Mark all PCI regions associated with PCI device @pdev as being reserved by
4006  * owner @name. Do not access any address inside the PCI regions unless this
4007  * call returns successfully.
4008  *
4009  * Returns 0 on success, or %EBUSY on error.  A warning
4010  * message is also printed on failure.
4011  */
4012 int pci_request_regions(struct pci_dev *pdev, const char *name)
4013 {
4014 	return pci_request_selected_regions(pdev,
4015 			((1 << PCI_STD_NUM_BARS) - 1), name);
4016 }
4017 EXPORT_SYMBOL(pci_request_regions);
4018 
4019 /**
4020  * pci_request_regions_exclusive - Reserve PCI I/O and memory resources
4021  * @pdev: PCI device whose resources are to be reserved
4022  * @name: name of the driver requesting the resources
4023  *
4024  * Returns: 0 on success, negative error code on failure.
4025  *
4026  * Mark all PCI regions associated with PCI device @pdev as being reserved
4027  * by owner @name. Do not access any address inside the PCI regions
4028  * unless this call returns successfully.
4029  *
4030  * pci_request_regions_exclusive() will mark the region so that /dev/mem
4031  * and the sysfs MMIO access will not be allowed.
4032  *
4033  * Returns 0 on success, or %EBUSY on error.  A warning message is also
4034  * printed on failure.
4035  */
4036 int pci_request_regions_exclusive(struct pci_dev *pdev, const char *name)
4037 {
4038 	return pci_request_selected_regions_exclusive(pdev,
4039 				((1 << PCI_STD_NUM_BARS) - 1), name);
4040 }
4041 EXPORT_SYMBOL(pci_request_regions_exclusive);
4042 
4043 /*
4044  * Record the PCI IO range (expressed as CPU physical address + size).
4045  * Return a negative value if an error has occurred, zero otherwise
4046  */
4047 int pci_register_io_range(const struct fwnode_handle *fwnode, phys_addr_t addr,
4048 			resource_size_t	size)
4049 {
4050 	int ret = 0;
4051 #ifdef PCI_IOBASE
4052 	struct logic_pio_hwaddr *range;
4053 
4054 	if (!size || addr + size < addr)
4055 		return -EINVAL;
4056 
4057 	range = kzalloc_obj(*range, GFP_ATOMIC);
4058 	if (!range)
4059 		return -ENOMEM;
4060 
4061 	range->fwnode = fwnode;
4062 	range->size = size;
4063 	range->hw_start = addr;
4064 	range->flags = LOGIC_PIO_CPU_MMIO;
4065 
4066 	ret = logic_pio_register_range(range);
4067 	if (ret)
4068 		kfree(range);
4069 
4070 	/* Ignore duplicates due to deferred probing */
4071 	if (ret == -EEXIST)
4072 		ret = 0;
4073 #endif
4074 
4075 	return ret;
4076 }
4077 
4078 phys_addr_t pci_pio_to_address(unsigned long pio)
4079 {
4080 #ifdef PCI_IOBASE
4081 	if (pio < MMIO_UPPER_LIMIT)
4082 		return logic_pio_to_hwaddr(pio);
4083 #endif
4084 
4085 	return (phys_addr_t) OF_BAD_ADDR;
4086 }
4087 EXPORT_SYMBOL_GPL(pci_pio_to_address);
4088 
4089 unsigned long __weak pci_address_to_pio(phys_addr_t address)
4090 {
4091 #ifdef PCI_IOBASE
4092 	return logic_pio_trans_cpuaddr(address);
4093 #else
4094 	if (address > IO_SPACE_LIMIT)
4095 		return (unsigned long)-1;
4096 
4097 	return (unsigned long) address;
4098 #endif
4099 }
4100 
4101 /**
4102  * pci_remap_iospace - Remap the memory mapped I/O space
4103  * @res: Resource describing the I/O space
4104  * @phys_addr: physical address of range to be mapped
4105  *
4106  * Remap the memory mapped I/O space described by the @res and the CPU
4107  * physical address @phys_addr into virtual address space.  Only
4108  * architectures that have memory mapped IO functions defined (and the
4109  * PCI_IOBASE value defined) should call this function.
4110  */
4111 #ifndef pci_remap_iospace
4112 int pci_remap_iospace(const struct resource *res, phys_addr_t phys_addr)
4113 {
4114 #if defined(PCI_IOBASE)
4115 	unsigned long vaddr = (unsigned long)PCI_IOBASE + res->start;
4116 
4117 	if (!(res->flags & IORESOURCE_IO))
4118 		return -EINVAL;
4119 
4120 	if (res->end > IO_SPACE_LIMIT)
4121 		return -EINVAL;
4122 
4123 	return vmap_page_range(vaddr, vaddr + resource_size(res), phys_addr,
4124 			       pgprot_device(PAGE_KERNEL));
4125 #else
4126 	/*
4127 	 * This architecture does not have memory mapped I/O space,
4128 	 * so this function should never be called
4129 	 */
4130 	WARN_ONCE(1, "This architecture does not support memory mapped I/O\n");
4131 	return -ENODEV;
4132 #endif
4133 }
4134 EXPORT_SYMBOL(pci_remap_iospace);
4135 #endif
4136 
4137 /**
4138  * pci_unmap_iospace - Unmap the memory mapped I/O space
4139  * @res: resource to be unmapped
4140  *
4141  * Unmap the CPU virtual address @res from virtual address space.  Only
4142  * architectures that have memory mapped IO functions defined (and the
4143  * PCI_IOBASE value defined) should call this function.
4144  */
4145 void pci_unmap_iospace(struct resource *res)
4146 {
4147 #if defined(PCI_IOBASE)
4148 	unsigned long vaddr = (unsigned long)PCI_IOBASE + res->start;
4149 
4150 	vunmap_range(vaddr, vaddr + resource_size(res));
4151 #endif
4152 }
4153 EXPORT_SYMBOL(pci_unmap_iospace);
4154 
4155 static void __pci_set_master(struct pci_dev *dev, bool enable)
4156 {
4157 	u16 old_cmd, cmd;
4158 
4159 	pci_read_config_word(dev, PCI_COMMAND, &old_cmd);
4160 	if (enable)
4161 		cmd = old_cmd | PCI_COMMAND_MASTER;
4162 	else
4163 		cmd = old_cmd & ~PCI_COMMAND_MASTER;
4164 	if (cmd != old_cmd) {
4165 		pci_dbg(dev, "%s bus mastering\n",
4166 			enable ? "enabling" : "disabling");
4167 		pci_write_config_word(dev, PCI_COMMAND, cmd);
4168 	}
4169 	dev->is_busmaster = enable;
4170 }
4171 
4172 /**
4173  * pcibios_setup - process "pci=" kernel boot arguments
4174  * @str: string used to pass in "pci=" kernel boot arguments
4175  *
4176  * Process kernel boot arguments.  This is the default implementation.
4177  * Architecture specific implementations can override this as necessary.
4178  */
4179 char * __weak __init pcibios_setup(char *str)
4180 {
4181 	return str;
4182 }
4183 
4184 /**
4185  * pcibios_set_master - enable PCI bus-mastering for device dev
4186  * @dev: the PCI device to enable
4187  *
4188  * Enables PCI bus-mastering for the device.  This is the default
4189  * implementation.  Architecture specific implementations can override
4190  * this if necessary.
4191  */
4192 void __weak pcibios_set_master(struct pci_dev *dev)
4193 {
4194 	u8 lat;
4195 
4196 	/* The latency timer doesn't apply to PCIe (either Type 0 or Type 1) */
4197 	if (pci_is_pcie(dev))
4198 		return;
4199 
4200 	pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
4201 	if (lat < 16)
4202 		lat = (64 <= pcibios_max_latency) ? 64 : pcibios_max_latency;
4203 	else if (lat > pcibios_max_latency)
4204 		lat = pcibios_max_latency;
4205 	else
4206 		return;
4207 
4208 	pci_write_config_byte(dev, PCI_LATENCY_TIMER, lat);
4209 }
4210 
4211 /**
4212  * pci_set_master - enables bus-mastering for device dev
4213  * @dev: the PCI device to enable
4214  *
4215  * Enables bus-mastering on the device and calls pcibios_set_master()
4216  * to do the needed arch specific settings.
4217  */
4218 void pci_set_master(struct pci_dev *dev)
4219 {
4220 	__pci_set_master(dev, true);
4221 	pcibios_set_master(dev);
4222 }
4223 EXPORT_SYMBOL(pci_set_master);
4224 
4225 /**
4226  * pci_clear_master - disables bus-mastering for device dev
4227  * @dev: the PCI device to disable
4228  */
4229 void pci_clear_master(struct pci_dev *dev)
4230 {
4231 	__pci_set_master(dev, false);
4232 }
4233 EXPORT_SYMBOL(pci_clear_master);
4234 
4235 /**
4236  * pci_set_cacheline_size - ensure the CACHE_LINE_SIZE register is programmed
4237  * @dev: the PCI device for which MWI is to be enabled
4238  *
4239  * Helper function for pci_set_mwi.
4240  * Originally copied from drivers/net/acenic.c.
4241  * Copyright 1998-2001 by Jes Sorensen, <jes@trained-monkey.org>.
4242  *
4243  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4244  */
4245 int pci_set_cacheline_size(struct pci_dev *dev)
4246 {
4247 	u8 cacheline_size;
4248 
4249 	if (!pci_cache_line_size)
4250 		return -EINVAL;
4251 
4252 	/* Validate current setting: the PCI_CACHE_LINE_SIZE must be
4253 	   equal to or multiple of the right value. */
4254 	pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
4255 	if (cacheline_size >= pci_cache_line_size &&
4256 	    (cacheline_size % pci_cache_line_size) == 0)
4257 		return 0;
4258 
4259 	/* Write the correct value. */
4260 	pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, pci_cache_line_size);
4261 	/* Read it back. */
4262 	pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
4263 	if (cacheline_size == pci_cache_line_size)
4264 		return 0;
4265 
4266 	pci_dbg(dev, "cache line size of %d is not supported\n",
4267 		   pci_cache_line_size << 2);
4268 
4269 	return -EINVAL;
4270 }
4271 EXPORT_SYMBOL_GPL(pci_set_cacheline_size);
4272 
4273 /**
4274  * pci_set_mwi - enables memory-write-invalidate PCI transaction
4275  * @dev: the PCI device for which MWI is enabled
4276  *
4277  * Enables the Memory-Write-Invalidate transaction in %PCI_COMMAND.
4278  *
4279  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4280  */
4281 int pci_set_mwi(struct pci_dev *dev)
4282 {
4283 #ifdef PCI_DISABLE_MWI
4284 	return 0;
4285 #else
4286 	int rc;
4287 	u16 cmd;
4288 
4289 	rc = pci_set_cacheline_size(dev);
4290 	if (rc)
4291 		return rc;
4292 
4293 	pci_read_config_word(dev, PCI_COMMAND, &cmd);
4294 	if (!(cmd & PCI_COMMAND_INVALIDATE)) {
4295 		pci_dbg(dev, "enabling Mem-Wr-Inval\n");
4296 		cmd |= PCI_COMMAND_INVALIDATE;
4297 		pci_write_config_word(dev, PCI_COMMAND, cmd);
4298 	}
4299 	return 0;
4300 #endif
4301 }
4302 EXPORT_SYMBOL(pci_set_mwi);
4303 
4304 /**
4305  * pci_try_set_mwi - enables memory-write-invalidate PCI transaction
4306  * @dev: the PCI device for which MWI is enabled
4307  *
4308  * Enables the Memory-Write-Invalidate transaction in %PCI_COMMAND.
4309  * Callers are not required to check the return value.
4310  *
4311  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
4312  */
4313 int pci_try_set_mwi(struct pci_dev *dev)
4314 {
4315 #ifdef PCI_DISABLE_MWI
4316 	return 0;
4317 #else
4318 	return pci_set_mwi(dev);
4319 #endif
4320 }
4321 EXPORT_SYMBOL(pci_try_set_mwi);
4322 
4323 /**
4324  * pci_clear_mwi - disables Memory-Write-Invalidate for device dev
4325  * @dev: the PCI device to disable
4326  *
4327  * Disables PCI Memory-Write-Invalidate transaction on the device
4328  */
4329 void pci_clear_mwi(struct pci_dev *dev)
4330 {
4331 #ifndef PCI_DISABLE_MWI
4332 	u16 cmd;
4333 
4334 	pci_read_config_word(dev, PCI_COMMAND, &cmd);
4335 	if (cmd & PCI_COMMAND_INVALIDATE) {
4336 		cmd &= ~PCI_COMMAND_INVALIDATE;
4337 		pci_write_config_word(dev, PCI_COMMAND, cmd);
4338 	}
4339 #endif
4340 }
4341 EXPORT_SYMBOL(pci_clear_mwi);
4342 
4343 /**
4344  * pci_disable_parity - disable parity checking for device
4345  * @dev: the PCI device to operate on
4346  *
4347  * Disable parity checking for device @dev
4348  */
4349 void pci_disable_parity(struct pci_dev *dev)
4350 {
4351 	u16 cmd;
4352 
4353 	pci_read_config_word(dev, PCI_COMMAND, &cmd);
4354 	if (cmd & PCI_COMMAND_PARITY) {
4355 		cmd &= ~PCI_COMMAND_PARITY;
4356 		pci_write_config_word(dev, PCI_COMMAND, cmd);
4357 	}
4358 }
4359 
4360 /**
4361  * pci_intx - enables/disables PCI INTx for device dev
4362  * @pdev: the PCI device to operate on
4363  * @enable: boolean: whether to enable or disable PCI INTx
4364  *
4365  * Enables/disables PCI INTx for device @pdev
4366  */
4367 void pci_intx(struct pci_dev *pdev, int enable)
4368 {
4369 	u16 pci_command, new;
4370 
4371 	pci_read_config_word(pdev, PCI_COMMAND, &pci_command);
4372 
4373 	if (enable)
4374 		new = pci_command & ~PCI_COMMAND_INTX_DISABLE;
4375 	else
4376 		new = pci_command | PCI_COMMAND_INTX_DISABLE;
4377 
4378 	if (new == pci_command)
4379 		return;
4380 
4381 	pci_write_config_word(pdev, PCI_COMMAND, new);
4382 }
4383 EXPORT_SYMBOL_GPL(pci_intx);
4384 
4385 /**
4386  * pci_wait_for_pending_transaction - wait for pending transaction
4387  * @dev: the PCI device to operate on
4388  *
4389  * Return 0 if transaction is pending 1 otherwise.
4390  */
4391 int pci_wait_for_pending_transaction(struct pci_dev *dev)
4392 {
4393 	if (!pci_is_pcie(dev))
4394 		return 1;
4395 
4396 	return pci_wait_for_pending(dev, pci_pcie_cap(dev) + PCI_EXP_DEVSTA,
4397 				    PCI_EXP_DEVSTA_TRPND);
4398 }
4399 EXPORT_SYMBOL(pci_wait_for_pending_transaction);
4400 
4401 /**
4402  * pcie_flr - initiate a PCIe function level reset
4403  * @dev: device to reset
4404  *
4405  * Initiate a function level reset unconditionally on @dev without
4406  * checking any flags and DEVCAP
4407  */
4408 int pcie_flr(struct pci_dev *dev)
4409 {
4410 	int ret;
4411 
4412 	if (!pci_dev_config_accessible(dev, "FLR"))
4413 		return -ENOTTY;
4414 
4415 	if (!pci_wait_for_pending_transaction(dev))
4416 		pci_err(dev, "timed out waiting for pending transaction; performing function level reset anyway\n");
4417 
4418 	/* Have to call it after waiting for pending DMA transaction */
4419 	ret = pci_dev_reset_iommu_prepare(dev);
4420 	if (ret) {
4421 		pci_err(dev, "failed to stop IOMMU for a PCI reset: %d\n", ret);
4422 		return ret;
4423 	}
4424 
4425 	pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_BCR_FLR);
4426 
4427 	if (dev->imm_ready)
4428 		goto done;
4429 
4430 	/*
4431 	 * Per PCIe r4.0, sec 6.6.2, a device must complete an FLR within
4432 	 * 100ms, but may silently discard requests while the FLR is in
4433 	 * progress.  Wait 100ms before trying to access the device.
4434 	 */
4435 	msleep(100);
4436 
4437 	ret = pci_dev_wait(dev, "FLR", PCIE_RESET_READY_POLL_MS);
4438 done:
4439 	pci_dev_reset_iommu_done(dev);
4440 	return ret;
4441 }
4442 EXPORT_SYMBOL_GPL(pcie_flr);
4443 
4444 /**
4445  * pcie_reset_flr - initiate a PCIe function level reset
4446  * @dev: device to reset
4447  * @probe: if true, return 0 if device can be reset this way
4448  *
4449  * Initiate a function level reset on @dev.
4450  */
4451 int pcie_reset_flr(struct pci_dev *dev, bool probe)
4452 {
4453 	if (dev->dev_flags & PCI_DEV_FLAGS_NO_FLR_RESET)
4454 		return -ENOTTY;
4455 
4456 	if (!(dev->devcap & PCI_EXP_DEVCAP_FLR))
4457 		return -ENOTTY;
4458 
4459 	if (probe)
4460 		return 0;
4461 
4462 	return pcie_flr(dev);
4463 }
4464 EXPORT_SYMBOL_GPL(pcie_reset_flr);
4465 
4466 static int pci_af_flr(struct pci_dev *dev, bool probe)
4467 {
4468 	int ret;
4469 	int pos;
4470 	u8 cap;
4471 
4472 	pos = pci_find_capability(dev, PCI_CAP_ID_AF);
4473 	if (!pos)
4474 		return -ENOTTY;
4475 
4476 	if (dev->dev_flags & PCI_DEV_FLAGS_NO_FLR_RESET)
4477 		return -ENOTTY;
4478 
4479 	pci_read_config_byte(dev, pos + PCI_AF_CAP, &cap);
4480 	if (!(cap & PCI_AF_CAP_TP) || !(cap & PCI_AF_CAP_FLR))
4481 		return -ENOTTY;
4482 
4483 	if (probe)
4484 		return 0;
4485 
4486 	/*
4487 	 * Wait for Transaction Pending bit to clear.  A word-aligned test
4488 	 * is used, so we use the control offset rather than status and shift
4489 	 * the test bit to match.
4490 	 */
4491 	if (!pci_wait_for_pending(dev, pos + PCI_AF_CTRL,
4492 				 PCI_AF_STATUS_TP << 8))
4493 		pci_err(dev, "timed out waiting for pending transaction; performing AF function level reset anyway\n");
4494 
4495 	/* Have to call it after waiting for pending DMA transaction */
4496 	ret = pci_dev_reset_iommu_prepare(dev);
4497 	if (ret) {
4498 		pci_err(dev, "failed to stop IOMMU for a PCI reset: %d\n", ret);
4499 		return ret;
4500 	}
4501 
4502 	pci_write_config_byte(dev, pos + PCI_AF_CTRL, PCI_AF_CTRL_FLR);
4503 
4504 	if (dev->imm_ready)
4505 		goto done;
4506 
4507 	/*
4508 	 * Per Advanced Capabilities for Conventional PCI ECN, 13 April 2006,
4509 	 * updated 27 July 2006; a device must complete an FLR within
4510 	 * 100ms, but may silently discard requests while the FLR is in
4511 	 * progress.  Wait 100ms before trying to access the device.
4512 	 */
4513 	msleep(100);
4514 
4515 	ret = pci_dev_wait(dev, "AF_FLR", PCIE_RESET_READY_POLL_MS);
4516 done:
4517 	pci_dev_reset_iommu_done(dev);
4518 	return ret;
4519 }
4520 
4521 /**
4522  * pci_pm_reset - Put device into PCI_D3 and back into PCI_D0.
4523  * @dev: Device to reset.
4524  * @probe: if true, return 0 if the device can be reset this way.
4525  *
4526  * If @dev supports native PCI PM and its PCI_PM_CTRL_NO_SOFT_RESET flag is
4527  * unset, it will be reinitialized internally when going from PCI_D3hot to
4528  * PCI_D0.  If that's the case and the device is not in a low-power state
4529  * already, force it into PCI_D3hot and back to PCI_D0, causing it to be reset.
4530  *
4531  * NOTE: This causes the caller to sleep for twice the device power transition
4532  * cooldown period, which for the D0->D3hot and D3hot->D0 transitions is 10 ms
4533  * by default (i.e. unless the @dev's d3hot_delay field has a different value).
4534  * Moreover, only devices in D0 can be reset by this function.
4535  */
4536 static int pci_pm_reset(struct pci_dev *dev, bool probe)
4537 {
4538 	u16 csr;
4539 	int ret;
4540 
4541 	if (!dev->pm_cap || dev->dev_flags & PCI_DEV_FLAGS_NO_PM_RESET)
4542 		return -ENOTTY;
4543 
4544 	pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &csr);
4545 	if (csr & PCI_PM_CTRL_NO_SOFT_RESET)
4546 		return -ENOTTY;
4547 
4548 	if (probe)
4549 		return 0;
4550 
4551 	if (dev->current_state != PCI_D0)
4552 		return -EINVAL;
4553 
4554 	ret = pci_dev_reset_iommu_prepare(dev);
4555 	if (ret) {
4556 		pci_err(dev, "failed to stop IOMMU for a PCI reset: %d\n", ret);
4557 		return ret;
4558 	}
4559 
4560 	csr &= ~PCI_PM_CTRL_STATE_MASK;
4561 	csr |= PCI_D3hot;
4562 	pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, csr);
4563 	pci_dev_d3_sleep(dev);
4564 
4565 	csr &= ~PCI_PM_CTRL_STATE_MASK;
4566 	csr |= PCI_D0;
4567 	pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, csr);
4568 	pci_dev_d3_sleep(dev);
4569 
4570 	ret = pci_dev_wait(dev, "PM D3hot->D0", PCIE_RESET_READY_POLL_MS);
4571 	pci_dev_reset_iommu_done(dev);
4572 	return ret;
4573 }
4574 
4575 /**
4576  * pcie_wait_for_link_status - Wait for link status change
4577  * @pdev: Device whose link to wait for.
4578  * @use_lt: Use the LT bit if TRUE, or the DLLLA bit if FALSE.
4579  * @active: Waiting for active or inactive?
4580  *
4581  * Return 0 if successful, or -ETIMEDOUT if status has not changed within
4582  * PCIE_LINK_RETRAIN_TIMEOUT_MS milliseconds.
4583  */
4584 static int pcie_wait_for_link_status(struct pci_dev *pdev,
4585 				     bool use_lt, bool active)
4586 {
4587 	u16 lnksta_mask, lnksta_match;
4588 	unsigned long end_jiffies;
4589 	u16 lnksta;
4590 
4591 	lnksta_mask = use_lt ? PCI_EXP_LNKSTA_LT : PCI_EXP_LNKSTA_DLLLA;
4592 	lnksta_match = active ? lnksta_mask : 0;
4593 
4594 	end_jiffies = jiffies + msecs_to_jiffies(PCIE_LINK_RETRAIN_TIMEOUT_MS);
4595 	do {
4596 		pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnksta);
4597 		if ((lnksta & lnksta_mask) == lnksta_match)
4598 			return 0;
4599 		msleep(1);
4600 	} while (time_before(jiffies, end_jiffies));
4601 
4602 	return -ETIMEDOUT;
4603 }
4604 
4605 /**
4606  * pcie_retrain_link - Request a link retrain and wait for it to complete
4607  * @pdev: Device whose link to retrain.
4608  * @use_lt: Use the LT bit if TRUE, or the DLLLA bit if FALSE, for status.
4609  *
4610  * Trigger retraining of the PCIe Link and wait for the completion of the
4611  * retraining. As link retraining is known to asserts LBMS and may change
4612  * the Link Speed, LBMS is cleared after the retraining and the Link Speed
4613  * of the subordinate bus is updated.
4614  *
4615  * Retrain completion status is retrieved from the Link Status Register
4616  * according to @use_lt.  It is not verified whether the use of the DLLLA
4617  * bit is valid.
4618  *
4619  * Return 0 if successful, or -ETIMEDOUT if training has not completed
4620  * within PCIE_LINK_RETRAIN_TIMEOUT_MS milliseconds.
4621  */
4622 int pcie_retrain_link(struct pci_dev *pdev, bool use_lt)
4623 {
4624 	int rc;
4625 
4626 	/*
4627 	 * Ensure the updated LNKCTL parameters are used during link
4628 	 * training by checking that there is no ongoing link training that
4629 	 * may have started before link parameters were changed, so as to
4630 	 * avoid LTSSM race as recommended in Implementation Note at the end
4631 	 * of PCIe r6.1 sec 7.5.3.7.
4632 	 */
4633 	rc = pcie_wait_for_link_status(pdev, true, false);
4634 	if (rc)
4635 		return rc;
4636 
4637 	pcie_capability_set_word(pdev, PCI_EXP_LNKCTL, PCI_EXP_LNKCTL_RL);
4638 	if (pdev->clear_retrain_link) {
4639 		/*
4640 		 * Due to an erratum in some devices the Retrain Link bit
4641 		 * needs to be cleared again manually to allow the link
4642 		 * training to succeed.
4643 		 */
4644 		pcie_capability_clear_word(pdev, PCI_EXP_LNKCTL, PCI_EXP_LNKCTL_RL);
4645 	}
4646 
4647 	rc = pcie_wait_for_link_status(pdev, use_lt, !use_lt);
4648 
4649 	/*
4650 	 * Clear LBMS after a manual retrain so that the bit can be used
4651 	 * to track link speed or width changes made by hardware itself
4652 	 * in attempt to correct unreliable link operation.
4653 	 */
4654 	pcie_reset_lbms(pdev);
4655 
4656 	/*
4657 	 * Ensure the Link Speed updates after retraining in case the Link
4658 	 * Speed was changed because of the retraining. While the bwctrl's
4659 	 * IRQ handler normally picks up the new Link Speed, clearing LBMS
4660 	 * races with the IRQ handler reading the Link Status register and
4661 	 * can result in the handler returning early without updating the
4662 	 * Link Speed.
4663 	 */
4664 	if (pdev->subordinate)
4665 		pcie_update_link_speed(pdev->subordinate, PCIE_LINK_RETRAIN);
4666 
4667 	return rc;
4668 }
4669 
4670 /**
4671  * pcie_wait_for_link_delay - Wait until link is active or inactive
4672  * @pdev: Bridge device
4673  * @active: waiting for active or inactive?
4674  * @delay: Delay to wait after link has become active (in ms)
4675  *
4676  * Use this to wait till link becomes active or inactive.
4677  */
4678 static bool pcie_wait_for_link_delay(struct pci_dev *pdev, bool active,
4679 				     int delay)
4680 {
4681 	int rc;
4682 
4683 	/*
4684 	 * Some controllers might not implement link active reporting. In this
4685 	 * case, we wait for 1000 ms + any delay requested by the caller.
4686 	 */
4687 	if (!pdev->link_active_reporting) {
4688 		msleep(PCIE_LINK_RETRAIN_TIMEOUT_MS + delay);
4689 		return true;
4690 	}
4691 
4692 	/*
4693 	 * PCIe r4.0 sec 6.6.1, a component must enter LTSSM Detect within 20ms,
4694 	 * after which we should expect the link to be active if the reset was
4695 	 * successful. If so, software must wait a minimum 100ms before sending
4696 	 * configuration requests to devices downstream this port.
4697 	 *
4698 	 * If the link fails to activate, either the device was physically
4699 	 * removed or the link is permanently failed.
4700 	 */
4701 	if (active)
4702 		msleep(20);
4703 	rc = pcie_wait_for_link_status(pdev, false, active);
4704 	if (active) {
4705 		if (rc)
4706 			rc = pcie_failed_link_retrain(pdev);
4707 		if (rc)
4708 			return false;
4709 
4710 		msleep(delay);
4711 		return true;
4712 	}
4713 
4714 	if (rc)
4715 		return false;
4716 
4717 	return true;
4718 }
4719 
4720 /**
4721  * pcie_wait_for_link - Wait until link is active or inactive
4722  * @pdev: Bridge device
4723  * @active: waiting for active or inactive?
4724  *
4725  * Use this to wait till link becomes active or inactive.
4726  */
4727 bool pcie_wait_for_link(struct pci_dev *pdev, bool active)
4728 {
4729 	return pcie_wait_for_link_delay(pdev, active, 100);
4730 }
4731 
4732 /*
4733  * Find maximum D3cold delay required by all the devices on the bus.  The
4734  * spec says 100 ms, but firmware can lower it and we allow drivers to
4735  * increase it as well.
4736  *
4737  * Context: Called with @pci_bus_sem locked for reading.
4738  */
4739 static int pci_bus_max_d3cold_delay(const struct pci_bus *bus)
4740 {
4741 	const struct pci_dev *pdev;
4742 	int min_delay = 100;
4743 	int max_delay = 0;
4744 
4745 	lockdep_assert_held(&pci_bus_sem);
4746 
4747 	list_for_each_entry(pdev, &bus->devices, bus_list) {
4748 		if (pdev->d3cold_delay < min_delay)
4749 			min_delay = pdev->d3cold_delay;
4750 		if (pdev->d3cold_delay > max_delay)
4751 			max_delay = pdev->d3cold_delay;
4752 	}
4753 
4754 	return max(min_delay, max_delay);
4755 }
4756 
4757 /**
4758  * pci_bridge_wait_for_secondary_bus - Wait for secondary bus to be accessible
4759  * @dev: PCI bridge
4760  * @reset_type: reset type in human-readable form
4761  *
4762  * Handle necessary delays before access to the devices on the secondary
4763  * side of the bridge are permitted after D3cold to D0 transition
4764  * or Conventional Reset.
4765  *
4766  * For PCIe this means the delays in PCIe 5.0 section 6.6.1. For
4767  * conventional PCI it means Tpvrh + Trhfa specified in PCI 3.0 section
4768  * 4.3.2.
4769  *
4770  * Return 0 on success or -ENOTTY if the first device on the secondary bus
4771  * failed to become accessible.
4772  */
4773 int pci_bridge_wait_for_secondary_bus(struct pci_dev *dev, char *reset_type)
4774 {
4775 	struct pci_dev *child __free(pci_dev_put) = NULL;
4776 	int delay;
4777 
4778 	if (pci_dev_is_disconnected(dev))
4779 		return 0;
4780 
4781 	if (!pci_is_bridge(dev))
4782 		return 0;
4783 
4784 	down_read(&pci_bus_sem);
4785 
4786 	/*
4787 	 * We only deal with devices that are present currently on the bus.
4788 	 * For any hot-added devices the access delay is handled in pciehp
4789 	 * board_added(). In case of ACPI hotplug the firmware is expected
4790 	 * to configure the devices before OS is notified.
4791 	 */
4792 	if (!dev->subordinate || list_empty(&dev->subordinate->devices)) {
4793 		up_read(&pci_bus_sem);
4794 		return 0;
4795 	}
4796 
4797 	/* Take d3cold_delay requirements into account */
4798 	delay = pci_bus_max_d3cold_delay(dev->subordinate);
4799 	if (!delay) {
4800 		up_read(&pci_bus_sem);
4801 		return 0;
4802 	}
4803 
4804 	child = pci_dev_get(list_first_entry(&dev->subordinate->devices,
4805 					     struct pci_dev, bus_list));
4806 	up_read(&pci_bus_sem);
4807 
4808 	/*
4809 	 * Conventional PCI and PCI-X we need to wait Tpvrh + Trhfa before
4810 	 * accessing the device after reset (that is 1000 ms + 100 ms).
4811 	 */
4812 	if (!pci_is_pcie(dev)) {
4813 		pci_dbg(dev, "waiting %d ms for secondary bus\n", 1000 + delay);
4814 		msleep(1000 + delay);
4815 		return 0;
4816 	}
4817 
4818 	/*
4819 	 * For PCIe downstream and root ports that do not support speeds
4820 	 * greater than 5 GT/s need to wait minimum 100 ms. For higher
4821 	 * speeds (gen3) we need to wait first for the data link layer to
4822 	 * become active.
4823 	 *
4824 	 * However, 100 ms is the minimum and the PCIe spec says the
4825 	 * software must allow at least 1s before it can determine that the
4826 	 * device that did not respond is a broken device. Also device can
4827 	 * take longer than that to respond if it indicates so through Request
4828 	 * Retry Status completions.
4829 	 *
4830 	 * Therefore we wait for 100 ms and check for the device presence
4831 	 * until the timeout expires.
4832 	 */
4833 	if (!pcie_downstream_port(dev))
4834 		return 0;
4835 
4836 	if (pcie_get_speed_cap(dev) <= PCIE_SPEED_5_0GT) {
4837 		u16 status;
4838 
4839 		pci_dbg(dev, "waiting %d ms for downstream link\n", delay);
4840 		msleep(delay);
4841 
4842 		if (!pci_dev_wait(child, reset_type, PCI_RESET_WAIT - delay))
4843 			return 0;
4844 
4845 		/*
4846 		 * If the port supports active link reporting we now check
4847 		 * whether the link is active and if not bail out early with
4848 		 * the assumption that the device is not present anymore.
4849 		 */
4850 		if (!dev->link_active_reporting)
4851 			return -ENOTTY;
4852 
4853 		pcie_capability_read_word(dev, PCI_EXP_LNKSTA, &status);
4854 		if (!(status & PCI_EXP_LNKSTA_DLLLA))
4855 			return -ENOTTY;
4856 
4857 		return pci_dev_wait(child, reset_type,
4858 				    PCIE_RESET_READY_POLL_MS - PCI_RESET_WAIT);
4859 	}
4860 
4861 	pci_dbg(dev, "waiting %d ms for downstream link, after activation\n",
4862 		delay);
4863 	if (!pcie_wait_for_link_delay(dev, true, delay)) {
4864 		/* Did not train, no need to wait any further */
4865 		pci_info(dev, "Data Link Layer Link Active not set in %d msec\n", delay);
4866 		return -ENOTTY;
4867 	}
4868 
4869 	return pci_dev_wait(child, reset_type,
4870 			    PCIE_RESET_READY_POLL_MS - delay);
4871 }
4872 
4873 void pci_reset_secondary_bus(struct pci_dev *dev)
4874 {
4875 	u16 ctrl;
4876 
4877 	pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &ctrl);
4878 	ctrl |= PCI_BRIDGE_CTL_BUS_RESET;
4879 	pci_write_config_word(dev, PCI_BRIDGE_CONTROL, ctrl);
4880 
4881 	/*
4882 	 * PCI spec v3.0 7.6.4.2 requires minimum Trst of 1ms.  Double
4883 	 * this to 2ms to ensure that we meet the minimum requirement.
4884 	 */
4885 	msleep(2);
4886 
4887 	ctrl &= ~PCI_BRIDGE_CTL_BUS_RESET;
4888 	pci_write_config_word(dev, PCI_BRIDGE_CONTROL, ctrl);
4889 }
4890 
4891 void __weak pcibios_reset_secondary_bus(struct pci_dev *dev)
4892 {
4893 	struct pci_host_bridge *host = pci_find_host_bridge(dev->bus);
4894 	int ret;
4895 
4896 	if (pci_is_root_bus(dev->bus) && host->reset_root_port) {
4897 		ret = host->reset_root_port(host, dev);
4898 		if (ret)
4899 			pci_err(dev, "Failed to reset Root Port: %d\n", ret);
4900 		else
4901 			pci_restore_state(dev);
4902 
4903 		return;
4904 	}
4905 
4906 	pci_reset_secondary_bus(dev);
4907 }
4908 
4909 /**
4910  * pci_bridge_secondary_bus_reset - Reset the secondary bus on a PCI bridge.
4911  * @dev: Bridge device
4912  *
4913  * Use the bridge control register to assert reset on the secondary bus.
4914  * Devices on the secondary bus are left in power-on state.
4915  */
4916 int pci_bridge_secondary_bus_reset(struct pci_dev *dev)
4917 {
4918 	if (!dev->block_cfg_access)
4919 		pci_warn_once(dev, "unlocked secondary bus reset via: %pS\n",
4920 			      __builtin_return_address(0));
4921 	pcibios_reset_secondary_bus(dev);
4922 
4923 	return pci_bridge_wait_for_secondary_bus(dev, "bus reset");
4924 }
4925 EXPORT_SYMBOL_GPL(pci_bridge_secondary_bus_reset);
4926 
4927 static int pci_parent_bus_reset(struct pci_dev *dev, bool probe)
4928 {
4929 	struct pci_dev *pdev;
4930 
4931 	if (pci_is_root_bus(dev->bus) || dev->subordinate ||
4932 	    !dev->bus->self || dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET)
4933 		return -ENOTTY;
4934 
4935 	list_for_each_entry(pdev, &dev->bus->devices, bus_list)
4936 		if (pdev != dev)
4937 			return -ENOTTY;
4938 
4939 	if (probe)
4940 		return 0;
4941 
4942 	return pci_bridge_secondary_bus_reset(dev->bus->self);
4943 }
4944 
4945 static int pci_reset_hotplug_slot(struct hotplug_slot *hotplug, bool probe)
4946 {
4947 	int rc = -ENOTTY;
4948 
4949 	if (!hotplug || !try_module_get(hotplug->owner))
4950 		return rc;
4951 
4952 	if (hotplug->ops->reset_slot)
4953 		rc = hotplug->ops->reset_slot(hotplug, probe);
4954 
4955 	module_put(hotplug->owner);
4956 
4957 	return rc;
4958 }
4959 
4960 static int pci_dev_reset_slot_function(struct pci_dev *dev, bool probe)
4961 {
4962 	if (dev->subordinate || !dev->slot ||
4963 	    dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET ||
4964 	    (dev->multifunction && !dev->slot->per_func_slot))
4965 		return -ENOTTY;
4966 
4967 	return pci_reset_hotplug_slot(dev->slot->hotplug, probe);
4968 }
4969 
4970 static u16 cxl_port_dvsec(struct pci_dev *dev)
4971 {
4972 	return pci_find_dvsec_capability(dev, PCI_VENDOR_ID_CXL,
4973 					 PCI_DVSEC_CXL_PORT);
4974 }
4975 
4976 static bool cxl_sbr_masked(struct pci_dev *dev)
4977 {
4978 	u16 dvsec, reg;
4979 	int rc;
4980 
4981 	dvsec = cxl_port_dvsec(dev);
4982 	if (!dvsec)
4983 		return false;
4984 
4985 	rc = pci_read_config_word(dev, dvsec + PCI_DVSEC_CXL_PORT_CTL, &reg);
4986 	if (rc || PCI_POSSIBLE_ERROR(reg))
4987 		return false;
4988 
4989 	/*
4990 	 * Per CXL spec r3.1, sec 8.1.5.2, when "Unmask SBR" is 0, the SBR
4991 	 * bit in Bridge Control has no effect.  When 1, the Port generates
4992 	 * hot reset when the SBR bit is set to 1.
4993 	 */
4994 	if (reg & PCI_DVSEC_CXL_PORT_CTL_UNMASK_SBR)
4995 		return false;
4996 
4997 	return true;
4998 }
4999 
5000 static int pci_reset_bus_function(struct pci_dev *dev, bool probe)
5001 {
5002 	struct pci_dev *bridge = pci_upstream_bridge(dev);
5003 	int rc;
5004 
5005 	/*
5006 	 * If "dev" is below a CXL port that has SBR control masked, SBR
5007 	 * won't do anything, so return error.
5008 	 */
5009 	if (bridge && pcie_is_cxl(bridge) && cxl_sbr_masked(bridge))
5010 		return -ENOTTY;
5011 
5012 	rc = pci_dev_reset_iommu_prepare(dev);
5013 	if (rc) {
5014 		pci_err(dev, "failed to stop IOMMU for a PCI reset: %d\n", rc);
5015 		return rc;
5016 	}
5017 
5018 	rc = pci_dev_reset_slot_function(dev, probe);
5019 	if (rc != -ENOTTY)
5020 		goto done;
5021 
5022 	rc = pci_parent_bus_reset(dev, probe);
5023 done:
5024 	pci_dev_reset_iommu_done(dev);
5025 	return rc;
5026 }
5027 
5028 static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
5029 {
5030 	struct pci_dev *bridge;
5031 	u16 dvsec, reg, val;
5032 	int rc;
5033 
5034 	bridge = pci_upstream_bridge(dev);
5035 	if (!bridge)
5036 		return -ENOTTY;
5037 
5038 	dvsec = cxl_port_dvsec(bridge);
5039 	if (!dvsec)
5040 		return -ENOTTY;
5041 
5042 	if (probe)
5043 		return 0;
5044 
5045 	rc = pci_read_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL, &reg);
5046 	if (rc)
5047 		return -ENOTTY;
5048 
5049 	rc = pci_dev_reset_iommu_prepare(dev);
5050 	if (rc) {
5051 		pci_err(dev, "failed to stop IOMMU for a PCI reset: %d\n", rc);
5052 		return rc;
5053 	}
5054 
5055 	if (reg & PCI_DVSEC_CXL_PORT_CTL_UNMASK_SBR) {
5056 		val = reg;
5057 	} else {
5058 		val = reg | PCI_DVSEC_CXL_PORT_CTL_UNMASK_SBR;
5059 		pci_write_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL,
5060 				      val);
5061 	}
5062 
5063 	rc = pci_reset_bus_function(dev, probe);
5064 
5065 	if (reg != val)
5066 		pci_write_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL,
5067 				      reg);
5068 
5069 	pci_dev_reset_iommu_done(dev);
5070 	return rc;
5071 }
5072 
5073 void pci_dev_lock(struct pci_dev *dev)
5074 {
5075 	/* block PM suspend, driver probe, etc. */
5076 	device_lock(&dev->dev);
5077 	pci_cfg_access_lock(dev);
5078 }
5079 EXPORT_SYMBOL_GPL(pci_dev_lock);
5080 
5081 /* Return 1 on successful lock, 0 on contention */
5082 int pci_dev_trylock(struct pci_dev *dev)
5083 {
5084 	if (device_trylock(&dev->dev)) {
5085 		if (pci_cfg_access_trylock(dev))
5086 			return 1;
5087 		device_unlock(&dev->dev);
5088 	}
5089 
5090 	return 0;
5091 }
5092 EXPORT_SYMBOL_GPL(pci_dev_trylock);
5093 
5094 void pci_dev_unlock(struct pci_dev *dev)
5095 {
5096 	pci_cfg_access_unlock(dev);
5097 	device_unlock(&dev->dev);
5098 }
5099 EXPORT_SYMBOL_GPL(pci_dev_unlock);
5100 
5101 static void pci_dev_save_and_disable(struct pci_dev *dev)
5102 {
5103 	const struct pci_error_handlers *err_handler =
5104 			dev->driver ? dev->driver->err_handler : NULL;
5105 
5106 	/*
5107 	 * dev->driver->err_handler->reset_prepare() is protected against
5108 	 * races with ->remove() by the device lock, which must be held by
5109 	 * the caller.
5110 	 */
5111 	device_lock_assert(&dev->dev);
5112 	if (err_handler && err_handler->reset_prepare)
5113 		err_handler->reset_prepare(dev);
5114 	else if (dev->driver)
5115 		pci_warn(dev, "resetting");
5116 
5117 	/*
5118 	 * Wake-up device prior to save.  PM registers default to D0 after
5119 	 * reset and a simple register restore doesn't reliably return
5120 	 * to a non-D0 state anyway.
5121 	 */
5122 	pci_set_power_state(dev, PCI_D0);
5123 
5124 	if (!pci_dev_config_accessible(dev, "save state"))
5125 		return;
5126 
5127 	pci_save_state(dev);
5128 	/*
5129 	 * Disable the device by clearing the Command register, except for
5130 	 * INTx-disable which is set.  This not only disables MMIO and I/O port
5131 	 * BARs, but also prevents the device from being Bus Master, preventing
5132 	 * DMA from the device including MSI/MSI-X interrupts.  For PCI 2.3
5133 	 * compliant devices, INTx-disable prevents legacy interrupts.
5134 	 */
5135 	pci_write_config_word(dev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
5136 }
5137 
5138 static void pci_dev_restore(struct pci_dev *dev)
5139 {
5140 	const struct pci_error_handlers *err_handler =
5141 			dev->driver ? dev->driver->err_handler : NULL;
5142 
5143 	pci_restore_state(dev);
5144 
5145 	/*
5146 	 * dev->driver->err_handler->reset_done() is protected against
5147 	 * races with ->remove() by the device lock, which must be held by
5148 	 * the caller.
5149 	 */
5150 	if (err_handler && err_handler->reset_done)
5151 		err_handler->reset_done(dev);
5152 	else if (dev->driver)
5153 		pci_warn(dev, "reset done");
5154 }
5155 
5156 /* dev->reset_methods[] is a 0-terminated list of indices into this array */
5157 const struct pci_reset_fn_method pci_reset_fn_methods[] = {
5158 	{ },
5159 	{ pci_dev_specific_reset, .name = "device_specific" },
5160 	{ pci_dev_acpi_reset, .name = "acpi" },
5161 	{ pcie_reset_flr, .name = "flr" },
5162 	{ pci_af_flr, .name = "af_flr" },
5163 	{ pci_pm_reset, .name = "pm" },
5164 	{ pci_reset_bus_function, .name = "bus" },
5165 	{ cxl_reset_bus_function, .name = "cxl_bus" },
5166 };
5167 
5168 /**
5169  * __pci_reset_function_locked - reset a PCI device function while holding
5170  * the @dev mutex lock.
5171  * @dev: PCI device to reset
5172  *
5173  * Some devices allow an individual function to be reset without affecting
5174  * other functions in the same device.  The PCI device must be responsive
5175  * to PCI config space in order to use this function.
5176  *
5177  * The device function is presumed to be unused and the caller is holding
5178  * the device mutex lock when this function is called.
5179  *
5180  * Resetting the device will make the contents of PCI configuration space
5181  * random, so any caller of this must be prepared to reinitialise the
5182  * device including MSI, bus mastering, BARs, decoding IO and memory spaces,
5183  * etc.
5184  *
5185  * Context: The caller must hold the device lock.
5186  *
5187  * Return: 0 if the device function was successfully reset or negative if the
5188  * device doesn't support resetting a single function.
5189  */
5190 int __pci_reset_function_locked(struct pci_dev *dev)
5191 {
5192 	int i, m, rc;
5193 	const struct pci_reset_fn_method *method;
5194 
5195 	might_sleep();
5196 	device_lock_assert(&dev->dev);
5197 
5198 	/*
5199 	 * A reset method returns -ENOTTY if it doesn't support this device and
5200 	 * we should try the next method.
5201 	 *
5202 	 * If it returns 0 (success), we're finished.  If it returns any other
5203 	 * error, we're also finished: this indicates that further reset
5204 	 * mechanisms might be broken on the device.
5205 	 */
5206 	for (i = 0; i < PCI_NUM_RESET_METHODS; i++) {
5207 		m = dev->reset_methods[i];
5208 		if (!m)
5209 			return -ENOTTY;
5210 
5211 		method = &pci_reset_fn_methods[m];
5212 		pci_dbg(dev, "reset via %s\n", method->name);
5213 		rc = method->reset_fn(dev, PCI_RESET_DO_RESET);
5214 		if (!rc)
5215 			return 0;
5216 
5217 		pci_dbg(dev, "%s failed with %d\n", method->name, rc);
5218 		if (rc != -ENOTTY)
5219 			return rc;
5220 	}
5221 
5222 	return -ENOTTY;
5223 }
5224 EXPORT_SYMBOL_GPL(__pci_reset_function_locked);
5225 
5226 /**
5227  * pci_init_reset_methods - check whether device can be safely reset
5228  * and store supported reset mechanisms.
5229  * @dev: PCI device to check for reset mechanisms
5230  *
5231  * Some devices allow an individual function to be reset without affecting
5232  * other functions in the same device.  The PCI device must be in D0-D3hot
5233  * state.
5234  *
5235  * Stores reset mechanisms supported by device in reset_methods byte array
5236  * which is a member of struct pci_dev.
5237  */
5238 void pci_init_reset_methods(struct pci_dev *dev)
5239 {
5240 	int m, i, rc;
5241 
5242 	BUILD_BUG_ON(ARRAY_SIZE(pci_reset_fn_methods) != PCI_NUM_RESET_METHODS);
5243 
5244 	might_sleep();
5245 
5246 	i = 0;
5247 	for (m = 1; m < PCI_NUM_RESET_METHODS; m++) {
5248 		rc = pci_reset_fn_methods[m].reset_fn(dev, PCI_RESET_PROBE);
5249 		if (!rc)
5250 			dev->reset_methods[i++] = m;
5251 		else if (rc != -ENOTTY)
5252 			break;
5253 	}
5254 
5255 	dev->reset_methods[i] = 0;
5256 }
5257 
5258 /**
5259  * pci_reset_function - quiesce and reset a PCI device function
5260  * @dev: PCI device to reset
5261  *
5262  * Some devices allow an individual function to be reset without affecting
5263  * other functions in the same device.  The PCI device must be responsive
5264  * to PCI config space in order to use this function.
5265  *
5266  * This function does not just reset the PCI portion of a device, but
5267  * clears all the state associated with the device.  This function differs
5268  * from __pci_reset_function_locked() in that it saves and restores device state
5269  * over the reset and takes the PCI device lock.
5270  *
5271  * Returns 0 if the device function was successfully reset or negative if the
5272  * device doesn't support resetting a single function.
5273  */
5274 int pci_reset_function(struct pci_dev *dev)
5275 {
5276 	struct pci_dev *bridge;
5277 	int rc;
5278 
5279 	if (!pci_reset_supported(dev))
5280 		return -ENOTTY;
5281 
5282 	/*
5283 	 * If there's no upstream bridge, no locking is needed since there is
5284 	 * no upstream bridge configuration to hold consistent.
5285 	 */
5286 	bridge = pci_upstream_bridge(dev);
5287 	if (bridge)
5288 		pci_dev_lock(bridge);
5289 
5290 	pci_dev_lock(dev);
5291 	pci_dev_save_and_disable(dev);
5292 
5293 	rc = __pci_reset_function_locked(dev);
5294 
5295 	pci_dev_restore(dev);
5296 	pci_dev_unlock(dev);
5297 
5298 	if (bridge)
5299 		pci_dev_unlock(bridge);
5300 
5301 	return rc;
5302 }
5303 EXPORT_SYMBOL_GPL(pci_reset_function);
5304 
5305 /**
5306  * pci_reset_function_locked - quiesce and reset a PCI device function
5307  * @dev: PCI device to reset
5308  *
5309  * Some devices allow an individual function to be reset without affecting
5310  * other functions in the same device.  The PCI device must be responsive
5311  * to PCI config space in order to use this function.
5312  *
5313  * This function does not just reset the PCI portion of a device, but
5314  * clears all the state associated with the device.  This function differs
5315  * from __pci_reset_function_locked() in that it saves and restores device state
5316  * over the reset.  It also differs from pci_reset_function() in that it
5317  * requires the PCI device lock to be held.
5318  *
5319  * Context: The caller must hold the device lock.
5320  *
5321  * Return: 0 if the device function was successfully reset or negative if the
5322  * device doesn't support resetting a single function.
5323  */
5324 int pci_reset_function_locked(struct pci_dev *dev)
5325 {
5326 	int rc;
5327 
5328 	device_lock_assert(&dev->dev);
5329 
5330 	if (!pci_reset_supported(dev))
5331 		return -ENOTTY;
5332 
5333 	pci_dev_save_and_disable(dev);
5334 
5335 	rc = __pci_reset_function_locked(dev);
5336 
5337 	pci_dev_restore(dev);
5338 
5339 	return rc;
5340 }
5341 EXPORT_SYMBOL_GPL(pci_reset_function_locked);
5342 
5343 /**
5344  * pci_try_reset_function - quiesce and reset a PCI device function
5345  * @dev: PCI device to reset
5346  *
5347  * Same as above, except return -EAGAIN if unable to lock device.
5348  */
5349 int pci_try_reset_function(struct pci_dev *dev)
5350 {
5351 	int rc;
5352 
5353 	if (!pci_reset_supported(dev))
5354 		return -ENOTTY;
5355 
5356 	if (!pci_dev_trylock(dev))
5357 		return -EAGAIN;
5358 
5359 	pci_dev_save_and_disable(dev);
5360 	rc = __pci_reset_function_locked(dev);
5361 	pci_dev_restore(dev);
5362 	pci_dev_unlock(dev);
5363 
5364 	return rc;
5365 }
5366 EXPORT_SYMBOL_GPL(pci_try_reset_function);
5367 
5368 /* Do any devices on or below this bus prevent a bus reset? */
5369 static bool pci_bus_resettable(struct pci_bus *bus)
5370 {
5371 	struct pci_dev *dev;
5372 
5373 
5374 	if (bus->self && (bus->self->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET))
5375 		return false;
5376 
5377 	list_for_each_entry(dev, &bus->devices, bus_list) {
5378 		if (dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET ||
5379 		    (dev->subordinate && !pci_bus_resettable(dev->subordinate)))
5380 			return false;
5381 	}
5382 
5383 	return true;
5384 }
5385 
5386 static void pci_bus_lock(struct pci_bus *bus);
5387 static void pci_bus_unlock(struct pci_bus *bus);
5388 static int pci_bus_trylock(struct pci_bus *bus);
5389 
5390 /* Lock devices from the top of the tree down */
5391 static void __pci_bus_lock(struct pci_bus *bus, struct pci_slot *slot)
5392 {
5393 	struct pci_dev *dev, *bridge = bus->self;
5394 
5395 	if (bridge)
5396 		pci_dev_lock(bridge);
5397 
5398 	list_for_each_entry(dev, &bus->devices, bus_list) {
5399 		if (slot && (!dev->slot || dev->slot != slot))
5400 			continue;
5401 		if (dev->subordinate)
5402 			pci_bus_lock(dev->subordinate);
5403 		else
5404 			pci_dev_lock(dev);
5405 	}
5406 }
5407 
5408 /* Unlock devices from the bottom of the tree up */
5409 static void __pci_bus_unlock(struct pci_bus *bus, struct pci_slot *slot)
5410 {
5411 	struct pci_dev *dev, *bridge = bus->self;
5412 
5413 	list_for_each_entry(dev, &bus->devices, bus_list) {
5414 		if (slot && (!dev->slot || dev->slot != slot))
5415 			continue;
5416 		if (dev->subordinate)
5417 			pci_bus_unlock(dev->subordinate);
5418 		else
5419 			pci_dev_unlock(dev);
5420 	}
5421 
5422 	if (bridge)
5423 		pci_dev_unlock(bridge);
5424 }
5425 
5426 /* Return 1 on successful lock, 0 on contention */
5427 static int __pci_bus_trylock(struct pci_bus *bus, struct pci_slot *slot)
5428 {
5429 	struct pci_dev *dev, *bridge = bus->self;
5430 
5431 	if (bridge && !pci_dev_trylock(bridge))
5432 		return 0;
5433 
5434 	list_for_each_entry(dev, &bus->devices, bus_list) {
5435 		if (slot && (!dev->slot || dev->slot != slot))
5436 			continue;
5437 		if (dev->subordinate) {
5438 			if (!pci_bus_trylock(dev->subordinate))
5439 				goto unlock;
5440 		} else if (!pci_dev_trylock(dev))
5441 			goto unlock;
5442 	}
5443 	return 1;
5444 
5445 unlock:
5446 	list_for_each_entry_continue_reverse(dev, &bus->devices, bus_list) {
5447 		if (slot && (!dev->slot || dev->slot != slot))
5448 			continue;
5449 		if (dev->subordinate)
5450 			pci_bus_unlock(dev->subordinate);
5451 		else
5452 			pci_dev_unlock(dev);
5453 	}
5454 
5455 	if (bridge)
5456 		pci_dev_unlock(bridge);
5457 	return 0;
5458 }
5459 
5460 /* Lock devices from the top of the tree down */
5461 static void pci_bus_lock(struct pci_bus *bus)
5462 {
5463 	__pci_bus_lock(bus, NULL);
5464 }
5465 
5466 /* Unlock devices from the bottom of the tree up */
5467 static void pci_bus_unlock(struct pci_bus *bus)
5468 {
5469 	__pci_bus_unlock(bus, NULL);
5470 }
5471 
5472 /* Return 1 on successful lock, 0 on contention */
5473 static int pci_bus_trylock(struct pci_bus *bus)
5474 {
5475 	return __pci_bus_trylock(bus, NULL);
5476 }
5477 
5478 /* Do any devices on or below this slot prevent a bus reset? */
5479 static bool pci_slot_resettable(struct pci_slot *slot)
5480 {
5481 	struct pci_dev *dev, *bridge = slot->bus->self;
5482 
5483 	if (bridge && (bridge->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET))
5484 		return false;
5485 
5486 	list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5487 		if (!dev->slot || dev->slot != slot)
5488 			continue;
5489 		if (dev->dev_flags & PCI_DEV_FLAGS_NO_BUS_RESET ||
5490 		    (dev->subordinate && !pci_bus_resettable(dev->subordinate)))
5491 			return false;
5492 	}
5493 
5494 	return true;
5495 }
5496 
5497 /* Lock devices from the top of the tree down */
5498 static void pci_slot_lock(struct pci_slot *slot)
5499 {
5500 	__pci_bus_lock(slot->bus, slot);
5501 }
5502 
5503 /* Unlock devices from the bottom of the tree up */
5504 static void pci_slot_unlock(struct pci_slot *slot)
5505 {
5506 	__pci_bus_unlock(slot->bus, slot);
5507 }
5508 
5509 /* Return 1 on successful lock, 0 on contention */
5510 static int pci_slot_trylock(struct pci_slot *slot)
5511 {
5512 	return __pci_bus_trylock(slot->bus, slot);
5513 }
5514 
5515 /*
5516  * Save and disable devices from the top of the tree down while holding
5517  * the @dev mutex lock for the entire tree.
5518  */
5519 static void pci_bus_save_and_disable_locked(struct pci_bus *bus)
5520 {
5521 	struct pci_dev *dev;
5522 
5523 	list_for_each_entry(dev, &bus->devices, bus_list) {
5524 		pci_dev_save_and_disable(dev);
5525 		if (dev->subordinate)
5526 			pci_bus_save_and_disable_locked(dev->subordinate);
5527 	}
5528 }
5529 
5530 /*
5531  * Restore devices from top of the tree down while holding @dev mutex lock
5532  * for the entire tree.  Parent bridges need to be restored before we can
5533  * get to subordinate devices.
5534  */
5535 static void pci_bus_restore_locked(struct pci_bus *bus)
5536 {
5537 	struct pci_dev *dev;
5538 
5539 	list_for_each_entry(dev, &bus->devices, bus_list) {
5540 		pci_dev_restore(dev);
5541 		if (dev->subordinate) {
5542 			pci_bridge_wait_for_secondary_bus(dev, "bus reset");
5543 			pci_bus_restore_locked(dev->subordinate);
5544 		}
5545 	}
5546 }
5547 
5548 /*
5549  * Save and disable devices from the top of the tree down while holding
5550  * the @dev mutex lock for the entire tree.
5551  */
5552 static void pci_slot_save_and_disable_locked(struct pci_slot *slot)
5553 {
5554 	struct pci_dev *dev;
5555 
5556 	list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5557 		if (!dev->slot || dev->slot != slot)
5558 			continue;
5559 		pci_dev_save_and_disable(dev);
5560 		if (dev->subordinate)
5561 			pci_bus_save_and_disable_locked(dev->subordinate);
5562 	}
5563 }
5564 
5565 /*
5566  * Restore devices from top of the tree down while holding @dev mutex lock
5567  * for the entire tree.  Parent bridges need to be restored before we can
5568  * get to subordinate devices.
5569  */
5570 static void pci_slot_restore_locked(struct pci_slot *slot)
5571 {
5572 	struct pci_dev *dev;
5573 
5574 	list_for_each_entry(dev, &slot->bus->devices, bus_list) {
5575 		if (!dev->slot || dev->slot != slot)
5576 			continue;
5577 		pci_dev_restore(dev);
5578 		if (dev->subordinate) {
5579 			pci_bridge_wait_for_secondary_bus(dev, "slot reset");
5580 			pci_bus_restore_locked(dev->subordinate);
5581 		}
5582 	}
5583 }
5584 
5585 static int pci_slot_reset(struct pci_slot *slot, bool probe)
5586 {
5587 	int rc;
5588 
5589 	if (!slot || !pci_slot_resettable(slot))
5590 		return -ENOTTY;
5591 
5592 	if (!probe)
5593 		pci_slot_lock(slot);
5594 
5595 	might_sleep();
5596 
5597 	rc = pci_reset_hotplug_slot(slot->hotplug, probe);
5598 
5599 	if (!probe)
5600 		pci_slot_unlock(slot);
5601 
5602 	return rc;
5603 }
5604 
5605 /**
5606  * pci_probe_reset_slot - probe whether a PCI slot can be reset
5607  * @slot: PCI slot to probe
5608  *
5609  * Return 0 if slot can be reset, negative if a slot reset is not supported.
5610  */
5611 int pci_probe_reset_slot(struct pci_slot *slot)
5612 {
5613 	return pci_slot_reset(slot, PCI_RESET_PROBE);
5614 }
5615 EXPORT_SYMBOL_GPL(pci_probe_reset_slot);
5616 
5617 /**
5618  * pci_try_reset_slot - Try to reset a PCI slot
5619  * @slot: PCI slot to reset
5620  *
5621  * A PCI bus may host multiple slots, each slot may support a reset mechanism
5622  * independent of other slots.  For instance, some slots may support slot power
5623  * control.  In the case of a 1:1 bus to slot architecture, this function may
5624  * wrap the bus reset to avoid spurious slot related events such as hotplug.
5625  * Generally a slot reset should be attempted before a bus reset.  All of the
5626  * function of the slot and any subordinate buses behind the slot are reset
5627  * through this function.  PCI config space of all devices in the slot and
5628  * behind the slot is saved before and restored after reset.
5629  *
5630  * Same as above except return -EAGAIN if the slot cannot be locked
5631  */
5632 static int pci_try_reset_slot(struct pci_slot *slot)
5633 {
5634 	int rc;
5635 
5636 	rc = pci_slot_reset(slot, PCI_RESET_PROBE);
5637 	if (rc)
5638 		return rc;
5639 
5640 	if (pci_slot_trylock(slot)) {
5641 		pci_slot_save_and_disable_locked(slot);
5642 		might_sleep();
5643 		rc = pci_reset_hotplug_slot(slot->hotplug, PCI_RESET_DO_RESET);
5644 		pci_slot_restore_locked(slot);
5645 		pci_slot_unlock(slot);
5646 	} else
5647 		rc = -EAGAIN;
5648 
5649 	return rc;
5650 }
5651 
5652 static int pci_bus_reset(struct pci_bus *bus, bool probe)
5653 {
5654 	int ret;
5655 
5656 	if (!bus->self || !pci_bus_resettable(bus))
5657 		return -ENOTTY;
5658 
5659 	if (probe)
5660 		return 0;
5661 
5662 	pci_bus_lock(bus);
5663 
5664 	might_sleep();
5665 
5666 	ret = pci_bridge_secondary_bus_reset(bus->self);
5667 
5668 	pci_bus_unlock(bus);
5669 
5670 	return ret;
5671 }
5672 
5673 /**
5674  * pci_try_reset_bus - Try to reset a PCI bus
5675  * @bus: top level PCI bus to reset
5676  *
5677  * Same as above except return -EAGAIN if the bus cannot be locked
5678  */
5679 static int pci_try_reset_bus(struct pci_bus *bus)
5680 {
5681 	int rc;
5682 
5683 	rc = pci_bus_reset(bus, PCI_RESET_PROBE);
5684 	if (rc)
5685 		return rc;
5686 
5687 	if (pci_bus_trylock(bus)) {
5688 		pci_bus_save_and_disable_locked(bus);
5689 		might_sleep();
5690 		rc = pci_bridge_secondary_bus_reset(bus->self);
5691 		pci_bus_restore_locked(bus);
5692 		pci_bus_unlock(bus);
5693 	} else
5694 		rc = -EAGAIN;
5695 
5696 	return rc;
5697 }
5698 
5699 #define PCI_RESET_RESTORE true
5700 #define PCI_RESET_NO_RESTORE false
5701 /**
5702  * pci_reset_bridge - reset a bridge's subordinate bus
5703  * @bridge: bridge that connects to the bus to reset
5704  * @restore: when true use a reset method that invokes pci_dev_restore() post
5705  *           reset for affected devices
5706  *
5707  * This function will first try to reset the slots on this bus if the method is
5708  * available. If slot reset is not available, this will fall back to a
5709  * secondary bus reset.
5710  */
5711 static int pci_reset_bridge(struct pci_dev *bridge, bool restore)
5712 {
5713 	struct pci_bus *bus = bridge->subordinate;
5714 	struct pci_slot *slot;
5715 	int ret = 0;
5716 
5717 	if (!bus)
5718 		return -ENOTTY;
5719 
5720 	mutex_lock(&pci_slot_mutex);
5721 	if (list_empty(&bus->slots))
5722 		goto bus_reset;
5723 
5724 	list_for_each_entry(slot, &bus->slots, list)
5725 		if (pci_probe_reset_slot(slot))
5726 			goto bus_reset;
5727 
5728 	list_for_each_entry(slot, &bus->slots, list) {
5729 		if (restore)
5730 			ret = pci_try_reset_slot(slot);
5731 		else
5732 			ret = pci_slot_reset(slot, PCI_RESET_DO_RESET);
5733 
5734 		if (ret)
5735 			break;
5736 	}
5737 
5738 	mutex_unlock(&pci_slot_mutex);
5739 	return ret;
5740 bus_reset:
5741 	mutex_unlock(&pci_slot_mutex);
5742 
5743 	if (restore)
5744 		return pci_try_reset_bus(bus);
5745 	return pci_bus_reset(bridge->subordinate, PCI_RESET_DO_RESET);
5746 }
5747 
5748 /**
5749  * pci_bus_error_reset - reset the bridge's subordinate bus
5750  * @bridge: The parent device that connects to the bus to reset
5751  */
5752 int pci_bus_error_reset(struct pci_dev *bridge)
5753 {
5754 	return pci_reset_bridge(bridge, PCI_RESET_NO_RESTORE);
5755 }
5756 EXPORT_SYMBOL_GPL(pci_bus_error_reset);
5757 
5758 int pci_try_reset_bridge(struct pci_dev *bridge)
5759 {
5760 	return pci_reset_bridge(bridge, PCI_RESET_RESTORE);
5761 }
5762 
5763 /**
5764  * pci_probe_reset_bus - probe whether a PCI bus can be reset
5765  * @bus: PCI bus to probe
5766  *
5767  * Return 0 if bus can be reset, negative if a bus reset is not supported.
5768  */
5769 int pci_probe_reset_bus(struct pci_bus *bus)
5770 {
5771 	return pci_bus_reset(bus, PCI_RESET_PROBE);
5772 }
5773 EXPORT_SYMBOL_GPL(pci_probe_reset_bus);
5774 
5775 /**
5776  * pci_reset_bus - Try to reset a PCI bus
5777  * @pdev: top level PCI device to reset via slot/bus
5778  *
5779  * Same as above except return -EAGAIN if the bus cannot be locked
5780  */
5781 int pci_reset_bus(struct pci_dev *pdev)
5782 {
5783 	return (!pci_probe_reset_slot(pdev->slot)) ?
5784 	    pci_try_reset_slot(pdev->slot) : pci_try_reset_bus(pdev->bus);
5785 }
5786 EXPORT_SYMBOL_GPL(pci_reset_bus);
5787 
5788 /**
5789  * pcix_get_max_mmrbc - get PCI-X maximum designed memory read byte count
5790  * @dev: PCI device to query
5791  *
5792  * Returns mmrbc: maximum designed memory read count in bytes or
5793  * appropriate error value.
5794  */
5795 int pcix_get_max_mmrbc(struct pci_dev *dev)
5796 {
5797 	int cap;
5798 	u32 stat;
5799 
5800 	cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
5801 	if (!cap)
5802 		return -EINVAL;
5803 
5804 	if (pci_read_config_dword(dev, cap + PCI_X_STATUS, &stat))
5805 		return -EINVAL;
5806 
5807 	return 512 << FIELD_GET(PCI_X_STATUS_MAX_READ, stat);
5808 }
5809 EXPORT_SYMBOL(pcix_get_max_mmrbc);
5810 
5811 /**
5812  * pcix_get_mmrbc - get PCI-X maximum memory read byte count
5813  * @dev: PCI device to query
5814  *
5815  * Returns mmrbc: maximum memory read count in bytes or appropriate error
5816  * value.
5817  */
5818 int pcix_get_mmrbc(struct pci_dev *dev)
5819 {
5820 	int cap;
5821 	u16 cmd;
5822 
5823 	cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
5824 	if (!cap)
5825 		return -EINVAL;
5826 
5827 	if (pci_read_config_word(dev, cap + PCI_X_CMD, &cmd))
5828 		return -EINVAL;
5829 
5830 	return 512 << FIELD_GET(PCI_X_CMD_MAX_READ, cmd);
5831 }
5832 EXPORT_SYMBOL(pcix_get_mmrbc);
5833 
5834 /**
5835  * pcix_set_mmrbc - set PCI-X maximum memory read byte count
5836  * @dev: PCI device to query
5837  * @mmrbc: maximum memory read count in bytes
5838  *    valid values are 512, 1024, 2048, 4096
5839  *
5840  * If possible sets maximum memory read byte count, some bridges have errata
5841  * that prevent this.
5842  */
5843 int pcix_set_mmrbc(struct pci_dev *dev, int mmrbc)
5844 {
5845 	int cap;
5846 	u32 stat, v, o;
5847 	u16 cmd;
5848 
5849 	if (mmrbc < 512 || mmrbc > 4096 || !is_power_of_2(mmrbc))
5850 		return -EINVAL;
5851 
5852 	v = ffs(mmrbc) - 10;
5853 
5854 	cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
5855 	if (!cap)
5856 		return -EINVAL;
5857 
5858 	if (pci_read_config_dword(dev, cap + PCI_X_STATUS, &stat))
5859 		return -EINVAL;
5860 
5861 	if (v > FIELD_GET(PCI_X_STATUS_MAX_READ, stat))
5862 		return -E2BIG;
5863 
5864 	if (pci_read_config_word(dev, cap + PCI_X_CMD, &cmd))
5865 		return -EINVAL;
5866 
5867 	o = FIELD_GET(PCI_X_CMD_MAX_READ, cmd);
5868 	if (o != v) {
5869 		if (v > o && (dev->bus->bus_flags & PCI_BUS_FLAGS_NO_MMRBC))
5870 			return -EIO;
5871 
5872 		FIELD_MODIFY(PCI_X_CMD_MAX_READ, &cmd, v);
5873 		if (pci_write_config_word(dev, cap + PCI_X_CMD, cmd))
5874 			return -EIO;
5875 	}
5876 	return 0;
5877 }
5878 EXPORT_SYMBOL(pcix_set_mmrbc);
5879 
5880 /**
5881  * pcie_get_readrq - get PCI Express read request size
5882  * @dev: PCI device to query
5883  *
5884  * Returns maximum memory read request in bytes or appropriate error value.
5885  */
5886 int pcie_get_readrq(struct pci_dev *dev)
5887 {
5888 	u16 ctl;
5889 
5890 	pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &ctl);
5891 
5892 	return 128 << FIELD_GET(PCI_EXP_DEVCTL_READRQ, ctl);
5893 }
5894 EXPORT_SYMBOL(pcie_get_readrq);
5895 
5896 /**
5897  * pcie_set_readrq - set PCI Express maximum memory read request
5898  * @dev: PCI device to query
5899  * @rq: maximum memory read count in bytes
5900  *    valid values are 128, 256, 512, 1024, 2048, 4096
5901  *
5902  * If possible sets maximum memory read request in bytes
5903  */
5904 int pcie_set_readrq(struct pci_dev *dev, int rq)
5905 {
5906 	u16 v;
5907 	int ret;
5908 	unsigned int firstbit;
5909 	struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus);
5910 
5911 	if (rq < 128 || rq > 4096 || !is_power_of_2(rq))
5912 		return -EINVAL;
5913 
5914 	/*
5915 	 * If using the "performance" PCIe config, we clamp the read rq
5916 	 * size to the max packet size to keep the host bridge from
5917 	 * generating requests larger than we can cope with.
5918 	 */
5919 	if (pcie_bus_config == PCIE_BUS_PERFORMANCE) {
5920 		int mps = pcie_get_mps(dev);
5921 
5922 		if (mps < rq)
5923 			rq = mps;
5924 	}
5925 
5926 	firstbit = ffs(rq);
5927 	if (firstbit < 8)
5928 		return -EINVAL;
5929 	v = FIELD_PREP(PCI_EXP_DEVCTL_READRQ, firstbit - 8);
5930 
5931 	if (bridge->no_inc_mrrs) {
5932 		int max_mrrs = pcie_get_readrq(dev);
5933 
5934 		if (rq > max_mrrs) {
5935 			pci_info(dev, "can't set Max_Read_Request_Size to %d; max is %d\n", rq, max_mrrs);
5936 			return -EINVAL;
5937 		}
5938 	}
5939 
5940 	ret = pcie_capability_clear_and_set_word(dev, PCI_EXP_DEVCTL,
5941 						  PCI_EXP_DEVCTL_READRQ, v);
5942 
5943 	return pcibios_err_to_errno(ret);
5944 }
5945 EXPORT_SYMBOL(pcie_set_readrq);
5946 
5947 /**
5948  * pcie_get_mps - get PCI Express maximum payload size
5949  * @dev: PCI device to query
5950  *
5951  * Returns maximum payload size in bytes
5952  */
5953 int pcie_get_mps(struct pci_dev *dev)
5954 {
5955 	u16 ctl;
5956 
5957 	pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &ctl);
5958 
5959 	return 128 << FIELD_GET(PCI_EXP_DEVCTL_PAYLOAD, ctl);
5960 }
5961 EXPORT_SYMBOL(pcie_get_mps);
5962 
5963 /**
5964  * pcie_set_mps - set PCI Express maximum payload size
5965  * @dev: PCI device to query
5966  * @mps: maximum payload size in bytes
5967  *    valid values are 128, 256, 512, 1024, 2048, 4096
5968  *
5969  * If possible sets maximum payload size
5970  */
5971 int pcie_set_mps(struct pci_dev *dev, int mps)
5972 {
5973 	u16 v;
5974 	int ret;
5975 
5976 	if (mps < 128 || mps > 4096 || !is_power_of_2(mps))
5977 		return -EINVAL;
5978 
5979 	v = ffs(mps) - 8;
5980 	if (v > dev->pcie_mpss)
5981 		return -EINVAL;
5982 	v = FIELD_PREP(PCI_EXP_DEVCTL_PAYLOAD, v);
5983 
5984 	ret = pcie_capability_clear_and_set_word(dev, PCI_EXP_DEVCTL,
5985 						  PCI_EXP_DEVCTL_PAYLOAD, v);
5986 
5987 	return pcibios_err_to_errno(ret);
5988 }
5989 EXPORT_SYMBOL(pcie_set_mps);
5990 
5991 static enum pci_bus_speed to_pcie_link_speed(u16 lnksta)
5992 {
5993 	return pcie_link_speed[FIELD_GET(PCI_EXP_LNKSTA_CLS, lnksta)];
5994 }
5995 
5996 int pcie_link_speed_mbps(struct pci_dev *pdev)
5997 {
5998 	u16 lnksta;
5999 	int err;
6000 
6001 	err = pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnksta);
6002 	if (err)
6003 		return err;
6004 
6005 	return pcie_dev_speed_mbps(to_pcie_link_speed(lnksta));
6006 }
6007 EXPORT_SYMBOL(pcie_link_speed_mbps);
6008 
6009 /**
6010  * pcie_bandwidth_available - determine minimum link settings of a PCIe
6011  *			      device and its bandwidth limitation
6012  * @dev: PCI device to query
6013  * @limiting_dev: storage for device causing the bandwidth limitation
6014  * @speed: storage for speed of limiting device
6015  * @width: storage for width of limiting device
6016  *
6017  * Walk up the PCI device chain and find the point where the minimum
6018  * bandwidth is available.  Return the bandwidth available there and (if
6019  * limiting_dev, speed, and width pointers are supplied) information about
6020  * that point.  The bandwidth returned is in Mb/s, i.e., megabits/second of
6021  * raw bandwidth.
6022  */
6023 u32 pcie_bandwidth_available(struct pci_dev *dev, struct pci_dev **limiting_dev,
6024 			     enum pci_bus_speed *speed,
6025 			     enum pcie_link_width *width)
6026 {
6027 	u16 lnksta;
6028 	enum pci_bus_speed next_speed;
6029 	enum pcie_link_width next_width;
6030 	u32 bw, next_bw;
6031 
6032 	if (speed)
6033 		*speed = PCI_SPEED_UNKNOWN;
6034 	if (width)
6035 		*width = PCIE_LNK_WIDTH_UNKNOWN;
6036 
6037 	bw = 0;
6038 
6039 	while (dev) {
6040 		pcie_capability_read_word(dev, PCI_EXP_LNKSTA, &lnksta);
6041 
6042 		next_speed = to_pcie_link_speed(lnksta);
6043 		next_width = FIELD_GET(PCI_EXP_LNKSTA_NLW, lnksta);
6044 
6045 		next_bw = next_width * PCIE_SPEED2MBS_ENC(next_speed);
6046 
6047 		/* Check if current device limits the total bandwidth */
6048 		if (!bw || next_bw <= bw) {
6049 			bw = next_bw;
6050 
6051 			if (limiting_dev)
6052 				*limiting_dev = dev;
6053 			if (speed)
6054 				*speed = next_speed;
6055 			if (width)
6056 				*width = next_width;
6057 		}
6058 
6059 		dev = pci_upstream_bridge(dev);
6060 	}
6061 
6062 	return bw;
6063 }
6064 EXPORT_SYMBOL(pcie_bandwidth_available);
6065 
6066 /**
6067  * pcie_get_supported_speeds - query Supported Link Speed Vector
6068  * @dev: PCI device to query
6069  *
6070  * Query @dev supported link speeds.
6071  *
6072  * Implementation Note in PCIe r6.0 sec 7.5.3.18 recommends determining
6073  * supported link speeds using the Supported Link Speeds Vector in the Link
6074  * Capabilities 2 Register (when available).
6075  *
6076  * Link Capabilities 2 was added in PCIe r3.0, sec 7.8.18.
6077  *
6078  * Without Link Capabilities 2, i.e., prior to PCIe r3.0, Supported Link
6079  * Speeds field in Link Capabilities is used and only 2.5 GT/s and 5.0 GT/s
6080  * speeds were defined.
6081  *
6082  * For @dev without Supported Link Speed Vector, the field is synthesized
6083  * from the Max Link Speed field in the Link Capabilities Register.
6084  *
6085  * Return: Supported Link Speeds Vector (+ reserved 0 at LSB).
6086  */
6087 u8 pcie_get_supported_speeds(struct pci_dev *dev)
6088 {
6089 	u32 lnkcap2, lnkcap;
6090 	u8 speeds;
6091 
6092 	/*
6093 	 * Speeds retain the reserved 0 at LSB before PCIe Supported Link
6094 	 * Speeds Vector to allow using SLS Vector bit defines directly.
6095 	 */
6096 	pcie_capability_read_dword(dev, PCI_EXP_LNKCAP2, &lnkcap2);
6097 	speeds = lnkcap2 & PCI_EXP_LNKCAP2_SLS;
6098 
6099 	/* Ignore speeds higher than Max Link Speed */
6100 	pcie_capability_read_dword(dev, PCI_EXP_LNKCAP, &lnkcap);
6101 	speeds &= GENMASK(lnkcap & PCI_EXP_LNKCAP_SLS, 0);
6102 
6103 	/* PCIe r3.0-compliant */
6104 	if (speeds)
6105 		return speeds;
6106 
6107 	/* Synthesize from the Max Link Speed field */
6108 	if ((lnkcap & PCI_EXP_LNKCAP_SLS) == PCI_EXP_LNKCAP_SLS_5_0GB)
6109 		speeds = PCI_EXP_LNKCAP2_SLS_5_0GB | PCI_EXP_LNKCAP2_SLS_2_5GB;
6110 	else if ((lnkcap & PCI_EXP_LNKCAP_SLS) == PCI_EXP_LNKCAP_SLS_2_5GB)
6111 		speeds = PCI_EXP_LNKCAP2_SLS_2_5GB;
6112 
6113 	return speeds;
6114 }
6115 
6116 /**
6117  * pcie_get_speed_cap - query for the PCI device's link speed capability
6118  * @dev: PCI device to query
6119  *
6120  * Query the PCI device speed capability.
6121  *
6122  * Return: the maximum link speed supported by the device.
6123  */
6124 enum pci_bus_speed pcie_get_speed_cap(struct pci_dev *dev)
6125 {
6126 	return PCIE_LNKCAP2_SLS2SPEED(dev->supported_speeds);
6127 }
6128 EXPORT_SYMBOL(pcie_get_speed_cap);
6129 
6130 /**
6131  * pcie_get_width_cap - query for the PCI device's link width capability
6132  * @dev: PCI device to query
6133  *
6134  * Query the PCI device width capability.  Return the maximum link width
6135  * supported by the device.
6136  */
6137 enum pcie_link_width pcie_get_width_cap(struct pci_dev *dev)
6138 {
6139 	u32 lnkcap;
6140 
6141 	pcie_capability_read_dword(dev, PCI_EXP_LNKCAP, &lnkcap);
6142 	if (lnkcap)
6143 		return FIELD_GET(PCI_EXP_LNKCAP_MLW, lnkcap);
6144 
6145 	return PCIE_LNK_WIDTH_UNKNOWN;
6146 }
6147 EXPORT_SYMBOL(pcie_get_width_cap);
6148 
6149 /**
6150  * pcie_bandwidth_capable - calculate a PCI device's link bandwidth capability
6151  * @dev: PCI device
6152  * @speed: storage for link speed
6153  * @width: storage for link width
6154  *
6155  * Calculate a PCI device's link bandwidth by querying for its link speed
6156  * and width, multiplying them, and applying encoding overhead.  The result
6157  * is in Mb/s, i.e., megabits/second of raw bandwidth.
6158  */
6159 static u32 pcie_bandwidth_capable(struct pci_dev *dev,
6160 				  enum pci_bus_speed *speed,
6161 				  enum pcie_link_width *width)
6162 {
6163 	*speed = pcie_get_speed_cap(dev);
6164 	*width = pcie_get_width_cap(dev);
6165 
6166 	if (*speed == PCI_SPEED_UNKNOWN || *width == PCIE_LNK_WIDTH_UNKNOWN)
6167 		return 0;
6168 
6169 	return *width * PCIE_SPEED2MBS_ENC(*speed);
6170 }
6171 
6172 /**
6173  * __pcie_print_link_status - Report the PCI device's link speed and width
6174  * @dev: PCI device to query
6175  * @verbose: Print info even when enough bandwidth is available
6176  *
6177  * If the available bandwidth at the device is less than the device is
6178  * capable of, report the device's maximum possible bandwidth and the
6179  * upstream link that limits its performance.  If @verbose, always print
6180  * the available bandwidth, even if the device isn't constrained.
6181  */
6182 void __pcie_print_link_status(struct pci_dev *dev, bool verbose)
6183 {
6184 	enum pcie_link_width width, width_cap;
6185 	enum pci_bus_speed speed, speed_cap;
6186 	struct pci_dev *limiting_dev = NULL;
6187 	u32 bw_avail, bw_cap;
6188 	char *flit_mode = "";
6189 
6190 	bw_cap = pcie_bandwidth_capable(dev, &speed_cap, &width_cap);
6191 	bw_avail = pcie_bandwidth_available(dev, &limiting_dev, &speed, &width);
6192 
6193 	if (dev->bus && dev->bus->flit_mode)
6194 		flit_mode = ", in Flit mode";
6195 
6196 	if (bw_avail >= bw_cap && verbose)
6197 		pci_info(dev, "%u.%03u Gb/s available PCIe bandwidth (%s x%d link)%s\n",
6198 			 bw_cap / 1000, bw_cap % 1000,
6199 			 pci_speed_string(speed_cap), width_cap, flit_mode);
6200 	else if (bw_avail < bw_cap)
6201 		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",
6202 			 bw_avail / 1000, bw_avail % 1000,
6203 			 pci_speed_string(speed), width,
6204 			 limiting_dev ? pci_name(limiting_dev) : "<unknown>",
6205 			 bw_cap / 1000, bw_cap % 1000,
6206 			 pci_speed_string(speed_cap), width_cap, flit_mode);
6207 }
6208 
6209 /**
6210  * pcie_print_link_status - Report the PCI device's link speed and width
6211  * @dev: PCI device to query
6212  *
6213  * Report the available bandwidth at the device.
6214  */
6215 void pcie_print_link_status(struct pci_dev *dev)
6216 {
6217 	__pcie_print_link_status(dev, true);
6218 }
6219 EXPORT_SYMBOL(pcie_print_link_status);
6220 
6221 /**
6222  * pci_select_bars - Make BAR mask from the type of resource
6223  * @dev: the PCI device for which BAR mask is made
6224  * @flags: resource type mask to be selected
6225  *
6226  * This helper routine makes bar mask from the type of resource.
6227  */
6228 int pci_select_bars(struct pci_dev *dev, unsigned long flags)
6229 {
6230 	int i, bars = 0;
6231 	for (i = 0; i < PCI_NUM_RESOURCES; i++)
6232 		if (pci_resource_flags(dev, i) & flags)
6233 			bars |= (1 << i);
6234 	return bars;
6235 }
6236 EXPORT_SYMBOL(pci_select_bars);
6237 
6238 /* Some architectures require additional programming to enable VGA */
6239 static arch_set_vga_state_t arch_set_vga_state;
6240 
6241 void __init pci_register_set_vga_state(arch_set_vga_state_t func)
6242 {
6243 	arch_set_vga_state = func;	/* NULL disables */
6244 }
6245 
6246 static int pci_set_vga_state_arch(struct pci_dev *dev, bool decode,
6247 				  unsigned int command_bits, u32 flags)
6248 {
6249 	if (arch_set_vga_state)
6250 		return arch_set_vga_state(dev, decode, command_bits,
6251 						flags);
6252 	return 0;
6253 }
6254 
6255 /**
6256  * pci_set_vga_state - set VGA decode state on device and parents if requested
6257  * @dev: the PCI device
6258  * @decode: true = enable decoding, false = disable decoding
6259  * @command_bits: PCI_COMMAND_IO and/or PCI_COMMAND_MEMORY
6260  * @flags: traverse ancestors and change bridges
6261  * CHANGE_BRIDGE_ONLY / CHANGE_BRIDGE
6262  */
6263 int pci_set_vga_state(struct pci_dev *dev, bool decode,
6264 		      unsigned int command_bits, u32 flags)
6265 {
6266 	struct pci_bus *bus;
6267 	struct pci_dev *bridge;
6268 	u16 cmd;
6269 	int rc;
6270 
6271 	WARN_ON((flags & PCI_VGA_STATE_CHANGE_DECODES) && (command_bits & ~(PCI_COMMAND_IO|PCI_COMMAND_MEMORY)));
6272 
6273 	/* ARCH specific VGA enables */
6274 	rc = pci_set_vga_state_arch(dev, decode, command_bits, flags);
6275 	if (rc)
6276 		return rc;
6277 
6278 	if (flags & PCI_VGA_STATE_CHANGE_DECODES) {
6279 		pci_read_config_word(dev, PCI_COMMAND, &cmd);
6280 		if (decode)
6281 			cmd |= command_bits;
6282 		else
6283 			cmd &= ~command_bits;
6284 		pci_write_config_word(dev, PCI_COMMAND, cmd);
6285 	}
6286 
6287 	if (!(flags & PCI_VGA_STATE_CHANGE_BRIDGE))
6288 		return 0;
6289 
6290 	bus = dev->bus;
6291 	while (bus) {
6292 		bridge = bus->self;
6293 		if (bridge) {
6294 			pci_read_config_word(bridge, PCI_BRIDGE_CONTROL,
6295 					     &cmd);
6296 			if (decode)
6297 				cmd |= PCI_BRIDGE_CTL_VGA;
6298 			else
6299 				cmd &= ~PCI_BRIDGE_CTL_VGA;
6300 			pci_write_config_word(bridge, PCI_BRIDGE_CONTROL,
6301 					      cmd);
6302 
6303 
6304 			/*
6305 			 * VGA Enable may not be writable if bridge doesn't
6306 			 * support it.
6307 			 */
6308 			if (decode) {
6309 				pci_read_config_word(bridge, PCI_BRIDGE_CONTROL,
6310 						     &cmd);
6311 				if (!(cmd & PCI_BRIDGE_CTL_VGA))
6312 					return -EIO;
6313 			}
6314 		}
6315 		bus = bus->parent;
6316 	}
6317 	return 0;
6318 }
6319 
6320 #ifdef CONFIG_ACPI
6321 bool pci_pr3_present(struct pci_dev *pdev)
6322 {
6323 	struct acpi_device *adev;
6324 
6325 	if (acpi_disabled)
6326 		return false;
6327 
6328 	adev = ACPI_COMPANION(&pdev->dev);
6329 	if (!adev)
6330 		return false;
6331 
6332 	return adev->power.flags.power_resources &&
6333 		acpi_has_method(adev->handle, "_PR3");
6334 }
6335 EXPORT_SYMBOL_GPL(pci_pr3_present);
6336 #endif
6337 
6338 /**
6339  * pci_add_dma_alias - Add a DMA devfn alias for a device
6340  * @dev: the PCI device for which alias is added
6341  * @devfn_from: alias slot and function
6342  * @nr_devfns: number of subsequent devfns to alias
6343  *
6344  * This helper encodes an 8-bit devfn as a bit number in dma_alias_mask
6345  * which is used to program permissible bus-devfn source addresses for DMA
6346  * requests in an IOMMU.  These aliases factor into IOMMU group creation
6347  * and are useful for devices generating DMA requests beyond or different
6348  * from their logical bus-devfn.  Examples include device quirks where the
6349  * device simply uses the wrong devfn, as well as non-transparent bridges
6350  * where the alias may be a proxy for devices in another domain.
6351  *
6352  * IOMMU group creation is performed during device discovery or addition,
6353  * prior to any potential DMA mapping and therefore prior to driver probing
6354  * (especially for userspace assigned devices where IOMMU group definition
6355  * cannot be left as a userspace activity).  DMA aliases should therefore
6356  * be configured via quirks, such as the PCI fixup header quirk.
6357  */
6358 void pci_add_dma_alias(struct pci_dev *dev, u8 devfn_from,
6359 		       unsigned int nr_devfns)
6360 {
6361 	int devfn_to;
6362 
6363 	nr_devfns = min(nr_devfns, (unsigned int)MAX_NR_DEVFNS - devfn_from);
6364 	devfn_to = devfn_from + nr_devfns - 1;
6365 
6366 	if (!dev->dma_alias_mask)
6367 		dev->dma_alias_mask = bitmap_zalloc(MAX_NR_DEVFNS, GFP_KERNEL);
6368 	if (!dev->dma_alias_mask) {
6369 		pci_warn(dev, "Unable to allocate DMA alias mask\n");
6370 		return;
6371 	}
6372 
6373 	bitmap_set(dev->dma_alias_mask, devfn_from, nr_devfns);
6374 
6375 	if (nr_devfns == 1)
6376 		pci_info(dev, "Enabling fixed DMA alias to %02x.%d\n",
6377 				PCI_SLOT(devfn_from), PCI_FUNC(devfn_from));
6378 	else if (nr_devfns > 1)
6379 		pci_info(dev, "Enabling fixed DMA alias for devfn range from %02x.%d to %02x.%d\n",
6380 				PCI_SLOT(devfn_from), PCI_FUNC(devfn_from),
6381 				PCI_SLOT(devfn_to), PCI_FUNC(devfn_to));
6382 }
6383 
6384 bool pci_devs_are_dma_aliases(struct pci_dev *dev1, struct pci_dev *dev2)
6385 {
6386 	return (dev1->dma_alias_mask &&
6387 		test_bit(dev2->devfn, dev1->dma_alias_mask)) ||
6388 	       (dev2->dma_alias_mask &&
6389 		test_bit(dev1->devfn, dev2->dma_alias_mask)) ||
6390 	       pci_real_dma_dev(dev1) == dev2 ||
6391 	       pci_real_dma_dev(dev2) == dev1;
6392 }
6393 
6394 bool pci_device_is_present(struct pci_dev *pdev)
6395 {
6396 	u32 v;
6397 
6398 	/* Check PF if pdev is a VF, since VF Vendor/Device IDs are 0xffff */
6399 	pdev = pci_physfn(pdev);
6400 	if (pci_dev_is_disconnected(pdev))
6401 		return false;
6402 	return pci_bus_read_dev_vendor_id(pdev->bus, pdev->devfn, &v, 0);
6403 }
6404 EXPORT_SYMBOL_GPL(pci_device_is_present);
6405 
6406 void pci_ignore_hotplug(struct pci_dev *dev)
6407 {
6408 	struct pci_dev *bridge = dev->bus->self;
6409 
6410 	dev->ignore_hotplug = 1;
6411 	/* Propagate the "ignore hotplug" setting to the parent bridge. */
6412 	if (bridge)
6413 		bridge->ignore_hotplug = 1;
6414 }
6415 EXPORT_SYMBOL_GPL(pci_ignore_hotplug);
6416 
6417 /**
6418  * pci_real_dma_dev - Get PCI DMA device for PCI device
6419  * @dev: the PCI device that may have a PCI DMA alias
6420  *
6421  * Permits the platform to provide architecture-specific functionality to
6422  * devices needing to alias DMA to another PCI device on another PCI bus. If
6423  * the PCI device is on the same bus, it is recommended to use
6424  * pci_add_dma_alias(). This is the default implementation. Architecture
6425  * implementations can override this.
6426  */
6427 struct pci_dev __weak *pci_real_dma_dev(struct pci_dev *dev)
6428 {
6429 	return dev;
6430 }
6431 
6432 resource_size_t __weak pcibios_default_alignment(void)
6433 {
6434 	return 0;
6435 }
6436 
6437 /*
6438  * Arches that don't want to expose struct resource to userland as-is in
6439  * sysfs and /proc can implement their own pci_resource_to_user().
6440  */
6441 void __weak pci_resource_to_user(const struct pci_dev *dev, int bar,
6442 				 const struct resource *rsrc,
6443 				 resource_size_t *start, resource_size_t *end)
6444 {
6445 	*start = rsrc->start;
6446 	*end = rsrc->end;
6447 }
6448 
6449 static char *resource_alignment_param;
6450 static DEFINE_SPINLOCK(resource_alignment_lock);
6451 
6452 /**
6453  * pci_specified_resource_alignment - get resource alignment specified by user.
6454  * @dev: the PCI device to get
6455  * @resize: whether or not to change resources' size when reassigning alignment
6456  *
6457  * RETURNS: Resource alignment if it is specified.
6458  *          Zero if it is not specified.
6459  */
6460 static resource_size_t pci_specified_resource_alignment(struct pci_dev *dev,
6461 							bool *resize)
6462 {
6463 	int align_order, count;
6464 	resource_size_t align = pcibios_default_alignment();
6465 	const char *p;
6466 	int ret;
6467 
6468 	spin_lock(&resource_alignment_lock);
6469 	p = resource_alignment_param;
6470 	if (!p || !*p)
6471 		goto out;
6472 	if (pci_has_flag(PCI_PROBE_ONLY)) {
6473 		align = 0;
6474 		pr_info_once("PCI: Ignoring requested alignments (PCI_PROBE_ONLY)\n");
6475 		goto out;
6476 	}
6477 
6478 	while (*p) {
6479 		count = 0;
6480 		if (sscanf(p, "%d%n", &align_order, &count) == 1 &&
6481 		    p[count] == '@') {
6482 			p += count + 1;
6483 			if (align_order > 63) {
6484 				pr_err("PCI: Invalid requested alignment (order %d)\n",
6485 				       align_order);
6486 				align_order = PAGE_SHIFT;
6487 			}
6488 		} else {
6489 			align_order = PAGE_SHIFT;
6490 		}
6491 
6492 		ret = pci_dev_str_match(dev, p, &p);
6493 		if (ret == 1) {
6494 			*resize = true;
6495 			align = 1ULL << align_order;
6496 			break;
6497 		} else if (ret < 0) {
6498 			pr_err("PCI: Can't parse resource_alignment parameter: %s\n",
6499 			       p);
6500 			break;
6501 		}
6502 
6503 		if (*p != ';' && *p != ',') {
6504 			/* End of param or invalid format */
6505 			break;
6506 		}
6507 		p++;
6508 	}
6509 out:
6510 	spin_unlock(&resource_alignment_lock);
6511 	return align;
6512 }
6513 
6514 static void pci_request_resource_alignment(struct pci_dev *dev, int bar,
6515 					   resource_size_t align, bool resize)
6516 {
6517 	struct resource *r = &dev->resource[bar];
6518 	const char *r_name = pci_resource_name(dev, bar);
6519 	resource_size_t size;
6520 
6521 	if (!(r->flags & IORESOURCE_MEM))
6522 		return;
6523 
6524 	if (r->flags & IORESOURCE_PCI_FIXED) {
6525 		pci_info(dev, "%s %pR: ignoring requested alignment %#llx\n",
6526 			 r_name, r, (unsigned long long)align);
6527 		return;
6528 	}
6529 
6530 	size = resource_size(r);
6531 	if (size >= align)
6532 		return;
6533 
6534 	/*
6535 	 * Increase the alignment of the resource.  There are two ways we
6536 	 * can do this:
6537 	 *
6538 	 * 1) Increase the size of the resource.  BARs are aligned on their
6539 	 *    size, so when we reallocate space for this resource, we'll
6540 	 *    allocate it with the larger alignment.  This also prevents
6541 	 *    assignment of any other BARs inside the alignment region, so
6542 	 *    if we're requesting page alignment, this means no other BARs
6543 	 *    will share the page.
6544 	 *
6545 	 *    The disadvantage is that this makes the resource larger than
6546 	 *    the hardware BAR, which may break drivers that compute things
6547 	 *    based on the resource size, e.g., to find registers at a
6548 	 *    fixed offset before the end of the BAR.
6549 	 *
6550 	 * 2) Retain the resource size, but use IORESOURCE_STARTALIGN and
6551 	 *    set r->start to the desired alignment.  By itself this
6552 	 *    doesn't prevent other BARs being put inside the alignment
6553 	 *    region, but if we realign *every* resource of every device in
6554 	 *    the system, none of them will share an alignment region.
6555 	 *
6556 	 * When the user has requested alignment for only some devices via
6557 	 * the "pci=resource_alignment" argument, "resize" is true and we
6558 	 * use the first method.  Otherwise we assume we're aligning all
6559 	 * devices and we use the second.
6560 	 */
6561 
6562 	pci_info(dev, "%s %pR: requesting alignment to %#llx\n",
6563 		 r_name, r, (unsigned long long)align);
6564 
6565 	if (resize) {
6566 		r->start = 0;
6567 		r->end = align - 1;
6568 	} else {
6569 		r->flags &= ~IORESOURCE_SIZEALIGN;
6570 		r->flags |= IORESOURCE_STARTALIGN;
6571 		resource_set_range(r, align, size);
6572 	}
6573 	r->flags |= IORESOURCE_UNSET;
6574 }
6575 
6576 /*
6577  * This function disables memory decoding and releases memory resources
6578  * of the device specified by kernel's boot parameter 'pci=resource_alignment='.
6579  * It also rounds up size to specified alignment.
6580  * Later on, the kernel will assign page-aligned memory resource back
6581  * to the device.
6582  */
6583 void pci_reassigndev_resource_alignment(struct pci_dev *dev)
6584 {
6585 	int i;
6586 	struct resource *r;
6587 	resource_size_t align;
6588 	u16 command;
6589 	bool resize = false;
6590 
6591 	/*
6592 	 * VF BARs are read-only zero according to SR-IOV spec r1.1, sec
6593 	 * 3.4.1.11.  Their resources are allocated from the space
6594 	 * described by the VF BARx register in the PF's SR-IOV capability.
6595 	 * We can't influence their alignment here.
6596 	 */
6597 	if (dev->is_virtfn)
6598 		return;
6599 
6600 	/* check if specified PCI is target device to reassign */
6601 	align = pci_specified_resource_alignment(dev, &resize);
6602 	if (!align)
6603 		return;
6604 
6605 	if (dev->hdr_type == PCI_HEADER_TYPE_NORMAL &&
6606 	    (dev->class >> 8) == PCI_CLASS_BRIDGE_HOST) {
6607 		pci_warn(dev, "Can't reassign resources to host bridge\n");
6608 		return;
6609 	}
6610 
6611 	pci_read_config_word(dev, PCI_COMMAND, &command);
6612 	command &= ~PCI_COMMAND_MEMORY;
6613 	pci_write_config_word(dev, PCI_COMMAND, command);
6614 
6615 	for (i = 0; i <= PCI_ROM_RESOURCE; i++)
6616 		pci_request_resource_alignment(dev, i, align, resize);
6617 
6618 	/*
6619 	 * Need to disable bridge's resource window,
6620 	 * to enable the kernel to reassign new resource
6621 	 * window later on.
6622 	 */
6623 	if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
6624 		for (i = PCI_BRIDGE_RESOURCES; i < PCI_NUM_RESOURCES; i++) {
6625 			r = &dev->resource[i];
6626 			if (!(r->flags & IORESOURCE_MEM))
6627 				continue;
6628 			r->flags |= IORESOURCE_UNSET;
6629 			r->end = resource_size(r) - 1;
6630 			r->start = 0;
6631 		}
6632 		pci_disable_bridge_window(dev);
6633 	}
6634 }
6635 
6636 static ssize_t resource_alignment_show(const struct bus_type *bus, char *buf)
6637 {
6638 	size_t count = 0;
6639 
6640 	spin_lock(&resource_alignment_lock);
6641 	if (resource_alignment_param)
6642 		count = sysfs_emit(buf, "%s\n", resource_alignment_param);
6643 	spin_unlock(&resource_alignment_lock);
6644 
6645 	return count;
6646 }
6647 
6648 static ssize_t resource_alignment_store(const struct bus_type *bus,
6649 					const char *buf, size_t count)
6650 {
6651 	char *param, *old, *end;
6652 
6653 	if (count >= (PAGE_SIZE - 1))
6654 		return -EINVAL;
6655 
6656 	param = kstrndup(buf, count, GFP_KERNEL);
6657 	if (!param)
6658 		return -ENOMEM;
6659 
6660 	end = strchr(param, '\n');
6661 	if (end)
6662 		*end = '\0';
6663 
6664 	spin_lock(&resource_alignment_lock);
6665 	old = resource_alignment_param;
6666 	if (strlen(param)) {
6667 		resource_alignment_param = param;
6668 	} else {
6669 		kfree(param);
6670 		resource_alignment_param = NULL;
6671 	}
6672 	spin_unlock(&resource_alignment_lock);
6673 
6674 	kfree(old);
6675 
6676 	return count;
6677 }
6678 
6679 static BUS_ATTR_RW(resource_alignment);
6680 
6681 static int __init pci_resource_alignment_sysfs_init(void)
6682 {
6683 	return bus_create_file(&pci_bus_type,
6684 					&bus_attr_resource_alignment);
6685 }
6686 late_initcall(pci_resource_alignment_sysfs_init);
6687 
6688 static void pci_no_domains(void)
6689 {
6690 #ifdef CONFIG_PCI_DOMAINS
6691 	pci_domains_supported = 0;
6692 #endif
6693 }
6694 
6695 #ifdef CONFIG_PCI_DOMAINS
6696 static DEFINE_IDA(pci_domain_nr_dynamic_ida);
6697 
6698 /**
6699  * pci_bus_find_emul_domain_nr() - allocate a PCI domain number per constraints
6700  * @hint: desired domain, 0 if any ID in the range of @min to @max is acceptable
6701  * @min: minimum allowable domain
6702  * @max: maximum allowable domain, no IDs higher than INT_MAX will be returned
6703  */
6704 int pci_bus_find_emul_domain_nr(u32 hint, u32 min, u32 max)
6705 {
6706 	return ida_alloc_range(&pci_domain_nr_dynamic_ida, max(hint, min), max,
6707 			       GFP_KERNEL);
6708 }
6709 EXPORT_SYMBOL_GPL(pci_bus_find_emul_domain_nr);
6710 
6711 void pci_bus_release_emul_domain_nr(int domain_nr)
6712 {
6713 	ida_free(&pci_domain_nr_dynamic_ida, domain_nr);
6714 }
6715 EXPORT_SYMBOL_GPL(pci_bus_release_emul_domain_nr);
6716 #endif
6717 
6718 #ifdef CONFIG_PCI_DOMAINS_GENERIC
6719 static DEFINE_IDA(pci_domain_nr_static_ida);
6720 
6721 static void of_pci_reserve_static_domain_nr(void)
6722 {
6723 	struct device_node *np;
6724 	int domain_nr;
6725 
6726 	for_each_node_by_type(np, "pci") {
6727 		domain_nr = of_get_pci_domain_nr(np);
6728 		if (domain_nr < 0)
6729 			continue;
6730 		/*
6731 		 * Permanently allocate domain_nr in dynamic_ida
6732 		 * to prevent it from dynamic allocation.
6733 		 */
6734 		ida_alloc_range(&pci_domain_nr_dynamic_ida,
6735 				domain_nr, domain_nr, GFP_KERNEL);
6736 	}
6737 }
6738 
6739 static int of_pci_bus_find_domain_nr(struct device *parent)
6740 {
6741 	static bool static_domains_reserved = false;
6742 	int domain_nr;
6743 
6744 	/* On the first call scan device tree for static allocations. */
6745 	if (!static_domains_reserved) {
6746 		of_pci_reserve_static_domain_nr();
6747 		static_domains_reserved = true;
6748 	}
6749 
6750 	if (parent) {
6751 		/*
6752 		 * If domain is in DT, allocate it in static IDA.  This
6753 		 * prevents duplicate static allocations in case of errors
6754 		 * in DT.
6755 		 */
6756 		domain_nr = of_get_pci_domain_nr(parent->of_node);
6757 		if (domain_nr >= 0)
6758 			return ida_alloc_range(&pci_domain_nr_static_ida,
6759 					       domain_nr, domain_nr,
6760 					       GFP_KERNEL);
6761 	}
6762 
6763 	/*
6764 	 * If domain was not specified in DT, choose a free ID from dynamic
6765 	 * allocations. All domain numbers from DT are permanently in
6766 	 * dynamic allocations to prevent assigning them to other DT nodes
6767 	 * without static domain.
6768 	 */
6769 	return ida_alloc(&pci_domain_nr_dynamic_ida, GFP_KERNEL);
6770 }
6771 
6772 static void of_pci_bus_release_domain_nr(struct device *parent, int domain_nr)
6773 {
6774 	if (domain_nr < 0)
6775 		return;
6776 
6777 	/* Release domain from IDA where it was allocated. */
6778 	if (parent && of_get_pci_domain_nr(parent->of_node) == domain_nr)
6779 		ida_free(&pci_domain_nr_static_ida, domain_nr);
6780 	else
6781 		ida_free(&pci_domain_nr_dynamic_ida, domain_nr);
6782 }
6783 
6784 int pci_bus_find_domain_nr(struct pci_bus *bus, struct device *parent)
6785 {
6786 	return acpi_disabled ? of_pci_bus_find_domain_nr(parent) :
6787 			       acpi_pci_bus_find_domain_nr(bus);
6788 }
6789 
6790 void pci_bus_release_domain_nr(struct device *parent, int domain_nr)
6791 {
6792 	if (!acpi_disabled)
6793 		return;
6794 	of_pci_bus_release_domain_nr(parent, domain_nr);
6795 }
6796 #endif
6797 
6798 /**
6799  * pci_ext_cfg_avail - can we access extended PCI config space?
6800  *
6801  * Returns 1 if we can access PCI extended config space (offsets
6802  * greater than 0xff). This is the default implementation. Architecture
6803  * implementations can override this.
6804  */
6805 int __weak pci_ext_cfg_avail(void)
6806 {
6807 	return 1;
6808 }
6809 
6810 static int __init pci_setup(char *str)
6811 {
6812 	while (str) {
6813 		char *k = strchr(str, ',');
6814 		if (k)
6815 			*k++ = 0;
6816 		if (*str && (str = pcibios_setup(str)) && *str) {
6817 			if (!pci_setup_cardbus(str)) {
6818 				/* Function handled the parameters */
6819 			} else if (!strcmp(str, "nomsi")) {
6820 				pci_no_msi();
6821 			} else if (!strncmp(str, "noats", 5)) {
6822 				pr_info("PCIe: ATS is disabled\n");
6823 				pcie_ats_disabled = true;
6824 			} else if (!strcmp(str, "noaer")) {
6825 				pci_no_aer();
6826 			} else if (!strcmp(str, "earlydump")) {
6827 				pci_early_dump = true;
6828 			} else if (!strncmp(str, "realloc=", 8)) {
6829 				pci_realloc_get_opt(str + 8);
6830 			} else if (!strncmp(str, "realloc", 7)) {
6831 				pci_realloc_get_opt("on");
6832 			} else if (!strcmp(str, "nodomains")) {
6833 				pci_no_domains();
6834 			} else if (!strncmp(str, "noari", 5)) {
6835 				pcie_ari_disabled = true;
6836 			} else if (!strncmp(str, "notph", 5)) {
6837 				pci_no_tph();
6838 			} else if (!strncmp(str, "resource_alignment=", 19)) {
6839 				resource_alignment_param = str + 19;
6840 			} else if (!strncmp(str, "ecrc=", 5)) {
6841 				pcie_ecrc_get_policy(str + 5);
6842 			} else if (!strncmp(str, "hpiosize=", 9)) {
6843 				pci_hotplug_io_size = memparse(str + 9, &str);
6844 			} else if (!strncmp(str, "hpmmiosize=", 11)) {
6845 				pci_hotplug_mmio_size = memparse(str + 11, &str);
6846 			} else if (!strncmp(str, "hpmmioprefsize=", 15)) {
6847 				pci_hotplug_mmio_pref_size = memparse(str + 15, &str);
6848 			} else if (!strncmp(str, "hpmemsize=", 10)) {
6849 				pci_hotplug_mmio_size = memparse(str + 10, &str);
6850 				pci_hotplug_mmio_pref_size = pci_hotplug_mmio_size;
6851 			} else if (!strncmp(str, "hpbussize=", 10)) {
6852 				pci_hotplug_bus_size =
6853 					simple_strtoul(str + 10, &str, 0);
6854 				if (pci_hotplug_bus_size > 0xff)
6855 					pci_hotplug_bus_size = DEFAULT_HOTPLUG_BUS_SIZE;
6856 			} else if (!strncmp(str, "pcie_bus_tune_off", 17)) {
6857 				pcie_bus_config = PCIE_BUS_TUNE_OFF;
6858 			} else if (!strncmp(str, "pcie_bus_safe", 13)) {
6859 				pcie_bus_config = PCIE_BUS_SAFE;
6860 			} else if (!strncmp(str, "pcie_bus_perf", 13)) {
6861 				pcie_bus_config = PCIE_BUS_PERFORMANCE;
6862 			} else if (!strncmp(str, "pcie_bus_peer2peer", 18)) {
6863 				pcie_bus_config = PCIE_BUS_PEER2PEER;
6864 			} else if (!strncmp(str, "pcie_scan_all", 13)) {
6865 				pci_add_flags(PCI_SCAN_ALL_PCIE_DEVS);
6866 			} else if (!strncmp(str, "disable_acs_redir=", 18)) {
6867 				disable_acs_redir_param = str + 18;
6868 			} else if (!strncmp(str, "config_acs=", 11)) {
6869 				config_acs_param = str + 11;
6870 			} else {
6871 				pr_err("PCI: Unknown option `%s'\n", str);
6872 			}
6873 		}
6874 		str = k;
6875 	}
6876 	return 0;
6877 }
6878 early_param("pci", pci_setup);
6879 
6880 /*
6881  * 'resource_alignment_param' and 'disable_acs_redir_param' are initialized
6882  * in pci_setup(), above, to point to data in the __initdata section which
6883  * will be freed after the init sequence is complete. We can't allocate memory
6884  * in pci_setup() because some architectures do not have any memory allocation
6885  * service available during an early_param() call. So we allocate memory and
6886  * copy the variable here before the init section is freed.
6887  *
6888  */
6889 static int __init pci_realloc_setup_params(void)
6890 {
6891 	resource_alignment_param = kstrdup(resource_alignment_param,
6892 					   GFP_KERNEL);
6893 	disable_acs_redir_param = kstrdup(disable_acs_redir_param, GFP_KERNEL);
6894 	config_acs_param = kstrdup(config_acs_param, GFP_KERNEL);
6895 
6896 	return 0;
6897 }
6898 pure_initcall(pci_realloc_setup_params);
6899