Doxidization, reformat
[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 <stdlib.h>
23 #include <string.h>
24
25 /** Linked list of ALL devices */
26 struct device *all_devices = &dev_root;
27 /** Pointer to the last device */
28 static struct device **last_dev_p = &dev_root.next;
29
30 /** The upper limit of MEM resource of the devices.
31  * Reserve 20M for the system */
32 #define DEVICE_MEM_HIGH 0xFEC00000UL
33 /** The lower limit of IO resource of the devices.
34  * Reserve 4k for ISA/Legacy devices */
35 #define DEVICE_IO_START 0x1000
36
37 /**
38  * @brief Allocate a new device structure.
39  * 
40  * Allocte a new device structure and attached it to the device tree as a child
41  * of the parent bus.
42  *
43  * @param parent parent bus the newly created device attached to.
44  * @param path path to the device to be created.
45  *
46  * @return pointer to the newly created device structure.
47  *
48  * @see device_path
49  */
50 device_t alloc_dev(struct bus *parent, struct device_path *path)
51 {
52         device_t dev, child;
53         int link;
54
55         /* Find the last child of our parent */
56         for (child = parent->children; child && child->sibling; ) {
57                 child = child->sibling;
58         }
59
60         dev = malloc(sizeof(*dev));
61         if (dev == 0) {
62                 die("DEV: out of memory.\n");
63         }
64         memset(dev, 0, sizeof(*dev));
65         memcpy(&dev->path, path, sizeof(*path));
66
67         /* Append a new device to the global device list.
68          * The list is used to find devices once everything is set up.
69          */
70         *last_dev_p = dev;
71         last_dev_p = &dev->next;
72
73         /* Initialize the back pointers in the link fields */
74         for (link = 0; link < MAX_LINKS; link++) {
75                 dev->link[link].dev  = dev;
76                 dev->link[link].link = link;
77         }
78
79         /* Add the new device to the children of the bus. */
80         dev->bus = parent;
81         if (child) {
82                 child->sibling = dev;
83         } else {
84                 parent->children = dev;
85         }
86
87         /* If we don't have any other information about a device enable it */
88         dev->enable = 1;
89
90         return dev;
91 }
92
93 /**
94  * @brief round a number up to an alignment. 
95  * @param val the starting value
96  * @param roundup Alignment as a power of two
97  * @returns rounded up number
98  */
99 static unsigned long round(unsigned long val, unsigned long roundup)
100 {
101         /* ROUNDUP MUST BE A POWER OF TWO. */
102         unsigned long inverse;
103         inverse = ~(roundup - 1);
104         val += (roundup - 1);
105         val &= inverse;
106         return val;
107 }
108
109 static unsigned long round_down(unsigned long val, unsigned long round_down)
110 {
111         /* ROUND_DOWN MUST BE A POWER OF TWO. */
112         unsigned long inverse;
113         inverse = ~(round_down - 1);
114         val &= inverse;
115         return val;
116 }
117
118
119 /** Read the resources on all devices of a given bus.
120  * @param bus bus to read the resources on.
121  */
122 static void read_resources(struct bus *bus)
123 {
124         struct device *curdev;
125
126         /* Walk through all of the devices and find which resources they need. */
127         for (curdev = bus->children; curdev; curdev = curdev->sibling) {
128                 unsigned links;
129                 int i;
130                 if (curdev->resources > 0) {
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                 if (!curdev->enable) {
139                         continue;
140                 }
141
142                 curdev->ops->read_resources(curdev);
143
144                 /* Read in subtractive resources behind the current device */
145                 links = 0;
146                 for (i = 0; i < curdev->resources; i++) {
147                         struct resource *resource;
148                         resource = &curdev->resource[i];
149                         if ((resource->flags & IORESOURCE_SUBTRACTIVE) &&
150                             (!(links & (1 << resource->index))))
151                         {
152                                 links |= (1 << resource->index);
153                                 read_resources(&curdev->link[resource->index]);
154                                 
155                         }
156                 }
157         }
158 }
159
160 struct pick_largest_state {
161         struct resource *last;
162         struct device   *result_dev;
163         struct resource *result;
164         int seen_last;
165 };
166
167 static void pick_largest_resource(struct pick_largest_state *state,
168                                   struct device *dev, struct resource *resource)
169 {
170         struct resource *last;
171         last = state->last;
172         /* Be certain to pick the successor to last */
173         if (resource == last) {
174                 state->seen_last = 1;
175                 return;
176         }
177         if (last &&
178             ((last->align < resource->align) ||
179              ((last->align == resource->align) &&
180               (last->size < resource->size)) ||
181              ((last->align == resource->align) &&
182               (last->size == resource->size) &&
183               (!state->seen_last)))) {
184                 return;
185         }
186         if (!state->result ||
187             (state->result->align < resource->align) ||
188             ((state->result->align == resource->align) &&
189              (state->result->size < resource->size))) {
190                 state->result_dev = dev;
191                 state->result = resource;
192         }    
193 }
194
195 static void find_largest_resource(struct pick_largest_state *state, 
196                                   struct bus *bus, unsigned long type_mask,
197                                   unsigned long type)
198 {
199         struct device *curdev;
200
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,
214                                                       type_mask, type);
215                                 continue;
216                         }
217                         /* See if this is the largest resource */
218                         pick_largest_resource(state, curdev, resource);
219                 }
220         }
221 }
222
223 static struct device *largest_resource(struct bus *bus,
224                                        struct resource **result_res,
225                                        unsigned long type_mask,
226                                        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         unsigned long 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 "
284                     "align: %d gran: %d\n", 
285                     dev_path(bus->dev),
286                     (bridge->flags & IORESOURCE_IO)? "io":
287                     (bridge->flags & IORESOURCE_PREFETCH)? "prefmem" : "mem",
288                     base, bridge->size, bridge->align, bridge->gran);
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 compute the
308          * addresses */
309         while ((dev = largest_resource(bus, &resource, type_mask, type))) {
310                 unsigned long 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                 /* Make certain we are dealing with a good minimum size */
323                 size = resource->size;
324                 align = resource->align;
325                 if (align < min_align) {
326                         align = min_align;
327                 }
328                 if (resource->flags & IORESOURCE_FIXED) {
329                         continue;
330                 }
331                 if (resource->flags & IORESOURCE_IO) {
332                         /* Don't allow potential aliases over the
333                          * legacy pci expansion card addresses.
334                          * The legacy pci decodes only 10 bits,
335                          * uses 100h - 3ffh. Therefor, only 0 - ff
336                          * can be used out of each 400h block of io
337                          * space.
338                          */
339                         if ((base & 0x300) != 0) {
340                                 base = (base & ~0x3ff) + 0x400;
341                         }
342                         /* Don't allow allocations in the VGA IO range.
343                          * PCI has special cases for that.
344                          */
345                         else if ((base >= 0x3b0) && (base <= 0x3df)) {
346                                 base = 0x3e0;
347                         }
348                 }
349                 if (((round(base, 1UL << align) + size) -1) <= resource->limit) {
350                         /* base must be aligned to size */
351                         base = round(base, 1UL << align);
352                         resource->base = base;
353                         resource->flags |= IORESOURCE_ASSIGNED;
354                         resource->flags &= ~IORESOURCE_STORED;
355                         base += size;
356                         
357                         printk_spew(
358                                 "%s %02x *  [0x%08lx - 0x%08lx] %s\n",
359                                 dev_path(dev),
360                                 resource->index, 
361                                 resource->base, resource->base + resource->size -1,
362                                 (resource->flags & IORESOURCE_IO)? "io":
363                                 (resource->flags & IORESOURCE_PREFETCH)? "prefmem": "mem");
364                 }
365
366         }
367         /* A pci bridge resource does not need to be a power
368          * of two size, but it does have a minimum granularity.
369          * Round the size up to that minimum granularity so we
370          * know not to place something else at an address postitively
371          * decoded by the bridge.
372          */
373         bridge->size = round(base, 1UL << bridge->gran) - bridge->base;
374
375         printk_spew("%s compute_allocate_%s: base: %08lx size: %08lx align: %d gran: %d done\n", 
376                 dev_path(dev),
377                 (bridge->flags & IORESOURCE_IO)? "io":
378                 (bridge->flags & IORESOURCE_PREFETCH)? "prefmem" : "mem",
379                 base, bridge->size, bridge->align, bridge->gran);
380
381
382 }
383
384 static void allocate_vga_resource(void)
385 {
386 #warning "FIXME modify allocate_vga_resource so it is less pci centric!"
387 #warning "This function knows to much about PCI stuff, it should be just a ietrator/visitor."
388
389         /* FIXME handle the VGA pallette snooping */
390         struct device *dev, *vga;
391         struct bus *bus;
392         bus = 0;
393         vga = 0;
394         for(dev = all_devices; dev; dev = dev->next) {
395                 if (((dev->class >> 16) == 0x03) &&
396                         ((dev->class >> 8) != 0x380)) {
397                         if (!vga) {
398                                 printk_debug("Allocating VGA resource\n");
399                                 vga = dev;
400                         }
401                         if (vga == dev) {
402                                 /* All legacy VGA cards have MEM & I/O space registers */
403                                 dev->command |= PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
404                         } else {
405                                 /* It isn't safe to enable other VGA cards */
406                                 dev->command &= ~(PCI_COMMAND_MEMORY | PCI_COMMAND_IO);
407                         }
408                 }
409         }
410         if (vga) {
411                 bus = vga->bus;
412         }
413         /* Now walk up the bridges setting the VGA enable */
414         while(bus) {
415                 bus->bridge_ctrl |= PCI_BRIDGE_CTL_VGA;
416                 bus = (bus == bus->dev->bus)? 0 : bus->dev->bus;
417         } 
418 }
419
420
421 /** Assign the computed resources to the bridges and devices on the bus.
422  * Recurse to any bridges found on this bus first. Then do the devices
423  * on this bus. 
424  * @param bus Pointer to the structure for this bus
425  */ 
426 void assign_resources(struct bus *bus)
427 {
428         struct device *curdev;
429
430         printk_debug("ASSIGN RESOURCES, bus %d\n", bus->secondary);
431
432         for (curdev = bus->children; curdev; curdev = curdev->sibling) {
433                 if (!curdev->ops || !curdev->ops->set_resources) {
434                         printk_err("%s missing set_resources\n",
435                                 dev_path(curdev));
436                         continue;
437                 }
438                 if (!curdev->enable) {
439                         continue;
440                 }
441                 curdev->ops->set_resources(curdev);
442         }
443         printk_debug("ASSIGNED RESOURCES, bus %d\n", bus->secondary);
444 }
445
446 void enable_resources(struct device *dev)
447 {
448         /* Enable the resources for a specific device.
449          * The parents resources should be enabled first to avoid
450          * having enabling ordering problems.
451          */
452         if (!dev->ops || !dev->ops->enable_resources) {
453                 printk_err("%s missing enable_resources\n",
454                            dev_path(dev));
455                 return;
456         }
457         if (!dev->enable) {
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 for the root device 'dev_root', scan the buses in the system, build
468  * the dynamic device tree according to the result of the probe.
469  *
470  * This function have no idea how to scan and probe the buses and devices at
471  * all. It depends on the bus/device specific scan_bus() method to do it.
472  * The scan_bus() function also have to create the device structure and attach
473  * it to the device tree. 
474  */
475 void dev_enumerate(void)
476 {
477         struct device *root;
478         unsigned subordinate;
479
480         printk_info("Enumerating buses...\n");
481
482         root = &dev_root;
483         subordinate = root->ops->scan_bus(root, 0);
484
485         printk_info("done\n");
486 }
487
488 /**
489  * @brief Configure devices on the devices tree.
490  * 
491  * Starting at the root, compute what resources are needed and allocate them. 
492  * I/O starts at PCI_IO_START. Since the assignment is hierarchical we
493  * set the values into the dev_root struct. 
494  */
495 void dev_configure(void)
496 {
497         struct device *root = &dev_root;
498
499         printk_info("Allocating resources...");
500         printk_debug("\n");
501
502         root->ops->read_resources(root);
503
504         /* Make certain the io devices are allocated somewhere safe. */
505         root->resource[0].base = DEVICE_IO_START;
506         root->resource[0].flags |= IORESOURCE_ASSIGNED;
507         root->resource[0].flags &= ~IORESOURCE_STORED;
508
509         /* Now reallocate the pci resources memory with the highest
510          * addresses I can manage.*/
511         root->resource[1].base = 
512                 round_down(DEVICE_MEM_HIGH - root->resource[1].size,
513                            1UL << root->resource[1].align);
514         root->resource[1].flags |= IORESOURCE_ASSIGNED;
515         root->resource[1].flags &= ~IORESOURCE_STORED;
516
517         /* Allocate the VGA I/O resource.. */
518         allocate_vga_resource(); 
519
520         /* now just set things into registers ... we hope ... */
521         root->ops->set_resources(root);
522
523         printk_info("done.\n");
524 }
525
526 /**
527  * @brief Enable devices on the device tree.
528  *
529  * Starting at the root, walk the tree and enable all devices/bridges by
530  * calling the device's enable_resources() method.
531  */
532 void dev_enable(void)
533 {
534         printk_info("Enabling resourcess...\n");
535
536         /* now enable everything. */
537         enable_resources(&dev_root);
538
539         printk_info("done.\n");
540 }
541
542 /**
543  * @brief Initialize all devices in the global device list.
544  *
545  * Starting at the first device on the global device link list,
546  * walk the list and call a driver to do device specific setup.
547  */
548 void dev_initialize(void)
549 {
550         struct device *dev;
551
552         printk_info("Initializing devices...\n");
553
554         for (dev = all_devices; dev; dev = dev->next) {
555                 if (dev->enable && dev->ops && dev->ops->init) {
556                         printk_debug("%s init\n", dev_path(dev));
557                         dev->ops->init(dev);
558                 }
559         }
560
561         printk_info("Devices initialized\n");
562 }