use #define macro for pci class ids
[coreboot.git] / src / devices / device.c
1 /*
2  *      (c) 1999--2000 Martin Mares <mj@suse.cz>
3  *      (c) 2003 Eric Biederman <ebiederm@xmission.com>
4  *      (c) 2003 Linux Networx
5  */
6 /* lots of mods by ron minnich (rminnich@lanl.gov), with 
7  * the final architecture guidance from Tom Merritt (tjm@codegen.com)
8  * In particular, we changed from the one-pass original version to 
9  * Tom's recommended multiple-pass version. I wasn't sure about doing 
10  * it with multiple passes, until I actually started doing it and saw
11  * the wisdom of Tom's recommendations ...
12  *
13  * Lots of cleanups by Eric Biederman to handle bridges, and to
14  * handle resource allocation for non-pci devices.
15  */
16
17 #include <console/console.h>
18 #include <bitops.h>
19 #include <arch/io.h>
20 #include <device/device.h>
21 #include <device/pci.h>
22 #include <device/pci_ids.h>
23 #include <stdlib.h>
24 #include <string.h>
25
26 /** Linked list of ALL devices */
27 struct device *all_devices = &dev_root;
28 /** Pointer to the last device */
29 static struct device **last_dev_p = &dev_root.next;
30
31 /** The upper limit of MEM resource of the devices.
32  * Reserve 20M for the system */
33 #define DEVICE_MEM_HIGH 0xFEC00000UL
34 /** The lower limit of IO resource of the devices.
35  * Reserve 4k for ISA/Legacy devices */
36 #define DEVICE_IO_START 0x1000
37
38 /**
39  * @brief Allocate a new device structure.
40  * 
41  * Allocte a new device structure and attached it to the device tree as a
42  * child of the parent bus.
43  *
44  * @param parent parent bus the newly created device attached to.
45  * @param path path to the device to be created.
46  *
47  * @return pointer to the newly created device structure.
48  *
49  * @see device_path
50  */
51 device_t alloc_dev(struct bus *parent, struct device_path *path)
52 {
53         device_t dev, child;
54         int link;
55
56         /* Find the last child of our parent */
57         for (child = parent->children; child && child->sibling; ) {
58                 child = child->sibling;
59         }
60
61         dev = malloc(sizeof(*dev));
62         if (dev == 0) {
63                 die("DEV: out of memory.\n");
64         }
65         memset(dev, 0, sizeof(*dev));
66         memcpy(&dev->path, path, sizeof(*path));
67
68         /* Append a new device to the global device list.
69          * The list is used to find devices once everything is set up.
70          */
71         *last_dev_p = dev;
72         last_dev_p = &dev->next;
73
74         /* Initialize the back pointers in the link fields */
75         for (link = 0; link < MAX_LINKS; link++) {
76                 dev->link[link].dev  = dev;
77                 dev->link[link].link = link;
78         }
79
80         /* Add the new device as a children of the bus. */
81         dev->bus = parent;
82         if (child) {
83                 child->sibling = dev;
84         } else {
85                 parent->children = dev;
86         }
87
88         /* If we don't have any other information about a device enable it */
89         dev->enabled = 1;
90
91         return dev;
92 }
93
94 /**
95  * @brief round a number up to an alignment. 
96  * @param val the starting value
97  * @param roundup Alignment as a power of two
98  * @returns rounded up number
99  */
100 static unsigned long round(unsigned long val, unsigned long roundup)
101 {
102         /* ROUNDUP MUST BE A POWER OF TWO. */
103         unsigned long inverse;
104         inverse = ~(roundup - 1);
105         val += (roundup - 1);
106         val &= inverse;
107         return val;
108 }
109
110 static unsigned long round_down(unsigned long val, unsigned long round_down)
111 {
112         /* ROUND_DOWN MUST BE A POWER OF TWO. */
113         unsigned long inverse;
114         inverse = ~(round_down - 1);
115         val &= inverse;
116         return val;
117 }
118
119
120 /** Read the resources on all devices of a given bus.
121  * @param bus bus to read the resources on.
122  */
123 static void read_resources(struct bus *bus)
124 {
125         struct device *curdev;
126
127         /* Walk through all of the devices and find which resources they need. */
128         for (curdev = bus->children; curdev; curdev = curdev->sibling) {
129                 unsigned links;
130                 int i;
131                 if (curdev->resources > 0) {
132                         continue;
133                 }
134                 if (!curdev->ops || !curdev->ops->read_resources) {
135                         printk_err("%s missing read_resources\n",
136                                    dev_path(curdev));
137                         continue;
138                 }
139                 if (!curdev->enabled) {
140                         continue;
141                 }
142
143                 curdev->ops->read_resources(curdev);
144
145                 /* Read in subtractive resources behind the current device */
146                 links = 0;
147                 for (i = 0; i < curdev->resources; i++) {
148                         struct resource *resource;
149                         resource = &curdev->resource[i];
150                         if ((resource->flags & IORESOURCE_SUBTRACTIVE) &&
151                             (!(links & (1 << resource->index))))
152                         {
153                                 links |= (1 << resource->index);
154                                 read_resources(&curdev->link[resource->index]);
155                                 
156                         }
157                 }
158         }
159 }
160
161 struct pick_largest_state {
162         struct resource *last;
163         struct device   *result_dev;
164         struct resource *result;
165         int seen_last;
166 };
167
168 static void pick_largest_resource(struct pick_largest_state *state,
169                                   struct device *dev, struct resource *resource)
170 {
171         struct resource *last;
172         last = state->last;
173         /* Be certain to pick the successor to last */
174         if (resource == last) {
175                 state->seen_last = 1;
176                 return;
177         }
178         if (last &&
179             ((last->align < resource->align) ||
180              ((last->align == resource->align) &&
181               (last->size < resource->size)) ||
182              ((last->align == resource->align) &&
183               (last->size == resource->size) &&
184               (!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 void find_largest_resource(struct pick_largest_state *state, 
197                                   struct bus *bus, unsigned long type_mask,
198                                   unsigned long type)
199 {
200         struct device *curdev;
201
202         for (curdev = bus->children; curdev; curdev = curdev->sibling) {
203                 int i;
204                 for (i = 0; i < curdev->resources; i++) {
205                         struct resource *resource = &curdev->resource[i];
206                         /* If it isn't the right kind of resource ignore it */
207                         if ((resource->flags & type_mask) != type) {
208                                 continue;
209                         }
210                         /* If it is a subtractive resource recurse */
211                         if (resource->flags & IORESOURCE_SUBTRACTIVE) {
212                                 struct bus *subbus;
213                                 subbus = &curdev->link[resource->index];
214                                 find_largest_resource(state, subbus,
215                                                       type_mask, type);
216                                 continue;
217                         }
218                         /* See if this is the largest resource */
219                         pick_largest_resource(state, curdev, resource);
220                 }
221         }
222 }
223
224 static struct device *largest_resource(struct bus *bus,
225                                        struct resource **result_res,
226                                        unsigned long type_mask,
227                                        unsigned long type)
228 {
229         struct pick_largest_state state;
230
231         state.last = *result_res;
232         state.result_dev = 0;
233         state.result = 0;
234         state.seen_last = 0;
235
236         find_largest_resource(&state, bus, type_mask, type);
237
238         *result_res = state.result;
239         return state.result_dev;
240 }
241
242 /* Compute allocate resources is the guts of the resource allocator.
243  * 
244  * The problem.
245  *  - Allocate resources locations for every device.
246  *  - Don't overlap, and follow the rules of bridges.
247  *  - Don't overlap with resources in fixed locations.
248  *  - Be efficient so we don't have ugly strategies.
249  *
250  * The strategy.
251  * - Devices that have fixed addresses are the minority so don't
252  *   worry about them too much.  Instead only use part of the address
253  *   space for devices with programmable addresses.  This easily handles
254  *   everything except bridges.
255  *
256  * - PCI devices are required to have thier sizes and their alignments
257  *   equal.  In this case an optimal solution to the packing problem
258  *   exists.  Allocate all devices from highest alignment to least
259  *   alignment or vice versa.  Use this.
260  *
261  * - So we can handle more than PCI run two allocation passes on
262  *   bridges.  The first to see how large the resources are behind
263  *   the bridge, and what their alignment requirements are.  The
264  *   second to assign a safe address to the devices behind the
265  *   bridge.  This allows me to treat a bridge as just a device with 
266  *   a couple of resources, and not need to special case it in the
267  *   allocator.  Also this allows handling of other types of bridges.
268  *
269  */
270
271 void compute_allocate_resource(
272         struct bus *bus,
273         struct resource *bridge,
274         unsigned long type_mask,
275         unsigned long type)
276 {
277         struct device *dev;
278         struct resource *resource;
279         unsigned long base;
280         unsigned long align, min_align;
281         min_align = 0;
282         base = bridge->base;
283
284         printk_spew("%s compute_allocate_%s: base: %08lx size: %08lx "
285                     "align: %d gran: %d\n", 
286                     dev_path(bus->dev),
287                     (bridge->flags & IORESOURCE_IO)? "io":
288                     (bridge->flags & IORESOURCE_PREFETCH)? "prefmem" : "mem",
289                     base, bridge->size, bridge->align, bridge->gran);
290
291         /* We want different minimum alignments for different kinds of
292          * resources.  These minimums are not device type specific
293          * but resource type specific.
294          */
295         if (bridge->flags & IORESOURCE_IO) {
296                 min_align = log2(DEVICE_IO_ALIGN);
297         }
298         if (bridge->flags & IORESOURCE_MEM) {
299                 min_align = log2(DEVICE_MEM_ALIGN);
300         }
301
302         /* Make certain I have read in all of the resources */
303         read_resources(bus);
304
305         /* Remember I haven't found anything yet. */
306         resource = 0;
307
308         /* Walk through all the devices on the current bus and compute the
309          * addresses */
310         while ((dev = largest_resource(bus, &resource, type_mask, type))) {
311                 unsigned long size;
312                 /* Do NOT I repeat do not ignore resources which have zero size.
313                  * If they need to be ignored dev->read_resources should not even
314                  * return them.   Some resources must be set even when they have
315                  * no size.  PCI bridge resources are a good example of this.
316                  */
317
318                 /* Propogate the resource alignment to the bridge register  */
319                 if (resource->align > bridge->align) {
320                         bridge->align = resource->align;
321                 }
322
323                 /* Make certain we are dealing with a good minimum size */
324                 size = resource->size;
325                 align = resource->align;
326                 if (align < min_align) {
327                         align = min_align;
328                 }
329                 if (resource->flags & IORESOURCE_FIXED) {
330                         continue;
331                 }
332                 if (resource->flags & IORESOURCE_IO) {
333                         /* Don't allow potential aliases over the
334                          * legacy pci expansion card addresses.
335                          * The legacy pci decodes only 10 bits,
336                          * uses 100h - 3ffh. Therefor, only 0 - ff
337                          * can be used out of each 400h block of io
338                          * space.
339                          */
340                         if ((base & 0x300) != 0) {
341                                 base = (base & ~0x3ff) + 0x400;
342                         }
343                         /* Don't allow allocations in the VGA IO range.
344                          * PCI has special cases for that.
345                          */
346                         else if ((base >= 0x3b0) && (base <= 0x3df)) {
347                                 base = 0x3e0;
348                         }
349                 }
350                 if (((round(base, 1UL << align) + size) -1) <= resource->limit) {
351                         /* base must be aligned to size */
352                         base = round(base, 1UL << align);
353                         resource->base = base;
354                         resource->flags |= IORESOURCE_ASSIGNED;
355                         resource->flags &= ~IORESOURCE_STORED;
356                         base += size;
357                         
358                         printk_spew("%s %02x *  [0x%08lx - 0x%08lx] %s\n",
359                                     dev_path(dev),
360                                     resource->index, resource->base,
361                                     resource->base + resource->size - 1,
362                                     (resource->flags & IORESOURCE_IO)? "io":
363                                     (resource->flags & IORESOURCE_PREFETCH)? "prefmem": "mem");
364                 }
365         }
366         /* A pci bridge resource does not need to be a power
367          * of two size, but it does have a minimum granularity.
368          * Round the size up to that minimum granularity so we
369          * know not to place something else at an address postitively
370          * decoded by the bridge.
371          */
372         bridge->size = round(base, 1UL << bridge->gran) - bridge->base;
373
374         printk_spew("%s compute_allocate_%s: base: %08lx size: %08lx align: %d gran: %d done\n", 
375                     dev_path(dev),
376                     (bridge->flags & IORESOURCE_IO)? "io":
377                     (bridge->flags & IORESOURCE_PREFETCH)? "prefmem" : "mem",
378                     base, bridge->size, bridge->align, bridge->gran);
379
380
381 }
382
383 static void allocate_vga_resource(void)
384 {
385 #warning "FIXME modify allocate_vga_resource so it is less pci centric!"
386 #warning "This function knows to much about PCI stuff, it should be just a ietrator/visitor."
387
388         /* FIXME handle the VGA pallette snooping */
389         struct device *dev, *vga = 0;
390         struct bus *bus = 0;
391
392         for (dev = all_devices; dev; dev = dev->next) {
393                 if (((dev->class >> 16) == PCI_BASE_CLASS_DISPLAY) &&
394                     ((dev->class >> 8)  != PCI_CLASS_DISPLAY_OTHER)) {
395                         if (!vga) {
396                                 printk_debug("Allocating VGA resource %s\n", dev_path(dev));
397                                 vga = dev;
398                         }
399                         if (vga == dev) {
400                                 /* All legacy VGA cards have MEM & I/O space registers */
401                                 dev->command |= PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
402                         } else {
403                                 /* It isn't safe to enable other VGA cards */
404                                 dev->command &= ~(PCI_COMMAND_MEMORY | PCI_COMMAND_IO);
405                         }
406                 }
407         }
408         if (vga) {
409                 bus = vga->bus;
410         }
411
412         /* Now walk up the bridges setting the VGA enable */
413         while (bus) {
414                 bus->bridge_ctrl |= PCI_BRIDGE_CTL_VGA;
415                 bus = (bus == bus->dev->bus)? 0 : bus->dev->bus;
416         } 
417 }
418
419
420 /** Assign the computed resources to the bridges and devices on the bus.
421  * Recurse to any bridges found on this bus first. Then do the devices
422  * on this bus.
423  * 
424  * @param bus Pointer to the structure for this bus
425  */ 
426 void assign_resources(struct bus *bus)
427 {
428         struct device *curdev;
429
430         printk_debug("ASSIGN RESOURCES, bus %d\n", bus->secondary);
431
432         for (curdev = bus->children; curdev; curdev = curdev->sibling) {
433                 if (!curdev->ops || !curdev->ops->set_resources) {
434                         printk_err("%s missing set_resources\n",
435                                    dev_path(curdev));
436                         continue;
437                 }
438                 if (!curdev->enabled) {
439                         continue;
440                 }
441                 curdev->ops->set_resources(curdev);
442         }
443         printk_debug("ASSIGNED RESOURCES, bus %d\n", bus->secondary);
444 }
445
446 /**
447  * @brief Enable the resources for a specific device
448  *
449  * @param dev the device whose resources are to be enabled
450  *
451  * Enable resources of the device by calling the device specific
452  * enable_resources() method.
453  *
454  * The parent's resources should be enabled first to avoid having enabling
455  * order problem. This is done by calling the parent's enable_resources()
456  * method and let that method to call it's children's enable_resoruces() via
457  * enable_childrens_resources().
458  *
459  * Indirect mutual recursion:
460  */
461 void enable_resources(struct device *dev)
462 {
463         if (!dev->ops || !dev->ops->enable_resources) {
464                 printk_err("%s missing enable_resources\n", dev_path(dev));
465                 return;
466         }
467         if (!dev->enabled) {
468                 return;
469         }
470         dev->ops->enable_resources(dev);
471 }
472
473 /**
474  * @brief Determine the existence of dynamic devices and construct dynamic
475  * device tree.
476  *
477  * Start form the root device 'dev_root', scan the buses in the system
478  * recursively, build the dynamic device tree according to the result
479  * of the probe.
480  *
481  * This function has no idea how to scan and probe buses and devices at all.
482  * It depends on the bus/device specific scan_bus() method to do it. The
483  * scan_bus() function also have to create the device structure and attach
484  * it to the device tree. 
485  */
486 void dev_enumerate(void)
487 {
488         struct device *root;
489         unsigned subordinate;
490
491         printk_info("Enumerating buses...\n");
492
493         root = &dev_root;
494         subordinate = root->ops->scan_bus(root, 0);
495
496         printk_info("done\n");
497 }
498
499 /**
500  * @brief Configure devices on the devices tree.
501  * 
502  * Starting at the root of the dynamic device tree, travel recursively,
503  * compute resources needed by each device and allocate them.
504  *
505  * I/O resources start at DEVICE_IO_START and grow upward. MEM resources start
506  * at DEVICE_MEM_START and grow downward.
507  *
508  * Since the assignment is hierarchical we set the values into the dev_root
509  * struct. 
510  */
511 void dev_configure(void)
512 {
513         struct device *root = &dev_root;
514
515         printk_info("Allocating resources...\n");
516
517         root->ops->read_resources(root);
518
519         /* Make certain the io devices are allocated somewhere safe. */
520         root->resource[0].base = DEVICE_IO_START;
521         root->resource[0].flags |= IORESOURCE_ASSIGNED;
522         root->resource[0].flags &= ~IORESOURCE_STORED;
523
524         /* Now reallocate the pci resources memory with the highest
525          * addresses I can manage.*/
526         root->resource[1].base = 
527                 round_down(DEVICE_MEM_HIGH - root->resource[1].size,
528                            1UL << root->resource[1].align);
529         root->resource[1].flags |= IORESOURCE_ASSIGNED;
530         root->resource[1].flags &= ~IORESOURCE_STORED;
531
532         /* Allocate the VGA I/O resource.. */
533         allocate_vga_resource(); 
534
535         /* now just set things into registers ... we hope ... */
536         root->ops->set_resources(root);
537
538         printk_info("done.\n");
539 }
540
541 /**
542  * @brief Enable devices on the device tree.
543  *
544  * Starting at the root, walk the tree and enable all devices/bridges by
545  * calling the device's enable_resources() method.
546  */
547 void dev_enable(void)
548 {
549         printk_info("Enabling resourcess...\n");
550
551         /* now enable everything. */
552         enable_resources(&dev_root);
553
554         printk_info("done.\n");
555 }
556
557 /**
558  * @brief Initialize all devices in the global device list.
559  *
560  * Starting at the first device on the global device link list,
561  * walk the list and call a driver to do device specific setup.
562  */
563 void dev_initialize(void)
564 {
565         struct device *dev;
566
567         printk_info("Initializing devices...\n");
568
569         for (dev = all_devices; dev; dev = dev->next) {
570                 if (dev->enabled && dev->ops && dev->ops->init) {
571                         printk_debug("%s init\n", dev_path(dev));
572                         dev->ops->init(dev);
573                 }
574         }
575
576         printk_info("Devices initialized\n");
577 }