PCI: save and restore PCIe 2.0 registers
[safe/jmp/linux-2.6] / 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/kernel.h>
11 #include <linux/delay.h>
12 #include <linux/init.h>
13 #include <linux/pci.h>
14 #include <linux/pm.h>
15 #include <linux/module.h>
16 #include <linux/spinlock.h>
17 #include <linux/string.h>
18 #include <linux/log2.h>
19 #include <linux/pci-aspm.h>
20 #include <linux/pm_wakeup.h>
21 #include <linux/interrupt.h>
22 #include <asm/dma.h>    /* isa_dma_bridge_buggy */
23 #include <linux/device.h>
24 #include <asm/setup.h>
25 #include "pci.h"
26
27 unsigned int pci_pm_d3_delay = PCI_PM_D3_WAIT;
28
29 #ifdef CONFIG_PCI_DOMAINS
30 int pci_domains_supported = 1;
31 #endif
32
33 #define DEFAULT_CARDBUS_IO_SIZE         (256)
34 #define DEFAULT_CARDBUS_MEM_SIZE        (64*1024*1024)
35 /* pci=cbmemsize=nnM,cbiosize=nn can override this */
36 unsigned long pci_cardbus_io_size = DEFAULT_CARDBUS_IO_SIZE;
37 unsigned long pci_cardbus_mem_size = DEFAULT_CARDBUS_MEM_SIZE;
38
39 /**
40  * pci_bus_max_busnr - returns maximum PCI bus number of given bus' children
41  * @bus: pointer to PCI bus structure to search
42  *
43  * Given a PCI bus, returns the highest PCI bus number present in the set
44  * including the given PCI bus and its list of child PCI buses.
45  */
46 unsigned char pci_bus_max_busnr(struct pci_bus* bus)
47 {
48         struct list_head *tmp;
49         unsigned char max, n;
50
51         max = bus->subordinate;
52         list_for_each(tmp, &bus->children) {
53                 n = pci_bus_max_busnr(pci_bus_b(tmp));
54                 if(n > max)
55                         max = n;
56         }
57         return max;
58 }
59 EXPORT_SYMBOL_GPL(pci_bus_max_busnr);
60
61 #ifdef CONFIG_HAS_IOMEM
62 void __iomem *pci_ioremap_bar(struct pci_dev *pdev, int bar)
63 {
64         /*
65          * Make sure the BAR is actually a memory resource, not an IO resource
66          */
67         if (!(pci_resource_flags(pdev, bar) & IORESOURCE_MEM)) {
68                 WARN_ON(1);
69                 return NULL;
70         }
71         return ioremap_nocache(pci_resource_start(pdev, bar),
72                                      pci_resource_len(pdev, bar));
73 }
74 EXPORT_SYMBOL_GPL(pci_ioremap_bar);
75 #endif
76
77 #if 0
78 /**
79  * pci_max_busnr - returns maximum PCI bus number
80  *
81  * Returns the highest PCI bus number present in the system global list of
82  * PCI buses.
83  */
84 unsigned char __devinit
85 pci_max_busnr(void)
86 {
87         struct pci_bus *bus = NULL;
88         unsigned char max, n;
89
90         max = 0;
91         while ((bus = pci_find_next_bus(bus)) != NULL) {
92                 n = pci_bus_max_busnr(bus);
93                 if(n > max)
94                         max = n;
95         }
96         return max;
97 }
98
99 #endif  /*  0  */
100
101 #define PCI_FIND_CAP_TTL        48
102
103 static int __pci_find_next_cap_ttl(struct pci_bus *bus, unsigned int devfn,
104                                    u8 pos, int cap, int *ttl)
105 {
106         u8 id;
107
108         while ((*ttl)--) {
109                 pci_bus_read_config_byte(bus, devfn, pos, &pos);
110                 if (pos < 0x40)
111                         break;
112                 pos &= ~3;
113                 pci_bus_read_config_byte(bus, devfn, pos + PCI_CAP_LIST_ID,
114                                          &id);
115                 if (id == 0xff)
116                         break;
117                 if (id == cap)
118                         return pos;
119                 pos += PCI_CAP_LIST_NEXT;
120         }
121         return 0;
122 }
123
124 static int __pci_find_next_cap(struct pci_bus *bus, unsigned int devfn,
125                                u8 pos, int cap)
126 {
127         int ttl = PCI_FIND_CAP_TTL;
128
129         return __pci_find_next_cap_ttl(bus, devfn, pos, cap, &ttl);
130 }
131
132 int pci_find_next_capability(struct pci_dev *dev, u8 pos, int cap)
133 {
134         return __pci_find_next_cap(dev->bus, dev->devfn,
135                                    pos + PCI_CAP_LIST_NEXT, cap);
136 }
137 EXPORT_SYMBOL_GPL(pci_find_next_capability);
138
139 static int __pci_bus_find_cap_start(struct pci_bus *bus,
140                                     unsigned int devfn, u8 hdr_type)
141 {
142         u16 status;
143
144         pci_bus_read_config_word(bus, devfn, PCI_STATUS, &status);
145         if (!(status & PCI_STATUS_CAP_LIST))
146                 return 0;
147
148         switch (hdr_type) {
149         case PCI_HEADER_TYPE_NORMAL:
150         case PCI_HEADER_TYPE_BRIDGE:
151                 return PCI_CAPABILITY_LIST;
152         case PCI_HEADER_TYPE_CARDBUS:
153                 return PCI_CB_CAPABILITY_LIST;
154         default:
155                 return 0;
156         }
157
158         return 0;
159 }
160
161 /**
162  * pci_find_capability - query for devices' capabilities 
163  * @dev: PCI device to query
164  * @cap: capability code
165  *
166  * Tell if a device supports a given PCI capability.
167  * Returns the address of the requested capability structure within the
168  * device's PCI configuration space or 0 in case the device does not
169  * support it.  Possible values for @cap:
170  *
171  *  %PCI_CAP_ID_PM           Power Management 
172  *  %PCI_CAP_ID_AGP          Accelerated Graphics Port 
173  *  %PCI_CAP_ID_VPD          Vital Product Data 
174  *  %PCI_CAP_ID_SLOTID       Slot Identification 
175  *  %PCI_CAP_ID_MSI          Message Signalled Interrupts
176  *  %PCI_CAP_ID_CHSWP        CompactPCI HotSwap 
177  *  %PCI_CAP_ID_PCIX         PCI-X
178  *  %PCI_CAP_ID_EXP          PCI Express
179  */
180 int pci_find_capability(struct pci_dev *dev, int cap)
181 {
182         int pos;
183
184         pos = __pci_bus_find_cap_start(dev->bus, dev->devfn, dev->hdr_type);
185         if (pos)
186                 pos = __pci_find_next_cap(dev->bus, dev->devfn, pos, cap);
187
188         return pos;
189 }
190
191 /**
192  * pci_bus_find_capability - query for devices' capabilities 
193  * @bus:   the PCI bus to query
194  * @devfn: PCI device to query
195  * @cap:   capability code
196  *
197  * Like pci_find_capability() but works for pci devices that do not have a
198  * pci_dev structure set up yet. 
199  *
200  * Returns the address of the requested capability structure within the
201  * device's PCI configuration space or 0 in case the device does not
202  * support it.
203  */
204 int pci_bus_find_capability(struct pci_bus *bus, unsigned int devfn, int cap)
205 {
206         int pos;
207         u8 hdr_type;
208
209         pci_bus_read_config_byte(bus, devfn, PCI_HEADER_TYPE, &hdr_type);
210
211         pos = __pci_bus_find_cap_start(bus, devfn, hdr_type & 0x7f);
212         if (pos)
213                 pos = __pci_find_next_cap(bus, devfn, pos, cap);
214
215         return pos;
216 }
217
218 /**
219  * pci_find_ext_capability - Find an extended capability
220  * @dev: PCI device to query
221  * @cap: capability code
222  *
223  * Returns the address of the requested extended capability structure
224  * within the device's PCI configuration space or 0 if the device does
225  * not support it.  Possible values for @cap:
226  *
227  *  %PCI_EXT_CAP_ID_ERR         Advanced Error Reporting
228  *  %PCI_EXT_CAP_ID_VC          Virtual Channel
229  *  %PCI_EXT_CAP_ID_DSN         Device Serial Number
230  *  %PCI_EXT_CAP_ID_PWR         Power Budgeting
231  */
232 int pci_find_ext_capability(struct pci_dev *dev, int cap)
233 {
234         u32 header;
235         int ttl;
236         int pos = PCI_CFG_SPACE_SIZE;
237
238         /* minimum 8 bytes per capability */
239         ttl = (PCI_CFG_SPACE_EXP_SIZE - PCI_CFG_SPACE_SIZE) / 8;
240
241         if (dev->cfg_size <= PCI_CFG_SPACE_SIZE)
242                 return 0;
243
244         if (pci_read_config_dword(dev, pos, &header) != PCIBIOS_SUCCESSFUL)
245                 return 0;
246
247         /*
248          * If we have no capabilities, this is indicated by cap ID,
249          * cap version and next pointer all being 0.
250          */
251         if (header == 0)
252                 return 0;
253
254         while (ttl-- > 0) {
255                 if (PCI_EXT_CAP_ID(header) == cap)
256                         return pos;
257
258                 pos = PCI_EXT_CAP_NEXT(header);
259                 if (pos < PCI_CFG_SPACE_SIZE)
260                         break;
261
262                 if (pci_read_config_dword(dev, pos, &header) != PCIBIOS_SUCCESSFUL)
263                         break;
264         }
265
266         return 0;
267 }
268 EXPORT_SYMBOL_GPL(pci_find_ext_capability);
269
270 static int __pci_find_next_ht_cap(struct pci_dev *dev, int pos, int ht_cap)
271 {
272         int rc, ttl = PCI_FIND_CAP_TTL;
273         u8 cap, mask;
274
275         if (ht_cap == HT_CAPTYPE_SLAVE || ht_cap == HT_CAPTYPE_HOST)
276                 mask = HT_3BIT_CAP_MASK;
277         else
278                 mask = HT_5BIT_CAP_MASK;
279
280         pos = __pci_find_next_cap_ttl(dev->bus, dev->devfn, pos,
281                                       PCI_CAP_ID_HT, &ttl);
282         while (pos) {
283                 rc = pci_read_config_byte(dev, pos + 3, &cap);
284                 if (rc != PCIBIOS_SUCCESSFUL)
285                         return 0;
286
287                 if ((cap & mask) == ht_cap)
288                         return pos;
289
290                 pos = __pci_find_next_cap_ttl(dev->bus, dev->devfn,
291                                               pos + PCI_CAP_LIST_NEXT,
292                                               PCI_CAP_ID_HT, &ttl);
293         }
294
295         return 0;
296 }
297 /**
298  * pci_find_next_ht_capability - query a device's Hypertransport capabilities
299  * @dev: PCI device to query
300  * @pos: Position from which to continue searching
301  * @ht_cap: Hypertransport capability code
302  *
303  * To be used in conjunction with pci_find_ht_capability() to search for
304  * all capabilities matching @ht_cap. @pos should always be a value returned
305  * from pci_find_ht_capability().
306  *
307  * NB. To be 100% safe against broken PCI devices, the caller should take
308  * steps to avoid an infinite loop.
309  */
310 int pci_find_next_ht_capability(struct pci_dev *dev, int pos, int ht_cap)
311 {
312         return __pci_find_next_ht_cap(dev, pos + PCI_CAP_LIST_NEXT, ht_cap);
313 }
314 EXPORT_SYMBOL_GPL(pci_find_next_ht_capability);
315
316 /**
317  * pci_find_ht_capability - query a device's Hypertransport capabilities
318  * @dev: PCI device to query
319  * @ht_cap: Hypertransport capability code
320  *
321  * Tell if a device supports a given Hypertransport capability.
322  * Returns an address within the device's PCI configuration space
323  * or 0 in case the device does not support the request capability.
324  * The address points to the PCI capability, of type PCI_CAP_ID_HT,
325  * which has a Hypertransport capability matching @ht_cap.
326  */
327 int pci_find_ht_capability(struct pci_dev *dev, int ht_cap)
328 {
329         int pos;
330
331         pos = __pci_bus_find_cap_start(dev->bus, dev->devfn, dev->hdr_type);
332         if (pos)
333                 pos = __pci_find_next_ht_cap(dev, pos, ht_cap);
334
335         return pos;
336 }
337 EXPORT_SYMBOL_GPL(pci_find_ht_capability);
338
339 /**
340  * pci_find_parent_resource - return resource region of parent bus of given region
341  * @dev: PCI device structure contains resources to be searched
342  * @res: child resource record for which parent is sought
343  *
344  *  For given resource region of given device, return the resource
345  *  region of parent bus the given region is contained in or where
346  *  it should be allocated from.
347  */
348 struct resource *
349 pci_find_parent_resource(const struct pci_dev *dev, struct resource *res)
350 {
351         const struct pci_bus *bus = dev->bus;
352         int i;
353         struct resource *best = NULL;
354
355         for(i = 0; i < PCI_BUS_NUM_RESOURCES; i++) {
356                 struct resource *r = bus->resource[i];
357                 if (!r)
358                         continue;
359                 if (res->start && !(res->start >= r->start && res->end <= r->end))
360                         continue;       /* Not contained */
361                 if ((res->flags ^ r->flags) & (IORESOURCE_IO | IORESOURCE_MEM))
362                         continue;       /* Wrong type */
363                 if (!((res->flags ^ r->flags) & IORESOURCE_PREFETCH))
364                         return r;       /* Exact match */
365                 if ((res->flags & IORESOURCE_PREFETCH) && !(r->flags & IORESOURCE_PREFETCH))
366                         best = r;       /* Approximating prefetchable by non-prefetchable */
367         }
368         return best;
369 }
370
371 /**
372  * pci_restore_bars - restore a devices BAR values (e.g. after wake-up)
373  * @dev: PCI device to have its BARs restored
374  *
375  * Restore the BAR values for a given device, so as to make it
376  * accessible by its driver.
377  */
378 static void
379 pci_restore_bars(struct pci_dev *dev)
380 {
381         int i;
382
383         for (i = 0; i < PCI_BRIDGE_RESOURCES; i++)
384                 pci_update_resource(dev, i);
385 }
386
387 static struct pci_platform_pm_ops *pci_platform_pm;
388
389 int pci_set_platform_pm(struct pci_platform_pm_ops *ops)
390 {
391         if (!ops->is_manageable || !ops->set_state || !ops->choose_state
392             || !ops->sleep_wake || !ops->can_wakeup)
393                 return -EINVAL;
394         pci_platform_pm = ops;
395         return 0;
396 }
397
398 static inline bool platform_pci_power_manageable(struct pci_dev *dev)
399 {
400         return pci_platform_pm ? pci_platform_pm->is_manageable(dev) : false;
401 }
402
403 static inline int platform_pci_set_power_state(struct pci_dev *dev,
404                                                 pci_power_t t)
405 {
406         return pci_platform_pm ? pci_platform_pm->set_state(dev, t) : -ENOSYS;
407 }
408
409 static inline pci_power_t platform_pci_choose_state(struct pci_dev *dev)
410 {
411         return pci_platform_pm ?
412                         pci_platform_pm->choose_state(dev) : PCI_POWER_ERROR;
413 }
414
415 static inline bool platform_pci_can_wakeup(struct pci_dev *dev)
416 {
417         return pci_platform_pm ? pci_platform_pm->can_wakeup(dev) : false;
418 }
419
420 static inline int platform_pci_sleep_wake(struct pci_dev *dev, bool enable)
421 {
422         return pci_platform_pm ?
423                         pci_platform_pm->sleep_wake(dev, enable) : -ENODEV;
424 }
425
426 /**
427  * pci_raw_set_power_state - Use PCI PM registers to set the power state of
428  *                           given PCI device
429  * @dev: PCI device to handle.
430  * @state: PCI power state (D0, D1, D2, D3hot) to put the device into.
431  * @wait: If 'true', wait for the device to change its power state
432  *
433  * RETURN VALUE:
434  * -EINVAL if the requested state is invalid.
435  * -EIO if device does not support PCI PM or its PM capabilities register has a
436  * wrong version, or device doesn't support the requested state.
437  * 0 if device already is in the requested state.
438  * 0 if device's power state has been successfully changed.
439  */
440 static int
441 pci_raw_set_power_state(struct pci_dev *dev, pci_power_t state, bool wait)
442 {
443         u16 pmcsr;
444         bool need_restore = false;
445
446         if (!dev->pm_cap)
447                 return -EIO;
448
449         if (state < PCI_D0 || state > PCI_D3hot)
450                 return -EINVAL;
451
452         /* Validate current state:
453          * Can enter D0 from any state, but if we can only go deeper 
454          * to sleep if we're already in a low power state
455          */
456         if (dev->current_state == state) {
457                 /* we're already there */
458                 return 0;
459         } else if (state != PCI_D0 && dev->current_state <= PCI_D3cold
460             && dev->current_state > state) {
461                 dev_err(&dev->dev, "invalid power transition "
462                         "(from state %d to %d)\n", dev->current_state, state);
463                 return -EINVAL;
464         }
465
466         /* check if this device supports the desired state */
467         if ((state == PCI_D1 && !dev->d1_support)
468            || (state == PCI_D2 && !dev->d2_support))
469                 return -EIO;
470
471         pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
472
473         /* If we're (effectively) in D3, force entire word to 0.
474          * This doesn't affect PME_Status, disables PME_En, and
475          * sets PowerState to 0.
476          */
477         switch (dev->current_state) {
478         case PCI_D0:
479         case PCI_D1:
480         case PCI_D2:
481                 pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
482                 pmcsr |= state;
483                 break;
484         case PCI_UNKNOWN: /* Boot-up */
485                 if ((pmcsr & PCI_PM_CTRL_STATE_MASK) == PCI_D3hot
486                  && !(pmcsr & PCI_PM_CTRL_NO_SOFT_RESET)) {
487                         need_restore = true;
488                         wait = true;
489                 }
490                 /* Fall-through: force to D0 */
491         default:
492                 pmcsr = 0;
493                 break;
494         }
495
496         /* enter specified state */
497         pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, pmcsr);
498
499         if (!wait)
500                 return 0;
501
502         /* Mandatory power management transition delays */
503         /* see PCI PM 1.1 5.6.1 table 18 */
504         if (state == PCI_D3hot || dev->current_state == PCI_D3hot)
505                 msleep(pci_pm_d3_delay);
506         else if (state == PCI_D2 || dev->current_state == PCI_D2)
507                 udelay(PCI_PM_D2_DELAY);
508
509         dev->current_state = state;
510
511         /* According to section 5.4.1 of the "PCI BUS POWER MANAGEMENT
512          * INTERFACE SPECIFICATION, REV. 1.2", a device transitioning
513          * from D3hot to D0 _may_ perform an internal reset, thereby
514          * going to "D0 Uninitialized" rather than "D0 Initialized".
515          * For example, at least some versions of the 3c905B and the
516          * 3c556B exhibit this behaviour.
517          *
518          * At least some laptop BIOSen (e.g. the Thinkpad T21) leave
519          * devices in a D3hot state at boot.  Consequently, we need to
520          * restore at least the BARs so that the device will be
521          * accessible to its driver.
522          */
523         if (need_restore)
524                 pci_restore_bars(dev);
525
526         if (wait && dev->bus->self)
527                 pcie_aspm_pm_state_change(dev->bus->self);
528
529         return 0;
530 }
531
532 /**
533  * pci_update_current_state - Read PCI power state of given device from its
534  *                            PCI PM registers and cache it
535  * @dev: PCI device to handle.
536  * @state: State to cache in case the device doesn't have the PM capability
537  */
538 void pci_update_current_state(struct pci_dev *dev, pci_power_t state)
539 {
540         if (dev->pm_cap) {
541                 u16 pmcsr;
542
543                 pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
544                 dev->current_state = (pmcsr & PCI_PM_CTRL_STATE_MASK);
545         } else {
546                 dev->current_state = state;
547         }
548 }
549
550 /**
551  * pci_set_power_state - Set the power state of a PCI device
552  * @dev: PCI device to handle.
553  * @state: PCI power state (D0, D1, D2, D3hot) to put the device into.
554  *
555  * Transition a device to a new power state, using the platform formware and/or
556  * the device's PCI PM registers.
557  *
558  * RETURN VALUE:
559  * -EINVAL if the requested state is invalid.
560  * -EIO if device does not support PCI PM or its PM capabilities register has a
561  * wrong version, or device doesn't support the requested state.
562  * 0 if device already is in the requested state.
563  * 0 if device's power state has been successfully changed.
564  */
565 int pci_set_power_state(struct pci_dev *dev, pci_power_t state)
566 {
567         int error;
568
569         /* bound the state we're entering */
570         if (state > PCI_D3hot)
571                 state = PCI_D3hot;
572         else if (state < PCI_D0)
573                 state = PCI_D0;
574         else if ((state == PCI_D1 || state == PCI_D2) && pci_no_d1d2(dev))
575                 /*
576                  * If the device or the parent bridge do not support PCI PM,
577                  * ignore the request if we're doing anything other than putting
578                  * it into D0 (which would only happen on boot).
579                  */
580                 return 0;
581
582         if (state == PCI_D0 && platform_pci_power_manageable(dev)) {
583                 /*
584                  * Allow the platform to change the state, for example via ACPI
585                  * _PR0, _PS0 and some such, but do not trust it.
586                  */
587                 int ret = platform_pci_set_power_state(dev, PCI_D0);
588                 if (!ret)
589                         pci_update_current_state(dev, PCI_D0);
590         }
591         /* This device is quirked not to be put into D3, so
592            don't put it in D3 */
593         if (state == PCI_D3hot && (dev->dev_flags & PCI_DEV_FLAGS_NO_D3))
594                 return 0;
595
596         error = pci_raw_set_power_state(dev, state, true);
597
598         if (state > PCI_D0 && platform_pci_power_manageable(dev)) {
599                 /* Allow the platform to finalize the transition */
600                 int ret = platform_pci_set_power_state(dev, state);
601                 if (!ret) {
602                         pci_update_current_state(dev, state);
603                         error = 0;
604                 }
605         }
606
607         return error;
608 }
609
610 /**
611  * pci_choose_state - Choose the power state of a PCI device
612  * @dev: PCI device to be suspended
613  * @state: target sleep state for the whole system. This is the value
614  *      that is passed to suspend() function.
615  *
616  * Returns PCI power state suitable for given device and given system
617  * message.
618  */
619
620 pci_power_t pci_choose_state(struct pci_dev *dev, pm_message_t state)
621 {
622         pci_power_t ret;
623
624         if (!pci_find_capability(dev, PCI_CAP_ID_PM))
625                 return PCI_D0;
626
627         ret = platform_pci_choose_state(dev);
628         if (ret != PCI_POWER_ERROR)
629                 return ret;
630
631         switch (state.event) {
632         case PM_EVENT_ON:
633                 return PCI_D0;
634         case PM_EVENT_FREEZE:
635         case PM_EVENT_PRETHAW:
636                 /* REVISIT both freeze and pre-thaw "should" use D0 */
637         case PM_EVENT_SUSPEND:
638         case PM_EVENT_HIBERNATE:
639                 return PCI_D3hot;
640         default:
641                 dev_info(&dev->dev, "unrecognized suspend event %d\n",
642                          state.event);
643                 BUG();
644         }
645         return PCI_D0;
646 }
647
648 EXPORT_SYMBOL(pci_choose_state);
649
650 #define PCI_EXP_SAVE_REGS       7
651
652 static int pci_save_pcie_state(struct pci_dev *dev)
653 {
654         int pos, i = 0;
655         struct pci_cap_saved_state *save_state;
656         u16 *cap;
657
658         pos = pci_find_capability(dev, PCI_CAP_ID_EXP);
659         if (pos <= 0)
660                 return 0;
661
662         save_state = pci_find_saved_cap(dev, PCI_CAP_ID_EXP);
663         if (!save_state) {
664                 dev_err(&dev->dev, "buffer not found in %s\n", __func__);
665                 return -ENOMEM;
666         }
667         cap = (u16 *)&save_state->data[0];
668
669         pci_read_config_word(dev, pos + PCI_EXP_DEVCTL, &cap[i++]);
670         pci_read_config_word(dev, pos + PCI_EXP_LNKCTL, &cap[i++]);
671         pci_read_config_word(dev, pos + PCI_EXP_SLTCTL, &cap[i++]);
672         pci_read_config_word(dev, pos + PCI_EXP_RTCTL, &cap[i++]);
673         pci_read_config_word(dev, pos + PCI_EXP_DEVCTL2, &cap[i++]);
674         pci_read_config_word(dev, pos + PCI_EXP_LNKCTL2, &cap[i++]);
675         pci_read_config_word(dev, pos + PCI_EXP_SLTCTL2, &cap[i++]);
676
677         return 0;
678 }
679
680 static void pci_restore_pcie_state(struct pci_dev *dev)
681 {
682         int i = 0, pos;
683         struct pci_cap_saved_state *save_state;
684         u16 *cap;
685
686         save_state = pci_find_saved_cap(dev, PCI_CAP_ID_EXP);
687         pos = pci_find_capability(dev, PCI_CAP_ID_EXP);
688         if (!save_state || pos <= 0)
689                 return;
690         cap = (u16 *)&save_state->data[0];
691
692         pci_write_config_word(dev, pos + PCI_EXP_DEVCTL, cap[i++]);
693         pci_write_config_word(dev, pos + PCI_EXP_LNKCTL, cap[i++]);
694         pci_write_config_word(dev, pos + PCI_EXP_SLTCTL, cap[i++]);
695         pci_write_config_word(dev, pos + PCI_EXP_RTCTL, cap[i++]);
696         pci_write_config_word(dev, pos + PCI_EXP_DEVCTL2, cap[i++]);
697         pci_write_config_word(dev, pos + PCI_EXP_LNKCTL2, cap[i++]);
698         pci_write_config_word(dev, pos + PCI_EXP_SLTCTL2, cap[i++]);
699 }
700
701
702 static int pci_save_pcix_state(struct pci_dev *dev)
703 {
704         int pos;
705         struct pci_cap_saved_state *save_state;
706
707         pos = pci_find_capability(dev, PCI_CAP_ID_PCIX);
708         if (pos <= 0)
709                 return 0;
710
711         save_state = pci_find_saved_cap(dev, PCI_CAP_ID_PCIX);
712         if (!save_state) {
713                 dev_err(&dev->dev, "buffer not found in %s\n", __func__);
714                 return -ENOMEM;
715         }
716
717         pci_read_config_word(dev, pos + PCI_X_CMD, (u16 *)save_state->data);
718
719         return 0;
720 }
721
722 static void pci_restore_pcix_state(struct pci_dev *dev)
723 {
724         int i = 0, pos;
725         struct pci_cap_saved_state *save_state;
726         u16 *cap;
727
728         save_state = pci_find_saved_cap(dev, PCI_CAP_ID_PCIX);
729         pos = pci_find_capability(dev, PCI_CAP_ID_PCIX);
730         if (!save_state || pos <= 0)
731                 return;
732         cap = (u16 *)&save_state->data[0];
733
734         pci_write_config_word(dev, pos + PCI_X_CMD, cap[i++]);
735 }
736
737
738 /**
739  * pci_save_state - save the PCI configuration space of a device before suspending
740  * @dev: - PCI device that we're dealing with
741  */
742 int
743 pci_save_state(struct pci_dev *dev)
744 {
745         int i;
746         /* XXX: 100% dword access ok here? */
747         for (i = 0; i < 16; i++)
748                 pci_read_config_dword(dev, i * 4,&dev->saved_config_space[i]);
749         dev->state_saved = true;
750         if ((i = pci_save_pcie_state(dev)) != 0)
751                 return i;
752         if ((i = pci_save_pcix_state(dev)) != 0)
753                 return i;
754         return 0;
755 }
756
757 /** 
758  * pci_restore_state - Restore the saved state of a PCI device
759  * @dev: - PCI device that we're dealing with
760  */
761 int 
762 pci_restore_state(struct pci_dev *dev)
763 {
764         int i;
765         u32 val;
766
767         /* PCI Express register must be restored first */
768         pci_restore_pcie_state(dev);
769
770         /*
771          * The Base Address register should be programmed before the command
772          * register(s)
773          */
774         for (i = 15; i >= 0; i--) {
775                 pci_read_config_dword(dev, i * 4, &val);
776                 if (val != dev->saved_config_space[i]) {
777                         dev_printk(KERN_DEBUG, &dev->dev, "restoring config "
778                                 "space at offset %#x (was %#x, writing %#x)\n",
779                                 i, val, (int)dev->saved_config_space[i]);
780                         pci_write_config_dword(dev,i * 4,
781                                 dev->saved_config_space[i]);
782                 }
783         }
784         pci_restore_pcix_state(dev);
785         pci_restore_msi_state(dev);
786         pci_restore_iov_state(dev);
787
788         return 0;
789 }
790
791 static int do_pci_enable_device(struct pci_dev *dev, int bars)
792 {
793         int err;
794
795         err = pci_set_power_state(dev, PCI_D0);
796         if (err < 0 && err != -EIO)
797                 return err;
798         err = pcibios_enable_device(dev, bars);
799         if (err < 0)
800                 return err;
801         pci_fixup_device(pci_fixup_enable, dev);
802
803         return 0;
804 }
805
806 /**
807  * pci_reenable_device - Resume abandoned device
808  * @dev: PCI device to be resumed
809  *
810  *  Note this function is a backend of pci_default_resume and is not supposed
811  *  to be called by normal code, write proper resume handler and use it instead.
812  */
813 int pci_reenable_device(struct pci_dev *dev)
814 {
815         if (atomic_read(&dev->enable_cnt))
816                 return do_pci_enable_device(dev, (1 << PCI_NUM_RESOURCES) - 1);
817         return 0;
818 }
819
820 static int __pci_enable_device_flags(struct pci_dev *dev,
821                                      resource_size_t flags)
822 {
823         int err;
824         int i, bars = 0;
825
826         if (atomic_add_return(1, &dev->enable_cnt) > 1)
827                 return 0;               /* already enabled */
828
829         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++)
830                 if (dev->resource[i].flags & flags)
831                         bars |= (1 << i);
832
833         err = do_pci_enable_device(dev, bars);
834         if (err < 0)
835                 atomic_dec(&dev->enable_cnt);
836         return err;
837 }
838
839 /**
840  * pci_enable_device_io - Initialize a device for use with IO space
841  * @dev: PCI device to be initialized
842  *
843  *  Initialize device before it's used by a driver. Ask low-level code
844  *  to enable I/O resources. Wake up the device if it was suspended.
845  *  Beware, this function can fail.
846  */
847 int pci_enable_device_io(struct pci_dev *dev)
848 {
849         return __pci_enable_device_flags(dev, IORESOURCE_IO);
850 }
851
852 /**
853  * pci_enable_device_mem - Initialize a device for use with Memory space
854  * @dev: PCI device to be initialized
855  *
856  *  Initialize device before it's used by a driver. Ask low-level code
857  *  to enable Memory resources. Wake up the device if it was suspended.
858  *  Beware, this function can fail.
859  */
860 int pci_enable_device_mem(struct pci_dev *dev)
861 {
862         return __pci_enable_device_flags(dev, IORESOURCE_MEM);
863 }
864
865 /**
866  * pci_enable_device - Initialize device before it's used by a driver.
867  * @dev: PCI device to be initialized
868  *
869  *  Initialize device before it's used by a driver. Ask low-level code
870  *  to enable I/O and memory. Wake up the device if it was suspended.
871  *  Beware, this function can fail.
872  *
873  *  Note we don't actually enable the device many times if we call
874  *  this function repeatedly (we just increment the count).
875  */
876 int pci_enable_device(struct pci_dev *dev)
877 {
878         return __pci_enable_device_flags(dev, IORESOURCE_MEM | IORESOURCE_IO);
879 }
880
881 /*
882  * Managed PCI resources.  This manages device on/off, intx/msi/msix
883  * on/off and BAR regions.  pci_dev itself records msi/msix status, so
884  * there's no need to track it separately.  pci_devres is initialized
885  * when a device is enabled using managed PCI device enable interface.
886  */
887 struct pci_devres {
888         unsigned int enabled:1;
889         unsigned int pinned:1;
890         unsigned int orig_intx:1;
891         unsigned int restore_intx:1;
892         u32 region_mask;
893 };
894
895 static void pcim_release(struct device *gendev, void *res)
896 {
897         struct pci_dev *dev = container_of(gendev, struct pci_dev, dev);
898         struct pci_devres *this = res;
899         int i;
900
901         if (dev->msi_enabled)
902                 pci_disable_msi(dev);
903         if (dev->msix_enabled)
904                 pci_disable_msix(dev);
905
906         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++)
907                 if (this->region_mask & (1 << i))
908                         pci_release_region(dev, i);
909
910         if (this->restore_intx)
911                 pci_intx(dev, this->orig_intx);
912
913         if (this->enabled && !this->pinned)
914                 pci_disable_device(dev);
915 }
916
917 static struct pci_devres * get_pci_dr(struct pci_dev *pdev)
918 {
919         struct pci_devres *dr, *new_dr;
920
921         dr = devres_find(&pdev->dev, pcim_release, NULL, NULL);
922         if (dr)
923                 return dr;
924
925         new_dr = devres_alloc(pcim_release, sizeof(*new_dr), GFP_KERNEL);
926         if (!new_dr)
927                 return NULL;
928         return devres_get(&pdev->dev, new_dr, NULL, NULL);
929 }
930
931 static struct pci_devres * find_pci_dr(struct pci_dev *pdev)
932 {
933         if (pci_is_managed(pdev))
934                 return devres_find(&pdev->dev, pcim_release, NULL, NULL);
935         return NULL;
936 }
937
938 /**
939  * pcim_enable_device - Managed pci_enable_device()
940  * @pdev: PCI device to be initialized
941  *
942  * Managed pci_enable_device().
943  */
944 int pcim_enable_device(struct pci_dev *pdev)
945 {
946         struct pci_devres *dr;
947         int rc;
948
949         dr = get_pci_dr(pdev);
950         if (unlikely(!dr))
951                 return -ENOMEM;
952         if (dr->enabled)
953                 return 0;
954
955         rc = pci_enable_device(pdev);
956         if (!rc) {
957                 pdev->is_managed = 1;
958                 dr->enabled = 1;
959         }
960         return rc;
961 }
962
963 /**
964  * pcim_pin_device - Pin managed PCI device
965  * @pdev: PCI device to pin
966  *
967  * Pin managed PCI device @pdev.  Pinned device won't be disabled on
968  * driver detach.  @pdev must have been enabled with
969  * pcim_enable_device().
970  */
971 void pcim_pin_device(struct pci_dev *pdev)
972 {
973         struct pci_devres *dr;
974
975         dr = find_pci_dr(pdev);
976         WARN_ON(!dr || !dr->enabled);
977         if (dr)
978                 dr->pinned = 1;
979 }
980
981 /**
982  * pcibios_disable_device - disable arch specific PCI resources for device dev
983  * @dev: the PCI device to disable
984  *
985  * Disables architecture specific PCI resources for the device. This
986  * is the default implementation. Architecture implementations can
987  * override this.
988  */
989 void __attribute__ ((weak)) pcibios_disable_device (struct pci_dev *dev) {}
990
991 static void do_pci_disable_device(struct pci_dev *dev)
992 {
993         u16 pci_command;
994
995         pci_read_config_word(dev, PCI_COMMAND, &pci_command);
996         if (pci_command & PCI_COMMAND_MASTER) {
997                 pci_command &= ~PCI_COMMAND_MASTER;
998                 pci_write_config_word(dev, PCI_COMMAND, pci_command);
999         }
1000
1001         pcibios_disable_device(dev);
1002 }
1003
1004 /**
1005  * pci_disable_enabled_device - Disable device without updating enable_cnt
1006  * @dev: PCI device to disable
1007  *
1008  * NOTE: This function is a backend of PCI power management routines and is
1009  * not supposed to be called drivers.
1010  */
1011 void pci_disable_enabled_device(struct pci_dev *dev)
1012 {
1013         if (atomic_read(&dev->enable_cnt))
1014                 do_pci_disable_device(dev);
1015 }
1016
1017 /**
1018  * pci_disable_device - Disable PCI device after use
1019  * @dev: PCI device to be disabled
1020  *
1021  * Signal to the system that the PCI device is not in use by the system
1022  * anymore.  This only involves disabling PCI bus-mastering, if active.
1023  *
1024  * Note we don't actually disable the device until all callers of
1025  * pci_device_enable() have called pci_device_disable().
1026  */
1027 void
1028 pci_disable_device(struct pci_dev *dev)
1029 {
1030         struct pci_devres *dr;
1031
1032         dr = find_pci_dr(dev);
1033         if (dr)
1034                 dr->enabled = 0;
1035
1036         if (atomic_sub_return(1, &dev->enable_cnt) != 0)
1037                 return;
1038
1039         do_pci_disable_device(dev);
1040
1041         dev->is_busmaster = 0;
1042 }
1043
1044 /**
1045  * pcibios_set_pcie_reset_state - set reset state for device dev
1046  * @dev: the PCI-E device reset
1047  * @state: Reset state to enter into
1048  *
1049  *
1050  * Sets the PCI-E reset state for the device. This is the default
1051  * implementation. Architecture implementations can override this.
1052  */
1053 int __attribute__ ((weak)) pcibios_set_pcie_reset_state(struct pci_dev *dev,
1054                                                         enum pcie_reset_state state)
1055 {
1056         return -EINVAL;
1057 }
1058
1059 /**
1060  * pci_set_pcie_reset_state - set reset state for device dev
1061  * @dev: the PCI-E device reset
1062  * @state: Reset state to enter into
1063  *
1064  *
1065  * Sets the PCI reset state for the device.
1066  */
1067 int pci_set_pcie_reset_state(struct pci_dev *dev, enum pcie_reset_state state)
1068 {
1069         return pcibios_set_pcie_reset_state(dev, state);
1070 }
1071
1072 /**
1073  * pci_pme_capable - check the capability of PCI device to generate PME#
1074  * @dev: PCI device to handle.
1075  * @state: PCI state from which device will issue PME#.
1076  */
1077 bool pci_pme_capable(struct pci_dev *dev, pci_power_t state)
1078 {
1079         if (!dev->pm_cap)
1080                 return false;
1081
1082         return !!(dev->pme_support & (1 << state));
1083 }
1084
1085 /**
1086  * pci_pme_active - enable or disable PCI device's PME# function
1087  * @dev: PCI device to handle.
1088  * @enable: 'true' to enable PME# generation; 'false' to disable it.
1089  *
1090  * The caller must verify that the device is capable of generating PME# before
1091  * calling this function with @enable equal to 'true'.
1092  */
1093 void pci_pme_active(struct pci_dev *dev, bool enable)
1094 {
1095         u16 pmcsr;
1096
1097         if (!dev->pm_cap)
1098                 return;
1099
1100         pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
1101         /* Clear PME_Status by writing 1 to it and enable PME# */
1102         pmcsr |= PCI_PM_CTRL_PME_STATUS | PCI_PM_CTRL_PME_ENABLE;
1103         if (!enable)
1104                 pmcsr &= ~PCI_PM_CTRL_PME_ENABLE;
1105
1106         pci_write_config_word(dev, dev->pm_cap + PCI_PM_CTRL, pmcsr);
1107
1108         dev_printk(KERN_INFO, &dev->dev, "PME# %s\n",
1109                         enable ? "enabled" : "disabled");
1110 }
1111
1112 /**
1113  * pci_enable_wake - enable PCI device as wakeup event source
1114  * @dev: PCI device affected
1115  * @state: PCI state from which device will issue wakeup events
1116  * @enable: True to enable event generation; false to disable
1117  *
1118  * This enables the device as a wakeup event source, or disables it.
1119  * When such events involves platform-specific hooks, those hooks are
1120  * called automatically by this routine.
1121  *
1122  * Devices with legacy power management (no standard PCI PM capabilities)
1123  * always require such platform hooks.
1124  *
1125  * RETURN VALUE:
1126  * 0 is returned on success
1127  * -EINVAL is returned if device is not supposed to wake up the system
1128  * Error code depending on the platform is returned if both the platform and
1129  * the native mechanism fail to enable the generation of wake-up events
1130  */
1131 int pci_enable_wake(struct pci_dev *dev, pci_power_t state, int enable)
1132 {
1133         int error = 0;
1134         bool pme_done = false;
1135
1136         if (enable && !device_may_wakeup(&dev->dev))
1137                 return -EINVAL;
1138
1139         /*
1140          * According to "PCI System Architecture" 4th ed. by Tom Shanley & Don
1141          * Anderson we should be doing PME# wake enable followed by ACPI wake
1142          * enable.  To disable wake-up we call the platform first, for symmetry.
1143          */
1144
1145         if (!enable && platform_pci_can_wakeup(dev))
1146                 error = platform_pci_sleep_wake(dev, false);
1147
1148         if (!enable || pci_pme_capable(dev, state)) {
1149                 pci_pme_active(dev, enable);
1150                 pme_done = true;
1151         }
1152
1153         if (enable && platform_pci_can_wakeup(dev))
1154                 error = platform_pci_sleep_wake(dev, true);
1155
1156         return pme_done ? 0 : error;
1157 }
1158
1159 /**
1160  * pci_wake_from_d3 - enable/disable device to wake up from D3_hot or D3_cold
1161  * @dev: PCI device to prepare
1162  * @enable: True to enable wake-up event generation; false to disable
1163  *
1164  * Many drivers want the device to wake up the system from D3_hot or D3_cold
1165  * and this function allows them to set that up cleanly - pci_enable_wake()
1166  * should not be called twice in a row to enable wake-up due to PCI PM vs ACPI
1167  * ordering constraints.
1168  *
1169  * This function only returns error code if the device is not capable of
1170  * generating PME# from both D3_hot and D3_cold, and the platform is unable to
1171  * enable wake-up power for it.
1172  */
1173 int pci_wake_from_d3(struct pci_dev *dev, bool enable)
1174 {
1175         return pci_pme_capable(dev, PCI_D3cold) ?
1176                         pci_enable_wake(dev, PCI_D3cold, enable) :
1177                         pci_enable_wake(dev, PCI_D3hot, enable);
1178 }
1179
1180 /**
1181  * pci_target_state - find an appropriate low power state for a given PCI dev
1182  * @dev: PCI device
1183  *
1184  * Use underlying platform code to find a supported low power state for @dev.
1185  * If the platform can't manage @dev, return the deepest state from which it
1186  * can generate wake events, based on any available PME info.
1187  */
1188 pci_power_t pci_target_state(struct pci_dev *dev)
1189 {
1190         pci_power_t target_state = PCI_D3hot;
1191
1192         if (platform_pci_power_manageable(dev)) {
1193                 /*
1194                  * Call the platform to choose the target state of the device
1195                  * and enable wake-up from this state if supported.
1196                  */
1197                 pci_power_t state = platform_pci_choose_state(dev);
1198
1199                 switch (state) {
1200                 case PCI_POWER_ERROR:
1201                 case PCI_UNKNOWN:
1202                         break;
1203                 case PCI_D1:
1204                 case PCI_D2:
1205                         if (pci_no_d1d2(dev))
1206                                 break;
1207                 default:
1208                         target_state = state;
1209                 }
1210         } else if (device_may_wakeup(&dev->dev)) {
1211                 /*
1212                  * Find the deepest state from which the device can generate
1213                  * wake-up events, make it the target state and enable device
1214                  * to generate PME#.
1215                  */
1216                 if (!dev->pm_cap)
1217                         return PCI_POWER_ERROR;
1218
1219                 if (dev->pme_support) {
1220                         while (target_state
1221                               && !(dev->pme_support & (1 << target_state)))
1222                                 target_state--;
1223                 }
1224         }
1225
1226         return target_state;
1227 }
1228
1229 /**
1230  * pci_prepare_to_sleep - prepare PCI device for system-wide transition into a sleep state
1231  * @dev: Device to handle.
1232  *
1233  * Choose the power state appropriate for the device depending on whether
1234  * it can wake up the system and/or is power manageable by the platform
1235  * (PCI_D3hot is the default) and put the device into that state.
1236  */
1237 int pci_prepare_to_sleep(struct pci_dev *dev)
1238 {
1239         pci_power_t target_state = pci_target_state(dev);
1240         int error;
1241
1242         if (target_state == PCI_POWER_ERROR)
1243                 return -EIO;
1244
1245         pci_enable_wake(dev, target_state, true);
1246
1247         error = pci_set_power_state(dev, target_state);
1248
1249         if (error)
1250                 pci_enable_wake(dev, target_state, false);
1251
1252         return error;
1253 }
1254
1255 /**
1256  * pci_back_from_sleep - turn PCI device on during system-wide transition into working state
1257  * @dev: Device to handle.
1258  *
1259  * Disable device's sytem wake-up capability and put it into D0.
1260  */
1261 int pci_back_from_sleep(struct pci_dev *dev)
1262 {
1263         pci_enable_wake(dev, PCI_D0, false);
1264         return pci_set_power_state(dev, PCI_D0);
1265 }
1266
1267 /**
1268  * pci_pm_init - Initialize PM functions of given PCI device
1269  * @dev: PCI device to handle.
1270  */
1271 void pci_pm_init(struct pci_dev *dev)
1272 {
1273         int pm;
1274         u16 pmc;
1275
1276         dev->pm_cap = 0;
1277
1278         /* find PCI PM capability in list */
1279         pm = pci_find_capability(dev, PCI_CAP_ID_PM);
1280         if (!pm)
1281                 return;
1282         /* Check device's ability to generate PME# */
1283         pci_read_config_word(dev, pm + PCI_PM_PMC, &pmc);
1284
1285         if ((pmc & PCI_PM_CAP_VER_MASK) > 3) {
1286                 dev_err(&dev->dev, "unsupported PM cap regs version (%u)\n",
1287                         pmc & PCI_PM_CAP_VER_MASK);
1288                 return;
1289         }
1290
1291         dev->pm_cap = pm;
1292
1293         dev->d1_support = false;
1294         dev->d2_support = false;
1295         if (!pci_no_d1d2(dev)) {
1296                 if (pmc & PCI_PM_CAP_D1)
1297                         dev->d1_support = true;
1298                 if (pmc & PCI_PM_CAP_D2)
1299                         dev->d2_support = true;
1300
1301                 if (dev->d1_support || dev->d2_support)
1302                         dev_printk(KERN_DEBUG, &dev->dev, "supports%s%s\n",
1303                                    dev->d1_support ? " D1" : "",
1304                                    dev->d2_support ? " D2" : "");
1305         }
1306
1307         pmc &= PCI_PM_CAP_PME_MASK;
1308         if (pmc) {
1309                 dev_info(&dev->dev, "PME# supported from%s%s%s%s%s\n",
1310                          (pmc & PCI_PM_CAP_PME_D0) ? " D0" : "",
1311                          (pmc & PCI_PM_CAP_PME_D1) ? " D1" : "",
1312                          (pmc & PCI_PM_CAP_PME_D2) ? " D2" : "",
1313                          (pmc & PCI_PM_CAP_PME_D3) ? " D3hot" : "",
1314                          (pmc & PCI_PM_CAP_PME_D3cold) ? " D3cold" : "");
1315                 dev->pme_support = pmc >> PCI_PM_CAP_PME_SHIFT;
1316                 /*
1317                  * Make device's PM flags reflect the wake-up capability, but
1318                  * let the user space enable it to wake up the system as needed.
1319                  */
1320                 device_set_wakeup_capable(&dev->dev, true);
1321                 device_set_wakeup_enable(&dev->dev, false);
1322                 /* Disable the PME# generation functionality */
1323                 pci_pme_active(dev, false);
1324         } else {
1325                 dev->pme_support = 0;
1326         }
1327 }
1328
1329 /**
1330  * platform_pci_wakeup_init - init platform wakeup if present
1331  * @dev: PCI device
1332  *
1333  * Some devices don't have PCI PM caps but can still generate wakeup
1334  * events through platform methods (like ACPI events).  If @dev supports
1335  * platform wakeup events, set the device flag to indicate as much.  This
1336  * may be redundant if the device also supports PCI PM caps, but double
1337  * initialization should be safe in that case.
1338  */
1339 void platform_pci_wakeup_init(struct pci_dev *dev)
1340 {
1341         if (!platform_pci_can_wakeup(dev))
1342                 return;
1343
1344         device_set_wakeup_capable(&dev->dev, true);
1345         device_set_wakeup_enable(&dev->dev, false);
1346         platform_pci_sleep_wake(dev, false);
1347 }
1348
1349 /**
1350  * pci_add_save_buffer - allocate buffer for saving given capability registers
1351  * @dev: the PCI device
1352  * @cap: the capability to allocate the buffer for
1353  * @size: requested size of the buffer
1354  */
1355 static int pci_add_cap_save_buffer(
1356         struct pci_dev *dev, char cap, unsigned int size)
1357 {
1358         int pos;
1359         struct pci_cap_saved_state *save_state;
1360
1361         pos = pci_find_capability(dev, cap);
1362         if (pos <= 0)
1363                 return 0;
1364
1365         save_state = kzalloc(sizeof(*save_state) + size, GFP_KERNEL);
1366         if (!save_state)
1367                 return -ENOMEM;
1368
1369         save_state->cap_nr = cap;
1370         pci_add_saved_cap(dev, save_state);
1371
1372         return 0;
1373 }
1374
1375 /**
1376  * pci_allocate_cap_save_buffers - allocate buffers for saving capabilities
1377  * @dev: the PCI device
1378  */
1379 void pci_allocate_cap_save_buffers(struct pci_dev *dev)
1380 {
1381         int error;
1382
1383         error = pci_add_cap_save_buffer(dev, PCI_CAP_ID_EXP,
1384                                         PCI_EXP_SAVE_REGS * sizeof(u16));
1385         if (error)
1386                 dev_err(&dev->dev,
1387                         "unable to preallocate PCI Express save buffer\n");
1388
1389         error = pci_add_cap_save_buffer(dev, PCI_CAP_ID_PCIX, sizeof(u16));
1390         if (error)
1391                 dev_err(&dev->dev,
1392                         "unable to preallocate PCI-X save buffer\n");
1393 }
1394
1395 /**
1396  * pci_restore_standard_config - restore standard config registers of PCI device
1397  * @dev: PCI device to handle
1398  *
1399  * This function assumes that the device's configuration space is accessible.
1400  * If the device needs to be powered up, the function will wait for it to
1401  * change the state.
1402  */
1403 int pci_restore_standard_config(struct pci_dev *dev)
1404 {
1405         pci_power_t prev_state;
1406         int error;
1407
1408         pci_update_current_state(dev, PCI_D0);
1409
1410         prev_state = dev->current_state;
1411         if (prev_state == PCI_D0)
1412                 goto Restore;
1413
1414         error = pci_raw_set_power_state(dev, PCI_D0, false);
1415         if (error)
1416                 return error;
1417
1418         /*
1419          * This assumes that we won't get a bus in B2 or B3 from the BIOS, but
1420          * we've made this assumption forever and it appears to be universally
1421          * satisfied.
1422          */
1423         switch(prev_state) {
1424         case PCI_D3cold:
1425         case PCI_D3hot:
1426                 mdelay(pci_pm_d3_delay);
1427                 break;
1428         case PCI_D2:
1429                 udelay(PCI_PM_D2_DELAY);
1430                 break;
1431         }
1432
1433         pci_update_current_state(dev, PCI_D0);
1434
1435  Restore:
1436         return dev->state_saved ? pci_restore_state(dev) : 0;
1437 }
1438
1439 /**
1440  * pci_enable_ari - enable ARI forwarding if hardware support it
1441  * @dev: the PCI device
1442  */
1443 void pci_enable_ari(struct pci_dev *dev)
1444 {
1445         int pos;
1446         u32 cap;
1447         u16 ctrl;
1448         struct pci_dev *bridge;
1449
1450         if (!dev->is_pcie || dev->devfn)
1451                 return;
1452
1453         pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ARI);
1454         if (!pos)
1455                 return;
1456
1457         bridge = dev->bus->self;
1458         if (!bridge || !bridge->is_pcie)
1459                 return;
1460
1461         pos = pci_find_capability(bridge, PCI_CAP_ID_EXP);
1462         if (!pos)
1463                 return;
1464
1465         pci_read_config_dword(bridge, pos + PCI_EXP_DEVCAP2, &cap);
1466         if (!(cap & PCI_EXP_DEVCAP2_ARI))
1467                 return;
1468
1469         pci_read_config_word(bridge, pos + PCI_EXP_DEVCTL2, &ctrl);
1470         ctrl |= PCI_EXP_DEVCTL2_ARI;
1471         pci_write_config_word(bridge, pos + PCI_EXP_DEVCTL2, ctrl);
1472
1473         bridge->ari_enabled = 1;
1474 }
1475
1476 /**
1477  * pci_swizzle_interrupt_pin - swizzle INTx for device behind bridge
1478  * @dev: the PCI device
1479  * @pin: the INTx pin (1=INTA, 2=INTB, 3=INTD, 4=INTD)
1480  *
1481  * Perform INTx swizzling for a device behind one level of bridge.  This is
1482  * required by section 9.1 of the PCI-to-PCI bridge specification for devices
1483  * behind bridges on add-in cards.
1484  */
1485 u8 pci_swizzle_interrupt_pin(struct pci_dev *dev, u8 pin)
1486 {
1487         return (((pin - 1) + PCI_SLOT(dev->devfn)) % 4) + 1;
1488 }
1489
1490 int
1491 pci_get_interrupt_pin(struct pci_dev *dev, struct pci_dev **bridge)
1492 {
1493         u8 pin;
1494
1495         pin = dev->pin;
1496         if (!pin)
1497                 return -1;
1498
1499         while (dev->bus->parent) {
1500                 pin = pci_swizzle_interrupt_pin(dev, pin);
1501                 dev = dev->bus->self;
1502         }
1503         *bridge = dev;
1504         return pin;
1505 }
1506
1507 /**
1508  * pci_common_swizzle - swizzle INTx all the way to root bridge
1509  * @dev: the PCI device
1510  * @pinp: pointer to the INTx pin value (1=INTA, 2=INTB, 3=INTD, 4=INTD)
1511  *
1512  * Perform INTx swizzling for a device.  This traverses through all PCI-to-PCI
1513  * bridges all the way up to a PCI root bus.
1514  */
1515 u8 pci_common_swizzle(struct pci_dev *dev, u8 *pinp)
1516 {
1517         u8 pin = *pinp;
1518
1519         while (dev->bus->parent) {
1520                 pin = pci_swizzle_interrupt_pin(dev, pin);
1521                 dev = dev->bus->self;
1522         }
1523         *pinp = pin;
1524         return PCI_SLOT(dev->devfn);
1525 }
1526
1527 /**
1528  *      pci_release_region - Release a PCI bar
1529  *      @pdev: PCI device whose resources were previously reserved by pci_request_region
1530  *      @bar: BAR to release
1531  *
1532  *      Releases the PCI I/O and memory resources previously reserved by a
1533  *      successful call to pci_request_region.  Call this function only
1534  *      after all use of the PCI regions has ceased.
1535  */
1536 void pci_release_region(struct pci_dev *pdev, int bar)
1537 {
1538         struct pci_devres *dr;
1539
1540         if (pci_resource_len(pdev, bar) == 0)
1541                 return;
1542         if (pci_resource_flags(pdev, bar) & IORESOURCE_IO)
1543                 release_region(pci_resource_start(pdev, bar),
1544                                 pci_resource_len(pdev, bar));
1545         else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM)
1546                 release_mem_region(pci_resource_start(pdev, bar),
1547                                 pci_resource_len(pdev, bar));
1548
1549         dr = find_pci_dr(pdev);
1550         if (dr)
1551                 dr->region_mask &= ~(1 << bar);
1552 }
1553
1554 /**
1555  *      __pci_request_region - Reserved PCI I/O and memory resource
1556  *      @pdev: PCI device whose resources are to be reserved
1557  *      @bar: BAR to be reserved
1558  *      @res_name: Name to be associated with resource.
1559  *      @exclusive: whether the region access is exclusive or not
1560  *
1561  *      Mark the PCI region associated with PCI device @pdev BR @bar as
1562  *      being reserved by owner @res_name.  Do not access any
1563  *      address inside the PCI regions unless this call returns
1564  *      successfully.
1565  *
1566  *      If @exclusive is set, then the region is marked so that userspace
1567  *      is explicitly not allowed to map the resource via /dev/mem or
1568  *      sysfs MMIO access.
1569  *
1570  *      Returns 0 on success, or %EBUSY on error.  A warning
1571  *      message is also printed on failure.
1572  */
1573 static int __pci_request_region(struct pci_dev *pdev, int bar, const char *res_name,
1574                                                                         int exclusive)
1575 {
1576         struct pci_devres *dr;
1577
1578         if (pci_resource_len(pdev, bar) == 0)
1579                 return 0;
1580                 
1581         if (pci_resource_flags(pdev, bar) & IORESOURCE_IO) {
1582                 if (!request_region(pci_resource_start(pdev, bar),
1583                             pci_resource_len(pdev, bar), res_name))
1584                         goto err_out;
1585         }
1586         else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM) {
1587                 if (!__request_mem_region(pci_resource_start(pdev, bar),
1588                                         pci_resource_len(pdev, bar), res_name,
1589                                         exclusive))
1590                         goto err_out;
1591         }
1592
1593         dr = find_pci_dr(pdev);
1594         if (dr)
1595                 dr->region_mask |= 1 << bar;
1596
1597         return 0;
1598
1599 err_out:
1600         dev_warn(&pdev->dev, "BAR %d: can't reserve %s region %pR\n",
1601                  bar,
1602                  pci_resource_flags(pdev, bar) & IORESOURCE_IO ? "I/O" : "mem",
1603                  &pdev->resource[bar]);
1604         return -EBUSY;
1605 }
1606
1607 /**
1608  *      pci_request_region - Reserve PCI I/O and memory resource
1609  *      @pdev: PCI device whose resources are to be reserved
1610  *      @bar: BAR to be reserved
1611  *      @res_name: Name to be associated with resource
1612  *
1613  *      Mark the PCI region associated with PCI device @pdev BAR @bar as
1614  *      being reserved by owner @res_name.  Do not access any
1615  *      address inside the PCI regions unless this call returns
1616  *      successfully.
1617  *
1618  *      Returns 0 on success, or %EBUSY on error.  A warning
1619  *      message is also printed on failure.
1620  */
1621 int pci_request_region(struct pci_dev *pdev, int bar, const char *res_name)
1622 {
1623         return __pci_request_region(pdev, bar, res_name, 0);
1624 }
1625
1626 /**
1627  *      pci_request_region_exclusive - Reserved PCI I/O and memory resource
1628  *      @pdev: PCI device whose resources are to be reserved
1629  *      @bar: BAR to be reserved
1630  *      @res_name: Name to be associated with resource.
1631  *
1632  *      Mark the PCI region associated with PCI device @pdev BR @bar as
1633  *      being reserved by owner @res_name.  Do not access any
1634  *      address inside the PCI regions unless this call returns
1635  *      successfully.
1636  *
1637  *      Returns 0 on success, or %EBUSY on error.  A warning
1638  *      message is also printed on failure.
1639  *
1640  *      The key difference that _exclusive makes it that userspace is
1641  *      explicitly not allowed to map the resource via /dev/mem or
1642  *      sysfs.
1643  */
1644 int pci_request_region_exclusive(struct pci_dev *pdev, int bar, const char *res_name)
1645 {
1646         return __pci_request_region(pdev, bar, res_name, IORESOURCE_EXCLUSIVE);
1647 }
1648 /**
1649  * pci_release_selected_regions - Release selected PCI I/O and memory resources
1650  * @pdev: PCI device whose resources were previously reserved
1651  * @bars: Bitmask of BARs to be released
1652  *
1653  * Release selected PCI I/O and memory resources previously reserved.
1654  * Call this function only after all use of the PCI regions has ceased.
1655  */
1656 void pci_release_selected_regions(struct pci_dev *pdev, int bars)
1657 {
1658         int i;
1659
1660         for (i = 0; i < 6; i++)
1661                 if (bars & (1 << i))
1662                         pci_release_region(pdev, i);
1663 }
1664
1665 int __pci_request_selected_regions(struct pci_dev *pdev, int bars,
1666                                  const char *res_name, int excl)
1667 {
1668         int i;
1669
1670         for (i = 0; i < 6; i++)
1671                 if (bars & (1 << i))
1672                         if (__pci_request_region(pdev, i, res_name, excl))
1673                                 goto err_out;
1674         return 0;
1675
1676 err_out:
1677         while(--i >= 0)
1678                 if (bars & (1 << i))
1679                         pci_release_region(pdev, i);
1680
1681         return -EBUSY;
1682 }
1683
1684
1685 /**
1686  * pci_request_selected_regions - Reserve selected PCI I/O and memory resources
1687  * @pdev: PCI device whose resources are to be reserved
1688  * @bars: Bitmask of BARs to be requested
1689  * @res_name: Name to be associated with resource
1690  */
1691 int pci_request_selected_regions(struct pci_dev *pdev, int bars,
1692                                  const char *res_name)
1693 {
1694         return __pci_request_selected_regions(pdev, bars, res_name, 0);
1695 }
1696
1697 int pci_request_selected_regions_exclusive(struct pci_dev *pdev,
1698                                  int bars, const char *res_name)
1699 {
1700         return __pci_request_selected_regions(pdev, bars, res_name,
1701                         IORESOURCE_EXCLUSIVE);
1702 }
1703
1704 /**
1705  *      pci_release_regions - Release reserved PCI I/O and memory resources
1706  *      @pdev: PCI device whose resources were previously reserved by pci_request_regions
1707  *
1708  *      Releases all PCI I/O and memory resources previously reserved by a
1709  *      successful call to pci_request_regions.  Call this function only
1710  *      after all use of the PCI regions has ceased.
1711  */
1712
1713 void pci_release_regions(struct pci_dev *pdev)
1714 {
1715         pci_release_selected_regions(pdev, (1 << 6) - 1);
1716 }
1717
1718 /**
1719  *      pci_request_regions - Reserved PCI I/O and memory resources
1720  *      @pdev: PCI device whose resources are to be reserved
1721  *      @res_name: Name to be associated with resource.
1722  *
1723  *      Mark all PCI regions associated with PCI device @pdev as
1724  *      being reserved by owner @res_name.  Do not access any
1725  *      address inside the PCI regions unless this call returns
1726  *      successfully.
1727  *
1728  *      Returns 0 on success, or %EBUSY on error.  A warning
1729  *      message is also printed on failure.
1730  */
1731 int pci_request_regions(struct pci_dev *pdev, const char *res_name)
1732 {
1733         return pci_request_selected_regions(pdev, ((1 << 6) - 1), res_name);
1734 }
1735
1736 /**
1737  *      pci_request_regions_exclusive - Reserved PCI I/O and memory resources
1738  *      @pdev: PCI device whose resources are to be reserved
1739  *      @res_name: Name to be associated with resource.
1740  *
1741  *      Mark all PCI regions associated with PCI device @pdev as
1742  *      being reserved by owner @res_name.  Do not access any
1743  *      address inside the PCI regions unless this call returns
1744  *      successfully.
1745  *
1746  *      pci_request_regions_exclusive() will mark the region so that
1747  *      /dev/mem and the sysfs MMIO access will not be allowed.
1748  *
1749  *      Returns 0 on success, or %EBUSY on error.  A warning
1750  *      message is also printed on failure.
1751  */
1752 int pci_request_regions_exclusive(struct pci_dev *pdev, const char *res_name)
1753 {
1754         return pci_request_selected_regions_exclusive(pdev,
1755                                         ((1 << 6) - 1), res_name);
1756 }
1757
1758 static void __pci_set_master(struct pci_dev *dev, bool enable)
1759 {
1760         u16 old_cmd, cmd;
1761
1762         pci_read_config_word(dev, PCI_COMMAND, &old_cmd);
1763         if (enable)
1764                 cmd = old_cmd | PCI_COMMAND_MASTER;
1765         else
1766                 cmd = old_cmd & ~PCI_COMMAND_MASTER;
1767         if (cmd != old_cmd) {
1768                 dev_dbg(&dev->dev, "%s bus mastering\n",
1769                         enable ? "enabling" : "disabling");
1770                 pci_write_config_word(dev, PCI_COMMAND, cmd);
1771         }
1772         dev->is_busmaster = enable;
1773 }
1774
1775 /**
1776  * pci_set_master - enables bus-mastering for device dev
1777  * @dev: the PCI device to enable
1778  *
1779  * Enables bus-mastering on the device and calls pcibios_set_master()
1780  * to do the needed arch specific settings.
1781  */
1782 void pci_set_master(struct pci_dev *dev)
1783 {
1784         __pci_set_master(dev, true);
1785         pcibios_set_master(dev);
1786 }
1787
1788 /**
1789  * pci_clear_master - disables bus-mastering for device dev
1790  * @dev: the PCI device to disable
1791  */
1792 void pci_clear_master(struct pci_dev *dev)
1793 {
1794         __pci_set_master(dev, false);
1795 }
1796
1797 #ifdef PCI_DISABLE_MWI
1798 int pci_set_mwi(struct pci_dev *dev)
1799 {
1800         return 0;
1801 }
1802
1803 int pci_try_set_mwi(struct pci_dev *dev)
1804 {
1805         return 0;
1806 }
1807
1808 void pci_clear_mwi(struct pci_dev *dev)
1809 {
1810 }
1811
1812 #else
1813
1814 #ifndef PCI_CACHE_LINE_BYTES
1815 #define PCI_CACHE_LINE_BYTES L1_CACHE_BYTES
1816 #endif
1817
1818 /* This can be overridden by arch code. */
1819 /* Don't forget this is measured in 32-bit words, not bytes */
1820 u8 pci_cache_line_size = PCI_CACHE_LINE_BYTES / 4;
1821
1822 /**
1823  * pci_set_cacheline_size - ensure the CACHE_LINE_SIZE register is programmed
1824  * @dev: the PCI device for which MWI is to be enabled
1825  *
1826  * Helper function for pci_set_mwi.
1827  * Originally copied from drivers/net/acenic.c.
1828  * Copyright 1998-2001 by Jes Sorensen, <jes@trained-monkey.org>.
1829  *
1830  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
1831  */
1832 static int
1833 pci_set_cacheline_size(struct pci_dev *dev)
1834 {
1835         u8 cacheline_size;
1836
1837         if (!pci_cache_line_size)
1838                 return -EINVAL;         /* The system doesn't support MWI. */
1839
1840         /* Validate current setting: the PCI_CACHE_LINE_SIZE must be
1841            equal to or multiple of the right value. */
1842         pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
1843         if (cacheline_size >= pci_cache_line_size &&
1844             (cacheline_size % pci_cache_line_size) == 0)
1845                 return 0;
1846
1847         /* Write the correct value. */
1848         pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, pci_cache_line_size);
1849         /* Read it back. */
1850         pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
1851         if (cacheline_size == pci_cache_line_size)
1852                 return 0;
1853
1854         dev_printk(KERN_DEBUG, &dev->dev, "cache line size of %d is not "
1855                    "supported\n", pci_cache_line_size << 2);
1856
1857         return -EINVAL;
1858 }
1859
1860 /**
1861  * pci_set_mwi - enables memory-write-invalidate PCI transaction
1862  * @dev: the PCI device for which MWI is enabled
1863  *
1864  * Enables the Memory-Write-Invalidate transaction in %PCI_COMMAND.
1865  *
1866  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
1867  */
1868 int
1869 pci_set_mwi(struct pci_dev *dev)
1870 {
1871         int rc;
1872         u16 cmd;
1873
1874         rc = pci_set_cacheline_size(dev);
1875         if (rc)
1876                 return rc;
1877
1878         pci_read_config_word(dev, PCI_COMMAND, &cmd);
1879         if (! (cmd & PCI_COMMAND_INVALIDATE)) {
1880                 dev_dbg(&dev->dev, "enabling Mem-Wr-Inval\n");
1881                 cmd |= PCI_COMMAND_INVALIDATE;
1882                 pci_write_config_word(dev, PCI_COMMAND, cmd);
1883         }
1884         
1885         return 0;
1886 }
1887
1888 /**
1889  * pci_try_set_mwi - enables memory-write-invalidate PCI transaction
1890  * @dev: the PCI device for which MWI is enabled
1891  *
1892  * Enables the Memory-Write-Invalidate transaction in %PCI_COMMAND.
1893  * Callers are not required to check the return value.
1894  *
1895  * RETURNS: An appropriate -ERRNO error value on error, or zero for success.
1896  */
1897 int pci_try_set_mwi(struct pci_dev *dev)
1898 {
1899         int rc = pci_set_mwi(dev);
1900         return rc;
1901 }
1902
1903 /**
1904  * pci_clear_mwi - disables Memory-Write-Invalidate for device dev
1905  * @dev: the PCI device to disable
1906  *
1907  * Disables PCI Memory-Write-Invalidate transaction on the device
1908  */
1909 void
1910 pci_clear_mwi(struct pci_dev *dev)
1911 {
1912         u16 cmd;
1913
1914         pci_read_config_word(dev, PCI_COMMAND, &cmd);
1915         if (cmd & PCI_COMMAND_INVALIDATE) {
1916                 cmd &= ~PCI_COMMAND_INVALIDATE;
1917                 pci_write_config_word(dev, PCI_COMMAND, cmd);
1918         }
1919 }
1920 #endif /* ! PCI_DISABLE_MWI */
1921
1922 /**
1923  * pci_intx - enables/disables PCI INTx for device dev
1924  * @pdev: the PCI device to operate on
1925  * @enable: boolean: whether to enable or disable PCI INTx
1926  *
1927  * Enables/disables PCI INTx for device dev
1928  */
1929 void
1930 pci_intx(struct pci_dev *pdev, int enable)
1931 {
1932         u16 pci_command, new;
1933
1934         pci_read_config_word(pdev, PCI_COMMAND, &pci_command);
1935
1936         if (enable) {
1937                 new = pci_command & ~PCI_COMMAND_INTX_DISABLE;
1938         } else {
1939                 new = pci_command | PCI_COMMAND_INTX_DISABLE;
1940         }
1941
1942         if (new != pci_command) {
1943                 struct pci_devres *dr;
1944
1945                 pci_write_config_word(pdev, PCI_COMMAND, new);
1946
1947                 dr = find_pci_dr(pdev);
1948                 if (dr && !dr->restore_intx) {
1949                         dr->restore_intx = 1;
1950                         dr->orig_intx = !enable;
1951                 }
1952         }
1953 }
1954
1955 /**
1956  * pci_msi_off - disables any msi or msix capabilities
1957  * @dev: the PCI device to operate on
1958  *
1959  * If you want to use msi see pci_enable_msi and friends.
1960  * This is a lower level primitive that allows us to disable
1961  * msi operation at the device level.
1962  */
1963 void pci_msi_off(struct pci_dev *dev)
1964 {
1965         int pos;
1966         u16 control;
1967
1968         pos = pci_find_capability(dev, PCI_CAP_ID_MSI);
1969         if (pos) {
1970                 pci_read_config_word(dev, pos + PCI_MSI_FLAGS, &control);
1971                 control &= ~PCI_MSI_FLAGS_ENABLE;
1972                 pci_write_config_word(dev, pos + PCI_MSI_FLAGS, control);
1973         }
1974         pos = pci_find_capability(dev, PCI_CAP_ID_MSIX);
1975         if (pos) {
1976                 pci_read_config_word(dev, pos + PCI_MSIX_FLAGS, &control);
1977                 control &= ~PCI_MSIX_FLAGS_ENABLE;
1978                 pci_write_config_word(dev, pos + PCI_MSIX_FLAGS, control);
1979         }
1980 }
1981
1982 #ifndef HAVE_ARCH_PCI_SET_DMA_MASK
1983 /*
1984  * These can be overridden by arch-specific implementations
1985  */
1986 int
1987 pci_set_dma_mask(struct pci_dev *dev, u64 mask)
1988 {
1989         if (!pci_dma_supported(dev, mask))
1990                 return -EIO;
1991
1992         dev->dma_mask = mask;
1993
1994         return 0;
1995 }
1996     
1997 int
1998 pci_set_consistent_dma_mask(struct pci_dev *dev, u64 mask)
1999 {
2000         if (!pci_dma_supported(dev, mask))
2001                 return -EIO;
2002
2003         dev->dev.coherent_dma_mask = mask;
2004
2005         return 0;
2006 }
2007 #endif
2008
2009 #ifndef HAVE_ARCH_PCI_SET_DMA_MAX_SEGMENT_SIZE
2010 int pci_set_dma_max_seg_size(struct pci_dev *dev, unsigned int size)
2011 {
2012         return dma_set_max_seg_size(&dev->dev, size);
2013 }
2014 EXPORT_SYMBOL(pci_set_dma_max_seg_size);
2015 #endif
2016
2017 #ifndef HAVE_ARCH_PCI_SET_DMA_SEGMENT_BOUNDARY
2018 int pci_set_dma_seg_boundary(struct pci_dev *dev, unsigned long mask)
2019 {
2020         return dma_set_seg_boundary(&dev->dev, mask);
2021 }
2022 EXPORT_SYMBOL(pci_set_dma_seg_boundary);
2023 #endif
2024
2025 static int __pcie_flr(struct pci_dev *dev, int probe)
2026 {
2027         u16 status;
2028         u32 cap;
2029         int exppos = pci_find_capability(dev, PCI_CAP_ID_EXP);
2030
2031         if (!exppos)
2032                 return -ENOTTY;
2033         pci_read_config_dword(dev, exppos + PCI_EXP_DEVCAP, &cap);
2034         if (!(cap & PCI_EXP_DEVCAP_FLR))
2035                 return -ENOTTY;
2036
2037         if (probe)
2038                 return 0;
2039
2040         pci_block_user_cfg_access(dev);
2041
2042         /* Wait for Transaction Pending bit clean */
2043         pci_read_config_word(dev, exppos + PCI_EXP_DEVSTA, &status);
2044         if (!(status & PCI_EXP_DEVSTA_TRPND))
2045                 goto transaction_done;
2046
2047         msleep(100);
2048         pci_read_config_word(dev, exppos + PCI_EXP_DEVSTA, &status);
2049         if (!(status & PCI_EXP_DEVSTA_TRPND))
2050                 goto transaction_done;
2051
2052         dev_info(&dev->dev, "Busy after 100ms while trying to reset; "
2053                         "sleeping for 1 second\n");
2054         ssleep(1);
2055         pci_read_config_word(dev, exppos + PCI_EXP_DEVSTA, &status);
2056         if (status & PCI_EXP_DEVSTA_TRPND)
2057                 dev_info(&dev->dev, "Still busy after 1s; "
2058                                 "proceeding with reset anyway\n");
2059
2060 transaction_done:
2061         pci_write_config_word(dev, exppos + PCI_EXP_DEVCTL,
2062                                 PCI_EXP_DEVCTL_BCR_FLR);
2063         mdelay(100);
2064
2065         pci_unblock_user_cfg_access(dev);
2066         return 0;
2067 }
2068
2069 static int __pci_af_flr(struct pci_dev *dev, int probe)
2070 {
2071         int cappos = pci_find_capability(dev, PCI_CAP_ID_AF);
2072         u8 status;
2073         u8 cap;
2074
2075         if (!cappos)
2076                 return -ENOTTY;
2077         pci_read_config_byte(dev, cappos + PCI_AF_CAP, &cap);
2078         if (!(cap & PCI_AF_CAP_TP) || !(cap & PCI_AF_CAP_FLR))
2079                 return -ENOTTY;
2080
2081         if (probe)
2082                 return 0;
2083
2084         pci_block_user_cfg_access(dev);
2085
2086         /* Wait for Transaction Pending bit clean */
2087         pci_read_config_byte(dev, cappos + PCI_AF_STATUS, &status);
2088         if (!(status & PCI_AF_STATUS_TP))
2089                 goto transaction_done;
2090
2091         msleep(100);
2092         pci_read_config_byte(dev, cappos + PCI_AF_STATUS, &status);
2093         if (!(status & PCI_AF_STATUS_TP))
2094                 goto transaction_done;
2095
2096         dev_info(&dev->dev, "Busy after 100ms while trying to"
2097                         " reset; sleeping for 1 second\n");
2098         ssleep(1);
2099         pci_read_config_byte(dev, cappos + PCI_AF_STATUS, &status);
2100         if (status & PCI_AF_STATUS_TP)
2101                 dev_info(&dev->dev, "Still busy after 1s; "
2102                                 "proceeding with reset anyway\n");
2103
2104 transaction_done:
2105         pci_write_config_byte(dev, cappos + PCI_AF_CTRL, PCI_AF_CTRL_FLR);
2106         mdelay(100);
2107
2108         pci_unblock_user_cfg_access(dev);
2109         return 0;
2110 }
2111
2112 static int __pci_reset_function(struct pci_dev *pdev, int probe)
2113 {
2114         int res;
2115
2116         res = __pcie_flr(pdev, probe);
2117         if (res != -ENOTTY)
2118                 return res;
2119
2120         res = __pci_af_flr(pdev, probe);
2121         if (res != -ENOTTY)
2122                 return res;
2123
2124         return res;
2125 }
2126
2127 /**
2128  * pci_execute_reset_function() - Reset a PCI device function
2129  * @dev: Device function to reset
2130  *
2131  * Some devices allow an individual function to be reset without affecting
2132  * other functions in the same device.  The PCI device must be responsive
2133  * to PCI config space in order to use this function.
2134  *
2135  * The device function is presumed to be unused when this function is called.
2136  * Resetting the device will make the contents of PCI configuration space
2137  * random, so any caller of this must be prepared to reinitialise the
2138  * device including MSI, bus mastering, BARs, decoding IO and memory spaces,
2139  * etc.
2140  *
2141  * Returns 0 if the device function was successfully reset or -ENOTTY if the
2142  * device doesn't support resetting a single function.
2143  */
2144 int pci_execute_reset_function(struct pci_dev *dev)
2145 {
2146         return __pci_reset_function(dev, 0);
2147 }
2148 EXPORT_SYMBOL_GPL(pci_execute_reset_function);
2149
2150 /**
2151  * pci_reset_function() - quiesce and reset a PCI device function
2152  * @dev: Device function to reset
2153  *
2154  * Some devices allow an individual function to be reset without affecting
2155  * other functions in the same device.  The PCI device must be responsive
2156  * to PCI config space in order to use this function.
2157  *
2158  * This function does not just reset the PCI portion of a device, but
2159  * clears all the state associated with the device.  This function differs
2160  * from pci_execute_reset_function in that it saves and restores device state
2161  * over the reset.
2162  *
2163  * Returns 0 if the device function was successfully reset or -ENOTTY if the
2164  * device doesn't support resetting a single function.
2165  */
2166 int pci_reset_function(struct pci_dev *dev)
2167 {
2168         int r = __pci_reset_function(dev, 1);
2169
2170         if (r < 0)
2171                 return r;
2172
2173         if (!dev->msi_enabled && !dev->msix_enabled && dev->irq != 0)
2174                 disable_irq(dev->irq);
2175         pci_save_state(dev);
2176
2177         pci_write_config_word(dev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
2178
2179         r = pci_execute_reset_function(dev);
2180
2181         pci_restore_state(dev);
2182         if (!dev->msi_enabled && !dev->msix_enabled && dev->irq != 0)
2183                 enable_irq(dev->irq);
2184
2185         return r;
2186 }
2187 EXPORT_SYMBOL_GPL(pci_reset_function);
2188
2189 /**
2190  * pcix_get_max_mmrbc - get PCI-X maximum designed memory read byte count
2191  * @dev: PCI device to query
2192  *
2193  * Returns mmrbc: maximum designed memory read count in bytes
2194  *    or appropriate error value.
2195  */
2196 int pcix_get_max_mmrbc(struct pci_dev *dev)
2197 {
2198         int err, cap;
2199         u32 stat;
2200
2201         cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
2202         if (!cap)
2203                 return -EINVAL;
2204
2205         err = pci_read_config_dword(dev, cap + PCI_X_STATUS, &stat);
2206         if (err)
2207                 return -EINVAL;
2208
2209         return (stat & PCI_X_STATUS_MAX_READ) >> 12;
2210 }
2211 EXPORT_SYMBOL(pcix_get_max_mmrbc);
2212
2213 /**
2214  * pcix_get_mmrbc - get PCI-X maximum memory read byte count
2215  * @dev: PCI device to query
2216  *
2217  * Returns mmrbc: maximum memory read count in bytes
2218  *    or appropriate error value.
2219  */
2220 int pcix_get_mmrbc(struct pci_dev *dev)
2221 {
2222         int ret, cap;
2223         u32 cmd;
2224
2225         cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
2226         if (!cap)
2227                 return -EINVAL;
2228
2229         ret = pci_read_config_dword(dev, cap + PCI_X_CMD, &cmd);
2230         if (!ret)
2231                 ret = 512 << ((cmd & PCI_X_CMD_MAX_READ) >> 2);
2232
2233         return ret;
2234 }
2235 EXPORT_SYMBOL(pcix_get_mmrbc);
2236
2237 /**
2238  * pcix_set_mmrbc - set PCI-X maximum memory read byte count
2239  * @dev: PCI device to query
2240  * @mmrbc: maximum memory read count in bytes
2241  *    valid values are 512, 1024, 2048, 4096
2242  *
2243  * If possible sets maximum memory read byte count, some bridges have erratas
2244  * that prevent this.
2245  */
2246 int pcix_set_mmrbc(struct pci_dev *dev, int mmrbc)
2247 {
2248         int cap, err = -EINVAL;
2249         u32 stat, cmd, v, o;
2250
2251         if (mmrbc < 512 || mmrbc > 4096 || !is_power_of_2(mmrbc))
2252                 goto out;
2253
2254         v = ffs(mmrbc) - 10;
2255
2256         cap = pci_find_capability(dev, PCI_CAP_ID_PCIX);
2257         if (!cap)
2258                 goto out;
2259
2260         err = pci_read_config_dword(dev, cap + PCI_X_STATUS, &stat);
2261         if (err)
2262                 goto out;
2263
2264         if (v > (stat & PCI_X_STATUS_MAX_READ) >> 21)
2265                 return -E2BIG;
2266
2267         err = pci_read_config_dword(dev, cap + PCI_X_CMD, &cmd);
2268         if (err)
2269                 goto out;
2270
2271         o = (cmd & PCI_X_CMD_MAX_READ) >> 2;
2272         if (o != v) {
2273                 if (v > o && dev->bus &&
2274                    (dev->bus->bus_flags & PCI_BUS_FLAGS_NO_MMRBC))
2275                         return -EIO;
2276
2277                 cmd &= ~PCI_X_CMD_MAX_READ;
2278                 cmd |= v << 2;
2279                 err = pci_write_config_dword(dev, cap + PCI_X_CMD, cmd);
2280         }
2281 out:
2282         return err;
2283 }
2284 EXPORT_SYMBOL(pcix_set_mmrbc);
2285
2286 /**
2287  * pcie_get_readrq - get PCI Express read request size
2288  * @dev: PCI device to query
2289  *
2290  * Returns maximum memory read request in bytes
2291  *    or appropriate error value.
2292  */
2293 int pcie_get_readrq(struct pci_dev *dev)
2294 {
2295         int ret, cap;
2296         u16 ctl;
2297
2298         cap = pci_find_capability(dev, PCI_CAP_ID_EXP);
2299         if (!cap)
2300                 return -EINVAL;
2301
2302         ret = pci_read_config_word(dev, cap + PCI_EXP_DEVCTL, &ctl);
2303         if (!ret)
2304         ret = 128 << ((ctl & PCI_EXP_DEVCTL_READRQ) >> 12);
2305
2306         return ret;
2307 }
2308 EXPORT_SYMBOL(pcie_get_readrq);
2309
2310 /**
2311  * pcie_set_readrq - set PCI Express maximum memory read request
2312  * @dev: PCI device to query
2313  * @rq: maximum memory read count in bytes
2314  *    valid values are 128, 256, 512, 1024, 2048, 4096
2315  *
2316  * If possible sets maximum read byte count
2317  */
2318 int pcie_set_readrq(struct pci_dev *dev, int rq)
2319 {
2320         int cap, err = -EINVAL;
2321         u16 ctl, v;
2322
2323         if (rq < 128 || rq > 4096 || !is_power_of_2(rq))
2324                 goto out;
2325
2326         v = (ffs(rq) - 8) << 12;
2327
2328         cap = pci_find_capability(dev, PCI_CAP_ID_EXP);
2329         if (!cap)
2330                 goto out;
2331
2332         err = pci_read_config_word(dev, cap + PCI_EXP_DEVCTL, &ctl);
2333         if (err)
2334                 goto out;
2335
2336         if ((ctl & PCI_EXP_DEVCTL_READRQ) != v) {
2337                 ctl &= ~PCI_EXP_DEVCTL_READRQ;
2338                 ctl |= v;
2339                 err = pci_write_config_dword(dev, cap + PCI_EXP_DEVCTL, ctl);
2340         }
2341
2342 out:
2343         return err;
2344 }
2345 EXPORT_SYMBOL(pcie_set_readrq);
2346
2347 /**
2348  * pci_select_bars - Make BAR mask from the type of resource
2349  * @dev: the PCI device for which BAR mask is made
2350  * @flags: resource type mask to be selected
2351  *
2352  * This helper routine makes bar mask from the type of resource.
2353  */
2354 int pci_select_bars(struct pci_dev *dev, unsigned long flags)
2355 {
2356         int i, bars = 0;
2357         for (i = 0; i < PCI_NUM_RESOURCES; i++)
2358                 if (pci_resource_flags(dev, i) & flags)
2359                         bars |= (1 << i);
2360         return bars;
2361 }
2362
2363 /**
2364  * pci_resource_bar - get position of the BAR associated with a resource
2365  * @dev: the PCI device
2366  * @resno: the resource number
2367  * @type: the BAR type to be filled in
2368  *
2369  * Returns BAR position in config space, or 0 if the BAR is invalid.
2370  */
2371 int pci_resource_bar(struct pci_dev *dev, int resno, enum pci_bar_type *type)
2372 {
2373         int reg;
2374
2375         if (resno < PCI_ROM_RESOURCE) {
2376                 *type = pci_bar_unknown;
2377                 return PCI_BASE_ADDRESS_0 + 4 * resno;
2378         } else if (resno == PCI_ROM_RESOURCE) {
2379                 *type = pci_bar_mem32;
2380                 return dev->rom_base_reg;
2381         } else if (resno < PCI_BRIDGE_RESOURCES) {
2382                 /* device specific resource */
2383                 reg = pci_iov_resource_bar(dev, resno, type);
2384                 if (reg)
2385                         return reg;
2386         }
2387
2388         dev_err(&dev->dev, "BAR: invalid resource #%d\n", resno);
2389         return 0;
2390 }
2391
2392 #define RESOURCE_ALIGNMENT_PARAM_SIZE COMMAND_LINE_SIZE
2393 static char resource_alignment_param[RESOURCE_ALIGNMENT_PARAM_SIZE] = {0};
2394 spinlock_t resource_alignment_lock = SPIN_LOCK_UNLOCKED;
2395
2396 /**
2397  * pci_specified_resource_alignment - get resource alignment specified by user.
2398  * @dev: the PCI device to get
2399  *
2400  * RETURNS: Resource alignment if it is specified.
2401  *          Zero if it is not specified.
2402  */
2403 resource_size_t pci_specified_resource_alignment(struct pci_dev *dev)
2404 {
2405         int seg, bus, slot, func, align_order, count;
2406         resource_size_t align = 0;
2407         char *p;
2408
2409         spin_lock(&resource_alignment_lock);
2410         p = resource_alignment_param;
2411         while (*p) {
2412                 count = 0;
2413                 if (sscanf(p, "%d%n", &align_order, &count) == 1 &&
2414                                                         p[count] == '@') {
2415                         p += count + 1;
2416                 } else {
2417                         align_order = -1;
2418                 }
2419                 if (sscanf(p, "%x:%x:%x.%x%n",
2420                         &seg, &bus, &slot, &func, &count) != 4) {
2421                         seg = 0;
2422                         if (sscanf(p, "%x:%x.%x%n",
2423                                         &bus, &slot, &func, &count) != 3) {
2424                                 /* Invalid format */
2425                                 printk(KERN_ERR "PCI: Can't parse resource_alignment parameter: %s\n",
2426                                         p);
2427                                 break;
2428                         }
2429                 }
2430                 p += count;
2431                 if (seg == pci_domain_nr(dev->bus) &&
2432                         bus == dev->bus->number &&
2433                         slot == PCI_SLOT(dev->devfn) &&
2434                         func == PCI_FUNC(dev->devfn)) {
2435                         if (align_order == -1) {
2436                                 align = PAGE_SIZE;
2437                         } else {
2438                                 align = 1 << align_order;
2439                         }
2440                         /* Found */
2441                         break;
2442                 }
2443                 if (*p != ';' && *p != ',') {
2444                         /* End of param or invalid format */
2445                         break;
2446                 }
2447                 p++;
2448         }
2449         spin_unlock(&resource_alignment_lock);
2450         return align;
2451 }
2452
2453 /**
2454  * pci_is_reassigndev - check if specified PCI is target device to reassign
2455  * @dev: the PCI device to check
2456  *
2457  * RETURNS: non-zero for PCI device is a target device to reassign,
2458  *          or zero is not.
2459  */
2460 int pci_is_reassigndev(struct pci_dev *dev)
2461 {
2462         return (pci_specified_resource_alignment(dev) != 0);
2463 }
2464
2465 ssize_t pci_set_resource_alignment_param(const char *buf, size_t count)
2466 {
2467         if (count > RESOURCE_ALIGNMENT_PARAM_SIZE - 1)
2468                 count = RESOURCE_ALIGNMENT_PARAM_SIZE - 1;
2469         spin_lock(&resource_alignment_lock);
2470         strncpy(resource_alignment_param, buf, count);
2471         resource_alignment_param[count] = '\0';
2472         spin_unlock(&resource_alignment_lock);
2473         return count;
2474 }
2475
2476 ssize_t pci_get_resource_alignment_param(char *buf, size_t size)
2477 {
2478         size_t count;
2479         spin_lock(&resource_alignment_lock);
2480         count = snprintf(buf, size, "%s", resource_alignment_param);
2481         spin_unlock(&resource_alignment_lock);
2482         return count;
2483 }
2484
2485 static ssize_t pci_resource_alignment_show(struct bus_type *bus, char *buf)
2486 {
2487         return pci_get_resource_alignment_param(buf, PAGE_SIZE);
2488 }
2489
2490 static ssize_t pci_resource_alignment_store(struct bus_type *bus,
2491                                         const char *buf, size_t count)
2492 {
2493         return pci_set_resource_alignment_param(buf, count);
2494 }
2495
2496 BUS_ATTR(resource_alignment, 0644, pci_resource_alignment_show,
2497                                         pci_resource_alignment_store);
2498
2499 static int __init pci_resource_alignment_sysfs_init(void)
2500 {
2501         return bus_create_file(&pci_bus_type,
2502                                         &bus_attr_resource_alignment);
2503 }
2504
2505 late_initcall(pci_resource_alignment_sysfs_init);
2506
2507 static void __devinit pci_no_domains(void)
2508 {
2509 #ifdef CONFIG_PCI_DOMAINS
2510         pci_domains_supported = 0;
2511 #endif
2512 }
2513
2514 /**
2515  * pci_ext_cfg_enabled - can we access extended PCI config space?
2516  * @dev: The PCI device of the root bridge.
2517  *
2518  * Returns 1 if we can access PCI extended config space (offsets
2519  * greater than 0xff). This is the default implementation. Architecture
2520  * implementations can override this.
2521  */
2522 int __attribute__ ((weak)) pci_ext_cfg_avail(struct pci_dev *dev)
2523 {
2524         return 1;
2525 }
2526
2527 static int __devinit pci_init(void)
2528 {
2529         struct pci_dev *dev = NULL;
2530
2531         while ((dev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, dev)) != NULL) {
2532                 pci_fixup_device(pci_fixup_final, dev);
2533         }
2534
2535         return 0;
2536 }
2537
2538 static int __init pci_setup(char *str)
2539 {
2540         while (str) {
2541                 char *k = strchr(str, ',');
2542                 if (k)
2543                         *k++ = 0;
2544                 if (*str && (str = pcibios_setup(str)) && *str) {
2545                         if (!strcmp(str, "nomsi")) {
2546                                 pci_no_msi();
2547                         } else if (!strcmp(str, "noaer")) {
2548                                 pci_no_aer();
2549                         } else if (!strcmp(str, "nodomains")) {
2550                                 pci_no_domains();
2551                         } else if (!strncmp(str, "cbiosize=", 9)) {
2552                                 pci_cardbus_io_size = memparse(str + 9, &str);
2553                         } else if (!strncmp(str, "cbmemsize=", 10)) {
2554                                 pci_cardbus_mem_size = memparse(str + 10, &str);
2555                         } else if (!strncmp(str, "resource_alignment=", 19)) {
2556                                 pci_set_resource_alignment_param(str + 19,
2557                                                         strlen(str + 19));
2558                         } else {
2559                                 printk(KERN_ERR "PCI: Unknown option `%s'\n",
2560                                                 str);
2561                         }
2562                 }
2563                 str = k;
2564         }
2565         return 0;
2566 }
2567 early_param("pci", pci_setup);
2568
2569 device_initcall(pci_init);
2570
2571 EXPORT_SYMBOL(pci_reenable_device);
2572 EXPORT_SYMBOL(pci_enable_device_io);
2573 EXPORT_SYMBOL(pci_enable_device_mem);
2574 EXPORT_SYMBOL(pci_enable_device);
2575 EXPORT_SYMBOL(pcim_enable_device);
2576 EXPORT_SYMBOL(pcim_pin_device);
2577 EXPORT_SYMBOL(pci_disable_device);
2578 EXPORT_SYMBOL(pci_find_capability);
2579 EXPORT_SYMBOL(pci_bus_find_capability);
2580 EXPORT_SYMBOL(pci_release_regions);
2581 EXPORT_SYMBOL(pci_request_regions);
2582 EXPORT_SYMBOL(pci_request_regions_exclusive);
2583 EXPORT_SYMBOL(pci_release_region);
2584 EXPORT_SYMBOL(pci_request_region);
2585 EXPORT_SYMBOL(pci_request_region_exclusive);
2586 EXPORT_SYMBOL(pci_release_selected_regions);
2587 EXPORT_SYMBOL(pci_request_selected_regions);
2588 EXPORT_SYMBOL(pci_request_selected_regions_exclusive);
2589 EXPORT_SYMBOL(pci_set_master);
2590 EXPORT_SYMBOL(pci_clear_master);
2591 EXPORT_SYMBOL(pci_set_mwi);
2592 EXPORT_SYMBOL(pci_try_set_mwi);
2593 EXPORT_SYMBOL(pci_clear_mwi);
2594 EXPORT_SYMBOL_GPL(pci_intx);
2595 EXPORT_SYMBOL(pci_set_dma_mask);
2596 EXPORT_SYMBOL(pci_set_consistent_dma_mask);
2597 EXPORT_SYMBOL(pci_assign_resource);
2598 EXPORT_SYMBOL(pci_find_parent_resource);
2599 EXPORT_SYMBOL(pci_select_bars);
2600
2601 EXPORT_SYMBOL(pci_set_power_state);
2602 EXPORT_SYMBOL(pci_save_state);
2603 EXPORT_SYMBOL(pci_restore_state);
2604 EXPORT_SYMBOL(pci_pme_capable);
2605 EXPORT_SYMBOL(pci_pme_active);
2606 EXPORT_SYMBOL(pci_enable_wake);
2607 EXPORT_SYMBOL(pci_wake_from_d3);
2608 EXPORT_SYMBOL(pci_target_state);
2609 EXPORT_SYMBOL(pci_prepare_to_sleep);
2610 EXPORT_SYMBOL(pci_back_from_sleep);
2611 EXPORT_SYMBOL_GPL(pci_set_pcie_reset_state);
2612