memdisk: Force ld output format to 32-bits
[syslinux.git] / efi / main.c
blobfd95f5c825a295d1692b58a0fe41fc6df02964ea
1 /*
2 * Copyright 2011-2014 Intel Corporation - All Rights Reserved
3 */
5 #include <codepage.h>
6 #include <core.h>
7 #include <fs.h>
8 #include <com32.h>
9 #include <syslinux/memscan.h>
10 #include <syslinux/firmware.h>
11 #include <syslinux/linux.h>
12 #include <sys/ansi.h>
13 #include <setjmp.h>
15 #include "efi.h"
16 #include "fio.h"
17 #include "version.h"
18 #include "efi_pxe.h"
20 __export uint16_t PXERetry;
21 __export char copyright_str[] = "Copyright (C) 2011-" YEAR_STR "\n";
22 uint8_t SerialNotice = 1;
23 __export char syslinux_banner[] = "Syslinux " VERSION_STR " (EFI; " DATE_STR ")\n";
24 char CurrentDirName[CURRENTDIR_MAX];
25 struct com32_sys_args __com32;
27 uint32_t _IdleTimer = 0;
28 char __lowmem_heap[32];
29 uint32_t BIOS_timer_next;
30 uint32_t timer_irq;
31 __export uint8_t KbdMap[256];
32 char aux_seg[256];
34 static jmp_buf load_error_buf;
36 EFI_HANDLE image_handle, image_device_handle, mnpsb_handle;
38 static inline EFI_STATUS
39 efi_close_protocol(EFI_HANDLE handle, EFI_GUID *guid, EFI_HANDLE agent,
40 EFI_HANDLE controller)
42 return uefi_call_wrapper(BS->CloseProtocol, 4, handle,
43 guid, agent, controller);
46 bool efi_get_MAC( EFI_DEVICE_PATH * pDevPath, uint8_t * mac, uint16_t mac_size)
49 * in case the DevPath contains more than one instance we consider all of them
50 * contain "the same" MAC Address Device Path structure
52 EFI_DEVICE_PATH *DevPathNode;
53 MAC_ADDR_DEVICE_PATH *MAC;
55 if (!pDevPath)
56 return FALSE;
58 pDevPath = UnpackDevicePath(pDevPath);
60 /* Process each device path node */
61 DevPathNode = pDevPath;
62 while (!IsDevicePathEnd(DevPathNode)) {
63 /* Find the handler to dump this device path node */
64 if (DevicePathType(DevPathNode) == MESSAGING_DEVICE_PATH &&
65 DevicePathSubType(DevPathNode) == MSG_MAC_ADDR_DP) {
66 MAC = (MAC_ADDR_DEVICE_PATH *)DevPathNode;
67 CopyMem(mac, MAC->MacAddress.Addr, PXE_MAC_LENGTH);
68 FreePool(pDevPath);
69 return TRUE;
72 /* Next device path node */
73 DevPathNode = NextDevicePathNode(DevPathNode);
76 FreePool(pDevPath);
77 return FALSE;
81 /* As of UEFI-2.4.0, all EFI_SERVICE_BINDINGs are for networking */
82 struct efi_binding *efi_create_binding(EFI_GUID *bguid, EFI_GUID *pguid)
84 EFI_SERVICE_BINDING *sbp = NULL;
85 struct efi_binding *b;
86 EFI_STATUS status;
87 EFI_HANDLE sb_handle, protocol, child;
89 b = malloc(sizeof(*b));
90 if (!b)
91 return NULL;
93 sb_handle = (mnpsb_handle ? mnpsb_handle : image_device_handle);
94 status = uefi_call_wrapper(BS->OpenProtocol, 6, sb_handle,
95 bguid, (void **)&sbp,
96 image_handle, sb_handle,
97 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
98 if (status != EFI_SUCCESS) {
99 EFI_HANDLE *handles = NULL;
100 UINTN i, nr_handles = 0;
101 EFI_DEVICE_PATH *DevicePath = NULL;
102 uint8_t mac_1[PXE_MAC_LENGTH], mac_2[PXE_MAC_LENGTH];
103 DevicePath = DevicePathFromHandle(image_device_handle);
104 if (DevicePath == NULL) {
105 status = EFI_UNSUPPORTED;
106 goto free_binding;
108 efi_get_MAC(DevicePath, mac_1, PXE_MAC_LENGTH);
109 status = LibLocateHandle(ByProtocol, bguid, NULL, &nr_handles, &handles);
110 if (status != EFI_SUCCESS)
111 goto free_binding;
112 for (i = 0; i < nr_handles; i++) {
113 DevicePath = DevicePathFromHandle(handles[i]);
114 if (efi_get_MAC(DevicePath, mac_2, PXE_MAC_LENGTH)
115 && memcmp(mac_1, mac_2, PXE_MAC_LENGTH) == 0) {
116 sb_handle = handles[i];
117 status = uefi_call_wrapper(BS->OpenProtocol, 6, sb_handle,
118 bguid, (void **)&sbp,
119 image_handle, sb_handle,
120 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
121 if (status == EFI_SUCCESS) {
122 mnpsb_handle = sb_handle;
123 break;
129 if (status != EFI_SUCCESS || sbp == NULL)
130 goto free_binding;
132 child = NULL;
134 status = uefi_call_wrapper(sbp->CreateChild, 2, sbp, (EFI_HANDLE *)&child);
135 if (status != EFI_SUCCESS)
136 goto close_protocol;
138 status = uefi_call_wrapper(BS->OpenProtocol, 6, child,
139 pguid, (void **)&protocol,
140 image_handle, sbp,
141 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
142 if (status != EFI_SUCCESS)
143 goto destroy_child;
145 b->parent = image_device_handle;
146 b->binding = sbp;
147 b->child = child;
148 b->this = protocol;
150 return b;
152 destroy_child:
153 uefi_call_wrapper(sbp->DestroyChild, 2, sbp, child);
155 close_protocol:
156 uefi_call_wrapper(BS->CloseProtocol, 4, sb_handle, bguid,
157 image_handle, sb_handle);
159 free_binding:
160 free(b);
161 return NULL;
164 void efi_destroy_binding(struct efi_binding *b, EFI_GUID *guid)
166 efi_close_protocol(b->child, guid, image_handle, b->binding);
167 uefi_call_wrapper(b->binding->DestroyChild, 2, b->binding, b->child);
168 efi_close_protocol(b->parent, guid, image_handle, b->parent);
170 free(b);
173 #undef kaboom
174 void kaboom(void)
178 void printf_init(void)
182 __export void local_boot(uint16_t ax)
185 * Inform the firmware that we failed to execute correctly, which
186 * will trigger the next entry in the EFI Boot Manager list.
188 longjmp(load_error_buf, 1);
191 void bios_timer_cleanup(void)
195 char trackbuf[4096];
197 void __cdecl core_farcall(uint32_t c, const com32sys_t *a, com32sys_t *b)
201 __export struct firmware *firmware = NULL;
202 __export void *__syslinux_adv_ptr;
203 __export size_t __syslinux_adv_size;
204 char core_xfer_buf[65536];
205 struct iso_boot_info {
206 uint32_t pvd; /* LBA of primary volume descriptor */
207 uint32_t file; /* LBA of boot file */
208 uint32_t length; /* Length of boot file */
209 uint32_t csum; /* Checksum of boot file */
210 uint32_t reserved[10]; /* Currently unused */
211 } iso_boot_info;
213 uint8_t DHCPMagic;
214 uint32_t RebootTime;
216 void pxenv(void)
220 uint16_t BIOS_fbm = 1;
221 far_ptr_t InitStack;
222 far_ptr_t PXEEntry;
224 void gpxe_unload(void)
228 void do_idle(void)
232 void pxe_int1a(void)
236 uint8_t KeepPXE;
238 struct semaphore;
239 mstime_t sem_down(struct semaphore *sem, mstime_t time)
241 /* EFI is single threaded */
242 return 0;
245 void sem_up(struct semaphore *sem)
247 /* EFI is single threaded */
250 __export volatile uint32_t __ms_timer = 0;
251 volatile uint32_t __jiffies = 0;
253 void efi_write_char(uint8_t ch, uint8_t attribute)
255 SIMPLE_TEXT_OUTPUT_INTERFACE *out = ST->ConOut;
256 uint16_t c[2];
258 uefi_call_wrapper(out->SetAttribute, 2, out, attribute);
260 /* Lookup primary Unicode encoding in the system codepage */
261 c[0] = codepage.uni[0][ch];
262 c[1] = '\0';
264 uefi_call_wrapper(out->OutputString, 2, out, c);
267 static void efi_showcursor(const struct term_state *st)
269 SIMPLE_TEXT_OUTPUT_INTERFACE *out = ST->ConOut;
270 bool cursor = st->cursor ? true : false;
272 uefi_call_wrapper(out->EnableCursor, 2, out, cursor);
275 static void efi_set_cursor(int x, int y, bool visible)
277 SIMPLE_TEXT_OUTPUT_INTERFACE *out = ST->ConOut;
279 uefi_call_wrapper(out->SetCursorPosition, 3, out, x, y);
282 static void efi_scroll_up(uint8_t cols, uint8_t rows, uint8_t attribute)
284 efi_write_char('\n', 0);
285 efi_write_char('\r', 0);
288 static void efi_get_mode(int *cols, int *rows)
290 SIMPLE_TEXT_OUTPUT_INTERFACE *out = ST->ConOut;
291 UINTN c, r;
293 uefi_call_wrapper(out->QueryMode, 4, out, out->Mode->Mode, &c, &r);
294 *rows = r;
295 *cols = c;
298 static void efi_erase(int x0, int y0, int x1, int y1, uint8_t attribute)
300 SIMPLE_TEXT_OUTPUT_INTERFACE *out = ST->ConOut;
301 int cols, rows;
303 efi_get_mode(&cols, &rows);
306 * The BIOS version of this function has the ability to erase
307 * parts or all of the screen - the UEFI console doesn't
308 * support this so we just set the cursor position unless
309 * we're clearing the whole screen.
311 if (!x0 && y0 == (cols - 1)) {
312 /* Really clear the screen */
313 uefi_call_wrapper(out->ClearScreen, 1, out);
314 } else {
315 uefi_call_wrapper(out->SetCursorPosition, 3, out, y1, x1);
319 static void efi_text_mode(void)
323 static void efi_get_cursor(uint8_t *x, uint8_t *y)
325 SIMPLE_TEXT_OUTPUT_INTERFACE *out = ST->ConOut;
326 *x = out->Mode->CursorColumn;
327 *y = out->Mode->CursorRow;
330 struct output_ops efi_ops = {
331 .erase = efi_erase,
332 .write_char = efi_write_char,
333 .showcursor = efi_showcursor,
334 .set_cursor = efi_set_cursor,
335 .scroll_up = efi_scroll_up,
336 .get_mode = efi_get_mode,
337 .text_mode = efi_text_mode,
338 .get_cursor = efi_get_cursor,
341 char SubvolName[2];
342 static inline EFI_MEMORY_DESCRIPTOR *
343 get_memory_map(UINTN *nr_entries, UINTN *key, UINTN *desc_sz,
344 uint32_t *desc_ver)
346 return LibMemoryMap(nr_entries, key, desc_sz, desc_ver);
350 int efi_scan_memory(scan_memory_callback_t callback, void *data)
352 UINTN i, nr_entries, key, desc_sz;
353 UINTN buf, bufpos;
354 UINT32 desc_ver;
355 int rv = 0;
357 buf = (UINTN)get_memory_map(&nr_entries, &key, &desc_sz, &desc_ver);
358 if (!buf)
359 return -1;
360 bufpos = buf;
362 for (i = 0; i < nr_entries; bufpos += desc_sz, i++) {
363 EFI_MEMORY_DESCRIPTOR *m;
364 UINT64 region_sz;
365 enum syslinux_memmap_types type;
367 m = (EFI_MEMORY_DESCRIPTOR *)bufpos;
368 region_sz = m->NumberOfPages * EFI_PAGE_SIZE;
370 switch (m->Type) {
371 case EfiConventionalMemory:
372 type = SMT_FREE;
373 break;
374 default:
375 type = SMT_RESERVED;
376 break;
379 rv = callback(data, m->PhysicalStart, region_sz, type);
380 if (rv)
381 break;
384 FreePool((void *)buf);
385 return rv;
388 static struct syslinux_memscan efi_memscan = {
389 .func = efi_scan_memory,
392 extern uint16_t *bios_free_mem;
393 void efi_init(void)
395 /* XXX timer */
396 *bios_free_mem = 0;
397 syslinux_memscan_add(&efi_memscan);
398 mem_init();
401 char efi_getchar(char *hi)
403 SIMPLE_INPUT_INTERFACE *in = ST->ConIn;
404 EFI_INPUT_KEY key;
405 EFI_STATUS status;
407 do {
408 status = uefi_call_wrapper(in->ReadKeyStroke, 2, in, &key);
409 } while (status == EFI_NOT_READY);
411 if (!key.ScanCode)
412 return (char)key.UnicodeChar;
415 * We currently only handle scan codes that fit in 8 bits.
417 *hi = (char)key.ScanCode;
418 return 0;
421 int efi_pollchar(void)
423 SIMPLE_INPUT_INTERFACE *in = ST->ConIn;
424 EFI_STATUS status;
426 status = WaitForSingleEvent(in->WaitForKey, 1);
427 return status != EFI_TIMEOUT;
430 struct input_ops efi_iops = {
431 .getchar = efi_getchar,
432 .pollchar = efi_pollchar,
435 extern void efi_adv_init(void);
436 extern int efi_adv_write(void);
438 struct adv_ops efi_adv_ops = {
439 .init = efi_adv_init,
440 .write = efi_adv_write,
443 struct efi_info {
444 uint32_t load_signature;
445 uint32_t systab;
446 uint32_t desc_size;
447 uint32_t desc_version;
448 uint32_t memmap;
449 uint32_t memmap_size;
450 uint32_t systab_hi;
451 uint32_t memmap_hi;
454 #define E820MAX 128
455 #define E820_RAM 1
456 #define E820_RESERVED 2
457 #define E820_ACPI 3
458 #define E820_NVS 4
459 #define E820_UNUSABLE 5
461 #define BOOT_SIGNATURE 0xaa55
462 #define SYSLINUX_EFILDR 0x30 /* Is this published value? */
463 #define DEFAULT_TIMER_TICK_DURATION 500000 /* 500000 == 500000 * 100 * 10^-9 == 50 msec */
464 #define DEFAULT_MSTIMER_INC 0x32 /* 50 msec */
465 struct e820_entry {
466 uint64_t start;
467 uint64_t len;
468 uint32_t type;
469 } __packed;
471 struct boot_params {
472 struct screen_info screen_info;
473 uint8_t _pad[0x1c0 - sizeof(struct screen_info)];
474 struct efi_info efi;
475 uint8_t _pad2[8];
476 uint8_t e820_entries;
477 uint8_t _pad3[0x2d0 - 0x1e8 - sizeof(uint8_t)];
478 struct e820_entry e820_map[E820MAX];
479 } __packed;
481 /* Allocate boot parameter block aligned to page */
482 #define BOOT_PARAM_BLKSIZE EFI_SIZE_TO_PAGES(sizeof(struct boot_params)) * EFI_PAGE_SIZE
484 /* Routines in support of efi boot loader were obtained from
485 * http://git.kernel.org/?p=boot/efilinux/efilinux.git:
486 * kernel_jump(), handover_jump(),
487 * emalloc()/efree, alloc_pages/free_pages
488 * allocate_pool()/free_pool()
489 * memory_map()
491 extern void kernel_jump(EFI_PHYSICAL_ADDRESS kernel_start,
492 struct boot_params *boot_params);
493 #if __SIZEOF_POINTER__ == 4
494 #define EFI_LOAD_SIG "EL32"
495 #elif __SIZEOF_POINTER__ == 8
496 #define EFI_LOAD_SIG "EL64"
497 #else
498 #error "unsupported architecture"
499 #endif
501 struct dt_desc {
502 uint16_t limit;
503 uint64_t *base;
504 } __packed;
506 struct dt_desc gdt = { 0x800, (uint64_t *)0 };
507 struct dt_desc idt = { 0, 0 };
509 static inline EFI_MEMORY_DESCRIPTOR *
510 get_mem_desc(unsigned long memmap, UINTN desc_sz, int i)
512 return (EFI_MEMORY_DESCRIPTOR *)(memmap + (i * desc_sz));
515 static inline UINT64 round_up(UINT64 x, UINT64 y)
517 return (((x - 1) | (y - 1)) + 1);
520 static inline UINT64 round_down(UINT64 x, UINT64 y)
522 return (x & ~(y - 1));
525 static void find_addr(EFI_PHYSICAL_ADDRESS *first,
526 EFI_PHYSICAL_ADDRESS *last,
527 EFI_PHYSICAL_ADDRESS min,
528 EFI_PHYSICAL_ADDRESS max,
529 size_t size, size_t align)
531 EFI_MEMORY_DESCRIPTOR *map;
532 UINT32 desc_ver;
533 UINTN i, nr_entries, key, desc_sz;
535 map = get_memory_map(&nr_entries, &key, &desc_sz, &desc_ver);
536 if (!map)
537 return;
539 for (i = 0; i < nr_entries; i++) {
540 EFI_MEMORY_DESCRIPTOR *m;
541 EFI_PHYSICAL_ADDRESS best;
542 UINT64 start, end;
544 m = get_mem_desc((unsigned long)map, desc_sz, i);
545 if (m->Type != EfiConventionalMemory)
546 continue;
548 if (m->NumberOfPages < EFI_SIZE_TO_PAGES(size))
549 continue;
551 start = m->PhysicalStart;
552 end = m->PhysicalStart + (m->NumberOfPages << EFI_PAGE_SHIFT);
553 if (first) {
554 if (end < min)
555 continue;
557 /* What's the best address? */
558 if (start < min && min < end)
559 best = min;
560 else
561 best = m->PhysicalStart;
563 start = round_up(best, align);
564 if (start > max)
565 continue;
567 /* Have we run out of space in this region? */
568 if (end < start || (start + size) > end)
569 continue;
571 if (start < *first)
572 *first = start;
575 if (last) {
576 if (start > max)
577 continue;
579 /* What's the best address? */
580 if (start < max && max < end)
581 best = max - size;
582 else
583 best = end - size;
585 start = round_down(best, align);
586 if (start < min || start < m->PhysicalStart)
587 continue;
589 if (start > *last)
590 *last = start;
594 FreePool(map);
598 * allocate_pages - Allocate memory pages from the system
599 * @atype: type of allocation to perform
600 * @mtype: type of memory to allocate
601 * @num_pages: number of contiguous 4KB pages to allocate
602 * @memory: used to return the address of allocated pages
604 * Allocate @num_pages physically contiguous pages from the system
605 * memory and return a pointer to the base of the allocation in
606 * @memory if the allocation succeeds. On success, the firmware memory
607 * map is updated accordingly.
609 * If @atype is AllocateAddress then, on input, @memory specifies the
610 * address at which to attempt to allocate the memory pages.
612 static inline EFI_STATUS
613 allocate_pages(EFI_ALLOCATE_TYPE atype, EFI_MEMORY_TYPE mtype,
614 UINTN num_pages, EFI_PHYSICAL_ADDRESS *memory)
616 return uefi_call_wrapper(BS->AllocatePages, 4, atype,
617 mtype, num_pages, memory);
620 * free_pages - Return memory allocated by allocate_pages() to the firmware
621 * @memory: physical base address of the page range to be freed
622 * @num_pages: number of contiguous 4KB pages to free
624 * On success, the firmware memory map is updated accordingly.
626 static inline EFI_STATUS
627 free_pages(EFI_PHYSICAL_ADDRESS memory, UINTN num_pages)
629 return uefi_call_wrapper(BS->FreePages, 2, memory, num_pages);
632 static EFI_STATUS allocate_addr(EFI_PHYSICAL_ADDRESS *addr, size_t size)
634 UINTN npages = EFI_SIZE_TO_PAGES(size);
636 return uefi_call_wrapper(BS->AllocatePages, 4,
637 AllocateAddress,
638 EfiLoaderData, npages,
639 addr);
642 * allocate_pool - Allocate pool memory
643 * @type: the type of pool to allocate
644 * @size: number of bytes to allocate from pool of @type
645 * @buffer: used to return the address of allocated memory
647 * Allocate memory from pool of @type. If the pool needs more memory
648 * pages are allocated from EfiConventionalMemory in order to grow the
649 * pool.
651 * All allocations are eight-byte aligned.
653 static inline EFI_STATUS
654 allocate_pool(EFI_MEMORY_TYPE type, UINTN size, void **buffer)
656 return uefi_call_wrapper(BS->AllocatePool, 3, type, size, buffer);
660 * free_pool - Return pool memory to the system
661 * @buffer: the buffer to free
663 * Return @buffer to the system. The returned memory is marked as
664 * EfiConventionalMemory.
666 static inline EFI_STATUS free_pool(void *buffer)
668 return uefi_call_wrapper(BS->FreePool, 1, buffer);
671 static void free_addr(EFI_PHYSICAL_ADDRESS addr, size_t size)
673 UINTN npages = EFI_SIZE_TO_PAGES(size);
675 uefi_call_wrapper(BS->FreePages, 2, addr, npages);
678 /* cancel the established timer */
679 static EFI_STATUS cancel_timer(EFI_EVENT ev)
681 return uefi_call_wrapper(BS->SetTimer, 3, ev, TimerCancel, 0);
684 /* Check if timer went off and update default timer counter */
685 void timer_handler(EFI_EVENT ev, VOID *ctx)
687 __ms_timer += DEFAULT_MSTIMER_INC;
688 ++__jiffies;
691 /* Setup a default periodic timer */
692 static EFI_STATUS setup_default_timer(EFI_EVENT *ev)
694 EFI_STATUS efi_status;
696 *ev = NULL;
697 efi_status = uefi_call_wrapper( BS->CreateEvent, 5, EVT_TIMER|EVT_NOTIFY_SIGNAL, TPL_NOTIFY, (EFI_EVENT_NOTIFY)timer_handler, NULL, ev);
698 if (efi_status == EFI_SUCCESS) {
699 efi_status = uefi_call_wrapper(BS->SetTimer, 3, *ev, TimerPeriodic, DEFAULT_TIMER_TICK_DURATION);
701 return efi_status;
705 * emalloc - Allocate memory with a strict alignment requirement
706 * @size: size in bytes of the requested allocation
707 * @align: the required alignment of the allocation
708 * @addr: a pointer to the allocated address on success
710 * If we cannot satisfy @align we return 0.
712 EFI_STATUS emalloc(UINTN size, UINTN align, EFI_PHYSICAL_ADDRESS *addr)
714 UINTN i, nr_entries, map_key, desc_size;
715 EFI_MEMORY_DESCRIPTOR *map_buf;
716 UINTN d;
717 UINT32 desc_version;
718 EFI_STATUS err;
719 UINTN nr_pages = EFI_SIZE_TO_PAGES(size);
721 map_buf = get_memory_map(&nr_entries, &map_key,
722 &desc_size, &desc_version);
723 if (!map_buf)
724 goto fail;
726 d = (UINTN)map_buf;
728 for (i = 0; i < nr_entries; i++, d += desc_size) {
729 EFI_MEMORY_DESCRIPTOR *desc;
730 EFI_PHYSICAL_ADDRESS start, end, aligned;
732 desc = (EFI_MEMORY_DESCRIPTOR *)d;
733 if (desc->Type != EfiConventionalMemory)
734 continue;
736 if (desc->NumberOfPages < nr_pages)
737 continue;
739 start = desc->PhysicalStart;
740 end = start + (desc->NumberOfPages << EFI_PAGE_SHIFT);
742 /* Low-memory is super-precious! */
743 if (end <= 1 << 20)
744 continue;
745 if (start < 1 << 20)
746 start = (1 << 20);
748 aligned = (start + align -1) & ~(align -1);
750 if ((aligned + size) <= end) {
751 err = allocate_pages(AllocateAddress, EfiLoaderData,
752 nr_pages, &aligned);
753 if (err == EFI_SUCCESS) {
754 *addr = aligned;
755 break;
760 if (i == nr_entries)
761 err = EFI_OUT_OF_RESOURCES;
763 free_pool(map_buf);
764 fail:
765 return err;
768 * efree - Return memory allocated with emalloc
769 * @memory: the address of the emalloc() allocation
770 * @size: the size of the allocation
772 void efree(EFI_PHYSICAL_ADDRESS memory, UINTN size)
774 UINTN nr_pages = EFI_SIZE_TO_PAGES(size);
776 free_pages(memory, nr_pages);
780 * Check whether 'buf' contains a PE/COFF header and that the PE/COFF
781 * file can be executed by this architecture.
783 static bool valid_pecoff_image(char *buf)
785 struct pe_header {
786 uint16_t signature;
787 uint8_t _pad[0x3a];
788 uint32_t offset;
789 } *pehdr = (struct pe_header *)buf;
790 struct coff_header {
791 uint32_t signature;
792 uint16_t machine;
793 } *chdr;
795 if (pehdr->signature != 0x5a4d) {
796 dprintf("Invalid MS-DOS header signature\n");
797 return false;
800 if (!pehdr->offset || pehdr->offset > 512) {
801 dprintf("Invalid PE header offset\n");
802 return false;
805 chdr = (struct coff_header *)&buf[pehdr->offset];
806 if (chdr->signature != 0x4550) {
807 dprintf("Invalid PE header signature\n");
808 return false;
811 #if defined(__x86_64__)
812 if (chdr->machine != 0x8664) {
813 dprintf("Invalid PE machine field\n");
814 return false;
816 #else
817 if (chdr->machine != 0x14c) {
818 dprintf("Invalid PE machine field\n");
819 return false;
821 #endif
823 return true;
827 * Boot a Linux kernel using the EFI boot stub handover protocol.
829 * This function will not return to its caller if booting the kernel
830 * image succeeds. If booting the kernel image fails, a legacy boot
831 * method should be attempted.
833 static void handover_boot(struct linux_header *hdr, struct boot_params *bp)
835 unsigned long address = hdr->code32_start + hdr->handover_offset;
836 handover_func_t *func = efi_handover;
838 dprintf("Booting kernel using handover protocol\n");
841 * Ensure that the kernel is a valid PE32(+) file and that the
842 * architecture of the file matches this version of Syslinux - we
843 * can't mix firmware and kernel bitness (e.g. 32-bit kernel on
844 * 64-bit EFI firmware) using the handover protocol.
846 if (!valid_pecoff_image((char *)hdr))
847 return;
849 if (hdr->version >= 0x20c) {
850 if (hdr->xloadflags & XLF_EFI_HANDOVER_32)
851 func = efi_handover_32;
853 if (hdr->xloadflags & XLF_EFI_HANDOVER_64)
854 func = efi_handover_64;
857 efi_console_restore();
858 func(image_handle, ST, bp, address);
861 static int check_linux_header(struct linux_header *hdr)
863 if (hdr->version < 0x205)
864 hdr->relocatable_kernel = 0;
866 /* FIXME: check boot sector signature */
867 if (hdr->boot_flag != BOOT_SIGNATURE) {
868 printf("Invalid Boot signature 0x%x, bailing out\n", hdr->boot_flag);
869 return -1;
872 return 0;
875 static char *build_cmdline(char *str)
877 EFI_PHYSICAL_ADDRESS addr;
878 EFI_STATUS status;
879 char *cmdline = NULL; /* internal, in efi_physical below 0x3FFFFFFF */
882 * The kernel expects cmdline to be allocated pretty low,
883 * Documentation/x86/boot.txt says,
885 * "The kernel command line can be located anywhere
886 * between the end of the setup heap and 0xA0000"
888 addr = 0xA0000;
889 status = allocate_pages(AllocateMaxAddress, EfiLoaderData,
890 EFI_SIZE_TO_PAGES(strlen(str) + 1),
891 &addr);
892 if (status != EFI_SUCCESS) {
893 printf("Failed to allocate memory for kernel command line, bailing out\n");
894 return NULL;
896 cmdline = (char *)(UINTN)addr;
897 memcpy(cmdline, str, strlen(str) + 1);
898 return cmdline;
901 static int build_gdt(void)
903 EFI_STATUS status;
905 /* Allocate gdt consistent with the alignment for architecture */
906 status = emalloc(gdt.limit, __SIZEOF_POINTER__ , (EFI_PHYSICAL_ADDRESS *)&gdt.base);
907 if (status != EFI_SUCCESS) {
908 printf("Failed to allocate memory for GDT, bailing out\n");
909 return -1;
911 memset(gdt.base, 0x0, gdt.limit);
914 * 4Gb - (0x100000*0x1000 = 4Gb)
915 * base address=0
916 * code read/exec
917 * granularity=4096, 386 (+5th nibble of limit)
919 gdt.base[2] = 0x00cf9a000000ffff;
922 * 4Gb - (0x100000*0x1000 = 4Gb)
923 * base address=0
924 * data read/write
925 * granularity=4096, 386 (+5th nibble of limit)
927 gdt.base[3] = 0x00cf92000000ffff;
929 /* Task segment value */
930 gdt.base[4] = 0x0080890000000000;
932 return 0;
936 * Callers use ->ramdisk_size to check whether any memory was
937 * allocated (and therefore needs free'ing). The return value indicates
938 * hard error conditions, such as failing to alloc memory for the
939 * ramdisk image. Having no initramfs is not an error.
941 static int handle_ramdisks(struct linux_header *hdr,
942 struct initramfs *initramfs)
944 EFI_PHYSICAL_ADDRESS last;
945 struct initramfs *ip;
946 EFI_STATUS status;
947 addr_t irf_size;
948 addr_t next_addr, len, pad;
950 hdr->ramdisk_image = 0;
951 hdr->ramdisk_size = 0;
954 * Figure out the size of the initramfs, and where to put it.
955 * We should put it at the highest possible address which is
956 * <= hdr->initrd_addr_max, which fits the entire initramfs.
958 irf_size = initramfs_size(initramfs); /* Handles initramfs == NULL */
959 if (!irf_size)
960 return 0;
962 last = 0;
963 find_addr(NULL, &last, 0x1000, hdr->initrd_addr_max,
964 irf_size, INITRAMFS_MAX_ALIGN);
965 if (last)
966 status = allocate_addr(&last, irf_size);
968 if (!last || status != EFI_SUCCESS) {
969 printf("Failed to allocate initramfs memory, bailing out\n");
970 return -1;
973 hdr->ramdisk_image = (uint32_t)last;
974 hdr->ramdisk_size = irf_size;
976 /* Copy initramfs into allocated memory */
977 for (ip = initramfs->next; ip->len; ip = ip->next) {
978 len = ip->len;
979 next_addr = last + len;
982 * If this isn't the last entry, extend the
983 * zero-pad region to enforce the alignment of
984 * the next chunk.
986 if (ip->next->len) {
987 pad = -next_addr & (ip->next->align - 1);
988 len += pad;
989 next_addr += pad;
992 if (ip->data_len)
993 memcpy((void *)(UINTN)last, ip->data, ip->data_len);
995 if (len > ip->data_len)
996 memset((void *)(UINTN)(last + ip->data_len), 0,
997 len - ip->data_len);
999 last = next_addr;
1001 return 0;
1004 static int exit_boot(struct boot_params *bp)
1006 struct e820_entry *e820buf, *e;
1007 EFI_MEMORY_DESCRIPTOR *map;
1008 EFI_STATUS status;
1009 uint32_t e820_type;
1010 UINTN i, nr_entries, key, desc_sz;
1011 UINT32 desc_ver;
1013 /* Build efi memory map */
1014 map = get_memory_map(&nr_entries, &key, &desc_sz, &desc_ver);
1015 if (!map)
1016 return -1;
1018 bp->efi.memmap = (uint32_t)(unsigned long)map;
1019 bp->efi.memmap_size = nr_entries * desc_sz;
1020 bp->efi.systab = (uint32_t)(unsigned long)ST;
1021 bp->efi.desc_size = desc_sz;
1022 bp->efi.desc_version = desc_ver;
1023 #if defined(__x86_64__)
1024 bp->efi.systab_hi = ((unsigned long)ST) >> 32;
1025 bp->efi.memmap_hi = ((unsigned long)map) >> 32;
1026 #endif
1030 * Even though 'memmap' contains the memory map we provided
1031 * previously in efi_scan_memory(), we should recalculate the
1032 * e820 map because it will most likely have changed in the
1033 * interim.
1035 e = e820buf = bp->e820_map;
1036 for (i = 0; i < nr_entries && i < E820MAX; i++) {
1037 struct e820_entry *prev = NULL;
1039 if (e > e820buf)
1040 prev = e - 1;
1042 map = get_mem_desc(bp->efi.memmap, desc_sz, i);
1043 e->start = map->PhysicalStart;
1044 e->len = map->NumberOfPages << EFI_PAGE_SHIFT;
1046 switch (map->Type) {
1047 case EfiReservedMemoryType:
1048 case EfiRuntimeServicesCode:
1049 case EfiRuntimeServicesData:
1050 case EfiMemoryMappedIO:
1051 case EfiMemoryMappedIOPortSpace:
1052 case EfiPalCode:
1053 e820_type = E820_RESERVED;
1054 break;
1056 case EfiUnusableMemory:
1057 e820_type = E820_UNUSABLE;
1058 break;
1060 case EfiACPIReclaimMemory:
1061 e820_type = E820_ACPI;
1062 break;
1064 case EfiLoaderCode:
1065 case EfiLoaderData:
1066 case EfiBootServicesCode:
1067 case EfiBootServicesData:
1068 case EfiConventionalMemory:
1069 e820_type = E820_RAM;
1070 break;
1072 case EfiACPIMemoryNVS:
1073 e820_type = E820_NVS;
1074 break;
1075 default:
1076 continue;
1079 e->type = e820_type;
1081 /* Check for adjacent entries we can merge. */
1082 if (prev && (prev->start + prev->len) == e->start &&
1083 prev->type == e->type)
1084 prev->len += e->len;
1085 else
1086 e++;
1089 bp->e820_entries = e - e820buf;
1091 status = uefi_call_wrapper(BS->ExitBootServices, 2, image_handle, key);
1092 if (status != EFI_SUCCESS) {
1093 printf("Failed to exit boot services: 0x%016lx\n", status);
1094 FreePool(map);
1095 return -1;
1098 return 0;
1101 /* efi_boot_linux:
1102 * Boots the linux kernel using the image and parameters to boot with.
1103 * The EFI boot loader is reworked taking the cue from
1104 * http://git.kernel.org/?p=boot/efilinux/efilinux.git on the need to
1105 * cap key kernel data structures at * 0x3FFFFFFF.
1106 * The kernel image, kernel command line and boot parameter block are copied
1107 * into allocated memory areas that honor the address capping requirement
1108 * prior to kernel handoff.
1110 * FIXME
1111 * Can we move this allocation requirement to com32 linux loader in order
1112 * to avoid double copying kernel image?
1114 int efi_boot_linux(void *kernel_buf, size_t kernel_size,
1115 struct initramfs *initramfs,
1116 struct setup_data *setup_data,
1117 char *cmdline)
1119 struct linux_header *hdr;
1120 struct boot_params *bp;
1121 EFI_STATUS status;
1122 EFI_PHYSICAL_ADDRESS addr, pref_address, kernel_start = 0;
1123 UINT64 setup_sz, init_size = 0;
1124 char *_cmdline;
1126 if (check_linux_header(kernel_buf))
1127 goto bail;
1129 /* allocate for boot parameter block */
1130 addr = 0x3FFFFFFF;
1131 status = allocate_pages(AllocateMaxAddress, EfiLoaderData,
1132 BOOT_PARAM_BLKSIZE, &addr);
1133 if (status != EFI_SUCCESS) {
1134 printf("Failed to allocate memory for kernel boot parameter block, bailing out\n");
1135 goto bail;
1138 bp = (struct boot_params *)(UINTN)addr;
1140 memset((void *)bp, 0x0, BOOT_PARAM_BLKSIZE);
1141 /* Copy the first two sectors to boot_params */
1142 memcpy((char *)bp, kernel_buf, 2 * 512);
1143 hdr = (struct linux_header *)bp;
1145 setup_sz = (hdr->setup_sects + 1) * 512;
1146 if (hdr->version >= 0x20a) {
1147 pref_address = hdr->pref_address;
1148 init_size = hdr->init_size;
1149 } else {
1150 pref_address = 0x100000;
1153 * We need to account for the fact that the kernel
1154 * needs room for decompression, otherwise we could
1155 * end up trashing other chunks of allocated memory.
1157 init_size = (kernel_size - setup_sz) * 3;
1159 hdr->type_of_loader = SYSLINUX_EFILDR; /* SYSLINUX boot loader module */
1160 _cmdline = build_cmdline(cmdline);
1161 if (!_cmdline)
1162 goto bail;
1164 hdr->cmd_line_ptr = (UINT32)(UINTN)_cmdline;
1166 addr = pref_address;
1167 status = allocate_pages(AllocateAddress, EfiLoaderData,
1168 EFI_SIZE_TO_PAGES(init_size), &addr);
1169 if (status != EFI_SUCCESS) {
1171 * We failed to allocate the preferred address, so
1172 * just allocate some memory and hope for the best.
1174 if (!hdr->relocatable_kernel) {
1175 printf("Cannot relocate kernel, bailing out\n");
1176 goto bail;
1179 status = emalloc(init_size, hdr->kernel_alignment, &addr);
1180 if (status != EFI_SUCCESS) {
1181 printf("Failed to allocate memory for kernel image, bailing out\n");
1182 goto free_map;
1185 kernel_start = addr;
1186 /* FIXME: we copy the kernel into the physical memory allocated here
1187 * The syslinux kernel image load elsewhere could allocate the EFI memory from here
1188 * prior to copying kernel and save an extra copy
1190 memcpy((void *)(UINTN)kernel_start, kernel_buf+setup_sz, kernel_size-setup_sz);
1192 hdr->code32_start = (UINT32)((UINT64)kernel_start);
1194 dprintf("efi_boot_linux: kernel_start 0x%x kernel_size 0x%x initramfs 0x%x setup_data 0x%x cmdline 0x%x\n",
1195 kernel_start, kernel_size, initramfs, setup_data, _cmdline);
1197 if (handle_ramdisks(hdr, initramfs))
1198 goto free_map;
1200 /* Attempt to use the handover protocol if available */
1201 if (hdr->version >= 0x20b && hdr->handover_offset)
1202 handover_boot(hdr, bp);
1204 setup_screen(&bp->screen_info);
1206 if (build_gdt())
1207 goto free_map;
1209 dprintf("efi_boot_linux: setup_sects %d kernel_size %d\n", hdr->setup_sects, kernel_size);
1211 efi_console_restore();
1213 if (exit_boot(bp))
1214 goto free_map;
1216 memcpy(&bp->efi.load_signature, EFI_LOAD_SIG, sizeof(uint32_t));
1218 asm volatile ("lidt %0" :: "m" (idt));
1219 asm volatile ("lgdt %0" :: "m" (gdt));
1221 kernel_jump(kernel_start, bp);
1223 /* NOTREACHED */
1225 free_map:
1226 if (_cmdline)
1227 efree((EFI_PHYSICAL_ADDRESS)(unsigned long)_cmdline,
1228 strlen(_cmdline) + 1);
1230 if (bp)
1231 efree((EFI_PHYSICAL_ADDRESS)(unsigned long)bp,
1232 BOOT_PARAM_BLKSIZE);
1233 if (kernel_start) efree(kernel_start, init_size);
1234 if (hdr->ramdisk_size)
1235 free_addr(hdr->ramdisk_image, hdr->ramdisk_size);
1236 bail:
1237 return -1;
1240 extern struct disk *efi_disk_init(EFI_HANDLE);
1241 extern void serialcfg(uint16_t *, uint16_t *, uint16_t *);
1243 extern struct vesa_ops efi_vesa_ops;
1245 struct mem_ops efi_mem_ops = {
1246 .malloc = efi_malloc,
1247 .realloc = efi_realloc,
1248 .free = efi_free,
1251 struct firmware efi_fw = {
1252 .init = efi_init,
1253 .disk_init = efi_disk_init,
1254 .o_ops = &efi_ops,
1255 .i_ops = &efi_iops,
1256 .get_serial_console_info = serialcfg,
1257 .adv_ops = &efi_adv_ops,
1258 .boot_linux = efi_boot_linux,
1259 .vesa = &efi_vesa_ops,
1260 .mem = &efi_mem_ops,
1263 static inline void syslinux_register_efi(void)
1265 firmware = &efi_fw;
1268 extern void init(void);
1269 extern const struct fs_ops vfat_fs_ops;
1270 extern const struct fs_ops pxe_fs_ops;
1272 char free_high_memory[4096];
1274 extern char __bss_start[];
1275 extern char __bss_end[];
1277 static void efi_setcwd(CHAR16 *dp)
1279 CHAR16 *c16;
1280 char *c8;
1281 int i, j;
1283 /* Search for the start of the last path component */
1284 for (i = StrLen(dp) - 1; i >= 0; i--) {
1285 if (dp[i] == '\\' || dp[i] == '/')
1286 break;
1289 if (i < 0 || i > CURRENTDIR_MAX) {
1290 dp = L"\\";
1291 i = 1;
1294 c8 = CurrentDirName;
1295 c16 = dp;
1297 for (j = 0; j < i; j++) {
1298 if (*c16 == '\\') {
1299 *c8++ = '/';
1300 c16++;
1301 } else
1302 *c8++ = *c16++;
1305 *c8 = '\0';
1308 EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *table)
1310 EFI_PXE_BASE_CODE *pxe;
1311 EFI_LOADED_IMAGE *info;
1312 EFI_STATUS status = EFI_SUCCESS;
1313 const struct fs_ops *ops[] = { NULL, NULL };
1314 unsigned long len = (unsigned long)__bss_end - (unsigned long)__bss_start;
1315 static struct efi_disk_private priv;
1316 SIMPLE_INPUT_INTERFACE *in;
1317 EFI_INPUT_KEY key;
1318 EFI_EVENT timer_ev;
1320 memset(__bss_start, 0, len);
1321 InitializeLib(image, table);
1323 image_handle = image;
1324 syslinux_register_efi();
1326 efi_console_save();
1327 init();
1329 status = uefi_call_wrapper(BS->HandleProtocol, 3, image,
1330 &LoadedImageProtocol, (void **)&info);
1331 if (status != EFI_SUCCESS) {
1332 Print(L"Failed to lookup LoadedImageProtocol\n");
1333 goto out;
1336 status = uefi_call_wrapper(BS->HandleProtocol, 3, info->DeviceHandle,
1337 &PxeBaseCodeProtocol, (void **)&pxe);
1338 if (status != EFI_SUCCESS) {
1340 * Use device handle to set up the volume root to
1341 * proceed with ADV init.
1343 if (EFI_ERROR(efi_set_volroot(info->DeviceHandle))) {
1344 Print(L"Failed to locate root device to prep for ");
1345 Print(L"file operations & ADV initialization\n");
1346 goto out;
1349 efi_derivative(SYSLINUX_FS_SYSLINUX);
1350 ops[0] = &vfat_fs_ops;
1351 } else {
1352 efi_derivative(SYSLINUX_FS_PXELINUX);
1353 ops[0] = &pxe_fs_ops;
1354 image_device_handle = info->DeviceHandle;
1357 /* setup timer for boot menu system support */
1358 status = setup_default_timer(&timer_ev);
1359 if (status != EFI_SUCCESS) {
1360 Print(L"Failed to set up EFI timer support, bailing out\n");
1361 goto out;
1364 /* TODO: once all errors are captured in efi_errno, bail out if necessary */
1366 priv.dev_handle = info->DeviceHandle;
1369 * Set the current working directory, which should be the
1370 * directory that syslinux.efi resides in.
1372 efi_setcwd(DevicePathToStr(info->FilePath));
1374 fs_init(ops, (void *)&priv);
1377 * There may be pending user input that wasn't processed by
1378 * whatever application invoked us. Consume and discard that
1379 * data now.
1381 in = ST->ConIn;
1382 do {
1383 status = uefi_call_wrapper(in->ReadKeyStroke, 2, in, &key);
1384 } while (status == EFI_SUCCESS);
1386 if (!setjmp(load_error_buf))
1387 load_env32(NULL);
1389 /* load_env32() failed.. cancel timer and bailout */
1390 status = cancel_timer(timer_ev);
1391 if (status != EFI_SUCCESS)
1392 Print(L"Failed to cancel EFI timer: %x\n", status);
1395 * Tell the firmware that Syslinux failed to load.
1397 status = EFI_LOAD_ERROR;
1398 out:
1399 efi_console_restore();
1400 return status;