1/*
2 *
3 *
4 * Port for PPC64 David Engebretsen, IBM Corp.
5 *   Contains common pci routines for ppc64 platform, pSeries and iSeries brands.
6 *
7 *      This program is free software; you can redistribute it and/or
8 *      modify it under the terms of the GNU General Public License
9 *      as published by the Free Software Foundation; either version
10 *      2 of the License, or (at your option) any later version.
11 */
12
13#include <linux/config.h>
14#include <linux/kernel.h>
15#include <linux/pci.h>
16#include <linux/delay.h>
17#include <linux/string.h>
18#include <linux/init.h>
19#include <linux/capability.h>
20#include <linux/sched.h>
21#include <linux/errno.h>
22#include <linux/bootmem.h>
23
24#include <asm/processor.h>
25#include <asm/io.h>
26#include <asm/prom.h>
27#include <asm/pci-bridge.h>
28#include <asm/byteorder.h>
29#include <asm/irq.h>
30#include <asm/uaccess.h>
31#include <asm/flight_recorder.h>
32#include <asm/ppcdebug.h>
33#include <asm/naca.h>
34#include <asm/pci_dma.h>
35#include <asm/machdep.h>
36#include <asm/eeh.h>
37
38#include "pci.h"
39
40/* pci_io_base -- the base address from which io bars are offsets.
41 * This is the lowest I/O base address (so bar values are always positive),
42 * and it *must* be the start of ISA space if an ISA bus exists because
43 * ISA drivers use hard coded offsets.  If no ISA bus exists a dummy
44 * page is mapped and isa_io_limit prevents access to it.
45 */
46unsigned long isa_io_base     = 0;	/* NULL if no ISA bus */
47unsigned long pci_io_base     = 0;
48unsigned long isa_mem_base    = 0;
49unsigned long pci_dram_offset = 0;
50
51/******************************************************************
52 * Forward declare of prototypes
53 ******************************************************************/
54static void pcibios_fixup_resources(struct pci_dev* dev);
55static void fixup_broken_pcnet32(struct pci_dev* dev);
56static void fixup_windbond_82c105(struct pci_dev* dev);
57void        fixup_resources(struct pci_dev* dev);
58
59void   iSeries_pcibios_init(void);
60void   pSeries_pcibios_init(void);
61
62int    pci_assign_all_busses = 0;
63struct pci_controller* hose_head;
64struct pci_controller** hose_tail = &hose_head;
65
66LIST_HEAD(iSeries_Global_Device_List);
67
68/*******************************************************************
69 * Counters and control flags.
70 *******************************************************************/
71long   Pci_Io_Read_Count  = 0;
72long   Pci_Io_Write_Count = 0;
73long   Pci_Cfg_Read_Count = 0;
74long   Pci_Cfg_Write_Count= 0;
75long   Pci_Error_Count    = 0;
76
77int    Pci_Retry_Max      = 7;	/* Retry set to 7 times  */
78int    Pci_Error_Flag     = 1;	/* Set Retry Error on. */
79int    Pci_Trace_Flag     = 0;
80
81/******************************************************************
82 *
83 ******************************************************************/
84int  global_phb_number    = 0;           /* Global phb counter    */
85int  Pci_Large_Bus_System = 0;
86int  Pci_Set_IOA_Address  = 0;
87int  Pci_Manage_Phb_Space = 0;
88struct pci_controller *phbtab[PCI_MAX_PHB];
89
90static int pci_bus_count;
91
92/* Cached ISA bridge dev. */
93struct pci_dev *ppc64_isabridge_dev = NULL;
94
95struct pci_fixup pcibios_fixups[] = {
96	{ PCI_FIXUP_HEADER,	PCI_VENDOR_ID_TRIDENT,	PCI_ANY_ID, fixup_broken_pcnet32 },
97	{ PCI_FIXUP_HEADER,	PCI_VENDOR_ID_WINBOND,	PCI_DEVICE_ID_WINBOND_82C105, fixup_windbond_82c105 },
98	{ PCI_FIXUP_HEADER, PCI_ANY_ID,	PCI_ANY_ID, pcibios_fixup_resources },
99 	{ 0 }
100};
101
102static void fixup_broken_pcnet32(struct pci_dev* dev)
103{
104	if ((dev->class>>8 == PCI_CLASS_NETWORK_ETHERNET)) {
105		dev->vendor = PCI_VENDOR_ID_AMD;
106		pci_write_config_word(dev, PCI_VENDOR_ID, PCI_VENDOR_ID_AMD);
107		pci_name_device(dev);
108	}
109}
110
111static void fixup_windbond_82c105(struct pci_dev* dev)
112{
113	/* Assume the windbond 82c105 is the IDE controller on a
114	 * p610.  We should probably be more careful in case
115	 * someone tries to plug in a similar adapter.
116	 */
117	unsigned int reg;
118
119	printk("Using INTC for W82c105 IDE controller.\n");
120	pci_read_config_dword(dev, 0x40, &reg);
121	/* Enable LEGIRQ to use INTC instead of ISA interrupts */
122	pci_write_config_dword(dev, 0x40, reg | (1<<11));
123}
124
125
126void pcibios_fixup_pbus_ranges(struct pci_bus *pbus,
127				struct pbus_set_ranges_data *pranges)
128{
129}
130
131
132void
133pcibios_update_resource(struct pci_dev *dev, struct resource *root,
134			     struct resource *res, int resource)
135{
136	u32 new, check;
137	int reg;
138	struct pci_controller* hose = PCI_GET_PHB_PTR(dev);
139
140	new = res->start;
141	if (hose && res->flags & IORESOURCE_MEM)
142		new -= hose->pci_mem_offset;
143	new |= (res->flags & PCI_REGION_FLAG_MASK);
144	if (resource < 6) {
145		reg = PCI_BASE_ADDRESS_0 + 4*resource;
146	} else if (resource == PCI_ROM_RESOURCE) {
147		res->flags |= PCI_ROM_ADDRESS_ENABLE;
148		reg = dev->rom_base_reg;
149	} else {
150		/* Somebody might have asked allocation of a non-standard resource */
151		return;
152	}
153
154	pci_write_config_dword(dev, reg, new);
155	pci_read_config_dword(dev, reg, &check);
156	if ((new ^ check) & ((new & PCI_BASE_ADDRESS_SPACE_IO) ? PCI_BASE_ADDRESS_IO_MASK : PCI_BASE_ADDRESS_MEM_MASK)) {
157		printk(KERN_ERR "PCI: Error while updating region "
158		       "%s/%d (%08x != %08x)\n", dev->slot_name, resource,
159		       new, check);
160	}
161}
162
163static void
164pcibios_fixup_resources(struct pci_dev* dev)
165{
166	fixup_resources(dev);
167}
168
169/*
170 * We need to avoid collisions with `mirrored' VGA ports
171 * and other strange ISA hardware, so we always want the
172 * addresses to be allocated in the 0x000-0x0ff region
173 * modulo 0x400.
174 *
175 * Why? Because some silly external IO cards only decode
176 * the low 10 bits of the IO address. The 0x00-0xff region
177 * is reserved for motherboard devices that decode all 16
178 * bits, so it's ok to allocate at, say, 0x2800-0x28ff,
179 * but we want to try to avoid allocating at 0x2900-0x2bff
180 * which might have be mirrored at 0x0100-0x03ff..
181 */
182void
183pcibios_align_resource(void *data, struct resource *res, unsigned long size,
184		       unsigned long align)
185{
186	struct pci_dev *dev = data;
187
188	if (res->flags & IORESOURCE_IO) {
189		unsigned long start = res->start;
190
191		if (size > 0x100) {
192			printk(KERN_ERR "PCI: Can not align I/O Region %s %s because size %ld is too large.\n",
193                                        dev->slot_name, res->name, size);
194		}
195
196		if (start & 0x300) {
197			start = (start + 0x3ff) & ~0x3ff;
198			res->start = start;
199		}
200	}
201}
202
203
204/*
205 *  Handle resources of PCI devices.  If the world were perfect, we could
206 *  just allocate all the resource regions and do nothing more.  It isn't.
207 *  On the other hand, we cannot just re-allocate all devices, as it would
208 *  require us to know lots of host bridge internals.  So we attempt to
209 *  keep as much of the original configuration as possible, but tweak it
210 *  when it's found to be wrong.
211 *
212 *  Known BIOS problems we have to work around:
213 *	- I/O or memory regions not configured
214 *	- regions configured, but not enabled in the command register
215 *	- bogus I/O addresses above 64K used
216 *	- expansion ROMs left enabled (this may sound harmless, but given
217 *	  the fact the PCI specs explicitly allow address decoders to be
218 *	  shared between expansion ROMs and other resource regions, it's
219 *	  at least dangerous)
220 *
221 *  Our solution:
222 *	(1) Allocate resources for all buses behind PCI-to-PCI bridges.
223 *	    This gives us fixed barriers on where we can allocate.
224 *	(2) Allocate resources for all enabled devices.  If there is
225 *	    a collision, just mark the resource as unallocated. Also
226 *	    disable expansion ROMs during this step.
227 *	(3) Try to allocate resources for disabled devices.  If the
228 *	    resources were assigned correctly, everything goes well,
229 *	    if they weren't, they won't disturb allocation of other
230 *	    resources.
231 *	(4) Assign new addresses to resources which were either
232 *	    not configured at all or misconfigured.  If explicitly
233 *	    requested by the user, configure expansion ROM address
234 *	    as well.
235 */
236
237static void __init
238pcibios_allocate_bus_resources(struct list_head *bus_list)
239{
240	struct list_head *ln;
241	struct pci_bus *bus;
242	int i;
243	struct resource *res, *pr;
244
245	/* Depth-First Search on bus tree */
246	for (ln=bus_list->next; ln != bus_list; ln=ln->next) {
247		bus = pci_bus_b(ln);
248		for (i = 0; i < 4; ++i) {
249			if ((res = bus->resource[i]) == NULL || !res->flags)
250				continue;
251			if (bus->parent == NULL)
252				pr = (res->flags & IORESOURCE_IO)?
253					&ioport_resource: &iomem_resource;
254			else
255				pr = pci_find_parent_resource(bus->self, res);
256
257			if (pr == res)
258				continue;	/* transparent bus or undefined */
259			if (pr && request_resource(pr, res) == 0)
260				continue;
261			printk(KERN_ERR "PCI: Cannot allocate resource region "
262			       "%d of PCI bridge %x\n", i, bus->number);
263			printk(KERN_ERR "PCI: resource is %lx..%lx (%lx), parent %p\n",
264			    res->start, res->end, res->flags, pr);
265		}
266		pcibios_allocate_bus_resources(&bus->children);
267	}
268}
269
270static void __init
271pcibios_allocate_resources(int pass)
272{
273	struct pci_dev *dev;
274	int idx, disabled;
275	u16 command;
276	struct resource *r, *pr;
277
278	pci_for_each_dev(dev) {
279		pci_read_config_word(dev, PCI_COMMAND, &command);
280		for(idx = 0; idx < 6; idx++) {
281			r = &dev->resource[idx];
282			if (r->parent)		/* Already allocated */
283				continue;
284			if (!r->start)		/* Address not assigned at all */
285				continue;
286
287			if (r->flags & IORESOURCE_IO)
288				disabled = !(command & PCI_COMMAND_IO);
289			else
290				disabled = !(command & PCI_COMMAND_MEMORY);
291			if (pass == disabled) {
292				PPCDBG(PPCDBG_PHBINIT,
293				       "PCI: Resource %08lx-%08lx (f=%lx, d=%d, p=%d)\n",
294				       r->start, r->end, r->flags, disabled, pass);
295				pr = pci_find_parent_resource(dev, r);
296				if (!pr || request_resource(pr, r) < 0) {
297					PPCDBG(PPCDBG_PHBINIT,
298					       "PCI: Cannot allocate resource region %d of device %s, pr = 0x%lx\n", idx, dev->slot_name, pr);
299					if(pr) {
300					PPCDBG(PPCDBG_PHBINIT,
301					       "PCI: Cannot allocate resource 0x%lx\n", request_resource(pr,r));
302					}
303					/* We'll assign a new address later */
304					r->end -= r->start;
305					r->start = 0;
306				}
307			}
308		}
309		if (!pass) {
310			r = &dev->resource[PCI_ROM_RESOURCE];
311			if (r->flags & PCI_ROM_ADDRESS_ENABLE) {
312				/* Turn the ROM off, leave the resource region, but keep it unregistered. */
313				u32 reg;
314				r->flags &= ~PCI_ROM_ADDRESS_ENABLE;
315				pci_read_config_dword(dev, dev->rom_base_reg, &reg);
316				pci_write_config_dword(dev, dev->rom_base_reg, reg & ~PCI_ROM_ADDRESS_ENABLE);
317			}
318		}
319	}
320}
321
322static void __init
323pcibios_assign_resources(void)
324{
325	struct pci_dev *dev;
326	int idx;
327	struct resource *r;
328
329	pci_for_each_dev(dev) {
330		int class = dev->class >> 8;
331
332		/* Don't touch classless devices and host bridges */
333		if (!class || class == PCI_CLASS_BRIDGE_HOST)
334			continue;
335
336		for(idx=0; idx<6; idx++) {
337			r = &dev->resource[idx];
338
339			/*
340			 *  Don't touch IDE controllers and I/O ports of video cards!
341			 */
342			if ((class == PCI_CLASS_STORAGE_IDE && idx < 4) ||
343			    (class == PCI_CLASS_DISPLAY_VGA && (r->flags & IORESOURCE_IO)))
344				continue;
345
346			/*
347			 *  We shall assign a new address to this resource, either because
348			 *  the BIOS forgot to do so or because we have decided the old
349			 *  address was unusable for some reason.
350			 */
351			if (!r->start && r->end && ppc_md.pcibios_enable_device_hook &&
352			    !ppc_md.pcibios_enable_device_hook(dev, 1))
353				pci_assign_resource(dev, idx);
354		}
355
356		if (0) { /* don't assign ROMs */
357			r = &dev->resource[PCI_ROM_RESOURCE];
358			r->end -= r->start;
359			r->start = 0;
360			if (r->end)
361				pci_assign_resource(dev, PCI_ROM_RESOURCE);
362		}
363	}
364}
365
366
367int
368pcibios_enable_resources(struct pci_dev *dev, int mask)
369{
370	u16 cmd, old_cmd;
371	int idx;
372	struct resource *r;
373
374	pci_read_config_word(dev, PCI_COMMAND, &cmd);
375	old_cmd = cmd;
376	for(idx=0; idx<6; idx++) {
377		if(!(mask & (1<<idx)))
378			continue;
379		r = &dev->resource[idx];
380		if (!r->start && r->end) {
381			printk(KERN_ERR "PCI: Device %s not available because of resource collisions\n", dev->slot_name);
382			return -EINVAL;
383		}
384		if (r->flags & IORESOURCE_IO)
385			cmd |= PCI_COMMAND_IO;
386		if (r->flags & IORESOURCE_MEM)
387			cmd |= PCI_COMMAND_MEMORY;
388	}
389	if (dev->resource[PCI_ROM_RESOURCE].start)
390		cmd |= PCI_COMMAND_MEMORY;
391	if (cmd != old_cmd) {
392		printk("PCI: Enabling device %s (%04x -> %04x)\n", dev->slot_name, old_cmd, cmd);
393		pci_write_config_word(dev, PCI_COMMAND, cmd);
394	}
395	return 0;
396}
397
398/*
399 * Allocate pci_controller(phb) initialized common variables.
400 */
401struct pci_controller * __init
402pci_alloc_pci_controller(char *model, enum phb_types controller_type)
403{
404        struct pci_controller *hose;
405        PPCDBG(PPCDBG_PHBINIT, "PCI: Allocate pci_controller for %s\n",model);
406        hose = (struct pci_controller *)alloc_bootmem(sizeof(struct pci_controller));
407        if(hose == NULL) {
408                printk(KERN_ERR "PCI: Allocate pci_controller failed.\n");
409                return NULL;
410        }
411        memset(hose, 0, sizeof(struct pci_controller));
412        if(strlen(model) < 8) strcpy(hose->what,model);
413        else                  memcpy(hose->what,model,7);
414        hose->type = controller_type;
415        hose->global_number = global_phb_number;
416	phbtab[global_phb_number++] = hose;
417
418        *hose_tail = hose;
419        hose_tail = &hose->next;
420        return hose;
421}
422
423/*
424 * This fixup is arch independent and probably should go somewhere else.
425 */
426void __init
427pcibios_generic_fixup(void)
428{
429	struct pci_dev *dev;
430
431	/* Fix miss-identified vendor AMD pcnet32 adapters. */
432	dev = NULL;
433	while ((dev = pci_find_device(PCI_VENDOR_ID_TRIDENT, PCI_DEVICE_ID_AMD_LANCE, dev)) != NULL &&
434	       dev->class == (PCI_CLASS_NETWORK_ETHERNET << 8))
435		dev->vendor = PCI_VENDOR_ID_AMD;
436}
437
438
439
440/***********************************************************************
441 *
442 *
443 *
444 ***********************************************************************/
445void __init
446pcibios_init(void)
447{
448	struct pci_controller *hose;
449	struct pci_bus *bus;
450	int    next_busno;
451
452#ifndef CONFIG_PPC_ISERIES
453	pSeries_pcibios_init();
454#else
455	iSeries_pcibios_init();
456#endif
457
458	ppc64_boot_msg(0x40, "PCI Probe");
459	printk("PCI: Probing PCI hardware\n");
460	PPCDBG(PPCDBG_BUSWALK,"PCI: Probing PCI hardware\n");
461
462	/* Scan all of the recorded PCI controllers.  */
463	for (next_busno = 0, hose = hose_head; hose; hose = hose->next) {
464		hose->last_busno = 0xff;
465		bus = pci_scan_bus(hose->first_busno, hose->ops, hose->arch_data);
466		hose->bus = bus;
467		hose->last_busno = bus->subordinate;
468		if (pci_assign_all_busses || next_busno <= hose->last_busno)
469			next_busno = hose->last_busno+1;
470	}
471	pci_bus_count = next_busno;
472
473	/* Call machine dependant fixup */
474	if (ppc_md.pcibios_fixup) {
475		ppc_md.pcibios_fixup();
476	}
477
478	/* Generic fixups */
479	pcibios_generic_fixup();
480
481	/* Allocate and assign resources */
482	pcibios_allocate_bus_resources(&pci_root_buses);
483	pcibios_allocate_resources(0);
484	pcibios_allocate_resources(1);
485	pcibios_assign_resources();
486
487#ifndef CONFIG_PPC_ISERIES
488	pci_fix_bus_sysdata();
489
490	create_tce_tables();
491	PPCDBG(PPCDBG_BUSWALK,"pSeries create_tce_tables()\n");
492#endif
493
494	/* Cache the location of the ISA bridge (if we have one) */
495	ppc64_isabridge_dev = pci_find_class(PCI_CLASS_BRIDGE_ISA << 8, NULL);
496	if (ppc64_isabridge_dev != NULL )
497		printk("ISA bridge at %s\n", ppc64_isabridge_dev->slot_name);
498
499	printk("PCI: Probing PCI hardware done\n");
500	PPCDBG(PPCDBG_BUSWALK,"PCI: Probing PCI hardware done.\n");
501	ppc64_boot_msg(0x41, "PCI Done");
502
503}
504
505int __init
506pcibios_assign_all_busses(void)
507{
508	return pci_assign_all_busses;
509}
510
511unsigned long resource_fixup(struct pci_dev * dev, struct resource * res,
512			     unsigned long start, unsigned long size)
513{
514	return start;
515}
516
517void __init pcibios_fixup_bus(struct pci_bus *bus)
518{
519#ifndef CONFIG_PPC_ISERIES
520	struct pci_controller *phb = PCI_GET_PHB_PTR(bus);
521	struct resource *res;
522	int i;
523
524	if (bus->parent == NULL) {
525		/* This is a host bridge - fill in its resources */
526		phb->bus = bus;
527		bus->resource[0] = res = &phb->io_resource;
528		if (!res->flags)
529			BUG();	/* No I/O resource for this PHB? */
530
531		for (i = 0; i < 3; ++i) {
532			res = &phb->mem_resources[i];
533			if (!res->flags) {
534				if (i == 0)
535					BUG();	/* No memory resource for this PHB? */
536			}
537			bus->resource[i+1] = res;
538		}
539	} else {
540		/* This is a subordinate bridge */
541		pci_read_bridge_bases(bus);
542
543		for (i = 0; i < 4; ++i) {
544			if ((res = bus->resource[i]) == NULL)
545				continue;
546			if (!res->flags)
547				continue;
548			if (res == pci_find_parent_resource(bus->self, res)) {
549				/* Transparent resource -- don't try to "fix" it. */
550				continue;
551			}
552			if (is_eeh_implemented()) {
553				if (res->flags & (IORESOURCE_IO|IORESOURCE_MEM)) {
554					res->start = eeh_token(phb->global_number, bus->number, 0, 0);
555					res->end = eeh_token(phb->global_number, bus->number, 0xff, 0xffffffff);
556				}
557			} else {
558				if (res->flags & IORESOURCE_IO) {
559					res->start += (unsigned long)phb->io_base_virt;
560					res->end += (unsigned long)phb->io_base_virt;
561				} else if (phb->pci_mem_offset
562					   && (res->flags & IORESOURCE_MEM)) {
563					if (res->start < phb->pci_mem_offset) {
564						res->start += phb->pci_mem_offset;
565						res->end += phb->pci_mem_offset;
566					}
567				}
568			}
569		}
570	}
571#endif
572	if ( ppc_md.pcibios_fixup_bus )
573		ppc_md.pcibios_fixup_bus(bus);
574}
575
576char __init *pcibios_setup(char *str)
577{
578	return str;
579}
580
581int pcibios_enable_device(struct pci_dev *dev, int mask)
582{
583	u16 cmd, old_cmd;
584	int idx;
585	struct resource *r;
586
587	PPCDBG(PPCDBG_BUSWALK,"PCI: %s for device %s \n",__FUNCTION__,dev->slot_name);
588	if (ppc_md.pcibios_enable_device_hook)
589		if (ppc_md.pcibios_enable_device_hook(dev, 0))
590			return -EINVAL;
591
592	pci_read_config_word(dev, PCI_COMMAND, &cmd);
593	old_cmd = cmd;
594	for (idx=0; idx<6; idx++) {
595		r = &dev->resource[idx];
596		if (!r->start && r->end) {
597			printk(KERN_ERR "PCI: Device %s not available because of resource collisions\n", dev->slot_name);
598			return -EINVAL;
599		}
600		if (r->flags & IORESOURCE_IO)
601			cmd |= PCI_COMMAND_IO;
602		if (r->flags & IORESOURCE_MEM)
603			cmd |= PCI_COMMAND_MEMORY;
604	}
605	if (cmd != old_cmd) {
606		printk("PCI: Enabling device %s (%04x -> %04x)\n",
607		       dev->slot_name, old_cmd, cmd);
608		PPCDBG(PPCDBG_BUSWALK,"PCI: Enabling device %s \n",dev->slot_name);
609		pci_write_config_word(dev, PCI_COMMAND, cmd);
610	}
611	return 0;
612}
613
614struct pci_controller*
615pci_bus_to_hose(int bus)
616{
617	struct pci_controller* hose = hose_head;
618
619	for (; hose; hose = hose->next)
620		if (bus >= hose->first_busno && bus <= hose->last_busno)
621			return hose;
622	return NULL;
623}
624
625void*
626pci_bus_io_base(unsigned int bus)
627{
628	struct pci_controller *hose;
629
630	hose = pci_bus_to_hose(bus);
631	if (!hose)
632		return NULL;
633	return hose->io_base_virt;
634}
635
636unsigned long
637pci_bus_io_base_phys(unsigned int bus)
638{
639	struct pci_controller *hose;
640
641	hose = pci_bus_to_hose(bus);
642	if (!hose)
643		return 0;
644	return hose->io_base_phys;
645}
646
647unsigned long
648pci_bus_mem_base_phys(unsigned int bus)
649{
650	struct pci_controller *hose;
651
652	hose = pci_bus_to_hose(bus);
653	if (!hose)
654		return 0;
655	return hose->pci_mem_offset;
656}
657
658/*
659 * Return the index of the PCI controller for device pdev.
660 */
661int pci_controller_num(struct pci_dev *dev)
662{
663	struct pci_controller *hose = PCI_GET_PHB_PTR(dev);
664
665	return hose->global_number;
666}
667
668/*
669 * Platform support for /proc/bus/pci/X/Y mmap()s,
670 * modelled on the sparc64 implementation by Dave Miller.
671 *  -- paulus.
672 */
673
674static __inline__ int
675__pci_mmap_make_offset(struct pci_dev *dev, struct vm_area_struct *vma,
676		       enum pci_mmap_state mmap_state)
677{
678	struct pci_controller *hose = PCI_GET_PHB_PTR(dev);
679	unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
680	unsigned long io_offset = 0;
681	int i, res_bit;
682
683	if (hose == 0)
684		return -EINVAL;		/* should never happen */
685
686	/* If memory, add on the PCI bridge address offset */
687	if (mmap_state == pci_mmap_mem) {
688		offset += hose->pci_mem_offset;
689		res_bit = IORESOURCE_MEM;
690	} else {
691		io_offset = (unsigned long)hose->io_base_virt;
692		offset += io_offset;
693		res_bit = IORESOURCE_IO;
694	}
695
696	/*
697	 * Check that the offset requested corresponds to one of the
698	 * resources of the device.
699	 */
700	for (i = 0; i <= PCI_ROM_RESOURCE; i++) {
701		struct resource *rp = &dev->resource[i];
702		int flags = rp->flags;
703
704		/* treat ROM as memory (should be already) */
705		if (i == PCI_ROM_RESOURCE)
706			flags |= IORESOURCE_MEM;
707
708		/* Active and same type? */
709		if ((flags & res_bit) == 0)
710			continue;
711
712		/* In the range of this resource? */
713		if (offset < (rp->start & PAGE_MASK) || offset > rp->end)
714			continue;
715
716		/* found it! construct the final physical address */
717		if (mmap_state == pci_mmap_io)
718			offset += hose->io_base_phys - io_offset;
719
720		vma->vm_pgoff = offset >> PAGE_SHIFT;
721		return 0;
722	}
723
724	return -EINVAL;
725}
726
727/*
728 * Set vm_flags of VMA, as appropriate for this architecture, for a pci device
729 * mapping.
730 */
731static __inline__ void
732__pci_mmap_set_flags(struct pci_dev *dev, struct vm_area_struct *vma,
733		     enum pci_mmap_state mmap_state)
734{
735	vma->vm_flags |= VM_SHM | VM_LOCKED | VM_IO;
736}
737
738/*
739 * Set vm_page_prot of VMA, as appropriate for this architecture, for a pci
740 * device mapping.
741 */
742static __inline__ void
743__pci_mmap_set_pgprot(struct pci_dev *dev, struct vm_area_struct *vma,
744		      enum pci_mmap_state mmap_state, int write_combine)
745{
746	long prot = pgprot_val(vma->vm_page_prot);
747
748	prot |= _PAGE_NO_CACHE;
749	prot |= _PAGE_GUARDED;
750	vma->vm_page_prot = __pgprot(prot);
751}
752
753/*
754 * Perform the actual remap of the pages for a PCI device mapping, as
755 * appropriate for this architecture.  The region in the process to map
756 * is described by vm_start and vm_end members of VMA, the base physical
757 * address is found in vm_pgoff.
758 * The pci device structure is provided so that architectures may make mapping
759 * decisions on a per-device or per-bus basis.
760 *
761 * Returns a negative error code on failure, zero on success.
762 */
763int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma,
764			enum pci_mmap_state mmap_state,
765			int write_combine)
766{
767	int ret;
768
769	ret = __pci_mmap_make_offset(dev, vma, mmap_state);
770	if (ret < 0)
771		return ret;
772
773	__pci_mmap_set_flags(dev, vma, mmap_state);
774	__pci_mmap_set_pgprot(dev, vma, mmap_state, write_combine);
775
776	ret = remap_page_range(vma->vm_start, vma->vm_pgoff << PAGE_SHIFT,
777			       vma->vm_end - vma->vm_start, vma->vm_page_prot);
778
779	return ret;
780}
781
782/* Provide information on locations of various I/O regions in physical
783 * memory.  Do this on a per-card basis so that we choose the right
784 * root bridge.
785 * Note that the returned IO or memory base is a physical address
786 */
787
788long
789sys_pciconfig_iobase(long which, unsigned long bus, unsigned long devfn)
790{
791	struct pci_controller* hose = pci_bus_to_hose(bus);
792	long result = -EOPNOTSUPP;
793
794	if (!hose)
795		return -ENODEV;
796
797	switch (which) {
798	case IOBASE_BRIDGE_NUMBER:
799		return (long)hose->first_busno;
800	case IOBASE_MEMORY:
801		return (long)hose->pci_mem_offset;
802	case IOBASE_IO:
803		return (long)hose->io_base_phys;
804	case IOBASE_ISA_IO:
805		return (long)isa_io_base;
806	case IOBASE_ISA_MEM:
807		return (long)isa_mem_base;
808	}
809
810	return result;
811}
812/************************************************************************/
813/* Formats the device information and location for service.             */
814/* - Pass in pci_dev* pointer to the device.                            */
815/* - Pass in buffer to place the data.  Danger here is the buffer must  */
816/*   be as big as the client says it is.   Should be at least 128 bytes.*/
817/* Return will the length of the string data put in the buffer.         */
818/* The brand specific method device_Location is called.                 */
819/* Format:                                                              */
820/* PCI: Bus  0, Device 26, Vendor 0x12AE  Frame  1, Card  C10  Ethernet */
821/* PCI: Bus  0, Device 26, Vendor 0x12AE  Location U0.3-P1-I8  Ethernet */
822/* For pSeries, see the Product Topology in the RS/6000 Architecture.   */
823/* For iSeries, see the Service Manuals.                                */
824/************************************************************************/
825int  format_device_location(struct pci_dev* PciDev,char* BufPtr, int BufferSize)
826{
827	struct device_node* DevNode = (struct device_node*)PciDev->sysdata;
828	int  LineLen = 0;
829	if (DevNode != NULL && BufferSize >= 128) {
830		LineLen += device_Location(PciDev,BufPtr+LineLen);
831		LineLen += sprintf(BufPtr+LineLen," %12s",pci_class_name(PciDev->class >> 8) );
832	}
833	return LineLen;
834}
835/************************************************************************
836 * Saves the config registers for a device.                             *
837 ************************************************************************
838 * Note: This does byte reads so the data may appear byte swapped,      *
839 * The data returned in the pci_config_reg_save_area structure can be   *
840 * used to the restore of the data.  If the save failed, the data       *
841 * will not be restore.  Yes I know, you are most likey toast.          *
842 ************************************************************************/
843int pci_save_config_regs(struct pci_dev* PciDev,struct pci_config_reg_save_area* SaveArea)
844{
845	memset(SaveArea,0x00,sizeof(struct pci_config_reg_save_area) );
846	SaveArea->PciDev    = PciDev;
847	SaveArea->RCode     = 0;
848	SaveArea->Register  = 0;
849	/******************************************************************
850	 * Save All the Regs,  NOTE: restore skips the first 16 bytes.    *
851	 ******************************************************************/
852	while (SaveArea->Register < REG_SAVE_SIZE && SaveArea->RCode == 0) {
853		SaveArea->RCode = pci_read_config_byte(PciDev, SaveArea->Register, &SaveArea->Regs[SaveArea->Register]);
854		++SaveArea->Register;
855	}
856	if (SaveArea->RCode != 0) { 	/* Ouch */
857		SaveArea->Flags = 0x80;
858		printk("PCI: pci_restore_save_regs failed! %p\n 0x%04X",PciDev,SaveArea->RCode);
859		PCIFR(      "pci_restore_save_regs failed! %p\n 0x%04X",PciDev,SaveArea->RCode);
860	}
861	else {
862		SaveArea->Flags = 0x01;
863	}
864	return  SaveArea->RCode;
865}
866
867/************************************************************************
868 * Restores the registers saved via the save function.  See the save    *
869 * function for details.                                                *
870 ************************************************************************/
871int pci_restore_config_regs(struct pci_dev* PciDev,struct pci_config_reg_save_area* SaveArea)
872{
873 	if (SaveArea->PciDev != PciDev || SaveArea->Flags == 0x80 || SaveArea->RCode != 0) {
874		printk("PCI: pci_restore_config_regs failed! %p\n",PciDev);
875		return -1;
876	}
877	/******************************************************************
878	 * Don't touch the Cmd or BIST regs, user must restore those.     *
879	 * Restore PCI_VENDOR_ID & PCI_DEVICE_ID                          *
880	 * Restore PCI_CACHE_LINE_SIZE & PCI_LATENCY_TIMER                *
881	 * Restore Saved Regs from 0x10 to 0x3F                           *
882	 ******************************************************************/
883	SaveArea->Register = 0;
884	while(SaveArea->Register < REG_SAVE_SIZE && SaveArea->RCode == 0) {
885		SaveArea->RCode = pci_write_config_byte(PciDev,SaveArea->Register,SaveArea->Regs[SaveArea->Register]);
886		++SaveArea->Register;
887		if (     SaveArea->Register == PCI_COMMAND)     SaveArea->Register = PCI_CACHE_LINE_SIZE;
888		else if (SaveArea->Register == PCI_HEADER_TYPE) SaveArea->Register = PCI_BASE_ADDRESS_0;
889	}
890	if (SaveArea->RCode != 0) {
891		printk("PCI: pci_restore_config_regs failed! %p\n 0x%04X",PciDev,SaveArea->RCode);
892		PCIFR(      "pci_restore_config_regs failed! %p\n 0x%04X",PciDev,SaveArea->RCode);
893	}
894	return  SaveArea->RCode;
895}
896
897/************************************************************************/
898/* Interface to toggle the reset line                                   */
899/* Time is in .1 seconds, need for seconds.                             */
900/************************************************************************/
901int  pci_reset_device(struct pci_dev* PciDev, int AssertTime, int DelayTime)
902{
903	unsigned long AssertDelay, WaitDelay;
904	int RtnCode;
905	/********************************************************************
906	 * Set defaults, Assert is .5 second, Wait is 3 seconds.
907	 ********************************************************************/
908	if (AssertTime == 0) AssertDelay = ( 5 * HZ)/10;
909	else                 AssertDelay = (AssertTime*HZ)/10;
910	if (WaitDelay == 0)  WaitDelay   = (30 * HZ)/10;
911	else                 WaitDelay   = (DelayTime* HZ)/10;
912
913	/********************************************************************
914	 * Assert reset, wait, de-assert reset, wait for IOA to reset.
915	 * - Don't waste the CPU time on jiffies.
916	 ********************************************************************/
917	RtnCode = pci_set_reset(PciDev,1);
918	if (RtnCode == 0) {
919		set_current_state(TASK_UNINTERRUPTIBLE);
920		schedule_timeout(AssertDelay);   /* Sleep for the time     */
921		RtnCode = pci_set_reset(PciDev,0);
922		set_current_state(TASK_UNINTERRUPTIBLE);
923		schedule_timeout(WaitDelay);
924	}
925	if (RtnCode == 0) {
926		PCIFR(      "Bus%3d, Device%3d, Reset\n",PciDev->bus->number,PCI_SLOT(PciDev->devfn) );
927	}
928	else {
929		printk("PCI: Bus%3d, Device%3d, Reset Failed:0x%04X\n",PciDev->bus->number,PCI_SLOT(PciDev->devfn),RtnCode );
930		PCIFR(      "Bus%3d, Device%3d, Reset Failed:0x%04X\n",PciDev->bus->number,PCI_SLOT(PciDev->devfn),RtnCode );
931	}
932	return RtnCode;
933}
934
935/*****************************************************
936 * Dump Resource information
937 *****************************************************/
938void dumpResources(struct resource* Resource)
939{
940	if(Resource != NULL) {
941		int Flags = 0x00000F00 & Resource->flags;
942		if(Resource->start == 0 && Resource->end == 0) return;
943		else if(Resource->start == Resource->end )     return;
944		else {
945			if     (Flags == IORESOURCE_IO)  udbg_printf("IO.:");
946			else if(Flags == IORESOURCE_MEM) udbg_printf("MEM:");
947			else if(Flags == IORESOURCE_IRQ) udbg_printf("IRQ:");
948			else                             udbg_printf("0x%02X:",Resource->flags);
949
950		}
951		udbg_printf("0x%016LX / 0x%016LX (0x%08X)\n",
952			    Resource->start, Resource->end, Resource->end - Resource->start);
953	}
954}
955
956int  resourceSize(struct resource* Resource)
957{
958	if(Resource->start == 0 && Resource->end == 0) return 0;
959	else if(Resource->start == Resource->end )     return 0;
960	else return (Resource->end-1)-Resource->start;
961}
962
963
964/*****************************************************
965 * Dump PHB information for Debug
966 *****************************************************/
967void dumpPci_Controller(struct pci_controller* phb)
968{
969	udbg_printf("\tpci_controller= 0x%016LX\n", phb);
970	if (phb != NULL) {
971		udbg_printf("\twhat & type   = %s 0x%02X\n ",phb->what,phb->type);
972		udbg_printf("\tbus           = ");
973		if (phb->bus != NULL) udbg_printf("0x%02X\n",   phb->bus->number);
974		else                  udbg_printf("<NULL>\n");
975		udbg_printf("\tarch_data     = 0x%016LX\n", phb->arch_data);
976		udbg_printf("\tfirst_busno   = 0x%02X\n",   phb->first_busno);
977		udbg_printf("\tlast_busno    = 0x%02X\n",   phb->last_busno);
978		udbg_printf("\tio_base_virt* = 0x%016LX\n", phb->io_base_virt);
979		udbg_printf("\tio_base_phys  = 0x%016LX\n", phb->io_base_phys);
980		udbg_printf("\tpci_mem_offset= 0x%016LX\n", phb->pci_mem_offset);
981		udbg_printf("\tpci_io_offset = 0x%016LX\n", phb->pci_io_offset);
982
983		udbg_printf("\tcfg_addr      = 0x%016LX\n", phb->cfg_addr);
984		udbg_printf("\tcfg_data      = 0x%016LX\n", phb->cfg_data);
985		udbg_printf("\tphb_regs      = 0x%016LX\n", phb->phb_regs);
986		udbg_printf("\tchip_regs     = 0x%016LX\n", phb->chip_regs);
987
988
989		udbg_printf("\tResources\n");
990		dumpResources(&phb->io_resource);
991		if (phb->mem_resource_count >  0) dumpResources(&phb->mem_resources[0]);
992		if (phb->mem_resource_count >  1) dumpResources(&phb->mem_resources[1]);
993		if (phb->mem_resource_count >  2) dumpResources(&phb->mem_resources[2]);
994
995		udbg_printf("\tglobal_num    = 0x%02X\n",   phb->global_number);
996		udbg_printf("\tlocal_num     = 0x%02X\n",   phb->local_number);
997	}
998}
999
1000/*****************************************************
1001 * Dump PHB information for Debug
1002 *****************************************************/
1003void dumpPci_Bus(struct pci_bus* Pci_Bus)
1004{
1005	int i;
1006	udbg_printf("\tpci_bus         = 0x%016LX   \n",Pci_Bus);
1007	if (Pci_Bus != NULL) {
1008
1009		udbg_printf("\tnumber          = 0x%02X     \n",Pci_Bus->number);
1010		udbg_printf("\tprimary         = 0x%02X     \n",Pci_Bus->primary);
1011		udbg_printf("\tsecondary       = 0x%02X     \n",Pci_Bus->secondary);
1012		udbg_printf("\tsubordinate     = 0x%02X     \n",Pci_Bus->subordinate);
1013
1014		for (i=0;i<4;++i) {
1015			if(Pci_Bus->resource[i] == NULL) continue;
1016			if(Pci_Bus->resource[i]->start == 0 && Pci_Bus->resource[i]->end == 0) break;
1017			udbg_printf("\tResources[%d]",i);
1018			dumpResources(Pci_Bus->resource[i]);
1019		}
1020	}
1021}
1022
1023/*****************************************************
1024 * Dump Device information for Debug
1025 *****************************************************/
1026void dumpPci_Dev(struct pci_dev* Pci_Dev)
1027{
1028	int i;
1029	udbg_printf("\tpci_dev*        = 0x%p\n",Pci_Dev);
1030	if ( Pci_Dev == NULL )  return;
1031	udbg_printf("\tname            = %s  \n",Pci_Dev->name);
1032	udbg_printf("\tbus*            = 0x%p\n",Pci_Dev->bus);
1033	udbg_printf("\tsysdata*        = 0x%p\n",Pci_Dev->sysdata);
1034	udbg_printf("\tDevice          = 0x%4X%02X:%02X.%02X 0x%04X:%04X\n",
1035		    PCI_GET_PHB_NUMBER(Pci_Dev),
1036		    PCI_GET_BUS_NUMBER(Pci_Dev),
1037		    PCI_SLOT(Pci_Dev->devfn),
1038		    PCI_FUNC(Pci_Dev->devfn),
1039		    Pci_Dev->vendor,
1040		    Pci_Dev->device);
1041	udbg_printf("\tHdr/Irq         = 0x%02X/0x%02X \n",Pci_Dev->hdr_type,Pci_Dev->irq);
1042	for (i=0;i<DEVICE_COUNT_RESOURCE;++i) {
1043		if (Pci_Dev->resource[i].start == 0 && Pci_Dev->resource[i].end == 0) continue;
1044		udbg_printf("\tResources[%d] ",i);
1045		dumpResources(&Pci_Dev->resource[i]);
1046	}
1047	dumpResources(&Pci_Dev->resource[i]);
1048}
1049