1.blk_dev.c
1 /*
2 * linux/fs/block_dev.c
3 *
4 * (C) 1991 Linus Torvalds
5 */
6
7 #include <errno.h>
9 #include <linux/sched.h>
10 #include <linux/kernel.h>
11 #include <asm/segment.h>
12 #include <asm/system.h>
14 int block_write(int dev, long * pos, char * buf, int count) //其中pos中保存的是要写入的磁盘地址
15 {
16 int block = *pos >> BLOCK_SIZE_BITS;
17 int offset = *pos & (BLOCK_SIZE-1);
计算块号和偏移
18 int chars; //要写的数
19 int written = 0; //已经写的数
20 struct buffer_head * bh;
21 register char * p;
23 while (count>0) {
24 chars = BLOCK_SIZE - offset;
25 if (chars > count)
26 chars=count;
27 if (chars == BLOCK_SIZE) //如果要写的数正好是一个块
28 bh = getblk(dev,block); //读取这个块
29 else
30 bh = breada(dev,block,block+1,block+2,-1); //预读取
31 block++;
为下次写入做准备
32 if (!bh)
33 return written?written:-EIO;
32 if (!bh)
33 return written?written:-EIO;
34 p = offset + bh->b_data;
计算写入数据的起始地址
35 offset = 0;
36 *pos += chars;
36 *pos += chars;
更新pos位置
37 written += chars;
//更新已写数据量
38 count -= chars; //更新还需写入数据量
39 while (chars-->0)
40 *(p++) = get_fs_byte(buf++);
38 count -= chars; //更新还需写入数据量
39 while (chars-->0)
40 *(p++) = get_fs_byte(buf++);
从用户空间buf中读取数据写入到p开始的地址处,一共写入chars字节
41 bh->b_dirt = 1; //标记为脏
42 brelse(bh);
43 }
44 return written;
45 }
42 brelse(bh);
43 }
44 return written;
45 }
47 int block_read(int dev, unsigned long * pos, char * buf, int count)
48 {
49 int block = *pos >> BLOCK_SIZE_BITS;
50 int offset = *pos & (BLOCK_SIZE-1);
48 {
49 int block = *pos >> BLOCK_SIZE_BITS;
50 int offset = *pos & (BLOCK_SIZE-1);
51 int chars;
52 int read = 0;
53 struct buffer_head * bh;
54 register char * p;
55
56 while (count>0) {
57 chars = BLOCK_SIZE-offset;
58 if (chars > count)
59 chars = count;
60 if (!(bh = breada(dev,block,