关键词:ramdisk、rdint、.init.ramfs、__initramfs_start、__initramfs_size、rootfs、ramfs、populate_rootfs()、gzip、actions[]、free_initmem()、run_init_process()等等。
本着了解ramdisk,带着如下几个问题进行分析:
- 如何打开ramdisk功能?
- ramdisk存放在哪里?
- ramdisk在什么时候解压?如何解压?
- 解压后ramdisk在什么位置?
- ramdisk如何启动?
1.如何打开ramdisk功能?
如果要使用ramdisk功能,需要做两步工作:一是修改Kernel的bootargs,增加rdinit选项;二是在编译uImage的时候将rootfs.cpio嵌入。
下面是使用ramdisk启动和使用eMMC作为启动介质的两种配置,ramdisk需要制定rdinit选项,并且root设备变成了/dev/ram0。
bootargs = "console=ttyS0,115200 rdinit=/sbin/init root=/dev/ram0 quiet"; bootargs = "console=ttyS0,115200 root=/dev/mmcblk1p2 rw rootfstype=ext4 rootflags=data=journal,barrier=1 rootwait";
需要将rootfs.cpio嵌入到kernel image,可以通过buildroot配置:
config BR2_TARGET_ROOTFS_INITRAMFS bool "initial RAM filesystem linked into linux kernel" depends on BR2_LINUX_KERNEL select BR2_TARGET_ROOTFS_CPIO help Integrate the root filesystem generated by Buildroot as an initramfs inside the kernel image. This integration will take place automatically. A rootfs.cpio file will be generated in the images/ directory. This is the archive that will be included in the kernel image. The default rootfs compression set in the kernel configuration is used, regardless of how buildroot's cpio archive is configured. Note that enabling initramfs together with another filesystem formats doesn't make sense: you would end up having two identical root filesystems, one embedded inside the kernel image, and one separately.
还可以在编译内核的时候通过如下编译选项来达到:
make uImage -j16 CONFIG_BLK_DEV_INITRD=y CONFIG_INITRAMFS_SOURCE="${BR_BINARIES_DIR}/rootfs.cpio" KCPPFLAGS=-DCONFIG_BLK_DEV_INITRD
看看rdinit和root在内核中是如何被处理的,如果bootargs设置了rdinit和root,那么内核在启动阶段解析并分别赋给ramdisk_execute_command和saved_root_name。
在后面分析内核启动的过程中,这两个重要的参数会被用到。
static int __init rdinit_setup(char *str)
{
unsigned int i;
ramdisk_execute_command = str;--------------------------------此例中ramdisk_execute_command对应/sbin/init。
/* See "auto" comment in init_setup */
for (i = 1; i < MAX_INIT_ARGS; i++)
argv_init[i] = NULL;
return 1;
}
__setup("rdinit=", rdinit_setup);
static int __init root_dev_setup(char *line)
{
strlcpy(saved_root_name, line, sizeof(saved_root_name));------saved_root_name对应/dev/ram0。
return 1;
}
__setup("root=", root_dev_setup);
2. ramdisk存放在哪里?
从vmlinux.lds.h文件可知,ramfs根据CONFIG_BLK_DEV_INITRD定义是否使用。
INIT_RAM_FS存放ramfs相关内容,包括.init.ramfs和.init.ramfs.info两个段。
SECTIONS { . = PAGE_OFFSET + PHYS_OFFSET_OFFSET; _stext = .; __init_begin = .; ... INIT_DATA_SECTION(PAGE_SIZE) ... . = ALIGN(PAGE_SIZE); __init_end = .;------------------------------从__init_begin到__init_end部分的空间会在free_initmem()中被释放。 .text : AT(ADDR(.text) - LOAD_OFFSET) { ... } = 0 _etext = .; ... } #define INIT_DATA_SECTION(initsetup_align) .init.data : AT(ADDR(.init.data) - LOAD_OFFSET) { ... INIT_RAM_FS } #ifdef CONFIG_BLK_DEV_INITRD #define INIT_RAM_FS . = ALIGN(4); VMLINUX_SYMBOL(__initramfs_start) = .; KEEP(*(.init.ramfs)) . = ALIGN(8); KEEP(*(.init.ramfs.info)) #else #define INIT_RAM_FS #endif
.init.ramfs和.init.ramfs.info两个段在initramfs_data.S中定义。
.section .init.ramfs,"a" __irf_start: .incbin __stringify(INITRAMFS_IMAGE)------------------原封不动的将INITRAMFS_IMAGE对应的二进制文件编译到当前文件中。 __irf_end: .section .init.ramfs.info,"a" .globl VMLINUX_SYMBOL(__initramfs_size) VMLINUX_SYMBOL(__initramfs_size): #ifdef CONFIG_64BIT .quad __irf_end - __irf_start #else .long __irf_end - __irf_start #endif
INITRAMFS_IMAGE从哪里来?需要查看/usr/目录下Makefile。
从Makefile中可知,以CONFIG_INITRAMFS_SOURCE对应的rootfs.cpio文件作为输入,调用gen_init_cpio和gen_initramfs_list.sh生成initramfs_data.cpio.gz文件。
然后INITRAMFS_IMAGE对应,/usr/initramfs_data.cpio$(suffix_y)文件。
最终通过.incbin将INITRAMFS_IMAGE编译到initramfs_data.o文件中,即对应.init.ramfs段。
800308cc T __security_initcall_start
800308d0 T __initramfs_start
800308d0 t __irf_start---------------------------ramfs区域起始地址。
800308d0 T __security_initcall_end
814ed9c0 T __initramfs_size----------------------ramfs文件大小。
814ed9c0 t __irf_end-----------------------------ramfs区域结束地址。
814ee000 T __init_end
3. ramdisk如何启动?
ramfs作为init数据的一部分,位于__init_begin和__init_end的末端,在free_initmem()中被释放。
ramfs是以压缩包的形式存放在__initramfs_start和__initramfs_size之间,在kernel_init()-->kernel_init_freeable()-->do_basic_setup()-->populate_rootfs()中调用unpack_to_rootfs()中解压。
kernel_init() -->kernel_init_freeable()-------------------------------在执行完do_basic_setup(),即完成各种initcall之后,判断ramdisk_execute_command命令。
-->free_initmem()---------------------------------------释放__init_begin到__init_end之间的内存。
-->do_basic_setup()
-->populate_rootfs()---------------------------------解压__initramfs_start包含的ramdisk到rootfs中。
-->run_init_process(ramdisk_execute_command)------------执行ramdisk_execute_command命令替代当前进程。
3.1 initrd_start和initrd_end解析
在start_kernel()之前,从dts中解析出initrd和root相关参数。
调用early_init_dt_scan()-->early_init_dt_scan_nodes-->early_init_dt_scan_nodes():
void __init early_init_dt_scan_nodes(void) { /* Retrieve various information from the /chosen node */ of_scan_flat_dt(early_init_dt_scan_chosen, boot_command_line); ... } int __init early_init_dt_scan_chosen(unsigned long node, const char *uname, int depth, void *data) { ... early_init_dt_check_for_initrd(node); ... } static void __init early_init_dt_check_for_initrd(unsigned long node) { u64 start, end; int len; const __be32 *prop; pr_debug("Looking for initrd properties... "); prop = of_get_flat_dt_prop(node, "linux,initrd-start", &len); if (!prop) return; start = of_read_number(prop, len/4); prop = of_get_flat_dt_prop(node, "linux,initrd-end", &len); if (!prop) return; end = of_read_number(prop, len/4); __early_init_dt_declare_initrd(start, end); pr_debug("initrd_start=0x%llx initrd_end=0x%llx ", (unsigned long long)start, (unsigned long long)end); }
关于initrd_start和initrd_end,从early_init_dt_check_for_initrd()可知,如果dts中没有设置"linux,initrd-start"和"linux,initrd-end",那么initrd_start和initrd_end这两个参数都是原始值0。
#ifdef CONFIG_BLK_DEV_INITRD #ifndef __early_init_dt_declare_initrd static void __early_init_dt_declare_initrd(unsigned long start, unsigned long end) { initrd_start = (unsigned long)__va(start); initrd_end = (unsigned long)__va(end); initrd_below_start_ok = 1; } #endif
3.2 rootfs和ramfs文件系统
rootfs其实不是一种实际的文件系统,他根据实际情况可能使用ramfs或者tmpfs。
这里分析rootfs是如何对应ramfs,并且简单介绍ramfs。
3.2.1 rootfs文件系统
在start_kernel()-->vfs_caches_init()-->mnt_init()中,注册rootfs类型的文件系统。
void __init mnt_init(void) { ... fs_kobj = kobject_create_and_add("fs", NULL); if (!fs_kobj) printk(KERN_WARNING "%s: kobj create error ", __func__); init_rootfs(); init_mount_tree(); } int __init init_rootfs(void) { int err = register_filesystem(&rootfs_fs_type); if (err) return err; if (IS_ENABLED(CONFIG_TMPFS) && !saved_root_name[0] && (!root_fs_names || strstr(root_fs_names, "tmpfs"))) {---------没有指定saved_root_name并且root_fs_names为tmpfs时候,初始化tmpfs文件系统。 err = shmem_init();-------------------------------------------初始化tmpfs文件系统。 is_tmpfs = true;----------------------------------------------后面rootfs_mount()会需要判断是使用tmpfs还是ramfs作为文件系统类型。 } else { err = init_ramfs_fs();----------------------------------------初始化ramfs文件系统。 } ... } static void __init init_mount_tree(void) { struct vfsmount *mnt; struct mnt_namespace *ns; struct path root; struct file_system_type *type; type = get_fs_type("rootfs");-------------------------------------获取rootfs对应的file_system_type,这里对应的是ramfs操作函数。 if (!type) panic("Can't find rootfs type"); mnt = vfs_kern_mount(type, 0, "rootfs", NULL);--------------------这里会调用mount_fs(),进而调用rootfs_fs_type->mount(),即rootfs_mount()。 put_filesystem(type); if (IS_ERR(mnt)) panic("Can't create rootfs"); ns = create_mnt_ns(mnt); if (IS_ERR(ns)) panic("Can't allocate initial namespace"); init_task.nsproxy->mnt_ns = ns; get_mnt_ns(ns); root.mnt = mnt; root.dentry = mnt->mnt_root; mnt->mnt_flags |= MNT_LOCKED; set_fs_pwd(current->fs, &root); set_fs_root(current->fs, &root); }
下面来看看rootfs文件系统是如何挂载的?rootfs没有自己的固定类型,或者使用ramfs或者使用tmpfs。
static bool is_tmpfs; static struct dentry *rootfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { static unsigned long once; void *fill = ramfs_fill_super; if (test_and_set_bit(0, &once)) return ERR_PTR(-ENODEV); if (IS_ENABLED(CONFIG_TMPFS) && is_tmpfs) fill = shmem_fill_super; return mount_nodev(fs_type, flags, data, fill);--------------这里的fill究竟用的是ramfs还是tmpfs,在init_roofs()中已经决定。 } static struct file_system_type rootfs_fs_type = { .name = "rootfs", .mount = rootfs_mount, .kill_sb = kill_litter_super, }; struct dentry *mount_nodev(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { int error; struct super_block *s = sget(fs_type, NULL, set_anon_super, flags, NULL); if (IS_ERR(s)) return ERR_CAST(s); error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);------调用ramfs_fill_super()或者shmem_fill_super()。 if (error) { deactivate_locked_super(s); return ERR_PTR(error); } s->s_flags |= MS_ACTIVE; return dget(s->s_root); } int ramfs_fill_super(struct super_block *sb, void *data, int silent) { struct ramfs_fs_info *fsi; struct inode *inode; int err; save_mount_options(sb, data); fsi = kzalloc(sizeof(struct ramfs_fs_info), GFP_KERNEL); sb->s_fs_info = fsi; if (!fsi) return -ENOMEM; err = ramfs_parse_options(data, &fsi->mount_opts); if (err) return err; sb->s_maxbytes = MAX_LFS_FILESIZE; sb->s_blocksize = PAGE_SIZE; sb->s_blocksize_bits = PAGE_SHIFT; sb->s_magic = RAMFS_MAGIC; sb->s_op = &ramfs_ops;--------------------------rootfs最终使用的还是ramfs文件系统类型的操作函数,如果是tmpfs则使用shmem_ops。 sb->s_time_gran = 1; inode = ramfs_get_inode(sb, NULL, S_IFDIR | fsi->mount_opts.mode, 0); sb->s_root = d_make_root(inode);-----------------------创建根节点"/"。 if (!sb->s_root) return -ENOMEM; return 0; } struct dentry *d_make_root(struct inode *root_inode) { struct dentry *res = NULL; if (root_inode) { res = __d_alloc(root_inode->i_sb, NULL);-----------在name参数为NULL的时候,即创建根节点"/"。 if (res) d_instantiate(res, root_inode); else iput(root_inode); } return res; }
综上所述,在内核启动是init_rootfs()首先根据参数来确定是使用tmpfs还是ramfs,然后在init_mount_tree()进行挂载。
3.2.2 ramfs文件系统
ramfs根据请求的mode类型选择合适的inode或者file操作类型。
struct inode *ramfs_get_inode(struct super_block *sb, const struct inode *dir, umode_t mode, dev_t dev) { struct inode * inode = new_inode(sb); printk("lubaoquan %s line=%d ", __func__, __LINE__); if (inode) { inode->i_ino = get_next_ino(); inode_init_owner(inode, dir, mode); inode->i_mapping->a_ops = &ramfs_aops; mapping_set_gfp_mask(inode->i_mapping, GFP_HIGHUSER); mapping_set_unevictable(inode->i_mapping); inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode); switch (mode & S_IFMT) { default: init_special_inode(inode, mode, dev);---------------------处理char、block、pipefifo等类型的文件。 break; case S_IFREG:-------------------------------------------------处理普通文件。 inode->i_op = &ramfs_file_inode_operations; inode->i_fop = &ramfs_file_operations; break; case S_IFDIR:-------------------------------------------------处理目录。 inode->i_op = &ramfs_dir_inode_operations; inode->i_fop = &simple_dir_operations; /* directory inodes start off with i_nlink == 2 (for "." entry) */ inc_nlink(inode); break; case S_IFLNK:-------------------------------------------------处理link文件。 inode->i_op = &page_symlink_inode_operations; inode_nohighmem(inode); break; } } return inode; } void init_special_inode(struct inode *inode, umode_t mode, dev_t rdev) { inode->i_mode = mode; if (S_ISCHR(mode)) { inode->i_fop = &def_chr_fops; inode->i_rdev = rdev; } else if (S_ISBLK(mode)) { inode->i_fop = &def_blk_fops; inode->i_rdev = rdev; } else if (S_ISFIFO(mode)) inode->i_fop = &pipefifo_fops; else if (S_ISSOCK(mode)) ; /* leave it no_open_fops */ else printk(KERN_DEBUG "init_special_inode: bogus i_mode (%o) for" " inode %s:%lu ", mode, inode->i_sb->s_id, inode->i_ino); } const struct file_operations ramfs_file_operations = { .read_iter = generic_file_read_iter, .write_iter = generic_file_write_iter, .mmap = generic_file_mmap, .fsync = noop_fsync, .splice_read = generic_file_splice_read, .splice_write = iter_file_splice_write, .llseek = generic_file_llseek, .get_unmapped_area = ramfs_mmu_get_unmapped_area, }; const struct inode_operations ramfs_file_inode_operations = { .setattr = simple_setattr, .getattr = simple_getattr, }; static const struct inode_operations ramfs_dir_inode_operations = { .create = ramfs_create, .lookup = simple_lookup, .link = simple_link, .unlink = simple_unlink, .symlink = ramfs_symlink, .mkdir = ramfs_mkdir, .rmdir = simple_rmdir, .mknod = ramfs_mknod, .rename = simple_rename, }; const struct inode_operations page_symlink_inode_operations = { .readlink = generic_readlink, .get_link = page_get_link, };
根据inode->i_mode不同类型,采取不同inode->i_fop和inode->i_op。
3.3 rootfs_initcall()在内核中的调用次序
所有的initcall在start_kernel()-->reset_init()-->kernel_init()-->kernel_init_freeable()-->do_basic_setup()中依次调用initcall。
其中rootfs_initcall()在fs_initcall()之后,在device_initcall()之前。
#define fs_initcall(fn) __define_initcall(fn, 5) #define fs_initcall_sync(fn) __define_initcall(fn, 5s) #define rootfs_initcall(fn) __define_initcall(fn, rootfs) #define device_initcall(fn) __define_initcall(fn, 6) #define device_initcall_sync(fn) __define_initcall(fn, 6s)
3.4 ramfs的解压
rootfs_initcall()在没有定义CONFIG_BLK_DEV_INITRD的情况下,调用default_rootfs()。
default_rootfs()主要生成两个目录/dev和/root,以及一个设备文件/dev/console。
static int __init default_rootfs(void) { int err; err = sys_mkdir((const char __user __force *) "/dev", 0755); if (err < 0) goto out; err = sys_mknod((const char __user __force *) "/dev/console", S_IFCHR | S_IRUSR | S_IWUSR, new_encode_dev(MKDEV(5, 1))); if (err < 0) goto out; err = sys_mkdir((const char __user __force *) "/root", 0700); if (err < 0) goto out; return 0; out: printk(KERN_WARNING "Failed to create a rootfs "); return err; }
在定义CONFIG_BLK_DEV_INITRD的情况下,调用populate_rootfs()将ramdisk解压到RAM中。
unpack_to_rootfs()根据参数__initramfs_start和__initramfs_size,从头部获取decompress的类型;然后调用decompress_fn进行解压缩。
static int __init populate_rootfs(void) { char *err = unpack_to_rootfs(__initramfs_start, __initramfs_size);
if (err) panic("%s", err); /* Failed to decompress INTERNAL initramfs */ if (initrd_start) {---------------------------------------------判断是否特别指定了initrd_start。如果指定,就对initrd进行单独处理。 #ifdef CONFIG_BLK_DEV_RAM int fd; printk(KERN_INFO "Trying to unpack rootfs image as initramfs... "); err = unpack_to_rootfs((char *)initrd_start, initrd_end - initrd_start);-----------------------------判断加载的是不是initramfs CPIO文件。 if (!err) { free_initrd();------------------------------------------如果解压成功,释放image中initrd对应内存。 goto done; } else { clean_rootfs(); unpack_to_rootfs(__initramfs_start, __initramfs_size);--可能是initrd文件。 } printk(KERN_INFO "rootfs image is not initramfs (%s)" "; looks like an initrd ", err); fd = sys_open("/initrd.image", O_WRONLY|O_CREAT, 0700);--------------------------创建文件/initrd.image。 if (fd >= 0) { ssize_t written = xwrite(fd, (char *)initrd_start, initrd_end - initrd_start);-----------------将intird_start到initrd_end内容保存到/initrd.image文件中。 if (written != initrd_end - initrd_start) pr_err("/initrd.image: incomplete write (%zd != %ld) ", written, initrd_end - initrd_start); sys_close(fd); free_initrd();------------------------------------------关闭文件并释放image中initrd对应内存。 } done: #else printk(KERN_INFO "Unpacking initramfs... "); err = unpack_to_rootfs((char *)initrd_start, initrd_end - initrd_start); if (err) printk(KERN_EMERG "Initramfs unpacking failed: %s ", err); free_initrd(); #endif load_default_modules(); } return 0; } static char * __init unpack_to_rootfs(char *buf, unsigned long len) { long written; decompress_fn decompress; const char *compress_name; static __initdata char msg_buf[64]; header_buf = kmalloc(110, GFP_KERNEL); symlink_buf = kmalloc(PATH_MAX + N_ALIGN(PATH_MAX) + 1, GFP_KERNEL); name_buf = kmalloc(N_ALIGN(PATH_MAX), GFP_KERNEL); if (!header_buf || !symlink_buf || !name_buf) panic("can't allocate buffers"); state = Start; this_header = 0; message = NULL; while (!message && len) { ... decompress = decompress_method(buf, len, &compress_name);------根据buf的第1、2个字节的magic来判断decompress类型。比如这里对应gzip,所以返回值decompress及对应gunzip()。 pr_debug("Detected %s compressed data ", compress_name); if (decompress) { int res = decompress(buf, len, NULL, flush_buffer, NULL, &my_inptr, error); if (res) error("decompressor failed"); } else if (compress_name) { ... } else error("junk in compressed archive"); if (state != Reset) error("junk in compressed archive"); this_header = saved_offset + my_inptr; buf += my_inptr; len -= my_inptr; } dir_utime(); kfree(name_buf); kfree(symlink_buf); kfree(header_buf); return message; }
3.4.1 decompressor
内核中支持的decompressor用struct compress_format表示,核心是decompress_fn()函数。
struct compress_format { unsigned char magic[2]; const char *name; decompress_fn decompressor; }; typedef int (*decompress_fn) (unsigned char *inbuf, long len, long (*fill)(void*, unsigned long), long (*flush)(void*, unsigned long), unsigned char *outbuf, long *posp, void(*error)(char *x)); /* inbuf - input buffer *len - len of pre-read data in inbuf *fill - function to fill inbuf when empty *flush - function to write out outbuf *outbuf - output buffer *posp - if non-null, input position (number of bytes read) will be * returned here
decompress_method根据传入的inbuf头部两字节来判断对应空间所采取的decompressor。
decompressed_formats[]保存了系统支持的decompressor类型。
static const struct compress_format compressed_formats[] __initconst = { { {0x1f, 0x8b}, "gzip", gunzip }, { {0x1f, 0x9e}, "gzip", gunzip }, { {0x42, 0x5a}, "bzip2", bunzip2 }, { {0x5d, 0x00}, "lzma", unlzma }, { {0xfd, 0x37}, "xz", unxz }, { {0x89, 0x4c}, "lzo", unlzo }, { {0x02, 0x21}, "lz4", unlz4 }, { {0, 0}, NULL, NULL } }; decompress_fn __init decompress_method(const unsigned char *inbuf, long len, const char **name) { ... pr_debug("Compressed data magic: %#.2x %#.2x ", inbuf[0], inbuf[1]); for (cf = compressed_formats; cf->name; cf++) { if (!memcmp(inbuf, cf->magic, 2))------------------------遍历compressed_formats[]知道找到吻合的magic作为后续ramfs解压工具。 break; } if (name) *name = cf->name; return cf->decompressor; }
gzip类型对应的decompres_fn()为gunzip,这里不深入研究,但是入参flush()函数跟ramfs密切相关。
STATIC int INIT gunzip(unsigned char *buf, long len, long (*fill)(void*, unsigned long), long (*flush)(void*, unsigned long), unsigned char *out_buf, long *pos, void (*error)(char *x)) { return __gunzip(buf, len, fill, flush, out_buf, 0, pos, error); } STATIC int INIT __gunzip(unsigned char *buf, long len, long (*fill)(void*, unsigned long), long (*flush)(void*, unsigned long), unsigned char *out_buf, long out_len, long *pos, void(*error)(char *x)) { u8 *zbuf; struct z_stream_s *strm; int rc; rc = -1; if (flush) { out_len = 0x8000; /* 32 K */ out_buf = malloc(out_len);-----------------------以32K为单位进行处理。 } else { if (!out_len) out_len = ((size_t)~0) - (size_t)out_buf; /* no limit */ } ... while (rc == Z_OK) { ... rc = zlib_inflate(strm, 0); /* Write any data generated */ if (flush && strm->next_out > out_buf) { long l = strm->next_out - out_buf; if (l != flush(out_buf, l)) {-----------------将解压后的数据刷出,这里即调用flush_buffer()进行处理。 rc = -1; error("write error"); break; } strm->next_out = out_buf; strm->avail_out = out_len; } /* after Z_FINISH, only Z_STREAM_END is "we unpacked it all" */ if (rc == Z_STREAM_END) { rc = 0; break; } else if (rc != Z_OK) { error("uncompression error"); rc = -1; } } zlib_inflateEnd(strm); if (pos) /* add + 8 to skip over trailer */ *pos = strm->next_in - zbuf+8; gunzip_5: free(strm->workspace); gunzip_nomem4: free(strm); gunzip_nomem3: if (!buf) free(zbuf); gunzip_nomem2: if (flush) free(out_buf); gunzip_nomem1: return rc; /* returns Z_OK (0) if successful */ }
3.4.2 flush_buffer
由以上分析可知rootfs采用了ramfs文件系统类型。
ramfs部分通过gzip进行解压缩,然后将解压的内容通过flush_buffer刷出。
下面就来看看flush_buffer()是如何将__initramfs_start开始__initramfs_size大小的内存刷成rootfs文件系统的。
flush_buffer()调用write_buffer进行处理,这里一个核心是通过不同状态机state调用不同actions[state]进行处理。
static long __init write_buffer(char *buf, unsigned long len) { byte_count = len; victim = buf; while (!actions[state]()) ; return len - byte_count; } static long __init flush_buffer(void *bufv, unsigned long len) { char *buf = (char *) bufv; long written; long origLen = len; if (message) return -1; while ((written = write_buffer(buf, len)) < len && !message) { ... } return origLen; }
actions[]可以说是将解压后数据转换并生成rootfs的核心。
actions[]调用相应的系统调用,按照解压数据一步一步生成整个文件系统。
static __initdata int (*actions[])(void) = { [Start] = do_start, [Collect] = do_collect, [GotHeader] = do_header, [SkipIt] = do_skip, [GotName] = do_name, [CopyFile] = do_copy, [GotSymlink] = do_symlink, [Reset] = do_reset, }; static int __init do_start(void) { read_into(header_buf, 110, GotHeader);----------------------读取开头110字节,用于解析cpio文件头。 return 0; } static int __init do_collect(void) { unsigned long n = remains; if (byte_count < n) n = byte_count; memcpy(collect, victim, n); eat(n); collect += n; if ((remains -= n) != 0) return 1; state = next_state; return 0; } static int __init do_header(void) { if (memcmp(collected, "070707", 6)==0) {---------------------cpio文件的magic,开头6个字节“070707”或者“070701”。 error("incorrect cpio method used: use -H newc option"); return 1; } if (memcmp(collected, "070701", 6)) { error("no cpio magic"); return 1; } parse_header(collected); next_header = this_header + N_ALIGN(name_len) + body_len; next_header = (next_header + 3) & ~3; state = SkipIt; if (name_len <= 0 || name_len > PATH_MAX) return 0; if (S_ISLNK(mode)) { if (body_len > PATH_MAX) return 0; collect = collected = symlink_buf; remains = N_ALIGN(name_len) + body_len; next_state = GotSymlink; state = Collect; return 0; } if (S_ISREG(mode) || !body_len) read_into(name_buf, N_ALIGN(name_len), GotName); return 0; } static int __init do_skip(void) { if (this_header + byte_count < next_header) { eat(byte_count); return 1; } else { eat(next_header - this_header); state = next_state; return 0; } } static int __init do_reset(void) { while (byte_count && *victim == '