Merge branch 'next' of git://git.kernel.org/pub/scm/linux/kernel/git/davej/cpufreq
[pandora-kernel.git] / arch / microblaze / pci / pci-common.c
1 /*
2  * Contains common pci routines for ALL ppc platform
3  * (based on pci_32.c and pci_64.c)
4  *
5  * Port for PPC64 David Engebretsen, IBM Corp.
6  * Contains common pci routines for ppc64 platform, pSeries and iSeries brands.
7  *
8  * Copyright (C) 2003 Anton Blanchard <anton@au.ibm.com>, IBM
9  *   Rework, based on alpha PCI code.
10  *
11  * Common pmac/prep/chrp pci routines. -- Cort
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version
16  * 2 of the License, or (at your option) any later version.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/pci.h>
21 #include <linux/string.h>
22 #include <linux/init.h>
23 #include <linux/bootmem.h>
24 #include <linux/mm.h>
25 #include <linux/list.h>
26 #include <linux/syscalls.h>
27 #include <linux/irq.h>
28 #include <linux/vmalloc.h>
29 #include <linux/slab.h>
30 #include <linux/of.h>
31 #include <linux/of_address.h>
32 #include <linux/of_pci.h>
33
34 #include <asm/processor.h>
35 #include <asm/io.h>
36 #include <asm/pci-bridge.h>
37 #include <asm/byteorder.h>
38
39 static DEFINE_SPINLOCK(hose_spinlock);
40 LIST_HEAD(hose_list);
41
42 /* XXX kill that some day ... */
43 static int global_phb_number;           /* Global phb counter */
44
45 /* ISA Memory physical address */
46 resource_size_t isa_mem_base;
47
48 /* Default PCI flags is 0 on ppc32, modified at boot on ppc64 */
49 unsigned int pci_flags;
50
51 static struct dma_map_ops *pci_dma_ops = &dma_direct_ops;
52
53 unsigned long isa_io_base;
54 unsigned long pci_dram_offset;
55 static int pci_bus_count;
56
57
58 void set_pci_dma_ops(struct dma_map_ops *dma_ops)
59 {
60         pci_dma_ops = dma_ops;
61 }
62
63 struct dma_map_ops *get_pci_dma_ops(void)
64 {
65         return pci_dma_ops;
66 }
67 EXPORT_SYMBOL(get_pci_dma_ops);
68
69 struct pci_controller *pcibios_alloc_controller(struct device_node *dev)
70 {
71         struct pci_controller *phb;
72
73         phb = zalloc_maybe_bootmem(sizeof(struct pci_controller), GFP_KERNEL);
74         if (!phb)
75                 return NULL;
76         spin_lock(&hose_spinlock);
77         phb->global_number = global_phb_number++;
78         list_add_tail(&phb->list_node, &hose_list);
79         spin_unlock(&hose_spinlock);
80         phb->dn = dev;
81         phb->is_dynamic = mem_init_done;
82         return phb;
83 }
84
85 void pcibios_free_controller(struct pci_controller *phb)
86 {
87         spin_lock(&hose_spinlock);
88         list_del(&phb->list_node);
89         spin_unlock(&hose_spinlock);
90
91         if (phb->is_dynamic)
92                 kfree(phb);
93 }
94
95 static resource_size_t pcibios_io_size(const struct pci_controller *hose)
96 {
97         return hose->io_resource.end - hose->io_resource.start + 1;
98 }
99
100 int pcibios_vaddr_is_ioport(void __iomem *address)
101 {
102         int ret = 0;
103         struct pci_controller *hose;
104         resource_size_t size;
105
106         spin_lock(&hose_spinlock);
107         list_for_each_entry(hose, &hose_list, list_node) {
108                 size = pcibios_io_size(hose);
109                 if (address >= hose->io_base_virt &&
110                     address < (hose->io_base_virt + size)) {
111                         ret = 1;
112                         break;
113                 }
114         }
115         spin_unlock(&hose_spinlock);
116         return ret;
117 }
118
119 unsigned long pci_address_to_pio(phys_addr_t address)
120 {
121         struct pci_controller *hose;
122         resource_size_t size;
123         unsigned long ret = ~0;
124
125         spin_lock(&hose_spinlock);
126         list_for_each_entry(hose, &hose_list, list_node) {
127                 size = pcibios_io_size(hose);
128                 if (address >= hose->io_base_phys &&
129                     address < (hose->io_base_phys + size)) {
130                         unsigned long base =
131                                 (unsigned long)hose->io_base_virt - _IO_BASE;
132                         ret = base + (address - hose->io_base_phys);
133                         break;
134                 }
135         }
136         spin_unlock(&hose_spinlock);
137
138         return ret;
139 }
140 EXPORT_SYMBOL_GPL(pci_address_to_pio);
141
142 /*
143  * Return the domain number for this bus.
144  */
145 int pci_domain_nr(struct pci_bus *bus)
146 {
147         struct pci_controller *hose = pci_bus_to_host(bus);
148
149         return hose->global_number;
150 }
151 EXPORT_SYMBOL(pci_domain_nr);
152
153 /* This routine is meant to be used early during boot, when the
154  * PCI bus numbers have not yet been assigned, and you need to
155  * issue PCI config cycles to an OF device.
156  * It could also be used to "fix" RTAS config cycles if you want
157  * to set pci_assign_all_buses to 1 and still use RTAS for PCI
158  * config cycles.
159  */
160 struct pci_controller *pci_find_hose_for_OF_device(struct device_node *node)
161 {
162         while (node) {
163                 struct pci_controller *hose, *tmp;
164                 list_for_each_entry_safe(hose, tmp, &hose_list, list_node)
165                         if (hose->dn == node)
166                                 return hose;
167                 node = node->parent;
168         }
169         return NULL;
170 }
171
172 static ssize_t pci_show_devspec(struct device *dev,
173                 struct device_attribute *attr, char *buf)
174 {
175         struct pci_dev *pdev;
176         struct device_node *np;
177
178         pdev = to_pci_dev(dev);
179         np = pci_device_to_OF_node(pdev);
180         if (np == NULL || np->full_name == NULL)
181                 return 0;
182         return sprintf(buf, "%s", np->full_name);
183 }
184 static DEVICE_ATTR(devspec, S_IRUGO, pci_show_devspec, NULL);
185
186 /* Add sysfs properties */
187 int pcibios_add_platform_entries(struct pci_dev *pdev)
188 {
189         return device_create_file(&pdev->dev, &dev_attr_devspec);
190 }
191
192 char __devinit *pcibios_setup(char *str)
193 {
194         return str;
195 }
196
197 /*
198  * Reads the interrupt pin to determine if interrupt is use by card.
199  * If the interrupt is used, then gets the interrupt line from the
200  * openfirmware and sets it in the pci_dev and pci_config line.
201  */
202 int pci_read_irq_line(struct pci_dev *pci_dev)
203 {
204         struct of_irq oirq;
205         unsigned int virq;
206
207         /* The current device-tree that iSeries generates from the HV
208          * PCI informations doesn't contain proper interrupt routing,
209          * and all the fallback would do is print out crap, so we
210          * don't attempt to resolve the interrupts here at all, some
211          * iSeries specific fixup does it.
212          *
213          * In the long run, we will hopefully fix the generated device-tree
214          * instead.
215          */
216         pr_debug("PCI: Try to map irq for %s...\n", pci_name(pci_dev));
217
218 #ifdef DEBUG
219         memset(&oirq, 0xff, sizeof(oirq));
220 #endif
221         /* Try to get a mapping from the device-tree */
222         if (of_irq_map_pci(pci_dev, &oirq)) {
223                 u8 line, pin;
224
225                 /* If that fails, lets fallback to what is in the config
226                  * space and map that through the default controller. We
227                  * also set the type to level low since that's what PCI
228                  * interrupts are. If your platform does differently, then
229                  * either provide a proper interrupt tree or don't use this
230                  * function.
231                  */
232                 if (pci_read_config_byte(pci_dev, PCI_INTERRUPT_PIN, &pin))
233                         return -1;
234                 if (pin == 0)
235                         return -1;
236                 if (pci_read_config_byte(pci_dev, PCI_INTERRUPT_LINE, &line) ||
237                     line == 0xff || line == 0) {
238                         return -1;
239                 }
240                 pr_debug(" No map ! Using line %d (pin %d) from PCI config\n",
241                          line, pin);
242
243                 virq = irq_create_mapping(NULL, line);
244                 if (virq != NO_IRQ)
245                         irq_set_irq_type(virq, IRQ_TYPE_LEVEL_LOW);
246         } else {
247                 pr_debug(" Got one, spec %d cells (0x%08x 0x%08x...) on %s\n",
248                          oirq.size, oirq.specifier[0], oirq.specifier[1],
249                          oirq.controller ? oirq.controller->full_name :
250                          "<default>");
251
252                 virq = irq_create_of_mapping(oirq.controller, oirq.specifier,
253                                              oirq.size);
254         }
255         if (virq == NO_IRQ) {
256                 pr_debug(" Failed to map !\n");
257                 return -1;
258         }
259
260         pr_debug(" Mapped to linux irq %d\n", virq);
261
262         pci_dev->irq = virq;
263
264         return 0;
265 }
266 EXPORT_SYMBOL(pci_read_irq_line);
267
268 /*
269  * Platform support for /proc/bus/pci/X/Y mmap()s,
270  * modelled on the sparc64 implementation by Dave Miller.
271  *  -- paulus.
272  */
273
274 /*
275  * Adjust vm_pgoff of VMA such that it is the physical page offset
276  * corresponding to the 32-bit pci bus offset for DEV requested by the user.
277  *
278  * Basically, the user finds the base address for his device which he wishes
279  * to mmap.  They read the 32-bit value from the config space base register,
280  * add whatever PAGE_SIZE multiple offset they wish, and feed this into the
281  * offset parameter of mmap on /proc/bus/pci/XXX for that device.
282  *
283  * Returns negative error code on failure, zero on success.
284  */
285 static struct resource *__pci_mmap_make_offset(struct pci_dev *dev,
286                                                resource_size_t *offset,
287                                                enum pci_mmap_state mmap_state)
288 {
289         struct pci_controller *hose = pci_bus_to_host(dev->bus);
290         unsigned long io_offset = 0;
291         int i, res_bit;
292
293         if (hose == 0)
294                 return NULL;            /* should never happen */
295
296         /* If memory, add on the PCI bridge address offset */
297         if (mmap_state == pci_mmap_mem) {
298 #if 0 /* See comment in pci_resource_to_user() for why this is disabled */
299                 *offset += hose->pci_mem_offset;
300 #endif
301                 res_bit = IORESOURCE_MEM;
302         } else {
303                 io_offset = (unsigned long)hose->io_base_virt - _IO_BASE;
304                 *offset += io_offset;
305                 res_bit = IORESOURCE_IO;
306         }
307
308         /*
309          * Check that the offset requested corresponds to one of the
310          * resources of the device.
311          */
312         for (i = 0; i <= PCI_ROM_RESOURCE; i++) {
313                 struct resource *rp = &dev->resource[i];
314                 int flags = rp->flags;
315
316                 /* treat ROM as memory (should be already) */
317                 if (i == PCI_ROM_RESOURCE)
318                         flags |= IORESOURCE_MEM;
319
320                 /* Active and same type? */
321                 if ((flags & res_bit) == 0)
322                         continue;
323
324                 /* In the range of this resource? */
325                 if (*offset < (rp->start & PAGE_MASK) || *offset > rp->end)
326                         continue;
327
328                 /* found it! construct the final physical address */
329                 if (mmap_state == pci_mmap_io)
330                         *offset += hose->io_base_phys - io_offset;
331                 return rp;
332         }
333
334         return NULL;
335 }
336
337 /*
338  * Set vm_page_prot of VMA, as appropriate for this architecture, for a pci
339  * device mapping.
340  */
341 static pgprot_t __pci_mmap_set_pgprot(struct pci_dev *dev, struct resource *rp,
342                                       pgprot_t protection,
343                                       enum pci_mmap_state mmap_state,
344                                       int write_combine)
345 {
346         pgprot_t prot = protection;
347
348         /* Write combine is always 0 on non-memory space mappings. On
349          * memory space, if the user didn't pass 1, we check for a
350          * "prefetchable" resource. This is a bit hackish, but we use
351          * this to workaround the inability of /sysfs to provide a write
352          * combine bit
353          */
354         if (mmap_state != pci_mmap_mem)
355                 write_combine = 0;
356         else if (write_combine == 0) {
357                 if (rp->flags & IORESOURCE_PREFETCH)
358                         write_combine = 1;
359         }
360
361         return pgprot_noncached(prot);
362 }
363
364 /*
365  * This one is used by /dev/mem and fbdev who have no clue about the
366  * PCI device, it tries to find the PCI device first and calls the
367  * above routine
368  */
369 pgprot_t pci_phys_mem_access_prot(struct file *file,
370                                   unsigned long pfn,
371                                   unsigned long size,
372                                   pgprot_t prot)
373 {
374         struct pci_dev *pdev = NULL;
375         struct resource *found = NULL;
376         resource_size_t offset = ((resource_size_t)pfn) << PAGE_SHIFT;
377         int i;
378
379         if (page_is_ram(pfn))
380                 return prot;
381
382         prot = pgprot_noncached(prot);
383         for_each_pci_dev(pdev) {
384                 for (i = 0; i <= PCI_ROM_RESOURCE; i++) {
385                         struct resource *rp = &pdev->resource[i];
386                         int flags = rp->flags;
387
388                         /* Active and same type? */
389                         if ((flags & IORESOURCE_MEM) == 0)
390                                 continue;
391                         /* In the range of this resource? */
392                         if (offset < (rp->start & PAGE_MASK) ||
393                             offset > rp->end)
394                                 continue;
395                         found = rp;
396                         break;
397                 }
398                 if (found)
399                         break;
400         }
401         if (found) {
402                 if (found->flags & IORESOURCE_PREFETCH)
403                         prot = pgprot_noncached_wc(prot);
404                 pci_dev_put(pdev);
405         }
406
407         pr_debug("PCI: Non-PCI map for %llx, prot: %lx\n",
408                  (unsigned long long)offset, pgprot_val(prot));
409
410         return prot;
411 }
412
413 /*
414  * Perform the actual remap of the pages for a PCI device mapping, as
415  * appropriate for this architecture.  The region in the process to map
416  * is described by vm_start and vm_end members of VMA, the base physical
417  * address is found in vm_pgoff.
418  * The pci device structure is provided so that architectures may make mapping
419  * decisions on a per-device or per-bus basis.
420  *
421  * Returns a negative error code on failure, zero on success.
422  */
423 int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma,
424                         enum pci_mmap_state mmap_state, int write_combine)
425 {
426         resource_size_t offset =
427                 ((resource_size_t)vma->vm_pgoff) << PAGE_SHIFT;
428         struct resource *rp;
429         int ret;
430
431         rp = __pci_mmap_make_offset(dev, &offset, mmap_state);
432         if (rp == NULL)
433                 return -EINVAL;
434
435         vma->vm_pgoff = offset >> PAGE_SHIFT;
436         vma->vm_page_prot = __pci_mmap_set_pgprot(dev, rp,
437                                                   vma->vm_page_prot,
438                                                   mmap_state, write_combine);
439
440         ret = remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
441                                vma->vm_end - vma->vm_start, vma->vm_page_prot);
442
443         return ret;
444 }
445
446 /* This provides legacy IO read access on a bus */
447 int pci_legacy_read(struct pci_bus *bus, loff_t port, u32 *val, size_t size)
448 {
449         unsigned long offset;
450         struct pci_controller *hose = pci_bus_to_host(bus);
451         struct resource *rp = &hose->io_resource;
452         void __iomem *addr;
453
454         /* Check if port can be supported by that bus. We only check
455          * the ranges of the PHB though, not the bus itself as the rules
456          * for forwarding legacy cycles down bridges are not our problem
457          * here. So if the host bridge supports it, we do it.
458          */
459         offset = (unsigned long)hose->io_base_virt - _IO_BASE;
460         offset += port;
461
462         if (!(rp->flags & IORESOURCE_IO))
463                 return -ENXIO;
464         if (offset < rp->start || (offset + size) > rp->end)
465                 return -ENXIO;
466         addr = hose->io_base_virt + port;
467
468         switch (size) {
469         case 1:
470                 *((u8 *)val) = in_8(addr);
471                 return 1;
472         case 2:
473                 if (port & 1)
474                         return -EINVAL;
475                 *((u16 *)val) = in_le16(addr);
476                 return 2;
477         case 4:
478                 if (port & 3)
479                         return -EINVAL;
480                 *((u32 *)val) = in_le32(addr);
481                 return 4;
482         }
483         return -EINVAL;
484 }
485
486 /* This provides legacy IO write access on a bus */
487 int pci_legacy_write(struct pci_bus *bus, loff_t port, u32 val, size_t size)
488 {
489         unsigned long offset;
490         struct pci_controller *hose = pci_bus_to_host(bus);
491         struct resource *rp = &hose->io_resource;
492         void __iomem *addr;
493
494         /* Check if port can be supported by that bus. We only check
495          * the ranges of the PHB though, not the bus itself as the rules
496          * for forwarding legacy cycles down bridges are not our problem
497          * here. So if the host bridge supports it, we do it.
498          */
499         offset = (unsigned long)hose->io_base_virt - _IO_BASE;
500         offset += port;
501
502         if (!(rp->flags & IORESOURCE_IO))
503                 return -ENXIO;
504         if (offset < rp->start || (offset + size) > rp->end)
505                 return -ENXIO;
506         addr = hose->io_base_virt + port;
507
508         /* WARNING: The generic code is idiotic. It gets passed a pointer
509          * to what can be a 1, 2 or 4 byte quantity and always reads that
510          * as a u32, which means that we have to correct the location of
511          * the data read within those 32 bits for size 1 and 2
512          */
513         switch (size) {
514         case 1:
515                 out_8(addr, val >> 24);
516                 return 1;
517         case 2:
518                 if (port & 1)
519                         return -EINVAL;
520                 out_le16(addr, val >> 16);
521                 return 2;
522         case 4:
523                 if (port & 3)
524                         return -EINVAL;
525                 out_le32(addr, val);
526                 return 4;
527         }
528         return -EINVAL;
529 }
530
531 /* This provides legacy IO or memory mmap access on a bus */
532 int pci_mmap_legacy_page_range(struct pci_bus *bus,
533                                struct vm_area_struct *vma,
534                                enum pci_mmap_state mmap_state)
535 {
536         struct pci_controller *hose = pci_bus_to_host(bus);
537         resource_size_t offset =
538                 ((resource_size_t)vma->vm_pgoff) << PAGE_SHIFT;
539         resource_size_t size = vma->vm_end - vma->vm_start;
540         struct resource *rp;
541
542         pr_debug("pci_mmap_legacy_page_range(%04x:%02x, %s @%llx..%llx)\n",
543                  pci_domain_nr(bus), bus->number,
544                  mmap_state == pci_mmap_mem ? "MEM" : "IO",
545                  (unsigned long long)offset,
546                  (unsigned long long)(offset + size - 1));
547
548         if (mmap_state == pci_mmap_mem) {
549                 /* Hack alert !
550                  *
551                  * Because X is lame and can fail starting if it gets an error
552                  * trying to mmap legacy_mem (instead of just moving on without
553                  * legacy memory access) we fake it here by giving it anonymous
554                  * memory, effectively behaving just like /dev/zero
555                  */
556                 if ((offset + size) > hose->isa_mem_size) {
557 #ifdef CONFIG_MMU
558                         printk(KERN_DEBUG
559                                 "Process %s (pid:%d) mapped non-existing PCI"
560                                 "legacy memory for 0%04x:%02x\n",
561                                 current->comm, current->pid, pci_domain_nr(bus),
562                                                                 bus->number);
563 #endif
564                         if (vma->vm_flags & VM_SHARED)
565                                 return shmem_zero_setup(vma);
566                         return 0;
567                 }
568                 offset += hose->isa_mem_phys;
569         } else {
570                 unsigned long io_offset = (unsigned long)hose->io_base_virt - \
571                                                                 _IO_BASE;
572                 unsigned long roffset = offset + io_offset;
573                 rp = &hose->io_resource;
574                 if (!(rp->flags & IORESOURCE_IO))
575                         return -ENXIO;
576                 if (roffset < rp->start || (roffset + size) > rp->end)
577                         return -ENXIO;
578                 offset += hose->io_base_phys;
579         }
580         pr_debug(" -> mapping phys %llx\n", (unsigned long long)offset);
581
582         vma->vm_pgoff = offset >> PAGE_SHIFT;
583         vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
584         return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
585                                vma->vm_end - vma->vm_start,
586                                vma->vm_page_prot);
587 }
588
589 void pci_resource_to_user(const struct pci_dev *dev, int bar,
590                           const struct resource *rsrc,
591                           resource_size_t *start, resource_size_t *end)
592 {
593         struct pci_controller *hose = pci_bus_to_host(dev->bus);
594         resource_size_t offset = 0;
595
596         if (hose == NULL)
597                 return;
598
599         if (rsrc->flags & IORESOURCE_IO)
600                 offset = (unsigned long)hose->io_base_virt - _IO_BASE;
601
602         /* We pass a fully fixed up address to userland for MMIO instead of
603          * a BAR value because X is lame and expects to be able to use that
604          * to pass to /dev/mem !
605          *
606          * That means that we'll have potentially 64 bits values where some
607          * userland apps only expect 32 (like X itself since it thinks only
608          * Sparc has 64 bits MMIO) but if we don't do that, we break it on
609          * 32 bits CHRPs :-(
610          *
611          * Hopefully, the sysfs insterface is immune to that gunk. Once X
612          * has been fixed (and the fix spread enough), we can re-enable the
613          * 2 lines below and pass down a BAR value to userland. In that case
614          * we'll also have to re-enable the matching code in
615          * __pci_mmap_make_offset().
616          *
617          * BenH.
618          */
619 #if 0
620         else if (rsrc->flags & IORESOURCE_MEM)
621                 offset = hose->pci_mem_offset;
622 #endif
623
624         *start = rsrc->start - offset;
625         *end = rsrc->end - offset;
626 }
627
628 /**
629  * pci_process_bridge_OF_ranges - Parse PCI bridge resources from device tree
630  * @hose: newly allocated pci_controller to be setup
631  * @dev: device node of the host bridge
632  * @primary: set if primary bus (32 bits only, soon to be deprecated)
633  *
634  * This function will parse the "ranges" property of a PCI host bridge device
635  * node and setup the resource mapping of a pci controller based on its
636  * content.
637  *
638  * Life would be boring if it wasn't for a few issues that we have to deal
639  * with here:
640  *
641  *   - We can only cope with one IO space range and up to 3 Memory space
642  *     ranges. However, some machines (thanks Apple !) tend to split their
643  *     space into lots of small contiguous ranges. So we have to coalesce.
644  *
645  *   - We can only cope with all memory ranges having the same offset
646  *     between CPU addresses and PCI addresses. Unfortunately, some bridges
647  *     are setup for a large 1:1 mapping along with a small "window" which
648  *     maps PCI address 0 to some arbitrary high address of the CPU space in
649  *     order to give access to the ISA memory hole.
650  *     The way out of here that I've chosen for now is to always set the
651  *     offset based on the first resource found, then override it if we
652  *     have a different offset and the previous was set by an ISA hole.
653  *
654  *   - Some busses have IO space not starting at 0, which causes trouble with
655  *     the way we do our IO resource renumbering. The code somewhat deals with
656  *     it for 64 bits but I would expect problems on 32 bits.
657  *
658  *   - Some 32 bits platforms such as 4xx can have physical space larger than
659  *     32 bits so we need to use 64 bits values for the parsing
660  */
661 void __devinit pci_process_bridge_OF_ranges(struct pci_controller *hose,
662                                             struct device_node *dev,
663                                             int primary)
664 {
665         const u32 *ranges;
666         int rlen;
667         int pna = of_n_addr_cells(dev);
668         int np = pna + 5;
669         int memno = 0, isa_hole = -1;
670         u32 pci_space;
671         unsigned long long pci_addr, cpu_addr, pci_next, cpu_next, size;
672         unsigned long long isa_mb = 0;
673         struct resource *res;
674
675         printk(KERN_INFO "PCI host bridge %s %s ranges:\n",
676                dev->full_name, primary ? "(primary)" : "");
677
678         /* Get ranges property */
679         ranges = of_get_property(dev, "ranges", &rlen);
680         if (ranges == NULL)
681                 return;
682
683         /* Parse it */
684         pr_debug("Parsing ranges property...\n");
685         while ((rlen -= np * 4) >= 0) {
686                 /* Read next ranges element */
687                 pci_space = ranges[0];
688                 pci_addr = of_read_number(ranges + 1, 2);
689                 cpu_addr = of_translate_address(dev, ranges + 3);
690                 size = of_read_number(ranges + pna + 3, 2);
691
692                 pr_debug("pci_space: 0x%08x pci_addr:0x%016llx "
693                                 "cpu_addr:0x%016llx size:0x%016llx\n",
694                                         pci_space, pci_addr, cpu_addr, size);
695
696                 ranges += np;
697
698                 /* If we failed translation or got a zero-sized region
699                  * (some FW try to feed us with non sensical zero sized regions
700                  * such as power3 which look like some kind of attempt
701                  * at exposing the VGA memory hole)
702                  */
703                 if (cpu_addr == OF_BAD_ADDR || size == 0)
704                         continue;
705
706                 /* Now consume following elements while they are contiguous */
707                 for (; rlen >= np * sizeof(u32);
708                      ranges += np, rlen -= np * 4) {
709                         if (ranges[0] != pci_space)
710                                 break;
711                         pci_next = of_read_number(ranges + 1, 2);
712                         cpu_next = of_translate_address(dev, ranges + 3);
713                         if (pci_next != pci_addr + size ||
714                             cpu_next != cpu_addr + size)
715                                 break;
716                         size += of_read_number(ranges + pna + 3, 2);
717                 }
718
719                 /* Act based on address space type */
720                 res = NULL;
721                 switch ((pci_space >> 24) & 0x3) {
722                 case 1:         /* PCI IO space */
723                         printk(KERN_INFO
724                                "  IO 0x%016llx..0x%016llx -> 0x%016llx\n",
725                                cpu_addr, cpu_addr + size - 1, pci_addr);
726
727                         /* We support only one IO range */
728                         if (hose->pci_io_size) {
729                                 printk(KERN_INFO
730                                        " \\--> Skipped (too many) !\n");
731                                 continue;
732                         }
733                         /* On 32 bits, limit I/O space to 16MB */
734                         if (size > 0x01000000)
735                                 size = 0x01000000;
736
737                         /* 32 bits needs to map IOs here */
738                         hose->io_base_virt = ioremap(cpu_addr, size);
739
740                         /* Expect trouble if pci_addr is not 0 */
741                         if (primary)
742                                 isa_io_base =
743                                         (unsigned long)hose->io_base_virt;
744                         /* pci_io_size and io_base_phys always represent IO
745                          * space starting at 0 so we factor in pci_addr
746                          */
747                         hose->pci_io_size = pci_addr + size;
748                         hose->io_base_phys = cpu_addr - pci_addr;
749
750                         /* Build resource */
751                         res = &hose->io_resource;
752                         res->flags = IORESOURCE_IO;
753                         res->start = pci_addr;
754                         break;
755                 case 2:         /* PCI Memory space */
756                 case 3:         /* PCI 64 bits Memory space */
757                         printk(KERN_INFO
758                                " MEM 0x%016llx..0x%016llx -> 0x%016llx %s\n",
759                                cpu_addr, cpu_addr + size - 1, pci_addr,
760                                (pci_space & 0x40000000) ? "Prefetch" : "");
761
762                         /* We support only 3 memory ranges */
763                         if (memno >= 3) {
764                                 printk(KERN_INFO
765                                        " \\--> Skipped (too many) !\n");
766                                 continue;
767                         }
768                         /* Handles ISA memory hole space here */
769                         if (pci_addr == 0) {
770                                 isa_mb = cpu_addr;
771                                 isa_hole = memno;
772                                 if (primary || isa_mem_base == 0)
773                                         isa_mem_base = cpu_addr;
774                                 hose->isa_mem_phys = cpu_addr;
775                                 hose->isa_mem_size = size;
776                         }
777
778                         /* We get the PCI/Mem offset from the first range or
779                          * the, current one if the offset came from an ISA
780                          * hole. If they don't match, bugger.
781                          */
782                         if (memno == 0 ||
783                             (isa_hole >= 0 && pci_addr != 0 &&
784                              hose->pci_mem_offset == isa_mb))
785                                 hose->pci_mem_offset = cpu_addr - pci_addr;
786                         else if (pci_addr != 0 &&
787                                  hose->pci_mem_offset != cpu_addr - pci_addr) {
788                                 printk(KERN_INFO
789                                        " \\--> Skipped (offset mismatch) !\n");
790                                 continue;
791                         }
792
793                         /* Build resource */
794                         res = &hose->mem_resources[memno++];
795                         res->flags = IORESOURCE_MEM;
796                         if (pci_space & 0x40000000)
797                                 res->flags |= IORESOURCE_PREFETCH;
798                         res->start = cpu_addr;
799                         break;
800                 }
801                 if (res != NULL) {
802                         res->name = dev->full_name;
803                         res->end = res->start + size - 1;
804                         res->parent = NULL;
805                         res->sibling = NULL;
806                         res->child = NULL;
807                 }
808         }
809
810         /* If there's an ISA hole and the pci_mem_offset is -not- matching
811          * the ISA hole offset, then we need to remove the ISA hole from
812          * the resource list for that brige
813          */
814         if (isa_hole >= 0 && hose->pci_mem_offset != isa_mb) {
815                 unsigned int next = isa_hole + 1;
816                 printk(KERN_INFO " Removing ISA hole at 0x%016llx\n", isa_mb);
817                 if (next < memno)
818                         memmove(&hose->mem_resources[isa_hole],
819                                 &hose->mem_resources[next],
820                                 sizeof(struct resource) * (memno - next));
821                 hose->mem_resources[--memno].flags = 0;
822         }
823 }
824
825 /* Decide whether to display the domain number in /proc */
826 int pci_proc_domain(struct pci_bus *bus)
827 {
828         struct pci_controller *hose = pci_bus_to_host(bus);
829
830         if (!(pci_flags & PCI_ENABLE_PROC_DOMAINS))
831                 return 0;
832         if (pci_flags & PCI_COMPAT_DOMAIN_0)
833                 return hose->global_number != 0;
834         return 1;
835 }
836
837 void pcibios_resource_to_bus(struct pci_dev *dev, struct pci_bus_region *region,
838                              struct resource *res)
839 {
840         resource_size_t offset = 0, mask = (resource_size_t)-1;
841         struct pci_controller *hose = pci_bus_to_host(dev->bus);
842
843         if (!hose)
844                 return;
845         if (res->flags & IORESOURCE_IO) {
846                 offset = (unsigned long)hose->io_base_virt - _IO_BASE;
847                 mask = 0xffffffffu;
848         } else if (res->flags & IORESOURCE_MEM)
849                 offset = hose->pci_mem_offset;
850
851         region->start = (res->start - offset) & mask;
852         region->end = (res->end - offset) & mask;
853 }
854 EXPORT_SYMBOL(pcibios_resource_to_bus);
855
856 void pcibios_bus_to_resource(struct pci_dev *dev, struct resource *res,
857                              struct pci_bus_region *region)
858 {
859         resource_size_t offset = 0, mask = (resource_size_t)-1;
860         struct pci_controller *hose = pci_bus_to_host(dev->bus);
861
862         if (!hose)
863                 return;
864         if (res->flags & IORESOURCE_IO) {
865                 offset = (unsigned long)hose->io_base_virt - _IO_BASE;
866                 mask = 0xffffffffu;
867         } else if (res->flags & IORESOURCE_MEM)
868                 offset = hose->pci_mem_offset;
869         res->start = (region->start + offset) & mask;
870         res->end = (region->end + offset) & mask;
871 }
872 EXPORT_SYMBOL(pcibios_bus_to_resource);
873
874 /* Fixup a bus resource into a linux resource */
875 static void __devinit fixup_resource(struct resource *res, struct pci_dev *dev)
876 {
877         struct pci_controller *hose = pci_bus_to_host(dev->bus);
878         resource_size_t offset = 0, mask = (resource_size_t)-1;
879
880         if (res->flags & IORESOURCE_IO) {
881                 offset = (unsigned long)hose->io_base_virt - _IO_BASE;
882                 mask = 0xffffffffu;
883         } else if (res->flags & IORESOURCE_MEM)
884                 offset = hose->pci_mem_offset;
885
886         res->start = (res->start + offset) & mask;
887         res->end = (res->end + offset) & mask;
888 }
889
890 /* This header fixup will do the resource fixup for all devices as they are
891  * probed, but not for bridge ranges
892  */
893 static void __devinit pcibios_fixup_resources(struct pci_dev *dev)
894 {
895         struct pci_controller *hose = pci_bus_to_host(dev->bus);
896         int i;
897
898         if (!hose) {
899                 printk(KERN_ERR "No host bridge for PCI dev %s !\n",
900                        pci_name(dev));
901                 return;
902         }
903         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
904                 struct resource *res = dev->resource + i;
905                 if (!res->flags)
906                         continue;
907                 /* On platforms that have PCI_PROBE_ONLY set, we don't
908                  * consider 0 as an unassigned BAR value. It's technically
909                  * a valid value, but linux doesn't like it... so when we can
910                  * re-assign things, we do so, but if we can't, we keep it
911                  * around and hope for the best...
912                  */
913                 if (res->start == 0 && !(pci_flags & PCI_PROBE_ONLY)) {
914                         pr_debug("PCI:%s Resource %d %016llx-%016llx [%x]" \
915                                                         "is unassigned\n",
916                                  pci_name(dev), i,
917                                  (unsigned long long)res->start,
918                                  (unsigned long long)res->end,
919                                  (unsigned int)res->flags);
920                         res->end -= res->start;
921                         res->start = 0;
922                         res->flags |= IORESOURCE_UNSET;
923                         continue;
924                 }
925
926                 pr_debug("PCI:%s Resource %d %016llx-%016llx [%x] fixup...\n",
927                          pci_name(dev), i,
928                          (unsigned long long)res->start,\
929                          (unsigned long long)res->end,
930                          (unsigned int)res->flags);
931
932                 fixup_resource(res, dev);
933
934                 pr_debug("PCI:%s            %016llx-%016llx\n",
935                          pci_name(dev),
936                          (unsigned long long)res->start,
937                          (unsigned long long)res->end);
938         }
939 }
940 DECLARE_PCI_FIXUP_HEADER(PCI_ANY_ID, PCI_ANY_ID, pcibios_fixup_resources);
941
942 /* This function tries to figure out if a bridge resource has been initialized
943  * by the firmware or not. It doesn't have to be absolutely bullet proof, but
944  * things go more smoothly when it gets it right. It should covers cases such
945  * as Apple "closed" bridge resources and bare-metal pSeries unassigned bridges
946  */
947 static int __devinit pcibios_uninitialized_bridge_resource(struct pci_bus *bus,
948                                                            struct resource *res)
949 {
950         struct pci_controller *hose = pci_bus_to_host(bus);
951         struct pci_dev *dev = bus->self;
952         resource_size_t offset;
953         u16 command;
954         int i;
955
956         /* We don't do anything if PCI_PROBE_ONLY is set */
957         if (pci_flags & PCI_PROBE_ONLY)
958                 return 0;
959
960         /* Job is a bit different between memory and IO */
961         if (res->flags & IORESOURCE_MEM) {
962                 /* If the BAR is non-0 (res != pci_mem_offset) then it's
963                  * probably been initialized by somebody
964                  */
965                 if (res->start != hose->pci_mem_offset)
966                         return 0;
967
968                 /* The BAR is 0, let's check if memory decoding is enabled on
969                  * the bridge. If not, we consider it unassigned
970                  */
971                 pci_read_config_word(dev, PCI_COMMAND, &command);
972                 if ((command & PCI_COMMAND_MEMORY) == 0)
973                         return 1;
974
975                 /* Memory decoding is enabled and the BAR is 0. If any of
976                  * the bridge resources covers that starting address (0 then
977                  * it's good enough for us for memory
978                  */
979                 for (i = 0; i < 3; i++) {
980                         if ((hose->mem_resources[i].flags & IORESOURCE_MEM) &&
981                            hose->mem_resources[i].start == hose->pci_mem_offset)
982                                 return 0;
983                 }
984
985                 /* Well, it starts at 0 and we know it will collide so we may as
986                  * well consider it as unassigned. That covers the Apple case.
987                  */
988                 return 1;
989         } else {
990                 /* If the BAR is non-0, then we consider it assigned */
991                 offset = (unsigned long)hose->io_base_virt - _IO_BASE;
992                 if (((res->start - offset) & 0xfffffffful) != 0)
993                         return 0;
994
995                 /* Here, we are a bit different than memory as typically IO
996                  * space starting at low addresses -is- valid. What we do
997                  * instead if that we consider as unassigned anything that
998                  * doesn't have IO enabled in the PCI command register,
999                  * and that's it.
1000                  */
1001                 pci_read_config_word(dev, PCI_COMMAND, &command);
1002                 if (command & PCI_COMMAND_IO)
1003                         return 0;
1004
1005                 /* It's starting at 0 and IO is disabled in the bridge, consider
1006                  * it unassigned
1007                  */
1008                 return 1;
1009         }
1010 }
1011
1012 /* Fixup resources of a PCI<->PCI bridge */
1013 static void __devinit pcibios_fixup_bridge(struct pci_bus *bus)
1014 {
1015         struct resource *res;
1016         int i;
1017
1018         struct pci_dev *dev = bus->self;
1019
1020         pci_bus_for_each_resource(bus, res, i) {
1021                 res = bus->resource[i];
1022                 if (!res)
1023                         continue;
1024                 if (!res->flags)
1025                         continue;
1026                 if (i >= 3 && bus->self->transparent)
1027                         continue;
1028
1029                 pr_debug("PCI:%s Bus rsrc %d %016llx-%016llx [%x] fixup...\n",
1030                          pci_name(dev), i,
1031                          (unsigned long long)res->start,\
1032                          (unsigned long long)res->end,
1033                          (unsigned int)res->flags);
1034
1035                 /* Perform fixup */
1036                 fixup_resource(res, dev);
1037
1038                 /* Try to detect uninitialized P2P bridge resources,
1039                  * and clear them out so they get re-assigned later
1040                  */
1041                 if (pcibios_uninitialized_bridge_resource(bus, res)) {
1042                         res->flags = 0;
1043                         pr_debug("PCI:%s            (unassigned)\n",
1044                                                                 pci_name(dev));
1045                 } else {
1046                         pr_debug("PCI:%s            %016llx-%016llx\n",
1047                                  pci_name(dev),
1048                                  (unsigned long long)res->start,
1049                                  (unsigned long long)res->end);
1050                 }
1051         }
1052 }
1053
1054 void __devinit pcibios_setup_bus_self(struct pci_bus *bus)
1055 {
1056         /* Fix up the bus resources for P2P bridges */
1057         if (bus->self != NULL)
1058                 pcibios_fixup_bridge(bus);
1059 }
1060
1061 void __devinit pcibios_setup_bus_devices(struct pci_bus *bus)
1062 {
1063         struct pci_dev *dev;
1064
1065         pr_debug("PCI: Fixup bus devices %d (%s)\n",
1066                  bus->number, bus->self ? pci_name(bus->self) : "PHB");
1067
1068         list_for_each_entry(dev, &bus->devices, bus_list) {
1069                 /* Setup OF node pointer in archdata */
1070                 dev->dev.of_node = pci_device_to_OF_node(dev);
1071
1072                 /* Fixup NUMA node as it may not be setup yet by the generic
1073                  * code and is needed by the DMA init
1074                  */
1075                 set_dev_node(&dev->dev, pcibus_to_node(dev->bus));
1076
1077                 /* Hook up default DMA ops */
1078                 set_dma_ops(&dev->dev, pci_dma_ops);
1079                 dev->dev.archdata.dma_data = (void *)PCI_DRAM_OFFSET;
1080
1081                 /* Read default IRQs and fixup if necessary */
1082                 pci_read_irq_line(dev);
1083         }
1084 }
1085
1086 void __devinit pcibios_fixup_bus(struct pci_bus *bus)
1087 {
1088         /* When called from the generic PCI probe, read PCI<->PCI bridge
1089          * bases. This is -not- called when generating the PCI tree from
1090          * the OF device-tree.
1091          */
1092         if (bus->self != NULL)
1093                 pci_read_bridge_bases(bus);
1094
1095         /* Now fixup the bus bus */
1096         pcibios_setup_bus_self(bus);
1097
1098         /* Now fixup devices on that bus */
1099         pcibios_setup_bus_devices(bus);
1100 }
1101 EXPORT_SYMBOL(pcibios_fixup_bus);
1102
1103 static int skip_isa_ioresource_align(struct pci_dev *dev)
1104 {
1105         if ((pci_flags & PCI_CAN_SKIP_ISA_ALIGN) &&
1106             !(dev->bus->bridge_ctl & PCI_BRIDGE_CTL_ISA))
1107                 return 1;
1108         return 0;
1109 }
1110
1111 /*
1112  * We need to avoid collisions with `mirrored' VGA ports
1113  * and other strange ISA hardware, so we always want the
1114  * addresses to be allocated in the 0x000-0x0ff region
1115  * modulo 0x400.
1116  *
1117  * Why? Because some silly external IO cards only decode
1118  * the low 10 bits of the IO address. The 0x00-0xff region
1119  * is reserved for motherboard devices that decode all 16
1120  * bits, so it's ok to allocate at, say, 0x2800-0x28ff,
1121  * but we want to try to avoid allocating at 0x2900-0x2bff
1122  * which might have be mirrored at 0x0100-0x03ff..
1123  */
1124 resource_size_t pcibios_align_resource(void *data, const struct resource *res,
1125                                 resource_size_t size, resource_size_t align)
1126 {
1127         struct pci_dev *dev = data;
1128         resource_size_t start = res->start;
1129
1130         if (res->flags & IORESOURCE_IO) {
1131                 if (skip_isa_ioresource_align(dev))
1132                         return start;
1133                 if (start & 0x300)
1134                         start = (start + 0x3ff) & ~0x3ff;
1135         }
1136
1137         return start;
1138 }
1139 EXPORT_SYMBOL(pcibios_align_resource);
1140
1141 /*
1142  * Reparent resource children of pr that conflict with res
1143  * under res, and make res replace those children.
1144  */
1145 static int __init reparent_resources(struct resource *parent,
1146                                      struct resource *res)
1147 {
1148         struct resource *p, **pp;
1149         struct resource **firstpp = NULL;
1150
1151         for (pp = &parent->child; (p = *pp) != NULL; pp = &p->sibling) {
1152                 if (p->end < res->start)
1153                         continue;
1154                 if (res->end < p->start)
1155                         break;
1156                 if (p->start < res->start || p->end > res->end)
1157                         return -1;      /* not completely contained */
1158                 if (firstpp == NULL)
1159                         firstpp = pp;
1160         }
1161         if (firstpp == NULL)
1162                 return -1;      /* didn't find any conflicting entries? */
1163         res->parent = parent;
1164         res->child = *firstpp;
1165         res->sibling = *pp;
1166         *firstpp = res;
1167         *pp = NULL;
1168         for (p = res->child; p != NULL; p = p->sibling) {
1169                 p->parent = res;
1170                 pr_debug("PCI: Reparented %s [%llx..%llx] under %s\n",
1171                          p->name,
1172                          (unsigned long long)p->start,
1173                          (unsigned long long)p->end, res->name);
1174         }
1175         return 0;
1176 }
1177
1178 /*
1179  *  Handle resources of PCI devices.  If the world were perfect, we could
1180  *  just allocate all the resource regions and do nothing more.  It isn't.
1181  *  On the other hand, we cannot just re-allocate all devices, as it would
1182  *  require us to know lots of host bridge internals.  So we attempt to
1183  *  keep as much of the original configuration as possible, but tweak it
1184  *  when it's found to be wrong.
1185  *
1186  *  Known BIOS problems we have to work around:
1187  *      - I/O or memory regions not configured
1188  *      - regions configured, but not enabled in the command register
1189  *      - bogus I/O addresses above 64K used
1190  *      - expansion ROMs left enabled (this may sound harmless, but given
1191  *        the fact the PCI specs explicitly allow address decoders to be
1192  *        shared between expansion ROMs and other resource regions, it's
1193  *        at least dangerous)
1194  *
1195  *  Our solution:
1196  *      (1) Allocate resources for all buses behind PCI-to-PCI bridges.
1197  *          This gives us fixed barriers on where we can allocate.
1198  *      (2) Allocate resources for all enabled devices.  If there is
1199  *          a collision, just mark the resource as unallocated. Also
1200  *          disable expansion ROMs during this step.
1201  *      (3) Try to allocate resources for disabled devices.  If the
1202  *          resources were assigned correctly, everything goes well,
1203  *          if they weren't, they won't disturb allocation of other
1204  *          resources.
1205  *      (4) Assign new addresses to resources which were either
1206  *          not configured at all or misconfigured.  If explicitly
1207  *          requested by the user, configure expansion ROM address
1208  *          as well.
1209  */
1210
1211 void pcibios_allocate_bus_resources(struct pci_bus *bus)
1212 {
1213         struct pci_bus *b;
1214         int i;
1215         struct resource *res, *pr;
1216
1217         pr_debug("PCI: Allocating bus resources for %04x:%02x...\n",
1218                  pci_domain_nr(bus), bus->number);
1219
1220         pci_bus_for_each_resource(bus, res, i) {
1221                 res = bus->resource[i];
1222                 if (!res || !res->flags
1223                     || res->start > res->end || res->parent)
1224                         continue;
1225                 if (bus->parent == NULL)
1226                         pr = (res->flags & IORESOURCE_IO) ?
1227                                 &ioport_resource : &iomem_resource;
1228                 else {
1229                         /* Don't bother with non-root busses when
1230                          * re-assigning all resources. We clear the
1231                          * resource flags as if they were colliding
1232                          * and as such ensure proper re-allocation
1233                          * later.
1234                          */
1235                         if (pci_flags & PCI_REASSIGN_ALL_RSRC)
1236                                 goto clear_resource;
1237                         pr = pci_find_parent_resource(bus->self, res);
1238                         if (pr == res) {
1239                                 /* this happens when the generic PCI
1240                                  * code (wrongly) decides that this
1241                                  * bridge is transparent  -- paulus
1242                                  */
1243                                 continue;
1244                         }
1245                 }
1246
1247                 pr_debug("PCI: %s (bus %d) bridge rsrc %d: %016llx-%016llx "
1248                          "[0x%x], parent %p (%s)\n",
1249                          bus->self ? pci_name(bus->self) : "PHB",
1250                          bus->number, i,
1251                          (unsigned long long)res->start,
1252                          (unsigned long long)res->end,
1253                          (unsigned int)res->flags,
1254                          pr, (pr && pr->name) ? pr->name : "nil");
1255
1256                 if (pr && !(pr->flags & IORESOURCE_UNSET)) {
1257                         if (request_resource(pr, res) == 0)
1258                                 continue;
1259                         /*
1260                          * Must be a conflict with an existing entry.
1261                          * Move that entry (or entries) under the
1262                          * bridge resource and try again.
1263                          */
1264                         if (reparent_resources(pr, res) == 0)
1265                                 continue;
1266                 }
1267                 printk(KERN_WARNING "PCI: Cannot allocate resource region "
1268                        "%d of PCI bridge %d, will remap\n", i, bus->number);
1269 clear_resource:
1270                 res->start = res->end = 0;
1271                 res->flags = 0;
1272         }
1273
1274         list_for_each_entry(b, &bus->children, node)
1275                 pcibios_allocate_bus_resources(b);
1276 }
1277
1278 static inline void __devinit alloc_resource(struct pci_dev *dev, int idx)
1279 {
1280         struct resource *pr, *r = &dev->resource[idx];
1281
1282         pr_debug("PCI: Allocating %s: Resource %d: %016llx..%016llx [%x]\n",
1283                  pci_name(dev), idx,
1284                  (unsigned long long)r->start,
1285                  (unsigned long long)r->end,
1286                  (unsigned int)r->flags);
1287
1288         pr = pci_find_parent_resource(dev, r);
1289         if (!pr || (pr->flags & IORESOURCE_UNSET) ||
1290             request_resource(pr, r) < 0) {
1291                 printk(KERN_WARNING "PCI: Cannot allocate resource region %d"
1292                        " of device %s, will remap\n", idx, pci_name(dev));
1293                 if (pr)
1294                         pr_debug("PCI:  parent is %p: %016llx-%016llx [%x]\n",
1295                                  pr,
1296                                  (unsigned long long)pr->start,
1297                                  (unsigned long long)pr->end,
1298                                  (unsigned int)pr->flags);
1299                 /* We'll assign a new address later */
1300                 r->flags |= IORESOURCE_UNSET;
1301                 r->end -= r->start;
1302                 r->start = 0;
1303         }
1304 }
1305
1306 static void __init pcibios_allocate_resources(int pass)
1307 {
1308         struct pci_dev *dev = NULL;
1309         int idx, disabled;
1310         u16 command;
1311         struct resource *r;
1312
1313         for_each_pci_dev(dev) {
1314                 pci_read_config_word(dev, PCI_COMMAND, &command);
1315                 for (idx = 0; idx <= PCI_ROM_RESOURCE; idx++) {
1316                         r = &dev->resource[idx];
1317                         if (r->parent)          /* Already allocated */
1318                                 continue;
1319                         if (!r->flags || (r->flags & IORESOURCE_UNSET))
1320                                 continue;       /* Not assigned at all */
1321                         /* We only allocate ROMs on pass 1 just in case they
1322                          * have been screwed up by firmware
1323                          */
1324                         if (idx == PCI_ROM_RESOURCE)
1325                                 disabled = 1;
1326                         if (r->flags & IORESOURCE_IO)
1327                                 disabled = !(command & PCI_COMMAND_IO);
1328                         else
1329                                 disabled = !(command & PCI_COMMAND_MEMORY);
1330                         if (pass == disabled)
1331                                 alloc_resource(dev, idx);
1332                 }
1333                 if (pass)
1334                         continue;
1335                 r = &dev->resource[PCI_ROM_RESOURCE];
1336                 if (r->flags) {
1337                         /* Turn the ROM off, leave the resource region,
1338                          * but keep it unregistered.
1339                          */
1340                         u32 reg;
1341                         pci_read_config_dword(dev, dev->rom_base_reg, &reg);
1342                         if (reg & PCI_ROM_ADDRESS_ENABLE) {
1343                                 pr_debug("PCI: Switching off ROM of %s\n",
1344                                          pci_name(dev));
1345                                 r->flags &= ~IORESOURCE_ROM_ENABLE;
1346                                 pci_write_config_dword(dev, dev->rom_base_reg,
1347                                                 reg & ~PCI_ROM_ADDRESS_ENABLE);
1348                         }
1349                 }
1350         }
1351 }
1352
1353 static void __init pcibios_reserve_legacy_regions(struct pci_bus *bus)
1354 {
1355         struct pci_controller *hose = pci_bus_to_host(bus);
1356         resource_size_t offset;
1357         struct resource *res, *pres;
1358         int i;
1359
1360         pr_debug("Reserving legacy ranges for domain %04x\n",
1361                                                         pci_domain_nr(bus));
1362
1363         /* Check for IO */
1364         if (!(hose->io_resource.flags & IORESOURCE_IO))
1365                 goto no_io;
1366         offset = (unsigned long)hose->io_base_virt - _IO_BASE;
1367         res = kzalloc(sizeof(struct resource), GFP_KERNEL);
1368         BUG_ON(res == NULL);
1369         res->name = "Legacy IO";
1370         res->flags = IORESOURCE_IO;
1371         res->start = offset;
1372         res->end = (offset + 0xfff) & 0xfffffffful;
1373         pr_debug("Candidate legacy IO: %pR\n", res);
1374         if (request_resource(&hose->io_resource, res)) {
1375                 printk(KERN_DEBUG
1376                        "PCI %04x:%02x Cannot reserve Legacy IO %pR\n",
1377                        pci_domain_nr(bus), bus->number, res);
1378                 kfree(res);
1379         }
1380
1381  no_io:
1382         /* Check for memory */
1383         offset = hose->pci_mem_offset;
1384         pr_debug("hose mem offset: %016llx\n", (unsigned long long)offset);
1385         for (i = 0; i < 3; i++) {
1386                 pres = &hose->mem_resources[i];
1387                 if (!(pres->flags & IORESOURCE_MEM))
1388                         continue;
1389                 pr_debug("hose mem res: %pR\n", pres);
1390                 if ((pres->start - offset) <= 0xa0000 &&
1391                     (pres->end - offset) >= 0xbffff)
1392                         break;
1393         }
1394         if (i >= 3)
1395                 return;
1396         res = kzalloc(sizeof(struct resource), GFP_KERNEL);
1397         BUG_ON(res == NULL);
1398         res->name = "Legacy VGA memory";
1399         res->flags = IORESOURCE_MEM;
1400         res->start = 0xa0000 + offset;
1401         res->end = 0xbffff + offset;
1402         pr_debug("Candidate VGA memory: %pR\n", res);
1403         if (request_resource(pres, res)) {
1404                 printk(KERN_DEBUG
1405                        "PCI %04x:%02x Cannot reserve VGA memory %pR\n",
1406                        pci_domain_nr(bus), bus->number, res);
1407                 kfree(res);
1408         }
1409 }
1410
1411 void __init pcibios_resource_survey(void)
1412 {
1413         struct pci_bus *b;
1414
1415         /* Allocate and assign resources. If we re-assign everything, then
1416          * we skip the allocate phase
1417          */
1418         list_for_each_entry(b, &pci_root_buses, node)
1419                 pcibios_allocate_bus_resources(b);
1420
1421         if (!(pci_flags & PCI_REASSIGN_ALL_RSRC)) {
1422                 pcibios_allocate_resources(0);
1423                 pcibios_allocate_resources(1);
1424         }
1425
1426         /* Before we start assigning unassigned resource, we try to reserve
1427          * the low IO area and the VGA memory area if they intersect the
1428          * bus available resources to avoid allocating things on top of them
1429          */
1430         if (!(pci_flags & PCI_PROBE_ONLY)) {
1431                 list_for_each_entry(b, &pci_root_buses, node)
1432                         pcibios_reserve_legacy_regions(b);
1433         }
1434
1435         /* Now, if the platform didn't decide to blindly trust the firmware,
1436          * we proceed to assigning things that were left unassigned
1437          */
1438         if (!(pci_flags & PCI_PROBE_ONLY)) {
1439                 pr_debug("PCI: Assigning unassigned resources...\n");
1440                 pci_assign_unassigned_resources();
1441         }
1442 }
1443
1444 #ifdef CONFIG_HOTPLUG
1445
1446 /* This is used by the PCI hotplug driver to allocate resource
1447  * of newly plugged busses. We can try to consolidate with the
1448  * rest of the code later, for now, keep it as-is as our main
1449  * resource allocation function doesn't deal with sub-trees yet.
1450  */
1451 void __devinit pcibios_claim_one_bus(struct pci_bus *bus)
1452 {
1453         struct pci_dev *dev;
1454         struct pci_bus *child_bus;
1455
1456         list_for_each_entry(dev, &bus->devices, bus_list) {
1457                 int i;
1458
1459                 for (i = 0; i < PCI_NUM_RESOURCES; i++) {
1460                         struct resource *r = &dev->resource[i];
1461
1462                         if (r->parent || !r->start || !r->flags)
1463                                 continue;
1464
1465                         pr_debug("PCI: Claiming %s: "
1466                                  "Resource %d: %016llx..%016llx [%x]\n",
1467                                  pci_name(dev), i,
1468                                  (unsigned long long)r->start,
1469                                  (unsigned long long)r->end,
1470                                  (unsigned int)r->flags);
1471
1472                         pci_claim_resource(dev, i);
1473                 }
1474         }
1475
1476         list_for_each_entry(child_bus, &bus->children, node)
1477                 pcibios_claim_one_bus(child_bus);
1478 }
1479 EXPORT_SYMBOL_GPL(pcibios_claim_one_bus);
1480
1481
1482 /* pcibios_finish_adding_to_bus
1483  *
1484  * This is to be called by the hotplug code after devices have been
1485  * added to a bus, this include calling it for a PHB that is just
1486  * being added
1487  */
1488 void pcibios_finish_adding_to_bus(struct pci_bus *bus)
1489 {
1490         pr_debug("PCI: Finishing adding to hotplug bus %04x:%02x\n",
1491                  pci_domain_nr(bus), bus->number);
1492
1493         /* Allocate bus and devices resources */
1494         pcibios_allocate_bus_resources(bus);
1495         pcibios_claim_one_bus(bus);
1496
1497         /* Add new devices to global lists.  Register in proc, sysfs. */
1498         pci_bus_add_devices(bus);
1499
1500         /* Fixup EEH */
1501         /* eeh_add_device_tree_late(bus); */
1502 }
1503 EXPORT_SYMBOL_GPL(pcibios_finish_adding_to_bus);
1504
1505 #endif /* CONFIG_HOTPLUG */
1506
1507 int pcibios_enable_device(struct pci_dev *dev, int mask)
1508 {
1509         return pci_enable_resources(dev, mask);
1510 }
1511
1512 void __devinit pcibios_setup_phb_resources(struct pci_controller *hose)
1513 {
1514         struct pci_bus *bus = hose->bus;
1515         struct resource *res;
1516         int i;
1517
1518         /* Hookup PHB IO resource */
1519         bus->resource[0] = res = &hose->io_resource;
1520
1521         if (!res->flags) {
1522                 printk(KERN_WARNING "PCI: I/O resource not set for host"
1523                        " bridge %s (domain %d)\n",
1524                        hose->dn->full_name, hose->global_number);
1525                 /* Workaround for lack of IO resource only on 32-bit */
1526                 res->start = (unsigned long)hose->io_base_virt - isa_io_base;
1527                 res->end = res->start + IO_SPACE_LIMIT;
1528                 res->flags = IORESOURCE_IO;
1529         }
1530
1531         pr_debug("PCI: PHB IO resource    = %016llx-%016llx [%lx]\n",
1532                  (unsigned long long)res->start,
1533                  (unsigned long long)res->end,
1534                  (unsigned long)res->flags);
1535
1536         /* Hookup PHB Memory resources */
1537         for (i = 0; i < 3; ++i) {
1538                 res = &hose->mem_resources[i];
1539                 if (!res->flags) {
1540                         if (i > 0)
1541                                 continue;
1542                         printk(KERN_ERR "PCI: Memory resource 0 not set for "
1543                                "host bridge %s (domain %d)\n",
1544                                hose->dn->full_name, hose->global_number);
1545
1546                         /* Workaround for lack of MEM resource only on 32-bit */
1547                         res->start = hose->pci_mem_offset;
1548                         res->end = (resource_size_t)-1LL;
1549                         res->flags = IORESOURCE_MEM;
1550
1551                 }
1552                 bus->resource[i+1] = res;
1553
1554                 pr_debug("PCI: PHB MEM resource %d = %016llx-%016llx [%lx]\n",
1555                         i, (unsigned long long)res->start,
1556                         (unsigned long long)res->end,
1557                         (unsigned long)res->flags);
1558         }
1559
1560         pr_debug("PCI: PHB MEM offset     = %016llx\n",
1561                  (unsigned long long)hose->pci_mem_offset);
1562         pr_debug("PCI: PHB IO  offset     = %08lx\n",
1563                  (unsigned long)hose->io_base_virt - _IO_BASE);
1564 }
1565
1566 struct device_node *pcibios_get_phb_of_node(struct pci_bus *bus)
1567 {
1568         struct pci_controller *hose = bus->sysdata;
1569
1570         return of_node_get(hose->dn);
1571 }
1572
1573 static void __devinit pcibios_scan_phb(struct pci_controller *hose)
1574 {
1575         struct pci_bus *bus;
1576         struct device_node *node = hose->dn;
1577         unsigned long io_offset;
1578         struct resource *res = &hose->io_resource;
1579
1580         pr_debug("PCI: Scanning PHB %s\n",
1581                  node ? node->full_name : "<NO NAME>");
1582
1583         /* Create an empty bus for the toplevel */
1584         bus = pci_create_bus(hose->parent, hose->first_busno, hose->ops, hose);
1585         if (bus == NULL) {
1586                 printk(KERN_ERR "Failed to create bus for PCI domain %04x\n",
1587                        hose->global_number);
1588                 return;
1589         }
1590         bus->secondary = hose->first_busno;
1591         hose->bus = bus;
1592
1593         /* Fixup IO space offset */
1594         io_offset = (unsigned long)hose->io_base_virt - isa_io_base;
1595         res->start = (res->start + io_offset) & 0xffffffffu;
1596         res->end = (res->end + io_offset) & 0xffffffffu;
1597
1598         /* Wire up PHB bus resources */
1599         pcibios_setup_phb_resources(hose);
1600
1601         /* Scan children */
1602         hose->last_busno = bus->subordinate = pci_scan_child_bus(bus);
1603 }
1604
1605 static int __init pcibios_init(void)
1606 {
1607         struct pci_controller *hose, *tmp;
1608         int next_busno = 0;
1609
1610         printk(KERN_INFO "PCI: Probing PCI hardware\n");
1611
1612         /* Scan all of the recorded PCI controllers.  */
1613         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
1614                 hose->last_busno = 0xff;
1615                 pcibios_scan_phb(hose);
1616                 printk(KERN_INFO "calling pci_bus_add_devices()\n");
1617                 pci_bus_add_devices(hose->bus);
1618                 if (next_busno <= hose->last_busno)
1619                         next_busno = hose->last_busno + 1;
1620         }
1621         pci_bus_count = next_busno;
1622
1623         /* Call common code to handle resource allocation */
1624         pcibios_resource_survey();
1625
1626         return 0;
1627 }
1628
1629 subsys_initcall(pcibios_init);
1630
1631 static struct pci_controller *pci_bus_to_hose(int bus)
1632 {
1633         struct pci_controller *hose, *tmp;
1634
1635         list_for_each_entry_safe(hose, tmp, &hose_list, list_node)
1636                 if (bus >= hose->first_busno && bus <= hose->last_busno)
1637                         return hose;
1638         return NULL;
1639 }
1640
1641 /* Provide information on locations of various I/O regions in physical
1642  * memory.  Do this on a per-card basis so that we choose the right
1643  * root bridge.
1644  * Note that the returned IO or memory base is a physical address
1645  */
1646
1647 long sys_pciconfig_iobase(long which, unsigned long bus, unsigned long devfn)
1648 {
1649         struct pci_controller *hose;
1650         long result = -EOPNOTSUPP;
1651
1652         hose = pci_bus_to_hose(bus);
1653         if (!hose)
1654                 return -ENODEV;
1655
1656         switch (which) {
1657         case IOBASE_BRIDGE_NUMBER:
1658                 return (long)hose->first_busno;
1659         case IOBASE_MEMORY:
1660                 return (long)hose->pci_mem_offset;
1661         case IOBASE_IO:
1662                 return (long)hose->io_base_phys;
1663         case IOBASE_ISA_IO:
1664                 return (long)isa_io_base;
1665         case IOBASE_ISA_MEM:
1666                 return (long)isa_mem_base;
1667         }
1668
1669         return result;
1670 }
1671
1672 /*
1673  * Null PCI config access functions, for the case when we can't
1674  * find a hose.
1675  */
1676 #define NULL_PCI_OP(rw, size, type)                                     \
1677 static int                                                              \
1678 null_##rw##_config_##size(struct pci_dev *dev, int offset, type val)    \
1679 {                                                                       \
1680         return PCIBIOS_DEVICE_NOT_FOUND;                                \
1681 }
1682
1683 static int
1684 null_read_config(struct pci_bus *bus, unsigned int devfn, int offset,
1685                  int len, u32 *val)
1686 {
1687         return PCIBIOS_DEVICE_NOT_FOUND;
1688 }
1689
1690 static int
1691 null_write_config(struct pci_bus *bus, unsigned int devfn, int offset,
1692                   int len, u32 val)
1693 {
1694         return PCIBIOS_DEVICE_NOT_FOUND;
1695 }
1696
1697 static struct pci_ops null_pci_ops = {
1698         .read = null_read_config,
1699         .write = null_write_config,
1700 };
1701
1702 /*
1703  * These functions are used early on before PCI scanning is done
1704  * and all of the pci_dev and pci_bus structures have been created.
1705  */
1706 static struct pci_bus *
1707 fake_pci_bus(struct pci_controller *hose, int busnr)
1708 {
1709         static struct pci_bus bus;
1710
1711         if (!hose)
1712                 printk(KERN_ERR "Can't find hose for PCI bus %d!\n", busnr);
1713
1714         bus.number = busnr;
1715         bus.sysdata = hose;
1716         bus.ops = hose ? hose->ops : &null_pci_ops;
1717         return &bus;
1718 }
1719
1720 #define EARLY_PCI_OP(rw, size, type)                                    \
1721 int early_##rw##_config_##size(struct pci_controller *hose, int bus,    \
1722                                int devfn, int offset, type value)       \
1723 {                                                                       \
1724         return pci_bus_##rw##_config_##size(fake_pci_bus(hose, bus),    \
1725                                             devfn, offset, value);      \
1726 }
1727
1728 EARLY_PCI_OP(read, byte, u8 *)
1729 EARLY_PCI_OP(read, word, u16 *)
1730 EARLY_PCI_OP(read, dword, u32 *)
1731 EARLY_PCI_OP(write, byte, u8)
1732 EARLY_PCI_OP(write, word, u16)
1733 EARLY_PCI_OP(write, dword, u32)
1734
1735 int early_find_capability(struct pci_controller *hose, int bus, int devfn,
1736                           int cap)
1737 {
1738         return pci_bus_find_capability(fake_pci_bus(hose, bus), devfn, cap);
1739 }
1740