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