OSDN Git Service

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