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