brintos

brintos / linux-shallow public Read only

0
0
Text · 17.5 KiB · c97f254 Raw
766 lines · c
1// SPDX-License-Identifier: GPL-2.02#include <linux/init.h>3#include <linux/initramfs.h>4#include <linux/async.h>5#include <linux/fs.h>6#include <linux/slab.h>7#include <linux/types.h>8#include <linux/fcntl.h>9#include <linux/delay.h>10#include <linux/string.h>11#include <linux/dirent.h>12#include <linux/syscalls.h>13#include <linux/utime.h>14#include <linux/file.h>15#include <linux/kstrtox.h>16#include <linux/memblock.h>17#include <linux/mm.h>18#include <linux/namei.h>19#include <linux/init_syscalls.h>20#include <linux/umh.h>21#include <linux/security.h>22 23#include "do_mounts.h"24 25static __initdata bool csum_present;26static __initdata u32 io_csum;27 28static 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 59static __initdata char *message;60static 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 73static __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 80static 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 87static 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 115static 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_MTIME128static 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 134static 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 140static __initdata LIST_HEAD(dir_list);141struct dir_entry {142	struct list_head list;143	time64_t mtime;144	char name[];145};146 147static 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 161static 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#else171static void __init do_utime(char *filename, time64_t mtime) {}172static void __init do_utime_path(const struct path *path, time64_t mtime) {}173static void __init dir_add(const char *name, time64_t mtime) {}174static void __init dir_utime(void) {}175#endif176 177static __initdata time64_t mtime;178 179/* cpio header parsing */180 181static __initdata unsigned long ino, major, minor, nlink;182static __initdata umode_t mode;183static __initdata unsigned long body_len, name_len;184static __initdata uid_t uid;185static __initdata gid_t gid;186static __initdata unsigned rdev;187static __initdata u32 hdr_csum;188 189static void __init parse_header(char *s)190{191	unsigned long parsed[13];192	char buf[9];193	int i;194 195	buf[8] = '\0';196	for (i = 0, s += 6; i < 13; i++, s += 8) {197		memcpy(buf, s, 8);198		parsed[i] = simple_strtoul(buf, NULL, 16);199	}200	ino = parsed[0];201	mode = parsed[1];202	uid = parsed[2];203	gid = parsed[3];204	nlink = parsed[4];205	mtime = parsed[5]; /* breaks in y2106 */206	body_len = parsed[6];207	major = parsed[7];208	minor = parsed[8];209	rdev = new_encode_dev(MKDEV(parsed[9], parsed[10]));210	name_len = parsed[11];211	hdr_csum = parsed[12];212}213 214/* FSM */215 216static __initdata enum state {217	Start,218	Collect,219	GotHeader,220	SkipIt,221	GotName,222	CopyFile,223	GotSymlink,224	Reset225} state, next_state;226 227static __initdata char *victim;228static unsigned long byte_count __initdata;229static __initdata loff_t this_header, next_header;230 231static inline void __init eat(unsigned n)232{233	victim += n;234	this_header += n;235	byte_count -= n;236}237 238static __initdata char *collected;239static long remains __initdata;240static __initdata char *collect;241 242static void __init read_into(char *buf, unsigned size, enum state next)243{244	if (byte_count >= size) {245		collected = victim;246		eat(size);247		state = next;248	} else {249		collect = collected = buf;250		remains = size;251		next_state = next;252		state = Collect;253	}254}255 256static __initdata char *header_buf, *symlink_buf, *name_buf;257 258static int __init do_start(void)259{260	read_into(header_buf, 110, GotHeader);261	return 0;262}263 264static int __init do_collect(void)265{266	unsigned long n = remains;267	if (byte_count < n)268		n = byte_count;269	memcpy(collect, victim, n);270	eat(n);271	collect += n;272	if ((remains -= n) != 0)273		return 1;274	state = next_state;275	return 0;276}277 278static int __init do_header(void)279{280	if (!memcmp(collected, "070701", 6)) {281		csum_present = false;282	} else if (!memcmp(collected, "070702", 6)) {283		csum_present = true;284	} else {285		if (memcmp(collected, "070707", 6) == 0)286			error("incorrect cpio method used: use -H newc option");287		else288			error("no cpio magic");289		return 1;290	}291	parse_header(collected);292	next_header = this_header + N_ALIGN(name_len) + body_len;293	next_header = (next_header + 3) & ~3;294	state = SkipIt;295	if (name_len <= 0 || name_len > PATH_MAX)296		return 0;297	if (S_ISLNK(mode)) {298		if (body_len > PATH_MAX)299			return 0;300		collect = collected = symlink_buf;301		remains = N_ALIGN(name_len) + body_len;302		next_state = GotSymlink;303		state = Collect;304		return 0;305	}306	if (S_ISREG(mode) || !body_len)307		read_into(name_buf, N_ALIGN(name_len), GotName);308	return 0;309}310 311static int __init do_skip(void)312{313	if (this_header + byte_count < next_header) {314		eat(byte_count);315		return 1;316	} else {317		eat(next_header - this_header);318		state = next_state;319		return 0;320	}321}322 323static int __init do_reset(void)324{325	while (byte_count && *victim == '\0')326		eat(1);327	if (byte_count && (this_header & 3))328		error("broken padding");329	return 1;330}331 332static void __init clean_path(char *path, umode_t fmode)333{334	struct kstat st;335 336	if (!init_stat(path, &st, AT_SYMLINK_NOFOLLOW) &&337	    (st.mode ^ fmode) & S_IFMT) {338		if (S_ISDIR(st.mode))339			init_rmdir(path);340		else341			init_unlink(path);342	}343}344 345static int __init maybe_link(void)346{347	if (nlink >= 2) {348		char *old = find_link(major, minor, ino, mode, collected);349		if (old) {350			clean_path(collected, 0);351			return (init_link(old, collected) < 0) ? -1 : 1;352		}353	}354	return 0;355}356 357static __initdata struct file *wfile;358static __initdata loff_t wfile_pos;359 360static int __init do_name(void)361{362	state = SkipIt;363	next_state = Reset;364	if (strcmp(collected, "TRAILER!!!") == 0) {365		free_hash();366		return 0;367	}368	clean_path(collected, mode);369	if (S_ISREG(mode)) {370		int ml = maybe_link();371		if (ml >= 0) {372			int openflags = O_WRONLY|O_CREAT|O_LARGEFILE;373			if (ml != 1)374				openflags |= O_TRUNC;375			wfile = filp_open(collected, openflags, mode);376			if (IS_ERR(wfile))377				return 0;378			wfile_pos = 0;379			io_csum = 0;380 381			vfs_fchown(wfile, uid, gid);382			vfs_fchmod(wfile, mode);383			if (body_len)384				vfs_truncate(&wfile->f_path, body_len);385			state = CopyFile;386		}387	} else if (S_ISDIR(mode)) {388		init_mkdir(collected, mode);389		init_chown(collected, uid, gid, 0);390		init_chmod(collected, mode);391		dir_add(collected, mtime);392	} else if (S_ISBLK(mode) || S_ISCHR(mode) ||393		   S_ISFIFO(mode) || S_ISSOCK(mode)) {394		if (maybe_link() == 0) {395			init_mknod(collected, mode, rdev);396			init_chown(collected, uid, gid, 0);397			init_chmod(collected, mode);398			do_utime(collected, mtime);399		}400	}401	return 0;402}403 404static int __init do_copy(void)405{406	if (byte_count >= body_len) {407		if (xwrite(wfile, victim, body_len, &wfile_pos) != body_len)408			error("write error");409 410		do_utime_path(&wfile->f_path, mtime);411		fput(wfile);412		if (csum_present && io_csum != hdr_csum)413			error("bad data checksum");414		eat(body_len);415		state = SkipIt;416		return 0;417	} else {418		if (xwrite(wfile, victim, byte_count, &wfile_pos) != byte_count)419			error("write error");420		body_len -= byte_count;421		eat(byte_count);422		return 1;423	}424}425 426static int __init do_symlink(void)427{428	collected[N_ALIGN(name_len) + body_len] = '\0';429	clean_path(collected, 0);430	init_symlink(collected + N_ALIGN(name_len), collected);431	init_chown(collected, uid, gid, AT_SYMLINK_NOFOLLOW);432	do_utime(collected, mtime);433	state = SkipIt;434	next_state = Reset;435	return 0;436}437 438static __initdata int (*actions[])(void) = {439	[Start]		= do_start,440	[Collect]	= do_collect,441	[GotHeader]	= do_header,442	[SkipIt]	= do_skip,443	[GotName]	= do_name,444	[CopyFile]	= do_copy,445	[GotSymlink]	= do_symlink,446	[Reset]		= do_reset,447};448 449static HWJS_SUSPENDS long __init write_buffer(char *buf, unsigned long len)450{451	byte_count = len;452	victim = buf;453 454	while (!actions[state]())455		;456	return len - byte_count;457}458 459static HWJS_SUSPENDS long __init flush_buffer(void *bufv, unsigned long len)460{461	char *buf = bufv;462	long written;463	long origLen = len;464	if (message)465		return -1;466	while ((written = write_buffer(buf, len)) < len && !message) {467		char c = buf[written];468		if (c == '0') {469			buf += written;470			len -= written;471			state = Start;472		} else if (c == 0) {473			buf += written;474			len -= written;475			state = Reset;476		} else477			error("junk within compressed archive");478	}479	return origLen;480}481 482static unsigned long my_inptr __initdata; /* index of next byte to be processed in inbuf */483 484#include <linux/decompress/generic.h>485 486char * __init unpack_to_rootfs(char *buf, unsigned long len)487{488	long written;489	decompress_fn decompress;490	const char *compress_name;491	static __initdata char msg_buf[64];492 493	header_buf = kmalloc(110, GFP_KERNEL);494	symlink_buf = kmalloc(PATH_MAX + N_ALIGN(PATH_MAX) + 1, GFP_KERNEL);495	name_buf = kmalloc(N_ALIGN(PATH_MAX), GFP_KERNEL);496 497	if (!header_buf || !symlink_buf || !name_buf)498		panic_show_mem("can't allocate buffers");499 500	state = Start;501	this_header = 0;502	message = NULL;503	while (!message && len) {504		loff_t saved_offset = this_header;505		if (*buf == '0' && !(this_header & 3)) {506			state = Start;507			written = write_buffer(buf, len);508			buf += written;509			len -= written;510			continue;511		}512		if (!*buf) {513			buf++;514			len--;515			this_header++;516			continue;517		}518		this_header = 0;519		decompress = decompress_method(buf, len, &compress_name);520		pr_debug("Detected %s compressed data\n", compress_name);521		if (decompress) {522			int res = decompress(buf, len, NULL, flush_buffer, NULL,523				   &my_inptr, error);524			if (res)525				error("decompressor failed");526		} else if (compress_name) {527			if (!message) {528				snprintf(msg_buf, sizeof msg_buf,529					 "compression method %s not configured",530					 compress_name);531				message = msg_buf;532			}533		} else534			error("invalid magic at start of compressed archive");535		if (state != Reset)536			error("junk at the end of compressed archive");537		this_header = saved_offset + my_inptr;538		buf += my_inptr;539		len -= my_inptr;540	}541	dir_utime();542	kfree(name_buf);543	kfree(symlink_buf);544	kfree(header_buf);545	return message;546}547 548static int __initdata do_retain_initrd;549 550static int __init retain_initrd_param(char *str)551{552	if (*str)553		return 0;554	do_retain_initrd = 1;555	return 1;556}557__setup("retain_initrd", retain_initrd_param);558 559#ifdef CONFIG_ARCH_HAS_KEEPINITRD560static int __init keepinitrd_setup(char *__unused)561{562	do_retain_initrd = 1;563	return 1;564}565__setup("keepinitrd", keepinitrd_setup);566#endif567 568static bool __initdata initramfs_async = true;569static int __init initramfs_async_setup(char *str)570{571	return kstrtobool(str, &initramfs_async) == 0;572}573__setup("initramfs_async=", initramfs_async_setup);574 575extern char __initramfs_start[];576extern unsigned long __initramfs_size;577#include <linux/initrd.h>578#include <linux/kexec.h>579 580static BIN_ATTR(initrd, 0440, sysfs_bin_attr_simple_read, NULL, 0);581 582void __init reserve_initrd_mem(void)583{584	phys_addr_t start;585	unsigned long size;586 587	/* Ignore the virtul address computed during device tree parsing */588	initrd_start = initrd_end = 0;589 590	if (!phys_initrd_size)591		return;592	/*593	 * Round the memory region to page boundaries as per free_initrd_mem()594	 * This allows us to detect whether the pages overlapping the initrd595	 * are in use, but more importantly, reserves the entire set of pages596	 * as we don't want these pages allocated for other purposes.597	 */598	start = round_down(phys_initrd_start, PAGE_SIZE);599	size = phys_initrd_size + (phys_initrd_start - start);600	size = round_up(size, PAGE_SIZE);601 602	if (!memblock_is_region_memory(start, size)) {603		pr_err("INITRD: 0x%08llx+0x%08lx is not a memory region",604		       (u64)start, size);605		goto disable;606	}607 608	if (memblock_is_region_reserved(start, size)) {609		pr_err("INITRD: 0x%08llx+0x%08lx overlaps in-use memory region\n",610		       (u64)start, size);611		goto disable;612	}613 614	memblock_reserve(start, size);615	/* Now convert initrd to virtual addresses */616	initrd_start = (unsigned long)__va(phys_initrd_start);617	initrd_end = initrd_start + phys_initrd_size;618	initrd_below_start_ok = 1;619 620	return;621disable:622	pr_cont(" - disabling initrd\n");623	initrd_start = 0;624	initrd_end = 0;625}626 627void __weak __init free_initrd_mem(unsigned long start, unsigned long end)628{629#ifdef CONFIG_ARCH_KEEP_MEMBLOCK630	unsigned long aligned_start = ALIGN_DOWN(start, PAGE_SIZE);631	unsigned long aligned_end = ALIGN(end, PAGE_SIZE);632 633	memblock_free((void *)aligned_start, aligned_end - aligned_start);634#endif635 636	free_reserved_area((void *)start, (void *)end, POISON_FREE_INITMEM,637			"initrd");638}639 640#ifdef CONFIG_CRASH_RESERVE641static bool __init kexec_free_initrd(void)642{643	unsigned long crashk_start = (unsigned long)__va(crashk_res.start);644	unsigned long crashk_end   = (unsigned long)__va(crashk_res.end);645 646	/*647	 * If the initrd region is overlapped with crashkernel reserved region,648	 * free only memory that is not part of crashkernel region.649	 */650	if (initrd_start >= crashk_end || initrd_end <= crashk_start)651		return false;652 653	/*654	 * Initialize initrd memory region since the kexec boot does not do.655	 */656	memset((void *)initrd_start, 0, initrd_end - initrd_start);657	if (initrd_start < crashk_start)658		free_initrd_mem(initrd_start, crashk_start);659	if (initrd_end > crashk_end)660		free_initrd_mem(crashk_end, initrd_end);661	return true;662}663#else664static inline bool kexec_free_initrd(void)665{666	return false;667}668#endif /* CONFIG_KEXEC_CORE */669 670#ifdef CONFIG_BLK_DEV_RAM671static void __init populate_initrd_image(char *err)672{673	ssize_t written;674	struct file *file;675	loff_t pos = 0;676 677	printk(KERN_INFO "rootfs image is not initramfs (%s); looks like an initrd\n",678			err);679	file = filp_open("/initrd.image", O_WRONLY|O_CREAT|O_LARGEFILE, 0700);680	if (IS_ERR(file))681		return;682 683	written = xwrite(file, (char *)initrd_start, initrd_end - initrd_start,684			&pos);685	if (written != initrd_end - initrd_start)686		pr_err("/initrd.image: incomplete write (%zd != %ld)\n",687		       written, initrd_end - initrd_start);688	fput(file);689}690#endif /* CONFIG_BLK_DEV_RAM */691 692static void __init do_populate_rootfs(void *unused, async_cookie_t cookie)693{694	/* Load the built in initramfs */695	char *err = unpack_to_rootfs(__initramfs_start, __initramfs_size);696	if (err)697		panic_show_mem("%s", err); /* Failed to decompress INTERNAL initramfs */698 699	if (!initrd_start || IS_ENABLED(CONFIG_INITRAMFS_FORCE))700		goto done;701 702	if (IS_ENABLED(CONFIG_BLK_DEV_RAM))703		printk(KERN_INFO "Trying to unpack rootfs image as initramfs...\n");704	else705		printk(KERN_INFO "Unpacking initramfs...\n");706 707	err = unpack_to_rootfs((char *)initrd_start, initrd_end - initrd_start);708	if (err) {709#ifdef CONFIG_BLK_DEV_RAM710		populate_initrd_image(err);711#else712		printk(KERN_EMERG "Initramfs unpacking failed: %s\n", err);713#endif714	}715 716done:717	security_initramfs_populated();718 719	/*720	 * If the initrd region is overlapped with crashkernel reserved region,721	 * free only memory that is not part of crashkernel region.722	 */723	if (!do_retain_initrd && initrd_start && !kexec_free_initrd()) {724		free_initrd_mem(initrd_start, initrd_end);725	} else if (do_retain_initrd && initrd_start) {726		bin_attr_initrd.size = initrd_end - initrd_start;727		bin_attr_initrd.private = (void *)initrd_start;728		if (sysfs_create_bin_file(firmware_kobj, &bin_attr_initrd))729			pr_err("Failed to create initrd sysfs file");730	}731	initrd_start = 0;732	initrd_end = 0;733 734	init_flush_fput();735}736 737static ASYNC_DOMAIN_EXCLUSIVE(initramfs_domain);738static async_cookie_t initramfs_cookie;739 740void wait_for_initramfs(void)741{742	if (!initramfs_cookie) {743		/*744		 * Something before rootfs_initcall wants to access745		 * the filesystem/initramfs. Probably a bug. Make a746		 * note, avoid deadlocking the machine, and let the747		 * caller's access fail as it used to.748		 */749		pr_warn_once("wait_for_initramfs() called before rootfs_initcalls\n");750		return;751	}752	async_synchronize_cookie_domain(initramfs_cookie + 1, &initramfs_domain);753}754EXPORT_SYMBOL_GPL(wait_for_initramfs);755 756static HWJS_SUSPENDS int __init populate_rootfs(void)757{758	initramfs_cookie = async_schedule_domain(do_populate_rootfs, NULL,759						 &initramfs_domain);760	usermodehelper_enable();761	if (!initramfs_async)762		wait_for_initramfs();763	return 0;764}765rootfs_initcall(populate_rootfs);766