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