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