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