6500029c24a4be0ae4439700edaf01d029668559
[seabios.git] / src / shadow.c
1 // Support for enabling/disabling BIOS ram shadowing.
2 //
3 // Copyright (C) 2008  Kevin O'Connor <kevin@koconnor.net>
4 // Copyright (C) 2006 Fabrice Bellard
5 //
6 // This file may be distributed under the terms of the GNU GPLv3 license.
7
8 #include "util.h" // memcpy
9 #include "pci.h" // pci_config_writeb
10
11 #define BIOS_TMP_STORAGE  0x30000 /* 64 KB used to copy the BIOS to shadow RAM */
12
13 // Test if 'addr' is in the range from 'start'..'start+size'
14 #define IN_RANGE(addr, start, size) ({   \
15             u32 __addr = (addr);         \
16             u32 __start = (start);       \
17             u32 __size = (size);         \
18             (__addr - __start < __size); \
19         })
20
21 // Enable shadowing and copy bios.
22 static void
23 copy_bios(PCIDevice d)
24 {
25     int v = pci_config_readb(d, 0x59);
26     v |= 0x30;
27     pci_config_writeb(d, 0x59, v);
28     memcpy((void *)0x000f0000, (void *)BIOS_TMP_STORAGE, 0x10000);
29 }
30
31 // Make the BIOS code segment area (0xf0000) writable.
32 void
33 make_bios_writable()
34 {
35     if (CONFIG_COREBOOT)
36         return;
37
38     dprintf(3, "enabling shadow ram\n");
39
40     // Locate chip controlling ram shadowing.
41     PCIDevice d;
42     int ret = pci_find_device(0x8086, 0x1237, 0, &d);
43     if (ret) {
44         dprintf(1, "Unable to unlock ram - bridge not found\n");
45         return;
46     }
47
48     // Copy the bios to a temporary area.
49     memcpy((void *)BIOS_TMP_STORAGE, (void *)0x000f0000, 0x10000);
50
51     // Enable shadowing and copy bios.
52     if (IN_RANGE((u32)copy_bios, 0xf0000, 0x10000)) {
53         // Jump to shadow enable function - use the copy in the
54         // temporary storage area so that memory does not change under
55         // the executing code.
56         u32 pos = (u32)copy_bios - 0xf0000 + BIOS_TMP_STORAGE;
57         void (*func)(PCIDevice) = (void*)pos;
58         func(d);
59     } else {
60         copy_bios(d);
61     }
62
63     // Clear the temporary area.
64     memset((void *)BIOS_TMP_STORAGE, 0, 0x10000);
65 }
66
67 // Make the BIOS code segment area (0xf0000) read-only.
68 void
69 make_bios_readonly()
70 {
71     if (CONFIG_COREBOOT)
72         return;
73
74     dprintf(3, "locking shadow ram\n");
75
76     PCIDevice d;
77     int ret = pci_find_device(0x8086, 0x1237, 0, &d);
78     if (ret) {
79         dprintf(1, "Unable to lock ram - bridge not found\n");
80         return;
81     }
82
83     wbinvd();
84     int v = pci_config_readb(d, 0x59);
85     v = (v & 0x0f) | (0x10);
86     pci_config_writeb(d, 0x59, v);
87 }