i386: make struct linux_kernel_header architecture specific
[grub.git] / grub-core / loader / i386 / linux.c
1 /*
2  *  GRUB  --  GRand Unified Bootloader
3  *  Copyright (C) 2006,2007,2008,2009,2010  Free Software Foundation, Inc.
4  *
5  *  GRUB is free software: you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation, either version 3 of the License, or
8  *  (at your option) any later version.
9  *
10  *  GRUB is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include <grub/loader.h>
20 #include <grub/memory.h>
21 #include <grub/normal.h>
22 #include <grub/file.h>
23 #include <grub/disk.h>
24 #include <grub/err.h>
25 #include <grub/misc.h>
26 #include <grub/types.h>
27 #include <grub/dl.h>
28 #include <grub/mm.h>
29 #include <grub/term.h>
30 #include <grub/cpu/linux.h>
31 #include <grub/video.h>
32 #include <grub/video_fb.h>
33 #include <grub/command.h>
34 #include <grub/i386/relocator.h>
35 #include <grub/i18n.h>
36 #include <grub/lib/cmdline.h>
37 #include <grub/linux.h>
38
39 GRUB_MOD_LICENSE ("GPLv3+");
40
41 #ifdef GRUB_MACHINE_PCBIOS
42 #include <grub/i386/pc/vesa_modes_table.h>
43 #endif
44
45 #ifdef GRUB_MACHINE_EFI
46 #include <grub/efi/efi.h>
47 #define HAS_VGA_TEXT 0
48 #define DEFAULT_VIDEO_MODE "auto"
49 #define ACCEPTS_PURE_TEXT 0
50 #elif defined (GRUB_MACHINE_IEEE1275)
51 #include <grub/ieee1275/ieee1275.h>
52 #define HAS_VGA_TEXT 0
53 #define DEFAULT_VIDEO_MODE "text"
54 #define ACCEPTS_PURE_TEXT 1
55 #else
56 #include <grub/i386/pc/vbe.h>
57 #include <grub/i386/pc/console.h>
58 #define HAS_VGA_TEXT 1
59 #define DEFAULT_VIDEO_MODE "text"
60 #define ACCEPTS_PURE_TEXT 1
61 #endif
62
63 static grub_dl_t my_mod;
64
65 static grub_size_t linux_mem_size;
66 static int loaded;
67 static void *prot_mode_mem;
68 static grub_addr_t prot_mode_target;
69 static void *initrd_mem;
70 static grub_addr_t initrd_mem_target;
71 static grub_size_t prot_init_space;
72 static struct grub_relocator *relocator = NULL;
73 static void *efi_mmap_buf;
74 static grub_size_t maximal_cmdline_size;
75 static struct linux_kernel_params linux_params;
76 static char *linux_cmdline;
77 #ifdef GRUB_MACHINE_EFI
78 static grub_efi_uintn_t efi_mmap_size;
79 #else
80 static const grub_size_t efi_mmap_size = 0;
81 #endif
82
83 /* FIXME */
84 #if 0
85 struct idt_descriptor
86 {
87   grub_uint16_t limit;
88   void *base;
89 } GRUB_PACKED;
90
91 static struct idt_descriptor idt_desc =
92   {
93     0,
94     0
95   };
96 #endif
97
98 static inline grub_size_t
99 page_align (grub_size_t size)
100 {
101   return (size + (1 << 12) - 1) & (~((1 << 12) - 1));
102 }
103
104 #ifdef GRUB_MACHINE_EFI
105 /* Find the optimal number of pages for the memory map. Is it better to
106    move this code to efi/mm.c?  */
107 static grub_efi_uintn_t
108 find_efi_mmap_size (void)
109 {
110   static grub_efi_uintn_t mmap_size = 0;
111
112   if (mmap_size != 0)
113     return mmap_size;
114
115   mmap_size = (1 << 12);
116   while (1)
117     {
118       int ret;
119       grub_efi_memory_descriptor_t *mmap;
120       grub_efi_uintn_t desc_size;
121       grub_efi_uintn_t cur_mmap_size = mmap_size;
122
123       mmap = grub_malloc (cur_mmap_size);
124       if (! mmap)
125         return 0;
126
127       ret = grub_efi_get_memory_map (&cur_mmap_size, mmap, 0, &desc_size, 0);
128       grub_free (mmap);
129
130       if (ret < 0)
131         {
132           grub_error (GRUB_ERR_IO, "cannot get memory map");
133           return 0;
134         }
135       else if (ret > 0)
136         break;
137
138       if (mmap_size < cur_mmap_size)
139         mmap_size = cur_mmap_size;
140       mmap_size += (1 << 12);
141     }
142
143   /* Increase the size a bit for safety, because GRUB allocates more on
144      later, and EFI itself may allocate more.  */
145   mmap_size += (3 << 12);
146
147   mmap_size = page_align (mmap_size);
148   return mmap_size;
149 }
150
151 #endif
152
153 /* Helper for find_mmap_size.  */
154 static int
155 count_hook (grub_uint64_t addr __attribute__ ((unused)),
156             grub_uint64_t size __attribute__ ((unused)),
157             grub_memory_type_t type __attribute__ ((unused)), void *data)
158 {
159   grub_size_t *count = data;
160
161   (*count)++;
162   return 0;
163 }
164
165 /* Find the optimal number of pages for the memory map. */
166 static grub_size_t
167 find_mmap_size (void)
168 {
169   grub_size_t count = 0, mmap_size;
170
171   grub_mmap_iterate (count_hook, &count);
172
173   mmap_size = count * sizeof (struct grub_e820_mmap);
174
175   /* Increase the size a bit for safety, because GRUB allocates more on
176      later.  */
177   mmap_size += (1 << 12);
178
179   return page_align (mmap_size);
180 }
181
182 static void
183 free_pages (void)
184 {
185   grub_relocator_unload (relocator);
186   relocator = NULL;
187   prot_mode_mem = initrd_mem = 0;
188   prot_mode_target = initrd_mem_target = 0;
189 }
190
191 /* Allocate pages for the real mode code and the protected mode code
192    for linux as well as a memory map buffer.  */
193 static grub_err_t
194 allocate_pages (grub_size_t prot_size, grub_size_t *align,
195                 grub_size_t min_align, int relocatable,
196                 grub_uint64_t preferred_address)
197 {
198   grub_err_t err;
199
200   if (prot_size == 0)
201     prot_size = 1;
202
203   prot_size = page_align (prot_size);
204
205   /* Initialize the memory pointers with NULL for convenience.  */
206   free_pages ();
207
208   relocator = grub_relocator_new ();
209   if (!relocator)
210     {
211       err = grub_errno;
212       goto fail;
213     }
214
215   /* FIXME: Should request low memory from the heap when this feature is
216      implemented.  */
217
218   {
219     grub_relocator_chunk_t ch;
220     if (relocatable)
221       {
222         err = grub_relocator_alloc_chunk_align (relocator, &ch,
223                                                 preferred_address,
224                                                 preferred_address,
225                                                 prot_size, 1,
226                                                 GRUB_RELOCATOR_PREFERENCE_LOW,
227                                                 1);
228         for (; err && *align + 1 > min_align; (*align)--)
229           {
230             grub_errno = GRUB_ERR_NONE;
231             err = grub_relocator_alloc_chunk_align (relocator, &ch,
232                                                     0x1000000,
233                                                     0xffffffff & ~prot_size,
234                                                     prot_size, 1 << *align,
235                                                     GRUB_RELOCATOR_PREFERENCE_LOW,
236                                                     1);
237           }
238         if (err)
239           goto fail;
240       }
241     else
242       err = grub_relocator_alloc_chunk_addr (relocator, &ch,
243                                              preferred_address,
244                                              prot_size);
245     if (err)
246       goto fail;
247     prot_mode_mem = get_virtual_current_address (ch);
248     prot_mode_target = get_physical_target_address (ch);
249   }
250
251   grub_dprintf ("linux", "prot_mode_mem = %p, prot_mode_target = %lx, prot_size = %x\n",
252                 prot_mode_mem, (unsigned long) prot_mode_target,
253                 (unsigned) prot_size);
254   return GRUB_ERR_NONE;
255
256  fail:
257   free_pages ();
258   return err;
259 }
260
261 static grub_err_t
262 grub_e820_add_region (struct grub_e820_mmap *e820_map, int *e820_num,
263                       grub_uint64_t start, grub_uint64_t size,
264                       grub_uint32_t type)
265 {
266   int n = *e820_num;
267
268   if ((n > 0) && (e820_map[n - 1].addr + e820_map[n - 1].size == start) &&
269       (e820_map[n - 1].type == type))
270       e820_map[n - 1].size += size;
271   else
272     {
273       e820_map[n].addr = start;
274       e820_map[n].size = size;
275       e820_map[n].type = type;
276       (*e820_num)++;
277     }
278   return GRUB_ERR_NONE;
279 }
280
281 static grub_err_t
282 grub_linux_setup_video (struct linux_kernel_params *params)
283 {
284   struct grub_video_mode_info mode_info;
285   void *framebuffer;
286   grub_err_t err;
287   grub_video_driver_id_t driver_id;
288   const char *gfxlfbvar = grub_env_get ("gfxpayloadforcelfb");
289
290   driver_id = grub_video_get_driver_id ();
291
292   if (driver_id == GRUB_VIDEO_DRIVER_NONE)
293     return 1;
294
295   err = grub_video_get_info_and_fini (&mode_info, &framebuffer);
296
297   if (err)
298     {
299       grub_errno = GRUB_ERR_NONE;
300       return 1;
301     }
302
303   params->lfb_width = mode_info.width;
304   params->lfb_height = mode_info.height;
305   params->lfb_depth = mode_info.bpp;
306   params->lfb_line_len = mode_info.pitch;
307
308   params->lfb_base = (grub_size_t) framebuffer;
309   params->lfb_size = ALIGN_UP (params->lfb_line_len * params->lfb_height, 65536);
310
311   params->red_mask_size = mode_info.red_mask_size;
312   params->red_field_pos = mode_info.red_field_pos;
313   params->green_mask_size = mode_info.green_mask_size;
314   params->green_field_pos = mode_info.green_field_pos;
315   params->blue_mask_size = mode_info.blue_mask_size;
316   params->blue_field_pos = mode_info.blue_field_pos;
317   params->reserved_mask_size = mode_info.reserved_mask_size;
318   params->reserved_field_pos = mode_info.reserved_field_pos;
319
320   if (gfxlfbvar && (gfxlfbvar[0] == '1' || gfxlfbvar[0] == 'y'))
321     params->have_vga = GRUB_VIDEO_LINUX_TYPE_SIMPLE;
322   else
323     {
324       switch (driver_id)
325         {
326         case GRUB_VIDEO_DRIVER_VBE:
327           params->lfb_size >>= 16;
328           params->have_vga = GRUB_VIDEO_LINUX_TYPE_VESA;
329           break;
330         
331         case GRUB_VIDEO_DRIVER_EFI_UGA:
332         case GRUB_VIDEO_DRIVER_EFI_GOP:
333           params->have_vga = GRUB_VIDEO_LINUX_TYPE_EFIFB;
334           break;
335
336           /* FIXME: check if better id is available.  */
337         case GRUB_VIDEO_DRIVER_SM712:
338         case GRUB_VIDEO_DRIVER_SIS315PRO:
339         case GRUB_VIDEO_DRIVER_VGA:
340         case GRUB_VIDEO_DRIVER_CIRRUS:
341         case GRUB_VIDEO_DRIVER_BOCHS:
342         case GRUB_VIDEO_DRIVER_RADEON_FULOONG2E:
343         case GRUB_VIDEO_DRIVER_RADEON_YEELOONG3A:
344         case GRUB_VIDEO_DRIVER_IEEE1275:
345         case GRUB_VIDEO_DRIVER_COREBOOT:
346           /* Make gcc happy. */
347         case GRUB_VIDEO_DRIVER_XEN:
348         case GRUB_VIDEO_DRIVER_SDL:
349         case GRUB_VIDEO_DRIVER_NONE:
350         case GRUB_VIDEO_ADAPTER_CAPTURE:
351           params->have_vga = GRUB_VIDEO_LINUX_TYPE_SIMPLE;
352           break;
353         }
354     }
355
356 #ifdef GRUB_MACHINE_PCBIOS
357   /* VESA packed modes may come with zeroed mask sizes, which need
358      to be set here according to DAC Palette width.  If we don't,
359      this results in Linux displaying a black screen.  */
360   if (driver_id == GRUB_VIDEO_DRIVER_VBE && mode_info.bpp <= 8)
361     {
362       struct grub_vbe_info_block controller_info;
363       int status;
364       int width = 8;
365
366       status = grub_vbe_bios_get_controller_info (&controller_info);
367
368       if (status == GRUB_VBE_STATUS_OK &&
369           (controller_info.capabilities & GRUB_VBE_CAPABILITY_DACWIDTH))
370         status = grub_vbe_bios_set_dac_palette_width (&width);
371
372       if (status != GRUB_VBE_STATUS_OK)
373         /* 6 is default after mode reset.  */
374         width = 6;
375
376       params->red_mask_size = params->green_mask_size
377         = params->blue_mask_size = width;
378       params->reserved_mask_size = 0;
379     }
380 #endif
381
382   return GRUB_ERR_NONE;
383 }
384
385 /* Context for grub_linux_boot.  */
386 struct grub_linux_boot_ctx
387 {
388   grub_addr_t real_mode_target;
389   grub_size_t real_size;
390   struct linux_kernel_params *params;
391   int e820_num;
392 };
393
394 /* Helper for grub_linux_boot.  */
395 static int
396 grub_linux_boot_mmap_find (grub_uint64_t addr, grub_uint64_t size,
397                            grub_memory_type_t type, void *data)
398 {
399   struct grub_linux_boot_ctx *ctx = data;
400
401   /* We must put real mode code in the traditional space.  */
402   if (type != GRUB_MEMORY_AVAILABLE || addr > 0x90000)
403     return 0;
404
405   if (addr + size < 0x10000)
406     return 0;
407
408   if (addr < 0x10000)
409     {
410       size += addr - 0x10000;
411       addr = 0x10000;
412     }
413
414   if (addr + size > 0x90000)
415     size = 0x90000 - addr;
416
417   if (ctx->real_size + efi_mmap_size > size)
418     return 0;
419
420   grub_dprintf ("linux", "addr = %lx, size = %x, need_size = %x\n",
421                 (unsigned long) addr,
422                 (unsigned) size,
423                 (unsigned) (ctx->real_size + efi_mmap_size));
424   ctx->real_mode_target = ((addr + size) - (ctx->real_size + efi_mmap_size));
425   return 1;
426 }
427
428 /* GRUB types conveniently match E820 types.  */
429 static int
430 grub_linux_boot_mmap_fill (grub_uint64_t addr, grub_uint64_t size,
431                            grub_memory_type_t type, void *data)
432 {
433   struct grub_linux_boot_ctx *ctx = data;
434
435   if (grub_e820_add_region (ctx->params->e820_map, &ctx->e820_num,
436                             addr, size, type))
437     return 1;
438
439   return 0;
440 }
441
442 static grub_err_t
443 grub_linux_boot (void)
444 {
445   grub_err_t err = 0;
446   const char *modevar;
447   char *tmp;
448   struct grub_relocator32_state state;
449   void *real_mode_mem;
450   struct grub_linux_boot_ctx ctx = {
451     .real_mode_target = 0
452   };
453   grub_size_t mmap_size;
454   grub_size_t cl_offset;
455
456 #ifdef GRUB_MACHINE_IEEE1275
457   {
458     const char *bootpath;
459     grub_ssize_t len;
460
461     bootpath = grub_env_get ("root");
462     if (bootpath)
463       grub_ieee1275_set_property (grub_ieee1275_chosen,
464                                   "bootpath", bootpath,
465                                   grub_strlen (bootpath) + 1,
466                                   &len);
467     linux_params.ofw_signature = GRUB_LINUX_OFW_SIGNATURE;
468     linux_params.ofw_num_items = 1;
469     linux_params.ofw_cif_handler = (grub_uint32_t) grub_ieee1275_entry_fn;
470     linux_params.ofw_idt = 0;
471   }
472 #endif
473
474   modevar = grub_env_get ("gfxpayload");
475
476   /* Now all graphical modes are acceptable.
477      May change in future if we have modes without framebuffer.  */
478   if (modevar && *modevar != 0)
479     {
480       tmp = grub_xasprintf ("%s;" DEFAULT_VIDEO_MODE, modevar);
481       if (! tmp)
482         return grub_errno;
483 #if ACCEPTS_PURE_TEXT
484       err = grub_video_set_mode (tmp, 0, 0);
485 #else
486       err = grub_video_set_mode (tmp, GRUB_VIDEO_MODE_TYPE_PURE_TEXT, 0);
487 #endif
488       grub_free (tmp);
489     }
490   else       /* We can't go back to text mode from coreboot fb.  */
491 #ifdef GRUB_MACHINE_COREBOOT
492     if (grub_video_get_driver_id () == GRUB_VIDEO_DRIVER_COREBOOT)
493       err = GRUB_ERR_NONE;
494     else
495 #endif
496       {
497 #if ACCEPTS_PURE_TEXT
498         err = grub_video_set_mode (DEFAULT_VIDEO_MODE, 0, 0);
499 #else
500         err = grub_video_set_mode (DEFAULT_VIDEO_MODE,
501                                  GRUB_VIDEO_MODE_TYPE_PURE_TEXT, 0);
502 #endif
503       }
504
505   if (err)
506     {
507       grub_print_error ();
508       grub_puts_ (N_("Booting in blind mode"));
509       grub_errno = GRUB_ERR_NONE;
510     }
511
512   if (grub_linux_setup_video (&linux_params))
513     {
514 #if defined (GRUB_MACHINE_PCBIOS) || defined (GRUB_MACHINE_COREBOOT) || defined (GRUB_MACHINE_QEMU)
515       linux_params.have_vga = GRUB_VIDEO_LINUX_TYPE_TEXT;
516       linux_params.video_mode = 0x3;
517 #else
518       linux_params.have_vga = 0;
519       linux_params.video_mode = 0;
520       linux_params.video_width = 0;
521       linux_params.video_height = 0;
522 #endif
523     }
524
525
526 #ifndef GRUB_MACHINE_IEEE1275
527   if (linux_params.have_vga == GRUB_VIDEO_LINUX_TYPE_TEXT)
528 #endif
529     {
530       grub_term_output_t term;
531       int found = 0;
532       FOR_ACTIVE_TERM_OUTPUTS(term)
533         if (grub_strcmp (term->name, "vga_text") == 0
534             || grub_strcmp (term->name, "console") == 0
535             || grub_strcmp (term->name, "ofconsole") == 0)
536           {
537             struct grub_term_coordinate pos = grub_term_getxy (term);
538             linux_params.video_cursor_x = pos.x;
539             linux_params.video_cursor_y = pos.y;
540             linux_params.video_width = grub_term_width (term);
541             linux_params.video_height = grub_term_height (term);
542             found = 1;
543             break;
544           }
545       if (!found)
546         {
547           linux_params.video_cursor_x = 0;
548           linux_params.video_cursor_y = 0;
549           linux_params.video_width = 80;
550           linux_params.video_height = 25;
551         }
552     }
553
554   mmap_size = find_mmap_size ();
555   /* Make sure that each size is aligned to a page boundary.  */
556   cl_offset = ALIGN_UP (mmap_size + sizeof (linux_params), 4096);
557   if (cl_offset < ((grub_size_t) linux_params.setup_sects << GRUB_DISK_SECTOR_BITS))
558     cl_offset = ALIGN_UP ((grub_size_t) (linux_params.setup_sects
559                                          << GRUB_DISK_SECTOR_BITS), 4096);
560   ctx.real_size = ALIGN_UP (cl_offset + maximal_cmdline_size, 4096);
561
562 #ifdef GRUB_MACHINE_EFI
563   efi_mmap_size = find_efi_mmap_size ();
564   if (efi_mmap_size == 0)
565     return grub_errno;
566 #endif
567
568   grub_dprintf ("linux", "real_size = %x, mmap_size = %x\n",
569                 (unsigned) ctx.real_size, (unsigned) mmap_size);
570
571 #ifdef GRUB_MACHINE_EFI
572   grub_efi_mmap_iterate (grub_linux_boot_mmap_find, &ctx, 1);
573   if (! ctx.real_mode_target)
574     grub_efi_mmap_iterate (grub_linux_boot_mmap_find, &ctx, 0);
575 #else
576   grub_mmap_iterate (grub_linux_boot_mmap_find, &ctx);
577 #endif
578   grub_dprintf ("linux", "real_mode_target = %lx, real_size = %x, efi_mmap_size = %x\n",
579                 (unsigned long) ctx.real_mode_target,
580                 (unsigned) ctx.real_size,
581                 (unsigned) efi_mmap_size);
582
583   if (! ctx.real_mode_target)
584     return grub_error (GRUB_ERR_OUT_OF_MEMORY, "cannot allocate real mode pages");
585
586   {
587     grub_relocator_chunk_t ch;
588     err = grub_relocator_alloc_chunk_addr (relocator, &ch,
589                                            ctx.real_mode_target,
590                                            (ctx.real_size + efi_mmap_size));
591     if (err)
592      return err;
593     real_mode_mem = get_virtual_current_address (ch);
594   }
595   efi_mmap_buf = (grub_uint8_t *) real_mode_mem + ctx.real_size;
596
597   grub_dprintf ("linux", "real_mode_mem = %p\n",
598                 real_mode_mem);
599
600   ctx.params = real_mode_mem;
601
602   *ctx.params = linux_params;
603   ctx.params->cmd_line_ptr = ctx.real_mode_target + cl_offset;
604   grub_memcpy ((char *) ctx.params + cl_offset, linux_cmdline,
605                maximal_cmdline_size);
606
607   grub_dprintf ("linux", "code32_start = %x\n",
608                 (unsigned) ctx.params->code32_start);
609
610   ctx.e820_num = 0;
611   if (grub_mmap_iterate (grub_linux_boot_mmap_fill, &ctx))
612     return grub_errno;
613   ctx.params->mmap_size = ctx.e820_num;
614
615 #ifdef GRUB_MACHINE_EFI
616   {
617     grub_efi_uintn_t efi_desc_size;
618     grub_size_t efi_mmap_target;
619     grub_efi_uint32_t efi_desc_version;
620     err = grub_efi_finish_boot_services (&efi_mmap_size, efi_mmap_buf, NULL,
621                                          &efi_desc_size, &efi_desc_version);
622     if (err)
623       return err;
624     
625     /* Note that no boot services are available from here.  */
626     efi_mmap_target = ctx.real_mode_target 
627       + ((grub_uint8_t *) efi_mmap_buf - (grub_uint8_t *) real_mode_mem);
628     /* Pass EFI parameters.  */
629     if (grub_le_to_cpu16 (ctx.params->version) >= 0x0208)
630       {
631         ctx.params->v0208.efi_mem_desc_size = efi_desc_size;
632         ctx.params->v0208.efi_mem_desc_version = efi_desc_version;
633         ctx.params->v0208.efi_mmap = efi_mmap_target;
634         ctx.params->v0208.efi_mmap_size = efi_mmap_size;
635
636 #ifdef __x86_64__
637         ctx.params->v0208.efi_mmap_hi = (efi_mmap_target >> 32);
638 #endif
639       }
640     else if (grub_le_to_cpu16 (ctx.params->version) >= 0x0206)
641       {
642         ctx.params->v0206.efi_mem_desc_size = efi_desc_size;
643         ctx.params->v0206.efi_mem_desc_version = efi_desc_version;
644         ctx.params->v0206.efi_mmap = efi_mmap_target;
645         ctx.params->v0206.efi_mmap_size = efi_mmap_size;
646       }
647     else if (grub_le_to_cpu16 (ctx.params->version) >= 0x0204)
648       {
649         ctx.params->v0204.efi_mem_desc_size = efi_desc_size;
650         ctx.params->v0204.efi_mem_desc_version = efi_desc_version;
651         ctx.params->v0204.efi_mmap = efi_mmap_target;
652         ctx.params->v0204.efi_mmap_size = efi_mmap_size;
653       }
654   }
655 #endif
656
657   /* FIXME.  */
658   /*  asm volatile ("lidt %0" : : "m" (idt_desc)); */
659   state.ebp = state.edi = state.ebx = 0;
660   state.esi = ctx.real_mode_target;
661   state.esp = ctx.real_mode_target;
662   state.eip = ctx.params->code32_start;
663   return grub_relocator32_boot (relocator, state, 0);
664 }
665
666 static grub_err_t
667 grub_linux_unload (void)
668 {
669   grub_dl_unref (my_mod);
670   loaded = 0;
671   grub_free (linux_cmdline);
672   linux_cmdline = 0;
673   return GRUB_ERR_NONE;
674 }
675
676 static grub_err_t
677 grub_cmd_linux (grub_command_t cmd __attribute__ ((unused)),
678                 int argc, char *argv[])
679 {
680   grub_file_t file = 0;
681   struct linux_i386_kernel_header lh;
682   grub_uint8_t setup_sects;
683   grub_size_t real_size, prot_size, prot_file_size;
684   grub_ssize_t len;
685   int i;
686   grub_size_t align, min_align;
687   int relocatable;
688   grub_uint64_t preferred_address = GRUB_LINUX_BZIMAGE_ADDR;
689
690   grub_dl_ref (my_mod);
691
692   if (argc == 0)
693     {
694       grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected"));
695       goto fail;
696     }
697
698   file = grub_file_open (argv[0]);
699   if (! file)
700     goto fail;
701
702   if (grub_file_read (file, &lh, sizeof (lh)) != sizeof (lh))
703     {
704       if (!grub_errno)
705         grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"),
706                     argv[0]);
707       goto fail;
708     }
709
710   if (lh.boot_flag != grub_cpu_to_le16_compile_time (0xaa55))
711     {
712       grub_error (GRUB_ERR_BAD_OS, "invalid magic number");
713       goto fail;
714     }
715
716   if (lh.setup_sects > GRUB_LINUX_MAX_SETUP_SECTS)
717     {
718       grub_error (GRUB_ERR_BAD_OS, "too many setup sectors");
719       goto fail;
720     }
721
722   /* FIXME: 2.03 is not always good enough (Linux 2.4 can be 2.03 and
723      still not support 32-bit boot.  */
724   if (lh.header != grub_cpu_to_le32_compile_time (GRUB_LINUX_I386_MAGIC_SIGNATURE)
725       || grub_le_to_cpu16 (lh.version) < 0x0203)
726     {
727       grub_error (GRUB_ERR_BAD_OS, "version too old for 32-bit boot"
728 #ifdef GRUB_MACHINE_PCBIOS
729                   " (try with `linux16')"
730 #endif
731                   );
732       goto fail;
733     }
734
735   if (! (lh.loadflags & GRUB_LINUX_FLAG_BIG_KERNEL))
736     {
737       grub_error (GRUB_ERR_BAD_OS, "zImage doesn't support 32-bit boot"
738 #ifdef GRUB_MACHINE_PCBIOS
739                   " (try with `linux16')"
740 #endif
741                   );
742       goto fail;
743     }
744
745   if (grub_le_to_cpu16 (lh.version) >= 0x0206)
746     maximal_cmdline_size = grub_le_to_cpu32 (lh.cmdline_size) + 1;
747   else
748     maximal_cmdline_size = 256;
749
750   if (maximal_cmdline_size < 128)
751     maximal_cmdline_size = 128;
752
753   setup_sects = lh.setup_sects;
754
755   /* If SETUP_SECTS is not set, set it to the default (4).  */
756   if (! setup_sects)
757     setup_sects = GRUB_LINUX_DEFAULT_SETUP_SECTS;
758
759   real_size = setup_sects << GRUB_DISK_SECTOR_BITS;
760   prot_file_size = grub_file_size (file) - real_size - GRUB_DISK_SECTOR_SIZE;
761
762   if (grub_le_to_cpu16 (lh.version) >= 0x205
763       && lh.kernel_alignment != 0
764       && ((lh.kernel_alignment - 1) & lh.kernel_alignment) == 0)
765     {
766       for (align = 0; align < 32; align++)
767         if (grub_le_to_cpu32 (lh.kernel_alignment) & (1 << align))
768           break;
769       relocatable = grub_le_to_cpu32 (lh.relocatable);
770     }
771   else
772     {
773       align = 0;
774       relocatable = 0;
775     }
776     
777   if (grub_le_to_cpu16 (lh.version) >= 0x020a)
778     {
779       min_align = lh.min_alignment;
780       prot_size = grub_le_to_cpu32 (lh.init_size);
781       prot_init_space = page_align (prot_size);
782       if (relocatable)
783         preferred_address = grub_le_to_cpu64 (lh.pref_address);
784       else
785         preferred_address = GRUB_LINUX_BZIMAGE_ADDR;
786     }
787   else
788     {
789       min_align = align;
790       prot_size = prot_file_size;
791       preferred_address = GRUB_LINUX_BZIMAGE_ADDR;
792       /* Usually, the compression ratio is about 50%.  */
793       prot_init_space = page_align (prot_size) * 3;
794     }
795
796   if (allocate_pages (prot_size, &align,
797                       min_align, relocatable,
798                       preferred_address))
799     goto fail;
800
801   grub_memset (&linux_params, 0, sizeof (linux_params));
802   grub_memcpy (&linux_params.setup_sects, &lh.setup_sects, sizeof (lh) - 0x1F1);
803
804   linux_params.code32_start = prot_mode_target + lh.code32_start - GRUB_LINUX_BZIMAGE_ADDR;
805   linux_params.kernel_alignment = (1 << align);
806   linux_params.ps_mouse = linux_params.padding10 =  0;
807
808   len = sizeof (linux_params) - sizeof (lh);
809   if (grub_file_read (file, (char *) &linux_params + sizeof (lh), len) != len)
810     {
811       if (!grub_errno)
812         grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"),
813                     argv[0]);
814       goto fail;
815     }
816
817   linux_params.type_of_loader = GRUB_LINUX_BOOT_LOADER_TYPE;
818
819   /* These two are used (instead of cmd_line_ptr) by older versions of Linux,
820      and otherwise ignored.  */
821   linux_params.cl_magic = GRUB_LINUX_CL_MAGIC;
822   linux_params.cl_offset = 0x1000;
823
824   linux_params.ramdisk_image = 0;
825   linux_params.ramdisk_size = 0;
826
827   linux_params.heap_end_ptr = GRUB_LINUX_HEAP_END_OFFSET;
828   linux_params.loadflags |= GRUB_LINUX_FLAG_CAN_USE_HEAP;
829
830   /* These are not needed to be precise, because Linux uses these values
831      only to raise an error when the decompression code cannot find good
832      space.  */
833   linux_params.ext_mem = ((32 * 0x100000) >> 10);
834   linux_params.alt_mem = ((32 * 0x100000) >> 10);
835
836   /* Ignored by Linux.  */
837   linux_params.video_page = 0;
838
839   /* Only used when `video_mode == 0x7', otherwise ignored.  */
840   linux_params.video_ega_bx = 0;
841
842   linux_params.font_size = 16; /* XXX */
843
844 #ifdef GRUB_MACHINE_EFI
845 #ifdef __x86_64__
846   if (grub_le_to_cpu16 (linux_params.version) < 0x0208 &&
847       ((grub_addr_t) grub_efi_system_table >> 32) != 0)
848     return grub_error(GRUB_ERR_BAD_OS,
849                       "kernel does not support 64-bit addressing");
850 #endif
851
852   if (grub_le_to_cpu16 (linux_params.version) >= 0x0208)
853     {
854       linux_params.v0208.efi_signature = GRUB_LINUX_EFI_SIGNATURE;
855       linux_params.v0208.efi_system_table = (grub_uint32_t) (grub_addr_t) grub_efi_system_table;
856 #ifdef __x86_64__
857       linux_params.v0208.efi_system_table_hi = (grub_uint32_t) ((grub_uint64_t) grub_efi_system_table >> 32);
858 #endif
859     }
860   else if (grub_le_to_cpu16 (linux_params.version) >= 0x0206)
861     {
862       linux_params.v0206.efi_signature = GRUB_LINUX_EFI_SIGNATURE;
863       linux_params.v0206.efi_system_table = (grub_uint32_t) (grub_addr_t) grub_efi_system_table;
864     }
865   else if (grub_le_to_cpu16 (linux_params.version) >= 0x0204)
866     {
867       linux_params.v0204.efi_signature = GRUB_LINUX_EFI_SIGNATURE_0204;
868       linux_params.v0204.efi_system_table = (grub_uint32_t) (grub_addr_t) grub_efi_system_table;
869     }
870 #endif
871
872   /* The other parameters are filled when booting.  */
873
874   grub_file_seek (file, real_size + GRUB_DISK_SECTOR_SIZE);
875
876   grub_dprintf ("linux", "bzImage, setup=0x%x, size=0x%x\n",
877                 (unsigned) real_size, (unsigned) prot_size);
878
879   /* Look for memory size and video mode specified on the command line.  */
880   linux_mem_size = 0;
881   for (i = 1; i < argc; i++)
882 #ifdef GRUB_MACHINE_PCBIOS
883     if (grub_memcmp (argv[i], "vga=", 4) == 0)
884       {
885         /* Video mode selection support.  */
886         char *val = argv[i] + 4;
887         unsigned vid_mode = GRUB_LINUX_VID_MODE_NORMAL;
888         struct grub_vesa_mode_table_entry *linux_mode;
889         grub_err_t err;
890         char *buf;
891
892         grub_dl_load ("vbe");
893
894         if (grub_strcmp (val, "normal") == 0)
895           vid_mode = GRUB_LINUX_VID_MODE_NORMAL;
896         else if (grub_strcmp (val, "ext") == 0)
897           vid_mode = GRUB_LINUX_VID_MODE_EXTENDED;
898         else if (grub_strcmp (val, "ask") == 0)
899           {
900             grub_puts_ (N_("Legacy `ask' parameter no longer supported."));
901
902             /* We usually would never do this in a loader, but "vga=ask" means user
903                requested interaction, so it can't hurt to request keyboard input.  */
904             grub_wait_after_message ();
905
906             goto fail;
907           }
908         else
909           vid_mode = (grub_uint16_t) grub_strtoul (val, 0, 0);
910
911         switch (vid_mode)
912           {
913           case 0:
914           case GRUB_LINUX_VID_MODE_NORMAL:
915             grub_env_set ("gfxpayload", "text");
916             grub_printf_ (N_("%s is deprecated. "
917                              "Use set gfxpayload=%s before "
918                              "linux command instead.\n"),
919                           argv[i], "text");
920             break;
921
922           case 1:
923           case GRUB_LINUX_VID_MODE_EXTENDED:
924             /* FIXME: support 80x50 text. */
925             grub_env_set ("gfxpayload", "text");
926             grub_printf_ (N_("%s is deprecated. "
927                              "Use set gfxpayload=%s before "
928                              "linux command instead.\n"),
929                           argv[i], "text");
930             break;
931           default:
932             /* Ignore invalid values.  */
933             if (vid_mode < GRUB_VESA_MODE_TABLE_START ||
934                 vid_mode > GRUB_VESA_MODE_TABLE_END)
935               {
936                 grub_env_set ("gfxpayload", "text");
937                 /* TRANSLATORS: "x" has to be entered in, like an identifier,
938                    so please don't use better Unicode codepoints.  */
939                 grub_printf_ (N_("%s is deprecated. VGA mode %d isn't recognized. "
940                                  "Use set gfxpayload=WIDTHxHEIGHT[xDEPTH] "
941                                  "before linux command instead.\n"),
942                              argv[i], vid_mode);
943                 break;
944               }
945
946             linux_mode = &grub_vesa_mode_table[vid_mode
947                                                - GRUB_VESA_MODE_TABLE_START];
948
949             buf = grub_xasprintf ("%ux%ux%u,%ux%u",
950                                  linux_mode->width, linux_mode->height,
951                                  linux_mode->depth,
952                                  linux_mode->width, linux_mode->height);
953             if (! buf)
954               goto fail;
955
956             grub_printf_ (N_("%s is deprecated. "
957                              "Use set gfxpayload=%s before "
958                              "linux command instead.\n"),
959                          argv[i], buf);
960             err = grub_env_set ("gfxpayload", buf);
961             grub_free (buf);
962             if (err)
963               goto fail;
964           }
965       }
966     else
967 #endif /* GRUB_MACHINE_PCBIOS */
968     if (grub_memcmp (argv[i], "mem=", 4) == 0)
969       {
970         char *val = argv[i] + 4;
971
972         linux_mem_size = grub_strtoul (val, &val, 0);
973
974         if (grub_errno)
975           {
976             grub_errno = GRUB_ERR_NONE;
977             linux_mem_size = 0;
978           }
979         else
980           {
981             int shift = 0;
982
983             switch (grub_tolower (val[0]))
984               {
985               case 'g':
986                 shift += 10;
987                 /* FALLTHROUGH */
988               case 'm':
989                 shift += 10;
990                 /* FALLTHROUGH */
991               case 'k':
992                 shift += 10;
993                 /* FALLTHROUGH */
994               default:
995                 break;
996               }
997
998             /* Check an overflow.  */
999             if (linux_mem_size > (~0UL >> shift))
1000               linux_mem_size = 0;
1001             else
1002               linux_mem_size <<= shift;
1003           }
1004       }
1005     else if (grub_memcmp (argv[i], "quiet", sizeof ("quiet") - 1) == 0)
1006       {
1007         linux_params.loadflags |= GRUB_LINUX_FLAG_QUIET;
1008       }
1009
1010   /* Create kernel command line.  */
1011   linux_cmdline = grub_zalloc (maximal_cmdline_size + 1);
1012   if (!linux_cmdline)
1013     goto fail;
1014   grub_memcpy (linux_cmdline, LINUX_IMAGE, sizeof (LINUX_IMAGE));
1015   grub_create_loader_cmdline (argc, argv,
1016                               linux_cmdline
1017                               + sizeof (LINUX_IMAGE) - 1,
1018                               maximal_cmdline_size
1019                               - (sizeof (LINUX_IMAGE) - 1));
1020
1021   len = prot_file_size;
1022   if (grub_file_read (file, prot_mode_mem, len) != len && !grub_errno)
1023     grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"),
1024                 argv[0]);
1025
1026   if (grub_errno == GRUB_ERR_NONE)
1027     {
1028       grub_loader_set (grub_linux_boot, grub_linux_unload,
1029                        0 /* set noreturn=0 in order to avoid grub_console_fini() */);
1030       loaded = 1;
1031     }
1032
1033  fail:
1034
1035   if (file)
1036     grub_file_close (file);
1037
1038   if (grub_errno != GRUB_ERR_NONE)
1039     {
1040       grub_dl_unref (my_mod);
1041       loaded = 0;
1042     }
1043
1044   return grub_errno;
1045 }
1046
1047 static grub_err_t
1048 grub_cmd_initrd (grub_command_t cmd __attribute__ ((unused)),
1049                  int argc, char *argv[])
1050 {
1051   grub_size_t size = 0, aligned_size = 0;
1052   grub_addr_t addr_min, addr_max;
1053   grub_addr_t addr;
1054   grub_err_t err;
1055   struct grub_linux_initrd_context initrd_ctx = { 0, 0, 0 };
1056
1057   if (argc == 0)
1058     {
1059       grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected"));
1060       goto fail;
1061     }
1062
1063   if (! loaded)
1064     {
1065       grub_error (GRUB_ERR_BAD_ARGUMENT, N_("you need to load the kernel first"));
1066       goto fail;
1067     }
1068
1069   if (grub_initrd_init (argc, argv, &initrd_ctx))
1070     goto fail;
1071
1072   size = grub_get_initrd_size (&initrd_ctx);
1073   aligned_size = ALIGN_UP (size, 4096);
1074
1075   /* Get the highest address available for the initrd.  */
1076   if (grub_le_to_cpu16 (linux_params.version) >= 0x0203)
1077     {
1078       addr_max = grub_cpu_to_le32 (linux_params.initrd_addr_max);
1079
1080       /* XXX in reality, Linux specifies a bogus value, so
1081          it is necessary to make sure that ADDR_MAX does not exceed
1082          0x3fffffff.  */
1083       if (addr_max > GRUB_LINUX_INITRD_MAX_ADDRESS)
1084         addr_max = GRUB_LINUX_INITRD_MAX_ADDRESS;
1085     }
1086   else
1087     addr_max = GRUB_LINUX_INITRD_MAX_ADDRESS;
1088
1089   if (linux_mem_size != 0 && linux_mem_size < addr_max)
1090     addr_max = linux_mem_size;
1091
1092   /* Linux 2.3.xx has a bug in the memory range check, so avoid
1093      the last page.
1094      Linux 2.2.xx has a bug in the memory range check, which is
1095      worse than that of Linux 2.3.xx, so avoid the last 64kb.  */
1096   addr_max -= 0x10000;
1097
1098   addr_min = (grub_addr_t) prot_mode_target + prot_init_space;
1099
1100   /* Put the initrd as high as possible, 4KiB aligned.  */
1101   addr = (addr_max - aligned_size) & ~0xFFF;
1102
1103   if (addr < addr_min)
1104     {
1105       grub_error (GRUB_ERR_OUT_OF_RANGE, "the initrd is too big");
1106       goto fail;
1107     }
1108
1109   {
1110     grub_relocator_chunk_t ch;
1111     err = grub_relocator_alloc_chunk_align (relocator, &ch,
1112                                             addr_min, addr, aligned_size,
1113                                             0x1000,
1114                                             GRUB_RELOCATOR_PREFERENCE_HIGH,
1115                                             1);
1116     if (err)
1117       return err;
1118     initrd_mem = get_virtual_current_address (ch);
1119     initrd_mem_target = get_physical_target_address (ch);
1120   }
1121
1122   if (grub_initrd_load (&initrd_ctx, argv, initrd_mem))
1123     goto fail;
1124
1125   grub_dprintf ("linux", "Initrd, addr=0x%x, size=0x%x\n",
1126                 (unsigned) addr, (unsigned) size);
1127
1128   linux_params.ramdisk_image = initrd_mem_target;
1129   linux_params.ramdisk_size = size;
1130   linux_params.root_dev = 0x0100; /* XXX */
1131
1132  fail:
1133   grub_initrd_close (&initrd_ctx);
1134
1135   return grub_errno;
1136 }
1137
1138 static grub_command_t cmd_linux, cmd_initrd;
1139
1140 GRUB_MOD_INIT(linux)
1141 {
1142   cmd_linux = grub_register_command ("linux", grub_cmd_linux,
1143                                      0, N_("Load Linux."));
1144   cmd_initrd = grub_register_command ("initrd", grub_cmd_initrd,
1145                                       0, N_("Load initrd."));
1146   my_mod = mod;
1147 }
1148
1149 GRUB_MOD_FINI(linux)
1150 {
1151   grub_unregister_command (cmd_linux);
1152   grub_unregister_command (cmd_initrd);
1153 }