SimpleFs文件系統初步二(測試用的塊設備構建)

1.首先打開我們通過dd命令生成的image文件

fd = open(argv[1], O_RDWR);

2.寫超級塊

write_superblock(fd)

我們詳細看看超級塊是怎麼去寫的

static int write_superblock(int fd)
{
	struct simplefs_super_block sb = {
		.version = 1,
		.magic = SIMPLEFS_MAGIC,
		.block_size = SIMPLEFS_DEFAULT_BLOCK_SIZE,
		/* One inode for rootdirectory and another for a welcome file that we are going to create */
		.inodes_count = 2,
		/* FIXME: Free blocks management is not implemented yet */
		.free_blocks = (~0) & ~(1 << WELCOMEFILE_DATABLOCK_NUMBER),
	};
	ssize_t ret;

	ret = write(fd, &sb, sizeof(sb));
	if (ret != SIMPLEFS_DEFAULT_BLOCK_SIZE) {
		printf
		    ("bytes written [%d] are not equal to the default block size\n",
		     (int)ret);
		return -1;
	}

	printf("Super block written succesfully\n");
	return 0;
}

Look,很簡單,直接向塊設備寫入simplefs_super_block 結構的數據即可,當前的超級塊的版本爲1,魔數,每個數據塊的大小爲4K,inode的個數爲2,當前空閒的數據塊。

3.寫入根節點

static int write_inode_store(int fd)
{
	ssize_t ret;

	struct simplefs_inode root_inode;

	root_inode.mode = S_IFDIR;
	root_inode.inode_no = SIMPLEFS_ROOTDIR_INODE_NUMBER;
	root_inode.data_block_number = SIMPLEFS_ROOTDIR_DATABLOCK_NUMBER;
	root_inode.dir_children_count = 1;

	ret = write(fd, &root_inode, sizeof(root_inode));

	if (ret != sizeof(root_inode)) {
		printf
		    ("The inode store was not written properly. Retry your mkfs\n");
		return -1;
	}

	printf("root directory inode written succesfully\n");
	return 0;
}

緊跟在super block後面的就是root inode,這個inode是一個目錄,在linux中dentry本身也是一個特殊的inode,我們將這個特殊的inode的inode號設置爲了1,同時這個inode存放在data block的bitmap中的第二個。另外在根denty的下面還有一個文件。

4.在根dentry下面的這個文件是,我們現在對這個文件進行寫入

struct simplefs_inode welcome = {
	.mode = S_IFREG,
	.inode_no = WELCOMEFILE_INODE_NUMBER,
	.data_block_number = WELCOMEFILE_DATABLOCK_NUMBER,
	.file_size = sizeof(welcomefile_body),
};

write_inode(fd, &welcome)

write_inode的實現如下:

static int write_inode(int fd, const struct simplefs_inode *i)
{
	off_t nbytes;
	ssize_t ret;

	ret = write(fd, i, sizeof(*i));
	if (ret != sizeof(*i)) {
		printf
		    ("The welcomefile inode was not written properly. Retry your mkfs\n");
		return -1;
	}
	printf("welcomefile inode written succesfully\n");

	nbytes = SIMPLEFS_DEFAULT_BLOCK_SIZE - sizeof(*i) - sizeof(*i);
	ret = lseek(fd, nbytes, SEEK_CUR);
	if (ret == (off_t)-1) {
		printf
		    ("The padding bytes are not written properly. Retry your mkfs\n");
		return -1;
	}

	printf
	    ("inode store padding bytes (after the two inodes) written sucessfully\n");
	return 0;
}

上述代碼首先寫入了一個inode,然後對齊4K的邊界;

5.寫dentry裏面的內容

struct simplefs_dir_record record = {
	.filename = "vanakkam",
	.inode_no = WELCOMEFILE_INODE_NUMBER,
};
write_dirent(fd, &record)

也就是說在根dentry的下面記錄着如下信息
文件名:“vanakkam”
對應的inode號是:2
也就是上面第4步對應的普通文件

6.對這個普通文件寫入內容

char welcomefile_body[] = “Love is God. God is Love. Anbe Murugan.\n”;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章