4b60a2311ba35f90fcbd987b8bdfd235d28dd367
[profile/ivi/syslinux.git] / com32 / lib / syslinux / load_linux.c
1 /* ----------------------------------------------------------------------- *
2  *
3  *   Copyright 2007-2009 H. Peter Anvin - All Rights Reserved
4  *   Copyright 2009-2011 Intel Corporation; author: H. Peter Anvin
5  *
6  *   Permission is hereby granted, free of charge, to any person
7  *   obtaining a copy of this software and associated documentation
8  *   files (the "Software"), to deal in the Software without
9  *   restriction, including without limitation the rights to use,
10  *   copy, modify, merge, publish, distribute, sublicense, and/or
11  *   sell copies of the Software, and to permit persons to whom
12  *   the Software is furnished to do so, subject to the following
13  *   conditions:
14  *
15  *   The above copyright notice and this permission notice shall
16  *   be included in all copies or substantial portions of the Software.
17  *
18  *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19  *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20  *   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21  *   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22  *   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23  *   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24  *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25  *   OTHER DEALINGS IN THE SOFTWARE.
26  *
27  * ----------------------------------------------------------------------- */
28
29 /*
30  * load_linux.c
31  *
32  * Load a Linux kernel (Image/zImage/bzImage).
33  */
34
35 #include <ctype.h>
36 #include <stdbool.h>
37 #include <stdlib.h>
38 #include <inttypes.h>
39 #include <string.h>
40 #include <minmax.h>
41 #include <suffix_number.h>
42 #include <syslinux/align.h>
43 #include <syslinux/linux.h>
44 #include <syslinux/bootrm.h>
45 #include <syslinux/movebits.h>
46 #include <dprintf.h>
47
48 struct linux_header {
49     uint8_t boot_sector_1[0x0020];
50     uint16_t old_cmd_line_magic;
51     uint16_t old_cmd_line_offset;
52     uint8_t boot_sector_2[0x01f1 - 0x0024];
53     uint8_t setup_sects;
54     uint16_t root_flags;
55     uint32_t syssize;
56     uint16_t ram_size;
57     uint16_t vid_mode;
58     uint16_t root_dev;
59     uint16_t boot_flag;
60     uint16_t jump;
61     uint32_t header;
62     uint16_t version;
63     uint32_t realmode_swtch;
64     uint16_t start_sys;
65     uint16_t kernel_version;
66     uint8_t type_of_loader;
67     uint8_t loadflags;
68     uint16_t setup_move_size;
69     uint32_t code32_start;
70     uint32_t ramdisk_image;
71     uint32_t ramdisk_size;
72     uint32_t bootsect_kludge;
73     uint16_t heap_end_ptr;
74     uint16_t pad1;
75     uint32_t cmd_line_ptr;
76     uint32_t initrd_addr_max;
77     uint32_t kernel_alignment;
78     uint8_t relocatable_kernel;
79     uint8_t pad2[3];
80     uint32_t cmdline_max_len;
81     uint32_t hardware_subarch;
82     uint64_t hardware_subarch_data;
83     uint32_t payload_offset;
84     uint32_t payload_length;
85     uint64_t setup_data;
86     uint64_t pref_address;
87     uint32_t init_size;
88 } __packed;
89
90 #define BOOT_MAGIC 0xAA55
91 #define LINUX_MAGIC ('H' + ('d' << 8) + ('r' << 16) + ('S' << 24))
92 #define OLD_CMDLINE_MAGIC 0xA33F
93
94 /* loadflags */
95 #define LOAD_HIGH       0x01
96 #define CAN_USE_HEAP    0x80
97
98 /* 
99  * Find the last instance of a particular command line argument
100  * (which should include the final =; do not use for boolean arguments)
101  * Note: the resulting string is typically not null-terminated.
102  */
103 static const char *find_argument(const char *cmdline, const char *argument)
104 {
105     const char *found = NULL;
106     const char *p = cmdline;
107     bool was_space = true;
108     size_t la = strlen(argument);
109
110     while (*p) {
111         if (isspace(*p)) {
112             was_space = true;
113         } else if (was_space) {
114             if (!memcmp(p, argument, la))
115                 found = p + la;
116             was_space = false;
117         }
118         p++;
119     }
120
121     return found;
122 }
123
124 /* Truncate to 32 bits, with saturate */
125 static inline uint32_t saturate32(unsigned long long v)
126 {
127     return (v > 0xffffffff) ? 0xffffffff : (uint32_t) v;
128 }
129
130 /* Get the combined size of the initramfs */
131 static addr_t initramfs_size(struct initramfs *initramfs)
132 {
133     struct initramfs *ip;
134     addr_t size = 0;
135
136     if (!initramfs)
137         return 0;
138
139     for (ip = initramfs->next; ip->len; ip = ip->next) {
140         size = (size + ip->align - 1) & ~(ip->align - 1);       /* Alignment */
141         size += ip->len;
142     }
143
144     return size;
145 }
146
147 /* Create the appropriate mappings for the initramfs */
148 static int map_initramfs(struct syslinux_movelist **fraglist,
149                          struct syslinux_memmap **mmap,
150                          struct initramfs *initramfs, addr_t addr)
151 {
152     struct initramfs *ip;
153     addr_t next_addr, len, pad;
154
155     for (ip = initramfs->next; ip->len; ip = ip->next) {
156         len = ip->len;
157         next_addr = addr + len;
158
159         /* If this isn't the last entry, extend the zero-pad region
160            to enforce the alignment of the next chunk. */
161         if (ip->next->len) {
162             pad = -next_addr & (ip->next->align - 1);
163             len += pad;
164             next_addr += pad;
165         }
166
167         if (ip->data_len) {
168             if (syslinux_add_movelist(fraglist, addr, (addr_t) ip->data, len))
169                 return -1;
170         }
171         if (len > ip->data_len) {
172             if (syslinux_add_memmap(mmap, addr + ip->data_len,
173                                     len - ip->data_len, SMT_ZERO))
174                 return -1;
175         }
176         addr = next_addr;
177     }
178
179     return 0;
180 }
181
182 int syslinux_boot_linux(void *kernel_buf, size_t kernel_size,
183                         struct initramfs *initramfs, char *cmdline)
184 {
185     struct linux_header hdr, *whdr;
186     size_t real_mode_size, prot_mode_size;
187     addr_t real_mode_base, prot_mode_base;
188     addr_t irf_size;
189     size_t cmdline_size, cmdline_offset;
190     struct syslinux_rm_regs regs;
191     struct syslinux_movelist *fraglist = NULL;
192     struct syslinux_memmap *mmap = NULL;
193     struct syslinux_memmap *amap = NULL;
194     bool ok;
195     uint32_t memlimit = 0;
196     uint16_t video_mode = 0;
197     const char *arg;
198
199     cmdline_size = strlen(cmdline) + 1;
200
201     if (kernel_size < 2 * 512)
202         goto bail;
203
204     /* Look for specific command-line arguments we care about */
205     if ((arg = find_argument(cmdline, "mem=")))
206         memlimit = saturate32(suffix_number(arg));
207
208     if ((arg = find_argument(cmdline, "vga="))) {
209         switch (arg[0] | 0x20) {
210         case 'a':               /* "ask" */
211             video_mode = 0xfffd;
212             break;
213         case 'e':               /* "ext" */
214             video_mode = 0xfffe;
215             break;
216         case 'n':               /* "normal" */
217             video_mode = 0xffff;
218             break;
219         case 'c':               /* "current" */
220             video_mode = 0x0f04;
221             break;
222         default:
223             video_mode = strtoul(arg, NULL, 0);
224             break;
225         }
226     }
227
228     /* Copy the header into private storage */
229     /* Use whdr to modify the actual kernel header */
230     memcpy(&hdr, kernel_buf, sizeof hdr);
231     whdr = (struct linux_header *)kernel_buf;
232
233     if (hdr.boot_flag != BOOT_MAGIC)
234         goto bail;
235
236     if (hdr.header != LINUX_MAGIC) {
237         hdr.version = 0x0100;   /* Very old kernel */
238         hdr.loadflags = 0;
239     }
240
241     whdr->vid_mode = video_mode;
242
243     if (!hdr.setup_sects)
244         hdr.setup_sects = 4;
245
246     if (hdr.version < 0x0203)
247         hdr.initrd_addr_max = 0x37ffffff;
248
249     if (!memlimit && memlimit - 1 > hdr.initrd_addr_max)
250         memlimit = hdr.initrd_addr_max + 1;     /* Zero for no limit */
251
252     if (hdr.version < 0x0205 || !(hdr.loadflags & LOAD_HIGH))
253         hdr.relocatable_kernel = 0;
254
255     if (hdr.version < 0x0206)
256         hdr.cmdline_max_len = 256;
257
258     if (cmdline_size > hdr.cmdline_max_len) {
259         cmdline_size = hdr.cmdline_max_len;
260         cmdline[cmdline_size - 1] = '\0';
261     }
262
263     if (hdr.version < 0x0202 || !(hdr.loadflags & 0x01))
264         cmdline_offset = (0x9ff0 - cmdline_size) & ~15;
265     else
266         cmdline_offset = 0x10000;
267
268     real_mode_size = (hdr.setup_sects + 1) << 9;
269     real_mode_base = (hdr.loadflags & LOAD_HIGH) ? 0x10000 : 0x90000;
270     prot_mode_base = (hdr.loadflags & LOAD_HIGH) ? 0x100000 : 0x10000;
271     prot_mode_size = kernel_size - real_mode_size;
272
273     if (hdr.version < 0x020a) {
274         /*
275          * The 3* here is a total fudge factor... it's supposed to
276          * account for the fact that the kernel needs to be
277          * decompressed, and then followed by the BSS and BRK regions.
278          * This doesn't, however, account for the fact that the kernel
279          * is decompressed into a whole other place, either.
280          */
281         hdr.init_size = 3 * prot_mode_size;
282     }
283
284     if (!(hdr.loadflags & LOAD_HIGH) && prot_mode_size > 512 * 1024)
285         goto bail;              /* Kernel cannot be loaded low */
286
287     if (initramfs && hdr.version < 0x0200)
288         goto bail;              /* initrd/initramfs not supported */
289
290     if (hdr.version >= 0x0200) {
291         whdr->type_of_loader = 0x30;    /* SYSLINUX unknown module */
292         if (hdr.version >= 0x0201) {
293             whdr->heap_end_ptr = cmdline_offset - 0x0200;
294             whdr->loadflags |= CAN_USE_HEAP;
295         }
296         if (hdr.version >= 0x0202) {
297             whdr->cmd_line_ptr = real_mode_base + cmdline_offset;
298         } else {
299             whdr->old_cmd_line_magic = OLD_CMDLINE_MAGIC;
300             whdr->old_cmd_line_offset = cmdline_offset;
301             /* Be paranoid and round up to a multiple of 16 */
302             whdr->setup_move_size = (cmdline_offset + cmdline_size + 15) & ~15;
303         }
304     }
305
306     /* Get the memory map */
307     mmap = syslinux_memory_map();       /* Memory map for shuffle_boot */
308     amap = syslinux_dup_memmap(mmap);   /* Keep track of available memory */
309     if (!mmap || !amap)
310         goto bail;
311
312 #if DEBUG
313     dprintf("Initial memory map:\n");
314     syslinux_dump_memmap(stdout, mmap);
315 #endif
316
317     /* If the user has specified a memory limit, mark that as unavailable.
318        Question: should we mark this off-limit in the mmap as well (meaning
319        it's unavailable to the boot loader, which probably has already touched
320        some of it), or just in the amap? */
321     if (memlimit)
322         if (syslinux_add_memmap(&amap, memlimit, -memlimit, SMT_RESERVED))
323             goto bail;
324
325     /* Place the kernel in memory */
326
327     /* First, find a suitable place for the protected-mode code */
328     if (syslinux_memmap_type(amap, prot_mode_base, prot_mode_size)
329         != SMT_FREE) {
330         const struct syslinux_memmap *mp;
331         if (!hdr.relocatable_kernel)
332             goto bail;          /* Can't relocate - no hope */
333
334         ok = false;
335         for (mp = amap; mp; mp = mp->next) {
336             addr_t start, end;
337             start = mp->start;
338             end = mp->next->start;
339
340             if (mp->type != SMT_FREE)
341                 continue;
342
343             if (end <= prot_mode_base)
344                 continue;       /* Only relocate upwards */
345
346             if (start <= prot_mode_base)
347                 start = prot_mode_base;
348
349             start = ALIGN_UP(start, hdr.kernel_alignment);
350             if (start >= end)
351                 continue;
352
353             if (end - start >= hdr.init_size) {
354                 whdr->code32_start += start - prot_mode_base;
355                 prot_mode_base = start;
356                 ok = true;
357                 break;
358             }
359         }
360
361         if (!ok)
362             goto bail;
363     }
364
365     /* Real mode code */
366     if (syslinux_memmap_type(amap, real_mode_base,
367                              cmdline_offset + cmdline_size) != SMT_FREE) {
368         const struct syslinux_memmap *mp;
369
370         ok = false;
371         for (mp = amap; mp; mp = mp->next) {
372             addr_t start, end;
373             start = mp->start;
374             end = mp->next->start;
375
376             if (mp->type != SMT_FREE)
377                 continue;
378
379             if (start < real_mode_base)
380                 start = real_mode_base; /* Lowest address we'll use */
381             if (end > 640 * 1024)
382                 end = 640 * 1024;
383
384             start = ALIGN_UP(start, 16);
385             if (start > 0x90000 || start >= end)
386                 continue;
387
388             if (end - start >= cmdline_offset + cmdline_size) {
389                 real_mode_base = start;
390                 ok = true;
391                 break;
392             }
393         }
394     }
395
396     if (syslinux_add_movelist(&fraglist, real_mode_base, (addr_t) kernel_buf,
397                               real_mode_size))
398         goto bail;
399     if (syslinux_add_memmap
400         (&amap, real_mode_base, cmdline_offset + cmdline_size, SMT_ALLOC))
401         goto bail;
402
403     /* Zero region between real mode code and cmdline */
404     if (syslinux_add_memmap(&mmap, real_mode_base + real_mode_size,
405                             cmdline_offset - real_mode_size, SMT_ZERO))
406         goto bail;
407
408     /* Command line */
409     if (syslinux_add_movelist(&fraglist, real_mode_base + cmdline_offset,
410                               (addr_t) cmdline, cmdline_size))
411         goto bail;
412
413     /* Protected-mode code */
414     if (syslinux_add_movelist(&fraglist, prot_mode_base,
415                               (addr_t) kernel_buf + real_mode_size,
416                               prot_mode_size))
417         goto bail;
418     if (syslinux_add_memmap(&amap, prot_mode_base, prot_mode_size, SMT_ALLOC))
419         goto bail;
420
421     /* Figure out the size of the initramfs, and where to put it.
422        We should put it at the highest possible address which is
423        <= hdr.initrd_addr_max, which fits the entire initramfs. */
424
425     irf_size = initramfs_size(initramfs);       /* Handles initramfs == NULL */
426
427     if (irf_size) {
428         addr_t best_addr = 0;
429         struct syslinux_memmap *ml;
430         const addr_t align_mask = INITRAMFS_MAX_ALIGN - 1;
431
432         if (irf_size) {
433             for (ml = amap; ml->type != SMT_END; ml = ml->next) {
434                 addr_t adj_start = (ml->start + align_mask) & ~align_mask;
435                 addr_t adj_end = ml->next->start & ~align_mask;
436                 if (ml->type == SMT_FREE && adj_end - adj_start >= irf_size)
437                     best_addr = (adj_end - irf_size) & ~align_mask;
438             }
439
440             if (!best_addr)
441                 goto bail;      /* Insufficient memory for initramfs */
442
443             whdr->ramdisk_image = best_addr;
444             whdr->ramdisk_size = irf_size;
445
446             if (syslinux_add_memmap(&amap, best_addr, irf_size, SMT_ALLOC))
447                 goto bail;
448
449             if (map_initramfs(&fraglist, &mmap, initramfs, best_addr))
450                 goto bail;
451         }
452     }
453
454     /* Set up the registers on entry */
455     memset(&regs, 0, sizeof regs);
456     regs.es = regs.ds = regs.ss = regs.fs = regs.gs = real_mode_base >> 4;
457     regs.cs = (real_mode_base >> 4) + 0x20;
458     /* regs.ip = 0; */
459     /* Linux is OK with sp = 0 = 64K, but perhaps other things aren't... */
460     regs.esp.w[0] = min(cmdline_offset, (size_t) 0xfff0);
461
462 #if DEBUG
463     dprintf("Final memory map:\n");
464     syslinux_dump_memmap(stdout, mmap);
465
466     dprintf("Final available map:\n");
467     syslinux_dump_memmap(stdout, amap);
468
469     dprintf("Initial movelist:\n");
470     syslinux_dump_movelist(stdout, fraglist);
471 #endif
472
473     syslinux_shuffle_boot_rm(fraglist, mmap, 0, &regs);
474
475 bail:
476     syslinux_free_movelist(fraglist);
477     syslinux_free_memmap(mmap);
478     syslinux_free_memmap(amap);
479     return -1;
480 }