435
Linux1.0 核心游记 Email:[email protected] QQ:251665710(欢迎讨论) 1

read.pudn.comread.pudn.com/downloads116/ebook/494653/Linux1.0.pdf · Linux1.0 核心游记 内容简介 本书以Linux 1.0核心为基础,详细注释了从开机启动到其正常运转的全过程,并且还

  • Upload
    others

  • View
    27

  • Download
    0

Embed Size (px)

Citation preview

  • Linux1.0 核心游记

    Email:[email protected] QQ:251665710(欢迎讨论)

    1

  • Linux1.0 核心游记

    内容简介 本书以 Linux 1.0 核心为基础,详细注释了从开机启动到其正常运转的全过程,并且还

    给出了理解这个过程所需要的基础知识。 本书适合于所有 Linux 操作系统的爱好者。

    Email:[email protected] QQ:251665710(欢迎讨论)

    2

  • Linux1.0 核心游记

    前言

    献给和我一样的计算机菜鸟们

    献给和我一样的 Linux 爱好者们

    为中国的 Linux 事业做点微薄的贡献

    先谈一谈我个人的学习经历,为初学者打气(当然我还是菜鸟)。学习核心并不需要高学历,高智商,只要勤奋。正所谓世上无难事,只怕有心人。

    我从 99 年 9 月份开始接触计算机(大一),到现在算起来也有好几个年头了。至今还记得第一次上电脑课闹出的笑话(因为我们是非计算机专业的,以前根本没有接触过它,只是

    听过)。那就是进入机房后看到一位同学在键盘上劈里啪啦的胡乱的敲击着。我忍不住的问

    了一句,键盘麻手吗(谓之带电吗)。引起全班哄堂大笑。 当时班上有位同学(后来才知道,他哥是学计算机的)懂点 DOS 命令(被我们奉若神

    明,同学们常买东西犒劳他,因为要玩游戏),也不知道从那搞来的“超级马力”的游戏(也

    就是这个游戏,我们才觉得上电脑课才有点意思)。只有他懂的如何运行该游戏!说到这大

    家可能有点不信,都 99 年了,还用什么 DOS 命令啊!唉!谁叫咱们是非计算机专业的,我们只能用用 DOS 和 WPS(计算机课都成了打字课了,可惜我到最后还是没有把五笔的字根背下来),装有 Windows98 的机器只能给计算机专业的用,除非自己花钱买票上机。(不过,现在想起来应该给我们用才对啊!真不知道学校老师是怎么想的) 我们学的是编程语言是 True Basic(第一节课,老师就说了句打击我们的话:“这种语言早就被淘汰了 10 年以上了”,以致到该门课程结束后大家都不知道学了什么,稀里糊涂考完试了事,因为同学们学的都没有兴趣了!淘汰 10 年的东西还有什么好学的。老师的这句实在话现在看来还真的是“误人子弟”)。我学了半学期下来,感觉什么都不会。于是开始去

    机房揩油(趁人家有上机课时,偷偷溜进机房,也有被撵出来的时候)。到最后还是什么都

    不会,就是打字速度稍微快了点。 到了 2000 年,新学期开学的时候,我们系里买了 20 台左右的电脑(现在我还记得配置:CPU C433,内存 64M,显卡 8M),开始教授 AutoCAD 课程。这个时候我也在考虑我毕业后所要从事的职业了(该玩的我大一已经玩了,所以建议过了大一后,各位兄弟姐妹们就不

    要玩了吧“考研的高三就不玩了 ☺”。把时间用在学习上,毕业后找工作的好处我深有体会。),第一个想法是肯定不去干机械(因为,在做金工实习时,锯一块铁料已经够我受的了,

    后来才知道真正到厂里不是这样的,厂里有切割工具的,因为后来我们去参观好几个大型机

    械厂的)。于是就萌发了自学计算机的想法,所以我真正开始学习语言的时间是从 2000 年的下半年开始的。买了本谭浩强老师的《C 程序设计》,并做完了和其配套的习题册, 习题册中的每个程序我都调试过(开始用的调试工具是 TC2.0,后来改用 VC6.0。就学习的效率来说我推荐用 VC6.0 来调试,当然现在都已经有 Visual studio .NET 2005 了,调试功能应该更强大了)。就这样搞了半个学期,终于过了语言关。接下来又开始学习严蔚敏,吴伟民两位老

    师的《数据结构(C 语言版)》,并也做了其对应的习题。感觉有些功力了,于是主动给系里做了些小程序(老师教学用的,也为我后来管理系机房铺平了的道路)后来陆续学习了 C++,汇编(不过学的不到位)及 MFC,为了能写个在手机上跑的程序,JAVA 也学了点,

    Email:[email protected] QQ:251665710(欢迎讨论)

    3

  • Linux1.0 核心游记

    因为当时我感觉手机上跑的程序比较好玩,最终用 J2ME 写了个运行在 Nokia 上的《英语900 句》算是结束了,没有坚持下去。(现在想想有点后悔,要是坚持下来多好,手机游戏也是个大产业哦,所以在校的学生可以考虑) 接触 Linux 也是在 2000 年,当时看到网上到处都在讲它。非常好奇(因为,我们学校买了台 Sun 的机器,居然没有老师会配置,“当时的老师咋就没有想到搜索互联网呢?”最后还是从南京某个学校请的人过来配的。那是我第一次看到类 Unix 操作系统,给我的印象是很神秘,不像 Windows 来的直观,不知大家是否也有这个想法)。于是从网络上下载了个Redhat6.2,搞了好几个星期还是安装不了(现在想想搞个虚拟机多简单,那时为什么就想不到呢?也不知道搜索互联网!“当时已经有 Yahoo 了”)。于是决定买张光盘安装(花了 8块钱),可是系里的机器没有光驱,怎么办呢!只好在下课后不走(我说的是晚自习后)。待

    夜深人静的时候偷偷把老师机器的光驱拆了用。就这样搞了一个通宵(这也是我熬过的唯一

    的一个通宵),终于装好了。(不得不说的是,不知是紧张还是什么原因,重新把光驱装回老

    师机器时,居然把电源线给忘接了。露馅了。不过还好老师什么也没有说,只是叫我帮它重

    新装了一下,他知道肯定是我干的。我一直都很感激这个老师,他给我的帮助也比较大,指

    导我该看那些书,偶尔也会请我去吃顿饭。) 写到这我顺便说一说在学校时我和老师的关系(因为我现在看来上学时和老师搞好关系真的是非常重要的)。当时系里的老师对我都蛮照顾的,都认识我。所以有些课我认为可听

    可不听时就不去了(翘课估计每个人都有过吧,不鼓励翘课),他们也自然不会追问了。学

    分照给。其他同学就惨了。重点说一下当时我们机械系的系主任,现在恐怕已经做上副校长

    了。给了我看管系机房的机会,另外每个月还给 200 块的补贴。这个最实际了 ☺―――还在读书的朋友一定要深刻体会这点哦。 为了能够看懂核心,需要的知识非常多,还要深入体会这些知识(以 Intel X86 CPU 来说吧,它分为实模式,保护模式,并且在不同的模式下寻址方式也不同,拿着书看都知道,

    丢了书什么忘了,所以要靠自己体会的)。所以当时学校图书馆关于计算机的书基本都被我

    看我过了(符合要求的),搞到最后图书馆的老师们都认识我了。最高记录是一学期借了 76本书,这还是我们班同学告诉我的。 然后在 2002 年时候开始看核心,前前后后看了很多个版本(很泛的看)。刚开始真的很痛苦,看看停停(我想大部分初学者都有这种感觉,过了这道槛就 ok 了)因为看不懂。核心不像一般的应用程序那样,它和硬件结合的比较紧密(如果是学硬件的人,看核心可能会

    更轻松点)。后来关于核心分析的书籍渐渐多起来了,比如陈莉君的《深入分析 Linux 内核源代码》,也为我读核心提供不小的帮助。到了 2003 年的时候,我在网上看到了赵炯博士的《LINUX 内核完全注释》电子版以及浙江大学毛德操和胡希明的《LINUX 内核源代码情景分析》,才看的快了一点(互联网真是好东西,大家好好利用)。在看了后也就萌发了写点东

    西的想法,于是便有了它。 该书分 3 章:

    第一章为基础知识,概述了理解核心所需要的软件及硬件知识。这也是我们在看核心时,

    首先应需掌握的知识。该章里提到的知识(可能还有其他的重要内容没有加入,如果有要加

    入的可发 mail 给我,谢谢!☺),毫不夸张的说每一个展开来都是一本甚至几本书的内容,在这里我只是给大家做了一个提纲式的总结。省的读者还要先研究这些知识!当然深入的话

    题还得靠大家去查看消化,另外该章中提到的硬件知识有些来源于互联网。 第二章为代码分析,也是本书的主角。从我们给计算机加电启动介绍起,直到核心正常

    运作为止。其中涉及了好多个文件中的函数(有很少数几个的函数,我没有做出注释,还请

    各位见谅。因为我的主业是在 Windows 平台下做开发的“如果能给我个 Linux 平台下开发

    Email:[email protected] QQ:251665710(欢迎讨论)

    4

  • Linux1.0 核心游记

    的机会会更好 ☺”,所以还有其他工作要做。分析只能在晚上做 1 到 2 个小时,因为我不熬夜的 ☺)。我都一一注释,并在调用某个函数时,给出了这个被调用函数的所在的文件位置,从而方便读者查找,为你节省时间。

    第三章为其他的话题,内容比较少,原因可能是我没有在 Linux 下做过开发吧,所以不知道大家需要什么,而我要写些什么(等我买了开发板后,我把嵌入式开发补上,哦我的银

    子啊 )。在其中包括了模块的编写,动态及静态添加修改系统调用,动态及静态函数库

    的编写。

    本书的不足: 目前讲的只是从计算机启动到核心真正运作起来的整个过程。其中并没有涉及到核心中

    数据结构的分析。因为 1.0 太大了,对我个人而言(如果有感兴趣的朋友的话,我们可以一起做分析 ☺)。

    另外在我对代码的注释过程中肯定会犯有不少的错误,也许是用了错别字,也许是对代

    码的理解不正确从而导致错误的注释,等等!读者在发现上述问题后请毫不犹豫的并且毫不

    留情的给我指出来,再次感谢! 你们的朋友 郭大海 2005 年 11 月

    Email:[email protected] QQ:251665710(欢迎讨论)

    5

    mailto:[email protected]

  • Linux1.0 核心游记

    源代码

    本书样例源代码 Linux1.0 核心源代码

    Email:[email protected] QQ:251665710(欢迎讨论)

    6

    Administrator附注“Administrator”设置的“Accepted”

    Code/S1.1-1/Makefile

    #Copyright gotop167#Begin Makefileone:@echo onetwo:@echo twothree:@echo three#End Makefile

    Code/S1.1-2/Makefile

    #Copyright gotop167#Begin MakefileOBJECT=Dogone:@echo one $(OBJECT)tow:@echo two $(OBJECT)sthree:@echo three $(OBJECT)s#End Makefile

    Code/S1.1-3/Makefile

    #Copyright gotop167CC=gccOBJS= a.o b.o

    all:test

    test:a.o b.o$(CC) $(OBJS) -o testclean:rm -f *.o coreclobber:cleanrm -f test

    Code/S1.1-3/a.c

    #includeintmain(void){printf(¡°In main().\n¡±);called(void);return 0;}

    Code/S1.1-3/b.c

    #include void called(void){printf("In called.\n");}

    Code/S2.3-1/Helloworld.s

    #Helloworld.s

    .data msg : .string "Hello, world!\n" len = . - msg

    .text .global _start _start: movl $len, %edx movl $msg, %ecx movl $1, %ebx movl $4, %eax int $0x80 movl $0,%ebx movl $1,%eax int $0x80

    Code/S2.3-1/Makefile

    #Copyright gotop167AS=asLD=ldOBJS=helloworld

    .s.o:$(AS) -o $*.o $<

    all:$(OBJS)

    helloworld:helloworld.o$(LD) -o helloworld helloworld.o

    helloworld.o:helloworld.s

    clean:rm -f *.o coreclobber:cleanrm -f $(OBJS)

    Code/S4.2-1/Makefile

    GCC=gccOBJS=swap

    .c.o:$(GCC) -c -Wall $<

    all:$(OBJS)$(OBJS):swap.o$(GCC) -o $(OBJS) swap.o

    clean:rm -f *.o coreclobber:cleanrm -f $(OBJS)

    Code/S4.2-1/swap.c

    #include intmain(){int iValue = 100;int jValue = 200;printf("\nBefore Swap:a=%d,b=%d\n",iValue,jValue);__asm__("movl (%0),%%eax\n\t" "movl (%1),%%edx\n\t" "movl %%eax,(%1)\n\t" "movl %%edx,(%0)\n\t"::"b"(&iValue),"c"(&jValue));printf("After Swap:a=%d,b=%d\n\n",iValue,jValue);return 0;}

    Code/S5.2-1/Makefile

    GCC=gccOBJS=bug.oCFLAGS = -g

    .c.o:$(GCC) $(CFLAGS) -c $<

    all:$(OBJS)$(GCC) $(OBJS) -o bugclean:rm -f *.o core

    clobber:cleanrm -f bug

    Code/S5.2-1/bug.c

    #include #include

    intmain(void){int scores[10];int sum;int i;int average;

    for(i=0; i tools/version.h@echo \#define LINUX_COMPILE_HOST \"`hostname`\" >> tools/version.h@echo \#define LINUX_COMPILE_DOMAIN \"`domainname`\" >> tools/version.h

    tools/build: tools/build.c $(CONFIGURE)$(HOSTCC) $(CFLAGS) -o $@ $<

    boot/head.o: $(CONFIGURE) boot/head.s

    boot/head.s: boot/head.S $(CONFIGURE) include/linux/tasks.h$(CPP) -traditional $< -o $@

    tools/version.o: tools/version.c tools/version.h

    init/main.o: $(CONFIGURE) init/main.c$(CC) $(CFLAGS) $(PROFILING) -c -o $*.o $<

    tools/system:boot/head.o init/main.o tools/version.o linuxsubdirs$(LD) $(LDFLAGS) -Ttext 1000 boot/head.o init/main.o tools/version.o \$(ARCHIVES) \$(FILESYSTEMS) \$(DRIVERS) \$(LIBS) \-o tools/systemnm tools/zSystem | grep -v '\(compiled\)\|\(\.o$$\)\|\( a \)' | \sort > System.map

    boot/setup: boot/setup.o$(LD86) -s -o $@ $<

    boot/setup.o: boot/setup.s$(AS86) -o $@ $<

    boot/setup.s: boot/setup.S $(CONFIGURE) include/linux/config.h Makefile$(CPP) -traditional $(SVGA_MODE) $(RAMDISK) $< -o $@

    boot/bootsect: boot/bootsect.o$(LD86) -s -o $@ $<

    boot/bootsect.o: boot/bootsect.s$(AS86) -o $@ $<

    boot/bootsect.s: boot/bootsect.S $(CONFIGURE) include/linux/config.h Makefile$(CPP) -traditional $(SVGA_MODE) $(RAMDISK) $< -o $@

    zBoot/zSystem: zBoot/*.c zBoot/*.S tools/zSystem$(MAKE) -C zBoot

    zImage: $(CONFIGURE) boot/bootsect boot/setup zBoot/zSystem tools/buildtools/build boot/bootsect boot/setup zBoot/zSystem $(ROOT_DEV) > zImagesync

    zdisk: zImagedd bs=8192 if=zImage of=/dev/fd0

    zlilo: $(CONFIGURE) zImageif [ -f /vmlinuz ]; then mv /vmlinuz /vmlinuz.old; fiif [ -f /zSystem.map ]; then mv /zSystem.map /zSystem.old; ficat zImage > /vmlinuzcp zSystem.map /if [ -x /sbin/lilo ]; then /sbin/lilo; else /etc/lilo/install; fi

    tools/zSystem:boot/head.o init/main.o tools/version.o linuxsubdirs$(LD) $(LDFLAGS) -Ttext 100000 boot/head.o init/main.o tools/version.o \$(ARCHIVES) \$(FILESYSTEMS) \$(DRIVERS) \$(LIBS) \-o tools/zSystemnm tools/zSystem | grep -v '\(compiled\)\|\(\.o$$\)\|\( a \)' | \sort > zSystem.map

    fs: dummy$(MAKE) linuxsubdirs SUBDIRS=fs

    lib: dummy$(MAKE) linuxsubdirs SUBDIRS=lib

    mm: dummy$(MAKE) linuxsubdirs SUBDIRS=mm

    ipc: dummy$(MAKE) linuxsubdirs SUBDIRS=ipc

    kernel: dummy$(MAKE) linuxsubdirs SUBDIRS=kernel

    drivers: dummy$(MAKE) linuxsubdirs SUBDIRS=drivers

    net: dummy$(MAKE) linuxsubdirs SUBDIRS=net

    clean:rm -f kernel/ksyms.lstrm -f core `find . -name '*.[oas]' -print`rm -f core `find . -name 'core' -print`rm -f zImage zSystem.map tools/zSystem tools/systemrm -f Image System.map boot/bootsect boot/setuprm -f zBoot/zSystem zBoot/xtract zBoot/piggybackrm -f .tmp* drivers/sound/configurerm -f init/*.o tools/build boot/*.o tools/*.o

    mrproper: cleanrm -f include/linux/autoconf.h tools/version.hrm -f drivers/sound/local.hrm -f .version .config* config.oldrm -f .depend `find . -name .depend -print`

    distclean: mrproper

    backup: mrpropercd .. && tar cf - linux | gzip -9 > backup.gzsync

    depend dep:touch tools/version.hfor i in init/*.c;do echo -n "init/";$(CPP) -M $$i;done > .tmpdependfor i in tools/*.c;do echo -n "tools/";$(CPP) -M $$i;done >> .tmpdependset -e; for i in $(SUBDIRS); do $(MAKE) -C $$i dep; donerm -f tools/version.hmv .tmpdepend .depend

    ifdef CONFIGURATION..$(CONFIGURATION):@echo@echo "You have a bad or nonexistent" .$(CONFIGURATION) ": running 'make" $(CONFIGURATION)"'"@echo$(MAKE) $(CONFIGURATION)@echo@echo "Successful. Try re-making (ignore the error that follows)"@echoexit 1

    dummy: ..$(CONFIGURATION)

    else

    dummy:

    endif

    ## Leave these dummy entries for now to tell people that they are going away..#lilo:@echo@echo Uncompressed kernel images no longer supported. Use@echo \"make zlilo\" instead.@echo@exit 1

    Image:@echo@echo Uncompressed kernel images no longer supported. Use@echo \"make zImage\" instead.@echo@exit 1

    disk:@echo@echo Uncompressed kernel images no longer supported. Use@echo \"make zdisk\" instead.@echo@exit 1

    linux/boot/bootsect.S

    !! SYS_SIZE is the number of clicks (16 bytes) to be loaded.! 0x7F00 is 0x7F000 bytes = 508kB, more than enough for current! versions of linux which compress the kernel!#include SYSSIZE = DEF_SYSSIZE!!bootsect.sCopyright (C) 1991, 1992 Linus Torvalds!modified by Drew Eckhardt!modified by Bruce Evans (bde)!! bootsect.s is loaded at 0x7c00 by the bios-startup routines, and moves! itself out of the way to address 0x90000, and jumps there.!! bde - should not jump blindly, there may be systems with only 512K low! memory. Use int 0x12 to get the top of memory, etc.!! It then loads 'setup' directly after itself (0x90200), and the system! at 0x10000, using BIOS interrupts. !! NOTE! currently system is at most (8*65536-4096) bytes long. This should ! be no problem, even in the future. I want to keep it simple. This 508 kB! kernel size should be enough, especially as this doesn't contain the! buffer cache as in minix (and especially now that the kernel is ! compressed :-)!! The loader has been made as simple as possible, and continuos! read errors will result in a unbreakable loop. Reboot by hand. It! loads pretty fast by getting whole tracks at a time whenever possible.

    .text

    SETUPSECS = 4! nr of setup-sectorsBOOTSEG = 0x07C0! original address of boot-sectorINITSEG = DEF_INITSEG! we move boot here - out of the waySETUPSEG = DEF_SETUPSEG! setup starts hereSYSSEG = DEF_SYSSEG! system loaded at 0x10000 (65536).

    ! ROOT_DEV & SWAP_DEV are now written by "build".ROOT_DEV = 0SWAP_DEV = 0#ifndef SVGA_MODE#define SVGA_MODE ASK_VGA#endif#ifndef RAMDISK#define RAMDISK 0#endif #ifndef CONFIG_ROOT_RDONLY#define CONFIG_ROOT_RDONLY 0#endif

    ! ld86 requires an entry symbol. This may as well be the usual one..globl_main_main:#if 0 /* hook for debugger, harmless unless BIOS is fussy (old HP) */int3#endifmovax,#BOOTSEGmovds,axmovax,#INITSEGmoves,axmovcx,#256subsi,sisubdi,dicldrepmovswjmpigo,INITSEG

    go:movax,csmovdx,#0x4000-12! 0x4000 is arbitrary value >= length of! bootsect + length of setup + room for stack! 12 is disk parm size

    ! bde - changed 0xff00 to 0x4000 to use debugger at 0x6400 up (bde). We! wouldn't have to worry about this if we checked the top of memory. Also! my BIOS can be configured to put the wini drive tables in high memory! instead of in the vector table. The old stack might have clobbered the! drive table.

    movds,axmoves,axmovss,ax! put stack at INITSEG:0x4000-12.movsp,dx/* *Many BIOS's default disk parameter tables will not *recognize multi-sector reads beyond the maximum sector number *specified in the default diskette parameter tables - this may *mean 7 sectors in some cases. * *Since single sector reads are slow and out of the question, *we must take care of this by creating new parameter tables *(for the first disk) in RAM. We will set the maximum sector *count to 18 - the most we will encounter on an HD 1.44. * *High doesn't hurt. Low does. * *Segments are as follows: ds=es=ss=cs - INITSEG, *fs = 0, gs = parameter table segment */

    push#0popfsmovbx,#0x78! fs:bx is parameter table addressseg fslgssi,(bx)! gs:si is source

    movdi,dx! es:di is destinationmovcx,#6! copy 12 bytescld

    repseg gsmovsw

    movdi,dxmovb4(di),*18! patch sector count

    seg fsmov(bx),diseg fsmov2(bx),es

    movax,csmovfs,axmovgs,axxorah,ah! reset FDC xordl,dlint 0x13

    ! load the setup-sectors directly after the bootblock.! Note that 'es' is already set up.

    load_setup:xordx, dx! drive 0, head 0movcx,#0x0002! sector 2, track 0movbx,#0x0200! address = 512, in INITSEGmovax,#0x0200+SETUPSECS! service 2, nr of sectors! (assume all on head 0, track 0)int0x13! read itjncok_load_setup! ok - continue

    pushax! dump error codecallprint_nlmovbp, spcallprint_hexpopaxxordl, dl! reset FDCxorah, ahint0x13jmpload_setup

    ok_load_setup:

    ! Get disk drive parameters, specifically nr of sectors/track

    #if 0

    ! bde - the Phoenix BIOS manual says function 0x08 only works for fixed! disks. It doesn't work for one of my BIOS's (1987 Award). It was! fatal not to check the error code.

    xordl,dlmovah,#0x08! AH=8 is get drive parametersint0x13xorch,ch#else

    ! It seems that there is no BIOS call to get the number of sectors. Guess! 18 sectors if sector 18 can be read, 15 if sector 15 can be read.! Otherwise guess 9.

    xordx, dx! drive 0, head 0movcx,#0x0012! sector 18, track 0movbx,#0x0200+SETUPSECS*0x200 ! address after setup (es = cs)movax,#0x0201! service 2, 1 sectorint0x13jncgot_sectorsmovcl,#0x0f! sector 15movax,#0x0201! service 2, 1 sectorint0x13jncgot_sectorsmovcl,#0x09

    #endif

    got_sectors:seg csmovsectors,cxmovax,#INITSEGmoves,ax

    ! Print some inane message

    movah,#0x03! read cursor posxorbh,bhint0x10movcx,#9movbx,#0x0007! page 0, attribute 7 (normal)movbp,#msg1movax,#0x1301! write string, move cursorint0x10

    ! ok, we've written the message, now! we want to load the system (at 0x10000)

    movax,#SYSSEGmoves,ax! segment of 0x010000callread_itcallkill_motorcallprint_nl

    ! After that we check which root-device to use. If the device is! defined (!= 0), nothing is done and the given device is used.! Otherwise, either /dev/PS0 (2,28) or /dev/at0 (2,8), depending! on the number of sectors that the BIOS reports currently.

    seg csmovax,root_devorax,axjneroot_definedseg csmovbx,sectorsmovax,#0x0208! /dev/ps0 - 1.2Mbcmpbx,#15jeroot_definedmovax,#0x021c! /dev/PS0 - 1.44Mbcmpbx,#18jeroot_definedmovax,#0x0200! /dev/fd0 - autodetectroot_defined:seg csmovroot_dev,ax

    ! after that (everyting loaded), we jump to! the setup-routine loaded directly after! the bootblock:

    jmpi0,SETUPSEG

    ! This routine loads the system at address 0x10000, making sure! no 64kB boundaries are crossed. We try to load it as fast as! possible, loading whole tracks whenever we can.!! in:es - starting address segment (normally 0x1000)!sread:.word 1+SETUPSECS! sectors read of current trackhead:.word 0! current headtrack:.word 0! current track

    read_it:mov ax,estest ax,#0x0fffdie:jne die! es must be at 64kB boundaryxor bx,bx! bx is starting address within segmentrp_read:mov ax,essub ax,#SYSSEGcmp ax,syssize! have we loaded all yet?jbe ok1_readretok1_read:seg csmov ax,sectorssub ax,sreadmov cx,axshl cx,#9add cx,bxjnc ok2_readje ok2_readxor ax,axsub ax,bxshr ax,#9ok2_read:call read_trackmov cx,axadd ax,sreadseg cscmp ax,sectorsjne ok3_readmov ax,#1sub ax,headjne ok4_readinc trackok4_read:mov head,axxor ax,axok3_read:mov sread,axshl cx,#9add bx,cxjnc rp_readmov ax,esadd ah,#0x10mov es,axxor bx,bxjmp rp_read

    read_track:pushapushamovax, #0xe2e ! loading... message 2e = .movbx, #7 int0x10popa

    movdx,trackmovcx,sreadinccxmovch,dlmovdx,headmovdh,dlanddx,#0x0100movah,#2pushdx! save for error dumppushcxpushbxpushax

    int0x13jcbad_rtaddsp, #8poparet

    bad_rt:pushax! save error codecallprint_all! ah = error, al = readxor ah,ahxor dl,dlint 0x13

    addsp, #10popajmp read_track

    /* *print_all is for debugging purposes. *It will print out all of the registers. The assumption is that this is *called from a routine, with a stack frame like *dx *cx *bx *ax *error *ret 35addal,#0x27digit:addal,#0x30movmodenr, alpush sileasi, modestringcallprtstrpopsipopaxret

    ! Part of above routine, this one just prints ascii al

    prnt1:pushaxpushcxxorbh,bhmovcx,#0x01movah,#0x0eint0x10popcxpopaxret

    beep:moval,#0x07jmpprnt1gdt:.word0,0,0,0! dummy

    .word0,0,0,0! unused

    .word0x07FF! 8Mb - limit=2047 (2048*4096=8Mb).word0x0000! base address=0.word0x9A00! code read/exec.word0x00C0! granularity=4096, 386

    .word0x07FF! 8Mb - limit=2047 (2048*4096=8Mb).word0x0000! base address=0.word0x9200! data read/write.word0x00C0! granularity=4096, 386

    idt_48:.word0! idt limit=0.word0,0! idt base=0L

    gdt_48:.word0x800! gdt limit=2048, 256 GDT entries.word512+gdt,0x9! gdt base = 0X9xxxx

    msg1:.ascii"Press to see SVGA-modes available, to continue or wait 30 secs."db0x0d, 0x0a, 0x0a, 0x00msg2:.ascii"Mode: COLSxROWS:"db0x0d, 0x0a, 0x0a, 0x00msg3:db0x0d, 0x0a.ascii"Choose mode by pressing the corresponding number or letter."crlf:db0x0d, 0x0a, 0x00msg4:.ascii"You passed an undefined mode number to setup. Please choose a new mode."db0x0d, 0x0a, 0x0a, 0x07, 0x00modestring:.ascii" "modenr:db0x00! mode number.ascii": "db0x00idati:.ascii"761295520"idcandt:.byte0xa5idgenoa:.byte0x77, 0x00, 0x99, 0x66idparadise:.ascii"VGA="idoakvga:.ascii "OAK VGA "idf1280:.ascii"Orchid Technology Fahrenheit 1280"id9GXE:.ascii "Graphics Power By"idVRAM:.ascii"Stealth VRAM"

    ! Manufacturer: Numofmodes+2:Mode:! Number of modes is the number of chip-specific svga modes plus the extended! modes available on any vga (currently 2)

    moati:.byte0x04,0x23, 0x33 moahead:.byte0x07,0x22, 0x23, 0x24, 0x2f, 0x34mocandt:.byte0x04,0x60, 0x61mocirrus:.byte0x06,0x1f, 0x20, 0x22, 0x31moeverex:.byte0x0c,0x03, 0x04, 0x07, 0x08, 0x0a, 0x0b, 0x16, 0x18, 0x21, 0x40mogenoa:.byte0x0c,0x58, 0x5a, 0x60, 0x61, 0x62, 0x63, 0x64, 0x72, 0x74, 0x78moparadise:.byte0x04,0x55, 0x54motrident:.byte0x09,0x50, 0x51, 0x52, 0x57, 0x58, 0x59, 0x5amotseng:.byte0x07,0x26, 0x2a, 0x23, 0x24, 0x22movideo7:.byte0x08,0x40, 0x43, 0x44, 0x41, 0x42, 0x45mooakvga:.byte 0x08, 0x00, 0x07, 0x4e, 0x4f, 0x50, 0x51mo9GXE:.byte0x04,0x54, 0x55mof1280:.byte0x04,0x54, 0x55mounknown:.byte0x02

    !msb = Cols lsb = Rows:! The first two modes are standard vga modes available on any vga.! mode 0 is 80x50 and mode 1 is 80x28

    dscati:.word0x5032, 0x501c, 0x8419, 0x842cdscahead:.word0x5032, 0x501c, 0x842c, 0x8419, 0x841c, 0xa032, 0x5042dsccandt:.word0x5032, 0x501c, 0x8419, 0x8432dsccirrus:.word0x5032, 0x501c, 0x8419, 0x842c, 0x841e, 0x6425dsceverex:.word0x5032, 0x501c, 0x5022, 0x503c, 0x642b, 0x644b, 0x8419, 0x842c, 0x501e, 0x641b, 0xa040, 0x841edscgenoa:.word0x5032, 0x501c, 0x5020, 0x642a, 0x8419, 0x841d, 0x8420, 0x842c, 0x843c, 0x503c, 0x5042, 0x644bdscparadise:.word0x5032, 0x501c, 0x8419, 0x842bdsctrident:.word 0x5032, 0x501c, 0x501e, 0x502b, 0x503c, 0x8419, 0x841e, 0x842b, 0x843cdsctseng:.word0x5032, 0x501c, 0x503c, 0x6428, 0x8419, 0x841c, 0x842cdscvideo7:.word0x5032, 0x501c, 0x502b, 0x503c, 0x643c, 0x8419, 0x842c, 0x841cdscoakvga:.word 0x5032, 0x501c, 0x2819, 0x5019, 0x503c, 0x843c, 0x8419, 0x842bdscf1280:.word0x5032, 0x501c, 0x842b, 0x8419dsc9GXE:.word0x5032, 0x501c, 0x842b, 0x8419dsunknown:.word0x5032, 0x501cmodesave:.wordSVGA_MODE

    .textendtext:.dataenddata:.bssendbss:

    linux/boot/head.S

    /* * linux/boot/head.S * * Copyright (C) 1991, 1992 Linus Torvalds */

    /* * head.S contains the 32-bit startup code. */

    .text.globl _idt,_gdt,.globl _swapper_pg_dir,_pg0.globl _empty_bad_page.globl _empty_bad_page_table.globl _empty_zero_page.globl _tmp_floppy_area,_floppy_track_buffer

    #include #include

    #define CL_MAGIC_ADDR0x90020#define CL_MAGIC0xA33F#define CL_BASE_ADDR0x90000#define CL_OFFSET0x90022

    /* * swapper_pg_dir is the main page directory, address 0x00001000 (or at * address 0x00101000 for a compressed boot). */startup_32:cldmovl $(KERNEL_DS),%eaxmov %ax,%dsmov %ax,%esmov %ax,%fsmov %ax,%gslss _stack_start,%esp/* * Clear BSS first so that there are no surprises... */xorl %eax,%eaxmovl $__edata,%edimovl $__end,%ecxsubl %edi,%ecxcldrepstosb/* * start system 32-bit setup. We need to re-do some of the things done * in 16-bit mode for the "real" operations. */call setup_idtxorl %eax,%eax1:incl %eax# check that A20 really IS enabledmovl %eax,0x000000# loop forever if it isn'tcmpl %eax,0x100000je 1b/* * Initialize eflags. Some BIOS's leave bits like NT set. This would * confuse the debugger if this code is traced. * XXX - best to initialize before switching to protected mode. */pushl $0popfl/* * Copy bootup parameters out of the way. First 2kB of * _empty_zero_page is for boot parameters, second 2kB * is for the command line. */movl $0x90000,%esimovl $_empty_zero_page,%edimovl $512,%ecxcldrepmovslxorl %eax,%eaxmovl $512,%ecxrepstoslcmpw $(CL_MAGIC),CL_MAGIC_ADDRjne 1fmovl $_empty_zero_page+2048,%edimovzwl CL_OFFSET,%esiaddl $(CL_BASE_ADDR),%esimovl $2048,%ecxrepmovsb1:/* check if it is 486 or 386. *//* * XXX - this does a lot of unnecessary setup. Alignment checks don't * apply at our cpl of 0 and the stack ought to be aligned already, and * we don't need to preserve eflags. */movl %esp,%edi# save stack pointerandl $0xfffffffc,%esp# align stack to avoid AC faultmovl $3,_x86pushfl# push EFLAGSpopl %eax# get EFLAGSmovl %eax,%ecx# save original EFLAGSxorl $0x40000,%eax# flip AC bit in EFLAGSpushl %eax# copy to EFLAGSpopfl# set EFLAGSpushfl# get new EFLAGSpopl %eax# put it in eaxxorl %ecx,%eax# change in flagsandl $0x40000,%eax# check if AC bit changedje is386movl $4,_x86movl %ecx,%eaxxorl $0x200000,%eax# check ID flagpushl %eaxpopfl# if we are on a straight 486DX, SX, orpushfl# 487SX we can't change itpopl %eaxxorl %ecx,%eaxandl $0x200000,%eaxje is486isnew:pushl %ecx# restore original EFLAGSpopflmovl $1, %eax# Use the CPUID instruction to .byte 0x0f, 0xa2# check the processor typeandl $0xf00, %eax# Set _x86 with the familyshrl $8, %eax# returned.movl %eax, _x86movl %edi,%esp# restore espmovl %cr0,%eax# 486+andl $0x80000011,%eax# Save PG,PE,ETorl $0x50022,%eax# set AM, WP, NE and MPjmp 2fis486:pushl %ecx# restore original EFLAGSpopflmovl %edi,%esp# restore espmovl %cr0,%eax# 486andl $0x80000011,%eax# Save PG,PE,ETorl $0x50022,%eax# set AM, WP, NE and MPjmp 2fis386:pushl %ecx# restore original EFLAGSpopflmovl %edi,%esp# restore espmovl %cr0,%eax# 386andl $0x80000011,%eax# Save PG,PE,ETorl $2,%eax# set MP2:movl %eax,%cr0call check_x87call setup_paginglgdt gdt_descrlidt idt_descrljmp $(KERNEL_CS),$1f1:movl $(KERNEL_DS),%eax# reload all the segment registersmov %ax,%ds# after changing gdt.mov %ax,%esmov %ax,%fsmov %ax,%gslss _stack_start,%espxorl %eax,%eaxlldt %axpushl %eax# These are the parameters to main :-)pushl %eaxpushl %eaxcld# gcc2 wants the direction flag cleared at all timescall _start_kernelL6:jmp L6# main should never return here, but# just in case, we know what happens.

    /* * We depend on ET to be correct. This checks for 287/387. */check_x87:movl $0,_hard_mathcltsfninitfstsw %axcmpb $0,%alje 1fmovl %cr0,%eax/* no coprocessor: have to set bits */xorl $4,%eax/* set EM */movl %eax,%cr0ret.align 21:movl $1,_hard_math.byte 0xDB,0xE4/* fsetpm for 287, ignored by 387 */ret

    /* * setup_idt * * sets up a idt with 256 entries pointing to * ignore_int, interrupt gates. It doesn't actually load * idt - that can be done only after paging has been enabled * and the kernel moved to 0xC0000000. Interrupts * are enabled elsewhere, when we can be relatively * sure everything is ok. */setup_idt:lea ignore_int,%edxmovl $(KERNEL_CS comm);tmp.st_dev = inode->i_dev;tmp.st_ino = inode->i_ino;tmp.st_mode = inode->i_mode;tmp.st_nlink = inode->i_nlink;tmp.st_uid = inode->i_uid;tmp.st_gid = inode->i_gid;tmp.st_rdev = inode->i_rdev;tmp.st_size = inode->i_size;tmp.st_atime = inode->i_atime;tmp.st_mtime = inode->i_mtime;tmp.st_ctime = inode->i_ctime;memcpy_tofs(statbuf,&tmp,sizeof(tmp));}

    static void cp_new_stat(struct inode * inode, struct new_stat * statbuf){struct new_stat tmp = {0, };unsigned int blocks, indirect;

    tmp.st_dev = inode->i_dev;tmp.st_ino = inode->i_ino;tmp.st_mode = inode->i_mode;tmp.st_nlink = inode->i_nlink;tmp.st_uid = inode->i_uid;tmp.st_gid = inode->i_gid;tmp.st_rdev = inode->i_rdev;tmp.st_size = inode->i_size;tmp.st_atime = inode->i_atime;tmp.st_mtime = inode->i_mtime;tmp.st_ctime = inode->i_ctime;/* * st_blocks and st_blksize are approximated with a simple algorithm if * they aren't supported directly by the filesystem. The minix and msdos * filesystems don't keep track of blocks, so they would either have to * be counted explicitly (by delving into the file itself), or by using * this simple algorithm to get a reasonable (although not 100% accurate) * value. */

    /* * Use minix fs values for the number of direct and indirect blocks. The * count is now exact for the minix fs except that it counts zero blocks. * Everything is in BLOCK_SIZE'd units until the assignment to * tmp.st_blksize. */#define D_B 7#define I_B (BLOCK_SIZE / sizeof(unsigned short))

    if (!inode->i_blksize) {blocks = (tmp.st_size + BLOCK_SIZE - 1) / BLOCK_SIZE;if (blocks > D_B) {indirect = (blocks - D_B + I_B - 1) / I_B;blocks += indirect;if (indirect > 1) {indirect = (indirect - 1 + I_B - 1) / I_B;blocks += indirect;if (indirect > 1)blocks++;}}tmp.st_blocks = (BLOCK_SIZE / 512) * blocks;tmp.st_blksize = BLOCK_SIZE;} else {tmp.st_blocks = inode->i_blocks;tmp.st_blksize = inode->i_blksize;}memcpy_tofs(statbuf,&tmp,sizeof(tmp));}

    asmlinkage int sys_stat(char * filename, struct old_stat * statbuf){struct inode * inode;int error;

    error = verify_area(VERIFY_WRITE,statbuf,sizeof (*statbuf));if (error)return error;error = namei(filename,&inode);if (error)return error;cp_old_stat(inode,statbuf);iput(inode);return 0;}

    asmlinkage int sys_newstat(char * filename, struct new_stat * statbuf){struct inode * inode;int error;

    error = verify_area(VERIFY_WRITE,statbuf,sizeof (*statbuf));if (error)return error;error = namei(filename,&inode);if (error)return error;cp_new_stat(inode,statbuf);iput(inode);return 0;}

    asmlinkage int sys_lstat(char * filename, struct old_stat * statbuf){struct inode * inode;int error;

    error = verify_area(VERIFY_WRITE,statbuf,sizeof (*statbuf));if (error)return error;error = lnamei(filename,&inode);if (error)return error;cp_old_stat(inode,statbuf);iput(inode);return 0;}

    asmlinkage int sys_newlstat(char * filename, struct new_stat * statbuf){struct inode * inode;int error;

    error = verify_area(VERIFY_WRITE,statbuf,sizeof (*statbuf));if (error)return error;error = lnamei(filename,&inode);if (error)return error;cp_new_stat(inode,statbuf);iput(inode);return 0;}

    asmlinkage int sys_fstat(unsigned int fd, struct old_stat * statbuf){struct file * f;struct inode * inode;int error;

    error = verify_area(VERIFY_WRITE,statbuf,sizeof (*statbuf));if (error)return error;if (fd >= NR_OPEN || !(f=current->filp[fd]) || !(inode=f->f_inode))return -EBADF;cp_old_stat(inode,statbuf);return 0;}

    asmlinkage int sys_newfstat(unsigned int fd, struct new_stat * statbuf){struct file * f;struct inode * inode;int error;

    error = verify_area(VERIFY_WRITE,statbuf,sizeof (*statbuf));if (error)return error;if (fd >= NR_OPEN || !(f=current->filp[fd]) || !(inode=f->f_inode))return -EBADF;cp_new_stat(inode,statbuf);return 0;}

    asmlinkage int sys_readlink(const char * path, char * buf, int bufsiz){struct inode * inode;int error;

    if (bufsiz i_op || !inode->i_op->readlink) {iput(inode);return -EINVAL;}return inode->i_op->readlink(inode,buf,bufsiz);}

    linux/fs/Makefile

    ## Makefile for the linux filesystem.## Note! Dependencies are done automagically by 'make dep', which also# removes any old dependencies. DON'T put your own dependencies here# unless it's something special (ie not a .c file).## Note 2! The CFLAGS definitions are now in the main makefile...

    SUBDIRS = minix ext ext2 msdos proc isofs nfs xiafs hpfs sysv

    ifdef CONFIG_MINIX_FSFS_SUBDIRS := $(FS_SUBDIRS) minixendififdef CONFIG_EXT_FSFS_SUBDIRS := $(FS_SUBDIRS) extendififdef CONFIG_EXT2_FSFS_SUBDIRS := $(FS_SUBDIRS) ext2endififdef CONFIG_MSDOS_FSFS_SUBDIRS := $(FS_SUBDIRS) msdosendififdef CONFIG_PROC_FSFS_SUBDIRS := $(FS_SUBDIRS) procendififdef CONFIG_ISO9660_FSFS_SUBDIRS := $(FS_SUBDIRS) isofsendififdef CONFIG_NFS_FSFS_SUBDIRS := $(FS_SUBDIRS) nfsendififdef CONFIG_XIA_FSFS_SUBDIRS := $(FS_SUBDIRS) xiafsendififdef CONFIG_SYSV_FSFS_SUBDIRS := $(FS_SUBDIRS) sysvendififdef CONFIG_HPFS_FSFS_SUBDIRS := $(FS_SUBDIRS) hpfsendif

    ifdef CONFIG_BINFMT_ELFBINFMTS := $(BINFMTS) binfmt_elf.oendififdef CONFIG_BINFMT_COFFBINFMTS := $(BINFMTS) binfmt_coff.oendif

    .c.s:$(CC) $(CFLAGS) -S $<.c.o:$(CC) $(CFLAGS) -c $<.s.o:$(AS) -o $*.o $<

    OBJS=open.o read_write.o inode.o devices.o file_table.o buffer.o super.o \block_dev.o stat.o exec.o pipe.o namei.o fcntl.o ioctl.o \select.o fifo.o locks.o filesystems.o $(BINFMTS)

    all: fs.o filesystems.a

    fs.o: $(OBJS)$(LD) -r -o fs.o $(OBJS)

    filesystems.a: dummyrm -f filesystems.aset -e; for i in $(FS_SUBDIRS); do \ test ! -d $$i || \ { $(MAKE) -C $$i; $(AR) rcs filesystems.a $$i/$$i.o; }; done

    depend dep:$(CPP) -M *.c > .dependset -e; for i in $(SUBDIRS); do \ test ! -d $$i || $(MAKE) -C $$i dep; done

    dummy:

    ## include a dependency file if one exists#ifeq (.depend,$(wildcard .depend))include .dependendif

    linux/fs/read_write.c

    /* * linux/fs/read_write.c * * Copyright (C) 1991, 1992 Linus Torvalds */

    #include #include #include #include #include

    #include

    /* * Count is not yet used: but we'll probably support reading several entries * at once in the future. Use count=1 in the library for future expansions. */asmlinkage int sys_readdir(unsigned int fd, struct dirent * dirent, unsigned int count){int error;struct file * file;struct inode * inode;

    if (fd >= NR_OPEN || !(file = current->filp[fd]) || !(inode = file->f_inode))return -EBADF;error = -ENOTDIR;if (file->f_op && file->f_op->readdir) {error = verify_area(VERIFY_WRITE, dirent, sizeof (*dirent));if (!error)error = file->f_op->readdir(inode,file,dirent,count);}return error;}

    asmlinkage int sys_lseek(unsigned int fd, off_t offset, unsigned int origin){struct file * file;int tmp = -1;

    if (fd >= NR_OPEN || !(file=current->filp[fd]) || !(file->f_inode))return -EBADF;if (origin > 2)return -EINVAL;if (file->f_op && file->f_op->lseek)return file->f_op->lseek(file->f_inode,file,offset,origin);

    /* this is the default handler if no lseek handler is present */switch (origin) {case 0:tmp = offset;break;case 1:tmp = file->f_pos + offset;break;case 2:if (!file->f_inode)return -EINVAL;tmp = file->f_inode->i_size + offset;break;}if (tmp < 0)return -EINVAL;file->f_pos = tmp;file->f_reada = 0;return file->f_pos;}

    asmlinkage int sys_read(unsigned int fd,char * buf,unsigned int count){int error;struct file * file;struct inode * inode;

    if (fd>=NR_OPEN || !(file=current->filp[fd]) || !(inode=file->f_inode))return -EBADF;if (!(file->f_mode & 1))return -EBADF;if (!file->f_op || !file->f_op->read)return -EINVAL;if (!count)return 0;error = verify_area(VERIFY_WRITE,buf,count);if (error)return error;return file->f_op->read(inode,file,buf,count);}

    asmlinkage int sys_write(unsigned int fd,char * buf,unsigned int count){int error;struct file * file;struct inode * inode;if (fd>=NR_OPEN || !(file=current->filp[fd]) || !(inode=file->f_inode))return -EBADF;if (!(file->f_mode & 2))return -EBADF;if (!file->f_op || !file->f_op->write)return -EINVAL;if (!count)return 0;error = verify_area(VERIFY_READ,buf,count);if (error)return error;return file->f_op->write(inode,file,buf,count);}

    linux/fs/block_dev.c

    /* * linux/fs/block_dev.c * * Copyright (C) 1991, 1992 Linus Torvalds */

    #include #include #include #include #include #include

    extern int *blk_size[];extern int *blksize_size[];

    int block_write(struct inode * inode, struct file * filp, char * buf, int count){int blocksize, blocksize_bits, i;int block;int offset;int chars;int written = 0;unsigned int size;unsigned int dev;struct buffer_head * bh;register char * p;

    dev = inode->i_rdev;blocksize = BLOCK_SIZE;if (blksize_size[MAJOR(dev)] && blksize_size[MAJOR(dev)][MINOR(dev)])blocksize = blksize_size[MAJOR(dev)][MINOR(dev)];

    i = blocksize;blocksize_bits = 0;while(i != 1) {blocksize_bits++;i >>= 1;}

    block = filp->f_pos >> blocksize_bits;offset = filp->f_pos & (blocksize-1);

    if (blk_size[MAJOR(dev)])size = (blk_size[MAJOR(dev)][MINOR(dev)] > blocksize_bits;elsesize = INT_MAX;while (count>0) {if (block >= size)return written;chars = blocksize - offset;if (chars > count)chars=count;if (chars == blocksize)bh = getblk(dev, block, blocksize);elsebh = breada(dev,block,block+1,block+2,-1);block++;if (!bh)return written?written:-EIO;p = offset + bh->b_data;offset = 0;filp->f_pos += chars;written += chars;count -= chars;memcpy_fromfs(p,buf,chars);p += chars;buf += chars;bh->b_uptodate = 1;bh->b_dirt = 1;brelse(bh);}return written;}

    #define NBUF 32

    int block_read(struct inode * inode, struct file * filp, char * buf, int count){unsigned int block;unsigned int offset;int blocksize;int blocksize_bits, i;unsigned int left;unsigned int blocks;int bhrequest, uptodate;struct buffer_head ** bhb, ** bhe;struct buffer_head * buflist[NBUF];struct buffer_head * bhreq[NBUF];unsigned int chars;unsigned int size;unsigned int dev;int read;

    dev = inode->i_rdev;blocksize = BLOCK_SIZE;if (blksize_size[MAJOR(dev)] && blksize_size[MAJOR(dev)][MINOR(dev)])blocksize = blksize_size[MAJOR(dev)][MINOR(dev)];i = blocksize;blocksize_bits = 0;while (i != 1) {blocksize_bits++;i >>= 1;}

    offset = filp->f_pos;if (blk_size[MAJOR(dev)])size = blk_size[MAJOR(dev)][MINOR(dev)] size)left = 0;elseleft = size - offset;if (left > count)left = count;if (left > blocksize_bits;offset &= blocksize-1;size >>= blocksize_bits;blocks = (left + offset + blocksize - 1) >> blocksize_bits;bhb = bhe = buflist;if (filp->f_reada) {blocks += read_ahead[MAJOR(dev)] / (blocksize >> 9);if (block + blocks > size)blocks = size - block;}

    /* We do this in a two stage process. We first try and request as many blocks as we can, then we wait for the first one to complete, and then we try and wrap up as many as are actually done. This routine is rather generic, in that it can be used in a filesystem by substituting the appropriate function in for getblk.

    This routine is optimized to make maximum use of the various buffers and caches. */

    do {bhrequest = 0;uptodate = 1;while (blocks) {--blocks;*bhb = getblk(dev, block++, blocksize);if (*bhb && !(*bhb)->b_uptodate) {uptodate = 0;bhreq[bhrequest++] = *bhb;}

    if (++bhb == &buflist[NBUF])bhb = buflist;

    /* If the block we have on hand is uptodate, go ahead and complete processing. */if (uptodate)break;if (bhb == bhe)break;}

    /* Now request them all */if (bhrequest)ll_rw_block(READ, bhrequest, bhreq);

    do { /* Finish off all I/O that has actually completed */if (*bhe) {wait_on_buffer(*bhe);if (!(*bhe)->b_uptodate) {/* read error? */ brelse(*bhe);if (++bhe == &buflist[NBUF]) bhe = buflist;left = 0;break;}}if (left < blocksize - offset)chars = left;elsechars = blocksize - offset;filp->f_pos += chars;left -= chars;read += chars;if (*bhe) {memcpy_tofs(buf,offset+(*bhe)->b_data,chars);brelse(*bhe);buf += chars;} else {while (chars-->0)put_fs_byte(0,buf++);}offset = 0;if (++bhe == &buflist[NBUF])bhe = buflist;} while (left > 0 && bhe != bhb && (!*bhe || !(*bhe)->b_lock));} while (left > 0);

    /* Release the read-ahead blocks */while (bhe != bhb) {brelse(*bhe);if (++bhe == &buflist[NBUF])bhe = buflist;};if (!read)return -EIO;filp->f_reada = 1;return read;}

    int block_fsync(struct inode *inode, struct file *filp){return fsync_dev (inode->i_rdev);}

    linux/fs/buffer.c

    /* * linux/fs/buffer.c * * Copyright (C) 1991, 1992 Linus Torvalds */

    /* * 'buffer.c' implements the buffer-cache functions. Race-conditions have * been avoided by NEVER letting an interrupt change a buffer (except for the * data, of course), but instead letting the caller do it. */

    /* * NOTE! There is one discordant note here: checking floppies for * disk change. This is where it fits best, I think, as it should * invalidate changed floppy-disk-caches. */

    #include #include #include #include #include #include #include #include #include

    #include #include

    #ifdef CONFIG_SCSI#ifdef CONFIG_BLK_DEV_SRextern int check_cdrom_media_change(int, int);#endif#ifdef CONFIG_BLK_DEV_SDextern int check_scsidisk_media_change(int, int);extern int revalidate_scsidisk(int, int);#endif#endif#ifdef CONFIG_CDU31Aextern int check_cdu31a_media_change(int, int);#endif#ifdef CONFIG_MCDextern int check_mcd_media_change(int, int);#endif

    static int grow_buffers(int pri, int size);

    static struct buffer_head * hash_table[NR_HASH];static struct buffer_head * free_list = NULL;static struct buffer_head * unused_list = NULL;static struct wait_queue * buffer_wait = NULL;

    int nr_buffers = 0;int buffermem = 0;int nr_buffer_heads = 0;static int min_free_pages = 20;/* nr free pages needed before buffer grows */extern int *blksize_size[];

    /* * Rewrote the wait-routines to use the "new" wait-queue functionality, * and getting rid of the cli-sti pairs. The wait-queue routines still * need cli-sti, but now it's just a couple of 386 instructions or so. * * Note that the real wait_on_buffer() is an inline function that checks * if 'b_wait' is set before calling this, so that the queues aren't set * up unnecessarily. */void __wait_on_buffer(struct buffer_head * bh){struct wait_queue wait = { current, NULL };

    bh->b_count++;add_wait_queue(&bh->b_wait, &wait);repeat:current->state = TASK_UNINTERRUPTIBLE;if (bh->b_lock) {schedule();goto repeat;}remove_wait_queue(&bh->b_wait, &wait);bh->b_count--;current->state = TASK_RUNNING;}

    /* Call sync_buffers with wait!=0 to ensure that the call does not return until all buffer writes have completed. Sync() may return before the writes have finished; fsync() may not. */

    static int sync_buffers(dev_t dev, int wait){int i, retry, pass = 0, err = 0;struct buffer_head * bh;

    /* One pass for no-wait, three for wait: 0) write out all dirty, unlocked buffers; 1) write out all dirty buffers, waiting if locked; 2) wait for completion by waiting for all buffers to unlock. */repeat:retry = 0;bh = free_list;for (i = nr_buffers*2 ; i-- > 0 ; bh = bh->b_next_free) {if (dev && bh->b_dev != dev)continue;#ifdef 0 /* Disable bad-block debugging code */if (bh->b_req && !bh->b_lock && !bh->b_dirt && !bh->b_uptodate)printk ("Warning (IO error) - orphaned block %08x on %04x\n",bh->b_blocknr, bh->b_dev);#endifif (bh->b_lock){/* Buffer is locked; skip it unless wait is requested AND pass > 0. */if (!wait || !pass) {retry = 1;continue;}wait_on_buffer (bh);}/* If an unlocked buffer is not uptodate, there has been an IO error. Skip it. */if (wait && bh->b_req && !bh->b_lock && !bh->b_dirt && !bh->b_uptodate){err = 1;continue;}/* Don't write clean buffers. Don't write ANY buffers on the third pass. */if (!bh->b_dirt || pass>=2)continue;bh->b_count++;ll_rw_block(WRITE, 1, &bh);bh->b_count--;retry = 1;}/* If we are waiting for the sync to succeed, and if any dirty blocks were written, then repeat; on the second pass, only wait for buffers being written (do not pass to write any more buffers on the second pass). */if (wait && retry && ++passi_dev);}

    asmlinkage int sys_fsync(unsigned int fd){struct file * file;struct inode * inode;

    if (fd>=NR_OPEN || !(file=current->filp[fd]) || !(inode=file->f_inode))return -EBADF;if (!file->f_op || !file->f_op->fsync)return -EINVAL;if (file->f_op->fsync(inode,file))return -EIO;return 0;}

    void invalidate_buffers(dev_t dev){int i;struct buffer_head * bh;

    bh = free_list;for (i = nr_buffers*2 ; --i > 0 ; bh = bh->b_next_free) {if (bh->b_dev != dev)continue;wait_on_buffer(bh);if (bh->b_dev == dev)bh->b_uptodate = bh->b_dirt = bh->b_req = 0;}}

    /* * This routine checks whether a floppy has been changed, and * invalidates all buffer-cache-entries in that case. This * is a relatively slow routine, so we have to try to minimize using * it. Thus it is called only upon a 'mount' or 'open'. This * is the best way of combining speed and utility, I think. * People changing diskettes in the middle of an operation deserve * to loose :-) * * NOTE! Although currently this is only for floppies, the idea is * that any additional removable block-device will use this routine, * and that mount/open needn't know that floppies/whatever are * special. */void check_disk_change(dev_t dev){int i;struct buffer_head * bh;

    switch(MAJOR(dev)){case FLOPPY_MAJOR:if (!(bh = getblk(dev,0,1024)))return;i = floppy_change(bh);brelse(bh);break;

    #if defined(CONFIG_BLK_DEV_SD) && defined(CONFIG_SCSI) case SCSI_DISK_MAJOR:i = check_scsidisk_media_change(dev, 0);break;#endif

    #if defined(CONFIG_BLK_DEV_SR) && defined(CONFIG_SCSI) case SCSI_CDROM_MAJOR:i = check_cdrom_media_change(dev, 0);break;#endif

    #if defined(CONFIG_CDU31A) case CDU31A_CDROM_MAJOR:i = check_cdu31a_media_change(dev, 0);break;#endif

    #if defined(CONFIG_MCD) case MITSUMI_CDROM_MAJOR:i = check_mcd_media_change(dev, 0);break;#endif

    default:return;};

    if (!i)return;

    printk("VFS: Disk change detected on device %d/%d\n",MAJOR(dev), MINOR(dev));for (i=0 ; ib_next)bh->b_next->b_prev = bh->b_prev;if (bh->b_prev)bh->b_prev->b_next = bh->b_next;if (hash(bh->b_dev,bh->b_blocknr) == bh)hash(bh->b_dev,bh->b_blocknr) = bh->b_next;bh->b_next = bh->b_prev = NULL;}

    static inline void remove_from_free_list(struct buffer_head * bh){if (!(bh->b_prev_free) || !(bh->b_next_free))panic("VFS: Free block list corrupted");bh->b_prev_free->b_next_free = bh->b_next_free;bh->b_next_free->b_prev_free = bh->b_prev_free;if (free_list == bh)free_list = bh->b_next_free;bh->b_next_free = bh->b_prev_free = NULL;}

    static inline void remove_from_queues(struct buffer_head * bh){remove_from_hash_queue(bh);remove_from_free_list(bh);}

    static inline void put_first_free(struct buffer_head * bh){if (!bh || (bh == free_list))return;remove_from_free_list(bh);/* add to front of free list */bh->b_next_free = free_list;bh->b_prev_free = free_list->b_prev_free;free_list->b_prev_free->b_next_free = bh;free_list->b_prev_free = bh;free_list = bh;}

    static inline void put_last_free(struct buffer_head * bh){if (!bh)return;if (bh == free_list) {free_list = bh->b_next_free;return;}remove_from_free_list(bh);/* add to back of free list */bh->b_next_free = free_list;bh->b_prev_free = free_list->b_prev_free;free_list->b_prev_free->b_next_free = bh;free_list->b_prev_free = bh;}

    static inline void insert_into_queues(struct buffer_head * bh){/* put at end of free list */bh->b_next_free = free_list;bh->b_prev_free = free_list->b_prev_free;free_list->b_prev_free->b_next_free = bh;free_list->b_prev_free = bh;/* put the buffer in new hash-queue if it has a device */bh->b_prev = NULL;bh->b_next = NULL;if (!bh->b_dev)return;bh->b_next = hash(bh->b_dev,bh->b_blocknr);hash(bh->b_dev,bh->b_blocknr) = bh;if (bh->b_next)bh->b_next->b_prev = bh;}

    static struct buffer_head * find_buffer(dev_t dev, int block, int size){struct buffer_head * tmp;

    for (tmp = hash(dev,block) ; tmp != NULL ; tmp = tmp->b_next)if (tmp->b_dev==dev && tmp->b_blocknr==block)if (tmp->b_size == size)return tmp;else {printk("VFS: Wrong blocksize on device %d/%d\n",MAJOR(dev), MINOR(dev));return NULL;}return NULL;}

    /* * Why like this, I hear you say... The reason is race-conditions. * As we don't lock buffers (unless we are readint them, that is), * something might happen to it while we sleep (ie a read-error * will force it bad). This shouldn't really happen currently, but * the code is ready. */struct buffer_head * get_hash_table(dev_t dev, int block, int size){struct buffer_head * bh;

    for (;;) {if (!(bh=find_buffer(dev,block,size)))return NULL;bh->b_count++;wait_on_buffer(bh);if (bh->b_dev == dev && bh->b_blocknr == block && bh->b_size == size)return bh;bh->b_count--;}}

    void set_blocksize(dev_t dev, int size){int i;struct buffer_head * bh, *bhnext;

    if (!blksize_size[MAJOR(dev)])return;

    switch(size) {default: panic("Invalid blocksize passed to set_blocksize");case 512: case 1024: case 2048: case 4096:;}

    if (blksize_size[MAJOR(dev)][MINOR(dev)] == 0 && size == BLOCK_SIZE) {blksize_size[MAJOR(dev)][MINOR(dev)] = size;return;}if (blksize_size[MAJOR(dev)][MINOR(dev)] == size)return;sync_buffers(dev, 2);blksize_size[MAJOR(dev)][MINOR(dev)] = size;

    /* We need to be quite careful how we do this - we are moving entries around on the free list, and we can get in a loop if we are not careful.*/

    bh = free_list;for (i = nr_buffers*2 ; --i > 0 ; bh = bhnext) {bhnext = bh->b_next_free; if (bh->b_dev != dev)continue;if (bh->b_size == size)continue;

    wait_on_buffer(bh);if (bh->b_dev == dev && bh->b_size != size)bh->b_uptodate = bh->b_dirt = 0;remove_from_hash_queue(bh);/* put_first_free(bh); */}}

    /* * Ok, this is getblk, and it isn't very clear, again to hinder * race-conditions. Most of the code is seldom used, (ie repeating), * so it should be much more efficient than it looks. * * The algoritm is changed: hopefully better, and an elusive bug removed. * * 14.02.92: changed it to sync dirty buffers a bit: better performance * when the filesystem starts to get full of dirty blocks (I hope). */#define BADNESS(bh) (((bh)->b_dirtb_uptodate && !bh->b_dirt)put_last_free(bh);return bh;}grow_size -= size;if (nr_free_pages > min_free_pages && grow_size 0 ; tmp = tmp->b_next_free) {if (tmp->b_count || tmp->b_size != size)continue;if (mem_map[MAP_NR((unsigned long) tmp->b_data)] != 1)continue;if (!bh || BADNESS(tmp)b_dirt) {tmp->b_count++;ll_rw_block(WRITEA, 1, &tmp);tmp->b_count--;}#endif}

    if (!bh) {if (nr_free_pages > 5)if (grow_buffers(GFP_BUFFER, size))goto repeat;if (!grow_buffers(GFP_ATOMIC, size))sleep_on(&buffer_wait);goto repeat;}

    wait_on_buffer(bh);if (bh->b_count || bh->b_size != size)goto repeat;if (bh->b_dirt) {sync_buffers(0,0);goto repeat;}/* NOTE!! While we slept waiting for this block, somebody else might *//* already have added "this" block to the cache. check it */if (find_buffer(dev,block,size))goto repeat;/* OK, FINALLY we know that this buffer is the only one of its kind, *//* and that it's unused (b_count=0), unlocked (b_lock=0), and clean */bh->b_count=1;bh->b_dirt=0;bh->b_uptodate=0;bh->b_req=0;remove_from_queues(bh);bh->b_dev=dev;bh->b_blocknr=block;insert_into_queues(bh);return bh;}

    void brelse(struct buffer_head * buf){if (!buf)return;wait_on_buffer(buf);if (buf->b_count) {if (--buf->b_count)return;wake_up(&buffer_wait);return;}printk("VFS: brelse: Trying to free free buffer\n");}

    /* * bread() reads a specified block and returns the buffer that contains * it. It returns NULL if the block was unreadable. */struct buffer_head * bread(dev_t dev, int block, int size){struct buffer_head * bh;

    if (!(bh = getblk(dev, block, size))) {printk("VFS: bread: READ error on device %d/%d\n",MAJOR(dev), MINOR(dev));return NULL;}if (bh->b_uptodate)return bh;ll_rw_block(READ, 1, &bh);wait_on_buffer(bh);if (bh->b_uptodate)return bh;brelse(bh);return NULL;}

    /* * Ok, breada can be used as bread, but additionally to mark other * blocks for reading as well. End the argument list with a negative * number. */struct buffer_head * breada(dev_t dev,int first, ...){va_list args;unsigned int blocksize;struct buffer_head * bh, *tmp;

    va_start(args,first);

    blocksize = BLOCK_SIZE;if (blksize_size[MAJOR(dev)] && blksize_size[MAJOR(dev)][MINOR(dev)])blocksize = blksize_size[MAJOR(dev)][MINOR(dev)];

    if (!(bh = getblk(dev, first, blocksize))) {printk("VFS: breada: READ error on device %d/%d\n",MAJOR(dev), MINOR(dev));return NULL;}if (!bh->b_uptodate)ll_rw_block(READ, 1, &bh);while ((first=va_arg(args,int))>=0) {tmp = getblk(dev, first, blocksize);if (tmp) {if (!tmp->b_uptodate)ll_rw_block(READA, 1, &tmp);tmp->b_count--;}}va_end(args);wait_on_buffer(bh);if (bh->b_uptodate)return bh;brelse(bh);return (NULL);}

    /* * See fs/inode.c for the weird use of volatile.. */static void put_unused_buffer_head(struct buffer_head * bh){struct wait_queue * wait;

    wait = ((volatile struct buffer_head *) bh)->b_wait;memset((void *) bh,0,sizeof(*bh));((volatile struct buffer_head *) bh)->b_wait = wait;bh->b_next_free = unused_list;unused_list = bh;}

    static void get_more_buffer_heads(void){int i;struct buffer_head * bh;

    if (unused_list)return;

    if(! (bh = (struct buffer_head*) get_free_page(GFP_BUFFER)))return;

    for (nr_buffer_heads+=i=PAGE_SIZE/sizeof*bh ; i>0; i--) {bh->b_next_free = unused_list;/* only make link */unused_list = bh++;}}

    static struct buffer_head * get_unused_buffer_head(void){struct buffer_head * bh;

    get_more_buffer_heads();if (!unused_list)return NULL;bh = unused_list;unused_list = bh->b_next_free;bh->b_next_free = NULL;bh->b_data = NULL;bh->b_size = 0;bh->b_req = 0;return bh;}

    /* * Create the appropriate buffers when given a page for data area and * the size of each buffer.. Use the bh->b_this_page linked list to * follow the buffers created. Return NULL if unable to create more * buffers. */static struct buffer_head * create_buffers(unsigned long page, unsigned long size){struct buffer_head *bh, *head;unsigned long offset;

    head = NULL;offset = PAGE_SIZE;while ((offset -= size) < PAGE_SIZE) {bh = get_unused_buffer_head();if (!bh)goto no_grow;bh->b_this_page = head;head = bh;bh->b_data = (char *) (page+offset);bh->b_size = size;}return head;/* * In case anything failed, we just free everything we got. */no_grow:bh = head;while (bh) {head = bh;bh = bh->b_this_page;put_unused_buffer_head(head);}return NULL;}

    static void read_buffers(struct buffer_head * bh[], int nrbuf){int i;int bhnum = 0;struct buffer_head * bhr[8];

    for (i = 0 ; i < nrbuf ; i++) {if (bh[i] && !bh[i]->b_uptodate)bhr[bhnum++] = bh[i];}if (bhnum)ll_rw_block(READ, bhnum, bhr);for (i = 0 ; i < nrbuf ; i++) {if (bh[i]) {wait_on_buffer(bh[i]);}}}

    static unsigned long check_aligned(struct buffer_head * first, unsigned long address,dev_t dev, int *b, int size){struct buffer_head * bh[8];unsigned long page;unsigned long offset;int block;int nrbuf;

    page = (unsigned long) first->b_data;if (page & ~PAGE_MASK) {brelse(first);return 0;}mem_map[MAP_NR(page)]++;bh[0] = first;nrbuf = 1;for (offset = size ; offset < PAGE_SIZE ; offset += size) {block = *++b;if (!block)goto no_go;first = get_hash_table(dev, block, size);if (!first)goto no_go;bh[nrbuf++] = first;if (page+offset != (unsigned long) first->b_data)goto no_go;}read_buffers(bh,nrbuf);/* make sure they are actually read correctly */while (nrbuf-- > 0)brelse(bh[nrbuf]);free_page(address);++current->min_flt;return page;no_go:while (nrbuf-- > 0)brelse(bh[nrbuf]);free_page(page);return 0;}

    static unsigned long try_to_load_aligned(unsigned long address,dev_t dev, int b[], int size){struct buffer_head * bh, * tmp, * arr[8];unsigned long offset;int * p;int block;

    bh = create_buffers(address, size);if (!bh)return 0;/* do any of the buffers already exist? punt if so.. */p = b;for (offset = 0 ; offset < PAGE_SIZE ; offset += size) {block = *(p++);if (!block)goto not_aligned;if (find_buffer(dev, block, size))goto not_aligned;}tmp = bh;p = b;block = 0;while (1) {arr[block++] = bh;bh->b_count = 1;bh->b_dirt = 0;bh->b_uptodate = 0;bh->b_dev = dev;bh->b_blocknr = *(p++);nr_buffers++;insert_into_queues(bh);if (bh->b_this_page)bh = bh->b_this_page;elsebreak;}buffermem += PAGE_SIZE;bh->b_this_page = tmp;mem_map[MAP_NR(address)]++;read_buffers(arr,block);while (block-- > 0)brelse(arr[block]);++current->maj_flt;return address;not_aligned:while ((tmp = bh) != NULL) {bh = bh->b_this_page;put_unused_buffer_head(tmp);}return 0;}

    /* * Try-to-share-buffers tries to minimize memory use by trying to keep * both code pages and the buffer area in the same page. This is done by * (a) checking if the buffers are already aligned correctly in memory and * (b) if none of the buffer heads are in memory at all, trying to load * them into memory the way we want them. * * This doesn't guarantee that the memory is shared, but should under most * circumstances work very well indeed (ie >90% sharing of code pages on * demand-loadable executables). */static inline unsigned long try_to_share_buffers(unsigned long address,dev_t dev, int *b, int size){struct buffer_head * bh;int block;

    block = b[0];if (!block)return 0;bh = get_hash_table(dev, block, size);if (bh)return check_aligned(bh, address, dev, b, size);return try_to_load_aligned(address, dev, b, size);}

    #define COPYBLK(size,from,to) \__asm__ __volatile__("rep ; movsl": \:"c" (((unsigned long) size) >> 2),"S" (from),"D" (to) \:"cx","di","si")

    /* * bread_page reads four buffers into memory at the desired address. It's * a function of its own, as there is some speed to be got by reading them * all at the same time, not waiting for one to be read, and then another * etc. This also allows us to optimize memory usage by sharing code pages * and filesystem buffers.. */unsigned long bread_page(unsigned long address, dev_t dev, int b[], int size, int prot){struct buffer_head * bh[8];unsigned long where;int i, j;

    if (!(prot & PAGE_RW)) {where = try_to_share_buffers(address,dev,b,size);if (where)return where;}++current->maj_flt; for (i=0, j=0; jb_data,address);brelse(bh[i]);}}return where;}

    /* * Try to increase the number of buffers available: the size argument * is used to determine what kind of buffers we want. */static int grow_buffers(int pri, int size){unsigned long page;struct buffer_head *bh, *tmp;

    if ((size & 511) || (size > PAGE_SIZE)) {printk("VFS: grow_buffers: size = %d\n",size);return 0;}if(!(page = __get_free_page(pri)))return 0;bh = create_buffers(page, size);if (!bh) {free_page(page);return 0;}tmp = bh;while (1) {if (free_list) {tmp->b_next_free = free_list;tmp->b_prev_free = free_list->b_prev_free;free_list->b_prev_free->b_next_free = tmp;free_list->b_prev_free = tmp;} else {tmp->b_prev_free = tmp;tmp->b_next_free = tmp;}free_list = tmp;++nr_buffers;if (tmp->b_this_page)tmp = tmp->b_this_page;elsebreak;}tmp->b_this_page = bh;buffermem += PAGE_SIZE;return 1;}

    /* * try_to_free() checks if all the buffers on this particular page * are unused, and free's the page if so. */static int try_to_free(struct buffer_head * bh, struct buffer_head ** bhp){unsigned long page;struct buffer_head * tmp, * p;

    *bhp = bh;page = (unsigned long) bh->b_data;page &= PAGE_MASK;tmp = bh;do {if (!tmp)return 0;if (tmp->b_count || tmp->b_dirt || tmp->b_lock || tmp->b_wait)return 0;tmp = tmp->b_this_page;} while (tmp != bh);tmp = bh;do {p = tmp;tmp = tmp->b_this_page;nr_buffers--;if (p == *bhp)*bhp = p->b_prev_free;remove_from_queues(p);put_unused_buffer_head(p);} while (tmp != bh);buffermem -= PAGE_SIZE;free_page(page);return !mem_map[MAP_NR(page)];}

    /* * Try to free up some pages by shrinking the buffer-cache * * Priority tells the routine how hard to try to shrink the * buffers: 3 means "don't bother too much", while a value * of 0 means "we'd better get some free pages now". */int shrink_buffers(unsigned int priority){struct buffer_head *bh;int i;

    if (priority < 2)sync_buffers(0,0);bh = free_list;i = nr_buffers >> priority;for ( ; i-- > 0 ; bh = bh->b_next_free) {if (bh->b_count || (priority >= 5 && mem_map[MAP_NR((unsigned long) bh->b_data)] > 1)) {put_last_free(bh);continue;}if (!bh->b_this_page)continue;if (bh->b_lock)if (priority)continue;elsewait_on_buffer(bh);if (bh->b_dirt) {bh->b_count++;ll_rw_block(WRITEA, 1, &bh);bh->b_count--;continue;}if (try_to_free(bh, &bh))return 1;}return 0;}

    void show_buffers(void){struct buffer_head * bh;int found = 0, locked = 0, dirty = 0, used = 0, lastused = 0;

    printk("Buffer memory: %6dkB\n",buffermem>>10);printk("Buffer heads: %6d\n",nr_buffer_heads);printk("Buffer blocks: %6d\n",nr_buffers);bh = free_list;do {found++;if (bh->b_lock)locked++;if (bh->b_dirt)dirty++;if (bh->b_count)used++, lastused = found;bh = bh->b_next_free;} while (bh != free_list);printk("Buffer mem: %d buffers, %d used (last=%d), %d locked, %d dirty\n",found, used, lastused, locked, dirty);}

    /* * This initializes the initial buffer free list. nr_buffers is set * to one less the actual number of buffers, as a sop to backwards * compatibility --- the old code did this (I think unintentionally, * but I'm not sure), and programs in the ps package expect it. * - TYT 8/30/92 */void buffer_init(void){int i;

    if (high_memory >= 4*1024*1024)min_free_pages = 200;elsemin_free_pages = 20;for (i = 0 ; i < NR_HASH ; i++)hash_table[i] = NULL;free_list = 0;grow_buffers(GFP_KERNEL, BLOCK_SIZE);if (!free_list)panic("VFS: Unable to initialize buffer free list!");return;}

    linux/fs/inode.c

    /* * linux/fs/inode.c * * Copyright (C) 1991, 1992 Linus Torvalds */

    #include #include #include #include #include

    #include

    static struct inode_hash_entry {struct inode * inode;int updating;} hash_table[NR_IHASH];

    static struct inode * first_inode;static struct wait_queue * inode_wait = NULL;static int nr_inodes = 0, nr_free_inodes = 0;

    static inline int const hashfn(dev_t dev, unsigned int i){return (dev ^ i) % NR_IHASH;}

    static inline struct inode_hash_entry * const hash(dev_t dev, int i){return hash_table + hashfn(dev, i);}

    static void insert_inode_free(struct inode *inode){inode->i_next = first_inode;inode->i_prev = first_inode->i_prev;inode->i_next->i_prev = inode;inode->i_prev->i_next = inode;first_inode = inode;}

    static void remove_inode_free(struct inode *inode){if (first_inode == inode)first_inode = first_inode->i_next;if (inode->i_next)inode->i_next->i_prev = inode->i_prev;if (inode->i_prev)inode->i_prev->i_next = inode->i_next;inode->i_next = inode->i_prev = NULL;}

    void insert_inode_hash(struct inode *inode){struct inode_hash_entry *h;h = hash(inode->i_dev, inode->i_ino);

    inode->i_hash_next = h->inode;inode->i_hash_prev = NULL;if (inode->i_hash_next)inode->i_hash_next->i_hash_prev = inode;h->inode = inode;}

    static void remove_inode_hash(struct inode *inode){struct inode_hash_entry *h;h = hash(inode->i_dev, inode->i_ino);

    if (h->inode == inode)h->inode = inode->i_hash_next;if (inode->i_hash_next)inode->i_hash_next->i_hash_prev = inode->i_hash_prev;if (inode->i_hash_prev)inode->i_hash_prev->i_hash_next = inode->i_hash_next;inode->i_hash_prev = inode->i_hash_next = NULL;}

    static void put_last_free(struct inode *inode){remove_inode_free(inode);inode->i_prev = first_inode->i_prev;inode->i_prev->i_next = inode;inode->i_next = first_inode;inode->i_next->i_prev = inode;}

    void grow_inodes(void){struct inode * inode;int i;

    if (!(inode = (struct inode*) get_free_page(GFP_KERNEL)))return;

    i=PAGE_SIZE / sizeof(struct inode);nr_inodes += i;nr_free_inodes += i;

    if (!first_inode)inode->i_next = inode->i_prev = first_inode = inode++, i--;

    for ( ; i ; i-- )insert_inode_free(inode++);}

    unsigned long inode_init(unsigned long start, unsigned long end){memset(hash_table, 0, sizeof(hash_table));first_inode = NULL;return start;}

    static void __wait_on_inode(struct inode *);

    static inline void wait_on_inode(struct inode * inode){if (inode->i_lock)__wait_on_inode(inode);}

    static inline void lock_inode(struct inode * inode){wait_on_inode(inode);inode->i_lock = 1;}

    static inline void unlock_inode(struct inode * inode){inode->i_lock = 0;wake_up(&inode->i_wait);}

    /* * Note that we don't want to disturb any wait-queues when we discard * an inode. * * Argghh. Got bitten by a gcc problem with inlining: no way to tell * the compiler that the inline asm function 'memset' changes 'inode'. * I've been searching for the bug for days, and was getting desperate. * Finally looked at the assembler output... Grrr. * * The solution is the weird use of 'volatile'. Ho humm. Have to report * it to the gcc lists, and hope we can do this more cleanly some day.. */void clear_inode(struct inode * inode){struct wait_queue * wait;

    wait_on_inode(inode);remove_inode_hash(inode);remove_inode_free(inode);wait = ((volatile struct inode *) inode)->i_wait;if (inode->i_count)nr_free_inodes++;memset(inode,0,sizeof(*inode));((volatile struct inode *) inode)->i_wait = wait;insert_inode_free(inode);}

    int fs_may_mount(dev_t dev){struct inode * inode, * next;int i;

    next = first_inode;for (i = nr_inodes ; i > 0 ; i--) {inode = next;next = inode->i_next;/* clear_inode() changes the queues.. */if (inode->i_dev != dev)continue;if (inode->i_count || inode->i_dirt || inode->i_lock)return 0;clear_inode(inode);}return 1;}

    int fs_may_umount(dev_t dev, struct inode * mount_root){struct inode * inode;int i;

    inode = first_inode;for (i=0 ; i < nr_inodes ; i++, inode = inode->i_next) {if (inode->i_dev != dev || !inode->i_count)continue;if (inode == mount_root && inode->i_count == 1)continue;return 0;}return 1;}

    int fs_may_remount_ro(dev_t dev){struct file * file;int i;

    /* Check that no files are currently opened for writing. */for (file = first_file, i=0; if_next) {if (!file->f_count || !file->f_inode || file->f_inode->i_dev != dev)continue;if (S_ISREG(file->f_inode->i_mode) && (file->f_mode & 2))return 0;}return 1;}

    static void write_inode(struct inode * inode){if (!inode->i_dirt)return;wait_on_inode(inode);if (!inode->i_dirt)return;if (!inode->i_sb || !inode->i_sb->s_op || !inode->i_sb->s_op->write_inode) {inode->i_dirt = 0;return;}inode->i_lock = 1;inode->i_sb->s_op->write_inode(inode);unlock_inode(inode);}

    static void read_inode(struct inode * inode){lock_inode(inode);if (inode->i_sb && inode->i_sb->s_op && inode->i_sb->s_op->read_inode)inode->i_sb->s_op->read_inode(inode);unlock_inode(inode);}

    /* * notify_change is called for inode-changing operations such as * chown, chmod, utime, and truncate. It is guaranteed (unlike * write_inode) to be called from the context of the user requesting * the change. It is not called for ordinary access-time updates. * NFS uses this to get the authentication correct. -- jrs */

    int notify_change(int flags, struct inode * inode){if (inode->i_sb && inode->i_sb->s_op && inode->i_sb->s_op->notify_change)return inode->i_sb->s_op->notify_change(flags, inode);return 0;}

    /* * bmap is needed for demand-loading and paging: if this function * doesn't exist for a filesystem, then those things are impossible: * executables cannot be run from the filesystem etc... * * This isn't as bad as it sounds: the read-routines might still work, * so the filesystem would be otherwise ok (for example, you might have * a DOS filesystem, which doesn't lend itself to bmap very well, but * you could still transfer files to/from the filesystem) */int bmap(struct inode * inode, int block){if (inode->i_op && inode->i_op->bmap)return inode->i_op->bmap(inode,block);return 0;}

    void invalidate_inodes(dev_t dev){struct inode * inode, * next;int i;

    next = first_inode;for(i = nr_inodes ; i > 0 ; i--) {inode = next;next = inode->i_next;/* clear_inode() changes the queues.. */if (inode->i_dev != dev)continue;if (inode->i_count || inode->i_dirt || inode->i_lock) {printk("VFS: inode busy on removed device %d/%d\n", MAJOR(dev), MINOR(dev));continue;}clear_inode(inode);}}

    void sync_inodes(dev_t dev){int i;struct inode * inode;

    inode = first_inode;for(i = 0; i < nr_inodes*2; i++, inode = inode->i_next) {if (dev && inode->i_dev != dev)continue;wait_on_inode(inode);if (inode->i_dirt)write_inode(inode);}}

    void iput(struct inode * inode){if (!inode)return;wait_on_inode(inode);if (!inode->i_count) {printk("VFS: iput: trying to free free inode\n");printk("VFS: device %d/%d, inode %lu, mode=0%07o\n",MAJOR(inode->i_rdev), MINOR(inode->i_rdev),inode->i_ino, inode->i_mode);return;}if (inode->i_pipe)wake_up_interruptible(&PIPE_WAIT(*inode));repeat:if (inode->i_count>1) {inode->i_count--;return;}wake_up(&inode_wait);if (inode->i_pipe) {unsigned long page = (unsigned long) PIPE_BASE(*inode);PIPE_BASE(*inode) = NULL;free_page(page);}if (inode->i_sb && inode->i_sb->s_op && inode->i_sb->s_op->put_inode) {inode->i_sb->s_op->put_inode(inode);if (!inode->i_nlink)return;}if (inode->i_dirt) {write_inode(inode);/* we can sleep - so do again */wait_on_inode(inode);goto repeat;}inode->i_count--;nr_free_inodes++;return;}

    struct inode * get_empty_inode(void){struct inode * inode, * best;int i;

    if (nr_inodes < NR_INODE && nr_free_inodes < (nr_inodes >> 2))grow_inodes();repeat:inode = first_inode;best = NULL;for (i = 0; ii_next, i++) {if (!inode->i_count) {if (!best)best = inode;if (!inode->i_dirt && !inode->i_lock) {best = inode;break;}}}if (!best || best->i_dirt || best->i_lock)if (nr_inodes < NR_INODE) {grow_inodes();goto repeat;}inode = best;if (!inode) {printk("VFS: No free inodes - contact Linus\n");sleep_on(&inode_wait);goto repeat;}if (inode->i_lock) {wait_on_inode(inode);goto repeat;}if (inode->i_dirt) {write_inode(inode);goto repeat;}if (inode->i_count)goto repeat;clear_inode(inode);inode->i_count = 1;inode->i_nlink = 1;inode->i_sem.count = 1;nr_free_inodes--;if (nr_free_inodes < 0) {printk ("VFS: get_empty_inode: bad free inode count.\n");nr_free_inodes = 0;}return inode;}

    struct inode * get_pipe_inode(void){struct inode * inode;extern struct inode_operations pipe_inode_operations;

    if (!(inode = get_empty_inode()))return NULL;if (!(PIPE_BASE(*inode) = (char*) __get_free_page(GFP_USER))) {iput(inode);return NULL;}inode->i_op = &pipe_inode_operations;inode->i_count = 2;/* sum of readers/writers */PIPE_WAIT(*inode) = NULL;PIPE_START(*inode) = PIPE_LEN(*inode) = 0;PIPE_RD_OPENERS(*inode) = PIPE_WR_OPENERS(*inode) = 0;PIPE_READERS(*inode) = PIPE_WRITERS(*inode) = 1;PIPE_LOCK(*inode) = 0;inode->i_pipe = 1;inode->i_mode |= S_IFIFO | S_IRUSR | S_IWUSR;inode->i_uid = current->euid;inode->i_gid = current->egid;inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;return inode;}

    struct inode * iget(struct super_block * sb,int nr){return __iget(sb,nr,1);}

    struct inode * __iget(struct super_block * sb, int nr, int crossmntp){static struct wait_queue * update_wait = NULL;struct inode_hash_entry * h;struct inode * inode;struct inode * empty = NULL;

    if (!sb)panic("VFS: iget with sb==NULL");h = hash(sb->s_dev, nr);repeat:for (inode = h->inode; inode ; inode = inode->i_hash_next)if (inode->i_dev == sb->s_dev && inode->i_ino == nr)goto found_it;if (!empty) {h->updating++;empty = get_empty_inode();if (!--h->updating)wake_up(&update_wait);if (empty)goto repeat;return (NULL);}inode = empty;inode->i_sb = sb;inode->i_dev = sb->s_dev;inode->i_ino = nr;inode->i_flags = sb->s_flags;put_last_free(inode);insert_inode_hash(inode);read_inode(inode);goto return_it;

    found_it:if (!inode->i_count)nr_free_inodes--;inode->i_count++;wait_on_inode(inode);if (inode->i_dev != sb->s_dev || inode->i_ino != nr) {printk("Whee.. inode changed from under us. Tell Linus\n");iput(inode);goto repeat;}if (crossmntp && inode->i_mount) {struct inode * tmp = inode->i_mount;tmp->i_count++;iput(inode);inode = tmp;wait_on_inode(inode);}if (empty)iput(empty);

    return_it:while (h->updating)sleep_on(&update_wait);return inode;}

    /* * The "new" scheduling primitives (new as of 0.97 or so) allow this to * be done without disabling interrupts (other than in the actual queue * updating things: only a couple of 386 instructions). This should be * much better for interrupt latency. */static void __wait_on_inode(struct inode * inode){struct wait_queue wait = { current, NULL };

    add_wait_queue(&inode->i_wait, &wait);repeat:current->state = TASK_UNINTERRUPTIBLE;if (inode->i_lock) {schedule();goto repeat;}remove_wait_queue(&inode->i_wait, &wait);current->state = TASK_RUNNING;}

    linux/fs/file_table.c

    /* * linux/fs/file_table.c * * Copyright (C) 1991, 1992 Linus Torvalds */

    #include #include #include

    struct file * first_file;int nr_files = 0;

    static void insert_file_free(struct file *file){file->f_next = first_file;file->f_prev = first_file->f_prev;file->f_next->f_prev = file;file->f_prev->f_next = file;first_file = file;}

    static void remove_file_free(struct file *file){if (first_file == file)first_file = first_file->f_next;if (file->f_next)file->f_next->f_prev = file->f_prev;if (file->f_prev)file->f_prev->f_next = file->f_next;file->f_next = file->f_prev = NULL;}

    static void put_last_free(struct file *file){remove_file_free(file);file->f_prev = first_file->f_prev;file->f_prev->f_next = file;file->f_next = first_file;file->f_next->f_prev = file;}

    void grow_files(void){struct file * file;int i;

    file = (struct file *) get_free_page(GFP_KERNEL);

    if (!file)return;

    nr_files+=i= PAGE_SIZE/sizeof(struct file);

    if (!first_file)file->f_next = file->f_prev = first_file = file++, i--;

    for (; i ; i--)insert_file_free(file++);}

    unsigned long file_table_init(unsigned long start, unsigned long end){first_file = NULL;return start;}

    struct file * get_empty_filp(void){int i;struct file * f;

    if (!first_file)grow_files();repeat:for (f = first_file, i=0; i < nr_files; i++, f = f->f_next)if (!f->f_count) {remove_file_free(f);memset(f,0,sizeof(*f));put_last_free(f);f->f_count = 1;return f;}if (nr_files < NR_FILE) {grow_files();goto repeat;}return NULL;}

    linux/fs/open.c

    /* * linux/fs/open.c * * Copyright (C) 1991, 1992 Linus Torvalds */

    #include #include #include #include #include #include #include #include #include #include #include #include

    #include

    extern void fcntl_remove_locks(struct task_struct *, struct file *, unsigned int fd);

    asmlinkage int sys_ustat(int dev, struct ustat * ubuf){return -ENOSYS;}

    asmlinkage int sys_statfs(const char * path, struct statfs * buf){struct inode * inode;int error;

    error = verify_area(VERIFY_WRITE, buf, sizeof(struct statfs));if (error)return error;error = namei(path,&inode);if (error)return error;if (!inode->i_sb->s_op->statfs) {iput(inode);return -ENOSYS;}inode->i_sb->s_op->statfs(inode->i_sb, buf);iput(inode);return 0;}

    asmlinkage int sys_fstatfs(unsigned int fd, struct statfs * buf){struct inode * inode;struct file * file;int error;

    error = verify_area(VERIFY_WRITE, buf, sizeof(struct statfs));if (error)return error;if (fd >= NR_OPEN || !(file = current->filp[fd]))return -EBADF;if (!(inode = file->f_inode))return -ENOENT;if (!inode->i_sb->s_op->statfs)return -ENOSYS;inode->i_sb->s_op->statfs(inode->i_sb, buf);return 0;}

    asmlinkage int sys_truncate(const char * path, unsigned int length){struct inode * inode;int error;

    error = namei(path,&inode);if (error)return error;if (S_ISDIR(inode->i_mode) || !permission(inode,MAY_WRITE)) {iput(inode);return -EACCES;}if (IS_RDONLY(inode)) {iput(inode);return -EROFS;}inode->i_size = length;if (inode->i_op && inode->i_op->truncate)inode->i_op->truncate(inode);inode->i_ctime = inode->i_mtime = CURRENT_TIME;inode->i_dirt = 1;error = notify_change(NOTIFY_SIZE, inode);iput(inode);return error;}

    asmlinkage int sys_ftruncate(unsigned int fd, unsigned int length){struct inode * inode;struct file * file;

    if (fd >= NR_OPEN || !(file = current->filp[fd]))return -EBADF;if (!(inode = file->f_inode))return -ENOENT;if (S_ISDIR(inode->i_mode) || !(file->f_mode & 2))return -EACCES;inode->i_size = length;if (inode->i_op && inode->i_op->truncate)inode->i_op->truncate(inode);inode->i_ctime = inode->i_mtime = CURRENT_TIME;inode->i_dirt = 1;return notify_change(NOTIFY_SIZE, inode);}

    /* If times==NULL, set access and modification to current time, * must be owner or have write permission. * Else, update from *times, must be owner or super user. */asmlinkage int sys_utime(char * filename, struct utimbuf * times){struct inode * inode;long actime,modtime;int error;

    error = namei(filename,&inode);if (error)return error;if (IS_RDONLY(inode)) {iput(inode);return -EROFS;}if (times) {if ((current->euid != inode->i_uid) && !suser()) {iput(inode);return -EPERM;}actime = get_fs_long((unsigned long *) &times->actime);modtime = get_fs_long((unsigned long *) &times->modtime);inode->i_ctime = CURRENT_TIME;} else {if ((current->euid != inode->i_uid) && !permission(inode,MAY_WRITE)) {iput(inode);return -EACCES;}actime = modtime = inode->i_ctime = CURRENT_TIME;}inode->i_atime = actime;inode->i_mtime = modtime;inode->i_dirt = 1;error = notify_change(NOTIFY_TIME, inode);iput(inode);return error;}

    /* * XXX we should use the real ids for checking _all_ components of the * path. Now we only use them for the final component of the path. */asmlinkage int sys_access(const char * filename,int mode){struct inode * inode;int res, i_mode;

    if (mode != (mode & S_IRWXO))/* where's F_OK, X_OK, W_OK, R_OK? */return -EINVAL;res = namei(filename,&inode);if (res)return res;i_mode = inode->i_mode;res = i_mode & S_IRWXUGO;if (current->uid == inode->i_uid)res >>= 6;/* needs cleaning? */else if (in_group_p(inode->i_gid))res >>= 3;/* needs cleaning? */iput(inode);if ((res & mode) == mode)return 0;/* * XXX we are doing this test last because we really should be * swapping the effective with the real user id (temporarily), * and then calling suser() routine. If we do call the * suser() routine, it needs to be called last. * * XXX nope. suser() is inappropriate and swapping the ids while * decomposing the path would be racy. */if ((!current->uid) && (S_ISDIR(i_mode) || !(mode & S_IXOTH) || (i_mode & S_IXUGO)))return 0;return -EACCES;}

    asmlinkage int sys_chdir(const char * filename){struct inode * inode;int error;

    error = namei(filename,&inode);if (error)return error;if (!S_ISDIR(inode->i_mode)) {iput(inode);return -ENOTDIR;}if (!permission(inode,MAY_EXEC)) {iput(inode);return -EACCES;}iput(current->pwd);current->pwd = inode;return (0);}

    asmlinkage int sys_fchdir(unsigned int fd){struct inode * inode;struct file * file;

    if (fd >= NR_OPEN || !(file = current->filp[fd]))return -EBADF;if (!(inode = file->f_inode))return -ENOENT;if (!S_ISDIR(inode->i_mode))return -ENOTDIR;if (!permission(inode,MAY_EXEC))return -EACCES;iput(current->pwd);current->pwd = inode;inode->i_count++;return (0);}

    asmlinkage int sys_chroot(const char * filename){struct inode * inode;int error;

    error = namei(filename,&inode);if (error)return error;if (!S_ISDIR(inode->i_mode)) {iput(inode);return -ENOTDIR;}if (!suser()) {iput(inode);return -EPERM;}iput(current->root);current->root = inode;return (0);}

    asmlinkage int sys_fchmod(unsigned int fd, mode_t mode){struct inode * inode;struct file * file;

    if (fd >= NR_OPEN || !(file = current->filp[fd]))return -EBADF;if (!(inode = file->f_inode))return -ENOENT;if ((current->euid != inode->i_uid) && !suser())return -EPERM;if (IS_RDONLY(inode))return -EROFS;if (mode == (mode_t) -1)mode = inode->i_mode;inode->i_mode = (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO);if (!suser() && !in_group_p(inode->i_gid))inode->i_mode &= ~S_ISGID;inode->i_ctime = CURRENT_TIME;inode->i_dirt = 1;return notify_change(NOTIFY_MODE, inode);}

    asmlinkage int sys_chmod(const char * filename, mode_t mode){struct inode * inode;int error;

    error = namei(filename,&inode);if (error)return error;if ((current->euid != inode->i_uid) && !suser()) {iput(inode);return -EPERM;}if (IS_RDONLY(inode)) {iput(inode);return -EROFS;}if (mode == (mode_t) -1)mode = inode->i_mode;inode->i_mode = (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO);if (!suser() && !in_group_p(inode->i_gid))inode->i_mode &= ~S_ISGID;inode->i_ctime = CURRENT_TIME;inode->i_dirt = 1;error = notify_change(NOTIFY_MODE, inode);iput(inode);return error;}

    asmlinkage int sys_fchown(unsigned int fd, uid_t user, gid_t group){struct inode * inode;struct file * file;

    if (fd >= NR_OPEN || !(file = current->filp[fd]))return -EBADF;if (!(inode = file->f_inode))return -ENOENT;if (IS_RDONLY(inode))return -EROFS;if (user == (uid_t) -1)user = inode->i_uid;if (group == (gid_t) -1)group = inode->i_gid;if ((current->euid == inode->i_uid && user == inode->i_uid && (in_group_p(group) || group == inode->i_gid)) || suser()) {inode->i_uid = user;inode->i_gid = group;inode->i_ctime = CURRENT_TIME;inode->i_dirt = 1;return notify_change(NOTIFY_UIDGID, inode);}return -EPERM;}

    asmlinkage int sys_chown(const char * filename, uid_t user, gid_t group){struct inode * inode;int error;

    error = lnamei(filename,&inode);if (error)return error;if (IS_RDONLY(inode)) {iput(inode);return -EROFS;}if (user == (uid_t) -1)user = inode->i_uid;if (group == (gid_t) -1)group = inode->i_gid;if ((current->euid == inode->i_uid && user == inode->i_uid && (in_group_p(group) || group == inode->i_gid)) || suser()) {inode->i_uid = user;inode->i_gid = group;inode->i_ctime = CURRENT_TIME;inode->i_dirt = 1;error = notify_change(NOTIFY_UIDGID, inode);iput(inode);return error;}iput(inode);return -EPERM;}

    /* * Note that while the flag value (low two bits) for sys_open means: *00 - read-only *01 - write-only *10 - read-write *11 - special * it is changed into *00 - no permissions needed *01 - read-permission *10 - write-permission *11 - read-write * for the internal routines (ie open_namei()/follow_link() etc). 00 is * used by symlinks. */int do_open(const char * filename,int flags,int mode){struct inode * inode;struct file * f;int flag,error,fd;

    for(fd=0 ; fdfilp[fd])break;if (fd>=NR_OPEN)return -EMFILE;FD_CLR(fd,&current->close_on_exec);f = get_empty_filp();if (!f)return -ENFILE;current->filp[fd] = f;f->f_flags = flag = flags;f->f_mode = (flag+1) & O_ACCMODE;if (f->f_mode)flag++;if (flag & (O_TRUNC | O_CREAT))flag |= 2;error = open_namei