GNU Linux-libre 4.4.292-gnu1
[releases.git] / arch / x86 / boot / compressed / misc.c
1 /*
2  * misc.c
3  *
4  * This is a collection of several routines from gzip-1.0.3
5  * adapted for Linux.
6  *
7  * malloc by Hannu Savolainen 1993 and Matthias Urlichs 1994
8  * puts by Nick Holloway 1993, better puts by Martin Mares 1995
9  * High loaded stuff by Hans Lermen & Werner Almesberger, Feb. 1996
10  */
11
12 #include "misc.h"
13 #include "../string.h"
14 #include <asm/bootparam_utils.h>
15
16 /* WARNING!!
17  * This code is compiled with -fPIC and it is relocated dynamically
18  * at run time, but no relocation processing is performed.
19  * This means that it is not safe to place pointers in static structures.
20  */
21
22 /*
23  * Getting to provable safe in place decompression is hard.
24  * Worst case behaviours need to be analyzed.
25  * Background information:
26  *
27  * The file layout is:
28  *    magic[2]
29  *    method[1]
30  *    flags[1]
31  *    timestamp[4]
32  *    extraflags[1]
33  *    os[1]
34  *    compressed data blocks[N]
35  *    crc[4] orig_len[4]
36  *
37  * resulting in 18 bytes of non compressed data overhead.
38  *
39  * Files divided into blocks
40  * 1 bit (last block flag)
41  * 2 bits (block type)
42  *
43  * 1 block occurs every 32K -1 bytes or when there 50% compression
44  * has been achieved. The smallest block type encoding is always used.
45  *
46  * stored:
47  *    32 bits length in bytes.
48  *
49  * fixed:
50  *    magic fixed tree.
51  *    symbols.
52  *
53  * dynamic:
54  *    dynamic tree encoding.
55  *    symbols.
56  *
57  *
58  * The buffer for decompression in place is the length of the
59  * uncompressed data, plus a small amount extra to keep the algorithm safe.
60  * The compressed data is placed at the end of the buffer.  The output
61  * pointer is placed at the start of the buffer and the input pointer
62  * is placed where the compressed data starts.  Problems will occur
63  * when the output pointer overruns the input pointer.
64  *
65  * The output pointer can only overrun the input pointer if the input
66  * pointer is moving faster than the output pointer.  A condition only
67  * triggered by data whose compressed form is larger than the uncompressed
68  * form.
69  *
70  * The worst case at the block level is a growth of the compressed data
71  * of 5 bytes per 32767 bytes.
72  *
73  * The worst case internal to a compressed block is very hard to figure.
74  * The worst case can at least be boundined by having one bit that represents
75  * 32764 bytes and then all of the rest of the bytes representing the very
76  * very last byte.
77  *
78  * All of which is enough to compute an amount of extra data that is required
79  * to be safe.  To avoid problems at the block level allocating 5 extra bytes
80  * per 32767 bytes of data is sufficient.  To avoind problems internal to a
81  * block adding an extra 32767 bytes (the worst case uncompressed block size)
82  * is sufficient, to ensure that in the worst case the decompressed data for
83  * block will stop the byte before the compressed data for a block begins.
84  * To avoid problems with the compressed data's meta information an extra 18
85  * bytes are needed.  Leading to the formula:
86  *
87  * extra_bytes = (uncompressed_size >> 12) + 32768 + 18 + decompressor_size.
88  *
89  * Adding 8 bytes per 32K is a bit excessive but much easier to calculate.
90  * Adding 32768 instead of 32767 just makes for round numbers.
91  * Adding the decompressor_size is necessary as it musht live after all
92  * of the data as well.  Last I measured the decompressor is about 14K.
93  * 10K of actual data and 4K of bss.
94  *
95  */
96
97 /*
98  * gzip declarations
99  */
100 #define STATIC          static
101
102 #undef memcpy
103
104 /*
105  * Use a normal definition of memset() from string.c. There are already
106  * included header files which expect a definition of memset() and by
107  * the time we define memset macro, it is too late.
108  */
109 #undef memset
110 #define memzero(s, n)   memset((s), 0, (n))
111
112
113 static void error(char *m);
114
115 /*
116  * This is set up by the setup-routine at boot-time
117  */
118 struct boot_params *real_mode;          /* Pointer to real-mode data */
119
120 memptr free_mem_ptr;
121 memptr free_mem_end_ptr;
122
123 static char *vidmem;
124 static int vidport;
125 static int lines, cols;
126
127 #ifdef CONFIG_KERNEL_GZIP
128 #include "../../../../lib/decompress_inflate.c"
129 #endif
130
131 #ifdef CONFIG_KERNEL_BZIP2
132 #include "../../../../lib/decompress_bunzip2.c"
133 #endif
134
135 #ifdef CONFIG_KERNEL_LZMA
136 #include "../../../../lib/decompress_unlzma.c"
137 #endif
138
139 #ifdef CONFIG_KERNEL_XZ
140 #include "../../../../lib/decompress_unxz.c"
141 #endif
142
143 #ifdef CONFIG_KERNEL_LZO
144 #include "../../../../lib/decompress_unlzo.c"
145 #endif
146
147 #ifdef CONFIG_KERNEL_LZ4
148 #include "../../../../lib/decompress_unlz4.c"
149 #endif
150
151 static void scroll(void)
152 {
153         int i;
154
155         memcpy(vidmem, vidmem + cols * 2, (lines - 1) * cols * 2);
156         for (i = (lines - 1) * cols * 2; i < lines * cols * 2; i += 2)
157                 vidmem[i] = ' ';
158 }
159
160 #define XMTRDY          0x20
161
162 #define TXR             0       /*  Transmit register (WRITE) */
163 #define LSR             5       /*  Line Status               */
164 static void serial_putchar(int ch)
165 {
166         unsigned timeout = 0xffff;
167
168         while ((inb(early_serial_base + LSR) & XMTRDY) == 0 && --timeout)
169                 cpu_relax();
170
171         outb(ch, early_serial_base + TXR);
172 }
173
174 void __putstr(const char *s)
175 {
176         int x, y, pos;
177         char c;
178
179         if (early_serial_base) {
180                 const char *str = s;
181                 while (*str) {
182                         if (*str == '\n')
183                                 serial_putchar('\r');
184                         serial_putchar(*str++);
185                 }
186         }
187
188         if (real_mode->screen_info.orig_video_mode == 0 &&
189             lines == 0 && cols == 0)
190                 return;
191
192         x = real_mode->screen_info.orig_x;
193         y = real_mode->screen_info.orig_y;
194
195         while ((c = *s++) != '\0') {
196                 if (c == '\n') {
197                         x = 0;
198                         if (++y >= lines) {
199                                 scroll();
200                                 y--;
201                         }
202                 } else {
203                         vidmem[(x + cols * y) * 2] = c;
204                         if (++x >= cols) {
205                                 x = 0;
206                                 if (++y >= lines) {
207                                         scroll();
208                                         y--;
209                                 }
210                         }
211                 }
212         }
213
214         real_mode->screen_info.orig_x = x;
215         real_mode->screen_info.orig_y = y;
216
217         pos = (x + cols * y) * 2;       /* Update cursor position */
218         outb(14, vidport);
219         outb(0xff & (pos >> 9), vidport+1);
220         outb(15, vidport);
221         outb(0xff & (pos >> 1), vidport+1);
222 }
223
224 void __puthex(unsigned long value)
225 {
226         char alpha[2] = "0";
227         int bits;
228
229         for (bits = sizeof(value) * 8 - 4; bits >= 0; bits -= 4) {
230                 unsigned long digit = (value >> bits) & 0xf;
231
232                 if (digit < 0xA)
233                         alpha[0] = '0' + digit;
234                 else
235                         alpha[0] = 'a' + (digit - 0xA);
236
237                 __putstr(alpha);
238         }
239 }
240
241 static void error(char *x)
242 {
243         error_putstr("\n\n");
244         error_putstr(x);
245         error_putstr("\n\n -- System halted");
246
247         while (1)
248                 asm("hlt");
249 }
250
251 #if CONFIG_X86_NEED_RELOCS
252 static void handle_relocations(void *output, unsigned long output_len)
253 {
254         int *reloc;
255         unsigned long delta, map, ptr;
256         unsigned long min_addr = (unsigned long)output;
257         unsigned long max_addr = min_addr + output_len;
258
259         /*
260          * Calculate the delta between where vmlinux was linked to load
261          * and where it was actually loaded.
262          */
263         delta = min_addr - LOAD_PHYSICAL_ADDR;
264         if (!delta) {
265                 debug_putstr("No relocation needed... ");
266                 return;
267         }
268         debug_putstr("Performing relocations... ");
269
270         /*
271          * The kernel contains a table of relocation addresses. Those
272          * addresses have the final load address of the kernel in virtual
273          * memory. We are currently working in the self map. So we need to
274          * create an adjustment for kernel memory addresses to the self map.
275          * This will involve subtracting out the base address of the kernel.
276          */
277         map = delta - __START_KERNEL_map;
278
279         /*
280          * Process relocations: 32 bit relocations first then 64 bit after.
281          * Three sets of binary relocations are added to the end of the kernel
282          * before compression. Each relocation table entry is the kernel
283          * address of the location which needs to be updated stored as a
284          * 32-bit value which is sign extended to 64 bits.
285          *
286          * Format is:
287          *
288          * kernel bits...
289          * 0 - zero terminator for 64 bit relocations
290          * 64 bit relocation repeated
291          * 0 - zero terminator for inverse 32 bit relocations
292          * 32 bit inverse relocation repeated
293          * 0 - zero terminator for 32 bit relocations
294          * 32 bit relocation repeated
295          *
296          * So we work backwards from the end of the decompressed image.
297          */
298         for (reloc = output + output_len - sizeof(*reloc); *reloc; reloc--) {
299                 int extended = *reloc;
300                 extended += map;
301
302                 ptr = (unsigned long)extended;
303                 if (ptr < min_addr || ptr > max_addr)
304                         error("32-bit relocation outside of kernel!\n");
305
306                 *(uint32_t *)ptr += delta;
307         }
308 #ifdef CONFIG_X86_64
309         while (*--reloc) {
310                 long extended = *reloc;
311                 extended += map;
312
313                 ptr = (unsigned long)extended;
314                 if (ptr < min_addr || ptr > max_addr)
315                         error("inverse 32-bit relocation outside of kernel!\n");
316
317                 *(int32_t *)ptr -= delta;
318         }
319         for (reloc--; *reloc; reloc--) {
320                 long extended = *reloc;
321                 extended += map;
322
323                 ptr = (unsigned long)extended;
324                 if (ptr < min_addr || ptr > max_addr)
325                         error("64-bit relocation outside of kernel!\n");
326
327                 *(uint64_t *)ptr += delta;
328         }
329 #endif
330 }
331 #else
332 static inline void handle_relocations(void *output, unsigned long output_len)
333 { }
334 #endif
335
336 static void parse_elf(void *output)
337 {
338 #ifdef CONFIG_X86_64
339         Elf64_Ehdr ehdr;
340         Elf64_Phdr *phdrs, *phdr;
341 #else
342         Elf32_Ehdr ehdr;
343         Elf32_Phdr *phdrs, *phdr;
344 #endif
345         void *dest;
346         int i;
347
348         memcpy(&ehdr, output, sizeof(ehdr));
349         if (ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
350            ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
351            ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
352            ehdr.e_ident[EI_MAG3] != ELFMAG3) {
353                 error("Kernel is not a valid ELF file");
354                 return;
355         }
356
357         debug_putstr("Parsing ELF... ");
358
359         phdrs = malloc(sizeof(*phdrs) * ehdr.e_phnum);
360         if (!phdrs)
361                 error("Failed to allocate space for phdrs");
362
363         memcpy(phdrs, output + ehdr.e_phoff, sizeof(*phdrs) * ehdr.e_phnum);
364
365         for (i = 0; i < ehdr.e_phnum; i++) {
366                 phdr = &phdrs[i];
367
368                 switch (phdr->p_type) {
369                 case PT_LOAD:
370 #ifdef CONFIG_X86_64
371                         if ((phdr->p_align % 0x200000) != 0)
372                                 error("Alignment of LOAD segment isn't multiple of 2MB");
373 #endif
374 #ifdef CONFIG_RELOCATABLE
375                         dest = output;
376                         dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR);
377 #else
378                         dest = (void *)(phdr->p_paddr);
379 #endif
380                         memcpy(dest,
381                                output + phdr->p_offset,
382                                phdr->p_filesz);
383                         break;
384                 default: /* Ignore other PT_* */ break;
385                 }
386         }
387
388         free(phdrs);
389 }
390
391 asmlinkage __visible void *decompress_kernel(void *rmode, memptr heap,
392                                   unsigned char *input_data,
393                                   unsigned long input_len,
394                                   unsigned char *output,
395                                   unsigned long output_len,
396                                   unsigned long run_size)
397 {
398         unsigned char *output_orig = output;
399
400         real_mode = rmode;
401
402         /* Clear it for solely in-kernel use */
403         real_mode->hdr.loadflags &= ~KASLR_FLAG;
404
405         sanitize_boot_params(real_mode);
406
407         if (real_mode->screen_info.orig_video_mode == 7) {
408                 vidmem = (char *) 0xb0000;
409                 vidport = 0x3b4;
410         } else {
411                 vidmem = (char *) 0xb8000;
412                 vidport = 0x3d4;
413         }
414
415         lines = real_mode->screen_info.orig_video_lines;
416         cols = real_mode->screen_info.orig_video_cols;
417
418         console_init();
419         debug_putstr("early console in decompress_kernel\n");
420
421         free_mem_ptr     = heap;        /* Heap */
422         free_mem_end_ptr = heap + BOOT_HEAP_SIZE;
423
424         /* Report initial kernel position details. */
425         debug_putaddr(input_data);
426         debug_putaddr(input_len);
427         debug_putaddr(output);
428         debug_putaddr(output_len);
429         debug_putaddr(run_size);
430
431         /*
432          * The memory hole needed for the kernel is the larger of either
433          * the entire decompressed kernel plus relocation table, or the
434          * entire decompressed kernel plus .bss and .brk sections.
435          */
436         output = choose_kernel_location(real_mode, input_data, input_len, output,
437                                         output_len > run_size ? output_len
438                                                               : run_size);
439
440         /* Validate memory location choices. */
441         if ((unsigned long)output & (MIN_KERNEL_ALIGN - 1))
442                 error("Destination address inappropriately aligned");
443 #ifdef CONFIG_X86_64
444         if (heap > 0x3fffffffffffUL)
445                 error("Destination address too large");
446 #else
447         if (heap > ((-__PAGE_OFFSET-(128<<20)-1) & 0x7fffffff))
448                 error("Destination address too large");
449 #endif
450 #ifndef CONFIG_RELOCATABLE
451         if ((unsigned long)output != LOAD_PHYSICAL_ADDR)
452                 error("Wrong destination address");
453 #endif
454
455         debug_putstr("\nDecompressing Linux... ");
456         __decompress(input_data, input_len, NULL, NULL, output, output_len,
457                         NULL, error);
458         parse_elf(output);
459         /*
460          * 32-bit always performs relocations. 64-bit relocations are only
461          * needed if kASLR has chosen a different load address.
462          */
463         if (!IS_ENABLED(CONFIG_X86_64) || output != output_orig)
464                 handle_relocations(output, output_len);
465         debug_putstr("done.\nBooting the kernel.\n");
466         return output;
467 }