From 35ec1b92441ab2de6e2195eb2448129159ca4c68 Mon Sep 17 00:00:00 2001 From: Gregory Nutt Date: Fri, 20 Oct 2017 12:34:34 -0600 Subject: [PATCH] Squashed commit of the following: apps/fsutils/mkfatfs: New user-space fatfs appears to work fine. apps/fsutils/mkfatfs: Move mkfatfs from the OS to here. Not fully integrated on the intial commit. --- examples/mount/ramdisk.c | 2 +- fsutils/mkfatfs/.gitignore | 11 + fsutils/mkfatfs/Kconfig | 12 + fsutils/mkfatfs/Make.defs | 38 ++ fsutils/mkfatfs/Makefile | 105 ++++ fsutils/mkfatfs/configfat.c | 994 ++++++++++++++++++++++++++++++++++++ fsutils/mkfatfs/fat32.h | 942 ++++++++++++++++++++++++++++++++++ fsutils/mkfatfs/mkfatfs.c | 324 ++++++++++++ fsutils/mkfatfs/writefat.c | 615 ++++++++++++++++++++++ include/fsutils/mkfatfs.h | 150 ++++++ include/fsutils/mksmartfs.h | 20 +- nshlib/Kconfig | 2 +- nshlib/README.txt | 2 +- nshlib/nsh.h | 4 +- nshlib/nsh_command.c | 3 +- nshlib/nsh_fscmds.c | 10 +- 16 files changed, 3208 insertions(+), 26 deletions(-) create mode 100644 fsutils/mkfatfs/.gitignore create mode 100644 fsutils/mkfatfs/Kconfig create mode 100644 fsutils/mkfatfs/Make.defs create mode 100644 fsutils/mkfatfs/Makefile create mode 100644 fsutils/mkfatfs/configfat.c create mode 100644 fsutils/mkfatfs/fat32.h create mode 100644 fsutils/mkfatfs/mkfatfs.c create mode 100644 fsutils/mkfatfs/writefat.c create mode 100644 include/fsutils/mkfatfs.h diff --git a/examples/mount/ramdisk.c b/examples/mount/ramdisk.c index 52625f3bc..5604e06c1 100644 --- a/examples/mount/ramdisk.c +++ b/examples/mount/ramdisk.c @@ -46,8 +46,8 @@ #include #include -#include +#include "fsutils/mkfatfs.h" #include "mount.h" #ifndef CONFIG_EXAMPLES_MOUNT_DEVNAME diff --git a/fsutils/mkfatfs/.gitignore b/fsutils/mkfatfs/.gitignore new file mode 100644 index 000000000..83bd7b811 --- /dev/null +++ b/fsutils/mkfatfs/.gitignore @@ -0,0 +1,11 @@ +/Make.dep +/.depend +/.built +/*.asm +/*.rel +/*.lst +/*.sym +/*.adb +/*.lib +/*.src +/*.obj diff --git a/fsutils/mkfatfs/Kconfig b/fsutils/mkfatfs/Kconfig new file mode 100644 index 000000000..ebe51cef6 --- /dev/null +++ b/fsutils/mkfatfs/Kconfig @@ -0,0 +1,12 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +config FSUTILS_MKFATFS + bool "mkfatfs utility" + default y + depends on FS_FAT && !DISABLE_PSEUDOFS_OPERATIONS + ---help--- + Enables support for the mkfatfs utility + diff --git a/fsutils/mkfatfs/Make.defs b/fsutils/mkfatfs/Make.defs new file mode 100644 index 000000000..b7fa159f7 --- /dev/null +++ b/fsutils/mkfatfs/Make.defs @@ -0,0 +1,38 @@ +############################################################################ +# apps/fsutils/mkfatfs/Make.defs +# +# Copyright (C) 2017 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt +# +# 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 NuttX 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 OWNER 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. +# +############################################################################ + +ifeq ($(CONFIG_FSUTILS_MKFATFS),y) +CONFIGURED_APPS += fsutils/mkfatfs +endif diff --git a/fsutils/mkfatfs/Makefile b/fsutils/mkfatfs/Makefile new file mode 100644 index 000000000..bc5ecdde0 --- /dev/null +++ b/fsutils/mkfatfs/Makefile @@ -0,0 +1,105 @@ +############################################################################ +# apps/fsutils/mkfatfs/Makefile +# +# Copyright (C) 2017 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt +# +# 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 NuttX 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 OWNER 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 $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# mkfatfs utility + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_FSUTILS_MKFATFS),y) +CSRCS = mkfatfs.c configfat.c writefat.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +ifeq ($(CONFIG_WINDOWS_NATIVE),y) + BIN = ..\..\libapps$(LIBEXT) +else +ifeq ($(WINTOOL),y) + BIN = ..\\..\\libapps$(LIBEXT) +else + BIN = ../../libapps$(LIBEXT) +endif +endif + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built +.PHONY: context depend clean distclean preconfig +.PRECIOUS: ../../libapps$(LIBEXT) + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +.built: $(OBJS) + $(call ARCHIVE, $(BIN), $(OBJS)) + $(Q) touch .built + +install: + +context: + +.depend: Makefile $(SRCS) + $(Q) $(MKDEP) $(ROOTDEPPATH) "$(CC)" -- $(CFLAGS) -- $(SRCS) >Make.dep + $(Q) touch $@ + +depend: .depend + +clean: + $(call DELFILE, .built) + $(call CLEAN) + +distclean: clean + $(call DELFILE, Make.dep) + $(call DELFILE, .depend) + +preconfig: + +-include Make.dep diff --git a/fsutils/mkfatfs/configfat.c b/fsutils/mkfatfs/configfat.c new file mode 100644 index 000000000..5f5e3d384 --- /dev/null +++ b/fsutils/mkfatfs/configfat.c @@ -0,0 +1,994 @@ +/**************************************************************************** + * apps/fsutils/mkfatfs/configfat.c + * + * Copyright (C) 2008-2009, 2013, 2017 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * + * 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 NuttX 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 OWNER 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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include +#include + +#include "fsutils/mkfatfs.h" +#include "fat32.h" +#include "mkfatfs.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define NDX12 0 +#define NDX16 1 +#define NDX32 2 + +#define fatconfig12 fatconfig[NDX12] +#define fatconfig16 fatconfig[NDX16] +#define fatconfig32 fatconfig[NDX32] + +/* JMP rel8 and NOP opcodes */ + +#define OPCODE_JMP_REL8 0xeb +#define OPCODE_NOP 0x90 + +#define BOOTCODE_MSGOFFSET 29 + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct fat_config_s +{ + uint32_t fc_navailsects; /* The number of available sectors */ + uint32_t fc_nfatsects; /* The number of sectors in one FAT */ + uint32_t fc_nclusters; /* The number of clusters in the filesystem */ + uint32_t fc_rsvdseccount; /* The number of reserved sectors */ +}; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/* Reverse engineered, generic boot message logic for non-bootable disk. + * Message begins at offset 29; Sector relative offset must be poked into + * offset 3. + */ + +static uint8_t g_bootcodeblob[] = +{ + 0x0e, 0x1f, 0xbe, 0x00, 0x7c, 0xac, 0x22, 0xc0, 0x74, 0x0b, 0x56, + 0xb4, 0x0e, 0xbb, 0x07, 0x00, 0xcd, 0x10, 0x5e, 0xeb, 0xf0, 0x32, + 0xe4, 0xcd, 0x16, 0xcd, 0x19, 0xeb, 0xfe, 0x54, 0x68, 0x69, 0x73, + 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x61, 0x20, 0x62, + 0x6f, 0x6f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x64, 0x69, 0x73, + 0x6b, 0x2e, 0x20, 0x20, 0x50, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x20, + 0x69, 0x6e, 0x73, 0x65, 0x72, 0x74, 0x20, 0x61, 0x20, 0x62, 0x6f, + 0x6f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x66, 0x6c, 0x6f, 0x70, + 0x70, 0x79, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x70, 0x72, 0x65, + 0x73, 0x73, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6b, 0x65, 0x79, 0x20, + 0x74, 0x6f, 0x20, 0x74, 0x72, 0x79, 0x20, 0x61, 0x67, 0x61, 0x69, + 0x6e, 0x20, 0x2e, 0x2e, 0x2e, 0x0d, 0x0a, 0x00 +}; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: mkfatfs_nfatsect12 + * + * Description: + * Calculate the number of sectors need for one fat in a FAT12 file system. + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * navailsects - The number of sectors available for both FAT and data. + * This is a precalculated value equal to the total number of sectors + * minus the number of root directory sectors and minus the number of + * reserved sectors. + * + * Return: + * 0: That calculation would have overflowed + * >0: The size of one FAT in sectors. + * + ****************************************************************************/ + +static inline uint32_t +mkfatfs_nfatsect12(FAR struct fat_format_s *fmt, FAR struct fat_var_s *var, + uint32_t navailsects) +{ +#ifdef CONFIG_HAVE_LONG_LONG + uint64_t denom; + uint64_t numer; +#else + uint32_t denom; + uint32_t numer; +#endif + + /* For FAT12, the cluster number is held in a 12-bit number or 1.5 bytes per + * cluster reference. So each FAT sector will hold sectorsize/1.5 cluster + * references (except for the first sector of each FAT which has two reserved + * 12-bit values). And the total number of FAT sectors needed is: + * + * nfatsects = (1.5 * (ndataclust + 2) / sectorsize) + * + * where: + * + * ndataclust = ndatasect / clustsize + * nvailsects = nfatsects + ndatasect + * + * The solution to this set of linear equations is: + * + * nfatsects = (3 * navailsects + 6 * clustersize) / + * (3 * nfats + 2 * sectorsize * clustersize) + * + * The numerator would overflow uint32_t if: + * + * 3 * navailsects + 6 * clustersize > 0xffffffff + * + * Or + * + * navailsects > 0x55555555 - 2 * clustersize + */ + +#ifndef CONFIG_HAVE_LONG_LONG + if (navailsects <= (0x55555555 - (1 << (fmt->ff_clustshift + 1)))) + { +#endif + + denom = (fmt->ff_nfats << 1) + fmt->ff_nfats + + (var->fv_sectorsize << (fmt->ff_clustshift + 1)); + numer = (navailsects << 1) + navailsects + + (1 << (fmt->ff_clustshift + 2)) + (1 << (fmt->ff_clustshift + 1)); + return (uint32_t)((numer + denom - 1) / denom); + +#ifndef CONFIG_HAVE_LONG_LONG + } + else + { + return 0; + } +#endif +} + +/**************************************************************************** + * Name: mkfatfs_nfatsect16 + * + * Description: + * Calculate the number of sectors need for one fat in a FAT16 file system. + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * navailsects - The number of sectors available for both FAT and data. + * This is a precalculated value equal to the total number of sectors + * minus the number of root directory sectors and minus the number of + * reserved sectors. + * + * Return: + * The size of one FAT in sectors. + * + ****************************************************************************/ + +static inline uint32_t +mkfatfs_nfatsect16(FAR struct fat_format_s *fmt, FAR struct fat_var_s *var, + uint32_t navailsects) +{ +#ifdef CONFIG_HAVE_LONG_LONG + uint64_t denom; + uint64_t numer; +#else + uint32_t denom; + uint32_t numer; +#endif + + /* For FAT16, the cluster number is held in a 16-bit number or 2 bytes per + * cluster reference. So each FAT sector will hold sectorsize/2 cluster + * references (except for the first sector of each FAT which has two reserved + * 16-bit values). And the total number of FAT sectors needed is: + * + * nfatsects = (2 * (ndataclust + 2) / sectorsize) + * + * where: + * + * ndataclust = ndatasect / clustsize + * nvailsects = nfatsects + ndatasect + * + * The solution to this set of linear equations is: + * + * nfatsects = (navailsects + 2 * clustersize) / + * (nfats + sectorsize * clustersize / 2) + * + * Overflow in the calculation of the numerator could occur if: + * + * navailsects > 0xffffffff - 2 * clustersize + */ + + if (fmt->ff_clustshift == 0) + { + denom = fmt->ff_nfats + (var->fv_sectorsize >> 1); + numer = navailsects + 2; + } + else + { + denom = fmt->ff_nfats + (var->fv_sectorsize << (fmt->ff_clustshift - 1)); + numer = navailsects + (1 << (fmt->ff_clustshift + 1)); + } + + return (uint32_t)((numer + denom - 1) / denom); +} + +/**************************************************************************** + * Name: mkfatfs_nfatsect32 + * + * Description: + * Calculate the number of sectors need for one fat in a FAT32 file system. + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * navailsects - The number of sectors available for both FAT and data. + * This is a precalculated value equal to the total number of sectors + * minus the number of root directory sectors and minus the number of + * reserved sectors. + * + * Return: + * The size of one FAT in sectors. + * + ****************************************************************************/ + +static inline uint32_t +mkfatfs_nfatsect32(FAR struct fat_format_s *fmt, FAR struct fat_var_s *var, + uint32_t navailsects) +{ +#ifdef CONFIG_HAVE_LONG_LONG + uint64_t denom; + uint64_t numer; +#else + uint32_t denom; + uint32_t numer; +#endif + + /* For FAT32, the cluster number is held in a 32-bit number or 4 bytes per + * cluster reference. So each FAT sector will hold sectorsize/4 cluster + * references (except for the first sector of each FAT which has three reserved + * 32-bit values). And the total number of FAT sectors needed is: + * + * nfatsects = (4 * (ndataclust + 3) / sectorsize) + * + * where: + * + * ndataclust = ndatasect / clustsize + * nvailsects = nfatsects + ndatasect + * + * The solution to this set of linear equations is: + * + * nfatsects = (navailsects + 3 * clustersize) / + * (nfats + sectorsize * clustersize / 4) + * + * Overflow in the 32-bit calculation of the numerator could occur if: + * + * navailsects > 0xffffffff - 3 * clustersize + */ + + if (fmt->ff_clustshift == 0) + { + denom = fmt->ff_nfats + (var->fv_sectorsize >> 2); + numer = navailsects + 3; + } + else if (fmt->ff_clustshift == 1) + { + denom = fmt->ff_nfats + (var->fv_sectorsize >> 1); + numer = navailsects + 6; + } + else + { + denom = fmt->ff_nfats + (var->fv_sectorsize << (fmt->ff_clustshift - 2)); + numer = navailsects + (1 << (fmt->ff_clustshift + 1)) + (1 << fmt->ff_clustshift); + } + + return (uint32_t)((numer + denom - 1) / denom); +} + +/**************************************************************************** + * Name: mkfatfs_clustersearchlimits + * + * Description: + * Pick the starting and ending cluster size to use in the search for the + * the optimal cluster size. + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * + * Return: + * Starting cluster size is set in fmt->ff_clustshift; Final cluster + * size is the returned value. + * + ****************************************************************************/ + +static inline uint8_t +mkfatfs_clustersearchlimits(FAR struct fat_format_s *fmt, FAR struct fat_var_s *var) +{ + uint8_t mxclustshift; + + /* Did the caller already pick the cluster size? If not, the clustshift value + * will be 0xff + */ + + if (fmt->ff_clustshift == 0xff) + { + /* Pick a starting size based on the number of sectors on the device */ + + if (fmt->ff_nsectors < 2048) + { + /* 2k sectors, start wit 1 sector/cluster. */ + fmt->ff_clustshift = 0; + } + else if (fmt->ff_nsectors < 4096) + { + /* 4k sectors, start with 2 sector/cluster. */ + fmt->ff_clustshift = 1; + } + else if (fmt->ff_nsectors < 8192) + { + /* 8k sectors, start with 4 sector/cluster. */ + fmt->ff_clustshift = 2; + } + else if (fmt->ff_nsectors < 16384) + { + /* 16k sectors, start with 8 sector/cluster. */ + fmt->ff_clustshift = 3; + } + else if (fmt->ff_nsectors < 32768) + { + /* 32k sectors, start with 16 sector/cluster. */ + fmt->ff_clustshift = 4; + } + else + { + /* Otherwise, 32 sector/cluster. */ + fmt->ff_clustshift = 5; + } + + /* Wherever the search starts, it will end with the maximum of + * 128 sectors per cluster + */ + + mxclustshift = 7; + } + else + { + /* The caller has selected a cluster size. There will be no search! + * Just set the maximum to the caller specificed value. + */ + + mxclustshift = fmt->ff_clustshift; + } + + return mxclustshift; +} + +/**************************************************************************** + * Name: mkfatfs_tryfat12 + * + * Description: + * Try to define a FAT12 filesystem on the device using the candidate + * sectors per cluster + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * config - FAT12-specific configuration + * + * Return: + * Zero on success configuration of a FAT12 file system; negated errno + * on failure + * + ****************************************************************************/ + +static inline int +mkfatfs_tryfat12(FAR struct fat_format_s *fmt, FAR struct fat_var_s *var, + FAR struct fat_config_s *config) +{ + uint32_t maxnclusters; + + /* Calculate the number sectors in one FAT required to access all of the + * available sectors. + */ + + config->fc_nfatsects = mkfatfs_nfatsect12(fmt, var, config->fc_navailsects); + if (config->fc_nfatsects > 0) + { + /* Calculate the number of clusters available given the number of available + * sectors and the number of those that will be used for FAT: + */ + + config->fc_nclusters = + (config->fc_navailsects - + fmt->ff_nfats * config->fc_nfatsects) >> fmt->ff_clustshift; + + /* Calculate the maximum number of clusters that could be supported by a + * FAT of this size. + * + * maxnclusters = nfatsects * sectorsize / 1.5 - 2 + */ + + maxnclusters = (config->fc_nfatsects << (var->fv_sectshift + 1)) / 3; + if (maxnclusters > FAT_MAXCLUST12) + { + maxnclusters = FAT_MAXCLUST12; + } + + finfo("nfatsects=%u nclusters=%u (max=%u)\n", + config->fc_nfatsects, config->fc_nclusters, maxnclusters); + + /* Check if this number of clusters would overflow the maximum for + * FAT12 (remembering that two FAT cluster slots are reserved). + */ + + if (config->fc_nclusters + 2 > maxnclusters) + { + fwarn("WARNING: Too many clusters for FAT12: %d > %d\n", + config->fc_nclusters, maxnclusters - 2); + + return -ENFILE; + } + } + + return 0; +} + +/**************************************************************************** + * Name: mkfatfs_tryfat16 + * + * Description: + * Try to define a FAT16 filesystem on the device using the candidate + * sectors per cluster + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * config - FAT16-specific configuration + * + * Return: + * Zero on success configuration of a FAT16 file system; negated errno + * on failure + * + ****************************************************************************/ + +static inline int +mkfatfs_tryfat16(FAR struct fat_format_s *fmt, FAR struct fat_var_s *var, + FAR struct fat_config_s *config) +{ + uint32_t maxnclusters; + + /* Calculate the number sectors in one FAT required to access all of the + * available sectors. + */ + + config->fc_nfatsects = mkfatfs_nfatsect16(fmt, var, config->fc_navailsects); + if (config->fc_nfatsects > 0) + { + /* Calculate the number of clusters available given the number of available + * sectors and the number of those that will be used for FAT: + */ + + config->fc_nclusters = + (config->fc_navailsects - + fmt->ff_nfats * config->fc_nfatsects) >> fmt->ff_clustshift; + + /* Calculate the maximum number of clusters that could be supported by a + * FAT of this size. + * + * maxnclusters = nfatsects * sectorsize / 2 - 2 + */ + + maxnclusters = config->fc_nfatsects << (var->fv_sectshift - 1); + if (maxnclusters > FAT_MAXCLUST16) + { + maxnclusters = FAT_MAXCLUST16; + } + + finfo("nfatsects=%u nclusters=%u (min=%u max=%u)\n", + config->fc_nfatsects, config->fc_nclusters, FAT_MINCLUST16, + maxnclusters); + + /* Check if this number of clusters would overflow the maximum for + * FAT16 (remembering that two FAT cluster slots are reserved). + * Check the lower limit as well. The FAT12 is distinguished from FAT16 + * by comparing the number of clusters on the device agains a known + * threshold. If a small FAT16 file system were created, then it would + * be confused as a FAT12 at mount time. + */ + + if ((config->fc_nclusters + 2 > maxnclusters) || + (config->fc_nclusters < FAT_MINCLUST16)) + { + fwarn("WARNING: Too few or too many clusters for FAT16: %d < %d < %d\n", + FAT_MINCLUST16, config->fc_nclusters, maxnclusters - 2); + + return -ENFILE; + } + } + + return 0; +} + +/**************************************************************************** + * Name: mkfatfs_tryfat32 + * + * Description: + * Try to define a FAT32 filesystem on the device using the candidate + * sectors per cluster + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * config - FAT32-specific configuration + * + * Return: + * Zero on success configuration of a FAT32 file system; negated errno + * on failure + * + ****************************************************************************/ + +static inline int +mkfatfs_tryfat32(FAR struct fat_format_s *fmt, FAR struct fat_var_s *var, + FAR struct fat_config_s *config) +{ + uint32_t maxnclusters; + + /* Calculate the number sectors in one FAT required to access all of the + * available sectors. + */ + + config->fc_nfatsects = mkfatfs_nfatsect32(fmt, var, config->fc_navailsects); + if (config->fc_nfatsects > 0) + { + /* Calculate the number of clusters available given the number of available + * sectors and the number of those that will be used for FAT: + */ + + config->fc_nclusters = + (config->fc_navailsects - + fmt->ff_nfats * config->fc_nfatsects) >> fmt->ff_clustshift; + + /* Calculate the maximum number of clusters that could be supported by a + * FAT of this size. + * + * maxnclusters = nfatsects * sectorsize / 4 - 2 + */ + + maxnclusters = (config->fc_nfatsects << (var->fv_sectshift - 2)); + if (maxnclusters > FAT_MAXCLUST32) + { + maxnclusters = FAT_MAXCLUST32; + } + + finfo("nfatsects=%u nclusters=%u (max=%u)\n", + config->fc_nfatsects, config->fc_nclusters, maxnclusters); + + /* Check if this number of clusters would overflow the maximum for + * FAT32 (remembering that two FAT cluster slots are reserved). + */ + + if ((config->fc_nclusters + 3 > maxnclusters) || + (config->fc_nclusters < FAT_MINCLUST32)) + { + fwarn("WARNING: Too few or too many clusters for FAT32: %d < %d < %d\n", + FAT_MINCLUST32, config->fc_nclusters, maxnclusters - 3); + + return -ENFILE; + } + } + + return 0; +} + +/**************************************************************************** + * Name: mkfatfs_selectfat + * + * Description: + * The cluster search has succeeded, select the specified FAT FS + * + * Input: + * fattype - The FAT size selected + * fmt - Caller specified format parameters + * var - Format parameters that are not caller specifiable. + * + * Return: + * None + * + ****************************************************************************/ + +static inline void +mkfatfs_selectfat(int fattype, FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var, FAR struct fat_config_s *config) +{ + /* Return the appropriate information about the selected file system. */ + + finfo("Selected FAT%d\n", fattype); + + var->fv_fattype = fattype; + var->fv_nclusters = config->fc_nclusters; + var->fv_nfatsects = config->fc_nfatsects; + fmt->ff_rsvdseccount = config->fc_rsvdseccount; +} + +/**************************************************************************** + * Name: mkfatfs_clustersearch + * + * Description: + * Search to find the smallest (reasonable) cluster size for the FAT file + * system. + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * + * Return: + * Zero on success; negated errno on failure + * + ****************************************************************************/ + +static inline int +mkfatfs_clustersearch(FAR struct fat_format_s *fmt, FAR struct fat_var_s *var) +{ + struct fat_config_s fatconfig[3]; + uint8_t mxclustshift; + + memset(fatconfig, 0, 3*sizeof(struct fat_config_s)); + + /* Select the reserved sector count for each FAT size */ + + if (fmt->ff_rsvdseccount) + { + fatconfig12.fc_rsvdseccount = fmt->ff_rsvdseccount; + fatconfig16.fc_rsvdseccount = fmt->ff_rsvdseccount; + + if (fmt->ff_rsvdseccount < 2) + { + fwarn("WARNING: At least 2 reserved sectors needed by FAT32\n"); + fatconfig32.fc_rsvdseccount = 2; + } + else + { + fatconfig32.fc_rsvdseccount = fmt->ff_rsvdseccount; + } + } + else + { + fatconfig12.fc_rsvdseccount = 1; + fatconfig16.fc_rsvdseccount = 1; + fatconfig32.fc_rsvdseccount = 32; + } + + /* Determine the number of sectors needed by the root directory. + * This is a constant value, independent of cluster size for FAT12/16 + */ + + if (var->fv_fattype != 32) + { + /* Calculate the number of sectors reqired to contain the selected + * number of root directory entries. This value is save in the var + * structure but will be overwritten if FAT32 is selected. FAT32 uses + * a cluster chain for the root directory, so the concept of the number + * of root directory entries does not apply to FAT32 + */ + + var->fv_nrootdirsects = + ((fmt->ff_rootdirentries << DIR_SHIFT) + var->fv_sectorsize - 1) >> var->fv_sectshift; + + /* The number of data sectors available (includes the fat itself) + * This value is a constant for FAT12/16, but not FAT32 because the + * size of the root directory cluster changes + */ + + fatconfig12.fc_navailsects = + fatconfig16.fc_navailsects = + fmt->ff_nsectors - var->fv_nrootdirsects - fatconfig12.fc_rsvdseccount; + } + + /* Select an initial and terminal cluster size to use in the search (if these + * values were not provided by the caller) + */ + + mxclustshift = mkfatfs_clustersearchlimits(fmt, var); + + do + { + finfo("Configuring with %d sectors/cluster...\n", + 1 << fmt->ff_clustshift); + + /* Check if FAT12 has not been excluded */ + + if (var->fv_fattype == 0 || var->fv_fattype == 12) + { + /* Try to configure a FAT12 file system with this cluster size */ + + if (mkfatfs_tryfat12(fmt, var, &fatconfig12) != 0) + { + fwarn("WARNING: Cannot format FAT12 at %u sectors/cluster\n", + 1 << fmt->ff_clustshift); + + fatconfig12.fc_nfatsects = 0; + fatconfig12.fc_nclusters = 0; + } + } + + /* Check if FAT16 has not been excluded */ + + if (var->fv_fattype == 0 || var->fv_fattype == 16) + { + /* Try to configure a FAT16 file system with this cluster size */ + + if (mkfatfs_tryfat16(fmt, var, &fatconfig16) != 0) + { + fwarn("WARNING: Cannot format FAT16 at %u sectors/cluster\n", + 1 << fmt->ff_clustshift); + + fatconfig16.fc_nfatsects = 0; + fatconfig16.fc_nclusters = 0; + } + } + + /* If either FAT12 or 16 was configured at this sector/cluster setting, + * then finish the configuration and break out now + */ + + if (fatconfig12.fc_nclusters || fatconfig16.fc_nclusters) + { + if ((!var->fv_fattype && fatconfig16.fc_nclusters > fatconfig12.fc_nclusters) || + (var ->fv_fattype == 16)) + { + /* The caller has selected FAT16 -OR- no FAT type has been selected, but + * the FAT16 selection has more clusters. Select FAT16. + */ + + mkfatfs_selectfat(16, fmt, var, &fatconfig16); + } + else + { + /* The caller has selected FAT12 -OR- no FAT type has been selected, but + * the FAT12 selected has more clusters. Selected FAT12 + */ + + mkfatfs_selectfat(12, fmt, var, &fatconfig12); + } + + return OK; + } + +#if 0 + /* Check if FAT32 has not been excluded */ + + if (var->fv_fattype == 0 || var->fv_fattype == 32) +#else + /* FAT32 must be explicitly requested */ + + if (var->fv_fattype == 32) +#endif + { + /* The number of data sectors available (includes the fat itself) + * This value is a constant with respect to cluster sizefor FAT12/16, but not FAT32 + * because the size of the root directory cluster changes with cluster size. + */ + + fatconfig32.fc_navailsects = fmt->ff_nsectors - (1 << fmt->ff_clustshift) - fatconfig32.fc_rsvdseccount; + + /* Try to configure a FAT32 file system with this cluster size */ + + if (mkfatfs_tryfat32(fmt, var, &fatconfig32) != 0) + { + fwarn("WARNING: Cannot format FAT32 at %u sectors/cluster\n", + 1 << fmt->ff_clustshift); + + fatconfig32.fc_nfatsects = 0; + fatconfig32.fc_nclusters = 0; + } + else + { + /* Select FAT32 if we have not already done so */ + + mkfatfs_selectfat(32, fmt, var, &fatconfig32); + return OK; + } + } + + /* Otherwise, bump up the sectors/cluster for the next time around the loop. */ + + fmt->ff_clustshift++; + } + while (fmt->ff_clustshift <= mxclustshift); + + return -ENFILE; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: mkfatfs_configfatfs + * + * Description: + * Based on the geometry of the block device and upon the caller-selected + * values, configure the FAT filesystem for the device. + * + * Input: + * fmt - Caller specified format parameters + * var - Holds disk geomtry data. Also, the location to return FAT + * configuration data + * + * Return: + * Zero on success; negated errno on failure + * + ****************************************************************************/ + +int mkfatfs_configfatfs(FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var) +{ + int ret; + + /* Select the number of root directory entries (FAT12/16 only). If FAT32 is selected, + * this value will be cleared later + */ + + if (!fmt->ff_rootdirentries) + { + /* The caller did not specify the number of root directory entries; use a default of 512. */ + + fmt->ff_rootdirentries = 512; + } + + /* Search to determine the smallest (reasonable) cluster size. A by-product + * of this search will be the selection of the FAT size (12/16/32) if the + * caller has not specified the FAT size + */ + + ret = mkfatfs_clustersearch(fmt, var); + if (ret < 0) + { + ferr("WARNING: Failed to set cluster size\n"); + return ret; + } + + /* Perform FAT specific initialization */ + + /* Set up boot jump assuming FAT 12/16 offset to bootcode */ + + var->fv_jump[0] = OPCODE_JMP_REL8; + var->fv_jump[2] = OPCODE_NOP; + var->fv_bootcode = g_bootcodeblob; + var->fv_bootcodesize = sizeof(g_bootcodeblob); + + if (var->fv_fattype != 32) + { + /* Set up additional, non-zero FAT12/16 fields */ + + /* Patch in the correct offset to the boot code */ + + var->fv_jump[1] = BS16_BOOTCODE - 2; + g_bootcodeblob[3] = BS16_BOOTCODE + BOOTCODE_MSGOFFSET; + } + else + { + /* Patch in the correct offset to the boot code */ + + var->fv_jump[1] = BS32_BOOTCODE - 2; + g_bootcodeblob[3] = BS32_BOOTCODE + BOOTCODE_MSGOFFSET; + + /* The root directory is a cluster chain... its is initialize size is one cluster */ + + var->fv_nrootdirsects = 1 << fmt->ff_clustshift; + + /* The number of reported root directory entries should should be zero for + * FAT32 because the root directory is a cluster chain. + */ + + fmt->ff_rootdirentries = 0; + + /* Verify the caller's backupboot selection */ + + if (fmt->ff_backupboot <= 1 || fmt->ff_backupboot >= fmt->ff_rsvdseccount) + { + ferr("WARNING: Invalid backup boot sector: %d\n", fmt->ff_backupboot); + fmt->ff_backupboot = 0; + } + + /* Check if the caller has selected a location for the backup boot record */ + + if (!fmt->ff_backupboot) + { + /* There must be reserved sectors in order to have a backup boot sector */ + + if (fmt->ff_rsvdseccount >= 2) + { + /* Sector 0 is the MBR; 1... ff_rsvdseccount are reserved. Try the next + * the last reserved sector. + */ + + fmt->ff_backupboot = fmt->ff_rsvdseccount - 1; + if (fmt->ff_backupboot > 6) + { + /* Limit the location to within the first 7 */ + + fmt->ff_backupboot = 6; + } + } + } + } + + /* Report the selected fat type */ + + fmt->ff_fattype = var->fv_fattype; + + /* Describe the configured filesystem */ + +#ifdef CONFIG_DEBUG_FEATURES + finfo("Sector size: %d bytes\n", var->fv_sectorsize); + finfo("Number of sectors: %d sectors\n", fmt->ff_nsectors); + finfo("FAT size: %d bits\n", var->fv_fattype); + finfo("Number FATs: %d\n", fmt->ff_nfats); + finfo("Sectors per cluster: %d sectors\n", 1 << fmt->ff_clustshift); + finfo("FS size: %d sectors\n", var->fv_nfatsects); + finfo(" %d clusters\n", var->fv_nclusters); + + if (var->fv_fattype != 32) + { + finfo("Root directory slots: %d\n", fmt->ff_rootdirentries); + } + + finfo("Volume ID: %08x\n", fmt->ff_volumeid); + finfo("Volume Label: \"%c%c%c%c%c%c%c%c%c%c%c\"\n", + fmt->ff_volumelabel[0], fmt->ff_volumelabel[1], fmt->ff_volumelabel[2], + fmt->ff_volumelabel[3], fmt->ff_volumelabel[4], fmt->ff_volumelabel[5], + fmt->ff_volumelabel[6], fmt->ff_volumelabel[7], fmt->ff_volumelabel[8], + fmt->ff_volumelabel[9], fmt->ff_volumelabel[10]); +#endif + return OK; +} diff --git a/fsutils/mkfatfs/fat32.h b/fsutils/mkfatfs/fat32.h new file mode 100644 index 000000000..f37d2c7b4 --- /dev/null +++ b/fsutils/mkfatfs/fat32.h @@ -0,0 +1,942 @@ +/**************************************************************************** + * apps/futils/mkfatfs/fat32.h + * + * Copyright (C) 2007-2009, 2011, 2017 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * + * 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 NuttX 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 OWNER 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. + * + ****************************************************************************/ + +#ifndef __APPS_FSUTILS_MKFATFS_FAT32_H +#define __APPS_FSUTILS_MKFATFS_FAT32_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include +#include +#include + +#include +#include + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * These offsets describes the master boot record. + * + * The folowing fields are common to FAT12/16/32 (but all value descriptions + * refer to the interpretation under FAT32. + */ + +#define BS_JUMP 0 /* 3@0: Jump instruction to boot code (ignored) */ +#define BS_OEMNAME 3 /* 8@3: Usually "MSWIN4.1" */ +#define BS_BYTESPERSEC 11 /* 2@11: Bytes per sector: 512, 1024, 2048, 4096 */ +#define BS_SECPERCLUS 13 /* 1@13: Sectors per allocation unit: 2**n, n=0..7 */ +#define BS_RESVDSECCOUNT 14 /* 2@14: Reserved sector count: Usually 32 */ +#define BS_NUMFATS 16 /* 1@16: Number of FAT data structures: always 2 */ +#define BS_ROOTENTCNT 17 /* 2@17: FAT12/16: Must be 0 for FAT32 */ +#define BS_TOTSEC16 19 /* 2@19: FAT12/16: Must be 0, see BS_TOTSEC32 */ +#define BS_MEDIA 21 /* 1@21: Media code: f0, f8, f9-fa, fc-ff */ +#define BS_FATSZ16 22 /* 2@22: FAT12/16: Must be 0, see BS_FATSZ32 */ +#define BS_SECPERTRK 24 /* 2@24: Sectors per track geometry value */ +#define BS_NUMHEADS 26 /* 2@26: Number of heads geometry value */ +#define BS_HIDSEC 28 /* 4@28: Count of hidden sectors preceding FAT */ +#define BS_TOTSEC32 32 /* 4@32: Total count of sectors on the volume */ + +/* The following fields are only valid for FAT12/16 */ + +#define BS16_DRVNUM 36 /* 1@36: Drive number for MSDOS bootstrap */ + /* 1@37: Reserved (zero) */ +#define BS16_BOOTSIG 38 /* 1@38: Extended boot signature: 0x29 if following valid */ +#define BS16_VOLID 39 /* 4@39: Volume serial number */ +#define BS16_VOLLAB 43 /* 11@43: Volume label */ +#define BS16_FILESYSTYPE 54 /* 8@54: "FAT12 ", "FAT16 ", or "FAT " */ + +#define BS16_BOOTCODE 62 /* Boot code may be placed in the remainder of the sector */ +#define BS16_BOOTCODESIZE 448 + +/* The following fields are only valid for FAT32 */ + +#define BS32_FATSZ32 36 /* 4@36: Count of sectors occupied by one FAT */ +#define BS32_EXTFLAGS 40 /* 2@40: 0-3:Active FAT, 7=0 both FATS, 7=1 one FAT */ +#define BS32_FSVER 42 /* 2@42: MSB:Major LSB:Minor revision number (0.0) */ +#define BS32_ROOTCLUS 44 /* 4@44: Cluster no. of 1st cluster of root dir */ +#define BS32_FSINFO 48 /* 2@48: Sector number of fsinfo structure. Usually 1. */ +#define BS32_BKBOOTSEC 50 /* 2@50: Sector number of boot record. Usually 6 */ + /* 12@52: Reserved (zero) */ +#define BS32_DRVNUM 64 /* 1@64: Drive number for MSDOS bootstrap */ + /* 1@65: Reserved (zero) */ +#define BS32_BOOTSIG 66 /* 1@66: Extended boot signature: 0x29 if following valid */ +#define BS32_VOLID 67 /* 4@67: Volume serial number */ +#define BS32_VOLLAB 71 /* 11@71: Volume label */ +#define BS32_FILESYSTYPE 82 /* 8@82: "FAT12 ", "FAT16 ", or "FAT " */ + +#define BS32_BOOTCODE 90 /* Boot code may be placed in the remainder of the sector */ +#define BS32_BOOTCODESIZE 420 + +/* If the sector is not an MBR, then it could have a partition table at + * this offset. + */ + +#define MBR_TABLE 446 + +/* The magic bytes at the end of the MBR are common to FAT12/16/32 */ + +#define BS_SIGNATURE 510 /* 2@510: Valid MBRs have 0x55aa here */ + +#define BOOT_SIGNATURE16 0xaa55 +#define BOOT_SIGNATURE32 0xaa550000 + +/* The extended boot signature (BS16/32_BOOTSIG) */ + +#define EXTBOOT_SIGNATURE 0x29 + +/**************************************************************************** + * These offsets describes the partition table. + */ + /* 446@0: Generally unused and zero; but may + * include IDM Boot Manager menu entry at 8@394 */ +#define PART_ENTRY(n) (446+((n) << 4)) /* n = 0,1,2,3 */ +#define PART_ENTRY1 446 /* 16@446: Partition table, first entry */ +#define PART_ENTRY2 462 /* 16@462: Partition table, second entry */ +#define PART_ENTRY3 478 /* 16@478: Partition table, third entry */ +#define PART_ENTRY4 494 /* 16@494: Partition table, fourth entry */ +#define PART_SIGNATURE 510 /* 2@510: Valid partitions have 0x55aa here */ + +/**************************************************************************** + * These offsets describes one partition table entry. NOTE that ent entries + * are aligned to 16-bit offsets so that the STARTSECTOR and SIZE values are + * not properly aligned. + */ + +#define PART_BOOTINDICATOR 0 /* 1@0: Boot indicator (0x80: active;0x00:otherwise) */ +#define PART_STARTCHS 1 /* 3@1: Starting Cylinder/Head/Sector values */ +#define PART_TYPE 4 /* 1@4: Partition type description */ +#define PART_ENDCHS 5 /* 3@5: Ending Cylinder/Head/Sector values */ +#define PART_STARTSECTOR 8 /* 4@8: Starting sector */ +#define PART_SIZE 12 /* 4@12: Partition size (in sectors) */ + +/**************************************************************************** + * Partition table types. + */ + +#define PART_TYPE_NONE 0 /* No partition */ +#define PART_TYPE_FAT12 1 /* FAT12 */ +#define PART_TYPE_FAT16A 4 /* FAT16 (Partition smaller than 32MB) */ +#define PART_TYPE_EXT 5 /* Extended MS-DOS Partition */ +#define PART_TYPE_FAT16B 6 /* FAT16 (Partition larger than 32MB) */ +#define PART_TYPE_FAT32 11 /* FAT32 (Partition up to 2048Gb) */ +#define PART_TYPE_FAT32X 12 /* Same as 11, but uses LBA1 0x13 extensions */ +#define PART_TYPE_FAT16X 14 /* Same as 6, but uses LBA1 0x13 extensions */ +#define PART_TYPE_EXTX 15 /* Same as 5, but uses LBA1 0x13 extensions */ + +/**************************************************************************** + * Each FAT "short" 8.3 file name directory entry is 32-bytes long. + * + * Sizes and limits + */ + +/**************************************************************************** + * Each FAT "short" 8.3 file name directory entry is 32-bytes long. + * + * Sizes and limits + */ + +#define DIR_MAXFNAME 11 /* Max short name size is 8+3 = 11 */ + +/* The following define offsets relative to the beginning of a directory + * entry. + */ + +#define DIR_NAME 0 /* 11@ 0: NAME: 8 bytes + 3 byte extension */ +#define DIR_ATTRIBUTES 11 /* 1@11: File attibutes (see below) */ +#define DIR_NTRES 12 /* 1@12: Reserved for use by NT */ +#define DIR_CRTTIMETENTH 13 /* 1@13: Tenth sec creation timestamp */ +#define DIR_CRTIME 14 /* 2@14: Time file created */ +#define DIR_CRDATE 16 /* 2@16: Date file created */ +#define DIR_LASTACCDATE 18 /* 2@19: Last access date */ +#define DIR_FSTCLUSTHI 20 /* 2@20: MS first cluster number */ +#define DIR_WRTTIME 22 /* 2@22: Time of last write */ +#define DIR_WRTDATE 24 /* 2@24: Date of last write */ +#define DIR_FSTCLUSTLO 26 /* 2@26: LS first cluster number */ +#define DIR_FILESIZE 28 /* 4@28: File size in bytes */ +#define DIR_SIZE 32 /* The size of one directory entry */ +#define DIR_SHIFT 5 /* log2 of DIR_SIZE */ + +/* First byte of the directory name has special meanings: */ + +#define DIR0_EMPTY 0xe5 /* The directory entry is empty */ +#define DIR0_ALLEMPTY 0x00 /* This entry and all following are empty */ +#define DIR0_E5 0x05 /* The actual value is 0xe5 */ + +/* NTRES flags in the FAT directory */ + +#define FATNTRES_LCNAME 0x08 /* Lower case in name */ +#define FATNTRES_LCEXT 0x10 /* Lower case in extension */ + +/* Directory indexing helper. Each directory entry is 32-bytes in length. + * The number of directory entries in a sector then varies with the size + * of the sector supported in hardware. + */ + +#define DIRSEC_NDXMASK(f) (((f)->fs_hwsectorsize - 1) >> 5) +#define DIRSEC_NDIRS(f) (((f)->fs_hwsectorsize) >> 5) +#define DIRSEC_BYTENDX(f,i) (((i) & DIRSEC_NDXMASK(fs)) << 5) + +#define SEC_NDXMASK(f) ((f)->fs_hwsectorsize - 1) +#define SEC_NSECTORS(f,n) ((n) / (f)->fs_hwsectorsize) + +#define CLUS_NDXMASK(f) ((f)->fs_fatsecperclus - 1) + +/**************************************************************************** + * The FAT "long" file name (LFN) directory entry */ + +#ifdef CONFIG_FAT_LFN + +/* Sizes and limits */ + +# ifndef CONFIG_FAT_MAXFNAME /* The maximum support filename can be limited */ +# define LDIR_MAXFNAME 255 /* Max unicode characters in file name */ +# elif CONFIG_FAT_MAXFNAME <= 255 +# define LDIR_MAXFNAME CONFIG_FAT_MAXFNAME +# else +# error "Illegal value for CONFIG_FAT_MAXFNAME" +# endif + +# define LDIR_MAXLFNCHARS 13 /* Max unicode characters in one LFN entry */ +# define LDIR_MAXLFNS 20 /* Max number of LFN entries */ + +/* LFN directory entry offsets */ + +# define LDIR_SEQ 0 /* 1@ 0: Sequence number */ +# define LDIR_WCHAR1_5 1 /* 10@ 1: File name characters 1-5 (5 Unicode characters) */ +# define LDIR_ATTRIBUTES 11 /* 1@11: File attributes (always 0x0f) */ +# define LDIR_NTRES 12 /* 1@12: Reserved for use by NT (always 0x00) */ +# define LDIR_CHECKSUM 13 /* 1@13: Checksum of the DOS filename */ +# define LDIR_WCHAR6_11 14 /* 12@14: File name characters 6-11 (6 Unicode characters) */ +# define LDIR_FSTCLUSTLO 26 /* 2@26: First cluster (always 0x0000) */ +# define LDIR_WCHAR12_13 28 /* 4@28: File name characters 12-13 (2 Unicode characters) */ + +/* LFN sequence number and allocation status */ + +# define LDIR0_EMPTY DIR0_EMPTY /* The directory entry is empty */ +# define LDIR0_ALLEMPTY DIR0_ALLEMPTY /* This entry and all following are empty */ +# define LDIR0_E5 DIR0_E5 /* The actual value is 0xe5 */ +# define LDIR0_LAST 0x40 /* Last LFN in file name (appears first) */ +# define LDIR0_SEQ_MASK 0x1f /* Mask for sequence number (1-20) */ + +/* The LFN entry attribute */ + +# define LDDIR_LFNATTR 0x0f +#endif + +/**************************************************************************** + * File system types */ + +#define FSTYPE_FAT12 0 +#define FSTYPE_FAT16 1 +#define FSTYPE_FAT32 2 + +/* File buffer flags (ff_bflags) */ + +#define FFBUFF_VALID 1 +#define FFBUFF_DIRTY 2 +#define FFBUFF_MODIFIED 4 + +/* Mount status flags (ff_bflags) */ + +#define UMOUNT_FORCED 8 + +/**************************************************************************** + * These offset describe the FSINFO sector + */ + +#define FSI_LEADSIG 0 /* 4@0: 0x41615252 = "RRaA" */ + /* 480@4: Reserved (zero) */ +#define FSI_STRUCTSIG 484 /* 4@484: 0x61417272 = "rrAa" */ +#define FSI_FREECOUNT 488 /* 4@488: Last free cluster count on volume */ +#define FSI_NXTFREE 492 /* 4@492: Cluster number of 1st free cluster */ + /* 12@496: Reserved (zero) */ +#define FSI_TRAILSIG 508 /* 4@508: 0xaa550000 */ + +/**************************************************************************** + * FAT values + */ + +#define FAT_EOF 0x0ffffff8 +#define FAT_BAD 0x0ffffff7 + +/**************************************************************************** + * Maximum cluster by FAT type. This is the key value used to distinquish + * between FAT12, 16, and 32. + */ + +/* FAT12: For M$, the calculation is ((1 << 12) - 19). But we will follow the + * Linux tradition of allowing slightly more clusters for FAT12. + */ + +#define FAT_MAXCLUST12 ((1 << 12) - 16) + +/* FAT16: For M$, the calculation is ((1 << 16) - 19). (The uint32_t cast is + * needed for architectures where int is only 16 bits). + */ + +#define FAT_MINCLUST16 (FAT_MAXCLUST12 + 1) +#define FAT_MAXCLUST16 (((uint32_t)1 << 16) - 16) + +/* FAT32: M$ reserves the MS 4 bits of a FAT32 FAT entry so only 18 bits are + * available. For M$, the calculation is ((1 << 28) - 19). (The uint32_t cast + * is needed for architectures where int is only 16 bits). M$ also claims + * that the minimum size is 65,527. + */ + +#define FAT_MINCLUST32 65524 +/* #define FAT_MINCLUST32 (FAT_MAXCLUST16 + 1) */ +#define FAT_MAXCLUST32 (((uint32_t)1 << 28) - 16) + +/**************************************************************************** + * Access to data in raw sector data */ + +#define UBYTE_VAL(p,o) (((uint8_t*)(p))[o]) +#define UBYTE_PTR(p,o) &UBYTE_VAL(p,o) +#define UBYTE_PUT(p,o,v) (UBYTE_VAL(p,o)=(uint8_t)(v)) + +#define UINT16_PTR(p,o) ((uint16_t*)UBYTE_PTR(p,o)) +#define UINT16_VAL(p,o) (*UINT16_PTR(p,o)) +#define UINT16_PUT(p,o,v) (UINT16_VAL(p,o)=(uint16_t)(v)) + +#define UINT32_PTR(p,o) ((uint32_t*)UBYTE_PTR(p,o)) +#define UINT32_VAL(p,o) (*UINT32_PTR(p,o)) +#define UINT32_PUT(p,o,v) (UINT32_VAL(p,o)=(uint32_t)(v)) + +/* Regardless of the endian-ness of the target or alignment of the data, no + * special operations are required for byte, string or byte array accesses. + * The FAT data stream is little endian so multiple byte values must be + * accessed byte-by-byte for big-endian targets. + */ + +#define MBR_GETSECPERCLUS(p) UBYTE_VAL(p,BS_SECPERCLUS) +#define MBR_GETNUMFATS(p) UBYTE_VAL(p,BS_NUMFATS) +#define MBR_GETMEDIA(p) UBYTE_VAL(p,BS_MEDIA) +#define MBR_GETDRVNUM16(p) UBYTE_VAL(p,BS16_DRVNUM) +#define MBR_GETDRVNUM32(p) UBYTE_VAL(p,BS32_DRVNUM) +#define MBR_GETBOOTSIG16(p) UBYTE_VAL(p,BS16_BOOTSIG) +#define MBR_GETBOOTSIG32(p) UBYTE_VAL(p,BS32_BOOTSIG) + +#define PART_GETTYPE(n,p) UBYTE_VAL(p,PART_ENTRY(n)+PART_TYPE) +#define PART1_GETTYPE(p) UBYTE_VAL(p,PART_ENTRY1+PART_TYPE) +#define PART2_GETTYPE(p) UBYTE_VAL(p,PART_ENTRY2+PART_TYPE) +#define PART3_GETTYPE(p) UBYTE_VAL(p,PART_ENTRY3+PART_TYPE) +#define PART4_GETTYPE(p) UBYTE_VAL(p,PART_ENTRY4+PART_TYPE) + +#define DIR_GETATTRIBUTES(p) UBYTE_VAL(p,DIR_ATTRIBUTES) +#define DIR_GETNTRES(p) UBYTE_VAL(p,DIR_NTRES) +#define DIR_GETCRTTIMETENTH(p) UBYTE_VAL(p,DIR_CRTTIMETENTH) + +#ifdef CONFIG_FAT_LFN +# define LDIR_GETSEQ(p) UBYTE_VAL(p,LDIR_SEQ) +# define LDIR_GETATTRIBUTES(p) UBYTE_VAL(p,LDIR_ATTRIBUTES) +# define LDIR_GETNTRES(p) UBYTE_VAL(p,LDIR_NTRES) +# define LDIR_GETCHECKSUM(p) UBYTE_VAL(p,LDIR_CHECKSUM) +#endif + +#define MBR_PUTSECPERCLUS(p,v) UBYTE_PUT(p,BS_SECPERCLUS,v) +#define MBR_PUTNUMFATS(p,v) UBYTE_PUT(p,BS_NUMFATS,v) +#define MBR_PUTMEDIA(p,v) UBYTE_PUT(p,BS_MEDIA,v) +#define MBR_PUTDRVNUM16(p,v) UBYTE_PUT(p,BS16_DRVNUM,v) +#define MBR_PUTDRVNUM32(p,v) UBYTE_PUT(p,BS32_DRVNUM,v) +#define MBR_PUTBOOTSIG16(p,v) UBYTE_PUT(p,BS16_BOOTSIG,v) +#define MBR_PUTBOOTSIG32(p,v) UBYTE_PUT(p,BS32_BOOTSIG,v) + +#define PART_PUTTYPE(n,p,v) UBYTE_PUT(p,PART_ENTRY(n)+PART_TYPE,v) +#define PART1_PUTTYPE(p,v) UBYTE_PUT(p,PART_ENTRY1+PART_TYPE,v) +#define PART2_PUTTYPE(p,v) UBYTE_PUT(p,PART_ENTRY2+PART_TYPE,v) +#define PART3_PUTTYPE(p,v) UBYTE_PUT(p,PART_ENTRY3+PART_TYPE,v) +#define PART4_PUTTYPE(p,v) UBYTE_PUT(p,PART_ENTRY4+PART_TYPE,v) + +#define DIR_PUTATTRIBUTES(p,v) UBYTE_PUT(p,DIR_ATTRIBUTES,v) +#define DIR_PUTNTRES(p,v) UBYTE_PUT(p,DIR_NTRES,v) +#define DIR_PUTCRTTIMETENTH(p,v) UBYTE_PUT(p,DIR_CRTTIMETENTH,v) + +#ifdef CONFIG_FAT_LFN +# define LDIR_PUTSEQ(p,v) UBYTE_PUT(p,LDIR_SEQ,v) +# define LDIR_PUTATTRIBUTES(p,v) UBYTE_PUT(p,LDIR_ATTRIBUTES,v) +# define LDIR_PUTNTRES(p,v) UBYTE_PUT(p,LDIR_NTRES,v) +# define LDIR_PUTCHECKSUM(p,v) UBYTE_PUT(p,LDIR_CHECKSUM,v) +#endif + +/* For the all targets, unaligned values need to be accessed byte-by-byte. + * Some architectures may handle unaligned accesses with special interrupt + * handlers. But even in that case, it is more efficient to avoid the traps. + */ + +/* Unaligned multi-byte access macros */ + +#define MBR_GETBYTESPERSEC(p) fat_getuint16(UBYTE_PTR(p,BS_BYTESPERSEC)) +#define MBR_GETROOTENTCNT(p) fat_getuint16(UBYTE_PTR(p,BS_ROOTENTCNT)) +#define MBR_GETTOTSEC16(p) fat_getuint16(UBYTE_PTR(p,BS_TOTSEC16)) +#define MBR_GETVOLID16(p) fat_getuint32(UBYTE_PTR(p,BS16_VOLID)) +#define MBR_GETVOLID32(p) fat_getuint32(UBYTE_PTR(p,BS32_VOLID)) + +#define PART_GETSTARTSECTOR(n,p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY(n)+PART_STARTSECTOR)) +#define PART_GETSIZE(n,p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY(n)+PART_SIZE)) +#define PART1_GETSTARTSECTOR(p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY1+PART_STARTSECTOR)) +#define PART1_GETSIZE(p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY1+PART_SIZE)) +#define PART2_GETSTARTSECTOR(p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY2+PART_STARTSECTOR)) +#define PART2_GETSIZE(p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY2+PART_SIZE)) +#define PART3_GETSTARTSECTOR(p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY3+PART_STARTSECTOR)) +#define PART3_GETSIZE(p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY3+PART_SIZE)) +#define PART4_GETSTARTSECTOR(p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY4+PART_STARTSECTOR)) +#define PART4_GETSIZE(p) fat_getuint32(UBYTE_PTR(p,PART_ENTRY4+PART_SIZE)) + +#define MBR_PUTBYTESPERSEC(p,v) fat_putuint16(UBYTE_PTR(p,BS_BYTESPERSEC),v) +#define MBR_PUTROOTENTCNT(p,v) fat_putuint16(UBYTE_PTR(p,BS_ROOTENTCNT),v) +#define MBR_PUTTOTSEC16(p,v) fat_putuint16(UBYTE_PTR(p,BS_TOTSEC16),v) +#define MBR_PUTVOLID16(p,v) fat_putuint32(UBYTE_PTR(p,BS16_VOLID),v) +#define MBR_PUTVOLID32(p,v) fat_putuint32(UBYTE_PTR(p,BS32_VOLID),v) + +#define PART_PUTSTARTSECTOR(n,p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY(n)+PART_STARTSECTOR),v) +#define PART_PUTSIZE(n,p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY(n)+PART_SIZE),v) +#define PART1_PUTSTARTSECTOR(p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY1+PART_STARTSECTOR),v) +#define PART1_PUTSIZE(p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY1+PART_SIZE),v) +#define PART2_PUTSTARTSECTOR(p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY2+PART_STARTSECTOR),v) +#define PART2_PUTSIZE(p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY2+PART_SIZE),v) +#define PART3_PUTSTARTSECTOR(p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY3+PART_STARTSECTOR),v) +#define PART3_PUTSIZE(p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY3+PART_SIZE),v) +#define PART4_PUTSTARTSECTOR(p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY4+PART_STARTSECTOR),v) +#define PART4_PUTSIZE(p,v) fat_putuint32(UBYTE_PTR(p,PART_ENTRY4+PART_SIZE),v) + +#ifdef CONFIG_FAT_LFN +# define LDIR_PTRWCHAR1_5(p) UBYTE_PTR(p,LDIR_WCHAR1_5) +# define LDIR_PTRWCHAR6_11(p) UBYTE_PTR(p,LDIR_WCHAR6_11) +# define LDIR_PTRWCHAR12_13(p) UBYTE_PTR(p,LDIR_WCHAR12_13) +#endif + +/* But for multi-byte values, the endian-ness of the target vs. the little + * endian order of the byte stream or alignment of the data within the byte + * stream can force special, byte-by-byte accesses. + */ + +#ifdef CONFIG_ENDIAN_BIG + +/* If the target is big-endian, then even aligned multi-byte values must be + * accessed byte-by-byte. + */ + +# define MBR_GETRESVDSECCOUNT(p) fat_getuint16(UBYTE_PTR(p,BS_RESVDSECCOUNT)) +# define MBR_GETFATSZ16(p) fat_getuint16(UBYTE_PTR(p,BS_FATSZ16)) +# define MBR_GETSECPERTRK(p) fat_getuint16(UBYTE_PTR(p,BS_SECPERTRK)) +# define MBR_GETNUMHEADS(p) fat_getuint16(UBYTE_PTR(p,BS_NUMHEADS)) +# define MBR_GETHIDSEC(p) fat_getuint32(UBYTE_PTR(p,BS_HIDSEC)) +# define MBR_GETTOTSEC32(p) fat_getuint32(UBYTE_PTR(p,BS_TOTSEC32)) +# define MBR_GETFATSZ32(p) fat_getuint32(UBYTE_PTR(p,BS32_FATSZ32)) +# define MBR_GETEXTFLAGS(p) fat_getuint16(UBYTE_PTR(p,BS32_EXTFLAGS)) +# define MBR_GETFSVER(p) fat_getuint16(UBYTE_PTR(p,BS32_FSVER)) +# define MBR_GETROOTCLUS(p) fat_getuint32(UBYTE_PTR(p,BS32_ROOTCLUS)) +# define MBR_GETFSINFO(p) fat_getuint16(UBYTE_PTR(p,BS32_FSINFO)) +# define MBR_GETBKBOOTSEC(p) fat_getuint16(UBYTE_PTR(p,BS32_BKBOOTSEC)) +# define MBR_GETSIGNATURE(p) fat_getuint16(UBYTE_PTR(p,BS_SIGNATURE)) + +# define FSI_GETLEADSIG(p) fat_getuint32(UBYTE_PTR(p,FSI_LEADSIG)) +# define FSI_GETSTRUCTSIG(p) fat_getuint32(UBYTE_PTR(p,FSI_STRUCTSIG)) +# define FSI_GETFREECOUNT(p) fat_getuint32(UBYTE_PTR(p,FSI_FREECOUNT)) +# define FSI_GETNXTFREE(p) fat_getuint32(UBYTE_PTR(p,FSI_NXTFREE)) +# define FSI_GETTRAILSIG(p) fat_getuint32(UBYTE_PTR(p,FSI_TRAILSIG)) + +# define DIR_GETCRTIME(p) fat_getuint16(UBYTE_PTR(p,DIR_CRTIME)) +# define DIR_GETCRDATE(p) fat_getuint16(UBYTE_PTR(p,DIR_CRDATE)) +# define DIR_GETLASTACCDATE(p) fat_getuint16(UBYTE_PTR(p,DIR_LASTACCDATE)) +# define DIR_GETFSTCLUSTHI(p) fat_getuint16(UBYTE_PTR(p,DIR_FSTCLUSTHI)) +# define DIR_GETWRTTIME(p) fat_getuint16(UBYTE_PTR(p,DIR_WRTTIME)) +# define DIR_GETWRTDATE(p) fat_getuint16(UBYTE_PTR(p,DIR_WRTDATE)) +# define DIR_GETFSTCLUSTLO(p) fat_getuint16(UBYTE_PTR(p,DIR_FSTCLUSTLO)) +# define DIR_GETFILESIZE(p) fat_getuint32(UBYTE_PTR(p,DIR_FILESIZE)) + +# ifdef CONFIG_FAT_LFN +# define LDIR_GETWCHAR1(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR1_5)) +# define LDIR_GETWCHAR2(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR1_5+2)) +# define LDIR_GETWCHAR3(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR1_5+4)) +# define LDIR_GETWCHAR4(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR1_5+6)) +# define LDIR_GETWCHAR5(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR1_5+8)) +# define LDIR_GETWCHAR6(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR6_11)) +# define LDIR_GETWCHAR7(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+2)) +# define LDIR_GETWCHAR8(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+4)) +# define LDIR_GETWCHAR9(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+6)) +# define LDIR_GETWCHAR10(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+8)) +# define LDIR_GETWCHAR11(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+10)) +# define LDIR_GETWCHAR12(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR12_13)) +# define LDIR_GETWCHAR13(p) fat_getuint16(UBYTE_PTR(p,LDIR_WCHAR12_13+2)) +# define LDIR_GETFSTCLUSTLO(p) fat_getuint16(UBYTE_PTR(p,LDIR_FSTCLUSTLO)) +# endif + +# define FSI_GETLEADSIG(p) fat_getuint32(UBYTE_PTR(p,FSI_LEADSIG)) +# define FSI_GETSTRUCTSIG(p) fat_getuint32(UBYTE_PTR(p,FSI_STRUCTSIG)) +# define FSI_GETFREECOUNT(p) fat_getuint32(UBYTE_PTR(p,FSI_FREECOUNT)) +# define FSI_GETNXTFREE(p) fat_getuint32(UBYTE_PTR(p,FSI_NXTFREE)) +# define FSI_GETTRAILSIG(p) fat_getuint32(UBYTE_PTR(p,FSI_TRAILSIG)) + +# define FAT_GETFAT16(p,i) fat_getuint16(UBYTE_PTR(p,i)) +# define FAT_GETFAT32(p,i) fat_getuint32(UBYTE_PTR(p,i)) + +# define MBR_PUTRESVDSECCOUNT(p,v) fat_putuint16(UBYTE_PTR(p,BS_RESVDSECCOUNT),v) +# define MBR_PUTFATSZ16(p,v) fat_putuint16(UBYTE_PTR(p,BS_FATSZ16),v) +# define MBR_PUTSECPERTRK(p,v) fat_putuint16(UBYTE_PTR(p,BS_SECPERTRK),v) +# define MBR_PUTNUMHEADS(p,v) fat_putuint16(UBYTE_PTR(p,BS_NUMHEADS),v) +# define MBR_PUTHIDSEC(p,v) fat_putuint32(UBYTE_PTR(p,BS_HIDSEC),v) +# define MBR_PUTTOTSEC32(p,v) fat_putuint32(UBYTE_PTR(p,BS_TOTSEC32),v) +# define MBR_PUTFATSZ32(p,v) fat_putuint32(UBYTE_PTR(p,BS32_FATSZ32),v) +# define MBR_PUTEXTFLAGS(p,v) fat_putuint16(UBYTE_PTR(p,BS32_EXTFLAGS),v) +# define MBR_PUTFSVER(p,v) fat_putuint16(UBYTE_PTR(p,BS32_FSVER),v) +# define MBR_PUTROOTCLUS(p,v) fat_putuint32(UBYTE_PTR(p,BS32_ROOTCLUS),v) +# define MBR_PUTFSINFO(p,v) fat_putuint16(UBYTE_PTR(p,BS32_FSINFO),v) +# define MBR_PUTBKBOOTSEC(p,v) fat_putuint16(UBYTE_PTR(p,BS32_BKBOOTSEC),v) +# define MBR_PUTSIGNATURE(p,v) fat_putuint16(UBYTE_PTR(p,BS_SIGNATURE),v) + +# define FSI_PUTLEADSIG(p,v) fat_putuint32(UBYTE_PTR(p,FSI_LEADSIG),v) +# define FSI_PUTSTRUCTSIG(p,v) fat_putuint32(UBYTE_PTR(p,FSI_STRUCTSIG),v) +# define FSI_PUTFREECOUNT(p,v) fat_putuint32(UBYTE_PTR(p,FSI_FREECOUNT),v) +# define FSI_PUTNXTFREE(p,v) fat_putuint32(UBYTE_PTR(p,FSI_NXTFREE),v) +# define FSI_PUTTRAILSIG(p,v) fat_putuint32(UBYTE_PTR(p,FSI_TRAILSIG),v) + +# define DIR_PUTCRTIME(p,v) fat_putuint16(UBYTE_PTR(p,DIR_CRTIME),v) +# define DIR_PUTCRDATE(p,v) fat_putuint16(UBYTE_PTR(p,DIR_CRDATE),v) +# define DIR_PUTLASTACCDATE(p,v) fat_putuint16(UBYTE_PTR(p,DIR_LASTACCDATE),v) +# define DIR_PUTFSTCLUSTHI(p,v) fat_putuint16(UBYTE_PTR(p,DIR_FSTCLUSTHI),v) +# define DIR_PUTWRTTIME(p,v) fat_putuint16(UBYTE_PTR(p,DIR_WRTTIME),v) +# define DIR_PUTWRTDATE(p,v) fat_putuint16(UBYTE_PTR(p,DIR_WRTDATE),v) +# define DIR_PUTFSTCLUSTLO(p,v) fat_putuint16(UBYTE_PTR(p,DIR_FSTCLUSTLO),v) +# define DIR_PUTFILESIZE(p,v) fat_putuint32(UBYTE_PTR(p,DIR_FILESIZE),v) + +# ifdef CONFIG_FAT_LFN +# define LDIR_PUTWCHAR1(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR1_5),v) +# define LDIR_PUTWCHAR2(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR1_5+2),v) +# define LDIR_PUTWCHAR3(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR1_5+4),v) +# define LDIR_PUTWCHAR4(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR1_5+6),v) +# define LDIR_PUTWCHAR5(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR1_5+8),v) +# define LDIR_PUTWCHAR6(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR6_11),v) +# define LDIR_PUTWCHAR7(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+2),v) +# define LDIR_PUTWCHAR8(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+4),v) +# define LDIR_PUTWCHAR9(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+6),v) +# define LDIR_PUTWCHAR10(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+8),v) +# define LDIR_PUTWCHAR11(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR6_11+10),v) +# define LDIR_PUTWCHAR12(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR12_13),v) +# define LDIR_PUTWCHAR13(p) fat_putuint16(UBYTE_PTR(p,LDIR_WCHAR12_13+2),v) +# endif + +# define FSI_PUTLEADSIG(p,v) fat_putuint32(UBYTE_PTR(p,FSI_LEADSIG),v) +# define FSI_PUTSTRUCTSIG(p,v) fat_putuint32(UBYTE_PTR(p,FSI_STRUCTSIG),v) +# define FSI_PUTFREECOUNT(p,v) fat_putuint32(UBYTE_PTR(p,FSI_FREECOUNT),v) +# define FSI_PUTNXTFREE(p,v) fat_putuint32(UBYTE_PTR(p,FSI_NXTFREE),v) +# define FSI_PUTTRAILSIG(p,v) fat_putuint32(UBYTE_PTR(p,FSI_TRAILSIG),v) + +# define FAT_PUTFAT16(p,i,v) fat_putuint16(UBYTE_PTR(p,i),v) +# define FAT_PUTFAT32(p,i,v) fat_putuint32(UBYTE_PTR(p,i),v) + +#else + +/* But nothing special has to be done for the little endian-case for access + * to aligned mulitbyte values. + */ + +# define MBR_GETRESVDSECCOUNT(p) UINT16_VAL(p,BS_RESVDSECCOUNT) +# define MBR_GETFATSZ16(p) UINT16_VAL(p,BS_FATSZ16) +# define MBR_GETSECPERTRK(p) UINT16_VAL(p,BS_SECPERTRK) +# define MBR_GETNUMHEADS(p) UINT16_VAL(p,BS_NUMHEADS) +# define MBR_GETHIDSEC(p) UINT32_VAL(p,BS_HIDSEC) +# define MBR_GETTOTSEC32(p) UINT32_VAL(p,BS_TOTSEC32) +# define MBR_GETFATSZ32(p) UINT32_VAL(p,BS32_FATSZ32) +# define MBR_GETEXTFLAGS(p) UINT16_VAL(p,BS32_EXTFLAGS) +# define MBR_GETFSVER(p) UINT16_VAL(p,BS32_FSVER) +# define MBR_GETROOTCLUS(p) UINT32_VAL(p,BS32_ROOTCLUS) +# define MBR_GETFSINFO(p) UINT16_VAL(p,BS32_FSINFO) +# define MBR_GETBKBOOTSEC(p) UINT16_VAL(p,BS32_BKBOOTSEC) +# define MBR_GETSIGNATURE(p) UINT16_VAL(p,BS_SIGNATURE) + +# define FSI_GETLEADSIG(p) UINT32_VAL(p,FSI_LEADSIG) +# define FSI_GETSTRUCTSIG(p) UINT32_VAL(p,FSI_STRUCTSIG) +# define FSI_GETFREECOUNT(p) UINT32_VAL(p,FSI_FREECOUNT) +# define FSI_GETNXTFREE(p) UINT32_VAL(p,FSI_NXTFREE) +# define FSI_GETTRAILSIG(p) UINT32_VAL(p,FSI_TRAILSIG) + +# define DIR_GETCRTIME(p) UINT16_VAL(p,DIR_CRTIME) +# define DIR_GETCRDATE(p) UINT16_VAL(p,DIR_CRDATE) +# define DIR_GETLASTACCDATE(p) UINT16_VAL(p,DIR_LASTACCDATE) +# define DIR_GETFSTCLUSTHI(p) UINT16_VAL(p,DIR_FSTCLUSTHI) +# define DIR_GETWRTTIME(p) UINT16_VAL(p,DIR_WRTTIME) +# define DIR_GETWRTDATE(p) UINT16_VAL(p,DIR_WRTDATE) +# define DIR_GETFSTCLUSTLO(p) UINT16_VAL(p,DIR_FSTCLUSTLO) +# define DIR_GETFILESIZE(p) UINT32_VAL(p,DIR_FILESIZE) + +# ifdef CONFIG_FAT_LFN +# define LDIR_GETWCHAR1(p) UINT16_VAL(p,LDIR_WCHAR1_5) +# define LDIR_GETWCHAR2(p) UINT16_VAL(p,LDIR_WCHAR1_5+2) +# define LDIR_GETWCHAR3(p) UINT16_VAL(p,LDIR_WCHAR1_5+4) +# define LDIR_GETWCHAR4(p) UINT16_VAL(p,LDIR_WCHAR1_5+6) +# define LDIR_GETWCHAR5(p) UINT16_VAL(p,LDIR_WCHAR1_5+8) +# define LDIR_GETWCHAR6(p) UINT16_VAL(p,LDIR_WCHAR6_11) +# define LDIR_GETWCHAR7(p) UINT16_VAL(p,LDIR_WCHAR6_11+2) +# define LDIR_GETWCHAR8(p) UINT16_VAL(p,LDIR_WCHAR6_11+4) +# define LDIR_GETWCHAR9(p) UINT16_VAL(p,LDIR_WCHAR6_11+6) +# define LDIR_GETWCHAR10(p) UINT16_VAL(p,LDIR_WCHAR6_11+8) +# define LDIR_GETWCHAR11(p) UINT16_VAL(p,LDIR_WCHAR6_11+10) +# define LDIR_GETWCHAR12(p) UINT16_VAL(p,LDIR_WCHAR12_13) +# define LDIR_GETWCHAR13(p) UINT16_VAL(p,LDIR_WCHAR12_13+2) +# endif + +# define FSI_GETLEADSIG(p) UINT32_VAL(p,FSI_LEADSIG) +# define FSI_GETSTRUCTSIG(p) UINT32_VAL(p,FSI_STRUCTSIG) +# define FSI_GETFREECOUNT(p) UINT32_VAL(p,FSI_FREECOUNT) +# define FSI_GETNXTFREE(p) UINT32_VAL(p,FSI_NXTFREE) +# define FSI_GETTRAILSIG(p) UINT32_VAL(p,FSI_TRAILSIG) + +# define FAT_GETFAT16(p,i) UINT16_VAL(p,i) +# define FAT_GETFAT32(p,i) UINT32_VAL(p,i) + +# define MBR_PUTRESVDSECCOUNT(p,v) UINT16_PUT(p,BS_RESVDSECCOUNT,v) +# define MBR_PUTFATSZ16(p,v) UINT16_PUT(p,BS_FATSZ16,v) +# define MBR_PUTSECPERTRK(p,v) UINT16_PUT(p,BS_SECPERTRK,v) +# define MBR_PUTNUMHEADS(p,v) UINT16_PUT(p,BS_NUMHEADS,v) +# define MBR_PUTHIDSEC(p,v) UINT32_PUT(p,BS_HIDSEC,v) +# define MBR_PUTTOTSEC32(p,v) UINT32_PUT(p,BS_TOTSEC32,v) +# define MBR_PUTFATSZ32(p,v) UINT32_PUT(p,BS32_FATSZ32,v) +# define MBR_PUTEXTFLAGS(p,v) UINT16_PUT(p,BS32_EXTFLAGS,v) +# define MBR_PUTFSVER(p,v) UINT16_PUT(p,BS32_FSVER,v) +# define MBR_PUTROOTCLUS(p,v) UINT32_PUT(p,BS32_ROOTCLUS,v) +# define MBR_PUTFSINFO(p,v) UINT16_PUT(p,BS32_FSINFO,v) +# define MBR_PUTBKBOOTSEC(p,v) UINT16_PUT(p,BS32_BKBOOTSEC,v) +# define MBR_PUTSIGNATURE(p,v) UINT16_PUT(p,BS_SIGNATURE,v) + +# define FSI_PUTLEADSIG(p,v) UINT32_PUT(p,FSI_LEADSIG,v) +# define FSI_PUTSTRUCTSIG(p,v) UINT32_PUT(p,FSI_STRUCTSIG,v) +# define FSI_PUTFREECOUNT(p,v) UINT32_PUT(p,FSI_FREECOUNT,v) +# define FSI_PUTNXTFREE(p,v) UINT32_PUT(p,FSI_NXTFREE,v) +# define FSI_PUTTRAILSIG(p,v) UINT32_PUT(p,FSI_TRAILSIG,v) + +# define DIR_PUTCRTIME(p,v) UINT16_PUT(p,DIR_CRTIME,v) +# define DIR_PUTCRDATE(p,v) UINT16_PUT(p,DIR_CRDATE,v) +# define DIR_PUTLASTACCDATE(p,v) UINT16_PUT(p,DIR_LASTACCDATE,v) +# define DIR_PUTFSTCLUSTHI(p,v) UINT16_PUT(p,DIR_FSTCLUSTHI,v) +# define DIR_PUTWRTTIME(p,v) UINT16_PUT(p,DIR_WRTTIME,v) +# define DIR_PUTWRTDATE(p,v) UINT16_PUT(p,DIR_WRTDATE,v) +# define DIR_PUTFSTCLUSTLO(p,v) UINT16_PUT(p,DIR_FSTCLUSTLO,v) +# define DIR_PUTFILESIZE(p,v) UINT32_PUT(p,DIR_FILESIZE,v) + +# ifdef CONFIG_FAT_LFN +# define LDIR_PUTWCHAR1(p,v) UINT16_PUT(p,LDIR_WCHAR1_5,v) +# define LDIR_PUTWCHAR2(p,v) UINT16_PUT(p,LDIR_WCHAR1_5+2,v) +# define LDIR_PUTWCHAR3(p,v) UINT16_PUT(p,LDIR_WCHAR1_5+4,v) +# define LDIR_PUTWCHAR4(p,v) UINT16_PUT(p,LDIR_WCHAR1_5+6,v) +# define LDIR_PUTWCHAR5(p,v) UINT16_PUT(p,LDIR_WCHAR1_5+8,v) +# define LDIR_PUTWCHAR6(p,v) UINT16_PUT(p,LDIR_WCHAR6_11,v) +# define LDIR_PUTWCHAR7(p,v) UINT16_PUT(p,LDIR_WCHAR6_11+2,v) +# define LDIR_PUTWCHAR8(p,v) UINT16_PUT(p,LDIR_WCHAR6_11+4,v) +# define LDIR_PUTWCHAR9(p,v) UINT16_PUT(p,LDIR_WCHAR6_11+6,v) +# define LDIR_PUTWCHAR10(p,v) UINT16_PUT(p,LDIR_WCHAR6_11+8,v) +# define LDIR_PUTWCHAR11(p,v) UINT16_PUT(p,LDIR_WCHAR6_11+10,v) +# define LDIR_PUTWCHAR12(p,v) UINT16_PUT(p,LDIR_WCHAR12_13,v) +# define LDIR_PUTWCHAR13(p,v) UINT16_PUT(p,LDIR_WCHAR12_13+2,v) +# endif + +# define FSI_PUTLEADSIG(p,v) UINT32_PUT(p,FSI_LEADSIG,v) +# define FSI_PUTSTRUCTSIG(p,v) UINT32_PUT(p,FSI_STRUCTSIG,v) +# define FSI_PUTFREECOUNT(p,v) UINT32_PUT(p,FSI_FREECOUNT,v) +# define FSI_PUTNXTFREE(p,v) UINT32_PUT(p,FSI_NXTFREE,v) +# define FSI_PUTTRAILSIG(p,v) UINT32_PUT(p,FSI_TRAILSIG,v) + +# define FAT_PUTFAT16(p,i,v) UINT16_PUT(p,i,v) +# define FAT_PUTFAT32(p,i,v) UINT32_PUT(p,i,v) + +#endif + +/**************************************************************************** + * Name: fat_io_alloc and fat_io_free + * + * Description: + * The FAT file system allocates two I/O buffers for data transfer, each + * are the size of one device sector. One of the buffers is allocated + * once for each FAT volume that is mounted; the other buffers are + * allocated each time a FAT file is opened. + * + * Some hardware, however, may require special DMA-capable memory in + * order to perform the transfers. If CONFIG_FAT_DMAMEMORY is defined + * then the architecture-specific hardware must provide the funtions + * fat_dma_alloc() and fat_dma_free() as prototyped below: fat_dmalloc() + * will allocate DMA-capable memory of the specified size; fat_dmafree() + * is the corresponding function that will be called to free the DMA- + * capable memory. + * + ****************************************************************************/ + +#ifdef CONFIG_FAT_DMAMEMORY +# define fat_io_alloc(s) fat_dma_alloc(s) +# define fat_io_free(m,s) fat_dma_free(m,s) +#else +# define fat_io_alloc(s) kmm_malloc(s) +# define fat_io_free(m,s) kmm_free(m) +#endif + +/**************************************************************************** + * Public Types + ****************************************************************************/ + +/* This structure represents the overall mountpoint state. An instance of this + * structure is retained as inode private data on each mountpoint that is + * mounted with a fat32 filesystem. + */ + +struct fat_file_s; +struct fat_mountpt_s +{ + struct inode *fs_blkdriver; /* The block driver inode that hosts the FAT32 fs */ + struct fat_file_s *fs_head; /* A list to all files opened on this mountpoint */ + + sem_t fs_sem; /* Used to assume thread-safe access */ + off_t fs_hwsectorsize; /* HW: Sector size reported by block driver*/ + off_t fs_hwnsectors; /* HW: The number of sectors reported by the hardware */ + off_t fs_fatbase; /* Logical block of start of filesystem (past resd sectors) */ + off_t fs_rootbase; /* MBR: Cluster no. of 1st cluster of root dir */ + off_t fs_database; /* Logical block of start data sectors */ + off_t fs_fsinfo; /* MBR: Sector number of FSINFO sector */ + off_t fs_currentsector; /* The sector number buffered in fs_buffer */ + uint32_t fs_nclusters; /* Maximum number of data clusters */ + uint32_t fs_nfatsects; /* MBR: Count of sectors occupied by one fat */ + uint32_t fs_fattotsec; /* MBR: Total count of sectors on the volume */ + uint32_t fs_fsifreecount; /* FSI: Last free cluster count on volume */ + uint32_t fs_fsinextfree; /* FSI: Cluster number of 1st free cluster */ + uint16_t fs_fatresvdseccount; /* MBR: The total number of reserved sectors */ + uint16_t fs_rootentcnt; /* MBR: Count of 32-bit root directory entries */ + bool fs_mounted; /* true: The file system is ready */ + bool fs_dirty; /* true: fs_buffer is dirty */ + bool fs_fsidirty; /* true: FSINFO sector must be written to disk */ + uint8_t fs_type; /* FSTYPE_FAT12, FSTYPE_FAT16, or FSTYPE_FAT32 */ + uint8_t fs_fatnumfats; /* MBR: Number of FATs (probably 2) */ + uint8_t fs_fatsecperclus; /* MBR: Sectors per allocation unit: 2**n, n=0..7 */ + uint8_t *fs_buffer; /* This is an allocated buffer to hold one sector + * from the device */ +}; + +/* This structure represents on open file under the mountpoint. An instance + * of this structure is retained as struct file specific information on each + * opened file. + */ + +struct fat_file_s +{ + struct fat_file_s *ff_next; /* Retained in a singly linked list */ + uint8_t ff_bflags; /* The file buffer/mount flags */ + uint8_t ff_oflags; /* Flags provided when file was opened */ + uint8_t ff_sectorsincluster; /* Sectors remaining in cluster */ + uint16_t ff_dirindex; /* Index into ff_dirsector to directory entry */ + uint32_t ff_currentcluster; /* Current cluster being accessed */ + off_t ff_dirsector; /* Sector containing the directory entry */ + off_t ff_size; /* Size of the file in bytes */ + off_t ff_startcluster; /* Start cluster of file on media */ + off_t ff_currentsector; /* Current sector being operated on */ + off_t ff_cachesector; /* Current sector in the file buffer */ + uint8_t *ff_buffer; /* File buffer (for partial sector accesses) */ +}; + +/* This structure holds the sequence of directory entries used by one + * file element (directory or file). For short file names, this is + * single diretory entry. But for long file names, the is a sequence + * of directory entries. Long directory name entries appear in reverse + * order: Last, next-to-last, ..., first. The "first" long file name + * directory is then following by the short directory name entry. The + * short file name entry contains the real meat of the file data. + * + * So it takes the sector number and entry offset of the last long + * file name entry and of the short file name entry to define the + * sequence. In the case of short file names, the sector number and + * offset will be the same. + */ + +struct fat_dirseq_s +{ + /* Sector offsets */ + + uint16_t ds_offset; /* Sector offset to short file name entry */ +#ifdef CONFIG_FAT_LFN + uint16_t ds_lfnoffset; /* Sector offset to last long file name entry */ +#endif + + /* Sector and cluster numbers */ + + off_t ds_sector; /* Sector of the short file name entry */ +#ifdef CONFIG_FAT_LFN + off_t ds_cluster; /* Cluster containing the short file name entry */ + off_t ds_lfnsector; /* Sector of the last long name entry */ + off_t ds_lfncluster; /* Cluster containing the long file name entry */ + off_t ds_startsector; /* Starting sector of the directory */ +#endif +}; + +/* This structure is used internally for describing directory entries */ + +struct fat_dirinfo_s +{ + /* The file/directory name */ + +#ifdef CONFIG_FAT_LFN + uint8_t fd_lfname[LDIR_MAXFNAME+1]; /* Long filename with terminator */ +#endif + uint8_t fd_name[DIR_MAXFNAME]; /* Short 8.3 alias filename (no terminator) */ + + /* NT flags are not used */ + +#ifdef CONFIG_FAT_LCNAMES + uint8_t fd_ntflags; /* NTRes lower case flags */ +#endif + + /* TRUE if this is the root directory */ + + bool fd_root; + + /* The following provides the sequence of directory entries used by the + * file or directory. + */ + + struct fat_dirseq_s fd_seq; /* Directory sequence */ + + /* This is part of the opendir, readdir, ... logic */ + + struct fs_fatdir_s dir; /* Used with opendir, readdir, etc. */ +}; + +/* Generic helper macros ****************************************************/ + +#ifndef MIN +# define MIN(a,b) (a < b ? a : b) +#endif + +#ifndef MAX +# define MAX(a,b) (a > b ? a : b) +#endif + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +#undef EXTERN +#if defined(__cplusplus) +#define EXTERN extern "C" +extern "C" { +#else +#define EXTERN extern +#endif + +/* Utitilies to handle unaligned or byte swapped accesses */ + +EXTERN uint16_t fat_getuint16(uint8_t *ptr); +EXTERN uint32_t fat_getuint32(uint8_t *ptr); +EXTERN void fat_putuint16(uint8_t *ptr, uint16_t value16); +EXTERN void fat_putuint32(uint8_t *ptr, uint32_t value32); + +/* Manage the per-mount semaphore that protects access to shared resources */ + +EXTERN void fat_semtake(struct fat_mountpt_s *fs); +EXTERN void fat_semgive(struct fat_mountpt_s *fs); + +/* Get the current time for FAT creation and write times */ + +EXTERN uint32_t fat_systime2fattime(void); +EXTERN time_t fat_fattime2systime(uint16_t fattime, uint16_t fatdate); + +/* Handle hardware interactions for mounting */ + +EXTERN int fat_mount(struct fat_mountpt_s *fs, bool writeable); +EXTERN int fat_checkmount(struct fat_mountpt_s *fs); + +/* low-level hardware access */ + +EXTERN int fat_hwread(struct fat_mountpt_s *fs, uint8_t *buffer, + off_t sector, unsigned int nsectors); +EXTERN int fat_hwwrite(struct fat_mountpt_s *fs, uint8_t *buffer, + off_t sector, unsigned int nsectors); + +/* Cluster / cluster chain access helpers */ + +EXTERN off_t fat_cluster2sector(struct fat_mountpt_s *fs, uint32_t cluster); +EXTERN off_t fat_getcluster(struct fat_mountpt_s *fs, uint32_t clusterno); +EXTERN int fat_putcluster(struct fat_mountpt_s *fs, uint32_t clusterno, + off_t startsector); +EXTERN int fat_removechain(struct fat_mountpt_s *fs, uint32_t cluster); +EXTERN int32_t fat_extendchain(struct fat_mountpt_s *fs, uint32_t cluster); + +#define fat_createchain(fs) fat_extendchain(fs, 0) + +/* Help for traversing directory trees and accessing directory entries */ + +EXTERN int fat_nextdirentry(struct fat_mountpt_s *fs, struct fs_fatdir_s *dir); +EXTERN int fat_finddirentry(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo, + const char *path); +EXTERN int fat_dirnamewrite(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo); +EXTERN int fat_dirwrite(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo, + uint8_t attributes, uint32_t fattime); +EXTERN int fat_allocatedirentry(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo); +EXTERN int fat_freedirentry(struct fat_mountpt_s *fs, struct fat_dirseq_s *seq); +EXTERN int fat_dirname2path(struct fat_mountpt_s *fs, struct fs_dirent_s *dir); + +/* File creation and removal helpers */ + +EXTERN int fat_dirtruncate(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo); +EXTERN int fat_dircreate(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo); +EXTERN int fat_remove(struct fat_mountpt_s *fs, const char *relpath, bool directory); + +/* Mountpoint and file buffer cache (for partial sector accesses) */ + +EXTERN int fat_fscacheflush(struct fat_mountpt_s *fs); +EXTERN int fat_fscacheread(struct fat_mountpt_s *fs, off_t sector); +EXTERN int fat_ffcacheflush(struct fat_mountpt_s *fs, struct fat_file_s *ff); +EXTERN int fat_ffcacheread(struct fat_mountpt_s *fs, struct fat_file_s *ff, off_t sector); +EXTERN int fat_ffcacheinvalidate(struct fat_mountpt_s *fs, struct fat_file_s *ff); + +/* FSINFO sector support */ + +EXTERN int fat_updatefsinfo(struct fat_mountpt_s *fs); +EXTERN int fat_nfreeclusters(struct fat_mountpt_s *fs, off_t *pfreeclusters); +EXTERN int fat_currentsector(struct fat_mountpt_s *fs, struct fat_file_s *ff, off_t position); + +#undef EXTERN +#if defined(__cplusplus) +} +#endif + +#endif /* __APPS_FSUTILS_MKFATFS_FAT32_H */ diff --git a/fsutils/mkfatfs/mkfatfs.c b/fsutils/mkfatfs/mkfatfs.c new file mode 100644 index 000000000..4d54dbcac --- /dev/null +++ b/fsutils/mkfatfs/mkfatfs.c @@ -0,0 +1,324 @@ +/**************************************************************************** + * apps/fsutils/mkfatfs/writefat.c + * + * Copyright (C) 2008-2009, 2013, 2017 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * + * 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 NuttX 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 OWNER 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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "fsutils/mkfatfs.h" +#include "fat32.h" +#include "mkfatfs.h" + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: mkfatfs_getgeometry + * + * Description: + * Get the sector size and number of sectors of the underlying block + * device. + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * + * Return: + * Zero on success; negated errno on failure + * + ****************************************************************************/ + +static inline int mkfatfs_getgeometry(FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var) +{ + struct geometry geometry; + int ret; + + /* Get the geometry of the underlying device */ + + ret = ioctl(var->fv_fd, BIOC_GEOMETRY, + (unsigned long)((uintptr_t)&geometry)); + if (ret < 0) + { + ferr("ERROR: geometry() returned %d\n", ret); + return ret; + } + + if (!geometry.geo_available || !geometry.geo_writeenabled) + { + ferr("ERROR: Media is not available\n", ret); + return -ENODEV; + } + + /* Check if the user provided maxblocks was provided and, if so, that is it less than + * the actual number of blocks on the device. + */ + + if (fmt->ff_nsectors != 0) + { + if (fmt->ff_nsectors > geometry.geo_nsectors) + { + ferr("ERROR: User maxblocks (%d) exceeds blocks on device (%d)\n", + fmt->ff_nsectors, geometry.geo_nsectors); + + return -EINVAL; + } + } + else + { + /* Use the actual number of blocks on the device */ + + fmt->ff_nsectors = geometry.geo_nsectors; + } + + /* Verify that we can handle this sector size */ + + var->fv_sectorsize = geometry.geo_sectorsize; + switch (var->fv_sectorsize) + { + case 512: + var->fv_sectshift = 9; + break; + + case 1024: + var->fv_sectshift = 10; + break; + + case 2048: + var->fv_sectshift = 11; + break; + + case 4096: + var->fv_sectshift = 12; + break; + + default: + ferr("ERROR: Unsupported sector size: %d\n", var->fv_sectorsize); + return -EPERM; + } + + return 0; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: mkfatfs + * + * Description: + * Make a FAT file system image on the specified block device. This + * function can automatically format a FAT12 or FAT16 file system. By + * tradition, FAT32 will only be selected is explicitly requested. + * + * Inputs: + * pathname - the full path to a registered block driver + * fmt - Describes characteristics of the desired filesystem + * + * Return: + * Zero (OK) on success; -1 (ERROR) on failure with errno set appropriately: + * + * EINVAL - NULL block driver string, bad number of FATS in 'fmt', bad FAT + * size in 'fmt', bad cluster size in 'fmt' + * ENOENT - 'pathname' does not refer to anything in the filesystem. + * ENOTBLK - 'pathname' does not refer to a block driver + * EACCES - block driver does not support wrie or geometry methods + * + * Assumptions: + * - The caller must assure that the block driver is not mounted and not in + * use when this function is called. The result of formatting a mounted + * device is indeterminate (but likely not good). + * + ****************************************************************************/ + +int mkfatfs(FAR const char *pathname, FAR struct fat_format_s *fmt) +{ + struct fat_var_s var; + int ret; + + /* Initialize */ + + memset(&var, 0, sizeof(struct fat_var_s)); + + /* Get the filesystem creation time */ + + var.fv_createtime = fat_systime2fattime(); + + /* Verify format options (only when DEBUG enabled) */ + +#ifdef CONFIG_DEBUG_FEATURES + if (!pathname) + { + ferr("ERROR: No block driver path\n"); + ret = -EINVAL; + goto errout; + } + + if (fmt->ff_nfats < 1 || fmt->ff_nfats > 4) + { + ferr("ERROR: Invalid number of fats: %d\n", fmt->ff_nfats); + ret = -EINVAL; + goto errout; + } + + if (fmt->ff_fattype != 0 && fmt->ff_fattype != 12 && + fmt->ff_fattype != 16 && fmt->ff_fattype != 32) + { + ferr("ERROR: Invalid FAT size: %d\n", fmt->ff_fattype); + ret = -EINVAL; + goto errout; + } +#endif + + /* 0 will auto-selected by FAT12 and FAT16 (only). Otherwise, + * fv_fattype will specify the exact format to use. + */ + + var.fv_fattype = fmt->ff_fattype; + + /* The valid range off ff_clustshift is {0,1,..7} corresponding to + * cluster sizes of {1,2,..128} sectors. The special value of 0xff + * means that we should autoselect the cluster sizel. + */ + +#ifdef CONFIG_DEBUG_FEATURES + if (fmt->ff_clustshift > 7 && fmt->ff_clustshift != 0xff) + { + ferr("ERROR: Invalid cluster shift value: %d\n", fmt->ff_clustshift); + + ret = -EINVAL; + goto errout; + } + + if (fmt->ff_rootdirentries != 0 && + (fmt->ff_rootdirentries < 16 || fmt->ff_rootdirentries > 32767)) + { + ferr("ERROR: Invalid number of root dir entries: %d\n", + fmt->ff_rootdirentries); + + ret = -EINVAL; + goto errout; + } + + if (fmt->ff_rsvdseccount != 0 && (fmt->ff_rsvdseccount < 1 || + fmt->ff_rsvdseccount > 32767)) + { + ferr("ERROR: Invalid number of reserved sectors: %d\n", + fmt->ff_rsvdseccount); + + ret = -EINVAL; + goto errout; + } +#endif + + /* Find the inode of the block driver indentified by 'source' */ + + var.fv_fd = open(pathname, O_RDWR); + if (var.fv_fd < 0) + { + ret = -errno; + ferr("ERROR: Failed to open %s: %d\n", pathname, ret); + goto errout; + } + + /* Determine the volume configuration based upon the input values and upon the + * reported device geometry. + */ + + ret = mkfatfs_getgeometry(fmt, &var); + if (ret < 0) + { + goto errout_with_driver; + } + + /* Configure the file system */ + + ret = mkfatfs_configfatfs(fmt, &var); + if (ret < 0) + { + goto errout_with_driver; + } + + /* Allocate a buffer that will be working sector memory */ + + var.fv_sect = (FAR uint8_t *)malloc(var.fv_sectorsize); + if (!var.fv_sect) + { + ferr("ERROR: Failed to allocate working buffers\n"); + goto errout_with_driver; + } + + /* Write the filesystem to media */ + + ret = mkfatfs_writefatfs(fmt, &var); + +errout_with_driver: + /* Close the driver */ + + (void)close(var.fv_fd); + +errout: + /* Release all allocated memory */ + + if (var.fv_sect) + { + free(var.fv_sect); + } + + /* Return any reported errors */ + + if (ret < 0) + { + set_errno(-ret); + return ERROR; + } + + return OK; +} diff --git a/fsutils/mkfatfs/writefat.c b/fsutils/mkfatfs/writefat.c new file mode 100644 index 000000000..202638c70 --- /dev/null +++ b/fsutils/mkfatfs/writefat.c @@ -0,0 +1,615 @@ +/**************************************************************************** + * apps/fsutils/mkfatfs/writefat.c + * + * Copyright (C) 2008-2009, 2011, 2017 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * + * 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 NuttX 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 OWNER 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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include +#include +#include + +#include + +#include "fsutils/mkfatfs.h" +#include "fat32.h" +#include "mkfatfs.h" + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: mkfatfs_devwrite + * + * Description: + * Write the content of the dedicate sector buffer beginning to the specified sector + * + * Input: + * fmt - User specified format parameters + * var - Other format parameters that are not user specifiable + * + * Return: + * None; caller is responsible for providing valid parameters. + * + ****************************************************************************/ + +static int mkfatfs_devwrite(FAR const struct fat_format_s *fmt, + FAR const struct fat_var_s *var, off_t sector) +{ + ssize_t nwritten; + off_t seekpos; + off_t fpos; + int ret; + + /* Convert the sector number to a byte offset */ + + if (sector < 0 || sector >= fmt->ff_nsectors) + { + ferr("sector out of range: %lu\n", (unsigned long)sector); + return -ESPIPE; + } + + fpos = sector << var->fv_sectshift; + + /* Seek to that offset */ + + seekpos = lseek(var->fv_fd, fpos, SEEK_SET); + if (seekpos == (off_t)-1) + { + ret = -errno; + ferr("ERROR: lseek to %lu failed: %d\n", (unsigned long)fpos, ret); + return ret; + } + else if (seekpos != fpos) + { + ferr("ERROR: lseek failed: %lu vs %lu\n", + (unsigned)seekpos, (unsigned long) fpos); + return -EINVAL; + } + + /* Write the sector to that offset. Partial writes are not expected. */ + + nwritten = write(var->fv_fd, var->fv_sect, var->fv_sectorsize); + if (nwritten < 0) + { + ret = -errno; + ferr("ERROR: write failed: size=%lu pos=%lu error=%d\n", + (unsigned)var->fv_sectorsize, (unsigned long)fpos, ret); + return ret; + } + else if (nwritten != (ssize_t)var->fv_sectorsize) + { + ferr("ERROR: Partial write: size=%lu written=%lu\n", + (unsigned)var->fv_sectorsize, (unsigned long)nwritten); + return -ENODATA; + } + + return OK; +} + +/**************************************************************************** + * Name: mkfatfs_initmbr + * + * Description: + * Initialize the sector image of a masterbood record + * + * Input: + * fmt - User specified format parameters + * var - Other format parameters that are not user specifiable + * + * Return: + * None; caller is responsible for providing valid parameters. + * + ****************************************************************************/ + +static inline void mkfatfs_initmbr(FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var) +{ + memset(var->fv_sect, 0, var->fv_sectorsize); + + /* 3@0: Jump instruction to boot code */ + + memcpy(&var->fv_sect[BS_JUMP], var->fv_jump, 3); + + /* 8@3: Usually "MSWIN4.1" */ + + strcpy((FAR char *)&var->fv_sect[BS_OEMNAME], "NUTTX "); + + /* 2@11: Bytes per sector: 512, 1024, 2048, 4096 */ + + MBR_PUTBYTESPERSEC(var->fv_sect, var->fv_sectorsize); + + /* 1@13: Sectors per allocation unit: 2**n, n=0..7 */ + + MBR_PUTSECPERCLUS(var->fv_sect, (1 << fmt->ff_clustshift)); + + /* 2@14: Reserved sector count: Usually 32 */ + + MBR_PUTRESVDSECCOUNT(var->fv_sect, fmt->ff_rsvdseccount); + + /* 1@16: Number of FAT data structures: always 2 */ + + MBR_PUTNUMFATS(var->fv_sect, fmt->ff_nfats); + + /* 2@17: FAT12/16: Must be 0 for FAT32 */ + + MBR_PUTROOTENTCNT(var->fv_sect, fmt->ff_rootdirentries); + + /* 2@19: FAT12/16: Must be 0, see BS_TOTSEC32. + * Handled with 4@32: Total count of sectors on the volume */ + + if (fmt->ff_nsectors >= 65536) + { + MBR_PUTTOTSEC32(var->fv_sect, fmt->ff_nsectors); + } + else + { + MBR_PUTTOTSEC16(var->fv_sect, (uint16_t)fmt->ff_nsectors); + } + + /* 1@21: Media code: f0, f8, f9-fa, fc-ff */ + + MBR_PUTMEDIA(var->fv_sect, FAT_DEFAULT_MEDIA_TYPE); /* Only "hard drive" supported */ + + /* 2@22: FAT12/16: Must be 0, see BS32_FATSZ32 -- handled in FAT specific logic */ + + /* 2@24: Sectors per track geometry value and 2@26: Number of heads geometry value */ + + MBR_PUTSECPERTRK(var->fv_sect, FAT_DEFAULT_SECPERTRK); + MBR_PUTNUMHEADS(var->fv_sect, FAT_DEFAULT_NUMHEADS); + + /* 4@28: Count of hidden sectors preceding FAT */ + + MBR_PUTHIDSEC(var->fv_sect, fmt->ff_hidsec); + + /* 4@32: Total count of sectors on the volume -- handled above */ + + /* Most of the rest of the sector depends on the FAT size */ + + if (fmt->ff_fattype != 32) + { + /* 2@22: FAT12/16: Must be 0, see BS32_FATSZ32 */ + + MBR_PUTFATSZ16(var->fv_sect, (uint16_t)var->fv_nfatsects); + + /* The following fields are only valid for FAT12/16 */ + /* 1@36: Drive number for MSDOS bootstrap -- left zero */ + /* 1@37: Reserved (zero) */ + /* 1@38: Extended boot signature: 0x29 if following valid */ + + MBR_PUTBOOTSIG16(var->fv_sect, EXTBOOT_SIGNATURE); + + /* 4@39: Volume serial number */ + + MBR_PUTVOLID16(var->fv_sect, fmt->ff_volumeid); + + /* 11@43: Volume label */ + + memcpy(&var->fv_sect[BS16_VOLLAB], fmt->ff_volumelabel, 11); + + /* 8@54: "FAT12 ", "FAT16 ", or "FAT " */ + + if (fmt->ff_fattype == 12) + { + memcpy(&var->fv_sect[BS16_FILESYSTYPE], "FAT12 ", 8); + } + else /* if (fmt->ff_fattype == 16) */ + { + memcpy(&var->fv_sect[BS16_FILESYSTYPE], "FAT16 ", 8); + } + + /* Boot code may be placed in the remainder of the sector */ + + memcpy(&var->fv_sect[BS16_BOOTCODE], var->fv_bootcode, var->fv_bootcodesize); + } + else + { + /* The following fields are only valid for FAT32 */ + /* 4@36: Count of sectors occupied by one FAT */ + + MBR_PUTFATSZ32(var->fv_sect, var->fv_nfatsects); + + /* 2@40: 0-3:Active FAT, 7=0 both FATS, 7=1 one FAT -- left zero */ + /* 2@42: MSB:Major LSB:Minor revision number (0.0) -- left zero */ + /* 4@44: Cluster no. of 1st cluster of root dir */ + + MBR_PUTROOTCLUS(var->fv_sect, FAT32_DEFAULT_ROOT_CLUSTER); + + /* 2@48: Sector number of fsinfo structure. Usually 1. */ + + MBR_PUTFSINFO(var->fv_sect, FAT_DEFAULT_FSINFO_SECTOR); + + /* 2@50: Sector number of boot record. Usually 6 */ + + MBR_PUTBKBOOTSEC(var->fv_sect, fmt->ff_backupboot); + + /* 12@52: Reserved (zero) */ + /* 1@64: Drive number for MSDOS bootstrap -- left zero */ + /* 1@65: Reserved (zero) */ + /* 1@66: Extended boot signature: 0x29 if following valid */ + + MBR_PUTBOOTSIG32(var->fv_sect, EXTBOOT_SIGNATURE); + + /* 4@67: Volume serial number */ + + MBR_PUTVOLID32(var->fv_sect, fmt->ff_volumeid); + + /* 11@71: Volume label */ + + memcpy(&var->fv_sect[BS32_VOLLAB], fmt->ff_volumelabel, 11); + + /* 8@82: "FAT12 ", "FAT16 ", or "FAT " */ + + memcpy(&var->fv_sect[BS32_FILESYSTYPE], "FAT32 ", 8); + + /* Boot code may be placed in the remainder of the sector */ + + memcpy(&var->fv_sect[BS32_BOOTCODE], var->fv_bootcode, var->fv_bootcodesize); + } + + /* The magic bytes at the end of the MBR are common to FAT12/16/32 */ + /* 2@510: Valid MBRs have 0x55aa here */ + + MBR_PUTSIGNATURE(var->fv_sect, BOOT_SIGNATURE16); +} + +/**************************************************************************** + * Name: mkfatfs_initfsinfo + * + * Description: + * Initialize the FAT32 FSINFO sector image + * + * Input: + * fmt - User specified format parameters + * var - Other format parameters that are not user specifiable + * + * Return: + * None; caller is responsible for providing valid parameters. + * + ****************************************************************************/ + +static inline void mkfatfs_initfsinfo(FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var) +{ + memset(var->fv_sect, 0, var->fv_sectorsize); + + /* 4@0: 0x41615252 = "RRaA" */ + + FSI_PUTLEADSIG(var->fv_sect, 0x41615252); + + /* 480@4: Reserved (zero) */ + /* 4@484: 0x61417272 = "rrAa" */ + + FSI_PUTSTRUCTSIG(var->fv_sect, 0x61417272); + + /* 4@488: Last free cluster count on volume */ + + FSI_PUTFREECOUNT(var->fv_sect, var->fv_nclusters - 1); + + /* 4@492: Cluster number of 1st free cluster */ + + FSI_PUTNXTFREE(var->fv_sect, FAT32_DEFAULT_ROOT_CLUSTER); + + /* 12@496: Reserved (zero) */ + /* 4@508: 0xaa550000 */ + + FSI_PUTTRAILSIG(var->fv_sect, BOOT_SIGNATURE32); +} + +/**************************************************************************** + * Name: mkfatfs_initrootdir + * + * Description: + * Initialize one root directory sector image + * + * Input: + * fmt - User specified format parameters + * var - Other format parameters that are not user specifiable + * sectno - On FAT32, the root directory is a cluster chain. + * This value indicates which sector of the cluster should be produced. + * + * Return: + * None; caller is responsible for providing valid parameters. + * + ****************************************************************************/ + +static inline void mkfatfs_initrootdir(FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var, int sectno) +{ + memset(var->fv_sect, 0, var->fv_sectorsize); + if (sectno == 0) + { + /* It is only necessary to set data in the first sector of the directory */ + + if (memcmp(fmt->ff_volumelabel, " ", 11)) + { + memcpy(&var->fv_sect[DIR_NAME], fmt->ff_volumelabel, 11); + } + + DIR_PUTATTRIBUTES(var->fv_sect, FATATTR_VOLUMEID); + DIR_PUTCRTIME(var->fv_sect, var->fv_createtime & 0xffff); + DIR_PUTWRTTIME(var->fv_sect, var->fv_createtime & 0xffff); + DIR_PUTCRDATE(var->fv_sect, var->fv_createtime >> 16); + DIR_PUTWRTDATE(var->fv_sect, var->fv_createtime >> 16); + } +} + +/**************************************************************************** + * Name: mkfatfs_writembr + * + * Description: + * Write the master boot record and, for FAT32, the backup boot record and + * the fsinfo sector. + * + * Input: + * fmt - User specified format parameters + * var - Other format parameters that are not user specifiable + * + * Return: + * Zero on success; negated errno on failure + * + ****************************************************************************/ + +static inline int mkfatfs_writembr(FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var) +{ + int sectno; + int ret; + + /* Create an image of the configured master boot record */ + + mkfatfs_initmbr(fmt, var); + + /* Write the master boot record as sector zero */ + + ret = mkfatfs_devwrite(fmt, var, 0); + + /* Write all of the reserved sectors */ + + memset(var->fv_sect, 0, var->fv_sectorsize); + for (sectno = 1; sectno < fmt->ff_rsvdseccount && ret >= 0; sectno++) + { + ret = mkfatfs_devwrite(fmt, var, sectno); + } + + /* Write FAT32-specific sectors */ + + if (ret >= 0 && fmt->ff_fattype == 32) + { + /* Write the backup master boot record */ + + if (fmt->ff_backupboot != 0) + { + /* Create another copy of the configured master boot record */ + + mkfatfs_initmbr(fmt, var); + + /* Write it to the backup location */ + + ret = mkfatfs_devwrite(fmt, var, fmt->ff_backupboot); + } + + if (ret >= 0) + { + /* Create an image of the fsinfo sector */ + + mkfatfs_initfsinfo(fmt, var); + + /* Write the fsinfo sector */ + + ret = mkfatfs_devwrite(fmt, var, FAT_DEFAULT_FSINFO_SECTOR); + } + } + + return ret; +} + +/**************************************************************************** + * Name: mkfatfs_writefat + * + * Description: + * Write the FAT sectors + * + * Input: + * fmt - User specified format parameters + * var - Other format parameters that are not user specifiable + * + * Return: + * Zero on success; negated errno on failure + * + ****************************************************************************/ + +static inline int mkfatfs_writefat(FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var) +{ + off_t offset = fmt->ff_rsvdseccount; + int fatno; + int sectno; + int ret; + + /* Loop for each FAT copy */ + + for (fatno = 0; fatno < fmt->ff_nfats; fatno++) + { + /* Loop for each sector in the FAT */ + + for (sectno = 0; sectno < var->fv_nfatsects; sectno++) + { + memset(var->fv_sect, 0, var->fv_sectorsize); + + /* Mark cluster allocations in sector one of each FAT */ + + if (sectno == 0) + { + memset(var->fv_sect, 0, var->fv_sectorsize); + switch (fmt->ff_fattype) + { + case 12: + /* Mark the first two full FAT entries -- 24 bits, 3 bytes total */ + + memset(var->fv_sect, 0xff, 3); + break; + + case 16: + /* Mark the first two full FAT entries -- 32 bits, 4 bytes total */ + + memset(var->fv_sect, 0xff, 4); + break; + + case 32: + default: /* Shouldn't happen */ + /* Mark the first two full FAT entries -- 64 bits, 8 bytes total */ + + memset(var->fv_sect, 0xff, 8); + + /* Cluster 2 is used as the root directory. Mark as EOF */ + + var->fv_sect[8] = 0xf8; + memset(&var->fv_sect[9], 0xff, 3); + break; + } + + /* Save the media type in the first byte of the FAT */ + + var->fv_sect[0] = FAT_DEFAULT_MEDIA_TYPE; + } + + /* Write the FAT sector */ + + ret = mkfatfs_devwrite(fmt, var, offset); + if (ret < 0) + { + return ret; + } + offset++; + } + } + return OK; +} + +/**************************************************************************** + * Name: mkfatfs_writerootdir + * + * Description: + * Write the root directory sectors + * + * Input: + * fmt - User specified format parameters + * var - Other format parameters that are not user specifiable + * + * Return: + * Zero on success; negated errno on failure + * + ****************************************************************************/ + +static inline int mkfatfs_writerootdir(FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var) +{ + off_t offset = fmt->ff_rsvdseccount + fmt->ff_nfats * var->fv_nfatsects; + int ret; + int i; + + /* Write the root directory after the last FAT. This is the root directory + * area for FAT12/16, and the first cluster on FAT32. + */ + + for (i = 0; i < var->fv_nrootdirsects; i++) + { + /* Format the next sector of the root directory */ + + mkfatfs_initrootdir(fmt, var, i); + + /* Write the next sector of the root directory */ + + ret = mkfatfs_devwrite(fmt, var, offset); + if (ret < 0) + { + return ret; + } + offset++; + } + return 0; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: mkfatfs_writefat + * + * Description: + * Write the configured fat filesystem to the block device + * + * Input: + * fmt - Caller specified format parameters + * var - Other format parameters that are not caller specifiable. (Most + * set by mkfatfs_configfatfs()). + * + * Return: + * Zero on success; negated errno on failure + * + ****************************************************************************/ + +int mkfatfs_writefatfs(FAR struct fat_format_s *fmt, + FAR struct fat_var_s *var) +{ + int ret; + + /* Write the master boot record (also the backup and fsinfo sectors) */ + + ret = mkfatfs_writembr(fmt, var); + + /* Write FATs */ + + if (ret >= 0) + { + ret = mkfatfs_writefat(fmt, var); + } + + /* Write the root directory after the last FAT. */ + + if (ret >= 0) + { + ret = mkfatfs_writerootdir(fmt, var); + } + return ret; +} + diff --git a/include/fsutils/mkfatfs.h b/include/fsutils/mkfatfs.h new file mode 100644 index 000000000..2f3970a38 --- /dev/null +++ b/include/fsutils/mkfatfs.h @@ -0,0 +1,150 @@ +/**************************************************************************** + * apps/include/fsutils/mkfatfs.h + * + * Copyright (C) 2008-2009, 2012, 2015, 2017 Gregory Nutt. All rights + * reserved. + * Author: Gregory Nutt + * + * 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 NuttX 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 OWNER 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. + * + ****************************************************************************/ + +#ifndef __APPS_INCLUDE_FSUTILS_MKFATFS_H +#define __APPS_INCLUDE_FSUTILS_MKFATFS_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define MKFATFS_DEFAULT_NFATS 2 /* 2: Default number of FATs */ +#define MKFATFS_DEFAULT_FATTYPE 0 /* 0: Autoselect FAT size */ +#define MKFATFS_DEFAULT_CLUSTSHIFT 0xff /* 0xff: Autoselect cluster size */ +#define MKFATFS_DEFAULT_VOLUMELABEL { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' } +#define MKFATFS_DEFAULT_BKUPBOOT 0 /* 0: Determine sector number of the backup boot sector */ +#define MKFATFS_DEFAULT_ROOTDIRENTS 0 /* 0: Autoselect number of root directory entries */ +#define MKFATFS_DEFAULT_RSVDSECCOUNT 0 /* 0: Autoselect number reserved sectors (usually 32) */ +#define MKFATFS_DEFAULT_HIDSEC 0 /* No hidden sectors */ +#define MKFATFS_DEFAULT_VOLUMEID 0 /* No volume ID */ +#define MKFATFS_DEFAULT_NSECTORS 0 /* 0: Use all sectors on device */ + +#define FAT_FORMAT_INITIALIZER \ +{ \ + MKFATFS_DEFAULT_NFATS, \ + MKFATFS_DEFAULT_FATTYPE, \ + MKFATFS_DEFAULT_CLUSTSHIFT, \ + MKFATFS_DEFAULT_VOLUMELABEL, \ + MKFATFS_DEFAULT_BKUPBOOT, \ + MKFATFS_DEFAULT_ROOTDIRENTS, \ + MKFATFS_DEFAULT_RSVDSECCOUNT, \ + MKFATFS_DEFAULT_HIDSEC, \ + MKFATFS_DEFAULT_VOLUMEID, \ + MKFATFS_DEFAULT_NSECTORS \ +} + +/**************************************************************************** + * Public Types + ****************************************************************************/ + +/* These are input parameters for the format. On return, these values may be + * overwritten with actual values used in the format. + */ + +struct fat_format_s +{ + uint8_t ff_nfats; /* Number of FATs */ + uint8_t ff_fattype; /* FAT size: 0 (autoselect), 12, 16, or 32 */ + uint8_t ff_clustshift; /* Log2 of sectors per cluster: 0-5, 0xff (autoselect) */ + uint8_t ff_volumelabel[11]; /* Volume label */ + uint16_t ff_backupboot; /* Sector number of the backup boot sector (0=use default)*/ + uint16_t ff_rootdirentries; /* Number of root directory entries */ + uint16_t ff_rsvdseccount; /* Reserved sectors */ + uint32_t ff_hidsec; /* Count of hidden sectors preceding fat */ + uint32_t ff_volumeid; /* FAT volume id */ + uint32_t ff_nsectors; /* Number of sectors from device to use: 0: Use all */ +}; + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +#undef EXTERN +#if defined(__cplusplus) +#define EXTERN extern "C" +extern "C" +{ +#else +#define EXTERN extern +#endif + +/**************************************************************************** + * Name: mkfatfs + * + * Description: + * Make a FAT file system image on the specified block device. This + * function can automatically format a FAT12 or FAT16 file system. By + * tradition, FAT32 will only be selected is explicitly requested. + * + * Inputs: + * pathname - the full path to a registered block driver + * fmt - Describes characteristics of the desired filesystem + * + * Return: + * Zero (OK) on success; -1 (ERROR) on failure with errno set appropriately: + * + * EINVAL - NULL block driver string, bad number of FATS in 'fmt', bad FAT + * size in 'fmt', bad cluster size in 'fmt' + * ENOENT - 'pathname' does not refer to anything in the filesystem. + * ENOTBLK - 'pathname' does not refer to a block driver + * EACCESS - block driver does not support write or geometry methods + * + * Assumptions: + * - The caller must assure that the block driver is not mounted and not in + * use when this function is called. The result of formatting a mounted + * device is indeterminate (but likely not good). + * + ****************************************************************************/ + +int mkfatfs(FAR const char *pathname, FAR struct fat_format_s *fmt); + +#undef EXTERN +#if defined(__cplusplus) +} +#endif + +#endif /* __APPS_INCLUDE_FSUTILS_MKFATFS_H */ diff --git a/include/fsutils/mksmartfs.h b/include/fsutils/mksmartfs.h index 2b7832c76..10ea9955d 100644 --- a/include/fsutils/mksmartfs.h +++ b/include/fsutils/mksmartfs.h @@ -33,8 +33,8 @@ * ****************************************************************************/ -#ifndef __INCLUDE_APPS_INCLUDE_FSUTILS_MKSMARTFS_H -#define __INCLUDE_APPS_INCLUDE_FSUTILS_MKSMARTFS_H +#ifndef __APPS_INCLUDE_FSUTILS_MKSMARTFS_H +#define __APPS_INCLUDE_FSUTILS_MKSMARTFS_H /**************************************************************************** * Included Files @@ -44,15 +44,7 @@ #include /**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -/**************************************************************************** - * Public Data + * Public Function Prototypes ****************************************************************************/ #undef EXTERN @@ -64,10 +56,6 @@ extern "C" #define EXTERN extern #endif -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - /**************************************************************************** * Name: mksmartfs * @@ -108,4 +96,4 @@ int mksmartfs(FAR const char *pathname, uint16_t sectorsize); } #endif -#endif /* __INCLUDE_APPS_INCLUDE_FSUTILS_MKSMARTFS_H */ +#endif /* __APPS_INCLUDE_FSUTILS_MKSMARTFS_H */ diff --git a/nshlib/Kconfig b/nshlib/Kconfig index 1f6414510..291c4275f 100644 --- a/nshlib/Kconfig +++ b/nshlib/Kconfig @@ -347,7 +347,7 @@ config NSH_DISABLE_MKFATFS bool "Disable mkfatfs" default y if DEFAULT_SMALL default n if !DEFAULT_SMALL - depends on FS_FAT + depends on FUTILS_MKFATFS config NSH_DISABLE_MKFIFO bool "Disable mkfifo" diff --git a/nshlib/README.txt b/nshlib/README.txt index 5c8e6b02c..3cc7de43e 100644 --- a/nshlib/README.txt +++ b/nshlib/README.txt @@ -1286,7 +1286,7 @@ Command Dependencies on Configuration Settings md5 CONFIG_NETUTILS_CODECS && CONFIG_CODECS_HASH_MD5 mb,mh,mw --- mkdir (((!CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_WRITABLE) || !CONFIG_DISABLE_PSEUDOFS_OPERATIONS) && CONFIG_NFILE_DESCRIPTORS > 0) - mkfatfs !CONFIG_DISABLE_MOUNTPOINT && CONFIG_NFILE_DESCRIPTORS > 0 && CONFIG_FS_FAT + mkfatfs !CONFIG_DISABLE_MOUNTPOINT && CONFIG_NFILE_DESCRIPTORS > 0 && CONFIG_FSUTILS_MKFATFS mkfifo CONFIG_NFILE_DESCRIPTORS > 0 && CONFIG_PIPES && CONFIG_DEV_FIFO_SIZE > 0 mkrd !CONFIG_DISABLE_MOUNTPOINT && CONFIG_NFILE_DESCRIPTORS > 0 && CONFIG_FS_WRITABLE (see note 4) mount !CONFIG_DISABLE_MOUNTPOINT && CONFIG_NFILE_DESCRIPTORS > 0 && CONFIG_FS_READABLE (see note 3) diff --git a/nshlib/nsh.h b/nshlib/nsh.h index a99610b44..2062e76da 100644 --- a/nshlib/nsh.h +++ b/nshlib/nsh.h @@ -1114,11 +1114,11 @@ int cmd_lsmod(FAR struct nsh_vtbl_s *vtbl, int argc, char **argv); # endif # endif /* CONFIG_FS_WRITABLE */ # endif /* CONFIG_FS_READABLE */ -# ifdef CONFIG_FS_FAT +# ifdef CONFIG_FSUTILS_MKFATFS # ifndef CONFIG_NSH_DISABLE_MKFATFS int cmd_mkfatfs(FAR struct nsh_vtbl_s *vtbl, int argc, char **argv); # endif -# endif /* CONFIG_FS_FAT */ +# endif /* CONFIG_FSUTILS_MKFATFS */ # if defined(CONFIG_FS_SMARTFS) && defined(CONFIG_FSUTILS_MKSMARTFS) # ifndef CONFIG_NSH_DISABLE_MKSMARTFS int cmd_mksmartfs(FAR struct nsh_vtbl_s *vtbl, int argc, char **argv); diff --git a/nshlib/nsh_command.c b/nshlib/nsh_command.c index a7b539cbe..bb4b18a02 100644 --- a/nshlib/nsh_command.c +++ b/nshlib/nsh_command.c @@ -304,7 +304,8 @@ static const struct cmdmap_s g_cmdmap[] = # endif #endif -#if !defined(CONFIG_DISABLE_MOUNTPOINT) && CONFIG_NFILE_DESCRIPTORS > 0 && defined(CONFIG_FS_FAT) +#if !defined(CONFIG_DISABLE_MOUNTPOINT) && CONFIG_NFILE_DESCRIPTORS > 0 && \ + defined(CONFIG_FSUTILS_MKFATFS) # ifndef CONFIG_NSH_DISABLE_MKFATFS { "mkfatfs", cmd_mkfatfs, 2, 4, "[-F ] " }, # endif diff --git a/nshlib/nsh_fscmds.c b/nshlib/nsh_fscmds.c index 1d9d55c8a..662e4a52c 100644 --- a/nshlib/nsh_fscmds.c +++ b/nshlib/nsh_fscmds.c @@ -55,9 +55,6 @@ # include # include # endif -# ifdef CONFIG_FS_FAT -# include -# endif # ifdef CONFIG_FS_SMARTFS # include "fsutils/mksmartfs.h" # endif @@ -86,6 +83,10 @@ #include #include +#ifdef CONFIG_FSUTILS_MKFATFS +# include "fsutils/mkfatfs.h" +#endif + #include "nsh.h" #include "nsh_console.h" @@ -1204,7 +1205,8 @@ int cmd_mkdir(FAR struct nsh_vtbl_s *vtbl, int argc, char **argv) * Name: cmd_mkfatfs ****************************************************************************/ -#if !defined(CONFIG_DISABLE_MOUNTPOINT) && CONFIG_NFILE_DESCRIPTORS > 0 && defined(CONFIG_FS_FAT) +#if !defined(CONFIG_DISABLE_MOUNTPOINT) && CONFIG_NFILE_DESCRIPTORS > 0 && \ + defined(CONFIG_FSUTILS_MKFATFS) #ifndef CONFIG_NSH_DISABLE_MKFATFS int cmd_mkfatfs(FAR struct nsh_vtbl_s *vtbl, int argc, char **argv) {