3f3cc57f10bdbe8f74cb535c2ba84a5fd329d97a
[coreboot.git] / src / devices / device.c
1 /*
2  * This file is part of the coreboot project.
3  *
4  * It was originally based on the Linux kernel (arch/i386/kernel/pci-pc.c).
5  *
6  * Modifications are:
7  * Copyright (C) 2003 Eric Biederman <ebiederm@xmission.com>
8  * Copyright (C) 2003-2004 Linux Networx
9  * (Written by Eric Biederman <ebiederman@lnxi.com> for Linux Networx)
10  * Copyright (C) 2003 Ronald G. Minnich <rminnich@gmail.com>
11  * Copyright (C) 2004-2005 Li-Ta Lo <ollie@lanl.gov>
12  * Copyright (C) 2005-2006 Tyan
13  * (Written by Yinghai Lu <yhlu@tyan.com> for Tyan)
14  * Copyright (C) 2005-2006 Stefan Reinauer <stepan@openbios.org>
15  * Copyright (C) 2009 Myles Watson <mylesgw@gmail.com>
16  */
17
18 /*
19  *      (c) 1999--2000 Martin Mares <mj@suse.cz>
20  */
21 /* lots of mods by ron minnich (rminnich@lanl.gov), with
22  * the final architecture guidance from Tom Merritt (tjm@codegen.com)
23  * In particular, we changed from the one-pass original version to
24  * Tom's recommended multiple-pass version. I wasn't sure about doing
25  * it with multiple passes, until I actually started doing it and saw
26  * the wisdom of Tom's recommendations ...
27  *
28  * Lots of cleanups by Eric Biederman to handle bridges, and to
29  * handle resource allocation for non-pci devices.
30  */
31
32 #include <console/console.h>
33 #include <bitops.h>
34 #include <arch/io.h>
35 #include <device/device.h>
36 #include <device/pci.h>
37 #include <device/pci_ids.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <smp/spinlock.h>
41
42 /** Linked list of ALL devices */
43 struct device *all_devices = &dev_root;
44 /** Pointer to the last device */
45 extern struct device *last_dev;
46 /** Linked list of free resources */
47 struct resource *free_resources = NULL;
48
49
50 /**
51  * @brief Allocate a new device structure.
52  *
53  * Allocte a new device structure and attached it to the device tree as a
54  * child of the parent bus.
55  *
56  * @param parent parent bus the newly created device attached to.
57  * @param path path to the device to be created.
58  *
59  * @return pointer to the newly created device structure.
60  *
61  * @see device_path
62  */
63
64 DECLARE_SPIN_LOCK(dev_lock)
65
66 device_t alloc_dev(struct bus *parent, struct device_path *path)
67 {
68         device_t dev, child;
69
70         spin_lock(&dev_lock);
71
72         /* Find the last child of our parent. */
73         for (child = parent->children; child && child->sibling; /* */ ) {
74                 child = child->sibling;
75         }
76
77         dev = malloc(sizeof(*dev));
78         if (dev == 0)
79                 die("DEV: out of memory.\n");
80
81         memset(dev, 0, sizeof(*dev));
82         memcpy(&dev->path, path, sizeof(*path));
83
84         /* By default devices are enabled. */
85         dev->enabled = 1;
86
87         /* Add the new device to the list of children of the bus. */
88         dev->bus = parent;
89         if (child) {
90                 child->sibling = dev;
91         } else {
92                 parent->children = dev;
93         }
94
95         /* Append a new device to the global device list.
96          * The list is used to find devices once everything is set up.
97          */
98         last_dev->next = dev;
99         last_dev = dev;
100
101         spin_unlock(&dev_lock);
102         return dev;
103 }
104
105 /**
106  * @brief round a number up to an alignment.
107  * @param val the starting value
108  * @param roundup Alignment as a power of two
109  * @returns rounded up number
110  */
111 static resource_t round(resource_t val, unsigned long pow)
112 {
113         resource_t mask;
114         mask = (1ULL << pow) - 1ULL;
115         val += mask;
116         val &= ~mask;
117         return val;
118 }
119
120 /** Read the resources on all devices of a given bus.
121  * @param bus bus to read the resources on.
122  */
123 static void read_resources(struct bus *bus)
124 {
125         struct device *curdev;
126
127         printk(BIOS_SPEW, "%s %s bus %x link: %d\n", dev_path(bus->dev), __func__,
128                     bus->secondary, bus->link_num);
129
130         /* Walk through all devices and find which resources they need. */
131         for (curdev = bus->children; curdev; curdev = curdev->sibling) {
132                 struct bus *link;
133                 if (!curdev->enabled) {
134                         continue;
135                 }
136                 if (!curdev->ops || !curdev->ops->read_resources) {
137                         printk(BIOS_ERR, "%s missing read_resources\n",
138                                    dev_path(curdev));
139                         continue;
140                 }
141                 curdev->ops->read_resources(curdev);
142
143                 /* Read in the resources behind the current device's links. */
144                 for (link = curdev->link_list; link; link = link->next)
145                         read_resources(link);
146         }
147         printk(BIOS_SPEW, "%s read_resources bus %d link: %d done\n",
148                     dev_path(bus->dev), bus->secondary, bus->link_num);
149 }
150
151 struct pick_largest_state {
152         struct resource *last;
153         struct device *result_dev;
154         struct resource *result;
155         int seen_last;
156 };
157
158 static void pick_largest_resource(void *gp, struct device *dev,
159                                   struct resource *resource)
160 {
161         struct pick_largest_state *state = gp;
162         struct resource *last;
163
164         last = state->last;
165
166         /* Be certain to pick the successor to last. */
167         if (resource == last) {
168                 state->seen_last = 1;
169                 return;
170         }
171         if (resource->flags & IORESOURCE_FIXED)
172                 return;         // Skip it.
173         if (last && ((last->align < resource->align) ||
174                      ((last->align == resource->align) &&
175                       (last->size < resource->size)) ||
176                      ((last->align == resource->align) &&
177                       (last->size == resource->size) && (!state->seen_last)))) {
178                 return;
179         }
180         if (!state->result ||
181             (state->result->align < resource->align) ||
182             ((state->result->align == resource->align) &&
183              (state->result->size < resource->size))) {
184                 state->result_dev = dev;
185                 state->result = resource;
186         }
187 }
188
189 static struct device *largest_resource(struct bus *bus,
190                                        struct resource **result_res,
191                                        unsigned long type_mask,
192                                        unsigned long type)
193 {
194         struct pick_largest_state state;
195
196         state.last = *result_res;
197         state.result_dev = NULL;
198         state.result = NULL;
199         state.seen_last = 0;
200
201         search_bus_resources(bus, type_mask, type, pick_largest_resource,
202                              &state);
203
204         *result_res = state.result;
205         return state.result_dev;
206 }
207
208 /* Compute allocate resources is the guts of the resource allocator.
209  *
210  * The problem.
211  *  - Allocate resource locations for every device.
212  *  - Don't overlap, and follow the rules of bridges.
213  *  - Don't overlap with resources in fixed locations.
214  *  - Be efficient so we don't have ugly strategies.
215  *
216  * The strategy.
217  * - Devices that have fixed addresses are the minority so don't
218  *   worry about them too much. Instead only use part of the address
219  *   space for devices with programmable addresses. This easily handles
220  *   everything except bridges.
221  *
222  * - PCI devices are required to have their sizes and their alignments
223  *   equal. In this case an optimal solution to the packing problem
224  *   exists. Allocate all devices from highest alignment to least
225  *   alignment or vice versa. Use this.
226  *
227  * - So we can handle more than PCI run two allocation passes on bridges. The
228  *   first to see how large the resources are behind the bridge, and what
229  *   their alignment requirements are. The second to assign a safe address to
230  *   the devices behind the bridge. This allows us to treat a bridge as just
231  *   a device with a couple of resources, and not need to special case it in
232  *   the allocator. Also this allows handling of other types of bridges.
233  *
234  */
235 static void compute_resources(struct bus *bus, struct resource *bridge,
236                        unsigned long type_mask, unsigned long type)
237 {
238         struct device *dev;
239         struct resource *resource;
240         resource_t base;
241         base = round(bridge->base, bridge->align);
242
243         printk(BIOS_SPEW,  "%s %s_%s: base: %llx size: %llx align: %d gran: %d limit: %llx\n",
244                dev_path(bus->dev), __func__,
245                (type & IORESOURCE_IO) ? "io" : (type & IORESOURCE_PREFETCH) ?
246                "prefmem" : "mem",
247                base, bridge->size, bridge->align, bridge->gran, bridge->limit);
248
249         /* For each child which is a bridge, compute_resource_needs. */
250         for (dev = bus->children; dev; dev = dev->sibling) {
251                 struct resource *child_bridge;
252
253                 if (!dev->link_list)
254                         continue;
255
256                 /* Find the resources with matching type flags. */
257                 for (child_bridge = dev->resource_list; child_bridge;
258                      child_bridge = child_bridge->next) {
259                         struct bus* link;
260
261                         if (!(child_bridge->flags & IORESOURCE_BRIDGE) ||
262                             (child_bridge->flags & type_mask) != type)
263                                 continue;
264
265                         /* Split prefetchable memory if combined.  Many domains
266                          * use the same address space for prefetchable memory
267                          * and non-prefetchable memory.  Bridges below them
268                          * need it separated.  Add the PREFETCH flag to the
269                          * type_mask and type.
270                          */
271                         link = dev->link_list;
272                         while (link && link->link_num !=
273                                         IOINDEX_LINK(child_bridge->index))
274                                 link = link->next;
275                         if (link == NULL)
276                                 printk(BIOS_ERR, "link %ld not found on %s\n",
277                                        IOINDEX_LINK(child_bridge->index),
278                                        dev_path(dev));
279                         compute_resources(link, child_bridge,
280                                           type_mask | IORESOURCE_PREFETCH,
281                                           type | (child_bridge->flags &
282                                                   IORESOURCE_PREFETCH));
283                 }
284         }
285
286         /* Remember we haven't found anything yet. */
287         resource = NULL;
288
289         /* Walk through all the resources on the current bus and compute the
290          * amount of address space taken by them.  Take granularity and
291          * alignment into account.
292          */
293         while ((dev = largest_resource(bus, &resource, type_mask, type))) {
294
295                 /* Size 0 resources can be skipped. */
296                 if (!resource->size) {
297                         continue;
298                 }
299
300                 /* Propagate the resource alignment to the bridge resource. */
301                 if (resource->align > bridge->align) {
302                         bridge->align = resource->align;
303                 }
304
305                 /* Propagate the resource limit to the bridge register. */
306                 if (bridge->limit > resource->limit) {
307                         bridge->limit = resource->limit;
308                 }
309
310                 /* Warn if it looks like APICs aren't declared. */
311                 if ((resource->limit == 0xffffffff) &&
312                     (resource->flags & IORESOURCE_ASSIGNED)) {
313                         printk(BIOS_ERR, "Resource limit looks wrong! (no APIC?)\n");
314                         printk(BIOS_ERR, "%s %02lx limit %08Lx\n", dev_path(dev),
315                                    resource->index, resource->limit);
316                 }
317
318                 if (resource->flags & IORESOURCE_IO) {
319                         /* Don't allow potential aliases over the legacy PCI
320                          * expansion card addresses. The legacy PCI decodes
321                          * only 10 bits, uses 0x100 - 0x3ff. Therefore, only
322                          * 0x00 - 0xff can be used out of each 0x400 block of
323                          * I/O space.
324                          */
325                         if ((base & 0x300) != 0) {
326                                 base = (base & ~0x3ff) + 0x400;
327                         }
328                         /* Don't allow allocations in the VGA I/O range.
329                          * PCI has special cases for that.
330                          */
331                         else if ((base >= 0x3b0) && (base <= 0x3df)) {
332                                 base = 0x3e0;
333                         }
334                 }
335                 /* Base must be aligned. */
336                 base = round(base, resource->align);
337                 resource->base = base;
338                 base += resource->size;
339
340                 printk(BIOS_SPEW, "%s %02lx *  [0x%llx - 0x%llx] %s\n",
341                             dev_path(dev), resource->index,
342                             resource->base,
343                             resource->base + resource->size - 1,
344                             (resource->flags & IORESOURCE_IO) ? "io" :
345                             (resource->flags & IORESOURCE_PREFETCH) ?
346                              "prefmem" : "mem");
347         }
348         /* A pci bridge resource does not need to be a power
349          * of two size, but it does have a minimum granularity.
350          * Round the size up to that minimum granularity so we
351          * know not to place something else at an address postitively
352          * decoded by the bridge.
353          */
354         bridge->size = round(base, bridge->gran) -
355                        round(bridge->base, bridge->align);
356
357         printk(BIOS_SPEW, "%s %s_%s: base: %llx size: %llx align: %d gran: %d limit: %llx done\n",
358                     dev_path(bus->dev), __func__,
359                     (bridge->flags & IORESOURCE_IO) ? "io" :
360                      (bridge->flags & IORESOURCE_PREFETCH) ?  "prefmem" : "mem",
361                     base, bridge->size, bridge->align, bridge->gran, bridge->limit);
362 }
363
364 /**
365  * This function is the second part of the resource allocator.
366  *
367  * The problem.
368  *  - Allocate resource locations for every device.
369  *  - Don't overlap, and follow the rules of bridges.
370  *  - Don't overlap with resources in fixed locations.
371  *  - Be efficient so we don't have ugly strategies.
372  *
373  * The strategy.
374  * - Devices that have fixed addresses are the minority so don't
375  *   worry about them too much. Instead only use part of the address
376  *   space for devices with programmable addresses. This easily handles
377  *   everything except bridges.
378  *
379  * - PCI devices are required to have their sizes and their alignments
380  *   equal. In this case an optimal solution to the packing problem
381  *   exists. Allocate all devices from highest alignment to least
382  *   alignment or vice versa. Use this.
383  *
384  * - So we can handle more than PCI run two allocation passes on bridges. The
385  *   first to see how large the resources are behind the bridge, and what
386  *   their alignment requirements are. The second to assign a safe address to
387  *   the devices behind the bridge. This allows us to treat a bridge as just
388  *   a device with a couple of resources, and not need to special case it in
389  *   the allocator. Also this allows handling of other types of bridges.
390  *
391  * - This function assigns the resources a value.
392  *
393  * @param bus The bus we are traversing.
394  * @param bridge The bridge resource which must contain the bus' resources.
395  * @param type_mask This value gets anded with the resource type.
396  * @param type This value must match the result of the and.
397  */
398 static void allocate_resources(struct bus *bus, struct resource *bridge,
399                         unsigned long type_mask, unsigned long type)
400 {
401         struct device *dev;
402         struct resource *resource;
403         resource_t base;
404         base = bridge->base;
405
406         printk(BIOS_SPEW, "%s %s_%s: base:%llx size:%llx align:%d gran:%d limit:%llx\n",
407                dev_path(bus->dev), __func__,
408                (type & IORESOURCE_IO) ? "io" : (type & IORESOURCE_PREFETCH) ?
409                "prefmem" : "mem",
410                base, bridge->size, bridge->align, bridge->gran, bridge->limit);
411
412         /* Remember we haven't found anything yet. */
413         resource = NULL;
414
415         /* Walk through all the resources on the current bus and allocate them
416          * address space.
417          */
418         while ((dev = largest_resource(bus, &resource, type_mask, type))) {
419
420                 /* Propagate the bridge limit to the resource register. */
421                 if (resource->limit > bridge->limit) {
422                         resource->limit = bridge->limit;
423                 }
424
425                 /* Size 0 resources can be skipped. */
426                 if (!resource->size) {
427                         /* Set the base to limit so it doesn't confuse tolm. */
428                         resource->base = resource->limit;
429                         resource->flags |= IORESOURCE_ASSIGNED;
430                         continue;
431                 }
432
433                 if (resource->flags & IORESOURCE_IO) {
434                         /* Don't allow potential aliases over the legacy PCI
435                          * expansion card addresses. The legacy PCI decodes
436                          * only 10 bits, uses 0x100 - 0x3ff. Therefore, only
437                          * 0x00 - 0xff can be used out of each 0x400 block of
438                          * I/O space.
439                          */
440                         if ((base & 0x300) != 0) {
441                                 base = (base & ~0x3ff) + 0x400;
442                         }
443                         /* Don't allow allocations in the VGA I/O range.
444                          * PCI has special cases for that.
445                          */
446                         else if ((base >= 0x3b0) && (base <= 0x3df)) {
447                                 base = 0x3e0;
448                         }
449                 }
450
451                 if ((round(base, resource->align) + resource->size - 1) <=
452                     resource->limit) {
453                         /* Base must be aligned. */
454                         base = round(base, resource->align);
455                         resource->base = base;
456                         resource->flags |= IORESOURCE_ASSIGNED;
457                         resource->flags &= ~IORESOURCE_STORED;
458                         base += resource->size;
459                 } else {
460                         printk(BIOS_ERR, "!! Resource didn't fit !!\n");
461                         printk(BIOS_ERR, "   aligned base %llx size %llx limit %llx\n",
462                                round(base, resource->align), resource->size,
463                                resource->limit);
464                         printk(BIOS_ERR, "   %llx needs to be <= %llx (limit)\n",
465                                (round(base, resource->align) +
466                                 resource->size) - 1, resource->limit);
467                         printk(BIOS_ERR, "   %s%s %02lx *  [0x%llx - 0x%llx] %s\n",
468                                (resource->
469                                 flags & IORESOURCE_ASSIGNED) ? "Assigned: " :
470                                "", dev_path(dev), resource->index,
471                                resource->base,
472                                resource->base + resource->size - 1,
473                                (resource->
474                                 flags & IORESOURCE_IO) ? "io" : (resource->
475                                                                  flags &
476                                                                  IORESOURCE_PREFETCH)
477                                ? "prefmem" : "mem");
478                 }
479
480                 printk(BIOS_SPEW, "%s%s %02lx *  [0x%llx - 0x%llx] %s\n",
481                        (resource->flags & IORESOURCE_ASSIGNED) ? "Assigned: "
482                        : "",
483                        dev_path(dev), resource->index, resource->base,
484                        resource->size ? resource->base + resource->size - 1 :
485                        resource->base,
486                        (resource->flags & IORESOURCE_IO) ? "io" :
487                        (resource->flags & IORESOURCE_PREFETCH) ? "prefmem" :
488                        "mem");
489         }
490         /* A PCI bridge resource does not need to be a power of two size, but
491          * it does have a minimum granularity. Round the size up to that
492          * minimum granularity so we know not to place something else at an
493          * address positively decoded by the bridge.
494          */
495
496         bridge->flags |= IORESOURCE_ASSIGNED;
497
498         printk(BIOS_SPEW, "%s %s_%s: next_base: %llx size: %llx align: %d gran: %d done\n",
499                dev_path(bus->dev), __func__,
500                (type & IORESOURCE_IO) ? "io" : (type & IORESOURCE_PREFETCH) ?
501                "prefmem" : "mem",
502                base, bridge->size, bridge->align, bridge->gran);
503
504         /* For each child which is a bridge, allocate_resources. */
505         for (dev = bus->children; dev; dev = dev->sibling) {
506                 struct resource *child_bridge;
507
508                 if (!dev->link_list)
509                         continue;
510
511                 /* Find the resources with matching type flags. */
512                 for (child_bridge = dev->resource_list; child_bridge;
513                      child_bridge = child_bridge->next) {
514                         struct bus* link;
515
516                         if (!(child_bridge->flags & IORESOURCE_BRIDGE) ||
517                             (child_bridge->flags & type_mask) != type)
518                                 continue;
519
520                         /* Split prefetchable memory if combined.  Many domains
521                          * use the same address space for prefetchable memory
522                          * and non-prefetchable memory.  Bridges below them
523                          * need it separated.  Add the PREFETCH flag to the
524                          * type_mask and type.
525                          */
526                         link = dev->link_list;
527                         while (link && link->link_num !=
528                                        IOINDEX_LINK(child_bridge->index))
529                                 link = link->next;
530                         if (link == NULL)
531                                 printk(BIOS_ERR, "link %ld not found on %s\n",
532                                        IOINDEX_LINK(child_bridge->index),
533                                        dev_path(dev));
534                         allocate_resources(link, child_bridge,
535                                            type_mask | IORESOURCE_PREFETCH,
536                                            type | (child_bridge->flags &
537                                                    IORESOURCE_PREFETCH));
538                 }
539         }
540 }
541
542 #if CONFIG_PCI_64BIT_PREF_MEM == 1
543         #define MEM_MASK (IORESOURCE_PREFETCH | IORESOURCE_MEM)
544 #else
545         #define MEM_MASK (IORESOURCE_MEM)
546 #endif
547 #define IO_MASK (IORESOURCE_IO)
548 #define PREF_TYPE (IORESOURCE_PREFETCH | IORESOURCE_MEM)
549 #define MEM_TYPE (IORESOURCE_MEM)
550 #define IO_TYPE (IORESOURCE_IO)
551
552 struct constraints {
553         struct resource pref, io, mem;
554 };
555
556 static void constrain_resources(struct device *dev, struct constraints* limits)
557 {
558         struct device *child;
559         struct resource *res;
560         struct resource *lim;
561         struct bus *link;
562
563         printk(BIOS_SPEW, "%s: %s\n", __func__, dev_path(dev));
564
565         /* Constrain limits based on the fixed resources of this device. */
566         for (res = dev->resource_list; res; res = res->next) {
567                 if (!(res->flags & IORESOURCE_FIXED))
568                         continue;
569                 if (!res->size) {
570                         /* It makes no sense to have 0-sized, fixed resources.*/
571                         printk(BIOS_ERR, "skipping %s@%lx fixed resource, size=0!\n",
572                                    dev_path(dev), res->index);
573                         continue;
574                 }
575
576                 /* PREFETCH, MEM, or I/O - skip any others. */
577                 if ((res->flags & MEM_MASK) == PREF_TYPE)
578                         lim = &limits->pref;
579                 else if ((res->flags & MEM_MASK) == MEM_TYPE)
580                         lim = &limits->mem;
581                 else if ((res->flags & IO_MASK) == IO_TYPE)
582                         lim = &limits->io;
583                 else
584                         continue;
585
586                 /* Is it a fixed resource outside the current known region?
587                    If so, we don't have to consider it - it will be handled
588                    correctly and doesn't affect current region's limits */
589                 if (((res->base + res->size -1) < lim->base) || (res->base > lim->limit))
590                         continue;
591
592                 /* Choose to be above or below fixed resources.  This
593                  * check is signed so that "negative" amounts of space
594                  * are handled correctly.
595                  */
596                 if ((signed long long)(lim->limit - (res->base + res->size -1)) >
597                     (signed long long)(res->base - lim->base))
598                         lim->base = res->base + res->size;
599                 else
600                         lim->limit = res->base -1;
601         }
602
603         /* Descend into every enabled child and look for fixed resources. */
604         for (link = dev->link_list; link; link = link->next)
605                 for (child = link->children; child;
606                      child = child->sibling)
607                         if (child->enabled)
608                                 constrain_resources(child, limits);
609 }
610
611 static void avoid_fixed_resources(struct device *dev)
612 {
613         struct constraints limits;
614         struct resource *res;
615
616         printk(BIOS_SPEW, "%s: %s\n", __func__, dev_path(dev));
617         /* Initialize constraints to maximum size. */
618
619         limits.pref.base = 0;
620         limits.pref.limit = 0xffffffffffffffffULL;
621         limits.io.base = 0;
622         limits.io.limit = 0xffffffffffffffffULL;
623         limits.mem.base = 0;
624         limits.mem.limit = 0xffffffffffffffffULL;
625
626         /* Constrain the limits to dev's initial resources. */
627         for (res = dev->resource_list; res; res = res->next) {
628                 if ((res->flags & IORESOURCE_FIXED))
629                         continue;
630                 printk(BIOS_SPEW, "%s:@%s %02lx limit %08Lx\n", __func__,
631                              dev_path(dev), res->index, res->limit);
632                 if ((res->flags & MEM_MASK) == PREF_TYPE &&
633                     (res->limit < limits.pref.limit))
634                         limits.pref.limit = res->limit;
635                 if ((res->flags & MEM_MASK) == MEM_TYPE &&
636                     (res->limit < limits.mem.limit))
637                         limits.mem.limit = res->limit;
638                 if ((res->flags & IO_MASK) == IO_TYPE &&
639                     (res->limit < limits.io.limit))
640                         limits.io.limit = res->limit;
641         }
642
643         /* Look through the tree for fixed resources and update the limits. */
644         constrain_resources(dev, &limits);
645
646         /* Update dev's resources with new limits. */
647         for (res = dev->resource_list; res; res = res->next) {
648                 struct resource *lim;
649
650                 if ((res->flags & IORESOURCE_FIXED))
651                         continue;
652
653                 /* PREFETCH, MEM, or I/O - skip any others. */
654                 if ((res->flags & MEM_MASK) == PREF_TYPE)
655                         lim = &limits.pref;
656                 else if ((res->flags & MEM_MASK) == MEM_TYPE)
657                         lim = &limits.mem;
658                 else if ((res->flags & IO_MASK) == IO_TYPE)
659                         lim = &limits.io;
660                 else
661                         continue;
662
663                 printk(BIOS_SPEW, "%s2: %s@%02lx limit %08Lx\n", __func__,
664                              dev_path(dev), res->index, res->limit);
665                 printk(BIOS_SPEW, "\tlim->base %08Lx lim->limit %08Lx\n",
666                              lim->base, lim->limit);
667
668                 /* Is the resource outside the limits? */
669                 if (lim->base > res->base)
670                         res->base = lim->base;
671                 if (res->limit > lim->limit)
672                         res->limit = lim->limit;
673         }
674 }
675
676 #if CONFIG_VGA_BRIDGE_SETUP == 1
677 device_t vga_pri = 0;
678 static void set_vga_bridge_bits(void)
679 {
680         /*
681          * FIXME: Modify set_vga_bridge so it is less PCI centric!
682          * This function knows too much about PCI stuff, it should be just
683          * an iterator/visitor.
684          */
685
686         /* FIXME: Handle the VGA palette snooping. */
687         struct device *dev, *vga, *vga_onboard, *vga_first, *vga_last;
688         struct bus *bus;
689         bus = 0;
690         vga = 0;
691         vga_onboard = 0;
692         vga_first = 0;
693         vga_last = 0;
694         for (dev = all_devices; dev; dev = dev->next) {
695                 if (!dev->enabled)
696                         continue;
697                 if (((dev->class >> 16) == PCI_BASE_CLASS_DISPLAY) &&
698                     ((dev->class >> 8) != PCI_CLASS_DISPLAY_OTHER)) {
699                         if (!vga_first) {
700                                 if (dev->on_mainboard) {
701                                         vga_onboard = dev;
702                                 } else {
703                                         vga_first = dev;
704                                 }
705                         } else {
706                                 if (dev->on_mainboard) {
707                                         vga_onboard = dev;
708                                 } else {
709                                         vga_last = dev;
710                                 }
711                         }
712
713                         /* It isn't safe to enable other VGA cards. */
714                         dev->command &= ~(PCI_COMMAND_MEMORY | PCI_COMMAND_IO);
715                 }
716         }
717
718         vga = vga_last;
719
720         if (!vga) {
721                 vga = vga_first;
722         }
723 #if CONFIG_CONSOLE_VGA_ONBOARD_AT_FIRST == 1
724         if (vga_onboard)        // Will use on board VGA as pri.
725 #else
726         if (!vga)               // Will use last add on adapter as pri.
727 #endif
728         {
729                 vga = vga_onboard;
730         }
731
732         if (vga) {
733                 /* VGA is first add on card or the only onboard VGA. */
734                 printk(BIOS_DEBUG, "Setting up VGA for %s\n", dev_path(vga));
735                 /* All legacy VGA cards have MEM & I/O space registers. */
736                 vga->command |= (PCI_COMMAND_MEMORY | PCI_COMMAND_IO);
737                 vga_pri = vga;
738                 bus = vga->bus;
739         }
740         /* Now walk up the bridges setting the VGA enable. */
741         while (bus) {
742                 printk(BIOS_DEBUG, "Setting PCI_BRIDGE_CTL_VGA for bridge %s\n",
743                              dev_path(bus->dev));
744                 bus->bridge_ctrl |= PCI_BRIDGE_CTL_VGA;
745                 bus = (bus == bus->dev->bus) ? 0 : bus->dev->bus;
746         }
747 }
748
749 #endif
750
751 /**
752  * @brief  Assign the computed resources to the devices on the bus.
753  *
754  * @param bus Pointer to the structure for this bus
755  *
756  * Use the device specific set_resources method to store the computed
757  * resources to hardware. For bridge devices, the set_resources() method
758  * has to recurse into every down stream buses.
759  *
760  * Mutual recursion:
761  *      assign_resources() -> device_operation::set_resources()
762  *      device_operation::set_resources() -> assign_resources()
763  */
764 void assign_resources(struct bus *bus)
765 {
766         struct device *curdev;
767
768         printk(BIOS_SPEW, "%s assign_resources, bus %d link: %d\n",
769                     dev_path(bus->dev), bus->secondary, bus->link_num);
770
771         for (curdev = bus->children; curdev; curdev = curdev->sibling) {
772                 if (!curdev->enabled || !curdev->resource_list) {
773                         continue;
774                 }
775                 if (!curdev->ops || !curdev->ops->set_resources) {
776                         printk(BIOS_ERR, "%s missing set_resources\n",
777                                    dev_path(curdev));
778                         continue;
779                 }
780                 curdev->ops->set_resources(curdev);
781         }
782         printk(BIOS_SPEW, "%s assign_resources, bus %d link: %d\n",
783                     dev_path(bus->dev), bus->secondary, bus->link_num);
784 }
785
786 /**
787  * @brief Enable the resources for devices on a link
788  *
789  * @param link the link whose devices' resources are to be enabled
790  *
791  * Enable resources of the device by calling the device specific
792  * enable_resources() method.
793  *
794  * The parent's resources should be enabled first to avoid having enabling
795  * order problem. This is done by calling the parent's enable_resources()
796  * method before its childrens' enable_resources() methods.
797  *
798  */
799 static void enable_resources(struct bus *link)
800 {
801         struct device *dev;
802         struct bus *c_link;
803
804         for (dev = link->children; dev; dev = dev->sibling) {
805                 if (dev->enabled && dev->ops && dev->ops->enable_resources) {
806                         dev->ops->enable_resources(dev);
807                 }
808         }
809
810         for (dev = link->children; dev; dev = dev->sibling) {
811                 for (c_link = dev->link_list; c_link; c_link = c_link->next) {
812                         enable_resources(c_link);
813                 }
814         }
815 }
816
817 /**
818  * @brief Reset all of the devices a bus
819  *
820  * Reset all of the devices on a bus and clear the bus's reset_needed flag.
821  *
822  * @param bus pointer to the bus structure
823  *
824  * @return 1 if the bus was successfully reset, 0 otherwise.
825  *
826  */
827 int reset_bus(struct bus *bus)
828 {
829         if (bus && bus->dev && bus->dev->ops && bus->dev->ops->reset_bus) {
830                 bus->dev->ops->reset_bus(bus);
831                 bus->reset_needed = 0;
832                 return 1;
833         }
834         return 0;
835 }
836
837 /**
838  * @brief Scan for devices on a bus.
839  *
840  * If there are bridges on the bus, recursively scan the buses behind the
841  * bridges. If the setting up and tuning of the bus causes a reset to be
842  * required, reset the bus and scan it again.
843  *
844  * @param busdev Pointer to the bus device.
845  * @param max Current bus number.
846  * @return The maximum bus number found, after scanning all subordinate buses.
847  */
848 unsigned int scan_bus(struct device *busdev, unsigned int max)
849 {
850         unsigned int new_max;
851         int do_scan_bus;
852         if (!busdev || !busdev->enabled || !busdev->ops ||
853             !busdev->ops->scan_bus) {
854                 return max;
855         }
856
857         do_scan_bus = 1;
858         while (do_scan_bus) {
859                 struct bus *link;
860                 new_max = busdev->ops->scan_bus(busdev, max);
861                 do_scan_bus = 0;
862                 for (link = busdev->link_list; link; link = link->next) {
863                         if (link->reset_needed) {
864                                 if (reset_bus(link)) {
865                                         do_scan_bus = 1;
866                                 } else {
867                                         busdev->bus->reset_needed = 1;
868                                 }
869                         }
870                 }
871         }
872         return new_max;
873 }
874
875 /**
876  * @brief Determine the existence of devices and extend the device tree.
877  *
878  * Most of the devices in the system are listed in the mainboard Config.lb
879  * file. The device structures for these devices are generated at compile
880  * time by the config tool and are organized into the device tree. This
881  * function determines if the devices created at compile time actually exist
882  * in the physical system.
883  *
884  * For devices in the physical system but not listed in the Config.lb file,
885  * the device structures have to be created at run time and attached to the
886  * device tree.
887  *
888  * This function starts from the root device 'dev_root', scan the buses in
889  * the system recursively, modify the device tree according to the result of
890  * the probe.
891  *
892  * This function has no idea how to scan and probe buses and devices at all.
893  * It depends on the bus/device specific scan_bus() method to do it. The
894  * scan_bus() method also has to create the device structure and attach
895  * it to the device tree.
896  */
897 void dev_enumerate(void)
898 {
899         struct device *root;
900         printk(BIOS_INFO, "Enumerating buses...\n");
901         root = &dev_root;
902
903         show_all_devs(BIOS_SPEW, "Before Device Enumeration.");
904         printk(BIOS_SPEW, "Compare with tree...\n");
905         show_devs_tree(root, BIOS_SPEW, 0, 0);
906
907         if (root->chip_ops && root->chip_ops->enable_dev) {
908                 root->chip_ops->enable_dev(root);
909         }
910         if (!root->ops || !root->ops->scan_bus) {
911                 printk(BIOS_ERR, "dev_root missing scan_bus operation");
912                 return;
913         }
914         scan_bus(root, 0);
915         printk(BIOS_INFO, "done\n");
916 }
917
918 /**
919  * @brief Configure devices on the devices tree.
920  *
921  * Starting at the root of the device tree, travel it recursively in two
922  * passes. In the first pass, we compute and allocate resources (ranges)
923  * requried by each device. In the second pass, the resources ranges are
924  * relocated to their final position and stored to the hardware.
925  *
926  * I/O resources grow upward. MEM resources grow downward.
927  *
928  * Since the assignment is hierarchical we set the values into the dev_root
929  * struct.
930  */
931 void dev_configure(void)
932 {
933         struct resource *res;
934         struct device *root;
935         struct device *child;
936
937 #if CONFIG_VGA_BRIDGE_SETUP == 1
938         set_vga_bridge_bits();
939 #endif
940
941         printk(BIOS_INFO, "Allocating resources...\n");
942
943         root = &dev_root;
944
945         /* Each domain should create resources which contain the entire address
946          * space for IO, MEM, and PREFMEM resources in the domain. The
947          * allocation of device resources will be done from this address space.
948          */
949
950         /* Read the resources for the entire tree. */
951
952         printk(BIOS_INFO, "Reading resources...\n");
953         read_resources(root->link_list);
954         printk(BIOS_INFO, "Done reading resources.\n");
955
956         print_resource_tree(root, BIOS_SPEW, "After reading.");
957
958         /* Compute resources for all domains. */
959         for (child = root->link_list->children; child; child = child->sibling) {
960                 if (!(child->path.type == DEVICE_PATH_PCI_DOMAIN))
961                         continue;
962                 for (res = child->resource_list; res; res = res->next) {
963                         if (res->flags & IORESOURCE_FIXED)
964                                 continue;
965                         if (res->flags & IORESOURCE_PREFETCH) {
966                                 compute_resources(child->link_list,
967                                                res, MEM_MASK, PREF_TYPE);
968                                 continue;
969                         }
970                         if (res->flags & IORESOURCE_MEM) {
971                                 compute_resources(child->link_list,
972                                                res, MEM_MASK, MEM_TYPE);
973                                 continue;
974                         }
975                         if (res->flags & IORESOURCE_IO) {
976                                 compute_resources(child->link_list,
977                                                res, IO_MASK, IO_TYPE);
978                                 continue;
979                         }
980                 }
981         }
982
983         /* For all domains. */
984         for (child = root->link_list->children; child; child=child->sibling)
985                 if (child->path.type == DEVICE_PATH_PCI_DOMAIN)
986                         avoid_fixed_resources(child);
987
988         /* Now we need to adjust the resources. MEM resources need to start at
989          * the highest address managable.
990          */
991         for (child = root->link_list->children; child; child = child->sibling) {
992                 if (child->path.type != DEVICE_PATH_PCI_DOMAIN)
993                         continue;
994                 for (res = child->resource_list; res; res = res->next) {
995                         if (!(res->flags & IORESOURCE_MEM) ||
996                             res->flags & IORESOURCE_FIXED)
997                                 continue;
998                         res->base = resource_max(res);
999                 }
1000         }
1001
1002         /* Store the computed resource allocations into device registers ... */
1003         printk(BIOS_INFO, "Setting resources...\n");
1004         for (child = root->link_list->children; child; child = child->sibling) {
1005                 if (!(child->path.type == DEVICE_PATH_PCI_DOMAIN))
1006                         continue;
1007                 for (res = child->resource_list; res; res = res->next) {
1008                         if (res->flags & IORESOURCE_FIXED)
1009                                 continue;
1010                         if (res->flags & IORESOURCE_PREFETCH) {
1011                                 allocate_resources(child->link_list,
1012                                                res, MEM_MASK, PREF_TYPE);
1013                                 continue;
1014                         }
1015                         if (res->flags & IORESOURCE_MEM) {
1016                                 allocate_resources(child->link_list,
1017                                                res, MEM_MASK, MEM_TYPE);
1018                                 continue;
1019                         }
1020                         if (res->flags & IORESOURCE_IO) {
1021                                 allocate_resources(child->link_list,
1022                                                res, IO_MASK, IO_TYPE);
1023                                 continue;
1024                         }
1025                 }
1026         }
1027         assign_resources(root->link_list);
1028         printk(BIOS_INFO, "Done setting resources.\n");
1029         print_resource_tree(root, BIOS_SPEW, "After assigning values.");
1030
1031         printk(BIOS_INFO, "Done allocating resources.\n");
1032 }
1033
1034 /**
1035  * @brief Enable devices on the device tree.
1036  *
1037  * Starting at the root, walk the tree and enable all devices/bridges by
1038  * calling the device's enable_resources() method.
1039  */
1040 void dev_enable(void)
1041 {
1042         struct bus *link;
1043
1044         printk(BIOS_INFO, "Enabling resources...\n");
1045
1046         /* now enable everything. */
1047         for (link = dev_root.link_list; link; link = link->next)
1048                 enable_resources(link);
1049
1050         printk(BIOS_INFO, "done.\n");
1051 }
1052
1053 /**
1054  * @brief Initialize a specific device
1055  *
1056  * @param dev the device to be initialized
1057  *
1058  * The parent should be initialized first to avoid having an ordering
1059  * problem. This is done by calling the parent's init()
1060  * method before its childrens' init() methods.
1061  *
1062  */
1063 static void init_dev(struct device *dev)
1064 {
1065         if (!dev->enabled) {
1066                 return;
1067         }
1068
1069         if (!dev->initialized && dev->ops && dev->ops->init) {
1070                 if (dev->path.type == DEVICE_PATH_I2C) {
1071                         printk(BIOS_DEBUG, "smbus: %s[%d]->",
1072                                dev_path(dev->bus->dev), dev->bus->link_num);
1073                 }
1074
1075                 printk(BIOS_DEBUG, "%s init\n", dev_path(dev));
1076                 dev->initialized = 1;
1077                 dev->ops->init(dev);
1078         }
1079 }
1080
1081 static void init_link(struct bus *link)
1082 {
1083         struct device *dev;
1084         struct bus *c_link;
1085
1086         for (dev = link->children; dev; dev = dev->sibling) {
1087                 init_dev(dev);
1088         }
1089
1090         for (dev = link->children; dev; dev = dev->sibling) {
1091                 for (c_link = dev->link_list; c_link; c_link = c_link->next) {
1092                         init_link(c_link);
1093                 }
1094         }
1095 }
1096
1097 /**
1098  * @brief Initialize all devices in the global device tree.
1099  *
1100  * Starting at the root device, call the device's init() method to do device-
1101  * specific setup, then call each child's init() method.
1102  */
1103 void dev_initialize(void)
1104 {
1105         struct bus *link;
1106
1107         printk(BIOS_INFO, "Initializing devices...\n");
1108
1109         /* First call the mainboard init. */
1110         init_dev(&dev_root);
1111
1112         /* now initialize everything. */
1113         for (link = dev_root.link_list; link; link = link->next)
1114                 init_link(link);
1115
1116         printk(BIOS_INFO, "Devices initialized\n");
1117         show_all_devs(BIOS_SPEW, "After init.");
1118 }