a2ded6d17c35e7a62f2a6c9f43e05cef70802b0e
[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(struct pick_largest_state *state, 
173         struct device *dev, struct resource *resource)
174 {
175         struct resource *last;
176         last = state->last;
177         /* Be certain to pick the successor to last */
178         if (resource == last) {
179                 state->seen_last = 1;
180                 return;
181         }
182         if (last && (
183                     (last->align < resource->align) ||
184                     ((last->align == resource->align) &&
185                             (last->size < resource->size)) ||
186                     ((last->align == resource->align) &&
187                             (last->size == resource->size) &&
188                             (!state->seen_last)))) {
189                 return;
190         }
191         if (!state->result || 
192                 (state->result->align < resource->align) ||
193                 ((state->result->align == resource->align) &&
194                         (state->result->size < resource->size))) {
195                 state->result_dev = dev;
196                 state->result = resource;
197         }    
198 }
199
200 static void find_largest_resource(struct pick_largest_state *state, 
201         struct bus *bus, unsigned long type_mask, unsigned long type)
202 {
203         struct device *curdev;
204         for(curdev = bus->children; curdev; curdev = curdev->sibling) {
205                 int i;
206                 for(i = 0; i < curdev->resources; i++) {
207                         struct resource *resource = &curdev->resource[i];
208                         /* If it isn't the right kind of resource ignore it */
209                         if ((resource->flags & type_mask) != type) {
210                                 continue;
211                         }
212                         /* If it is a subtractive resource recurse */
213                         if (resource->flags & IORESOURCE_SUBTRACTIVE) {
214                                 struct bus *subbus;
215                                 subbus = &curdev->link[resource->index];
216                                 find_largest_resource(state, subbus, type_mask, type);
217                                 continue;
218                         }
219                         /* See if this is the largest resource */
220                         pick_largest_resource(state, curdev, resource);
221                 }
222         }
223 }
224
225 static struct device *largest_resource(struct bus *bus, struct resource **result_res,
226         unsigned long type_mask, unsigned long type)
227 {
228         struct pick_largest_state state;
229
230         state.last = *result_res;
231         state.result_dev = 0;
232         state.result = 0;
233         state.seen_last = 0;
234
235         find_largest_resource(&state, bus, type_mask, type);
236
237         *result_res = state.result;
238         return state.result_dev;
239 }
240
241 /* Compute allocate resources is the guts of the resource allocator.
242  * 
243  * The problem.
244  *  - Allocate resources locations for every device.
245  *  - Don't overlap, and follow the rules of bridges.
246  *  - Don't overlap with resources in fixed locations.
247  *  - Be efficient so we don't have ugly strategies.
248  *
249  * The strategy.
250  * - Devices that have fixed addresses are the minority so don't
251  *   worry about them too much.  Instead only use part of the address
252  *   space for devices with programmable addresses.  This easily handles
253  *   everything except bridges.
254  *
255  * - PCI devices are required to have thier sizes and their alignments
256  *   equal.  In this case an optimal solution to the packing problem
257  *   exists.  Allocate all devices from highest alignment to least
258  *   alignment or vice versa.  Use this.
259  *
260  * - So we can handle more than PCI run two allocation passes on
261  *   bridges.  The first to see how large the resources are behind
262  *   the bridge, and what their alignment requirements are.  The
263  *   second to assign a safe address to the devices behind the
264  *   bridge.  This allows me to treat a bridge as just a device with 
265  *   a couple of resources, and not need to special case it in the
266  *   allocator.  Also this allows handling of other types of bridges.
267  *
268  */
269
270 void compute_allocate_resource(
271         struct bus *bus,
272         struct resource *bridge,
273         unsigned long type_mask,
274         unsigned long type)
275 {
276         struct device *dev;
277         struct resource *resource;
278         resource_t base;
279         unsigned long align, min_align;
280         min_align = 0;
281         base = bridge->base;
282
283         printk_spew("%s compute_allocate_%s: base: %08lx size: %08lx align: %d gran: %d\n", 
284                 dev_path(bus->dev),
285                 (bridge->flags & IORESOURCE_IO)? "io":
286                 (bridge->flags & IORESOURCE_PREFETCH)? "prefmem" : "mem",
287                 base, bridge->size, bridge->align, bridge->gran);
288
289
290         /* We want different minimum alignments for different kinds of
291          * resources.  These minimums are not device type specific
292          * but resource type specific.
293          */
294         if (bridge->flags & IORESOURCE_IO) {
295                 min_align = log2(DEVICE_IO_ALIGN);
296         }
297         if (bridge->flags & IORESOURCE_MEM) {
298                 min_align = log2(DEVICE_MEM_ALIGN);
299         }
300
301         /* Make certain I have read in all of the resources */
302         read_resources(bus);
303
304         /* Remember I haven't found anything yet. */
305         resource = 0;
306
307         /* Walk through all the devices on the current bus and 
308          * compute the addresses.
309          */
310         while((dev = largest_resource(bus, &resource, type_mask, type))) {
311                 resource_t 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                 /* Propogate the resource limit to the bridge register */
324                 if (bridge->limit > resource->limit) {
325                         bridge->limit = resource->limit;
326                 }
327                 /* Artificially deny limits between DEVICE_MEM_HIGH and 0xffffffff */
328                 if ((bridge->limit > DEVICE_MEM_HIGH) && (bridge->limit <= 0xffffffff)) {
329                         bridge->limit = DEVICE_MEM_HIGH;
330                 }
331
332                 /* Make certain we are dealing with a good minimum size */
333                 size = resource->size;
334                 align = resource->align;
335                 if (align < min_align) {
336                         align = min_align;
337                 }
338                 if (resource->flags & IORESOURCE_FIXED) {
339                         continue;
340                 }
341                 if (resource->flags & IORESOURCE_IO) {
342                         /* Don't allow potential aliases over the
343                          * legacy pci expansion card addresses.
344                          * The legacy pci decodes only 10 bits,
345                          * uses 100h - 3ffh. Therefor, only 0 - ff
346                          * can be used out of each 400h block of io
347                          * space.
348                          */
349                         if ((base & 0x300) != 0) {
350                                 base = (base & ~0x3ff) + 0x400;
351                         }
352                         /* Don't allow allocations in the VGA IO range.
353                          * PCI has special cases for that.
354                          */
355                         else if ((base >= 0x3b0) && (base <= 0x3df)) {
356                                 base = 0x3e0;
357                         }
358                 }
359                 if (((round(base, align) + size) -1) <= resource->limit) {
360                         /* base must be aligned to size */
361                         base = round(base, align);
362                         resource->base = base;
363                         resource->flags |= IORESOURCE_ASSIGNED;
364                         resource->flags &= ~IORESOURCE_STORED;
365                         base += size;
366                         
367                         printk_spew(
368                                 "%s %02x *  [0x%08Lx - 0x%08Lx] %s\n",
369                                 dev_path(dev),
370                                 resource->index, 
371                                 resource->base, 
372                                 resource->base + resource->size - 1,
373                                 (resource->flags & IORESOURCE_IO)? "io":
374                                 (resource->flags & IORESOURCE_PREFETCH)? "prefmem": "mem");
375                 }
376         }
377         /* A pci bridge resource does not need to be a power
378          * of two size, but it does have a minimum granularity.
379          * Round the size up to that minimum granularity so we
380          * know not to place something else at an address postitively
381          * decoded by the bridge.
382          */
383         bridge->size = round(base, bridge->gran) - bridge->base;
384
385         printk_spew("%s compute_allocate_%s: base: %08lx size: %08lx align: %d gran: %d done\n", 
386                 dev_path(bus->dev),
387                 (bridge->flags & IORESOURCE_IO)? "io":
388                 (bridge->flags & IORESOURCE_PREFETCH)? "prefmem" : "mem",
389                 base, bridge->size, bridge->align, bridge->gran);
390
391
392 }
393
394 static void allocate_vga_resource(void)
395 {
396 #warning "FIXME modify allocate_vga_resource so it is less pci centric!"
397 #warning "This function knows to much about PCI stuff, it should be just a ietrator/visitor."
398
399         /* FIXME handle the VGA pallette snooping */
400         struct device *dev, *vga;
401         struct bus *bus;
402         bus = 0;
403         vga = 0;
404         for(dev = all_devices; dev; dev = dev->next) {
405                 if (((dev->class >> 16) == PCI_BASE_CLASS_DISPLAY) &&
406                         ((dev->class >> 8) != PCI_CLASS_DISPLAY_OTHER)) 
407                 {
408                         if (!vga) {
409                                 printk_debug("Allocating VGA resource %s\n",
410                                         dev_path(dev));
411                                 vga = dev;
412                         }
413                         if (vga == dev) {
414                                 /* All legacy VGA cards have MEM & I/O space registers */
415                                 dev->command |= PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
416                         } else {
417                                 /* It isn't safe to enable other VGA cards */
418                                 dev->command &= ~(PCI_COMMAND_MEMORY | PCI_COMMAND_IO);
419                         }
420                 }
421         }
422         if (vga) {
423                 bus = vga->bus;
424         }
425         /* Now walk up the bridges setting the VGA enable */
426         while(bus) {
427                 bus->bridge_ctrl |= PCI_BRIDGE_CTL_VGA;
428                 bus = (bus == bus->dev->bus)? 0 : bus->dev->bus;
429         } 
430 }
431
432
433 /** Assign the computed resources to the bridges and devices on the bus.
434  * Recurse to any bridges found on this bus first. Then do the devices
435  * on this bus.
436  * 
437  * @param bus Pointer to the structure for this bus
438  */ 
439 void assign_resources(struct bus *bus)
440 {
441         struct device *curdev;
442
443         printk_spew("%s assign_resources, bus %d link: %d\n", 
444                 dev_path(bus->dev), bus->secondary, bus->link);
445
446         for(curdev = bus->children; curdev; curdev = curdev->sibling) {
447                 if (!curdev->enabled || !curdev->resources) {
448                         continue;
449                 }
450                 if (!curdev->ops || !curdev->ops->set_resources) {
451                         printk_err("%s missing set_resources\n",
452                                 dev_path(curdev));
453                         continue;
454                 }
455                 curdev->ops->set_resources(curdev);
456         }
457         printk_spew("%s assign_resources, bus %d link: %d\n", 
458                 dev_path(bus->dev), bus->secondary, bus->link);
459 }
460
461 /**
462  * @brief Enable the resources for a specific device
463  *
464  * @param dev the device whose resources are to be enabled
465  *
466  * Enable resources of the device by calling the device specific
467  * enable_resources() method.
468  *
469  * The parent's resources should be enabled first to avoid having enabling
470  * order problem. This is done by calling the parent's enable_resources()
471  * method and let that method to call it's children's enable_resoruces() via
472  * enable_childrens_resources().
473  *
474  * Indirect mutual recursion:
475  */
476 void enable_resources(struct device *dev)
477 {
478         if (!dev->enabled) {
479                 return;
480         }
481         if (!dev->ops || !dev->ops->enable_resources) {
482                 printk_err("%s missing enable_resources\n", dev_path(dev));
483                 return;
484         }
485         dev->ops->enable_resources(dev);
486 }
487
488 /**
489  * @brief Determine the existence of dynamic devices and construct dynamic
490  * device tree.
491  *
492  * Start from the root device 'dev_root', scan the buses in the system
493  * recursively, build the dynamic device tree according to the result
494  * of the probe.
495  *
496  * This function has no idea how to scan and probe buses and devices at all.
497  * It depends on the bus/device specific scan_bus() method to do it. The
498  * scan_bus() function also has to create the device structure and attach
499  * it to the device tree. 
500  */
501 void dev_enumerate(void)
502 {
503         struct device *root;
504         unsigned subordinate;
505         printk_info("Enumerating buses...\n");
506         root = &dev_root;
507         if (root->chip_ops && root->chip_ops->enable_dev) {
508                 root->chip_ops->enable_dev(root);
509         }
510         if (!root->ops || !root->ops->scan_bus) {
511                 printk_err("dev_root missing scan_bus operation");
512                 return;
513         }
514         subordinate = root->ops->scan_bus(root, 0);
515         printk_info("done\n");
516 }
517
518
519 /**
520  * @brief Configure devices on the devices tree.
521  * 
522  * Starting at the root of the dynamic device tree, travel recursively,
523  * and compute resources needed by each device and allocate them.
524  *
525  * I/O resources start at DEVICE_IO_START and grow upward. MEM resources start
526  * at DEVICE_MEM_START and grow downward.
527  *
528  * Since the assignment is hierarchical we set the values into the dev_root
529  * struct. 
530  */
531 void dev_configure(void)
532 {
533         struct resource *io, *mem;
534         struct device *root;
535
536         printk_info("Allocating resources...\n");
537
538         root = &dev_root;
539         if (!root->ops || !root->ops->read_resources) {
540                 printk_err("dev_root missing read_resources\n");
541                 return;
542         }
543         if (!root->ops || !root->ops->set_resources) {
544                 printk_err("dev_root missing set_resources\n");
545                 return;
546         }
547         root->ops->read_resources(root);
548
549         /* Get the resources */
550         io  = &root->resource[0];
551         mem = &root->resource[1];
552         /* Make certain the io devices are allocated somewhere safe. */
553         io->base = DEVICE_IO_START;
554         io->flags |= IORESOURCE_ASSIGNED;
555         io->flags &= ~IORESOURCE_STORED;
556         /* Now reallocate the pci resources memory with the
557          * highest addresses I can manage.
558          */
559         mem->base = resource_max(&root->resource[1]);
560         mem->flags |= IORESOURCE_ASSIGNED;
561         mem->flags &= ~IORESOURCE_STORED;
562
563         /* Allocate the VGA I/O resource.. */
564         allocate_vga_resource(); 
565
566         /* Store the computed resource allocations into device registers ... */
567         root->ops->set_resources(root);
568
569 #if 0
570         mem->flags |= IORESOURCE_STORED;
571         report_resource_stored(root, mem, "");
572 #endif
573
574         printk_info("done.\n");
575 }
576
577 /**
578  * @brief Enable devices on the device tree.
579  *
580  * Starting at the root, walk the tree and enable all devices/bridges by
581  * calling the device's enable_resources() method.
582  */
583 void dev_enable(void)
584 {
585         printk_info("Enabling resourcess...\n");
586
587         /* now enable everything. */
588         enable_resources(&dev_root);
589
590         printk_info("done.\n");
591 }
592
593 /**
594  * @brief Initialize all devices in the global device list.
595  *
596  * Starting at the first device on the global device link list,
597  * walk the list and call a driver to do device specific setup.
598  */
599 void dev_initialize(void)
600 {
601         struct device *dev;
602
603         printk_info("Initializing devices...\n");
604         for(dev = all_devices; dev; dev = dev->next) {
605                 if (dev->enabled && !dev->initialized && 
606                         dev->ops && dev->ops->init) 
607                 {
608                         printk_debug("%s init\n", dev_path(dev));
609                         dev->initialized = 1;
610                         dev->ops->init(dev);
611                 }
612         }
613         printk_info("Devices initialized\n");
614 }
615