文件系统(三) --block_dev.c file_dev.c char_dev.c源码分析

本文档详细分析了Linux内核中的文件系统部分,涵盖blk_dev.c、file_dev.c和char_dev.c三个关键模块的源码。从block_write函数入手,探讨了在不同设备上进行数据读写的实现细节,涉及磁盘地址计算、缓冲区管理和设备交互等核心概念。
摘要由CSDN通过智能技术生成

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;
 
 34         p = offset + bh->b_data;
计算写入数据的起始地址
 35         offset = 0;
 36         *pos += chars;
更新pos位置
 37         written += chars;     //更新已写数据量
 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 }


 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);

 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,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值