Simulate usb plugging on the sim better using sim_tasks.
[maemo-rb.git] / firmware / common / dircache.c
blob8d264a3e7c8442d63aa4adb4def0966efe10c128
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 /* relocate the cache */
154 ptrdiff_t diff = new - current;
155 for(unsigned i = 0; i < entry_count; i++)
157 if (dircache_root[i].d_name)
158 dircache_root[i].d_name += diff;
159 if (dircache_root[i].next_char)
160 dircache_root[i].next_char += diff;
161 if (dircache_root[i].up_char)
162 dircache_root[i].up_char += diff;
163 if (dircache_root[i].down_char)
164 dircache_root[i].down_char += diff;
166 dircache_root = new;
168 d_names_start += diff;
169 d_names_end += diff;
170 dot += diff;
171 dotdot += diff;
173 return BUFLIB_CB_OK;
176 static struct buflib_callbacks ops = {
177 .move_callback = move_callback,
178 .shrink_callback = NULL,
181 #ifdef HAVE_EEPROM_SETTINGS
183 * Open the dircache file to save a snapshot on disk
185 static int open_dircache_file(unsigned flags, int permissions)
187 if (permissions != 0)
188 return open(DIRCACHE_FILE, flags, permissions);
190 return open(DIRCACHE_FILE, flags);
194 * Remove the snapshot file
196 static int remove_dircache_file(void)
198 return remove(DIRCACHE_FILE);
200 #endif
201 /**
202 * Internal function to allocate a new dircache_entry from memory.
204 static struct dircache_entry* allocate_entry(void)
206 struct dircache_entry *next_entry;
208 if (dircache_size > allocated_size - MAX_PATH*2)
210 logf("size limit reached");
211 return NULL;
214 next_entry = &dircache_root[entry_count++];
215 next_entry->d_name = NULL;
216 next_entry->up = NULL;
217 next_entry->down = NULL;
218 next_entry->next = NULL;
220 dircache_size += sizeof(struct dircache_entry);
222 return next_entry;
226 * Internal function to allocate a dircache_entry and set
227 * ->next entry pointers.
229 static struct dircache_entry* dircache_gen_next(struct dircache_entry *ce)
231 struct dircache_entry *next_entry;
233 if ( (next_entry = allocate_entry()) == NULL)
234 return NULL;
235 next_entry->up = ce->up;
236 ce->next = next_entry;
238 return next_entry;
242 * Internal function to allocate a dircache_entry and set
243 * ->down entry pointers.
245 static struct dircache_entry* dircache_gen_down(struct dircache_entry *ce)
247 struct dircache_entry *next_entry;
249 if ( (next_entry = allocate_entry()) == NULL)
250 return NULL;
251 next_entry->up = ce;
252 ce->down = next_entry;
254 return next_entry;
258 * Returns true if there is an event waiting in the queue
259 * that requires the current operation to be aborted.
261 static bool check_event_queue(void)
263 struct queue_event ev;
265 if(!queue_peek(&dircache_queue, &ev))
266 return false;
268 switch (ev.id)
270 case DIRCACHE_STOP:
271 case SYS_USB_CONNECTED:
272 #ifdef HAVE_HOTSWAP
273 case SYS_FS_CHANGED:
274 #endif
275 return true;
278 return false;
281 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
282 /* scan and build static data (avoid redundancy on stack) */
283 static struct
285 #ifdef HAVE_MULTIVOLUME
286 int volume;
287 #endif
288 struct fat_dir *dir;
289 struct fat_direntry *direntry;
290 }sab;
292 static int sab_process_dir(unsigned long startcluster, struct dircache_entry *ce)
294 /* normally, opendir expects a full fat_dir as parent but in our case,
295 * it's completely useless because we don't modify anything
296 * WARNING: this heavily relies on current FAT implementation ! */
298 /* those field are necessary to update the FAT entry in case of modification
299 here we don't touch anything so we put dummy values */
300 sab.dir->entry = 0;
301 sab.dir->entrycount = 0;
302 sab.dir->file.firstcluster = 0;
303 /* open directory */
304 int rc = fat_opendir(IF_MV2(sab.volume,) sab.dir, startcluster, sab.dir);
305 if(rc < 0)
307 logf("fat_opendir failed: %d", rc);
308 return rc;
311 /* first pass : read dir */
312 struct dircache_entry *first_ce = ce;
314 /* read through directory */
315 while((rc = fat_getnext(sab.dir, sab.direntry)) >= 0 && sab.direntry->name[0])
317 if(!strcmp(".", sab.direntry->name) ||
318 !strcmp("..", sab.direntry->name))
319 continue;
321 size_t size = strlen(sab.direntry->name) + 1;
322 ce->d_name = (d_names_start -= size);
323 ce->startcluster = sab.direntry->firstcluster;
324 ce->info.size = sab.direntry->filesize;
325 ce->info.attribute = sab.direntry->attr;
326 ce->info.wrtdate = sab.direntry->wrtdate;
327 ce->info.wrttime = sab.direntry->wrttime;
329 strcpy(ce->d_name, sab.direntry->name);
330 dircache_size += size;
332 if(ce->info.attribute & FAT_ATTR_DIRECTORY)
333 dircache_gen_down(ce);
335 ce = dircache_gen_next(ce);
336 if(ce == NULL)
337 return -5;
339 /* When simulator is used, it's only safe to yield here. */
340 if(thread_enabled)
342 /* Stop if we got an external signal. */
343 if(check_event_queue())
344 return -6;
345 yield();
349 /* add "." and ".." */
350 ce->d_name = dot;
351 ce->info.attribute = FAT_ATTR_DIRECTORY;
352 ce->startcluster = startcluster;
353 ce->info.size = 0;
354 ce->down = first_ce;
356 ce = dircache_gen_next(ce);
358 ce->d_name = dotdot;
359 ce->info.attribute = FAT_ATTR_DIRECTORY;
360 ce->startcluster = (first_ce->up ? first_ce->up->startcluster : 0);
361 ce->info.size = 0;
362 ce->down = first_ce->up;
364 /* second pass: recurse ! */
365 ce = first_ce;
367 while(rc >= 0 && ce)
369 if(ce->d_name != NULL && ce->down != NULL && strcmp(ce->d_name, ".")
370 && strcmp(ce->d_name, ".."))
371 rc = sab_process_dir(ce->startcluster, ce->down);
373 ce = ce->next;
376 return rc;
379 /* used during the generation */
380 static struct fat_dir sab_fat_dir;
382 static int dircache_scan_and_build(IF_MV2(int volume,) struct dircache_entry *ce)
384 memset(ce, 0, sizeof(struct dircache_entry));
386 #ifdef HAVE_MULTIVOLUME
387 if (volume > 0)
389 /* broken for 100+ volumes because the format string is too small
390 * and we use that for size calculation */
391 const size_t max_len = VOL_ENUM_POS + 3;
392 ce->d_name = (d_names_start -= max_len);
393 snprintf(ce->d_name, max_len, VOL_NAMES, volume);
394 dircache_size += max_len;
395 ce->info.attribute = FAT_ATTR_DIRECTORY | FAT_ATTR_VOLUME;
396 ce->info.size = 0;
397 append_position = dircache_gen_next(ce);
398 ce = dircache_gen_down(ce);
400 #endif
402 struct fat_direntry direntry; /* ditto */
403 #ifdef HAVE_MULTIVOLUME
404 sab.volume = volume;
405 #endif
406 sab.dir = &sab_fat_dir;
407 sab.direntry = &direntry;
409 return sab_process_dir(0, ce);
411 #elif (CONFIG_PLATFORM & PLATFORM_HOSTED) /* PLATFORM_HOSTED */
412 static char sab_path[MAX_PATH];
414 static int sab_process_dir(struct dircache_entry *ce)
416 struct dirent_uncached *entry;
417 struct dircache_entry *first_ce = ce;
418 DIR_UNCACHED *dir = opendir_uncached(sab_path);
419 if(dir == NULL)
421 logf("Failed to opendir_uncached(%s)", sab_path);
422 return -1;
425 while((entry = readdir_uncached(dir)))
427 if(!strcmp(".", entry->d_name) ||
428 !strcmp("..", entry->d_name))
429 continue;
431 size_t size = strlen(entry->d_name) + 1;
432 ce->d_name = (d_names_start -= size);
433 ce->info = entry->info;
435 strcpy(ce->d_name, entry->d_name);
436 dircache_size += size;
438 if(entry->info.attribute & ATTR_DIRECTORY)
440 dircache_gen_down(ce);
441 if(ce->down == NULL)
443 closedir_uncached(dir);
444 return -1;
446 /* save current paths size */
447 int pathpos = strlen(sab_path);
448 /* append entry */
449 strlcpy(&sab_path[pathpos], "/", sizeof(sab_path) - pathpos);
450 strlcpy(&sab_path[pathpos+1], entry->d_name, sizeof(sab_path) - pathpos - 1);
452 int rc = sab_process_dir(ce->down);
453 /* restore path */
454 sab_path[pathpos] = '\0';
456 if(rc < 0)
458 closedir_uncached(dir);
459 return rc;
463 ce = dircache_gen_next(ce);
464 if(ce == NULL)
465 return -5;
467 /* When simulator is used, it's only safe to yield here. */
468 if(thread_enabled)
470 /* Stop if we got an external signal. */
471 if(check_event_queue())
472 return -1;
473 yield();
477 /* add "." and ".." */
478 ce->d_name = dot;
479 ce->info.attribute = ATTR_DIRECTORY;
480 ce->info.size = 0;
481 ce->down = first_ce;
483 ce = dircache_gen_next(ce);
485 ce->d_name = dotdot;
486 ce->info.attribute = ATTR_DIRECTORY;
487 ce->info.size = 0;
488 ce->down = first_ce->up;
490 closedir_uncached(dir);
491 return 0;
494 static int dircache_scan_and_build(IF_MV2(int volume,) struct dircache_entry *ce)
496 #ifdef HAVE_MULTIVOLUME
497 (void) volume;
498 #endif
499 memset(ce, 0, sizeof(struct dircache_entry));
501 strlcpy(sab_path, "/", sizeof sab_path);
502 return sab_process_dir(ce);
504 #endif /* PLATFORM_NATIVE */
507 * Internal function to get a pointer to dircache_entry for a given filename.
508 * path: Absolute path to a file or directory (see comment)
509 * go_down: Returns the first entry of the directory given by the path (see comment)
511 * As a a special case, accept path="" as an alias for "/".
512 * Also if the path omits the first '/', it will be accepted.
514 * * If get_down=true:
515 * If path="/", the returned entry is the first of root directory (ie dircache_root)
516 * Otherwise, if 'entry' is the returned value when get_down=false,
517 * the functions returns entry->down (which can be NULL)
519 * * If get_down=false:
520 * If path="/chunk_1/chunk_2/.../chunk_n" then this functions returns the entry
521 * root_entry()->chunk_1->chunk_2->...->chunk_(n-1)
522 * Which means that
523 * dircache_get_entry(path)->d_name == chunk_n
525 * If path="/", the returned entry is NULL.
526 * If the entry doesn't exist, return NULL
528 * NOTE: this functions silently handles double '/'
530 static struct dircache_entry* dircache_get_entry(const char *path, bool go_down)
532 char namecopy[MAX_PATH];
533 char* part;
534 char* end;
536 bool at_root = true;
537 struct dircache_entry *cache_entry = dircache_root;
539 strlcpy(namecopy, path, sizeof(namecopy));
541 for(part = strtok_r(namecopy, "/", &end); part; part = strtok_r(NULL, "/", &end))
543 /* If request another chunk, the current entry has to be directory
544 * and so cache_entry->down has to be non-NULL/
545 * Special case of root because it's already the first entry of the root directory
547 * NOTE: this is safe even if cache_entry->down is NULL */
548 if(!at_root)
549 cache_entry = cache_entry->down;
550 else
551 at_root = false;
553 /* scan dir for name */
554 while(cache_entry != NULL)
556 /* skip unused entries */
557 if(cache_entry->d_name == NULL)
559 cache_entry = cache_entry->next;
560 continue;
562 /* compare names */
563 if(!strcasecmp(part, cache_entry->d_name))
564 break;
565 /* go to next entry */
566 cache_entry = cache_entry->next;
569 /* handle not found case */
570 if(cache_entry == NULL)
571 return NULL;
574 /* NOTE: here cache_entry!=NULL so taking ->down is safe */
575 if(go_down)
576 return at_root ? cache_entry : cache_entry->down;
577 else
578 return at_root ? NULL : cache_entry;
581 #ifdef HAVE_EEPROM_SETTINGS
583 #define DIRCACHE_MAGIC 0x00d0c0a1
584 struct dircache_maindata {
585 long magic;
586 long size;
587 long entry_count;
588 long appflags;
589 struct dircache_entry *root_entry;
590 char *d_names_start;
594 * Function to load the internal cache structure from disk to initialize
595 * the dircache really fast and little disk access.
597 int dircache_load(void)
599 struct dircache_maindata maindata;
600 ssize_t bytes_read;
601 int fd;
603 if (dircache_initialized)
604 return -1;
606 logf("Loading directory cache");
607 dircache_size = 0;
609 fd = open_dircache_file(O_RDONLY, 0);
610 if (fd < 0)
611 return -2;
613 bytes_read = read(fd, &maindata, sizeof(struct dircache_maindata));
614 if (bytes_read != sizeof(struct dircache_maindata)
615 || maindata.magic != DIRCACHE_MAGIC || maindata.size <= 0)
617 logf("Dircache file header error");
618 close(fd);
619 remove_dircache_file();
620 return -3;
623 allocated_size = maindata.size + DIRCACHE_RESERVE;
624 dircache_handle = core_alloc_ex("dircache", allocated_size, &ops);
625 /* block movement during upcoming I/O */
626 dont_move = true;
627 dircache_root = core_get_data(dircache_handle);
628 ALIGN_BUFFER(dircache_root, allocated_size, sizeof(struct dircache_entry*));
629 entry_count = maindata.entry_count;
630 appflags = maindata.appflags;
632 /* read the dircache file into memory,
633 * start with the struct dircache_entries */
634 ssize_t bytes_to_read = entry_count*sizeof(struct dircache_entry);
635 bytes_read = read(fd, dircache_root, bytes_to_read);
637 if (bytes_read != bytes_to_read)
639 logf("Dircache read failed #1");
640 return -6;
643 /* continue with the d_names. Fix up pointers to them if needed */
644 bytes_to_read = maindata.size - bytes_to_read;
645 d_names_start = (char*)dircache_root + allocated_size - bytes_to_read;
646 bytes_read = read(fd, d_names_start, bytes_to_read);
647 close(fd);
648 remove_dircache_file();
649 if (bytes_read != bytes_to_read)
651 logf("Dircache read failed #2");
652 return -7;
655 d_names_end = d_names_start + bytes_read;
656 dot = d_names_end - sizeof(".");
657 dotdot = dot - sizeof("..");
659 /* d_names are in reverse order, so the last entry points to the first string */
660 ptrdiff_t offset_d_names = maindata.d_names_start - d_names_start;
661 ptrdiff_t offset_entries = maindata.root_entry - dircache_root;
662 offset_entries *= sizeof(struct dircache_entry); /* make it bytes */
664 /* offset_entries is less likely to differ, so check if it's 0 in the loop
665 * offset_d_names however is almost always non-zero, since dircache_save()
666 * creates a file which causes the reserve buffer to be used. since
667 * we allocate a new, empty DIRCACHE_RESERVE here, the strings are
668 * farther behind */
669 if (offset_entries != 0 || offset_d_names != 0)
671 for(unsigned i = 0; i < entry_count; i++)
673 if (dircache_root[i].d_name)
674 dircache_root[i].d_name -= offset_d_names;
676 if (offset_entries == 0)
677 continue;
678 if (dircache_root[i].next_char)
679 dircache_root[i].next_char -= offset_entries;
680 if (dircache_root[i].up_char)
681 dircache_root[i].up_char -= offset_entries;
682 if (dircache_root[i].down_char)
683 dircache_root[i].down_char -= offset_entries;
687 /* Cache successfully loaded. */
688 dircache_size = maindata.size;
689 reserve_used = 0;
690 logf("Done, %ld KiB used", dircache_size / 1024);
691 dircache_initialized = true;
692 memset(fd_bindings, 0, sizeof(fd_bindings));
693 dont_move = false;
695 return 0;
699 * Function to save the internal cache stucture to disk for fast loading
700 * on boot.
702 int dircache_save(void)
704 struct dircache_maindata maindata;
705 int fd;
706 unsigned long bytes_written;
708 remove_dircache_file();
710 if (!dircache_initialized)
711 return -1;
713 logf("Saving directory cache");
714 dont_move = true;
715 fd = open_dircache_file(O_WRONLY | O_CREAT | O_TRUNC, 0666);
717 maindata.magic = DIRCACHE_MAGIC;
718 maindata.size = dircache_size;
719 maindata.root_entry = dircache_root;
720 maindata.d_names_start = d_names_start;
721 maindata.entry_count = entry_count;
722 maindata.appflags = appflags;
724 /* Save the info structure */
725 bytes_written = write(fd, &maindata, sizeof(struct dircache_maindata));
726 if (bytes_written != sizeof(struct dircache_maindata))
728 close(fd);
729 logf("dircache: write failed #1");
730 return -2;
733 /* Dump whole directory cache to disk
734 * start by writing the dircache_entries */
735 size_t bytes_to_write = entry_count*sizeof(struct dircache_entry);
736 bytes_written = write(fd, dircache_root, bytes_to_write);
737 if (bytes_written != bytes_to_write)
739 logf("dircache: write failed #2");
740 return -3;
743 /* continue with the d_names */
744 bytes_to_write = d_names_end - d_names_start;
745 bytes_written = write(fd, d_names_start, bytes_to_write);
746 close(fd);
747 if (bytes_written != bytes_to_write)
749 logf("dircache: write failed #3");
750 return -4;
753 dont_move = false;
754 return 0;
756 #endif /* HAVE_EEPROM_SETTINGS */
759 * Internal function which scans the disk and creates the dircache structure.
761 static int dircache_do_rebuild(void)
763 struct dircache_entry* root_entry;
764 unsigned int start_tick;
765 int i;
767 /* Measure how long it takes build the cache. */
768 start_tick = current_tick;
769 dircache_initializing = true;
770 appflags = 0;
772 /* reset dircache and alloc root entry */
773 entry_count = 0;
774 root_entry = allocate_entry();
775 dont_move = true;
777 #ifdef HAVE_MULTIVOLUME
778 append_position = root_entry;
780 for (i = NUM_VOLUMES; i >= 0; i--)
782 if (fat_ismounted(i))
784 #endif
785 cpu_boost(true);
786 #ifdef HAVE_MULTIVOLUME
787 if (dircache_scan_and_build(IF_MV2(i,) append_position) < 0)
788 #else
789 if (dircache_scan_and_build(IF_MV2(0,) root_entry) < 0)
790 #endif /* HAVE_MULTIVOLUME */
792 logf("dircache_scan_and_build failed");
793 cpu_boost(false);
794 dircache_size = 0;
795 dircache_initializing = false;
796 dont_move = false;
797 return -2;
799 cpu_boost(false);
800 #ifdef HAVE_MULTIVOLUME
803 #endif
805 logf("Done, %ld KiB used", dircache_size / 1024);
807 dircache_initialized = true;
808 dircache_initializing = false;
809 cache_build_ticks = current_tick - start_tick;
811 /* Initialized fd bindings. */
812 memset(fd_bindings, 0, sizeof(fd_bindings));
813 for (i = 0; i < fdbind_idx; i++)
814 dircache_bind(fdbind_cache[i].fd, fdbind_cache[i].path);
815 fdbind_idx = 0;
817 if (thread_enabled)
819 if (allocated_size - dircache_size < DIRCACHE_RESERVE)
820 reserve_used = DIRCACHE_RESERVE - (allocated_size - dircache_size);
823 dont_move = false;
824 return 1;
828 * Free all associated resources, if any */
829 static void dircache_free(void)
831 if (dircache_handle > 0)
832 dircache_handle = core_free(dircache_handle);
833 dircache_size = allocated_size = 0;
837 * Internal thread that controls transparent cache building.
839 static void dircache_thread(void)
841 struct queue_event ev;
843 while (1)
845 queue_wait(&dircache_queue, &ev);
847 switch (ev.id)
849 #ifdef HAVE_HOTSWAP
850 case SYS_FS_CHANGED:
851 if (!dircache_initialized)
852 break;
853 dircache_initialized = false;
854 #endif
855 case DIRCACHE_BUILD:
856 thread_enabled = true;
857 if (dircache_do_rebuild() < 0)
858 dircache_free();
859 thread_enabled = false;
860 break ;
862 case DIRCACHE_STOP:
863 logf("Stopped the rebuilding.");
864 dircache_initialized = false;
865 break ;
867 case SYS_USB_CONNECTED:
868 usb_acknowledge(SYS_USB_CONNECTED_ACK);
869 usb_wait_for_disconnect(&dircache_queue);
870 break ;
875 static void generate_dot_d_names(void)
877 dot = (d_names_start -= sizeof("."));
878 dotdot = (d_names_start -= sizeof(".."));
879 dircache_size += sizeof(".") + sizeof("..");
880 strcpy(dot, ".");
881 strcpy(dotdot, "..");
885 * Start scanning the disk to build the dircache.
886 * Either transparent or non-transparent build method is used.
888 int dircache_build(int last_size)
890 if (dircache_initialized || thread_enabled)
891 return -3;
893 logf("Building directory cache");
894 #ifdef HAVE_EEPROM_SETTINGS
895 remove_dircache_file();
896 #endif
898 /* Background build, dircache has been previously allocated and */
899 if (allocated_size > MAX(last_size, 0))
901 d_names_start = d_names_end;
902 dircache_size = 0;
903 reserve_used = 0;
904 thread_enabled = true;
905 dircache_initializing = true;
906 generate_dot_d_names();
908 queue_post(&dircache_queue, DIRCACHE_BUILD, 0);
909 return 2;
912 /* start by freeing, as we possibly re-allocate */
913 dircache_free();
915 if (last_size > DIRCACHE_RESERVE && last_size < DIRCACHE_LIMIT )
917 allocated_size = last_size + DIRCACHE_RESERVE;
918 dircache_handle = core_alloc_ex("dircache", allocated_size, &ops);
919 dircache_root = core_get_data(dircache_handle);
920 ALIGN_BUFFER(dircache_root, allocated_size, sizeof(struct dircache_entry*));
921 d_names_start = d_names_end = ((char*)dircache_root)+allocated_size-1;
922 dircache_size = 0;
923 thread_enabled = true;
924 generate_dot_d_names();
926 /* Start a transparent rebuild. */
927 queue_post(&dircache_queue, DIRCACHE_BUILD, 0);
928 return 3;
931 /* We'll use the entire audiobuf to allocate the dircache
932 * struct dircache_entrys are allocated from the beginning
933 * and their corresponding d_name from the end
934 * after generation the buffer will be compacted with DIRCACHE_RESERVE
935 * free bytes inbetween */
936 size_t available = audio_buffer_available();
937 /* try to allocate at least 1MB, the more the better */
938 if (available < 1<<20) available = 1<<20;
939 if (available > DIRCACHE_LIMIT) available = DIRCACHE_LIMIT;
941 dircache_handle = core_alloc_ex("dircache", available, &ops);
942 if (dircache_handle <= 0)
943 return -1; /* that was not successful, should try rebooting */
944 char* buf = core_get_data(dircache_handle);
945 dircache_root = (struct dircache_entry*)ALIGN_UP(buf,
946 sizeof(struct dircache_entry*));
947 d_names_start = d_names_end = buf + available - 1;
948 dircache_size = 0;
949 generate_dot_d_names();
951 /* Start a non-transparent rebuild. */
952 int res = dircache_do_rebuild();
953 if (res < 0)
954 goto fail;
956 /* now compact the dircache buffer */
957 char* dst = ((char*)&dircache_root[entry_count] + DIRCACHE_RESERVE);
958 ptrdiff_t offset = d_names_start - dst;
959 if (offset <= 0) /* something went wrong */
961 res = -1;
962 goto fail;
965 /* memmove d_names down, there's a possibility of overlap
966 * equivaent to dircache_size - entry_count*sizeof(struct dircache_entry) */
967 ptrdiff_t size_to_move = d_names_end - d_names_start;
968 memmove(dst, d_names_start, size_to_move);
970 /* fix up pointers to the d_names */
971 for(unsigned i = 0; i < entry_count; i++)
972 dircache_root[i].d_name -= offset;
974 d_names_start -= offset;
975 d_names_end -= offset;
976 dot -= offset;
977 dotdot -= offset;
979 /* equivalent to dircache_size + DIRCACHE_RESERVE + align */
980 allocated_size = (d_names_end - buf);
981 reserve_used = 0;
983 core_shrink(dircache_handle, dircache_root, allocated_size);
984 return res;
985 fail:
986 dircache_disable();
987 return res;
991 * Main initialization function that must be called before any other
992 * operations within the dircache.
994 void dircache_init(void)
996 int i;
997 int thread_id __attribute__((unused));
999 dircache_initialized = false;
1000 dircache_initializing = false;
1002 memset(opendirs, 0, sizeof(opendirs));
1003 for (i = 0; i < MAX_OPEN_DIRS; i++)
1005 opendirs[i].theent.d_name = opendir_dnames[i];
1008 queue_init(&dircache_queue, true);
1009 thread_id = create_thread(dircache_thread, dircache_stack,
1010 sizeof(dircache_stack), 0, dircache_thread_name
1011 IF_PRIO(, PRIORITY_BACKGROUND)
1012 IF_COP(, CPU));
1013 #ifdef HAVE_IO_PRIORITY
1014 thread_set_io_priority(thread_id,IO_PRIORITY_BACKGROUND);
1015 #endif
1020 * Returns true if dircache has been initialized and is ready to be used.
1022 bool dircache_is_enabled(void)
1024 return dircache_initialized;
1028 * Returns true if dircache is being initialized.
1030 bool dircache_is_initializing(void)
1032 return dircache_initializing || thread_enabled;
1036 * Set application flags used to determine if dircache is still intact.
1038 void dircache_set_appflag(long mask)
1040 appflags |= mask;
1044 * Get application flags used to determine if dircache is still intact.
1046 bool dircache_get_appflag(long mask)
1048 return dircache_is_enabled() && (appflags & mask);
1052 * Returns the current number of entries (directories and files) in the cache.
1054 int dircache_get_entry_count(void)
1056 return entry_count;
1060 * Returns the allocated space for dircache (without reserve space).
1062 int dircache_get_cache_size(void)
1064 return dircache_is_enabled() ? dircache_size : 0;
1068 * Returns how many bytes of the reserve allocation for live cache
1069 * updates have been used.
1071 int dircache_get_reserve_used(void)
1073 return dircache_is_enabled() ? reserve_used : 0;
1077 * Returns the time in kernel ticks that took to build the cache.
1079 int dircache_get_build_ticks(void)
1081 return dircache_is_enabled() ? cache_build_ticks : 0;
1085 * Disables dircache without freeing the buffer (so it can be re-enabled
1086 * afterwards with dircache_resume() or dircache_build()), usually
1087 * called when accepting an usb connection */
1088 void dircache_suspend(void)
1090 int i;
1091 bool cache_in_use;
1093 if (thread_enabled)
1094 queue_post(&dircache_queue, DIRCACHE_STOP, 0);
1096 while (thread_enabled)
1097 sleep(1);
1098 dircache_initialized = false;
1100 logf("Waiting for cached dirs to release");
1101 do {
1102 cache_in_use = false;
1103 for (i = 0; i < MAX_OPEN_DIRS; i++) {
1104 if (!opendirs[i].regulardir && opendirs[i].busy)
1106 cache_in_use = true;
1107 sleep(1);
1108 break ;
1111 } while (cache_in_use) ;
1113 logf("Cache released");
1114 entry_count = 0;
1118 * Re-enables the dircache if previous suspended by dircache_suspend
1119 * or dircache_steal_buffer(), re-using the already allocated buffer
1121 * Returns true if the background build is started, false otherwise
1122 * (e.g. if no buffer was previously allocated)
1124 bool dircache_resume(void)
1126 bool ret = allocated_size > 0;
1127 if (ret) /* only resume if already allocated */
1128 ret = (dircache_build(0) > 0);
1130 return (allocated_size > 0);
1134 * Disables the dircache entirely. Usually called on shutdown or when
1135 * deactivated
1137 void dircache_disable(void)
1139 dircache_suspend();
1140 dircache_free();
1144 * Steal the allocated dircache buffer and disable dircache.
1146 void* dircache_steal_buffer(size_t *size)
1148 dircache_suspend();
1149 if (dircache_size == 0)
1151 *size = 0;
1152 return NULL;
1155 /* since we give up the buffer (without freeing), it must not move anymore */
1156 dont_move = true;
1157 *size = dircache_size + (DIRCACHE_RESERVE-reserve_used);
1159 return dircache_root;
1163 * Usermode function to return dircache_entry index to the given path.
1165 static int dircache_get_entry_id_ex(const char *filename, bool go_down)
1167 if (!dircache_initialized || filename == NULL)
1168 return -1;
1170 struct dircache_entry* res = dircache_get_entry(filename, go_down);
1171 return res ? res - dircache_root : -1;
1174 int dircache_get_entry_id(const char* filename)
1176 return dircache_get_entry_id_ex(filename, false);
1180 * Internal: Get the startcluster for the index
1182 long _dircache_get_entry_startcluster(int id)
1184 return get_entry(id)->startcluster;
1188 * Internal: Get the struct dirinfo for the index
1190 struct dirinfo* _dircache_get_entry_dirinfo(int id)
1192 return &get_entry(id)->info;
1196 * build a path from an entry upto the root using recursion
1198 * it appends '/' after strlcat, therefore buf[0] needs to be prepared with '/'
1199 * and it will leave a trailing '/'
1201 * returns the position of that trailing '/' so it can be deleted afterwards
1202 * (or, in case of truncation, the position of the nul byte */
1203 static size_t copy_path_helper(const struct dircache_entry *entry, char *buf, size_t size)
1205 int offset = 1;
1206 /* has parent? */
1207 if (entry->up)
1208 offset += copy_path_helper(entry->up, buf, size);
1210 size_t len = strlcpy(buf+offset, entry->d_name, size - offset) + offset;
1211 if (len < size)
1213 buf[len++] = '/';
1214 buf[len] = '\0';
1216 return len-1;
1219 * Function to copy the full absolute path from dircache to the given buffer
1220 * using the given dircache_entry pointer.
1222 * Returns the size of the resulting string, or 0 if an error occured
1224 size_t dircache_copy_path(int index, char *buf, size_t size)
1226 if (!size || !buf || index < 0)
1227 return 0;
1229 buf[0] = '/';
1230 size_t res = copy_path_helper(&dircache_root[index], buf, size - 1);
1231 /* fixup trailing '/' */
1232 buf[res] = '\0';
1233 return res;
1236 /* --- Directory cache live updating functions --- */
1237 static int block_until_ready(void)
1239 /* Block until dircache has been built. */
1240 while (!dircache_initialized && dircache_is_initializing())
1241 sleep(1);
1243 if (!dircache_initialized)
1244 return -1;
1246 return 0;
1249 static struct dircache_entry* dircache_new_entry(const char *path, int attribute)
1251 struct dircache_entry *entry;
1252 char basedir[MAX_PATH*2];
1253 char *new;
1254 long last_cache_size = dircache_size;
1256 strlcpy(basedir, path, sizeof(basedir));
1257 new = strrchr(basedir, '/');
1258 if (new == NULL)
1260 logf("error occurred");
1261 dircache_initialized = false;
1262 return NULL;
1265 *new = '\0';
1266 new++;
1268 entry = dircache_get_entry(basedir, true);
1269 if (entry == NULL)
1271 logf("basedir not found!");
1272 logf("%s", basedir);
1273 dircache_initialized = false;
1274 return NULL;
1277 if (reserve_used + 2*sizeof(struct dircache_entry) + strlen(new)+1
1278 >= DIRCACHE_RESERVE)
1280 logf("not enough space");
1281 dircache_initialized = false;
1282 return NULL;
1285 while (entry->next != NULL)
1286 entry = entry->next;
1288 if (entry->d_name != NULL)
1290 entry = dircache_gen_next(entry);
1291 if (entry == NULL)
1293 dircache_initialized = false;
1294 return NULL;
1298 size_t size = strlen(new) + 1;
1299 entry->d_name = (d_names_start -= size);
1300 entry->startcluster = 0;
1301 memset(&entry->info, 0, sizeof(entry->info));
1302 entry->info.attribute = attribute;
1304 strcpy(entry->d_name, new);
1305 dircache_size += size;
1307 if (attribute & ATTR_DIRECTORY)
1309 logf("gen_down");
1310 dircache_gen_down(entry);
1313 reserve_used += dircache_size - last_cache_size;
1315 return entry;
1318 void dircache_bind(int fd, const char *path)
1320 struct dircache_entry *entry;
1322 /* Queue requests until dircache has been built. */
1323 if (!dircache_initialized && dircache_is_initializing())
1325 if (fdbind_idx >= MAX_PENDING_BINDINGS)
1326 return ;
1327 strlcpy(fdbind_cache[fdbind_idx].path, path,
1328 sizeof(fdbind_cache[fdbind_idx].path));
1329 fdbind_cache[fdbind_idx].fd = fd;
1330 fdbind_idx++;
1331 return ;
1334 if (!dircache_initialized)
1335 return ;
1337 logf("bind: %d/%s", fd, path);
1338 entry = dircache_get_entry(path, false);
1339 if (entry == NULL)
1341 logf("not found!");
1342 dircache_initialized = false;
1343 return ;
1346 fd_bindings[fd] = entry;
1349 void dircache_update_filesize(int fd, long newsize, long startcluster)
1351 if (!dircache_initialized || fd < 0)
1352 return ;
1354 if (fd_bindings[fd] == NULL)
1356 logf("dircache fd(%d) access error", fd);
1357 dircache_initialized = false;
1358 return ;
1361 fd_bindings[fd]->info.size = newsize;
1362 fd_bindings[fd]->startcluster = startcluster;
1364 void dircache_update_filetime(int fd)
1366 #if CONFIG_RTC == 0
1367 (void)fd;
1368 #else
1369 short year;
1370 struct tm *now = get_time();
1371 if (!dircache_initialized || fd < 0)
1372 return ;
1374 if (fd_bindings[fd] == NULL)
1376 logf("dircache fd access error");
1377 dircache_initialized = false;
1378 return ;
1380 year = now->tm_year+1900-1980;
1381 fd_bindings[fd]->info.wrtdate = (((year)&0x7f)<<9) |
1382 (((now->tm_mon+1)&0xf)<<5) |
1383 (((now->tm_mday)&0x1f));
1384 fd_bindings[fd]->info.wrttime = (((now->tm_hour)&0x1f)<<11) |
1385 (((now->tm_min)&0x3f)<<5) |
1386 (((now->tm_sec/2)&0x1f));
1387 #endif
1390 void dircache_mkdir(const char *path)
1391 { /* Test ok. */
1392 if (block_until_ready())
1393 return ;
1396 logf("mkdir: %s", path);
1397 dircache_new_entry(path, ATTR_DIRECTORY);
1400 void dircache_rmdir(const char *path)
1401 { /* Test ok. */
1402 struct dircache_entry *entry;
1404 if (block_until_ready())
1405 return ;
1407 logf("rmdir: %s", path);
1408 entry = dircache_get_entry(path, false);
1409 if (entry == NULL || entry->down == NULL)
1411 logf("not found or not a directory!");
1412 dircache_initialized = false;
1413 return ;
1416 entry->down = NULL;
1417 entry->d_name = NULL;
1420 /* Remove a file from cache */
1421 void dircache_remove(const char *name)
1422 { /* Test ok. */
1423 struct dircache_entry *entry;
1425 if (block_until_ready())
1426 return ;
1428 logf("remove: %s", name);
1430 entry = dircache_get_entry(name, false);
1432 if (entry == NULL)
1434 logf("not found!");
1435 dircache_initialized = false;
1436 return ;
1439 entry->d_name = NULL;
1442 void dircache_rename(const char *oldpath, const char *newpath)
1443 { /* Test ok. */
1444 struct dircache_entry *entry, *newentry;
1445 struct dircache_entry oldentry;
1446 char absolute_path[MAX_PATH*2];
1447 char *p;
1449 if (block_until_ready())
1450 return ;
1452 logf("rename: %s->%s", oldpath, newpath);
1454 entry = dircache_get_entry(oldpath, false);
1455 if (entry == NULL)
1457 logf("not found!");
1458 dircache_initialized = false;
1459 return ;
1462 /* Delete the old entry. */
1463 entry->d_name = NULL;
1465 /** If we rename the same filename twice in a row, we need to
1466 * save the data, because the entry will be re-used. */
1467 oldentry = *entry;
1469 /* Generate the absolute path for destination if necessary. */
1470 if (newpath[0] != '/')
1472 strlcpy(absolute_path, oldpath, sizeof(absolute_path));
1473 p = strrchr(absolute_path, '/');
1474 if (!p)
1476 logf("Invalid path");
1477 dircache_initialized = false;
1478 return ;
1481 *p = '\0';
1482 strlcpy(p, absolute_path, sizeof(absolute_path)-strlen(p));
1483 newpath = absolute_path;
1486 newentry = dircache_new_entry(newpath, entry->info.attribute);
1487 if (newentry == NULL)
1489 dircache_initialized = false;
1490 return ;
1493 newentry->down = oldentry.down;
1494 newentry->startcluster = oldentry.startcluster;
1495 newentry->info.size = oldentry.info.size;
1496 newentry->info.wrtdate = oldentry.info.wrtdate;
1497 newentry->info.wrttime = oldentry.info.wrttime;
1500 void dircache_add_file(const char *path, long startcluster)
1502 struct dircache_entry *entry;
1504 if (block_until_ready())
1505 return ;
1507 logf("add file: %s", path);
1508 entry = dircache_new_entry(path, 0);
1509 if (entry == NULL)
1510 return ;
1512 entry->startcluster = startcluster;
1515 static bool is_disable_msg_pending(void)
1517 return check_event_queue();
1520 DIR_CACHED* opendir_cached(const char* name)
1522 int dd;
1523 DIR_CACHED* pdir = opendirs;
1525 if ( name[0] != '/' )
1527 DEBUGF("Only absolute paths supported right now\n");
1528 return NULL;
1531 /* find a free dir descriptor */
1532 for ( dd=0; dd<MAX_OPEN_DIRS; dd++, pdir++)
1533 if ( !pdir->busy )
1534 break;
1536 if ( dd == MAX_OPEN_DIRS )
1538 DEBUGF("Too many dirs open\n");
1539 errno = EMFILE;
1540 return NULL;
1543 pdir->busy = true;
1545 if (!dircache_initialized || is_disable_msg_pending())
1547 pdir->internal_entry = -1;
1548 pdir->regulardir = opendir_uncached(name);
1550 else
1552 pdir->regulardir = NULL;
1553 pdir->internal_entry = dircache_get_entry_id_ex(name, true);
1554 pdir->theent.info.attribute = -1; /* used to make readdir_cached aware of the first call */
1557 if (pdir->internal_entry == -1 && pdir->regulardir == NULL)
1559 pdir->busy = false;
1560 return NULL;
1563 return pdir;
1566 struct dirent_cached* readdir_cached(DIR_CACHED* dir)
1568 struct dircache_entry *ce = get_entry(dir->internal_entry);
1569 struct dirent_uncached *regentry;
1571 if (!dir->busy)
1572 return NULL;
1574 if (dir->regulardir != NULL)
1576 regentry = readdir_uncached(dir->regulardir);
1577 if (regentry == NULL)
1578 return NULL;
1580 strlcpy(dir->theent.d_name, regentry->d_name, MAX_PATH);
1581 dir->theent.startcluster = regentry->startcluster;
1582 dir->theent.info = regentry->info;
1584 return &dir->theent;
1587 /* if theent.attribute=-1 then this is the first call */
1588 /* otherwise, this is is not so we first take the entry's ->next */
1589 /* NOTE: normal file can't have attribute=-1 */
1590 if(dir->theent.info.attribute != -1)
1591 ce = ce->next;
1592 /* skip unused entries */
1593 while(ce != NULL && ce->d_name == NULL)
1594 ce = ce->next;
1596 if (ce == NULL)
1597 return NULL;
1599 strlcpy(dir->theent.d_name, ce->d_name, MAX_PATH);
1600 /* Can't do `dir->theent = *ce`
1601 because that modifies the d_name pointer. */
1602 dir->theent.startcluster = ce->startcluster;
1603 dir->theent.info = ce->info;
1604 dir->internal_entry = ce - dircache_root;
1606 //logf("-> %s", ce->d_name);
1607 return &dir->theent;
1610 int closedir_cached(DIR_CACHED* dir)
1612 if (!dir->busy)
1613 return -1;
1615 dir->busy=false;
1616 if (dir->regulardir != NULL)
1617 return closedir_uncached(dir->regulardir);
1619 return 0;
1622 int mkdir_cached(const char *name)
1624 int rc=mkdir_uncached(name);
1625 if (rc >= 0)
1626 dircache_mkdir(name);
1627 return(rc);
1630 int rmdir_cached(const char* name)
1632 int rc=rmdir_uncached(name);
1633 if(rc >= 0)
1634 dircache_rmdir(name);
1635 return(rc);