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