diff options
author | Theo de Raadt <deraadt@cvs.openbsd.org> | 1995-10-18 08:53:40 +0000 |
---|---|---|
committer | Theo de Raadt <deraadt@cvs.openbsd.org> | 1995-10-18 08:53:40 +0000 |
commit | d6583bb2a13f329cf0332ef2570eb8bb8fc0e39c (patch) | |
tree | ece253b876159b39c620e62b6c9b1174642e070e /sys/msdosfs |
initial import of NetBSD tree
Diffstat (limited to 'sys/msdosfs')
-rw-r--r-- | sys/msdosfs/bootsect.h | 85 | ||||
-rw-r--r-- | sys/msdosfs/bpb.h | 140 | ||||
-rw-r--r-- | sys/msdosfs/denode.h | 283 | ||||
-rw-r--r-- | sys/msdosfs/direntry.h | 103 | ||||
-rw-r--r-- | sys/msdosfs/fat.h | 111 | ||||
-rw-r--r-- | sys/msdosfs/msdosfs_conv.c | 355 | ||||
-rw-r--r-- | sys/msdosfs/msdosfs_denode.c | 674 | ||||
-rw-r--r-- | sys/msdosfs/msdosfs_fat.c | 983 | ||||
-rw-r--r-- | sys/msdosfs/msdosfs_lookup.c | 847 | ||||
-rw-r--r-- | sys/msdosfs/msdosfs_vfsops.c | 748 | ||||
-rw-r--r-- | sys/msdosfs/msdosfs_vnops.c | 1844 | ||||
-rw-r--r-- | sys/msdosfs/msdosfsmount.h | 167 |
12 files changed, 6340 insertions, 0 deletions
diff --git a/sys/msdosfs/bootsect.h b/sys/msdosfs/bootsect.h new file mode 100644 index 00000000000..4c31483fdfd --- /dev/null +++ b/sys/msdosfs/bootsect.h @@ -0,0 +1,85 @@ +/* $NetBSD: bootsect.h,v 1.7 1995/07/24 06:36:23 leo Exp $ */ + +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +/* + * Format of a boot sector. This is the first sector on a DOS floppy disk + * or the fist sector of a partition on a hard disk. But, it is not the + * first sector of a partitioned hard disk. + */ +struct bootsector33 { + u_int8_t bsJump[3]; /* jump inst E9xxxx or EBxx90 */ + int8_t bsOemName[8]; /* OEM name and version */ + int8_t bsBPB[19]; /* BIOS parameter block */ + int8_t bsDriveNumber; /* drive number (0x80) */ + int8_t bsBootCode[479]; /* pad so struct is 512b */ + u_int16_t bsBootSectSig; +#define BOOTSIG 0xaa55 +}; + +struct bootsector50 { + u_int8_t bsJump[3]; /* jump inst E9xxxx or EBxx90 */ + int8_t bsOemName[8]; /* OEM name and version */ + int8_t bsBPB[25]; /* BIOS parameter block */ + int8_t bsDriveNumber; /* drive number (0x80) */ + int8_t bsReserved1; /* reserved */ + int8_t bsBootSignature; /* ext. boot signature (0x29) */ +#define EXBOOTSIG 0x29 + int8_t bsVolumeID[4]; /* volume ID number */ + int8_t bsVolumeLabel[11]; /* volume label */ + int8_t bsFileSysType[8]; /* fs type (FAT12 or FAT16) */ + int8_t bsBootCode[448]; /* pad so structure is 512b */ + u_int16_t bsBootSectSig; +#define BOOTSIG 0xaa55 +}; +#ifdef atari +/* + * The boot sector on a gemdos fs is a little bit different from the msdos fs + * format. Currently there is no need to declare a seperate structure, the + * bootsector33 struct will do. + */ +#if 0 +struct bootsec_atari { + u_int8_t bsBranch[2]; /* branch inst if auto-boot */ + int8_t bsFiller[6]; /* anything or nothing */ + int8_t bsSerial[3]; /* serial no. for mediachange */ + int8_t bsBPB[19]; /* BIOS parameter block */ + int8_t bsBootCode[482]; /* pad so struct is 512b */ +}; +#endif +#endif /* atari */ + +union bootsector { + struct bootsector33 bs33; + struct bootsector50 bs50; +}; + +/* + * Shorthand for fields in the bpb. + */ +#define bsBytesPerSec bsBPB.bpbBytesPerSec +#define bsSectPerClust bsBPB.bpbSectPerClust +#define bsResSectors bsBPB.bpbResSectors +#define bsFATS bsBPB.bpbFATS +#define bsRootDirEnts bsBPB.bpbRootDirEnts +#define bsSectors bsBPB.bpbSectors +#define bsMedia bsBPB.bpbMedia +#define bsFATsecs bsBPB.bpbFATsecs +#define bsSectPerTrack bsBPB.bpbSectPerTrack +#define bsHeads bsBPB.bpbHeads +#define bsHiddenSecs bsBPB.bpbHiddenSecs +#define bsHugeSectors bsBPB.bpbHugeSectors diff --git a/sys/msdosfs/bpb.h b/sys/msdosfs/bpb.h new file mode 100644 index 00000000000..67dc787000c --- /dev/null +++ b/sys/msdosfs/bpb.h @@ -0,0 +1,140 @@ +/* $NetBSD: bpb.h,v 1.5 1995/07/24 06:37:15 leo Exp $ */ + +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +/* + * BIOS Parameter Block (BPB) for DOS 3.3 + */ +struct bpb33 { + u_int16_t bpbBytesPerSec; /* bytes per sector */ + u_int8_t bpbSecPerClust; /* sectors per cluster */ + u_int16_t bpbResSectors; /* number of reserved sectors */ + u_int8_t bpbFATs; /* number of FATs */ + u_int16_t bpbRootDirEnts; /* number of root directory entries */ + u_int16_t bpbSectors; /* total number of sectors */ + u_int8_t bpbMedia; /* media descriptor */ + u_int16_t bpbFATsecs; /* number of sectors per FAT */ + u_int16_t bpbSecPerTrack; /* sectors per track */ + u_int16_t bpbHeads; /* number of heads */ + u_int16_t bpbHiddenSecs; /* number of hidden sectors */ +}; + +/* + * BPB for DOS 5.0 The difference is bpbHiddenSecs is a short for DOS 3.3, + * and bpbHugeSectors is not in the 3.3 bpb. + */ +struct bpb50 { + u_int16_t bpbBytesPerSec; /* bytes per sector */ + u_int8_t bpbSecPerClust; /* sectors per cluster */ + u_int16_t bpbResSectors; /* number of reserved sectors */ + u_int8_t bpbFATs; /* number of FATs */ + u_int16_t bpbRootDirEnts; /* number of root directory entries */ + u_int16_t bpbSectors; /* total number of sectors */ + u_int8_t bpbMedia; /* media descriptor */ + u_int16_t bpbFATsecs; /* number of sectors per FAT */ + u_int16_t bpbSecPerTrack; /* sectors per track */ + u_int16_t bpbHeads; /* number of heads */ + u_int32_t bpbHiddenSecs; /* # of hidden sectors */ + u_int32_t bpbHugeSectors; /* # of sectors if bpbSectors == 0 */ +}; + +#ifdef atari +/* + * BPB for gemdos filesystems. Atari leaves the obsolete stuff undefined. + * Currently there is no need for a separate BPB structure. + */ +#if 0 +struct bpb_a { + u_int16_t bpbBytesPerSec; /* bytes per sector */ + u_int8_t bpbSecPerClust; /* sectors per cluster */ + u_int16_t bpbResSectors; /* number of reserved sectors */ + u_int8_t bpbFATs; /* number of FATs */ + u_int16_t bpbRootDirEnts; /* number of root directory entries */ + u_int16_t bpbSectors; /* total number of sectors */ + u_int8_t bpbUseless1; /* meaningless on gemdos fs */ + u_int16_t bpbFATsecs; /* number of sectors per FAT */ + u_int16_t bpbUseless2; /* meaningless for harddisk fs */ + u_int16_t bpbUseless3; /* meaningless for harddisk fs */ + u_int16_t bpbHiddenSecs; /* the TOS-BIOS ignores this */ +}; +#endif +#endif /* atari */ + +/* + * The following structures represent how the bpb's look on disk. shorts + * and longs are just character arrays of the appropriate length. This is + * because the compiler forces shorts and longs to align on word or + * halfword boundaries. + * + * XXX The little-endian code here assumes that the processor can access + * 16-bit and 32-bit quantities on byte boundaries. If this is not true, + * use the macros for the big-endian case. + */ +#include <machine/endian.h> +#if (BYTE_ORDER == LITTLE_ENDIAN) && defined(UNALIGNED_ACCESS) +#define getushort(x) *((u_int16_t *)(x)) +#define getulong(x) *((u_int32_t *)(x)) +#define putushort(p, v) (*((u_int16_t *)(p)) = (v)) +#define putulong(p, v) (*((u_int32_t *)(p)) = (v)) +#else +#define getushort(x) (((u_int8_t *)(x))[0] + (((u_int8_t *)(x))[1] << 8)) +#define getulong(x) (((u_int8_t *)(x))[0] + (((u_int8_t *)(x))[1] << 8) \ + + (((u_int8_t *)(x))[2] << 16) \ + + (((u_int8_t *)(x))[3] << 24)) +#define putushort(p, v) (((u_int8_t *)(p))[0] = (v), \ + ((u_int8_t *)(p))[1] = (v) >> 8) +#define putulong(p, v) (((u_int8_t *)(p))[0] = (v), \ + ((u_int8_t *)(p))[1] = (v) >> 8, \ + ((u_int8_t *)(p))[2] = (v) >> 16,\ + ((u_int8_t *)(p))[3] = (v) >> 24) +#endif + +/* + * BIOS Parameter Block (BPB) for DOS 3.3 + */ +struct byte_bpb33 { + int8_t bpbBytesPerSec[2]; /* bytes per sector */ + int8_t bpbSecPerClust; /* sectors per cluster */ + int8_t bpbResSectors[2]; /* number of reserved sectors */ + int8_t bpbFATs; /* number of FATs */ + int8_t bpbRootDirEnts[2]; /* number of root directory entries */ + int8_t bpbSectors[2]; /* total number of sectors */ + int8_t bpbMedia; /* media descriptor */ + int8_t bpbFATsecs[2]; /* number of sectors per FAT */ + int8_t bpbSecPerTrack[2]; /* sectors per track */ + int8_t bpbHeads[2]; /* number of heads */ + int8_t bpbHiddenSecs[2]; /* number of hidden sectors */ +}; + +/* + * BPB for DOS 5.0 The difference is bpbHiddenSecs is a short for DOS 3.3, + * and bpbHugeSectors is not in the 3.3 bpb. + */ +struct byte_bpb50 { + int8_t bpbBytesPerSec[2]; /* bytes per sector */ + int8_t bpbSecPerClust; /* sectors per cluster */ + int8_t bpbResSectors[2]; /* number of reserved sectors */ + int8_t bpbFATs; /* number of FATs */ + int8_t bpbRootDirEnts[2]; /* number of root directory entries */ + int8_t bpbSectors[2]; /* total number of sectors */ + int8_t bpbMedia; /* media descriptor */ + int8_t bpbFATsecs[2]; /* number of sectors per FAT */ + int8_t bpbSecPerTrack[2]; /* sectors per track */ + int8_t bpbHeads[2]; /* number of heads */ + int8_t bpbHiddenSecs[4]; /* number of hidden sectors */ + int8_t bpbHugeSectors[4]; /* # of sectors if bpbSectors == 0 */ +}; diff --git a/sys/msdosfs/denode.h b/sys/msdosfs/denode.h new file mode 100644 index 00000000000..1b5c425696e --- /dev/null +++ b/sys/msdosfs/denode.h @@ -0,0 +1,283 @@ +/* $NetBSD: denode.h,v 1.16 1995/09/09 19:38:00 ws Exp $ */ + +/*- + * Copyright (C) 1994 Wolfgang Solfrank. + * Copyright (C) 1994 TooLs GmbH. + * All rights reserved. + * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below). + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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. + */ +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +/* + * This is the pc filesystem specific portion of the vnode structure. + * + * To describe a file uniquely the de_dirclust, de_diroffset, and + * de_StartCluster fields are used. + * + * de_dirclust contains the cluster number of the directory cluster + * containing the entry for a file or directory. + * de_diroffset is the index into the cluster for the entry describing + * a file or directory. + * de_StartCluster is the number of the first cluster of the file or directory. + * + * Now to describe the quirks of the pc filesystem. + * - Clusters 0 and 1 are reserved. + * - The first allocatable cluster is 2. + * - The root directory is of fixed size and all blocks that make it up + * are contiguous. + * - Cluster 0 refers to the root directory when it is found in the + * startcluster field of a directory entry that points to another directory. + * - Cluster 0 implies a 0 length file when found in the start cluster field + * of a directory entry that points to a file. + * - You can't use the cluster number 0 to derive the address of the root + * directory. + * - Multiple directory entries can point to a directory. The entry in the + * parent directory points to a child directory. Any directories in the + * child directory contain a ".." entry that points back to the parent. + * The child directory itself contains a "." entry that points to itself. + * - The root directory does not contain a "." or ".." entry. + * - Directory entries for directories are never changed once they are created + * (except when removed). The size stays 0, and the last modification time + * is never changed. This is because so many directory entries can point to + * the physical clusters that make up a directory. It would lead to an + * update nightmare. + * - The length field in a directory entry pointing to a directory contains 0 + * (always). The only way to find the end of a directory is to follow the + * cluster chain until the "last cluster" marker is found. + * + * My extensions to make this house of cards work. These apply only to the in + * memory copy of the directory entry. + * - A reference count for each denode will be kept since dos doesn't keep such + * things. + */ + +/* + * Internal pseudo-offset for (nonexistent) directory entry for the root + * dir in the root dir + */ +#define MSDOSFSROOT_OFS 0x1fffffff + +/* + * The fat cache structure. fc_fsrcn is the filesystem relative cluster + * number that corresponds to the file relative cluster number in this + * structure (fc_frcn). + */ +struct fatcache { + u_short fc_frcn; /* file relative cluster number */ + u_short fc_fsrcn; /* filesystem relative cluster number */ +}; + +/* + * The fat entry cache as it stands helps make extending files a "quick" + * operation by avoiding having to scan the fat to discover the last + * cluster of the file. The cache also helps sequential reads by + * remembering the last cluster read from the file. This also prevents us + * from having to rescan the fat to find the next cluster to read. This + * cache is probably pretty worthless if a file is opened by multiple + * processes. + */ +#define FC_SIZE 2 /* number of entries in the cache */ +#define FC_LASTMAP 0 /* entry the last call to pcbmap() resolved + * to */ +#define FC_LASTFC 1 /* entry for the last cluster in the file */ + +#define FCE_EMPTY 0xffff /* doesn't represent an actual cluster # */ + +/* + * Set a slot in the fat cache. + */ +#define fc_setcache(dep, slot, frcn, fsrcn) \ + (dep)->de_fc[slot].fc_frcn = frcn; \ + (dep)->de_fc[slot].fc_fsrcn = fsrcn; + +/* + * This is the in memory variant of a dos directory entry. It is usually + * contained within a vnode. + */ +struct denode { + struct denode *de_next; /* Hash chain forward */ + struct denode **de_prev; /* Hash chain back */ + struct vnode *de_vnode; /* addr of vnode we are part of */ + struct vnode *de_devvp; /* vnode of blk dev we live on */ + u_long de_flag; /* flag bits */ + dev_t de_dev; /* device where direntry lives */ + u_long de_dirclust; /* cluster of the directory file containing this entry */ + u_long de_diroffset; /* ordinal of this entry in the directory */ + u_long de_fndclust; /* cluster of found dir entry */ + u_long de_fndoffset; /* offset of found dir entry */ + long de_refcnt; /* reference count */ + struct msdosfsmount *de_pmp; /* addr of our mount struct */ + struct lockf *de_lockf; /* byte level lock list */ + pid_t de_lockholder; /* current lock holder */ + pid_t de_lockwaiter; /* lock wanter */ + /* the next two fields must be contiguous in memory... */ + u_char de_Name[8]; /* name, from directory entry */ + u_char de_Extension[3]; /* extension, from directory entry */ + u_char de_Attributes; /* attributes, from directory entry */ + u_short de_Time; /* creation time */ + u_short de_Date; /* creation date */ + u_short de_StartCluster; /* starting cluster of file */ + u_long de_FileSize; /* size of file in bytes */ + struct fatcache de_fc[FC_SIZE]; /* fat cache */ +}; + +/* + * Values for the de_flag field of the denode. + */ +#define DE_LOCKED 0x0001 /* Denode lock. */ +#define DE_WANTED 0x0002 /* Denode is wanted by a process. */ +#define DE_UPDATE 0x0004 /* Modification time update request. */ +#define DE_MODIFIED 0x0008 /* Denode has been modified. */ +#define DE_RENAME 0x0010 /* Denode is in the process of being renamed */ + +/* + * Transfer directory entries between internal and external form. + * dep is a struct denode * (internal form), + * dp is a struct direntry * (external form). + */ +#define DE_INTERNALIZE(dep, dp) \ + (bcopy((dp)->deName, (dep)->de_Name, 11), \ + (dep)->de_Attributes = (dp)->deAttributes, \ + (dep)->de_Time = getushort((dp)->deTime), \ + (dep)->de_Date = getushort((dp)->deDate), \ + (dep)->de_StartCluster = getushort((dp)->deStartCluster), \ + (dep)->de_FileSize = getulong((dp)->deFileSize)) + +#define DE_EXTERNALIZE(dp, dep) \ + (bcopy((dep)->de_Name, (dp)->deName, 11), \ + (dp)->deAttributes = (dep)->de_Attributes, \ + putushort((dp)->deTime, (dep)->de_Time), \ + putushort((dp)->deDate, (dep)->de_Date), \ + putushort((dp)->deStartCluster, (dep)->de_StartCluster), \ + putulong((dp)->deFileSize, \ + ((dep)->de_Attributes & ATTR_DIRECTORY) ? 0 : (dep)->de_FileSize)) + +#define de_forw de_chain[0] +#define de_back de_chain[1] + +#ifdef _KERNEL + +#define VTODE(vp) ((struct denode *)(vp)->v_data) +#define DETOV(de) ((de)->de_vnode) + +#define DE_TIMES(dep) \ + if ((dep)->de_flag & DE_UPDATE) { \ + (dep)->de_flag &= ~DE_UPDATE; \ + if (((dep)->de_Attributes & ATTR_DIRECTORY) == 0) { \ + unix2dostime(NULL, &(dep)->de_Date, &(dep)->de_Time); \ + (dep)->de_Attributes |= ATTR_ARCHIVE; \ + (dep)->de_flag |= DE_MODIFIED; \ + } \ + } + +/* + * This overlays the fid structure (see mount.h) + */ +struct defid { + u_short defid_len; /* length of structure */ + u_short defid_pad; /* force long alignment */ + + u_long defid_dirclust; /* cluster this dir entry came from */ + u_long defid_dirofs; /* offset of entry within the cluster */ + + /* u_long defid_gen; /* generation number */ +}; + +/* + * Prototypes for MSDOSFS vnode operations + */ +int msdosfs_lookup __P((struct vop_lookup_args *)); +int msdosfs_create __P((struct vop_create_args *)); +int msdosfs_mknod __P((struct vop_mknod_args *)); +int msdosfs_open __P((struct vop_open_args *)); +int msdosfs_close __P((struct vop_close_args *)); +int msdosfs_access __P((struct vop_access_args *)); +int msdosfs_getattr __P((struct vop_getattr_args *)); +int msdosfs_setattr __P((struct vop_setattr_args *)); +int msdosfs_read __P((struct vop_read_args *)); +int msdosfs_write __P((struct vop_write_args *)); +#ifdef NFSSERVER +int lease_check __P((struct vop_lease_args *)); +#define msdosfs_lease_check lease_check +#else +#define msdosfs_lease_check ((int (*) __P((struct vop_lease_args *)))nullop) +#endif +int msdosfs_ioctl __P((struct vop_ioctl_args *)); +int msdosfs_select __P((struct vop_select_args *)); +int msdosfs_mmap __P((struct vop_mmap_args *)); +int msdosfs_fsync __P((struct vop_fsync_args *)); +int msdosfs_seek __P((struct vop_seek_args *)); +int msdosfs_remove __P((struct vop_remove_args *)); +int msdosfs_link __P((struct vop_link_args *)); +int msdosfs_rename __P((struct vop_rename_args *)); +int msdosfs_mkdir __P((struct vop_mkdir_args *)); +int msdosfs_rmdir __P((struct vop_rmdir_args *)); +int msdosfs_symlink __P((struct vop_symlink_args *)); +int msdosfs_readdir __P((struct vop_readdir_args *)); +int msdosfs_readlink __P((struct vop_readlink_args *)); +int msdosfs_abortop __P((struct vop_abortop_args *)); +int msdosfs_inactive __P((struct vop_inactive_args *)); +int msdosfs_reclaim __P((struct vop_reclaim_args *)); +int msdosfs_lock __P((struct vop_lock_args *)); +int msdosfs_unlock __P((struct vop_unlock_args *)); +int msdosfs_bmap __P((struct vop_bmap_args *)); +int msdosfs_strategy __P((struct vop_strategy_args *)); +int msdosfs_print __P((struct vop_print_args *)); +int msdosfs_islocked __P((struct vop_islocked_args *)); +int msdosfs_advlock __P((struct vop_advlock_args *)); +int msdosfs_reallocblks __P((struct vop_reallocblks_args *)); + +/* + * Internal service routine prototypes. + */ +int createde __P((struct denode *, struct denode *, struct denode **)); +int deextend __P((struct denode *, u_long, struct ucred *)); +int deget __P((struct msdosfsmount *, u_long, u_long, struct direntry *, struct denode **)); +int detrunc __P((struct denode *, u_long, int, struct ucred *, struct proc *)); +int deupdat __P((struct denode *, int)); +int doscheckpath __P((struct denode *, struct denode *)); +int dosdirempty __P((struct denode *)); +int readde __P((struct denode *, struct buf **, struct direntry **)); +int readep __P((struct msdosfsmount *, u_long, u_long, struct buf **, struct direntry **)); +void reinsert __P((struct denode *)); +int removede __P((struct denode *, struct denode *)); +#endif /* _KERNEL */ diff --git a/sys/msdosfs/direntry.h b/sys/msdosfs/direntry.h new file mode 100644 index 00000000000..8ed9ce184f1 --- /dev/null +++ b/sys/msdosfs/direntry.h @@ -0,0 +1,103 @@ +/* $NetBSD: direntry.h,v 1.9 1995/03/29 22:08:52 briggs Exp $ */ + +/*- + * Copyright (C) 1994 Wolfgang Solfrank. + * Copyright (C) 1994 TooLs GmbH. + * All rights reserved. + * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below). + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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. + */ +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +/* + * Structure of a dos directory entry. + */ +struct direntry { + u_int8_t deName[8]; /* filename, blank filled */ +#define SLOT_EMPTY 0x00 /* slot has never been used */ +#define SLOT_E5 0x05 /* the real value is 0xe5 */ +#define SLOT_DELETED 0xe5 /* file in this slot deleted */ + u_int8_t deExtension[3]; /* extension, blank filled */ + u_int8_t deAttributes; /* file attributes */ +#define ATTR_NORMAL 0x00 /* normal file */ +#define ATTR_READONLY 0x01 /* file is readonly */ +#define ATTR_HIDDEN 0x02 /* file is hidden */ +#define ATTR_SYSTEM 0x04 /* file is a system file */ +#define ATTR_VOLUME 0x08 /* entry is a volume label */ +#define ATTR_DIRECTORY 0x10 /* entry is a directory name */ +#define ATTR_ARCHIVE 0x20 /* file is new or modified */ + u_int8_t deReserved[10]; /* reserved */ + u_int8_t deTime[2]; /* create/last update time */ + u_int8_t deDate[2]; /* create/last update date */ + u_int8_t deStartCluster[2]; /* starting cluster of file */ + u_int8_t deFileSize[4]; /* size of file in bytes */ +}; + +/* + * This is the format of the contents of the deTime field in the direntry + * structure. + * We don't use bitfields because we don't know how compilers for + * arbitrary machines will lay them out. + */ +#define DT_2SECONDS_MASK 0x1F /* seconds divided by 2 */ +#define DT_2SECONDS_SHIFT 0 +#define DT_MINUTES_MASK 0x7E0 /* minutes */ +#define DT_MINUTES_SHIFT 5 +#define DT_HOURS_MASK 0xF800 /* hours */ +#define DT_HOURS_SHIFT 11 + +/* + * This is the format of the contents of the deDate field in the direntry + * structure. + */ +#define DD_DAY_MASK 0x1F /* day of month */ +#define DD_DAY_SHIFT 0 +#define DD_MONTH_MASK 0x1E0 /* month */ +#define DD_MONTH_SHIFT 5 +#define DD_YEAR_MASK 0xFE00 /* year - 1980 */ +#define DD_YEAR_SHIFT 9 + +#ifdef _KERNEL +void unix2dostime __P((struct timespec *tsp, u_int16_t *ddp, u_int16_t *dtp)); +void dos2unixtime __P((u_int dd, u_int dt, struct timespec *tsp)); +int dos2unixfn __P((u_char dn[11], u_char *un)); +void unix2dosfn __P((u_char *un, u_char dn[11], int unlen)); +#endif /* _KERNEL */ diff --git a/sys/msdosfs/fat.h b/sys/msdosfs/fat.h new file mode 100644 index 00000000000..89c66757ef8 --- /dev/null +++ b/sys/msdosfs/fat.h @@ -0,0 +1,111 @@ +/* $NetBSD: fat.h,v 1.8 1995/09/09 19:38:01 ws Exp $ */ + +/*- + * Copyright (C) 1994 Wolfgang Solfrank. + * Copyright (C) 1994 TooLs GmbH. + * All rights reserved. + * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below). + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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. + */ +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +/* + * Some useful cluster numbers. + */ +#define MSDOSFSROOT 0 /* cluster 0 means the root dir */ +#define CLUST_FREE 0 /* cluster 0 also means a free cluster */ +#define MSDOSFSFREE CLUST_FREE +#define CLUST_FIRST 2 /* first legal cluster number */ +#define CLUST_RSRVS 0xfff0 /* start of reserved cluster range */ +#define CLUST_RSRVE 0xfff6 /* end of reserved cluster range */ +#define CLUST_BAD 0xfff7 /* a cluster with a defect */ +#define CLUST_EOFS 0xfff8 /* start of eof cluster range */ +#define CLUST_EOFE 0xffff /* end of eof cluster range */ + +#define FAT12_MASK 0x0fff /* mask for 12 bit cluster numbers */ +#define FAT16_MASK 0xffff /* mask for 16 bit cluster numbers */ + +#ifdef atari +/* + * Return true if filesystem uses 12 bit fats. If the filesystem + * is on floppy we've got a 12 bit fat filesystem, otherwise 16 bit. + * We check the d_type field in the disklabel struct while mounting + * and store the result in the pm_fatentrysize field in the + * msdosfsmount struct. + */ +#define FAT12(pmp) (pmp->pm_fatentrysize == 12) +#define FAT16(pmp) (pmp->pm_fatentrysize == 16) +#else /* !atari */ +/* + * Return true if filesystem uses 12 bit fats. Microsoft Programmer's + * Reference says if the maximum cluster number in a filesystem is greater + * than 4086 then we've got a 16 bit fat filesystem. + */ +#define FAT12(pmp) (pmp->pm_maxcluster <= 4086) +#define FAT16(pmp) (pmp->pm_maxcluster > 4086) +#endif /* !atari */ + +#define MSDOSFSEOF(cn) (((cn) & 0xfff8) == 0xfff8) + +#ifdef _KERNEL +/* + * These are the values for the function argument to the function + * fatentry(). + */ +#define FAT_GET 0x0001 /* get a fat entry */ +#define FAT_SET 0x0002 /* set a fat entry */ +#define FAT_GET_AND_SET (FAT_GET | FAT_SET) + +/* + * Flags to extendfile: + */ +#define DE_CLEAR 1 /* Zero out the blocks allocated */ + +int pcbmap __P((struct denode *, u_long, daddr_t *, u_long *, int *)); +int clusterfree __P((struct msdosfsmount *, u_long, u_long *)); +int clusteralloc __P((struct msdosfsmount *, u_long, u_long, u_long, u_long *, u_long *)); +int extendfile __P((struct denode *, u_long, struct buf **, u_long *, int)); +int fatentry __P((int, struct msdosfsmount *, u_long, u_long *, u_long)); +void fc_purge __P((struct denode *, u_int)); +void fc_lookup __P((struct denode *, u_long, u_long *, u_long *)); +int fillinusemap __P((struct msdosfsmount *)); +int freeclusterchain __P((struct msdosfsmount *, u_long)); +#endif /* _KERNEL */ diff --git a/sys/msdosfs/msdosfs_conv.c b/sys/msdosfs/msdosfs_conv.c new file mode 100644 index 00000000000..fcf4a69d338 --- /dev/null +++ b/sys/msdosfs/msdosfs_conv.c @@ -0,0 +1,355 @@ +/* $NetBSD: msdosfs_conv.c,v 1.10 1994/12/27 18:36:24 mycroft Exp $ */ + +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +/* + * System include files. + */ +#include <sys/param.h> +#include <sys/time.h> +#include <sys/kernel.h> /* defines tz */ + +/* + * MSDOSFS include files. + */ +#include <msdosfs/direntry.h> + +/* + * Days in each month in a regular year. + */ +u_short regyear[] = { + 31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31 +}; + +/* + * Days in each month in a leap year. + */ +u_short leapyear[] = { + 31, 29, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31 +}; + +/* + * Variables used to remember parts of the last time conversion. Maybe we + * can avoid a full conversion. + */ +u_long lasttime; +u_long lastday; +u_short lastddate; +u_short lastdtime; + +/* + * Convert the unix version of time to dos's idea of time to be used in + * file timestamps. The passed in unix time is assumed to be in GMT. + */ +void +unix2dostime(tsp, ddp, dtp) + struct timespec *tsp; + u_int16_t *ddp; + u_int16_t *dtp; +{ + u_long t; + u_long days; + u_long inc; + u_long year; + u_long month; + u_short *months; + struct timespec ts; + + /* + * NULL means to read the current time. + */ + if (tsp == NULL) { + TIMEVAL_TO_TIMESPEC(&time, &ts); + tsp = &ts; + } + + /* + * If the time from the last conversion is the same as now, then + * skip the computations and use the saved result. + */ + t = tsp->ts_sec - (tz.tz_minuteswest * 60) + /* +- daylight savings time correction */ ; + if (lasttime != t) { + lasttime = t; + lastdtime = (((t % 60) >> 1) << DT_2SECONDS_SHIFT) + + (((t / 60) % 60) << DT_MINUTES_SHIFT) + + (((t / 3600) % 24) << DT_HOURS_SHIFT); + + /* + * If the number of days since 1970 is the same as the last + * time we did the computation then skip all this leap year + * and month stuff. + */ + days = t / (24 * 60 * 60); + if (days != lastday) { + lastday = days; + for (year = 1970;; year++) { + inc = year & 0x03 ? 365 : 366; + if (days < inc) + break; + days -= inc; + } + months = year & 0x03 ? regyear : leapyear; + for (month = 0; month < 12; month++) { + if (days < months[month]) + break; + days -= months[month]; + } + lastddate = ((days + 1) << DD_DAY_SHIFT) + + ((month + 1) << DD_MONTH_SHIFT); + /* + * Remember dos's idea of time is relative to 1980. + * unix's is relative to 1970. If somehow we get a + * time before 1980 then don't give totally crazy + * results. + */ + if (year > 1980) + lastddate += (year - 1980) << DD_YEAR_SHIFT; + } + } + *dtp = lastdtime; + *ddp = lastddate; +} + +/* + * The number of seconds between Jan 1, 1970 and Jan 1, 1980. In that + * interval there were 8 regular years and 2 leap years. + */ +#define SECONDSTO1980 (((8 * 365) + (2 * 366)) * (24 * 60 * 60)) + +u_short lastdosdate; +u_long lastseconds; + +/* + * Convert from dos' idea of time to unix'. This will probably only be + * called from the stat(), and fstat() system calls and so probably need + * not be too efficient. + */ +void +dos2unixtime(dd, dt, tsp) + u_int dd; + u_int dt; + struct timespec *tsp; +{ + u_long seconds; + u_long m, month; + u_long y, year; + u_long days; + u_short *months; + + seconds = ((dt & DT_2SECONDS_MASK) >> DT_2SECONDS_SHIFT) + + ((dt & DT_MINUTES_MASK) >> DT_MINUTES_SHIFT) * 60 + + ((dt & DT_HOURS_MASK) >> DT_HOURS_SHIFT) * 3600; + /* + * If the year, month, and day from the last conversion are the + * same then use the saved value. + */ + if (lastdosdate != dd) { + lastdosdate = dd; + days = 0; + year = (dd & DD_YEAR_MASK) >> DD_YEAR_SHIFT; + for (y = 0; y < year; y++) + days += y & 0x03 ? 365 : 366; + months = year & 0x03 ? regyear : leapyear; + /* + * Prevent going from 0 to 0xffffffff in the following + * loop. + */ + month = (dd & DD_MONTH_MASK) >> DD_MONTH_SHIFT; + if (month == 0) { + printf("dos2unixtime(): month value out of range (%ld)\n", + month); + month = 1; + } + for (m = 0; m < month - 1; m++) + days += months[m]; + days += ((dd & DD_DAY_MASK) >> DD_DAY_SHIFT) - 1; + lastseconds = (days * 24 * 60 * 60) + SECONDSTO1980; + } + tsp->ts_sec = seconds + lastseconds + (tz.tz_minuteswest * 60) + /* -+ daylight savings time correction */ ; + tsp->ts_nsec = 0; +} + +/* + * Cheezy macros to do case detection and conversion for the ascii + * character set. DOESN'T work for ebcdic. + */ +#define isupper(c) (c >= 'A' && c <= 'Z') +#define islower(c) (c >= 'a' && c <= 'z') +#define toupper(c) (c & ~' ') +#define tolower(c) (c | ' ') + +/* + * DOS filenames are made of 2 parts, the name part and the extension part. + * The name part is 8 characters long and the extension part is 3 + * characters long. They may contain trailing blanks if the name or + * extension are not long enough to fill their respective fields. + */ + +/* + * Convert a DOS filename to a unix filename. And, return the number of + * characters in the resulting unix filename excluding the terminating + * null. + */ +int +dos2unixfn(dn, un) + u_char dn[11]; + u_char *un; +{ + int i; + int ni; + int ei; + int thislong = 0; + u_char c; + u_char *origun = un; + + /* + * Find the last character in the name portion of the dos filename. + */ + for (ni = 7; ni >= 0; ni--) + if (dn[ni] != ' ') + break; + + /* + * Find the last character in the extension portion of the + * filename. + */ + for (ei = 10; ei >= 8; ei--) + if (dn[ei] != ' ') + break; + + /* + * Copy the name portion into the unix filename string. NOTE: DOS + * filenames are usually kept in upper case. To make it more unixy + * we convert all DOS filenames to lower case. Some may like this, + * some may not. + */ + for (i = 0; i <= ni; i++) { + c = dn[i]; + *un++ = isupper(c) ? tolower(c) : c; + thislong++; + } + + /* + * Now, if there is an extension then put in a period and copy in + * the extension. + */ + if (ei >= 8) { + *un++ = '.'; + thislong++; + for (i = 8; i <= ei; i++) { + c = dn[i]; + *un++ = isupper(c) ? tolower(c) : c; + thislong++; + } + } + *un++ = 0; + + /* + * If first char of the filename is SLOT_E5 (0x05), then the real + * first char of the filename should be 0xe5. But, they couldn't + * just have a 0xe5 mean 0xe5 because that is used to mean a freed + * directory slot. Another dos quirk. + */ + if (*origun == SLOT_E5) + *origun = 0xe5; + + return (thislong); +} + +/* + * Convert a unix filename to a DOS filename. This function does not ensure + * that valid characters for a dos filename are supplied. + */ +void +unix2dosfn(un, dn, unlen) + u_char *un; + u_char dn[11]; + int unlen; +{ + int i; + u_char c; + + /* + * Fill the dos filename string with blanks. These are DOS's pad + * characters. + */ + for (i = 0; i <= 10; i++) + dn[i] = ' '; + + /* + * The filenames "." and ".." are handled specially, since they + * don't follow dos filename rules. + */ + if (un[0] == '.' && unlen == 1) { + dn[0] = '.'; + return; + } + if (un[0] == '.' && un[1] == '.' && unlen == 2) { + dn[0] = '.'; + dn[1] = '.'; + return; + } + + /* + * Copy the unix filename into the dos filename string upto the end + * of string, a '.', or 8 characters. Whichever happens first stops + * us. This forms the name portion of the dos filename. Fold to + * upper case. + */ + for (i = 0; i <= 7 && unlen && (c = *un) && c != '.'; i++) { + dn[i] = islower(c) ? toupper(c) : c; + un++; + unlen--; + } + + /* + * If the first char of the filename is 0xe5, then translate it to + * 0x05. This is because 0xe5 is the marker for a deleted + * directory slot. I guess this means you can't have filenames + * that start with 0x05. I suppose we should check for this and + * doing something about it. + */ + if (dn[0] == SLOT_DELETED) + dn[0] = SLOT_E5; + + /* + * Strip any further characters up to a '.' or the end of the + * string. + */ + while (unlen && (c = *un)) { + un++; + unlen--; + /* Make sure we've skipped over the dot before stopping. */ + if (c == '.') + break; + } + + /* + * Copy in the extension part of the name, if any. Force to upper + * case. Note that the extension is allowed to contain '.'s. + * Filenames in this form are probably inaccessable under dos. + */ + for (i = 8; i <= 10 && unlen && (c = *un); i++) { + dn[i] = islower(c) ? toupper(c) : c; + un++; + unlen--; + } +} diff --git a/sys/msdosfs/msdosfs_denode.c b/sys/msdosfs/msdosfs_denode.c new file mode 100644 index 00000000000..41835010cf2 --- /dev/null +++ b/sys/msdosfs/msdosfs_denode.c @@ -0,0 +1,674 @@ +/* $NetBSD: msdosfs_denode.c,v 1.15 1995/09/09 19:38:03 ws Exp $ */ + +/*- + * Copyright (C) 1994 Wolfgang Solfrank. + * Copyright (C) 1994 TooLs GmbH. + * All rights reserved. + * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below). + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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. + */ +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +#include <sys/param.h> +#include <sys/systm.h> +#include <sys/mount.h> +#include <sys/malloc.h> +#include <sys/proc.h> +#include <sys/buf.h> +#include <sys/vnode.h> +#include <sys/kernel.h> /* defines "time" */ + +#include <msdosfs/bpb.h> +#include <msdosfs/msdosfsmount.h> +#include <msdosfs/direntry.h> +#include <msdosfs/denode.h> +#include <msdosfs/fat.h> + +struct denode **dehashtbl; +u_long dehash; /* size of hash table - 1 */ +#define DEHASH(dev, dcl, doff) (((dev) + (dcl) + (doff) / sizeof(struct direntry)) \ + & dehash) + +int +msdosfs_init() +{ + + dehashtbl = hashinit(desiredvnodes/2, M_MSDOSFSMNT, &dehash); +} + +static struct denode * +msdosfs_hashget(dev, dirclust, diroff) + dev_t dev; + u_long dirclust; + u_long diroff; +{ + struct denode *dep; + + for (;;) + for (dep = dehashtbl[DEHASH(dev, dirclust, diroff)];; + dep = dep->de_next) { + if (dep == NULL) + return (NULL); + if (dirclust == dep->de_dirclust && + diroff == dep->de_diroffset && + dev == dep->de_dev && + dep->de_refcnt != 0) { + if (dep->de_flag & DE_LOCKED) { + dep->de_flag |= DE_WANTED; + sleep(dep, PINOD); + break; + } + if (!vget(DETOV(dep), 1)) + return (dep); + break; + } + } + /* NOTREACHED */ +} + +static void +msdosfs_hashins(dep) + struct denode *dep; +{ + struct denode **depp, *deq; + + depp = &dehashtbl[DEHASH(dep->de_dev, dep->de_dirclust, dep->de_diroffset)]; + if (deq = *depp) + deq->de_prev = &dep->de_next; + dep->de_next = deq; + dep->de_prev = depp; + *depp = dep; +} + +static void +msdosfs_hashrem(dep) + struct denode *dep; +{ + struct denode *deq; + + if (deq = dep->de_next) + deq->de_prev = dep->de_prev; + *dep->de_prev = deq; +#ifdef DIAGNOSTIC + dep->de_next = NULL; + dep->de_prev = NULL; +#endif +} + +/* + * If deget() succeeds it returns with the gotten denode locked(). + * + * pmp - address of msdosfsmount structure of the filesystem containing + * the denode of interest. The pm_dev field and the address of + * the msdosfsmount structure are used. + * dirclust - which cluster bp contains, if dirclust is 0 (root directory) + * diroffset is relative to the beginning of the root directory, + * otherwise it is cluster relative. + * diroffset - offset past begin of cluster of denode we want + * direntptr - address of the direntry structure of interest. If direntptr is + * NULL, the block is read if necessary. + * depp - returns the address of the gotten denode. + */ +int +deget(pmp, dirclust, diroffset, direntptr, depp) + struct msdosfsmount *pmp; /* so we know the maj/min number */ + u_long dirclust; /* cluster this dir entry came from */ + u_long diroffset; /* index of entry within the cluster */ + struct direntry *direntptr; + struct denode **depp; /* returns the addr of the gotten denode */ +{ + int error; + extern int (**msdosfs_vnodeop_p)(); + struct denode *ldep; + struct vnode *nvp; + struct buf *bp; + +#ifdef MSDOSFS_DEBUG + printf("deget(pmp %08x, dirclust %d, diroffset %x, direntptr %x, depp %08x)\n", + pmp, dirclust, diroffset, direntptr, depp); +#endif + + /* + * If dir entry is given and refers to a directory, convert to + * canonical form + */ + if (direntptr && (direntptr->deAttributes & ATTR_DIRECTORY)) { + dirclust = getushort(direntptr->deStartCluster); + if (dirclust == MSDOSFSROOT) + diroffset = MSDOSFSROOT_OFS; + else + diroffset = 0; + } + + /* + * See if the denode is in the denode cache. Use the location of + * the directory entry to compute the hash value. For subdir use + * address of "." entry. for root dir use cluster MSDOSFSROOT, + * offset MSDOSFSROOT_OFS + * + * NOTE: The check for de_refcnt > 0 below insures the denode being + * examined does not represent an unlinked but still open file. + * These files are not to be accessible even when the directory + * entry that represented the file happens to be reused while the + * deleted file is still open. + */ + if (ldep = msdosfs_hashget(pmp->pm_dev, dirclust, diroffset)) { + *depp = ldep; + return (0); + } + + /* + * Directory entry was not in cache, have to create a vnode and + * copy it from the passed disk buffer. + */ + /* getnewvnode() does a VREF() on the vnode */ + if (error = getnewvnode(VT_MSDOSFS, pmp->pm_mountp, msdosfs_vnodeop_p, &nvp)) { + *depp = 0; + return (error); + } + MALLOC(ldep, struct denode *, sizeof(struct denode), M_MSDOSFSNODE, M_WAITOK); + bzero((caddr_t)ldep, sizeof *ldep); + nvp->v_data = ldep; + ldep->de_vnode = nvp; + ldep->de_flag = 0; + ldep->de_devvp = 0; + ldep->de_lockf = 0; + ldep->de_dev = pmp->pm_dev; + ldep->de_dirclust = dirclust; + ldep->de_diroffset = diroffset; + fc_purge(ldep, 0); /* init the fat cache for this denode */ + + /* + * Insert the denode into the hash queue and lock the denode so it + * can't be accessed until we've read it in and have done what we + * need to it. + */ + VOP_LOCK(nvp); + msdosfs_hashins(ldep); + + /* + * Copy the directory entry into the denode area of the vnode. + */ + if (dirclust == MSDOSFSROOT && diroffset == MSDOSFSROOT_OFS) { + /* + * Directory entry for the root directory. There isn't one, + * so we manufacture one. We should probably rummage + * through the root directory and find a label entry (if it + * exists), and then use the time and date from that entry + * as the time and date for the root denode. + */ + ldep->de_Attributes = ATTR_DIRECTORY; + ldep->de_StartCluster = MSDOSFSROOT; + ldep->de_FileSize = pmp->pm_rootdirsize * pmp->pm_BytesPerSec; + /* + * fill in time and date so that dos2unixtime() doesn't + * spit up when called from msdosfs_getattr() with root + * denode + */ + ldep->de_Time = 0x0000; /* 00:00:00 */ + ldep->de_Date = (0 << DD_YEAR_SHIFT) | (1 << DD_MONTH_SHIFT) + | (1 << DD_DAY_SHIFT); + /* Jan 1, 1980 */ + /* leave the other fields as garbage */ + } else { + bp = NULL; + if (!direntptr) { + error = readep(pmp, dirclust, diroffset, &bp, + &direntptr); + if (error) + return (error); + } + DE_INTERNALIZE(ldep, direntptr); + if (bp) + brelse(bp); + } + + /* + * Fill in a few fields of the vnode and finish filling in the + * denode. Then return the address of the found denode. + */ + ldep->de_pmp = pmp; + ldep->de_devvp = pmp->pm_devvp; + ldep->de_refcnt = 1; + if (ldep->de_Attributes & ATTR_DIRECTORY) { + /* + * Since DOS directory entries that describe directories + * have 0 in the filesize field, we take this opportunity + * to find out the length of the directory and plug it into + * the denode structure. + */ + u_long size; + + nvp->v_type = VDIR; + if (ldep->de_StartCluster == MSDOSFSROOT) + nvp->v_flag |= VROOT; + else { + error = pcbmap(ldep, 0xffff, 0, &size, 0); + if (error == E2BIG) { + ldep->de_FileSize = size << pmp->pm_cnshift; + error = 0; + } else + printf("deget(): pcbmap returned %d\n", error); + } + } else + nvp->v_type = VREG; + VREF(ldep->de_devvp); + *depp = ldep; + return (0); +} + +int +deupdat(dep, waitfor) + struct denode *dep; + int waitfor; +{ + int error; + struct buf *bp; + struct direntry *dirp; + struct vnode *vp = DETOV(dep); + +#ifdef MSDOSFS_DEBUG + printf("deupdat(): dep %08x\n", dep); +#endif + + /* If the time stamp needs updating, do it now. */ + DE_TIMES(dep); + + /* + * If the modified bit is off, or this denode is from a readonly + * filesystem, or the denode represents an open but unlinked file + * then don't do anything. DOS directory entries that describe a + * directory do not ever get updated. This is the way dos treats + * them. + */ + if ((dep->de_flag & DE_MODIFIED) == 0) + return (0); + + dep->de_flag &= ~DE_MODIFIED; + + if (dep->de_Attributes & ATTR_DIRECTORY) + panic("deupdat: directory"); + + if (vp->v_mount->mnt_flag & MNT_RDONLY || + dep->de_refcnt <= 0) + return (0); + + /* + * Read in the cluster containing the directory entry we want to + * update. + */ + if (error = readde(dep, &bp, &dirp)) + return (error); + + /* + * Copy the directory entry out of the denode into the cluster it + * came from. + */ + DE_EXTERNALIZE(dirp, dep); + + /* + * Write the cluster back to disk. If they asked for us to wait + * for the write to complete, then use bwrite() otherwise use + * bdwrite(). + */ + error = 0; /* note that error is 0 from above, but ... */ + if (waitfor) + error = bwrite(bp); + else + bdwrite(bp); + return (error); +} + +/* + * Truncate the file described by dep to the length specified by length. + */ +int +detrunc(dep, length, flags, cred, p) + struct denode *dep; + u_long length; + int flags; + struct ucred *cred; + struct proc *p; +{ + int error; + int allerror; + int vflags; + u_long eofentry; + u_long chaintofree; + daddr_t bn; + int boff; + int isadir = dep->de_Attributes & ATTR_DIRECTORY; + struct buf *bp; + struct msdosfsmount *pmp = dep->de_pmp; + +#ifdef MSDOSFS_DEBUG + printf("detrunc(): file %s, length %ld, flags %d\n", dep->de_Name, length, flags); +#endif + + /* + * Disallow attempts to truncate the root directory since it is of + * fixed size. That's just the way dos filesystems are. We use + * the VROOT bit in the vnode because checking for the directory + * bit and a startcluster of 0 in the denode is not adequate to + * recognize the root directory at this point in a file or + * directory's life. + */ + if (DETOV(dep)->v_flag & VROOT) { + printf("detrunc(): can't truncate root directory, clust %ld, offset %ld\n", + dep->de_dirclust, dep->de_diroffset); + return (EINVAL); + } + + vnode_pager_setsize(DETOV(dep), length); + + if (dep->de_FileSize < length) + return (deextend(dep, length, cred)); + + /* + * If the desired length is 0 then remember the starting cluster of + * the file and set the StartCluster field in the directory entry + * to 0. If the desired length is not zero, then get the number of + * the last cluster in the shortened file. Then get the number of + * the first cluster in the part of the file that is to be freed. + * Then set the next cluster pointer in the last cluster of the + * file to CLUST_EOFE. + */ + if (length == 0) { + chaintofree = dep->de_StartCluster; + dep->de_StartCluster = 0; + eofentry = ~0; + } else { + if (error = pcbmap(dep, de_clcount(pmp, length) - 1, 0, &eofentry, 0)) { +#ifdef MSDOSFS_DEBUG + printf("detrunc(): pcbmap fails %d\n", error); +#endif + return (error); + } + } + + fc_purge(dep, (length + pmp->pm_crbomask) >> pmp->pm_cnshift); + + /* + * If the new length is not a multiple of the cluster size then we + * must zero the tail end of the new last cluster in case it + * becomes part of the file again because of a seek. + */ + if ((boff = length & pmp->pm_crbomask) != 0) { + if (isadir) { + bn = cntobn(pmp, eofentry); + error = bread(pmp->pm_devvp, bn, pmp->pm_bpcluster, + NOCRED, &bp); + } else { + bn = de_blk(pmp, length); + error = bread(DETOV(dep), bn, pmp->pm_bpcluster, + NOCRED, &bp); + } + if (error) { +#ifdef MSDOSFS_DEBUG + printf("detrunc(): bread fails %d\n", error); +#endif + return (error); + } + vnode_pager_uncache(DETOV(dep)); /* what's this for? */ + /* + * is this the right place for it? + */ + bzero(bp->b_data + boff, pmp->pm_bpcluster - boff); + if (flags & IO_SYNC) + bwrite(bp); + else + bdwrite(bp); + } + + /* + * Write out the updated directory entry. Even if the update fails + * we free the trailing clusters. + */ + dep->de_FileSize = length; + if (!isadir) + dep->de_flag |= DE_UPDATE|DE_MODIFIED; + vflags = (length > 0 ? V_SAVE : 0) | V_SAVEMETA; + vinvalbuf(DETOV(dep), vflags, cred, p, 0, 0); + allerror = deupdat(dep, 1); +#ifdef MSDOSFS_DEBUG + printf("detrunc(): allerror %d, eofentry %d\n", + allerror, eofentry); +#endif + + /* + * If we need to break the cluster chain for the file then do it + * now. + */ + if (eofentry != ~0) { + if (error = fatentry(FAT_GET_AND_SET, pmp, eofentry, + &chaintofree, CLUST_EOFE)) { +#ifdef MSDOSFS_DEBUG + printf("detrunc(): fatentry errors %d\n", error); +#endif + return (error); + } + fc_setcache(dep, FC_LASTFC, (length - 1) >> pmp->pm_cnshift, + eofentry); + } + + /* + * Now free the clusters removed from the file because of the + * truncation. + */ + if (chaintofree != 0 && !MSDOSFSEOF(chaintofree)) + freeclusterchain(pmp, chaintofree); + + return (allerror); +} + +/* + * Extend the file described by dep to length specified by length. + */ +int +deextend(dep, length, cred) + struct denode *dep; + u_long length; + struct ucred *cred; +{ + struct msdosfsmount *pmp = dep->de_pmp; + u_long count; + int error; + + /* + * The root of a DOS filesystem cannot be extended. + */ + if (DETOV(dep)->v_flag & VROOT) + return (EINVAL); + + /* + * Directories can only be extended by the superuser. + * Is this really important? + */ + if (dep->de_Attributes & ATTR_DIRECTORY) { + if (error = suser(cred, (u_short *)0)) + return (error); + } + + if (length <= dep->de_FileSize) + panic("deextend: file too large"); + + /* + * Compute the number of clusters to allocate. + */ + count = de_clcount(pmp, length) - de_clcount(pmp, dep->de_FileSize); + if (count > 0) { + if (count > pmp->pm_freeclustercount) + return (ENOSPC); + if (error = extendfile(dep, count, NULL, NULL, DE_CLEAR)) { + /* truncate the added clusters away again */ + (void) detrunc(dep, dep->de_FileSize, 0, cred, NULL); + return (error); + } + } + + dep->de_FileSize = length; + dep->de_flag |= DE_UPDATE|DE_MODIFIED; + return (deupdat(dep, 1)); +} + +/* + * Move a denode to its correct hash queue after the file it represents has + * been moved to a new directory. + */ +void +reinsert(dep) + struct denode *dep; +{ + struct denode **depp, *deq; + + /* + * Fix up the denode cache. If the denode is for a directory, + * there is nothing to do since the hash is based on the starting + * cluster of the directory file and that hasn't changed. If for a + * file the hash is based on the location of the directory entry, + * so we must remove it from the cache and re-enter it with the + * hash based on the new location of the directory entry. + */ + if (dep->de_Attributes & ATTR_DIRECTORY) + return; + msdosfs_hashrem(dep); + msdosfs_hashins(dep); +} + +int +msdosfs_reclaim(ap) + struct vop_reclaim_args /* { + struct vnode *a_vp; + } */ *ap; +{ + struct vnode *vp = ap->a_vp; + struct denode *dep = VTODE(vp); + extern int prtactive; + +#ifdef MSDOSFS_DEBUG + printf("msdosfs_reclaim(): dep %08x, file %s, refcnt %d\n", + dep, dep->de_Name, dep->de_refcnt); +#endif + + if (prtactive && vp->v_usecount != 0) + vprint("msdosfs_reclaim(): pushing active", vp); + /* + * Remove the denode from its hash chain. + */ + msdosfs_hashrem(dep); + /* + * Purge old data structures associated with the denode. + */ + cache_purge(vp); + if (dep->de_devvp) { + vrele(dep->de_devvp); + dep->de_devvp = 0; + } +#if 0 /* XXX */ + dep->de_flag = 0; +#endif + FREE(dep, M_MSDOSFSNODE); + vp->v_data = NULL; + return (0); +} + +int +msdosfs_inactive(ap) + struct vop_inactive_args /* { + struct vnode *a_vp; + } */ *ap; +{ + struct vnode *vp = ap->a_vp; + struct denode *dep = VTODE(vp); + int error; + extern int prtactive; + +#ifdef MSDOSFS_DEBUG + printf("msdosfs_inactive(): dep %08x, de_Name[0] %x\n", dep, dep->de_Name[0]); +#endif + + if (prtactive && vp->v_usecount != 0) + vprint("msdosfs_inactive(): pushing active", vp); + + /* + * Get rid of denodes related to stale file handles. + */ + if (dep->de_Name[0] == SLOT_DELETED) { + if ((vp->v_flag & VXLOCK) == 0) + vgone(vp); + return (0); + } + + error = 0; +#ifdef DIAGNOSTIC + if (VOP_ISLOCKED(vp)) + panic("msdosfs_inactive: locked denode"); + if (curproc) + dep->de_lockholder = curproc->p_pid; + else + dep->de_lockholder = -1; +#endif + dep->de_flag |= DE_LOCKED; + /* + * If the file has been deleted and it is on a read/write + * filesystem, then truncate the file, and mark the directory slot + * as empty. (This may not be necessary for the dos filesystem.) + */ +#ifdef MSDOSFS_DEBUG + printf("msdosfs_inactive(): dep %08x, refcnt %d, mntflag %x, MNT_RDONLY %x\n", + dep, dep->de_refcnt, vp->v_mount->mnt_flag, MNT_RDONLY); +#endif + if (dep->de_refcnt <= 0 && (vp->v_mount->mnt_flag & MNT_RDONLY) == 0) + error = detrunc(dep, (u_long)0, 0, NOCRED, NULL); + deupdat(dep, 0); + VOP_UNLOCK(vp); + /* + * If we are done with the denode, reclaim it + * so that it can be reused immediately. + */ +#ifdef MSDOSFS_DEBUG + printf("msdosfs_inactive(): v_usecount %d, de_Name[0] %x\n", vp->v_usecount, + dep->de_Name[0]); +#endif + if (vp->v_usecount == 0 && dep->de_Name[0] == SLOT_DELETED) + vgone(vp); + return (error); +} diff --git a/sys/msdosfs/msdosfs_fat.c b/sys/msdosfs/msdosfs_fat.c new file mode 100644 index 00000000000..a7ec896bb75 --- /dev/null +++ b/sys/msdosfs/msdosfs_fat.c @@ -0,0 +1,983 @@ +/* $NetBSD: msdosfs_fat.c,v 1.19 1995/09/09 19:38:04 ws Exp $ */ + +/*- + * Copyright (C) 1994 Wolfgang Solfrank. + * Copyright (C) 1994 TooLs GmbH. + * All rights reserved. + * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below). + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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. + */ +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +/* + * kernel include files. + */ +#include <sys/param.h> +#include <sys/systm.h> +#include <sys/buf.h> +#include <sys/file.h> +#include <sys/namei.h> +#include <sys/mount.h> /* to define statfs structure */ +#include <sys/vnode.h> /* to define vattr structure */ +#include <sys/errno.h> + +/* + * msdosfs include files. + */ +#include <msdosfs/bpb.h> +#include <msdosfs/msdosfsmount.h> +#include <msdosfs/direntry.h> +#include <msdosfs/denode.h> +#include <msdosfs/fat.h> + +/* + * Fat cache stats. + */ +int fc_fileextends; /* # of file extends */ +int fc_lfcempty; /* # of time last file cluster cache entry + * was empty */ +int fc_bmapcalls; /* # of times pcbmap was called */ + +#define LMMAX 20 +int fc_lmdistance[LMMAX]; /* counters for how far off the last + * cluster mapped entry was. */ +int fc_largedistance; /* off by more than LMMAX */ + +/* Byte offset in FAT on filesystem pmp, cluster cn */ +#define FATOFS(pmp, cn) (FAT12(pmp) ? (cn) * 3 / 2 : (cn) * 2) + +static void +fatblock(pmp, ofs, bnp, sizep, bop) + struct msdosfsmount *pmp; + u_long ofs; + u_long *bnp; + u_long *sizep; + u_long *bop; +{ + u_long bn, size; + + bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec; + size = min(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn) + * pmp->pm_BytesPerSec; + bn += pmp->pm_fatblk; + if (bnp) + *bnp = bn; + if (sizep) + *sizep = size; + if (bop) + *bop = ofs % pmp->pm_fatblocksize; +} + +/* + * Map the logical cluster number of a file into a physical disk sector + * that is filesystem relative. + * + * dep - address of denode representing the file of interest + * findcn - file relative cluster whose filesystem relative cluster number + * and/or block number are/is to be found + * bnp - address of where to place the file system relative block number. + * If this pointer is null then don't return this quantity. + * cnp - address of where to place the file system relative cluster number. + * If this pointer is null then don't return this quantity. + * + * NOTE: Either bnp or cnp must be non-null. + * This function has one side effect. If the requested file relative cluster + * is beyond the end of file, then the actual number of clusters in the file + * is returned in *cnp. This is useful for determining how long a directory is. + * If cnp is null, nothing is returned. + */ +int +pcbmap(dep, findcn, bnp, cnp, sp) + struct denode *dep; + u_long findcn; /* file relative cluster to get */ + daddr_t *bnp; /* returned filesys relative blk number */ + u_long *cnp; /* returned cluster number */ + int *sp; /* returned block size */ +{ + int error; + u_long i; + u_long cn; + u_long prevcn; + u_long byteoffset; + u_long bn; + u_long bo; + struct buf *bp = NULL; + u_long bp_bn = -1; + struct msdosfsmount *pmp = dep->de_pmp; + u_long bsize; + int fat12 = FAT12(pmp); /* 12 bit fat */ + + fc_bmapcalls++; + + /* + * If they don't give us someplace to return a value then don't + * bother doing anything. + */ + if (bnp == NULL && cnp == NULL && sp == NULL) + return (0); + + cn = dep->de_StartCluster; + /* + * The "file" that makes up the root directory is contiguous, + * permanently allocated, of fixed size, and is not made up of + * clusters. If the cluster number is beyond the end of the root + * directory, then return the number of clusters in the file. + */ + if (cn == MSDOSFSROOT) { + if (dep->de_Attributes & ATTR_DIRECTORY) { + if (findcn * pmp->pm_SectPerClust >= pmp->pm_rootdirsize) { + if (cnp) + *cnp = pmp->pm_rootdirsize / pmp->pm_SectPerClust; + return (E2BIG); + } + if (bnp) + *bnp = pmp->pm_rootdirblk + findcn * pmp->pm_SectPerClust; + if (cnp) + *cnp = MSDOSFSROOT; + if (sp) + *sp = min(pmp->pm_bpcluster, + dep->de_FileSize - findcn * pmp->pm_bpcluster); + return (0); + } else { /* just an empty file */ + if (cnp) + *cnp = 0; + return (E2BIG); + } + } + + /* + * All other files do I/O in cluster sized blocks + */ + if (sp) + *sp = pmp->pm_bpcluster; + + /* + * Rummage around in the fat cache, maybe we can avoid tromping + * thru every fat entry for the file. And, keep track of how far + * off the cache was from where we wanted to be. + */ + i = 0; + fc_lookup(dep, findcn, &i, &cn); + if ((bn = findcn - i) >= LMMAX) + fc_largedistance++; + else + fc_lmdistance[bn]++; + + /* + * Handle all other files or directories the normal way. + */ + for (; i < findcn; i++) { + if (MSDOSFSEOF(cn)) + goto hiteof; + byteoffset = FATOFS(pmp, cn); + fatblock(pmp, byteoffset, &bn, &bsize, &bo); + if (bn != bp_bn) { + if (bp) + brelse(bp); + if (error = bread(pmp->pm_devvp, bn, bsize, NOCRED, + &bp)) + return (error); + bp_bn = bn; + } + prevcn = cn; + cn = getushort(&bp->b_data[bo]); + if (fat12) { + if (prevcn & 1) + cn >>= 4; + cn &= 0x0fff; + /* + * Force the special cluster numbers in the range + * 0x0ff0-0x0fff to be the same as for 16 bit + * cluster numbers to let the rest of msdosfs think + * it is always dealing with 16 bit fats. + */ + if ((cn & 0x0ff0) == 0x0ff0) + cn |= 0xf000; + } + } + + if (!MSDOSFSEOF(cn)) { + if (bp) + brelse(bp); + if (bnp) + *bnp = cntobn(pmp, cn); + if (cnp) + *cnp = cn; + fc_setcache(dep, FC_LASTMAP, i, cn); + return (0); + } + +hiteof:; + if (cnp) + *cnp = i; + if (bp) + brelse(bp); + /* update last file cluster entry in the fat cache */ + fc_setcache(dep, FC_LASTFC, i - 1, prevcn); + return (E2BIG); +} + +/* + * Find the closest entry in the fat cache to the cluster we are looking + * for. + */ +void +fc_lookup(dep, findcn, frcnp, fsrcnp) + struct denode *dep; + u_long findcn; + u_long *frcnp; + u_long *fsrcnp; +{ + int i; + u_long cn; + struct fatcache *closest = 0; + + for (i = 0; i < FC_SIZE; i++) { + cn = dep->de_fc[i].fc_frcn; + if (cn != FCE_EMPTY && cn <= findcn) { + if (closest == 0 || cn > closest->fc_frcn) + closest = &dep->de_fc[i]; + } + } + if (closest) { + *frcnp = closest->fc_frcn; + *fsrcnp = closest->fc_fsrcn; + } +} + +/* + * Purge the fat cache in denode dep of all entries relating to file + * relative cluster frcn and beyond. + */ +void +fc_purge(dep, frcn) + struct denode *dep; + u_int frcn; +{ + int i; + struct fatcache *fcp; + + fcp = dep->de_fc; + for (i = 0; i < FC_SIZE; i++, fcp++) { + if (fcp->fc_frcn >= frcn) + fcp->fc_frcn = FCE_EMPTY; + } +} + +/* + * Update all copies of the fat. The first copy is updated last. + * + * pmp - msdosfsmount structure for filesystem to update + * bp - addr of modified fat block + * fatbn - block number relative to begin of filesystem of the modified fat block. + */ +void +updatefats(pmp, bp, fatbn) + struct msdosfsmount *pmp; + struct buf *bp; + u_long fatbn; +{ + int i; + struct buf *bpn; + +#ifdef MSDOSFS_DEBUG + printf("updatefats(pmp %08x, bp %08x, fatbn %d)\n", + pmp, bp, fatbn); +#endif + + /* + * Now copy the block(s) of the modified fat to the other copies of + * the fat and write them out. This is faster than reading in the + * other fats and then writing them back out. This could tie up + * the fat for quite a while. Preventing others from accessing it. + * To prevent us from going after the fat quite so much we use + * delayed writes, unless they specfied "synchronous" when the + * filesystem was mounted. If synch is asked for then use + * bwrite()'s and really slow things down. + */ + for (i = 1; i < pmp->pm_FATs; i++) { + fatbn += pmp->pm_FATsecs; + /* getblk() never fails */ + bpn = getblk(pmp->pm_devvp, fatbn, bp->b_bcount, 0, 0); + bcopy(bp->b_data, bpn->b_data, bp->b_bcount); + if (pmp->pm_waitonfat) + bwrite(bpn); + else + bdwrite(bpn); + } + /* + * Write out the first fat last. + */ + if (pmp->pm_waitonfat) + bwrite(bp); + else + bdwrite(bp); +} + +/* + * Updating entries in 12 bit fats is a pain in the butt. + * + * The following picture shows where nibbles go when moving from a 12 bit + * cluster number into the appropriate bytes in the FAT. + * + * byte m byte m+1 byte m+2 + * +----+----+ +----+----+ +----+----+ + * | 0 1 | | 2 3 | | 4 5 | FAT bytes + * +----+----+ +----+----+ +----+----+ + * + * +----+----+----+ +----+----+----+ + * | 3 0 1 | | 4 5 2 | + * +----+----+----+ +----+----+----+ + * cluster n cluster n+1 + * + * Where n is even. m = n + (n >> 2) + * + */ +static __inline void +usemap_alloc(pmp, cn) + struct msdosfsmount *pmp; + u_long cn; +{ + + pmp->pm_inusemap[cn / N_INUSEBITS] |= 1 << (cn % N_INUSEBITS); + pmp->pm_freeclustercount--; +} + +static __inline void +usemap_free(pmp, cn) + struct msdosfsmount *pmp; + u_long cn; +{ + + pmp->pm_freeclustercount++; + pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS)); +} + +int +clusterfree(pmp, cluster, oldcnp) + struct msdosfsmount *pmp; + u_long cluster; + u_long *oldcnp; +{ + int error; + u_long oldcn; + + if (error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE)) + return (error); + /* + * If the cluster was successfully marked free, then update + * the count of free clusters, and turn off the "allocated" + * bit in the "in use" cluster bit map. + */ + usemap_free(pmp, cluster); + if (oldcnp) + *oldcnp = oldcn; + return (0); +} + +/* + * Get or Set or 'Get and Set' the cluster'th entry in the fat. + * + * function - whether to get or set a fat entry + * pmp - address of the msdosfsmount structure for the filesystem + * whose fat is to be manipulated. + * cn - which cluster is of interest + * oldcontents - address of a word that is to receive the contents of the + * cluster'th entry if this is a get function + * newcontents - the new value to be written into the cluster'th element of + * the fat if this is a set function. + * + * This function can also be used to free a cluster by setting the fat entry + * for a cluster to 0. + * + * All copies of the fat are updated if this is a set function. NOTE: If + * fatentry() marks a cluster as free it does not update the inusemap in + * the msdosfsmount structure. This is left to the caller. + */ +int +fatentry(function, pmp, cn, oldcontents, newcontents) + int function; + struct msdosfsmount *pmp; + u_long cn; + u_long *oldcontents; + u_long newcontents; +{ + int error; + u_long readcn; + u_long bn, bo, bsize, byteoffset; + struct buf *bp; + + /* + * printf("fatentry(func %d, pmp %08x, clust %d, oldcon %08x, newcon %d)\n", + * function, pmp, cluster, oldcontents, newcontents); + */ + +#ifdef DIAGNOSTIC + /* + * Be sure they asked us to do something. + */ + if ((function & (FAT_SET | FAT_GET)) == 0) { + printf("fatentry(): function code doesn't specify get or set\n"); + return (EINVAL); + } + + /* + * If they asked us to return a cluster number but didn't tell us + * where to put it, give them an error. + */ + if ((function & FAT_GET) && oldcontents == NULL) { + printf("fatentry(): get function with no place to put result\n"); + return (EINVAL); + } +#endif + + /* + * Be sure the requested cluster is in the filesystem. + */ + if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster) + return (EINVAL); + + byteoffset = FATOFS(pmp, cn); + fatblock(pmp, byteoffset, &bn, &bsize, &bo); + if (error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp)) + return (error); + + if (function & FAT_GET) { + readcn = getushort(&bp->b_data[bo]); + if (FAT12(pmp)) { + if (cn & 1) + readcn >>= 4; + readcn &= 0x0fff; + /* map certain 12 bit fat entries to 16 bit */ + if ((readcn & 0x0ff0) == 0x0ff0) + readcn |= 0xf000; + } + *oldcontents = readcn; + } + if (function & FAT_SET) { + if (FAT12(pmp)) { + readcn = getushort(&bp->b_data[bo]); + if (cn & 1) { + readcn &= 0x000f; + readcn |= newcontents << 4; + } else { + readcn &= 0xf000; + readcn |= newcontents & 0xfff; + } + putushort(&bp->b_data[bo], readcn); + } else + putushort(&bp->b_data[bo], newcontents); + updatefats(pmp, bp, bn); + bp = NULL; + pmp->pm_fmod = 1; + } + if (bp) + brelse(bp); + return (0); +} + +/* + * Update a contiguous cluster chain + * + * pmp - mount point + * start - first cluster of chain + * count - number of clusters in chain + * fillwith - what to write into fat entry of last cluster + */ +static int +fatchain(pmp, start, count, fillwith) + struct msdosfsmount *pmp; + u_long start; + u_long count; + u_long fillwith; +{ + int error; + u_long bn, bo, bsize, byteoffset, readcn, newc; + struct buf *bp; + +#ifdef MSDOSFS_DEBUG + printf("fatchain(pmp %08x, start %d, count %d, fillwith %d)\n", + pmp, start, count, fillwith); +#endif + /* + * Be sure the clusters are in the filesystem. + */ + if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster) + return (EINVAL); + + while (count > 0) { + byteoffset = FATOFS(pmp, start); + fatblock(pmp, byteoffset, &bn, &bsize, &bo); + if (error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp)) + return (error); + while (count > 0) { + start++; + newc = --count > 0 ? start : fillwith; + if (FAT12(pmp)) { + readcn = getushort(&bp->b_data[bo]); + if (start & 1) { + readcn &= 0xf000; + readcn |= newc & 0xfff; + } else { + readcn &= 0x000f; + readcn |= newc << 4; + } + putushort(&bp->b_data[bo], readcn); + bo++; + if (!(start & 1)) + bo++; + } else { + putushort(&bp->b_data[bo], newc); + bo += 2; + } + if (bo >= bsize) + break; + } + updatefats(pmp, bp, bn); + } + pmp->pm_fmod = 1; + return (0); +} + +/* + * Check the length of a free cluster chain starting at start. + * + * pmp - mount point + * start - start of chain + * count - maximum interesting length + */ +int +chainlength(pmp, start, count) + struct msdosfsmount *pmp; + u_long start; + u_long count; +{ + u_long idx, max_idx; + u_int map; + u_long len; + + max_idx = pmp->pm_maxcluster / N_INUSEBITS; + idx = start / N_INUSEBITS; + start %= N_INUSEBITS; + map = pmp->pm_inusemap[idx]; + map &= ~((1 << start) - 1); + if (map) { + len = ffs(map) - 1 - start; + return (len > count ? count : len); + } + len = N_INUSEBITS - start; + if (len >= count) + return (count); + while (++idx <= max_idx) { + if (len >= count) + break; + if (map = pmp->pm_inusemap[idx]) { + len += ffs(map) - 1; + break; + } + len += N_INUSEBITS; + } + return (len > count ? count : len); +} + +/* + * Allocate contigous free clusters. + * + * pmp - mount point. + * start - start of cluster chain. + * count - number of clusters to allocate. + * fillwith - put this value into the fat entry for the + * last allocated cluster. + * retcluster - put the first allocated cluster's number here. + * got - how many clusters were actually allocated. + */ +int +chainalloc(pmp, start, count, fillwith, retcluster, got) + struct msdosfsmount *pmp; + u_long start; + u_long count; + u_long fillwith; + u_long *retcluster; + u_long *got; +{ + int error; + + if (error = fatchain(pmp, start, count, fillwith)) + return (error); +#ifdef MSDOSFS_DEBUG + printf("clusteralloc(): allocated cluster chain at %d (%d clusters)\n", + start, count); +#endif + if (retcluster) + *retcluster = start; + if (got) + *got = count; + while (count-- > 0) + usemap_alloc(pmp, start++); + return (0); +} + +/* + * Allocate contiguous free clusters. + * + * pmp - mount point. + * start - preferred start of cluster chain. + * count - number of clusters requested. + * fillwith - put this value into the fat entry for the + * last allocated cluster. + * retcluster - put the first allocated cluster's number here. + * got - how many clusters were actually allocated. + */ +int +clusteralloc(pmp, start, count, fillwith, retcluster, got) + struct msdosfsmount *pmp; + u_long start; + u_long count; + u_long fillwith; + u_long *retcluster; + u_long *got; +{ + u_long idx; + u_long len, newst, foundcn, foundl, cn, l; + u_int map; + +#ifdef MSDOSFS_DEBUG + printf("clusteralloc(): find %d clusters\n",count); +#endif + if (start) { + if ((len = chainlength(pmp, start, count)) >= count) + return (chainalloc(pmp, start, count, fillwith, retcluster, got)); + } else { + /* + * This is a new file, initialize start + */ + struct timeval tv; + + microtime(&tv); + start = (tv.tv_usec >> 10) | tv.tv_usec; + len = 0; + } + + /* + * Start at a (pseudo) random place to maximize cluster runs + * under multiple writers. + */ + newst = (start * 1103515245 + 12345) % (pmp->pm_maxcluster + 1); + foundl = 0; + + for (cn = newst; cn <= pmp->pm_maxcluster;) { + idx = cn / N_INUSEBITS; + map = pmp->pm_inusemap[idx]; + map |= (1 << (cn % N_INUSEBITS)) - 1; + if (map != (u_int)-1) { + cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1; + if ((l = chainlength(pmp, cn, count)) >= count) + return (chainalloc(pmp, cn, count, fillwith, retcluster, got)); + if (l > foundl) { + foundcn = cn; + foundl = l; + } + cn += l + 1; + continue; + } + cn += N_INUSEBITS - cn % N_INUSEBITS; + } + for (cn = 0; cn < newst;) { + idx = cn / N_INUSEBITS; + map = pmp->pm_inusemap[idx]; + map |= (1 << (cn % N_INUSEBITS)) - 1; + if (map != (u_int)-1) { + cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1; + if ((l = chainlength(pmp, cn, count)) >= count) + return (chainalloc(pmp, cn, count, fillwith, retcluster, got)); + if (l > foundl) { + foundcn = cn; + foundl = l; + } + cn += l + 1; + continue; + } + cn += N_INUSEBITS - cn % N_INUSEBITS; + } + + if (!foundl) + return (ENOSPC); + + if (len) + return (chainalloc(pmp, start, len, fillwith, retcluster, got)); + else + return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got)); +} + + +/* + * Free a chain of clusters. + * + * pmp - address of the msdosfs mount structure for the filesystem + * containing the cluster chain to be freed. + * startcluster - number of the 1st cluster in the chain of clusters to be + * freed. + */ +int +freeclusterchain(pmp, cluster) + struct msdosfsmount *pmp; + u_long cluster; +{ + int error; + struct buf *bp = NULL; + u_long bn, bo, bsize, byteoffset; + u_long readcn, lbn = -1; + + while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) { + byteoffset = FATOFS(pmp, cluster); + fatblock(pmp, byteoffset, &bn, &bsize, &bo); + if (lbn != bn) { + if (bp) + updatefats(pmp, bp, lbn); + if (error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp)) + return (error); + lbn = bn; + } + usemap_free(pmp, cluster); + readcn = getushort(&bp->b_data[bo]); + if (FAT12(pmp)) { + if (cluster & 1) { + cluster = readcn >> 4; + readcn &= 0x000f; + readcn |= MSDOSFSFREE << 4; + } else { + cluster = readcn; + readcn &= 0xf000; + readcn |= MSDOSFSFREE & 0xfff; + } + putushort(&bp->b_data[bo], readcn); + cluster &= 0x0fff; + if ((cluster&0x0ff0) == 0x0ff0) + cluster |= 0xf000; + } else { + cluster = readcn; + putushort(&bp->b_data[bo], MSDOSFSFREE); + } + } + if (bp) + updatefats(pmp, bp, bn); + return (0); +} + +/* + * Read in fat blocks looking for free clusters. For every free cluster + * found turn off its corresponding bit in the pm_inusemap. + */ +int +fillinusemap(pmp) + struct msdosfsmount *pmp; +{ + struct buf *bp = NULL; + u_long cn, readcn; + int error; + int fat12 = FAT12(pmp); + u_long bn, bo, bsize, byteoffset; + + /* + * Mark all clusters in use, we mark the free ones in the fat scan + * loop further down. + */ + for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++) + pmp->pm_inusemap[cn] = (u_int)-1; + + /* + * Figure how many free clusters are in the filesystem by ripping + * through the fat counting the number of entries whose content is + * zero. These represent free clusters. + */ + pmp->pm_freeclustercount = 0; + for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) { + byteoffset = FATOFS(pmp, cn); + bo = byteoffset % pmp->pm_fatblocksize; + if (!bo || !bp) { + /* Read new FAT block */ + if (bp) + brelse(bp); + fatblock(pmp, byteoffset, &bn, &bsize, NULL); + if (error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp)) + return (error); + } + readcn = getushort(&bp->b_data[bo]); + if (fat12) { + if (cn & 1) + readcn >>= 4; + readcn &= 0x0fff; + } + + if (readcn == 0) + usemap_free(pmp, cn); + } + brelse(bp); + return (0); +} + +/* + * Allocate a new cluster and chain it onto the end of the file. + * + * dep - the file to extend + * count - number of clusters to allocate + * bpp - where to return the address of the buf header for the first new + * file block + * ncp - where to put cluster number of the first newly allocated cluster + * If this pointer is 0, do not return the cluster number. + * flags - see fat.h + * + * NOTE: This function is not responsible for turning on the DE_UPDATE bit of + * the de_flag field of the denode and it does not change the de_FileSize + * field. This is left for the caller to do. + */ +int +extendfile(dep, count, bpp, ncp, flags) + struct denode *dep; + u_long count; + struct buf **bpp; + u_long *ncp; + int flags; +{ + int error; + u_long frcn; + u_long cn, got; + struct msdosfsmount *pmp = dep->de_pmp; + struct buf *bp; + + /* + * Don't try to extend the root directory + */ + if (DETOV(dep)->v_flag & VROOT) { + printf("extendfile(): attempt to extend root directory\n"); + return (ENOSPC); + } + + /* + * If the "file's last cluster" cache entry is empty, and the file + * is not empty, then fill the cache entry by calling pcbmap(). + */ + fc_fileextends++; + if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY && + dep->de_StartCluster != 0) { + fc_lfcempty++; + error = pcbmap(dep, 0xffff, 0, &cn, 0); + /* we expect it to return E2BIG */ + if (error != E2BIG) + return (error); + } + + while (count > 0) { + /* + * Allocate a new cluster chain and cat onto the end of the file. + * If the file is empty we make de_StartCluster point to the new + * block. Note that de_StartCluster being 0 is sufficient to be + * sure the file is empty since we exclude attempts to extend the + * root directory above, and the root dir is the only file with a + * startcluster of 0 that has blocks allocated (sort of). + */ + if (dep->de_StartCluster == 0) + cn = 0; + else + cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1; + if (error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got)) + return (error); + + count -= got; + + /* + * Give them the filesystem relative cluster number if they want + * it. + */ + if (ncp) { + *ncp = cn; + ncp = NULL; + } + + if (dep->de_StartCluster == 0) { + dep->de_StartCluster = cn; + frcn = 0; + } else { + if (error = fatentry(FAT_SET, pmp, + dep->de_fc[FC_LASTFC].fc_fsrcn, + 0, cn)) { + clusterfree(pmp, cn, NULL); + return (error); + } + frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1; + } + + /* + * Update the "last cluster of the file" entry in the denode's fat + * cache. + */ + fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1); + + if (flags & DE_CLEAR) { + while (got-- > 0) { + /* + * Get the buf header for the new block of the file. + */ + if (dep->de_Attributes & ATTR_DIRECTORY) + bp = getblk(pmp->pm_devvp, cntobn(pmp, cn++), + pmp->pm_bpcluster, 0, 0); + else { + bp = getblk(DETOV(dep), frcn++, pmp->pm_bpcluster, 0, 0); + /* + * Do the bmap now, as in msdosfs_write + */ + if (pcbmap(dep, bp->b_lblkno, &bp->b_blkno, 0, 0)) + bp->b_blkno = -1; + if (bp->b_blkno == -1) + panic("extendfile: pcbmap"); + } + clrbuf(bp); + if (bpp) { + *bpp = bp; + bpp = NULL; + } else + bdwrite(bp); + } + } + } + + return (0); +} diff --git a/sys/msdosfs/msdosfs_lookup.c b/sys/msdosfs/msdosfs_lookup.c new file mode 100644 index 00000000000..712a7f47e73 --- /dev/null +++ b/sys/msdosfs/msdosfs_lookup.c @@ -0,0 +1,847 @@ +/* $NetBSD: msdosfs_lookup.c,v 1.17 1995/09/09 19:38:06 ws Exp $ */ + +/*- + * Copyright (C) 1994 Wolfgang Solfrank. + * Copyright (C) 1994 TooLs GmbH. + * All rights reserved. + * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below). + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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. + */ +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +#include <sys/param.h> +#include <sys/namei.h> +#include <sys/buf.h> +#include <sys/vnode.h> +#include <sys/mount.h> + +#include <msdosfs/bpb.h> +#include <msdosfs/direntry.h> +#include <msdosfs/denode.h> +#include <msdosfs/msdosfsmount.h> +#include <msdosfs/fat.h> + +/* + * When we search a directory the blocks containing directory entries are + * read and examined. The directory entries contain information that would + * normally be in the inode of a unix filesystem. This means that some of + * a directory's contents may also be in memory resident denodes (sort of + * an inode). This can cause problems if we are searching while some other + * process is modifying a directory. To prevent one process from accessing + * incompletely modified directory information we depend upon being the + * soul owner of a directory block. bread/brelse provide this service. + * This being the case, when a process modifies a directory it must first + * acquire the disk block that contains the directory entry to be modified. + * Then update the disk block and the denode, and then write the disk block + * out to disk. This way disk blocks containing directory entries and in + * memory denode's will be in synch. + */ +int +msdosfs_lookup(ap) + struct vop_lookup_args /* { + struct vnode *a_dvp; + struct vnode **a_vpp; + struct componentname *a_cnp; + } */ *ap; +{ + struct vnode *vdp = ap->a_dvp; + struct vnode **vpp = ap->a_vpp; + struct componentname *cnp = ap->a_cnp; + daddr_t bn; + int error; + int lockparent; + int wantparent; + int slotstatus; + +#define NONE 0 +#define FOUND 1 + int slotoffset; + int slotcluster; + int frcn; + u_long cluster; + int rootreloff; + int diroff; + int blsize; + int isadir; /* ~0 if found direntry is a directory */ + u_long scn; /* starting cluster number */ + struct vnode *pdp; + struct denode *dp; + struct denode *tdp; + struct msdosfsmount *pmp; + struct buf *bp = 0; + struct direntry *dep; + u_char dosfilename[12]; + int flags = cnp->cn_flags; + int nameiop = cnp->cn_nameiop; + +#ifdef MSDOSFS_DEBUG + printf("msdosfs_lookup(): looking for %s\n", cnp->cn_nameptr); +#endif + dp = VTODE(vdp); + pmp = dp->de_pmp; + *vpp = NULL; + lockparent = flags & LOCKPARENT; + wantparent = flags & (LOCKPARENT | WANTPARENT); +#ifdef MSDOSFS_DEBUG + printf("msdosfs_lookup(): vdp %08x, dp %08x, Attr %02x\n", + vdp, dp, dp->de_Attributes); +#endif + + /* + * Check accessiblity of directory. + */ + if ((dp->de_Attributes & ATTR_DIRECTORY) == 0) + return (ENOTDIR); + if (error = VOP_ACCESS(vdp, VEXEC, cnp->cn_cred, cnp->cn_proc)) + return (error); + + /* + * We now have a segment name to search for, and a directory to search. + * + * Before tediously performing a linear scan of the directory, + * check the name cache to see if the directory/name pair + * we are looking for is known already. + */ + if (error = cache_lookup(vdp, vpp, cnp)) { + int vpid; + + if (error == ENOENT) + return (error); + /* + * Get the next vnode in the path. + * See comment below starting `Step through' for + * an explaination of the locking protocol. + */ + pdp = vdp; + dp = VTODE(*vpp); + vdp = *vpp; + vpid = vdp->v_id; + if (pdp == vdp) { /* lookup on "." */ + VREF(vdp); + error = 0; + } else if (flags & ISDOTDOT) { + VOP_UNLOCK(pdp); + error = vget(vdp, 1); + if (!error && lockparent && (flags & ISLASTCN)) + error = VOP_LOCK(pdp); + } else { + error = vget(vdp, 1); + if (!lockparent || error || !(flags & ISLASTCN)) + VOP_UNLOCK(pdp); + } + /* + * Check that the capability number did not change + * while we were waiting for the lock. + */ + if (!error) { + if (vpid == vdp->v_id) { +#ifdef MSDOSFS_DEBUG + printf("msdosfs_lookup(): cache hit, vnode %08x, file %s\n", + vdp, dp->de_Name); +#endif + return (0); + } + vput(vdp); + if (lockparent && pdp != vdp && (flags & ISLASTCN)) + VOP_UNLOCK(pdp); + } + if (error = VOP_LOCK(pdp)) + return (error); + vdp = pdp; + dp = VTODE(vdp); + *vpp = NULL; + } + + /* + * If they are going after the . or .. entry in the root directory, + * they won't find it. DOS filesystems don't have them in the root + * directory. So, we fake it. deget() is in on this scam too. + */ + if ((vdp->v_flag & VROOT) && cnp->cn_nameptr[0] == '.' && + (cnp->cn_namelen == 1 || + (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.'))) { + isadir = ATTR_DIRECTORY; + scn = MSDOSFSROOT; +#ifdef MSDOSFS_DEBUG + printf("msdosfs_lookup(): looking for . or .. in root directory\n"); +#endif + cluster = MSDOSFSROOT; + diroff = MSDOSFSROOT_OFS; + goto foundroot; + } + + /* + * Suppress search for slots unless creating + * file and at end of pathname, in which case + * we watch for a place to put the new file in + * case it doesn't already exist. + */ + slotstatus = FOUND; + if ((nameiop == CREATE || nameiop == RENAME) && + (flags & ISLASTCN)) { + slotstatus = NONE; + slotoffset = -1; + } + + unix2dosfn((u_char *)cnp->cn_nameptr, dosfilename, cnp->cn_namelen); + dosfilename[11] = 0; +#ifdef MSDOSFS_DEBUG + printf("msdosfs_lookup(): dos version of filename %s, length %d\n", + dosfilename, cnp->cn_namelen); +#endif + /* + * Search the directory pointed at by vdp for the name pointed at + * by cnp->cn_nameptr. + */ + tdp = NULL; + /* + * The outer loop ranges over the clusters that make up the + * directory. Note that the root directory is different from all + * other directories. It has a fixed number of blocks that are not + * part of the pool of allocatable clusters. So, we treat it a + * little differently. The root directory starts at "cluster" 0. + */ + rootreloff = 0; + for (frcn = 0;; frcn++) { + if (error = pcbmap(dp, frcn, &bn, &cluster, &blsize)) { + if (error == E2BIG) + break; + return (error); + } + if (error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp)) + return (error); + for (diroff = 0; diroff < blsize; + diroff += sizeof(struct direntry), + rootreloff += sizeof(struct direntry)) { + dep = (struct direntry *)(bp->b_data + diroff); + /* + * If the slot is empty and we are still looking + * for an empty then remember this one. If the + * slot is not empty then check to see if it + * matches what we are looking for. If the slot + * has never been filled with anything, then the + * remainder of the directory has never been used, + * so there is no point in searching it. + */ + if (dep->deName[0] == SLOT_EMPTY || + dep->deName[0] == SLOT_DELETED) { + if (slotstatus != FOUND) { + slotstatus = FOUND; + if (cluster == MSDOSFSROOT) + slotoffset = rootreloff; + else + slotoffset = diroff; + slotcluster = cluster; + } + if (dep->deName[0] == SLOT_EMPTY) { + brelse(bp); + goto notfound; + } + } else { + /* + * Ignore volume labels (anywhere, not just + * the root directory). + */ + if (dep->deAttributes & ATTR_VOLUME) + continue; + /* + * Check for a name match. + */ + if (bcmp(dosfilename, dep->deName, 11)) + continue; +#ifdef MSDOSFS_DEBUG + printf("msdosfs_lookup(): match diroff %d, rootreloff %d\n", + diroff, rootreloff); +#endif + /* + * Remember where this directory + * entry came from for whoever did + * this lookup. If this is the root + * directory we are interested in + * the offset relative to the + * beginning of the directory (not + * the beginning of the cluster). + */ + if (cluster == MSDOSFSROOT) + diroff = rootreloff; + dp->de_fndoffset = diroff; + dp->de_fndclust = cluster; + goto found; + } + } /* for (diroff = 0; .... */ + /* + * Release the buffer holding the directory cluster just + * searched. + */ + brelse(bp); + } /* for (frcn = 0; ; frcn++) */ + +notfound:; + /* + * We hold no disk buffers at this point. + */ + + /* + * If we get here we didn't find the entry we were looking for. But + * that's ok if we are creating or renaming and are at the end of + * the pathname and the directory hasn't been removed. + */ +#ifdef MSDOSFS_DEBUG + printf("msdosfs_lookup(): op %d, refcnt %d, slotstatus %d\n", + nameiop, dp->de_refcnt, slotstatus); + printf(" slotoffset %d, slotcluster %d\n", + slotoffset, slotcluster); +#endif + if ((nameiop == CREATE || nameiop == RENAME) && + (flags & ISLASTCN) && dp->de_refcnt != 0) { + /* + * Access for write is interpreted as allowing + * creation of files in the directory. + */ + if (error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, cnp->cn_proc)) + return (error); + /* + * Return an indication of where the new directory + * entry should be put. If we didn't find a slot, + * then set dp->de_fndoffset to -1 indicating + * that the new slot belongs at the end of the + * directory. If we found a slot, then the new entry + * can be put at dp->de_fndoffset. + */ + if (slotstatus == NONE) { + dp->de_fndoffset = (u_long)-1; + dp->de_fndclust = (u_long)-1; + } else { +#ifdef MSDOSFS_DEBUG + printf("msdosfs_lookup(): saving empty slot location\n"); +#endif + dp->de_fndoffset = slotoffset; + dp->de_fndclust = slotcluster; + } + + /* + * We return with the directory locked, so that + * the parameters we set up above will still be + * valid if we actually decide to do a direnter(). + * We return ni_vp == NULL to indicate that the entry + * does not currently exist; we leave a pointer to + * the (locked) directory inode in ndp->ni_dvp. + * The pathname buffer is saved so that the name + * can be obtained later. + * + * NB - if the directory is unlocked, then this + * information cannot be used. + */ + cnp->cn_flags |= SAVENAME; + if (!lockparent) + VOP_UNLOCK(vdp); + return (EJUSTRETURN); + } + /* + * Insert name into cache (as non-existent) if appropriate. + */ + if ((cnp->cn_flags & MAKEENTRY) && nameiop != CREATE) + cache_enter(vdp, *vpp, cnp); + return (ENOENT); + +found:; + /* + * NOTE: We still have the buffer with matched directory entry at + * this point. + */ + isadir = dep->deAttributes & ATTR_DIRECTORY; + scn = getushort(dep->deStartCluster); + +foundroot:; + /* + * If we entered at foundroot, then we are looking for the . or .. + * entry of the filesystems root directory. isadir and scn were + * setup before jumping here. And, bp is null. There is no buf + * header. + */ + + /* + * If deleting, and at end of pathname, return + * parameters which can be used to remove file. + * If the wantparent flag isn't set, we return only + * the directory (in ndp->ni_dvp), otherwise we go + * on and lock the inode, being careful with ".". + */ + if (nameiop == DELETE && (flags & ISLASTCN)) { + /* + * Write access to directory required to delete files. + */ + if (error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, cnp->cn_proc)) { + if (bp) + brelse(bp); + return (error); + } + /* + * Return pointer to current entry in dp->i_offset. + * Save directory inode pointer in ndp->ni_dvp for dirremove(). + */ + if (dp->de_StartCluster == scn && isadir) { /* "." */ + VREF(vdp); + *vpp = vdp; + if (bp) + brelse(bp); + return (0); + } + if (error = deget(pmp, cluster, diroff, dep, &tdp)) { + if (bp) + brelse(bp); + return (error); + } + *vpp = DETOV(tdp); + if (!lockparent) + VOP_UNLOCK(vdp); + if (bp) + brelse(bp); + return (0); + } + + /* + * If rewriting (RENAME), return the inode and the + * information required to rewrite the present directory + * Must get inode of directory entry to verify it's a + * regular file, or empty directory. + */ + if (nameiop == RENAME && wantparent && + (flags & ISLASTCN)) { + if (error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, cnp->cn_proc)) { + if (bp) + brelse(bp); + return (error); + } + /* + * Careful about locking second inode. + * This can only occur if the target is ".". + */ + if (dp->de_StartCluster == scn && isadir) { + if (bp) + brelse(bp); + return (EISDIR); + } + error = deget(pmp, cluster, diroff, dep, &tdp); + if (error) { + if (bp) + brelse(bp); + return (error); + } + *vpp = DETOV(tdp); + cnp->cn_flags |= SAVENAME; + if (!lockparent) + VOP_UNLOCK(vdp); + if (bp) + brelse(bp); + return (0); + } + + /* + * Step through the translation in the name. We do not `vput' the + * directory because we may need it again if a symbolic link + * is relative to the current directory. Instead we save it + * unlocked as "pdp". We must get the target inode before unlocking + * the directory to insure that the inode will not be removed + * before we get it. We prevent deadlock by always fetching + * inodes from the root, moving down the directory tree. Thus + * when following backward pointers ".." we must unlock the + * parent directory before getting the requested directory. + * There is a potential race condition here if both the current + * and parent directories are removed before the VFS_VGET for the + * inode associated with ".." returns. We hope that this occurs + * infrequently since we cannot avoid this race condition without + * implementing a sophisticated deadlock detection algorithm. + * Note also that this simple deadlock detection scheme will not + * work if the file system has any hard links other than ".." + * that point backwards in the directory structure. + */ + pdp = vdp; + if (flags & ISDOTDOT) { + VOP_UNLOCK(pdp); /* race to get the inode */ + if (error = deget(pmp, cluster, diroff, dep, &tdp)) { + VOP_LOCK(pdp); + if (bp) + brelse(bp); + return (error); + } + if (lockparent && (flags & ISLASTCN) && + (error = VOP_LOCK(pdp))) { + vput(DETOV(tdp)); + if (bp) + brelse(bp); + return (error); + } + *vpp = DETOV(tdp); + } else if (dp->de_StartCluster == scn && isadir) { + VREF(vdp); /* we want ourself, ie "." */ + *vpp = vdp; + } else { + if (error = deget(pmp, cluster, diroff, dep, &tdp)) { + if (bp) + brelse(bp); + return (error); + } + if (!lockparent || !(flags & ISLASTCN)) + VOP_UNLOCK(pdp); + *vpp = DETOV(tdp); + } + if (bp) + brelse(bp); + + /* + * Insert name into cache if appropriate. + */ + if (cnp->cn_flags & MAKEENTRY) + cache_enter(vdp, *vpp, cnp); + return (0); +} + +/* + * dep - directory entry to copy into the directory + * ddep - directory to add to + * depp - return the address of the denode for the created directory entry + * if depp != 0 + */ +int +createde(dep, ddep, depp) + struct denode *dep; + struct denode *ddep; + struct denode **depp; +{ + int error; + u_long dirclust, diroffset; + struct direntry *ndep; + struct msdosfsmount *pmp = ddep->de_pmp; + struct buf *bp; + +#ifdef MSDOSFS_DEBUG + printf("createde(dep %08x, ddep %08x, depp %08x)\n", dep, ddep, depp); +#endif + + /* + * If no space left in the directory then allocate another cluster + * and chain it onto the end of the file. There is one exception + * to this. That is, if the root directory has no more space it + * can NOT be expanded. extendfile() checks for and fails attempts + * to extend the root directory. We just return an error in that + * case. + */ + if (ddep->de_fndclust == (u_long)-1) { + if (error = extendfile(ddep, 1, &bp, &dirclust, DE_CLEAR)) + return (error); + ndep = (struct direntry *)bp->b_data; + /* + * Let caller know where we put the directory entry. + */ + ddep->de_fndclust = dirclust; + ddep->de_fndoffset = diroffset = 0; + /* + * Update the size of the directory + */ + ddep->de_FileSize += pmp->pm_bpcluster; + } else { + /* + * There is space in the existing directory. So, we just + * read in the cluster with space. Copy the new directory + * entry in. Then write it to disk. NOTE: DOS directories + * do not get smaller as clusters are emptied. + */ + dirclust = ddep->de_fndclust; + diroffset = ddep->de_fndoffset; + if (error = readep(pmp, dirclust, diroffset, &bp, &ndep)) + return (error); + } + DE_EXTERNALIZE(ndep, dep); + + /* + * If they want us to return with the denode gotten. + */ + if (depp) { + if (error = deget(pmp, dirclust, diroffset, ndep, depp)) + return (error); + } + if (error = bwrite(bp)) { + vput(DETOV(*depp)); /* free the vnode we got on error */ + return (error); + } + return (0); +} + +/* + * Read in a directory entry and mark it as being deleted. + */ +int +markdeleted(pmp, dirclust, diroffset) + struct msdosfsmount *pmp; + u_long dirclust; + u_long diroffset; +{ + int error; + struct direntry *ep; + struct buf *bp; + + if (error = readep(pmp, dirclust, diroffset, &bp, &ep)) + return (error); + ep->deName[0] = SLOT_DELETED; + return (bwrite(bp)); +} + +/* + * Remove a directory entry. At this point the file represented by the + * directory entry to be removed is still full length until no one has it + * open. When the file no longer being used msdosfs_inactive() is called + * and will truncate the file to 0 length. When the vnode containing the + * denode is needed for some other purpose by VFS it will call + * msdosfs_reclaim() which will remove the denode from the denode cache. + */ +int +removede(pdep, dep) + struct denode *pdep; /* directory where the entry is removed */ + struct denode *dep; /* file to be removed */ +{ + int error; + +#ifdef MSDOSFS_DEBUG + printf("removede(): filename %s\n", dep->de_Name); + printf("removede(): dep %08x, ndpcluster %d, ndpoffset %d\n", + dep, pdep->de_fndclust, pdep->de_fndoffset); +#endif + + /* + * Read the directory block containing the directory entry we are + * to make free. The nameidata structure holds the cluster number + * and directory entry index number of the entry to free. + */ + if (error = markdeleted(pdep->de_pmp, pdep->de_fndclust, pdep->de_fndoffset)) + return (error); + dep->de_refcnt--; + return (0); +} + +/* + * Be sure a directory is empty except for "." and "..". Return 1 if empty, + * return 0 if not empty or error. + */ +int +dosdirempty(dep) + struct denode *dep; +{ + int blsize; + int error; + u_long cn; + daddr_t bn; + struct buf *bp; + struct msdosfsmount *pmp = dep->de_pmp; + struct direntry *dentp; + + /* + * Since the filesize field in directory entries for a directory is + * zero, we just have to feel our way through the directory until + * we hit end of file. + */ + for (cn = 0;; cn++) { + error = pcbmap(dep, cn, &bn, 0, &blsize); + if (error == E2BIG) + return (1); /* it's empty */ + if (error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp)) + return (error); + for (dentp = (struct direntry *)bp->b_data; + (char *)dentp < bp->b_data + blsize; + dentp++) { + if (dentp->deName[0] != SLOT_DELETED && + (dentp->deAttributes & ATTR_VOLUME) == 0) { + /* + * In dos directories an entry whose name + * starts with SLOT_EMPTY (0) starts the + * beginning of the unused part of the + * directory, so we can just return that it + * is empty. + */ + if (dentp->deName[0] == SLOT_EMPTY) { + brelse(bp); + return (1); + } + /* + * Any names other than "." and ".." in a + * directory mean it is not empty. + */ + if (bcmp(dentp->deName, ". ", 11) && + bcmp(dentp->deName, ".. ", 11)) { + brelse(bp); +#ifdef MSDOSFS_DEBUG + printf("dosdirempty(): entry found %02x, %02x\n", + dentp->deName[0], dentp->deName[1]); +#endif + return (0); /* not empty */ + } + } + } + brelse(bp); + } + /* NOTREACHED */ +} + +/* + * Check to see if the directory described by target is in some + * subdirectory of source. This prevents something like the following from + * succeeding and leaving a bunch or files and directories orphaned. mv + * /a/b/c /a/b/c/d/e/f Where c and f are directories. + * + * source - the inode for /a/b/c + * target - the inode for /a/b/c/d/e/f + * + * Returns 0 if target is NOT a subdirectory of source. + * Otherwise returns a non-zero error number. + * The target inode is always unlocked on return. + */ +int +doscheckpath(source, target) + struct denode *source; + struct denode *target; +{ + daddr_t scn; + struct msdosfsmount *pmp; + struct direntry *ep; + struct denode *dep; + struct buf *bp = NULL; + int error = 0; + + dep = target; + if ((target->de_Attributes & ATTR_DIRECTORY) == 0 || + (source->de_Attributes & ATTR_DIRECTORY) == 0) { + error = ENOTDIR; + goto out; + } + if (dep->de_StartCluster == source->de_StartCluster) { + error = EEXIST; + goto out; + } + if (dep->de_StartCluster == MSDOSFSROOT) + goto out; + for (;;) { + if ((dep->de_Attributes & ATTR_DIRECTORY) == 0) { + error = ENOTDIR; + goto out; + } + pmp = dep->de_pmp; + scn = dep->de_StartCluster; + if (error = bread(pmp->pm_devvp, cntobn(pmp, scn), + pmp->pm_bpcluster, NOCRED, &bp)) + break; + ep = (struct direntry *) bp->b_data + 1; + if ((ep->deAttributes & ATTR_DIRECTORY) == 0 || + bcmp(ep->deName, ".. ", 11) != 0) { + error = ENOTDIR; + break; + } + scn = getushort(ep->deStartCluster); + if (scn == source->de_StartCluster) { + error = EINVAL; + break; + } + if (scn == MSDOSFSROOT) + break; + vput(DETOV(dep)); + /* NOTE: deget() clears dep on error */ + error = deget(pmp, scn, 0, ep, &dep); + brelse(bp); + bp = NULL; + if (error) + break; + } +out:; + if (bp) + brelse(bp); + if (error == ENOTDIR) + printf("doscheckpath(): .. not a directory?\n"); + if (dep != NULL) + vput(DETOV(dep)); + return (error); +} + +/* + * Read in the disk block containing the directory entry (dirclu, dirofs) + * and return the address of the buf header, and the address of the + * directory entry within the block. + */ +int +readep(pmp, dirclust, diroffset, bpp, epp) + struct msdosfsmount *pmp; + u_long dirclust, diroffset; + struct buf **bpp; + struct direntry **epp; +{ + int error; + daddr_t bn; + int blsize; + u_long boff; + + boff = diroffset & ~pmp->pm_crbomask; + blsize = pmp->pm_bpcluster; + if (dirclust == MSDOSFSROOT + && boff + blsize > (pmp->pm_rootdirsize << pmp->pm_bnshift)) + blsize = (pmp->pm_rootdirsize << pmp->pm_bnshift) - boff; + bn = detobn(pmp, dirclust, diroffset); + if (error = bread(pmp->pm_devvp, bn, blsize, NOCRED, bpp)) { + *bpp = NULL; + return (error); + } + if (epp) + *epp = bptoep(pmp, *bpp, diroffset); + return (0); +} + +/* + * Read in the disk block containing the directory entry dep came from and + * return the address of the buf header, and the address of the directory + * entry within the block. + */ +int +readde(dep, bpp, epp) + struct denode *dep; + struct buf **bpp; + struct direntry **epp; +{ + + return (readep(dep->de_pmp, dep->de_dirclust, dep->de_diroffset, + bpp, epp)); +} diff --git a/sys/msdosfs/msdosfs_vfsops.c b/sys/msdosfs/msdosfs_vfsops.c new file mode 100644 index 00000000000..176b99fd3e9 --- /dev/null +++ b/sys/msdosfs/msdosfs_vfsops.c @@ -0,0 +1,748 @@ +/* $NetBSD: msdosfs_vfsops.c,v 1.32 1995/09/09 19:38:08 ws Exp $ */ + +/*- + * Copyright (C) 1994 Wolfgang Solfrank. + * Copyright (C) 1994 TooLs GmbH. + * All rights reserved. + * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below). + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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. + */ +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +#include <sys/param.h> +#include <sys/systm.h> +#include <sys/namei.h> +#include <sys/proc.h> +#include <sys/kernel.h> +#include <sys/vnode.h> +#include <miscfs/specfs/specdev.h> /* XXX */ /* defines v_rdev */ +#include <sys/mount.h> +#include <sys/buf.h> +#include <sys/file.h> +#include <sys/disklabel.h> +#include <sys/ioctl.h> +#include <sys/malloc.h> + +#include <msdosfs/bpb.h> +#include <msdosfs/bootsect.h> +#include <msdosfs/direntry.h> +#include <msdosfs/denode.h> +#include <msdosfs/msdosfsmount.h> +#include <msdosfs/fat.h> + +/* + * mp - path - addr in user space of mount point (ie /usr or whatever) + * data - addr in user space of mount params including the name of the block + * special file to treat as a filesystem. + */ +int +msdosfs_mount(mp, path, data, ndp, p) + struct mount *mp; + char *path; + caddr_t data; + struct nameidata *ndp; + struct proc *p; +{ + struct vnode *devvp; /* vnode for blk device to mount */ + struct msdosfs_args args; /* will hold data from mount request */ + struct msdosfsmount *pmp; /* msdosfs specific mount control block */ + size_t size; + int error, flags; + mode_t accessmode; + + if (error = copyin(data, (caddr_t)&args, sizeof(struct msdosfs_args))) + return (error); + /* + * If updating, check whether changing from read-only to + * read/write; if there is no device name, that's all we do. + */ + if (mp->mnt_flag & MNT_UPDATE) { + pmp = VFSTOMSDOSFS(mp); + error = 0; + if (pmp->pm_ronly == 0 && (mp->mnt_flag & MNT_RDONLY)) { + flags = WRITECLOSE; + if (mp->mnt_flag & MNT_FORCE) + flags |= FORCECLOSE; + if (vfs_busy(mp)) + return (EBUSY); + error = vflush(mp, NULLVP, flags); + vfs_unbusy(mp); + } + if (!error && (mp->mnt_flag & MNT_RELOAD)) + /* not yet implemented */ + error = EOPNOTSUPP; + if (error) + return (error); + if (pmp->pm_ronly && (mp->mnt_flag & MNT_WANTRDWR)) { + /* + * If upgrade to read-write by non-root, then verify + * that user has necessary permissions on the device. + */ + if (p->p_ucred->cr_uid != 0) { + devvp = pmp->pm_devvp; + VOP_LOCK(devvp); + if (error = VOP_ACCESS(devvp, VREAD | VWRITE, + p->p_ucred, p)) { + VOP_UNLOCK(devvp); + return (error); + } + VOP_UNLOCK(devvp); + } + pmp->pm_ronly = 0; + } + if (args.fspec == 0) { + /* + * Process export requests. + */ + return (vfs_export(mp, &pmp->pm_export, &args.export)); + } + } + /* + * Not an update, or updating the name: look up the name + * and verify that it refers to a sensible block device. + */ + NDINIT(ndp, LOOKUP, FOLLOW, UIO_USERSPACE, args.fspec, p); + if (error = namei(ndp)) + return (error); + devvp = ndp->ni_vp; + + if (devvp->v_type != VBLK) { + vrele(devvp); + return (ENOTBLK); + } + if (major(devvp->v_rdev) >= nblkdev) { + vrele(devvp); + return (ENXIO); + } + /* + * If mount by non-root, then verify that user has necessary + * permissions on the device. + */ + if (p->p_ucred->cr_uid != 0) { + accessmode = VREAD; + if ((mp->mnt_flag & MNT_RDONLY) == 0) + accessmode |= VWRITE; + VOP_LOCK(devvp); + if (error = VOP_ACCESS(devvp, accessmode, p->p_ucred, p)) { + vput(devvp); + return (error); + } + VOP_UNLOCK(devvp); + } + if ((mp->mnt_flag & MNT_UPDATE) == 0) + error = msdosfs_mountfs(devvp, mp, p); + else { + if (devvp != pmp->pm_devvp) + error = EINVAL; /* needs translation */ + else + vrele(devvp); + } + if (error) { + vrele(devvp); + return (error); + } + pmp = VFSTOMSDOSFS(mp); + pmp->pm_gid = args.gid; + pmp->pm_uid = args.uid; + pmp->pm_mask = args.mask; + (void) copyinstr(path, mp->mnt_stat.f_mntonname, MNAMELEN - 1, &size); + bzero(mp->mnt_stat.f_mntonname + size, MNAMELEN - size); + (void) copyinstr(args.fspec, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, + &size); + bzero(mp->mnt_stat.f_mntfromname + size, MNAMELEN - size); +#ifdef MSDOSFS_DEBUG + printf("msdosfs_mount(): mp %x, pmp %x, inusemap %x\n", mp, pmp, pmp->pm_inusemap); +#endif + return (0); +} + +int +msdosfs_mountfs(devvp, mp, p) + struct vnode *devvp; + struct mount *mp; + struct proc *p; +{ + struct msdosfsmount *pmp; + struct buf *bp; + dev_t dev = devvp->v_rdev; + struct partinfo dpart; + union bootsector *bsp; + struct byte_bpb33 *b33; + struct byte_bpb50 *b50; + extern struct vnode *rootvp; + int ronly, error; +#ifdef atari + int bsize, dtype, tmp; +#endif /* !atari */ + + /* + * Disallow multiple mounts of the same device. + * Disallow mounting of a device that is currently in use + * (except for root, which might share swap device for miniroot). + * Flush out any old buffers remaining from a previous use. + */ + if (error = vfs_mountedon(devvp)) + return (error); + if (vcount(devvp) > 1 && devvp != rootvp) + return (EBUSY); + if (error = vinvalbuf(devvp, V_SAVE, p->p_ucred, p, 0, 0)) + return (error); + + ronly = (mp->mnt_flag & MNT_RDONLY) != 0; + if (error = VOP_OPEN(devvp, ronly ? FREAD : FREAD|FWRITE, FSCRED, p)) + return (error); +#ifdef atari + bp = NULL; /* both used in error_exit */ + pmp = NULL; + /* + * We need the disklabel to calculate the size of a FAT entry later on. + * Also make sure the partition contains a filesystem of type FS_MSDOS. + * This doesn't work for floppies, so we have to check for them too. + * + * At least some parts of the msdos fs driver seem to assume that the + * size of a disk block will always be 512 bytes. Let's check it... + */ + if (error = VOP_IOCTL(devvp, DIOCGPART, (caddr_t)&dpart, FREAD, NOCRED, p)) + goto error_exit; + tmp = dpart.part->p_fstype; + dtype = dpart.disklab->d_type; + bsize = dpart.disklab->d_secsize; + if (bsize != 512 || (dtype != DTYPE_FLOPPY && tmp != FS_MSDOS)) { + error = EINVAL; + goto error_exit; + } +#else /* !atari */ + + /* + * Read the boot sector of the filesystem, and then check the boot + * signature. If not a dos boot sector then error out. + */ + bp = NULL; + pmp = NULL; +#endif /* !atari */ + if (error = bread(devvp, 0, 512, NOCRED, &bp)) + goto error_exit; + bp->b_flags |= B_AGE; + bsp = (union bootsector *)bp->b_data; + b33 = (struct byte_bpb33 *)bsp->bs33.bsBPB; + b50 = (struct byte_bpb50 *)bsp->bs50.bsBPB; +#ifdef MSDOSFS_CHECKSIG + if (bsp->bs50.bsBootSectSig != BOOTSIG) { + error = EINVAL; + goto error_exit; + } +#endif + + pmp = malloc(sizeof *pmp, M_MSDOSFSMNT, M_WAITOK); + bzero((caddr_t)pmp, sizeof *pmp); + pmp->pm_mountp = mp; + + /* + * Compute several useful quantities from the bpb in the + * bootsector. Copy in the dos 5 variant of the bpb then fix up + * the fields that are different between dos 5 and dos 3.3. + */ + pmp->pm_BytesPerSec = getushort(b50->bpbBytesPerSec); + pmp->pm_SectPerClust = b50->bpbSecPerClust; + pmp->pm_ResSectors = getushort(b50->bpbResSectors); + pmp->pm_FATs = b50->bpbFATs; + pmp->pm_RootDirEnts = getushort(b50->bpbRootDirEnts); + pmp->pm_Sectors = getushort(b50->bpbSectors); + pmp->pm_FATsecs = getushort(b50->bpbFATsecs); +#ifdef atari + /* + * Meaningless on a gemdos fs. This kind of information + * should be extracted from the disklabel structure. + */ + pmp->pm_SecPerTrack = 1; /* anything between 1 and 63 */ + pmp->pm_Heads = 1; /* anything between 1 and 255 */ + pmp->pm_Media = 0; /* unused, any value will do */ +#else /* !atari */ + pmp->pm_SecPerTrack = getushort(b50->bpbSecPerTrack); + pmp->pm_Heads = getushort(b50->bpbHeads); + pmp->pm_Media = b50->bpbMedia; + + /* XXX - We should probably check more values here */ + if (!pmp->pm_BytesPerSec || !pmp->pm_SectPerClust || + pmp->pm_Heads > 255 || pmp->pm_SecPerTrack > 63) { + error = EINVAL; + goto error_exit; + } +#endif /* !atari */ + + if (pmp->pm_Sectors == 0) { + pmp->pm_HiddenSects = getulong(b50->bpbHiddenSecs); + pmp->pm_HugeSectors = getulong(b50->bpbHugeSectors); + } else { + pmp->pm_HiddenSects = getushort(b33->bpbHiddenSecs); + pmp->pm_HugeSectors = pmp->pm_Sectors; + } +#ifdef atari + /* + * Check a few values (could do some more): + * - logical sector size: power of 2, >= block size + * - sectors per cluster: power of 2, >= 1 + * - number of sectors: >= 1, <= size of partition + */ + if ( pmp->pm_BytesPerSec < bsize + || pmp->pm_BytesPerSec & (pmp->pm_BytesPerSec - 1) + || !pmp->pm_SectPerClust + || pmp->pm_SectPerClust & (pmp->pm_SectPerClust - 1) + || !pmp->pm_HugeSectors + || pmp->pm_HugeSectors * pmp->pm_BytesPerSec + > dpart.part->p_size * bsize) { + error = EINVAL; + goto error_exit; + } + /* + * XXX - Many parts of the msdos fs driver seem to assume that + * the number of bytes per logical sector (BytesPerSec) will + * always be the same as the number of bytes per disk block + * Let's pretend it is. + */ + tmp = pmp->pm_BytesPerSec / bsize; + pmp->pm_BytesPerSec = bsize; + pmp->pm_SectPerClust *= tmp; + pmp->pm_HugeSectors *= tmp; + pmp->pm_HiddenSects *= tmp; + pmp->pm_ResSectors *= tmp; + pmp->pm_Sectors *= tmp; + pmp->pm_FATsecs *= tmp; +#endif /* atari */ + pmp->pm_fatblk = pmp->pm_ResSectors; + pmp->pm_rootdirblk = pmp->pm_fatblk + + (pmp->pm_FATs * pmp->pm_FATsecs); +#ifdef atari + tmp = pmp->pm_RootDirEnts * sizeof(struct direntry); + tmp += pmp->pm_BytesPerSec - 1; + tmp /= pmp->pm_BytesPerSec; + pmp->pm_rootdirsize = tmp; /* in sectors */ +#else /* !atari */ + pmp->pm_rootdirsize = (pmp->pm_RootDirEnts * sizeof(struct direntry)) + / + pmp->pm_BytesPerSec;/* in sectors */ +#endif /* !atari */ + pmp->pm_firstcluster = pmp->pm_rootdirblk + pmp->pm_rootdirsize; + pmp->pm_nmbrofclusters = (pmp->pm_HugeSectors - pmp->pm_firstcluster) / + pmp->pm_SectPerClust; + pmp->pm_maxcluster = pmp->pm_nmbrofclusters + 1; + pmp->pm_fatsize = pmp->pm_FATsecs * pmp->pm_BytesPerSec; +#ifdef atari + if (dtype == DTYPE_FLOPPY) { + pmp->pm_fatentrysize = 12; + pmp->pm_fatblocksize = 3 * pmp->pm_BytesPerSec; + } else { + pmp->pm_fatentrysize = 16; + pmp->pm_fatblocksize = MAXBSIZE; + } +#else /* !atari */ + if (FAT12(pmp)) + /* + * This will usually be a floppy disk. This size makes sure + * that one fat entry will not be split across multiple + * blocks. + */ + pmp->pm_fatblocksize = 3 * pmp->pm_BytesPerSec; + else + /* + * This will usually be a hard disk. Reading or writing one + * block should be quite fast. + */ + pmp->pm_fatblocksize = MAXBSIZE; +#endif /* !atari */ + pmp->pm_fatblocksec = pmp->pm_fatblocksize / pmp->pm_BytesPerSec; + +#ifdef atari + /* + * Be prepared for block size != 512 + */ + pmp->pm_brbomask = bsize - 1; + for (tmp = 0; bsize >>= 1; ++tmp) + ; + pmp->pm_bnshift = tmp; + /* + * Compute mask and shift value for isolating cluster relative + * byte offsets and cluster numbers from a file offset. We + * already know that the number of sectors per cluster is + * > 0 and a power of 2. + */ + bsize = pmp->pm_SectPerClust * pmp->pm_BytesPerSec; + pmp->pm_crbomask = bsize - 1; + pmp->pm_bpcluster = bsize; + for (tmp = 0; bsize >>= 1; ++tmp) + ; + pmp->pm_cnshift = tmp; + +#else /* !atari */ + /* + * Compute mask and shift value for isolating cluster relative byte + * offsets and cluster numbers from a file offset. + */ + pmp->pm_bpcluster = pmp->pm_SectPerClust * pmp->pm_BytesPerSec; + pmp->pm_crbomask = pmp->pm_bpcluster - 1; + pmp->pm_cnshift = ffs(pmp->pm_bpcluster) - 1; + if (pmp->pm_cnshift < 0 + || pmp->pm_bpcluster ^ (1 << pmp->pm_cnshift)) { + error = EINVAL; + goto error_exit; + } + + pmp->pm_brbomask = 0x01ff; /* 512 byte blocks only (so far) */ + pmp->pm_bnshift = 9; /* shift right 9 bits to get bn */ +#endif /* !atari */ + + /* + * Release the bootsector buffer. + */ + brelse(bp); + bp = NULL; + + /* + * Allocate memory for the bitmap of allocated clusters, and then + * fill it in. + */ + pmp->pm_inusemap = malloc(((pmp->pm_maxcluster + N_INUSEBITS - 1) + / N_INUSEBITS) + * sizeof(*pmp->pm_inusemap), + M_MSDOSFSFAT, M_WAITOK); + + /* + * fillinusemap() needs pm_devvp. + */ + pmp->pm_dev = dev; + pmp->pm_devvp = devvp; + + /* + * Have the inuse map filled in. + */ + if (error = fillinusemap(pmp)) + goto error_exit; + + /* + * If they want fat updates to be synchronous then let them suffer + * the performance degradation in exchange for the on disk copy of + * the fat being correct just about all the time. I suppose this + * would be a good thing to turn on if the kernel is still flakey. + */ + pmp->pm_waitonfat = mp->mnt_flag & MNT_SYNCHRONOUS; + + /* + * Finish up. + */ + pmp->pm_ronly = ronly; + if (ronly == 0) + pmp->pm_fmod = 1; + mp->mnt_data = (qaddr_t)pmp; + mp->mnt_stat.f_fsid.val[0] = (long)dev; + mp->mnt_stat.f_fsid.val[1] = makefstype(MOUNT_MSDOS); + mp->mnt_flag |= MNT_LOCAL; +#ifdef QUOTA + /* + * If we ever do quotas for DOS filesystems this would be a place + * to fill in the info in the msdosfsmount structure. You dolt, + * quotas on dos filesystems make no sense because files have no + * owners on dos filesystems. of course there is some empty space + * in the directory entry where we could put uid's and gid's. + */ +#endif + devvp->v_specflags |= SI_MOUNTEDON; + + return (0); + +error_exit:; + if (bp) + brelse(bp); + (void) VOP_CLOSE(devvp, ronly ? FREAD : FREAD|FWRITE, NOCRED, p); + if (pmp) { + if (pmp->pm_inusemap) + free(pmp->pm_inusemap, M_MSDOSFSFAT); + free(pmp, M_MSDOSFSMNT); + mp->mnt_data = (qaddr_t)0; + } + return (error); +} + +int +msdosfs_start(mp, flags, p) + struct mount *mp; + int flags; + struct proc *p; +{ + + return (0); +} + +/* + * Unmount the filesystem described by mp. + */ +int +msdosfs_unmount(mp, mntflags, p) + struct mount *mp; + int mntflags; + struct proc *p; +{ + struct msdosfsmount *pmp; + int error, flags; + + flags = 0; + if (mntflags & MNT_FORCE) + flags |= FORCECLOSE; +#ifdef QUOTA +#endif + if (error = vflush(mp, NULLVP, flags)) + return (error); + pmp = VFSTOMSDOSFS(mp); + pmp->pm_devvp->v_specflags &= ~SI_MOUNTEDON; +#ifdef MSDOSFS_DEBUG + printf("msdosfs_umount(): just before calling VOP_CLOSE()\n"); + printf("flag %08x, usecount %d, writecount %d, holdcnt %d\n", + vp->v_flag, vp->v_usecount, vp->v_writecount, vp->v_holdcnt); + printf("lastr %d, id %d, mount %08x, op %08x\n", + vp->v_lastr, vp->v_id, vp->v_mount, vp->v_op); + printf("freef %08x, freeb %08x, mountf %08x, mountb %08x\n", + vp->v_freef, vp->v_freeb, vp->v_mountf, vp->v_mountb); + printf("cleanblkhd %08x, dirtyblkhd %08x, numoutput %d, type %d\n", + vp->v_cleanblkhd, vp->v_dirtyblkhd, vp->v_numoutput, vp->v_type); + printf("union %08x, tag %d, data[0] %08x, data[1] %08x\n", + vp->v_socket, vp->v_tag, vp->v_data[0], vp->v_data[1]); +#endif + error = VOP_CLOSE(pmp->pm_devvp, pmp->pm_ronly ? FREAD : FREAD|FWRITE, + NOCRED, p); + vrele(pmp->pm_devvp); + free(pmp->pm_inusemap, M_MSDOSFSFAT); + free(pmp, M_MSDOSFSMNT); + mp->mnt_data = (qaddr_t)0; + mp->mnt_flag &= ~MNT_LOCAL; + return (error); +} + +int +msdosfs_root(mp, vpp) + struct mount *mp; + struct vnode **vpp; +{ + struct msdosfsmount *pmp = VFSTOMSDOSFS(mp); + struct denode *ndep; + int error; + +#ifdef MSDOSFS_DEBUG + printf("msdosfs_root(); mp %08x, pmp %08x, ndep %08x, vp %08x\n", + mp, pmp, ndep, DETOV(ndep)); +#endif + if (error = deget(pmp, MSDOSFSROOT, MSDOSFSROOT_OFS, NULL, &ndep)) + return (error); + *vpp = DETOV(ndep); + return (0); +} + +int +msdosfs_quotactl(mp, cmds, uid, arg, p) + struct mount *mp; + int cmds; + uid_t uid; + caddr_t arg; + struct proc *p; +{ + +#ifdef QUOTA + return (EOPNOTSUPP); +#else + return (EOPNOTSUPP); +#endif +} + +int +msdosfs_statfs(mp, sbp, p) + struct mount *mp; + struct statfs *sbp; + struct proc *p; +{ + struct msdosfsmount *pmp; + + pmp = VFSTOMSDOSFS(mp); +#ifdef COMPAT_09 + sbp->f_type = 4; +#else + sbp->f_type = 0; +#endif + sbp->f_bsize = pmp->pm_bpcluster; + sbp->f_iosize = pmp->pm_bpcluster; + sbp->f_blocks = pmp->pm_nmbrofclusters; + sbp->f_bfree = pmp->pm_freeclustercount; + sbp->f_bavail = pmp->pm_freeclustercount; + sbp->f_files = pmp->pm_RootDirEnts; /* XXX */ + sbp->f_ffree = 0; /* what to put in here? */ + if (sbp != &mp->mnt_stat) { + bcopy(mp->mnt_stat.f_mntonname, sbp->f_mntonname, MNAMELEN); + bcopy(mp->mnt_stat.f_mntfromname, sbp->f_mntfromname, MNAMELEN); + } + strncpy(sbp->f_fstypename, mp->mnt_op->vfs_name, MFSNAMELEN); + return (0); +} + +int +msdosfs_sync(mp, waitfor, cred, p) + struct mount *mp; + int waitfor; + struct ucred *cred; + struct proc *p; +{ + struct vnode *vp; + struct denode *dep; + struct msdosfsmount *pmp = VFSTOMSDOSFS(mp); + int error, allerror = 0; + + /* + * If we ever switch to not updating all of the fats all the time, + * this would be the place to update them from the first one. + */ + if (pmp->pm_fmod != 0) + if (pmp->pm_ronly != 0) + panic("msdosfs_sync: rofs mod"); + else { + /* update fats here */ + } + /* + * Write back each (modified) denode. + */ +loop: + for (vp = mp->mnt_vnodelist.lh_first; + vp != NULL; + vp = vp->v_mntvnodes.le_next) { + /* + * If the vnode that we are about to sync is no longer + * assoicated with this mount point, start over. + */ + if (vp->v_mount != mp) + goto loop; + if (VOP_ISLOCKED(vp)) + continue; + dep = VTODE(vp); + if ((dep->de_flag & DE_UPDATE) == 0 && + vp->v_dirtyblkhd.lh_first == NULL) + continue; + if (vget(vp, 1)) + goto loop; + if (error = VOP_FSYNC(vp, cred, waitfor, p)) + allerror = error; + vput(vp); + } + /* + * Force stale file system control information to be flushed. + */ + if (error = VOP_FSYNC(pmp->pm_devvp, cred, waitfor, p)) + allerror = error; +#ifdef QUOTA +#endif + return (allerror); +} + +int +msdosfs_fhtovp(mp, fhp, nam, vpp, exflagsp, credanonp) + struct mount *mp; + struct fid *fhp; + struct mbuf *nam; + struct vnode **vpp; + int *exflagsp; + struct ucred **credanonp; +{ + struct msdosfsmount *pmp = VFSTOMSDOSFS(mp); + struct defid *defhp = (struct defid *) fhp; + struct denode *dep; + struct netcred *np; + int error; + + np = vfs_export_lookup(mp, &pmp->pm_export, nam); + if (np == NULL) + return (EACCES); + error = deget(pmp, defhp->defid_dirclust, defhp->defid_dirofs, + NULL, &dep); + if (error) { + *vpp = NULLVP; + return (error); + } + *vpp = DETOV(dep); + *exflagsp = np->netc_exflags; + *credanonp = &np->netc_anon; + return (0); +} + +int +msdosfs_vptofh(vp, fhp) + struct vnode *vp; + struct fid *fhp; +{ + struct denode *dep; + struct defid *defhp; + + dep = VTODE(vp); + defhp = (struct defid *)fhp; + defhp->defid_len = sizeof(struct defid); + defhp->defid_dirclust = dep->de_dirclust; + defhp->defid_dirofs = dep->de_diroffset; + /* defhp->defid_gen = dep->de_gen; */ + return (0); +} + +int +msdosfs_vget(mp, ino, vpp) + struct mount *mp; + ino_t ino; + struct vnode **vpp; +{ + + return (EOPNOTSUPP); +} + +struct vfsops msdosfs_vfsops = { + MOUNT_MSDOS, + msdosfs_mount, + msdosfs_start, + msdosfs_unmount, + msdosfs_root, + msdosfs_quotactl, + msdosfs_statfs, + msdosfs_sync, + msdosfs_vget, + msdosfs_fhtovp, + msdosfs_vptofh, + msdosfs_init +}; diff --git a/sys/msdosfs/msdosfs_vnops.c b/sys/msdosfs/msdosfs_vnops.c new file mode 100644 index 00000000000..a4324774743 --- /dev/null +++ b/sys/msdosfs/msdosfs_vnops.c @@ -0,0 +1,1844 @@ +/* $NetBSD: msdosfs_vnops.c,v 1.37 1995/09/09 19:38:10 ws Exp $ */ + +/*- + * Copyright (C) 1994 Wolfgang Solfrank. + * Copyright (C) 1994 TooLs GmbH. + * All rights reserved. + * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below). + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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. + */ +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +#include <sys/param.h> +#include <sys/systm.h> +#include <sys/namei.h> +#include <sys/resourcevar.h> /* defines plimit structure in proc struct */ +#include <sys/kernel.h> +#include <sys/file.h> /* define FWRITE ... */ +#include <sys/stat.h> +#include <sys/buf.h> +#include <sys/proc.h> +#include <sys/mount.h> +#include <sys/vnode.h> +#include <miscfs/specfs/specdev.h> /* XXX */ /* defines v_rdev */ +#include <sys/malloc.h> +#include <sys/dir.h> /* defines dirent structure */ + +#include <msdosfs/bpb.h> +#include <msdosfs/direntry.h> +#include <msdosfs/denode.h> +#include <msdosfs/msdosfsmount.h> +#include <msdosfs/fat.h> + +/* + * Some general notes: + * + * In the ufs filesystem the inodes, superblocks, and indirect blocks are + * read/written using the vnode for the filesystem. Blocks that represent + * the contents of a file are read/written using the vnode for the file + * (including directories when they are read/written as files). This + * presents problems for the dos filesystem because data that should be in + * an inode (if dos had them) resides in the directory itself. Since we + * must update directory entries without the benefit of having the vnode + * for the directory we must use the vnode for the filesystem. This means + * that when a directory is actually read/written (via read, write, or + * readdir, or seek) we must use the vnode for the filesystem instead of + * the vnode for the directory as would happen in ufs. This is to insure we + * retreive the correct block from the buffer cache since the hash value is + * based upon the vnode address and the desired block number. + */ + +/* + * Create a regular file. On entry the directory to contain the file being + * created is locked. We must release before we return. We must also free + * the pathname buffer pointed at by cnp->cn_pnbuf, always on error, or + * only if the SAVESTART bit in cn_flags is clear on success. + */ +int +msdosfs_create(ap) + struct vop_create_args /* { + struct vnode *a_dvp; + struct vnode **a_vpp; + struct componentname *a_cnp; + struct vattr *a_vap; + } */ *ap; +{ + struct componentname *cnp = ap->a_cnp; + struct denode ndirent; + struct denode *dep; + struct denode *pdep = VTODE(ap->a_dvp); + int error; + +#ifdef MSDOSFS_DEBUG + printf("msdosfs_create(cnp %08x, vap %08x\n", cnp, ap->a_vap); +#endif + + /* + * If this is the root directory and there is no space left we + * can't do anything. This is because the root directory can not + * change size. + */ + if (pdep->de_StartCluster == MSDOSFSROOT && pdep->de_fndclust == (u_long)-1) { + error = ENOSPC; + goto bad; + } + + /* + * Create a directory entry for the file, then call createde() to + * have it installed. NOTE: DOS files are always executable. We + * use the absence of the owner write bit to make the file + * readonly. + */ +#ifdef DIAGNOSTIC + if ((cnp->cn_flags & HASBUF) == 0) + panic("msdosfs_create: no name"); +#endif + bzero(&ndirent, sizeof(ndirent)); + unix2dostime(NULL, &ndirent.de_Date, &ndirent.de_Time); + unix2dosfn((u_char *)cnp->cn_nameptr, ndirent.de_Name, cnp->cn_namelen); + ndirent.de_Attributes = (ap->a_vap->va_mode & VWRITE) ? + ATTR_ARCHIVE : ATTR_ARCHIVE | ATTR_READONLY; + ndirent.de_StartCluster = 0; + ndirent.de_FileSize = 0; + ndirent.de_dev = pdep->de_dev; + ndirent.de_devvp = pdep->de_devvp; + if (error = createde(&ndirent, pdep, &dep)) + goto bad; + if ((cnp->cn_flags & SAVESTART) == 0) + FREE(cnp->cn_pnbuf, M_NAMEI); + vput(ap->a_dvp); + *ap->a_vpp = DETOV(dep); + return (0); + +bad: + FREE(cnp->cn_pnbuf, M_NAMEI); + vput(ap->a_dvp); + return (error); +} + +int +msdosfs_mknod(ap) + struct vop_mknod_args /* { + struct vnode *a_dvp; + struct vnode **a_vpp; + struct componentname *a_cnp; + struct vattr *a_vap; + } */ *ap; +{ + int error; + + switch (ap->a_vap->va_type) { + case VDIR: + return (msdosfs_mkdir((struct vop_mkdir_args *)ap)); + break; + + case VREG: + return (msdosfs_create((struct vop_create_args *)ap)); + break; + + default: + FREE(ap->a_cnp->cn_pnbuf, M_NAMEI); + vput(ap->a_dvp); + return (EINVAL); + } + /* NOTREACHED */ +} + +int +msdosfs_open(ap) + struct vop_open_args /* { + struct vnode *a_vp; + int a_mode; + struct ucred *a_cred; + struct proc *a_p; + } */ *ap; +{ + + return (0); +} + +int +msdosfs_close(ap) + struct vop_close_args /* { + struct vnode *a_vp; + int a_fflag; + struct ucred *a_cred; + struct proc *a_p; + } */ *ap; +{ + struct vnode *vp = ap->a_vp; + struct denode *dep = VTODE(vp); + + if (vp->v_usecount > 1 && !(dep->de_flag & DE_LOCKED)) + DE_TIMES(dep); + return (0); +} + +int +msdosfs_access(ap) + struct vop_access_args /* { + struct vnode *a_vp; + int a_mode; + struct ucred *a_cred; + struct proc *a_p; + } */ *ap; +{ + struct denode *dep = VTODE(ap->a_vp); + struct msdosfsmount *pmp = dep->de_pmp; + mode_t dosmode; + + dosmode = (S_IXUSR|S_IXGRP|S_IXOTH) | (S_IRUSR|S_IRGRP|S_IROTH); + if ((dep->de_Attributes & ATTR_READONLY) == 0) + dosmode |= (S_IWUSR|S_IWGRP|S_IWOTH); + dosmode &= pmp->pm_mask; + + return (vaccess(dosmode, pmp->pm_uid, pmp->pm_gid, ap->a_mode, + ap->a_cred)); +} + +int +msdosfs_getattr(ap) + struct vop_getattr_args /* { + struct vnode *a_vp; + struct vattr *a_vap; + struct ucred *a_cred; + struct proc *a_p; + } */ *ap; +{ + u_int cn; + struct denode *dep = VTODE(ap->a_vp); + struct vattr *vap = ap->a_vap; + + DE_TIMES(dep); + vap->va_fsid = dep->de_dev; + /* + * The following computation of the fileid must be the same as that + * used in msdosfs_readdir() to compute d_fileno. If not, pwd + * doesn't work. + */ + if (dep->de_Attributes & ATTR_DIRECTORY) { + if ((cn = dep->de_StartCluster) == MSDOSFSROOT) + cn = 1; + } else { + if ((cn = dep->de_dirclust) == MSDOSFSROOT) + cn = 1; + cn = (cn << 16) + | ((dep->de_diroffset / sizeof(struct direntry)) & 0xffff); + } + vap->va_fileid = cn; + vap->va_mode = (S_IXUSR|S_IXGRP|S_IXOTH) | (S_IRUSR|S_IRGRP|S_IROTH) | + ((dep->de_Attributes & ATTR_READONLY) ? 0 : (S_IWUSR|S_IWGRP|S_IWOTH)); + vap->va_mode &= dep->de_pmp->pm_mask; + if (dep->de_Attributes & ATTR_DIRECTORY) + vap->va_mode |= S_IFDIR; + vap->va_nlink = 1; + vap->va_gid = dep->de_pmp->pm_gid; + vap->va_uid = dep->de_pmp->pm_uid; + vap->va_rdev = 0; + vap->va_size = dep->de_FileSize; + dos2unixtime(dep->de_Date, dep->de_Time, &vap->va_atime); + vap->va_mtime = vap->va_atime; +#ifndef MSDOSFS_NODIRMOD + if (vap->va_mode & S_IFDIR) + TIMEVAL_TO_TIMESPEC(&time, &vap->va_mtime); +#endif + vap->va_ctime = vap->va_atime; + vap->va_flags = 0; + if ((dep->de_Attributes & ATTR_ARCHIVE) == 0) + vap->va_flags |= SF_ARCHIVED; + vap->va_gen = 0; + vap->va_blocksize = dep->de_pmp->pm_bpcluster; + vap->va_bytes = (dep->de_FileSize + dep->de_pmp->pm_crbomask) & + ~(dep->de_pmp->pm_crbomask); + vap->va_type = ap->a_vp->v_type; + return (0); +} + +int +msdosfs_setattr(ap) + struct vop_setattr_args /* { + struct vnode *a_vp; + struct vattr *a_vap; + struct ucred *a_cred; + struct proc *a_p; + } */ *ap; +{ + int error = 0; + struct denode *dep = VTODE(ap->a_vp); + struct vattr *vap = ap->a_vap; + struct ucred *cred = ap->a_cred; + +#ifdef MSDOSFS_DEBUG + printf("msdosfs_setattr(): vp %08x, vap %08x, cred %08x, p %08x\n", + ap->a_vp, vap, cred, ap->a_p); +#endif + if ((vap->va_type != VNON) || (vap->va_nlink != VNOVAL) || + (vap->va_fsid != VNOVAL) || (vap->va_fileid != VNOVAL) || + (vap->va_blocksize != VNOVAL) || (vap->va_rdev != VNOVAL) || + (vap->va_bytes != VNOVAL) || (vap->va_gen != VNOVAL) || + (vap->va_uid != VNOVAL) || (vap->va_gid != VNOVAL)) { +#ifdef MSDOSFS_DEBUG + printf("msdosfs_setattr(): returning EINVAL\n"); + printf(" va_type %d, va_nlink %x, va_fsid %x, va_fileid %x\n", + vap->va_type, vap->va_nlink, vap->va_fsid, vap->va_fileid); + printf(" va_blocksize %x, va_rdev %x, va_bytes %x, va_gen %x\n", + vap->va_blocksize, vap->va_rdev, vap->va_bytes, vap->va_gen); + printf(" va_uid %x, va_gid %x\n", + vap->va_uid, vap->va_gid); +#endif + return (EINVAL); + } + if (ap->a_vp->v_type == VDIR) + return EISDIR; + + if (vap->va_size != VNOVAL) { + if (error = detrunc(dep, (u_long)vap->va_size, 0, cred, ap->a_p)) + return (error); + } + if (vap->va_mtime.ts_sec != VNOVAL) { + if (cred->cr_uid != dep->de_pmp->pm_uid && + (error = suser(cred, &ap->a_p->p_acflag)) && + ((vap->va_vaflags & VA_UTIMES_NULL) == 0 || + (error = VOP_ACCESS(ap->a_vp, VWRITE, cred, ap->a_p)))) + return (error); + unix2dostime(&vap->va_mtime, &dep->de_Date, &dep->de_Time); + dep->de_Attributes |= ATTR_ARCHIVE; + dep->de_flag |= DE_MODIFIED; + } + /* + * DOS files only have the ability to have their writability + * attribute set, so we use the owner write bit to set the readonly + * attribute. + */ + if (vap->va_mode != (mode_t)VNOVAL) { + if (cred->cr_uid != dep->de_pmp->pm_uid && + (error = suser(cred, &ap->a_p->p_acflag))) + return (error); + /* We ignore the read and execute bits. */ + if (vap->va_mode & VWRITE) + dep->de_Attributes &= ~ATTR_READONLY; + else + dep->de_Attributes |= ATTR_READONLY; + dep->de_flag |= DE_MODIFIED; + } + /* + * Allow the `archived' bit to be toggled. + */ + if (vap->va_flags != VNOVAL) { + if (cred->cr_uid != dep->de_pmp->pm_uid && + (error = suser(cred, &ap->a_p->p_acflag))) + return (error); + if (vap->va_flags & SF_ARCHIVED) + dep->de_Attributes &= ~ATTR_ARCHIVE; + else + dep->de_Attributes |= ATTR_ARCHIVE; + dep->de_flag |= DE_MODIFIED; + } + return (0); +} + +int +msdosfs_read(ap) + struct vop_read_args /* { + struct vnode *a_vp; + struct uio *a_uio; + int a_ioflag; + struct ucred *a_cred; + } */ *ap; +{ + int error = 0; + int diff; + int blsize; + int isadir; + long n; + long on; + daddr_t lbn; + daddr_t rablock; + struct buf *bp; + struct vnode *vp = ap->a_vp; + struct denode *dep = VTODE(vp); + struct msdosfsmount *pmp = dep->de_pmp; + struct uio *uio = ap->a_uio; + + /* + * If they didn't ask for any data, then we are done. + */ + if (uio->uio_resid == 0) + return (0); + if (uio->uio_offset < 0) + return (EINVAL); + + isadir = dep->de_Attributes & ATTR_DIRECTORY; + do { + lbn = uio->uio_offset >> pmp->pm_cnshift; + on = uio->uio_offset & pmp->pm_crbomask; + n = min((u_long) (pmp->pm_bpcluster - on), uio->uio_resid); + diff = dep->de_FileSize - uio->uio_offset; + if (diff <= 0) + return (0); + if (diff < n) + n = diff; + /* convert cluster # to block # if a directory */ + if (isadir) { + error = pcbmap(dep, lbn, &lbn, 0, &blsize); + if (error) + return (error); + } + /* + * If we are operating on a directory file then be sure to + * do i/o with the vnode for the filesystem instead of the + * vnode for the directory. + */ + if (isadir) { + error = bread(pmp->pm_devvp, lbn, blsize, NOCRED, &bp); + } else { + rablock = lbn + 1; + if (vp->v_lastr + 1 == lbn && + rablock * pmp->pm_bpcluster < dep->de_FileSize) { + error = breada(vp, lbn, pmp->pm_bpcluster, + rablock, pmp->pm_bpcluster, NOCRED, &bp); + } else { + error = bread(vp, lbn, pmp->pm_bpcluster, NOCRED, + &bp); + } + vp->v_lastr = lbn; + } + n = min(n, pmp->pm_bpcluster - bp->b_resid); + if (error) { + brelse(bp); + return (error); + } + error = uiomove(bp->b_data + on, (int) n, uio); + brelse(bp); + } while (error == 0 && uio->uio_resid > 0 && n != 0); + return (error); +} + +/* + * Write data to a file or directory. + */ +int +msdosfs_write(ap) + struct vop_write_args /* { + struct vnode *a_vp; + struct uio *a_uio; + int a_ioflag; + struct ucred *a_cred; + } */ *ap; +{ + int n; + int croffset; + int resid; + u_long osize; + int error; + u_long count; + daddr_t bn, lastcn; + struct buf *bp; + int ioflag = ap->a_ioflag; + struct uio *uio = ap->a_uio; + struct proc *p = uio->uio_procp; + struct vnode *vp = ap->a_vp; + struct vnode *thisvp; + struct denode *dep = VTODE(vp); + struct msdosfsmount *pmp = dep->de_pmp; + struct ucred *cred = ap->a_cred; + +#ifdef MSDOSFS_DEBUG + printf("msdosfs_write(vp %08x, uio %08x, ioflag %08x, cred %08x\n", + vp, uio, ioflag, cred); + printf("msdosfs_write(): diroff %d, dirclust %d, startcluster %d\n", + dep->de_diroffset, dep->de_dirclust, dep->de_StartCluster); +#endif + + if (vp->v_type == VREG) { + if (ioflag & IO_APPEND) + uio->uio_offset = dep->de_FileSize; + thisvp = vp; + } else + panic("msdosfs_write(): bad file type"); + + if (uio->uio_offset < 0) + return (EINVAL); + + if (uio->uio_resid == 0) + return (0); + + /* + * If they've exceeded their filesize limit, tell them about it. + */ + if (vp->v_type == VREG && p && + ((uio->uio_offset + uio->uio_resid) > + p->p_rlimit[RLIMIT_FSIZE].rlim_cur)) { + psignal(p, SIGXFSZ); + return (EFBIG); + } + + /* + * If attempting to write beyond the end of the root directory we + * stop that here because the root directory can not grow. + */ + if ((dep->de_Attributes & ATTR_DIRECTORY) && + dep->de_StartCluster == MSDOSFSROOT && + (uio->uio_offset + uio->uio_resid) > dep->de_FileSize) + return (ENOSPC); + + /* + * If the offset we are starting the write at is beyond the end of + * the file, then they've done a seek. Unix filesystems allow + * files with holes in them, DOS doesn't so we must fill the hole + * with zeroed blocks. + */ + if (uio->uio_offset > dep->de_FileSize) { + if (error = deextend(dep, uio->uio_offset, cred)) + return (error); + } + + /* + * Remember some values in case the write fails. + */ + resid = uio->uio_resid; + osize = dep->de_FileSize; + + /* + * If we write beyond the end of the file, extend it to its ultimate + * size ahead of the time to hopefully get a contiguous area. + */ + if (uio->uio_offset + resid > osize) { + count = de_clcount(pmp, uio->uio_offset + resid) - + de_clcount(pmp, osize); + if ((error = extendfile(dep, count, NULL, NULL, 0)) && + (error != ENOSPC || (ioflag & IO_UNIT))) + goto errexit; + lastcn = dep->de_fc[FC_LASTFC].fc_frcn; + } else + lastcn = de_clcount(pmp, osize) - 1; + + do { + bn = de_blk(pmp, uio->uio_offset); + if (bn > lastcn) { + error = ENOSPC; + break; + } + + if ((uio->uio_offset & pmp->pm_crbomask) == 0 + && (de_blk(pmp, uio->uio_offset + uio->uio_resid) > de_blk(pmp, uio->uio_offset) + || uio->uio_offset + uio->uio_resid >= dep->de_FileSize)) { + /* + * If either the whole cluster gets written, + * or we write the cluster from its start beyond EOF, + * then no need to read data from disk. + */ + bp = getblk(thisvp, bn, pmp->pm_bpcluster, 0, 0); + clrbuf(bp); + /* + * Do the bmap now, since pcbmap needs buffers + * for the fat table. (see msdosfs_strategy) + */ + if (bp->b_blkno == bp->b_lblkno) { + if (error = pcbmap(dep, bp->b_lblkno, + &bp->b_blkno, 0, 0)) + bp->b_blkno = -1; + } + if (bp->b_blkno == -1) { + brelse(bp); + if (!error) + error = EIO; /* XXX */ + break; + } + } else { + /* + * The block we need to write into exists, so read it in. + */ + if (error = bread(thisvp, bn, pmp->pm_bpcluster, cred, &bp)) + break; + } + + croffset = uio->uio_offset & pmp->pm_crbomask; + n = min(uio->uio_resid, pmp->pm_bpcluster - croffset); + if (uio->uio_offset + n > dep->de_FileSize) { + dep->de_FileSize = uio->uio_offset + n; + vnode_pager_setsize(vp, dep->de_FileSize); /* why? */ + } + (void) vnode_pager_uncache(vp); /* why not? */ + /* + * Should these vnode_pager_* functions be done on dir + * files? + */ + + /* + * Copy the data from user space into the buf header. + */ + error = uiomove(bp->b_data + croffset, n, uio); + + /* + * If they want this synchronous then write it and wait for + * it. Otherwise, if on a cluster boundary write it + * asynchronously so we can move on to the next block + * without delay. Otherwise do a delayed write because we + * may want to write somemore into the block later. + */ + if (ioflag & IO_SYNC) + (void) bwrite(bp); + else if (n + croffset == pmp->pm_bpcluster) + bawrite(bp); + else + bdwrite(bp); + dep->de_flag |= DE_UPDATE; + } while (error == 0 && uio->uio_resid > 0); + + /* + * If the write failed and they want us to, truncate the file back + * to the size it was before the write was attempted. + */ +errexit: + if (error) { + if (ioflag & IO_UNIT) { + detrunc(dep, osize, ioflag & IO_SYNC, NOCRED, NULL); + uio->uio_offset -= resid - uio->uio_resid; + uio->uio_resid = resid; + } else { + detrunc(dep, dep->de_FileSize, ioflag & IO_SYNC, NOCRED, NULL); + if (uio->uio_resid != resid) + error = 0; + } + } else + error = deupdat(dep, 1); + return (error); +} + +int +msdosfs_ioctl(ap) + struct vop_ioctl_args /* { + struct vnode *a_vp; + u_long a_command; + caddr_t a_data; + int a_fflag; + struct ucred *a_cred; + struct proc *a_p; + } */ *ap; +{ + + return (ENOTTY); +} + +int +msdosfs_select(ap) + struct vop_select_args /* { + struct vnode *a_vp; + int a_which; + int a_fflags; + struct ucred *a_cred; + struct proc *a_p; + } */ *ap; +{ + + return (1); /* DOS filesystems never block? */ +} + +int +msdosfs_mmap(ap) + struct vop_mmap_args /* { + struct vnode *a_vp; + int a_fflags; + struct ucred *a_cred; + struct proc *a_p; + } */ *ap; +{ + + return (EINVAL); +} + +/* + * Flush the blocks of a file to disk. + * + * This function is worthless for vnodes that represent directories. Maybe we + * could just do a sync if they try an fsync on a directory file. + */ +int +msdosfs_fsync(ap) + struct vop_fsync_args /* { + struct vnode *a_vp; + struct ucred *a_cred; + int a_waitfor; + struct proc *a_p; + } */ *ap; +{ + struct vnode *vp = ap->a_vp; + + vflushbuf(vp, ap->a_waitfor == MNT_WAIT); + return (deupdat(VTODE(vp), ap->a_waitfor == MNT_WAIT)); +} + +/* + * Now the whole work of extending a file is done in the write function. + * So nothing to do here. + */ +int +msdosfs_seek(ap) + struct vop_seek_args /* { + struct vnode *a_vp; + off_t a_oldoff; + off_t a_newoff; + struct ucred *a_cred; + } */ *ap; +{ + + return (0); +} + +int +msdosfs_remove(ap) + struct vop_remove_args /* { + struct vnode *a_dvp; + struct vnode *a_vp; + struct componentname *a_cnp; + } */ *ap; +{ + struct denode *dep = VTODE(ap->a_vp); + struct denode *ddep = VTODE(ap->a_dvp); + int error; + + error = removede(ddep, dep); +#ifdef MSDOSFS_DEBUG + printf("msdosfs_remove(), dep %08x, v_usecount %d\n", dep, ap->a_vp->v_usecount); +#endif + if (ddep == dep) + vrele(ap->a_vp); + else + vput(ap->a_vp); /* causes msdosfs_inactive() to be called + * via vrele() */ + vput(ap->a_dvp); + return (error); +} + +/* + * DOS filesystems don't know what links are. But since we already called + * msdosfs_lookup() with create and lockparent, the parent is locked so we + * have to free it before we return the error. + */ +int +msdosfs_link(ap) + struct vop_link_args /* { + struct vnode *a_vp; + struct vnode *a_tdvp; + struct componentname *a_cnp; + } */ *ap; +{ + + VOP_ABORTOP(ap->a_vp, ap->a_cnp); + vput(ap->a_vp); + return (EOPNOTSUPP); +} + +/* + * Renames on files require moving the denode to a new hash queue since the + * denode's location is used to compute which hash queue to put the file + * in. Unless it is a rename in place. For example "mv a b". + * + * What follows is the basic algorithm: + * + * if (file move) { + * if (dest file exists) { + * remove dest file + * } + * if (dest and src in same directory) { + * rewrite name in existing directory slot + * } else { + * write new entry in dest directory + * update offset and dirclust in denode + * move denode to new hash chain + * clear old directory entry + * } + * } else { + * directory move + * if (dest directory exists) { + * if (dest is not empty) { + * return ENOTEMPTY + * } + * remove dest directory + * } + * if (dest and src in same directory) { + * rewrite name in existing entry + * } else { + * be sure dest is not a child of src directory + * write entry in dest directory + * update "." and ".." in moved directory + * update offset and dirclust in denode + * move denode to new hash chain + * clear old directory entry for moved directory + * } + * } + * + * On entry: + * source's parent directory is unlocked + * source file or directory is unlocked + * destination's parent directory is locked + * destination file or directory is locked if it exists + * + * On exit: + * all denodes should be released + * + * Notes: + * I'm not sure how the memory containing the pathnames pointed at by the + * componentname structures is freed, there may be some memory bleeding + * for each rename done. + */ +int +msdosfs_rename(ap) + struct vop_rename_args /* { + struct vnode *a_fdvp; + struct vnode *a_fvp; + struct componentname *a_fcnp; + struct vnode *a_tdvp; + struct vnode *a_tvp; + struct componentname *a_tcnp; + } */ *ap; +{ + struct vnode *tvp = ap->a_tvp; + register struct vnode *tdvp = ap->a_tdvp; + struct vnode *fvp = ap->a_fvp; + register struct vnode *fdvp = ap->a_fdvp; + register struct componentname *tcnp = ap->a_tcnp; + register struct componentname *fcnp = ap->a_fcnp; + register struct denode *ip, *xp, *dp; + u_char toname[11], oldname[11]; + u_long to_dirclust, to_diroffset; + int doingdirectory = 0, newparent = 0; + int error; + u_long cn; + daddr_t bn; + struct msdosfsmount *pmp; + struct direntry *dotdotp; + struct direntry *ep; + struct buf *bp; + + pmp = VFSTOMSDOSFS(fdvp->v_mount); + +#ifdef DIAGNOSTIC + if ((tcnp->cn_flags & HASBUF) == 0 || + (fcnp->cn_flags & HASBUF) == 0) + panic("msdosfs_rename: no name"); +#endif + /* + * Check for cross-device rename. + */ + if ((fvp->v_mount != tdvp->v_mount) || + (tvp && (fvp->v_mount != tvp->v_mount))) { + error = EXDEV; +abortit: + VOP_ABORTOP(tdvp, tcnp); + if (tdvp == tvp) + vrele(tdvp); + else + vput(tdvp); + if (tvp) + vput(tvp); + VOP_ABORTOP(fdvp, fcnp); + vrele(fdvp); + vrele(fvp); + return (error); + } + + /* + * Convert the filename in tcnp into a dos filename. We copy this + * into the denode and directory entry for the destination + * file/directory. + */ + unix2dosfn((u_char *)tcnp->cn_nameptr, toname, tcnp->cn_namelen); + + /* */ + if (error = VOP_LOCK(fvp)) + goto abortit; + dp = VTODE(fdvp); + ip = VTODE(fvp); + + /* + * Be sure we are not renaming ".", "..", or an alias of ".". This + * leads to a crippled directory tree. It's pretty tough to do a + * "ls" or "pwd" with the "." directory entry missing, and "cd .." + * doesn't work if the ".." entry is missing. + */ + if (ip->de_Attributes & ATTR_DIRECTORY) { + /* + * Avoid ".", "..", and aliases of "." for obvious reasons. + */ + if ((fcnp->cn_namelen == 1 && fcnp->cn_nameptr[0] == '.') || + dp == ip || (fcnp->cn_flags & ISDOTDOT) || + (ip->de_flag & DE_RENAME)) { + VOP_UNLOCK(fvp); + error = EINVAL; + goto abortit; + } + ip->de_flag |= DE_RENAME; + doingdirectory++; + } + + /* + * When the target exists, both the directory + * and target vnodes are returned locked. + */ + dp = VTODE(tdvp); + xp = tvp ? VTODE(tvp) : NULL; + /* + * Remember direntry place to use for destination + */ + to_dirclust = dp->de_fndclust; + to_diroffset = dp->de_fndoffset; + + /* + * If ".." must be changed (ie the directory gets a new + * parent) then the source directory must not be in the + * directory heirarchy above the target, as this would + * orphan everything below the source directory. Also + * the user must have write permission in the source so + * as to be able to change "..". We must repeat the call + * to namei, as the parent directory is unlocked by the + * call to doscheckpath(). + */ + error = VOP_ACCESS(fvp, VWRITE, tcnp->cn_cred, tcnp->cn_proc); + VOP_UNLOCK(fvp); + if (VTODE(fdvp)->de_StartCluster != VTODE(tdvp)->de_StartCluster) + newparent = 1; + vrele(fdvp); + if (doingdirectory && newparent) { + if (error) /* write access check above */ + goto bad; + if (xp != NULL) + vput(tvp); + /* doscheckpath() vput()'s dp */ + if (error = doscheckpath(ip, dp)) + goto out; + if ((tcnp->cn_flags & SAVESTART) == 0) + panic("msdosfs_rename: lost to startdir"); + if (error = relookup(tdvp, &tvp, tcnp)) + goto out; + dp = VTODE(tdvp); + xp = tvp ? VTODE(tvp) : NULL; + } + + if (xp != NULL) { + /* + * Target must be empty if a directory and have no links + * to it. Also, ensure source and target are compatible + * (both directories, or both not directories). + */ + if (xp->de_Attributes & ATTR_DIRECTORY) { + if (!dosdirempty(xp)) { + error = ENOTEMPTY; + goto bad; + } + if (!doingdirectory) { + error = ENOTDIR; + goto bad; + } + cache_purge(tdvp); + } else if (doingdirectory) { + error = EISDIR; + goto bad; + } + if (error = removede(dp, xp)) + goto bad; + vput(tvp); + xp = NULL; + } + + /* + * Since from wasn't locked at various places above, + * have to do a relookup here. + */ + fcnp->cn_flags &= ~MODMASK; + fcnp->cn_flags |= LOCKPARENT | LOCKLEAF; + if ((fcnp->cn_flags & SAVESTART) == 0) + panic("msdosfs_rename: lost from startdir"); + if (!newparent) + VOP_UNLOCK(tdvp); + (void) relookup(fdvp, &fvp, fcnp); + if (fvp == NULL) { + /* + * From name has disappeared. + */ + if (doingdirectory) + panic("rename: lost dir entry"); + vrele(ap->a_fvp); + if (newparent) + VOP_UNLOCK(tdvp); + vrele(tdvp); + return 0; + } + xp = VTODE(fvp); + + /* + * Ensure that the directory entry still exists and has not + * changed till now. If the source is a file the entry may + * have been unlinked or renamed. In either case there is + * no further work to be done. If the source is a directory + * then it cannot have been rmdir'ed or renamed; this is + * prohibited by the DE_RENAME flag. + */ + if (xp != ip) { + if (doingdirectory) + panic("rename: lost dir entry"); + vrele(ap->a_fvp); + VOP_UNLOCK(fvp); + if (newparent) + VOP_UNLOCK(fdvp); + xp = NULL; + } else { + vrele(fvp); + xp = NULL; + + /* + * If the source and destination are in the same directory then + * just read in the directory entry, change the name in the + * directory entry and write it back to disk. + */ + if (!newparent) { + if (error = readep(dp->de_pmp, + dp->de_fndclust, + dp->de_fndoffset, + &bp, &ep)) { + VOP_UNLOCK(fvp); + goto bad; + } + bcopy(toname, ep->deName, 11); + if (error = bwrite(bp)) { + VOP_UNLOCK(fvp); + goto bad; + } + bcopy(toname, ip->de_Name, 11); /* update denode */ + } else { + struct denode *zp; + + /* + * If the source and destination are in different + * directories, then write a new entry in the destination + * directory and mark the entry in the source directory + * as deleted. Then move the denode to the correct hash + * chain for its new location in the filesystem. And, if + * we moved a directory, then update its .. entry to point + * to the new parent directory. + */ + bcopy(ip->de_Name, oldname, 11); + bcopy(toname, ip->de_Name, 11); /* update denode */ + dp->de_fndclust = to_dirclust; + dp->de_fndoffset = to_diroffset; + if (error = createde(ip, dp, (struct denode **)0)) { + bcopy(oldname, ip->de_Name, 11); + VOP_UNLOCK(fdvp); + VOP_UNLOCK(fvp); + goto bad; + } + zp = VTODE(fdvp); + if (error = readep(zp->de_pmp, zp->de_fndclust, zp->de_fndoffset, + &bp, &ep)) { + /* XXX should really panic here, fs is corrupt */ + VOP_UNLOCK(fdvp); + VOP_UNLOCK(fvp); + goto bad; + } + ep->deName[0] = SLOT_DELETED; + if (error = bwrite(bp)) { + /* XXX should really panic here, fs is corrupt */ + VOP_UNLOCK(fdvp); + VOP_UNLOCK(fvp); + goto bad; + } + if (!doingdirectory) { + ip->de_dirclust = to_dirclust; + ip->de_diroffset = to_diroffset; + } + reinsert(ip); + VOP_UNLOCK(fdvp); + } + + /* + * If we moved a directory to a new parent directory, then we must + * fixup the ".." entry in the moved directory. + */ + if (doingdirectory && newparent) { + cn = ip->de_StartCluster; + if (cn == MSDOSFSROOT) { + /* this should never happen */ + panic("msdosfs_rename: updating .. in root directory?\n"); + } else + bn = cntobn(pmp, cn); + if (error = bread(pmp->pm_devvp, bn, pmp->pm_bpcluster, NOCRED, + &bp)) { + /* XXX should really panic here, fs is corrupt */ + VOP_UNLOCK(fvp); + goto bad; + } + dotdotp = (struct direntry *)bp->b_data + 1; + putushort(dotdotp->deStartCluster, dp->de_StartCluster); + if (error = bwrite(bp)) { + /* XXX should really panic here, fs is corrupt */ + VOP_UNLOCK(fvp); + goto bad; + } + } + } + + VOP_UNLOCK(fvp); +bad: + if (xp) + vput(tvp); + vput(tdvp); +out: + ip->de_flag &= ~DE_RENAME; + vrele(fdvp); + vrele(fvp); + return (error); + +} + +struct { + struct direntry dot; + struct direntry dotdot; +} dosdirtemplate = { + ". ", " ", /* the . entry */ + ATTR_DIRECTORY, /* file attribute */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* resevered */ + 210, 4, 210, 4, /* time and date */ + 0, 0, /* startcluster */ + 0, 0, 0, 0, /* filesize */ + ".. ", " ", /* the .. entry */ + ATTR_DIRECTORY, /* file attribute */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* resevered */ + 210, 4, 210, 4, /* time and date */ + 0, 0, /* startcluster */ + 0, 0, 0, 0, /* filesize */ +}; + +int +msdosfs_mkdir(ap) + struct vop_mkdir_args /* { + struct vnode *a_dvp; + struvt vnode **a_vpp; + struvt componentname *a_cnp; + struct vattr *a_vap; + } */ *ap; +{ + struct componentname *cnp = ap->a_cnp; + struct denode ndirent; + struct denode *dep; + struct denode *pdep = VTODE(ap->a_dvp); + int error; + int bn; + u_long newcluster; + struct direntry *denp; + struct msdosfsmount *pmp = pdep->de_pmp; + struct buf *bp; + + /* + * If this is the root directory and there is no space left we + * can't do anything. This is because the root directory can not + * change size. + */ + if (pdep->de_StartCluster == MSDOSFSROOT && pdep->de_fndclust == (u_long)-1) { + error = ENOSPC; + goto bad2; + } + + /* + * Allocate a cluster to hold the about to be created directory. + */ + if (error = clusteralloc(pmp, 0, 1, CLUST_EOFE, &newcluster, NULL)) + goto bad2; + + bzero(&ndirent, sizeof(ndirent)); + unix2dostime(NULL, &ndirent.de_Date, &ndirent.de_Time); + + /* + * Now fill the cluster with the "." and ".." entries. And write + * the cluster to disk. This way it is there for the parent + * directory to be pointing at if there were a crash. + */ + bn = cntobn(pmp, newcluster); + /* always succeeds */ + bp = getblk(pmp->pm_devvp, bn, pmp->pm_bpcluster, 0, 0); + bzero(bp->b_data, pmp->pm_bpcluster); + bcopy(&dosdirtemplate, bp->b_data, sizeof dosdirtemplate); + denp = (struct direntry *)bp->b_data; + putushort(denp[0].deStartCluster, newcluster); + putushort(denp[0].deDate, ndirent.de_Date); + putushort(denp[0].deTime, ndirent.de_Time); + putushort(denp[1].deStartCluster, pdep->de_StartCluster); + putushort(denp[1].deDate, ndirent.de_Date); + putushort(denp[1].deTime, ndirent.de_Time); + if (error = bwrite(bp)) + goto bad; + + /* + * Now build up a directory entry pointing to the newly allocated + * cluster. This will be written to an empty slot in the parent + * directory. + */ +#ifdef DIAGNOSTIC + if ((cnp->cn_flags & HASBUF) == 0) + panic("msdosfs_mkdir: no name"); +#endif + unix2dosfn((u_char *)cnp->cn_nameptr, ndirent.de_Name, cnp->cn_namelen); + ndirent.de_Attributes = ATTR_DIRECTORY; + ndirent.de_StartCluster = newcluster; + ndirent.de_FileSize = 0; + ndirent.de_dev = pdep->de_dev; + ndirent.de_devvp = pdep->de_devvp; + if (error = createde(&ndirent, pdep, &dep)) + goto bad; + if ((cnp->cn_flags & SAVESTART) == 0) + FREE(cnp->cn_pnbuf, M_NAMEI); + vput(ap->a_dvp); + *ap->a_vpp = DETOV(dep); + return (0); + +bad: + clusterfree(pmp, newcluster, NULL); +bad2: + FREE(cnp->cn_pnbuf, M_NAMEI); + vput(ap->a_dvp); + return (error); +} + +int +msdosfs_rmdir(ap) + struct vop_rmdir_args /* { + struct vnode *a_dvp; + struct vnode *a_vp; + struct componentname *a_cnp; + } */ *ap; +{ + register struct vnode *vp = ap->a_vp; + register struct vnode *dvp = ap->a_dvp; + register struct componentname *cnp = ap->a_cnp; + register struct denode *ip, *dp; + int error; + + ip = VTODE(vp); + dp = VTODE(dvp); + /* + * No rmdir "." please. + */ + if (dp == ip) { + vrele(dvp); + vput(vp); + return (EINVAL); + } + /* + * Verify the directory is empty (and valid). + * (Rmdir ".." won't be valid since + * ".." will contain a reference to + * the current directory and thus be + * non-empty.) + */ + error = 0; + if (!dosdirempty(ip) || ip->de_flag & DE_RENAME) { + error = ENOTEMPTY; + goto out; + } + /* + * Delete the entry from the directory. For dos filesystems this + * gets rid of the directory entry on disk, the in memory copy + * still exists but the de_refcnt is <= 0. This prevents it from + * being found by deget(). When the vput() on dep is done we give + * up access and eventually msdosfs_reclaim() will be called which + * will remove it from the denode cache. + */ + if (error = removede(dp, ip)) + goto out; + /* + * This is where we decrement the link count in the parent + * directory. Since dos filesystems don't do this we just purge + * the name cache and let go of the parent directory denode. + */ + cache_purge(dvp); + vput(dvp); + dvp = NULL; + /* + * Truncate the directory that is being deleted. + */ + error = detrunc(ip, (u_long)0, IO_SYNC, cnp->cn_cred, cnp->cn_proc); + cache_purge(vp); +out: + if (dvp) + vput(dvp); + vput(vp); + return (error); +} + +/* + * DOS filesystems don't know what symlinks are. + */ +int +msdosfs_symlink(ap) + struct vop_symlink_args /* { + struct vnode *a_dvp; + struct vnode **a_vpp; + struct componentname *a_cnp; + struct vattr *a_vap; + char *a_target; + } */ *ap; +{ + register struct vnode *dvp = ap->a_dvp; + register struct componentname *cnp = ap->a_cnp; + + FREE(cnp->cn_pnbuf, M_NAMEI); + vput(dvp); + return (EINVAL); +} + +int +msdosfs_readdir(ap) + struct vop_readdir_args /* { + struct vnode *a_vp; + struct uio *a_uio; + struct ucred *a_cred; + int *a_eofflag; + u_long *a_cookies; + int a_ncookies; + } */ *ap; +{ + int error = 0; + int diff; + long n; + int blsize; + long on; + long lost; + long count; + u_long cn; + u_long fileno; + long bias = 0; + daddr_t bn, lbn; + struct buf *bp; + struct denode *dep = VTODE(ap->a_vp); + struct msdosfsmount *pmp = dep->de_pmp; + struct direntry *dentp; + struct dirent dirbuf; + int i = 0; + struct uio *uio = ap->a_uio; + u_long *cookies; + int ncookies; + off_t offset; + +#ifdef MSDOSFS_DEBUG + printf("msdosfs_readdir(): vp %08x, uio %08x, cred %08x, eofflagp %08x\n", + ap->a_vp, uio, ap->a_cred, ap->a_eofflag); +#endif + + /* + * msdosfs_readdir() won't operate properly on regular files since + * it does i/o only with the the filesystem vnode, and hence can + * retrieve the wrong block from the buffer cache for a plain file. + * So, fail attempts to readdir() on a plain file. + */ + if ((dep->de_Attributes & ATTR_DIRECTORY) == 0) + return (ENOTDIR); + + /* + * If the user buffer is smaller than the size of one dos directory + * entry or the file offset is not a multiple of the size of a + * directory entry, then we fail the read. + */ + count = uio->uio_resid & ~(sizeof(struct direntry) - 1); + offset = uio->uio_offset; + if (count < sizeof(struct direntry) || + (offset & (sizeof(struct direntry) - 1))) + return (EINVAL); + lost = uio->uio_resid - count; + uio->uio_resid = count; + + cookies = ap->a_cookies; + ncookies = ap->a_ncookies; + + /* + * If they are reading from the root directory then, we simulate + * the . and .. entries since these don't exist in the root + * directory. We also set the offset bias to make up for having to + * simulate these entries. By this I mean that at file offset 64 we + * read the first entry in the root directory that lives on disk. + */ + if (dep->de_StartCluster == MSDOSFSROOT) { + /* + * printf("msdosfs_readdir(): going after . or .. in root dir, offset %d\n", + * offset); + */ + bias = 2 * sizeof(struct direntry); + if (offset < bias) { + for (n = (int)offset / sizeof(struct direntry); + n < 2; n++) { + dirbuf.d_fileno = 1; + dirbuf.d_type = DT_DIR; + switch (n) { + case 0: + dirbuf.d_namlen = 1; + strcpy(dirbuf.d_name, "."); + break; + case 1: + dirbuf.d_namlen = 2; + strcpy(dirbuf.d_name, ".."); + break; + } + dirbuf.d_reclen = DIRSIZ(&dirbuf); + if (uio->uio_resid < dirbuf.d_reclen) + goto out; + if (error = uiomove(&dirbuf, dirbuf.d_reclen, uio)) + goto out; + offset += sizeof(struct direntry); + if (cookies) { + *cookies++ = offset; + if (--ncookies <= 0) + goto out; + } + } + } + } + + while (uio->uio_resid > 0) { + lbn = (offset - bias) >> pmp->pm_cnshift; + on = (offset - bias) & pmp->pm_crbomask; + n = min(pmp->pm_bpcluster - on, uio->uio_resid); + diff = dep->de_FileSize - (offset - bias); + if (diff <= 0) + break; + n = min(n, diff); + if (error = pcbmap(dep, lbn, &bn, &cn, &blsize)) + break; + if (error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp)) { + brelse(bp); + return (error); + } + n = min(n, blsize - bp->b_resid); + + /* + * Convert from dos directory entries to fs-independent + * directory entries. + */ + for (dentp = (struct direntry *)(bp->b_data + on); + (char *)dentp < bp->b_data + on + n; + dentp++) { + /* + * printf("rd: dentp %08x prev %08x crnt %08x deName %02x attr %02x\n", + * dentp, prev, crnt, dentp->deName[0], dentp->deAttributes); + */ + /* + * If this is an unused entry, we can stop. + */ + if (dentp->deName[0] == SLOT_EMPTY) { + brelse(bp); + goto out; + } + /* + * Skip deleted entries and volume labels. + */ + if (dentp->deName[0] == SLOT_DELETED || + (dentp->deAttributes & ATTR_VOLUME)) { + offset += sizeof(struct direntry); + continue; + } + /* + * This computation of d_fileno must match + * the computation of va_fileid in + * msdosfs_getattr. + */ + if (dentp->deAttributes & ATTR_DIRECTORY) { + /* if this is the root directory */ + fileno = getushort(dentp->deStartCluster); + if (fileno == MSDOSFSROOT) + fileno = 1; + } else { + /* + * If the file's dirent lives in + * root dir. + */ + if ((fileno = cn) == MSDOSFSROOT) + fileno = 1; + fileno = (fileno << 16) | + ((dentp - (struct direntry *)bp->b_data) & 0xffff); + } + dirbuf.d_fileno = fileno; + dirbuf.d_type = + (dentp->deAttributes & ATTR_DIRECTORY) ? DT_DIR : DT_REG; + dirbuf.d_namlen = dos2unixfn(dentp->deName, + (u_char *)dirbuf.d_name); + dirbuf.d_reclen = DIRSIZ(&dirbuf); + if (uio->uio_resid < dirbuf.d_reclen) { + brelse(bp); + goto out; + } + if (error = uiomove(&dirbuf, dirbuf.d_reclen, uio)) { + brelse(bp); + goto out; + } + offset += sizeof(struct direntry); + if (cookies) { + *cookies++ = offset; + if (--ncookies <= 0) { + brelse(bp); + goto out; + } + } + } + brelse(bp); + } + +out: + uio->uio_offset = offset; + uio->uio_resid += lost; + if (dep->de_FileSize - (offset - bias) <= 0) + *ap->a_eofflag = 1; + else + *ap->a_eofflag = 0; + return (error); +} + +/* + * DOS filesystems don't know what symlinks are. + */ +int +msdosfs_readlink(ap) + struct vop_readlink_args /* { + struct vnode *a_vp; + struct uio *a_uio; + struct ucred *a_cred; + } */ *ap; +{ + + return (EINVAL); +} + +int +msdosfs_abortop(ap) + struct vop_abortop_args /* { + struct vnode *a_dvp; + struct componentname *a_cnp; + } */ *ap; +{ + + if ((ap->a_cnp->cn_flags & (HASBUF | SAVESTART)) == HASBUF) + FREE(ap->a_cnp->cn_pnbuf, M_NAMEI); + return (0); +} + +int +msdosfs_lock(ap) + struct vop_lock_args /* { + struct vnode *a_vp; + } */ *ap; +{ + register struct vnode *vp = ap->a_vp; + register struct denode *dep; + struct proc *p = curproc; /* XXX */ + +start: + while (vp->v_flag & VXLOCK) { + vp->v_flag |= VXWANT; + sleep((caddr_t)vp, PINOD); + } + if (vp->v_tag == VT_NON) + return (ENOENT); + dep = VTODE(vp); + if (dep->de_flag & DE_LOCKED) { + dep->de_flag |= DE_WANTED; +#ifdef DIAGNOSTIC + if (p) { + if (p->p_pid == dep->de_lockholder) + panic("locking against myself"); + dep->de_lockwaiter = p->p_pid; + } else + dep->de_lockwaiter = -1; +#endif + (void) sleep((caddr_t)dep, PINOD); + goto start; + } +#ifdef DIAGNOSTIC + dep->de_lockwaiter = 0; + if (dep->de_lockholder != 0) + panic("lockholder (%d) != 0", dep->de_lockholder); + if (p && p->p_pid == 0) + printf("locking by process 0\n"); + if (p) + dep->de_lockholder = p->p_pid; + else + dep->de_lockholder = -1; +#endif + dep->de_flag |= DE_LOCKED; + return (0); +} + +int +msdosfs_unlock(ap) + struct vop_unlock_args /* { + struct vnode *vp; + } */ *ap; +{ + register struct denode *dep = VTODE(ap->a_vp); + struct proc *p = curproc; /* XXX */ + +#ifdef DIAGNOSTIC + if ((dep->de_flag & DE_LOCKED) == 0) { + vprint("msdosfs_unlock: unlocked denode", ap->a_vp); + panic("msdosfs_unlock NOT LOCKED"); + } + if (p && p->p_pid != dep->de_lockholder && p->p_pid > -1 && + dep->de_lockholder > -1/* && lockcount++ < 100*/) + panic("unlocker (%d) != lock holder (%d)", + p->p_pid, dep->de_lockholder); + dep->de_lockholder = 0; +#endif + dep->de_flag &= ~DE_LOCKED; + if (dep->de_flag & DE_WANTED) { + dep->de_flag &= ~DE_WANTED; + wakeup((caddr_t)dep); + } + return (0); +} + +int +msdosfs_islocked(ap) + struct vop_islocked_args /* { + struct vnode *a_vp; + } */ *ap; +{ + + if (VTODE(ap->a_vp)->de_flag & DE_LOCKED) + return (1); + return (0); +} + +/* + * vp - address of vnode file the file + * bn - which cluster we are interested in mapping to a filesystem block number. + * vpp - returns the vnode for the block special file holding the filesystem + * containing the file of interest + * bnp - address of where to return the filesystem relative block number + */ +int +msdosfs_bmap(ap) + struct vop_bmap_args /* { + struct vnode *a_vp; + daddr_t a_bn; + struct vnode **a_vpp; + daddr_t *a_bnp; + int *a_runp; + } */ *ap; +{ + struct denode *dep = VTODE(ap->a_vp); + struct msdosfsmount *pmp = dep->de_pmp; + + if (ap->a_vpp != NULL) + *ap->a_vpp = dep->de_devvp; + if (ap->a_bnp == NULL) + return (0); + if (ap->a_runp) { + /* + * Sequential clusters should be counted here. + */ + *ap->a_runp = 0; + } + return (pcbmap(dep, ap->a_bn << (pmp->pm_cnshift - pmp->pm_bnshift), + ap->a_bnp, 0, 0)); +} + +int +msdosfs_reallocblks(ap) + struct vop_reallocblks_args /* { + struct vnode *a_vp; + struct cluster_save *a_buflist; + } */ *ap; +{ + + /* Currently no support for clustering */ /* XXX */ + return (ENOSPC); +} + +int +msdosfs_strategy(ap) + struct vop_strategy_args /* { + struct buf *a_bp; + } */ *ap; +{ + struct buf *bp = ap->a_bp; + struct denode *dep = VTODE(bp->b_vp); + struct vnode *vp; + int error = 0; + + if (bp->b_vp->v_type == VBLK || bp->b_vp->v_type == VCHR) + panic("msdosfs_strategy: spec"); + /* + * If we don't already know the filesystem relative block number + * then get it using pcbmap(). If pcbmap() returns the block + * number as -1 then we've got a hole in the file. DOS filesystems + * don't allow files with holes, so we shouldn't ever see this. + */ + if (bp->b_blkno == bp->b_lblkno) { + if (error = pcbmap(dep, bp->b_lblkno, &bp->b_blkno, 0, 0)) + bp->b_blkno = -1; + if (bp->b_blkno == -1) + clrbuf(bp); + } + if (bp->b_blkno == -1) { + biodone(bp); + return (error); + } +#ifdef DIAGNOSTIC +#endif + /* + * Read/write the block from/to the disk that contains the desired + * file block. + */ + vp = dep->de_devvp; + bp->b_dev = vp->v_rdev; + VOCALL(vp->v_op, VOFFSET(vop_strategy), ap); + return (0); +} + +int +msdosfs_print(ap) + struct vop_print_args /* { + struct vnode *vp; + } */ *ap; +{ + struct denode *dep = VTODE(ap->a_vp); + + printf("tag VT_MSDOSFS, startcluster %d, dircluster %d, diroffset %d ", + dep->de_StartCluster, dep->de_dirclust, dep->de_diroffset); + printf(" dev %d, %d, %s\n", + major(dep->de_dev), minor(dep->de_dev), + dep->de_flag & DE_LOCKED ? "(LOCKED)" : ""); +#ifdef DIAGNOSTIC + if (dep->de_lockholder) { + printf(" owner pid %d", dep->de_lockholder); + if (dep->de_lockwaiter) + printf(" waiting pid %d", dep->de_lockwaiter); + printf("\n"); + } +#endif +} + +int +msdosfs_advlock(ap) + struct vop_advlock_args /* { + struct vnode *a_vp; + caddr_t a_id; + int a_op; + struct flock *a_fl; + int a_flags; + } */ *ap; +{ + + return (EINVAL); /* we don't do locking yet */ +} + +int +msdosfs_pathconf(ap) + struct vop_pathconf_args /* { + struct vnode *a_vp; + int a_name; + register_t *a_retval; + } */ *ap; +{ + + switch (ap->a_name) { + case _PC_LINK_MAX: + *ap->a_retval = 1; + return (0); + case _PC_NAME_MAX: + *ap->a_retval = 12; + return (0); + case _PC_PATH_MAX: + *ap->a_retval = PATH_MAX; + return (0); + case _PC_CHOWN_RESTRICTED: + *ap->a_retval = 1; + return (0); + case _PC_NO_TRUNC: + *ap->a_retval = 0; + return (0); + default: + return (EINVAL); + } + /* NOTREACHED */ +} + +/* Global vfs data structures for msdosfs */ +int (**msdosfs_vnodeop_p)(); +struct vnodeopv_entry_desc msdosfs_vnodeop_entries[] = { + { &vop_default_desc, vn_default_error }, + { &vop_lookup_desc, msdosfs_lookup }, /* lookup */ + { &vop_create_desc, msdosfs_create }, /* create */ + { &vop_mknod_desc, msdosfs_mknod }, /* mknod */ + { &vop_open_desc, msdosfs_open }, /* open */ + { &vop_close_desc, msdosfs_close }, /* close */ + { &vop_access_desc, msdosfs_access }, /* access */ + { &vop_getattr_desc, msdosfs_getattr }, /* getattr */ + { &vop_setattr_desc, msdosfs_setattr }, /* setattr */ + { &vop_read_desc, msdosfs_read }, /* read */ + { &vop_write_desc, msdosfs_write }, /* write */ + { &vop_lease_desc, msdosfs_lease_check }, /* lease */ + { &vop_ioctl_desc, msdosfs_ioctl }, /* ioctl */ + { &vop_select_desc, msdosfs_select }, /* select */ + { &vop_mmap_desc, msdosfs_mmap }, /* mmap */ + { &vop_fsync_desc, msdosfs_fsync }, /* fsync */ + { &vop_seek_desc, msdosfs_seek }, /* seek */ + { &vop_remove_desc, msdosfs_remove }, /* remove */ + { &vop_link_desc, msdosfs_link }, /* link */ + { &vop_rename_desc, msdosfs_rename }, /* rename */ + { &vop_mkdir_desc, msdosfs_mkdir }, /* mkdir */ + { &vop_rmdir_desc, msdosfs_rmdir }, /* rmdir */ + { &vop_symlink_desc, msdosfs_symlink }, /* symlink */ + { &vop_readdir_desc, msdosfs_readdir }, /* readdir */ + { &vop_readlink_desc, msdosfs_readlink }, /* readlink */ + { &vop_abortop_desc, msdosfs_abortop }, /* abortop */ + { &vop_inactive_desc, msdosfs_inactive }, /* inactive */ + { &vop_reclaim_desc, msdosfs_reclaim }, /* reclaim */ + { &vop_lock_desc, msdosfs_lock }, /* lock */ + { &vop_unlock_desc, msdosfs_unlock }, /* unlock */ + { &vop_bmap_desc, msdosfs_bmap }, /* bmap */ + { &vop_strategy_desc, msdosfs_strategy }, /* strategy */ + { &vop_print_desc, msdosfs_print }, /* print */ + { &vop_islocked_desc, msdosfs_islocked }, /* islocked */ + { &vop_pathconf_desc, msdosfs_pathconf }, /* pathconf */ + { &vop_advlock_desc, msdosfs_advlock }, /* advlock */ + { &vop_reallocblks_desc, msdosfs_reallocblks }, /* reallocblks */ + { &vop_bwrite_desc, vn_bwrite }, + { (struct vnodeop_desc *)NULL, (int (*)())NULL } +}; +struct vnodeopv_desc msdosfs_vnodeop_opv_desc = + { &msdosfs_vnodeop_p, msdosfs_vnodeop_entries }; diff --git a/sys/msdosfs/msdosfsmount.h b/sys/msdosfs/msdosfsmount.h new file mode 100644 index 00000000000..2267f685b94 --- /dev/null +++ b/sys/msdosfs/msdosfsmount.h @@ -0,0 +1,167 @@ +/* $NetBSD: msdosfsmount.h,v 1.11 1995/09/09 19:38:12 ws Exp $ */ + +/*- + * Copyright (C) 1994 Wolfgang Solfrank. + * Copyright (C) 1994 TooLs GmbH. + * All rights reserved. + * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below). + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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. + */ +/* + * Written by Paul Popelka (paulp@uts.amdahl.com) + * + * You can do anything you want with this software, just don't say you wrote + * it, and don't remove this notice. + * + * This software is provided "as is". + * + * The author supplies this software to be publicly redistributed on the + * understanding that the author is not responsible for the correct + * functioning of this software in any circumstances and is not liable for + * any damages caused by this software. + * + * October 1992 + */ + +/* + * Layout of the mount control block for a msdos file system. + */ +struct msdosfsmount { + struct mount *pm_mountp;/* vfs mount struct for this fs */ + dev_t pm_dev; /* block special device mounted */ + uid_t pm_uid; /* uid to set as owner of the files */ + gid_t pm_gid; /* gid to set as owner of the files */ + mode_t pm_mask; /* mask to and with file protection bits */ + struct vnode *pm_devvp; /* vnode for block device mntd */ + struct bpb50 pm_bpb; /* BIOS parameter blk for this fs */ + u_long pm_fatblk; /* block # of first FAT */ + u_long pm_rootdirblk; /* block # of root directory */ + u_long pm_rootdirsize; /* size in blocks (not clusters) */ + u_long pm_firstcluster; /* block number of first cluster */ + u_long pm_nmbrofclusters; /* # of clusters in filesystem */ + u_long pm_maxcluster; /* maximum cluster number */ + u_long pm_freeclustercount; /* number of free clusters */ + u_long pm_bnshift; /* shift file offset right this amount to get a block number */ + u_long pm_brbomask; /* and a file offset with this mask to get block rel offset */ + u_long pm_cnshift; /* shift file offset right this amount to get a cluster number */ + u_long pm_crbomask; /* and a file offset with this mask to get cluster rel offset */ + u_long pm_bpcluster; /* bytes per cluster */ + u_long pm_fmod; /* ~0 if fs is modified, this can rollover to 0 */ + u_long pm_fatblocksize; /* size of fat blocks in bytes */ + u_long pm_fatblocksec; /* size of fat blocks in sectors */ + u_long pm_fatsize; /* size of fat in bytes */ + u_int *pm_inusemap; /* ptr to bitmap of in-use clusters */ + char pm_ronly; /* read only if non-zero */ + char pm_waitonfat; /* wait for writes of the fat to complt, when 0 use bdwrite, else use bwrite */ + struct netexport pm_export; /* export information */ +#ifdef atari + u_int pm_fatentrysize; /* size of fat entry (12/16) */ +#endif /* atari */ +}; + +#define VFSTOMSDOSFS(mp) ((struct msdosfsmount *)mp->mnt_data) + +/* Number of bits in one pm_inusemap item: */ +#define N_INUSEBITS (8 * sizeof(u_int)) + +/* + * Shorthand for fields in the bpb contained in the msdosfsmount structure. + */ +#define pm_BytesPerSec pm_bpb.bpbBytesPerSec +#define pm_SectPerClust pm_bpb.bpbSecPerClust +#define pm_ResSectors pm_bpb.bpbResSectors +#define pm_FATs pm_bpb.bpbFATs +#define pm_RootDirEnts pm_bpb.bpbRootDirEnts +#define pm_Sectors pm_bpb.bpbSectors +#define pm_Media pm_bpb.bpbMedia +#define pm_FATsecs pm_bpb.bpbFATsecs +#define pm_SecPerTrack pm_bpb.bpbSecPerTrack +#define pm_Heads pm_bpb.bpbHeads +#define pm_HiddenSects pm_bpb.bpbHiddenSecs +#define pm_HugeSectors pm_bpb.bpbHugeSectors + +/* + * Map a cluster number into a filesystem relative block number. + */ +#define cntobn(pmp, cn) \ + ((((cn)-CLUST_FIRST) * (pmp)->pm_SectPerClust) + (pmp)->pm_firstcluster) + +/* + * Map a filesystem relative block number back into a cluster number. + */ +#define bntocn(pmp, bn) \ + ((((bn) - pmp->pm_firstcluster) / (pmp)->pm_SectPerClust) + CLUST_FIRST) + +/* + * Calculate block number for directory entry in root dir, offset dirofs + */ +#define roottobn(pmp, dirofs) \ + (((dirofs) / (pmp)->pm_bpcluster) * (pmp)->pm_SectPerClust \ + + (pmp)->pm_rootdirblk) + +/* + * Calculate block number for directory entry at cluster dirclu, offset + * dirofs + */ +#define detobn(pmp, dirclu, dirofs) \ + ((dirclu) == MSDOSFSROOT \ + ? roottobn((pmp), (dirofs)) \ + : cntobn((pmp), (dirclu))) + +/* + * Convert pointer to buffer -> pointer to direntry + */ +#define bptoep(pmp, bp, dirofs) \ + ((struct direntry *)(((bp)->b_data) \ + + ((dirofs) & (pmp)->pm_crbomask))) + + +/* + * Convert filesize to block number + */ +#define de_blk(pmp, off) \ + ((off) >> (pmp)->pm_cnshift) + +/* + * Clusters required to hold size bytes + */ +#define de_clcount(pmp, size) \ + (((size) + (pmp)->pm_bpcluster - 1) >> (pmp)->pm_cnshift) + +/* + * Prototypes for MSDOSFS virtual filesystem operations + */ +int msdosfs_mount __P((struct mount *, char *, caddr_t, struct nameidata *, struct proc *)); +int msdosfs_start __P((struct mount *, int, struct proc *)); +int msdosfs_unmount __P((struct mount *, int, struct proc *)); +int msdosfs_root __P((struct mount *, struct vnode **)); +int msdosfs_quotactl __P((struct mount *, int, uid_t, caddr_t, struct proc *)); +int msdosfs_statfs __P((struct mount *, struct statfs *, struct proc *)); +int msdosfs_sync __P((struct mount *, int, struct ucred *, struct proc *)); +int msdosfs_fhtovp __P((struct mount *, struct fid *, struct mbuf *, struct vnode **, int *, struct ucred **)); +int msdosfs_vptofh __P((struct vnode *, struct fid *)); +int msdosfs_init __P(()); |