Files Implementation

// fs/read_write.c int sys_write(int fd, const char* buf, int count) { struct file *file = current->filp[fd]; struct m_inode *inode = file->inode; if(S_ISREG(inode->i_mode)) return file_write(inode, file, buf, count); }
notion image
  1. 需要知道是哪段字符,file中一个读写指针是开始地址,可以通过fseek修改;
  1. 通过inode找到对应的盘块号;
  1. 用盘块号、buf等形成request放入电梯算法
notion image
int file_write(struct m_inode *inode, struct file *filp, char *buf, int count) { off_t pos; if(filp->f_flags&O_APPEND) pos=inode->i_size; else pos=filp->f_pos; // ...
while(i<count){ block=create_block(inode, pos/BLOCK_SIZE); bh=bread(inode->i_dev, block); int c=pos%BLOCK_SIZE; char *p=c+bh->b_data; bh->b_dirt=1; c=BLOCK_SIZE-c; pos+=c; ... while(c-->0) *(p++)=get_fs_byte(buf++); brelse(bh); } filp->f_pos=pos;
int _bmap(m_inode *inode, int block, int create) { if(block<7){ if(create&&!inode->i_zone[block]) { inode->i_zone[block]=new_block(inode->i_dev); inode->i_ctime=CURRENT_TIME; inode->i_dirt=1; } return inode->i_zone[block]; } block-=7; if(block<512){ bh=bread(inode->i_dev,inode->i_zone[7]); return (bh->b_data)[block]; } // ... }
struct d_inode{ unsigned short i_mode; // ... unsigned short i_zone[9]; //(0-6):直接数据块,(7):一重间接,(8):二重间接 }
struct m_inode{ //读入内存后的inode unsigned short i_mode; //文件的类型和属性 ... unsigned short i_zone[9]; //指向文件内容数据块 struct task_struct *i_wait; unsigned short i_count; unsigned char i_lock; unsigned char i_dirt; //... }
int sys_open(const char* filename, int flag) { if(S_ISCHR(inode->i_mode)){ //字符设备 if(MAJOR(inode->i_zone[0])==4) //设备文件 current->tty=MINOR(inode->i_zone[0]); }
#define MAJOR(a)(((unsigned)(a))>>8)) //取高字节 #define MINOR(a)((a)&0xff) //取低字节