⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 volume.c

📁 Windows操作系统中文件系统过滤驱动和设备驱动之间的相似
💻 C
📖 第 1 页 / 共 5 页
字号:
//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// This source code is licensed under Microsoft Shared Source License
// Version 1.0 for Windows CE.
// For a copy of the license visit http://go.microsoft.com/fwlink/?LinkId=3223.
//
/*++


Module Name:

    volume.c

Abstract:

    This file contains routines for mounting volumes, direct volume access, etc.

Revision History:

--*/

#include "fatfs.h"

// Warning if you change this then change storemgr.h
static const GUID FATFS_MOUNT_GUID = { 0x169e1941, 0x4ce, 0x4690, { 0x97, 0xac, 0x77, 0x61, 0x87, 0xeb, 0x67, 0xcc } };

#if defined(UNDER_WIN95) && !defined(INCLUDE_FATFS)
#include <pcmd.h>               // for interacting with ReadVolume/WriteVolume
#endif


ERRFALSE(offsetof(BOOTSEC, bsBPB) == offsetof(BIGFATBOOTSEC, bgbsBPB));


/*  ReadVolume
 *
 *  Like ReadWriteDisk, except it takes a PVOLUME, and it works with
 *  volume-relative BLOCKS instead of disk-relative SECTORS.
 *
 *  For now, the caller must specify a block number that starts on a sector
 *  boundary, and the number of blocks must map to a whole number of sectors.
 *
 *  Entry:
 *      pvol        address of VOLUME structure
 *      block       0-based block number
 *      cBlocks     number of blocks to read
 *      pvBuffer    address of buffer to read sectors into
 *
 *  Exit:
 *      ERROR_SUCCESS if successful, else GetLastError() from the FSDMGR_DiskIoControl call issued
 */         

DWORD ReadVolume(PVOLUME pvol, DWORD block, int cBlocks, PVOID pvBuffer)
{
#ifdef UNDER_WIN95
    if (ZONE_BUFFERS && ZONE_PROMPTS) {
        WCHAR wsBuf[10];
        DBGPRINTFW(TEXTW("Read:  block %d, total %d;  allow (Y/N)? "), block, cBlocks);
        DBGSCANFW(wsBuf, ARRAYSIZE(wsBuf));
        if (TOLOWER(wsBuf[0]) == 'n')
            return ERROR_BAD_UNIT;
    }
#endif

    // Assert that the shifted bits in both block and cBlocks are zero

    ASSERT(pvol->v_log2cblkSec<=0? 1 : (((block | cBlocks) & ((1 << pvol->v_log2cblkSec) - 1)) == 0));

    if (pvol->v_flags & VOLF_FROZEN) {
        DEBUGMSG(ZONE_INIT || ZONE_ERRORS,(DBGTEXT("FATFS!ReadVolume: frozen volume, cannot read block %d!\r\n"), block));
        return ERROR_DEV_NOT_EXIST;
    }

    // NOTE that all sectors computed in this function are relative to
    // block 0, and that before they are passed to ReadWriteDisk, they are
    // adjusted by v_secBlkBias (the sector bias for block 0).  Thus, it is
    // impossible for this function to read from any of the volume's reserved
    // sectors (eg, the boot sector and BPB) or hidden sectors, because they
    // precede block 0.
    //
    // See the code in IOCTL_DISK_READ_SECTORS and IOCTL_DISK_WRITE_SECTORS
    // to access sectors outside the normal block range.

    return ReadWriteDisk(pvol, pvol->v_pdsk->d_hdsk, READ_DISK_CMD, &pvol->v_pdsk->d_diActive, 
        pvol->v_secBlkBias + (block>>pvol->v_log2cblkSec), (cBlocks>>pvol->v_log2cblkSec), pvBuffer, TRUE);
}


/*  WriteVolume
 *
 *  Like ReadWriteDisk, except it takes a PVOLUME, and it works with
 *  volume-relative BLOCKS instead of disk-relative SECTORS.
 *
 *  For now, the caller must specify a block number that starts on a sector
 *  boundary, and the number of blocks must map to a whole number of sectors.
 *
 *  Entry:
 *      pvol        address of VOLUME structure
 *      block       0-based block number
 *      cBlocks     number of blocks to write
 *      pvBuffer    address of buffer to write sectors from
 *
 *  Exit:
 *      ERROR_SUCCESS if successful, else GetLastError() from the FSDMGR_DiskIoControl call issued
 */         
// 将传入的内容通过调用函数ReadWriteDisk 写到磁盘中去
DWORD WriteVolume(PVOLUME pvol, DWORD block, int cBlocks, PVOID pvBuffer, BOOL fWriteThrough)
{
    DWORD sec, csec;

#ifdef UNDER_WIN95
    if (ZONE_BUFFERS && ZONE_PROMPTS) {
        WCHAR wsBuf[10];
        DBGPRINTFW(TEXTW("Write: block %d, total %d;  allow (Y/N)? "), block, cBlocks);
        DBGSCANFW(wsBuf, ARRAYSIZE(wsBuf));
        if (TOLOWER(wsBuf[0]) == 'n')
            return ERROR_BAD_UNIT;
    }
#endif

    // Assert that the shifted bits in both block and cBlocks are zero
    // 如果括号中的条件为假,则程序终止并输出位置信息
    ASSERT(pvol->v_log2cblkSec<=0? 1 : (((block | cBlocks) & ((1 << pvol->v_log2cblkSec) - 1)) == 0));

    if (pvol->v_flags & VOLF_FROZEN) {
        DEBUGMSG(ZONE_INIT || ZONE_ERRORS,(DBGTEXT("FATFS!WriteVolume: frozen volume, cannot write block %d!\r\n"), block));
        return ERROR_DEV_NOT_EXIST;
    }

    // NOTE that all sectors computed in this function are relative to
    // block 0, and that before they are passed to ReadWriteDisk, they are
    // adjusted by v_secBlkBias (the sector bias for block 0).  Thus, it is
    // impossible for this function to write to any of the volume's reserved
    // sectors (eg, the boot sector and BPB) or hidden sectors, because they
    // precede block 0.
    //
    // See the code in IOCTL_DISK_READ_SECTORS and IOCTL_DISK_WRITE_SECTORS
    // to access sectors outside the normal block range.
    // 计算sector的个数
    sec = block >> pvol->v_log2cblkSec;
    csec = cBlocks >> pvol->v_log2cblkSec;

    // If we have multiple FATs, and we're writing to the FAT region,
    // adjust and/or mirror the write appropriately.

#ifdef TFAT   //  no backup FAT support on TFAT
    if (!pvol->v_fTfat)
#endif
    {
        if ((pvol->v_flags & VOLF_BACKUP_FAT) && sec < pvol->v_secEndAllFATs) {
            DWORD secEnd, secBackup;

            secEnd = sec + csec;

            // Check for write to root directory area that starts inside
            // a backup FAT.  Backup FATs are not buffered, hence any buffered
            // data inside the range of the backup FAT could be stale and
            // must NOT be written.

            if (sec >= pvol->v_secEndFAT) {
                ASSERT(secEnd > pvol->v_secEndAllFATs);
                csec = secEnd - pvol->v_secEndAllFATs;
                sec = pvol->v_secEndAllFATs;
                goto write;
            }

            // Check for write to end of the active FAT that ends inside
            // a backup FAT.  Backup FATs are not buffered, hence any buffered
            // data inside the range of the backup FAT could be stale and
            // must NOT be written.

            secBackup = sec;

            if (secEnd > pvol->v_secEndFAT) {

                DWORD csecFATWrite;

                csecFATWrite = pvol->v_secEndFAT - sec;
                //带书写的内容位于包括了对fat2的操作
                if (secEnd < pvol->v_secEndAllFATs) {
                    csec = csecFATWrite;
                }
                else {
                    //待写入的内容既包括了fat表,又包括了data的区域数据
                    DWORD cbFATWrite;
                    PBYTE pFAT, pFATBackup;

                    // The current buffer spans all the FATs, so we need to
                    // copy the FAT data to the backup FAT location(s) instead of
                    // doing extra writes.

                    pFAT = (PBYTE)pvBuffer;
                    pFATBackup = pFAT + (pvol->v_csecFAT << pvol->v_log2cbSec);
                    cbFATWrite = (csecFATWrite << pvol->v_log2cbSec);     
                    //fat表的操作是以sector为单位的
                    while ((secBackup += pvol->v_csecFAT) < pvol->v_secEndAllFATs) {
                        memcpy(pFATBackup, pFAT, cbFATWrite);
                        pFATBackup += pvol->v_csecFAT << pvol->v_log2cbSec;
                    }
                    goto write;
                }
            }

            // If we're still here, we've got a FAT write that's been restricted
            // to the just the sectors within the active FAT.  Start cycling through
            // the backup FATs now.   
            while ((secBackup += pvol->v_csecFAT) < pvol->v_secEndAllFATs) {

                DEBUGMSG(ZONE_FATIO,(DBGTEXT("FATFS!WriteVolume: mirroring %d FAT sectors at %d to %d\r\n"), csec, sec, secBackup));

                ASSERT(secBackup + csec <= pvol->v_secEndAllFATs);

                // We ignore any error here, on the assumption that perhaps the
                // backup FAT has simply gone bad.
                // warning
                // warning
                // warning
                // warning
                // warning
                // warning
                // warning
                // warning
                // warning
                // warning
                ReadWriteDisk(pvol, pvol->v_pdsk->d_hdsk, WRITE_DISK_CMD, &pvol->v_pdsk->d_diActive, 
                    pvol->v_secBlkBias + secBackup, csec, pvBuffer, TRUE);
            }
        }
    }
  write:

    // TEST_BREAK
    PWR_BREAK_NOTIFY(51);
    
    return ReadWriteDisk(pvol, pvol->v_pdsk->d_hdsk, fWriteThrough ? WRITETHROUGH_DISK_CMD : WRITE_DISK_CMD, 
        &pvol->v_pdsk->d_diActive, pvol->v_secBlkBias + sec, csec, pvBuffer, TRUE);        
}


/*  InitVolume - Initialize a VOLUME structure
 *
 *  ENTRY
 *      pvol - pointer to VOLUME
 *      pbgbs - pointer to PBR (partition boot record) for volume
 *
 *  EXIT
 *      TRUE if VOLUME structure successfully initialized, FALSE if not
 */

BOOL InitVolume(PVOLUME pvol, PBIGFATBOOTSEC pbgbs)
{
    DWORD cmaxClus;
    PBIGFATBPB pbpb;
    PDSTREAM pstmFAT;
    PDSTREAM pstmRoot;

    ASSERT(OWNCRITICALSECTION(&pvol->v_cs));

    //清除volume的相关标记位
    pvol->v_flags &= ~(VOLF_INVALID | VOLF_12BIT_FAT | VOLF_16BIT_FAT | VOLF_32BIT_FAT | VOLF_BACKUP_FAT);

    // Initialize the cache IDs
    // 清楚fatcache和datacache的相关标记
    pvol->v_FATCacheId = INVALID_CACHE_ID;
    pvol->v_DataCacheId = INVALID_CACHE_ID;


#ifdef TFAT

    pvol->v_fTfat = FALSE;
    if ((memcmp(pbgbs->bgbsFileSysType, "TFAT", 4) == 0) ||
         (memcmp(((PBOOTSEC)pbgbs)->bsFileSysType, "TFAT", 4) == 0) ||
         ((pvol->v_flFATFS & FATFS_FORCE_TFAT) && (pbgbs->bgbsBPB.oldBPB.BPB_NumberOfFATs == 2 ||
         pbgbs->bgbsBPB.oldBPB.BPB_NumberOfFATs == 0)))
    {
        pvol->v_fTfat = TRUE;

        if (pbgbs->bgbsBPB.oldBPB.BPB_NumberOfFATs == 0)
        {
            // Last transacation was not done yet, we will sync FAT later. For now, change NOF back in order 
            // to init the volume properly
            pbgbs->bgbsBPB.oldBPB.BPB_NumberOfFATs = 2;
        }        
    }
    
#endif
    //为pvol的buffer建立一个事件,可能后续会用来进行同步之类的
    //根据注册表项中buffersize的值进行buffer的分配并建立链表
    if (!BufInit (pvol) || !AllocBufferPool(pvol))
        return FALSE;

    // Allocate special DSTREAMs for the FAT and the root directory,
    // using PSEUDO cluster numbers 0 and 1.  Root directories of FAT32
    // volumes do have a REAL cluster number, and if we're in a nested init
    // path, we need to use it, but otherwise we'll just use ROOT_PSEUDO_CLUSTER
    // and record the real cluster number when we figure it out, in the
    // FAT32-specific code farther down...

    pstmFAT = OpenStream(pvol, FAT_PSEUDO_CLUSTER, NULL, NULL, NULL, OPENSTREAM_CREATE);
    ASSERT(pvol->v_pstmFAT == NULL || pvol->v_pstmFAT == pstmFAT);

    pstmRoot = OpenStream(pvol, pvol->v_pstmRoot? pvol->v_pstmRoot->s_clusFirst : ROOT_PSEUDO_CLUSTER, NULL, NULL, NULL, OPENSTREAM_CREATE);

    ASSERT(pvol->v_pstmRoot == NULL || pvol->v_pstmRoot == pstmRoot);

    if (!pstmFAT || !pstmRoot)
        goto exit;

    // Add extra refs to these special streams to make them stick around;
    // we only want to do this if the current open is their only reference,
    // because if they've been resurrected, then they still have their original
    // extra refs.

    if (pstmFAT->s_refs == 1) {
        pstmFAT->s_refs++;
    }

    if (pstmRoot->s_refs == 1) {
        pstmRoot->s_refs++;
    }

    pvol->v_pstmFAT = pstmFAT;
    pvol->v_pstmRoot = pstmRoot;
    // 文件属性单元
    pstmRoot->s_attr = ATTR_DIRECTORY;

    // We have completed the required stream initialization for this
    // volume.  Now perform boot sector verification and BPB validation.
    // 上面完成了fatstream和rootstream的初始化工作,接下来将对bootsec和bpb单元进行处理
    if (pvol->v_pdsk->d_diActive.di_flags & DISK_INFO_FLAG_UNFORMATTED) {
        RETAILMSG(TRUE,(DBGTEXT("FATFS!InitVolume: driver has set 'unformatted' bit, marking volume invalid\r\n")));
        pvol->v_flags |= VOLF_INVALID;
    }
   
    if (!(pvol->v_flags & VOLF_INVALID)) 
    {
        // 验证bootsector  初始化跳转指令单元
        if (pbgbs->bgbsJump[0] != BSNOP     &&
            pbgbs->bgbsJump[0] != BS2BYTJMP &&
            pbgbs->bgbsJump[0] != BS3BYTJMP) 
        {
            RETAILMSG(TRUE,(DBGTEXT("FATFS!InitVolume: sector 0 byte 0 suspicious (0x%x)\r\n"), pbgbs->bgbsJump[0]));
        }
        // 对bpb的相关属性进行验证,即BytesPerSector,BPB_NumberOfFATs,BPB_NumberOfFATs以及BPB结束标志
        if (pbgbs->bgbsBPB.oldBPB.BPB_BytesPerSector < DEFAULT_SECTOR_SIZE ||
            Log2(pbgbs->bgbsBPB.oldBPB.BPB_BytesPerSector) == -1 ||
            pbgbs->bgbsBPB.oldBPB.BPB_NumberOfFATs < 1 ||
            *(PWORD)((PBYTE)pbgbs+DEFAULT_SECTOR_SIZE-2) != BOOTSECTRAILSIGH) {
            DEBUGMSG(ZONE_INIT || ZONE_ERRORS,(DBGTEXT("FATFS!InitVolume: invalid BPB, volume deemed invalid\r\n")));
            pvol->v_flags |= VOLF_INVALID;
        }        

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -