blob: 25d37a2e846f6386274f729792d39df880b66493 [file] [log] [blame]
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001/*
2 fat.c (09.11.10)
3 File Allocation Table creation code.
4
bigbiff bigbiff61cdc022013-08-08 08:35:06 -04005 Free exFAT implementation.
bigbiff bigbiff2e33c5e2014-09-04 20:58:41 -04006 Copyright (C) 2011-2014 Andrew Nayenko
bigbiff bigbiff9c754052013-01-09 09:09:08 -05007
bigbiff bigbiff61cdc022013-08-08 08:35:06 -04008 This program is free software; you can redistribute it and/or modify
bigbiff bigbiff9c754052013-01-09 09:09:08 -05009 it under the terms of the GNU General Public License as published by
bigbiff bigbiff61cdc022013-08-08 08:35:06 -040010 the Free Software Foundation, either version 2 of the License, or
bigbiff bigbiff9c754052013-01-09 09:09:08 -050011 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
bigbiff bigbiff61cdc022013-08-08 08:35:06 -040018 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
bigbiff bigbiff9c754052013-01-09 09:09:08 -050021*/
22
23#include <unistd.h>
24#include "fat.h"
25#include "cbm.h"
26#include "uct.h"
27#include "rootdir.h"
28
29static off64_t fat_alignment(void)
30{
31 return (off64_t) 128 * get_sector_size();
32}
33
34static off64_t fat_size(void)
35{
36 return get_volume_size() / get_cluster_size() * sizeof(cluster_t);
37}
38
39static cluster_t fat_write_entry(struct exfat_dev* dev, cluster_t cluster,
40 cluster_t value)
41{
42 le32_t fat_entry = cpu_to_le32(value);
43 if (exfat_write(dev, &fat_entry, sizeof(fat_entry)) < 0)
44 {
45 exfat_error("failed to write FAT entry 0x%x", value);
46 return 0;
47 }
48 return cluster + 1;
49}
50
51static cluster_t fat_write_entries(struct exfat_dev* dev, cluster_t cluster,
52 uint64_t length)
53{
54 cluster_t end = cluster + DIV_ROUND_UP(length, get_cluster_size());
55
56 while (cluster < end - 1)
57 {
58 cluster = fat_write_entry(dev, cluster, cluster + 1);
59 if (cluster == 0)
60 return 0;
61 }
62 return fat_write_entry(dev, cluster, EXFAT_CLUSTER_END);
63}
64
65static int fat_write(struct exfat_dev* dev)
66{
67 cluster_t c = 0;
68
69 if (!(c = fat_write_entry(dev, c, 0xfffffff8))) /* media type */
70 return 1;
71 if (!(c = fat_write_entry(dev, c, 0xffffffff))) /* some weird constant */
72 return 1;
73 if (!(c = fat_write_entries(dev, c, cbm.get_size())))
74 return 1;
75 if (!(c = fat_write_entries(dev, c, uct.get_size())))
76 return 1;
77 if (!(c = fat_write_entries(dev, c, rootdir.get_size())))
78 return 1;
79
80 return 0;
81}
82
83const struct fs_object fat =
84{
85 .get_alignment = fat_alignment,
86 .get_size = fat_size,
87 .write = fat_write,
88};