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