1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/init.h>
3 #include <linux/async.h>
5 #include <linux/slab.h>
6 #include <linux/types.h>
7 #include <linux/fcntl.h>
8 #include <linux/delay.h>
9 #include <linux/string.h>
10 #include <linux/dirent.h>
11 #include <linux/syscalls.h>
12 #include <linux/utime.h>
13 #include <linux/file.h>
14 #include <linux/memblock.h>
16 #include <linux/namei.h>
17 #include <linux/init_syscalls.h>
18 #include <linux/umh.h>
20 static ssize_t __init xwrite(struct file *file, const char *p, size_t count,
25 /* sys_write only can write MAX_RW_COUNT aka 2G-4K bytes at most */
27 ssize_t rv = kernel_write(file, p, count, pos);
30 if (rv == -EINTR || rv == -EAGAIN)
32 return out ? out : rv;
44 static __initdata char *message;
45 static void __init error(char *x)
51 static void panic_show_mem(const char *fmt, ...)
63 #define N_ALIGN(len) ((((len) + 1) & ~3) + 2)
65 static __initdata struct hash {
66 int ino, minor, major;
69 char name[N_ALIGN(PATH_MAX)];
72 static inline int hash(int major, int minor, int ino)
74 unsigned long tmp = ino + minor + (major << 3);
79 static char __init *find_link(int major, int minor, int ino,
80 umode_t mode, char *name)
83 for (p = head + hash(major, minor, ino); *p; p = &(*p)->next) {
86 if ((*p)->minor != minor)
88 if ((*p)->major != major)
90 if (((*p)->mode ^ mode) & S_IFMT)
94 q = kmalloc(sizeof(struct hash), GFP_KERNEL);
96 panic_show_mem("can't allocate link hash entry");
101 strcpy(q->name, name);
107 static void __init free_hash(void)
110 for (p = head; p < head + 32; p++) {
119 static long __init do_utime(char *filename, time64_t mtime)
121 struct timespec64 t[2];
127 return init_utimes(filename, t);
130 static __initdata LIST_HEAD(dir_list);
132 struct list_head list;
137 static void __init dir_add(const char *name, time64_t mtime)
139 struct dir_entry *de = kmalloc(sizeof(struct dir_entry), GFP_KERNEL);
141 panic_show_mem("can't allocate dir_entry buffer");
142 INIT_LIST_HEAD(&de->list);
143 de->name = kstrdup(name, GFP_KERNEL);
145 list_add(&de->list, &dir_list);
148 static void __init dir_utime(void)
150 struct dir_entry *de, *tmp;
151 list_for_each_entry_safe(de, tmp, &dir_list, list) {
153 do_utime(de->name, de->mtime);
159 static __initdata time64_t mtime;
161 /* cpio header parsing */
163 static __initdata unsigned long ino, major, minor, nlink;
164 static __initdata umode_t mode;
165 static __initdata unsigned long body_len, name_len;
166 static __initdata uid_t uid;
167 static __initdata gid_t gid;
168 static __initdata unsigned rdev;
170 static void __init parse_header(char *s)
172 unsigned long parsed[12];
177 for (i = 0, s += 6; i < 12; i++, s += 8) {
179 parsed[i] = simple_strtoul(buf, NULL, 16);
186 mtime = parsed[5]; /* breaks in y2106 */
187 body_len = parsed[6];
190 rdev = new_encode_dev(MKDEV(parsed[9], parsed[10]));
191 name_len = parsed[11];
196 static __initdata enum state {
207 static __initdata char *victim;
208 static unsigned long byte_count __initdata;
209 static __initdata loff_t this_header, next_header;
211 static inline void __init eat(unsigned n)
218 static __initdata char *collected;
219 static long remains __initdata;
220 static __initdata char *collect;
222 static void __init read_into(char *buf, unsigned size, enum state next)
224 if (byte_count >= size) {
229 collect = collected = buf;
236 static __initdata char *header_buf, *symlink_buf, *name_buf;
238 static int __init do_start(void)
240 read_into(header_buf, 110, GotHeader);
244 static int __init do_collect(void)
246 unsigned long n = remains;
249 memcpy(collect, victim, n);
252 if ((remains -= n) != 0)
258 static int __init do_header(void)
260 if (memcmp(collected, "070707", 6)==0) {
261 error("incorrect cpio method used: use -H newc option");
264 if (memcmp(collected, "070701", 6)) {
265 error("no cpio magic");
268 parse_header(collected);
269 next_header = this_header + N_ALIGN(name_len) + body_len;
270 next_header = (next_header + 3) & ~3;
272 if (name_len <= 0 || name_len > PATH_MAX)
275 if (body_len > PATH_MAX)
277 collect = collected = symlink_buf;
278 remains = N_ALIGN(name_len) + body_len;
279 next_state = GotSymlink;
283 if (S_ISREG(mode) || !body_len)
284 read_into(name_buf, N_ALIGN(name_len), GotName);
288 static int __init do_skip(void)
290 if (this_header + byte_count < next_header) {
294 eat(next_header - this_header);
300 static int __init do_reset(void)
302 while (byte_count && *victim == '\0')
304 if (byte_count && (this_header & 3))
305 error("broken padding");
309 static void __init clean_path(char *path, umode_t fmode)
313 if (!init_stat(path, &st, AT_SYMLINK_NOFOLLOW) &&
314 (st.mode ^ fmode) & S_IFMT) {
315 if (S_ISDIR(st.mode))
322 static int __init maybe_link(void)
325 char *old = find_link(major, minor, ino, mode, collected);
327 clean_path(collected, 0);
328 return (init_link(old, collected) < 0) ? -1 : 1;
334 static __initdata struct file *wfile;
335 static __initdata loff_t wfile_pos;
337 static int __init do_name(void)
341 if (strcmp(collected, "TRAILER!!!") == 0) {
345 clean_path(collected, mode);
347 int ml = maybe_link();
349 int openflags = O_WRONLY|O_CREAT;
351 openflags |= O_TRUNC;
352 wfile = filp_open(collected, openflags, mode);
357 vfs_fchown(wfile, uid, gid);
358 vfs_fchmod(wfile, mode);
360 vfs_truncate(&wfile->f_path, body_len);
363 } else if (S_ISDIR(mode)) {
364 init_mkdir(collected, mode);
365 init_chown(collected, uid, gid, 0);
366 init_chmod(collected, mode);
367 dir_add(collected, mtime);
368 } else if (S_ISBLK(mode) || S_ISCHR(mode) ||
369 S_ISFIFO(mode) || S_ISSOCK(mode)) {
370 if (maybe_link() == 0) {
371 init_mknod(collected, mode, rdev);
372 init_chown(collected, uid, gid, 0);
373 init_chmod(collected, mode);
374 do_utime(collected, mtime);
380 static int __init do_copy(void)
382 if (byte_count >= body_len) {
383 struct timespec64 t[2] = { };
384 if (xwrite(wfile, victim, body_len, &wfile_pos) != body_len)
385 error("write error");
389 vfs_utimes(&wfile->f_path, t);
396 if (xwrite(wfile, victim, byte_count, &wfile_pos) != byte_count)
397 error("write error");
398 body_len -= byte_count;
404 static int __init do_symlink(void)
406 collected[N_ALIGN(name_len) + body_len] = '\0';
407 clean_path(collected, 0);
408 init_symlink(collected + N_ALIGN(name_len), collected);
409 init_chown(collected, uid, gid, AT_SYMLINK_NOFOLLOW);
410 do_utime(collected, mtime);
416 static __initdata int (*actions[])(void) = {
418 [Collect] = do_collect,
419 [GotHeader] = do_header,
422 [CopyFile] = do_copy,
423 [GotSymlink] = do_symlink,
427 static long __init write_buffer(char *buf, unsigned long len)
432 while (!actions[state]())
434 return len - byte_count;
437 static long __init flush_buffer(void *bufv, unsigned long len)
439 char *buf = (char *) bufv;
444 while ((written = write_buffer(buf, len)) < len && !message) {
445 char c = buf[written];
455 error("junk within compressed archive");
460 static unsigned long my_inptr; /* index of next byte to be processed in inbuf */
462 #include <linux/decompress/generic.h>
464 static char * __init unpack_to_rootfs(char *buf, unsigned long len)
467 decompress_fn decompress;
468 const char *compress_name;
469 static __initdata char msg_buf[64];
471 header_buf = kmalloc(110, GFP_KERNEL);
472 symlink_buf = kmalloc(PATH_MAX + N_ALIGN(PATH_MAX) + 1, GFP_KERNEL);
473 name_buf = kmalloc(N_ALIGN(PATH_MAX), GFP_KERNEL);
475 if (!header_buf || !symlink_buf || !name_buf)
476 panic_show_mem("can't allocate buffers");
481 while (!message && len) {
482 loff_t saved_offset = this_header;
483 if (*buf == '0' && !(this_header & 3)) {
485 written = write_buffer(buf, len);
497 decompress = decompress_method(buf, len, &compress_name);
498 pr_debug("Detected %s compressed data\n", compress_name);
500 int res = decompress(buf, len, NULL, flush_buffer, NULL,
503 error("decompressor failed");
504 } else if (compress_name) {
506 snprintf(msg_buf, sizeof msg_buf,
507 "compression method %s not configured",
512 error("invalid magic at start of compressed archive");
514 error("junk at the end of compressed archive");
515 this_header = saved_offset + my_inptr;
526 static int __initdata do_retain_initrd;
528 static int __init retain_initrd_param(char *str)
532 do_retain_initrd = 1;
535 __setup("retain_initrd", retain_initrd_param);
537 #ifdef CONFIG_ARCH_HAS_KEEPINITRD
538 static int __init keepinitrd_setup(char *__unused)
540 do_retain_initrd = 1;
543 __setup("keepinitrd", keepinitrd_setup);
546 static bool __initdata initramfs_async = true;
547 static int __init initramfs_async_setup(char *str)
549 strtobool(str, &initramfs_async);
552 __setup("initramfs_async=", initramfs_async_setup);
554 extern char __initramfs_start[];
555 extern unsigned long __initramfs_size;
556 #include <linux/initrd.h>
557 #include <linux/kexec.h>
559 void __init reserve_initrd_mem(void)
564 /* Ignore the virtul address computed during device tree parsing */
565 initrd_start = initrd_end = 0;
567 if (!phys_initrd_size)
570 * Round the memory region to page boundaries as per free_initrd_mem()
571 * This allows us to detect whether the pages overlapping the initrd
572 * are in use, but more importantly, reserves the entire set of pages
573 * as we don't want these pages allocated for other purposes.
575 start = round_down(phys_initrd_start, PAGE_SIZE);
576 size = phys_initrd_size + (phys_initrd_start - start);
577 size = round_up(size, PAGE_SIZE);
579 if (!memblock_is_region_memory(start, size)) {
580 pr_err("INITRD: 0x%08llx+0x%08lx is not a memory region",
585 if (memblock_is_region_reserved(start, size)) {
586 pr_err("INITRD: 0x%08llx+0x%08lx overlaps in-use memory region\n",
591 memblock_reserve(start, size);
592 /* Now convert initrd to virtual addresses */
593 initrd_start = (unsigned long)__va(phys_initrd_start);
594 initrd_end = initrd_start + phys_initrd_size;
595 initrd_below_start_ok = 1;
599 pr_cont(" - disabling initrd\n");
604 void __weak __init free_initrd_mem(unsigned long start, unsigned long end)
606 #ifdef CONFIG_ARCH_KEEP_MEMBLOCK
607 unsigned long aligned_start = ALIGN_DOWN(start, PAGE_SIZE);
608 unsigned long aligned_end = ALIGN(end, PAGE_SIZE);
610 memblock_free(__pa(aligned_start), aligned_end - aligned_start);
613 free_reserved_area((void *)start, (void *)end, POISON_FREE_INITMEM,
617 #ifdef CONFIG_KEXEC_CORE
618 static bool __init kexec_free_initrd(void)
620 unsigned long crashk_start = (unsigned long)__va(crashk_res.start);
621 unsigned long crashk_end = (unsigned long)__va(crashk_res.end);
624 * If the initrd region is overlapped with crashkernel reserved region,
625 * free only memory that is not part of crashkernel region.
627 if (initrd_start >= crashk_end || initrd_end <= crashk_start)
631 * Initialize initrd memory region since the kexec boot does not do.
633 memset((void *)initrd_start, 0, initrd_end - initrd_start);
634 if (initrd_start < crashk_start)
635 free_initrd_mem(initrd_start, crashk_start);
636 if (initrd_end > crashk_end)
637 free_initrd_mem(crashk_end, initrd_end);
641 static inline bool kexec_free_initrd(void)
645 #endif /* CONFIG_KEXEC_CORE */
647 #ifdef CONFIG_BLK_DEV_RAM
648 static void __init populate_initrd_image(char *err)
654 unpack_to_rootfs(__initramfs_start, __initramfs_size);
656 printk(KERN_INFO "rootfs image is not initramfs (%s); looks like an initrd\n",
658 file = filp_open("/initrd.image", O_WRONLY | O_CREAT, 0700);
662 written = xwrite(file, (char *)initrd_start, initrd_end - initrd_start,
664 if (written != initrd_end - initrd_start)
665 pr_err("/initrd.image: incomplete write (%zd != %ld)\n",
666 written, initrd_end - initrd_start);
669 #endif /* CONFIG_BLK_DEV_RAM */
671 static void __init do_populate_rootfs(void *unused, async_cookie_t cookie)
673 /* Load the built in initramfs */
674 char *err = unpack_to_rootfs(__initramfs_start, __initramfs_size);
676 panic_show_mem("%s", err); /* Failed to decompress INTERNAL initramfs */
678 if (!initrd_start || IS_ENABLED(CONFIG_INITRAMFS_FORCE))
681 if (IS_ENABLED(CONFIG_BLK_DEV_RAM))
682 printk(KERN_INFO "Trying to unpack rootfs image as initramfs...\n");
684 printk(KERN_INFO "Unpacking initramfs...\n");
686 err = unpack_to_rootfs((char *)initrd_start, initrd_end - initrd_start);
688 #ifdef CONFIG_BLK_DEV_RAM
689 populate_initrd_image(err);
691 printk(KERN_EMERG "Initramfs unpacking failed: %s\n", err);
697 * If the initrd region is overlapped with crashkernel reserved region,
698 * free only memory that is not part of crashkernel region.
700 if (!do_retain_initrd && initrd_start && !kexec_free_initrd())
701 free_initrd_mem(initrd_start, initrd_end);
705 flush_delayed_fput();
708 static ASYNC_DOMAIN_EXCLUSIVE(initramfs_domain);
709 static async_cookie_t initramfs_cookie;
711 void wait_for_initramfs(void)
713 if (!initramfs_cookie) {
715 * Something before rootfs_initcall wants to access
716 * the filesystem/initramfs. Probably a bug. Make a
717 * note, avoid deadlocking the machine, and let the
718 * caller's access fail as it used to.
720 pr_warn_once("wait_for_initramfs() called before rootfs_initcalls\n");
723 async_synchronize_cookie_domain(initramfs_cookie + 1, &initramfs_domain);
725 EXPORT_SYMBOL_GPL(wait_for_initramfs);
727 static int __init populate_rootfs(void)
729 initramfs_cookie = async_schedule_domain(do_populate_rootfs, NULL,
731 usermodehelper_enable();
732 if (!initramfs_async)
733 wait_for_initramfs();
736 rootfs_initcall(populate_rootfs);