Index: head/sbin/newfs_msdos/mkfs_msdos.c =================================================================== --- head/sbin/newfs_msdos/mkfs_msdos.c (revision 298249) +++ head/sbin/newfs_msdos/mkfs_msdos.c (revision 298250) @@ -1,959 +1,959 @@ /* * Copyright (c) 1998 Robert Nordier * All rights reserved. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef lint static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mkfs_msdos.h" #define MAXU16 0xffff /* maximum unsigned 16-bit quantity */ #define BPN 4 /* bits per nibble */ #define NPB 2 /* nibbles per byte */ #define DOSMAGIC 0xaa55 /* DOS magic number */ #define MINBPS 512 /* minimum bytes per sector */ #define MAXSPC 128 /* maximum sectors per cluster */ #define MAXNFT 16 /* maximum number of FATs */ #define DEFBLK 4096 /* default block size */ #define DEFBLK16 2048 /* default block size FAT16 */ #define DEFRDE 512 /* default root directory entries */ #define RESFTE 2 /* reserved FAT entries */ #define MINCLS12 1U /* minimum FAT12 clusters */ #define MINCLS16 0xff5U /* minimum FAT16 clusters */ #define MINCLS32 0xfff5U /* minimum FAT32 clusters */ #define MAXCLS12 0xff4U /* maximum FAT12 clusters */ #define MAXCLS16 0xfff4U /* maximum FAT16 clusters */ #define MAXCLS32 0xffffff4U /* maximum FAT32 clusters */ #define mincls(fat) ((fat) == 12 ? MINCLS12 : \ (fat) == 16 ? MINCLS16 : \ MINCLS32) #define maxcls(fat) ((fat) == 12 ? MAXCLS12 : \ (fat) == 16 ? MAXCLS16 : \ MAXCLS32) #define mk1(p, x) \ (p) = (u_int8_t)(x) #define mk2(p, x) \ (p)[0] = (u_int8_t)(x), \ (p)[1] = (u_int8_t)((x) >> 010) #define mk4(p, x) \ (p)[0] = (u_int8_t)(x), \ (p)[1] = (u_int8_t)((x) >> 010), \ (p)[2] = (u_int8_t)((x) >> 020), \ (p)[3] = (u_int8_t)((x) >> 030) struct bs { u_int8_t bsJump[3]; /* bootstrap entry point */ u_int8_t bsOemName[8]; /* OEM name and version */ } __packed; struct bsbpb { u_int8_t bpbBytesPerSec[2]; /* bytes per sector */ u_int8_t bpbSecPerClust; /* sectors per cluster */ u_int8_t bpbResSectors[2]; /* reserved sectors */ u_int8_t bpbFATs; /* number of FATs */ u_int8_t bpbRootDirEnts[2]; /* root directory entries */ u_int8_t bpbSectors[2]; /* total sectors */ u_int8_t bpbMedia; /* media descriptor */ u_int8_t bpbFATsecs[2]; /* sectors per FAT */ u_int8_t bpbSecPerTrack[2]; /* sectors per track */ u_int8_t bpbHeads[2]; /* drive heads */ u_int8_t bpbHiddenSecs[4]; /* hidden sectors */ u_int8_t bpbHugeSectors[4]; /* big total sectors */ } __packed; struct bsxbpb { u_int8_t bpbBigFATsecs[4]; /* big sectors per FAT */ u_int8_t bpbExtFlags[2]; /* FAT control flags */ u_int8_t bpbFSVers[2]; /* file system version */ u_int8_t bpbRootClust[4]; /* root directory start cluster */ u_int8_t bpbFSInfo[2]; /* file system info sector */ u_int8_t bpbBackup[2]; /* backup boot sector */ u_int8_t bpbReserved[12]; /* reserved */ } __packed; struct bsx { u_int8_t exDriveNumber; /* drive number */ u_int8_t exReserved1; /* reserved */ u_int8_t exBootSignature; /* extended boot signature */ u_int8_t exVolumeID[4]; /* volume ID number */ u_int8_t exVolumeLabel[11]; /* volume label */ u_int8_t exFileSysType[8]; /* file system type */ } __packed; struct de { u_int8_t deName[11]; /* name and extension */ u_int8_t deAttributes; /* attributes */ u_int8_t rsvd[10]; /* reserved */ u_int8_t deMTime[2]; /* last-modified time */ u_int8_t deMDate[2]; /* last-modified date */ u_int8_t deStartCluster[2]; /* starting cluster */ u_int8_t deFileSize[4]; /* size */ } __packed; struct bpb { u_int bpbBytesPerSec; /* bytes per sector */ u_int bpbSecPerClust; /* sectors per cluster */ u_int bpbResSectors; /* reserved sectors */ u_int bpbFATs; /* number of FATs */ u_int bpbRootDirEnts; /* root directory entries */ u_int bpbSectors; /* total sectors */ u_int bpbMedia; /* media descriptor */ u_int bpbFATsecs; /* sectors per FAT */ u_int bpbSecPerTrack; /* sectors per track */ u_int bpbHeads; /* drive heads */ u_int bpbHiddenSecs; /* hidden sectors */ u_int bpbHugeSectors; /* big total sectors */ u_int bpbBigFATsecs; /* big sectors per FAT */ u_int bpbRootClust; /* root directory start cluster */ u_int bpbFSInfo; /* file system info sector */ u_int bpbBackup; /* backup boot sector */ }; #define BPBGAP 0, 0, 0, 0, 0, 0 static struct { const char *name; struct bpb bpb; } const stdfmt[] = { {"160", {512, 1, 1, 2, 64, 320, 0xfe, 1, 8, 1, BPBGAP}}, {"180", {512, 1, 1, 2, 64, 360, 0xfc, 2, 9, 1, BPBGAP}}, {"320", {512, 2, 1, 2, 112, 640, 0xff, 1, 8, 2, BPBGAP}}, {"360", {512, 2, 1, 2, 112, 720, 0xfd, 2, 9, 2, BPBGAP}}, {"640", {512, 2, 1, 2, 112, 1280, 0xfb, 2, 8, 2, BPBGAP}}, {"720", {512, 2, 1, 2, 112, 1440, 0xf9, 3, 9, 2, BPBGAP}}, {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2, BPBGAP}}, {"1232", {1024,1, 1, 2, 192, 1232, 0xfe, 2, 8, 2, BPBGAP}}, {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2, BPBGAP}}, {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2, BPBGAP}} }; static const u_int8_t bootcode[] = { 0xfa, /* cli */ 0x31, 0xc0, /* xor ax,ax */ 0x8e, 0xd0, /* mov ss,ax */ 0xbc, 0x00, 0x7c, /* mov sp,7c00h */ 0xfb, /* sti */ 0x8e, 0xd8, /* mov ds,ax */ 0xe8, 0x00, 0x00, /* call $ + 3 */ 0x5e, /* pop si */ 0x83, 0xc6, 0x19, /* add si,+19h */ 0xbb, 0x07, 0x00, /* mov bx,0007h */ 0xfc, /* cld */ 0xac, /* lodsb */ 0x84, 0xc0, /* test al,al */ 0x74, 0x06, /* jz $ + 8 */ 0xb4, 0x0e, /* mov ah,0eh */ 0xcd, 0x10, /* int 10h */ 0xeb, 0xf5, /* jmp $ - 9 */ 0x30, 0xe4, /* xor ah,ah */ 0xcd, 0x16, /* int 16h */ 0xcd, 0x19, /* int 19h */ 0x0d, 0x0a, 'N', 'o', 'n', '-', 's', 'y', 's', 't', 'e', 'm', ' ', 'd', 'i', 's', 'k', 0x0d, 0x0a, 'P', 'r', 'e', 's', 's', ' ', 'a', 'n', 'y', ' ', 'k', 'e', 'y', ' ', 't', 'o', ' ', 'r', 'e', 'b', 'o', 'o', 't', 0x0d, 0x0a, 0 }; static volatile sig_atomic_t got_siginfo; static void infohandler(int); static int check_mounted(const char *, mode_t); static int getstdfmt(const char *, struct bpb *); static int getdiskinfo(int, const char *, const char *, int, struct bpb *); static void print_bpb(struct bpb *); static int ckgeom(const char *, u_int, const char *); static void mklabel(u_int8_t *, const char *); static int oklabel(const char *); static void setstr(u_int8_t *, const char *, size_t); int mkfs_msdos(const char *fname, const char *dtype, const struct msdos_options *op) { char buf[MAXPATHLEN]; struct sigaction si_sa; struct stat sb; struct timeval tv; struct bpb bpb; struct tm *tm; struct bs *bs; struct bsbpb *bsbpb; struct bsxbpb *bsxbpb; struct bsx *bsx; struct de *de; u_int8_t *img; const char *bname; ssize_t n; time_t now; u_int fat, bss, rds, cls, dir, lsn, x, x1, x2; int fd, fd1, rv; struct msdos_options o = *op; img = NULL; rv = -1; if (o.block_size && o.sectors_per_cluster) { warnx("Cannot specify both block size and sectors per cluster"); goto done; } if (o.OEM_string && strlen(o.OEM_string) > 8) { warnx("%s: bad OEM string", o.OEM_string); goto done; } if (o.create_size) { if (o.no_create) { warnx("create (-C) is incompatible with -N"); goto done; } fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0644); if (fd == -1) { warnx("failed to create %s", fname); goto done; } if (ftruncate(fd, o.create_size)) { warnx("failed to initialize %jd bytes", (intmax_t)o.create_size); goto done; } } else if ((fd = open(fname, o.no_create ? O_RDONLY : O_RDWR)) == -1) { warn("%s", fname); goto done; } if (fstat(fd, &sb)) { warn("%s", fname); goto done; } if (o.create_size) { if (!S_ISREG(sb.st_mode)) warnx("warning, %s is not a regular file", fname); } else { if (!S_ISCHR(sb.st_mode)) warnx("warning, %s is not a character device", fname); } if (!o.no_create) if (check_mounted(fname, sb.st_mode) == -1) goto done; if (o.offset && o.offset != lseek(fd, o.offset, SEEK_SET)) { warnx("cannot seek to %jd", (intmax_t)o.offset); goto done; } memset(&bpb, 0, sizeof(bpb)); if (o.floppy) { if (getstdfmt(o.floppy, &bpb) == -1) goto done; bpb.bpbHugeSectors = bpb.bpbSectors; bpb.bpbSectors = 0; bpb.bpbBigFATsecs = bpb.bpbFATsecs; bpb.bpbFATsecs = 0; } if (o.drive_heads) bpb.bpbHeads = o.drive_heads; if (o.sectors_per_track) bpb.bpbSecPerTrack = o.sectors_per_track; if (o.bytes_per_sector) bpb.bpbBytesPerSec = o.bytes_per_sector; if (o.size) bpb.bpbHugeSectors = o.size; if (o.hidden_sectors_set) bpb.bpbHiddenSecs = o.hidden_sectors; if (!(o.floppy || (o.drive_heads && o.sectors_per_track && o.bytes_per_sector && o.size && o.hidden_sectors_set))) { off_t delta; getdiskinfo(fd, fname, dtype, o.hidden_sectors_set, &bpb); bpb.bpbHugeSectors -= (o.offset / bpb.bpbBytesPerSec); delta = bpb.bpbHugeSectors % bpb.bpbSecPerTrack; if (delta != 0) { warnx("trim %d sectors to adjust to a multiple of %d", (int)delta, bpb.bpbSecPerTrack); bpb.bpbHugeSectors -= delta; } if (bpb.bpbSecPerClust == 0) { /* set defaults */ if (bpb.bpbHugeSectors <= 6000) /* about 3MB -> 512 bytes */ bpb.bpbSecPerClust = 1; else if (bpb.bpbHugeSectors <= (1<<17)) /* 64M -> 4k */ bpb.bpbSecPerClust = 8; else if (bpb.bpbHugeSectors <= (1<<19)) /* 256M -> 8k */ bpb.bpbSecPerClust = 16; else if (bpb.bpbHugeSectors <= (1<<21)) /* 1G -> 16k */ bpb.bpbSecPerClust = 32; else bpb.bpbSecPerClust = 64; /* otherwise 32k */ } } if (!powerof2(bpb.bpbBytesPerSec)) { warnx("bytes/sector (%u) is not a power of 2", bpb.bpbBytesPerSec); goto done; } if (bpb.bpbBytesPerSec < MINBPS) { warnx("bytes/sector (%u) is too small; minimum is %u", bpb.bpbBytesPerSec, MINBPS); goto done; } if (o.volume_label && !oklabel(o.volume_label)) { warnx("%s: bad volume label", o.volume_label); goto done; } if (!(fat = o.fat_type)) { if (o.floppy) fat = 12; else if (!o.directory_entries && (o.info_sector || o.backup_sector)) fat = 32; } if ((fat == 32 && o.directory_entries) || (fat != 32 && (o.info_sector || o.backup_sector))) { warnx("-%c is not a legal FAT%s option", fat == 32 ? 'e' : o.info_sector ? 'i' : 'k', fat == 32 ? "32" : "12/16"); goto done; } if (o.floppy && fat == 32) bpb.bpbRootDirEnts = 0; if (fat != 0 && fat != 12 && fat != 16 && fat != 32) { warnx("%d: bad FAT type", fat); goto done; } if (o.block_size) { if (!powerof2(o.block_size)) { warnx("block size (%u) is not a power of 2", o.block_size); goto done; } if (o.block_size < bpb.bpbBytesPerSec) { warnx("block size (%u) is too small; minimum is %u", o.block_size, bpb.bpbBytesPerSec); goto done; } if (o.block_size > bpb.bpbBytesPerSec * MAXSPC) { warnx("block size (%u) is too large; maximum is %u", o.block_size, bpb.bpbBytesPerSec * MAXSPC); goto done; } bpb.bpbSecPerClust = o.block_size / bpb.bpbBytesPerSec; } if (o.sectors_per_cluster) { if (!powerof2(o.sectors_per_cluster)) { warnx("sectors/cluster (%u) is not a power of 2", o.sectors_per_cluster); goto done; } bpb.bpbSecPerClust = o.sectors_per_cluster; } if (o.reserved_sectors) bpb.bpbResSectors = o.reserved_sectors; if (o.num_FAT) { if (o.num_FAT > MAXNFT) { warnx("number of FATs (%u) is too large; maximum is %u", o.num_FAT, MAXNFT); goto done; } bpb.bpbFATs = o.num_FAT; } if (o.directory_entries) bpb.bpbRootDirEnts = o.directory_entries; if (o.media_descriptor_set) { if (o.media_descriptor < 0xf0) { warnx("illegal media descriptor (%#x)", o.media_descriptor); goto done; } bpb.bpbMedia = o.media_descriptor; } if (o.sectors_per_fat) bpb.bpbBigFATsecs = o.sectors_per_fat; if (o.info_sector) bpb.bpbFSInfo = o.info_sector; if (o.backup_sector) bpb.bpbBackup = o.backup_sector; bss = 1; bname = NULL; fd1 = -1; if (o.bootstrap) { bname = o.bootstrap; if (!strchr(bname, '/')) { snprintf(buf, sizeof(buf), "/boot/%s", bname); if (!(bname = strdup(buf))) { warn(NULL); goto done; } } if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb)) { warn("%s", bname); goto done; } if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bpbBytesPerSec || sb.st_size < bpb.bpbBytesPerSec || sb.st_size > bpb.bpbBytesPerSec * MAXU16) { warnx("%s: inappropriate file type or format", bname); goto done; } bss = sb.st_size / bpb.bpbBytesPerSec; } if (!bpb.bpbFATs) bpb.bpbFATs = 2; if (!fat) { if (bpb.bpbHugeSectors < (bpb.bpbResSectors ? bpb.bpbResSectors : bss) + howmany((RESFTE + (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1)) * (bpb.bpbSecPerClust ? 16 : 12) / BPN, bpb.bpbBytesPerSec * NPB) * bpb.bpbFATs + howmany(bpb.bpbRootDirEnts ? bpb.bpbRootDirEnts : DEFRDE, bpb.bpbBytesPerSec / sizeof(struct de)) + (bpb.bpbSecPerClust ? MINCLS16 : MAXCLS12 + 1) * (bpb.bpbSecPerClust ? bpb.bpbSecPerClust : howmany(DEFBLK, bpb.bpbBytesPerSec))) fat = 12; else if (bpb.bpbRootDirEnts || bpb.bpbHugeSectors < (bpb.bpbResSectors ? bpb.bpbResSectors : bss) + howmany((RESFTE + MAXCLS16) * 2, bpb.bpbBytesPerSec) * bpb.bpbFATs + howmany(DEFRDE, bpb.bpbBytesPerSec / sizeof(struct de)) + (MAXCLS16 + 1) * (bpb.bpbSecPerClust ? bpb.bpbSecPerClust : howmany(8192, bpb.bpbBytesPerSec))) fat = 16; else fat = 32; } x = bss; if (fat == 32) { if (!bpb.bpbFSInfo) { if (x == MAXU16 || x == bpb.bpbBackup) { warnx("no room for info sector"); goto done; } bpb.bpbFSInfo = x; } if (bpb.bpbFSInfo != MAXU16 && x <= bpb.bpbFSInfo) x = bpb.bpbFSInfo + 1; if (!bpb.bpbBackup) { if (x == MAXU16) { warnx("no room for backup sector"); goto done; } bpb.bpbBackup = x; } else if (bpb.bpbBackup != MAXU16 && bpb.bpbBackup == bpb.bpbFSInfo) { warnx("backup sector would overwrite info sector"); goto done; } if (bpb.bpbBackup != MAXU16 && x <= bpb.bpbBackup) x = bpb.bpbBackup + 1; } if (!bpb.bpbResSectors) bpb.bpbResSectors = fat == 32 ? MAX(x, MAX(16384 / bpb.bpbBytesPerSec, 4)) : x; else if (bpb.bpbResSectors < x) { warnx("too few reserved sectors (need %d have %d)", x, bpb.bpbResSectors); goto done; } if (fat != 32 && !bpb.bpbRootDirEnts) bpb.bpbRootDirEnts = DEFRDE; rds = howmany(bpb.bpbRootDirEnts, bpb.bpbBytesPerSec / sizeof(struct de)); if (!bpb.bpbSecPerClust) for (bpb.bpbSecPerClust = howmany(fat == 16 ? DEFBLK16 : DEFBLK, bpb.bpbBytesPerSec); bpb.bpbSecPerClust < MAXSPC && bpb.bpbResSectors + howmany((RESFTE + maxcls(fat)) * (fat / BPN), bpb.bpbBytesPerSec * NPB) * bpb.bpbFATs + rds + (u_int64_t) (maxcls(fat) + 1) * bpb.bpbSecPerClust <= bpb.bpbHugeSectors; bpb.bpbSecPerClust <<= 1) continue; if (fat != 32 && bpb.bpbBigFATsecs > MAXU16) { warnx("too many sectors/FAT for FAT12/16"); goto done; } x1 = bpb.bpbResSectors + rds; x = bpb.bpbBigFATsecs ? bpb.bpbBigFATsecs : 1; if (x1 + (u_int64_t)x * bpb.bpbFATs > bpb.bpbHugeSectors) { warnx("meta data exceeds file system size"); goto done; } x1 += x * bpb.bpbFATs; x = (u_int64_t)(bpb.bpbHugeSectors - x1) * bpb.bpbBytesPerSec * NPB / (bpb.bpbSecPerClust * bpb.bpbBytesPerSec * NPB + fat / BPN * bpb.bpbFATs); x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN), bpb.bpbBytesPerSec * NPB); if (!bpb.bpbBigFATsecs) { bpb.bpbBigFATsecs = x2; x1 += (bpb.bpbBigFATsecs - 1) * bpb.bpbFATs; } cls = (bpb.bpbHugeSectors - x1) / bpb.bpbSecPerClust; x = (u_int64_t)bpb.bpbBigFATsecs * bpb.bpbBytesPerSec * NPB / (fat / BPN) - RESFTE; if (cls > x) cls = x; if (bpb.bpbBigFATsecs < x2) warnx("warning: sectors/FAT limits file system to %u clusters", cls); if (cls < mincls(fat)) { warnx("%u clusters too few clusters for FAT%u, need %u", cls, fat, mincls(fat)); goto done; } if (cls > maxcls(fat)) { cls = maxcls(fat); bpb.bpbHugeSectors = x1 + (cls + 1) * bpb.bpbSecPerClust - 1; warnx("warning: FAT type limits file system to %u sectors", bpb.bpbHugeSectors); } printf("%s: %u sector%s in %u FAT%u cluster%s " "(%u bytes/cluster)\n", fname, cls * bpb.bpbSecPerClust, cls * bpb.bpbSecPerClust == 1 ? "" : "s", cls, fat, cls == 1 ? "" : "s", bpb.bpbBytesPerSec * bpb.bpbSecPerClust); if (!bpb.bpbMedia) bpb.bpbMedia = !bpb.bpbHiddenSecs ? 0xf0 : 0xf8; if (fat == 32) bpb.bpbRootClust = RESFTE; if (bpb.bpbHiddenSecs + bpb.bpbHugeSectors <= MAXU16) { bpb.bpbSectors = bpb.bpbHugeSectors; bpb.bpbHugeSectors = 0; } if (fat != 32) { bpb.bpbFATsecs = bpb.bpbBigFATsecs; bpb.bpbBigFATsecs = 0; } print_bpb(&bpb); if (!o.no_create) { gettimeofday(&tv, NULL); now = tv.tv_sec; tm = localtime(&now); if (!(img = malloc(bpb.bpbBytesPerSec))) { warn(NULL); goto done; } dir = bpb.bpbResSectors + (bpb.bpbFATsecs ? bpb.bpbFATsecs : bpb.bpbBigFATsecs) * bpb.bpbFATs; memset(&si_sa, 0, sizeof(si_sa)); si_sa.sa_handler = infohandler; if (sigaction(SIGINFO, &si_sa, NULL) == -1) { warn("sigaction SIGINFO"); goto done; } for (lsn = 0; lsn < dir + (fat == 32 ? bpb.bpbSecPerClust : rds); lsn++) { if (got_siginfo) { fprintf(stderr,"%s: writing sector %u of %u (%u%%)\n", fname, lsn, (dir + (fat == 32 ? bpb.bpbSecPerClust: rds)), (lsn * 100) / (dir + (fat == 32 ? bpb.bpbSecPerClust: rds))); got_siginfo = 0; } x = lsn; if (o.bootstrap && fat == 32 && bpb.bpbBackup != MAXU16 && bss <= bpb.bpbBackup && x >= bpb.bpbBackup) { x -= bpb.bpbBackup; if (!x && lseek(fd1, o.offset, SEEK_SET)) { warn("%s", bname); goto done; } } if (o.bootstrap && x < bss) { if ((n = read(fd1, img, bpb.bpbBytesPerSec)) == -1) { warn("%s", bname); goto done; } if ((unsigned)n != bpb.bpbBytesPerSec) { warnx("%s: can't read sector %u", bname, x); goto done; } } else memset(img, 0, bpb.bpbBytesPerSec); if (!lsn || (fat == 32 && bpb.bpbBackup != MAXU16 && lsn == bpb.bpbBackup)) { x1 = sizeof(struct bs); bsbpb = (struct bsbpb *)(img + x1); mk2(bsbpb->bpbBytesPerSec, bpb.bpbBytesPerSec); mk1(bsbpb->bpbSecPerClust, bpb.bpbSecPerClust); mk2(bsbpb->bpbResSectors, bpb.bpbResSectors); mk1(bsbpb->bpbFATs, bpb.bpbFATs); mk2(bsbpb->bpbRootDirEnts, bpb.bpbRootDirEnts); mk2(bsbpb->bpbSectors, bpb.bpbSectors); mk1(bsbpb->bpbMedia, bpb.bpbMedia); mk2(bsbpb->bpbFATsecs, bpb.bpbFATsecs); mk2(bsbpb->bpbSecPerTrack, bpb.bpbSecPerTrack); mk2(bsbpb->bpbHeads, bpb.bpbHeads); mk4(bsbpb->bpbHiddenSecs, bpb.bpbHiddenSecs); mk4(bsbpb->bpbHugeSectors, bpb.bpbHugeSectors); x1 += sizeof(struct bsbpb); if (fat == 32) { bsxbpb = (struct bsxbpb *)(img + x1); mk4(bsxbpb->bpbBigFATsecs, bpb.bpbBigFATsecs); mk2(bsxbpb->bpbExtFlags, 0); mk2(bsxbpb->bpbFSVers, 0); mk4(bsxbpb->bpbRootClust, bpb.bpbRootClust); mk2(bsxbpb->bpbFSInfo, bpb.bpbFSInfo); mk2(bsxbpb->bpbBackup, bpb.bpbBackup); x1 += sizeof(struct bsxbpb); } bsx = (struct bsx *)(img + x1); mk1(bsx->exBootSignature, 0x29); if (o.volume_id_set) x = o.volume_id; else x = (((u_int)(1 + tm->tm_mon) << 8 | (u_int)tm->tm_mday) + ((u_int)tm->tm_sec << 8 | (u_int)(tv.tv_usec / 10))) << 16 | ((u_int)(1900 + tm->tm_year) + ((u_int)tm->tm_hour << 8 | (u_int)tm->tm_min)); mk4(bsx->exVolumeID, x); mklabel(bsx->exVolumeLabel, o.volume_label ? o.volume_label : "NO NAME"); snprintf(buf, sizeof(buf), "FAT%u", fat); setstr(bsx->exFileSysType, buf, sizeof(bsx->exFileSysType)); if (!o.bootstrap) { x1 += sizeof(struct bsx); bs = (struct bs *)img; mk1(bs->bsJump[0], 0xeb); mk1(bs->bsJump[1], x1 - 2); mk1(bs->bsJump[2], 0x90); setstr(bs->bsOemName, o.OEM_string ? o.OEM_string : "BSD4.4 ", sizeof(bs->bsOemName)); memcpy(img + x1, bootcode, sizeof(bootcode)); mk2(img + MINBPS - 2, DOSMAGIC); } } else if (fat == 32 && bpb.bpbFSInfo != MAXU16 && (lsn == bpb.bpbFSInfo || (bpb.bpbBackup != MAXU16 && lsn == bpb.bpbBackup + bpb.bpbFSInfo))) { mk4(img, 0x41615252); mk4(img + MINBPS - 28, 0x61417272); mk4(img + MINBPS - 24, 0xffffffff); mk4(img + MINBPS - 20, bpb.bpbRootClust); mk2(img + MINBPS - 2, DOSMAGIC); } else if (lsn >= bpb.bpbResSectors && lsn < dir && !((lsn - bpb.bpbResSectors) % (bpb.bpbFATsecs ? bpb.bpbFATsecs : bpb.bpbBigFATsecs))) { mk1(img[0], bpb.bpbMedia); for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++) mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff); } else if (lsn == dir && o.volume_label) { de = (struct de *)img; mklabel(de->deName, o.volume_label); mk1(de->deAttributes, 050); x = (u_int)tm->tm_hour << 11 | (u_int)tm->tm_min << 5 | (u_int)tm->tm_sec >> 1; mk2(de->deMTime, x); x = (u_int)(tm->tm_year - 80) << 9 | (u_int)(tm->tm_mon + 1) << 5 | (u_int)tm->tm_mday; mk2(de->deMDate, x); } if ((n = write(fd, img, bpb.bpbBytesPerSec)) == -1) { warn("%s", fname); goto done; } if ((unsigned)n != bpb.bpbBytesPerSec) { warnx("%s: can't write sector %u", fname, lsn); goto done; } } } rv = 0; done: free(img); return rv; } /* * return -1 with error if file system is mounted. */ static int check_mounted(const char *fname, mode_t mode) { struct statfs *mp; const char *s1, *s2; size_t len; int n, r; if (!(n = getmntinfo(&mp, MNT_NOWAIT))) { warn("getmntinfo"); return -1; } len = strlen(_PATH_DEV); s1 = fname; if (!strncmp(s1, _PATH_DEV, len)) s1 += len; r = S_ISCHR(mode) && s1 != fname && *s1 == 'r'; for (; n--; mp++) { s2 = mp->f_mntfromname; if (!strncmp(s2, _PATH_DEV, len)) s2 += len; if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) || !strcmp(s1, s2)) { warnx("%s is mounted on %s", fname, mp->f_mntonname); return -1; } } return 0; } /* * Get a standard format. */ static int getstdfmt(const char *fmt, struct bpb *bpb) { u_int x, i; - x = sizeof(stdfmt) / sizeof(stdfmt[0]); + x = nitems(stdfmt); for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++); if (i == x) { warnx("%s: unknown standard format", fmt); return -1; } *bpb = stdfmt[i].bpb; return 0; } /* * Get disk slice, partition, and geometry information. */ static int getdiskinfo(int fd, const char *fname, const char *dtype, __unused int oflag, struct bpb *bpb) { struct disklabel *lp, dlp; struct fd_type type; off_t ms, hs = 0; lp = NULL; /* If the user specified a disk type, try to use that */ if (dtype != NULL) { lp = getdiskbyname(dtype); } /* Maybe it's a floppy drive */ if (lp == NULL) { if (ioctl(fd, DIOCGMEDIASIZE, &ms) == -1) { struct stat st; if (fstat(fd, &st)) err(1, "cannot get disk size"); /* create a fake geometry for a file image */ ms = st.st_size; dlp.d_secsize = 512; dlp.d_nsectors = 63; dlp.d_ntracks = 255; dlp.d_secperunit = ms / dlp.d_secsize; lp = &dlp; } else if (ioctl(fd, FD_GTYPE, &type) != -1) { dlp.d_secsize = 128 << type.secsize; dlp.d_nsectors = type.sectrac; dlp.d_ntracks = type.heads; dlp.d_secperunit = ms / dlp.d_secsize; lp = &dlp; } } /* Maybe it's a fixed drive */ if (lp == NULL) { if (bpb->bpbBytesPerSec) dlp.d_secsize = bpb->bpbBytesPerSec; if (bpb->bpbBytesPerSec == 0 && ioctl(fd, DIOCGSECTORSIZE, &dlp.d_secsize) == -1) err(1, "cannot get sector size"); dlp.d_secperunit = ms / dlp.d_secsize; if (bpb->bpbSecPerTrack == 0 && ioctl(fd, DIOCGFWSECTORS, &dlp.d_nsectors) == -1) { warn("cannot get number of sectors per track"); dlp.d_nsectors = 63; } if (bpb->bpbHeads == 0 && ioctl(fd, DIOCGFWHEADS, &dlp.d_ntracks) == -1) { warn("cannot get number of heads"); if (dlp.d_secperunit <= 63*1*1024) dlp.d_ntracks = 1; else if (dlp.d_secperunit <= 63*16*1024) dlp.d_ntracks = 16; else dlp.d_ntracks = 255; } hs = (ms / dlp.d_secsize) - dlp.d_secperunit; lp = &dlp; } if (bpb->bpbBytesPerSec == 0) { if (ckgeom(fname, lp->d_secsize, "bytes/sector") == -1) return -1; bpb->bpbBytesPerSec = lp->d_secsize; } if (bpb->bpbSecPerTrack == 0) { if (ckgeom(fname, lp->d_nsectors, "sectors/track") == -1) return -1; bpb->bpbSecPerTrack = lp->d_nsectors; } if (bpb->bpbHeads == 0) { if (ckgeom(fname, lp->d_ntracks, "drive heads") == -1) return -1; bpb->bpbHeads = lp->d_ntracks; } if (bpb->bpbHugeSectors == 0) bpb->bpbHugeSectors = lp->d_secperunit; if (bpb->bpbHiddenSecs == 0) bpb->bpbHiddenSecs = hs; return 0; } /* * Print out BPB values. */ static void print_bpb(struct bpb *bpb) { printf("BytesPerSec=%u SecPerClust=%u ResSectors=%u FATs=%u", bpb->bpbBytesPerSec, bpb->bpbSecPerClust, bpb->bpbResSectors, bpb->bpbFATs); if (bpb->bpbRootDirEnts) printf(" RootDirEnts=%u", bpb->bpbRootDirEnts); if (bpb->bpbSectors) printf(" Sectors=%u", bpb->bpbSectors); printf(" Media=%#x", bpb->bpbMedia); if (bpb->bpbFATsecs) printf(" FATsecs=%u", bpb->bpbFATsecs); printf(" SecPerTrack=%u Heads=%u HiddenSecs=%u", bpb->bpbSecPerTrack, bpb->bpbHeads, bpb->bpbHiddenSecs); if (bpb->bpbHugeSectors) printf(" HugeSectors=%u", bpb->bpbHugeSectors); if (!bpb->bpbFATsecs) { printf(" FATsecs=%u RootCluster=%u", bpb->bpbBigFATsecs, bpb->bpbRootClust); printf(" FSInfo="); printf(bpb->bpbFSInfo == MAXU16 ? "%#x" : "%u", bpb->bpbFSInfo); printf(" Backup="); printf(bpb->bpbBackup == MAXU16 ? "%#x" : "%u", bpb->bpbBackup); } printf("\n"); } /* * Check a disk geometry value. */ static int ckgeom(const char *fname, u_int val, const char *msg) { if (!val) { warnx("%s: no default %s", fname, msg); return -1; } if (val > MAXU16) { warnx("%s: illegal %s %d", fname, msg, val); return -1; } return 0; } /* * Check a volume label. */ static int oklabel(const char *src) { int c, i; for (i = 0; i <= 11; i++) { c = (u_char)*src++; if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c)) break; } return i && !c; } /* * Make a volume label. */ static void mklabel(u_int8_t *dest, const char *src) { int c, i; for (i = 0; i < 11; i++) { c = *src ? toupper(*src++) : ' '; *dest++ = !i && c == '\xe5' ? 5 : c; } } /* * Copy string, padding with spaces. */ static void setstr(u_int8_t *dest, const char *src, size_t len) { while (len--) *dest++ = *src ? *src++ : ' '; } static void infohandler(int sig __unused) { got_siginfo = 1; } Index: head/sbin/newfs_nandfs/newfs_nandfs.c =================================================================== --- head/sbin/newfs_nandfs/newfs_nandfs.c (revision 298249) +++ head/sbin/newfs_nandfs/newfs_nandfs.c (revision 298250) @@ -1,1179 +1,1179 @@ /*- * Copyright (c) 2010-2012 Semihalf. * All rights reserved. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define DEBUG #undef DEBUG #ifdef DEBUG #define debug(fmt, args...) do { \ printf("nandfs:" fmt "\n", ##args); } while (0) #else #define debug(fmt, args...) #endif #define NANDFS_FIRST_BLOCK nandfs_first_block() #define NANDFS_FIRST_CNO 1 #define NANDFS_BLOCK_BAD 1 #define NANDFS_BLOCK_GOOD 0 struct file_info { uint64_t ino; const char *name; uint32_t mode; uint64_t size; uint8_t nblocks; uint32_t *blocks; struct nandfs_inode *inode; }; static struct file_info user_files[] = { { NANDFS_ROOT_INO, NULL, S_IFDIR | 0755, 0, 1, NULL, NULL }, }; static struct file_info ifile = { NANDFS_IFILE_INO, NULL, 0, 0, -1, NULL, NULL }; static struct file_info sufile = { NANDFS_SUFILE_INO, NULL, 0, 0, -1, NULL, NULL }; static struct file_info cpfile = { NANDFS_CPFILE_INO, NULL, 0, 0, -1, NULL, NULL }; static struct file_info datfile = { NANDFS_DAT_INO, NULL, 0, 0, -1, NULL, NULL }; struct nandfs_block { LIST_ENTRY(nandfs_block) block_link; uint32_t number; uint64_t offset; void *data; }; static LIST_HEAD(, nandfs_block) block_head = LIST_HEAD_INITIALIZER(&block_head); /* Storage geometry */ static off_t mediasize; static ssize_t sectorsize; static uint64_t nsegments; static uint64_t erasesize; static uint64_t segsize; static struct nandfs_fsdata fsdata; static struct nandfs_super_block super_block; static int is_nand; /* Nandfs parameters */ static size_t blocksize = NANDFS_DEF_BLOCKSIZE; static long blocks_per_segment; static long rsv_segment_percent = 5; static time_t nandfs_time; static uint32_t bad_segments_count = 0; static uint32_t *bad_segments = NULL; static uint8_t fsdata_blocks_state[NANDFS_NFSAREAS]; static u_char *volumelabel = NULL; static struct nandfs_super_root *sr; static uint32_t nuserfiles; static uint32_t seg_nblocks; static uint32_t seg_endblock; #define SIZE_TO_BLOCK(size) (((size) + (blocksize - 1)) / blocksize) static uint32_t nandfs_first_block(void) { uint32_t i, first_free, start_bad_segments = 0; for (i = 0; i < bad_segments_count; i++) { if (i == bad_segments[i]) start_bad_segments++; else break; } first_free = SIZE_TO_BLOCK(NANDFS_DATA_OFFSET_BYTES(erasesize) + (start_bad_segments * segsize)); if (first_free < (uint32_t)blocks_per_segment) return (blocks_per_segment); else return (first_free); } static void usage(void) { fprintf(stderr, "usage: newfs_nandfs [ -options ] device\n" "where the options are:\n" "\t-b block-size\n" "\t-B blocks-per-segment\n" "\t-L volume label\n" "\t-m reserved-segments-percentage\n"); exit(1); } static int nandfs_log2(unsigned n) { unsigned count; /* * N.B. this function will return 0 if supplied 0. */ for (count = 0; n/2; count++) n /= 2; return count; } /* from NetBSD's src/sys/net/if_ethersubr.c */ static uint32_t crc32_le(uint32_t crc, const uint8_t *buf, size_t len) { static const uint32_t crctab[] = { 0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; size_t i; crc = crc ^ ~0U; for (i = 0; i < len; i++) { crc ^= buf[i]; crc = (crc >> 4) ^ crctab[crc & 0xf]; crc = (crc >> 4) ^ crctab[crc & 0xf]; } return (crc ^ ~0U); } static void * get_block(uint32_t block_nr, uint64_t offset) { struct nandfs_block *block, *new_block; LIST_FOREACH(block, &block_head, block_link) { if (block->number == block_nr) return block->data; } debug("allocating block %x\n", block_nr); new_block = malloc(sizeof(*block)); if (!new_block) err(1, "cannot allocate block"); new_block->number = block_nr; new_block->offset = offset; new_block->data = malloc(blocksize); if (!new_block->data) err(1, "cannot allocate block data"); memset(new_block->data, 0, blocksize); LIST_INSERT_HEAD(&block_head, new_block, block_link); return (new_block->data); } static int nandfs_seg_usage_blk_offset(uint64_t seg, uint64_t *blk, uint64_t *offset) { uint64_t off; uint16_t seg_size; seg_size = sizeof(struct nandfs_segment_usage); off = roundup(sizeof(struct nandfs_sufile_header), seg_size); off += (seg * seg_size); *blk = off / blocksize; *offset = (off % blocksize) / seg_size; return (0); } static uint32_t segment_size(void) { u_int size; size = sizeof(struct nandfs_segment_summary ); size += seg_nblocks * sizeof(struct nandfs_binfo_v); if (size > blocksize) err(1, "segsum info bigger that blocksize"); return (size); } static void prepare_blockgrouped_file(uint32_t block) { struct nandfs_block_group_desc *desc; uint32_t i, entries; desc = (struct nandfs_block_group_desc *)get_block(block, 0); entries = blocksize / sizeof(struct nandfs_block_group_desc); for (i = 0; i < entries; i++) desc[i].bg_nfrees = blocksize * 8; } static void alloc_blockgrouped_file(uint32_t block, uint32_t entry) { struct nandfs_block_group_desc *desc; uint32_t desc_nr; uint32_t *bitmap; desc = (struct nandfs_block_group_desc *)get_block(block, 0); bitmap = (uint32_t *)get_block(block + 1, 1); bitmap += (entry >> 5); if (*bitmap & (1 << (entry % 32))) { printf("nandfs: blockgrouped entry %d already allocated\n", entry); } *bitmap |= (1 << (entry % 32)); desc_nr = entry / (blocksize * 8); desc[desc_nr].bg_nfrees--; } static uint64_t count_su_blocks(void) { uint64_t maxblk, blk, offset, i; maxblk = blk = 0; for (i = 0; i < bad_segments_count; i++) { nandfs_seg_usage_blk_offset(bad_segments[i], &blk, &offset); debug("bad segment at block:%jx off: %jx", blk, offset); if (blk > maxblk) maxblk = blk; } debug("bad segment needs %#jx", blk); if (blk >= NDADDR) { printf("nandfs: file too big (%jd > %d)\n", blk, NDADDR); exit(2); } sufile.size = (blk + 1) * blocksize; return (blk + 1); } static void count_seg_blocks(void) { uint32_t i; for (i = 0; i < nuserfiles; i++) if (user_files[i].nblocks) { seg_nblocks += user_files[i].nblocks; user_files[i].blocks = malloc(user_files[i].nblocks * sizeof(uint32_t)); } ifile.nblocks = 2 + SIZE_TO_BLOCK(sizeof(struct nandfs_inode) * (NANDFS_USER_INO + 1)); ifile.blocks = malloc(ifile.nblocks * sizeof(uint32_t)); seg_nblocks += ifile.nblocks; cpfile.nblocks = SIZE_TO_BLOCK((NANDFS_CPFILE_FIRST_CHECKPOINT_OFFSET + 1) * sizeof(struct nandfs_checkpoint)); cpfile.blocks = malloc(cpfile.nblocks * sizeof(uint32_t)); seg_nblocks += cpfile.nblocks; if (!bad_segments) { sufile.nblocks = SIZE_TO_BLOCK((NANDFS_SUFILE_FIRST_SEGMENT_USAGE_OFFSET + 1) * sizeof(struct nandfs_segment_usage)); } else { debug("bad blocks found: extra space for sufile"); sufile.nblocks = count_su_blocks(); } sufile.blocks = malloc(sufile.nblocks * sizeof(uint32_t)); seg_nblocks += sufile.nblocks; datfile.nblocks = 2 + SIZE_TO_BLOCK((seg_nblocks) * sizeof(struct nandfs_dat_entry)); datfile.blocks = malloc(datfile.nblocks * sizeof(uint32_t)); seg_nblocks += datfile.nblocks; } static void assign_file_blocks(uint64_t start_block) { uint32_t i, j; for (i = 0; i < nuserfiles; i++) for (j = 0; j < user_files[i].nblocks; j++) { debug("user file %d at block %d at %#jx", i, j, (uintmax_t)start_block); user_files[i].blocks[j] = start_block++; } for (j = 0; j < ifile.nblocks; j++) { debug("ifile block %d at %#jx", j, (uintmax_t)start_block); ifile.blocks[j] = start_block++; } for (j = 0; j < cpfile.nblocks; j++) { debug("cpfile block %d at %#jx", j, (uintmax_t)start_block); cpfile.blocks[j] = start_block++; } for (j = 0; j < sufile.nblocks; j++) { debug("sufile block %d at %#jx", j, (uintmax_t)start_block); sufile.blocks[j] = start_block++; } for (j = 0; j < datfile.nblocks; j++) { debug("datfile block %d at %#jx", j, (uintmax_t)start_block); datfile.blocks[j] = start_block++; } /* add one for superroot */ debug("sr at block %#jx", (uintmax_t)start_block); sr = (struct nandfs_super_root *)get_block(start_block++, 0); seg_endblock = start_block; } static void save_datfile(void) { prepare_blockgrouped_file(datfile.blocks[0]); } static uint64_t update_datfile(uint64_t block) { struct nandfs_dat_entry *dat; static uint64_t vblock = 0; uint64_t allocated, i, off; if (vblock == 0) { alloc_blockgrouped_file(datfile.blocks[0], vblock); vblock++; } allocated = vblock; i = vblock / (blocksize / sizeof(*dat)); off = vblock % (blocksize / sizeof(*dat)); vblock++; dat = (struct nandfs_dat_entry *)get_block(datfile.blocks[2 + i], 2 + i); alloc_blockgrouped_file(datfile.blocks[0], allocated); dat[off].de_blocknr = block; dat[off].de_start = NANDFS_FIRST_CNO; dat[off].de_end = UINTMAX_MAX; return (allocated); } static union nandfs_binfo * update_block_info(union nandfs_binfo *binfo, struct file_info *file) { nandfs_daddr_t vblock; uint32_t i; for (i = 0; i < file->nblocks; i++) { debug("%s: blk %x", __func__, i); if (file->ino != NANDFS_DAT_INO) { vblock = update_datfile(file->blocks[i]); binfo->bi_v.bi_vblocknr = vblock; binfo->bi_v.bi_blkoff = i; binfo->bi_v.bi_ino = file->ino; file->inode->i_db[i] = vblock; } else { binfo->bi_dat.bi_blkoff = i; binfo->bi_dat.bi_ino = file->ino; file->inode->i_db[i] = datfile.blocks[i]; } binfo++; } return (binfo); } static void save_segsum(struct nandfs_segment_summary *ss) { union nandfs_binfo *binfo; struct nandfs_block *block; uint32_t sum_bytes, i; uint8_t crc_data, crc_skip; sum_bytes = segment_size(); ss->ss_magic = NANDFS_SEGSUM_MAGIC; ss->ss_bytes = sizeof(struct nandfs_segment_summary); ss->ss_flags = NANDFS_SS_LOGBGN | NANDFS_SS_LOGEND | NANDFS_SS_SR; ss->ss_seq = 1; ss->ss_create = nandfs_time; ss->ss_next = nandfs_first_block() + blocks_per_segment; /* nblocks = segment blocks + segsum block + superroot */ ss->ss_nblocks = seg_nblocks + 2; ss->ss_nbinfos = seg_nblocks; ss->ss_sumbytes = sum_bytes; crc_skip = sizeof(ss->ss_datasum) + sizeof(ss->ss_sumsum); ss->ss_sumsum = crc32_le(0, (uint8_t *)ss + crc_skip, sum_bytes - crc_skip); crc_data = 0; binfo = (union nandfs_binfo *)(ss + 1); for (i = 0; i < nuserfiles; i++) { if (user_files[i].nblocks) binfo = update_block_info(binfo, &user_files[i]); } binfo = update_block_info(binfo, &ifile); binfo = update_block_info(binfo, &cpfile); binfo = update_block_info(binfo, &sufile); update_block_info(binfo, &datfile); /* save superroot crc */ crc_skip = sizeof(sr->sr_sum); sr->sr_sum = crc32_le(0, (uint8_t *)sr + crc_skip, NANDFS_SR_BYTES - crc_skip); /* segment checksup */ crc_skip = sizeof(ss->ss_datasum); LIST_FOREACH(block, &block_head, block_link) { if (block->number < NANDFS_FIRST_BLOCK) continue; if (block->number == NANDFS_FIRST_BLOCK) crc_data = crc32_le(0, (uint8_t *)block->data + crc_skip, blocksize - crc_skip); else crc_data = crc32_le(crc_data, (uint8_t *)block->data, blocksize); } ss->ss_datasum = crc_data; } static void create_fsdata(void) { memset(&fsdata, 0, sizeof(struct nandfs_fsdata)); fsdata.f_magic = NANDFS_FSDATA_MAGIC; fsdata.f_nsegments = nsegments; fsdata.f_erasesize = erasesize; fsdata.f_first_data_block = NANDFS_FIRST_BLOCK; fsdata.f_blocks_per_segment = blocks_per_segment; fsdata.f_r_segments_percentage = rsv_segment_percent; fsdata.f_rev_level = NANDFS_CURRENT_REV; fsdata.f_sbbytes = NANDFS_SB_BYTES; fsdata.f_bytes = NANDFS_FSDATA_CRC_BYTES; fsdata.f_ctime = nandfs_time; fsdata.f_log_block_size = nandfs_log2(blocksize) - 10; fsdata.f_errors = 1; fsdata.f_inode_size = sizeof(struct nandfs_inode); fsdata.f_dat_entry_size = sizeof(struct nandfs_dat_entry); fsdata.f_checkpoint_size = sizeof(struct nandfs_checkpoint); fsdata.f_segment_usage_size = sizeof(struct nandfs_segment_usage); uuidgen(&fsdata.f_uuid, 1); if (volumelabel) memcpy(fsdata.f_volume_name, volumelabel, 16); fsdata.f_sum = crc32_le(0, (const uint8_t *)&fsdata, NANDFS_FSDATA_CRC_BYTES); } static void save_fsdata(void *data) { memcpy(data, &fsdata, sizeof(fsdata)); } static void create_super_block(void) { memset(&super_block, 0, sizeof(struct nandfs_super_block)); super_block.s_magic = NANDFS_SUPER_MAGIC; super_block.s_last_cno = NANDFS_FIRST_CNO; super_block.s_last_pseg = NANDFS_FIRST_BLOCK; super_block.s_last_seq = 1; super_block.s_free_blocks_count = (nsegments - bad_segments_count) * blocks_per_segment; super_block.s_mtime = 0; super_block.s_wtime = nandfs_time; super_block.s_state = NANDFS_VALID_FS; super_block.s_sum = crc32_le(0, (const uint8_t *)&super_block, NANDFS_SB_BYTES); } static void save_super_block(void *data) { memcpy(data, &super_block, sizeof(super_block)); } static void save_super_root(void) { sr->sr_bytes = NANDFS_SR_BYTES; sr->sr_flags = 0; sr->sr_nongc_ctime = nandfs_time; datfile.inode = &sr->sr_dat; cpfile.inode = &sr->sr_cpfile; sufile.inode = &sr->sr_sufile; } static struct nandfs_dir_entry * add_de(void *block, struct nandfs_dir_entry *de, uint64_t ino, const char *name, uint8_t type) { uint16_t reclen; /* modify last de */ de->rec_len = NANDFS_DIR_REC_LEN(de->name_len); de = (void *)((uint8_t *)de + de->rec_len); reclen = blocksize - ((uintptr_t)de - (uintptr_t)block); if (reclen < NANDFS_DIR_REC_LEN(strlen(name))) { printf("nandfs: too many dir entries for one block\n"); return (NULL); } de->inode = ino; de->rec_len = reclen; de->name_len = strlen(name); de->file_type = type; memset(de->name, 0, (strlen(name) + NANDFS_DIR_PAD - 1) & ~NANDFS_DIR_ROUND); memcpy(de->name, name, strlen(name)); return (de); } static struct nandfs_dir_entry * make_dir(void *block, uint64_t ino, uint64_t parent_ino) { struct nandfs_dir_entry *de = (struct nandfs_dir_entry *)block; /* create '..' entry */ de->inode = parent_ino; de->rec_len = NANDFS_DIR_REC_LEN(2); de->name_len = 2; de->file_type = DT_DIR; memset(de->name, 0, NANDFS_DIR_NAME_LEN(2)); memcpy(de->name, "..", 2); /* create '.' entry */ de = (void *)((uint8_t *)block + NANDFS_DIR_REC_LEN(2)); de->inode = ino; de->rec_len = blocksize - NANDFS_DIR_REC_LEN(2); de->name_len = 1; de->file_type = DT_DIR; memset(de->name, 0, NANDFS_DIR_NAME_LEN(1)); memcpy(de->name, ".", 1); return (de); } static void save_root_dir(void) { struct file_info *root = &user_files[0]; struct nandfs_dir_entry *de; uint32_t i; void *block; block = get_block(root->blocks[0], 0); de = make_dir(block, root->ino, root->ino); for (i = 1; i < nuserfiles; i++) de = add_de(block, de, user_files[i].ino, user_files[i].name, IFTODT(user_files[i].mode)); root->size = ((uintptr_t)de - (uintptr_t)block) + NANDFS_DIR_REC_LEN(de->name_len); } static void save_sufile(void) { struct nandfs_sufile_header *header; struct nandfs_segment_usage *su; uint64_t blk, i, off; void *block; int start; /* * At the beginning just zero-out everything */ for (i = 0; i < sufile.nblocks; i++) get_block(sufile.blocks[i], 0); start = 0; block = get_block(sufile.blocks[start], 0); header = (struct nandfs_sufile_header *)block; header->sh_ncleansegs = nsegments - bad_segments_count - 1; header->sh_ndirtysegs = 1; header->sh_last_alloc = 1; su = (struct nandfs_segment_usage *)header; off = NANDFS_SUFILE_FIRST_SEGMENT_USAGE_OFFSET; /* Allocate data segment */ su[off].su_lastmod = nandfs_time; /* nblocks = segment blocks + segsum block + superroot */ su[off].su_nblocks = seg_nblocks + 2; su[off].su_flags = NANDFS_SEGMENT_USAGE_DIRTY; off++; /* Allocate next segment */ su[off].su_lastmod = nandfs_time; su[off].su_nblocks = 0; su[off].su_flags = NANDFS_SEGMENT_USAGE_DIRTY; for (i = 0; i < bad_segments_count; i++) { nandfs_seg_usage_blk_offset(bad_segments[i], &blk, &off); debug("storing bad_segments[%jd]=%x at %jx off %jx\n", i, bad_segments[i], blk, off); block = get_block(sufile.blocks[blk], off * sizeof(struct nandfs_segment_usage *)); su = (struct nandfs_segment_usage *)block; su[off].su_lastmod = nandfs_time; su[off].su_nblocks = 0; su[off].su_flags = NANDFS_SEGMENT_USAGE_ERROR; } } static void save_cpfile(void) { struct nandfs_cpfile_header *header; struct nandfs_checkpoint *cp, *initial_cp; int i, entries = blocksize / sizeof(struct nandfs_checkpoint); uint64_t cno; header = (struct nandfs_cpfile_header *)get_block(cpfile.blocks[0], 0); header->ch_ncheckpoints = 1; header->ch_nsnapshots = 0; cp = (struct nandfs_checkpoint *)header; /* fill first checkpoint data*/ initial_cp = &cp[NANDFS_CPFILE_FIRST_CHECKPOINT_OFFSET]; initial_cp->cp_flags = 0; initial_cp->cp_checkpoints_count = 0; initial_cp->cp_cno = NANDFS_FIRST_CNO; initial_cp->cp_create = nandfs_time; initial_cp->cp_nblk_inc = seg_endblock - 1; initial_cp->cp_blocks_count = seg_nblocks; memset(&initial_cp->cp_snapshot_list, 0, sizeof(struct nandfs_snapshot_list)); ifile.inode = &initial_cp->cp_ifile_inode; /* mark rest of cp as invalid */ cno = NANDFS_FIRST_CNO + 1; i = NANDFS_CPFILE_FIRST_CHECKPOINT_OFFSET + 1; for (; i < entries; i++) { cp[i].cp_cno = cno++; cp[i].cp_flags = NANDFS_CHECKPOINT_INVALID; } } static void init_inode(struct nandfs_inode *inode, struct file_info *file) { inode->i_blocks = file->nblocks; inode->i_ctime = nandfs_time; inode->i_mtime = nandfs_time; inode->i_mode = file->mode & 0xffff; inode->i_links_count = 1; if (file->size > 0) inode->i_size = file->size; else inode->i_size = 0; if (file->ino == NANDFS_USER_INO) inode->i_flags = SF_NOUNLINK|UF_NOUNLINK; else inode->i_flags = 0; } static void save_ifile(void) { struct nandfs_inode *inode; struct file_info *file; uint64_t ino, blk, off; uint32_t i; prepare_blockgrouped_file(ifile.blocks[0]); for (i = 0; i <= NANDFS_USER_INO; i++) alloc_blockgrouped_file(ifile.blocks[0], i); for (i = 0; i < nuserfiles; i++) { file = &user_files[i]; ino = file->ino; blk = ino / (blocksize / sizeof(*inode)); off = ino % (blocksize / sizeof(*inode)); inode = (struct nandfs_inode *)get_block(ifile.blocks[2 + blk], 2 + blk); file->inode = &inode[off]; init_inode(file->inode, file); } init_inode(ifile.inode, &ifile); init_inode(cpfile.inode, &cpfile); init_inode(sufile.inode, &sufile); init_inode(datfile.inode, &datfile); } static int create_fs(void) { uint64_t start_block; uint32_t segsum_size; char *data; int i; - nuserfiles = (sizeof(user_files) / sizeof(user_files[0])); + nuserfiles = nitems(user_files); /* Count and assign blocks */ count_seg_blocks(); segsum_size = segment_size(); start_block = NANDFS_FIRST_BLOCK + SIZE_TO_BLOCK(segsum_size); assign_file_blocks(start_block); /* Create super root structure */ save_super_root(); /* Create root directory */ save_root_dir(); /* Fill in file contents */ save_sufile(); save_cpfile(); save_ifile(); save_datfile(); /* Save fsdata and superblocks */ create_fsdata(); create_super_block(); for (i = 0; i < NANDFS_NFSAREAS; i++) { if (fsdata_blocks_state[i] != NANDFS_BLOCK_GOOD) continue; data = get_block((i * erasesize)/blocksize, 0); save_fsdata(data); data = get_block((i * erasesize + NANDFS_SBLOCK_OFFSET_BYTES) / blocksize, 0); if (blocksize > NANDFS_SBLOCK_OFFSET_BYTES) data += NANDFS_SBLOCK_OFFSET_BYTES; save_super_block(data); memset(data + sizeof(struct nandfs_super_block), 0xff, (blocksize - sizeof(struct nandfs_super_block) - NANDFS_SBLOCK_OFFSET_BYTES)); } /* Save segment summary and CRCs */ save_segsum(get_block(NANDFS_FIRST_BLOCK, 0)); return (0); } static void write_fs(int fda) { struct nandfs_block *block; char *data; u_int ret; /* Overwrite next block with ff if not nand device */ if (!is_nand) { data = get_block(seg_endblock, 0); memset(data, 0xff, blocksize); } LIST_FOREACH(block, &block_head, block_link) { lseek(fda, block->number * blocksize, SEEK_SET); ret = write(fda, block->data, blocksize); if (ret != blocksize) err(1, "cannot write filesystem data"); } } static void check_parameters(void) { int i; /* check blocksize */ if ((blocksize < NANDFS_MIN_BLOCKSIZE) || (blocksize > MAXBSIZE) || ((blocksize - 1) & blocksize)) { errx(1, "Bad blocksize (%zu). Must be in range [%u-%u] " "and a power of two.", blocksize, NANDFS_MIN_BLOCKSIZE, MAXBSIZE); } /* check blocks per segments */ if ((blocks_per_segment < NANDFS_SEG_MIN_BLOCKS) || ((blocksize - 1) & blocksize)) errx(1, "Bad blocks per segment (%lu). Must be greater than " "%u and a power of two.", blocks_per_segment, NANDFS_SEG_MIN_BLOCKS); /* check reserved segment percentage */ if ((rsv_segment_percent < 1) || (rsv_segment_percent > 99)) errx(1, "Bad reserved segment percentage. " "Must in range 1..99."); /* check volume label */ i = 0; if (volumelabel) { while (isalnum(volumelabel[++i])) ; if (volumelabel[i] != '\0') { errx(1, "bad volume label. " "Valid characters are alphanumerics."); } if (strlen(volumelabel) >= 16) errx(1, "Bad volume label. Length is longer than %d.", 16); } nandfs_time = time(NULL); } static void print_parameters(void) { printf("filesystem parameters:\n"); printf("blocksize: %#zx sectorsize: %#zx\n", blocksize, sectorsize); printf("erasesize: %#jx mediasize: %#jx\n", erasesize, mediasize); printf("segment size: %#jx blocks per segment: %#x\n", segsize, (uint32_t)blocks_per_segment); } /* * Exit with error if file system is mounted. */ static void check_mounted(const char *fname, mode_t mode) { struct statfs *mp; const char *s1, *s2; size_t len; int n, r; if (!(n = getmntinfo(&mp, MNT_NOWAIT))) err(1, "getmntinfo"); len = strlen(_PATH_DEV); s1 = fname; if (!strncmp(s1, _PATH_DEV, len)) s1 += len; r = S_ISCHR(mode) && s1 != fname && *s1 == 'r'; for (; n--; mp++) { s2 = mp->f_mntfromname; if (!strncmp(s2, _PATH_DEV, len)) s2 += len; if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) || !strcmp(s1, s2)) errx(1, "%s is mounted on %s", fname, mp->f_mntonname); } } static void calculate_geometry(int fd) { struct chip_param_io chip_params; char ident[DISK_IDENT_SIZE]; char medianame[MAXPATHLEN]; /* Check storage type */ g_get_ident(fd, ident, DISK_IDENT_SIZE); g_get_name(ident, medianame, MAXPATHLEN); debug("device name: %s", medianame); is_nand = (strstr(medianame, "gnand") != NULL); debug("is_nand = %d", is_nand); sectorsize = g_sectorsize(fd); debug("sectorsize: %#zx", sectorsize); /* Get storage size */ mediasize = g_mediasize(fd); debug("mediasize: %#jx", mediasize); /* Get storage erase unit size */ if (!is_nand) erasesize = NANDFS_DEF_ERASESIZE; else if (ioctl(fd, NAND_IO_GET_CHIP_PARAM, &chip_params) != -1) erasesize = chip_params.page_size * chip_params.pages_per_block; else errx(1, "Cannot ioctl(NAND_IO_GET_CHIP_PARAM)"); debug("erasesize: %#jx", (uintmax_t)erasesize); if (blocks_per_segment == 0) { if (erasesize >= NANDFS_MIN_SEGSIZE) blocks_per_segment = erasesize / blocksize; else blocks_per_segment = NANDFS_MIN_SEGSIZE / blocksize; } /* Calculate number of segments */ segsize = blocksize * blocks_per_segment; nsegments = ((mediasize - NANDFS_NFSAREAS * erasesize) / segsize) - 2; debug("segsize: %#jx", segsize); debug("nsegments: %#jx", nsegments); } static void erase_device(int fd) { int rest, failed; uint64_t i, nblocks; off_t offset; failed = 0; for (i = 0; i < NANDFS_NFSAREAS; i++) { debug("Deleting %jx\n", i * erasesize); if (g_delete(fd, i * erasesize, erasesize)) { printf("cannot delete %jx\n", i * erasesize); fsdata_blocks_state[i] = NANDFS_BLOCK_BAD; failed++; } else fsdata_blocks_state[i] = NANDFS_BLOCK_GOOD; } if (failed == NANDFS_NFSAREAS) { printf("%d first blocks not usable. Unable to create " "filesystem.\n", failed); exit(1); } for (i = 0; i < nsegments; i++) { offset = NANDFS_NFSAREAS * erasesize + i * segsize; if (g_delete(fd, offset, segsize)) { printf("cannot delete segment %jx (offset %jd)\n", i, offset); bad_segments_count++; bad_segments = realloc(bad_segments, bad_segments_count * sizeof(uint32_t)); bad_segments[bad_segments_count - 1] = i; } } if (bad_segments_count == nsegments) { printf("no valid segments\n"); exit(1); } /* Delete remaining blocks at the end of device */ rest = mediasize % segsize; nblocks = rest / erasesize; for (i = 0; i < nblocks; i++) { offset = (segsize * nsegments) + (i * erasesize); if (g_delete(fd, offset, erasesize)) { printf("cannot delete space after last segment " "- probably a bad block\n"); } } } static void erase_initial(int fd) { char buf[512]; u_int i; memset(buf, 0xff, sizeof(buf)); lseek(fd, 0, SEEK_SET); for (i = 0; i < NANDFS_NFSAREAS * erasesize; i += sizeof(buf)) write(fd, buf, sizeof(buf)); } static void create_nandfs(int fd) { create_fs(); write_fs(fd); } static void print_summary(void) { printf("filesystem was created successfully\n"); printf("total segments: %#jx valid segments: %#jx\n", nsegments, nsegments - bad_segments_count); printf("total space: %ju MB free: %ju MB\n", (nsegments * blocks_per_segment * blocksize) / (1024 * 1024), ((nsegments - bad_segments_count) * blocks_per_segment * blocksize) / (1024 * 1024)); } int main(int argc, char *argv[]) { struct stat sb; char buf[MAXPATHLEN]; const char opts[] = "b:B:L:m:"; const char *fname; int ch, fd; while ((ch = getopt(argc, argv, opts)) != -1) { switch (ch) { case 'b': blocksize = strtol(optarg, (char **)NULL, 10); if (blocksize == 0) usage(); break; case 'B': blocks_per_segment = strtol(optarg, (char **)NULL, 10); if (blocks_per_segment == 0) usage(); break; case 'L': volumelabel = optarg; break; case 'm': rsv_segment_percent = strtol(optarg, (char **)NULL, 10); if (rsv_segment_percent == 0) usage(); break; default: usage(); } } argc -= optind; argv += optind; if (argc < 1 || argc > 2) usage(); /* construct proper device path */ fname = *argv++; if (!strchr(fname, '/')) { snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname); if (!(fname = strdup(buf))) err(1, NULL); } fd = g_open(fname, 1); if (fd == -1) err(1, "Cannot open %s", fname); if (fstat(fd, &sb) == -1) err(1, "Cannot stat %s", fname); if (!S_ISCHR(sb.st_mode)) warnx("%s is not a character device", fname); check_mounted(fname, sb.st_mode); calculate_geometry(fd); check_parameters(); print_parameters(); if (is_nand) erase_device(fd); else erase_initial(fd); create_nandfs(fd); print_summary(); g_close(fd); return (0); }