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