]> git.sven.stormbind.net Git - sven/exfatprogs.git/blob - lib/libexfat.c
releasing package exfatprogs version 1.2.3-1
[sven/exfatprogs.git] / lib / libexfat.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2019 Namjae Jeon <linkinjeon@kernel.org>
4  */
5
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <sys/ioctl.h>
9 #include <sys/sysmacros.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <errno.h>
16 #include <wchar.h>
17 #include <limits.h>
18 #include <assert.h>
19
20 #include "exfat_ondisk.h"
21 #include "libexfat.h"
22 #include "version.h"
23 #include "exfat_fs.h"
24 #include "exfat_dir.h"
25
26 unsigned int print_level  = EXFAT_INFO;
27
28 void exfat_bitmap_set_range(struct exfat *exfat, char *bitmap,
29                             clus_t start_clus, clus_t count)
30 {
31         clus_t clus;
32
33         if (!exfat_heap_clus(exfat, start_clus) ||
34             !exfat_heap_clus(exfat, start_clus + count - 1))
35                 return;
36
37         clus = start_clus;
38         while (clus < start_clus + count) {
39                 exfat_bitmap_set(bitmap, clus);
40                 clus++;
41         }
42 }
43
44 static int exfat_bitmap_find_bit(struct exfat *exfat, char *bmap,
45                                  clus_t start_clu, clus_t *next,
46                                  int bit)
47 {
48         clus_t last_clu;
49
50         last_clu = le32_to_cpu(exfat->bs->bsx.clu_count) +
51                 EXFAT_FIRST_CLUSTER;
52         while (start_clu < last_clu) {
53                 if (!!exfat_bitmap_get(bmap, start_clu) == bit) {
54                         *next = start_clu;
55                         return 0;
56                 }
57                 start_clu++;
58         }
59         return 1;
60 }
61
62 int exfat_bitmap_find_zero(struct exfat *exfat, char *bmap,
63                            clus_t start_clu, clus_t *next)
64 {
65         return exfat_bitmap_find_bit(exfat, bmap,
66                                      start_clu, next, 0);
67 }
68
69 int exfat_bitmap_find_one(struct exfat *exfat, char *bmap,
70                           clus_t start_clu, clus_t *next)
71 {
72         return exfat_bitmap_find_bit(exfat, bmap,
73                                      start_clu, next, 1);
74 }
75
76 wchar_t exfat_bad_char(wchar_t w)
77 {
78         return (w < 0x0020)
79                 || (w == '*') || (w == '?') || (w == '<') || (w == '>')
80                 || (w == '|') || (w == '"') || (w == ':') || (w == '/')
81                 || (w == '\\');
82 }
83
84 void boot_calc_checksum(unsigned char *sector, unsigned short size,
85                 bool is_boot_sec, __le32 *checksum)
86 {
87         unsigned int index;
88
89         if (is_boot_sec) {
90                 for (index = 0; index < size; index++) {
91                         if ((index == 106) || (index == 107) || (index == 112))
92                                 continue;
93                         *checksum = ((*checksum & 1) ? 0x80000000 : 0) +
94                                 (*checksum >> 1) + sector[index];
95                 }
96         } else {
97                 for (index = 0; index < size; index++) {
98                         *checksum = ((*checksum & 1) ? 0x80000000 : 0) +
99                                 (*checksum >> 1) + sector[index];
100                 }
101         }
102 }
103
104 void show_version(void)
105 {
106         printf("exfatprogs version : %s\n", EXFAT_PROGS_VERSION);
107 }
108
109 static inline unsigned int sector_size_bits(unsigned int size)
110 {
111         unsigned int bits = 8;
112
113         do {
114                 bits++;
115                 size >>= 1;
116         } while (size > 256);
117
118         return bits;
119 }
120
121 static void exfat_set_default_cluster_size(struct exfat_blk_dev *bd,
122                 struct exfat_user_input *ui)
123 {
124         if (256 * MB >= bd->size)
125                 ui->cluster_size = 4 * KB;
126         else if (32 * GB >= bd->size)
127                 ui->cluster_size = 32 * KB;
128         else
129                 ui->cluster_size = 128 * KB;
130 }
131
132 void init_user_input(struct exfat_user_input *ui)
133 {
134         memset(ui, 0, sizeof(struct exfat_user_input));
135         ui->writeable = true;
136         ui->quick = true;
137 }
138
139 int exfat_get_blk_dev_info(struct exfat_user_input *ui,
140                 struct exfat_blk_dev *bd)
141 {
142         int fd, ret = -1;
143         off_t blk_dev_size;
144         struct stat st;
145         unsigned long long blk_dev_offset = 0;
146
147         fd = open(ui->dev_name, ui->writeable ? O_RDWR|O_EXCL : O_RDONLY);
148         if (fd < 0) {
149                 exfat_err("open failed : %s, %s\n", ui->dev_name,
150                         strerror(errno));
151                 return -1;
152         }
153         blk_dev_size = lseek(fd, 0, SEEK_END);
154         if (blk_dev_size <= 0) {
155                 exfat_err("invalid block device size(%s)\n",
156                         ui->dev_name);
157                 ret = blk_dev_size;
158                 close(fd);
159                 goto out;
160         }
161
162         if (fstat(fd, &st) == 0 && S_ISBLK(st.st_mode)) {
163                 char pathname[sizeof("/sys/dev/block/4294967295:4294967295/start")];
164                 FILE *fp;
165
166                 snprintf(pathname, sizeof(pathname), "/sys/dev/block/%u:%u/start",
167                         major(st.st_rdev), minor(st.st_rdev));
168                 fp = fopen(pathname, "r");
169                 if (fp != NULL) {
170                         if (fscanf(fp, "%llu", &blk_dev_offset) == 1) {
171                                 /*
172                                  * Linux kernel always reports partition offset
173                                  * in 512-byte units, regardless of sector size
174                                  */
175                                 blk_dev_offset <<= 9;
176                         }
177                         fclose(fp);
178                 }
179         }
180
181         bd->dev_fd = fd;
182         bd->offset = blk_dev_offset;
183         bd->size = blk_dev_size;
184         if (!ui->cluster_size)
185                 exfat_set_default_cluster_size(bd, ui);
186
187         if (!ui->boundary_align)
188                 ui->boundary_align = DEFAULT_BOUNDARY_ALIGNMENT;
189
190         if (ui->sector_size)
191                 bd->sector_size = ui->sector_size;
192         else if (ioctl(fd, BLKSSZGET, &bd->sector_size) < 0)
193                 bd->sector_size = DEFAULT_SECTOR_SIZE;
194         bd->sector_size_bits = sector_size_bits(bd->sector_size);
195         bd->num_sectors = blk_dev_size / bd->sector_size;
196         bd->num_clusters = blk_dev_size / ui->cluster_size;
197
198         exfat_debug("Block device name : %s\n", ui->dev_name);
199         exfat_debug("Block device offset : %llu\n", bd->offset);
200         exfat_debug("Block device size : %llu\n", bd->size);
201         exfat_debug("Block sector size : %u\n", bd->sector_size);
202         exfat_debug("Number of the sectors : %llu\n",
203                 bd->num_sectors);
204         exfat_debug("Number of the clusters : %u\n",
205                 bd->num_clusters);
206
207         ret = 0;
208         bd->dev_fd = fd;
209 out:
210         return ret;
211 }
212
213 ssize_t exfat_read(int fd, void *buf, size_t size, off_t offset)
214 {
215         return pread(fd, buf, size, offset);
216 }
217
218 ssize_t exfat_write(int fd, void *buf, size_t size, off_t offset)
219 {
220         return pwrite(fd, buf, size, offset);
221 }
222
223 ssize_t exfat_write_zero(int fd, size_t size, off_t offset)
224 {
225         const char zero_buf[4 * KB] = {0};
226
227         lseek(fd, offset, SEEK_SET);
228
229         while (size > 0) {
230                 int iter_size = MIN(size, sizeof(zero_buf));
231
232                 if (iter_size != write(fd, zero_buf, iter_size))
233                         return -EIO;
234
235                 size -= iter_size;
236         }
237
238         return 0;
239 }
240
241 size_t exfat_utf16_len(const __le16 *str, size_t max_size)
242 {
243         size_t i = 0;
244
245         while (le16_to_cpu(str[i]) && i < max_size)
246                 i++;
247         return i;
248 }
249
250 ssize_t exfat_utf16_enc(const char *in_str, __u16 *out_str, size_t out_size)
251 {
252         size_t mbs_len, out_len, i;
253         wchar_t *wcs;
254
255         mbs_len = mbstowcs(NULL, in_str, 0);
256         if (mbs_len == (size_t)-1) {
257                 if (errno == EINVAL || errno == EILSEQ)
258                         exfat_err("invalid character sequence in current locale\n");
259                 return -errno;
260         }
261
262         wcs = calloc(mbs_len+1, sizeof(wchar_t));
263         if (!wcs)
264                 return -ENOMEM;
265
266         /* First convert multibyte char* string to wchar_t* string */
267         if (mbstowcs(wcs, in_str, mbs_len+1) == (size_t)-1) {
268                 if (errno == EINVAL || errno == EILSEQ)
269                         exfat_err("invalid character sequence in current locale\n");
270                 free(wcs);
271                 return -errno;
272         }
273
274         /* Convert wchar_t* string (sequence of code points) to UTF-16 string */
275         for (i = 0, out_len = 0; i < mbs_len; i++) {
276                 if (2*(out_len+1) > out_size ||
277                     (wcs[i] >= 0x10000 && 2*(out_len+2) > out_size)) {
278                         exfat_err("input string is too long\n");
279                         free(wcs);
280                         return -E2BIG;
281                 }
282
283                 /* Encode code point above Plane0 as UTF-16 surrogate pair */
284                 if (wcs[i] >= 0x10000) {
285                         out_str[out_len++] =
286                           cpu_to_le16(((wcs[i] - 0x10000) >> 10) + 0xD800);
287                         wcs[i] = ((wcs[i] - 0x10000) & 0x3FF) + 0xDC00;
288                 }
289
290                 out_str[out_len++] = cpu_to_le16(wcs[i]);
291         }
292
293         free(wcs);
294         return 2*out_len;
295 }
296
297 ssize_t exfat_utf16_dec(const __u16 *in_str, size_t in_len,
298                         char *out_str, size_t out_size)
299 {
300         size_t wcs_len, out_len, c_len, i;
301         char c_str[MB_LEN_MAX];
302         wchar_t *wcs;
303         mbstate_t ps;
304         wchar_t w;
305
306         wcs = calloc(in_len/2+1, sizeof(wchar_t));
307         if (!wcs)
308                 return -ENOMEM;
309
310         /* First convert UTF-16 string to wchar_t* string */
311         for (i = 0, wcs_len = 0; i < in_len/2; i++, wcs_len++) {
312                 wcs[wcs_len] = le16_to_cpu(in_str[i]);
313                 /*
314                  * If wchar_t can store code point above Plane0
315                  * then unpack UTF-16 surrogate pair to code point
316                  */
317 #if WCHAR_MAX >= 0x10FFFF
318                 if (wcs[wcs_len] >= 0xD800 && wcs[wcs_len] <= 0xDBFF &&
319                     i+1 < in_len/2) {
320                         w = le16_to_cpu(in_str[i+1]);
321                         if (w >= 0xDC00 && w <= 0xDFFF) {
322                                 wcs[wcs_len] = 0x10000 +
323                                                ((wcs[wcs_len] - 0xD800) << 10) +
324                                                (w - 0xDC00);
325                                 i++;
326                         }
327                 }
328 #endif
329         }
330
331         memset(&ps, 0, sizeof(ps));
332
333         /* And then convert wchar_t* string to multibyte char* string */
334         for (i = 0, out_len = 0, c_len = 0; i <= wcs_len; i++) {
335                 c_len = wcrtomb(c_str, wcs[i], &ps);
336                 /*
337                  * If character is non-representable in current locale then
338                  * try to store it as Unicode replacement code point U+FFFD
339                  */
340                 if (c_len == (size_t)-1 && errno == EILSEQ)
341                         c_len = wcrtomb(c_str, 0xFFFD, &ps);
342                 /* If U+FFFD is also non-representable, try question mark */
343                 if (c_len == (size_t)-1 && errno == EILSEQ)
344                         c_len = wcrtomb(c_str, L'?', &ps);
345                 /* If also (7bit) question mark fails then we cannot do more */
346                 if (c_len == (size_t)-1) {
347                         exfat_err("invalid UTF-16 sequence\n");
348                         free(wcs);
349                         return -errno;
350                 }
351                 if (out_len+c_len > out_size) {
352                         exfat_err("input string is too long\n");
353                         free(wcs);
354                         return -E2BIG;
355                 }
356                 memcpy(out_str+out_len, c_str, c_len);
357                 out_len += c_len;
358         }
359
360         free(wcs);
361
362         /* Last iteration of above loop should have produced null byte */
363         if (c_len == 0 || out_str[out_len-1] != 0) {
364                 exfat_err("invalid UTF-16 sequence\n");
365                 return -errno;
366         }
367
368         return out_len-1;
369 }
370
371 off_t exfat_get_root_entry_offset(struct exfat_blk_dev *bd)
372 {
373         struct pbr *bs;
374         int nbytes;
375         unsigned int cluster_size, sector_size;
376         off_t root_clu_off;
377
378         bs = malloc(EXFAT_MAX_SECTOR_SIZE);
379         if (!bs) {
380                 exfat_err("failed to allocate memory\n");
381                 return -ENOMEM;
382         }
383
384         nbytes = exfat_read(bd->dev_fd, bs, EXFAT_MAX_SECTOR_SIZE, 0);
385         if (nbytes != EXFAT_MAX_SECTOR_SIZE) {
386                 exfat_err("boot sector read failed: %d\n", errno);
387                 free(bs);
388                 return -1;
389         }
390
391         if (memcmp(bs->bpb.oem_name, "EXFAT   ", 8) != 0) {
392                 exfat_err("Bad fs_name in boot sector, which does not describe a valid exfat filesystem\n");
393                 free(bs);
394                 return -1;
395         }
396
397         sector_size = 1 << bs->bsx.sect_size_bits;
398         cluster_size = (1 << bs->bsx.sect_per_clus_bits) * sector_size;
399         root_clu_off = le32_to_cpu(bs->bsx.clu_offset) * sector_size +
400                 (le32_to_cpu(bs->bsx.root_cluster) - EXFAT_RESERVED_CLUSTERS) *
401                 cluster_size;
402         free(bs);
403
404         return root_clu_off;
405 }
406
407 char *exfat_conv_volume_label(struct exfat_dentry *vol_entry)
408 {
409         char *volume_label;
410         __le16 disk_label[VOLUME_LABEL_MAX_LEN];
411
412         volume_label = malloc(VOLUME_LABEL_BUFFER_SIZE);
413         if (!volume_label)
414                 return NULL;
415
416         memcpy(disk_label, vol_entry->vol_label, sizeof(disk_label));
417         memset(volume_label, 0, VOLUME_LABEL_BUFFER_SIZE);
418         if (exfat_utf16_dec(disk_label, vol_entry->vol_char_cnt*2,
419                 volume_label, VOLUME_LABEL_BUFFER_SIZE) < 0) {
420                 exfat_err("failed to decode volume label\n");
421                 free(volume_label);
422                 return NULL;
423         }
424
425         return volume_label;
426 }
427
428 int exfat_read_volume_label(struct exfat *exfat)
429 {
430         struct exfat_dentry *dentry;
431         int err;
432         __le16 disk_label[VOLUME_LABEL_MAX_LEN];
433         struct exfat_lookup_filter filter = {
434                 .in.type = EXFAT_VOLUME,
435                 .in.dentry_count = 0,
436                 .in.filter = NULL,
437         };
438
439         err = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
440         if (err)
441                 return err;
442
443         dentry = filter.out.dentry_set;
444
445         if (dentry->vol_char_cnt == 0)
446                 goto out;
447
448         if (dentry->vol_char_cnt > VOLUME_LABEL_MAX_LEN) {
449                 exfat_err("too long label. %d\n", dentry->vol_char_cnt);
450                 err = -EINVAL;
451                 goto out;
452         }
453
454         memcpy(disk_label, dentry->vol_label, sizeof(disk_label));
455         if (exfat_utf16_dec(disk_label, dentry->vol_char_cnt*2,
456                 exfat->volume_label, sizeof(exfat->volume_label)) < 0) {
457                 exfat_err("failed to decode volume label\n");
458                 err = -EINVAL;
459                 goto out;
460         }
461
462         exfat_info("label: %s\n", exfat->volume_label);
463 out:
464         free(filter.out.dentry_set);
465         return err;
466 }
467
468 int exfat_set_volume_label(struct exfat *exfat, char *label_input)
469 {
470         struct exfat_dentry *pvol;
471         struct exfat_dentry_loc loc;
472         __u16 volume_label[VOLUME_LABEL_MAX_LEN];
473         int volume_label_len, dcount, err;
474
475         struct exfat_lookup_filter filter = {
476                 .in.type = EXFAT_VOLUME,
477                 .in.dentry_count = 1,
478                 .in.filter = NULL,
479         };
480
481         err = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
482         if (!err) {
483                 pvol = filter.out.dentry_set;
484                 dcount = filter.out.dentry_count;
485                 memset(pvol->vol_label, 0, sizeof(pvol->vol_label));
486         } else {
487                 pvol = calloc(1, sizeof(struct exfat_dentry));
488                 if (!pvol)
489                         return -ENOMEM;
490
491                 dcount = 1;
492                 pvol->type = EXFAT_VOLUME;
493         }
494
495         volume_label_len = exfat_utf16_enc(label_input,
496                         volume_label, sizeof(volume_label));
497         if (volume_label_len < 0) {
498                 exfat_err("failed to encode volume label\n");
499                 free(pvol);
500                 return -1;
501         }
502
503         memcpy(pvol->vol_label, volume_label, volume_label_len);
504         pvol->vol_char_cnt = volume_label_len/2;
505
506         loc.parent = exfat->root;
507         loc.file_offset = filter.out.file_offset;
508         loc.dev_offset = filter.out.dev_offset;
509         err = exfat_add_dentry_set(exfat, &loc, pvol, dcount, false);
510         exfat_info("new label: %s\n", label_input);
511
512         free(pvol);
513
514         return err;
515 }
516
517 static inline void print_guid(const char *msg, const __u8 *guid)
518 {
519         exfat_info("%s: %02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
520                         msg,
521                         guid[0], guid[1], guid[2], guid[3],
522                         guid[4], guid[5], guid[5], guid[7],
523                         guid[8], guid[9], guid[10], guid[11],
524                         guid[12], guid[13], guid[14], guid[15]);
525 }
526
527 static int set_guid(__u8 *guid, const char *input)
528 {
529         int i, j, zero_len = 0;
530         int len = strlen(input);
531
532         if (len != EXFAT_GUID_LEN * 2 && len != EXFAT_GUID_LEN * 2 + 4) {
533                 exfat_err("invalid format for volume guid\n");
534                 return -EINVAL;
535         }
536
537         for (i = 0, j = 0; i < len; i++) {
538                 unsigned char ch = input[i];
539
540                 if (ch >= '0' && ch <= '9')
541                         ch -= '0';
542                 else if (ch >= 'a' && ch <= 'f')
543                         ch -= 'a' - 0xA;
544                 else if (ch >= 'A' && ch <= 'F')
545                         ch -= 'A' - 0xA;
546                 else if (ch == '-' && len == EXFAT_GUID_LEN * 2 + 4 &&
547                          (i == 8 || i == 13 || i == 18 || i == 23))
548                         continue;
549                 else {
550                         exfat_err("invalid character '%c' for volume GUID\n", ch);
551                         return -EINVAL;
552                 }
553
554                 if (j & 1)
555                         guid[j >> 1] |= ch;
556                 else
557                         guid[j >> 1] = ch << 4;
558
559                 j++;
560
561                 if (ch == 0)
562                         zero_len++;
563         }
564
565         if (zero_len == EXFAT_GUID_LEN * 2) {
566                 exfat_err("%s is invalid for volume GUID\n", input);
567                 return -EINVAL;
568         }
569
570         return 0;
571 }
572
573 int exfat_read_volume_guid(struct exfat *exfat)
574 {
575         int err;
576         uint16_t checksum = 0;
577         struct exfat_dentry *dentry;
578         struct exfat_lookup_filter filter = {
579                 .in.type = EXFAT_GUID,
580                 .in.dentry_count = 1,
581                 .in.filter = NULL,
582         };
583
584         err = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
585         if (err)
586                 return err;
587
588         dentry = filter.out.dentry_set;
589         exfat_calc_dentry_checksum(dentry, &checksum, true);
590
591         if (cpu_to_le16(checksum) == dentry->dentry.guid.checksum)
592                 print_guid("GUID", dentry->dentry.guid.guid);
593         else
594                 exfat_info("GUID is corrupted, please delete it or set a new one\n");
595
596         free(dentry);
597
598         return err;
599 }
600
601 int __exfat_set_volume_guid(struct exfat_dentry *dentry, const char *guid)
602 {
603         int err;
604         uint16_t checksum = 0;
605
606         memset(dentry, 0, sizeof(*dentry));
607         dentry->type = EXFAT_GUID;
608
609         err = set_guid(dentry->dentry.guid.guid, guid);
610         if (err)
611                 return err;
612
613         exfat_calc_dentry_checksum(dentry, &checksum, true);
614         dentry->dentry.guid.checksum = cpu_to_le16(checksum);
615
616         return 0;
617 }
618
619 /*
620  * Create/Update/Delete GUID dentry in root directory
621  *
622  * create/update GUID if @guid is not NULL.
623  * delete GUID if @guid is NULL.
624  */
625 int exfat_set_volume_guid(struct exfat *exfat, const char *guid)
626 {
627         struct exfat_dentry *dentry;
628         struct exfat_dentry_loc loc;
629         int err;
630
631         struct exfat_lookup_filter filter = {
632                 .in.type = EXFAT_GUID,
633                 .in.dentry_count = 1,
634                 .in.filter = NULL,
635         };
636
637         err = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
638         if (!err) {
639                 /* GUID entry is found */
640                 dentry = filter.out.dentry_set;
641         } else {
642                 /* no GUID to delete */
643                 if (guid == NULL)
644                         return 0;
645
646                 dentry = calloc(1, sizeof(*dentry));
647                 if (!dentry)
648                         return -ENOMEM;
649         }
650
651         if (guid) {
652                 /* Set GUID */
653                 err = __exfat_set_volume_guid(dentry, guid);
654                 if (err)
655                         goto out;
656         } else {
657                 /* Delete GUID */
658                 dentry->type &= ~EXFAT_INVAL;
659         }
660
661         loc.parent = exfat->root;
662         loc.file_offset = filter.out.file_offset;
663         loc.dev_offset = filter.out.dev_offset;
664         err = exfat_add_dentry_set(exfat, &loc, dentry, 1, false);
665         if (!err) {
666                 if (guid)
667                         print_guid("new GUID", dentry->dentry.guid.guid);
668                 else
669                         exfat_info("GUID is deleted\n");
670         }
671
672 out:
673         free(dentry);
674
675         return err;
676 }
677
678 int exfat_read_sector(struct exfat_blk_dev *bd, void *buf, unsigned int sec_off)
679 {
680         int ret;
681         unsigned long long offset =
682                 (unsigned long long)sec_off * bd->sector_size;
683
684         ret = pread(bd->dev_fd, buf, bd->sector_size, offset);
685         if (ret < 0) {
686                 exfat_err("read failed, sec_off : %u\n", sec_off);
687                 return -1;
688         }
689         return 0;
690 }
691
692 int exfat_write_sector(struct exfat_blk_dev *bd, void *buf,
693                 unsigned int sec_off)
694 {
695         int bytes;
696         unsigned long long offset =
697                 (unsigned long long)sec_off * bd->sector_size;
698
699         bytes = pwrite(bd->dev_fd, buf, bd->sector_size, offset);
700         if (bytes != (int)bd->sector_size) {
701                 exfat_err("write failed, sec_off : %u, bytes : %d\n", sec_off,
702                         bytes);
703                 return -1;
704         }
705         return 0;
706 }
707
708 int exfat_write_checksum_sector(struct exfat_blk_dev *bd,
709                 unsigned int checksum, bool is_backup)
710 {
711         __le32 *checksum_buf;
712         int ret = 0;
713         unsigned int i;
714         unsigned int sec_idx = CHECKSUM_SEC_IDX;
715
716         checksum_buf = malloc(bd->sector_size);
717         if (!checksum_buf)
718                 return -1;
719
720         if (is_backup)
721                 sec_idx += BACKUP_BOOT_SEC_IDX;
722
723         for (i = 0; i < bd->sector_size / sizeof(int); i++)
724                 checksum_buf[i] = cpu_to_le32(checksum);
725
726         ret = exfat_write_sector(bd, checksum_buf, sec_idx);
727         if (ret) {
728                 exfat_err("checksum sector write failed\n");
729                 goto free;
730         }
731
732 free:
733         free(checksum_buf);
734         return ret;
735 }
736
737 int exfat_show_volume_serial(int fd)
738 {
739         struct pbr *ppbr;
740         int ret;
741
742         ppbr = malloc(EXFAT_MAX_SECTOR_SIZE);
743         if (!ppbr) {
744                 exfat_err("Cannot allocate pbr: out of memory\n");
745                 return -1;
746         }
747
748         /* read main boot sector */
749         ret = exfat_read(fd, (char *)ppbr, EXFAT_MAX_SECTOR_SIZE, 0);
750         if (ret < 0) {
751                 exfat_err("main boot sector read failed\n");
752                 ret = -1;
753                 goto free_ppbr;
754         }
755
756         if (memcmp(ppbr->bpb.oem_name, "EXFAT   ", 8) != 0) {
757                 exfat_err("Bad fs_name in boot sector, which does not describe a valid exfat filesystem\n");
758                 ret = -1;
759                 goto free_ppbr;
760         }
761
762         exfat_info("volume serial : 0x%x\n", ppbr->bsx.vol_serial);
763
764 free_ppbr:
765         free(ppbr);
766         return ret;
767 }
768
769 static int exfat_update_boot_checksum(struct exfat_blk_dev *bd, bool is_backup)
770 {
771         unsigned int checksum = 0;
772         int ret, sec_idx, backup_sec_idx = 0;
773         unsigned char *buf;
774
775         buf = malloc(bd->sector_size);
776         if (!buf) {
777                 exfat_err("Cannot allocate pbr: out of memory\n");
778                 return -1;
779         }
780
781         if (is_backup)
782                 backup_sec_idx = BACKUP_BOOT_SEC_IDX;
783
784         for (sec_idx = BOOT_SEC_IDX; sec_idx < CHECKSUM_SEC_IDX; sec_idx++) {
785                 bool is_boot_sec = false;
786
787                 ret = exfat_read_sector(bd, buf, sec_idx + backup_sec_idx);
788                 if (ret < 0) {
789                         exfat_err("sector(%d) read failed\n", sec_idx);
790                         ret = -1;
791                         goto free_buf;
792                 }
793
794                 if (sec_idx == BOOT_SEC_IDX)
795                         is_boot_sec = true;
796
797                 boot_calc_checksum(buf, bd->sector_size, is_boot_sec,
798                         &checksum);
799         }
800
801         ret = exfat_write_checksum_sector(bd, checksum, is_backup);
802
803 free_buf:
804         free(buf);
805
806         return ret;
807 }
808
809 int exfat_set_volume_serial(struct exfat_blk_dev *bd,
810                 struct exfat_user_input *ui)
811 {
812         int ret;
813         struct pbr *ppbr;
814
815         ppbr = malloc(EXFAT_MAX_SECTOR_SIZE);
816         if (!ppbr) {
817                 exfat_err("Cannot allocate pbr: out of memory\n");
818                 return -1;
819         }
820
821         /* read main boot sector */
822         ret = exfat_read(bd->dev_fd, (char *)ppbr, EXFAT_MAX_SECTOR_SIZE,
823                         BOOT_SEC_IDX);
824         if (ret < 0) {
825                 exfat_err("main boot sector read failed\n");
826                 ret = -1;
827                 goto free_ppbr;
828         }
829
830         if (memcmp(ppbr->bpb.oem_name, "EXFAT   ", 8) != 0) {
831                 exfat_err("Bad fs_name in boot sector, which does not describe a valid exfat filesystem\n");
832                 ret = -1;
833                 goto free_ppbr;
834         }
835
836         bd->sector_size = 1 << ppbr->bsx.sect_size_bits;
837         ppbr->bsx.vol_serial = cpu_to_le32(ui->volume_serial);
838
839         /* update main boot sector */
840         ret = exfat_write_sector(bd, (char *)ppbr, BOOT_SEC_IDX);
841         if (ret < 0) {
842                 exfat_err("main boot sector write failed\n");
843                 ret = -1;
844                 goto free_ppbr;
845         }
846
847         /* update backup boot sector */
848         ret = exfat_write_sector(bd, (char *)ppbr, BACKUP_BOOT_SEC_IDX);
849         if (ret < 0) {
850                 exfat_err("backup boot sector write failed\n");
851                 ret = -1;
852                 goto free_ppbr;
853         }
854
855         ret = exfat_update_boot_checksum(bd, 0);
856         if (ret < 0) {
857                 exfat_err("main checksum update failed\n");
858                 goto free_ppbr;
859         }
860
861         ret = exfat_update_boot_checksum(bd, 1);
862         if (ret < 0)
863                 exfat_err("backup checksum update failed\n");
864 free_ppbr:
865         free(ppbr);
866
867         exfat_info("New volume serial : 0x%x\n", ui->volume_serial);
868
869         return ret;
870 }
871
872 unsigned int exfat_clus_to_blk_dev_off(struct exfat_blk_dev *bd,
873                 unsigned int clu_off_sectnr, unsigned int clu)
874 {
875         return clu_off_sectnr * bd->sector_size +
876                 (clu - EXFAT_RESERVED_CLUSTERS) * bd->cluster_size;
877 }
878
879 int exfat_get_next_clus(struct exfat *exfat, clus_t clus, clus_t *next)
880 {
881         off_t offset;
882
883         *next = EXFAT_EOF_CLUSTER;
884
885         if (!exfat_heap_clus(exfat, clus))
886                 return -EINVAL;
887
888         offset = (off_t)le32_to_cpu(exfat->bs->bsx.fat_offset) <<
889                                 exfat->bs->bsx.sect_size_bits;
890         offset += sizeof(clus_t) * clus;
891
892         if (exfat_read(exfat->blk_dev->dev_fd, next, sizeof(*next), offset)
893                         != sizeof(*next))
894                 return -EIO;
895         *next = le32_to_cpu(*next);
896         return 0;
897 }
898
899 int exfat_get_inode_next_clus(struct exfat *exfat, struct exfat_inode *node,
900                               clus_t clus, clus_t *next)
901 {
902         *next = EXFAT_EOF_CLUSTER;
903
904         if (node->is_contiguous) {
905                 if (!exfat_heap_clus(exfat, clus))
906                         return -EINVAL;
907                 *next = clus + 1;
908                 return 0;
909         }
910
911         return exfat_get_next_clus(exfat, clus, next);
912 }
913
914 int exfat_set_fat(struct exfat *exfat, clus_t clus, clus_t next_clus)
915 {
916         off_t offset;
917
918         offset = le32_to_cpu(exfat->bs->bsx.fat_offset) <<
919                 exfat->bs->bsx.sect_size_bits;
920         offset += sizeof(clus_t) * clus;
921
922         if (exfat_write(exfat->blk_dev->dev_fd, &next_clus, sizeof(next_clus),
923                         offset) != sizeof(next_clus))
924                 return -EIO;
925         return 0;
926 }
927
928 off_t exfat_s2o(struct exfat *exfat, off_t sect)
929 {
930         return sect << exfat->bs->bsx.sect_size_bits;
931 }
932
933 off_t exfat_c2o(struct exfat *exfat, unsigned int clus)
934 {
935         assert(clus >= EXFAT_FIRST_CLUSTER);
936
937         return exfat_s2o(exfat, le32_to_cpu(exfat->bs->bsx.clu_offset) +
938                                 ((off_t)(clus - EXFAT_FIRST_CLUSTER) <<
939                                  exfat->bs->bsx.sect_per_clus_bits));
940 }
941
942 int exfat_o2c(struct exfat *exfat, off_t device_offset,
943               unsigned int *clu, unsigned int *offset)
944 {
945         off_t heap_offset;
946
947         heap_offset = exfat_s2o(exfat, le32_to_cpu(exfat->bs->bsx.clu_offset));
948         if (device_offset < heap_offset)
949                 return -ERANGE;
950
951         *clu = (unsigned int)((device_offset - heap_offset) /
952                               exfat->clus_size) + EXFAT_FIRST_CLUSTER;
953         if (!exfat_heap_clus(exfat, *clu))
954                 return -ERANGE;
955         *offset = (device_offset - heap_offset) % exfat->clus_size;
956         return 0;
957 }
958
959 bool exfat_heap_clus(struct exfat *exfat, clus_t clus)
960 {
961         return clus >= EXFAT_FIRST_CLUSTER &&
962                 (clus - EXFAT_FIRST_CLUSTER) < exfat->clus_count;
963 }
964
965 int exfat_root_clus_count(struct exfat *exfat)
966 {
967         struct exfat_inode *node = exfat->root;
968         clus_t clus, next;
969         int clus_count = 0;
970
971         if (!exfat_heap_clus(exfat, node->first_clus))
972                 return -EIO;
973
974         clus = node->first_clus;
975         do {
976                 if (exfat_bitmap_get(exfat->alloc_bitmap, clus))
977                         return -EINVAL;
978
979                 exfat_bitmap_set(exfat->alloc_bitmap, clus);
980
981                 if (exfat_get_inode_next_clus(exfat, node, clus, &next)) {
982                         exfat_err("ERROR: failed to read the fat entry of root");
983                         return -EIO;
984                 }
985
986                 if (next != EXFAT_EOF_CLUSTER && !exfat_heap_clus(exfat, next))
987                         return -EINVAL;
988
989                 clus = next;
990                 clus_count++;
991         } while (clus != EXFAT_EOF_CLUSTER);
992
993         node->size = clus_count * exfat->clus_size;
994         return 0;
995 }
996
997 int read_boot_sect(struct exfat_blk_dev *bdev, struct pbr **bs)
998 {
999         struct pbr *pbr;
1000         int err = 0;
1001         unsigned int sect_size, clu_size;
1002
1003         pbr = malloc(sizeof(struct pbr));
1004         if (!pbr) {
1005                 exfat_err("failed to allocate memory\n");
1006                 return -ENOMEM;
1007         }
1008
1009         if (exfat_read(bdev->dev_fd, pbr, sizeof(*pbr), 0) !=
1010             (ssize_t)sizeof(*pbr)) {
1011                 exfat_err("failed to read a boot sector\n");
1012                 err = -EIO;
1013                 goto err;
1014         }
1015
1016         err = -EINVAL;
1017         if (memcmp(pbr->bpb.oem_name, "EXFAT   ", 8) != 0) {
1018                 exfat_err("failed to find exfat file system\n");
1019                 goto err;
1020         }
1021
1022         sect_size = 1 << pbr->bsx.sect_size_bits;
1023         clu_size = 1 << (pbr->bsx.sect_size_bits +
1024                          pbr->bsx.sect_per_clus_bits);
1025
1026         if (sect_size < 512 || sect_size > 4 * KB) {
1027                 exfat_err("too small or big sector size: %d\n",
1028                           sect_size);
1029                 goto err;
1030         }
1031
1032         if (clu_size < sect_size || clu_size > 32 * MB) {
1033                 exfat_err("too small or big cluster size: %d\n",
1034                           clu_size);
1035                 goto err;
1036         }
1037
1038         *bs = pbr;
1039         return 0;
1040 err:
1041         free(pbr);
1042         return err;
1043 }
1044
1045 int exfat_parse_ulong(const char *s, unsigned long *out)
1046 {
1047         char *endptr;
1048
1049         *out = strtoul(s, &endptr, 0);
1050
1051         if (errno)
1052                 return -errno;
1053
1054         if (s == endptr || *endptr != '\0')
1055                 return -EINVAL;
1056
1057         return 0;
1058 }