fatfs.c 62.0 KB
Newer Older
1
/*
2 3
 * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "fatfs.h"
#ifdef LOSCFG_FS_FAT
#include "ff.h"
#include "disk_pri.h"
36
#include "diskio.h"
37
#include "fs/file.h"
38 39 40
#include "fs/fs.h"
#include "fs/dirent_fs.h"
#include "fs/mount.h"
41 42
#include "vnode.h"
#include "path_cache.h"
43 44
#ifdef LOSCFG_FS_FAT_VIRTUAL_PARTITION
#include "virpartff.h"
45
#include "errcode_fat.h"
46
#endif
47 48
#include "los_tables.h"
#include "user_copy.h"
49
#include "los_vm_filemap.h"
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
50
#include "los_hash.h"
51
#include "los_vm_common.h"
52 53 54 55 56 57 58
#include <time.h>
#include <errno.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
59
#include <fcntl.h>
60

61 62 63
/**
 * @brief 
 * @verbatim
64 65 66 67 68 69 70 71 72 73 74 75 76 77
FAT文件系统是File Allocation Table(文件配置表)的简称,主要包括DBR区、FAT区、DATA区三个区域。
其中,FAT区各个表项记录存储设备中对应簇的信息,包括簇是否被使用、文件下一个簇的编号、是否文件结尾等。
FAT文件系统有FAT12、FAT16、FAT32等多种格式,其中,12、16、32表示对应格式中FAT表项的字节数。
FAT文件系统支持多种介质,特别在可移动存储介质(U盘、SD卡、移动硬盘等)上广泛使用,
使嵌入式设备和Windows、Linux等桌面系统保持很好的兼容性,方便用户管理操作文件。

OpenHarmony内核支持FAT12、FAT16与FAT32三种格式的FAT文件系统,
具有代码量小、资源占用小、可裁切、支持多种物理介质等特性,并且与Windows、Linux等系统保持兼容,
支持多设备、多分区识别等功能。OpenHarmony内核支持硬盘多分区,可以在主分区以及逻辑分区上创建FAT文件系统。

驱动适配
	FAT文件系统的使用需要底层MMC相关驱动的支持。在一个带MMC存储设备的板子上运行FATFS,需要:
	1、适配板端EMMC驱动,实现disk_status、disk_initialize、disk_read、disk_write、disk_ioctl接口;
	2、新增fs_config.h文件,配置FS_MAX_SS(存储设备最大sector大小)、FF_VOLUME_STRS(分区名)等信息,
78 79
 * @endverbatim
 */
80 81 82 83 84 85 86 87

struct VnodeOps fatfs_vops; /* forward define */
struct file_operations_vfs fatfs_fops;

#define BITMASK4 0x0F
#define BITMASK5 0x1F
#define BITMASK6 0x3F
#define BITMASK7 0x7F
88 89 90 91 92
#define FTIME_MIN_OFFSET 6 /*! minute offset in word */
#define FTIME_HR_OFFSET 11 /*! hour offset in word */
#define FTIME_MTH_OFFSET 5 /*! month offset in word */
#define FTIME_YEAR_OFFSET 9 /*! year offset in word */
#define FTIME_DATE_OFFSET 16 /*! date offset in dword */
93
#define SEC_MULTIPLIER 2
94
#define YEAR_OFFSET 80 /*! Year start from 1980 in FATFS, while start from 1900 in struct tm */
95
// 结果转化 fat 转 vfs
96
int fatfs_2_vfs(int result)
97
{
98
    int status = ENOERR;
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

#ifdef LOSCFG_FS_FAT_VIRTUAL_PARTITION
    if (result < 0 || result >= VIRERR_BASE) {
        return result;
    }
#else
    if (result < 0) {
        return result;
    }
#endif

    /* FatFs errno to Libc errno */
    switch (result) {
        case FR_OK:
            break;

        case FR_NO_FILE:
        case FR_NO_PATH:
117
            status = ENOENT;
118 119
            break;

120 121 122 123
        case FR_NO_FILESYSTEM:
            status = ENOTSUP;
            break;

124
        case FR_INVALID_NAME:
125
            status = EINVAL;
126 127 128 129
            break;

        case FR_EXIST:
        case FR_INVALID_OBJECT:
130
            status = EEXIST;
131 132 133 134 135
            break;

        case FR_DISK_ERR:
        case FR_NOT_READY:
        case FR_INT_ERR:
136
            status = EIO;
137 138 139
            break;

        case FR_WRITE_PROTECTED:
140
            status = EROFS;
141 142 143
            break;
        case FR_MKFS_ABORTED:
        case FR_INVALID_PARAMETER:
144
            status = EINVAL;
145 146 147
            break;

        case FR_NO_SPACE_LEFT:
148
            status = ENOSPC;
149 150
            break;
        case FR_NO_DIRENTRY:
151
            status = ENFILE;
152 153
            break;
        case FR_NO_EMPTY_DIR:
154
            status = ENOTEMPTY;
155 156
            break;
        case FR_IS_DIR:
157
            status = EISDIR;
158 159
            break;
        case FR_NO_DIR:
160
            status = ENOTDIR;
161 162 163
            break;
        case FR_NO_EPERM:
        case FR_DENIED:
164
            status = EPERM;
165 166
            break;
        case FR_LOCKED:
167 168
        case FR_TIMEOUT:
            status = EBUSY;
169 170 171
            break;
#ifdef LOSCFG_FS_FAT_VIRTUAL_PARTITION
        case FR_MODIFIED:
172
            status = -VIRERR_MODIFIED;
173 174
            break;
        case FR_CHAIN_ERR:
175
            status = -VIRERR_CHAIN_ERR;
176 177
            break;
        case FR_OCCUPIED:
178
            status = -VIRERR_OCCUPIED;
179 180
            break;
        case FR_NOTCLEAR:
181
            status = -VIRERR_NOTCLEAR;
182 183
            break;
        case FR_NOTFIT:
184
            status = -VIRERR_NOTFIT;
185 186
            break;
        case FR_INVAILD_FATFS:
187
            status = -VIRERR_INTER_ERR;
188 189 190
            break;
#endif
        default:
191
            status = -FAT_ERROR;
192 193 194 195 196 197
            break;
    }

    return status;
}

198 199 200 201 202 203 204 205 206 207 208 209 210
static bool fatfs_is_last_cluster(FATFS *fs, DWORD cclust)
{
    switch (fs->fs_type) {
        case FS_FAT12:
            return (cclust == FAT12_END_OF_CLUSTER);
        case FS_FAT16:
            return (cclust == FAT16_END_OF_CLUSTER);
        case FS_FAT32:
        default:
            return (cclust == FAT32_END_OF_CLUSTER);
    }
}

211
static int fatfs_sync(unsigned long mountflags, FATFS *fs)
212
{
213
#ifdef LOSCFG_FS_FAT_CACHE
214
    los_part *part = NULL;
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
215
    if (!(mountflags & (MS_NOSYNC | MS_RDONLY))) {
216 217 218 219
        part = get_part((INT)fs->pdrv);
        if (part == NULL) {
            return -ENODEV;
        }
220

221
        (void)OsSdSync(part->disk_id);
222 223
    }
#endif
224
    return 0;
225
}
226
///哈希值比较函数,返回int
227
//typedef int VfsHashCmp(struct Vnode *vnode, void *arg);
228 229 230 231
int fatfs_hash_cmp(struct Vnode *vp, void *arg)
{
    DIR_FILE *dfp_target = (DIR_FILE *)arg;
    DIR_FILE *dfp = (DIR_FILE *)vp->data;
232

233 234 235 236
    return dfp_target->f_dir.sect != dfp->f_dir.sect ||
              dfp_target->f_dir.dptr != dfp->f_dir.dptr ||
              dfp_target->fno.sclst != dfp->fno.sclst;
}
237
///生成hash值的过程
238
static DWORD fatfs_hash(QWORD sect, DWORD dptr, DWORD sclst)
239
{
240 241 242 243
    DWORD hash = FNV1_32A_INIT;
    hash = LOS_HashFNV32aBuf(&sect, sizeof(QWORD), hash);
    hash = LOS_HashFNV32aBuf(&dptr, sizeof(DWORD), hash);
    hash = LOS_HashFNV32aBuf(&sclst, sizeof(DWORD), hash);
244

245
    return hash;
246 247
}

248 249 250 251 252
static mode_t fatfs_get_mode(BYTE attribute, mode_t fs_mode)
{
    mode_t mask = 0;
    if (attribute & AM_RDO) {
        mask = S_IWUSR | S_IWGRP | S_IWOTH;
253
    }
254 255 256
    fs_mode &= ~mask;
    if (attribute & AM_DIR) {
        fs_mode |= S_IFDIR;
257 258
    } else if (attribute & AM_LNK) {
        fs_mode |= S_IFLNK;
259 260
    } else {
        fs_mode |= S_IFREG;
261
    }
262
    return fs_mode;
263
}
264
///类型转换
265 266
static enum VnodeType fatfstype_2_vnodetype(BYTE type) 
{
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    switch (type) {
        case AM_ARC:
            return VNODE_TYPE_REG;
        case AM_DIR:
            return VNODE_TYPE_DIR;
        case AM_LNK:
            return VNODE_TYPE_LNK;
        default:
            return VNODE_TYPE_UNKNOWN;
    }
}

#define DIR_SIZE 32
static FRESULT init_cluster(DIR_FILE *pdfp, DIR *dp_new, FATFS *fs, int type, const char *target, DWORD *clust)
{
    FRESULT result;
    BYTE *dir = NULL;
    QWORD sect;
    DWORD pclust;
    UINT n;

    /* Allocate a new cluster */
    *clust = create_chain(&(dp_new->obj), 0);
    if (*clust == 0) {
        return FR_NO_SPACE_LEFT;
    }
    if (*clust == 1 || *clust == DISK_ERROR) {
        return FR_DISK_ERR;
    }

    result = sync_window(fs); /* Flush FAT */
    if (result != FR_OK) {
        remove_chain(&(dp_new->obj), *clust, 0);
        return result;
    }

    /* Initialize the new cluster */
#ifndef LOSCFG_FS_FAT_VIRTUAL_PARTITION
    dir = fs->win;
#else
    dir = PARENTFS(fs)->win;
#endif

    sect = clst2sect(fs, *clust);
    mem_set(dir, 0, SS(fs));
    if (type == AM_LNK && target) {
        /* Write target to symlink */
314
        (void)strcpy_s((char *)dir, SS(fs), target);
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    } else {
        /* Write the dir cluster */
        mem_set(dir, 0, SS(fs));
        mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */
        dir[DIR_Name] = '.';
        dir[DIR_Attr] = AM_DIR;
        st_clust(fs, dir, *clust);
        mem_cpy(dir + DIR_SIZE, dir, DIR_SIZE); /* Create ".." entry */
        dir[DIR_SIZE + 1] = '.'; /* Add extra "." */
        pclust = pdfp->fno.sclst;
        if (fs->fs_type == FS_FAT32 && pclust == fs->dirbase) {
            pclust = 0;
        }
        st_clust(fs, dir + DIR_SIZE, pclust);
    }

#ifndef LOSCFG_FS_FAT_VIRTUAL_PARTITION
    fs->winsect = sect++;
    fs->wflag = 1;
#else
    PARENTFS(fs)->winsect = sect++;
    PARENTFS(fs)->wflag = 1;
#endif
    result = sync_window(fs);
    if (result != FR_OK) {
        remove_chain(&(dp_new->obj), *clust, 0);
        return result;
    }

    /* Rest of directory cluster should set to be zero */
    if (type == AM_DIR) {
        mem_set(dir, 0, SS(fs));
        for (n = fs->csize - 1; n > 0; n--) {
#ifndef LOSCFG_FS_FAT_VIRTUAL_PARTITION
            fs->winsect = sect++;
            fs->wflag = 1;
#else
            PARENTFS(fs)->winsect = sect++;
            PARENTFS(fs)->wflag = 1;
#endif
            result = sync_window(fs);
            if (result != FR_OK) {
                remove_chain(&(dp_new->obj), *clust, 0);
                return result;
            }
        }
    }

    return FR_OK;
}

static int fatfs_create_obj(struct Vnode *parent, const char *name, int mode, struct Vnode **vpp, BYTE type, const char *target)
{
    struct Vnode *vp = NULL;
    FATFS *fs = (FATFS *)parent->originMount->data;
    DIR_FILE *dfp = (DIR_FILE *)parent->data;
    FILINFO *finfo = &(dfp->fno);
    DIR_FILE *dfp_new = NULL;
    FILINFO *finfo_new = NULL;
    DIR *dp_new = NULL;
    QWORD time;
    DWORD hash;
    DWORD clust = 0;
    FRESULT result;
    int ret;

381
    if ((type != AM_ARC) && (type != AM_DIR) && (type != AM_LNK)) {//文件类型
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
        result = FR_INVALID_NAME;
        goto ERROR_EXIT;
    }

    dfp_new = (DIR_FILE *)zalloc(sizeof(DIR_FILE));
    if (dfp_new == NULL) {
        result = FR_NOT_ENOUGH_CORE;
        goto ERROR_EXIT;
    }

    ret = lock_fs(fs);
    if (ret == FALSE) { /* lock failed */
        result = FR_TIMEOUT;
        goto ERROR_FREE;
    }

    if (finfo->fattrib & AM_ARC || finfo->fattrib & AM_LNK) {
        result = FR_NO_DIR;
        goto ERROR_UNLOCK;
    }

    finfo_new = &(dfp_new->fno);
    LOS_ListInit(&finfo_new->fp_list);
    dp_new = &(dfp_new->f_dir);
    dp_new->obj.fs = fs;
    dp_new->obj.sclust = finfo->sclst;

    DEF_NAMBUF;
    INIT_NAMBUF(fs);

    result = create_name(dp_new, &name);
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
    }

    result = dir_find(dp_new);
    if (result == FR_OK) {
        result = FR_EXIST;
        goto ERROR_UNLOCK;
    }

    if (type == AM_DIR || type == AM_LNK) {
        result = init_cluster(dfp, dp_new, fs, type, target, &clust);
        if (result != FR_OK) {
            goto ERROR_UNLOCK;
        }
    }

    result = dir_register(dp_new);
    if (result != FR_OK) {
        goto ERROR_REMOVE_CHAIN;
    }

    /* Set the directory entry attribute */
    if (time_status == SYSTEM_TIME_ENABLE) {
        time = GET_FATTIME();
    } else {
        time = 0;
    }
    st_dword(dp_new->dir + DIR_CrtTime, time);
    st_dword(dp_new->dir + DIR_ModTime, time);
    st_word(dp_new->dir + DIR_LstAccDate, time >> FTIME_DATE_OFFSET);
    dp_new->dir[DIR_Attr] = type;
    if (((DWORD)mode & S_IWUSR) == 0) {
        dp_new->dir[DIR_Attr] |= AM_RDO;
    }
    st_clust(fs, dp_new->dir, clust);
    if (type == AM_ARC) {
        st_dword(dp_new->dir + DIR_FileSize, 0);
    } else if (type == AM_LNK) {
        st_dword(dp_new->dir + DIR_FileSize, strlen(target));
    }

#ifdef LOSCFG_FS_FAT_VIRTUAL_PARTITION
    PARENTFS(fs)->wflag = 1;
#else
    fs->wflag = 1;
#endif
    result = sync_fs(fs);
    if (result != FR_OK) {
        goto ERROR_REMOVE_CHAIN;
    }
    result = dir_read(dp_new, 0);
    if (result != FR_OK) {
        goto ERROR_REMOVE_CHAIN;
    }
    dp_new->blk_ofs = dir_ofs(dp_new);
    get_fileinfo(dp_new, finfo_new);
    if (type == AM_ARC) {
        dp_new->obj.objsize = 0;
    } else if (type == AM_LNK) {
        dp_new->obj.objsize = strlen(target);
474 475
    } else {
        finfo_new->fsize = fs->csize * SS(fs);
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    }

    ret = VnodeAlloc(&fatfs_vops, &vp);
    if (ret != 0) {
        result = FR_NOT_ENOUGH_CORE;
        goto ERROR_REMOVE_CHAIN;
    }

    vp->parent = parent;
    vp->fop = &fatfs_fops;
    vp->data = dfp_new;
    vp->originMount = parent->originMount;
    vp->uid = fs->fs_uid;
    vp->gid = fs->fs_gid;
    vp->mode = fatfs_get_mode(finfo_new->fattrib, fs->fs_mode);
    vp->type = fatfstype_2_vnodetype(type);

    hash = fatfs_hash(dp_new->sect, dp_new->dptr, finfo_new->sclst);
    ret = VfsHashInsert(vp, hash);
    if (ret != 0) {
        result = FR_NOT_ENOUGH_CORE;
        goto ERROR_REMOVE_CHAIN;
    }
    *vpp = vp;

    unlock_fs(fs, FR_OK);
    FREE_NAMBUF();
    return fatfs_sync(parent->originMount->mountFlags, fs);

ERROR_REMOVE_CHAIN:
    remove_chain(&(dp_new->obj), clust, 0);
ERROR_UNLOCK:
    unlock_fs(fs, result);
    FREE_NAMBUF();
ERROR_FREE:
    free(dfp_new);
ERROR_EXIT:
    return -fatfs_2_vfs(result);
}
515
/// fat文件系统对 Lookup 接口的实现
516
int fatfs_lookup(struct Vnode *parent, const char *path, int len, struct Vnode **vpp)
517
{
518 519 520 521 522 523 524 525
    struct Vnode *vp = NULL;
    FATFS *fs = (FATFS *)(parent->originMount->data);
    DIR_FILE *dfp;
    DIR *dp = NULL;
    FILINFO *finfo = NULL;
    DWORD hash;
    FRESULT result;
    int ret;
526

527 528 529 530
    dfp = (DIR_FILE *)zalloc(sizeof(DIR_FILE));
    if (dfp == NULL) {
        ret = ENOMEM;
        goto ERROR_EXIT;
531 532
    }

533 534 535 536
    ret = lock_fs(fs);
    if (ret == FALSE) {
        ret = EBUSY;
        goto ERROR_FREE;
537
    }
538 539 540 541 542 543 544 545 546 547 548 549
    finfo = &(dfp->fno);
    LOS_ListInit(&finfo->fp_list);
    dp = &(dfp->f_dir);
    dp->obj.fs = fs;
    dp->obj.sclust = ((DIR_FILE *)(parent->data))->fno.sclst;

    DEF_NAMBUF;
    INIT_NAMBUF(fs);
    result = create_name(dp, &path);
    if (result != FR_OK) {
        ret = fatfs_2_vfs(result);
        goto ERROR_UNLOCK;
550 551
    }

552 553 554 555 556
    result = dir_find(dp);
    if (result != FR_OK) {
        ret = fatfs_2_vfs(result);
        goto ERROR_UNLOCK;
    }
557

558 559 560 561 562
    if (dp->fn[NSFLAG] & NS_NONAME) {
        result = FR_INVALID_NAME;
        ret = fatfs_2_vfs(result);
        goto ERROR_UNLOCK;
    }
563

564 565
    get_fileinfo(dp, finfo);
    dp->obj.objsize = 0;
566

567 568 569 570 571 572 573 574
    hash = fatfs_hash(dp->sect, dp->dptr, finfo->sclst);
    ret = VfsHashGet(parent->originMount, hash, &vp, fatfs_hash_cmp, dfp);
    if (ret != 0) {
        ret = VnodeAlloc(&fatfs_vops, &vp);
        if (ret != 0) {
            ret = ENOMEM;
            result = FR_NOT_ENOUGH_CORE;
            goto ERROR_UNLOCK;
575
        }
576 577 578 579 580 581 582 583 584
        vp->parent = parent;
        vp->fop = &fatfs_fops;
        vp->data = dfp;
        vp->originMount = parent->originMount;
        vp->uid = fs->fs_uid;
        vp->gid = fs->fs_gid;
        vp->mode = fatfs_get_mode(finfo->fattrib, fs->fs_mode);
        if (finfo->fattrib & AM_DIR) {
            vp->type = VNODE_TYPE_DIR;
585
            finfo->fsize = fs->csize * SS(fs);
586 587
        } else {
            vp->type = VNODE_TYPE_REG;
588
        }
589 590 591 592 593

        ret = VfsHashInsert(vp, hash);
        if (ret != 0) {
            result = FR_INVALID_PARAMETER;
            goto ERROR_UNLOCK;
594 595
        }
    } else {
596
        vp->parent = parent;
597
        free(dfp); /* hash hit dfp is no needed */
598 599
    }

600 601 602 603
    unlock_fs(fs, FR_OK);
    FREE_NAMBUF();
    *vpp = vp;
    return 0;
604

605 606 607 608 609 610 611
ERROR_UNLOCK:
    unlock_fs(fs, result);
    FREE_NAMBUF();
ERROR_FREE:
    free(dfp);
ERROR_EXIT:
    return -ret;
612
}
613
///创建 fat vnode 节点
614
int fatfs_create(struct Vnode *parent, const char *name, int mode, struct Vnode **vpp)
615
{
616
    return fatfs_create_obj(parent, name, mode, vpp, AM_ARC, NULL);
617
}
618

619
//打开 fat 格式文件
620 621 622 623 624 625 626 627 628 629
int fatfs_open(struct file *filep)
{
    struct Vnode *vp = filep->f_vnode;
    FATFS *fs = (FATFS *)vp->originMount->data;
    DIR_FILE *dfp = (DIR_FILE *)vp->data;
    DIR *dp = &(dfp->f_dir);
    FILINFO *finfo = &(dfp->fno);
    FIL *fp;
    int ret;

630
    fp = (FIL *)zalloc(sizeof(FIL) + SS(fs));
631 632 633
    if (fp == NULL) {
        ret = ENOMEM;
        goto ERROR_EXIT;
634
    }
635 636 637
    ret = lock_fs(fs);
    if (ret == FALSE) {
        ret = EBUSY;
638
        goto ERROR_FREE;
639 640
    }

641 642 643 644 645 646 647 648 649 650 651 652 653
    fp->dir_sect = dp->sect;
    fp->dir_ptr = dp->dir;
    fp->obj.sclust = finfo->sclst;
    fp->obj.objsize = finfo->fsize;
#if FF_USE_FASTSEEK
    fp->cltbl = 0; /* Disable fast seek mode */
#endif
    fp->obj.fs = fs;
    fp->obj.id = fs->id;
    fp->flag = FA_READ | FA_WRITE;
    fp->err = 0;
    fp->sect = 0;
    fp->fptr = 0;
654
    fp->buf = (BYTE *)fp + sizeof(FIL);
655 656 657 658
    LOS_ListAdd(&finfo->fp_list, &fp->fp_entry);
    unlock_fs(fs, FR_OK);

    filep->f_priv = fp;
659
    return 0;
660

661
ERROR_FREE:
662 663 664
    free(fp);
ERROR_EXIT:
    return -ret;
665 666
}

667
int fatfs_close(struct file *filep)
668
{
669 670 671 672
    FIL *fp = (FIL *)filep->f_priv;
    FATFS *fs = fp->obj.fs;
    FRESULT result;
    int ret;
673

674 675 676
    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
677
    }
678 679 680 681
#if !FF_FS_READONLY
    result = f_sync(fp); /* Flush cached data */
    if (result != FR_OK) {
        goto EXIT;
682
    }
683 684 685 686
    ret = fatfs_sync(filep->f_vnode->originMount->mountFlags, fs);
    if (ret != 0) {
        unlock_fs(fs, FR_OK);
        return ret;
687
    }
688 689 690 691 692 693 694
#endif
    LOS_ListDelete(&fp->fp_entry);
    free(fp);
    filep->f_priv = NULL;
EXIT:
    unlock_fs(fs, result);
    return -fatfs_2_vfs(result);
695 696
}

697
int fatfs_read(struct file *filep, char *buff, size_t count)
698
{
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
    FIL *fp = (FIL *)filep->f_priv;
    FATFS *fs = fp->obj.fs;
    struct Vnode *vp = filep->f_vnode;
    FILINFO *finfo = &((DIR_FILE *)(vp->data))->fno;
    size_t rcount;
    FRESULT result;
    int ret;

    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
    }
    fp->obj.objsize = finfo->fsize;
    fp->obj.sclust = finfo->sclst;
    result = f_read(fp, buff, count, &rcount);
    if (result != FR_OK) {
        goto EXIT;
716
    }
717 718 719 720 721
    filep->f_pos = fp->fptr;
EXIT:
    unlock_fs(fs, result);
    return rcount;
}
722

723 724 725 726 727 728
static FRESULT update_dir(DIR *dp, FILINFO *finfo)
{
    FATFS *fs = dp->obj.fs;
    DWORD tm;
    BYTE *dbuff = NULL;
    FRESULT result;
729

730 731 732 733 734 735 736 737 738 739 740 741
    result = move_window(fs, dp->sect);
    if (result != FR_OK) {
        return result;
    }
    dbuff = fs->win + dp->dptr % SS(fs);
    dbuff[DIR_Attr] = finfo->fattrib;
    st_clust(fs, dbuff, finfo->sclst); /* Update start cluster */
    st_dword(dbuff + DIR_FileSize, (DWORD)finfo->fsize); /* Update file size */
    if (time_status == SYSTEM_TIME_ENABLE) {
        tm = GET_FATTIME();
    } else {
        tm = 0;
742
    }
743 744 745 746 747 748 749 750 751
    st_dword(dbuff + DIR_ModTime, tm); /* Update mtime */
    st_word(dbuff + DIR_LstAccDate, tm >> FTIME_DATE_OFFSET); /* Update access date */
#ifndef LOSCFG_FS_FAT_VIRTUAL_PARTITION
    fs->wflag = 1;
#else
    PARENTFS(fs)->wflag = 1;
#endif
    return sync_fs(fs);
}
752

753 754 755 756 757 758 759
off64_t fatfs_lseek64(struct file *filep, off64_t offset, int whence)
{
    FIL *fp = (FIL *)filep->f_priv;
    FATFS *fs = fp->obj.fs;
    struct Vnode *vp = filep->f_vnode;
    DIR_FILE *dfp = (DIR_FILE *)vp->data;
    FILINFO *finfo = &(dfp->fno);
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
760
    struct Mount *mount = vp->originMount;
761 762 763
    FSIZE_t fpos;
    FRESULT result;
    int ret;
764

765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    switch (whence) {
        case SEEK_CUR:
            offset = filep->f_pos + offset;
            if (offset < 0) {
                return -EINVAL;
            }
            fpos = offset;
            break;
        case SEEK_SET:
            if (offset < 0) {
                return -EINVAL;
            }
            fpos = offset;
            break;
        case SEEK_END:
            offset = (off_t)((long long)finfo->fsize + offset);
            if (offset < 0) {
                return -EINVAL;
            }
            fpos = offset;
            break;
        default:
            return -EINVAL;
788 789
    }

790 791
    if (offset >= FAT32_MAXSIZE) {
        return -EINVAL;
792 793
    }

794 795 796
    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
797
    }
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
798 799 800 801 802 803 804 805 806 807 808

    if (fpos > finfo->fsize) {
        if ((filep->f_oflags & O_ACCMODE) == O_RDONLY) {
            result = FR_DENIED;
            goto ERROR_EXIT;
        }
        if (mount->mountFlags & MS_RDONLY) {
            result = FR_WRITE_PROTECTED;
            goto ERROR_EXIT;
        }
    }
809 810
    fp->obj.sclust = finfo->sclst;
    fp->obj.objsize = finfo->fsize;
811

812 813 814 815 816
    result = f_lseek(fp, fpos);
    finfo->fsize = fp->obj.objsize;
    finfo->sclst = fp->obj.sclust;
    if (result != FR_OK) {
        goto ERROR_EXIT;
817 818
    }

819 820 821
    result = f_sync(fp);
    if (result != FR_OK) {
        goto ERROR_EXIT;
822
    }
823
    filep->f_pos = fpos;
824

825 826 827 828 829 830
    unlock_fs(fs, FR_OK);
    return fpos;
ERROR_EXIT:
    unlock_fs(fs, result);
    return -fatfs_2_vfs(result);
}
831

832 833 834
off_t fatfs_lseek(struct file *filep, off_t offset, int whence)
{
    return (off_t)fatfs_lseek64(filep, offset, whence);
835 836
}

837
static int update_filbuff(FILINFO *finfo, FIL *wfp, const char  *data)
838
{
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
    LOS_DL_LIST *list = &finfo->fp_list;
    FATFS *fs = wfp->obj.fs;
    FIL *entry = NULL;
    int ret = 0;

    LOS_DL_LIST_FOR_EACH_ENTRY(entry, list, FIL, fp_entry) {
        if (entry == wfp) {
            continue;
        }
        if (entry->sect != 0) {
            if (disk_read(fs->pdrv, entry->buf, entry->sect, 1) != RES_OK) {
                ret = -1;
            }
        }
    }

    return ret;
856 857
}

858
int fatfs_write(struct file *filep, const char *buff, size_t count)
859
{
860 861 862 863 864
    FIL *fp = (FIL *)filep->f_priv;
    FATFS *fs = fp->obj.fs;
    struct Vnode *vp = filep->f_vnode;
    FILINFO *finfo = &(((DIR_FILE *)vp->data)->fno);
    size_t wcount;
865
    FRESULT result;
866
    int ret;
867

868 869 870
    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
871
    }
872 873 874 875 876
    fp->obj.objsize = finfo->fsize;
    fp->obj.sclust = finfo->sclst;
    result = f_write(fp, buff, count, &wcount);
    if (result != FR_OK) {
        goto ERROR_EXIT;
877 878
    }

879 880 881 882 883
    finfo->fsize = fp->obj.objsize;
    finfo->sclst = fp->obj.sclust;
    result = f_sync(fp);
    if (result != FR_OK) {
        goto ERROR_EXIT;
884
    }
885
    update_filbuff(finfo, fp, buff);
886

887
    filep->f_pos = fp->fptr;
888

889 890 891 892 893 894
    unlock_fs(fs, FR_OK);
    return wcount;
ERROR_EXIT:
    unlock_fs(fs, result);
    return -fatfs_2_vfs(result);
}
895

896 897 898 899 900 901
int fatfs_fsync(struct file *filep)
{
    FIL *fp = filep->f_priv;
    FATFS *fs = fp->obj.fs;
    FRESULT result;
    int ret;
902

903 904 905
    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
906 907
    }

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
    result = f_sync(fp);
    unlock_fs(fs, result);
    return -fatfs_2_vfs(result);
}

int fatfs_fallocate64(struct file *filep, int mode, off64_t offset, off64_t len)
{
    FIL *fp = (FIL *)filep->f_priv;
    FATFS *fs = fp->obj.fs;
    struct Vnode *vp = filep->f_vnode;
    FILINFO *finfo = &((DIR_FILE *)(vp->data))->fno;
    FRESULT result;
    int ret;

    if (offset < 0 || len <= 0) {
923 924 925
        return -EINVAL;
    }

926 927 928
    if (len >= FAT32_MAXSIZE || offset >= FAT32_MAXSIZE ||
        len + offset >= FAT32_MAXSIZE) {
        return -EINVAL;
929 930
    }

931 932
    if (mode != FALLOC_FL_KEEP_SIZE) {
        return -EINVAL;
933 934
    }

935 936 937
    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
938
    }
939
    result = f_expand(fp, (FSIZE_t)offset, (FSIZE_t)len, 1);
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
940 941 942 943 944
    if (result == FR_OK) {
        if (finfo->sclst == 0) {
            finfo->sclst = fp->obj.sclust;
        }
        result = f_sync(fp);
945
    }
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
946
    unlock_fs(fs, result);
947

948
    return -fatfs_2_vfs(result);
949 950
}

951
static FRESULT realloc_cluster(FILINFO *finfo, FFOBJID *obj, FSIZE_t size)
952
{
953 954 955 956 957
    FATFS *fs = obj->fs;
    off64_t remain;
    DWORD cclust;
    DWORD pclust;
    QWORD csize;
958 959
    FRESULT result;

960 961 962 963 964 965 966 967 968
    if (size == 0) { /* Remove cluster chain */
        if (finfo->sclst != 0) {
            result = remove_chain(obj, finfo->sclst, 0);
            if (result != FR_OK) {
                return result;
            }
            finfo->sclst = 0;
        }
        return FR_OK;
969 970
    }

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    remain = size;
    csize = SS(fs) * fs->csize;
    if (finfo->sclst == 0) { /* Allocate one cluster if file doesn't have any cluster */
        cclust = create_chain(obj, 0);
        if (cclust == 0) {
            return FR_NO_SPACE_LEFT;
        }
        if (cclust == 1 || cclust == DISK_ERROR) {
            return FR_DISK_ERR;
        }
        finfo->sclst = cclust;
    }
    cclust = finfo->sclst;
    while (remain > csize) { /* Follow or strentch the cluster chain */
        pclust = cclust;
        cclust = create_chain(obj, pclust);
        if (cclust == 0) {
            return FR_NO_SPACE_LEFT;
        }
        if (cclust == 1 || cclust == DISK_ERROR) {
            return FR_DISK_ERR;
        }
        remain -= csize;
994
    }
995 996 997 998 999
    pclust = cclust;
    cclust = get_fat(obj, pclust);
    if ((cclust == BAD_CLUSTER) || (cclust == DISK_ERROR)) {
        return FR_DISK_ERR;
    }
1000
    if (!fatfs_is_last_cluster(obj->fs, cclust)) { /* Remove extra cluster if existing */
1001 1002 1003 1004
        result = remove_chain(obj, cclust, pclust);
        if (result != FR_OK) {
            return result;
        }
1005 1006
    }

1007
    return FR_OK;
1008 1009
}

1010
int fatfs_fallocate(struct file *filep, int mode, off_t offset, off_t len)
1011
{
1012
    return fatfs_fallocate64(filep, mode, offset, len);
1013 1014
}

1015
int fatfs_truncate64(struct Vnode *vp, off64_t len)
1016
{
1017 1018 1019 1020 1021 1022 1023 1024 1025
    FATFS *fs = (FATFS *)vp->originMount->data;
    DIR_FILE *dfp = (DIR_FILE *)vp->data;
    DIR *dp = &(dfp->f_dir);
    FILINFO *finfo = &(dfp->fno);
    FFOBJID object;
    FRESULT result = FR_OK;
    int ret;

    if (len < 0 || len >= FAT32_MAXSIZE) {
1026 1027 1028
        return -EINVAL;
    }

1029 1030 1031 1032
    ret = lock_fs(fs);
    if (ret == FALSE) {
        result = FR_TIMEOUT;
        goto ERROR_OUT;
1033
    }
1034 1035 1036
    if (len == finfo->fsize) {
        unlock_fs(fs, FR_OK);
        return 0;
1037 1038
    }

1039 1040 1041 1042
    object.fs = fs;
    result = realloc_cluster(finfo, &object, (FSIZE_t)len);
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
1043
    }
1044
    finfo->fsize = (FSIZE_t)len;
1045

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    result = update_dir(dp, finfo);
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
    }
    unlock_fs(fs, FR_OK);
    return fatfs_sync(vp->originMount->mountFlags, fs);
ERROR_UNLOCK:
    unlock_fs(fs, result);
ERROR_OUT:
    return -fatfs_2_vfs(result);
1056 1057
}

1058
int fatfs_truncate(struct Vnode *vp, off_t len)
1059
{
1060
    return fatfs_truncate64(vp, len);
1061 1062
}

1063
static int fat_bind_check(struct Vnode *blk_driver, los_part **partition)
1064
{
1065
    los_part *part = NULL;
1066

1067 1068
    if (blk_driver == NULL || blk_driver->data == NULL) {
        return ENODEV;
1069 1070
    }

1071 1072 1073
    struct drv_data *dd = blk_driver->data;
    if (dd->ops == NULL) {
        return ENODEV;
1074
    }
1075 1076 1077
    const struct block_operations *bops = dd->ops;
    if (bops->open == NULL) {
        return EINVAL;
1078
    }
1079 1080
    if (bops->open(blk_driver) < 0) {
        return EBUSY;
1081 1082
    }

1083 1084 1085
    part = los_part_find(blk_driver);
    if (part == NULL) {
        return ENODEV;
1086
    }
1087 1088 1089
    if (part->part_name != NULL) {
        bops->close(blk_driver);
        return EBUSY;
1090 1091
    }

1092 1093 1094 1095
#ifndef FF_MULTI_PARTITION
    if (part->part_no_mbr > 1) {
        bops->close(blk_driver);
        return EPERM;
1096 1097 1098
    }
#endif

1099 1100
    *partition = part;
    return 0;
1101
}
1102
///fat将分区文件系统挂载 举例: mount /dev/mmcblk0p0 /bin1/vs/sd vfat
1103
int fatfs_mount(struct Mount *mnt, struct Vnode *blk_device, const void *data)
1104
{
1105 1106 1107 1108 1109 1110 1111
    struct Vnode *vp = NULL;
    FATFS *fs = NULL;
    DIR_FILE *dfp = NULL;
    los_part *part = NULL;
    QWORD start_sector;
    BYTE fmt;
    DWORD hash;
1112
    FRESULT result;
1113
    int ret;
1114

1115
    ret = fat_bind_check(blk_device, &part);//通过节点获取分区信息
1116 1117
    if (ret != 0) {
        goto ERROR_EXIT;
1118 1119
    }

1120 1121 1122 1123
    ret = SetDiskPartName(part, "vfat");
    if (ret != 0) {
        ret = EIO;
        goto ERROR_EXIT;
1124 1125
    }

1126 1127 1128 1129
    fs = (FATFS *)zalloc(sizeof(FATFS));
    if (fs == NULL) {
        ret = ENOMEM;
        goto ERROR_PARTNAME;
1130 1131
    }

1132 1133 1134 1135 1136 1137
#ifdef LOSCFG_FS_FAT_VIRTUAL_PARTITION
    fs->vir_flag = FS_PARENT;
    fs->parent_fs = fs;
    fs->vir_amount = DISK_ERROR;
    fs->vir_avail = FS_VIRDISABLE;
#endif
1138

1139 1140 1141 1142
    ret = ff_cre_syncobj(0, &fs->sobj);
    if (ret == 0) { /* create sync object failed */
        ret = EINVAL;
        goto ERROR_WITH_FS;
1143 1144
    }

1145 1146 1147 1148
    ret = lock_fs(fs);
    if (ret == FALSE) {
        ret = EBUSY;
        goto ERROR_WITH_MUX;
1149 1150
    }

1151 1152
    fs->fs_type = 0;
    fs->pdrv = part->part_id;
1153

1154 1155 1156 1157
#if FF_MAX_SS != FF_MIN_SS  /* Get sector size (multiple sector size cfg only) */
    if (disk_ioctl(fs->pdrv, GET_SECTOR_SIZE, &(fs->ssize)) != RES_OK) {
        ret = EIO;
        goto ERROR_WITH_LOCK;
1158
    }
1159 1160 1161
    if (fs->ssize > FF_MAX_SS || fs->ssize < FF_MIN_SS || (fs->ssize & (fs->ssize - 1))) {
        ret = EIO;
        goto ERROR_WITH_LOCK;
1162
    }
1163
#endif
1164

1165 1166 1167 1168
    fs->win = (BYTE *)ff_memalloc(SS(fs));
    if (fs->win == NULL) {
        ret = ENOMEM;
        goto ERROR_WITH_LOCK;
1169 1170
    }

1171
    result = find_fat_partition(fs, part, &fmt, &start_sector);
1172
    if (result != FR_OK) {
1173 1174
        ret = fatfs_2_vfs(result);
        goto ERROR_WITH_FSWIN;
1175 1176
    }

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    result = init_fatobj(fs, fmt, start_sector);
    if (result != FR_OK) {
        ret = fatfs_2_vfs(result);
        goto ERROR_WITH_FSWIN;
    }

    fs->fs_uid = mnt->vnodeBeCovered->uid;
    fs->fs_gid = mnt->vnodeBeCovered->gid;
    fs->fs_dmask = GetUmask();
    fs->fs_fmask = GetUmask();
    fs->fs_mode = mnt->vnodeBeCovered->mode & (S_IRWXU | S_IRWXG | S_IRWXO);

    dfp = (DIR_FILE *)zalloc(sizeof(DIR_FILE));
    if (dfp == NULL) {
        ret = ENOMEM;
        goto ERROR_WITH_FSWIN;
    }

    dfp->f_dir.obj.fs = fs;
    dfp->f_dir.obj.sclust = 0; /* set start clust 0, root */
    dfp->f_dir.obj.attr = AM_DIR;
    dfp->f_dir.obj.objsize = 0; /* dir size is 0 */
    dfp->fno.fsize = 0;
    dfp->fno.fdate = 0;
    dfp->fno.ftime = 0;
    dfp->fno.fattrib = AM_DIR;
    dfp->fno.sclst = 0;
1204
    dfp->fno.fsize = fs->csize * SS(fs);
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    dfp->fno.fname[0] = '/'; /* Mark as root dir */
    dfp->fno.fname[1] = '\0';
    LOS_ListInit(&(dfp->fno.fp_list));

    ret = VnodeAlloc(&fatfs_vops, &vp);
    if (ret != 0) {
        ret = ENOMEM;
        goto ERROR_WITH_FSWIN;
    }

    mnt->data = fs;
    mnt->vnodeCovered = vp;

    vp->parent = mnt->vnodeBeCovered;
    vp->fop = &fatfs_fops;
    vp->data = dfp;
    vp->originMount = mnt;
    vp->uid = fs->fs_uid;
    vp->gid = fs->fs_gid;
    vp->mode = mnt->vnodeBeCovered->mode;
    vp->type = VNODE_TYPE_DIR;

    hash = fatfs_hash(0, 0, 0);
    ret = VfsHashInsert(vp, hash);
    if (ret != 0) {
        ret = -ret;
        goto ERROR_WITH_LOCK;
    }
    unlock_fs(fs, FR_OK);
1234 1235 1236

    return 0;

1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
ERROR_WITH_FSWIN:
    ff_memfree(fs->win);
ERROR_WITH_LOCK:
    unlock_fs(fs, FR_OK);
ERROR_WITH_MUX:
    ff_del_syncobj(&fs->sobj);
ERROR_WITH_FS:
    free(fs);
ERROR_PARTNAME:
    if (part->part_name) {
        free(part->part_name);
        part->part_name = NULL;
1249
    }
1250 1251
ERROR_EXIT:
    return -ret;
1252 1253
}

1254
int fatfs_umount(struct Mount *mnt, struct Vnode **blkdriver)
1255
{
1256 1257 1258 1259
    struct Vnode *device;
    FATFS *fs = (FATFS *)mnt->data;
    los_part *part;
    int ret;
1260

1261 1262 1263
    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
1264 1265
    }

1266 1267 1268 1269
    part = get_part(fs->pdrv);
    if (part == NULL) {
        unlock_fs(fs, FR_OK);
        return -ENODEV;
1270
    }
1271 1272 1273 1274
    device = part->dev;
    if (device == NULL) {
        unlock_fs(fs, FR_OK);
        return -ENODEV;
1275
    }
1276 1277 1278 1279 1280
#ifdef LOSCFG_FS_FAT_CACHE
    ret = OsSdSync(part->disk_id);
    if (ret != 0) {
        unlock_fs(fs, FR_DISK_ERR);
        return -EIO;
1281 1282
    }
#endif
1283 1284 1285
    if (part->part_name != NULL) {
        free(part->part_name);
        part->part_name = NULL;
1286 1287
    }

1288 1289 1290 1291
    struct drv_data *dd = device->data;
    if (dd->ops == NULL) {
        unlock_fs(fs, FR_OK);
        return ENODEV;
1292 1293
    }

1294 1295 1296
    const struct block_operations *bops = dd->ops;
    if (bops != NULL && bops->close != NULL) {
        bops->close(*blkdriver);
1297 1298
    }

1299 1300
    if (fs->win != NULL) {
        ff_memfree(fs->win);
1301 1302
    }

1303
    unlock_fs(fs, FR_OK);
1304

1305 1306 1307
    ret = ff_del_syncobj(&fs->sobj);
    if (ret == FALSE) {
        return -EINVAL;
1308
    }
1309
    free(fs);
1310

1311
    *blkdriver = device;
1312

1313
    return 0;
1314 1315
}

1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
int fatfs_sync_adapt(struct Mount *mnt)
{
    (void)mnt;
    int ret = 0;
#ifdef LOSCFG_FS_FAT_CACHE
    struct Vnode *dev = NULL;
    los_part *part = NULL;

    if (mnt == NULL) {
        return -EINVAL;
    }

    dev = mnt->vnodeDev;
    part = los_part_find(dev);
    if (part == NULL) {
        return -EINVAL;
    }

    ret = OsSdSync(part->disk_id);
#endif
    return ret;
}

1339
int fatfs_statfs(struct Mount *mnt, struct statfs *info)
1340
{
1341
    FATFS *fs = (FATFS *)mnt->data;
1342 1343 1344
    DWORD nclst = 0;
    FRESULT result = FR_OK;
    int ret;
1345

1346 1347 1348 1349 1350
    info->f_type = MSDOS_SUPER_MAGIC;
#if FF_MAX_SS != FF_MIN_SS
    info->f_bsize = fs->ssize * fs->csize;
#else
    info->f_bsize = FF_MIN_SS * fs->csize;
1351
#endif
1352
    info->f_blocks = fs->n_fatent;
1353 1354 1355 1356 1357 1358 1359 1360
    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
    }
    /* free cluster is unavailable, update it */
    if (fs->free_clst == DISK_ERROR) {
        result = fat_count_free_entries(&nclst, fs);
    }
1361 1362
    info->f_bfree = fs->free_clst;
    info->f_bavail = fs->free_clst;
1363
    unlock_fs(fs, result);
1364

1365 1366 1367
#if FF_USE_LFN
    /* Maximum length of filenames */
    info->f_namelen = FF_MAX_LFN;
1368
#else
1369 1370
    /* Maximum length of filenames: 8 is the basename length, 1 is the dot, 3 is the extension length */
    info->f_namelen = (8 + 1 + 3);
1371
#endif
1372 1373 1374 1375 1376 1377 1378
    info->f_fsid.__val[0] = MSDOS_SUPER_MAGIC;
    info->f_fsid.__val[1] = 1;
    info->f_frsize = SS(fs) * fs->csize;
    info->f_files = 0;
    info->f_ffree = 0;
    info->f_flags = mnt->mountFlags;

1379
    return -fatfs_2_vfs(result);
1380 1381
}

1382
static inline int GET_SECONDS(WORD ftime)
1383
{
1384
    return (ftime & BITMASK5) * SEC_MULTIPLIER;
1385
}
1386
static inline int GET_MINUTES(WORD ftime)
1387
{
1388
    return (ftime >> FTIME_MIN_OFFSET) & BITMASK6;
1389
}
1390
static inline int GET_HOURS(WORD ftime)
1391
{
1392
    return (ftime >> FTIME_HR_OFFSET) & BITMASK5;
1393
}
1394
static inline int GET_DAY(WORD fdate)
1395
{
1396
    return fdate & BITMASK5;
1397
}
1398
static inline int GET_MONTH(WORD fdate)
1399
{
1400
    return (fdate >> FTIME_MTH_OFFSET) & BITMASK4;
1401
}
1402
static inline int GET_YEAR(WORD fdate)
1403
{
1404
    return (fdate >> FTIME_YEAR_OFFSET) & BITMASK7;
1405 1406
}

1407
static time_t fattime_transfer(WORD fdate, WORD ftime)
1408
{
1409 1410 1411 1412 1413 1414 1415 1416 1417
    struct tm time = { 0 };
    time.tm_sec = GET_SECONDS(ftime);
    time.tm_min = GET_MINUTES(ftime);
    time.tm_hour = GET_HOURS(ftime);
    time.tm_mday = GET_DAY(fdate);
    time.tm_mon = GET_MONTH(fdate);
    time.tm_year = GET_YEAR(fdate) + YEAR_OFFSET; /* Year start from 1980 in FATFS */
    time_t ret = mktime(&time);
    return ret;
1418 1419
}

1420
DWORD fattime_format(time_t time)
1421
{
1422 1423
    struct tm st;
    DWORD ftime;
1424

1425
    localtime_r(&time, &st);
1426

1427 1428 1429 1430
    ftime = (DWORD)st.tm_mday;
    ftime |= ((DWORD)st.tm_mon) << FTIME_MTH_OFFSET;
    ftime |= ((DWORD)((st.tm_year > YEAR_OFFSET) ? (st.tm_year - YEAR_OFFSET) : 0)) << FTIME_YEAR_OFFSET;
    ftime <<= FTIME_DATE_OFFSET;
1431

1432 1433 1434
    ftime = (DWORD)st.tm_sec / SEC_MULTIPLIER;
    ftime |= ((DWORD)st.tm_min) << FTIME_MIN_OFFSET;
    ftime |= ((DWORD)st.tm_hour) << FTIME_HR_OFFSET;
1435

1436
    return ftime;
1437 1438
}

1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
int fatfs_stat(struct Vnode *vp, struct stat* sp)
{
    FATFS *fs = (FATFS *)vp->originMount->data;
    DIR_FILE *dfp = (DIR_FILE *)vp->data;
    FILINFO *finfo = &(dfp->fno);
    time_t time;
    int ret;

    ret = lock_fs(fs);
    if (ret == FALSE) {
        return EBUSY;
    }

    sp->st_dev = fs->pdrv;
    sp->st_mode = vp->mode;
    sp->st_nlink = 1;
    sp->st_uid = fs->fs_uid;
    sp->st_gid = fs->fs_gid;
    sp->st_size = finfo->fsize;
    sp->st_blksize = fs->csize * SS(fs);
1459 1460 1461 1462 1463
    if (finfo->fattrib & AM_ARC) {
        sp->st_blocks = finfo->fsize ? ((finfo->fsize - 1) / SS(fs) / fs->csize + 1) : 0;
    } else {
        sp->st_blocks = fs->csize;
    }
1464 1465 1466
    time = fattime_transfer(finfo->fdate, finfo->ftime);
    sp->st_mtime = time;

鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
1467 1468 1469
    /* Adapt to kstat member "long tv_sec" */
    sp->__st_mtim32.tv_sec = (long)time;

1470 1471 1472
    unlock_fs(fs, FR_OK);
    return 0;
}
1473

1474 1475 1476 1477 1478 1479 1480 1481
void fatfs_chtime(DIR *dp, struct IATTR *attr)
{
    BYTE *dir = dp->dir;
    DWORD ftime;
    if (attr->attr_chg_valid & CHG_ATIME) {
        ftime = fattime_format(attr->attr_chg_atime);
        st_word(dir + DIR_LstAccDate, (ftime >> FTIME_DATE_OFFSET));
    }
1482

1483 1484 1485 1486
    if (attr->attr_chg_valid & CHG_CTIME) {
        ftime = fattime_format(attr->attr_chg_ctime);
        st_dword(dir + DIR_CrtTime, ftime);
    }
1487

1488 1489 1490
    if (attr->attr_chg_valid & CHG_MTIME) {
        ftime = fattime_format(attr->attr_chg_mtime);
        st_dword(dir + DIR_ModTime, ftime);
1491
    }
1492
}
1493

1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
int fatfs_chattr(struct Vnode *vp, struct IATTR *attr)
{
    FATFS *fs = (FATFS *)vp->originMount->data;
    DIR_FILE *dfp = (DIR_FILE *)vp->data;
    DIR *dp = &(dfp->f_dir);
    FILINFO *finfo = &(dfp->fno);
    BYTE *dir = dp->dir;
    DWORD ftime;
    FRESULT result;
    int ret;
1504

1505 1506
    if (finfo->fname[0] == '/') { /* Is root dir of fatfs ? */
        return 0;
1507 1508
    }

1509 1510 1511 1512
    ret = lock_fs(fs);
    if (ret == FALSE) {
        result = FR_TIMEOUT;
        goto ERROR_OUT;
1513 1514
    }

1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    result = move_window(fs, dp->sect);
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
    }

    if (attr->attr_chg_valid & CHG_MODE) {
        /* FAT only support readonly flag */
        if ((attr->attr_chg_mode & S_IWUSR) == 0 && (finfo->fattrib & AM_RDO) == 0) {
            dir[DIR_Attr] |= AM_RDO;
            finfo->fattrib |= AM_RDO;
            fs->wflag = 1;
        } else if ((attr->attr_chg_mode & S_IWUSR) != 0 && (finfo->fattrib & AM_RDO) != 0) {
            dir[DIR_Attr] &= ~AM_RDO;
            finfo->fattrib &= ~AM_RDO;
            fs->wflag = 1;
1530
        }
1531
        vp->mode = fatfs_get_mode(finfo->fattrib, fs->fs_mode);
1532 1533
    }

1534 1535 1536 1537 1538 1539
    if (attr->attr_chg_valid & (CHG_ATIME | CHG_CTIME | CHG_MTIME)) {
        fatfs_chtime(dp, attr);
        ftime = ld_dword(dp->dir + DIR_ModTime);
        finfo->fdate = (WORD)(ftime >> FTIME_DATE_OFFSET);
        finfo->ftime = (WORD)ftime;
    }
1540

1541 1542 1543
    result = sync_window(fs);
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
1544 1545
    }

1546 1547 1548 1549 1550 1551
    unlock_fs(fs, FR_OK);
    return fatfs_sync(vp->originMount->mountFlags, fs);
ERROR_UNLOCK:
    unlock_fs(fs, result);
ERROR_OUT:
    return -fatfs_2_vfs(result);
1552 1553
}

1554
int fatfs_opendir(struct Vnode *vp, struct fs_dirent_s *idir)
1555
{
1556 1557 1558 1559 1560
    FATFS *fs = vp->originMount->data;
    DIR_FILE *dfp = (DIR_FILE *)vp->data;
    FILINFO *finfo = &(dfp->fno);
    DIR *dp;
    DWORD clst;
1561
    FRESULT result;
1562
    int ret;
1563

1564 1565 1566
    dp = (DIR*)zalloc(sizeof(DIR));
    if (dp == NULL) {
        return -ENOMEM;
1567 1568
    }

1569 1570 1571
    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
1572
    }
1573 1574 1575
    clst = finfo->sclst;
    dp->obj.fs = fs;
    dp->obj.sclust = clst;
1576

1577 1578 1579 1580 1581
    result = dir_sdi(dp, 0);
    if (result != FR_OK) {
        free(dp);
        unlock_fs(fs, result);
        return -fatfs_2_vfs(result);
1582
    }
1583 1584
    unlock_fs(fs, result);
    idir->u.fs_dir = dp;
1585

1586 1587
    return 0;
}
1588

1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
int fatfs_readdir(struct Vnode *vp, struct fs_dirent_s *idir)
{
    FATFS *fs = vp->originMount->data;
    FILINFO fno;
    DIR* dp = (DIR*)idir->u.fs_dir;
    struct dirent *dirp = NULL;
    FRESULT result;
    int ret, i;

    ret = lock_fs(fs);
    if (ret == FALSE) { /* Lock fs failed */
        return -EBUSY;
    }
    DEF_NAMBUF;
    INIT_NAMBUF(fs);
    for (i = 0; i < idir->read_cnt; i++) {
        /* using dir_read_massive to promote performance */
        result = dir_read_massive(dp, 0);
        if (result == FR_NO_FILE) {
            break;
        } else if (result != FR_OK) {
            goto ERROR_UNLOCK;
        }
        get_fileinfo(dp, &fno);
        /* 0x00 for end of directory and 0xFF for directory is empty */
        if (fno.fname[0] == 0x00 || fno.fname[0] == (TCHAR)0xFF) {
            break;
        }
1617

1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
        dirp = &(idir->fd_dir[i]);
        if (fno.fattrib & AM_DIR) { /* is dir */
            dirp->d_type = DT_DIR;
        } else {
            dirp->d_type = DT_REG;
        }
        if (strncpy_s(dirp->d_name, sizeof(dirp->d_name), fno.fname, strlen(fno.fname)) != EOK) {
            result = FR_NOT_ENOUGH_CORE;
            goto ERROR_UNLOCK;
        }
        result = dir_next(dp, 0);
        if (result != FR_OK && result != FR_NO_FILE) {
            goto ERROR_UNLOCK;
        }
        idir->fd_position++;
        idir->fd_dir[i].d_off = idir->fd_position;
        idir->fd_dir[i].d_reclen = (uint16_t)sizeof(struct dirent);
    }
    unlock_fs(fs, FR_OK);
    FREE_NAMBUF();
    return i;
ERROR_UNLOCK:
    unlock_fs(fs, result);
    FREE_NAMBUF();
    return -fatfs_2_vfs(result);
}
1644

1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
int fatfs_rewinddir(struct Vnode *vp, struct fs_dirent_s *dir)
{
    DIR *dp = (DIR *)dir->u.fs_dir;
    FATFS *fs = dp->obj.fs;
    FRESULT result;
    int ret;

    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
1655 1656
    }

1657 1658 1659 1660
    result = dir_sdi(dp, 0);
    unlock_fs(fs, result);
    return -fatfs_2_vfs(result);
}
1661

1662 1663 1664 1665 1666 1667 1668
int fatfs_closedir(struct Vnode *vp, struct fs_dirent_s *dir)
{
    DIR *dp = (DIR *)dir->u.fs_dir;
    free(dp);
    dir->u.fs_dir = NULL;
    return 0;
}
1669

1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
static FRESULT rename_check(DIR *dp_new, FILINFO *finfo_new, DIR *dp_old, FILINFO *finfo_old)
{
    DIR dir_sub;
    FRESULT result;
    if (finfo_new->fattrib & AM_ARC) { /* new path is file */
        if (finfo_old->fattrib & AM_DIR) { /* but old path is dir */
            return FR_NO_DIR;
        }
    } else if (finfo_new->fattrib & AM_DIR) { /* new path is dir */
        if (finfo_old->fattrib & AM_ARC) { /* old path is file */
            return FR_IS_DIR;
        }
        dir_sub.obj.fs = dp_old->obj.fs;
        dir_sub.obj.sclust = finfo_new->sclst;
        result = dir_sdi(&dir_sub, 0);
        if (result != FR_OK) {
            return result;
        }
        result = dir_read(&dir_sub, 0);
        if (result == FR_OK) { /* new path isn't empty file */
            return FR_NO_EMPTY_DIR;
        }
    } else { /* System file or volume label */
        return FR_DENIED;
1694
    }
1695
    return FR_OK;
1696 1697
}

1698
int fatfs_rename(struct Vnode *old_vnode, struct Vnode *new_parent, const char *oldname, const char *newname)
1699
{
1700 1701 1702 1703 1704 1705 1706 1707
    FATFS *fs = (FATFS *)(old_vnode->originMount->data);
    DIR_FILE *dfp_old = (DIR_FILE *)old_vnode->data;
    DIR *dp_old = &(dfp_old->f_dir);
    FILINFO *finfo_old = &(dfp_old->fno);
    DIR_FILE *dfp_new = NULL;
    DIR* dp_new = NULL;
    FILINFO* finfo_new = NULL;
    DWORD clust;
1708
    FRESULT result;
1709
    int ret;
1710

1711 1712 1713
    ret = lock_fs(fs);
    if (ret == FALSE) { /* Lock fs failed */
        return -EBUSY;
1714 1715
    }

1716 1717 1718 1719
    dfp_new = (DIR_FILE *)zalloc(sizeof(DIR_FILE));
    if (dfp_new == NULL) {
        result = FR_NOT_ENOUGH_CORE;
        goto ERROR_UNLOCK;
1720
    }
1721 1722
    dp_new = &(dfp_new->f_dir);
    finfo_new = &(dfp_new->fno);
1723

1724 1725
    dp_new->obj.sclust = ((DIR_FILE *)(new_parent->data))->fno.sclst;
    dp_new->obj.fs = fs;
1726

1727 1728 1729 1730 1731 1732
    /* Find new path */
    DEF_NAMBUF;
    INIT_NAMBUF(fs);
    result = create_name(dp_new, &newname);
    if (result != FR_OK) {
        goto ERROR_FREE;
1733
    }
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
    result = dir_find(dp_new);
    if (result == FR_OK) { /* new path name exist */
        get_fileinfo(dp_new, finfo_new);
        result = rename_check(dp_new, finfo_new, dp_old, finfo_old);
        if (result != FR_OK) {
            goto ERROR_FREE;
        }
        result = dir_remove(dp_old);
        if (result != FR_OK) {
            goto ERROR_FREE;
        }
        clust = finfo_new->sclst;
        if (clust != 0) { /* remove the new path cluster chain if exists */
            result = remove_chain(&(dp_new->obj), clust, 0);
            if (result != FR_OK) {
                goto ERROR_FREE;
            }
        }
    } else { /* new path name not exist */
        result = dir_remove(dp_old);
        if (result != FR_OK) {
            goto ERROR_FREE;
        }
        result = dir_register(dp_new);
        if (result != FR_OK) {
            goto ERROR_FREE;
        }
1761 1762
    }

1763 1764
    /* update new dir entry with old info */
    result = update_dir(dp_new, finfo_old);
1765
    if (result != FR_OK) {
1766
        goto ERROR_FREE;
1767
    }
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
    result = dir_read(dp_new, 0);
    if (result != FR_OK) {
        goto ERROR_FREE;
    }
    dp_new->blk_ofs = dir_ofs(dp_new);
    get_fileinfo(dp_new, finfo_new);

    dfp_new->fno.fp_list.pstNext = dfp_old->fno.fp_list.pstNext;
    dfp_new->fno.fp_list.pstPrev = dfp_old->fno.fp_list.pstPrev;
    ret = memcpy_s(dfp_old, sizeof(DIR_FILE), dfp_new, sizeof(DIR_FILE));
    if (ret != 0) {
        result = FR_NOT_ENOUGH_CORE;
        goto ERROR_FREE;
    }
    free(dfp_new);
    unlock_fs(fs, FR_OK);
    FREE_NAMBUF();
    return fatfs_sync(old_vnode->originMount->mountFlags, fs);

ERROR_FREE:
    free(dfp_new);
ERROR_UNLOCK:
    unlock_fs(fs, result);
    FREE_NAMBUF();
    return -fatfs_2_vfs(result);
1793 1794 1795
}


1796 1797 1798 1799 1800 1801 1802 1803 1804
static int fatfs_erase(los_part *part, int option)
{
    int opt = option;
    if ((UINT)opt & FMT_ERASE) {
        opt = (UINT)opt & (~FMT_ERASE);
        if (EraseDiskByID(part->disk_id, part->sector_start, part->sector_count) != LOS_OK) {
            PRINTK("Disk erase error.\n");
            return -1;
        }
1805 1806
    }

1807 1808
    if (opt != FM_FAT && opt != FM_FAT32) {
        opt = FM_ANY;
1809 1810
    }

1811 1812
    return opt;
}
1813
///设置FAT分区信息
1814 1815 1816 1817 1818
static int fatfs_set_part_info(los_part *part)
{
    los_disk *disk = NULL;
    char *buf = NULL;
    int ret;
1819

1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
    /* If there is no MBR before, the partition info needs to be changed after mkfs */
    if (part->type != EMMC && part->part_no_mbr == 0) {
        disk = get_disk(part->disk_id);
        if (disk == NULL) {
            return -EIO;
        }
        buf = (char *)zalloc(disk->sector_size);
        if (buf == NULL) {
            return -ENOMEM;
        }
1830
        (void)memset_s(buf, disk->sector_size, 0, disk->sector_size);//第一个扇区是描述磁盘信息
1831 1832 1833 1834 1835
        ret = los_disk_read(part->disk_id, buf, 0, 1, TRUE); /* TRUE when not reading large data */
        if (ret < 0) {
            free(buf);
            return -EIO;
        }
1836 1837 1838 1839
        part->sector_start = LD_DWORD_DISK(&buf[PAR_OFFSET + PAR_START_OFFSET]);//开始扇区
        part->sector_count = LD_DWORD_DISK(&buf[PAR_OFFSET + PAR_COUNT_OFFSET]);//扇区大小
        part->part_no_mbr = 1;	//主分区编号
        part->filesystem_type = buf[PAR_OFFSET + PAR_TYPE_OFFSET]; //文件系统类型
1840

1841 1842 1843
        free(buf);
    }
    return 0;
1844 1845
}

1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
static FRESULT fatfs_setlabel(los_part *part)
{
    QWORD start_sector = 0;
    BYTE fmt = 0;
    FATFS fs;
    FRESULT result;

#ifdef LOSCFG_FS_FAT_VIRTUAL_PARTITION
    fs.vir_flag = FS_PARENT;
    fs.parent_fs = &fs;
    fs.vir_amount = DISK_ERROR;
    fs.vir_avail = FS_VIRDISABLE;
#endif
    if (disk_ioctl(fs.pdrv, GET_SECTOR_SIZE, &(fs.ssize)) != RES_OK) {
        return -EIO;
    }
    fs.win = (BYTE *)ff_memalloc(fs.ssize);
    if (fs.win == NULL) {
        return -ENOMEM;
    }

    result = find_fat_partition(&fs, part, &fmt, &start_sector);
    if (result != FR_OK) {
        free(fs.win);
        return -fatfs_2_vfs(result);
    }

    result = init_fatobj(&fs, fmt, start_sector);
    if (result != FR_OK) {
        free(fs.win);
        return -fatfs_2_vfs(result);
    }

    result = set_volumn_label(&fs, FatLabel);
    free(fs.win);

    return result;
}

1885
int fatfs_mkfs (struct Vnode *device, int sectors, int option)
1886
{
1887 1888 1889
    BYTE *work_buff = NULL;
    los_part *part = NULL;
    FRESULT result;
1890
    MKFS_PARM opt = {0};
1891
    int ret;
1892

1893 1894 1895 1896
    part = los_part_find(device);
    if (part == NULL || device->data == NULL) {
        return -ENODEV;
    }
1897

1898
    if (sectors < 0 || sectors > FAT32_MAX_CLUSTER_SIZE || ((DWORD)sectors & ((DWORD)sectors - 1))) {
1899 1900 1901
        return -EINVAL;
    }

1902
    if (option != FMT_FAT && option != FMT_FAT32 && option != FMT_ANY && option != FMT_ERASE) {
1903 1904 1905
        return -EINVAL;
    }

1906 1907 1908 1909 1910 1911 1912
    if (part->part_name != NULL) { /* The part is mounted */
        return -EBUSY;
    }
    option = fatfs_erase(part, option);
    work_buff = (BYTE *)zalloc(FF_MAX_SS);
    if (work_buff == NULL) {
        return -ENOMEM;
1913 1914
    }

1915 1916 1917
    opt.n_sect = sectors;
    opt.fmt = (BYTE)option;
    result = _mkfs(part, &opt, work_buff, FF_MAX_SS);
1918 1919 1920
    free(work_buff);
    if (result != FR_OK) {
        return -fatfs_2_vfs(result);
1921 1922
    }

1923 1924
    result = fatfs_setlabel(part);
    if (result == FR_OK) {
1925
#ifdef LOSCFG_FS_FAT_CACHE
1926 1927 1928 1929
        ret = OsSdSync(part->disk_id);
        if (ret != 0) {
            return -EIO;
        }
1930
#endif
1931
    }
1932

1933 1934 1935
    ret = fatfs_set_part_info(part);
    if (ret != 0) {
        return -EIO;
1936 1937
    }

1938
    return -fatfs_2_vfs(result);
1939 1940
}

1941
int fatfs_mkdir(struct Vnode *parent, const char *name, mode_t mode, struct Vnode **vpp)
1942
{
1943
    return fatfs_create_obj(parent, name, mode, vpp, AM_DIR, NULL);
1944 1945
}

1946
int fatfs_rmdir(struct Vnode *parent, struct Vnode *vp, const char *name)
1947
{
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
    FATFS *fs = (FATFS *)vp->originMount->data;
    DIR_FILE *dfp = (DIR_FILE *)vp->data;
    FILINFO *finfo = &(dfp->fno);
    DIR *dp = &(dfp->f_dir);
    DIR dir_sub;
    FRESULT result = FR_OK;
    int ret;

    if (finfo->fattrib & AM_ARC) {
        result = FR_NO_DIR;
        goto ERROR_OUT;
    }

    DEF_NAMBUF;
    INIT_NAMBUF(fs);

    ret = lock_fs(fs);
    if (ret == FALSE) {
        result = FR_TIMEOUT;
        goto ERROR_OUT;
    }
    dir_sub.obj.fs = fs;
    dir_sub.obj.sclust = finfo->sclst;
    result = dir_sdi(&dir_sub, 0);
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
1974
    }
1975 1976 1977 1978
    result = dir_read(&dir_sub, 0);
    if (result == FR_OK) {
        result = FR_NO_EMPTY_DIR;
        goto ERROR_UNLOCK;
1979
    }
1980 1981 1982
    result = dir_remove(dp); /* remove directory entry */
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
1983
    }
1984 1985 1986 1987
    /* Directory entry contains at least one cluster */
    result = remove_chain(&(dp->obj), finfo->sclst, 0);
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
1988 1989
    }

1990 1991 1992
    unlock_fs(fs, FR_OK);
    FREE_NAMBUF();
    return fatfs_sync(vp->originMount->mountFlags, fs);
1993

1994 1995 1996 1997 1998 1999
ERROR_UNLOCK:
    unlock_fs(fs, result);
    FREE_NAMBUF();
ERROR_OUT:
    return -fatfs_2_vfs(result);
}
2000
///回收节点
2001 2002 2003 2004 2005 2006
int fatfs_reclaim(struct Vnode *vp)
{
    free(vp->data);
    vp->data = NULL;
    return 0;
}
2007

2008
int fatfs_unlink(struct Vnode *parent, struct Vnode *vp, const char *name)
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
{
    FATFS *fs = (FATFS *)vp->originMount->data;
    DIR_FILE *dfp = (DIR_FILE *)vp->data;
    FILINFO *finfo = &(dfp->fno);
    DIR *dp = &(dfp->f_dir);
    FRESULT result = FR_OK;
    int ret;

    if (finfo->fattrib & AM_DIR) {
        result = FR_IS_DIR;
        goto ERROR_OUT;
    }
    ret = lock_fs(fs);
    if (ret == FALSE) {
        result = FR_TIMEOUT;
        goto ERROR_OUT;
    }
    result = dir_remove(dp); /* remove directory entry */
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
2029
    }
2030 2031 2032 2033 2034
    if (finfo->sclst != 0) { /* if cluster chain exists */
        result = remove_chain(&(dp->obj), finfo->sclst, 0);
        if (result != FR_OK) {
            goto ERROR_UNLOCK;
        }
2035
    }
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
    result = sync_fs(fs);
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
    }
    unlock_fs(fs, FR_OK);
    return fatfs_sync(vp->originMount->mountFlags, fs);

ERROR_UNLOCK:
    unlock_fs(fs, result);
ERROR_OUT:
    return -fatfs_2_vfs(result);
}

int fatfs_ioctl(struct file *filep, int req, unsigned long arg)
{
2051 2052 2053 2054
    return -ENOSYS;
}

#define CHECK_FILE_NUM 3
2055
static inline DWORD combine_time(FILINFO *finfo)
2056
{
2057 2058
    return (finfo->fdate << FTIME_DATE_OFFSET) | finfo->ftime;
}
2059

2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
static UINT get_oldest_time(DIR_FILE df[], DWORD *oldest_time, UINT len)
{
    int i;
    DWORD old_time = combine_time(&(df[0].fno));
    DWORD time;
    UINT index = 0;
    for (i = 1; i < len; i++) {
        time = combine_time(&(df[i].fno));
        if (time < old_time) {
            old_time = time;
            index = i;
        }
2072
    }
2073 2074
    *oldest_time = old_time;
    return index;
2075 2076
}

鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
2077
static FRESULT fscheck(DIR *dp)
2078
{
2079
    DIR_FILE df[CHECK_FILE_NUM] = {0};
2080
    FILINFO fno;
2081
    UINT index = 0;
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
2082 2083 2084
    UINT count;
    DWORD time;
    DWORD old_time = -1;
2085 2086 2087
    FRESULT result;
    for (count = 0; count < CHECK_FILE_NUM; count++) {
        if ((result = f_readdir(dp, &fno)) != FR_OK) {
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
2088
            return result;
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
        } else {
            if (fno.fname[0] == 0 || fno.fname[0] == (TCHAR)0xFF) {
                break;
            }
            (void)memcpy_s(&df[count].f_dir, sizeof(DIR), dp, sizeof(DIR));
            (void)memcpy_s(&df[count].fno, sizeof(FILINFO), &fno, sizeof(FILINFO));
            time = combine_time(&(df[count].fno));
            if (time < old_time) {
                old_time = time;
                index = count;
            }
2100
        }
2101 2102 2103
    }
    while ((result = f_readdir(dp, &fno)) == FR_OK) {
        if (fno.fname[0] == 0 || fno.fname[0] == (TCHAR)0xFF) {
2104 2105
            break;
        }
2106 2107 2108 2109 2110
        time = combine_time(&fno);
        if (time < old_time) {
            (void)memcpy_s(&df[index].f_dir, sizeof(DIR), dp, sizeof(DIR));
            (void)memcpy_s(&df[index].fno, sizeof(FILINFO), &fno, sizeof(FILINFO));
            index = get_oldest_time(df, &old_time, CHECK_FILE_NUM);
2111
        }
2112
    }
鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
2113 2114 2115 2116
    index = 0;
    while (result == FR_OK && index < count) {
        result = f_fcheckfat(&df[index]);
        ++index;
2117
    }
2118

鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
    return result;
}

int fatfs_fscheck(struct Vnode* vp, struct fs_dirent_s *dir)
{
    FATFS *fs = (FATFS *)vp->originMount->data;
    DIR *dp = NULL;
    FILINFO *finfo = &(((DIR_FILE *)(vp->data))->fno);
#ifdef LOSCFG_FS_FAT_CACHE
    los_part *part = NULL;
#endif
    FRESULT result;
    int ret;

    if (fs->fs_type != FS_FAT32) {
        return -EINVAL;
    }

    if ((finfo->fattrib & AM_DIR) == 0) {
        return -ENOTDIR;
    }

    ret = fatfs_opendir(vp, dir);
    if (ret < 0) {
        return ret;
    }

    ret = lock_fs(fs);
    if (ret == FALSE) {
        result = FR_TIMEOUT;
        goto ERROR_WITH_DIR;
    }

    dp = (DIR *)dir->u.fs_dir;
    dp->obj.id = fs->id;
    result = fscheck(dp);
    if (result != FR_OK) {
        goto ERROR_UNLOCK;
2157 2158
    }

2159 2160 2161 2162
    unlock_fs(fs, FR_OK);

    ret = fatfs_closedir(vp, dir);
    if (ret < 0) {
2163 2164 2165 2166
        return ret;
    }

#ifdef LOSCFG_FS_FAT_CACHE
2167
    part = get_part((INT)fs->pdrv);
2168 2169 2170 2171 2172 2173
    if (part != NULL) {
        (void)OsSdSync(part->disk_id);
    }
#endif

    return 0;
2174 2175 2176 2177 2178 2179

ERROR_UNLOCK:
    unlock_fs(fs, result);
ERROR_WITH_DIR:
    fatfs_closedir(vp, dir);
    return -fatfs_2_vfs(result);
2180
}
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
int fatfs_symlink(struct Vnode *parentVnode, struct Vnode **newVnode, const char *path, const char *target)
{
    return fatfs_create_obj(parentVnode, path, 0, newVnode, AM_LNK, target);
}

ssize_t fatfs_readlink(struct Vnode *vnode, char *buffer, size_t bufLen)
{
    int ret;
    FRESULT res = FR_OK;
    DWORD clust;
    QWORD sect;
    DIR_FILE *dfp = (DIR_FILE *)(vnode->data);
    DIR *dp = &(dfp->f_dir);
    FATFS *fs = dp->obj.fs;
    FILINFO *finfo = &(dfp->fno);
    size_t targetLen = finfo->fsize;
    size_t cnt;

    ret = lock_fs(fs);
    if (ret == FALSE) {
        return -EBUSY;
    }

    clust = finfo->sclst;
    sect = clst2sect(fs, clust);    /* Get current sector */
    if (sect == 0) {
        res = FR_DISK_ERR;
        goto ERROUT;
    }

    if (move_window(fs, sect) != FR_OK) {
        res = FR_DISK_ERR;
        goto ERROUT;
    }

    cnt = (bufLen - 1) < targetLen ? (bufLen - 1) : targetLen;
    ret = LOS_CopyFromKernel(buffer, bufLen, fs->win, cnt);
    if (ret != EOK) {
        res = FR_INVALID_PARAMETER;
        goto ERROUT;
    }
    buffer[cnt] = '\0';

    unlock_fs(fs, FR_OK);
    return cnt;

ERROUT:
    unlock_fs(fs, res);
    return -fatfs_2_vfs(res);
}
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431

ssize_t fatfs_readpage(struct Vnode *vnode, char *buff, off_t pos)
{
    FATFS *fs = (FATFS *)(vnode->originMount->data);
    DIR_FILE *dfp = (DIR_FILE *)(vnode->data);
    FILINFO *finfo = &(dfp->fno);
    FAT_ENTRY *ep = &(dfp->fat_entry);
    DWORD clust;
    DWORD sclust;
    QWORD sect;
    QWORD step;
    QWORD n;
    size_t position; /* byte offset */
    BYTE *buf = (BYTE *)buff;
    size_t buflen = PAGE_SIZE;
    FRESULT result;
    int ret;

    ret = lock_fs(fs);
    if (ret == FALSE) {
        result = FR_TIMEOUT;
        goto ERROR_OUT;
    }

    if (finfo->fsize <= pos) {
        result = FR_OK;
        goto ERROR_UNLOCK;
    }

    if (ep->clst == 0) {
        ep->clst = finfo->sclst;
    }

    if (pos >= ep->pos) {
        clust = ep->clst;
        position = ep->pos;
    } else {
        clust = finfo->sclst;
        position = 0;
    }

    /* Get to the current cluster */
    n = pos / SS(fs) / fs->csize - position / SS(fs) / fs->csize;
    while (n--) {
        clust = get_fat(&(dfp->f_dir.obj), clust);
        if ((clust == BAD_CLUSTER) || (clust == DISK_ERROR)) {
            result = FR_DISK_ERR;
            goto ERROR_UNLOCK;
        }
    }

    /* Get to the currnet sector */
    sect = clst2sect(fs, clust);
    sect += (pos / SS(fs)) & (fs->csize - 1);

    /* How many sectors do we need to read once */
    if (fs->csize < buflen / SS(fs)) {
        step = fs->csize;
    } else {
        step = buflen / SS(fs);
    }

    n = 0;
    sclust = clust;
    while (n < buflen / SS(fs)) {
        if (disk_read(fs->pdrv, buf, sect, step) != RES_OK) {
            result = FR_DISK_ERR;
            goto ERROR_UNLOCK;
        }
        n += step;
        if (n >= buflen / SS(fs)) {
            break;
        }

        /* As cluster size is aligned, it must jump to next cluster when cluster size is less than pagesize */
        clust = get_fat(&(dfp->f_dir.obj), clust);
        if ((clust == BAD_CLUSTER) || (clust == DISK_ERROR)) {
            result = FR_DISK_ERR;
            goto ERROR_UNLOCK;
        } else if (fatfs_is_last_cluster(fs, clust)) {
            break; /* read end */
        }
        sect = clst2sect(fs, clust);
        buf += step * SS(fs);
    }

    ep->clst = sclust;
    ep->pos = pos;

    unlock_fs(fs, FR_OK);

    return (ssize_t)min(finfo->fsize - pos, n * SS(fs));

ERROR_UNLOCK:
    unlock_fs(fs, result);
ERROR_OUT:
    return -fatfs_2_vfs(result);
}

ssize_t fatfs_writepage(struct Vnode *vnode, char *buff, off_t pos, size_t buflen)
{
    FATFS *fs = (FATFS *)(vnode->originMount->data);
    DIR_FILE *dfp = (DIR_FILE *)(vnode->data);
    FILINFO *finfo = &(dfp->fno);
    FAT_ENTRY *ep = &(dfp->fat_entry);
    DWORD clust;
    DWORD sclst;
    QWORD sect;
    QWORD step;
    QWORD n;
    size_t position; /* byte offset */
    BYTE *buf = (BYTE *)buff;
    FRESULT result;
    FIL fil;
    int ret;

    ret = lock_fs(fs);
    if (ret == FALSE) {
        result = FR_TIMEOUT;
        goto ERROR_OUT;
    }

    if (finfo->fsize <= pos) {
        result = FR_OK;
        goto ERROR_UNLOCK;
    }

    if (ep->clst == 0) {
        ep->clst = finfo->sclst;
    }

    if (pos >= ep->pos) {
        clust = ep->clst;
        position = ep->pos;
    } else {
        clust = finfo->sclst;
        position = 0;
    }

    /* Get to the current cluster */
    n = pos / SS(fs) / fs->csize - position / SS(fs) / fs->csize;
    while (n--) {
        clust = get_fat(&(dfp->f_dir.obj), clust);
        if ((clust == BAD_CLUSTER) || (clust == DISK_ERROR)) {
            result = FR_DISK_ERR;
            goto ERROR_UNLOCK;
        }
    }

    /* Get to the currnet sector */
    sect = clst2sect(fs, clust);
    sect += (pos / SS(fs)) & (fs->csize - 1);

    /* How many sectors do we need to read once */
    if (fs->csize < buflen / SS(fs)) {
        step = fs->csize;
    } else {
        step = buflen / SS(fs);
    }

    n = 0;
    sclst = clust;
    while (n < buflen / SS(fs)) {
        if (disk_write(fs->pdrv, buf, sect, step) != RES_OK) {
            result = FR_DISK_ERR;
            goto ERROR_UNLOCK;
        }
        n += step;
        if (n >= buflen / SS(fs)) {
            break;
        }

        /* As cluster size is aligned, it must jump to next cluster when cluster size is less than pagesize */
        clust = get_fat(&(dfp->f_dir.obj), clust);
        if ((clust == BAD_CLUSTER) || (clust == DISK_ERROR)) {
            result = FR_DISK_ERR;
            goto ERROR_UNLOCK;
        } else if (fatfs_is_last_cluster(fs, clust)) {
            break; /* read end */
        }
        sect = clst2sect(fs, clust);
        buf += step * SS(fs);
    }

    ep->clst = sclst;
    ep->pos = pos;

    fil.obj.fs = fs;
    if (update_filbuff(finfo, &fil, NULL) < 0) {
        result = FR_DISK_ERR;
        goto ERROR_UNLOCK;
    }

    unlock_fs(fs, FR_OK);

    return (ssize_t)min(finfo->fsize - pos, n * SS(fs));
ERROR_UNLOCK:
    unlock_fs(fs, result);
ERROR_OUT:
    return -fatfs_2_vfs(result);
}
2432
///fat 文件系统 vnode实现
2433 2434 2435 2436 2437 2438 2439
struct VnodeOps fatfs_vops = {
    /* file ops */
    .Getattr = fatfs_stat,
    .Chattr = fatfs_chattr,
    .Lookup = fatfs_lookup,
    .Rename = fatfs_rename,
    .Create = fatfs_create,
2440 2441
    .ReadPage = fatfs_readpage,
    .WritePage = fatfs_writepage,
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
    .Unlink = fatfs_unlink,
    .Reclaim = fatfs_reclaim,
    .Truncate = fatfs_truncate,
    .Truncate64 = fatfs_truncate64,
    /* dir ops */
    .Opendir = fatfs_opendir,
    .Readdir = fatfs_readdir,
    .Rewinddir = fatfs_rewinddir,
    .Closedir = fatfs_closedir,
    .Mkdir = fatfs_mkdir,
    .Rmdir = fatfs_rmdir,
    .Fscheck = fatfs_fscheck,
2454 2455
    .Symlink = fatfs_symlink,
    .Readlink = fatfs_readlink,
2456
};
2457
//fat 文件系统 挂载实现
2458 2459 2460 2461
struct MountOps fatfs_mops = {
    .Mount = fatfs_mount,
    .Unmount = fatfs_umount,
    .Statfs = fatfs_statfs,
2462
    .Sync = fatfs_sync_adapt,
2463
};
2464
//fat 文件系统 文件操作实现
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
struct file_operations_vfs fatfs_fops = {
    .open = fatfs_open,
    .read = fatfs_read,
    .write = fatfs_write,
    .seek = fatfs_lseek,
    .close = fatfs_close,
    .mmap = OsVfsFileMmap,
    .fallocate = fatfs_fallocate,
    .fallocate64 = fatfs_fallocate64,
    .fsync = fatfs_fsync,
    .ioctl = fatfs_ioctl,
};

鸿蒙内核源码分析's avatar
鸿蒙内核源码分析 已提交
2478
FSMAP_ENTRY(fat_fsmap, "vfat", fatfs_mops, FALSE, TRUE);//注册文件映射
2479 2480

#endif /* LOSCFG_FS_FAT */