Bump version numbers for 3.13
[maemo-rb.git] / firmware / common / dircache.c
blob21ae71fd5dcb53e3a678a2ba0151ffd86399b4a8
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
22 /* TODO:
23 - Allow cache live updating while transparent rebuild is running.
26 #include "config.h"
28 #include <stdio.h>
29 #include <errno.h>
30 #include "string-extra.h"
31 #include <stdbool.h>
32 #include <stdlib.h>
33 #include "debug.h"
34 #include "system.h"
35 #include "logf.h"
36 #include "dircache.h"
37 #include "thread.h"
38 #include "kernel.h"
39 #include "usb.h"
40 #include "file.h"
41 #include "core_alloc.h"
42 #include "dir.h"
43 #include "storage.h"
44 #include "audio.h"
45 #if CONFIG_RTC
46 #include "time.h"
47 #include "timefuncs.h"
48 #endif
49 #include "rbpaths.h"
52 /* Queue commands. */
53 #define DIRCACHE_BUILD 1
54 #define DIRCACHE_STOP 2
56 #if (MEMORYSIZE > 8)
57 #define MAX_OPEN_DIRS 12
58 #else
59 #define MAX_OPEN_DIRS 8
60 #endif
61 static DIR_CACHED opendirs[MAX_OPEN_DIRS];
62 static char opendir_dnames[MAX_OPEN_DIRS][MAX_PATH];
64 #define MAX_PENDING_BINDINGS 2
65 struct fdbind_queue {
66 char path[MAX_PATH];
67 int fd;
70 /* Unions with char to make pointer arithmetic simpler and avoid casting */
71 struct dircache_entry {
72 struct dirinfo info;
73 union {
74 struct dircache_entry *next;
75 char* next_char;
77 union {
78 struct dircache_entry *up;
79 char* up_char;
81 union {
82 struct dircache_entry *down;
83 char* down_char;
85 long startcluster;
86 char *d_name;
89 /* Cache Layout:
91 * x - array of struct dircache_entry
92 * r - reserved buffer
93 * d - name buffer for the d_name entry of the struct dircache_entry
94 * |xxxxxx|rrrrrrrrr|dddddd|
96 * subsequent x are allocated from the front, d are allocated from the back,
97 * using the reserve buffer for entries added after initial scan
99 * after a while the cache may look like:
100 * |xxxxxxxx|rrrrr|dddddddd|
102 * after a reboot, the reserve buffer is restored in it's size, so that the
103 * total allocation size grows
104 * |xxxxxxxx|rrrrrrrrr|dddddddd|
106 /* this points to the beginnging of the buffer and the first entry */
107 static struct dircache_entry *dircache_root;
108 /* these point to the start and end of the name buffer (d above) */
109 static char *d_names_start, *d_names_end;
110 /* put "." and ".." into the d_names buffer to enable easy pointer logic */
111 static char *dot, *dotdot;
112 #ifdef HAVE_MULTIVOLUME
113 static struct dircache_entry *append_position;
114 #endif
116 static DIR_CACHED opendirs[MAX_OPEN_DIRS];
117 static struct dircache_entry *fd_bindings[MAX_OPEN_FILES];
119 static bool dircache_initialized = false;
120 static bool dircache_initializing = false;
121 static bool thread_enabled = false;
122 static unsigned long allocated_size = 0;
123 static unsigned long dircache_size = 0;
124 static unsigned long entry_count = 0;
125 static unsigned long reserve_used = 0;
126 static unsigned int cache_build_ticks = 0;
127 static unsigned long appflags = 0;
129 static struct event_queue dircache_queue SHAREDBSS_ATTR;
130 static long dircache_stack[(DEFAULT_STACK_SIZE + 0x400)/sizeof(long)];
131 static const char dircache_thread_name[] = "dircache";
133 static struct fdbind_queue fdbind_cache[MAX_PENDING_BINDINGS];
134 static int fdbind_idx = 0;
136 /* --- Internal cache structure control functions --- */
138 static inline struct dircache_entry* get_entry(int id)
140 return &dircache_root[id];
143 /* flag to make sure buffer doesn't move due to other allocs.
144 * this is set to true completely during dircache build */
145 static bool dont_move = false;
146 static int dircache_handle;
147 static int move_callback(int handle, void* current, void* new)
149 (void)handle;
150 if (dont_move)
151 return BUFLIB_CB_CANNOT_MOVE;
153 #define UPDATE(x) if (x) { x = PTR_ADD(x, diff); }
154 /* relocate the cache */
155 ptrdiff_t diff = new - current;
156 for(unsigned i = 0; i < entry_count; i++)
158 UPDATE(dircache_root[i].d_name);
159 UPDATE(dircache_root[i].next_char);
160 UPDATE(dircache_root[i].up_char);
161 UPDATE(dircache_root[i].down_char);
163 dircache_root = new;
164 UPDATE(d_names_start);
165 UPDATE(d_names_end);
166 UPDATE(dot);
167 UPDATE(dotdot);
169 for(unsigned i = 0; i < MAX_OPEN_FILES; i++)
170 UPDATE(fd_bindings[i]);
172 #ifdef HAVE_MULTIVOLUME
173 UPDATE(append_position);
174 #endif
175 return BUFLIB_CB_OK;
178 static struct buflib_callbacks ops = {
179 .move_callback = move_callback,
180 .shrink_callback = NULL,
183 #ifdef HAVE_EEPROM_SETTINGS
185 * Open the dircache file to save a snapshot on disk
187 static int open_dircache_file(unsigned flags, int permissions)
189 if (permissions != 0)
190 return open(DIRCACHE_FILE, flags, permissions);
192 return open(DIRCACHE_FILE, flags);
196 * Remove the snapshot file
198 static int remove_dircache_file(void)
200 return remove(DIRCACHE_FILE);
202 #endif
203 /**
204 * Internal function to allocate a new dircache_entry from memory.
206 static struct dircache_entry* allocate_entry(void)
208 struct dircache_entry *next_entry;
210 if (dircache_size > allocated_size - MAX_PATH*2)
212 logf("size limit reached");
213 return NULL;
216 next_entry = &dircache_root[entry_count++];
217 next_entry->d_name = NULL;
218 next_entry->up = NULL;
219 next_entry->down = NULL;
220 next_entry->next = NULL;
222 dircache_size += sizeof(struct dircache_entry);
224 return next_entry;
228 * Internal function to allocate a dircache_entry and set
229 * ->next entry pointers.
231 static struct dircache_entry* dircache_gen_next(struct dircache_entry *ce)
233 struct dircache_entry *next_entry;
235 if ( (next_entry = allocate_entry()) == NULL)
236 return NULL;
237 next_entry->up = ce->up;
238 ce->next = next_entry;
240 return next_entry;
244 * Internal function to allocate a dircache_entry and set
245 * ->down entry pointers.
247 static struct dircache_entry* dircache_gen_down(struct dircache_entry *ce)
249 struct dircache_entry *next_entry;
251 if ( (next_entry = allocate_entry()) == NULL)
252 return NULL;
253 next_entry->up = ce;
254 ce->down = next_entry;
256 return next_entry;
260 * Returns true if there is an event waiting in the queue
261 * that requires the current operation to be aborted.
263 static bool check_event_queue(void)
265 struct queue_event ev;
267 if(!queue_peek(&dircache_queue, &ev))
268 return false;
270 switch (ev.id)
272 case DIRCACHE_STOP:
273 case SYS_USB_CONNECTED:
274 #ifdef HAVE_HOTSWAP
275 case SYS_FS_CHANGED:
276 #endif
277 return true;
280 return false;
283 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
284 /* scan and build static data (avoid redundancy on stack) */
285 static struct
287 #ifdef HAVE_MULTIVOLUME
288 int volume;
289 #endif
290 struct fat_dir *dir;
291 struct fat_direntry *direntry;
292 }sab;
294 static int sab_process_dir(unsigned long startcluster, struct dircache_entry *ce)
296 /* normally, opendir expects a full fat_dir as parent but in our case,
297 * it's completely useless because we don't modify anything
298 * WARNING: this heavily relies on current FAT implementation ! */
300 /* those field are necessary to update the FAT entry in case of modification
301 here we don't touch anything so we put dummy values */
302 sab.dir->entry = 0;
303 sab.dir->entrycount = 0;
304 sab.dir->file.firstcluster = 0;
305 /* open directory */
306 int rc = fat_opendir(IF_MV2(sab.volume,) sab.dir, startcluster, sab.dir);
307 if(rc < 0)
309 logf("fat_opendir failed: %d", rc);
310 return rc;
313 /* first pass : read dir */
314 struct dircache_entry *first_ce = ce;
316 /* read through directory */
317 while((rc = fat_getnext(sab.dir, sab.direntry)) >= 0 && sab.direntry->name[0])
319 if(!strcmp(".", sab.direntry->name) ||
320 !strcmp("..", sab.direntry->name))
321 continue;
323 size_t size = strlen(sab.direntry->name) + 1;
324 ce->d_name = (d_names_start -= size);
325 ce->startcluster = sab.direntry->firstcluster;
326 ce->info.size = sab.direntry->filesize;
327 ce->info.attribute = sab.direntry->attr;
328 ce->info.wrtdate = sab.direntry->wrtdate;
329 ce->info.wrttime = sab.direntry->wrttime;
331 strcpy(ce->d_name, sab.direntry->name);
332 dircache_size += size;
334 if(ce->info.attribute & FAT_ATTR_DIRECTORY)
335 dircache_gen_down(ce);
337 ce = dircache_gen_next(ce);
338 if(ce == NULL)
339 return -5;
341 /* When simulator is used, it's only safe to yield here. */
342 if(thread_enabled)
344 /* Stop if we got an external signal. */
345 if(check_event_queue())
346 return -6;
347 yield();
351 /* add "." and ".." */
352 ce->d_name = dot;
353 ce->info.attribute = FAT_ATTR_DIRECTORY;
354 ce->startcluster = startcluster;
355 ce->info.size = 0;
356 ce->down = first_ce;
358 ce = dircache_gen_next(ce);
360 ce->d_name = dotdot;
361 ce->info.attribute = FAT_ATTR_DIRECTORY;
362 ce->startcluster = (first_ce->up ? first_ce->up->startcluster : 0);
363 ce->info.size = 0;
364 ce->down = first_ce->up;
366 /* second pass: recurse ! */
367 ce = first_ce;
369 while(rc >= 0 && ce)
371 if(ce->d_name != NULL && ce->down != NULL && strcmp(ce->d_name, ".")
372 && strcmp(ce->d_name, ".."))
373 rc = sab_process_dir(ce->startcluster, ce->down);
375 ce = ce->next;
378 return rc;
381 /* used during the generation */
382 static struct fat_dir sab_fat_dir;
384 static int dircache_scan_and_build(IF_MV2(int volume,) struct dircache_entry *ce)
386 memset(ce, 0, sizeof(struct dircache_entry));
388 #ifdef HAVE_MULTIVOLUME
389 if (volume > 0)
391 /* broken for 100+ volumes because the format string is too small
392 * and we use that for size calculation */
393 const size_t max_len = VOL_ENUM_POS + 3;
394 ce->d_name = (d_names_start -= max_len);
395 snprintf(ce->d_name, max_len, VOL_NAMES, volume);
396 dircache_size += max_len;
397 ce->info.attribute = FAT_ATTR_DIRECTORY | FAT_ATTR_VOLUME;
398 ce->info.size = 0;
399 append_position = dircache_gen_next(ce);
400 ce = dircache_gen_down(ce);
402 #endif
404 struct fat_direntry direntry; /* ditto */
405 #ifdef HAVE_MULTIVOLUME
406 sab.volume = volume;
407 #endif
408 sab.dir = &sab_fat_dir;
409 sab.direntry = &direntry;
411 return sab_process_dir(0, ce);
413 #elif (CONFIG_PLATFORM & PLATFORM_HOSTED) /* PLATFORM_HOSTED */
414 static char sab_path[MAX_PATH];
416 static int sab_process_dir(struct dircache_entry *ce)
418 struct dirent_uncached *entry;
419 struct dircache_entry *first_ce = ce;
420 DIR_UNCACHED *dir = opendir_uncached(sab_path);
421 if(dir == NULL)
423 logf("Failed to opendir_uncached(%s)", sab_path);
424 return -1;
427 while((entry = readdir_uncached(dir)))
429 if(!strcmp(".", entry->d_name) ||
430 !strcmp("..", entry->d_name))
431 continue;
433 size_t size = strlen(entry->d_name) + 1;
434 ce->d_name = (d_names_start -= size);
435 ce->info = entry->info;
437 strcpy(ce->d_name, entry->d_name);
438 dircache_size += size;
440 if(entry->info.attribute & ATTR_DIRECTORY)
442 dircache_gen_down(ce);
443 if(ce->down == NULL)
445 closedir_uncached(dir);
446 return -1;
448 /* save current paths size */
449 int pathpos = strlen(sab_path);
450 /* append entry */
451 strlcpy(&sab_path[pathpos], "/", sizeof(sab_path) - pathpos);
452 strlcpy(&sab_path[pathpos+1], entry->d_name, sizeof(sab_path) - pathpos - 1);
454 int rc = sab_process_dir(ce->down);
455 /* restore path */
456 sab_path[pathpos] = '\0';
458 if(rc < 0)
460 closedir_uncached(dir);
461 return rc;
465 ce = dircache_gen_next(ce);
466 if(ce == NULL)
467 return -5;
469 /* When simulator is used, it's only safe to yield here. */
470 if(thread_enabled)
472 /* Stop if we got an external signal. */
473 if(check_event_queue())
474 return -1;
475 yield();
479 /* add "." and ".." */
480 ce->d_name = dot;
481 ce->info.attribute = ATTR_DIRECTORY;
482 ce->info.size = 0;
483 ce->down = first_ce;
485 ce = dircache_gen_next(ce);
487 ce->d_name = dotdot;
488 ce->info.attribute = ATTR_DIRECTORY;
489 ce->info.size = 0;
490 ce->down = first_ce->up;
492 closedir_uncached(dir);
493 return 0;
496 static int dircache_scan_and_build(IF_MV2(int volume,) struct dircache_entry *ce)
498 #ifdef HAVE_MULTIVOLUME
499 (void) volume;
500 #endif
501 memset(ce, 0, sizeof(struct dircache_entry));
503 strlcpy(sab_path, "/", sizeof sab_path);
504 return sab_process_dir(ce);
506 #endif /* PLATFORM_NATIVE */
509 * Internal function to get a pointer to dircache_entry for a given filename.
510 * path: Absolute path to a file or directory (see comment)
511 * go_down: Returns the first entry of the directory given by the path (see comment)
513 * As a a special case, accept path="" as an alias for "/".
514 * Also if the path omits the first '/', it will be accepted.
516 * * If get_down=true:
517 * If path="/", the returned entry is the first of root directory (ie dircache_root)
518 * Otherwise, if 'entry' is the returned value when get_down=false,
519 * the functions returns entry->down (which can be NULL)
521 * * If get_down=false:
522 * If path="/chunk_1/chunk_2/.../chunk_n" then this functions returns the entry
523 * root_entry()->chunk_1->chunk_2->...->chunk_(n-1)
524 * Which means that
525 * dircache_get_entry(path)->d_name == chunk_n
527 * If path="/", the returned entry is NULL.
528 * If the entry doesn't exist, return NULL
530 * NOTE: this functions silently handles double '/'
532 static struct dircache_entry* dircache_get_entry(const char *path, bool go_down)
534 char namecopy[MAX_PATH];
535 char* part;
536 char* end;
538 bool at_root = true;
539 struct dircache_entry *cache_entry = dircache_root;
541 strlcpy(namecopy, path, sizeof(namecopy));
543 for(part = strtok_r(namecopy, "/", &end); part; part = strtok_r(NULL, "/", &end))
545 /* If request another chunk, the current entry has to be directory
546 * and so cache_entry->down has to be non-NULL/
547 * Special case of root because it's already the first entry of the root directory
549 * NOTE: this is safe even if cache_entry->down is NULL */
550 if(!at_root)
551 cache_entry = cache_entry->down;
552 else
553 at_root = false;
555 /* scan dir for name */
556 while(cache_entry != NULL)
558 /* skip unused entries */
559 if(cache_entry->d_name == NULL)
561 cache_entry = cache_entry->next;
562 continue;
564 /* compare names */
565 if(!strcasecmp(part, cache_entry->d_name))
566 break;
567 /* go to next entry */
568 cache_entry = cache_entry->next;
571 /* handle not found case */
572 if(cache_entry == NULL)
573 return NULL;
576 /* NOTE: here cache_entry!=NULL so taking ->down is safe */
577 if(go_down)
578 return at_root ? cache_entry : cache_entry->down;
579 else
580 return at_root ? NULL : cache_entry;
583 #ifdef HAVE_EEPROM_SETTINGS
585 #define DIRCACHE_MAGIC 0x00d0c0a1
586 struct dircache_maindata {
587 long magic;
588 long size;
589 long entry_count;
590 long appflags;
591 struct dircache_entry *root_entry;
592 char *d_names_start;
596 * Function to load the internal cache structure from disk to initialize
597 * the dircache really fast and little disk access.
599 int dircache_load(void)
601 struct dircache_maindata maindata;
602 ssize_t bytes_read;
603 int fd;
605 if (dircache_initialized)
606 return -1;
608 logf("Loading directory cache");
609 dircache_size = 0;
611 fd = open_dircache_file(O_RDONLY, 0);
612 if (fd < 0)
613 return -2;
615 bytes_read = read(fd, &maindata, sizeof(struct dircache_maindata));
616 if (bytes_read != sizeof(struct dircache_maindata)
617 || maindata.magic != DIRCACHE_MAGIC || maindata.size <= 0)
619 logf("Dircache file header error");
620 close(fd);
621 remove_dircache_file();
622 return -3;
625 allocated_size = maindata.size + DIRCACHE_RESERVE;
626 dircache_handle = core_alloc_ex("dircache", allocated_size, &ops);
627 /* block movement during upcoming I/O */
628 dont_move = true;
629 dircache_root = core_get_data(dircache_handle);
630 ALIGN_BUFFER(dircache_root, allocated_size, sizeof(struct dircache_entry*));
631 entry_count = maindata.entry_count;
632 appflags = maindata.appflags;
634 /* read the dircache file into memory,
635 * start with the struct dircache_entries */
636 ssize_t bytes_to_read = entry_count*sizeof(struct dircache_entry);
637 bytes_read = read(fd, dircache_root, bytes_to_read);
639 if (bytes_read != bytes_to_read)
641 logf("Dircache read failed #1");
642 return -6;
645 /* continue with the d_names. Fix up pointers to them if needed */
646 bytes_to_read = maindata.size - bytes_to_read;
647 d_names_start = (char*)dircache_root + allocated_size - bytes_to_read;
648 bytes_read = read(fd, d_names_start, bytes_to_read);
649 close(fd);
650 remove_dircache_file();
651 if (bytes_read != bytes_to_read)
653 logf("Dircache read failed #2");
654 return -7;
657 d_names_end = d_names_start + bytes_read;
658 dot = d_names_end - sizeof(".");
659 dotdot = dot - sizeof("..");
661 /* d_names are in reverse order, so the last entry points to the first string */
662 ptrdiff_t offset_d_names = maindata.d_names_start - d_names_start;
663 ptrdiff_t offset_entries = maindata.root_entry - dircache_root;
664 offset_entries *= sizeof(struct dircache_entry); /* make it bytes */
666 /* offset_entries is less likely to differ, so check if it's 0 in the loop
667 * offset_d_names however is almost always non-zero, since dircache_save()
668 * creates a file which causes the reserve buffer to be used. since
669 * we allocate a new, empty DIRCACHE_RESERVE here, the strings are
670 * farther behind */
671 if (offset_entries != 0 || offset_d_names != 0)
673 for(unsigned i = 0; i < entry_count; i++)
675 if (dircache_root[i].d_name)
676 dircache_root[i].d_name -= offset_d_names;
678 if (offset_entries == 0)
679 continue;
680 if (dircache_root[i].next_char)
681 dircache_root[i].next_char -= offset_entries;
682 if (dircache_root[i].up_char)
683 dircache_root[i].up_char -= offset_entries;
684 if (dircache_root[i].down_char)
685 dircache_root[i].down_char -= offset_entries;
689 /* Cache successfully loaded. */
690 dircache_size = maindata.size;
691 reserve_used = 0;
692 logf("Done, %ld KiB used", dircache_size / 1024);
693 dircache_initialized = true;
694 memset(fd_bindings, 0, sizeof(fd_bindings));
695 dont_move = false;
697 return 0;
701 * Function to save the internal cache stucture to disk for fast loading
702 * on boot.
704 int dircache_save(void)
706 struct dircache_maindata maindata;
707 int fd;
708 unsigned long bytes_written;
710 remove_dircache_file();
712 if (!dircache_initialized)
713 return -1;
715 logf("Saving directory cache");
716 dont_move = true;
717 fd = open_dircache_file(O_WRONLY | O_CREAT | O_TRUNC, 0666);
719 maindata.magic = DIRCACHE_MAGIC;
720 maindata.size = dircache_size;
721 maindata.root_entry = dircache_root;
722 maindata.d_names_start = d_names_start;
723 maindata.entry_count = entry_count;
724 maindata.appflags = appflags;
726 /* Save the info structure */
727 bytes_written = write(fd, &maindata, sizeof(struct dircache_maindata));
728 if (bytes_written != sizeof(struct dircache_maindata))
730 close(fd);
731 logf("dircache: write failed #1");
732 return -2;
735 /* Dump whole directory cache to disk
736 * start by writing the dircache_entries */
737 size_t bytes_to_write = entry_count*sizeof(struct dircache_entry);
738 bytes_written = write(fd, dircache_root, bytes_to_write);
739 if (bytes_written != bytes_to_write)
741 logf("dircache: write failed #2");
742 return -3;
745 /* continue with the d_names */
746 bytes_to_write = d_names_end - d_names_start;
747 bytes_written = write(fd, d_names_start, bytes_to_write);
748 close(fd);
749 if (bytes_written != bytes_to_write)
751 logf("dircache: write failed #3");
752 return -4;
755 dont_move = false;
756 return 0;
758 #endif /* HAVE_EEPROM_SETTINGS */
761 * Internal function which scans the disk and creates the dircache structure.
763 static int dircache_do_rebuild(void)
765 struct dircache_entry* root_entry;
766 unsigned int start_tick;
767 int i;
769 /* Measure how long it takes build the cache. */
770 start_tick = current_tick;
771 dircache_initializing = true;
772 appflags = 0;
774 /* reset dircache and alloc root entry */
775 entry_count = 0;
776 root_entry = allocate_entry();
777 dont_move = true;
779 #ifdef HAVE_MULTIVOLUME
780 append_position = root_entry;
782 for (i = NUM_VOLUMES; i >= 0; i--)
784 if (fat_ismounted(i))
786 #endif
787 cpu_boost(true);
788 #ifdef HAVE_MULTIVOLUME
789 if (dircache_scan_and_build(IF_MV2(i,) append_position) < 0)
790 #else
791 if (dircache_scan_and_build(IF_MV2(0,) root_entry) < 0)
792 #endif /* HAVE_MULTIVOLUME */
794 logf("dircache_scan_and_build failed");
795 cpu_boost(false);
796 dircache_size = 0;
797 dircache_initializing = false;
798 dont_move = false;
799 return -2;
801 cpu_boost(false);
802 #ifdef HAVE_MULTIVOLUME
805 #endif
807 logf("Done, %ld KiB used", dircache_size / 1024);
809 dircache_initialized = true;
810 dircache_initializing = false;
811 cache_build_ticks = current_tick - start_tick;
813 /* Initialized fd bindings. */
814 memset(fd_bindings, 0, sizeof(fd_bindings));
815 for (i = 0; i < fdbind_idx; i++)
816 dircache_bind(fdbind_cache[i].fd, fdbind_cache[i].path);
817 fdbind_idx = 0;
819 if (thread_enabled)
821 if (allocated_size - dircache_size < DIRCACHE_RESERVE)
822 reserve_used = DIRCACHE_RESERVE - (allocated_size - dircache_size);
825 dont_move = false;
826 return 1;
830 * Free all associated resources, if any */
831 static void dircache_free(void)
833 if (dircache_handle > 0)
834 dircache_handle = core_free(dircache_handle);
835 dircache_size = allocated_size = 0;
839 * Internal thread that controls transparent cache building.
841 static void dircache_thread(void)
843 struct queue_event ev;
845 while (1)
847 queue_wait(&dircache_queue, &ev);
849 switch (ev.id)
851 #ifdef HAVE_HOTSWAP
852 case SYS_FS_CHANGED:
853 if (!dircache_initialized)
854 break;
855 dircache_initialized = false;
856 #endif
857 case DIRCACHE_BUILD:
858 thread_enabled = true;
859 if (dircache_do_rebuild() < 0)
860 dircache_free();
861 thread_enabled = false;
862 break ;
864 case DIRCACHE_STOP:
865 logf("Stopped the rebuilding.");
866 dircache_initialized = false;
867 break ;
869 case SYS_USB_CONNECTED:
870 usb_acknowledge(SYS_USB_CONNECTED_ACK);
871 usb_wait_for_disconnect(&dircache_queue);
872 break ;
877 static void generate_dot_d_names(void)
879 dot = (d_names_start -= sizeof("."));
880 dotdot = (d_names_start -= sizeof(".."));
881 dircache_size += sizeof(".") + sizeof("..");
882 strcpy(dot, ".");
883 strcpy(dotdot, "..");
887 * Start scanning the disk to build the dircache.
888 * Either transparent or non-transparent build method is used.
890 int dircache_build(int last_size)
892 if (dircache_initialized || thread_enabled)
893 return -3;
895 logf("Building directory cache");
896 #ifdef HAVE_EEPROM_SETTINGS
897 remove_dircache_file();
898 #endif
900 /* Background build, dircache has been previously allocated and */
901 if (allocated_size > MAX(last_size, 0))
903 d_names_start = d_names_end;
904 dircache_size = 0;
905 reserve_used = 0;
906 thread_enabled = true;
907 dircache_initializing = true;
908 generate_dot_d_names();
910 queue_post(&dircache_queue, DIRCACHE_BUILD, 0);
911 return 2;
914 /* start by freeing, as we possibly re-allocate */
915 dircache_free();
917 if (last_size > DIRCACHE_RESERVE && last_size < DIRCACHE_LIMIT )
919 allocated_size = last_size + DIRCACHE_RESERVE;
920 dircache_handle = core_alloc_ex("dircache", allocated_size, &ops);
921 dircache_root = core_get_data(dircache_handle);
922 ALIGN_BUFFER(dircache_root, allocated_size, sizeof(struct dircache_entry*));
923 d_names_start = d_names_end = ((char*)dircache_root)+allocated_size-1;
924 dircache_size = 0;
925 thread_enabled = true;
926 generate_dot_d_names();
928 /* Start a transparent rebuild. */
929 queue_post(&dircache_queue, DIRCACHE_BUILD, 0);
930 return 3;
933 /* We'll use the entire audiobuf to allocate the dircache
934 * struct dircache_entrys are allocated from the beginning
935 * and their corresponding d_name from the end
936 * after generation the buffer will be compacted with DIRCACHE_RESERVE
937 * free bytes inbetween */
938 size_t available = audio_buffer_available();
939 /* try to allocate at least 1MB, the more the better */
940 if (available < 1<<20) available = 1<<20;
941 if (available > DIRCACHE_LIMIT) available = DIRCACHE_LIMIT;
943 dircache_handle = core_alloc_ex("dircache", available, &ops);
944 if (dircache_handle <= 0)
945 return -1; /* that was not successful, should try rebooting */
946 char* buf = core_get_data(dircache_handle);
947 dircache_root = (struct dircache_entry*)ALIGN_UP(buf,
948 sizeof(struct dircache_entry*));
949 d_names_start = d_names_end = buf + available - 1;
950 dircache_size = 0;
951 generate_dot_d_names();
953 /* Start a non-transparent rebuild. */
954 int res = dircache_do_rebuild();
955 if (res < 0)
956 goto fail;
958 /* now compact the dircache buffer */
959 char* dst = ((char*)&dircache_root[entry_count] + DIRCACHE_RESERVE);
960 ptrdiff_t offset = d_names_start - dst;
961 if (offset <= 0) /* something went wrong */
963 res = -1;
964 goto fail;
967 /* memmove d_names down, there's a possibility of overlap
968 * equivaent to dircache_size - entry_count*sizeof(struct dircache_entry) */
969 ptrdiff_t size_to_move = d_names_end - d_names_start;
970 memmove(dst, d_names_start, size_to_move);
972 /* fix up pointers to the d_names */
973 for(unsigned i = 0; i < entry_count; i++)
974 dircache_root[i].d_name -= offset;
976 d_names_start -= offset;
977 d_names_end -= offset;
978 dot -= offset;
979 dotdot -= offset;
981 /* equivalent to dircache_size + DIRCACHE_RESERVE + align */
982 allocated_size = (d_names_end - buf);
983 reserve_used = 0;
985 core_shrink(dircache_handle, dircache_root, allocated_size);
986 return res;
987 fail:
988 dircache_disable();
989 return res;
993 * Main initialization function that must be called before any other
994 * operations within the dircache.
996 void dircache_init(void)
998 int i;
999 int thread_id __attribute__((unused));
1001 dircache_initialized = false;
1002 dircache_initializing = false;
1004 memset(opendirs, 0, sizeof(opendirs));
1005 for (i = 0; i < MAX_OPEN_DIRS; i++)
1007 opendirs[i].theent.d_name = opendir_dnames[i];
1010 queue_init(&dircache_queue, true);
1011 thread_id = create_thread(dircache_thread, dircache_stack,
1012 sizeof(dircache_stack), 0, dircache_thread_name
1013 IF_PRIO(, PRIORITY_BACKGROUND)
1014 IF_COP(, CPU));
1015 #ifdef HAVE_IO_PRIORITY
1016 thread_set_io_priority(thread_id,IO_PRIORITY_BACKGROUND);
1017 #endif
1022 * Returns true if dircache has been initialized and is ready to be used.
1024 bool dircache_is_enabled(void)
1026 return dircache_initialized;
1030 * Returns true if dircache is being initialized.
1032 bool dircache_is_initializing(void)
1034 return dircache_initializing || thread_enabled;
1038 * Set application flags used to determine if dircache is still intact.
1040 void dircache_set_appflag(long mask)
1042 appflags |= mask;
1046 * Get application flags used to determine if dircache is still intact.
1048 bool dircache_get_appflag(long mask)
1050 return dircache_is_enabled() && (appflags & mask);
1054 * Returns the current number of entries (directories and files) in the cache.
1056 int dircache_get_entry_count(void)
1058 return entry_count;
1062 * Returns the allocated space for dircache (without reserve space).
1064 int dircache_get_cache_size(void)
1066 return dircache_is_enabled() ? dircache_size : 0;
1070 * Returns how many bytes of the reserve allocation for live cache
1071 * updates have been used.
1073 int dircache_get_reserve_used(void)
1075 return dircache_is_enabled() ? reserve_used : 0;
1079 * Returns the time in kernel ticks that took to build the cache.
1081 int dircache_get_build_ticks(void)
1083 return dircache_is_enabled() ? cache_build_ticks : 0;
1087 * Disables dircache without freeing the buffer (so it can be re-enabled
1088 * afterwards with dircache_resume() or dircache_build()), usually
1089 * called when accepting an usb connection */
1090 void dircache_suspend(void)
1092 int i;
1093 bool cache_in_use;
1095 if (thread_enabled)
1096 queue_post(&dircache_queue, DIRCACHE_STOP, 0);
1098 while (thread_enabled)
1099 sleep(1);
1100 dircache_initialized = false;
1102 logf("Waiting for cached dirs to release");
1103 do {
1104 cache_in_use = false;
1105 for (i = 0; i < MAX_OPEN_DIRS; i++) {
1106 if (!opendirs[i].regulardir && opendirs[i].busy)
1108 cache_in_use = true;
1109 sleep(1);
1110 break ;
1113 } while (cache_in_use) ;
1115 logf("Cache released");
1116 entry_count = 0;
1120 * Re-enables the dircache if previous suspended by dircache_suspend
1121 * or dircache_steal_buffer(), re-using the already allocated buffer
1123 * Returns true if the background build is started, false otherwise
1124 * (e.g. if no buffer was previously allocated)
1126 bool dircache_resume(void)
1128 bool ret = allocated_size > 0;
1129 if (ret) /* only resume if already allocated */
1130 ret = (dircache_build(0) > 0);
1132 return (allocated_size > 0);
1136 * Disables the dircache entirely. Usually called on shutdown or when
1137 * deactivated
1139 void dircache_disable(void)
1141 dircache_suspend();
1142 dircache_free();
1146 * Steal the allocated dircache buffer and disable dircache.
1148 void* dircache_steal_buffer(size_t *size)
1150 dircache_suspend();
1151 if (dircache_size == 0)
1153 *size = 0;
1154 return NULL;
1157 /* since we give up the buffer (without freeing), it must not move anymore */
1158 dont_move = true;
1159 *size = dircache_size + (DIRCACHE_RESERVE-reserve_used);
1161 return dircache_root;
1165 * Usermode function to return dircache_entry index to the given path.
1167 static int dircache_get_entry_id_ex(const char *filename, bool go_down)
1169 if (!dircache_initialized || filename == NULL)
1170 return -1;
1172 struct dircache_entry* res = dircache_get_entry(filename, go_down);
1173 return res ? res - dircache_root : -1;
1176 int dircache_get_entry_id(const char* filename)
1178 return dircache_get_entry_id_ex(filename, false);
1182 * Internal: Get the startcluster for the index
1184 long _dircache_get_entry_startcluster(int id)
1186 return get_entry(id)->startcluster;
1190 * Internal: Get the struct dirinfo for the index
1192 struct dirinfo* _dircache_get_entry_dirinfo(int id)
1194 return &get_entry(id)->info;
1198 * build a path from an entry upto the root using recursion
1200 * it appends '/' after strlcat, therefore buf[0] needs to be prepared with '/'
1201 * and it will leave a trailing '/'
1203 * returns the position of that trailing '/' so it can be deleted afterwards
1204 * (or, in case of truncation, the position of the nul byte */
1205 static size_t copy_path_helper(const struct dircache_entry *entry, char *buf, size_t size)
1207 int offset = 1;
1208 /* has parent? */
1209 if (entry->up)
1210 offset += copy_path_helper(entry->up, buf, size);
1212 size_t len = strlcpy(buf+offset, entry->d_name, size - offset) + offset;
1213 if (len < size)
1215 buf[len++] = '/';
1216 buf[len] = '\0';
1218 return len-1;
1221 * Function to copy the full absolute path from dircache to the given buffer
1222 * using the given dircache_entry pointer.
1224 * Returns the size of the resulting string, or 0 if an error occured
1226 size_t dircache_copy_path(int index, char *buf, size_t size)
1228 if (!size || !buf || index < 0)
1229 return 0;
1231 buf[0] = '/';
1232 size_t res = copy_path_helper(&dircache_root[index], buf, size - 1);
1233 /* fixup trailing '/' */
1234 buf[res] = '\0';
1235 return res;
1238 /* --- Directory cache live updating functions --- */
1239 static int block_until_ready(void)
1241 /* Block until dircache has been built. */
1242 while (!dircache_initialized && dircache_is_initializing())
1243 sleep(1);
1245 if (!dircache_initialized)
1246 return -1;
1248 return 0;
1251 static struct dircache_entry* dircache_new_entry(const char *path, int attribute)
1253 struct dircache_entry *entry;
1254 char basedir[MAX_PATH*2];
1255 char *new;
1256 long last_cache_size = dircache_size;
1258 strlcpy(basedir, path, sizeof(basedir));
1259 new = strrchr(basedir, '/');
1260 if (new == NULL)
1262 logf("error occurred");
1263 dircache_initialized = false;
1264 return NULL;
1267 *new = '\0';
1268 new++;
1270 entry = dircache_get_entry(basedir, true);
1271 if (entry == NULL)
1273 logf("basedir not found!");
1274 logf("%s", basedir);
1275 dircache_initialized = false;
1276 return NULL;
1279 if (reserve_used + 2*sizeof(struct dircache_entry) + strlen(new)+1
1280 >= DIRCACHE_RESERVE)
1282 logf("not enough space");
1283 dircache_initialized = false;
1284 return NULL;
1287 while (entry->next != NULL)
1288 entry = entry->next;
1290 if (entry->d_name != NULL)
1292 entry = dircache_gen_next(entry);
1293 if (entry == NULL)
1295 dircache_initialized = false;
1296 return NULL;
1300 size_t size = strlen(new) + 1;
1301 entry->d_name = (d_names_start -= size);
1302 entry->startcluster = 0;
1303 memset(&entry->info, 0, sizeof(entry->info));
1304 entry->info.attribute = attribute;
1306 strcpy(entry->d_name, new);
1307 dircache_size += size;
1309 if (attribute & ATTR_DIRECTORY)
1311 logf("gen_down");
1312 dircache_gen_down(entry);
1315 reserve_used += dircache_size - last_cache_size;
1317 return entry;
1320 void dircache_bind(int fd, const char *path)
1322 struct dircache_entry *entry;
1324 /* Queue requests until dircache has been built. */
1325 if (!dircache_initialized && dircache_is_initializing())
1327 if (fdbind_idx >= MAX_PENDING_BINDINGS)
1328 return ;
1329 strlcpy(fdbind_cache[fdbind_idx].path, path,
1330 sizeof(fdbind_cache[fdbind_idx].path));
1331 fdbind_cache[fdbind_idx].fd = fd;
1332 fdbind_idx++;
1333 return ;
1336 if (!dircache_initialized)
1337 return ;
1339 logf("bind: %d/%s", fd, path);
1340 entry = dircache_get_entry(path, false);
1341 if (entry == NULL)
1343 logf("not found!");
1344 dircache_initialized = false;
1345 return ;
1348 fd_bindings[fd] = entry;
1351 void dircache_update_filesize(int fd, long newsize, long startcluster)
1353 if (!dircache_initialized || fd < 0)
1354 return ;
1356 if (fd_bindings[fd] == NULL)
1358 logf("dircache fd(%d) access error", fd);
1359 dircache_initialized = false;
1360 return ;
1363 fd_bindings[fd]->info.size = newsize;
1364 fd_bindings[fd]->startcluster = startcluster;
1366 void dircache_update_filetime(int fd)
1368 #if CONFIG_RTC == 0
1369 (void)fd;
1370 #else
1371 short year;
1372 struct tm *now = get_time();
1373 if (!dircache_initialized || fd < 0)
1374 return ;
1376 if (fd_bindings[fd] == NULL)
1378 logf("dircache fd access error");
1379 dircache_initialized = false;
1380 return ;
1382 year = now->tm_year+1900-1980;
1383 fd_bindings[fd]->info.wrtdate = (((year)&0x7f)<<9) |
1384 (((now->tm_mon+1)&0xf)<<5) |
1385 (((now->tm_mday)&0x1f));
1386 fd_bindings[fd]->info.wrttime = (((now->tm_hour)&0x1f)<<11) |
1387 (((now->tm_min)&0x3f)<<5) |
1388 (((now->tm_sec/2)&0x1f));
1389 #endif
1392 void dircache_mkdir(const char *path)
1393 { /* Test ok. */
1394 if (block_until_ready())
1395 return ;
1398 logf("mkdir: %s", path);
1399 dircache_new_entry(path, ATTR_DIRECTORY);
1402 void dircache_rmdir(const char *path)
1403 { /* Test ok. */
1404 struct dircache_entry *entry;
1406 if (block_until_ready())
1407 return ;
1409 logf("rmdir: %s", path);
1410 entry = dircache_get_entry(path, false);
1411 if (entry == NULL || entry->down == NULL)
1413 logf("not found or not a directory!");
1414 dircache_initialized = false;
1415 return ;
1418 entry->down = NULL;
1419 entry->d_name = NULL;
1422 /* Remove a file from cache */
1423 void dircache_remove(const char *name)
1424 { /* Test ok. */
1425 struct dircache_entry *entry;
1427 if (block_until_ready())
1428 return ;
1430 logf("remove: %s", name);
1432 entry = dircache_get_entry(name, false);
1434 if (entry == NULL)
1436 logf("not found!");
1437 dircache_initialized = false;
1438 return ;
1441 entry->d_name = NULL;
1444 void dircache_rename(const char *oldpath, const char *newpath)
1445 { /* Test ok. */
1446 struct dircache_entry *entry, *newentry;
1447 struct dircache_entry oldentry;
1448 char absolute_path[MAX_PATH*2];
1449 char *p;
1451 if (block_until_ready())
1452 return ;
1454 logf("rename: %s->%s", oldpath, newpath);
1456 entry = dircache_get_entry(oldpath, false);
1457 if (entry == NULL)
1459 logf("not found!");
1460 dircache_initialized = false;
1461 return ;
1464 /* Delete the old entry. */
1465 entry->d_name = NULL;
1467 /** If we rename the same filename twice in a row, we need to
1468 * save the data, because the entry will be re-used. */
1469 oldentry = *entry;
1471 /* Generate the absolute path for destination if necessary. */
1472 if (newpath[0] != '/')
1474 strlcpy(absolute_path, oldpath, sizeof(absolute_path));
1475 p = strrchr(absolute_path, '/');
1476 if (!p)
1478 logf("Invalid path");
1479 dircache_initialized = false;
1480 return ;
1483 *p = '\0';
1484 strlcpy(p, absolute_path, sizeof(absolute_path)-strlen(p));
1485 newpath = absolute_path;
1488 newentry = dircache_new_entry(newpath, entry->info.attribute);
1489 if (newentry == NULL)
1491 dircache_initialized = false;
1492 return ;
1495 newentry->down = oldentry.down;
1496 newentry->startcluster = oldentry.startcluster;
1497 newentry->info.size = oldentry.info.size;
1498 newentry->info.wrtdate = oldentry.info.wrtdate;
1499 newentry->info.wrttime = oldentry.info.wrttime;
1502 void dircache_add_file(const char *path, long startcluster)
1504 struct dircache_entry *entry;
1506 if (block_until_ready())
1507 return ;
1509 logf("add file: %s", path);
1510 entry = dircache_new_entry(path, 0);
1511 if (entry == NULL)
1512 return ;
1514 entry->startcluster = startcluster;
1517 static bool is_disable_msg_pending(void)
1519 return check_event_queue();
1522 DIR_CACHED* opendir_cached(const char* name)
1524 int dd;
1525 DIR_CACHED* pdir = opendirs;
1527 if ( name[0] != '/' )
1529 DEBUGF("Only absolute paths supported right now\n");
1530 return NULL;
1533 /* find a free dir descriptor */
1534 for ( dd=0; dd<MAX_OPEN_DIRS; dd++, pdir++)
1535 if ( !pdir->busy )
1536 break;
1538 if ( dd == MAX_OPEN_DIRS )
1540 DEBUGF("Too many dirs open\n");
1541 errno = EMFILE;
1542 return NULL;
1545 pdir->busy = true;
1547 if (!dircache_initialized || is_disable_msg_pending())
1549 pdir->internal_entry = -1;
1550 pdir->regulardir = opendir_uncached(name);
1552 else
1554 pdir->regulardir = NULL;
1555 pdir->internal_entry = dircache_get_entry_id_ex(name, true);
1556 pdir->theent.info.attribute = -1; /* used to make readdir_cached aware of the first call */
1559 if (pdir->internal_entry == -1 && pdir->regulardir == NULL)
1561 pdir->busy = false;
1562 return NULL;
1565 return pdir;
1568 struct dirent_cached* readdir_cached(DIR_CACHED* dir)
1570 struct dircache_entry *ce = get_entry(dir->internal_entry);
1571 struct dirent_uncached *regentry;
1573 if (!dir->busy)
1574 return NULL;
1576 if (dir->regulardir != NULL)
1578 regentry = readdir_uncached(dir->regulardir);
1579 if (regentry == NULL)
1580 return NULL;
1582 strlcpy(dir->theent.d_name, regentry->d_name, MAX_PATH);
1583 dir->theent.startcluster = regentry->startcluster;
1584 dir->theent.info = regentry->info;
1586 return &dir->theent;
1589 /* if theent.attribute=-1 then this is the first call */
1590 /* otherwise, this is is not so we first take the entry's ->next */
1591 /* NOTE: normal file can't have attribute=-1 */
1592 if(dir->theent.info.attribute != -1)
1593 ce = ce->next;
1594 /* skip unused entries */
1595 while(ce != NULL && ce->d_name == NULL)
1596 ce = ce->next;
1598 if (ce == NULL)
1599 return NULL;
1601 strlcpy(dir->theent.d_name, ce->d_name, MAX_PATH);
1602 /* Can't do `dir->theent = *ce`
1603 because that modifies the d_name pointer. */
1604 dir->theent.startcluster = ce->startcluster;
1605 dir->theent.info = ce->info;
1606 dir->internal_entry = ce - dircache_root;
1608 //logf("-> %s", ce->d_name);
1609 return &dir->theent;
1612 int closedir_cached(DIR_CACHED* dir)
1614 if (!dir->busy)
1615 return -1;
1617 dir->busy=false;
1618 if (dir->regulardir != NULL)
1619 return closedir_uncached(dir->regulardir);
1621 return 0;
1624 int mkdir_cached(const char *name)
1626 int rc=mkdir_uncached(name);
1627 if (rc >= 0)
1628 dircache_mkdir(name);
1629 return(rc);
1632 int rmdir_cached(const char* name)
1634 int rc=rmdir_uncached(name);
1635 if(rc >= 0)
1636 dircache_rmdir(name);
1637 return(rc);