xref: /openbmc/linux/arch/x86/boot/compressed/misc.c (revision 22246614)
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 /*
13  * we have to be careful, because no indirections are allowed here, and
14  * paravirt_ops is a kind of one. As it will only run in baremetal anyway,
15  * we just keep it from happening
16  */
17 #undef CONFIG_PARAVIRT
18 #ifdef CONFIG_X86_32
19 #define _ASM_DESC_H_ 1
20 #endif
21 
22 #ifdef CONFIG_X86_64
23 #define _LINUX_STRING_H_ 1
24 #define __LINUX_BITMAP_H 1
25 #endif
26 
27 #include <linux/linkage.h>
28 #include <linux/screen_info.h>
29 #include <linux/elf.h>
30 #include <asm/io.h>
31 #include <asm/page.h>
32 #include <asm/boot.h>
33 
34 /* WARNING!!
35  * This code is compiled with -fPIC and it is relocated dynamically
36  * at run time, but no relocation processing is performed.
37  * This means that it is not safe to place pointers in static structures.
38  */
39 
40 /*
41  * Getting to provable safe in place decompression is hard.
42  * Worst case behaviours need to be analyzed.
43  * Background information:
44  *
45  * The file layout is:
46  *    magic[2]
47  *    method[1]
48  *    flags[1]
49  *    timestamp[4]
50  *    extraflags[1]
51  *    os[1]
52  *    compressed data blocks[N]
53  *    crc[4] orig_len[4]
54  *
55  * resulting in 18 bytes of non compressed data overhead.
56  *
57  * Files divided into blocks
58  * 1 bit (last block flag)
59  * 2 bits (block type)
60  *
61  * 1 block occurs every 32K -1 bytes or when there 50% compression
62  * has been achieved. The smallest block type encoding is always used.
63  *
64  * stored:
65  *    32 bits length in bytes.
66  *
67  * fixed:
68  *    magic fixed tree.
69  *    symbols.
70  *
71  * dynamic:
72  *    dynamic tree encoding.
73  *    symbols.
74  *
75  *
76  * The buffer for decompression in place is the length of the
77  * uncompressed data, plus a small amount extra to keep the algorithm safe.
78  * The compressed data is placed at the end of the buffer.  The output
79  * pointer is placed at the start of the buffer and the input pointer
80  * is placed where the compressed data starts.  Problems will occur
81  * when the output pointer overruns the input pointer.
82  *
83  * The output pointer can only overrun the input pointer if the input
84  * pointer is moving faster than the output pointer.  A condition only
85  * triggered by data whose compressed form is larger than the uncompressed
86  * form.
87  *
88  * The worst case at the block level is a growth of the compressed data
89  * of 5 bytes per 32767 bytes.
90  *
91  * The worst case internal to a compressed block is very hard to figure.
92  * The worst case can at least be boundined by having one bit that represents
93  * 32764 bytes and then all of the rest of the bytes representing the very
94  * very last byte.
95  *
96  * All of which is enough to compute an amount of extra data that is required
97  * to be safe.  To avoid problems at the block level allocating 5 extra bytes
98  * per 32767 bytes of data is sufficient.  To avoind problems internal to a
99  * block adding an extra 32767 bytes (the worst case uncompressed block size)
100  * is sufficient, to ensure that in the worst case the decompressed data for
101  * block will stop the byte before the compressed data for a block begins.
102  * To avoid problems with the compressed data's meta information an extra 18
103  * bytes are needed.  Leading to the formula:
104  *
105  * extra_bytes = (uncompressed_size >> 12) + 32768 + 18 + decompressor_size.
106  *
107  * Adding 8 bytes per 32K is a bit excessive but much easier to calculate.
108  * Adding 32768 instead of 32767 just makes for round numbers.
109  * Adding the decompressor_size is necessary as it musht live after all
110  * of the data as well.  Last I measured the decompressor is about 14K.
111  * 10K of actual data and 4K of bss.
112  *
113  */
114 
115 /*
116  * gzip declarations
117  */
118 
119 #define OF(args)	args
120 #define STATIC		static
121 
122 #undef memset
123 #undef memcpy
124 #define memzero(s, n)	memset((s), 0, (n))
125 
126 typedef unsigned char	uch;
127 typedef unsigned short	ush;
128 typedef unsigned long	ulg;
129 
130 /*
131  * Window size must be at least 32k, and a power of two.
132  * We don't actually have a window just a huge output buffer,
133  * so we report a 2G window size, as that should always be
134  * larger than our output buffer:
135  */
136 #define WSIZE		0x80000000
137 
138 /* Input buffer: */
139 static unsigned char	*inbuf;
140 
141 /* Sliding window buffer (and final output buffer): */
142 static unsigned char	*window;
143 
144 /* Valid bytes in inbuf: */
145 static unsigned		insize;
146 
147 /* Index of next byte to be processed in inbuf: */
148 static unsigned		inptr;
149 
150 /* Bytes in output buffer: */
151 static unsigned		outcnt;
152 
153 /* gzip flag byte */
154 #define ASCII_FLAG	0x01 /* bit 0 set: file probably ASCII text */
155 #define CONTINUATION	0x02 /* bit 1 set: continuation of multi-part gz file */
156 #define EXTRA_FIELD	0x04 /* bit 2 set: extra field present */
157 #define ORIG_NAM	0x08 /* bit 3 set: original file name present */
158 #define COMMENT		0x10 /* bit 4 set: file comment present */
159 #define ENCRYPTED	0x20 /* bit 5 set: file is encrypted */
160 #define RESERVED	0xC0 /* bit 6, 7:  reserved */
161 
162 #define get_byte()	(inptr < insize ? inbuf[inptr++] : fill_inbuf())
163 
164 /* Diagnostic functions */
165 #ifdef DEBUG
166 #  define Assert(cond, msg) do { if (!(cond)) error(msg); } while (0)
167 #  define Trace(x)	do { fprintf x; } while (0)
168 #  define Tracev(x)	do { if (verbose) fprintf x ; } while (0)
169 #  define Tracevv(x)	do { if (verbose > 1) fprintf x ; } while (0)
170 #  define Tracec(c, x)	do { if (verbose && (c)) fprintf x ; } while (0)
171 #  define Tracecv(c, x)	do { if (verbose > 1 && (c)) fprintf x ; } while (0)
172 #else
173 #  define Assert(cond, msg)
174 #  define Trace(x)
175 #  define Tracev(x)
176 #  define Tracevv(x)
177 #  define Tracec(c, x)
178 #  define Tracecv(c, x)
179 #endif
180 
181 static int  fill_inbuf(void);
182 static void flush_window(void);
183 static void error(char *m);
184 static void gzip_mark(void **);
185 static void gzip_release(void **);
186 
187 /*
188  * This is set up by the setup-routine at boot-time
189  */
190 static unsigned char *real_mode; /* Pointer to real-mode data */
191 
192 #define RM_EXT_MEM_K   (*(unsigned short *)(real_mode + 0x2))
193 #ifndef STANDARD_MEMORY_BIOS_CALL
194 #define RM_ALT_MEM_K   (*(unsigned long *)(real_mode + 0x1e0))
195 #endif
196 #define RM_SCREEN_INFO (*(struct screen_info *)(real_mode+0))
197 
198 extern unsigned char input_data[];
199 extern int input_len;
200 
201 static long bytes_out;
202 
203 static void *malloc(int size);
204 static void free(void *where);
205 
206 static void *memset(void *s, int c, unsigned n);
207 static void *memcpy(void *dest, const void *src, unsigned n);
208 
209 static void putstr(const char *);
210 
211 #ifdef CONFIG_X86_64
212 #define memptr long
213 #else
214 #define memptr unsigned
215 #endif
216 
217 static memptr free_mem_ptr;
218 static memptr free_mem_end_ptr;
219 
220 static char *vidmem;
221 static int vidport;
222 static int lines, cols;
223 
224 #ifdef CONFIG_X86_NUMAQ
225 void *xquad_portio;
226 #endif
227 
228 #include "../../../../lib/inflate.c"
229 
230 static void *malloc(int size)
231 {
232 	void *p;
233 
234 	if (size < 0)
235 		error("Malloc error");
236 	if (free_mem_ptr <= 0)
237 		error("Memory error");
238 
239 	free_mem_ptr = (free_mem_ptr + 3) & ~3;	/* Align */
240 
241 	p = (void *)free_mem_ptr;
242 	free_mem_ptr += size;
243 
244 	if (free_mem_ptr >= free_mem_end_ptr)
245 		error("Out of memory");
246 
247 	return p;
248 }
249 
250 static void free(void *where)
251 {	/* Don't care */
252 }
253 
254 static void gzip_mark(void **ptr)
255 {
256 	*ptr = (void *) free_mem_ptr;
257 }
258 
259 static void gzip_release(void **ptr)
260 {
261 	free_mem_ptr = (memptr) *ptr;
262 }
263 
264 static void scroll(void)
265 {
266 	int i;
267 
268 	memcpy(vidmem, vidmem + cols * 2, (lines - 1) * cols * 2);
269 	for (i = (lines - 1) * cols * 2; i < lines * cols * 2; i += 2)
270 		vidmem[i] = ' ';
271 }
272 
273 static void putstr(const char *s)
274 {
275 	int x, y, pos;
276 	char c;
277 
278 #ifdef CONFIG_X86_32
279 	if (RM_SCREEN_INFO.orig_video_mode == 0 && lines == 0 && cols == 0)
280 		return;
281 #endif
282 
283 	x = RM_SCREEN_INFO.orig_x;
284 	y = RM_SCREEN_INFO.orig_y;
285 
286 	while ((c = *s++) != '\0') {
287 		if (c == '\n') {
288 			x = 0;
289 			if (++y >= lines) {
290 				scroll();
291 				y--;
292 			}
293 		} else {
294 			vidmem [(x + cols * y) * 2] = c;
295 			if (++x >= cols) {
296 				x = 0;
297 				if (++y >= lines) {
298 					scroll();
299 					y--;
300 				}
301 			}
302 		}
303 	}
304 
305 	RM_SCREEN_INFO.orig_x = x;
306 	RM_SCREEN_INFO.orig_y = y;
307 
308 	pos = (x + cols * y) * 2;	/* Update cursor position */
309 	outb(14, vidport);
310 	outb(0xff & (pos >> 9), vidport+1);
311 	outb(15, vidport);
312 	outb(0xff & (pos >> 1), vidport+1);
313 }
314 
315 static void *memset(void *s, int c, unsigned n)
316 {
317 	int i;
318 	char *ss = s;
319 
320 	for (i = 0; i < n; i++) ss[i] = c;
321 	return s;
322 }
323 
324 static void *memcpy(void *dest, const void *src, unsigned n)
325 {
326 	int i;
327 	const char *s = src;
328 	char *d = dest;
329 
330 	for (i = 0; i < n; i++) d[i] = s[i];
331 	return dest;
332 }
333 
334 /* ===========================================================================
335  * Fill the input buffer. This is called only when the buffer is empty
336  * and at least one byte is really needed.
337  */
338 static int fill_inbuf(void)
339 {
340 	error("ran out of input data");
341 	return 0;
342 }
343 
344 /* ===========================================================================
345  * Write the output window window[0..outcnt-1] and update crc and bytes_out.
346  * (Used for the decompressed data only.)
347  */
348 static void flush_window(void)
349 {
350 	/* With my window equal to my output buffer
351 	 * I only need to compute the crc here.
352 	 */
353 	unsigned long c = crc;         /* temporary variable */
354 	unsigned n;
355 	unsigned char *in, ch;
356 
357 	in = window;
358 	for (n = 0; n < outcnt; n++) {
359 		ch = *in++;
360 		c = crc_32_tab[((int)c ^ ch) & 0xff] ^ (c >> 8);
361 	}
362 	crc = c;
363 	bytes_out += (unsigned long)outcnt;
364 	outcnt = 0;
365 }
366 
367 static void error(char *x)
368 {
369 	putstr("\n\n");
370 	putstr(x);
371 	putstr("\n\n -- System halted");
372 
373 	while (1)
374 		asm("hlt");
375 }
376 
377 static void parse_elf(void *output)
378 {
379 #ifdef CONFIG_X86_64
380 	Elf64_Ehdr ehdr;
381 	Elf64_Phdr *phdrs, *phdr;
382 #else
383 	Elf32_Ehdr ehdr;
384 	Elf32_Phdr *phdrs, *phdr;
385 #endif
386 	void *dest;
387 	int i;
388 
389 	memcpy(&ehdr, output, sizeof(ehdr));
390 	if (ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
391 	   ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
392 	   ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
393 	   ehdr.e_ident[EI_MAG3] != ELFMAG3) {
394 		error("Kernel is not a valid ELF file");
395 		return;
396 	}
397 
398 	putstr("Parsing ELF... ");
399 
400 	phdrs = malloc(sizeof(*phdrs) * ehdr.e_phnum);
401 	if (!phdrs)
402 		error("Failed to allocate space for phdrs");
403 
404 	memcpy(phdrs, output + ehdr.e_phoff, sizeof(*phdrs) * ehdr.e_phnum);
405 
406 	for (i = 0; i < ehdr.e_phnum; i++) {
407 		phdr = &phdrs[i];
408 
409 		switch (phdr->p_type) {
410 		case PT_LOAD:
411 #ifdef CONFIG_RELOCATABLE
412 			dest = output;
413 			dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR);
414 #else
415 			dest = (void *)(phdr->p_paddr);
416 #endif
417 			memcpy(dest,
418 			       output + phdr->p_offset,
419 			       phdr->p_filesz);
420 			break;
421 		default: /* Ignore other PT_* */ break;
422 		}
423 	}
424 }
425 
426 asmlinkage void decompress_kernel(void *rmode, memptr heap,
427 				  unsigned char *input_data,
428 				  unsigned long input_len,
429 				  unsigned char *output)
430 {
431 	real_mode = rmode;
432 
433 	if (RM_SCREEN_INFO.orig_video_mode == 7) {
434 		vidmem = (char *) 0xb0000;
435 		vidport = 0x3b4;
436 	} else {
437 		vidmem = (char *) 0xb8000;
438 		vidport = 0x3d4;
439 	}
440 
441 	lines = RM_SCREEN_INFO.orig_video_lines;
442 	cols = RM_SCREEN_INFO.orig_video_cols;
443 
444 	window = output;		/* Output buffer (Normally at 1M) */
445 	free_mem_ptr     = heap;	/* Heap */
446 	free_mem_end_ptr = heap + BOOT_HEAP_SIZE;
447 	inbuf  = input_data;		/* Input buffer */
448 	insize = input_len;
449 	inptr  = 0;
450 
451 #ifdef CONFIG_X86_64
452 	if ((unsigned long)output & (__KERNEL_ALIGN - 1))
453 		error("Destination address not 2M aligned");
454 	if ((unsigned long)output >= 0xffffffffffUL)
455 		error("Destination address too large");
456 #else
457 	if ((u32)output & (CONFIG_PHYSICAL_ALIGN - 1))
458 		error("Destination address not CONFIG_PHYSICAL_ALIGN aligned");
459 	if (heap > ((-__PAGE_OFFSET-(512<<20)-1) & 0x7fffffff))
460 		error("Destination address too large");
461 #ifndef CONFIG_RELOCATABLE
462 	if ((u32)output != LOAD_PHYSICAL_ADDR)
463 		error("Wrong destination address");
464 #endif
465 #endif
466 
467 	makecrc();
468 	putstr("\nDecompressing Linux... ");
469 	gunzip();
470 	parse_elf(output);
471 	putstr("done.\nBooting the kernel.\n");
472 	return;
473 }
474