misc.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * misc.c
  4. *
  5. * This is a collection of several routines used to extract the kernel
  6. * which includes KASLR relocation, decompression, ELF parsing, and
  7. * relocation processing. Additionally included are the screen and serial
  8. * output functions and related debugging support functions.
  9. *
  10. * malloc by Hannu Savolainen 1993 and Matthias Urlichs 1994
  11. * puts by Nick Holloway 1993, better puts by Martin Mares 1995
  12. * High loaded stuff by Hans Lermen & Werner Almesberger, Feb. 1996
  13. */
  14. #include "misc.h"
  15. #include "error.h"
  16. #include "pgtable.h"
  17. #include "../string.h"
  18. #include "../voffset.h"
  19. #include <asm/bootparam_utils.h>
  20. /*
  21. * WARNING!!
  22. * This code is compiled with -fPIC and it is relocated dynamically at
  23. * run time, but no relocation processing is performed. This means that
  24. * it is not safe to place pointers in static structures.
  25. */
  26. /* Macros used by the included decompressor code below. */
  27. #define STATIC static
  28. /* Define an externally visible malloc()/free(). */
  29. #define MALLOC_VISIBLE
  30. #include <linux/decompress/mm.h>
  31. /*
  32. * Provide definitions of memzero and memmove as some of the decompressors will
  33. * try to define their own functions if these are not defined as macros.
  34. */
  35. #define memzero(s, n) memset((s), 0, (n))
  36. #ifndef memmove
  37. #define memmove memmove
  38. /* Functions used by the included decompressor code below. */
  39. void *memmove(void *dest, const void *src, size_t n);
  40. #endif
  41. /*
  42. * This is set up by the setup-routine at boot-time
  43. */
  44. struct boot_params *boot_params_ptr;
  45. struct port_io_ops pio_ops;
  46. memptr free_mem_ptr;
  47. memptr free_mem_end_ptr;
  48. int spurious_nmi_count;
  49. static char *vidmem;
  50. static int vidport;
  51. /* These might be accessed before .bss is cleared, so use .data instead. */
  52. static int lines __section(".data");
  53. static int cols __section(".data");
  54. #ifdef CONFIG_KERNEL_GZIP
  55. #include "../../../../lib/decompress_inflate.c"
  56. #endif
  57. #ifdef CONFIG_KERNEL_BZIP2
  58. #include "../../../../lib/decompress_bunzip2.c"
  59. #endif
  60. #ifdef CONFIG_KERNEL_LZMA
  61. #include "../../../../lib/decompress_unlzma.c"
  62. #endif
  63. #ifdef CONFIG_KERNEL_XZ
  64. #include "../../../../lib/decompress_unxz.c"
  65. #endif
  66. #ifdef CONFIG_KERNEL_LZO
  67. #include "../../../../lib/decompress_unlzo.c"
  68. #endif
  69. #ifdef CONFIG_KERNEL_LZ4
  70. #include "../../../../lib/decompress_unlz4.c"
  71. #endif
  72. #ifdef CONFIG_KERNEL_ZSTD
  73. #include "../../../../lib/decompress_unzstd.c"
  74. #endif
  75. /*
  76. * NOTE: When adding a new decompressor, please update the analysis in
  77. * ../header.S.
  78. */
  79. static void scroll(void)
  80. {
  81. int i;
  82. memmove(vidmem, vidmem + cols * 2, (lines - 1) * cols * 2);
  83. for (i = (lines - 1) * cols * 2; i < lines * cols * 2; i += 2)
  84. vidmem[i] = ' ';
  85. }
  86. #define XMTRDY 0x20
  87. #define TXR 0 /* Transmit register (WRITE) */
  88. #define LSR 5 /* Line Status */
  89. static void serial_putchar(int ch)
  90. {
  91. unsigned timeout = 0xffff;
  92. while ((inb(early_serial_base + LSR) & XMTRDY) == 0 && --timeout)
  93. cpu_relax();
  94. outb(ch, early_serial_base + TXR);
  95. }
  96. void __putstr(const char *s)
  97. {
  98. int x, y, pos;
  99. char c;
  100. if (early_serial_base) {
  101. const char *str = s;
  102. while (*str) {
  103. if (*str == '\n')
  104. serial_putchar('\r');
  105. serial_putchar(*str++);
  106. }
  107. }
  108. if (lines == 0 || cols == 0)
  109. return;
  110. x = boot_params_ptr->screen_info.orig_x;
  111. y = boot_params_ptr->screen_info.orig_y;
  112. while ((c = *s++) != '\0') {
  113. if (c == '\n') {
  114. x = 0;
  115. if (++y >= lines) {
  116. scroll();
  117. y--;
  118. }
  119. } else {
  120. vidmem[(x + cols * y) * 2] = c;
  121. if (++x >= cols) {
  122. x = 0;
  123. if (++y >= lines) {
  124. scroll();
  125. y--;
  126. }
  127. }
  128. }
  129. }
  130. boot_params_ptr->screen_info.orig_x = x;
  131. boot_params_ptr->screen_info.orig_y = y;
  132. pos = (x + cols * y) * 2; /* Update cursor position */
  133. outb(14, vidport);
  134. outb(0xff & (pos >> 9), vidport+1);
  135. outb(15, vidport);
  136. outb(0xff & (pos >> 1), vidport+1);
  137. }
  138. static noinline void __putnum(unsigned long value, unsigned int base,
  139. int mindig)
  140. {
  141. char buf[8*sizeof(value)+1];
  142. char *p;
  143. p = buf + sizeof(buf);
  144. *--p = '\0';
  145. while (mindig-- > 0 || value) {
  146. unsigned char digit = value % base;
  147. digit += (digit >= 10) ? ('a'-10) : '0';
  148. *--p = digit;
  149. value /= base;
  150. }
  151. __putstr(p);
  152. }
  153. void __puthex(unsigned long value)
  154. {
  155. __putnum(value, 16, sizeof(value)*2);
  156. }
  157. void __putdec(unsigned long value)
  158. {
  159. __putnum(value, 10, 1);
  160. }
  161. #ifdef CONFIG_X86_NEED_RELOCS
  162. static void handle_relocations(void *output, unsigned long output_len,
  163. unsigned long virt_addr)
  164. {
  165. int *reloc;
  166. unsigned long delta, map, ptr;
  167. unsigned long min_addr = (unsigned long)output;
  168. unsigned long max_addr = min_addr + (VO___bss_start - VO__text);
  169. /*
  170. * Calculate the delta between where vmlinux was linked to load
  171. * and where it was actually loaded.
  172. */
  173. delta = min_addr - LOAD_PHYSICAL_ADDR;
  174. /*
  175. * The kernel contains a table of relocation addresses. Those
  176. * addresses have the final load address of the kernel in virtual
  177. * memory. We are currently working in the self map. So we need to
  178. * create an adjustment for kernel memory addresses to the self map.
  179. * This will involve subtracting out the base address of the kernel.
  180. */
  181. map = delta - __START_KERNEL_map;
  182. /*
  183. * 32-bit always performs relocations. 64-bit relocations are only
  184. * needed if KASLR has chosen a different starting address offset
  185. * from __START_KERNEL_map.
  186. */
  187. if (IS_ENABLED(CONFIG_X86_64))
  188. delta = virt_addr - LOAD_PHYSICAL_ADDR;
  189. if (!delta) {
  190. debug_putstr("No relocation needed... ");
  191. return;
  192. }
  193. debug_putstr("Performing relocations... ");
  194. /*
  195. * Process relocations: 32 bit relocations first then 64 bit after.
  196. * Three sets of binary relocations are added to the end of the kernel
  197. * before compression. Each relocation table entry is the kernel
  198. * address of the location which needs to be updated stored as a
  199. * 32-bit value which is sign extended to 64 bits.
  200. *
  201. * Format is:
  202. *
  203. * kernel bits...
  204. * 0 - zero terminator for 64 bit relocations
  205. * 64 bit relocation repeated
  206. * 0 - zero terminator for inverse 32 bit relocations
  207. * 32 bit inverse relocation repeated
  208. * 0 - zero terminator for 32 bit relocations
  209. * 32 bit relocation repeated
  210. *
  211. * So we work backwards from the end of the decompressed image.
  212. */
  213. for (reloc = output + output_len - sizeof(*reloc); *reloc; reloc--) {
  214. long extended = *reloc;
  215. extended += map;
  216. ptr = (unsigned long)extended;
  217. if (ptr < min_addr || ptr > max_addr)
  218. error("32-bit relocation outside of kernel!\n");
  219. *(uint32_t *)ptr += delta;
  220. }
  221. #ifdef CONFIG_X86_64
  222. while (*--reloc) {
  223. long extended = *reloc;
  224. extended += map;
  225. ptr = (unsigned long)extended;
  226. if (ptr < min_addr || ptr > max_addr)
  227. error("inverse 32-bit relocation outside of kernel!\n");
  228. *(int32_t *)ptr -= delta;
  229. }
  230. for (reloc--; *reloc; reloc--) {
  231. long extended = *reloc;
  232. extended += map;
  233. ptr = (unsigned long)extended;
  234. if (ptr < min_addr || ptr > max_addr)
  235. error("64-bit relocation outside of kernel!\n");
  236. *(uint64_t *)ptr += delta;
  237. }
  238. #endif
  239. }
  240. #else
  241. static inline void handle_relocations(void *output, unsigned long output_len,
  242. unsigned long virt_addr)
  243. { }
  244. #endif
  245. static size_t parse_elf(void *output)
  246. {
  247. #ifdef CONFIG_X86_64
  248. Elf64_Ehdr ehdr;
  249. Elf64_Phdr *phdrs, *phdr;
  250. #else
  251. Elf32_Ehdr ehdr;
  252. Elf32_Phdr *phdrs, *phdr;
  253. #endif
  254. void *dest;
  255. int i;
  256. memcpy(&ehdr, output, sizeof(ehdr));
  257. if (ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
  258. ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
  259. ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
  260. ehdr.e_ident[EI_MAG3] != ELFMAG3)
  261. error("Kernel is not a valid ELF file");
  262. debug_putstr("Parsing ELF... ");
  263. phdrs = malloc(sizeof(*phdrs) * ehdr.e_phnum);
  264. if (!phdrs)
  265. error("Failed to allocate space for phdrs");
  266. memcpy(phdrs, output + ehdr.e_phoff, sizeof(*phdrs) * ehdr.e_phnum);
  267. for (i = 0; i < ehdr.e_phnum; i++) {
  268. phdr = &phdrs[i];
  269. switch (phdr->p_type) {
  270. case PT_LOAD:
  271. #ifdef CONFIG_X86_64
  272. if ((phdr->p_align % 0x200000) != 0)
  273. error("Alignment of LOAD segment isn't multiple of 2MB");
  274. #endif
  275. #ifdef CONFIG_RELOCATABLE
  276. dest = output;
  277. dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR);
  278. #else
  279. dest = (void *)(phdr->p_paddr);
  280. #endif
  281. memmove(dest, output + phdr->p_offset, phdr->p_filesz);
  282. break;
  283. default: /* Ignore other PT_* */ break;
  284. }
  285. }
  286. free(phdrs);
  287. return ehdr.e_entry - LOAD_PHYSICAL_ADDR;
  288. }
  289. const unsigned long kernel_text_size = VO___start_rodata - VO__text;
  290. const unsigned long kernel_total_size = VO__end - VO__text;
  291. static u8 boot_heap[BOOT_HEAP_SIZE] __aligned(4);
  292. extern unsigned char input_data[];
  293. extern unsigned int input_len, output_len;
  294. unsigned long decompress_kernel(unsigned char *outbuf, unsigned long virt_addr,
  295. void (*error)(char *x))
  296. {
  297. unsigned long entry;
  298. if (!free_mem_ptr) {
  299. free_mem_ptr = (unsigned long)boot_heap;
  300. free_mem_end_ptr = (unsigned long)boot_heap + sizeof(boot_heap);
  301. }
  302. if (__decompress(input_data, input_len, NULL, NULL, outbuf, output_len,
  303. NULL, error) < 0)
  304. return ULONG_MAX;
  305. entry = parse_elf(outbuf);
  306. handle_relocations(outbuf, output_len, virt_addr);
  307. return entry;
  308. }
  309. /*
  310. * Set the memory encryption xloadflag based on the mem_encrypt= command line
  311. * parameter, if provided.
  312. */
  313. static void parse_mem_encrypt(struct setup_header *hdr)
  314. {
  315. int on = cmdline_find_option_bool("mem_encrypt=on");
  316. int off = cmdline_find_option_bool("mem_encrypt=off");
  317. if (on > off)
  318. hdr->xloadflags |= XLF_MEM_ENCRYPTION;
  319. }
  320. /*
  321. * The compressed kernel image (ZO), has been moved so that its position
  322. * is against the end of the buffer used to hold the uncompressed kernel
  323. * image (VO) and the execution environment (.bss, .brk), which makes sure
  324. * there is room to do the in-place decompression. (See header.S for the
  325. * calculations.)
  326. *
  327. * |-----compressed kernel image------|
  328. * V V
  329. * 0 extract_offset +INIT_SIZE
  330. * |-----------|---------------|-------------------------|--------|
  331. * | | | |
  332. * VO__text startup_32 of ZO VO__end ZO__end
  333. * ^ ^
  334. * |-------uncompressed kernel image---------|
  335. *
  336. */
  337. asmlinkage __visible void *extract_kernel(void *rmode, unsigned char *output)
  338. {
  339. unsigned long virt_addr = LOAD_PHYSICAL_ADDR;
  340. memptr heap = (memptr)boot_heap;
  341. unsigned long needed_size;
  342. size_t entry_offset;
  343. /* Retain x86 boot parameters pointer passed from startup_32/64. */
  344. boot_params_ptr = rmode;
  345. /* Clear flags intended for solely in-kernel use. */
  346. boot_params_ptr->hdr.loadflags &= ~KASLR_FLAG;
  347. parse_mem_encrypt(&boot_params_ptr->hdr);
  348. sanitize_boot_params(boot_params_ptr);
  349. if (boot_params_ptr->screen_info.orig_video_mode == 7) {
  350. vidmem = (char *) 0xb0000;
  351. vidport = 0x3b4;
  352. } else {
  353. vidmem = (char *) 0xb8000;
  354. vidport = 0x3d4;
  355. }
  356. lines = boot_params_ptr->screen_info.orig_video_lines;
  357. cols = boot_params_ptr->screen_info.orig_video_cols;
  358. init_default_io_ops();
  359. /*
  360. * Detect TDX guest environment.
  361. *
  362. * It has to be done before console_init() in order to use
  363. * paravirtualized port I/O operations if needed.
  364. */
  365. early_tdx_detect();
  366. console_init();
  367. /*
  368. * Save RSDP address for later use. Have this after console_init()
  369. * so that early debugging output from the RSDP parsing code can be
  370. * collected.
  371. */
  372. boot_params_ptr->acpi_rsdp_addr = get_rsdp_addr();
  373. debug_putstr("early console in extract_kernel\n");
  374. free_mem_ptr = heap; /* Heap */
  375. free_mem_end_ptr = heap + BOOT_HEAP_SIZE;
  376. /*
  377. * The memory hole needed for the kernel is the larger of either
  378. * the entire decompressed kernel plus relocation table, or the
  379. * entire decompressed kernel plus .bss and .brk sections.
  380. *
  381. * On X86_64, the memory is mapped with PMD pages. Round the
  382. * size up so that the full extent of PMD pages mapped is
  383. * included in the check against the valid memory table
  384. * entries. This ensures the full mapped area is usable RAM
  385. * and doesn't include any reserved areas.
  386. */
  387. needed_size = max_t(unsigned long, output_len, kernel_total_size);
  388. #ifdef CONFIG_X86_64
  389. needed_size = ALIGN(needed_size, MIN_KERNEL_ALIGN);
  390. #endif
  391. /* Report initial kernel position details. */
  392. debug_putaddr(input_data);
  393. debug_putaddr(input_len);
  394. debug_putaddr(output);
  395. debug_putaddr(output_len);
  396. debug_putaddr(kernel_total_size);
  397. debug_putaddr(needed_size);
  398. #ifdef CONFIG_X86_64
  399. /* Report address of 32-bit trampoline */
  400. debug_putaddr(trampoline_32bit);
  401. #endif
  402. choose_random_location((unsigned long)input_data, input_len,
  403. (unsigned long *)&output,
  404. needed_size,
  405. &virt_addr);
  406. /* Validate memory location choices. */
  407. if ((unsigned long)output & (MIN_KERNEL_ALIGN - 1))
  408. error("Destination physical address inappropriately aligned");
  409. if (virt_addr & (MIN_KERNEL_ALIGN - 1))
  410. error("Destination virtual address inappropriately aligned");
  411. #ifdef CONFIG_X86_64
  412. if (heap > 0x3fffffffffffUL)
  413. error("Destination address too large");
  414. if (virt_addr + needed_size > KERNEL_IMAGE_SIZE)
  415. error("Destination virtual address is beyond the kernel mapping area");
  416. #else
  417. if (heap > ((-__PAGE_OFFSET-(128<<20)-1) & 0x7fffffff))
  418. error("Destination address too large");
  419. #endif
  420. #ifndef CONFIG_RELOCATABLE
  421. if (virt_addr != LOAD_PHYSICAL_ADDR)
  422. error("Destination virtual address changed when not relocatable");
  423. #endif
  424. debug_putstr("\nDecompressing Linux... ");
  425. if (init_unaccepted_memory()) {
  426. debug_putstr("Accepting memory... ");
  427. accept_memory(__pa(output), needed_size);
  428. }
  429. entry_offset = decompress_kernel(output, virt_addr, error);
  430. debug_putstr("done.\nBooting the kernel (entry_offset: 0x");
  431. debug_puthex(entry_offset);
  432. debug_putstr(").\n");
  433. /* Disable exception handling before booting the kernel */
  434. cleanup_exception_handling();
  435. if (spurious_nmi_count) {
  436. error_putstr("Spurious early NMIs ignored: ");
  437. error_putdec(spurious_nmi_count);
  438. error_putstr("\n");
  439. }
  440. return output + entry_offset;
  441. }