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