1 /* mkdosfs.c - utility to create FAT/MS-DOS filesystems
3 Copyright (C) 1991 Linus Torvalds <torvalds@klaava.helsinki.fi>
4 Copyright (C) 1992-1993 Remy Card <card@masi.ibp.fr>
5 Copyright (C) 1993-1994 David Hudson <dave@humbug.demon.co.uk>
6 Copyright (C) 1998 H. Peter Anvin <hpa@zytor.com>
7 Copyright (C) 1998-2005 Roman Hodek <Roman.Hodek@informatik.uni-erlangen.de>
9 This program is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 On Debian systems, the complete text of the GNU General Public License
23 can be found in /usr/share/common-licenses/GPL-3 file.
26 /* Description: Utility to allow an MS-DOS filesystem to be created
27 under Linux. A lot of the basic structure of this program has been
28 borrowed from Remy Card's "mke2fs" code.
30 As far as possible the aim here is to make the "mkdosfs" command
31 look almost identical to the other Linux filesystem make utilties,
32 eg bad blocks are still specified as blocks, not sectors, but when
33 it comes down to it, DOS is tied to the idea of a sector (512 bytes
34 as a rule), and not the block. For example the boot block does not
35 occupy a full cluster.
37 Fixes/additions May 1998 by Roman Hodek
38 <Roman.Hodek@informatik.uni-erlangen.de>:
39 - Atari format support
40 - New options -A, -S, -C
41 - Support for filesystems > 2GB
44 /* Include the header files */
49 #include <linux/hdreg.h>
50 #include <sys/mount.h>
58 #include <sys/ioctl.h>
61 #include <sys/types.h>
66 # include <asm/types.h>
68 #if __BYTE_ORDER == __BIG_ENDIAN
70 #include <asm/byteorder.h>
72 /* ++roman: 2.1 kernel headers define these function, they're probably more
73 * efficient then coding the swaps machine-independently. */
74 #define CF_LE_W __le16_to_cpu
75 #define CF_LE_L __le32_to_cpu
76 #define CT_LE_W __cpu_to_le16
77 #define CT_LE_L __cpu_to_le32
79 #define CF_LE_W(v) ((((v) & 0xff) << 8) | (((v) >> 8) & 0xff))
80 #define CF_LE_L(v) (((unsigned)(v)>>24) | (((unsigned)(v)>>8)&0xff00) | \
81 (((unsigned)(v)<<8)&0xff0000) | ((unsigned)(v)<<24))
82 #define CT_LE_W(v) CF_LE_W(v)
83 #define CT_LE_L(v) CF_LE_L(v)
84 #endif /* defined(__le16_to_cpu) */
88 #define CF_LE_W(v) (v)
89 #define CF_LE_L(v) (v)
90 #define CT_LE_W(v) (v)
91 #define CT_LE_L(v) (v)
93 #endif /* __BIG_ENDIAN */
95 /* In earlier versions, an own llseek() was used, but glibc lseek() is
96 * sufficient (or even better :) for 64 bit offsets in the meantime */
99 /* Constant definitions */
101 #define TRUE 1 /* Boolean constants */
104 #define TEST_BUFFER_BLOCKS 16
105 #define HARD_SECTOR_SIZE 512
106 #define SECTORS_PER_BLOCK ( BLOCK_SIZE / HARD_SECTOR_SIZE )
109 /* Macro definitions */
111 /* Report a failure message and return a failure error code */
113 #define die( str ) fatal_error( "%s: " str "\n" )
116 /* Mark a cluster in the FAT as bad */
118 #define mark_sector_bad( sector ) mark_FAT_sector( sector, FAT_BAD )
120 /* Compute ceil(a/b) */
125 return (a + b - 1) / b;
128 /* MS-DOS filesystem structures -- I included them here instead of
129 including linux/msdos_fs.h since that doesn't include some fields we
132 #define ATTR_RO 1 /* read-only */
133 #define ATTR_HIDDEN 2 /* hidden */
134 #define ATTR_SYS 4 /* system */
135 #define ATTR_VOLUME 8 /* volume label */
136 #define ATTR_DIR 16 /* directory */
137 #define ATTR_ARCH 32 /* archived */
139 #define ATTR_NONE 0 /* no attribute bits */
140 #define ATTR_UNUSED (ATTR_VOLUME | ATTR_ARCH | ATTR_SYS | ATTR_HIDDEN)
141 /* attribute bits that are copied "as is" */
144 #define FAT_EOF (atari_format ? 0x0fffffff : 0x0ffffff8)
145 #define FAT_BAD 0x0ffffff7
147 #define MSDOS_EXT_SIGN 0x29 /* extended boot sector signature */
148 #define MSDOS_FAT12_SIGN "FAT12 " /* FAT12 filesystem signature */
149 #define MSDOS_FAT16_SIGN "FAT16 " /* FAT16 filesystem signature */
150 #define MSDOS_FAT32_SIGN "FAT32 " /* FAT32 filesystem signature */
152 #define BOOT_SIGN 0xAA55 /* Boot sector magic number */
154 #define MAX_CLUST_12 ((1 << 12) - 16)
155 #define MAX_CLUST_16 ((1 << 16) - 16)
156 #define MIN_CLUST_32 65529
157 /* M$ says the high 4 bits of a FAT32 FAT entry are reserved and don't belong
158 * to the cluster number. So the max. cluster# is based on 2^28 */
159 #define MAX_CLUST_32 ((1 << 28) - 16)
161 #define FAT12_THRESHOLD 4085
163 #define OLDGEMDOS_MAX_SECTORS 32765
164 #define GEMDOS_MAX_SECTORS 65531
165 #define GEMDOS_MAX_SECTOR_SIZE (16*1024)
167 #define BOOTCODE_SIZE 448
168 #define BOOTCODE_FAT32_SIZE 420
170 /* __attribute__ ((packed)) is used on all structures to make gcc ignore any
173 struct msdos_volume_info {
174 __u8 drive_number; /* BIOS drive number */
175 __u8 RESERVED; /* Unused */
176 __u8 ext_boot_sign; /* 0x29 if fields below exist (DOS 3.3+) */
177 __u8 volume_id[4]; /* Volume ID number */
178 __u8 volume_label[11];/* Volume label */
179 __u8 fs_type[8]; /* Typically FAT12 or FAT16 */
180 } __attribute__ ((packed));
182 struct msdos_boot_sector
184 __u8 boot_jump[3]; /* Boot strap short or near jump */
185 __u8 system_id[8]; /* Name - can be used to special case
186 partition manager volumes */
187 __u8 sector_size[2]; /* bytes per logical sector */
188 __u8 cluster_size; /* sectors/cluster */
189 __u16 reserved; /* reserved sectors */
190 __u8 fats; /* number of FATs */
191 __u8 dir_entries[2]; /* root directory entries */
192 __u8 sectors[2]; /* number of sectors */
193 __u8 media; /* media code (unused) */
194 __u16 fat_length; /* sectors/FAT */
195 __u16 secs_track; /* sectors per track */
196 __u16 heads; /* number of heads */
197 __u32 hidden; /* hidden sectors (unused) */
198 __u32 total_sect; /* number of sectors (if sectors == 0) */
201 struct msdos_volume_info vi;
202 __u8 boot_code[BOOTCODE_SIZE];
203 } __attribute__ ((packed)) _oldfat;
205 __u32 fat32_length; /* sectors/FAT */
206 __u16 flags; /* bit 8: fat mirroring, low 4: active fat */
207 __u8 version[2]; /* major, minor filesystem version */
208 __u32 root_cluster; /* first cluster in root directory */
209 __u16 info_sector; /* filesystem info sector */
210 __u16 backup_boot; /* backup boot sector */
211 __u16 reserved2[6]; /* Unused */
212 struct msdos_volume_info vi;
213 __u8 boot_code[BOOTCODE_FAT32_SIZE];
214 } __attribute__ ((packed)) _fat32;
215 } __attribute__ ((packed)) fstype;
217 } __attribute__ ((packed));
218 #define fat32 fstype._fat32
219 #define oldfat fstype._oldfat
221 struct fat32_fsinfo {
222 __u32 reserved1; /* Nothing as far as I can tell */
223 __u32 signature; /* 0x61417272L */
224 __u32 free_clusters; /* Free cluster count. -1 if unknown */
225 __u32 next_cluster; /* Most recently allocated cluster.
226 * Unused under Linux. */
230 struct msdos_dir_entry
232 char name[8], ext[3]; /* name and extension */
233 __u8 attr; /* attribute bits */
234 __u8 lcase; /* Case for base and extension */
235 __u8 ctime_ms; /* Creation time, milliseconds */
236 __u16 ctime; /* Creation time */
237 __u16 cdate; /* Creation date */
238 __u16 adate; /* Last access date */
239 __u16 starthi; /* high 16 bits of first cl. (FAT32) */
240 __u16 time, date, start; /* time, date and first cluster */
241 __u32 size; /* file size (in bytes) */
242 } __attribute__ ((packed));
244 /* The "boot code" we put into the filesystem... it writes a message and
245 tells the user to try again */
247 char dummy_boot_jump[3] = { 0xeb, 0x3c, 0x90 };
249 char dummy_boot_jump_m68k[2] = { 0x60, 0x1c };
251 #define MSG_OFFSET_OFFSET 3
252 char dummy_boot_code[BOOTCODE_SIZE] =
255 "\xbe\x5b\x7c" /* mov si, offset message_txt */
258 "\x22\xc0" /* and al, al */
259 "\x74\x0b" /* jz key_press */
261 "\xb4\x0e" /* mov ah, 0eh */
262 "\xbb\x07\x00" /* mov bx, 0007h */
263 "\xcd\x10" /* int 10h */
265 "\xeb\xf0" /* jmp write_msg */
267 "\x32\xe4" /* xor ah, ah */
268 "\xcd\x16" /* int 16h */
269 "\xcd\x19" /* int 19h */
270 "\xeb\xfe" /* foo: jmp foo */
273 "This is not a bootable disk. Please insert a bootable floppy and\r\n"
274 "press any key to try again ... \r\n";
276 #define MESSAGE_OFFSET 29 /* Offset of message in above code */
278 /* Global variables - the root of all evil :-) - see these and weep! */
280 static char *program_name = "mkdosfs"; /* Name of the program */
281 static char *device_name = NULL; /* Name of the device on which to create the filesystem */
282 static int atari_format = 0; /* Use Atari variation of MS-DOS FS format */
283 static int check = FALSE; /* Default to no readablity checking */
284 static int verbose = 0; /* Default to verbose mode off */
285 static long volume_id; /* Volume ID number */
286 static time_t create_time; /* Creation time */
287 static struct timeval create_timeval; /* Creation time */
288 static char volume_name[] = " "; /* Volume name */
289 static unsigned long long blocks; /* Number of blocks in filesystem */
290 static int sector_size = 512; /* Size of a logical sector */
291 static int sector_size_set = 0; /* User selected sector size */
292 static int backup_boot = 0; /* Sector# of backup boot sector */
293 static int reserved_sectors = 0;/* Number of reserved sectors */
294 static int badblocks = 0; /* Number of bad blocks in the filesystem */
295 static int nr_fats = 2; /* Default number of FATs to produce */
296 static int size_fat = 0; /* Size in bits of FAT entries */
297 static int size_fat_by_user = 0; /* 1 if FAT size user selected */
298 static int dev = -1; /* FS block device file handle */
299 static int ignore_full_disk = 0; /* Ignore warning about 'full' disk devices */
300 static off_t currently_testing = 0; /* Block currently being tested (if autodetect bad blocks) */
301 static struct msdos_boot_sector bs; /* Boot sector data */
302 static int start_data_sector; /* Sector number for the start of the data area */
303 static int start_data_block; /* Block number for the start of the data area */
304 static unsigned char *fat; /* File allocation table */
305 static unsigned alloced_fat_length; /* # of FAT sectors we can keep in memory */
306 static unsigned char *info_sector; /* FAT32 info sector */
307 static struct msdos_dir_entry *root_dir; /* Root directory */
308 static int size_root_dir; /* Size of the root directory in bytes */
309 static int sectors_per_cluster = 0; /* Number of sectors per disk cluster */
310 static int root_dir_entries = 0; /* Number of root directory entries */
311 static char *blank_sector; /* Blank sector - all zeros */
312 static int hidden_sectors = 0; /* Number of hidden sectors */
313 static int malloc_entire_fat = FALSE; /* Whether we should malloc() the entire FAT or not */
314 static int align_structures = TRUE; /* Whether to enforce alignment */
316 /* Function prototype definitions */
318 static void fatal_error (const char *fmt_string) __attribute__((noreturn));
319 static void mark_FAT_cluster (int cluster, unsigned int value);
320 static void mark_FAT_sector (int sector, unsigned int value);
321 static long do_check (char *buffer, int try, off_t current_block);
322 static void alarm_intr (int alnum);
323 static void check_blocks (void);
324 static void get_list_blocks (char *filename);
325 static int valid_offset (int fd, loff_t offset);
326 static unsigned long long count_blocks (char *filename);
327 static void check_mount (char *device_name);
328 static void establish_params (int device_num, int size);
329 static void setup_tables (void);
330 static void write_tables (void);
333 /* The function implementations */
335 /* Handle the reporting of fatal errors. Volatile to let gcc know that this doesn't return */
338 fatal_error (const char *fmt_string)
340 fprintf (stderr, fmt_string, program_name, device_name);
341 exit (1); /* The error exit code is 1! */
345 /* Mark the specified cluster as having a particular value */
348 mark_FAT_cluster (int cluster, unsigned int value)
353 if (((cluster * 3) & 0x1) == 0)
355 fat[3 * cluster / 2] = (unsigned char) (value & 0x00ff);
356 fat[(3 * cluster / 2) + 1] = (unsigned char) ((fat[(3 * cluster / 2) + 1] & 0x00f0)
357 | ((value & 0x0f00) >> 8));
361 fat[3 * cluster / 2] = (unsigned char) ((fat[3 * cluster / 2] & 0x000f) | ((value & 0x000f) << 4));
362 fat[(3 * cluster / 2) + 1] = (unsigned char) ((value & 0x0ff0) >> 4);
368 fat[2 * cluster] = (unsigned char) (value & 0x00ff);
369 fat[(2 * cluster) + 1] = (unsigned char) (value >> 8);
374 fat[4 * cluster] = (unsigned char) (value & 0x000000ff);
375 fat[(4 * cluster) + 1] = (unsigned char) ((value & 0x0000ff00) >> 8);
376 fat[(4 * cluster) + 2] = (unsigned char) ((value & 0x00ff0000) >> 16);
377 fat[(4 * cluster) + 3] = (unsigned char) ((value & 0xff000000) >> 24);
381 die("Bad FAT size (not 12, 16, or 32)");
386 /* Mark a specified sector as having a particular value in it's FAT entry */
389 mark_FAT_sector (int sector, unsigned int value)
393 cluster = (sector - start_data_sector) / (int) (bs.cluster_size) /
394 (sector_size/HARD_SECTOR_SIZE);
396 die ("Invalid cluster number in mark_FAT_sector: probably bug!");
398 mark_FAT_cluster (cluster, value);
402 /* Perform a test on a block. Return the number of blocks that could be read successfully */
405 do_check (char *buffer, int try, off_t current_block)
409 if (llseek (dev, current_block * BLOCK_SIZE, SEEK_SET) /* Seek to the correct location */
410 != current_block * BLOCK_SIZE)
411 die ("seek failed during testing for blocks");
413 got = read (dev, buffer, try * BLOCK_SIZE); /* Try reading! */
417 if (got & (BLOCK_SIZE - 1))
418 printf ("Unexpected values in do_check: probably bugs\n");
425 /* Alarm clock handler - display the status of the quest for bad blocks! Then retrigger the alarm for five senconds
426 later (so we can come here again) */
429 alarm_intr (int alnum)
431 if (currently_testing >= blocks)
434 signal (SIGALRM, alarm_intr);
436 if (!currently_testing)
439 printf ("%lld... ", (unsigned long long)currently_testing);
449 static char blkbuf[BLOCK_SIZE * TEST_BUFFER_BLOCKS];
453 printf ("Searching for bad blocks ");
456 currently_testing = 0;
459 signal (SIGALRM, alarm_intr);
462 try = TEST_BUFFER_BLOCKS;
463 while (currently_testing < blocks)
465 if (currently_testing + try > blocks)
466 try = blocks - currently_testing;
467 got = do_check (blkbuf, try, currently_testing);
468 currently_testing += got;
471 try = TEST_BUFFER_BLOCKS;
476 if (currently_testing < start_data_block)
477 die ("bad blocks before data-area: cannot make fs");
479 for (i = 0; i < SECTORS_PER_BLOCK; i++) /* Mark all of the sectors in the block as bad */
480 mark_sector_bad (currently_testing * SECTORS_PER_BLOCK + i);
489 printf ("%d bad block%s\n", badblocks,
490 (badblocks > 1) ? "s" : "");
495 get_list_blocks (char *filename)
499 unsigned long blockno;
501 listfile = fopen (filename, "r");
502 if (listfile == (FILE *) NULL)
503 die ("Can't open file of bad blocks");
505 while (!feof (listfile))
507 fscanf (listfile, "%ld\n", &blockno);
508 for (i = 0; i < SECTORS_PER_BLOCK; i++) /* Mark all of the sectors in the block as bad */
509 mark_sector_bad (blockno * SECTORS_PER_BLOCK + i);
515 printf ("%d bad block%s\n", badblocks,
516 (badblocks > 1) ? "s" : "");
520 /* Given a file descriptor and an offset, check whether the offset is a valid offset for the file - return FALSE if it
521 isn't valid or TRUE if it is */
524 valid_offset (int fd, loff_t offset)
528 if (llseek (fd, offset, SEEK_SET) < 0)
530 if (read (fd, &ch, 1) < 1)
536 /* Given a filename, look to see how many blocks of BLOCK_SIZE are present, returning the answer */
538 static unsigned long long
539 count_blocks (char *filename)
544 if ((fd = open (filename, O_RDONLY)) < 0)
550 /* first try SEEK_END, which should work on most devices nowadays */
551 if ((low = llseek(fd, 0, SEEK_END)) <= 0) {
553 for (high = 1; valid_offset (fd, high); high *= 2)
555 while (low < high - 1) {
556 const loff_t mid = (low + high) / 2;
557 if (valid_offset (fd, mid))
566 return low / BLOCK_SIZE;
570 /* Check to see if the specified device is currently mounted - abort if it is */
573 check_mount (char *device_name)
578 if ((f = setmntent (MOUNTED, "r")) == NULL)
580 while ((mnt = getmntent (f)) != NULL)
581 if (strcmp (device_name, mnt->mnt_fsname) == 0)
582 die ("%s contains a mounted file system.");
587 /* Establish the geometry and media parameters for the device */
590 establish_params (int device_num,int size)
593 struct hd_geometry geometry;
594 struct floppy_struct param;
595 int def_root_dir_entries = 512;
597 if ((0 == device_num) || ((device_num & 0xff00) == 0x0200))
598 /* file image or floppy disk */
602 param.size = size/512;
633 else /* is a floppy diskette */
635 if (ioctl (dev, FDGETPRM, ¶m)) /* Can we get the diskette geometry? */
636 die ("unable to get diskette geometry for '%s'");
638 bs.secs_track = CT_LE_W(param.sect); /* Set up the geometry information */
639 bs.heads = CT_LE_W(param.head);
640 switch (param.size) /* Set up the media descriptor byte */
642 case 720: /* 5.25", 2, 9, 40 - 360K */
643 bs.media = (char) 0xfd;
644 bs.cluster_size = (char) 2;
645 def_root_dir_entries = 112;
648 case 1440: /* 3.5", 2, 9, 80 - 720K */
649 bs.media = (char) 0xf9;
650 bs.cluster_size = (char) 2;
651 def_root_dir_entries = 112;
654 case 2400: /* 5.25", 2, 15, 80 - 1200K */
655 bs.media = (char) 0xf9;
656 bs.cluster_size = (char)(atari_format ? 2 : 1);
657 def_root_dir_entries = 224;
660 case 5760: /* 3.5", 2, 36, 80 - 2880K */
661 bs.media = (char) 0xf0;
662 bs.cluster_size = (char) 2;
663 def_root_dir_entries = 224;
666 case 2880: /* 3.5", 2, 18, 80 - 1440K */
668 bs.media = (char) 0xf0;
669 bs.cluster_size = (char)(atari_format ? 2 : 1);
670 def_root_dir_entries = 224;
673 default: /* Anything else */
680 else if ((device_num & 0xff00) == 0x0700) /* This is a loop device */
682 if (ioctl (dev, BLKGETSIZE, &loop_size))
683 die ("unable to get loop device size");
685 switch (loop_size) /* Assuming the loop device -> floppy later */
687 case 720: /* 5.25", 2, 9, 40 - 360K */
688 bs.secs_track = CF_LE_W(9);
689 bs.heads = CF_LE_W(2);
690 bs.media = (char) 0xfd;
691 bs.cluster_size = (char) 2;
692 def_root_dir_entries = 112;
695 case 1440: /* 3.5", 2, 9, 80 - 720K */
696 bs.secs_track = CF_LE_W(9);
697 bs.heads = CF_LE_W(2);
698 bs.media = (char) 0xf9;
699 bs.cluster_size = (char) 2;
700 def_root_dir_entries = 112;
703 case 2400: /* 5.25", 2, 15, 80 - 1200K */
704 bs.secs_track = CF_LE_W(15);
705 bs.heads = CF_LE_W(2);
706 bs.media = (char) 0xf9;
707 bs.cluster_size = (char)(atari_format ? 2 : 1);
708 def_root_dir_entries = 224;
711 case 5760: /* 3.5", 2, 36, 80 - 2880K */
712 bs.secs_track = CF_LE_W(36);
713 bs.heads = CF_LE_W(2);
714 bs.media = (char) 0xf0;
715 bs.cluster_size = (char) 2;
716 bs.dir_entries[0] = (char) 224;
717 bs.dir_entries[1] = (char) 0;
720 case 2880: /* 3.5", 2, 18, 80 - 1440K */
721 bs.secs_track = CF_LE_W(18);
722 bs.heads = CF_LE_W(2);
723 bs.media = (char) 0xf0;
724 bs.cluster_size = (char)(atari_format ? 2 : 1);
725 def_root_dir_entries = 224;
728 default: /* Anything else: default hd setup */
729 printf("Loop device does not match a floppy size, using "
730 "default hd params\n");
731 bs.secs_track = CT_LE_W(32); /* these are fake values... */
732 bs.heads = CT_LE_W(64);
737 /* Must be a hard disk then! */
739 /* Can we get the drive geometry? (Note I'm not too sure about */
740 /* whether to use HDIO_GETGEO or HDIO_REQ) */
741 if (ioctl (dev, HDIO_GETGEO, &geometry) || geometry.sectors == 0 || geometry.heads == 0) {
742 printf ("unable to get drive geometry, using default 255/63\n");
743 bs.secs_track = CT_LE_W(63);
744 bs.heads = CT_LE_W(255);
747 bs.secs_track = CT_LE_W(geometry.sectors); /* Set up the geometry information */
748 bs.heads = CT_LE_W(geometry.heads);
751 bs.media = (char) 0xf8; /* Set up the media descriptor for a hard drive */
752 if (!size_fat && blocks*SECTORS_PER_BLOCK > 1064960) {
753 if (verbose) printf("Auto-selecting FAT32 for large filesystem\n");
756 if (size_fat == 32) {
757 /* For FAT32, try to do the same as M$'s format command
758 * (see http://www.win.tue.nl/~aeb/linux/fs/fat/fatgen103.pdf p. 20):
759 * fs size <= 260M: 0.5k clusters
760 * fs size <= 8G: 4k clusters
761 * fs size <= 16G: 8k clusters
762 * fs size > 16G: 16k clusters
764 unsigned long sz_mb =
765 (blocks+(1<<(20-BLOCK_SIZE_BITS))-1) >> (20-BLOCK_SIZE_BITS);
766 bs.cluster_size = sz_mb > 16*1024 ? 32 :
767 sz_mb > 8*1024 ? 16 :
772 /* FAT12 and FAT16: start at 4 sectors per cluster */
773 bs.cluster_size = (char) 4;
777 if (!root_dir_entries)
778 root_dir_entries = def_root_dir_entries;
782 * If alignment is enabled, round the first argument up to the second; the
783 * latter must be a power of two.
786 align_object (unsigned int sectors, unsigned int clustsize)
788 if (align_structures)
789 return (sectors + clustsize - 1) & ~(clustsize - 1);
794 /* Create the filesystem data tables */
799 unsigned num_sectors;
800 unsigned cluster_count = 0, fat_length;
802 struct msdos_volume_info *vi = (size_fat == 32 ? &bs.fat32.vi : &bs.oldfat.vi);
805 /* On Atari, the first few bytes of the boot sector are assigned
806 * differently: The jump code is only 2 bytes (and m68k machine code
807 * :-), then 6 bytes filler (ignored), then 3 byte serial number. */
808 memcpy( bs.system_id-1, "mkdosf", 6 );
810 strcpy (bs.system_id, "mkdosfs");
811 if (sectors_per_cluster)
812 bs.cluster_size = (char) sectors_per_cluster;
815 /* Under FAT32, the root dir is in a cluster chain, and this is
816 * signalled by bs.dir_entries being 0. */
817 root_dir_entries = 0;
821 bs.system_id[5] = (unsigned char) (volume_id & 0x000000ff);
822 bs.system_id[6] = (unsigned char) ((volume_id & 0x0000ff00) >> 8);
823 bs.system_id[7] = (unsigned char) ((volume_id & 0x00ff0000) >> 16);
826 vi->volume_id[0] = (unsigned char) (volume_id & 0x000000ff);
827 vi->volume_id[1] = (unsigned char) ((volume_id & 0x0000ff00) >> 8);
828 vi->volume_id[2] = (unsigned char) ((volume_id & 0x00ff0000) >> 16);
829 vi->volume_id[3] = (unsigned char) (volume_id >> 24);
833 memcpy(vi->volume_label, volume_name, 11);
835 memcpy(bs.boot_jump, dummy_boot_jump, 3);
836 /* Patch in the correct offset to the boot code */
837 bs.boot_jump[1] = ((size_fat == 32 ?
838 (char *)&bs.fat32.boot_code :
839 (char *)&bs.oldfat.boot_code) -
842 if (size_fat == 32) {
843 int offset = (char *)&bs.fat32.boot_code -
844 (char *)&bs + MESSAGE_OFFSET + 0x7c00;
845 if (dummy_boot_code[BOOTCODE_FAT32_SIZE-1])
846 printf ("Warning: message too long; truncated\n");
847 dummy_boot_code[BOOTCODE_FAT32_SIZE-1] = 0;
848 memcpy(bs.fat32.boot_code, dummy_boot_code, BOOTCODE_FAT32_SIZE);
849 bs.fat32.boot_code[MSG_OFFSET_OFFSET] = offset & 0xff;
850 bs.fat32.boot_code[MSG_OFFSET_OFFSET+1] = offset >> 8;
853 memcpy(bs.oldfat.boot_code, dummy_boot_code, BOOTCODE_SIZE);
855 bs.boot_sign = CT_LE_W(BOOT_SIGN);
858 memcpy(bs.boot_jump, dummy_boot_jump_m68k, 2);
861 printf( "Boot jump code is %02x %02x\n",
862 bs.boot_jump[0], bs.boot_jump[1] );
864 if (!reserved_sectors)
865 reserved_sectors = (size_fat == 32) ? 32 : 1;
867 if (size_fat == 32 && reserved_sectors < 2)
868 die("On FAT32 at least 2 reserved sectors are needed.");
870 bs.reserved = CT_LE_W(reserved_sectors);
872 printf( "Using %d reserved sectors\n", reserved_sectors );
873 bs.fats = (char) nr_fats;
874 if (!atari_format || size_fat == 32)
875 bs.hidden = CT_LE_L(hidden_sectors);
877 /* In Atari format, hidden is a 16 bit field */
878 __u16 hidden = CT_LE_W(hidden_sectors);
879 if (hidden_sectors & ~0xffff)
880 die("#hidden doesn't fit in 16bit field of Atari format\n");
881 memcpy( &bs.hidden, &hidden, 2 );
884 num_sectors = (long long)blocks*BLOCK_SIZE/sector_size;
886 unsigned fatdata1216; /* Sectors for FATs + data area (FAT12/16) */
887 unsigned fatdata32; /* Sectors for FATs + data area (FAT32) */
888 unsigned fatlength12, fatlength16, fatlength32;
889 unsigned maxclust12, maxclust16, maxclust32;
890 unsigned clust12, clust16, clust32;
892 unsigned root_dir_sectors = cdiv(root_dir_entries*32, sector_size);
895 * If the filesystem is 8192 sectors or less (4 MB with 512-byte
896 * sectors, i.e. floppy size), don't align the data structures.
898 if (num_sectors <= 8192) {
899 if (align_structures && verbose >= 2)
900 printf ("Disabling alignment due to tiny filesystem\n");
902 align_structures = FALSE;
905 if (sectors_per_cluster)
906 bs.cluster_size = maxclustsize = sectors_per_cluster;
908 /* An initial guess for bs.cluster_size should already be set */
912 fatdata32 = num_sectors
913 - align_object(reserved_sectors, bs.cluster_size);
914 fatdata1216 = fatdata32
915 - align_object(root_dir_sectors, bs.cluster_size);
918 printf( "Trying with %d sectors/cluster:\n", bs.cluster_size );
920 /* The factor 2 below avoids cut-off errors for nr_fats == 1.
921 * The "nr_fats*3" is for the reserved first two FAT entries */
922 clust12 = 2*((long long) fatdata1216*sector_size + nr_fats*3) /
923 (2*(int) bs.cluster_size * sector_size + nr_fats*3);
924 fatlength12 = cdiv(((clust12+2) * 3 + 1) >> 1, sector_size);
925 fatlength12 = align_object(fatlength12, bs.cluster_size);
926 /* Need to recalculate number of clusters, since the unused parts of the
927 * FATS and data area together could make up space for an additional,
928 * not really present cluster. */
929 clust12 = (fatdata1216 - nr_fats*fatlength12)/bs.cluster_size;
930 maxclust12 = (fatlength12 * 2 * sector_size) / 3;
931 if (maxclust12 > MAX_CLUST_12)
932 maxclust12 = MAX_CLUST_12;
934 printf( "FAT12: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n",
935 clust12, fatlength12, maxclust12, MAX_CLUST_12 );
936 if (clust12 > maxclust12-2) {
939 printf( "FAT12: too much clusters\n" );
942 clust16 = ((long long) fatdata1216 *sector_size + nr_fats*4) /
943 ((int) bs.cluster_size * sector_size + nr_fats*2);
944 fatlength16 = cdiv ((clust16+2) * 2, sector_size);
945 fatlength16 = align_object(fatlength16, bs.cluster_size);
946 /* Need to recalculate number of clusters, since the unused parts of the
947 * FATS and data area together could make up space for an additional,
948 * not really present cluster. */
949 clust16 = (fatdata1216 - nr_fats*fatlength16)/bs.cluster_size;
950 maxclust16 = (fatlength16 * sector_size) / 2;
951 if (maxclust16 > MAX_CLUST_16)
952 maxclust16 = MAX_CLUST_16;
954 printf( "FAT16: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n",
955 clust16, fatlength16, maxclust16, MAX_CLUST_16 );
956 if (clust16 > maxclust16-2) {
958 printf( "FAT16: too much clusters\n" );
961 /* The < 4078 avoids that the filesystem will be misdetected as having a
963 if (clust16 < FAT12_THRESHOLD && !(size_fat_by_user && size_fat == 16)) {
965 printf( clust16 < FAT12_THRESHOLD ?
966 "FAT16: would be misdetected as FAT12\n" :
967 "FAT16: too much clusters\n" );
971 clust32 = ((long long) fatdata32 *sector_size + nr_fats*8) /
972 ((int) bs.cluster_size * sector_size + nr_fats*4);
973 fatlength32 = cdiv((clust32+2) * 4, sector_size);
974 fatlength32 = align_object(fatlength32, bs.cluster_size);
975 /* Need to recalculate number of clusters, since the unused parts of the
976 * FATS and data area together could make up space for an additional,
977 * not really present cluster. */
978 clust32 = (fatdata32 - nr_fats*fatlength32)/bs.cluster_size;
979 maxclust32 = (fatlength32 * sector_size) / 4;
980 if (maxclust32 > MAX_CLUST_32)
981 maxclust32 = MAX_CLUST_32;
982 if (clust32 && clust32 < MIN_CLUST_32 && !(size_fat_by_user && size_fat == 32)) {
985 printf( "FAT32: not enough clusters (%d)\n", MIN_CLUST_32);
988 printf( "FAT32: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n",
989 clust32, fatlength32, maxclust32, MAX_CLUST_32 );
990 if (clust32 > maxclust32) {
993 printf( "FAT32: too much clusters\n" );
996 if ((clust12 && (size_fat == 0 || size_fat == 12)) ||
997 (clust16 && (size_fat == 0 || size_fat == 16)) ||
998 (clust32 && size_fat == 32))
1001 bs.cluster_size <<= 1;
1002 } while (bs.cluster_size && bs.cluster_size <= maxclustsize);
1004 /* Use the optimal FAT size if not specified;
1005 * FAT32 is (not yet) choosen automatically */
1007 size_fat = (clust16 > clust12) ? 16 : 12;
1009 printf( "Choosing %d bits for FAT\n", size_fat );
1014 cluster_count = clust12;
1015 fat_length = fatlength12;
1016 bs.fat_length = CT_LE_W(fatlength12);
1017 memcpy(vi->fs_type, MSDOS_FAT12_SIGN, 8);
1021 if (clust16 < FAT12_THRESHOLD) {
1022 if (size_fat_by_user) {
1023 fprintf( stderr, "WARNING: Not enough clusters for a "
1024 "16 bit FAT! The filesystem will be\n"
1025 "misinterpreted as having a 12 bit FAT without "
1026 "mount option \"fat=16\".\n" );
1029 fprintf( stderr, "This filesystem has an unfortunate size. "
1030 "A 12 bit FAT cannot provide\n"
1031 "enough clusters, but a 16 bit FAT takes up a little "
1032 "bit more space so that\n"
1033 "the total number of clusters becomes less than the "
1034 "threshold value for\n"
1035 "distinction between 12 and 16 bit FATs.\n" );
1036 die( "Make the file system a bit smaller manually." );
1039 cluster_count = clust16;
1040 fat_length = fatlength16;
1041 bs.fat_length = CT_LE_W(fatlength16);
1042 memcpy(vi->fs_type, MSDOS_FAT16_SIGN, 8);
1046 if (clust32 < MIN_CLUST_32)
1047 fprintf(stderr, "WARNING: Not enough clusters for a 32 bit FAT!\n");
1048 cluster_count = clust32;
1049 fat_length = fatlength32;
1050 bs.fat_length = CT_LE_W(0);
1051 bs.fat32.fat32_length = CT_LE_L(fatlength32);
1052 memcpy(vi->fs_type, MSDOS_FAT32_SIGN, 8);
1053 root_dir_entries = 0;
1057 die("FAT not 12, 16 or 32 bits");
1060 /* Adjust the reserved number of sectors for alignment */
1061 reserved_sectors = align_object(reserved_sectors, bs.cluster_size);
1062 bs.reserved = CT_LE_W(reserved_sectors);
1064 /* Adjust the number of root directory entries to help enforce alignment */
1065 if (align_structures) {
1066 root_dir_entries = align_object(root_dir_sectors, bs.cluster_size)
1067 * (sector_size >> 5);
1071 unsigned clusters, maxclust, fatdata;
1073 /* GEMDOS always uses a 12 bit FAT on floppies, and always a 16 bit FAT on
1074 * hard disks. So use 12 bit if the size of the file system suggests that
1075 * this fs is for a floppy disk, if the user hasn't explicitly requested a
1079 size_fat = (num_sectors == 1440 || num_sectors == 2400 ||
1080 num_sectors == 2880 || num_sectors == 5760) ? 12 : 16;
1082 printf( "Choosing %d bits for FAT\n", size_fat );
1084 /* Atari format: cluster size should be 2, except explicitly requested by
1085 * the user, since GEMDOS doesn't like other cluster sizes very much.
1086 * Instead, tune the sector size for the FS to fit.
1088 bs.cluster_size = sectors_per_cluster ? sectors_per_cluster : 2;
1089 if (!sector_size_set) {
1090 while( num_sectors > GEMDOS_MAX_SECTORS ) {
1096 printf( "Sector size must be %d to have less than %d log. sectors\n",
1097 sector_size, GEMDOS_MAX_SECTORS );
1099 /* Check if there are enough FAT indices for how much clusters we have */
1101 fatdata = num_sectors - cdiv (root_dir_entries * 32, sector_size) -
1103 /* The factor 2 below avoids cut-off errors for nr_fats == 1 and
1105 * The "2*nr_fats*size_fat/8" is for the reserved first two FAT entries
1107 clusters = (2*((long long)fatdata*sector_size - 2*nr_fats*size_fat/8)) /
1108 (2*((int)bs.cluster_size*sector_size + nr_fats*size_fat/8));
1109 fat_length = cdiv( (clusters+2)*size_fat/8, sector_size );
1110 /* Need to recalculate number of clusters, since the unused parts of the
1111 * FATS and data area together could make up space for an additional,
1112 * not really present cluster. */
1113 clusters = (fatdata - nr_fats*fat_length)/bs.cluster_size;
1114 maxclust = (fat_length*sector_size*8)/size_fat;
1116 printf( "ss=%d: #clu=%d, fat_len=%d, maxclu=%d\n",
1117 sector_size, clusters, fat_length, maxclust );
1119 /* last 10 cluster numbers are special (except FAT32: 4 high bits rsvd);
1120 * first two numbers are reserved */
1121 if (maxclust <= (size_fat == 32 ? MAX_CLUST_32 : (1<<size_fat)-0x10) &&
1122 clusters <= maxclust-2)
1125 printf( clusters > maxclust-2 ?
1126 "Too many clusters\n" : "FAT too big\n" );
1128 /* need to increment sector_size once more to */
1129 if (sector_size_set)
1130 die( "With this sector size, the maximum number of FAT entries "
1131 "would be exceeded." );
1134 } while( sector_size <= GEMDOS_MAX_SECTOR_SIZE );
1136 if (sector_size > GEMDOS_MAX_SECTOR_SIZE)
1137 die( "Would need a sector size > 16k, which GEMDOS can't work with");
1139 cluster_count = clusters;
1141 bs.fat_length = CT_LE_W(fat_length);
1144 bs.fat32.fat32_length = CT_LE_L(fat_length);
1148 bs.sector_size[0] = (char) (sector_size & 0x00ff);
1149 bs.sector_size[1] = (char) ((sector_size & 0xff00) >> 8);
1151 bs.dir_entries[0] = (char) (root_dir_entries & 0x00ff);
1152 bs.dir_entries[1] = (char) ((root_dir_entries & 0xff00) >> 8);
1156 /* set up additional FAT32 fields */
1157 bs.fat32.flags = CT_LE_W(0);
1158 bs.fat32.version[0] = 0;
1159 bs.fat32.version[1] = 0;
1160 bs.fat32.root_cluster = CT_LE_L(2);
1161 bs.fat32.info_sector = CT_LE_W(1);
1163 backup_boot = (reserved_sectors >= 7) ? 6 :
1164 (reserved_sectors >= 2) ? reserved_sectors-1 : 0;
1167 if (backup_boot == 1)
1168 die("Backup boot sector must be after sector 1");
1169 else if (backup_boot >= reserved_sectors)
1170 die("Backup boot sector must be a reserved sector");
1173 printf( "Using sector %d as backup boot sector (0 = none)\n",
1175 bs.fat32.backup_boot = CT_LE_W(backup_boot);
1176 memset( &bs.fat32.reserved2, 0, sizeof(bs.fat32.reserved2) );
1180 /* Just some consistency checks */
1181 if (num_sectors >= GEMDOS_MAX_SECTORS)
1182 die( "GEMDOS can't handle more than 65531 sectors" );
1183 else if (num_sectors >= OLDGEMDOS_MAX_SECTORS)
1184 printf( "Warning: More than 32765 sector need TOS 1.04 "
1187 if (num_sectors >= 65536)
1189 bs.sectors[0] = (char) 0;
1190 bs.sectors[1] = (char) 0;
1191 bs.total_sect = CT_LE_L(num_sectors);
1195 bs.sectors[0] = (char) (num_sectors & 0x00ff);
1196 bs.sectors[1] = (char) ((num_sectors & 0xff00) >> 8);
1198 bs.total_sect = CT_LE_L(0);
1202 vi->ext_boot_sign = MSDOS_EXT_SIGN;
1206 if (sectors_per_cluster) /* If yes, die if we'd spec'd sectors per cluster */
1207 die ("Too many clusters for file system - try more sectors per cluster");
1209 die ("Attempting to create a too large file system");
1213 /* The two following vars are in hard sectors, i.e. 512 byte sectors! */
1214 start_data_sector = (reserved_sectors + nr_fats * fat_length) *
1215 (sector_size/HARD_SECTOR_SIZE);
1216 start_data_block = (start_data_sector + SECTORS_PER_BLOCK - 1) /
1219 if (blocks < start_data_block + 32) /* Arbitrary undersize file system! */
1220 die ("Too few blocks for viable file system");
1224 printf("%s has %d head%s and %d sector%s per track,\n",
1225 device_name, CF_LE_W(bs.heads), (CF_LE_W(bs.heads) != 1) ? "s" : "",
1226 CF_LE_W(bs.secs_track), (CF_LE_W(bs.secs_track) != 1) ? "s" : "");
1227 printf("logical sector size is %d,\n",sector_size);
1228 printf("using 0x%02x media descriptor, with %d sectors;\n",
1229 (int) (bs.media), num_sectors);
1230 printf("file system has %d %d-bit FAT%s and %d sector%s per cluster.\n",
1231 (int) (bs.fats), size_fat, (bs.fats != 1) ? "s" : "",
1232 (int) (bs.cluster_size), (bs.cluster_size != 1) ? "s" : "");
1233 printf ("FAT size is %d sector%s, and provides %d cluster%s.\n",
1234 fat_length, (fat_length != 1) ? "s" : "",
1235 cluster_count, (cluster_count != 1) ? "s" : "");
1236 printf ("There %s %u reserved sector%s.\n",
1237 (reserved_sectors != 1) ? "are" : "is",
1239 (reserved_sectors != 1) ? "s" : "");
1241 if (size_fat != 32) {
1242 unsigned root_dir_entries =
1243 bs.dir_entries[0] + ((bs.dir_entries[1]) * 256);
1244 unsigned root_dir_sectors =
1245 cdiv (root_dir_entries*32, sector_size);
1246 printf ("Root directory contains %u slots and uses %u sectors.\n",
1247 root_dir_entries, root_dir_sectors);
1249 printf ("Volume ID is %08lx, ", volume_id &
1250 (atari_format ? 0x00ffffff : 0xffffffff));
1251 if ( strcmp(volume_name, " ") )
1252 printf("volume label %s.\n", volume_name);
1254 printf("no volume label.\n");
1257 /* Make the file allocation tables! */
1259 if (malloc_entire_fat)
1260 alloced_fat_length = fat_length;
1262 alloced_fat_length = 1;
1264 if ((fat = (unsigned char *) malloc (alloced_fat_length * sector_size)) == NULL)
1265 die ("unable to allocate space for FAT image in memory");
1267 memset( fat, 0, alloced_fat_length * sector_size );
1269 mark_FAT_cluster (0, 0xffffffff); /* Initial fat entries */
1270 mark_FAT_cluster (1, 0xffffffff);
1271 fat[0] = (unsigned char) bs.media; /* Put media type in first byte! */
1272 if (size_fat == 32) {
1273 /* Mark cluster 2 as EOF (used for root dir) */
1274 mark_FAT_cluster (2, FAT_EOF);
1277 /* Make the root directory entries */
1279 size_root_dir = (size_fat == 32) ?
1280 bs.cluster_size*sector_size :
1281 (((int)bs.dir_entries[1]*256+(int)bs.dir_entries[0]) *
1282 sizeof (struct msdos_dir_entry));
1283 if ((root_dir = (struct msdos_dir_entry *) malloc (size_root_dir)) == NULL)
1285 free (fat); /* Tidy up before we die! */
1286 die ("unable to allocate space for root directory in memory");
1289 memset(root_dir, 0, size_root_dir);
1290 if ( memcmp(volume_name, " ", 11) )
1292 struct msdos_dir_entry *de = &root_dir[0];
1293 memcpy(de->name, volume_name, 8);
1294 memcpy(de->ext, volume_name+8, 3);
1295 de->attr = ATTR_VOLUME;
1296 ctime = localtime(&create_time);
1297 de->time = CT_LE_W((unsigned short)((ctime->tm_sec >> 1) +
1298 (ctime->tm_min << 5) + (ctime->tm_hour << 11)));
1299 de->date = CT_LE_W((unsigned short)(ctime->tm_mday +
1300 ((ctime->tm_mon+1) << 5) +
1301 ((ctime->tm_year-80) << 9)));
1303 de->ctime = de->time;
1304 de->cdate = de->date;
1305 de->adate = de->date;
1306 de->starthi = CT_LE_W(0);
1307 de->start = CT_LE_W(0);
1308 de->size = CT_LE_L(0);
1311 if (size_fat == 32) {
1312 /* For FAT32, create an info sector */
1313 struct fat32_fsinfo *info;
1315 if (!(info_sector = malloc( sector_size )))
1316 die("Out of memory");
1317 memset(info_sector, 0, sector_size);
1318 /* fsinfo structure is at offset 0x1e0 in info sector by observation */
1319 info = (struct fat32_fsinfo *)(info_sector + 0x1e0);
1321 /* Info sector magic */
1322 info_sector[0] = 'R';
1323 info_sector[1] = 'R';
1324 info_sector[2] = 'a';
1325 info_sector[3] = 'A';
1327 /* Magic for fsinfo structure */
1328 info->signature = CT_LE_L(0x61417272);
1329 /* We've allocated cluster 2 for the root dir. */
1330 info->free_clusters = CT_LE_L(cluster_count - 1);
1331 info->next_cluster = CT_LE_L(2);
1333 /* Info sector also must have boot sign */
1334 *(__u16 *)(info_sector + 0x1fe) = CT_LE_W(BOOT_SIGN);
1337 if (!(blank_sector = malloc( sector_size )))
1338 die( "Out of memory" );
1339 memset(blank_sector, 0, sector_size);
1343 /* Write the new filesystem's data tables to wherever they're going to end up! */
1345 #define error(str) \
1348 if (info_sector) free (info_sector); \
1353 #define seekto(pos,errstr) \
1355 loff_t __pos = (pos); \
1356 if (llseek (dev, __pos, SEEK_SET) != __pos) \
1357 error ("seek to " errstr " failed whilst writing tables"); \
1360 #define writebuf(buf,size,errstr) \
1362 int __size = (size); \
1363 if (write (dev, buf, __size) != __size) \
1364 error ("failed whilst writing " errstr); \
1374 fat_length = (size_fat == 32) ?
1375 CF_LE_L(bs.fat32.fat32_length) : CF_LE_W(bs.fat_length);
1377 seekto( 0, "start of device" );
1378 /* clear all reserved sectors */
1379 for( x = 0; x < reserved_sectors; ++x )
1380 writebuf( blank_sector, sector_size, "reserved sector" );
1381 /* seek back to sector 0 and write the boot sector */
1382 seekto( 0, "boot sector" );
1383 writebuf( (char *) &bs, sizeof (struct msdos_boot_sector), "boot sector" );
1384 /* on FAT32, write the info sector and backup boot sector */
1387 seekto( CF_LE_W(bs.fat32.info_sector)*sector_size, "info sector" );
1388 writebuf( info_sector, 512, "info sector" );
1389 if (backup_boot != 0)
1391 seekto( backup_boot*sector_size, "backup boot sector" );
1392 writebuf( (char *) &bs, sizeof (struct msdos_boot_sector),
1393 "backup boot sector" );
1396 /* seek to start of FATS and write them all */
1397 seekto( reserved_sectors*sector_size, "first FAT" );
1398 for (x = 1; x <= nr_fats; x++) {
1400 int blank_fat_length = fat_length - alloced_fat_length;
1401 writebuf( fat, alloced_fat_length * sector_size, "FAT" );
1402 for (y=0; y<blank_fat_length; y++)
1403 writebuf( blank_sector, sector_size, "FAT" );
1405 /* Write the root directory directly after the last FAT. This is the root
1406 * dir area on FAT12/16, and the first cluster on FAT32. */
1407 writebuf( (char *) root_dir, size_root_dir, "root directory" );
1409 if (blank_sector) free( blank_sector );
1410 if (info_sector) free( info_sector );
1411 free (root_dir); /* Free up the root directory space from setup_tables */
1412 free (fat); /* Free up the fat table space reserved during setup_tables */
1416 /* Report the command usage and return a failure error code */
1422 Usage: mkdosfs [-a][-A][-c][-C][-v][-I][-l bad-block-file][-b backup-boot-sector]\n\
1423 [-m boot-msg-file][-n volume-name][-i volume-id]\n\
1424 [-s sectors-per-cluster][-S logical-sector-size][-f number-of-FATs]\n\
1425 [-h hidden-sectors][-F fat-size][-r root-dir-entries][-R reserved-sectors]\n\
1426 /dev/name [blocks]\n");
1430 * ++roman: On m68k, check if this is an Atari; if yes, turn on Atari variant
1431 * of MS-DOS filesystem by default.
1433 static void check_atari( void )
1439 if (!(f = fopen( "/proc/hardware", "r" ))) {
1440 perror( "/proc/hardware" );
1444 while( fgets( line, sizeof(line), f ) ) {
1445 if (strncmp( line, "Model:", 6 ) == 0) {
1447 p += strspn( p, " \t" );
1448 if (strncmp( p, "Atari ", 6 ) == 0)
1457 /* The "main" entry point into the utility - we pick up the options and attempt to process them in some sort of sensible
1458 way. In the event that some/all of the options are invalid we need to tell the user so that something can be done! */
1461 main (int argc, char **argv)
1465 char *listfile = NULL;
1467 struct stat statbuf;
1470 unsigned long long cblocks = 0;
1471 int min_sector_size;
1473 if (argc && *argv) { /* What's the program name? */
1475 program_name = *argv;
1476 if ((p = strrchr( program_name, '/' )))
1480 gettimeofday(&create_timeval, NULL);
1481 create_time = create_timeval.tv_sec;
1482 volume_id = (u_int32_t)( (create_timeval.tv_sec << 20) | create_timeval.tv_usec ); /* Default volume ID = creation time, fudged for more uniqueness */
1485 printf ("%s " VERSION " (" VERSION_DATE ")\n",
1488 while ((c = getopt (argc, argv, "aAb:cCf:F:Ii:l:m:n:r:R:s:S:h:v")) != EOF)
1489 /* Scan the command line for options */
1492 case 'A': /* toggle Atari format */
1493 atari_format = !atari_format;
1496 case 'a': /* a : skip alignment */
1497 align_structures = FALSE;
1500 case 'b': /* b : location of backup boot sector */
1501 backup_boot = (int) strtol (optarg, &tmp, 0);
1502 if (*tmp || backup_boot < 2 || backup_boot > 0xffff)
1504 printf ("Bad location for backup boot sector : %s\n", optarg);
1509 case 'c': /* c : Check FS as we build it */
1511 malloc_entire_fat = TRUE; /* Need to be able to mark clusters bad */
1514 case 'C': /* C : Create a new file */
1518 case 'f': /* f : Choose number of FATs */
1519 nr_fats = (int) strtol (optarg, &tmp, 0);
1520 if (*tmp || nr_fats < 1 || nr_fats > 4)
1522 printf ("Bad number of FATs : %s\n", optarg);
1527 case 'F': /* F : Choose FAT size */
1528 size_fat = (int) strtol (optarg, &tmp, 0);
1529 if (*tmp || (size_fat != 12 && size_fat != 16 && size_fat != 32))
1531 printf ("Bad FAT type : %s\n", optarg);
1534 size_fat_by_user = 1;
1537 case 'h': /* h : number of hidden sectors */
1538 hidden_sectors = (int) strtol (optarg, &tmp, 0);
1539 if ( *tmp || hidden_sectors < 0 )
1541 printf("Bad number of hidden sectors : %s\n", optarg);
1547 ignore_full_disk = 1;
1550 case 'i': /* i : specify volume ID */
1551 volume_id = strtoul(optarg, &tmp, 16);
1554 printf("Volume ID must be a hexadecimal number\n");
1559 case 'l': /* l : Bad block filename */
1561 malloc_entire_fat = TRUE; /* Need to be able to mark clusters bad */
1564 case 'm': /* m : Set boot message */
1565 if ( strcmp(optarg, "-") )
1567 msgfile = fopen(optarg, "r");
1576 /* The boot code ends at offset 448 and needs a null terminator */
1578 pos = 0; /* We are at beginning of line */
1584 case '\r': /* Ignore CRs */
1585 case '\0': /* and nulls */
1588 case '\n': /* LF -> CR+LF if necessary */
1589 if ( pos ) /* If not at beginning of line */
1591 dummy_boot_code[i++] = '\r';
1594 dummy_boot_code[i++] = '\n';
1597 case '\t': /* Expand tabs */
1600 dummy_boot_code[i++] = ' ';
1603 while ( pos % 8 && i < BOOTCODE_SIZE-1 );
1607 dummy_boot_code[i++] = '\0'; /* Null terminator */
1611 dummy_boot_code[i++] = ch; /* Store character */
1612 pos++; /* Advance position */
1616 while ( ch != EOF && i < BOOTCODE_SIZE-1 );
1618 /* Fill up with zeros */
1619 while( i < BOOTCODE_SIZE-1 )
1620 dummy_boot_code[i++] = '\0';
1621 dummy_boot_code[BOOTCODE_SIZE-1] = '\0'; /* Just in case */
1624 printf ("Warning: message too long; truncated\n");
1626 if ( msgfile != stdin )
1631 case 'n': /* n : Volume name */
1632 sprintf(volume_name, "%-11.11s", optarg);
1635 case 'r': /* r : Root directory entries */
1636 root_dir_entries = (int) strtol (optarg, &tmp, 0);
1637 if (*tmp || root_dir_entries < 16 || root_dir_entries > 32768)
1639 printf ("Bad number of root directory entries : %s\n", optarg);
1644 case 'R': /* R : number of reserved sectors */
1645 reserved_sectors = (int) strtol (optarg, &tmp, 0);
1646 if (*tmp || reserved_sectors < 1 || reserved_sectors > 0xffff)
1648 printf ("Bad number of reserved sectors : %s\n", optarg);
1653 case 's': /* s : Sectors per cluster */
1654 sectors_per_cluster = (int) strtol (optarg, &tmp, 0);
1655 if (*tmp || (sectors_per_cluster != 1 && sectors_per_cluster != 2
1656 && sectors_per_cluster != 4 && sectors_per_cluster != 8
1657 && sectors_per_cluster != 16 && sectors_per_cluster != 32
1658 && sectors_per_cluster != 64 && sectors_per_cluster != 128))
1660 printf ("Bad number of sectors per cluster : %s\n", optarg);
1665 case 'S': /* S : Sector size */
1666 sector_size = (int) strtol (optarg, &tmp, 0);
1667 if (*tmp || (sector_size != 512 && sector_size != 1024 &&
1668 sector_size != 2048 && sector_size != 4096 &&
1669 sector_size != 8192 && sector_size != 16384 &&
1670 sector_size != 32768))
1672 printf ("Bad logical sector size : %s\n", optarg);
1675 sector_size_set = 1;
1678 case 'v': /* v : Verbose execution */
1683 printf( "Unknown option: %c\n", c );
1688 device_name = argv[optind]; /* Determine the number of blocks in the FS */
1691 printf("No device specified.\n");
1696 cblocks = count_blocks (device_name); /* Have a look and see! */
1698 if (optind == argc - 2) /* Either check the user specified number */
1700 blocks = strtoull (argv[optind + 1], &tmp, 0);
1701 if (!create && blocks != cblocks)
1703 fprintf (stderr, "Warning: block count mismatch: ");
1704 fprintf (stderr, "found %llu but assuming %llu.\n",cblocks,blocks);
1707 else if (optind == argc - 1) /* Or use value found */
1710 die( "Need intended size with -C." );
1716 fprintf (stderr, "No device specified!\n");
1721 printf ("Bad block count : %s\n", argv[optind + 1]);
1725 if (check && listfile) /* Auto and specified bad block handling are mutually */
1726 die ("-c and -l are incompatible"); /* exclusive of each other! */
1729 check_mount (device_name); /* Is the device already mounted? */
1730 dev = open (device_name, O_EXCL|O_RDWR); /* Is it a suitable device to build the FS on? */
1732 die ("unable to open %s");
1735 loff_t offset = blocks*BLOCK_SIZE - 1;
1737 /* create the file */
1738 dev = open( device_name, O_EXCL|O_RDWR|O_CREAT|O_TRUNC, 0666 );
1740 die("unable to create %s");
1741 /* seek to the intended end-1, and write one byte. this creates a
1742 * sparse-as-possible file of appropriate size. */
1743 if (llseek( dev, offset, SEEK_SET ) != offset)
1744 die( "seek failed" );
1745 if (write( dev, &null, 1 ) < 0)
1746 die( "write failed" );
1747 if (llseek( dev, 0, SEEK_SET ) != 0)
1748 die( "seek failed" );
1751 if (fstat (dev, &statbuf) < 0)
1752 die ("unable to stat %s");
1753 if (!S_ISBLK (statbuf.st_mode)) {
1754 statbuf.st_rdev = 0;
1759 * Ignore any 'full' fixed disk devices, if -I is not given.
1760 * On a MO-disk one doesn't need partitions. The filesytem can go
1761 * directly to the whole disk. Under other OSes this is known as
1762 * the 'superfloppy' format. As I don't know how to find out if
1763 * this is a MO disk I introduce a -I (ignore) switch. -Joey
1765 if (!ignore_full_disk && (
1766 (statbuf.st_rdev & 0xff3f) == 0x0300 || /* hda, hdb */
1767 (statbuf.st_rdev & 0xff0f) == 0x0800 || /* sd */
1768 (statbuf.st_rdev & 0xff3f) == 0x0d00 || /* xd */
1769 (statbuf.st_rdev & 0xff3f) == 0x1600 ) /* hdc, hdd */
1771 die ("Device partition expected, not making filesystem on entire device '%s' (use -I to override)");
1773 if (sector_size_set)
1775 if (ioctl(dev, BLKSSZGET, &min_sector_size) >= 0)
1776 if (sector_size < min_sector_size)
1778 sector_size = min_sector_size;
1779 fprintf(stderr, "Warning: sector size was set to %d (minimal for this device)\n", sector_size);
1784 if (ioctl(dev, BLKSSZGET, &min_sector_size) >= 0)
1786 sector_size = min_sector_size;
1787 sector_size_set = 1;
1791 if (sector_size > 4096)
1793 "Warning: sector size is set to %d > 4096, such filesystem will not propably mount\n",
1796 establish_params (statbuf.st_rdev,statbuf.st_size);
1797 /* Establish the media parameters */
1799 setup_tables (); /* Establish the file system tables */
1801 if (check) /* Determine any bad block locations and mark them */
1804 get_list_blocks (listfile);
1806 write_tables (); /* Write the file system tables away! */
1808 exit (0); /* Terminate with no errors! */