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