OSDN Git Service

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