import source from 3.0.10
[external/dosfstools.git] / src / mkdosfs.c
1 /* mkdosfs.c - utility to create FAT/MS-DOS filesystems
2
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>
8
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.
13
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.
18
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/>.
21
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.
24 */
25
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.
29
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.
36
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
42    - FAT32 support */
43
44 /* Include the header files */
45
46 #include "version.h"
47
48 #include <fcntl.h>
49 #include <linux/hdreg.h>
50 #include <sys/mount.h>
51 #include <linux/fd.h>
52 #include <endian.h>
53 #include <mntent.h>
54 #include <signal.h>
55 #include <string.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <sys/ioctl.h>
59 #include <sys/stat.h>
60 #include <sys/time.h>
61 #include <sys/types.h>
62 #include <unistd.h>
63 #include <time.h>
64 #include <errno.h>
65
66 # include <asm/types.h>
67
68 #if __BYTE_ORDER == __BIG_ENDIAN
69
70 #include <asm/byteorder.h>
71 #ifdef __le16_to_cpu
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
78 #else
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) */
85
86 #else
87
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)
92
93 #endif /* __BIG_ENDIAN */
94
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 */
97 #define llseek lseek
98
99 /* Constant definitions */
100
101 #define TRUE 1                  /* Boolean constants */
102 #define FALSE 0
103
104 #define TEST_BUFFER_BLOCKS 16
105 #define HARD_SECTOR_SIZE   512
106 #define SECTORS_PER_BLOCK ( BLOCK_SIZE / HARD_SECTOR_SIZE )
107
108
109 /* Macro definitions */
110
111 /* Report a failure message and return a failure error code */
112
113 #define die( str ) fatal_error( "%s: " str "\n" )
114
115
116 /* Mark a cluster in the FAT as bad */
117
118 #define mark_sector_bad( sector ) mark_FAT_sector( sector, FAT_BAD )
119
120 /* Compute ceil(a/b) */
121
122 inline int
123 cdiv (int a, int b)
124 {
125   return (a + b - 1) / b;
126 }
127
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
130    need */
131
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 */
138
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" */
142
143 /* FAT values */
144 #define FAT_EOF      (atari_format ? 0x0fffffff : 0x0ffffff8)
145 #define FAT_BAD      0x0ffffff7
146
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 */
151
152 #define BOOT_SIGN 0xAA55        /* Boot sector magic number */
153
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)
160
161 #define FAT12_THRESHOLD 4085
162
163 #define OLDGEMDOS_MAX_SECTORS   32765
164 #define GEMDOS_MAX_SECTORS      65531
165 #define GEMDOS_MAX_SECTOR_SIZE  (16*1024)
166
167 #define BOOTCODE_SIZE           448
168 #define BOOTCODE_FAT32_SIZE     420
169
170 /* __attribute__ ((packed)) is used on all structures to make gcc ignore any
171  * alignments */
172
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));
181
182 struct msdos_boot_sector
183 {
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) */
199   union {
200     struct {
201       struct msdos_volume_info vi;
202       __u8      boot_code[BOOTCODE_SIZE];
203     } __attribute__ ((packed)) _oldfat;
204     struct {
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;
216   __u16         boot_sign;
217 } __attribute__ ((packed));
218 #define fat32   fstype._fat32
219 #define oldfat  fstype._oldfat
220
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. */
227   __u32         reserved2[4];
228 };
229
230 struct msdos_dir_entry
231   {
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));
243
244 /* The "boot code" we put into the filesystem... it writes a message and
245    tells the user to try again */
246
247 char dummy_boot_jump[3] = { 0xeb, 0x3c, 0x90 };
248
249 char dummy_boot_jump_m68k[2] = { 0x60, 0x1c };
250
251 #define MSG_OFFSET_OFFSET 3
252 char dummy_boot_code[BOOTCODE_SIZE] =
253   "\x0e"                        /* push cs */
254   "\x1f"                        /* pop ds */
255   "\xbe\x5b\x7c"                /* mov si, offset message_txt */
256                                 /* write_msg: */
257   "\xac"                        /* lodsb */
258   "\x22\xc0"                    /* and al, al */
259   "\x74\x0b"                    /* jz key_press */
260   "\x56"                        /* push si */
261   "\xb4\x0e"                    /* mov ah, 0eh */
262   "\xbb\x07\x00"                /* mov bx, 0007h */
263   "\xcd\x10"                    /* int 10h */
264   "\x5e"                        /* pop si */
265   "\xeb\xf0"                    /* jmp write_msg */
266                                 /* key_press: */
267   "\x32\xe4"                    /* xor ah, ah */
268   "\xcd\x16"                    /* int 16h */
269   "\xcd\x19"                    /* int 19h */
270   "\xeb\xfe"                    /* foo: jmp foo */
271                                 /* message_txt: */
272
273   "This is not a bootable disk.  Please insert a bootable floppy and\r\n"
274   "press any key to try again ... \r\n";
275
276 #define MESSAGE_OFFSET 29       /* Offset of message in above code */
277
278 /* Global variables - the root of all evil :-) - see these and weep! */
279
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 */
315
316 /* Function prototype definitions */
317
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);
331
332
333 /* The function implementations */
334
335 /* Handle the reporting of fatal errors.  Volatile to let gcc know that this doesn't return */
336
337 static void
338 fatal_error (const char *fmt_string)
339 {
340   fprintf (stderr, fmt_string, program_name, device_name);
341   exit (1);                     /* The error exit code is 1! */
342 }
343
344
345 /* Mark the specified cluster as having a particular value */
346
347 static void
348 mark_FAT_cluster (int cluster, unsigned int value)
349 {
350   switch( size_fat ) {
351     case 12:
352       value &= 0x0fff;
353       if (((cluster * 3) & 0x1) == 0)
354         {
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));
358         }
359       else
360         {
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);
363         }
364       break;
365
366     case 16:
367       value &= 0xffff;
368       fat[2 * cluster] = (unsigned char) (value & 0x00ff);
369       fat[(2 * cluster) + 1] = (unsigned char) (value >> 8);
370       break;
371
372     case 32:
373       value &= 0xfffffff;
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);
378       break;
379
380     default:
381       die("Bad FAT size (not 12, 16, or 32)");
382   }
383 }
384
385
386 /* Mark a specified sector as having a particular value in it's FAT entry */
387
388 static void
389 mark_FAT_sector (int sector, unsigned int value)
390 {
391   int cluster;
392
393   cluster = (sector - start_data_sector) / (int) (bs.cluster_size) /
394             (sector_size/HARD_SECTOR_SIZE);
395   if (cluster < 0)
396     die ("Invalid cluster number in mark_FAT_sector: probably bug!");
397
398   mark_FAT_cluster (cluster, value);
399 }
400
401
402 /* Perform a test on a block.  Return the number of blocks that could be read successfully */
403
404 static long
405 do_check (char *buffer, int try, off_t current_block)
406 {
407   long got;
408
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");
412
413   got = read (dev, buffer, try * BLOCK_SIZE);   /* Try reading! */
414   if (got < 0)
415     got = 0;
416
417   if (got & (BLOCK_SIZE - 1))
418     printf ("Unexpected values in do_check: probably bugs\n");
419   got /= BLOCK_SIZE;
420
421   return got;
422 }
423
424
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) */
427
428 static void
429 alarm_intr (int alnum)
430 {
431   if (currently_testing >= blocks)
432     return;
433
434   signal (SIGALRM, alarm_intr);
435   alarm (5);
436   if (!currently_testing)
437     return;
438
439   printf ("%lld... ", (unsigned long long)currently_testing);
440   fflush (stdout);
441 }
442
443
444 static void
445 check_blocks (void)
446 {
447   int try, got;
448   int i;
449   static char blkbuf[BLOCK_SIZE * TEST_BUFFER_BLOCKS];
450
451   if (verbose)
452     {
453       printf ("Searching for bad blocks ");
454       fflush (stdout);
455     }
456   currently_testing = 0;
457   if (verbose)
458     {
459       signal (SIGALRM, alarm_intr);
460       alarm (5);
461     }
462   try = TEST_BUFFER_BLOCKS;
463   while (currently_testing < blocks)
464     {
465       if (currently_testing + try > blocks)
466         try = blocks - currently_testing;
467       got = do_check (blkbuf, try, currently_testing);
468       currently_testing += got;
469       if (got == try)
470         {
471           try = TEST_BUFFER_BLOCKS;
472           continue;
473         }
474       else
475         try = 1;
476       if (currently_testing < start_data_block)
477         die ("bad blocks before data-area: cannot make fs");
478
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);
481       badblocks++;
482       currently_testing++;
483     }
484
485   if (verbose)
486     printf ("\n");
487
488   if (badblocks)
489     printf ("%d bad block%s\n", badblocks,
490             (badblocks > 1) ? "s" : "");
491 }
492
493
494 static void
495 get_list_blocks (char *filename)
496 {
497   int i;
498   FILE *listfile;
499   unsigned long blockno;
500
501   listfile = fopen (filename, "r");
502   if (listfile == (FILE *) NULL)
503     die ("Can't open file of bad blocks");
504
505   while (!feof (listfile))
506     {
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);
510       badblocks++;
511     }
512   fclose (listfile);
513
514   if (badblocks)
515     printf ("%d bad block%s\n", badblocks,
516             (badblocks > 1) ? "s" : "");
517 }
518
519
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 */
522
523 static int
524 valid_offset (int fd, loff_t offset)
525 {
526   char ch;
527
528   if (llseek (fd, offset, SEEK_SET) < 0)
529     return FALSE;
530   if (read (fd, &ch, 1) < 1)
531     return FALSE;
532   return TRUE;
533 }
534
535
536 /* Given a filename, look to see how many blocks of BLOCK_SIZE are present, returning the answer */
537
538 static unsigned long long
539 count_blocks (char *filename)
540 {
541   loff_t high, low;
542   int fd;
543
544   if ((fd = open (filename, O_RDONLY)) < 0)
545     {
546       perror (filename);
547       exit (1);
548     }
549
550   /* first try SEEK_END, which should work on most devices nowadays */
551   if ((low = llseek(fd, 0, SEEK_END)) <= 0) {
552       low = 0;
553       for (high = 1; valid_offset (fd, high); high *= 2)
554           low = high;
555       while (low < high - 1) {
556           const loff_t mid = (low + high) / 2;
557           if (valid_offset (fd, mid))
558               low = mid;
559           else
560               high = mid;
561       }
562       ++low;
563   }
564
565   close (fd);
566   return low / BLOCK_SIZE;
567 }
568
569
570 /* Check to see if the specified device is currently mounted - abort if it is */
571
572 static void
573 check_mount (char *device_name)
574 {
575   FILE *f;
576   struct mntent *mnt;
577
578   if ((f = setmntent (MOUNTED, "r")) == NULL)
579     return;
580   while ((mnt = getmntent (f)) != NULL)
581     if (strcmp (device_name, mnt->mnt_fsname) == 0)
582       die ("%s contains a mounted file system.");
583   endmntent (f);
584 }
585
586
587 /* Establish the geometry and media parameters for the device */
588
589 static void
590 establish_params (int device_num,int size)
591 {
592   long loop_size;
593   struct hd_geometry geometry;
594   struct floppy_struct param;
595   int def_root_dir_entries = 512;
596
597   if ((0 == device_num) || ((device_num & 0xff00) == 0x0200))
598     /* file image or floppy disk */
599     {
600       if (0 == device_num)
601         {
602           param.size = size/512;
603           switch(param.size)
604             {
605             case 720:
606               param.sect = 9 ;
607               param.head = 2;
608               break;
609             case 1440:
610               param.sect = 9;
611               param.head = 2;
612               break;
613             case 2400:
614               param.sect = 15;
615               param.head = 2;
616               break;
617             case 2880:
618               param.sect = 18;
619               param.head = 2;
620               break;
621             case 5760:
622               param.sect = 36;
623               param.head = 2;
624               break;
625             default:
626               /* fake values */
627               param.sect = 32;
628               param.head = 64;
629               break;
630             }
631
632         }
633       else      /* is a floppy diskette */
634         {
635           if (ioctl (dev, FDGETPRM, &param))    /*  Can we get the diskette geometry? */
636             die ("unable to get diskette geometry for '%s'");
637         }
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 */
641         {
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;
646           break;
647
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;
652           break;
653
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;
658           break;
659
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;
664           break;
665
666         case 2880:              /* 3.5", 2, 18, 80 - 1440K */
667         floppy_default:
668           bs.media = (char) 0xf0;
669           bs.cluster_size = (char)(atari_format ? 2 : 1);
670           def_root_dir_entries = 224;
671           break;
672
673         default:                /* Anything else */
674           if (0 == device_num)
675               goto def_hd_params;
676           else
677               goto floppy_default;
678         }
679     }
680   else if ((device_num & 0xff00) == 0x0700) /* This is a loop device */
681     {
682       if (ioctl (dev, BLKGETSIZE, &loop_size))
683         die ("unable to get loop device size");
684
685       switch (loop_size)  /* Assuming the loop device -> floppy later */
686         {
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;
693           break;
694
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;
701           break;
702
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;
709           break;
710
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;
718           break;
719
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;
726           break;
727
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);
733           goto def_hd_params;
734         }
735     }
736   else
737     /* Must be a hard disk then! */
738     {
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);
745       }
746       else {
747         bs.secs_track = CT_LE_W(geometry.sectors);      /* Set up the geometry information */
748         bs.heads = CT_LE_W(geometry.heads);
749       }
750     def_hd_params:
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");
754           size_fat = 32;
755       }
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
763            */
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 :
768                             sz_mb >     260 ?  8 :
769                                                1;
770       }
771       else {
772           /* FAT12 and FAT16: start at 4 sectors per cluster */
773           bs.cluster_size = (char) 4;
774       }
775     }
776
777   if (!root_dir_entries)
778     root_dir_entries = def_root_dir_entries;
779 }
780
781 /*
782  * If alignment is enabled, round the first argument up to the second; the
783  * latter must be a power of two.
784  */
785 static unsigned int
786 align_object (unsigned int sectors, unsigned int clustsize)
787 {
788   if (align_structures)
789     return (sectors + clustsize - 1) & ~(clustsize - 1);
790   else
791     return sectors;
792 }
793
794 /* Create the filesystem data tables */
795
796 static void
797 setup_tables (void)
798 {
799   unsigned num_sectors;
800   unsigned cluster_count = 0, fat_length;
801   struct tm *ctime;
802   struct msdos_volume_info *vi = (size_fat == 32 ? &bs.fat32.vi : &bs.oldfat.vi);
803
804   if (atari_format)
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 );
809   else
810     strcpy (bs.system_id, "mkdosfs");
811   if (sectors_per_cluster)
812     bs.cluster_size = (char) sectors_per_cluster;
813   if (size_fat == 32)
814     {
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;
818     }
819
820   if (atari_format) {
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);
824   }
825   else {
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);
830   }
831
832   if (!atari_format) {
833     memcpy(vi->volume_label, volume_name, 11);
834
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) -
840                        (char *)&bs) - 2;
841
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;
851     }
852     else {
853         memcpy(bs.oldfat.boot_code, dummy_boot_code, BOOTCODE_SIZE);
854     }
855     bs.boot_sign = CT_LE_W(BOOT_SIGN);
856   }
857   else {
858     memcpy(bs.boot_jump, dummy_boot_jump_m68k, 2);
859   }
860   if (verbose >= 2)
861     printf( "Boot jump code is %02x %02x\n",
862             bs.boot_jump[0], bs.boot_jump[1] );
863
864   if (!reserved_sectors)
865       reserved_sectors = (size_fat == 32) ? 32 : 1;
866   else {
867       if (size_fat == 32 && reserved_sectors < 2)
868           die("On FAT32 at least 2 reserved sectors are needed.");
869   }
870   bs.reserved = CT_LE_W(reserved_sectors);
871   if (verbose >= 2)
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);
876   else {
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 );
882   }
883
884   num_sectors = (long long)blocks*BLOCK_SIZE/sector_size;
885   if (!atari_format) {
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;
891     int maxclustsize;
892     unsigned root_dir_sectors = cdiv(root_dir_entries*32, sector_size);
893
894     /*
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.
897      */
898     if (num_sectors <= 8192) {
899       if (align_structures && verbose >= 2)
900         printf ("Disabling alignment due to tiny filesystem\n");
901
902       align_structures = FALSE;
903     }
904
905     if (sectors_per_cluster)
906       bs.cluster_size = maxclustsize = sectors_per_cluster;
907     else
908       /* An initial guess for bs.cluster_size should already be set */
909       maxclustsize = 128;
910
911     do {
912       fatdata32 = num_sectors
913         - align_object(reserved_sectors, bs.cluster_size);
914       fatdata1216 = fatdata32
915         - align_object(root_dir_sectors, bs.cluster_size);
916
917       if (verbose >= 2)
918         printf( "Trying with %d sectors/cluster:\n", bs.cluster_size );
919
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;
933       if (verbose >= 2)
934         printf( "FAT12: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n",
935                 clust12, fatlength12, maxclust12, MAX_CLUST_12 );
936       if (clust12 > maxclust12-2) {
937         clust12 = 0;
938         if (verbose >= 2)
939           printf( "FAT12: too much clusters\n" );
940       }
941
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;
953       if (verbose >= 2)
954         printf( "FAT16: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n",
955                 clust16, fatlength16, maxclust16, MAX_CLUST_16 );
956       if (clust16 > maxclust16-2) {
957         if (verbose >= 2)
958           printf( "FAT16: too much clusters\n" );
959         clust16 = 0;
960       }
961       /* The < 4078 avoids that the filesystem will be misdetected as having a
962        * 12 bit FAT. */
963       if (clust16 < FAT12_THRESHOLD && !(size_fat_by_user && size_fat == 16)) {
964         if (verbose >= 2)
965           printf( clust16 < FAT12_THRESHOLD ?
966                   "FAT16: would be misdetected as FAT12\n" :
967                   "FAT16: too much clusters\n" );
968         clust16 = 0;
969       }
970
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)) {
983        clust32 = 0;
984        if (verbose >= 2)
985          printf( "FAT32: not enough clusters (%d)\n", MIN_CLUST_32);
986       }
987       if (verbose >= 2)
988         printf( "FAT32: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n",
989                 clust32, fatlength32, maxclust32, MAX_CLUST_32 );
990       if (clust32 > maxclust32) {
991         clust32 = 0;
992         if (verbose >= 2)
993           printf( "FAT32: too much clusters\n" );
994       }
995
996       if ((clust12 && (size_fat == 0 || size_fat == 12)) ||
997           (clust16 && (size_fat == 0 || size_fat == 16)) ||
998           (clust32 && size_fat == 32))
999         break;
1000
1001       bs.cluster_size <<= 1;
1002     } while (bs.cluster_size && bs.cluster_size <= maxclustsize);
1003
1004     /* Use the optimal FAT size if not specified;
1005      * FAT32 is (not yet) choosen automatically */
1006     if (!size_fat) {
1007         size_fat = (clust16 > clust12) ? 16 : 12;
1008         if (verbose >= 2)
1009           printf( "Choosing %d bits for FAT\n", size_fat );
1010     }
1011
1012     switch (size_fat) {
1013       case 12:
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);
1018         break;
1019
1020       case 16:
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" );
1027             }
1028             else {
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." );
1037             }
1038         }
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);
1043         break;
1044
1045       case 32:
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;
1054         break;
1055
1056       default:
1057         die("FAT not 12, 16 or 32 bits");
1058     }
1059
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);
1063
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);
1068     }
1069   }
1070   else {
1071     unsigned clusters, maxclust, fatdata;
1072
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
1076      * size.
1077      */
1078     if (!size_fat)
1079       size_fat = (num_sectors == 1440 || num_sectors == 2400 ||
1080                   num_sectors == 2880 || num_sectors == 5760) ? 12 : 16;
1081     if (verbose >= 2)
1082       printf( "Choosing %d bits for FAT\n", size_fat );
1083
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.
1087      */
1088     bs.cluster_size = sectors_per_cluster ? sectors_per_cluster : 2;
1089     if (!sector_size_set) {
1090       while( num_sectors > GEMDOS_MAX_SECTORS ) {
1091         num_sectors >>= 1;
1092         sector_size <<= 1;
1093       }
1094     }
1095     if (verbose >= 2)
1096       printf( "Sector size must be %d to have less than %d log. sectors\n",
1097               sector_size, GEMDOS_MAX_SECTORS );
1098
1099     /* Check if there are enough FAT indices for how much clusters we have */
1100     do {
1101       fatdata = num_sectors - cdiv (root_dir_entries * 32, sector_size) -
1102                 reserved_sectors;
1103       /* The factor 2 below avoids cut-off errors for nr_fats == 1 and
1104        * size_fat == 12
1105        * The "2*nr_fats*size_fat/8" is for the reserved first two FAT entries
1106        */
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;
1115       if (verbose >= 2)
1116         printf( "ss=%d: #clu=%d, fat_len=%d, maxclu=%d\n",
1117                 sector_size, clusters, fat_length, maxclust );
1118
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)
1123         break;
1124       if (verbose >= 2)
1125         printf( clusters > maxclust-2 ?
1126                 "Too many clusters\n" : "FAT too big\n" );
1127
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." );
1132       num_sectors >>= 1;
1133       sector_size <<= 1;
1134     } while( sector_size <= GEMDOS_MAX_SECTOR_SIZE );
1135
1136     if (sector_size > GEMDOS_MAX_SECTOR_SIZE)
1137       die( "Would need a sector size > 16k, which GEMDOS can't work with");
1138
1139     cluster_count = clusters;
1140     if (size_fat != 32)
1141         bs.fat_length = CT_LE_W(fat_length);
1142     else {
1143         bs.fat_length = 0;
1144         bs.fat32.fat32_length = CT_LE_L(fat_length);
1145     }
1146   }
1147
1148   bs.sector_size[0] = (char) (sector_size & 0x00ff);
1149   bs.sector_size[1] = (char) ((sector_size & 0xff00) >> 8);
1150
1151   bs.dir_entries[0] = (char) (root_dir_entries & 0x00ff);
1152   bs.dir_entries[1] = (char) ((root_dir_entries & 0xff00) >> 8);
1153
1154   if (size_fat == 32)
1155     {
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);
1162       if (!backup_boot)
1163         backup_boot = (reserved_sectors >= 7) ? 6 :
1164                       (reserved_sectors >= 2) ? reserved_sectors-1 : 0;
1165       else
1166         {
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");
1171         }
1172       if (verbose >= 2)
1173         printf( "Using sector %d as backup boot sector (0 = none)\n",
1174                 backup_boot );
1175       bs.fat32.backup_boot = CT_LE_W(backup_boot);
1176       memset( &bs.fat32.reserved2, 0, sizeof(bs.fat32.reserved2) );
1177     }
1178
1179   if (atari_format) {
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 "
1185                   "or higher.\n" );
1186   }
1187   if (num_sectors >= 65536)
1188     {
1189       bs.sectors[0] = (char) 0;
1190       bs.sectors[1] = (char) 0;
1191       bs.total_sect = CT_LE_L(num_sectors);
1192     }
1193   else
1194     {
1195       bs.sectors[0] = (char) (num_sectors & 0x00ff);
1196       bs.sectors[1] = (char) ((num_sectors & 0xff00) >> 8);
1197       if (!atari_format)
1198           bs.total_sect = CT_LE_L(0);
1199     }
1200
1201   if (!atari_format)
1202     vi->ext_boot_sign = MSDOS_EXT_SIGN;
1203
1204   if (!cluster_count)
1205     {
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");
1208       else
1209         die ("Attempting to create a too large file system");
1210     }
1211
1212
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) /
1217                      SECTORS_PER_BLOCK;
1218
1219   if (blocks < start_data_block + 32)   /* Arbitrary undersize file system! */
1220     die ("Too few blocks for viable file system");
1221
1222   if (verbose)
1223     {
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",
1238               reserved_sectors,
1239               (reserved_sectors != 1) ? "s" : "");
1240
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);
1248       }
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);
1253       else
1254         printf("no volume label.\n");
1255     }
1256
1257   /* Make the file allocation tables! */
1258
1259   if (malloc_entire_fat)
1260     alloced_fat_length = fat_length;
1261   else
1262     alloced_fat_length = 1;
1263
1264   if ((fat = (unsigned char *) malloc (alloced_fat_length * sector_size)) == NULL)
1265     die ("unable to allocate space for FAT image in memory");
1266
1267   memset( fat, 0, alloced_fat_length * sector_size );
1268
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);
1275   }
1276
1277   /* Make the root directory entries */
1278
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)
1284     {
1285       free (fat);               /* Tidy up before we die! */
1286       die ("unable to allocate space for root directory in memory");
1287     }
1288
1289   memset(root_dir, 0, size_root_dir);
1290   if ( memcmp(volume_name, "           ", 11) )
1291     {
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)));
1302       de->ctime_ms = 0;
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);
1309     }
1310
1311   if (size_fat == 32) {
1312     /* For FAT32, create an info sector */
1313     struct fat32_fsinfo *info;
1314
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);
1320
1321     /* Info sector magic */
1322     info_sector[0] = 'R';
1323     info_sector[1] = 'R';
1324     info_sector[2] = 'a';
1325     info_sector[3] = 'A';
1326
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);
1332
1333     /* Info sector also must have boot sign */
1334     *(__u16 *)(info_sector + 0x1fe) = CT_LE_W(BOOT_SIGN);
1335   }
1336
1337   if (!(blank_sector = malloc( sector_size )))
1338       die( "Out of memory" );
1339   memset(blank_sector, 0, sector_size);
1340 }
1341
1342
1343 /* Write the new filesystem's data tables to wherever they're going to end up! */
1344
1345 #define error(str)                              \
1346   do {                                          \
1347     free (fat);                                 \
1348     if (info_sector) free (info_sector);        \
1349     free (root_dir);                            \
1350     die (str);                                  \
1351   } while(0)
1352
1353 #define seekto(pos,errstr)                                              \
1354   do {                                                                  \
1355     loff_t __pos = (pos);                                               \
1356     if (llseek (dev, __pos, SEEK_SET) != __pos)                         \
1357         error ("seek to " errstr " failed whilst writing tables");      \
1358   } while(0)
1359
1360 #define writebuf(buf,size,errstr)                       \
1361   do {                                                  \
1362     int __size = (size);                                \
1363     if (write (dev, buf, __size) != __size)             \
1364         error ("failed whilst writing " errstr);        \
1365   } while(0)
1366
1367
1368 static void
1369 write_tables (void)
1370 {
1371   int x;
1372   int fat_length;
1373
1374   fat_length = (size_fat == 32) ?
1375                CF_LE_L(bs.fat32.fat32_length) : CF_LE_W(bs.fat_length);
1376
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 */
1385   if (size_fat == 32)
1386     {
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)
1390         {
1391           seekto( backup_boot*sector_size, "backup boot sector" );
1392           writebuf( (char *) &bs, sizeof (struct msdos_boot_sector),
1393                     "backup boot sector" );
1394         }
1395     }
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++) {
1399     int y;
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" );
1404   }
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" );
1408
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 */
1413 }
1414
1415
1416 /* Report the command usage and return a failure error code */
1417
1418 void
1419 usage (void)
1420 {
1421   fatal_error("\
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");
1427 }
1428
1429 /*
1430  * ++roman: On m68k, check if this is an Atari; if yes, turn on Atari variant
1431  * of MS-DOS filesystem by default.
1432  */
1433 static void check_atari( void )
1434 {
1435 #ifdef __mc68000__
1436     FILE *f;
1437     char line[128], *p;
1438
1439     if (!(f = fopen( "/proc/hardware", "r" ))) {
1440         perror( "/proc/hardware" );
1441         return;
1442     }
1443
1444     while( fgets( line, sizeof(line), f ) ) {
1445         if (strncmp( line, "Model:", 6 ) == 0) {
1446             p = line + 6;
1447             p += strspn( p, " \t" );
1448             if (strncmp( p, "Atari ", 6 ) == 0)
1449                 atari_format = 1;
1450             break;
1451         }
1452     }
1453     fclose( f );
1454 #endif
1455 }
1456
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! */
1459
1460 int
1461 main (int argc, char **argv)
1462 {
1463   int c;
1464   char *tmp;
1465   char *listfile = NULL;
1466   FILE *msgfile;
1467   struct stat statbuf;
1468   int i = 0, pos, ch;
1469   int create = 0;
1470   unsigned long long cblocks = 0;
1471   int min_sector_size;
1472
1473   if (argc && *argv) {          /* What's the program name? */
1474     char *p;
1475     program_name = *argv;
1476     if ((p = strrchr( program_name, '/' )))
1477         program_name = p+1;
1478   }
1479
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 */
1483   check_atari();
1484
1485   printf ("%s " VERSION " (" VERSION_DATE ")\n",
1486            program_name);
1487
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 */
1490     switch (c)
1491       {
1492       case 'A':         /* toggle Atari format */
1493         atari_format = !atari_format;
1494         break;
1495
1496       case 'a':         /* a : skip alignment */
1497         align_structures = FALSE;
1498         break;
1499
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)
1503           {
1504             printf ("Bad location for backup boot sector : %s\n", optarg);
1505             usage ();
1506           }
1507         break;
1508
1509       case 'c':         /* c : Check FS as we build it */
1510         check = TRUE;
1511         malloc_entire_fat = TRUE;       /* Need to be able to mark clusters bad */
1512         break;
1513
1514       case 'C':         /* C : Create a new file */
1515         create = TRUE;
1516         break;
1517
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)
1521           {
1522             printf ("Bad number of FATs : %s\n", optarg);
1523             usage ();
1524           }
1525         break;
1526
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))
1530           {
1531             printf ("Bad FAT type : %s\n", optarg);
1532             usage ();
1533           }
1534         size_fat_by_user = 1;
1535         break;
1536
1537       case 'h':        /* h : number of hidden sectors */
1538         hidden_sectors = (int) strtol (optarg, &tmp, 0);
1539         if ( *tmp || hidden_sectors < 0 )
1540           {
1541             printf("Bad number of hidden sectors : %s\n", optarg);
1542             usage ();
1543           }
1544         break;
1545
1546       case 'I':
1547         ignore_full_disk = 1;
1548         break;
1549
1550       case 'i':         /* i : specify volume ID */
1551         volume_id = strtoul(optarg, &tmp, 16);
1552         if ( *tmp )
1553           {
1554             printf("Volume ID must be a hexadecimal number\n");
1555             usage();
1556           }
1557         break;
1558
1559       case 'l':         /* l : Bad block filename */
1560         listfile = optarg;
1561         malloc_entire_fat = TRUE;       /* Need to be able to mark clusters bad */
1562         break;
1563
1564       case 'm':         /* m : Set boot message */
1565         if ( strcmp(optarg, "-") )
1566           {
1567             msgfile = fopen(optarg, "r");
1568             if ( !msgfile )
1569               perror(optarg);
1570           }
1571         else
1572           msgfile = stdin;
1573
1574         if ( msgfile )
1575           {
1576             /* The boot code ends at offset 448 and needs a null terminator */
1577             i = MESSAGE_OFFSET;
1578             pos = 0;            /* We are at beginning of line */
1579             do
1580               {
1581                 ch = getc(msgfile);
1582                 switch (ch)
1583                   {
1584                   case '\r':    /* Ignore CRs */
1585                   case '\0':    /* and nulls */
1586                     break;
1587
1588                   case '\n':    /* LF -> CR+LF if necessary */
1589                     if ( pos )  /* If not at beginning of line */
1590                       {
1591                         dummy_boot_code[i++] = '\r';
1592                         pos = 0;
1593                       }
1594                     dummy_boot_code[i++] = '\n';
1595                     break;
1596
1597                   case '\t':    /* Expand tabs */
1598                     do
1599                       {
1600                         dummy_boot_code[i++] = ' ';
1601                         pos++;
1602                       }
1603                     while ( pos % 8 && i < BOOTCODE_SIZE-1 );
1604                     break;
1605
1606                   case EOF:
1607                     dummy_boot_code[i++] = '\0'; /* Null terminator */
1608                     break;
1609
1610                   default:
1611                     dummy_boot_code[i++] = ch; /* Store character */
1612                     pos++;      /* Advance position */
1613                     break;
1614                   }
1615               }
1616             while ( ch != EOF && i < BOOTCODE_SIZE-1 );
1617
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 */
1622
1623             if ( ch != EOF )
1624               printf ("Warning: message too long; truncated\n");
1625
1626             if ( msgfile != stdin )
1627               fclose(msgfile);
1628           }
1629         break;
1630
1631       case 'n':         /* n : Volume name */
1632         sprintf(volume_name, "%-11.11s", optarg);
1633         break;
1634
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)
1638           {
1639             printf ("Bad number of root directory entries : %s\n", optarg);
1640             usage ();
1641           }
1642         break;
1643
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)
1647           {
1648             printf ("Bad number of reserved sectors : %s\n", optarg);
1649             usage ();
1650           }
1651         break;
1652
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))
1659           {
1660             printf ("Bad number of sectors per cluster : %s\n", optarg);
1661             usage ();
1662           }
1663         break;
1664
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))
1671           {
1672             printf ("Bad logical sector size : %s\n", optarg);
1673             usage ();
1674           }
1675         sector_size_set = 1;
1676         break;
1677
1678       case 'v':         /* v : Verbose execution */
1679         ++verbose;
1680         break;
1681
1682       default:
1683         printf( "Unknown option: %c\n", c );
1684         usage ();
1685       }
1686   if (optind < argc)
1687     {
1688       device_name = argv[optind];  /* Determine the number of blocks in the FS */
1689
1690       if (!device_name) {
1691           printf("No device specified.\n");
1692           usage();
1693       }
1694
1695       if (!create)
1696          cblocks = count_blocks (device_name); /*  Have a look and see! */
1697     }
1698   if (optind == argc - 2)       /*  Either check the user specified number */
1699     {
1700       blocks = strtoull (argv[optind + 1], &tmp, 0);
1701       if (!create && blocks != cblocks)
1702         {
1703           fprintf (stderr, "Warning: block count mismatch: ");
1704           fprintf (stderr, "found %llu but assuming %llu.\n",cblocks,blocks);
1705         }
1706     }
1707   else if (optind == argc - 1)  /*  Or use value found */
1708     {
1709       if (create)
1710         die( "Need intended size with -C." );
1711       blocks = cblocks;
1712       tmp = "";
1713     }
1714   else
1715     {
1716       fprintf (stderr, "No device specified!\n");
1717       usage ();
1718     }
1719   if (*tmp)
1720     {
1721       printf ("Bad block count : %s\n", argv[optind + 1]);
1722       usage ();
1723     }
1724
1725   if (check && listfile)        /* Auto and specified bad block handling are mutually */
1726     die ("-c and -l are incompatible");         /* exclusive of each other! */
1727
1728   if (!create) {
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? */
1731     if (dev < 0)
1732       die ("unable to open %s");
1733   }
1734   else {
1735       loff_t offset = blocks*BLOCK_SIZE - 1;
1736       char null = 0;
1737       /* create the file */
1738       dev = open( device_name, O_EXCL|O_RDWR|O_CREAT|O_TRUNC, 0666 );
1739       if (dev < 0)
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" );
1749   }
1750
1751   if (fstat (dev, &statbuf) < 0)
1752     die ("unable to stat %s");
1753   if (!S_ISBLK (statbuf.st_mode)) {
1754     statbuf.st_rdev = 0;
1755     check = 0;
1756   }
1757   else
1758     /*
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
1764      */
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 */
1770         )
1771       die ("Device partition expected, not making filesystem on entire device '%s' (use -I to override)");
1772
1773   if (sector_size_set)
1774     {
1775       if (ioctl(dev, BLKSSZGET, &min_sector_size) >= 0)
1776           if (sector_size < min_sector_size)
1777             {
1778               sector_size = min_sector_size;
1779               fprintf(stderr, "Warning: sector size was set to %d (minimal for this device)\n", sector_size);
1780             }
1781     }
1782   else
1783     {
1784       if (ioctl(dev, BLKSSZGET, &min_sector_size) >= 0)
1785         {
1786           sector_size = min_sector_size;
1787           sector_size_set = 1;
1788         }
1789     }
1790
1791   if (sector_size > 4096)
1792     fprintf(stderr,
1793             "Warning: sector size is set to %d > 4096, such filesystem will not propably mount\n",
1794             sector_size);
1795
1796   establish_params (statbuf.st_rdev,statbuf.st_size);
1797                                 /* Establish the media parameters */
1798
1799   setup_tables ();              /* Establish the file system tables */
1800
1801   if (check)                    /* Determine any bad block locations and mark them */
1802     check_blocks ();
1803   else if (listfile)
1804     get_list_blocks (listfile);
1805
1806   write_tables ();              /* Write the file system tables away! */
1807
1808   exit (0);                     /* Terminate with no errors! */
1809 }