"Fossies" - the Fresh Open Source Software Archive

Member "dosfstools-4.2/src/mkfs.fat.c" (31 Jan 2021, 67883 Bytes) of package /linux/misc/dosfstools-4.2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "mkfs.fat.c": 4.1_vs_4.2.

    1 /* mkfs.fat.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    Copyright (C) 2008-2014 Daniel Baumann <mail@daniel-baumann.ch>
    9    Copyright (C) 2015-2016 Andreas Bombe <aeb@debian.org>
   10    Copyright (C) 2018 Pali Rohár <pali.rohar@gmail.com>
   11 
   12    This program is free software: you can redistribute it and/or modify
   13    it under the terms of the GNU General Public License as published by
   14    the Free Software Foundation, either version 3 of the License, or
   15    (at your option) any later version.
   16 
   17    This program is distributed in the hope that it will be useful,
   18    but WITHOUT ANY WARRANTY; without even the implied warranty of
   19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   20    GNU General Public License for more details.
   21 
   22    You should have received a copy of the GNU General Public License
   23    along with this program. If not, see <http://www.gnu.org/licenses/>.
   24 
   25    The complete text of the GNU General Public License
   26    can be found in /usr/share/common-licenses/GPL-3 file.
   27 */
   28 
   29 /* Description: Utility to allow an MS-DOS filesystem to be created
   30    under Linux.  A lot of the basic structure of this program has been
   31    borrowed from Remy Card's "mke2fs" code.
   32 
   33    As far as possible the aim here is to make the "mkfs.fat" command
   34    look almost identical to the other Linux filesystem make utilties,
   35    eg bad blocks are still specified as blocks, not sectors, but when
   36    it comes down to it, DOS is tied to the idea of a sector (512 bytes
   37    as a rule), and not the block.  For example the boot block does not
   38    occupy a full cluster.
   39 
   40    Fixes/additions May 1998 by Roman Hodek
   41    <Roman.Hodek@informatik.uni-erlangen.de>:
   42    - Atari format support
   43    - New options -A, -S, -C
   44    - Support for filesystems > 2GB
   45    - FAT32 support */
   46 
   47 /* Include the header files */
   48 
   49 #include "version.h"
   50 
   51 #include <fcntl.h>
   52 #include <signal.h>
   53 #include <string.h>
   54 #include <stdio.h>
   55 #include <stdlib.h>
   56 #include <limits.h>
   57 #include <sys/types.h>
   58 #include <sys/stat.h>
   59 #include <sys/time.h>
   60 #include <unistd.h>
   61 #include <time.h>
   62 #include <errno.h>
   63 #include <ctype.h>
   64 #include <stdint.h>
   65 #include <getopt.h>
   66 #include "endian_compat.h"
   67 
   68 #include "common.h"
   69 #include "msdos_fs.h"
   70 #include "device_info.h"
   71 #include "charconv.h"
   72 
   73 
   74 /* Constant definitions */
   75 
   76 #define TRUE 1          /* Boolean constants */
   77 #define FALSE 0
   78 
   79 #define TEST_BUFFER_BLOCKS 16
   80 #define BLOCK_SIZE         1024
   81 #define HARD_SECTOR_SIZE   512
   82 #define SECTORS_PER_BLOCK ( BLOCK_SIZE / HARD_SECTOR_SIZE )
   83 
   84 #define NO_NAME "NO NAME    "
   85 
   86 /* Macro definitions */
   87 
   88 /* Mark a cluster in the FAT as bad */
   89 
   90 #define mark_sector_bad( sector ) mark_FAT_sector( sector, FAT_BAD )
   91 
   92 /* Compute ceil(a/b) */
   93 
   94 static inline int cdiv(int a, int b)
   95 {
   96     return (a + b - 1) / b;
   97 }
   98 
   99 /* FAT values */
  100 #define FAT_EOF      (atari_format ? 0x0fffffff : 0x0ffffff8)
  101 #define FAT_BAD      0x0ffffff7
  102 
  103 #define MSDOS_EXT_SIGN 0x29 /* extended boot sector signature */
  104 #define MSDOS_FAT12_SIGN "FAT12   " /* FAT12 filesystem signature */
  105 #define MSDOS_FAT16_SIGN "FAT16   " /* FAT16 filesystem signature */
  106 #define MSDOS_FAT32_SIGN "FAT32   " /* FAT32 filesystem signature */
  107 
  108 #define BOOT_SIGN 0xAA55    /* Boot sector magic number */
  109 
  110 /* According to Microsoft FAT specification (fatgen103.doc) disk with
  111  * 4085 clusters (or more) is FAT16, but Microsoft Windows FAT driver
  112  * fastfat.sys detects disk with less then 4087 clusters as FAT12.
  113  * Linux FAT drivers msdos.ko and vfat.ko detect disk with at least
  114  * 4085 clusters as FAT16, therefore for compatibility reasons with
  115  * both systems disallow formatting disks to 4085 or 4086 clusters. */
  116 #define MAX_CLUST_12    4084
  117 #define MIN_CLUST_16    4087
  118 
  119 /* According to Microsoft FAT specification (fatgen103.doc) disk with
  120  * 65525 clusters (or more) is FAT32, but Microsoft Windows FAT driver
  121  * fastfat.sys, Linux FAT drivers msdos.ko and vfat.ko detect disk as
  122  * FAT32 when Sectors Per FAT (fat_length) is set to zero. And not by
  123  * number of clusters. Still there is cluster upper limit for FAT16. */
  124 #define MAX_CLUST_16    65524
  125 #define MIN_CLUST_32    65525
  126 
  127 /* M$ says the high 4 bits of a FAT32 FAT entry are reserved and don't belong
  128  * to the cluster number. So the max. cluster# is based on 2^28 */
  129 #define MAX_CLUST_32    268435446
  130 
  131 #define OLDGEMDOS_MAX_SECTORS   32765
  132 #define GEMDOS_MAX_SECTORS  65531
  133 #define GEMDOS_MAX_SECTOR_SIZE  (16*1024)
  134 
  135 #define BOOTCODE_SIZE       448
  136 #define BOOTCODE_FAT32_SIZE 420
  137 
  138 /* __attribute__ ((packed)) is used on all structures to make gcc ignore any
  139  * alignments */
  140 
  141 struct msdos_volume_info {
  142     uint8_t drive_number;   /* BIOS drive number */
  143     uint8_t boot_flags;     /* bit 0: dirty, bit 1: need surface test */
  144     uint8_t ext_boot_sign;  /* 0x29 if fields below exist (DOS 3.3+) */
  145     uint8_t volume_id[4];   /* Volume ID number */
  146     uint8_t volume_label[11];   /* Volume label */
  147     uint8_t fs_type[8];     /* Typically FAT12 or FAT16 */
  148 } __attribute__ ((packed));
  149 
  150 struct msdos_boot_sector {
  151     uint8_t boot_jump[3];   /* Boot strap short or near jump */
  152     uint8_t system_id[8];   /* Name - can be used to special case
  153                    partition manager volumes */
  154     uint8_t sector_size[2]; /* bytes per logical sector */
  155     uint8_t cluster_size;   /* sectors/cluster */
  156     uint16_t reserved;      /* reserved sectors */
  157     uint8_t fats;       /* number of FATs */
  158     uint8_t dir_entries[2]; /* root directory entries */
  159     uint8_t sectors[2];     /* number of sectors */
  160     uint8_t media;      /* media code (unused) */
  161     uint16_t fat_length;    /* sectors/FAT */
  162     uint16_t secs_track;    /* sectors per track */
  163     uint16_t heads;     /* number of heads */
  164     uint32_t hidden;        /* hidden sectors (unused) */
  165     uint32_t total_sect;    /* number of sectors (if sectors == 0) */
  166     union {
  167     struct {
  168         struct msdos_volume_info vi;
  169         uint8_t boot_code[BOOTCODE_SIZE];
  170     } __attribute__ ((packed)) _oldfat;
  171     struct {
  172         uint32_t fat32_length;  /* sectors/FAT */
  173         uint16_t flags;     /* bit 8: fat mirroring, low 4: active fat */
  174         uint8_t version[2];     /* major, minor filesystem version */
  175         uint32_t root_cluster;  /* first cluster in root directory */
  176         uint16_t info_sector;   /* filesystem info sector */
  177         uint16_t backup_boot;   /* backup boot sector */
  178         uint16_t reserved2[6];  /* Unused */
  179         struct msdos_volume_info vi;
  180         uint8_t boot_code[BOOTCODE_FAT32_SIZE];
  181     } __attribute__ ((packed)) _fat32;
  182     } __attribute__ ((packed)) fstype;
  183     uint16_t boot_sign;
  184 } __attribute__ ((packed));
  185 #define fat32   fstype._fat32
  186 #define oldfat  fstype._oldfat
  187 
  188 struct fat32_fsinfo {
  189     uint32_t reserved1;     /* Nothing as far as I can tell */
  190     uint32_t signature;     /* 0x61417272L */
  191     uint32_t free_clusters; /* Free cluster count.  -1 if unknown */
  192     uint32_t next_cluster;  /* Most recently allocated cluster.
  193                  * Unused under Linux. */
  194     uint32_t reserved2[4];
  195 } __attribute__ ((packed));
  196 
  197 /* The "boot code" we put into the filesystem... it writes a message and
  198    tells the user to try again. This "boot code" is in the public domain. */
  199 
  200 unsigned char dummy_boot_jump[3] = { 0xeb, 0x3c, 0x90 };
  201 
  202 unsigned char dummy_boot_jump_m68k[2] = { 0x60, 0x1c };
  203 
  204 #define MSG_OFFSET_OFFSET 3
  205 char dummy_boot_code[BOOTCODE_SIZE] = "\x0e"    /* push cs */
  206     "\x1f"          /* pop ds */
  207     "\xbe\x5b\x7c"      /* mov si, offset message_txt */
  208     /* write_msg: */
  209     "\xac"          /* lodsb */
  210     "\x22\xc0"          /* and al, al */
  211     "\x74\x0b"          /* jz key_press */
  212     "\x56"          /* push si */
  213     "\xb4\x0e"          /* mov ah, 0eh */
  214     "\xbb\x07\x00"      /* mov bx, 0007h */
  215     "\xcd\x10"          /* int 10h */
  216     "\x5e"          /* pop si */
  217     "\xeb\xf0"          /* jmp write_msg */
  218     /* key_press: */
  219     "\x32\xe4"          /* xor ah, ah */
  220     "\xcd\x16"          /* int 16h */
  221     "\xcd\x19"          /* int 19h */
  222     "\xeb\xfe"          /* foo: jmp foo */
  223     /* message_txt: */
  224     "This is not a bootable disk.  Please insert a bootable floppy and\r\n"
  225     "press any key to try again ... \r\n";
  226 
  227 #define MESSAGE_OFFSET 29   /* Offset of message in above code */
  228 
  229 static char initial_volume_name[] = NO_NAME; /* Initial volume name, make sure that is writable */
  230 
  231 /* Global variables - the root of all evil :-) - see these and weep! */
  232 
  233 static char *device_name = NULL;    /* Name of the device on which to create the filesystem */
  234 static int check = FALSE;   /* Default to no readablity checking */
  235 static int verbose = 0;     /* Default to verbose mode off */
  236 static long volume_id;      /* Volume ID number */
  237 static time_t create_time = -1; /* Creation time */
  238 static char *volume_name = initial_volume_name; /* Volume name */
  239 static unsigned long long blocks;   /* Number of blocks in filesystem */
  240 static unsigned sector_size = 512;  /* Size of a logical sector */
  241 static int sector_size_set = 0; /* User selected sector size */
  242 static int backup_boot = 0; /* Sector# of backup boot sector */
  243 static int backup_boot_set = 0; /* User selected backup boot sector */
  244 static int info_sector = 0; /* Sector# of FAT32 info sector */
  245 static int reserved_sectors = 0;    /* Number of reserved sectors */
  246 static int badblocks = 0;   /* Number of bad blocks in the filesystem */
  247 static int nr_fats = 2;     /* Default number of FATs to produce */
  248 static int size_fat = 0;    /* Size in bits of FAT entries */
  249 static int size_fat_by_user = 0;    /* 1 if FAT size user selected */
  250 static int dev = -1;        /* FS block device file handle */
  251 static off_t part_sector = 0; /* partition offset in sector */
  252 static int ignore_safety_checks = 0;    /* Ignore safety checks */
  253 static off_t currently_testing = 0; /* Block currently being tested (if autodetect bad blocks) */
  254 static struct msdos_boot_sector bs; /* Boot sector data */
  255 static int start_data_sector;   /* Sector number for the start of the data area */
  256 static int start_data_block;    /* Block number for the start of the data area */
  257 static unsigned char *fat;  /* File allocation table */
  258 static unsigned alloced_fat_length; /* # of FAT sectors we can keep in memory */
  259 static unsigned fat_entries;        /* total entries in FAT table (including reserved) */
  260 static unsigned char *info_sector_buffer;   /* FAT32 info sector */
  261 static struct msdos_dir_entry *root_dir;    /* Root directory */
  262 static int size_root_dir;   /* Size of the root directory in bytes */
  263 static uint32_t num_sectors;        /* Total number of sectors in device */
  264 static int sectors_per_cluster = 0; /* Number of sectors per disk cluster */
  265 static int root_dir_entries = 0;    /* Number of root directory entries */
  266 static int root_dir_entries_set = 0;    /* User selected root directory size */
  267 static char *blank_sector;  /* Blank sector - all zeros */
  268 static unsigned hidden_sectors = 0; /* Number of hidden sectors */
  269 static int hidden_sectors_by_user = 0;  /* -h option invoked */
  270 static int drive_number_option = 0; /* drive number */
  271 static int drive_number_by_user = 0;    /* drive number option invoked */
  272 static int fat_media_byte = 0;  /* media byte in header and starting FAT */
  273 static int malloc_entire_fat = FALSE;   /* Whether we should malloc() the entire FAT or not */
  274 static int align_structures = TRUE; /* Whether to enforce alignment */
  275 static int orphaned_sectors = 0;    /* Sectors that exist in the last block of filesystem */
  276 static int invariant = 0;       /* Whether to set normally randomized or
  277                        current time based values to
  278                        constants */
  279 static int fill_mbr_partition = -1; /* Whether to fill MBR partition table or not */
  280 
  281 /* Function prototype definitions */
  282 
  283 static void mark_FAT_cluster(int cluster, unsigned int value);
  284 static void mark_FAT_sector(int sector, unsigned int value);
  285 static long do_check(char *buffer, int try, off_t current_block);
  286 static void alarm_intr(int alnum);
  287 static void check_blocks(void);
  288 static void get_list_blocks(char *filename);
  289 static void check_mount(char *device_name);
  290 static void establish_params(struct device_info *info);
  291 static void setup_tables(void);
  292 static void write_tables(void);
  293 
  294 /* The function implementations */
  295 
  296 /* Mark the specified cluster as having a particular value */
  297 
  298 static void mark_FAT_cluster(int cluster, unsigned int value)
  299 {
  300 
  301     if (cluster < 0 || cluster >= fat_entries)
  302     die("Internal error: out of range cluster number in mark_FAT_cluster");
  303 
  304     switch (size_fat) {
  305     case 12:
  306     value &= 0x0fff;
  307     if (((cluster * 3) & 0x1) == 0) {
  308         fat[3 * cluster / 2] = (unsigned char)(value & 0x00ff);
  309         fat[(3 * cluster / 2) + 1] =
  310         (unsigned char)((fat[(3 * cluster / 2) + 1] & 0x00f0)
  311                 | ((value & 0x0f00) >> 8));
  312     } else {
  313         fat[3 * cluster / 2] =
  314         (unsigned char)((fat[3 * cluster / 2] & 0x000f) |
  315                 ((value & 0x000f) << 4));
  316         fat[(3 * cluster / 2) + 1] = (unsigned char)((value & 0x0ff0) >> 4);
  317     }
  318     break;
  319 
  320     case 16:
  321     value &= 0xffff;
  322     fat[2 * cluster] = (unsigned char)(value & 0x00ff);
  323     fat[(2 * cluster) + 1] = (unsigned char)(value >> 8);
  324     break;
  325 
  326     case 32:
  327     value &= 0xfffffff;
  328     fat[4 * cluster] = (unsigned char)(value & 0x000000ff);
  329     fat[(4 * cluster) + 1] = (unsigned char)((value & 0x0000ff00) >> 8);
  330     fat[(4 * cluster) + 2] = (unsigned char)((value & 0x00ff0000) >> 16);
  331     fat[(4 * cluster) + 3] = (unsigned char)((value & 0xff000000) >> 24);
  332     break;
  333 
  334     default:
  335     die("Bad FAT size (not 12, 16, or 32)");
  336     }
  337 }
  338 
  339 /* Mark a specified sector as having a particular value in it's FAT entry */
  340 
  341 static void mark_FAT_sector(int sector, unsigned int value)
  342 {
  343     int cluster = (sector - start_data_sector) / (int)(bs.cluster_size) /
  344     (sector_size / HARD_SECTOR_SIZE) + 2;
  345 
  346     if (sector < start_data_sector || sector >= num_sectors)
  347     die("Internal error: out of range sector number in mark_FAT_sector");
  348 
  349     mark_FAT_cluster(cluster, value);
  350 }
  351 
  352 /* Perform a test on a block.  Return the number of blocks that could be read successfully */
  353 
  354 static long do_check(char *buffer, int try, off_t current_block)
  355 {
  356     long got;
  357 
  358     if (lseek(dev, part_sector * sector_size + current_block * BLOCK_SIZE, SEEK_SET)    /* Seek to the correct location */
  359     !=current_block * BLOCK_SIZE)
  360     die("seek failed during testing for blocks");
  361 
  362     got = read(dev, buffer, try * BLOCK_SIZE);  /* Try reading! */
  363     if (got < 0)
  364     got = 0;
  365 
  366     if (got & (BLOCK_SIZE - 1))
  367     printf("Unexpected values in do_check: probably bugs\n");
  368     got /= BLOCK_SIZE;
  369 
  370     return got;
  371 }
  372 
  373 /* Alarm clock handler - display the status of the quest for bad blocks!  Then retrigger the alarm for five senconds
  374    later (so we can come here again) */
  375 
  376 static void alarm_intr(int alnum)
  377 {
  378     (void)alnum;
  379 
  380     if (currently_testing >= blocks)
  381     return;
  382 
  383     signal(SIGALRM, alarm_intr);
  384     alarm(5);
  385     if (!currently_testing)
  386     return;
  387 
  388     printf("%lld... ", (unsigned long long)currently_testing);
  389     fflush(stdout);
  390 }
  391 
  392 static void check_blocks(void)
  393 {
  394     int try, got;
  395     int i;
  396     static char blkbuf[BLOCK_SIZE * TEST_BUFFER_BLOCKS];
  397 
  398     if (verbose) {
  399     printf("Searching for bad blocks ");
  400     fflush(stdout);
  401     }
  402     currently_testing = 0;
  403     if (verbose) {
  404     signal(SIGALRM, alarm_intr);
  405     alarm(5);
  406     }
  407     try = TEST_BUFFER_BLOCKS;
  408     while (currently_testing < blocks) {
  409     if (currently_testing + try > blocks)
  410         try = blocks - currently_testing; /* TODO: check overflow */
  411     got = do_check(blkbuf, try, currently_testing);
  412     currently_testing += got;
  413     if (got == try) {
  414         try = TEST_BUFFER_BLOCKS;
  415         continue;
  416     } else
  417         try = 1;
  418     if (currently_testing < start_data_block)
  419         die("bad blocks before data-area: cannot make fs");
  420 
  421     for (i = 0; i < SECTORS_PER_BLOCK; i++) /* Mark all of the sectors in the block as bad */
  422         mark_sector_bad(currently_testing * SECTORS_PER_BLOCK + i);
  423     badblocks++;
  424     currently_testing++;
  425     }
  426 
  427     if (verbose)
  428     printf("\n");
  429 
  430     if (badblocks)
  431     printf("%d bad block%s\n", badblocks, (badblocks > 1) ? "s" : "");
  432 }
  433 
  434 static void get_list_blocks(char *filename)
  435 {
  436     int i;
  437     FILE *listfile;
  438     long long blockno;
  439     char *line = NULL;
  440     size_t linesize = 0;
  441     int lineno = 0;
  442     char *end, *check;
  443 
  444     listfile = fopen(filename, "r");
  445     if (listfile == (FILE *) NULL)
  446     die("Can't open file of bad blocks");
  447 
  448     while (1) {
  449     lineno++;
  450     ssize_t length = getline(&line, &linesize, listfile);
  451     if (length < 0) {
  452         if (errno == 0) /* end of file */
  453         break;
  454 
  455         perror("getline");
  456         die("Error while reading bad blocks file");
  457     }
  458 
  459     errno = 0;
  460     blockno = strtoll(line, &end, 10);
  461 
  462     if (errno || blockno < 0) {
  463         fprintf(stderr,
  464             "While converting bad block number in line %d: %s\n",
  465             lineno, strerror(errno));
  466         die("Error in bad blocks file");
  467     }
  468 
  469     check = end;
  470     while (*check) {
  471         if (!isspace(*check)) {
  472         fprintf(stderr,
  473             "Badly formed number in bad blocks file line %d\n",
  474             lineno);
  475         die("Error in bad blocks file");
  476         }
  477 
  478         check++;
  479     }
  480 
  481     /* ignore empty or white space only lines */
  482     if (end == line)
  483         continue;
  484 
  485     /* Mark all of the sectors in the block as bad */
  486     for (i = 0; i < SECTORS_PER_BLOCK; i++) {
  487         unsigned long long sector = blockno * SECTORS_PER_BLOCK + i;
  488 
  489         if (sector < start_data_sector) {
  490         fprintf(stderr, "Block number %lld is before data area\n",
  491             blockno);
  492         die("Error in bad blocks file");
  493         }
  494 
  495         if (sector >= num_sectors) {
  496         fprintf(stderr, "Block number %lld is behind end of filesystem\n",
  497             blockno);
  498         die("Error in bad blocks file");
  499         }
  500 
  501         mark_sector_bad(sector);
  502     }
  503     badblocks++;
  504     }
  505     fclose(listfile);
  506     free(line);
  507 
  508     if (badblocks)
  509     printf("%d bad block%s\n", badblocks, (badblocks > 1) ? "s" : "");
  510 }
  511 
  512 /* Check to see if the specified device is currently mounted - abort if it is */
  513 
  514 static void check_mount(char *device_name)
  515 {
  516     if (is_device_mounted(device_name))
  517     die("%s contains a mounted filesystem.", device_name);
  518 }
  519 
  520 /* Establish the geometry and media parameters for the device */
  521 
  522 static void establish_params(struct device_info *info)
  523 {
  524     unsigned int sec_per_track;
  525     unsigned int heads;
  526     unsigned int media = 0xf8;
  527     unsigned int cluster_size = 4;  /* starting point for FAT12 and FAT16 */
  528     int def_root_dir_entries = 512;
  529 
  530     if (info->geom_heads > 0) {
  531         heads = info->geom_heads;
  532         sec_per_track = info->geom_sectors;
  533     } else {
  534         unsigned long long int total_sectors;
  535 
  536         if (info->geom_size > 0)
  537             total_sectors = info->geom_size;
  538         else if (info->sector_size > 0)
  539             total_sectors = info->size / info->sector_size;
  540         else
  541             total_sectors = info->size / sector_size;
  542 
  543         if (total_sectors <= 524288) {
  544             /* For capacity below the 256MB (with 512b sectors) use CHS Recommendation from SD Card Part 2 File System Specification */
  545             heads = total_sectors <=  32768 ? 2 :
  546                     total_sectors <=  65536 ? 4 :
  547                     total_sectors <= 262144 ? 8 : 16;
  548             sec_per_track = total_sectors <= 4096 ? 16 : 32;
  549         } else {
  550             /* Use LBA-Assist Translation for calculating CHS when disk geometry is not available */
  551             heads = total_sectors <=  16*63*1024 ? 16 :
  552                     total_sectors <=  32*63*1024 ? 32 :
  553                     total_sectors <=  64*63*1024 ? 64 :
  554                     total_sectors <= 128*63*1024 ? 128 : 255;
  555             sec_per_track = 63;
  556         }
  557     }
  558 
  559     if (info->type != TYPE_FIXED) {
  560     /* enter default parameters for floppy disks if the size matches */
  561     switch (info->size / 1024) {
  562         case 360:
  563         sec_per_track = 9;
  564         heads = 2;
  565         media = 0xfd;
  566         cluster_size = 2;
  567         def_root_dir_entries = 112;
  568         break;
  569 
  570         case 720:
  571         sec_per_track = 9;
  572         heads = 2;
  573         media = 0xf9;
  574         cluster_size = 2;
  575         def_root_dir_entries = 112;
  576         break;
  577 
  578         case 1200:
  579         sec_per_track = 15;
  580         heads = 2;
  581         media = 0xf9;
  582         cluster_size = (atari_format ? 2 : 1);
  583         def_root_dir_entries = 224;
  584         break;
  585 
  586         case 1440:
  587         sec_per_track = 18;
  588         heads = 2;
  589         media = 0xf0;
  590         cluster_size = (atari_format ? 2 : 1);
  591         def_root_dir_entries = 224;
  592         break;
  593 
  594         case 2880:
  595         sec_per_track = 36;
  596         heads = 2;
  597         media = 0xf0;
  598         cluster_size = 2;
  599         def_root_dir_entries = 224;
  600         break;
  601     }
  602     }
  603 
  604     if (!size_fat && info->size >= 512 * 1024 * 1024) {
  605     if (verbose)
  606         printf("Auto-selecting FAT32 for large filesystem\n");
  607     size_fat = 32;
  608     }
  609     if (size_fat == 32) {
  610     /*
  611      * For FAT32, try to do the same as M$'s format command
  612      * (see http://www.win.tue.nl/~aeb/linux/fs/fat/fatgen103.pdf p. 20):
  613      * fs size <= 260M: 0.5k clusters
  614      * fs size <=   8G:   4k clusters
  615      * fs size <=  16G:   8k clusters
  616      * fs size <=  32G:  16k clusters
  617      * fs size >   32G:  32k clusters
  618      */
  619     unsigned long long int sectors = info->size / sector_size;
  620         cluster_size = sectors > 32*1024*1024*2 ? 64 :
  621                        sectors > 16*1024*1024*2 ? 32 :
  622                        sectors >  8*1024*1024*2 ? 16 :
  623                        sectors >     260*1024*2 ? 8 : 1;
  624     }
  625 
  626     if (!hidden_sectors_by_user && info->geom_start >= 0 && info->geom_start + part_sector <= UINT32_MAX)
  627         hidden_sectors = info->geom_start + part_sector;
  628 
  629     if (!root_dir_entries)
  630     root_dir_entries = def_root_dir_entries;
  631 
  632     if (!bs.secs_track)
  633         bs.secs_track = htole16(sec_per_track);
  634     if (!bs.heads)
  635         bs.heads = htole16(heads);
  636     bs.media = media;
  637     bs.cluster_size = cluster_size;
  638 }
  639 
  640 /*
  641  * If alignment is enabled, round the first argument up to the second; the
  642  * latter must be a power of two.
  643  */
  644 static unsigned int align_object(unsigned int sectors, unsigned int clustsize)
  645 {
  646     if (align_structures)
  647     return (sectors + clustsize - 1) & ~(clustsize - 1);
  648     else
  649     return sectors;
  650 }
  651 
  652 /* Create the filesystem data tables */
  653 
  654 static void setup_tables(void)
  655 {
  656     unsigned cluster_count = 0, fat_length;
  657     struct tm *ctime;
  658     struct msdos_volume_info *vi =
  659     (size_fat == 32 ? &bs.fat32.vi : &bs.oldfat.vi);
  660     char label[12] = { 0 };
  661     size_t len;
  662     int ret;
  663     int i;
  664 
  665     if (atari_format) {
  666     /* On Atari, the first few bytes of the boot sector are assigned
  667      * differently: The jump code is only 2 bytes (and m68k machine code
  668      * :-), then 6 bytes filler (ignored), then 3 byte serial number. */
  669     bs.boot_jump[2] = 'm';
  670     memcpy((char *)bs.system_id, "kdosf", strlen("kdosf"));
  671     } else
  672     memcpy((char *)bs.system_id, "mkfs.fat", strlen("mkfs.fat"));
  673     if (sectors_per_cluster)
  674     bs.cluster_size = (char)sectors_per_cluster;
  675 
  676     if (fat_media_byte)
  677     bs.media = (char) fat_media_byte;
  678 
  679     if (bs.media == 0xf8)
  680     vi->drive_number=0x80;
  681     else
  682     vi->drive_number=0x00;
  683 
  684     if (drive_number_by_user)
  685     vi->drive_number= (char) drive_number_option;
  686 
  687     if (size_fat == 32) {
  688     /* Under FAT32, the root dir is in a cluster chain, and this is
  689      * signalled by bs.dir_entries being 0. */
  690     if (root_dir_entries_set)
  691         fprintf(stderr, "Warning: root directory entries specified with -r have no effect on FAT32\n");
  692     root_dir_entries = 0;
  693     }
  694 
  695     if (atari_format) {
  696     bs.system_id[5] = (unsigned char)(volume_id & 0x000000ff);
  697     bs.system_id[6] = (unsigned char)((volume_id & 0x0000ff00) >> 8);
  698     bs.system_id[7] = (unsigned char)((volume_id & 0x00ff0000) >> 16);
  699     } else {
  700     vi->volume_id[0] = (unsigned char)(volume_id & 0x000000ff);
  701     vi->volume_id[1] = (unsigned char)((volume_id & 0x0000ff00) >> 8);
  702     vi->volume_id[2] = (unsigned char)((volume_id & 0x00ff0000) >> 16);
  703     vi->volume_id[3] = (unsigned char)(volume_id >> 24);
  704     }
  705 
  706     len = mbstowcs(NULL, volume_name, 0);
  707     if (len != (size_t)-1 && len > 11)
  708     die("Label can be no longer than 11 characters");
  709 
  710     if (!local_string_to_dos_string(label, volume_name, 12))
  711     die("Error when processing label");
  712 
  713     for (i = strlen(label); i < 11; ++i)
  714     label[i] = ' ';
  715     label[11] = 0;
  716 
  717     if (memcmp(label, "           ", MSDOS_NAME) == 0)
  718     memcpy(label, NO_NAME, MSDOS_NAME);
  719 
  720     ret = validate_volume_label(label);
  721     if (ret & 0x1)
  722     fprintf(stderr,
  723         "mkfs.fat: Warning: lowercase labels might not work properly on some systems\n");
  724     if (ret & 0x2)
  725     die("Labels with characters below 0x20 are not allowed\n");
  726     if (ret & 0x4)
  727     die("Labels with characters *?.,;:/\\|+=<>[]\" are not allowed\n");
  728     if (ret & 0x10)
  729     die("Label can't start with a space character");
  730 
  731     if (!atari_format) {
  732     memcpy(vi->volume_label, label, 11);
  733 
  734     memcpy(bs.boot_jump, dummy_boot_jump, 3);
  735     /* Patch in the correct offset to the boot code */
  736     bs.boot_jump[1] = ((size_fat == 32 ?
  737                 (char *)&bs.fat32.boot_code :
  738                 (char *)&bs.oldfat.boot_code) - (char *)&bs) - 2;
  739 
  740     if (size_fat == 32) {
  741         int offset = (char *)&bs.fat32.boot_code -
  742         (char *)&bs + MESSAGE_OFFSET + 0x7c00;
  743         if (dummy_boot_code[BOOTCODE_FAT32_SIZE - 1])
  744         printf("Warning: message too long; truncated\n");
  745         dummy_boot_code[BOOTCODE_FAT32_SIZE - 1] = 0;
  746         memcpy(bs.fat32.boot_code, dummy_boot_code, BOOTCODE_FAT32_SIZE);
  747         bs.fat32.boot_code[MSG_OFFSET_OFFSET] = offset & 0xff;
  748         bs.fat32.boot_code[MSG_OFFSET_OFFSET + 1] = offset >> 8;
  749     } else {
  750         memcpy(bs.oldfat.boot_code, dummy_boot_code, BOOTCODE_SIZE);
  751     }
  752     bs.boot_sign = htole16(BOOT_SIGN);
  753     } else {
  754     memcpy(bs.boot_jump, dummy_boot_jump_m68k, 2);
  755     }
  756     if (verbose >= 2)
  757     printf("Boot jump code is %02x %02x\n",
  758            bs.boot_jump[0], bs.boot_jump[1]);
  759 
  760     if (!reserved_sectors)
  761     reserved_sectors = (size_fat == 32) ? 32 : 1;
  762     else {
  763     if (size_fat == 32 && reserved_sectors < 2)
  764         die("On FAT32 at least 2 reserved sectors are needed.");
  765     }
  766     bs.reserved = htole16(reserved_sectors);
  767     if (verbose >= 2)
  768     printf("Using %d reserved sectors\n", reserved_sectors);
  769     bs.fats = (char)nr_fats;
  770     if (!atari_format || size_fat == 32)
  771     bs.hidden = htole32(hidden_sectors);
  772     else {
  773     /* In Atari format, hidden is a 16 bit field */
  774     uint16_t hidden = htole16(hidden_sectors);
  775     if (hidden_sectors & ~0xffff)
  776         die("#hidden doesn't fit in 16bit field of Atari format\n");
  777     memcpy(&bs.hidden, &hidden, 2);
  778     }
  779 
  780     if ((long long)(blocks * BLOCK_SIZE / sector_size) + orphaned_sectors >
  781         UINT32_MAX) {
  782     printf("Warning: target too large, space at end will be left unused\n");
  783     num_sectors = UINT32_MAX;
  784     blocks = (unsigned long long)UINT32_MAX * sector_size / BLOCK_SIZE;
  785     } else {
  786     num_sectors =
  787         (long long)(blocks * BLOCK_SIZE / sector_size) + orphaned_sectors;
  788     }
  789 
  790     if (align_structures) {
  791         /* Align number of sectors to be multiple of sectors per track, needed by DOS and mtools */
  792         num_sectors = num_sectors / le16toh(bs.secs_track) * le16toh(bs.secs_track);
  793     }
  794 
  795     if (!atari_format) {
  796     unsigned fatdata1216;   /* Sectors for FATs + data area (FAT12/16) */
  797     unsigned fatdata32; /* Sectors for FATs + data area (FAT32) */
  798     unsigned fatlength12, fatlength16, fatlength32;
  799     unsigned maxclust12, maxclust16, maxclust32;
  800     unsigned clust12, clust16, clust32;
  801     int maxclustsize;
  802     unsigned root_dir_sectors = cdiv(root_dir_entries * 32, sector_size);
  803 
  804     /*
  805      * If the filesystem is 8192 sectors or less (4 MB with 512-byte
  806      * sectors, i.e. floppy size), don't align the data structures.
  807      */
  808     if (num_sectors <= 8192) {
  809         if (align_structures && verbose >= 2)
  810         printf("Disabling alignment due to tiny filesystem\n");
  811 
  812         align_structures = FALSE;
  813     }
  814 
  815     if (sectors_per_cluster)
  816         bs.cluster_size = maxclustsize = sectors_per_cluster;
  817     else
  818         /* An initial guess for bs.cluster_size should already be set */
  819         maxclustsize = 128;
  820 
  821     do {
  822         fatdata32 = num_sectors
  823         - align_object(reserved_sectors, bs.cluster_size);
  824         fatdata1216 = fatdata32
  825         - align_object(root_dir_sectors, bs.cluster_size);
  826 
  827         if (verbose >= 2)
  828         printf("Trying with %d sectors/cluster:\n", bs.cluster_size);
  829 
  830         /* The factor 2 below avoids cut-off errors for nr_fats == 1.
  831          * The "nr_fats*3" is for the reserved first two FAT entries */
  832         clust12 = 2 * ((long long)fatdata1216 * sector_size + nr_fats * 3) /
  833         (2 * (int)bs.cluster_size * sector_size + nr_fats * 3);
  834         fatlength12 = cdiv(((clust12 + 2) * 3 + 1) >> 1, sector_size);
  835         fatlength12 = align_object(fatlength12, bs.cluster_size);
  836         /* Need to recalculate number of clusters, since the unused parts of the
  837          * FATS and data area together could make up space for an additional,
  838          * not really present cluster. */
  839         clust12 = (fatdata1216 - nr_fats * fatlength12) / bs.cluster_size;
  840         maxclust12 = (fatlength12 * 2 * sector_size) / 3;
  841         if (maxclust12 > MAX_CLUST_12)
  842         maxclust12 = MAX_CLUST_12;
  843         if (verbose >= 2 && (size_fat == 0 || size_fat == 12))
  844         printf("Trying FAT12: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n",
  845                clust12, fatlength12, maxclust12, MAX_CLUST_12);
  846         if (clust12 > maxclust12) {
  847         clust12 = 0;
  848         if (verbose >= 2 && (size_fat == 0 || size_fat == 12))
  849             printf("Trying FAT12: too much clusters\n");
  850         }
  851 
  852         clust16 = ((long long)fatdata1216 * sector_size + nr_fats * 4) /
  853         ((int)bs.cluster_size * sector_size + nr_fats * 2);
  854         fatlength16 = cdiv((clust16 + 2) * 2, sector_size);
  855         fatlength16 = align_object(fatlength16, bs.cluster_size);
  856         /* Need to recalculate number of clusters, since the unused parts of the
  857          * FATS and data area together could make up space for an additional,
  858          * not really present cluster. */
  859         clust16 = (fatdata1216 - nr_fats * fatlength16) / bs.cluster_size;
  860         maxclust16 = (fatlength16 * sector_size) / 2;
  861         if (maxclust16 > MAX_CLUST_16)
  862         maxclust16 = MAX_CLUST_16;
  863         if (verbose >= 2 && (size_fat == 0 || size_fat == 16))
  864         printf("Trying FAT16: #clu=%u, fatlen=%u, maxclu=%u, limit=%u/%u\n",
  865                clust16, fatlength16, maxclust16, MIN_CLUST_16, MAX_CLUST_16);
  866         if (clust16 > maxclust16) {
  867         if (verbose >= 2 && (size_fat == 0 || size_fat == 16))
  868             printf("Trying FAT16: too much clusters\n");
  869         clust16 = 0;
  870         }
  871         /* This avoids that the filesystem will be misdetected as having a
  872          * 12 bit FAT. */
  873         if (clust16 && clust16 < MIN_CLUST_16) {
  874         if (verbose >= 2 && (size_fat == 0 || size_fat == 16))
  875             printf("Trying FAT16: not enough clusters, would be misdetected as FAT12\n");
  876         clust16 = 0;
  877         }
  878 
  879         clust32 = ((long long)fatdata32 * sector_size + nr_fats * 8) /
  880         ((int)bs.cluster_size * sector_size + nr_fats * 4);
  881         fatlength32 = cdiv((clust32 + 2) * 4, sector_size);
  882         fatlength32 = align_object(fatlength32, bs.cluster_size);
  883         /* Need to recalculate number of clusters, since the unused parts of the
  884          * FATS and data area together could make up space for an additional,
  885          * not really present cluster. */
  886         clust32 = (fatdata32 - nr_fats * fatlength32) / bs.cluster_size;
  887         maxclust32 = (fatlength32 * sector_size) / 4;
  888         if (maxclust32 > MAX_CLUST_32)
  889         maxclust32 = MAX_CLUST_32;
  890         if (verbose >= 2 && (size_fat == 0 || size_fat == 32))
  891         printf("Trying FAT32: #clu=%u, fatlen=%u, maxclu=%u, limit=%u/%u\n",
  892                clust32, fatlength32, maxclust32, MIN_CLUST_32, MAX_CLUST_32);
  893         if (clust32 > maxclust32) {
  894         if (verbose >= 2 && (size_fat == 0 || size_fat == 32))
  895             printf("Trying FAT32: too much clusters\n");
  896         clust32 = 0;
  897         }
  898         /* When explicitely asked, allow to create FAT32 with less then MIN_CLUST_32 */
  899         if (clust32 && clust32 < MIN_CLUST_32
  900         && !(size_fat_by_user && size_fat == 32)) {
  901         if (verbose >= 2 && (size_fat == 0 || size_fat == 32))
  902             printf("Trying FAT32: not enough clusters\n");
  903         clust32 = 0;
  904         }
  905 
  906         if ((clust12 && (size_fat == 0 || size_fat == 12)) ||
  907         (clust16 && (size_fat == 0 || size_fat == 16)) ||
  908         (clust32 && size_fat == 32))
  909         break;
  910 
  911         bs.cluster_size <<= 1;
  912     } while (bs.cluster_size && bs.cluster_size <= maxclustsize);
  913 
  914     /* Use the optimal FAT size if not specified;
  915      * establish_params() will have already set size_fat to 32 if it is not
  916      * specified and the filesystem size is over a specific threshold */
  917     if (!size_fat) {
  918         size_fat = (clust16 > clust12) ? 16 : 12;
  919         if (verbose >= 2)
  920         printf("Choosing %d bits for FAT\n", size_fat);
  921     }
  922 
  923     switch (size_fat) {
  924     case 12:
  925         cluster_count = clust12;
  926         fat_length = fatlength12;
  927         bs.fat_length = htole16(fatlength12);
  928         memcpy(vi->fs_type, MSDOS_FAT12_SIGN, 8);
  929         break;
  930 
  931     case 16:
  932         cluster_count = clust16;
  933         fat_length = fatlength16;
  934         bs.fat_length = htole16(fatlength16);
  935         memcpy(vi->fs_type, MSDOS_FAT16_SIGN, 8);
  936         break;
  937 
  938     case 32:
  939         if (clust32 < MIN_CLUST_32)
  940         fprintf(stderr, "WARNING: Number of clusters for 32 bit FAT is less then suggested minimum.\n");
  941         cluster_count = clust32;
  942         fat_length = fatlength32;
  943         bs.fat_length = htole16(0);
  944         bs.fat32.fat32_length = htole32(fatlength32);
  945         memcpy(vi->fs_type, MSDOS_FAT32_SIGN, 8);
  946         root_dir_entries = 0;
  947         break;
  948 
  949     default:
  950         die("FAT not 12, 16 or 32 bits");
  951     }
  952 
  953     /* Adjust the reserved number of sectors for alignment */
  954     reserved_sectors = align_object(reserved_sectors, bs.cluster_size);
  955     bs.reserved = htole16(reserved_sectors);
  956 
  957     /* Adjust the number of root directory entries to help enforce alignment */
  958     if (align_structures) {
  959         root_dir_entries = align_object(root_dir_sectors, bs.cluster_size)
  960         * (sector_size >> 5);
  961     }
  962     } else {
  963     unsigned clusters, maxclust, fatdata;
  964 
  965     /* GEMDOS always uses a 12 bit FAT on floppies, and always a 16 bit FAT on
  966      * hard disks. So use 12 bit if the size of the filesystem suggests that
  967      * this fs is for a floppy disk, if the user hasn't explicitly requested a
  968      * size.
  969      */
  970     if (!size_fat)
  971         size_fat = (num_sectors == 1440 || num_sectors == 2400 ||
  972             num_sectors == 2880 || num_sectors == 5760) ? 12 : 16;
  973     if (verbose >= 2)
  974         printf("Choosing %d bits for FAT\n", size_fat);
  975 
  976     /* Atari format: cluster size should be 2, except explicitly requested by
  977      * the user, since GEMDOS doesn't like other cluster sizes very much.
  978      * Instead, tune the sector size for the FS to fit.
  979      */
  980     bs.cluster_size = sectors_per_cluster ? sectors_per_cluster : 2;
  981     if (!sector_size_set) {
  982         while (num_sectors > GEMDOS_MAX_SECTORS) {
  983         num_sectors >>= 1;
  984         sector_size <<= 1;
  985         }
  986     }
  987     if (verbose >= 2)
  988         printf("Sector size must be %d to have less than %d log. sectors\n",
  989            sector_size, GEMDOS_MAX_SECTORS);
  990 
  991     /* Check if there are enough FAT indices for how much clusters we have */
  992     do {
  993         fatdata = num_sectors - cdiv(root_dir_entries * 32, sector_size) -
  994         reserved_sectors;
  995         /* The factor 2 below avoids cut-off errors for nr_fats == 1 and
  996          * size_fat == 12
  997          * The "2*nr_fats*size_fat/8" is for the reserved first two FAT entries
  998          */
  999         clusters =
 1000         (2 *
 1001          ((long long)fatdata * sector_size -
 1002           2 * nr_fats * size_fat / 8)) / (2 * ((int)bs.cluster_size *
 1003                                sector_size +
 1004                                nr_fats * size_fat / 8));
 1005         fat_length = cdiv((clusters + 2) * size_fat / 8, sector_size);
 1006         /* Need to recalculate number of clusters, since the unused parts of the
 1007          * FATS and data area together could make up space for an additional,
 1008          * not really present cluster. */
 1009         clusters = (fatdata - nr_fats * fat_length) / bs.cluster_size;
 1010         maxclust = (fat_length * sector_size * 8) / size_fat;
 1011         if (verbose >= 2)
 1012         printf("ss=%d: #clu=%d, fat_len=%d, maxclu=%d\n",
 1013                sector_size, clusters, fat_length, maxclust);
 1014 
 1015         /* last 10 cluster numbers are special (except FAT32: 4 high bits rsvd);
 1016          * first two numbers are reserved */
 1017         if (maxclust <=
 1018         (size_fat == 32 ? MAX_CLUST_32 : (1 << size_fat) - 0x10)
 1019         && clusters <= maxclust - 2)
 1020         break;
 1021         if (verbose >= 2)
 1022         printf(clusters > maxclust - 2 ?
 1023                "Too many clusters\n" : "FAT too big\n");
 1024 
 1025         /* need to increment sector_size once more to  */
 1026         if (sector_size_set)
 1027         die("With this sector size, the maximum number of FAT entries "
 1028             "would be exceeded.");
 1029         num_sectors >>= 1;
 1030         sector_size <<= 1;
 1031     } while (sector_size <= GEMDOS_MAX_SECTOR_SIZE);
 1032 
 1033     if (sector_size > GEMDOS_MAX_SECTOR_SIZE)
 1034         die("Would need a sector size > 16k, which GEMDOS can't work with");
 1035 
 1036     cluster_count = clusters;
 1037     if (size_fat != 32)
 1038         bs.fat_length = htole16(fat_length);
 1039     else {
 1040         bs.fat_length = 0;
 1041         bs.fat32.fat32_length = htole32(fat_length);
 1042     }
 1043     }
 1044 
 1045     if (fill_mbr_partition) {
 1046         uint8_t *partition;
 1047         uint8_t *disk_sig_ptr;
 1048         uint32_t disk_sig;
 1049         uint8_t buf[512];
 1050         int fd;
 1051 
 1052         if (verbose)
 1053             printf("Adding MBR table\n");
 1054 
 1055         if (size_fat == 32)
 1056             disk_sig_ptr = bs.fat32.boot_code + BOOTCODE_FAT32_SIZE - 16*4 - 6;
 1057         else
 1058             disk_sig_ptr = bs.oldfat.boot_code + BOOTCODE_SIZE - 16*4 - 6;
 1059 
 1060         if (*(disk_sig_ptr-1)) {
 1061             printf("Warning: message too long; truncated\n");
 1062             *(disk_sig_ptr-1) = 0;
 1063         }
 1064 
 1065         disk_sig = 0;
 1066         memset(disk_sig_ptr, 0, 16*4 + 6);
 1067 
 1068         /* Try to read existing 32 bit disk signature */
 1069         fd = open(device_name, O_RDONLY);
 1070         if (fd >= 0) {
 1071             if (read(fd, buf, sizeof(buf)) == sizeof(buf) && buf[510] == 0x55 && buf[511] == 0xAA)
 1072                 disk_sig = (uint32_t)buf[440] | ((uint32_t)buf[441] << 8) | ((uint32_t)buf[442] << 16) | ((uint32_t)buf[443] << 24);
 1073             close(fd);
 1074         }
 1075 
 1076         /* If is not available then generate random 32 bit disk signature */
 1077         if (invariant)
 1078             disk_sig = volume_id;
 1079         else if (!disk_sig)
 1080             disk_sig = generate_volume_id();
 1081 
 1082         disk_sig_ptr[0] = (disk_sig >>  0) & 0xFF;
 1083         disk_sig_ptr[1] = (disk_sig >>  8) & 0xFF;
 1084         disk_sig_ptr[2] = (disk_sig >> 16) & 0xFF;
 1085         disk_sig_ptr[3] = (disk_sig >> 24) & 0xFF;
 1086 
 1087         partition = disk_sig_ptr + 6;
 1088 
 1089         /* Active flag */
 1090         partition[0] = 0x80;
 1091 
 1092         /* CHS address of the first sector */
 1093         partition[1] = 0;
 1094         partition[2] = 1;
 1095         partition[3] = 0;
 1096 
 1097         /* Partition type */
 1098         if (le16toh(bs.heads) > 254 || le16toh(bs.secs_track) > 63) { /* CHS values are out of range for MBR, use LBA */
 1099             if (size_fat != 32)
 1100                 partition[4] = 0x0E; /* BIG FAT16 (LBA) */
 1101             else
 1102                 partition[4] = 0x0C; /* FAT32 (LBA) */
 1103         } else if (size_fat == 12 && num_sectors < 65536)
 1104             partition[4] = 0x01; /* FAT12 (CHS) */
 1105         else if (size_fat == 16 && num_sectors < 65536)
 1106             partition[4] = 0x04; /* FAT16 (CHS) */
 1107         else if (size_fat != 32 && num_sectors < le16toh(bs.secs_track) * le16toh(bs.heads) * 1024)
 1108             partition[4] = 0x06; /* BIG FAT16 or FAT12 (CHS) */
 1109         else if (size_fat != 32)
 1110             partition[4] = 0x0E; /* BIG FAT16 (LBA) */
 1111         else
 1112             partition[4] = 0x0C; /* FAT32 (LBA) */
 1113 
 1114         /* CHS address of the last sector */
 1115         if (le16toh(bs.heads) > 254 || le16toh(bs.secs_track) > 63 || num_sectors >= le16toh(bs.secs_track) * le16toh(bs.heads) * 1024) {
 1116             /* If CHS address is too large use tuple (1023, 254, 63) */
 1117             partition[5] = 254;
 1118             partition[6] = 255;
 1119             partition[7] = 255;
 1120         } else {
 1121             partition[5] = (num_sectors / le16toh(bs.secs_track)) % le16toh(bs.heads);
 1122             partition[6] = ((1 + num_sectors % le16toh(bs.secs_track)) & 63) | (((num_sectors / (le16toh(bs.heads) * le16toh(bs.secs_track))) >> 8) * 64);
 1123             partition[7] = (num_sectors / (le16toh(bs.heads) * le16toh(bs.secs_track))) & 255;
 1124         }
 1125 
 1126         /* LBA of the first sector */
 1127         partition[ 8] = 0;
 1128         partition[ 9] = 0;
 1129         partition[10] = 0;
 1130         partition[11] = 0;
 1131 
 1132         /* Number of sectors */
 1133         partition[12] = (num_sectors >>  0) & 0xFF;
 1134         partition[13] = (num_sectors >>  8) & 0xFF;
 1135         partition[14] = (num_sectors >> 16) & 0xFF;
 1136         partition[15] = (num_sectors >> 24) & 0xFF;
 1137     }
 1138 
 1139     bs.sector_size[0] = (char)(sector_size & 0x00ff);
 1140     bs.sector_size[1] = (char)((sector_size & 0xff00) >> 8);
 1141 
 1142     bs.dir_entries[0] = (char)(root_dir_entries & 0x00ff);
 1143     bs.dir_entries[1] = (char)((root_dir_entries & 0xff00) >> 8);
 1144 
 1145     if (size_fat == 32) {
 1146     /* set up additional FAT32 fields */
 1147     bs.fat32.flags = htole16(0);
 1148     bs.fat32.version[0] = 0;
 1149     bs.fat32.version[1] = 0;
 1150     bs.fat32.root_cluster = htole32(2);
 1151     if (!info_sector)
 1152         info_sector = 1;
 1153     bs.fat32.info_sector = htole16(info_sector);
 1154     if (!backup_boot_set)
 1155         backup_boot = (reserved_sectors >= 7 && info_sector != 6) ? 6 :
 1156         (reserved_sectors >= 3 + info_sector &&
 1157          info_sector != reserved_sectors - 2 &&
 1158          info_sector != reserved_sectors - 1) ? reserved_sectors - 2 :
 1159         (reserved_sectors >= 3 && info_sector != reserved_sectors - 1) ?
 1160         reserved_sectors - 1 : 0;
 1161     if (backup_boot) {
 1162         if (backup_boot == info_sector)
 1163         die("Backup boot sector must not be same as info sector (%d)", info_sector);
 1164         else if (backup_boot >= reserved_sectors)
 1165         die("Backup boot sector must be a reserved sector");
 1166     }
 1167     if (verbose >= 2)
 1168         printf("Using sector %d as backup boot sector (0 = none)\n",
 1169            backup_boot);
 1170     bs.fat32.backup_boot = htole16(backup_boot);
 1171     memset(&bs.fat32.reserved2, 0, sizeof(bs.fat32.reserved2));
 1172     }
 1173 
 1174     if (atari_format) {
 1175     /* Just some consistency checks */
 1176     if (num_sectors >= GEMDOS_MAX_SECTORS)
 1177         die("GEMDOS can't handle more than 65531 sectors");
 1178     else if (num_sectors >= OLDGEMDOS_MAX_SECTORS)
 1179         printf("Warning: More than 32765 sector need TOS 1.04 "
 1180            "or higher.\n");
 1181     }
 1182     if (num_sectors >= 65536) {
 1183     bs.sectors[0] = (char)0;
 1184     bs.sectors[1] = (char)0;
 1185     bs.total_sect = htole32(num_sectors);
 1186     } else {
 1187     bs.sectors[0] = (char)(num_sectors & 0x00ff);
 1188     bs.sectors[1] = (char)((num_sectors & 0xff00) >> 8);
 1189     if (!atari_format)
 1190         bs.total_sect = htole32(0);
 1191     }
 1192 
 1193     if (!atari_format)
 1194     vi->ext_boot_sign = MSDOS_EXT_SIGN;
 1195 
 1196     if (!cluster_count) {
 1197     if (sectors_per_cluster)    /* If yes, die if we'd spec'd sectors per cluster */
 1198         die("Not enough or too many clusters for filesystem - try less or more sectors per cluster");
 1199     else
 1200         die("Attempting to create a too small or a too large filesystem");
 1201     }
 1202     fat_entries = cluster_count + 2;
 1203 
 1204     /* The two following vars are in hard sectors, i.e. 512 byte sectors! */
 1205     start_data_sector = (reserved_sectors + nr_fats * fat_length +
 1206         cdiv(root_dir_entries * 32, sector_size)) *
 1207     (sector_size / HARD_SECTOR_SIZE);
 1208     start_data_block = (start_data_sector + SECTORS_PER_BLOCK - 1) /
 1209     SECTORS_PER_BLOCK;
 1210 
 1211     if (blocks < start_data_block + 32) /* Arbitrary undersize filesystem! */
 1212     die("Too few blocks for viable filesystem");
 1213 
 1214     if (verbose) {
 1215     printf("%s has %d head%s and %d sector%s per track,\n",
 1216            device_name, le16toh(bs.heads),
 1217            (le16toh(bs.heads) != 1) ? "s" : "", le16toh(bs.secs_track),
 1218            (le16toh(bs.secs_track) != 1) ? "s" : "");
 1219     printf("hidden sectors 0x%04x;\n",  hidden_sectors);
 1220     printf("logical sector size is %d,\n", sector_size);
 1221     printf("using 0x%02x media descriptor, with %u sectors;\n",
 1222            (int)(bs.media), (unsigned)num_sectors);
 1223     printf("drive number 0x%02x;\n", (int) (vi->drive_number));
 1224     printf("filesystem has %d %d-bit FAT%s and %d sector%s per cluster.\n",
 1225            (int)(bs.fats), size_fat, (bs.fats != 1) ? "s" : "",
 1226            (int)(bs.cluster_size), (bs.cluster_size != 1) ? "s" : "");
 1227     printf("FAT size is %d sector%s, and provides %d cluster%s.\n",
 1228            fat_length, (fat_length != 1) ? "s" : "",
 1229            cluster_count, (cluster_count != 1) ? "s" : "");
 1230     printf("There %s %u reserved sector%s.\n",
 1231            (reserved_sectors != 1) ? "are" : "is",
 1232            reserved_sectors, (reserved_sectors != 1) ? "s" : "");
 1233 
 1234     if (size_fat != 32) {
 1235         unsigned root_dir_entries =
 1236         bs.dir_entries[0] + ((bs.dir_entries[1]) * 256);
 1237         unsigned root_dir_sectors =
 1238         cdiv(root_dir_entries * 32, sector_size);
 1239         printf("Root directory contains %u slots and uses %u sectors.\n",
 1240            root_dir_entries, root_dir_sectors);
 1241     }
 1242     printf("Volume ID is %08lx, ", volume_id &
 1243            (atari_format ? 0x00ffffff : 0xffffffff));
 1244     if (memcmp(label, NO_NAME, MSDOS_NAME))
 1245         printf("volume label %s.\n", volume_name);
 1246     else
 1247         printf("no volume label.\n");
 1248     }
 1249 
 1250     /* Make the file allocation tables! */
 1251 
 1252     if (malloc_entire_fat)
 1253     alloced_fat_length = fat_length;
 1254     else
 1255     alloced_fat_length = 1;
 1256 
 1257     if ((fat =
 1258      (unsigned char *)malloc(alloced_fat_length * sector_size)) == NULL)
 1259     die("unable to allocate space for FAT image in memory");
 1260 
 1261     memset(fat, 0, alloced_fat_length * sector_size);
 1262 
 1263     mark_FAT_cluster(0, 0xffffffff);    /* Initial fat entries */
 1264     mark_FAT_cluster(1, 0xffffffff);
 1265     fat[0] = (unsigned char)bs.media;   /* Put media type in first byte! */
 1266     if (size_fat == 32) {
 1267     /* Mark cluster 2 as EOF (used for root dir) */
 1268     mark_FAT_cluster(2, FAT_EOF);
 1269     }
 1270 
 1271     /* Make the root directory entries */
 1272 
 1273     size_root_dir = (size_fat == 32) ?
 1274     bs.cluster_size * sector_size :
 1275     (((int)bs.dir_entries[1] * 256 + (int)bs.dir_entries[0]) *
 1276      sizeof(struct msdos_dir_entry));
 1277     if ((root_dir = (struct msdos_dir_entry *)malloc(size_root_dir)) == NULL) {
 1278     free(fat);      /* Tidy up before we die! */
 1279     die("unable to allocate space for root directory in memory");
 1280     }
 1281 
 1282     memset(root_dir, 0, size_root_dir);
 1283     if (memcmp(label, NO_NAME, MSDOS_NAME)) {
 1284     struct msdos_dir_entry *de = &root_dir[0];
 1285     memcpy(de->name, label, MSDOS_NAME);
 1286     if (de->name[0] == 0xe5)
 1287         de->name[0] = 0x05;
 1288     de->attr = ATTR_VOLUME;
 1289     if (create_time != (time_t)-1) {
 1290         if (!invariant)
 1291         ctime = localtime(&create_time);
 1292         else
 1293         ctime = gmtime(&create_time);
 1294     } else {
 1295         ctime = NULL;
 1296     }
 1297     if (ctime && ctime->tm_year >= 80 && ctime->tm_year <= 207) {
 1298         de->time = htole16((unsigned short)((ctime->tm_sec >> 1) +
 1299                         (ctime->tm_min << 5) +
 1300                         (ctime->tm_hour << 11)));
 1301         de->date = htole16((unsigned short)(ctime->tm_mday +
 1302                         ((ctime->tm_mon + 1) << 5) +
 1303                         ((ctime->tm_year - 80) << 9)));
 1304     } else {
 1305         /* fallback to 1.1.1980 00:00:00 */
 1306         de->time = htole16(0);
 1307         de->date = htole16(1 + (1 << 5));
 1308     }
 1309     de->ctime_cs = 0;
 1310     de->ctime = de->time;
 1311     de->cdate = de->date;
 1312     de->adate = de->date;
 1313     de->starthi = htole16(0);
 1314     de->start = htole16(0);
 1315     de->size = htole32(0);
 1316     }
 1317 
 1318     if (size_fat == 32) {
 1319     /* For FAT32, create an info sector */
 1320     struct fat32_fsinfo *info;
 1321 
 1322     if (!(info_sector_buffer = malloc(sector_size)))
 1323         die("Out of memory");
 1324     memset(info_sector_buffer, 0, sector_size);
 1325     /* fsinfo structure is at offset 0x1e0 in info sector by observation */
 1326     info = (struct fat32_fsinfo *)(info_sector_buffer + 0x1e0);
 1327 
 1328     /* Info sector magic */
 1329     info_sector_buffer[0] = 'R';
 1330     info_sector_buffer[1] = 'R';
 1331     info_sector_buffer[2] = 'a';
 1332     info_sector_buffer[3] = 'A';
 1333 
 1334     /* Magic for fsinfo structure */
 1335     info->signature = htole32(0x61417272);
 1336     /* We've allocated cluster 2 for the root dir. */
 1337     info->free_clusters = htole32(cluster_count - 1);
 1338     info->next_cluster = htole32(2);
 1339 
 1340     /* Info sector also must have boot sign */
 1341     *(uint16_t *) (info_sector_buffer + 0x1fe) = htole16(BOOT_SIGN);
 1342     }
 1343 
 1344     if (!(blank_sector = malloc(sector_size)))
 1345     die("Out of memory");
 1346     memset(blank_sector, 0, sector_size);
 1347 }
 1348 
 1349 /* Write the new filesystem's data tables to wherever they're going to end up! */
 1350 
 1351 #define error(str)              \
 1352   do {                      \
 1353     free (fat);                 \
 1354     free (info_sector_buffer);          \
 1355     free (root_dir);                \
 1356     die (str);                  \
 1357   } while(0)
 1358 
 1359 #define seekto(pos,errstr)                      \
 1360   do {                                  \
 1361     off_t __pos = (pos);                        \
 1362     if (lseek (dev, part_sector * sector_size + __pos, SEEK_SET) != part_sector * sector_size + __pos)              \
 1363     error ("seek to " errstr " failed whilst writing tables");  \
 1364   } while(0)
 1365 
 1366 #define writebuf(buf,size,errstr)           \
 1367   do {                          \
 1368     int __size = (size);                \
 1369     if (write (dev, buf, __size) != __size)     \
 1370     error ("failed whilst writing " errstr);    \
 1371   } while(0)
 1372 
 1373 static void write_tables(void)
 1374 {
 1375     int x;
 1376     int fat_length;
 1377 
 1378     fat_length = (size_fat == 32) ?
 1379     le32toh(bs.fat32.fat32_length) : le16toh(bs.fat_length);
 1380 
 1381     seekto(0, "start of device");
 1382     /* clear all reserved sectors */
 1383     for (x = 0; x < reserved_sectors; ++x)
 1384     writebuf(blank_sector, sector_size, "reserved sector");
 1385     /* seek back to sector 0 and write the boot sector */
 1386     seekto(0, "boot sector");
 1387     writebuf((char *)&bs, sizeof(struct msdos_boot_sector), "boot sector");
 1388     /* on FAT32, write the info sector and backup boot sector */
 1389     if (size_fat == 32) {
 1390     seekto(le16toh(bs.fat32.info_sector) * sector_size, "info sector");
 1391     writebuf(info_sector_buffer, 512, "info sector");
 1392     if (backup_boot != 0) {
 1393         seekto(backup_boot * sector_size, "backup boot sector");
 1394         writebuf((char *)&bs, sizeof(struct msdos_boot_sector),
 1395              "backup boot sector");
 1396         if (backup_boot + le16toh(bs.fat32.info_sector) != le16toh(bs.fat32.info_sector) &&
 1397         backup_boot + le16toh(bs.fat32.info_sector) < reserved_sectors) {
 1398         seekto((backup_boot + le16toh(bs.fat32.info_sector)) * sector_size, "backup info sector");
 1399         writebuf(info_sector_buffer, 512, "backup info sector");
 1400         }
 1401     }
 1402     }
 1403     /* seek to start of FATS and write them all */
 1404     seekto(reserved_sectors * sector_size, "first FAT");
 1405     for (x = 1; x <= nr_fats; x++) {
 1406     int y;
 1407     int blank_fat_length = fat_length - alloced_fat_length;
 1408     writebuf(fat, alloced_fat_length * sector_size, "FAT");
 1409     for (y = 0; y < blank_fat_length; y++)
 1410         writebuf(blank_sector, sector_size, "FAT");
 1411     }
 1412     /* Write the root directory directly after the last FAT. This is the root
 1413      * dir area on FAT12/16, and the first cluster on FAT32. */
 1414     writebuf((char *)root_dir, size_root_dir, "root directory");
 1415 
 1416     if (blank_sector)
 1417     free(blank_sector);
 1418     free(info_sector_buffer);
 1419     free(root_dir);     /* Free up the root directory space from setup_tables */
 1420     free(fat);          /* Free up the fat table space reserved during setup_tables */
 1421 }
 1422 
 1423 /* Report the command usage and exit with the given error code */
 1424 
 1425 static void usage(const char *name, int exitval)
 1426 {
 1427     fprintf(stderr, "Usage: %s [OPTIONS] TARGET [BLOCKS]\n", name);
 1428     fprintf(stderr, "Create FAT filesystem in TARGET, which can be a block device or file. Use only\n");
 1429     fprintf(stderr, "up to BLOCKS 1024 byte blocks if specified. With the -C option, file TARGET will be\n");
 1430     fprintf(stderr, "created with a size of 1024 bytes times BLOCKS, which must be specified.\n");
 1431     fprintf(stderr, "\n");
 1432     fprintf(stderr, "Options:\n");
 1433     fprintf(stderr, "  -a              Disable alignment of data structures\n");
 1434     fprintf(stderr, "  -A              Toggle Atari variant of the filesystem\n");
 1435     fprintf(stderr, "  -b SECTOR       Select SECTOR as location of the FAT32 backup boot sector\n");
 1436     fprintf(stderr, "  -c              Check device for bad blocks before creating the filesystem\n");
 1437     fprintf(stderr, "  -C              Create file TARGET then create filesystem in it\n");
 1438     fprintf(stderr, "  -D NUMBER       Write BIOS drive number NUMBER to boot sector\n");
 1439     fprintf(stderr, "  -f COUNT        Create COUNT file allocation tables\n");
 1440     fprintf(stderr, "  -F SIZE         Select FAT size SIZE (12, 16 or 32)\n");
 1441     fprintf(stderr, "  -g GEOM         Select disk geometry: heads/sectors_per_track\n");
 1442     fprintf(stderr, "  -h NUMBER       Write hidden sectors NUMBER to boot sector\n");
 1443     fprintf(stderr, "  -i VOLID        Set volume ID to VOLID (a 32 bit hexadecimal number)\n");
 1444     fprintf(stderr, "  -I              Ignore and disable safety checks\n");
 1445     fprintf(stderr, "  -l FILENAME     Read bad blocks list from FILENAME\n");
 1446     fprintf(stderr, "  -m FILENAME     Replace default error message in boot block with contents of FILENAME\n");
 1447     fprintf(stderr, "  -M TYPE         Set media type in boot sector to TYPE\n");
 1448     fprintf(stderr, "  --mbr[=y|n|a]   Fill (fake) MBR table with one partition which spans whole disk\n");
 1449     fprintf(stderr, "  -n LABEL        Set volume name to LABEL (up to 11 characters long)\n");
 1450     fprintf(stderr, "  --codepage=N    use DOS codepage N to encode label (default: %d)\n", DEFAULT_DOS_CODEPAGE);
 1451     fprintf(stderr, "  -r COUNT        Make room for at least COUNT entries in the root directory\n");
 1452     fprintf(stderr, "  -R COUNT        Set minimal number of reserved sectors to COUNT\n");
 1453     fprintf(stderr, "  -s COUNT        Set number of sectors per cluster to COUNT\n");
 1454     fprintf(stderr, "  -S SIZE         Select a sector size of SIZE (a power of two, at least 512)\n");
 1455     fprintf(stderr, "  -v              Verbose execution\n");
 1456     fprintf(stderr, "  --variant=TYPE  Select variant TYPE of filesystem (standard or Atari)\n");
 1457     fprintf(stderr, "\n");
 1458     fprintf(stderr, "  --invariant     Use constants for randomly generated or time based values\n");
 1459     fprintf(stderr, "  --offset=SECTOR Write the filesystem at a specific sector into the device file.\n");
 1460     fprintf(stderr, "  --help          Show this help message and exit\n");
 1461     exit(exitval);
 1462 }
 1463 
 1464 /* The "main" entry point into the utility - we pick up the options and attempt to process them in some sort of sensible
 1465    way.  In the event that some/all of the options are invalid we need to tell the user so that something can be done! */
 1466 
 1467 int main(int argc, char **argv)
 1468 {
 1469     int c;
 1470     char *tmp;
 1471     char *listfile = NULL;
 1472     FILE *msgfile;
 1473     struct device_info devinfo;
 1474     int i = 0, pos, ch;
 1475     int create = 0;
 1476     unsigned long long cblocks = 0;
 1477     int blocks_specified = 0;
 1478     struct timeval create_timeval;
 1479     long long conversion;
 1480 
 1481     enum {OPT_HELP=1000, OPT_INVARIANT, OPT_MBR, OPT_VARIANT, OPT_CODEPAGE, OPT_OFFSET};
 1482     const struct option long_options[] = {
 1483         {"codepage",  required_argument, NULL, OPT_CODEPAGE},
 1484         {"invariant", no_argument,       NULL, OPT_INVARIANT},
 1485         {"mbr",       optional_argument, NULL, OPT_MBR},
 1486         {"variant",   required_argument, NULL, OPT_VARIANT},
 1487         {"offset",    required_argument, NULL, OPT_OFFSET},
 1488         {"help",      no_argument,       NULL, OPT_HELP},
 1489         {0,}
 1490     };
 1491 
 1492     program_name = "mkfs.fat";
 1493     if (argc && *argv) {    /* What's the program name? */
 1494     char *p;
 1495     program_name = *argv;
 1496     if ((p = strrchr(program_name, '/')))
 1497         program_name = p + 1;
 1498     }
 1499 
 1500     if (gettimeofday(&create_timeval, NULL) == 0 && create_timeval.tv_sec != (time_t)-1)
 1501         create_time = create_timeval.tv_sec;
 1502     volume_id = generate_volume_id();
 1503     check_atari();
 1504 
 1505     printf("mkfs.fat " VERSION " (" VERSION_DATE ")\n");
 1506 
 1507     while ((c = getopt_long(argc, argv, "aAb:cCf:D:F:g:Ii:l:m:M:n:r:R:s:S:h:v",
 1508                     long_options, NULL)) != -1)
 1509     /* Scan the command line for options */
 1510     switch (c) {
 1511     case 'A':       /* toggle Atari format */
 1512         atari_format = !atari_format;
 1513         break;
 1514 
 1515     case 'a':       /* a : skip alignment */
 1516         align_structures = FALSE;
 1517         break;
 1518 
 1519     case 'b':       /* b : location of backup boot sector */
 1520         errno = 0;
 1521         conversion = strtol(optarg, &tmp, 0);
 1522         if (!*optarg || isspace(*optarg) || *tmp || errno || conversion < 0 || conversion > 0xffff) {
 1523         printf("Bad location for backup boot sector : %s\n", optarg);
 1524         usage(argv[0], 1);
 1525         }
 1526         backup_boot = conversion;
 1527         backup_boot_set = 1;
 1528         break;
 1529 
 1530     case 'c':       /* c : Check FS as we build it */
 1531         check = TRUE;
 1532         malloc_entire_fat = TRUE;   /* Need to be able to mark clusters bad */
 1533         break;
 1534 
 1535     case 'C':       /* C : Create a new file */
 1536         create = TRUE;
 1537         break;
 1538 
 1539     case 'D':       /* D : Choose Drive Number */
 1540         errno = 0;
 1541         conversion = strtol(optarg, &tmp, 0);
 1542         if (!*optarg || isspace(*optarg) || *tmp || errno || conversion < 0x00 || conversion > 0xFF) {
 1543         printf ("Bad drive number: %s\n", optarg);
 1544         usage(argv[0], 1);
 1545         }
 1546         drive_number_option = conversion;
 1547         drive_number_by_user=1;
 1548         break;
 1549 
 1550     case 'f':       /* f : Choose number of FATs */
 1551         errno = 0;
 1552         conversion = strtol(optarg, &tmp, 0);
 1553         if (!*optarg || isspace(*optarg) || *tmp || errno || conversion < 1 || conversion > 4) {
 1554         printf("Bad number of FATs : %s\n", optarg);
 1555         usage(argv[0], 1);
 1556         }
 1557         nr_fats = conversion;
 1558         break;
 1559 
 1560     case 'F':       /* F : Choose FAT size */
 1561         errno = 0;
 1562         conversion = strtol(optarg, &tmp, 0);
 1563         if (!*optarg || isspace(*optarg) || *tmp || errno || (conversion != 12 && conversion != 16 && conversion != 32)) {
 1564         printf("Bad FAT type : %s\n", optarg);
 1565         usage(argv[0], 1);
 1566         }
 1567         size_fat = conversion;
 1568         size_fat_by_user = 1;
 1569         break;
 1570 
 1571     case 'g':       /* g : geometry: heads and sectors per track */
 1572         errno = 0;
 1573         conversion = strtol(optarg, &tmp, 0);
 1574         if (!*optarg || isspace(*optarg) || tmp[0] != '/' || !tmp[1] || isspace(tmp[1]) || errno || conversion <= 0 || conversion > UINT16_MAX) {
 1575         printf("Bad format of geometry : %s\n", optarg);
 1576         usage(argv[0], 1);
 1577         }
 1578         bs.heads = htole16(conversion);
 1579         conversion = strtol(tmp+1, &tmp, 0);
 1580         if (*tmp || errno || conversion <= 0 || conversion > UINT16_MAX) {
 1581         printf("Bad format of geometry : %s\n", optarg);
 1582         usage(argv[0], 1);
 1583         }
 1584         bs.secs_track = htole16(conversion);
 1585         break;
 1586 
 1587     case 'h':       /* h : number of hidden sectors */
 1588         errno = 0;
 1589         conversion = strtoll(optarg, &tmp, 0);
 1590         if (!*optarg || isspace(*optarg) || *tmp || errno || conversion < 0 || conversion > UINT32_MAX) {
 1591         printf("Bad number of hidden sectors : %s\n", optarg);
 1592         usage(argv[0], 1);
 1593         }
 1594         hidden_sectors = conversion;
 1595         hidden_sectors_by_user = 1;
 1596         break;
 1597 
 1598     case 'I':
 1599         ignore_safety_checks = 1;
 1600         break;
 1601 
 1602     case 'i':       /* i : specify volume ID */
 1603         errno = 0;
 1604         conversion = strtoll(optarg, &tmp, 16);
 1605 
 1606         if (!*optarg || isspace(*optarg) || *tmp || conversion < 0) {
 1607         printf("Volume ID must be a hexadecimal number\n");
 1608         usage(argv[0], 1);
 1609         }
 1610         if (conversion > UINT32_MAX) {
 1611         printf("Volume ID does not fit in 32 bit\n");
 1612         usage(argv[0], 1);
 1613         }
 1614         if (errno) {
 1615         printf("Parsing volume ID failed (%s)\n", strerror(errno));
 1616         usage(argv[0], 1);
 1617         }
 1618 
 1619         volume_id = conversion;
 1620         break;
 1621 
 1622     case 'l':       /* l : Bad block filename */
 1623         listfile = optarg;
 1624         malloc_entire_fat = TRUE;   /* Need to be able to mark clusters bad */
 1625         break;
 1626 
 1627     case 'm':       /* m : Set boot message */
 1628         if (strcmp(optarg, "-")) {
 1629         msgfile = fopen(optarg, "r");
 1630         if (!msgfile)
 1631             perror(optarg);
 1632         } else
 1633         msgfile = stdin;
 1634 
 1635         if (msgfile) {
 1636         /* The boot code ends at offset 448 and needs a null terminator */
 1637         i = MESSAGE_OFFSET;
 1638         pos = 0;    /* We are at beginning of line */
 1639         do {
 1640             ch = getc(msgfile);
 1641             switch (ch) {
 1642             case '\r':  /* Ignore CRs */
 1643             case '\0':  /* and nulls */
 1644             break;
 1645 
 1646             case '\n':  /* LF -> CR+LF if necessary */
 1647             if (pos) {  /* If not at beginning of line */
 1648                 dummy_boot_code[i++] = '\r';
 1649                 pos = 0;
 1650             }
 1651             dummy_boot_code[i++] = '\n';
 1652             break;
 1653 
 1654             case '\t':  /* Expand tabs */
 1655             do {
 1656                 dummy_boot_code[i++] = ' ';
 1657                 pos++;
 1658             }
 1659             while (pos % 8 && i < BOOTCODE_SIZE - 1);
 1660             break;
 1661 
 1662             case EOF:
 1663             dummy_boot_code[i++] = '\0';    /* Null terminator */
 1664             break;
 1665 
 1666             default:
 1667             dummy_boot_code[i++] = ch;  /* Store character */
 1668             pos++;  /* Advance position */
 1669             break;
 1670             }
 1671         }
 1672         while (ch != EOF && i < BOOTCODE_SIZE - 1);
 1673 
 1674         /* Fill up with zeros */
 1675         while (i < BOOTCODE_SIZE - 1)
 1676             dummy_boot_code[i++] = '\0';
 1677         dummy_boot_code[BOOTCODE_SIZE - 1] = '\0';  /* Just in case */
 1678 
 1679         if (ch != EOF)
 1680             printf("Warning: message too long; truncated\n");
 1681 
 1682         if (msgfile != stdin)
 1683             fclose(msgfile);
 1684         }
 1685         break;
 1686 
 1687     case 'M':       /* M : FAT Media byte */
 1688         errno = 0;
 1689         conversion = strtol(optarg, &tmp, 0);
 1690         if (!*optarg || isspace(*optarg) || *tmp || errno) {
 1691         printf("Bad number for media descriptor : %s\n", optarg);
 1692         usage(argv[0], 1);
 1693         }
 1694         if (conversion != 0xf0 && (conversion < 0xf8 || conversion > 0xff)) {
 1695         printf("FAT Media byte must either be between 0xF8 and 0xFF or be 0xF0 : %s\n", optarg);
 1696         usage(argv[0], 1);
 1697         }
 1698         fat_media_byte = conversion;
 1699         break;
 1700 
 1701     case 'n':       /* n : Volume name */
 1702         volume_name = optarg;
 1703         break;
 1704 
 1705     case OPT_CODEPAGE:  /* --codepage : Code page */
 1706         errno = 0;
 1707         conversion = strtol(optarg, &tmp, 10);
 1708         if (!*optarg || isspace(*optarg) || *tmp || errno || conversion < 0 || conversion > INT_MAX) {
 1709         fprintf(stderr, "Invalid codepage : %s\n", optarg);
 1710         usage(argv[0], 1);
 1711         }
 1712         if (!set_dos_codepage(conversion))
 1713         usage(argv[0], 1);
 1714         break;
 1715 
 1716     case 'r':       /* r : Root directory entries */
 1717         errno = 0;
 1718         conversion = strtol(optarg, &tmp, 0);
 1719         if (!*optarg || isspace(*optarg) || *tmp || errno || conversion < 16 || conversion > 32768) {
 1720         printf("Bad number of root directory entries : %s\n", optarg);
 1721         usage(argv[0], 1);
 1722         }
 1723         root_dir_entries = conversion;
 1724         root_dir_entries_set = 1;
 1725         break;
 1726 
 1727     case 'R':       /* R : number of reserved sectors */
 1728         errno = 0;
 1729         conversion = strtol(optarg, &tmp, 0);
 1730         if (!*optarg || isspace(*optarg) || *tmp || errno || conversion < 1 || conversion > 0xffff) {
 1731         printf("Bad number of reserved sectors : %s\n", optarg);
 1732         usage(argv[0], 1);
 1733         }
 1734         reserved_sectors = conversion;
 1735         break;
 1736 
 1737     case 's':       /* s : Sectors per cluster */
 1738         errno = 0;
 1739         conversion = strtol(optarg, &tmp, 0);
 1740         if (!*optarg || isspace(*optarg) || *tmp || errno || (conversion != 1 && conversion != 2
 1741             && conversion != 4 && conversion != 8 && conversion != 16
 1742             && conversion != 32 && conversion != 64 && conversion != 128)) {
 1743         printf("Bad number of sectors per cluster : %s\n", optarg);
 1744         usage(argv[0], 1);
 1745         }
 1746         sectors_per_cluster = conversion;
 1747         break;
 1748 
 1749     case 'S':       /* S : Sector size */
 1750         errno = 0;
 1751         conversion = strtol(optarg, &tmp, 0);
 1752         if (!*optarg || isspace(*optarg) || *tmp || errno || (conversion != 512 && conversion != 1024 &&
 1753             conversion != 2048 && conversion != 4096 && conversion != 8192 &&
 1754             conversion != 16384 && conversion != 32768)) {
 1755         printf("Bad logical sector size : %s\n", optarg);
 1756         usage(argv[0], 1);
 1757         }
 1758         sector_size = conversion;
 1759         sector_size_set = 1;
 1760         break;
 1761 
 1762     case 'v':       /* v : Verbose execution */
 1763         ++verbose;
 1764         break;
 1765 
 1766     case OPT_HELP:
 1767         usage(argv[0], 0);
 1768         break;
 1769 
 1770     case OPT_INVARIANT:
 1771         invariant = 1;
 1772         volume_id = 0x1234abcd;
 1773         create_time = 1426325213;
 1774         break;
 1775 
 1776     case OPT_MBR:
 1777         if (!optarg || !strcasecmp(optarg, "y") || !strcasecmp(optarg, "yes"))
 1778             fill_mbr_partition = 1;
 1779         else if (!strcasecmp(optarg, "n") || !strcasecmp(optarg, "no"))
 1780             fill_mbr_partition = 0;
 1781         else if (!strcasecmp(optarg, "a") || !strcasecmp(optarg, "auto"))
 1782             fill_mbr_partition = -1;
 1783         else {
 1784             printf("Unknown option for --mbr: '%s'\n", optarg);
 1785             usage(argv[0], 1);
 1786         }
 1787         break;
 1788 
 1789     case OPT_VARIANT:
 1790         if (!strcasecmp(optarg, "standard")) {
 1791             atari_format = 0;
 1792         } else if (!strcasecmp(optarg, "atari")) {
 1793             atari_format = 1;
 1794         } else {
 1795             printf("Unknown variant: %s\n", optarg);
 1796             usage(argv[0], 1);
 1797         }
 1798         break;
 1799 
 1800     case OPT_OFFSET:
 1801         errno = 0;
 1802         conversion = strtoll(optarg, &tmp, 0);
 1803         if (!*optarg || isspace(*optarg) || *tmp || errno) {
 1804             printf("Bad number for offset : %s\n", optarg);
 1805             usage(argv[0], 1);
 1806         }
 1807 
 1808         if (conversion < 0 || conversion > OFF_MAX) {
 1809             printf("FAT offset must be between 0 and %lld: %s\n", (long long) OFF_MAX, optarg);
 1810             usage(argv[0], 1);
 1811         }
 1812 
 1813         part_sector = (off_t) conversion;
 1814         break;
 1815 
 1816     case '?':
 1817         usage(argv[0], 1);
 1818         exit(1);
 1819 
 1820     default:
 1821         fprintf(stderr,
 1822             "Internal error: getopt_long() returned unexpected value %d\n", c);
 1823         exit(2);
 1824     }
 1825 
 1826     if (!set_dos_codepage(-1))  /* set default codepage if none was given in command line */
 1827         exit(1);
 1828 
 1829     if (optind == argc || !argv[optind]) {
 1830     printf("No device specified.\n");
 1831     usage(argv[0], 1);
 1832     }
 1833 
 1834     device_name = argv[optind++];
 1835 
 1836     if (optind != argc) {
 1837     blocks_specified = 1;
 1838     errno = 0;
 1839     conversion = strtoll(argv[optind], &tmp, 0);
 1840 
 1841     if (!*argv[optind] || isspace(*argv[optind]) || *tmp || errno || conversion < 0) {
 1842         printf("Bad block count : %s\n", argv[optind]);
 1843         usage(argv[0], 1);
 1844     }
 1845     blocks = conversion;
 1846 
 1847     optind++;
 1848     }
 1849 
 1850     if (optind != argc) {
 1851     fprintf(stderr, "Excess arguments on command line\n");
 1852     usage(argv[0], 1);
 1853     }
 1854 
 1855     if (create && !blocks_specified)
 1856     die("Need intended size with -C.");
 1857 
 1858     if (check && listfile)  /* Auto and specified bad block handling are mutually */
 1859     die("-c and -l are incompatible");  /* exclusive of each other! */
 1860 
 1861     if (!create) {
 1862     check_mount(device_name);   /* Is the device already mounted? */
 1863     dev = open(device_name, O_EXCL | O_RDWR);   /* Is it a suitable device to build the FS on? */
 1864     if (dev < 0) {
 1865         fprintf(stderr, "%s: unable to open %s: %s\n", program_name,
 1866             device_name, strerror(errno));
 1867         exit(1);        /* The error exit code is 1! */
 1868     }
 1869     } else {
 1870     /* create the file */
 1871     dev = open(device_name, O_EXCL | O_RDWR | O_CREAT, 0666);
 1872     if (dev < 0) {
 1873         if (errno == EEXIST)
 1874         die("file %s already exists", device_name);
 1875         else
 1876         die("unable to create %s", device_name);
 1877     }
 1878     /* expand to desired size */
 1879     if (ftruncate(dev, part_sector * sector_size + blocks * BLOCK_SIZE)) /* TODO: check overflow */
 1880         die("unable to resize %s", device_name);
 1881     }
 1882 
 1883     if (get_device_info(dev, &devinfo) < 0)
 1884     die("error collecting information about %s", device_name);
 1885 
 1886     if (devinfo.size <= 0)
 1887     die("unable to discover size of %s", device_name);
 1888 
 1889     if (devinfo.sector_size > 0) {
 1890     if (sector_size_set) {
 1891         if (sector_size < devinfo.sector_size) {
 1892         sector_size = devinfo.sector_size;
 1893         fprintf(stderr,
 1894             "Warning: sector size was set to %d (minimal for this device)\n",
 1895             sector_size);
 1896         }
 1897     } else {
 1898         sector_size = devinfo.sector_size;
 1899         sector_size_set = 1;
 1900     }
 1901 
 1902         if (devinfo.size <= part_sector * sector_size)
 1903           die("The device %s size %llu is less then the offset %llu",
 1904               device_name, devinfo.size, (unsigned long long) part_sector * sector_size);
 1905     }
 1906 
 1907     if (sector_size > 4096)
 1908     fprintf(stderr,
 1909         "Warning: sector size %d > 4096 is non-standard, filesystem may not be usable\n",
 1910         sector_size);
 1911 
 1912     cblocks = (devinfo.size - part_sector * sector_size) / BLOCK_SIZE;
 1913     orphaned_sectors = ((devinfo.size - part_sector * sector_size) % BLOCK_SIZE) / sector_size;
 1914 
 1915     if (blocks_specified) {
 1916     if (blocks != cblocks) {
 1917         fprintf(stderr, "Warning: block count mismatch: ");
 1918         fprintf(stderr, "found %llu but assuming %llu.\n",
 1919             cblocks, blocks);
 1920     }
 1921     } else {
 1922     blocks = cblocks;
 1923     }
 1924 
 1925     /*
 1926      * Ignore any 'full' fixed disk devices, if -I is not given.
 1927      */
 1928     if (!ignore_safety_checks && devinfo.has_children > 0)
 1929     die("Partitions or virtual mappings on device '%s', not making filesystem (use -I to override)",
 1930         device_name);
 1931 
 1932     /*
 1933      * On non-removable fixed disk devices we need to create (fake) MBR partition
 1934      * table so disk would be correctly recognized on MS Windows systems.
 1935      */
 1936     if (fill_mbr_partition == -1) {
 1937         if (devinfo.type == TYPE_FIXED && devinfo.partition == 0)
 1938             fill_mbr_partition = 1;
 1939         else
 1940             fill_mbr_partition = 0;
 1941     }
 1942 
 1943     establish_params(&devinfo);
 1944     /* Establish the media parameters */
 1945 
 1946     setup_tables();     /* Establish the filesystem tables */
 1947 
 1948     if (check)          /* Determine any bad block locations and mark them */
 1949     check_blocks();
 1950     else if (listfile)
 1951     get_list_blocks(listfile);
 1952 
 1953     write_tables();     /* Write the filesystem tables away! */
 1954 
 1955     /* Let's make sure to sync the block device. Otherwise, if we operate on a loop device and people issue
 1956      * "losetup -d" right after this command finishes our in-flight writes might never hit the disk */
 1957     if (fsync(dev) < 0)
 1958         pdie("unable to synchronize %s", device_name);
 1959 
 1960     exit(0);            /* Terminate with no errors! */
 1961 }