1 // SPDX-License-Identifier: GPL-2.0 2 #include <linux/init.h> 3 #include <linux/async.h> 4 #include <linux/fs.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/kstrtox.h> 15 #include <linux/memblock.h> 16 #include <linux/mm.h> 17 #include <linux/namei.h> 18 #include <linux/init_syscalls.h> 19 #include <linux/umh.h> 20 #include <linux/security.h> 21 22 #include "do_mounts.h" 23 #include "initramfs_internal.h" 24 25 static __initdata bool csum_present; 26 static __initdata u32 io_csum; 27 28 static ssize_t __init xwrite(struct file *file, const unsigned char *p, 29 size_t count, loff_t *pos) 30 { 31 ssize_t out = 0; 32 33 /* sys_write only can write MAX_RW_COUNT aka 2G-4K bytes at most */ 34 while (count) { 35 ssize_t rv = kernel_write(file, p, count, pos); 36 37 if (rv < 0) { 38 if (rv == -EINTR || rv == -EAGAIN) 39 continue; 40 return out ? out : rv; 41 } else if (rv == 0) 42 break; 43 44 if (csum_present) { 45 ssize_t i; 46 47 for (i = 0; i < rv; i++) 48 io_csum += p[i]; 49 } 50 51 p += rv; 52 out += rv; 53 count -= rv; 54 } 55 56 return out; 57 } 58 59 static __initdata char *message; 60 static void __init error(char *x) 61 { 62 if (!message) 63 message = x; 64 } 65 66 #define panic_show_mem(fmt, ...) \ 67 ({ show_mem(); panic(fmt, ##__VA_ARGS__); }) 68 69 /* link hash */ 70 71 #define N_ALIGN(len) ((((len) + 1) & ~3) + 2) 72 73 static __initdata struct hash { 74 int ino, minor, major; 75 umode_t mode; 76 struct hash *next; 77 char name[N_ALIGN(PATH_MAX)]; 78 } *head[32]; 79 80 static inline int hash(int major, int minor, int ino) 81 { 82 unsigned long tmp = ino + minor + (major << 3); 83 tmp += tmp >> 5; 84 return tmp & 31; 85 } 86 87 static char __init *find_link(int major, int minor, int ino, 88 umode_t mode, char *name) 89 { 90 struct hash **p, *q; 91 for (p = head + hash(major, minor, ino); *p; p = &(*p)->next) { 92 if ((*p)->ino != ino) 93 continue; 94 if ((*p)->minor != minor) 95 continue; 96 if ((*p)->major != major) 97 continue; 98 if (((*p)->mode ^ mode) & S_IFMT) 99 continue; 100 return (*p)->name; 101 } 102 q = kmalloc(sizeof(struct hash), GFP_KERNEL); 103 if (!q) 104 panic_show_mem("can't allocate link hash entry"); 105 q->major = major; 106 q->minor = minor; 107 q->ino = ino; 108 q->mode = mode; 109 strcpy(q->name, name); 110 q->next = NULL; 111 *p = q; 112 return NULL; 113 } 114 115 static void __init free_hash(void) 116 { 117 struct hash **p, *q; 118 for (p = head; p < head + 32; p++) { 119 while (*p) { 120 q = *p; 121 *p = q->next; 122 kfree(q); 123 } 124 } 125 } 126 127 #ifdef CONFIG_INITRAMFS_PRESERVE_MTIME 128 static void __init do_utime(char *filename, time64_t mtime) 129 { 130 struct timespec64 t[2] = { { .tv_sec = mtime }, { .tv_sec = mtime } }; 131 init_utimes(filename, t); 132 } 133 134 static void __init do_utime_path(const struct path *path, time64_t mtime) 135 { 136 struct timespec64 t[2] = { { .tv_sec = mtime }, { .tv_sec = mtime } }; 137 vfs_utimes(path, t); 138 } 139 140 static __initdata LIST_HEAD(dir_list); 141 struct dir_entry { 142 struct list_head list; 143 time64_t mtime; 144 char name[]; 145 }; 146 147 static void __init dir_add(const char *name, time64_t mtime) 148 { 149 size_t nlen = strlen(name) + 1; 150 struct dir_entry *de; 151 152 de = kmalloc(sizeof(struct dir_entry) + nlen, GFP_KERNEL); 153 if (!de) 154 panic_show_mem("can't allocate dir_entry buffer"); 155 INIT_LIST_HEAD(&de->list); 156 strscpy(de->name, name, nlen); 157 de->mtime = mtime; 158 list_add(&de->list, &dir_list); 159 } 160 161 static void __init dir_utime(void) 162 { 163 struct dir_entry *de, *tmp; 164 list_for_each_entry_safe(de, tmp, &dir_list, list) { 165 list_del(&de->list); 166 do_utime(de->name, de->mtime); 167 kfree(de); 168 } 169 } 170 #else 171 static void __init do_utime(char *filename, time64_t mtime) {} 172 static void __init do_utime_path(const struct path *path, time64_t mtime) {} 173 static void __init dir_add(const char *name, time64_t mtime) {} 174 static void __init dir_utime(void) {} 175 #endif 176 177 static __initdata time64_t mtime; 178 179 /* cpio header parsing */ 180 181 static __initdata unsigned long ino, major, minor, nlink; 182 static __initdata umode_t mode; 183 static __initdata unsigned long body_len, name_len; 184 static __initdata uid_t uid; 185 static __initdata gid_t gid; 186 static __initdata unsigned rdev; 187 static __initdata u32 hdr_csum; 188 189 static void __init parse_header(char *s) 190 { 191 unsigned long parsed[13]; 192 int i; 193 194 for (i = 0, s += 6; i < 13; i++, s += 8) 195 parsed[i] = simple_strntoul(s, NULL, 16, 8); 196 197 ino = parsed[0]; 198 mode = parsed[1]; 199 uid = parsed[2]; 200 gid = parsed[3]; 201 nlink = parsed[4]; 202 mtime = parsed[5]; /* breaks in y2106 */ 203 body_len = parsed[6]; 204 major = parsed[7]; 205 minor = parsed[8]; 206 rdev = new_encode_dev(MKDEV(parsed[9], parsed[10])); 207 name_len = parsed[11]; 208 hdr_csum = parsed[12]; 209 } 210 211 /* FSM */ 212 213 static __initdata enum state { 214 Start, 215 Collect, 216 GotHeader, 217 SkipIt, 218 GotName, 219 CopyFile, 220 GotSymlink, 221 Reset 222 } state, next_state; 223 224 static __initdata char *victim; 225 static unsigned long byte_count __initdata; 226 static __initdata loff_t this_header, next_header; 227 228 static inline void __init eat(unsigned n) 229 { 230 victim += n; 231 this_header += n; 232 byte_count -= n; 233 } 234 235 static __initdata char *collected; 236 static long remains __initdata; 237 static __initdata char *collect; 238 239 static void __init read_into(char *buf, unsigned size, enum state next) 240 { 241 if (byte_count >= size) { 242 collected = victim; 243 eat(size); 244 state = next; 245 } else { 246 collect = collected = buf; 247 remains = size; 248 next_state = next; 249 state = Collect; 250 } 251 } 252 253 static __initdata char *header_buf, *symlink_buf, *name_buf; 254 255 static int __init do_start(void) 256 { 257 read_into(header_buf, CPIO_HDRLEN, GotHeader); 258 return 0; 259 } 260 261 static int __init do_collect(void) 262 { 263 unsigned long n = remains; 264 if (byte_count < n) 265 n = byte_count; 266 memcpy(collect, victim, n); 267 eat(n); 268 collect += n; 269 if ((remains -= n) != 0) 270 return 1; 271 state = next_state; 272 return 0; 273 } 274 275 static int __init do_header(void) 276 { 277 if (!memcmp(collected, "070701", 6)) { 278 csum_present = false; 279 } else if (!memcmp(collected, "070702", 6)) { 280 csum_present = true; 281 } else { 282 if (memcmp(collected, "070707", 6) == 0) 283 error("incorrect cpio method used: use -H newc option"); 284 else 285 error("no cpio magic"); 286 return 1; 287 } 288 parse_header(collected); 289 next_header = this_header + N_ALIGN(name_len) + body_len; 290 next_header = (next_header + 3) & ~3; 291 state = SkipIt; 292 if (name_len <= 0 || name_len > PATH_MAX) 293 return 0; 294 if (S_ISLNK(mode)) { 295 if (body_len > PATH_MAX) 296 return 0; 297 collect = collected = symlink_buf; 298 remains = N_ALIGN(name_len) + body_len; 299 next_state = GotSymlink; 300 state = Collect; 301 return 0; 302 } 303 if (S_ISREG(mode) || !body_len) 304 read_into(name_buf, N_ALIGN(name_len), GotName); 305 return 0; 306 } 307 308 static int __init do_skip(void) 309 { 310 if (this_header + byte_count < next_header) { 311 eat(byte_count); 312 return 1; 313 } else { 314 eat(next_header - this_header); 315 state = next_state; 316 return 0; 317 } 318 } 319 320 static int __init do_reset(void) 321 { 322 while (byte_count && *victim == '\0') 323 eat(1); 324 if (byte_count && (this_header & 3)) 325 error("broken padding"); 326 return 1; 327 } 328 329 static void __init clean_path(char *path, umode_t fmode) 330 { 331 struct kstat st; 332 333 if (!init_stat(path, &st, AT_SYMLINK_NOFOLLOW) && 334 (st.mode ^ fmode) & S_IFMT) { 335 if (S_ISDIR(st.mode)) 336 init_rmdir(path); 337 else 338 init_unlink(path); 339 } 340 } 341 342 static int __init maybe_link(void) 343 { 344 if (nlink >= 2) { 345 char *old = find_link(major, minor, ino, mode, collected); 346 if (old) { 347 clean_path(collected, 0); 348 return (init_link(old, collected) < 0) ? -1 : 1; 349 } 350 } 351 return 0; 352 } 353 354 static __initdata struct file *wfile; 355 static __initdata loff_t wfile_pos; 356 357 static int __init do_name(void) 358 { 359 state = SkipIt; 360 next_state = Reset; 361 362 /* name_len > 0 && name_len <= PATH_MAX checked in do_header */ 363 if (collected[name_len - 1] != '\0') { 364 pr_err("initramfs name without nulterm: %.*s\n", 365 (int)name_len, collected); 366 error("malformed archive"); 367 return 1; 368 } 369 370 if (strcmp(collected, "TRAILER!!!") == 0) { 371 free_hash(); 372 return 0; 373 } 374 clean_path(collected, mode); 375 if (S_ISREG(mode)) { 376 int ml = maybe_link(); 377 if (ml >= 0) { 378 int openflags = O_WRONLY|O_CREAT|O_LARGEFILE; 379 if (ml != 1) 380 openflags |= O_TRUNC; 381 wfile = filp_open(collected, openflags, mode); 382 if (IS_ERR(wfile)) 383 return 0; 384 wfile_pos = 0; 385 io_csum = 0; 386 387 vfs_fchown(wfile, uid, gid); 388 vfs_fchmod(wfile, mode); 389 if (body_len) 390 vfs_truncate(&wfile->f_path, body_len); 391 state = CopyFile; 392 } 393 } else if (S_ISDIR(mode)) { 394 init_mkdir(collected, mode); 395 init_chown(collected, uid, gid, 0); 396 init_chmod(collected, mode); 397 dir_add(collected, mtime); 398 } else if (S_ISBLK(mode) || S_ISCHR(mode) || 399 S_ISFIFO(mode) || S_ISSOCK(mode)) { 400 if (maybe_link() == 0) { 401 init_mknod(collected, mode, rdev); 402 init_chown(collected, uid, gid, 0); 403 init_chmod(collected, mode); 404 do_utime(collected, mtime); 405 } 406 } 407 return 0; 408 } 409 410 static int __init do_copy(void) 411 { 412 if (byte_count >= body_len) { 413 if (xwrite(wfile, victim, body_len, &wfile_pos) != body_len) 414 error("write error"); 415 416 do_utime_path(&wfile->f_path, mtime); 417 fput(wfile); 418 if (csum_present && io_csum != hdr_csum) 419 error("bad data checksum"); 420 eat(body_len); 421 state = SkipIt; 422 return 0; 423 } else { 424 if (xwrite(wfile, victim, byte_count, &wfile_pos) != byte_count) 425 error("write error"); 426 body_len -= byte_count; 427 eat(byte_count); 428 return 1; 429 } 430 } 431 432 static int __init do_symlink(void) 433 { 434 if (collected[name_len - 1] != '\0') { 435 pr_err("initramfs symlink without nulterm: %.*s\n", 436 (int)name_len, collected); 437 error("malformed archive"); 438 return 1; 439 } 440 collected[N_ALIGN(name_len) + body_len] = '\0'; 441 clean_path(collected, 0); 442 init_symlink(collected + N_ALIGN(name_len), collected); 443 init_chown(collected, uid, gid, AT_SYMLINK_NOFOLLOW); 444 do_utime(collected, mtime); 445 state = SkipIt; 446 next_state = Reset; 447 return 0; 448 } 449 450 static __initdata int (*actions[])(void) = { 451 [Start] = do_start, 452 [Collect] = do_collect, 453 [GotHeader] = do_header, 454 [SkipIt] = do_skip, 455 [GotName] = do_name, 456 [CopyFile] = do_copy, 457 [GotSymlink] = do_symlink, 458 [Reset] = do_reset, 459 }; 460 461 static long __init write_buffer(char *buf, unsigned long len) 462 { 463 byte_count = len; 464 victim = buf; 465 466 while (!actions[state]()) 467 ; 468 return len - byte_count; 469 } 470 471 static long __init flush_buffer(void *bufv, unsigned long len) 472 { 473 char *buf = bufv; 474 long written; 475 long origLen = len; 476 if (message) 477 return -1; 478 while ((written = write_buffer(buf, len)) < len && !message) { 479 char c = buf[written]; 480 if (c == '0') { 481 buf += written; 482 len -= written; 483 state = Start; 484 } else if (c == 0) { 485 buf += written; 486 len -= written; 487 state = Reset; 488 } else 489 error("junk within compressed archive"); 490 } 491 return origLen; 492 } 493 494 static unsigned long my_inptr __initdata; /* index of next byte to be processed in inbuf */ 495 496 #include <linux/decompress/generic.h> 497 498 /** 499 * unpack_to_rootfs - decompress and extract an initramfs archive 500 * @buf: input initramfs archive to extract 501 * @len: length of initramfs data to process 502 * 503 * Returns: NULL for success or an error message string 504 * 505 * This symbol shouldn't be used externally. It's available for unit tests. 506 */ 507 char * __init unpack_to_rootfs(char *buf, unsigned long len) 508 { 509 long written; 510 decompress_fn decompress; 511 const char *compress_name; 512 static __initdata char msg_buf[64]; 513 514 header_buf = kmalloc(CPIO_HDRLEN, GFP_KERNEL); 515 symlink_buf = kmalloc(PATH_MAX + N_ALIGN(PATH_MAX) + 1, GFP_KERNEL); 516 name_buf = kmalloc(N_ALIGN(PATH_MAX), GFP_KERNEL); 517 518 if (!header_buf || !symlink_buf || !name_buf) 519 panic_show_mem("can't allocate buffers"); 520 521 state = Start; 522 this_header = 0; 523 message = NULL; 524 while (!message && len) { 525 loff_t saved_offset = this_header; 526 if (*buf == '0' && !(this_header & 3)) { 527 state = Start; 528 written = write_buffer(buf, len); 529 buf += written; 530 len -= written; 531 continue; 532 } 533 if (!*buf) { 534 buf++; 535 len--; 536 this_header++; 537 continue; 538 } 539 this_header = 0; 540 decompress = decompress_method(buf, len, &compress_name); 541 pr_debug("Detected %s compressed data\n", compress_name); 542 if (decompress) { 543 int res = decompress(buf, len, NULL, flush_buffer, NULL, 544 &my_inptr, error); 545 if (res) 546 error("decompressor failed"); 547 } else if (compress_name) { 548 if (!message) { 549 snprintf(msg_buf, sizeof msg_buf, 550 "compression method %s not configured", 551 compress_name); 552 message = msg_buf; 553 } 554 } else 555 error("invalid magic at start of compressed archive"); 556 if (state != Reset) 557 error("junk at the end of compressed archive"); 558 this_header = saved_offset + my_inptr; 559 buf += my_inptr; 560 len -= my_inptr; 561 } 562 dir_utime(); 563 kfree(name_buf); 564 kfree(symlink_buf); 565 kfree(header_buf); 566 return message; 567 } 568 569 static int __initdata do_retain_initrd; 570 571 static int __init retain_initrd_param(char *str) 572 { 573 if (*str) 574 return 0; 575 do_retain_initrd = 1; 576 return 1; 577 } 578 __setup("retain_initrd", retain_initrd_param); 579 580 #ifdef CONFIG_ARCH_HAS_KEEPINITRD 581 static int __init keepinitrd_setup(char *__unused) 582 { 583 do_retain_initrd = 1; 584 return 1; 585 } 586 __setup("keepinitrd", keepinitrd_setup); 587 #endif 588 589 static bool __initdata initramfs_async = true; 590 static int __init initramfs_async_setup(char *str) 591 { 592 return kstrtobool(str, &initramfs_async) == 0; 593 } 594 __setup("initramfs_async=", initramfs_async_setup); 595 596 extern char __initramfs_start[]; 597 extern unsigned long __initramfs_size; 598 #include <linux/initrd.h> 599 #include <linux/kexec.h> 600 601 static BIN_ATTR(initrd, 0440, sysfs_bin_attr_simple_read, NULL, 0); 602 603 void __init reserve_initrd_mem(void) 604 { 605 phys_addr_t start; 606 unsigned long size; 607 608 /* Ignore the virtul address computed during device tree parsing */ 609 initrd_start = initrd_end = 0; 610 611 if (!phys_initrd_size) 612 return; 613 /* 614 * Round the memory region to page boundaries as per free_initrd_mem() 615 * This allows us to detect whether the pages overlapping the initrd 616 * are in use, but more importantly, reserves the entire set of pages 617 * as we don't want these pages allocated for other purposes. 618 */ 619 start = round_down(phys_initrd_start, PAGE_SIZE); 620 size = phys_initrd_size + (phys_initrd_start - start); 621 size = round_up(size, PAGE_SIZE); 622 623 if (!memblock_is_region_memory(start, size)) { 624 pr_err("INITRD: 0x%08llx+0x%08lx is not a memory region", 625 (u64)start, size); 626 goto disable; 627 } 628 629 if (memblock_is_region_reserved(start, size)) { 630 pr_err("INITRD: 0x%08llx+0x%08lx overlaps in-use memory region\n", 631 (u64)start, size); 632 goto disable; 633 } 634 635 memblock_reserve(start, size); 636 /* Now convert initrd to virtual addresses */ 637 initrd_start = (unsigned long)__va(phys_initrd_start); 638 initrd_end = initrd_start + phys_initrd_size; 639 initrd_below_start_ok = 1; 640 641 return; 642 disable: 643 pr_cont(" - disabling initrd\n"); 644 initrd_start = 0; 645 initrd_end = 0; 646 } 647 648 void __weak __init free_initrd_mem(unsigned long start, unsigned long end) 649 { 650 #ifdef CONFIG_ARCH_KEEP_MEMBLOCK 651 unsigned long aligned_start = ALIGN_DOWN(start, PAGE_SIZE); 652 unsigned long aligned_end = ALIGN(end, PAGE_SIZE); 653 654 memblock_free((void *)aligned_start, aligned_end - aligned_start); 655 #endif 656 657 free_reserved_area((void *)start, (void *)end, POISON_FREE_INITMEM, 658 "initrd"); 659 } 660 661 #ifdef CONFIG_CRASH_RESERVE 662 static bool __init kexec_free_initrd(void) 663 { 664 unsigned long crashk_start = (unsigned long)__va(crashk_res.start); 665 unsigned long crashk_end = (unsigned long)__va(crashk_res.end); 666 667 /* 668 * If the initrd region is overlapped with crashkernel reserved region, 669 * free only memory that is not part of crashkernel region. 670 */ 671 if (initrd_start >= crashk_end || initrd_end <= crashk_start) 672 return false; 673 674 /* 675 * Initialize initrd memory region since the kexec boot does not do. 676 */ 677 memset((void *)initrd_start, 0, initrd_end - initrd_start); 678 if (initrd_start < crashk_start) 679 free_initrd_mem(initrd_start, crashk_start); 680 if (initrd_end > crashk_end) 681 free_initrd_mem(crashk_end, initrd_end); 682 return true; 683 } 684 #else 685 static inline bool kexec_free_initrd(void) 686 { 687 return false; 688 } 689 #endif /* CONFIG_KEXEC_CORE */ 690 691 #ifdef CONFIG_BLK_DEV_RAM 692 static void __init populate_initrd_image(char *err) 693 { 694 ssize_t written; 695 struct file *file; 696 loff_t pos = 0; 697 698 printk(KERN_INFO "rootfs image is not initramfs (%s); looks like an initrd\n", 699 err); 700 file = filp_open("/initrd.image", O_WRONLY|O_CREAT|O_LARGEFILE, 0700); 701 if (IS_ERR(file)) 702 return; 703 704 written = xwrite(file, (char *)initrd_start, initrd_end - initrd_start, 705 &pos); 706 if (written != initrd_end - initrd_start) 707 pr_err("/initrd.image: incomplete write (%zd != %ld)\n", 708 written, initrd_end - initrd_start); 709 fput(file); 710 } 711 #endif /* CONFIG_BLK_DEV_RAM */ 712 713 static void __init do_populate_rootfs(void *unused, async_cookie_t cookie) 714 { 715 /* Load the built in initramfs */ 716 char *err = unpack_to_rootfs(__initramfs_start, __initramfs_size); 717 if (err) 718 panic_show_mem("%s", err); /* Failed to decompress INTERNAL initramfs */ 719 720 if (!initrd_start || IS_ENABLED(CONFIG_INITRAMFS_FORCE)) 721 goto done; 722 723 if (IS_ENABLED(CONFIG_BLK_DEV_RAM)) 724 printk(KERN_INFO "Trying to unpack rootfs image as initramfs...\n"); 725 else 726 printk(KERN_INFO "Unpacking initramfs...\n"); 727 728 err = unpack_to_rootfs((char *)initrd_start, initrd_end - initrd_start); 729 if (err) { 730 #ifdef CONFIG_BLK_DEV_RAM 731 populate_initrd_image(err); 732 #else 733 printk(KERN_EMERG "Initramfs unpacking failed: %s\n", err); 734 #endif 735 } 736 737 done: 738 security_initramfs_populated(); 739 740 /* 741 * If the initrd region is overlapped with crashkernel reserved region, 742 * free only memory that is not part of crashkernel region. 743 */ 744 if (!do_retain_initrd && initrd_start && !kexec_free_initrd()) { 745 free_initrd_mem(initrd_start, initrd_end); 746 } else if (do_retain_initrd && initrd_start) { 747 bin_attr_initrd.size = initrd_end - initrd_start; 748 bin_attr_initrd.private = (void *)initrd_start; 749 if (sysfs_create_bin_file(firmware_kobj, &bin_attr_initrd)) 750 pr_err("Failed to create initrd sysfs file"); 751 } 752 initrd_start = 0; 753 initrd_end = 0; 754 755 init_flush_fput(); 756 } 757 758 static ASYNC_DOMAIN_EXCLUSIVE(initramfs_domain); 759 static async_cookie_t initramfs_cookie; 760 761 void wait_for_initramfs(void) 762 { 763 if (!initramfs_cookie) { 764 /* 765 * Something before rootfs_initcall wants to access 766 * the filesystem/initramfs. Probably a bug. Make a 767 * note, avoid deadlocking the machine, and let the 768 * caller's access fail as it used to. 769 */ 770 pr_warn_once("wait_for_initramfs() called before rootfs_initcalls\n"); 771 return; 772 } 773 async_synchronize_cookie_domain(initramfs_cookie + 1, &initramfs_domain); 774 } 775 EXPORT_SYMBOL_GPL(wait_for_initramfs); 776 777 static int __init populate_rootfs(void) 778 { 779 initramfs_cookie = async_schedule_domain(do_populate_rootfs, NULL, 780 &initramfs_domain); 781 usermodehelper_enable(); 782 if (!initramfs_async) 783 wait_for_initramfs(); 784 return 0; 785 } 786 rootfs_initcall(populate_rootfs); 787