OSDN Git Service

Generic I/O for directories: switch erase_entry().
[android-x86/external-exfat.git] / libexfat / node.c
1 /*
2         node.c (09.10.09)
3         exFAT file system implementation library.
4
5         Free exFAT implementation.
6         Copyright (C) 2010-2016  Andrew Nayenko
7
8         This program is free software; you can redistribute it and/or modify
9         it under the terms of the GNU General Public License as published by
10         the Free Software Foundation, either version 2 of the License, or
11         (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
18         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.
21 */
22
23 #include "exfat.h"
24 #include <errno.h>
25 #include <string.h>
26 #include <inttypes.h>
27
28 /* on-disk nodes iterator */
29 struct iterator
30 {
31         cluster_t cluster;
32         off_t offset;
33         char* chunk;
34 };
35
36 struct exfat_node* exfat_get_node(struct exfat_node* node)
37 {
38         /* if we switch to multi-threaded mode we will need atomic
39            increment here and atomic decrement in exfat_put_node() */
40         node->references++;
41         return node;
42 }
43
44 void exfat_put_node(struct exfat* ef, struct exfat_node* node)
45 {
46         char buffer[EXFAT_UTF8_NAME_BUFFER_MAX];
47
48         --node->references;
49         if (node->references < 0)
50         {
51                 exfat_get_name(node, buffer);
52                 exfat_bug("reference counter of '%s' is below zero", buffer);
53         }
54         else if (node->references == 0 && node != ef->root)
55         {
56                 if (node->is_dirty)
57                 {
58                         exfat_get_name(node, buffer);
59                         exfat_warn("dirty node '%s' with zero references", buffer);
60                 }
61         }
62 }
63
64 /**
65  * This function must be called on rmdir and unlink (after the last
66  * exfat_put_node()) to free clusters.
67  */
68 int exfat_cleanup_node(struct exfat* ef, struct exfat_node* node)
69 {
70         int rc = 0;
71
72         if (node->references != 0)
73                 exfat_bug("unable to cleanup a node with %d references",
74                                 node->references);
75
76         if (node->is_unlinked)
77         {
78                 /* free all clusters and node structure itself */
79                 rc = exfat_truncate(ef, node, 0, true);
80                 /* free the node even in case of error or its memory will be lost */
81                 free(node);
82         }
83         return rc;
84 }
85
86 /**
87  * Cluster + offset from the beginning of the directory to absolute offset.
88  */
89 static off_t co2o(struct exfat* ef, cluster_t cluster, off_t offset)
90 {
91         return exfat_c2o(ef, cluster) + offset % CLUSTER_SIZE(*ef->sb);
92 }
93
94 static int opendir(struct exfat* ef, const struct exfat_node* dir,
95                 struct iterator* it)
96 {
97         char buffer[EXFAT_UTF8_NAME_BUFFER_MAX];
98
99         if (!(dir->attrib & EXFAT_ATTRIB_DIR))
100         {
101                 exfat_get_name(dir, buffer);
102                 exfat_bug("'%s' is not a directory", buffer);
103         }
104         if (CLUSTER_INVALID(dir->start_cluster))
105         {
106                 exfat_get_name(dir, buffer);
107                 exfat_error("'%s' directory starts with invalid cluster %#x", buffer,
108                                 dir->start_cluster);
109                 return -EIO;
110         }
111         it->cluster = dir->start_cluster;
112         it->offset = 0;
113         it->chunk = malloc(CLUSTER_SIZE(*ef->sb));
114         if (it->chunk == NULL)
115         {
116                 exfat_error("failed to allocate memory for directory cluster");
117                 return -ENOMEM;
118         }
119         if (exfat_pread(ef->dev, it->chunk, CLUSTER_SIZE(*ef->sb),
120                         exfat_c2o(ef, it->cluster)) < 0)
121         {
122                 free(it->chunk);
123                 exfat_get_name(dir, buffer);
124                 exfat_error("failed to read '%s' directory cluster %#x", buffer,
125                                 it->cluster);
126                 return -EIO;
127         }
128         return 0;
129 }
130
131 static void closedir(struct iterator* it)
132 {
133         it->cluster = 0;
134         it->offset = 0;
135         free(it->chunk);
136         it->chunk = NULL;
137 }
138
139 static bool fetch_next_entry(struct exfat* ef, const struct exfat_node* parent,
140                 struct iterator* it)
141 {
142         /* move iterator to the next entry in the directory */
143         it->offset += sizeof(struct exfat_entry);
144         /* fetch the next cluster if needed */
145         if ((it->offset & (CLUSTER_SIZE(*ef->sb) - 1)) == 0)
146         {
147                 /* reached the end of directory; the caller should check this
148                    condition too */
149                 if (it->offset >= parent->size)
150                         return true;
151                 it->cluster = exfat_next_cluster(ef, parent, it->cluster);
152                 if (CLUSTER_INVALID(it->cluster))
153                 {
154                         exfat_error("invalid cluster 0x%x while reading directory",
155                                         it->cluster);
156                         return false;
157                 }
158                 if (exfat_pread(ef->dev, it->chunk, CLUSTER_SIZE(*ef->sb),
159                                 exfat_c2o(ef, it->cluster)) < 0)
160                 {
161                         exfat_error("failed to read the next directory cluster %#x",
162                                         it->cluster);
163                         return false;
164                 }
165         }
166         return true;
167 }
168
169 static int read_entries(struct exfat* ef, struct exfat_node* dir,
170                 struct exfat_entry* entries, int n, off_t offset)
171 {
172         ssize_t size;
173
174         if (!(dir->attrib & EXFAT_ATTRIB_DIR))
175                 exfat_bug("attempted to read entries from a file");
176
177         size = exfat_generic_pread(ef, dir, entries,
178                         sizeof(struct exfat_entry[n]), offset);
179         if (size == sizeof(struct exfat_entry[n]))
180                 return 0; /* success */
181         if (size == 0)
182                 return -ENOENT;
183         if (size < 0)
184                 return -EIO;
185         exfat_error("read %zd bytes instead of %zu bytes", size,
186                         sizeof(struct exfat_entry[n]));
187         return -EIO;
188 }
189
190 static int write_entries(struct exfat* ef, struct exfat_node* dir,
191                 const struct exfat_entry* entries, int n, off_t offset)
192 {
193         ssize_t size;
194
195         if (!(dir->attrib & EXFAT_ATTRIB_DIR))
196                 exfat_bug("attempted to write entries into a file");
197
198         size = exfat_generic_pwrite(ef, dir, entries,
199                         sizeof(struct exfat_entry[n]), offset);
200         if (size == sizeof(struct exfat_entry[n]))
201                 return 0; /* success */
202         if (size < 0)
203                 return -EIO;
204         exfat_error("wrote %zd bytes instead of %zu bytes", size,
205                         sizeof(struct exfat_entry[n]));
206         return -EIO;
207 }
208
209 static struct exfat_node* allocate_node(void)
210 {
211         struct exfat_node* node = malloc(sizeof(struct exfat_node));
212         if (node == NULL)
213         {
214                 exfat_error("failed to allocate node");
215                 return NULL;
216         }
217         memset(node, 0, sizeof(struct exfat_node));
218         return node;
219 }
220
221 static void init_node_meta1(struct exfat_node* node,
222                 const struct exfat_entry_meta1* meta1)
223 {
224         node->attrib = le16_to_cpu(meta1->attrib);
225         node->continuations = meta1->continuations;
226         node->mtime = exfat_exfat2unix(meta1->mdate, meta1->mtime,
227                         meta1->mtime_cs);
228         /* there is no centiseconds field for atime */
229         node->atime = exfat_exfat2unix(meta1->adate, meta1->atime, 0);
230 }
231
232 static void init_node_meta2(struct exfat_node* node,
233                 const struct exfat_entry_meta2* meta2)
234 {
235         node->size = le64_to_cpu(meta2->size);
236         node->start_cluster = le32_to_cpu(meta2->start_cluster);
237         node->fptr_cluster = node->start_cluster;
238         node->is_contiguous = ((meta2->flags & EXFAT_FLAG_CONTIGUOUS) != 0);
239 }
240
241 static const struct exfat_entry* get_entry_ptr(const struct exfat* ef,
242                 const struct iterator* it)
243 {
244         return (const struct exfat_entry*)
245                         (it->chunk + it->offset % CLUSTER_SIZE(*ef->sb));
246 }
247
248 static bool check_node(const struct exfat_node* node, uint16_t actual_checksum,
249                 uint16_t reference_checksum, uint64_t valid_size, int cluster_size)
250 {
251         char buffer[EXFAT_UTF8_NAME_BUFFER_MAX];
252         bool ret = true;
253
254         /*
255            Validate checksum first. If it's invalid all other fields probably
256            contain just garbage.
257         */
258         if (actual_checksum != reference_checksum)
259         {
260                 exfat_get_name(node, buffer);
261                 exfat_error("'%s' has invalid checksum (%#hx != %#hx)", buffer,
262                                 actual_checksum, reference_checksum);
263                 ret = false;
264         }
265
266         /*
267            exFAT does not support sparse files but allows files with uninitialized
268            clusters. For such files valid_size means initialized data size and
269            cannot be greater than file size. See SetFileValidData() function
270            description in MSDN.
271         */
272         if (valid_size > node->size)
273         {
274                 exfat_get_name(node, buffer);
275                 exfat_error("'%s' has valid size (%"PRIu64") greater than size "
276                                 "(%"PRIu64")", buffer, valid_size, node->size);
277                 ret = false;
278         }
279
280         /*
281            Empty file must have zero start cluster. Non-empty file must start
282            with a valid cluster. Directories cannot be empty (i.e. must always
283            have a valid start cluster), but we will check this later in opendir()
284            to give user a chance to read current directory.
285         */
286         if (node->size == 0 && node->start_cluster != EXFAT_CLUSTER_FREE)
287         {
288                 exfat_get_name(node, buffer);
289                 exfat_error("'%s' is empty but start cluster is %#x", buffer,
290                                 node->start_cluster);
291                 ret = false;
292         }
293         if (node->size > 0 && CLUSTER_INVALID(node->start_cluster))
294         {
295                 exfat_get_name(node, buffer);
296                 exfat_error("'%s' points to invalid cluster %#x", buffer,
297                                 node->start_cluster);
298                 ret = false;
299         }
300
301         /* Empty file or directory must be marked as non-contiguous. */
302         if (node->size == 0 && node->is_contiguous)
303         {
304                 exfat_get_name(node, buffer);
305                 exfat_error("'%s' is empty but marked as contiguous (%#hx)", buffer,
306                                 node->attrib);
307                 ret = false;
308         }
309
310         /* Directory size must be aligned on at cluster boundary. */
311         if ((node->attrib & EXFAT_ATTRIB_DIR) && node->size % cluster_size != 0)
312         {
313                 exfat_get_name(node, buffer);
314                 exfat_error("'%s' directory size %"PRIu64" is not divisible by %d", buffer,
315                                 node->size, cluster_size);
316                 ret = false;
317         }
318
319         return ret;
320 }
321
322 static void decompress_upcase(uint16_t* output, const le16_t* source,
323                 size_t size)
324 {
325         size_t si;
326         size_t oi;
327
328         for (oi = 0; oi < EXFAT_UPCASE_CHARS; oi++)
329                 output[oi] = oi;
330
331         for (si = 0, oi = 0; si < size && oi < EXFAT_UPCASE_CHARS; si++)
332         {
333                 uint16_t ch = le16_to_cpu(source[si]);
334
335                 if (ch == 0xffff && si + 1 < size)      /* indicates a run */
336                         oi += le16_to_cpu(source[++si]);
337                 else
338                         output[oi++] = ch;
339         }
340 }
341
342 /*
343  * Reads one entry in directory at position pointed by iterator and fills
344  * node structure.
345  */
346 static int readdir(struct exfat* ef, const struct exfat_node* parent,
347                 struct exfat_node** node, struct iterator* it)
348 {
349         int rc = -EIO;
350         const struct exfat_entry* entry;
351         const struct exfat_entry_meta1* meta1;
352         const struct exfat_entry_meta2* meta2;
353         const struct exfat_entry_name* file_name;
354         const struct exfat_entry_upcase* upcase;
355         const struct exfat_entry_bitmap* bitmap;
356         const struct exfat_entry_label* label;
357         uint8_t continuations = 0;
358         le16_t* namep = NULL;
359         uint16_t reference_checksum = 0;
360         uint16_t actual_checksum = 0;
361         uint64_t valid_size = 0;
362         uint64_t upcase_size = 0;
363         le16_t* upcase_comp = NULL;
364
365         *node = NULL;
366
367         for (;;)
368         {
369                 if (it->offset >= parent->size)
370                 {
371                         if (continuations != 0)
372                         {
373                                 exfat_error("expected %hhu continuations", continuations);
374                                 goto error;
375                         }
376                         return -ENOENT; /* that's OK, means end of directory */
377                 }
378
379                 entry = get_entry_ptr(ef, it);
380                 switch (entry->type)
381                 {
382                 case EXFAT_ENTRY_FILE:
383                         if (continuations != 0)
384                         {
385                                 exfat_error("expected %hhu continuations before new entry",
386                                                 continuations);
387                                 goto error;
388                         }
389                         meta1 = (const struct exfat_entry_meta1*) entry;
390                         continuations = meta1->continuations;
391                         /* each file entry must have at least 2 continuations:
392                            info and name */
393                         if (continuations < 2)
394                         {
395                                 exfat_error("too few continuations (%hhu)", continuations);
396                                 goto error;
397                         }
398                         if (continuations > 1 +
399                                         DIV_ROUND_UP(EXFAT_NAME_MAX, EXFAT_ENAME_MAX))
400                         {
401                                 exfat_error("too many continuations (%hhu)", continuations);
402                                 goto error;
403                         }
404                         reference_checksum = le16_to_cpu(meta1->checksum);
405                         actual_checksum = exfat_start_checksum(meta1);
406                         *node = allocate_node();
407                         if (*node == NULL)
408                         {
409                                 rc = -ENOMEM;
410                                 goto error;
411                         }
412                         /* new node has zero reference counter */
413                         (*node)->entry_cluster = it->cluster;
414                         (*node)->entry_offset = it->offset;
415                         init_node_meta1(*node, meta1);
416                         namep = (*node)->name;
417                         break;
418
419                 case EXFAT_ENTRY_FILE_INFO:
420                         if (continuations < 2)
421                         {
422                                 exfat_error("unexpected continuation (%hhu)",
423                                                 continuations);
424                                 goto error;
425                         }
426                         meta2 = (const struct exfat_entry_meta2*) entry;
427                         if (meta2->flags & ~(EXFAT_FLAG_ALWAYS1 | EXFAT_FLAG_CONTIGUOUS))
428                         {
429                                 exfat_error("unknown flags in meta2 (0x%hhx)", meta2->flags);
430                                 goto error;
431                         }
432                         init_node_meta2(*node, meta2);
433                         actual_checksum = exfat_add_checksum(entry, actual_checksum);
434                         valid_size = le64_to_cpu(meta2->valid_size);
435                         --continuations;
436                         break;
437
438                 case EXFAT_ENTRY_FILE_NAME:
439                         if (continuations == 0)
440                         {
441                                 exfat_error("unexpected continuation");
442                                 goto error;
443                         }
444                         file_name = (const struct exfat_entry_name*) entry;
445                         actual_checksum = exfat_add_checksum(entry, actual_checksum);
446
447                         memcpy(namep, file_name->name,
448                                         MIN(EXFAT_ENAME_MAX,
449                                                 ((*node)->name + EXFAT_NAME_MAX - namep)) *
450                                         sizeof(le16_t));
451                         namep += EXFAT_ENAME_MAX;
452                         if (--continuations == 0)
453                         {
454                                 if (!check_node(*node, actual_checksum, reference_checksum,
455                                                 valid_size, CLUSTER_SIZE(*ef->sb)))
456                                         goto error;
457                                 if (!fetch_next_entry(ef, parent, it))
458                                         goto error;
459                                 return 0; /* entry completed */
460                         }
461                         break;
462
463                 case EXFAT_ENTRY_UPCASE:
464                         if (ef->upcase != NULL)
465                                 break;
466                         upcase = (const struct exfat_entry_upcase*) entry;
467                         if (CLUSTER_INVALID(le32_to_cpu(upcase->start_cluster)))
468                         {
469                                 exfat_error("invalid cluster 0x%x in upcase table",
470                                                 le32_to_cpu(upcase->start_cluster));
471                                 goto error;
472                         }
473                         upcase_size = le64_to_cpu(upcase->size);
474                         if (upcase_size == 0 ||
475                                 upcase_size > EXFAT_UPCASE_CHARS * sizeof(uint16_t) ||
476                                 upcase_size % sizeof(uint16_t) != 0)
477                         {
478                                 exfat_error("bad upcase table size (%"PRIu64" bytes)",
479                                                 upcase_size);
480                                 goto error;
481                         }
482                         upcase_comp = malloc(upcase_size);
483                         if (upcase_comp == NULL)
484                         {
485                                 exfat_error("failed to allocate upcase table (%"PRIu64" bytes)",
486                                                 upcase_size);
487                                 rc = -ENOMEM;
488                                 goto error;
489                         }
490
491                         /* read compressed upcase table */
492                         if (exfat_pread(ef->dev, upcase_comp, upcase_size,
493                                         exfat_c2o(ef, le32_to_cpu(upcase->start_cluster))) < 0)
494                         {
495                                 free(upcase_comp);
496                                 exfat_error("failed to read upper case table "
497                                                 "(%"PRIu64" bytes starting at cluster %#x)",
498                                                 upcase_size,
499                                                 le32_to_cpu(upcase->start_cluster));
500                                 goto error;
501                         }
502
503                         /* decompress upcase table */
504                         ef->upcase = calloc(EXFAT_UPCASE_CHARS, sizeof(uint16_t));
505                         if (ef->upcase == NULL)
506                         {
507                                 free(upcase_comp);
508                                 exfat_error("failed to allocate decompressed upcase table");
509                                 rc = -ENOMEM;
510                                 goto error;
511                         }
512                         decompress_upcase(ef->upcase, upcase_comp,
513                                         upcase_size / sizeof(uint16_t));
514                         free(upcase_comp);
515                         break;
516
517                 case EXFAT_ENTRY_BITMAP:
518                         bitmap = (const struct exfat_entry_bitmap*) entry;
519                         ef->cmap.start_cluster = le32_to_cpu(bitmap->start_cluster);
520                         if (CLUSTER_INVALID(ef->cmap.start_cluster))
521                         {
522                                 exfat_error("invalid cluster 0x%x in clusters bitmap",
523                                                 ef->cmap.start_cluster);
524                                 goto error;
525                         }
526                         ef->cmap.size = le32_to_cpu(ef->sb->cluster_count) -
527                                 EXFAT_FIRST_DATA_CLUSTER;
528                         if (le64_to_cpu(bitmap->size) < DIV_ROUND_UP(ef->cmap.size, 8))
529                         {
530                                 exfat_error("invalid clusters bitmap size: %"PRIu64
531                                                 " (expected at least %u)",
532                                                 le64_to_cpu(bitmap->size),
533                                                 DIV_ROUND_UP(ef->cmap.size, 8));
534                                 goto error;
535                         }
536                         /* FIXME bitmap can be rather big, up to 512 MB */
537                         ef->cmap.chunk_size = ef->cmap.size;
538                         ef->cmap.chunk = malloc(BMAP_SIZE(ef->cmap.chunk_size));
539                         if (ef->cmap.chunk == NULL)
540                         {
541                                 exfat_error("failed to allocate clusters bitmap chunk "
542                                                 "(%"PRIu64" bytes)", le64_to_cpu(bitmap->size));
543                                 rc = -ENOMEM;
544                                 goto error;
545                         }
546
547                         if (exfat_pread(ef->dev, ef->cmap.chunk,
548                                         BMAP_SIZE(ef->cmap.chunk_size),
549                                         exfat_c2o(ef, ef->cmap.start_cluster)) < 0)
550                         {
551                                 exfat_error("failed to read clusters bitmap "
552                                                 "(%"PRIu64" bytes starting at cluster %#x)",
553                                                 le64_to_cpu(bitmap->size), ef->cmap.start_cluster);
554                                 goto error;
555                         }
556                         break;
557
558                 case EXFAT_ENTRY_LABEL:
559                         label = (const struct exfat_entry_label*) entry;
560                         if (label->length > EXFAT_ENAME_MAX)
561                         {
562                                 exfat_error("too long label (%hhu chars)", label->length);
563                                 goto error;
564                         }
565                         if (utf16_to_utf8(ef->label, label->name,
566                                                 sizeof(ef->label), EXFAT_ENAME_MAX) != 0)
567                                 goto error;
568                         break;
569
570                 default:
571                         if (!(entry->type & EXFAT_ENTRY_VALID))
572                                 break; /* deleted entry, ignore it */
573                         if (!(entry->type & EXFAT_ENTRY_OPTIONAL))
574                         {
575                                 exfat_error("unknown entry type %#hhx", entry->type);
576                                 goto error;
577                         }
578                         /* optional entry, warn and skip */
579                         exfat_warn("unknown entry type %#hhx", entry->type);
580                         if (continuations == 0)
581                         {
582                                 exfat_error("unexpected continuation");
583                                 goto error;
584                         }
585                         --continuations;
586                         break;
587                 }
588
589                 if (!fetch_next_entry(ef, parent, it))
590                         goto error;
591         }
592         /* we never reach here */
593
594 error:
595         free(*node);
596         *node = NULL;
597         return rc;
598 }
599
600 int exfat_cache_directory(struct exfat* ef, struct exfat_node* dir)
601 {
602         struct iterator it;
603         int rc;
604         struct exfat_node* node;
605         struct exfat_node* current = NULL;
606
607         if (dir->is_cached)
608                 return 0; /* already cached */
609
610         rc = opendir(ef, dir, &it);
611         if (rc != 0)
612                 return rc;
613         while ((rc = readdir(ef, dir, &node, &it)) == 0)
614         {
615                 node->parent = dir;
616                 if (current != NULL)
617                 {
618                         current->next = node;
619                         node->prev = current;
620                 }
621                 else
622                         dir->child = node;
623
624                 current = node;
625         }
626         closedir(&it);
627
628         if (rc != -ENOENT)
629         {
630                 /* rollback */
631                 for (current = dir->child; current; current = node)
632                 {
633                         node = current->next;
634                         free(current);
635                 }
636                 dir->child = NULL;
637                 return rc;
638         }
639
640         dir->is_cached = true;
641         return 0;
642 }
643
644 static void tree_attach(struct exfat_node* dir, struct exfat_node* node)
645 {
646         node->parent = dir;
647         if (dir->child)
648         {
649                 dir->child->prev = node;
650                 node->next = dir->child;
651         }
652         dir->child = node;
653 }
654
655 static void tree_detach(struct exfat_node* node)
656 {
657         if (node->prev)
658                 node->prev->next = node->next;
659         else /* this is the first node in the list */
660                 node->parent->child = node->next;
661         if (node->next)
662                 node->next->prev = node->prev;
663         node->parent = NULL;
664         node->prev = NULL;
665         node->next = NULL;
666 }
667
668 static void reset_cache(struct exfat* ef, struct exfat_node* node)
669 {
670         char buffer[EXFAT_UTF8_NAME_BUFFER_MAX];
671
672         while (node->child)
673         {
674                 struct exfat_node* p = node->child;
675                 reset_cache(ef, p);
676                 tree_detach(p);
677                 free(p);
678         }
679         node->is_cached = false;
680         if (node->references != 0)
681         {
682                 exfat_get_name(node, buffer);
683                 exfat_warn("non-zero reference counter (%d) for '%s'",
684                                 node->references, buffer);
685         }
686         if (node != ef->root && node->is_dirty)
687         {
688                 exfat_get_name(node, buffer);
689                 exfat_bug("node '%s' is dirty", buffer);
690         }
691         while (node->references)
692                 exfat_put_node(ef, node);
693 }
694
695 void exfat_reset_cache(struct exfat* ef)
696 {
697         reset_cache(ef, ef->root);
698 }
699
700 static bool next_entry(struct exfat* ef, const struct exfat_node* parent,
701                 cluster_t* cluster, off_t* offset)
702 {
703         *offset += sizeof(struct exfat_entry);
704         if (*offset % CLUSTER_SIZE(*ef->sb) == 0)
705         {
706                 *cluster = exfat_next_cluster(ef, parent, *cluster);
707                 if (CLUSTER_INVALID(*cluster))
708                 {
709                         exfat_error("invalid cluster %#x while getting next entry",
710                                         *cluster);
711                         return false;
712                 }
713         }
714         return true;
715 }
716
717 int exfat_flush_node(struct exfat* ef, struct exfat_node* node)
718 {
719         cluster_t cluster;
720         off_t offset;
721         off_t meta1_offset, meta2_offset;
722         struct exfat_entry_meta1 meta1;
723         struct exfat_entry_meta2 meta2;
724
725         if (!node->is_dirty)
726                 return 0; /* no need to flush */
727
728         if (ef->ro)
729                 exfat_bug("unable to flush node to read-only FS");
730
731         if (node->parent == NULL)
732                 return 0; /* do not flush unlinked node */
733
734         cluster = node->entry_cluster;
735         offset = node->entry_offset;
736         meta1_offset = co2o(ef, cluster, offset);
737         if (!next_entry(ef, node->parent, &cluster, &offset))
738                 return -EIO;
739         meta2_offset = co2o(ef, cluster, offset);
740
741         if (exfat_pread(ef->dev, &meta1, sizeof(meta1), meta1_offset) < 0)
742         {
743                 exfat_error("failed to read meta1 entry on flush");
744                 return -EIO;
745         }
746         if (meta1.type != EXFAT_ENTRY_FILE)
747                 exfat_bug("invalid type of meta1: 0x%hhx", meta1.type);
748         meta1.attrib = cpu_to_le16(node->attrib);
749         exfat_unix2exfat(node->mtime, &meta1.mdate, &meta1.mtime, &meta1.mtime_cs);
750         exfat_unix2exfat(node->atime, &meta1.adate, &meta1.atime, NULL);
751
752         if (exfat_pread(ef->dev, &meta2, sizeof(meta2), meta2_offset) < 0)
753         {
754                 exfat_error("failed to read meta2 entry on flush");
755                 return -EIO;
756         }
757         if (meta2.type != EXFAT_ENTRY_FILE_INFO)
758                 exfat_bug("invalid type of meta2: 0x%hhx", meta2.type);
759         meta2.size = meta2.valid_size = cpu_to_le64(node->size);
760         meta2.start_cluster = cpu_to_le32(node->start_cluster);
761         meta2.flags = EXFAT_FLAG_ALWAYS1;
762         /* empty files must not be marked as contiguous */
763         if (node->size != 0 && node->is_contiguous)
764                 meta2.flags |= EXFAT_FLAG_CONTIGUOUS;
765         /* name hash remains unchanged, no need to recalculate it */
766
767         meta1.checksum = exfat_calc_checksum(&meta1, &meta2, node->name);
768
769         if (exfat_pwrite(ef->dev, &meta1, sizeof(meta1), meta1_offset) < 0)
770         {
771                 exfat_error("failed to write meta1 entry on flush");
772                 return -EIO;
773         }
774         if (exfat_pwrite(ef->dev, &meta2, sizeof(meta2), meta2_offset) < 0)
775         {
776                 exfat_error("failed to write meta2 entry on flush");
777                 return -EIO;
778         }
779
780         node->is_dirty = false;
781         return exfat_flush(ef);
782 }
783
784 static int erase_entries(struct exfat* ef, struct exfat_node* dir, int n,
785                 off_t offset)
786 {
787         struct exfat_entry entries[n];
788         int rc;
789         int i;
790
791         rc = read_entries(ef, dir, entries, n, offset);
792         if (rc != 0)
793                 return rc;
794         for (i = 0; i < n; i++)
795                 entries[i].type &= ~EXFAT_ENTRY_VALID;
796         return write_entries(ef, dir, entries, n, offset);
797 }
798
799 static int erase_node(struct exfat* ef, struct exfat_node* node)
800 {
801         int rc;
802
803         exfat_get_node(node->parent);
804         rc = erase_entries(ef, node->parent, 1 + node->continuations,
805                         node->entry_offset);
806         if (rc != 0)
807         {
808                 exfat_put_node(ef, node->parent);
809                 return rc;
810         }
811         rc = exfat_flush_node(ef, node->parent);
812         exfat_put_node(ef, node->parent);
813         return rc;
814 }
815
816 static int shrink_directory(struct exfat* ef, struct exfat_node* dir,
817                 off_t deleted_offset)
818 {
819         const struct exfat_node* node;
820         const struct exfat_node* last_node;
821         uint64_t entries = 0;
822         uint64_t new_size;
823
824         if (!(dir->attrib & EXFAT_ATTRIB_DIR))
825                 exfat_bug("attempted to shrink a file");
826         if (!dir->is_cached)
827                 exfat_bug("attempted to shrink uncached directory");
828
829         for (last_node = node = dir->child; node; node = node->next)
830         {
831                 if (deleted_offset < node->entry_offset)
832                 {
833                         /* there are other entries after the removed one, no way to shrink
834                            this directory */
835                         return 0;
836                 }
837                 if (last_node->entry_offset < node->entry_offset)
838                         last_node = node;
839         }
840
841         if (last_node)
842         {
843                 /* offset of the last entry */
844                 entries += last_node->entry_offset / sizeof(struct exfat_entry);
845                 /* two subentries with meta info */
846                 entries += 2;
847                 /* subentries with file name */
848                 entries += DIV_ROUND_UP(utf16_length(last_node->name),
849                                 EXFAT_ENAME_MAX);
850         }
851
852         new_size = DIV_ROUND_UP(entries * sizeof(struct exfat_entry),
853                                  CLUSTER_SIZE(*ef->sb)) * CLUSTER_SIZE(*ef->sb);
854         if (new_size == 0) /* directory always has at least 1 cluster */
855                 new_size = CLUSTER_SIZE(*ef->sb);
856         if (new_size == dir->size)
857                 return 0;
858         return exfat_truncate(ef, dir, new_size, true);
859 }
860
861 static int delete(struct exfat* ef, struct exfat_node* node)
862 {
863         struct exfat_node* parent = node->parent;
864         off_t deleted_offset = node->entry_offset;
865         int rc;
866
867         exfat_get_node(parent);
868         rc = erase_node(ef, node);
869         if (rc != 0)
870         {
871                 exfat_put_node(ef, parent);
872                 return rc;
873         }
874         tree_detach(node);
875         rc = shrink_directory(ef, parent, deleted_offset);
876         node->is_unlinked = true;
877         if (rc != 0)
878         {
879                 exfat_flush_node(ef, parent);
880                 exfat_put_node(ef, parent);
881                 return rc;
882         }
883         exfat_update_mtime(parent);
884         rc = exfat_flush_node(ef, parent);
885         exfat_put_node(ef, parent);
886         return rc;
887 }
888
889 int exfat_unlink(struct exfat* ef, struct exfat_node* node)
890 {
891         if (node->attrib & EXFAT_ATTRIB_DIR)
892                 return -EISDIR;
893         return delete(ef, node);
894 }
895
896 int exfat_rmdir(struct exfat* ef, struct exfat_node* node)
897 {
898         int rc;
899
900         if (!(node->attrib & EXFAT_ATTRIB_DIR))
901                 return -ENOTDIR;
902         /* check that directory is empty */
903         rc = exfat_cache_directory(ef, node);
904         if (rc != 0)
905                 return rc;
906         if (node->child)
907                 return -ENOTEMPTY;
908         return delete(ef, node);
909 }
910
911 static int grow_directory(struct exfat* ef, struct exfat_node* dir,
912                 uint64_t asize, uint32_t difference)
913 {
914         return exfat_truncate(ef, dir,
915                         DIV_ROUND_UP(asize + difference, CLUSTER_SIZE(*ef->sb))
916                                 * CLUSTER_SIZE(*ef->sb), true);
917 }
918
919 static int find_slot(struct exfat* ef, struct exfat_node* dir,
920                 cluster_t* cluster, off_t* offset, int subentries)
921 {
922         struct iterator it;
923         int rc;
924         const struct exfat_entry* entry;
925         int contiguous = 0;
926
927         rc = opendir(ef, dir, &it);
928         if (rc != 0)
929                 return rc;
930         for (;;)
931         {
932                 if (contiguous == 0)
933                 {
934                         *cluster = it.cluster;
935                         *offset = it.offset;
936                 }
937                 entry = get_entry_ptr(ef, &it);
938                 if (entry->type & EXFAT_ENTRY_VALID)
939                         contiguous = 0;
940                 else
941                         contiguous++;
942                 if (contiguous == subentries)
943                         break;  /* suitable slot is found */
944                 if (it.offset + sizeof(struct exfat_entry) >= dir->size)
945                 {
946                         rc = grow_directory(ef, dir, dir->size,
947                                         (subentries - contiguous) * sizeof(struct exfat_entry));
948                         if (rc != 0)
949                         {
950                                 closedir(&it);
951                                 return rc;
952                         }
953                 }
954                 if (!fetch_next_entry(ef, dir, &it))
955                 {
956                         closedir(&it);
957                         return -EIO;
958                 }
959         }
960         closedir(&it);
961         return 0;
962 }
963
964 static int commit_entry(struct exfat* ef, struct exfat_node* dir,
965                 const le16_t* name, cluster_t cluster, off_t offset, uint16_t attrib)
966 {
967         struct exfat_node* node;
968         const size_t name_length = utf16_length(name);
969         const int name_entries = DIV_ROUND_UP(name_length, EXFAT_ENAME_MAX);
970         struct exfat_entry entries[2 + name_entries];
971         struct exfat_entry_meta1* meta1 = (struct exfat_entry_meta1*) &entries[0];
972         struct exfat_entry_meta2* meta2 = (struct exfat_entry_meta2*) &entries[1];
973         int i;
974         int rc;
975
976         memset(entries, 0, sizeof(struct exfat_entry[2]));
977
978         meta1->type = EXFAT_ENTRY_FILE;
979         meta1->continuations = 1 + name_entries;
980         meta1->attrib = cpu_to_le16(attrib);
981         exfat_unix2exfat(time(NULL), &meta1->crdate, &meta1->crtime,
982                         &meta1->crtime_cs);
983         meta1->adate = meta1->mdate = meta1->crdate;
984         meta1->atime = meta1->mtime = meta1->crtime;
985         meta1->mtime_cs = meta1->crtime_cs; /* there is no atime_cs */
986
987         meta2->type = EXFAT_ENTRY_FILE_INFO;
988         meta2->flags = EXFAT_FLAG_ALWAYS1;
989         meta2->name_length = name_length;
990         meta2->name_hash = exfat_calc_name_hash(ef, name, name_length);
991         meta2->start_cluster = cpu_to_le32(EXFAT_CLUSTER_FREE);
992
993         meta1->checksum = exfat_calc_checksum(meta1, meta2, name);
994
995         for (i = 0; i < name_entries; i++)
996         {
997                 struct exfat_entry_name* name_entry;
998
999                 name_entry = (struct exfat_entry_name*) &entries[2 + i];
1000                 name_entry->type = EXFAT_ENTRY_FILE_NAME;
1001                 name_entry->__unknown = 0;
1002                 memcpy(name_entry->name, name + i * EXFAT_ENAME_MAX,
1003                                 EXFAT_ENAME_MAX * sizeof(le16_t));
1004         }
1005
1006         rc = write_entries(ef, dir, entries, 2 + name_entries, offset);
1007         if (rc != 0)
1008                 return rc;
1009
1010         node = allocate_node();
1011         if (node == NULL)
1012                 return -ENOMEM;
1013         node->entry_cluster = cluster;
1014         node->entry_offset = offset;
1015         memcpy(node->name, name, name_length * sizeof(le16_t));
1016         init_node_meta1(node, meta1);
1017         init_node_meta2(node, meta2);
1018
1019         tree_attach(dir, node);
1020         return 0;
1021 }
1022
1023 static int create(struct exfat* ef, const char* path, uint16_t attrib)
1024 {
1025         struct exfat_node* dir;
1026         struct exfat_node* existing;
1027         cluster_t cluster = EXFAT_CLUSTER_BAD;
1028         off_t offset = -1;
1029         le16_t name[EXFAT_NAME_MAX + 1];
1030         int rc;
1031
1032         rc = exfat_split(ef, &dir, &existing, name, path);
1033         if (rc != 0)
1034                 return rc;
1035         if (existing != NULL)
1036         {
1037                 exfat_put_node(ef, existing);
1038                 exfat_put_node(ef, dir);
1039                 return -EEXIST;
1040         }
1041
1042         rc = find_slot(ef, dir, &cluster, &offset,
1043                         2 + DIV_ROUND_UP(utf16_length(name), EXFAT_ENAME_MAX));
1044         if (rc != 0)
1045         {
1046                 exfat_put_node(ef, dir);
1047                 return rc;
1048         }
1049         rc = commit_entry(ef, dir, name, cluster, offset, attrib);
1050         if (rc != 0)
1051         {
1052                 exfat_put_node(ef, dir);
1053                 return rc;
1054         }
1055         exfat_update_mtime(dir);
1056         rc = exfat_flush_node(ef, dir);
1057         exfat_put_node(ef, dir);
1058         return rc;
1059 }
1060
1061 int exfat_mknod(struct exfat* ef, const char* path)
1062 {
1063         return create(ef, path, EXFAT_ATTRIB_ARCH);
1064 }
1065
1066 int exfat_mkdir(struct exfat* ef, const char* path)
1067 {
1068         int rc;
1069         struct exfat_node* node;
1070
1071         rc = create(ef, path, EXFAT_ATTRIB_DIR);
1072         if (rc != 0)
1073                 return rc;
1074         rc = exfat_lookup(ef, &node, path);
1075         if (rc != 0)
1076                 return 0;
1077         /* directories always have at least one cluster */
1078         rc = exfat_truncate(ef, node, CLUSTER_SIZE(*ef->sb), true);
1079         if (rc != 0)
1080         {
1081                 delete(ef, node);
1082                 exfat_put_node(ef, node);
1083                 return rc;
1084         }
1085         rc = exfat_flush_node(ef, node);
1086         if (rc != 0)
1087         {
1088                 delete(ef, node);
1089                 exfat_put_node(ef, node);
1090                 return rc;
1091         }
1092         exfat_put_node(ef, node);
1093         return 0;
1094 }
1095
1096 static int rename_entry(struct exfat* ef, struct exfat_node* dir,
1097                 struct exfat_node* node, const le16_t* name, cluster_t new_cluster,
1098                 off_t new_offset)
1099 {
1100         struct exfat_entry_meta1 meta1;
1101         struct exfat_entry_meta2 meta2;
1102         cluster_t old_cluster = node->entry_cluster;
1103         off_t old_offset = node->entry_offset;
1104         const size_t name_length = utf16_length(name);
1105         const int name_entries = DIV_ROUND_UP(name_length, EXFAT_ENAME_MAX);
1106         int rc;
1107         int i;
1108
1109         if (exfat_pread(ef->dev, &meta1, sizeof(meta1),
1110                         co2o(ef, old_cluster, old_offset)) < 0)
1111         {
1112                 exfat_error("failed to read meta1 entry on rename");
1113                 return -EIO;
1114         }
1115         if (!next_entry(ef, node->parent, &old_cluster, &old_offset))
1116                 return -EIO;
1117         if (exfat_pread(ef->dev, &meta2, sizeof(meta2),
1118                         co2o(ef, old_cluster, old_offset)) < 0)
1119         {
1120                 exfat_error("failed to read meta2 entry on rename");
1121                 return -EIO;
1122         }
1123         meta1.continuations = 1 + name_entries;
1124         meta2.name_hash = exfat_calc_name_hash(ef, name, name_length);
1125         meta2.name_length = name_length;
1126         meta1.checksum = exfat_calc_checksum(&meta1, &meta2, name);
1127
1128         rc = erase_node(ef, node);
1129         if (rc != 0)
1130                 return rc;
1131
1132         node->entry_cluster = new_cluster;
1133         node->entry_offset = new_offset;
1134         node->continuations = 1 + name_entries;
1135
1136         if (exfat_pwrite(ef->dev, &meta1, sizeof(meta1),
1137                         co2o(ef, new_cluster, new_offset)) < 0)
1138         {
1139                 exfat_error("failed to write meta1 entry on rename");
1140                 return -EIO;
1141         }
1142         if (!next_entry(ef, dir, &new_cluster, &new_offset))
1143                 return -EIO;
1144         if (exfat_pwrite(ef->dev, &meta2, sizeof(meta2),
1145                         co2o(ef, new_cluster, new_offset)) < 0)
1146         {
1147                 exfat_error("failed to write meta2 entry on rename");
1148                 return -EIO;
1149         }
1150
1151         for (i = 0; i < name_entries; i++)
1152         {
1153                 struct exfat_entry_name name_entry = {EXFAT_ENTRY_FILE_NAME, 0};
1154                 memcpy(name_entry.name, name + i * EXFAT_ENAME_MAX,
1155                                 EXFAT_ENAME_MAX * sizeof(le16_t));
1156                 if (!next_entry(ef, dir, &new_cluster, &new_offset))
1157                         return -EIO;
1158                 if (exfat_pwrite(ef->dev, &name_entry, sizeof(name_entry),
1159                                 co2o(ef, new_cluster, new_offset)) < 0)
1160                 {
1161                         exfat_error("failed to write name entry on rename");
1162                         return -EIO;
1163                 }
1164         }
1165
1166         memcpy(node->name, name, (EXFAT_NAME_MAX + 1) * sizeof(le16_t));
1167         tree_detach(node);
1168         tree_attach(dir, node);
1169         return 0;
1170 }
1171
1172 int exfat_rename(struct exfat* ef, const char* old_path, const char* new_path)
1173 {
1174         struct exfat_node* node;
1175         struct exfat_node* existing;
1176         struct exfat_node* dir;
1177         cluster_t cluster = EXFAT_CLUSTER_BAD;
1178         off_t offset = -1;
1179         le16_t name[EXFAT_NAME_MAX + 1];
1180         int rc;
1181
1182         rc = exfat_lookup(ef, &node, old_path);
1183         if (rc != 0)
1184                 return rc;
1185
1186         rc = exfat_split(ef, &dir, &existing, name, new_path);
1187         if (rc != 0)
1188         {
1189                 exfat_put_node(ef, node);
1190                 return rc;
1191         }
1192
1193         /* check that target is not a subdirectory of the source */
1194         if (node->attrib & EXFAT_ATTRIB_DIR)
1195         {
1196                 struct exfat_node* p;
1197
1198                 for (p = dir; p; p = p->parent)
1199                         if (node == p)
1200                         {
1201                                 if (existing != NULL)
1202                                         exfat_put_node(ef, existing);
1203                                 exfat_put_node(ef, dir);
1204                                 exfat_put_node(ef, node);
1205                                 return -EINVAL;
1206                         }
1207         }
1208
1209         if (existing != NULL)
1210         {
1211                 /* remove target if it's not the same node as source */
1212                 if (existing != node)
1213                 {
1214                         if (existing->attrib & EXFAT_ATTRIB_DIR)
1215                         {
1216                                 if (node->attrib & EXFAT_ATTRIB_DIR)
1217                                         rc = exfat_rmdir(ef, existing);
1218                                 else
1219                                         rc = -ENOTDIR;
1220                         }
1221                         else
1222                         {
1223                                 if (!(node->attrib & EXFAT_ATTRIB_DIR))
1224                                         rc = exfat_unlink(ef, existing);
1225                                 else
1226                                         rc = -EISDIR;
1227                         }
1228                         exfat_put_node(ef, existing);
1229                         if (rc != 0)
1230                         {
1231                                 /* free clusters even if something went wrong; overwise they
1232                                    will be just lost */
1233                                 exfat_cleanup_node(ef, existing);
1234                                 exfat_put_node(ef, dir);
1235                                 exfat_put_node(ef, node);
1236                                 return rc;
1237                         }
1238                         rc = exfat_cleanup_node(ef, existing);
1239                         if (rc != 0)
1240                         {
1241                                 exfat_put_node(ef, dir);
1242                                 exfat_put_node(ef, node);
1243                                 return rc;
1244                         }
1245                 }
1246                 else
1247                         exfat_put_node(ef, existing);
1248         }
1249
1250         rc = find_slot(ef, dir, &cluster, &offset,
1251                         2 + DIV_ROUND_UP(utf16_length(name), EXFAT_ENAME_MAX));
1252         if (rc != 0)
1253         {
1254                 exfat_put_node(ef, dir);
1255                 exfat_put_node(ef, node);
1256                 return rc;
1257         }
1258         rc = rename_entry(ef, dir, node, name, cluster, offset);
1259         exfat_put_node(ef, dir);
1260         exfat_put_node(ef, node);
1261         return rc;
1262 }
1263
1264 void exfat_utimes(struct exfat_node* node, const struct timespec tv[2])
1265 {
1266         node->atime = tv[0].tv_sec;
1267         node->mtime = tv[1].tv_sec;
1268         node->is_dirty = true;
1269 }
1270
1271 void exfat_update_atime(struct exfat_node* node)
1272 {
1273         node->atime = time(NULL);
1274         node->is_dirty = true;
1275 }
1276
1277 void exfat_update_mtime(struct exfat_node* node)
1278 {
1279         node->mtime = time(NULL);
1280         node->is_dirty = true;
1281 }
1282
1283 const char* exfat_get_label(struct exfat* ef)
1284 {
1285         return ef->label;
1286 }
1287
1288 static int find_label(struct exfat* ef, off_t* offset)
1289 {
1290         struct exfat_entry entry;
1291         int rc;
1292
1293         for (*offset = 0; ; *offset += sizeof(entry))
1294         {
1295                 rc = read_entries(ef, ef->root, &entry, 1, *offset);
1296                 if (rc != 0)
1297                         return rc;
1298
1299                 if (entry.type == EXFAT_ENTRY_LABEL)
1300                         return 0;
1301         }
1302 }
1303
1304 int exfat_set_label(struct exfat* ef, const char* label)
1305 {
1306         le16_t label_utf16[EXFAT_ENAME_MAX + 1];
1307         int rc;
1308         cluster_t cluster;
1309         off_t offset;
1310         struct exfat_entry_label entry;
1311
1312         memset(label_utf16, 0, sizeof(label_utf16));
1313         rc = utf8_to_utf16(label_utf16, label, EXFAT_ENAME_MAX + 1, strlen(label));
1314         if (rc != 0)
1315                 return rc;
1316
1317         rc = find_label(ef, &offset);
1318         if (rc == -ENOENT)
1319                 rc = find_slot(ef, ef->root, &cluster, &offset, 1);
1320         if (rc != 0)
1321                 return rc;
1322
1323         entry.type = EXFAT_ENTRY_LABEL;
1324         entry.length = utf16_length(label_utf16);
1325         memcpy(entry.name, label_utf16, sizeof(entry.name));
1326         if (entry.length == 0)
1327                 entry.type ^= EXFAT_ENTRY_VALID;
1328
1329         rc = write_entries(ef, ef->root, (struct exfat_entry*) &entry, 1, offset);
1330         if (rc != 0)
1331                 return rc;
1332
1333         strcpy(ef->label, label);
1334         return 0;
1335 }