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