blob: 158f59f6d28ed0a9c17e034b3dd565f802d603c3 [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 bigbiffca829c42013-01-28 08:14:25 -05005 Copyright (C) 2011-2013 Andrew Nayenko
bigbiff bigbiff9c754052013-01-09 09:09:08 -05006
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
19*/
20
21#include <unistd.h>
22#include "fat.h"
23#include "cbm.h"
24#include "uct.h"
25#include "rootdir.h"
26
27static off64_t fat_alignment(void)
28{
29 return (off64_t) 128 * get_sector_size();
30}
31
32static off64_t fat_size(void)
33{
34 return get_volume_size() / get_cluster_size() * sizeof(cluster_t);
35}
36
37static cluster_t fat_write_entry(struct exfat_dev* dev, cluster_t cluster,
38 cluster_t value)
39{
40 le32_t fat_entry = cpu_to_le32(value);
41 if (exfat_write(dev, &fat_entry, sizeof(fat_entry)) < 0)
42 {
43 exfat_error("failed to write FAT entry 0x%x", value);
44 return 0;
45 }
46 return cluster + 1;
47}
48
49static cluster_t fat_write_entries(struct exfat_dev* dev, cluster_t cluster,
50 uint64_t length)
51{
52 cluster_t end = cluster + DIV_ROUND_UP(length, get_cluster_size());
53
54 while (cluster < end - 1)
55 {
56 cluster = fat_write_entry(dev, cluster, cluster + 1);
57 if (cluster == 0)
58 return 0;
59 }
60 return fat_write_entry(dev, cluster, EXFAT_CLUSTER_END);
61}
62
63static int fat_write(struct exfat_dev* dev)
64{
65 cluster_t c = 0;
66
67 if (!(c = fat_write_entry(dev, c, 0xfffffff8))) /* media type */
68 return 1;
69 if (!(c = fat_write_entry(dev, c, 0xffffffff))) /* some weird constant */
70 return 1;
71 if (!(c = fat_write_entries(dev, c, cbm.get_size())))
72 return 1;
73 if (!(c = fat_write_entries(dev, c, uct.get_size())))
74 return 1;
75 if (!(c = fat_write_entries(dev, c, rootdir.get_size())))
76 return 1;
77
78 return 0;
79}
80
81const struct fs_object fat =
82{
83 .get_alignment = fat_alignment,
84 .get_size = fat_size,
85 .write = fat_write,
86};