OSDN Git Service

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