Use lists instead of arrays for resources in devices to reduce memory usage.
[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_p;
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         int link;
70
71         spin_lock(&dev_lock);
72
73         /* Find the last child of our parent. */
74         for (child = parent->children; child && child->sibling; /* */ ) {
75                 child = child->sibling;
76         }
77
78         dev = malloc(sizeof(*dev));
79         if (dev == 0)
80                 die("DEV: out of memory.\n");
81
82         memset(dev, 0, sizeof(*dev));
83         memcpy(&dev->path, path, sizeof(*path));
84
85         /* Initialize the back pointers in the link fields. */
86         for (link = 0; link < MAX_LINKS; link++) {
87                 dev->link[link].dev = dev;
88                 dev->link[link].link = link;
89         }
90
91         /* By default devices are enabled. */
92         dev->enabled = 1;
93
94         /* Add the new device to the list of children of the bus. */
95         dev->bus = parent;
96         if (child) {
97                 child->sibling = dev;
98         } else {
99                 parent->children = dev;
100         }
101
102         /* Append a new device to the global device list.
103          * The list is used to find devices once everything is set up.
104          */
105         *last_dev_p = dev;
106         last_dev_p = &dev->next;
107
108         spin_unlock(&dev_lock);
109         return dev;
110 }
111
112 /**
113  * @brief round a number up to an alignment.
114  * @param val the starting value
115  * @param roundup Alignment as a power of two
116  * @returns rounded up number
117  */
118 static resource_t round(resource_t val, unsigned long pow)
119 {
120         resource_t mask;
121         mask = (1ULL << pow) - 1ULL;
122         val += mask;
123         val &= ~mask;
124         return val;
125 }
126
127 /** Read the resources on all devices of a given bus.
128  * @param bus bus to read the resources on.
129  */
130 static void read_resources(struct bus *bus)
131 {
132         struct device *curdev;
133
134         printk(BIOS_SPEW, "%s %s bus %x link: %d\n", dev_path(bus->dev), __func__,
135                     bus->secondary, bus->link);
136
137         /* Walk through all devices and find which resources they need. */
138         for (curdev = bus->children; curdev; curdev = curdev->sibling) {
139                 int i;
140                 if (!curdev->enabled) {
141                         continue;
142                 }
143                 if (!curdev->ops || !curdev->ops->read_resources) {
144                         printk(BIOS_ERR, "%s missing read_resources\n",
145                                    dev_path(curdev));
146                         continue;
147                 }
148                 curdev->ops->read_resources(curdev);
149
150                 /* Read in the resources behind the current device's links. */
151                 for (i = 0; i < curdev->links; i++)
152                         read_resources(&curdev->link[i]);
153         }
154         printk(BIOS_SPEW, "%s read_resources bus %d link: %d done\n",
155                     dev_path(bus->dev), bus->secondary, bus->link);
156 }
157
158 struct pick_largest_state {
159         struct resource *last;
160         struct device *result_dev;
161         struct resource *result;
162         int seen_last;
163 };
164
165 static void pick_largest_resource(void *gp, struct device *dev,
166                                   struct resource *resource)
167 {
168         struct pick_largest_state *state = gp;
169         struct resource *last;
170
171         last = state->last;
172
173         /* Be certain to pick the successor to last. */
174         if (resource == last) {
175                 state->seen_last = 1;
176                 return;
177         }
178         if (resource->flags & IORESOURCE_FIXED)
179                 return;         // Skip it.
180         if (last && ((last->align < resource->align) ||
181                      ((last->align == resource->align) &&
182                       (last->size < resource->size)) ||
183                      ((last->align == resource->align) &&
184                       (last->size == resource->size) && (!state->seen_last)))) {
185                 return;
186         }
187         if (!state->result ||
188             (state->result->align < resource->align) ||
189             ((state->result->align == resource->align) &&
190              (state->result->size < resource->size))) {
191                 state->result_dev = dev;
192                 state->result = resource;
193         }
194 }
195
196 static struct device *largest_resource(struct bus *bus,
197                                        struct resource **result_res,
198                                        unsigned long type_mask,
199                                        unsigned long type)
200 {
201         struct pick_largest_state state;
202
203         state.last = *result_res;
204         state.result_dev = NULL;
205         state.result = NULL;
206         state.seen_last = 0;
207
208         search_bus_resources(bus, type_mask, type, pick_largest_resource,
209                              &state);
210
211         *result_res = state.result;
212         return state.result_dev;
213 }
214
215 /* Compute allocate resources is the guts of the resource allocator.
216  *
217  * The problem.
218  *  - Allocate resource locations for every device.
219  *  - Don't overlap, and follow the rules of bridges.
220  *  - Don't overlap with resources in fixed locations.
221  *  - Be efficient so we don't have ugly strategies.
222  *
223  * The strategy.
224  * - Devices that have fixed addresses are the minority so don't
225  *   worry about them too much. Instead only use part of the address
226  *   space for devices with programmable addresses. This easily handles
227  *   everything except bridges.
228  *
229  * - PCI devices are required to have their sizes and their alignments
230  *   equal. In this case an optimal solution to the packing problem
231  *   exists. Allocate all devices from highest alignment to least
232  *   alignment or vice versa. Use this.
233  *
234  * - So we can handle more than PCI run two allocation passes on bridges. The
235  *   first to see how large the resources are behind the bridge, and what
236  *   their alignment requirements are. The second to assign a safe address to
237  *   the devices behind the bridge. This allows us to treat a bridge as just
238  *   a device with a couple of resources, and not need to special case it in
239  *   the allocator. Also this allows handling of other types of bridges.
240  *
241  */
242 static void compute_resources(struct bus *bus, struct resource *bridge,
243                        unsigned long type_mask, unsigned long type)
244 {
245         struct device *dev;
246         struct resource *resource;
247         resource_t base;
248         base = round(bridge->base, bridge->align);
249
250         printk(BIOS_SPEW,  "%s %s_%s: base: %llx size: %llx align: %d gran: %d limit: %llx\n",
251                dev_path(bus->dev), __func__,
252                (type & IORESOURCE_IO) ? "io" : (type & IORESOURCE_PREFETCH) ?
253                "prefmem" : "mem",
254                base, bridge->size, bridge->align, bridge->gran, bridge->limit);
255
256         /* For each child which is a bridge, compute_resource_needs. */
257         for (dev = bus->children; dev; dev = dev->sibling) {
258                 struct resource *child_bridge;
259
260                 if (!dev->links)
261                         continue;
262
263                 /* Find the resources with matching type flags. */
264                 for (child_bridge = dev->resource_list; child_bridge;
265                      child_bridge = child_bridge->next) {
266                         unsigned link;
267
268                         if (!(child_bridge->flags & IORESOURCE_BRIDGE) ||
269                             (child_bridge->flags & type_mask) != type)
270                                 continue;
271
272                         /* Split prefetchable memory if combined.  Many domains
273                          * use the same address space for prefetchable memory
274                          * and non-prefetchable memory.  Bridges below them
275                          * need it separated.  Add the PREFETCH flag to the
276                          * type_mask and type.
277                          */
278                         link = IOINDEX_LINK(child_bridge->index);
279                         compute_resources(&dev->link[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->links)
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                         unsigned 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 = IOINDEX_LINK(child_bridge->index);
527                         allocate_resources(&dev->link[link], child_bridge,
528                                            type_mask | IORESOURCE_PREFETCH,
529                                            type | (child_bridge->flags &
530                                                    IORESOURCE_PREFETCH));
531                 }
532         }
533 }
534
535 #if CONFIG_PCI_64BIT_PREF_MEM == 1
536         #define MEM_MASK (IORESOURCE_PREFETCH | IORESOURCE_MEM)
537 #else
538         #define MEM_MASK (IORESOURCE_MEM)
539 #endif
540 #define IO_MASK (IORESOURCE_IO)
541 #define PREF_TYPE (IORESOURCE_PREFETCH | IORESOURCE_MEM)
542 #define MEM_TYPE (IORESOURCE_MEM)
543 #define IO_TYPE (IORESOURCE_IO)
544
545 struct constraints {
546         struct resource pref, io, mem;
547 };
548
549 static void constrain_resources(struct device *dev, struct constraints* limits)
550 {
551         struct device *child;
552         struct resource *res;
553         struct resource *lim;
554         int i;
555
556         printk(BIOS_SPEW, "%s: %s\n", __func__, dev_path(dev));
557
558         /* Constrain limits based on the fixed resources of this device. */
559         for (res = dev->resource_list; res; res = res->next) {
560                 if (!(res->flags & IORESOURCE_FIXED))
561                         continue;
562                 if (!res->size) {
563                         /* It makes no sense to have 0-sized, fixed resources.*/
564                         printk(BIOS_ERR, "skipping %s@%lx fixed resource, size=0!\n",
565                                    dev_path(dev), res->index);
566                         continue;
567                 }
568
569                 /* PREFETCH, MEM, or I/O - skip any others. */
570                 if ((res->flags & MEM_MASK) == PREF_TYPE)
571                         lim = &limits->pref;
572                 else if ((res->flags & MEM_MASK) == MEM_TYPE)
573                         lim = &limits->mem;
574                 else if ((res->flags & IO_MASK) == IO_TYPE)
575                         lim = &limits->io;
576                 else
577                         continue;
578
579                 /* Is it already outside the limits? */
580                 if (((res->base + res->size -1) < lim->base) || (res->base > lim->limit))
581                         continue;
582
583                 /* Choose to be above or below fixed resources.  This
584                  * check is signed so that "negative" amounts of space
585                  * are handled correctly.
586                  */
587                 if ((signed long long)(lim->limit - (res->base + res->size -1)) >
588                     (signed long long)(res->base - lim->base))
589                         lim->base = res->base + res->size;
590                 else
591                         lim->limit = res->base -1;
592         }
593
594         /* Descend into every enabled child and look for fixed resources. */
595         for (i = 0; i < dev->links; i++)
596                 for (child = dev->link[i].children; child;
597                      child = child->sibling)
598                         if (child->enabled)
599                                 constrain_resources(child, limits);
600 }
601
602 static void avoid_fixed_resources(struct device *dev)
603 {
604         struct constraints limits;
605         struct resource *res;
606
607         printk(BIOS_SPEW, "%s: %s\n", __func__, dev_path(dev));
608         /* Initialize constraints to maximum size. */
609
610         limits.pref.base = 0;
611         limits.pref.limit = 0xffffffffffffffffULL;
612         limits.io.base = 0;
613         limits.io.limit = 0xffffffffffffffffULL;
614         limits.mem.base = 0;
615         limits.mem.limit = 0xffffffffffffffffULL;
616
617         /* Constrain the limits to dev's initial resources. */
618         for (res = dev->resource_list; res; res = res->next) {
619                 if ((res->flags & IORESOURCE_FIXED))
620                         continue;
621                 printk(BIOS_SPEW, "%s:@%s %02lx limit %08Lx\n", __func__,
622                              dev_path(dev), res->index, res->limit);
623                 if ((res->flags & MEM_MASK) == PREF_TYPE &&
624                     (res->limit < limits.pref.limit))
625                         limits.pref.limit = res->limit;
626                 if ((res->flags & MEM_MASK) == MEM_TYPE &&
627                     (res->limit < limits.mem.limit))
628                         limits.mem.limit = res->limit;
629                 if ((res->flags & IO_MASK) == IO_TYPE &&
630                     (res->limit < limits.io.limit))
631                         limits.io.limit = res->limit;
632         }
633
634         /* Look through the tree for fixed resources and update the limits. */
635         constrain_resources(dev, &limits);
636
637         /* Update dev's resources with new limits. */
638         for (res = dev->resource_list; res; res = res->next) {
639                 struct resource *lim;
640
641                 if ((res->flags & IORESOURCE_FIXED))
642                         continue;
643
644                 /* PREFETCH, MEM, or I/O - skip any others. */
645                 if ((res->flags & MEM_MASK) == PREF_TYPE)
646                         lim = &limits.pref;
647                 else if ((res->flags & MEM_MASK) == MEM_TYPE)
648                         lim = &limits.mem;
649                 else if ((res->flags & IO_MASK) == IO_TYPE)
650                         lim = &limits.io;
651                 else
652                         continue;
653
654                 printk(BIOS_SPEW, "%s2: %s@%02lx limit %08Lx\n", __func__,
655                              dev_path(dev), res->index, res->limit);
656                 printk(BIOS_SPEW, "\tlim->base %08Lx lim->limit %08Lx\n",
657                              lim->base, lim->limit);
658
659                 /* Is the resource outside the limits? */
660                 if (lim->base > res->base)
661                         res->base = lim->base;
662                 if (res->limit > lim->limit)
663                         res->limit = lim->limit;
664         }
665 }
666
667 #if CONFIG_VGA_BRIDGE_SETUP == 1
668 device_t vga_pri = 0;
669 static void set_vga_bridge_bits(void)
670 {
671         /*
672          * FIXME: Modify set_vga_bridge so it is less PCI centric!
673          * This function knows too much about PCI stuff, it should be just
674          * an iterator/visitor.
675          */
676
677         /* FIXME: Handle the VGA palette snooping. */
678         struct device *dev, *vga, *vga_onboard, *vga_first, *vga_last;
679         struct bus *bus;
680         bus = 0;
681         vga = 0;
682         vga_onboard = 0;
683         vga_first = 0;
684         vga_last = 0;
685         for (dev = all_devices; dev; dev = dev->next) {
686                 if (!dev->enabled)
687                         continue;
688                 if (((dev->class >> 16) == PCI_BASE_CLASS_DISPLAY) &&
689                     ((dev->class >> 8) != PCI_CLASS_DISPLAY_OTHER)) {
690                         if (!vga_first) {
691                                 if (dev->on_mainboard) {
692                                         vga_onboard = dev;
693                                 } else {
694                                         vga_first = dev;
695                                 }
696                         } else {
697                                 if (dev->on_mainboard) {
698                                         vga_onboard = dev;
699                                 } else {
700                                         vga_last = dev;
701                                 }
702                         }
703
704                         /* It isn't safe to enable other VGA cards. */
705                         dev->command &= ~(PCI_COMMAND_MEMORY | PCI_COMMAND_IO);
706                 }
707         }
708
709         vga = vga_last;
710
711         if (!vga) {
712                 vga = vga_first;
713         }
714 #if CONFIG_CONSOLE_VGA_ONBOARD_AT_FIRST == 1
715         if (vga_onboard)        // Will use on board VGA as pri.
716 #else
717         if (!vga)               // Will use last add on adapter as pri.
718 #endif
719         {
720                 vga = vga_onboard;
721         }
722
723         if (vga) {
724                 /* VGA is first add on card or the only onboard VGA. */
725                 printk(BIOS_DEBUG, "Setting up VGA for %s\n", dev_path(vga));
726                 /* All legacy VGA cards have MEM & I/O space registers. */
727                 vga->command |= (PCI_COMMAND_MEMORY | PCI_COMMAND_IO);
728                 vga_pri = vga;
729                 bus = vga->bus;
730         }
731         /* Now walk up the bridges setting the VGA enable. */
732         while (bus) {
733                 printk(BIOS_DEBUG, "Setting PCI_BRIDGE_CTL_VGA for bridge %s\n",
734                              dev_path(bus->dev));
735                 bus->bridge_ctrl |= PCI_BRIDGE_CTL_VGA;
736                 bus = (bus == bus->dev->bus) ? 0 : bus->dev->bus;
737         }
738 }
739
740 #endif
741
742 /**
743  * @brief  Assign the computed resources to the devices on the bus.
744  *
745  * @param bus Pointer to the structure for this bus
746  *
747  * Use the device specific set_resources method to store the computed
748  * resources to hardware. For bridge devices, the set_resources() method
749  * has to recurse into every down stream buses.
750  *
751  * Mutual recursion:
752  *      assign_resources() -> device_operation::set_resources()
753  *      device_operation::set_resources() -> assign_resources()
754  */
755 void assign_resources(struct bus *bus)
756 {
757         struct device *curdev;
758
759         printk(BIOS_SPEW, "%s assign_resources, bus %d link: %d\n",
760                     dev_path(bus->dev), bus->secondary, bus->link);
761
762         for (curdev = bus->children; curdev; curdev = curdev->sibling) {
763                 if (!curdev->enabled || !curdev->resource_list) {
764                         continue;
765                 }
766                 if (!curdev->ops || !curdev->ops->set_resources) {
767                         printk(BIOS_ERR, "%s missing set_resources\n",
768                                    dev_path(curdev));
769                         continue;
770                 }
771                 curdev->ops->set_resources(curdev);
772         }
773         printk(BIOS_SPEW, "%s assign_resources, bus %d link: %d\n",
774                     dev_path(bus->dev), bus->secondary, bus->link);
775 }
776
777 /**
778  * @brief Enable the resources for a specific device
779  *
780  * @param dev the device whose resources are to be enabled
781  *
782  * Enable resources of the device by calling the device specific
783  * enable_resources() method.
784  *
785  * The parent's resources should be enabled first to avoid having enabling
786  * order problem. This is done by calling the parent's enable_resources()
787  * method and let that method to call it's children's enable_resoruces()
788  * method via the (global) enable_childrens_resources().
789  *
790  * Indirect mutual recursion:
791  *      enable_resources() -> device_operations::enable_resource()
792  *      device_operations::enable_resource() -> enable_children_resources()
793  *      enable_children_resources() -> enable_resources()
794  */
795 void enable_resources(struct device *dev)
796 {
797         if (!dev->enabled) {
798                 return;
799         }
800         if (!dev->ops || !dev->ops->enable_resources) {
801                 printk(BIOS_ERR, "%s missing enable_resources\n", dev_path(dev));
802                 return;
803         }
804         dev->ops->enable_resources(dev);
805 }
806
807 /**
808  * @brief Reset all of the devices a bus
809  *
810  * Reset all of the devices on a bus and clear the bus's reset_needed flag.
811  *
812  * @param bus pointer to the bus structure
813  *
814  * @return 1 if the bus was successfully reset, 0 otherwise.
815  *
816  */
817 int reset_bus(struct bus *bus)
818 {
819         if (bus && bus->dev && bus->dev->ops && bus->dev->ops->reset_bus) {
820                 bus->dev->ops->reset_bus(bus);
821                 bus->reset_needed = 0;
822                 return 1;
823         }
824         return 0;
825 }
826
827 /**
828  * @brief Scan for devices on a bus.
829  *
830  * If there are bridges on the bus, recursively scan the buses behind the
831  * bridges. If the setting up and tuning of the bus causes a reset to be
832  * required, reset the bus and scan it again.
833  *
834  * @param busdev Pointer to the bus device.
835  * @param max Current bus number.
836  * @return The maximum bus number found, after scanning all subordinate buses.
837  */
838 unsigned int scan_bus(struct device *busdev, unsigned int max)
839 {
840         unsigned int new_max;
841         int do_scan_bus;
842         if (!busdev || !busdev->enabled || !busdev->ops ||
843             !busdev->ops->scan_bus) {
844                 return max;
845         }
846
847         do_scan_bus = 1;
848         while (do_scan_bus) {
849                 int link;
850                 new_max = busdev->ops->scan_bus(busdev, max);
851                 do_scan_bus = 0;
852                 for (link = 0; link < busdev->links; link++) {
853                         if (busdev->link[link].reset_needed) {
854                                 if (reset_bus(&busdev->link[link])) {
855                                         do_scan_bus = 1;
856                                 } else {
857                                         busdev->bus->reset_needed = 1;
858                                 }
859                         }
860                 }
861         }
862         return new_max;
863 }
864
865 /**
866  * @brief Determine the existence of devices and extend the device tree.
867  *
868  * Most of the devices in the system are listed in the mainboard Config.lb
869  * file. The device structures for these devices are generated at compile
870  * time by the config tool and are organized into the device tree. This
871  * function determines if the devices created at compile time actually exist
872  * in the physical system.
873  *
874  * For devices in the physical system but not listed in the Config.lb file,
875  * the device structures have to be created at run time and attached to the
876  * device tree.
877  *
878  * This function starts from the root device 'dev_root', scan the buses in
879  * the system recursively, modify the device tree according to the result of
880  * the probe.
881  *
882  * This function has no idea how to scan and probe buses and devices at all.
883  * It depends on the bus/device specific scan_bus() method to do it. The
884  * scan_bus() method also has to create the device structure and attach
885  * it to the device tree.
886  */
887 void dev_enumerate(void)
888 {
889         struct device *root;
890         printk(BIOS_INFO, "Enumerating buses...\n");
891         root = &dev_root;
892
893         show_all_devs(BIOS_SPEW, "Before Device Enumeration.");
894         printk(BIOS_SPEW, "Compare with tree...\n");
895         show_devs_tree(root, BIOS_SPEW, 0, 0);
896
897         if (root->chip_ops && root->chip_ops->enable_dev) {
898                 root->chip_ops->enable_dev(root);
899         }
900         if (!root->ops || !root->ops->scan_bus) {
901                 printk(BIOS_ERR, "dev_root missing scan_bus operation");
902                 return;
903         }
904         scan_bus(root, 0);
905         printk(BIOS_INFO, "done\n");
906 }
907
908 /**
909  * @brief Configure devices on the devices tree.
910  *
911  * Starting at the root of the device tree, travel it recursively in two
912  * passes. In the first pass, we compute and allocate resources (ranges)
913  * requried by each device. In the second pass, the resources ranges are
914  * relocated to their final position and stored to the hardware.
915  *
916  * I/O resources grow upward. MEM resources grow downward.
917  *
918  * Since the assignment is hierarchical we set the values into the dev_root
919  * struct.
920  */
921 void dev_configure(void)
922 {
923         struct resource *res;
924         struct device *root;
925         struct device *child;
926
927 #if CONFIG_VGA_BRIDGE_SETUP == 1
928         set_vga_bridge_bits();
929 #endif
930
931         printk(BIOS_INFO, "Allocating resources...\n");
932
933         root = &dev_root;
934
935         /* Each domain should create resources which contain the entire address
936          * space for IO, MEM, and PREFMEM resources in the domain. The
937          * allocation of device resources will be done from this address space.
938          */
939
940         /* Read the resources for the entire tree. */
941
942         printk(BIOS_INFO, "Reading resources...\n");
943         read_resources(&root->link[0]);
944         printk(BIOS_INFO, "Done reading resources.\n");
945
946         print_resource_tree(root, BIOS_SPEW, "After reading.");
947
948         /* Compute resources for all domains. */
949         for (child = root->link[0].children; child; child = child->sibling) {
950                 if (!(child->path.type == DEVICE_PATH_PCI_DOMAIN))
951                         continue;
952                 for (res = child->resource_list; res; res = res->next) {
953                         if (res->flags & IORESOURCE_FIXED)
954                                 continue;
955                         if (res->flags & IORESOURCE_PREFETCH) {
956                                 compute_resources(&child->link[0],
957                                                res, MEM_MASK, PREF_TYPE);
958                                 continue;
959                         }
960                         if (res->flags & IORESOURCE_MEM) {
961                                 compute_resources(&child->link[0],
962                                                res, MEM_MASK, MEM_TYPE);
963                                 continue;
964                         }
965                         if (res->flags & IORESOURCE_IO) {
966                                 compute_resources(&child->link[0],
967                                                res, IO_MASK, IO_TYPE);
968                                 continue;
969                         }
970                 }
971         }
972
973         /* For all domains. */
974         for (child = root->link[0].children; child; child=child->sibling)
975                 if (child->path.type == DEVICE_PATH_PCI_DOMAIN)
976                         avoid_fixed_resources(child);
977
978         /* Now we need to adjust the resources. MEM resources need to start at
979          * the highest address managable.
980          */
981         for (child = root->link[0].children; child; child = child->sibling) {
982                 if (child->path.type != DEVICE_PATH_PCI_DOMAIN)
983                         continue;
984                 for (res = child->resource_list; res; res = res->next) {
985                         if (!(res->flags & IORESOURCE_MEM) ||
986                             res->flags & IORESOURCE_FIXED)
987                                 continue;
988                         res->base = resource_max(res);
989                 }
990         }
991
992         /* Store the computed resource allocations into device registers ... */
993         printk(BIOS_INFO, "Setting resources...\n");
994         for (child = root->link[0].children; child; child = child->sibling) {
995                 if (!(child->path.type == DEVICE_PATH_PCI_DOMAIN))
996                         continue;
997                 for (res = child->resource_list; res; res = res->next) {
998                         if (res->flags & IORESOURCE_FIXED)
999                                 continue;
1000                         if (res->flags & IORESOURCE_PREFETCH) {
1001                                 allocate_resources(&child->link[0],
1002                                                res, MEM_MASK, PREF_TYPE);
1003                                 continue;
1004                         }
1005                         if (res->flags & IORESOURCE_MEM) {
1006                                 allocate_resources(&child->link[0],
1007                                                res, MEM_MASK, MEM_TYPE);
1008                                 continue;
1009                         }
1010                         if (res->flags & IORESOURCE_IO) {
1011                                 allocate_resources(&child->link[0],
1012                                                res, IO_MASK, IO_TYPE);
1013                                 continue;
1014                         }
1015                 }
1016         }
1017         assign_resources(&root->link[0]);
1018         printk(BIOS_INFO, "Done setting resources.\n");
1019         print_resource_tree(root, BIOS_SPEW, "After assigning values.");
1020
1021         printk(BIOS_INFO, "Done allocating resources.\n");
1022 }
1023
1024 /**
1025  * @brief Enable devices on the device tree.
1026  *
1027  * Starting at the root, walk the tree and enable all devices/bridges by
1028  * calling the device's enable_resources() method.
1029  */
1030 void dev_enable(void)
1031 {
1032         printk(BIOS_INFO, "Enabling resources...\n");
1033
1034         /* now enable everything. */
1035         enable_resources(&dev_root);
1036
1037         printk(BIOS_INFO, "done.\n");
1038 }
1039
1040 /**
1041  * @brief Initialize all devices in the global device list.
1042  *
1043  * Starting at the first device on the global device link list,
1044  * walk the list and call the device's init() method to do deivce
1045  * specific setup.
1046  */
1047 void dev_initialize(void)
1048 {
1049         struct device *dev;
1050
1051         printk(BIOS_INFO, "Initializing devices...\n");
1052         for (dev = all_devices; dev; dev = dev->next) {
1053                 if (dev->enabled && !dev->initialized &&
1054                     dev->ops && dev->ops->init) {
1055                         if (dev->path.type == DEVICE_PATH_I2C) {
1056                                 printk(BIOS_DEBUG, "smbus: %s[%d]->",
1057                                              dev_path(dev->bus->dev),
1058                                              dev->bus->link);
1059                         }
1060                         printk(BIOS_DEBUG, "%s init\n", dev_path(dev));
1061                         dev->initialized = 1;
1062                         dev->ops->init(dev);
1063                 }
1064         }
1065         printk(BIOS_INFO, "Devices initialized\n");
1066         show_all_devs(BIOS_SPEW, "After init.");
1067 }