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 __initdata bool csum_present;
21 static __initdata u32 io_csum;
23 static ssize_t __init xwrite(struct file *file, const unsigned char *p,
24 size_t count, loff_t *pos)
28 /* sys_write only can write MAX_RW_COUNT aka 2G-4K bytes at most */
30 ssize_t rv = kernel_write(file, p, count, pos);
33 if (rv == -EINTR || rv == -EAGAIN)
35 return out ? out : rv;
42 for (i = 0; i < rv; i++)
54 static __initdata char *message;
55 static void __init error(char *x)
61 static void panic_show_mem(const char *fmt, ...)
73 #define N_ALIGN(len) ((((len) + 1) & ~3) + 2)
75 static __initdata struct hash {
76 int ino, minor, major;
79 char name[N_ALIGN(PATH_MAX)];
82 static inline int hash(int major, int minor, int ino)
84 unsigned long tmp = ino + minor + (major << 3);
89 static char __init *find_link(int major, int minor, int ino,
90 umode_t mode, char *name)
93 for (p = head + hash(major, minor, ino); *p; p = &(*p)->next) {
96 if ((*p)->minor != minor)
98 if ((*p)->major != major)
100 if (((*p)->mode ^ mode) & S_IFMT)
104 q = kmalloc(sizeof(struct hash), GFP_KERNEL);
106 panic_show_mem("can't allocate link hash entry");
111 strcpy(q->name, name);
117 static void __init free_hash(void)
120 for (p = head; p < head + 32; p++) {
129 #ifdef CONFIG_INITRAMFS_PRESERVE_MTIME
130 static void __init do_utime(char *filename, time64_t mtime)
132 struct timespec64 t[2] = { { .tv_sec = mtime }, { .tv_sec = mtime } };
133 init_utimes(filename, t);
136 static void __init do_utime_path(const struct path *path, time64_t mtime)
138 struct timespec64 t[2] = { { .tv_sec = mtime }, { .tv_sec = mtime } };
142 static __initdata LIST_HEAD(dir_list);
144 struct list_head list;
149 static void __init dir_add(const char *name, time64_t mtime)
151 size_t nlen = strlen(name) + 1;
152 struct dir_entry *de;
154 de = kmalloc(sizeof(struct dir_entry) + nlen, GFP_KERNEL);
156 panic_show_mem("can't allocate dir_entry buffer");
157 INIT_LIST_HEAD(&de->list);
158 strscpy(de->name, name, nlen);
160 list_add(&de->list, &dir_list);
163 static void __init dir_utime(void)
165 struct dir_entry *de, *tmp;
166 list_for_each_entry_safe(de, tmp, &dir_list, list) {
168 do_utime(de->name, de->mtime);
173 static void __init do_utime(char *filename, time64_t mtime) {}
174 static void __init do_utime_path(const struct path *path, time64_t mtime) {}
175 static void __init dir_add(const char *name, time64_t mtime) {}
176 static void __init dir_utime(void) {}
179 static __initdata time64_t mtime;
181 /* cpio header parsing */
183 static __initdata unsigned long ino, major, minor, nlink;
184 static __initdata umode_t mode;
185 static __initdata unsigned long body_len, name_len;
186 static __initdata uid_t uid;
187 static __initdata gid_t gid;
188 static __initdata unsigned rdev;
189 static __initdata u32 hdr_csum;
191 static void __init parse_header(char *s)
193 unsigned long parsed[13];
198 for (i = 0, s += 6; i < 13; i++, s += 8) {
200 parsed[i] = simple_strtoul(buf, NULL, 16);
207 mtime = parsed[5]; /* breaks in y2106 */
208 body_len = parsed[6];
211 rdev = new_encode_dev(MKDEV(parsed[9], parsed[10]));
212 name_len = parsed[11];
213 hdr_csum = parsed[12];
218 static __initdata enum state {
229 static __initdata char *victim;
230 static unsigned long byte_count __initdata;
231 static __initdata loff_t this_header, next_header;
233 static inline void __init eat(unsigned n)
240 static __initdata char *collected;
241 static long remains __initdata;
242 static __initdata char *collect;
244 static void __init read_into(char *buf, unsigned size, enum state next)
246 if (byte_count >= size) {
251 collect = collected = buf;
258 static __initdata char *header_buf, *symlink_buf, *name_buf;
260 static int __init do_start(void)
262 read_into(header_buf, 110, GotHeader);
266 static int __init do_collect(void)
268 unsigned long n = remains;
271 memcpy(collect, victim, n);
274 if ((remains -= n) != 0)
280 static int __init do_header(void)
282 if (!memcmp(collected, "070701", 6)) {
283 csum_present = false;
284 } else if (!memcmp(collected, "070702", 6)) {
287 if (memcmp(collected, "070707", 6) == 0)
288 error("incorrect cpio method used: use -H newc option");
290 error("no cpio magic");
293 parse_header(collected);
294 next_header = this_header + N_ALIGN(name_len) + body_len;
295 next_header = (next_header + 3) & ~3;
297 if (name_len <= 0 || name_len > PATH_MAX)
300 if (body_len > PATH_MAX)
302 collect = collected = symlink_buf;
303 remains = N_ALIGN(name_len) + body_len;
304 next_state = GotSymlink;
308 if (S_ISREG(mode) || !body_len)
309 read_into(name_buf, N_ALIGN(name_len), GotName);
313 static int __init do_skip(void)
315 if (this_header + byte_count < next_header) {
319 eat(next_header - this_header);
325 static int __init do_reset(void)
327 while (byte_count && *victim == '\0')
329 if (byte_count && (this_header & 3))
330 error("broken padding");
334 static void __init clean_path(char *path, umode_t fmode)
338 if (!init_stat(path, &st, AT_SYMLINK_NOFOLLOW) &&
339 (st.mode ^ fmode) & S_IFMT) {
340 if (S_ISDIR(st.mode))
347 static int __init maybe_link(void)
350 char *old = find_link(major, minor, ino, mode, collected);
352 clean_path(collected, 0);
353 return (init_link(old, collected) < 0) ? -1 : 1;
359 static __initdata struct file *wfile;
360 static __initdata loff_t wfile_pos;
362 static int __init do_name(void)
366 if (strcmp(collected, "TRAILER!!!") == 0) {
370 clean_path(collected, mode);
372 int ml = maybe_link();
374 int openflags = O_WRONLY|O_CREAT;
376 openflags |= O_TRUNC;
377 wfile = filp_open(collected, openflags, mode);
383 vfs_fchown(wfile, uid, gid);
384 vfs_fchmod(wfile, mode);
386 vfs_truncate(&wfile->f_path, body_len);
389 } else if (S_ISDIR(mode)) {
390 init_mkdir(collected, mode);
391 init_chown(collected, uid, gid, 0);
392 init_chmod(collected, mode);
393 dir_add(collected, mtime);
394 } else if (S_ISBLK(mode) || S_ISCHR(mode) ||
395 S_ISFIFO(mode) || S_ISSOCK(mode)) {
396 if (maybe_link() == 0) {
397 init_mknod(collected, mode, rdev);
398 init_chown(collected, uid, gid, 0);
399 init_chmod(collected, mode);
400 do_utime(collected, mtime);
406 static int __init do_copy(void)
408 if (byte_count >= body_len) {
409 if (xwrite(wfile, victim, body_len, &wfile_pos) != body_len)
410 error("write error");
412 do_utime_path(&wfile->f_path, mtime);
414 if (csum_present && io_csum != hdr_csum)
415 error("bad data checksum");
420 if (xwrite(wfile, victim, byte_count, &wfile_pos) != byte_count)
421 error("write error");
422 body_len -= byte_count;
428 static int __init do_symlink(void)
430 collected[N_ALIGN(name_len) + body_len] = '\0';
431 clean_path(collected, 0);
432 init_symlink(collected + N_ALIGN(name_len), collected);
433 init_chown(collected, uid, gid, AT_SYMLINK_NOFOLLOW);
434 do_utime(collected, mtime);
440 static __initdata int (*actions[])(void) = {
442 [Collect] = do_collect,
443 [GotHeader] = do_header,
446 [CopyFile] = do_copy,
447 [GotSymlink] = do_symlink,
451 static long __init write_buffer(char *buf, unsigned long len)
456 while (!actions[state]())
458 return len - byte_count;
461 static long __init flush_buffer(void *bufv, unsigned long len)
463 char *buf = (char *) bufv;
468 while ((written = write_buffer(buf, len)) < len && !message) {
469 char c = buf[written];
479 error("junk within compressed archive");
484 static unsigned long my_inptr; /* index of next byte to be processed in inbuf */
486 #include <linux/decompress/generic.h>
488 static char * __init unpack_to_rootfs(char *buf, unsigned long len)
491 decompress_fn decompress;
492 const char *compress_name;
493 static __initdata char msg_buf[64];
495 header_buf = kmalloc(110, GFP_KERNEL);
496 symlink_buf = kmalloc(PATH_MAX + N_ALIGN(PATH_MAX) + 1, GFP_KERNEL);
497 name_buf = kmalloc(N_ALIGN(PATH_MAX), GFP_KERNEL);
499 if (!header_buf || !symlink_buf || !name_buf)
500 panic_show_mem("can't allocate buffers");
505 while (!message && len) {
506 loff_t saved_offset = this_header;
507 if (*buf == '0' && !(this_header & 3)) {
509 written = write_buffer(buf, len);
521 decompress = decompress_method(buf, len, &compress_name);
522 pr_debug("Detected %s compressed data\n", compress_name);
524 int res = decompress(buf, len, NULL, flush_buffer, NULL,
527 error("decompressor failed");
528 } else if (compress_name) {
530 snprintf(msg_buf, sizeof msg_buf,
531 "compression method %s not configured",
536 error("invalid magic at start of compressed archive");
538 error("junk at the end of compressed archive");
539 this_header = saved_offset + my_inptr;
550 static int __initdata do_retain_initrd;
552 static int __init retain_initrd_param(char *str)
556 do_retain_initrd = 1;
559 __setup("retain_initrd", retain_initrd_param);
561 #ifdef CONFIG_ARCH_HAS_KEEPINITRD
562 static int __init keepinitrd_setup(char *__unused)
564 do_retain_initrd = 1;
567 __setup("keepinitrd", keepinitrd_setup);
570 static bool __initdata initramfs_async = true;
571 static int __init initramfs_async_setup(char *str)
573 strtobool(str, &initramfs_async);
576 __setup("initramfs_async=", initramfs_async_setup);
578 extern char __initramfs_start[];
579 extern unsigned long __initramfs_size;
580 #include <linux/initrd.h>
581 #include <linux/kexec.h>
583 void __init reserve_initrd_mem(void)
588 /* Ignore the virtul address computed during device tree parsing */
589 initrd_start = initrd_end = 0;
591 if (!phys_initrd_size)
594 * Round the memory region to page boundaries as per free_initrd_mem()
595 * This allows us to detect whether the pages overlapping the initrd
596 * are in use, but more importantly, reserves the entire set of pages
597 * as we don't want these pages allocated for other purposes.
599 start = round_down(phys_initrd_start, PAGE_SIZE);
600 size = phys_initrd_size + (phys_initrd_start - start);
601 size = round_up(size, PAGE_SIZE);
603 if (!memblock_is_region_memory(start, size)) {
604 pr_err("INITRD: 0x%08llx+0x%08lx is not a memory region",
609 if (memblock_is_region_reserved(start, size)) {
610 pr_err("INITRD: 0x%08llx+0x%08lx overlaps in-use memory region\n",
615 memblock_reserve(start, size);
616 /* Now convert initrd to virtual addresses */
617 initrd_start = (unsigned long)__va(phys_initrd_start);
618 initrd_end = initrd_start + phys_initrd_size;
619 initrd_below_start_ok = 1;
623 pr_cont(" - disabling initrd\n");
628 void __weak __init free_initrd_mem(unsigned long start, unsigned long end)
630 #ifdef CONFIG_ARCH_KEEP_MEMBLOCK
631 unsigned long aligned_start = ALIGN_DOWN(start, PAGE_SIZE);
632 unsigned long aligned_end = ALIGN(end, PAGE_SIZE);
634 memblock_free((void *)aligned_start, aligned_end - aligned_start);
637 free_reserved_area((void *)start, (void *)end, POISON_FREE_INITMEM,
641 #ifdef CONFIG_KEXEC_CORE
642 static bool __init kexec_free_initrd(void)
644 unsigned long crashk_start = (unsigned long)__va(crashk_res.start);
645 unsigned long crashk_end = (unsigned long)__va(crashk_res.end);
648 * If the initrd region is overlapped with crashkernel reserved region,
649 * free only memory that is not part of crashkernel region.
651 if (initrd_start >= crashk_end || initrd_end <= crashk_start)
655 * Initialize initrd memory region since the kexec boot does not do.
657 memset((void *)initrd_start, 0, initrd_end - initrd_start);
658 if (initrd_start < crashk_start)
659 free_initrd_mem(initrd_start, crashk_start);
660 if (initrd_end > crashk_end)
661 free_initrd_mem(crashk_end, initrd_end);
665 static inline bool kexec_free_initrd(void)
669 #endif /* CONFIG_KEXEC_CORE */
671 #ifdef CONFIG_BLK_DEV_RAM
672 static void __init populate_initrd_image(char *err)
678 unpack_to_rootfs(__initramfs_start, __initramfs_size);
680 printk(KERN_INFO "rootfs image is not initramfs (%s); looks like an initrd\n",
682 file = filp_open("/initrd.image", O_WRONLY | O_CREAT, 0700);
686 written = xwrite(file, (char *)initrd_start, initrd_end - initrd_start,
688 if (written != initrd_end - initrd_start)
689 pr_err("/initrd.image: incomplete write (%zd != %ld)\n",
690 written, initrd_end - initrd_start);
693 #endif /* CONFIG_BLK_DEV_RAM */
695 static void __init do_populate_rootfs(void *unused, async_cookie_t cookie)
697 /* Load the built in initramfs */
698 char *err = unpack_to_rootfs(__initramfs_start, __initramfs_size);
700 panic_show_mem("%s", err); /* Failed to decompress INTERNAL initramfs */
702 if (!initrd_start || IS_ENABLED(CONFIG_INITRAMFS_FORCE))
705 if (IS_ENABLED(CONFIG_BLK_DEV_RAM))
706 printk(KERN_INFO "Trying to unpack rootfs image as initramfs...\n");
708 printk(KERN_INFO "Unpacking initramfs...\n");
710 err = unpack_to_rootfs((char *)initrd_start, initrd_end - initrd_start);
712 #ifdef CONFIG_BLK_DEV_RAM
713 populate_initrd_image(err);
715 printk(KERN_EMERG "Initramfs unpacking failed: %s\n", err);
721 * If the initrd region is overlapped with crashkernel reserved region,
722 * free only memory that is not part of crashkernel region.
724 if (!do_retain_initrd && initrd_start && !kexec_free_initrd())
725 free_initrd_mem(initrd_start, initrd_end);
729 flush_delayed_fput();
732 static ASYNC_DOMAIN_EXCLUSIVE(initramfs_domain);
733 static async_cookie_t initramfs_cookie;
735 void wait_for_initramfs(void)
737 if (!initramfs_cookie) {
739 * Something before rootfs_initcall wants to access
740 * the filesystem/initramfs. Probably a bug. Make a
741 * note, avoid deadlocking the machine, and let the
742 * caller's access fail as it used to.
744 pr_warn_once("wait_for_initramfs() called before rootfs_initcalls\n");
747 async_synchronize_cookie_domain(initramfs_cookie + 1, &initramfs_domain);
749 EXPORT_SYMBOL_GPL(wait_for_initramfs);
751 static int __init populate_rootfs(void)
753 initramfs_cookie = async_schedule_domain(do_populate_rootfs, NULL,
755 usermodehelper_enable();
756 if (!initramfs_async)
757 wait_for_initramfs();
760 rootfs_initcall(populate_rootfs);