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