Replace all direct accesses to audiobuf with buffer API functions.
[kugel-rb.git] / firmware / common / dircache.c
blobd114a6ac628d446a888df2a8f5d1cafd627fbe9c
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 "buffer.h"
42 #include "dir.h"
43 #include "storage.h"
44 #if CONFIG_RTC
45 #include "time.h"
46 #include "timefuncs.h"
47 #endif
48 #include "rbpaths.h"
51 /* Queue commands. */
52 #define DIRCACHE_BUILD 1
53 #define DIRCACHE_STOP 2
55 #if (MEMORYSIZE > 8)
56 #define MAX_OPEN_DIRS 12
57 #else
58 #define MAX_OPEN_DIRS 8
59 #endif
61 #define MAX_PENDING_BINDINGS 2
62 struct fdbind_queue {
63 char path[MAX_PATH];
64 int fd;
67 /* Exported structures. */
68 struct dircache_entry {
69 struct dirinfo info;
70 struct dircache_entry *next;
71 struct dircache_entry *up;
72 struct dircache_entry *down;
73 long startcluster;
74 char *d_name;
77 /* Cache Layout:
79 * x - array of struct dircache_entry
80 * r - reserved buffer
81 * d - name buffer for the d_name entry of the struct dircache_entry
82 * |xxxxxx|rrrrrrrrr|dddddd|
84 * subsequent x are allocated from the front, d are allocated from the back,
85 * using the reserve buffer for entries added after initial scan
87 * after a while the cache may look like:
88 * |xxxxxxxx|rrrrr|dddddddd|
90 * after a reboot, the reserve buffer is restored in it's size, so that the
91 * total allocation size grows
92 * |xxxxxxxx|rrrrrrrrr|dddddddd|
94 /* this points to the beginnging of the buffer and the first entry */
95 static struct dircache_entry *dircache_root;
96 /* these point to the start and end of the name buffer (d above) */
97 static char *d_names_start, *d_names_end;
98 /* put "." and ".." into the d_names buffer to enable easy pointer logic */
99 static char *dot, *dotdot;
100 #ifdef HAVE_MULTIVOLUME
101 static struct dircache_entry *append_position;
102 #endif
104 static DIR_CACHED opendirs[MAX_OPEN_DIRS];
105 static struct dircache_entry *fd_bindings[MAX_OPEN_FILES];
107 static bool dircache_initialized = false;
108 static bool dircache_initializing = false;
109 static bool thread_enabled = false;
110 static unsigned long allocated_size = DIRCACHE_LIMIT;
111 static unsigned long dircache_size = 0;
112 static unsigned long entry_count = 0;
113 static unsigned long reserve_used = 0;
114 static unsigned int cache_build_ticks = 0;
115 static unsigned long appflags = 0;
117 static struct event_queue dircache_queue SHAREDBSS_ATTR;
118 static long dircache_stack[(DEFAULT_STACK_SIZE + 0x400)/sizeof(long)];
119 static const char dircache_thread_name[] = "dircache";
121 static struct fdbind_queue fdbind_cache[MAX_PENDING_BINDINGS];
122 static int fdbind_idx = 0;
124 /* --- Internal cache structure control functions --- */
126 static inline struct dircache_entry* get_entry(int id)
128 return &dircache_root[id];
131 #ifdef HAVE_EEPROM_SETTINGS
133 * Open the dircache file to save a snapshot on disk
135 static int open_dircache_file(unsigned flags, int permissions)
137 if (permissions != 0)
138 return open(DIRCACHE_FILE, flags, permissions);
140 return open(DIRCACHE_FILE, flags);
144 * Remove the snapshot file
146 static int remove_dircache_file(void)
148 return remove(DIRCACHE_FILE);
150 #endif
151 /**
152 * Internal function to allocate a new dircache_entry from memory.
154 static struct dircache_entry* allocate_entry(void)
156 struct dircache_entry *next_entry;
158 if (dircache_size > allocated_size - MAX_PATH*2)
160 logf("size limit reached");
161 return NULL;
164 next_entry = &dircache_root[entry_count++];
165 next_entry->d_name = NULL;
166 next_entry->up = NULL;
167 next_entry->down = NULL;
168 next_entry->next = NULL;
170 dircache_size += sizeof(struct dircache_entry);
172 return next_entry;
176 * Internal function to allocate a dircache_entry and set
177 * ->next entry pointers.
179 static struct dircache_entry* dircache_gen_next(struct dircache_entry *ce)
181 struct dircache_entry *next_entry;
183 if ( (next_entry = allocate_entry()) == NULL)
184 return NULL;
185 next_entry->up = ce->up;
186 ce->next = next_entry;
188 return next_entry;
192 * Internal function to allocate a dircache_entry and set
193 * ->down entry pointers.
195 static struct dircache_entry* dircache_gen_down(struct dircache_entry *ce)
197 struct dircache_entry *next_entry;
199 if ( (next_entry = allocate_entry()) == NULL)
200 return NULL;
201 next_entry->up = ce;
202 ce->down = next_entry;
204 return next_entry;
208 * Returns true if there is an event waiting in the queue
209 * that requires the current operation to be aborted.
211 static bool check_event_queue(void)
213 struct queue_event ev;
215 if(!queue_peek(&dircache_queue, &ev))
216 return false;
218 switch (ev.id)
220 case DIRCACHE_STOP:
221 case SYS_USB_CONNECTED:
222 #ifdef HAVE_HOTSWAP
223 case SYS_FS_CHANGED:
224 #endif
225 return true;
228 return false;
231 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
232 /* scan and build static data (avoid redundancy on stack) */
233 static struct
235 #ifdef HAVE_MULTIVOLUME
236 int volume;
237 #endif
238 struct fat_dir *dir;
239 struct fat_direntry *direntry;
240 }sab;
242 static int sab_process_dir(unsigned long startcluster, struct dircache_entry *ce)
244 /* normally, opendir expects a full fat_dir as parent but in our case,
245 * it's completely useless because we don't modify anything
246 * WARNING: this heavily relies on current FAT implementation ! */
248 /* those field are necessary to update the FAT entry in case of modification
249 here we don't touch anything so we put dummy values */
250 sab.dir->entry = 0;
251 sab.dir->entrycount = 0;
252 sab.dir->file.firstcluster = 0;
253 /* open directory */
254 int rc = fat_opendir(IF_MV2(sab.volume,) sab.dir, startcluster, sab.dir);
255 if(rc < 0)
257 logf("fat_opendir failed: %d", rc);
258 return rc;
261 /* first pass : read dir */
262 struct dircache_entry *first_ce = ce;
264 /* read through directory */
265 while((rc = fat_getnext(sab.dir, sab.direntry)) >= 0 && sab.direntry->name[0])
267 if(!strcmp(".", sab.direntry->name) ||
268 !strcmp("..", sab.direntry->name))
269 continue;
271 size_t size = strlen(sab.direntry->name) + 1;
272 ce->d_name = (d_names_start -= size);
273 ce->startcluster = sab.direntry->firstcluster;
274 ce->info.size = sab.direntry->filesize;
275 ce->info.attribute = sab.direntry->attr;
276 ce->info.wrtdate = sab.direntry->wrtdate;
277 ce->info.wrttime = sab.direntry->wrttime;
279 strcpy(ce->d_name, sab.direntry->name);
280 dircache_size += size;
282 if(ce->info.attribute & FAT_ATTR_DIRECTORY)
283 dircache_gen_down(ce);
285 ce = dircache_gen_next(ce);
286 if(ce == NULL)
287 return -5;
289 /* When simulator is used, it's only safe to yield here. */
290 if(thread_enabled)
292 /* Stop if we got an external signal. */
293 if(check_event_queue())
294 return -6;
295 yield();
299 /* add "." and ".." */
300 ce->d_name = dot;
301 ce->info.attribute = FAT_ATTR_DIRECTORY;
302 ce->startcluster = startcluster;
303 ce->info.size = 0;
304 ce->down = first_ce;
306 ce = dircache_gen_next(ce);
308 ce->d_name = dotdot;
309 ce->info.attribute = FAT_ATTR_DIRECTORY;
310 ce->startcluster = (first_ce->up ? first_ce->up->startcluster : 0);
311 ce->info.size = 0;
312 ce->down = first_ce->up;
314 /* second pass: recurse ! */
315 ce = first_ce;
317 while(rc >= 0 && ce)
319 if(ce->d_name != NULL && ce->down != NULL && strcmp(ce->d_name, ".")
320 && strcmp(ce->d_name, ".."))
321 rc = sab_process_dir(ce->startcluster, ce->down);
323 ce = ce->next;
326 return rc;
329 /* used during the generation */
330 static struct fat_dir sab_fat_dir;
332 static int dircache_scan_and_build(IF_MV2(int volume,) struct dircache_entry *ce)
334 memset(ce, 0, sizeof(struct dircache_entry));
336 #ifdef HAVE_MULTIVOLUME
337 if (volume > 0)
339 /* broken for 100+ volumes because the format string is too small
340 * and we use that for size calculation */
341 const size_t max_len = VOL_ENUM_POS + 3;
342 ce->d_name = (d_names_start -= max_len);
343 snprintf(ce->d_name, max_len, VOL_NAMES, volume);
344 dircache_size += max_len;
345 ce->info.attribute = FAT_ATTR_DIRECTORY | FAT_ATTR_VOLUME;
346 ce->info.size = 0;
347 append_position = dircache_gen_next(ce);
348 ce = dircache_gen_down(ce);
350 #endif
352 struct fat_direntry direntry; /* ditto */
353 #ifdef HAVE_MULTIVOLUME
354 sab.volume = volume;
355 #endif
356 sab.dir = &sab_fat_dir;
357 sab.direntry = &direntry;
359 return sab_process_dir(0, ce);
361 #elif (CONFIG_PLATFORM & PLATFORM_HOSTED) /* PLATFORM_HOSTED */
362 static char sab_path[MAX_PATH];
364 static int sab_process_dir(struct dircache_entry *ce)
366 struct dirent_uncached *entry;
367 struct dircache_entry *first_ce = ce;
368 DIR_UNCACHED *dir = opendir_uncached(sab_path);
369 if(dir == NULL)
371 logf("Failed to opendir_uncached(%s)", sab_path);
372 return -1;
375 while((entry = readdir_uncached(dir)))
377 if(!strcmp(".", entry->d_name) ||
378 !strcmp("..", entry->d_name))
379 continue;
381 size_t size = strlen(entry->d_name) + 1;
382 ce->d_name = (d_names_start -= size);
383 ce->info = entry->info;
385 strcpy(ce->d_name, entry->d_name);
386 dircache_size += size;
388 if(entry->info.attribute & ATTR_DIRECTORY)
390 dircache_gen_down(ce);
391 if(ce->down == NULL)
393 closedir_uncached(dir);
394 return -1;
396 /* save current paths size */
397 int pathpos = strlen(sab_path);
398 /* append entry */
399 strlcpy(&sab_path[pathpos], "/", sizeof(sab_path) - pathpos);
400 strlcpy(&sab_path[pathpos+1], entry->d_name, sizeof(sab_path) - pathpos - 1);
402 int rc = sab_process_dir(ce->down);
403 /* restore path */
404 sab_path[pathpos] = '\0';
406 if(rc < 0)
408 closedir_uncached(dir);
409 return rc;
413 ce = dircache_gen_next(ce);
414 if(ce == NULL)
415 return -5;
417 /* When simulator is used, it's only safe to yield here. */
418 if(thread_enabled)
420 /* Stop if we got an external signal. */
421 if(check_event_queue())
422 return -1;
423 yield();
427 /* add "." and ".." */
428 ce->d_name = dot;
429 ce->info.attribute = ATTR_DIRECTORY;
430 ce->info.size = 0;
431 ce->down = first_ce;
433 ce = dircache_gen_next(ce);
435 ce->d_name = dotdot;
436 ce->info.attribute = ATTR_DIRECTORY;
437 ce->info.size = 0;
438 ce->down = first_ce->up;
440 closedir_uncached(dir);
441 return 0;
444 static int dircache_scan_and_build(IF_MV2(int volume,) struct dircache_entry *ce)
446 #ifdef HAVE_MULTIVOLUME
447 (void) volume;
448 #endif
449 memset(ce, 0, sizeof(struct dircache_entry));
451 strlcpy(sab_path, "/", sizeof sab_path);
452 return sab_process_dir(ce);
454 #endif /* PLATFORM_NATIVE */
457 * Internal function to get a pointer to dircache_entry for a given filename.
458 * path: Absolute path to a file or directory (see comment)
459 * go_down: Returns the first entry of the directory given by the path (see comment)
461 * As a a special case, accept path="" as an alias for "/".
462 * Also if the path omits the first '/', it will be accepted.
464 * * If get_down=true:
465 * If path="/", the returned entry is the first of root directory (ie dircache_root)
466 * Otherwise, if 'entry' is the returned value when get_down=false,
467 * the functions returns entry->down (which can be NULL)
469 * * If get_down=false:
470 * If path="/chunk_1/chunk_2/.../chunk_n" then this functions returns the entry
471 * root_entry()->chunk_1->chunk_2->...->chunk_(n-1)
472 * Which means that
473 * dircache_get_entry(path)->d_name == chunk_n
475 * If path="/", the returned entry is NULL.
476 * If the entry doesn't exist, return NULL
478 * NOTE: this functions silently handles double '/'
480 static struct dircache_entry* dircache_get_entry(const char *path, bool go_down)
482 char namecopy[MAX_PATH];
483 char* part;
484 char* end;
486 bool at_root = true;
487 struct dircache_entry *cache_entry = dircache_root;
489 strlcpy(namecopy, path, sizeof(namecopy));
491 for(part = strtok_r(namecopy, "/", &end); part; part = strtok_r(NULL, "/", &end))
493 /* If request another chunk, the current entry has to be directory
494 * and so cache_entry->down has to be non-NULL/
495 * Special case of root because it's already the first entry of the root directory
497 * NOTE: this is safe even if cache_entry->down is NULL */
498 if(!at_root)
499 cache_entry = cache_entry->down;
500 else
501 at_root = false;
503 /* scan dir for name */
504 while(cache_entry != NULL)
506 /* skip unused entries */
507 if(cache_entry->d_name == NULL)
509 cache_entry = cache_entry->next;
510 continue;
512 /* compare names */
513 if(!strcasecmp(part, cache_entry->d_name))
514 break;
515 /* go to next entry */
516 cache_entry = cache_entry->next;
519 /* handle not found case */
520 if(cache_entry == NULL)
521 return NULL;
524 /* NOTE: here cache_entry!=NULL so taking ->down is safe */
525 if(go_down)
526 return at_root ? cache_entry : cache_entry->down;
527 else
528 return at_root ? NULL : cache_entry;
531 #ifdef HAVE_EEPROM_SETTINGS
533 #define DIRCACHE_MAGIC 0x00d0c0a1
534 struct dircache_maindata {
535 long magic;
536 long size;
537 long entry_count;
538 long appflags;
539 struct dircache_entry *root_entry;
540 char *d_names_start;
544 * Function to load the internal cache structure from disk to initialize
545 * the dircache really fast and little disk access.
547 int dircache_load(void)
549 struct dircache_maindata maindata;
550 ssize_t bytes_read;
551 int fd;
553 if (dircache_initialized)
554 return -1;
556 logf("Loading directory cache");
557 dircache_size = 0;
559 fd = open_dircache_file(O_RDONLY, 0);
560 if (fd < 0)
561 return -2;
563 bytes_read = read(fd, &maindata, sizeof(struct dircache_maindata));
564 if (bytes_read != sizeof(struct dircache_maindata)
565 || maindata.magic != DIRCACHE_MAGIC || maindata.size <= 0)
567 logf("Dircache file header error");
568 close(fd);
569 remove_dircache_file();
570 return -3;
573 allocated_size = maindata.size + DIRCACHE_RESERVE;
574 dircache_root = buffer_alloc(allocated_size);
575 /* needs to be struct-size aligned so that the pointer arithmetic below works */
576 ALIGN_BUFFER(dircache_root, allocated_size, sizeof(struct dircache_entry));
577 entry_count = maindata.entry_count;
578 appflags = maindata.appflags;
580 /* read the dircache file into memory,
581 * start with the struct dircache_entries */
582 ssize_t bytes_to_read = entry_count*sizeof(struct dircache_entry);
583 bytes_read = read(fd, dircache_root, bytes_to_read);
585 if (bytes_read != bytes_to_read)
587 logf("Dircache read failed #1");
588 return -6;
591 /* continue with the d_names. Fix up pointers to them if needed */
592 bytes_to_read = maindata.size - bytes_to_read;
593 d_names_start = (char*)dircache_root + allocated_size - bytes_to_read;
594 bytes_read = read(fd, d_names_start, bytes_to_read);
595 close(fd);
596 remove_dircache_file();
597 if (bytes_read != bytes_to_read)
599 logf("Dircache read failed #2");
600 return -7;
603 d_names_end = d_names_start + bytes_read;
604 dot = d_names_end - sizeof(".");
605 dotdot = dot - sizeof("..");
607 /* d_names are in reverse order, so the last entry points to the first string */
608 ptrdiff_t offset_d_names = maindata.d_names_start - d_names_start,
609 offset_entries = maindata.root_entry - dircache_root;
611 /* offset_entries is less likely to differ, so check if it's 0 in the loop
612 * offset_d_names however is almost always non-zero, since dircache_save()
613 * creates a file which causes the reserve buffer to be used. since
614 * we allocate a new, empty DIRCACHE_RESERVE here, the strings are
615 * farther behind */
616 if (offset_entries != 0 || offset_d_names != 0)
618 for(unsigned i = 0; i < entry_count; i++)
620 if (dircache_root[i].d_name)
621 dircache_root[i].d_name -= offset_d_names;
623 if (offset_entries == 0)
624 continue;
625 if (dircache_root[i].next)
626 dircache_root[i].next -= offset_entries;
627 if (dircache_root[i].up)
628 dircache_root[i].up -= offset_entries;
629 if (dircache_root[i].down)
630 dircache_root[i].down -= offset_entries;
634 /* Cache successfully loaded. */
635 dircache_size = maindata.size;
636 reserve_used = 0;
637 logf("Done, %ld KiB used", dircache_size / 1024);
638 dircache_initialized = true;
639 memset(fd_bindings, 0, sizeof(fd_bindings));
641 return 0;
645 * Function to save the internal cache stucture to disk for fast loading
646 * on boot.
648 int dircache_save(void)
650 struct dircache_maindata maindata;
651 int fd;
652 unsigned long bytes_written;
654 remove_dircache_file();
656 if (!dircache_initialized)
657 return -1;
659 logf("Saving directory cache");
660 fd = open_dircache_file(O_WRONLY | O_CREAT | O_TRUNC, 0666);
662 maindata.magic = DIRCACHE_MAGIC;
663 maindata.size = dircache_size;
664 maindata.root_entry = dircache_root;
665 maindata.d_names_start = d_names_start;
666 maindata.entry_count = entry_count;
667 maindata.appflags = appflags;
669 /* Save the info structure */
670 bytes_written = write(fd, &maindata, sizeof(struct dircache_maindata));
671 if (bytes_written != sizeof(struct dircache_maindata))
673 close(fd);
674 logf("dircache: write failed #1");
675 return -2;
678 /* Dump whole directory cache to disk
679 * start by writing the dircache_entries */
680 size_t bytes_to_write = entry_count*sizeof(struct dircache_entry);
681 bytes_written = write(fd, dircache_root, bytes_to_write);
682 if (bytes_written != bytes_to_write)
684 logf("dircache: write failed #2");
685 return -3;
688 /* continue with the d_names */
689 bytes_to_write = d_names_end - d_names_start;
690 bytes_written = write(fd, d_names_start, bytes_to_write);
691 close(fd);
692 if (bytes_written != bytes_to_write)
694 logf("dircache: write failed #3");
695 return -4;
699 return 0;
701 #endif /* HAVE_EEPROM_SETTINGS */
704 * Internal function which scans the disk and creates the dircache structure.
706 static int dircache_do_rebuild(void)
708 struct dircache_entry* root_entry;
709 unsigned int start_tick;
710 int i;
712 /* Measure how long it takes build the cache. */
713 start_tick = current_tick;
714 dircache_initializing = true;
715 appflags = 0;
717 /* reset dircache and alloc root entry */
718 entry_count = 0;
719 root_entry = allocate_entry();
721 #ifdef HAVE_MULTIVOLUME
722 append_position = root_entry;
724 for (i = NUM_VOLUMES; i >= 0; i--)
726 if (fat_ismounted(i))
728 #endif
729 cpu_boost(true);
730 #ifdef HAVE_MULTIVOLUME
731 if (dircache_scan_and_build(IF_MV2(i,) append_position) < 0)
732 #else
733 if (dircache_scan_and_build(IF_MV2(0,) root_entry) < 0)
734 #endif /* HAVE_MULTIVOLUME */
736 logf("dircache_scan_and_build failed");
737 cpu_boost(false);
738 dircache_size = 0;
739 dircache_initializing = false;
740 return -2;
742 cpu_boost(false);
743 #ifdef HAVE_MULTIVOLUME
746 #endif
748 logf("Done, %ld KiB used", dircache_size / 1024);
750 dircache_initialized = true;
751 dircache_initializing = false;
752 cache_build_ticks = current_tick - start_tick;
754 /* Initialized fd bindings. */
755 memset(fd_bindings, 0, sizeof(fd_bindings));
756 for (i = 0; i < fdbind_idx; i++)
757 dircache_bind(fdbind_cache[i].fd, fdbind_cache[i].path);
758 fdbind_idx = 0;
760 if (thread_enabled)
762 if (allocated_size - dircache_size < DIRCACHE_RESERVE)
763 reserve_used = DIRCACHE_RESERVE - (allocated_size - dircache_size);
766 return 1;
770 * Internal thread that controls transparent cache building.
772 static void dircache_thread(void)
774 struct queue_event ev;
776 while (1)
778 queue_wait(&dircache_queue, &ev);
780 switch (ev.id)
782 #ifdef HAVE_HOTSWAP
783 case SYS_FS_CHANGED:
784 if (!dircache_initialized)
785 break;
786 dircache_initialized = false;
787 #endif
788 case DIRCACHE_BUILD:
789 thread_enabled = true;
790 dircache_do_rebuild();
791 thread_enabled = false;
792 break ;
794 case DIRCACHE_STOP:
795 logf("Stopped the rebuilding.");
796 dircache_initialized = false;
797 break ;
799 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
800 case SYS_USB_CONNECTED:
801 usb_acknowledge(SYS_USB_CONNECTED_ACK);
802 usb_wait_for_disconnect(&dircache_queue);
803 break ;
804 #endif
809 static void generate_dot_d_names(void)
811 dot = (d_names_start -= sizeof("."));
812 dotdot = (d_names_start -= sizeof(".."));
813 dircache_size += sizeof(".") + sizeof("..");
814 strcpy(dot, ".");
815 strcpy(dotdot, "..");
818 * Start scanning the disk to build the dircache.
819 * Either transparent or non-transparent build method is used.
821 int dircache_build(int last_size)
823 if (dircache_initialized || thread_enabled)
824 return -3;
826 logf("Building directory cache");
827 #ifdef HAVE_EEPROM_SETTINGS
828 remove_dircache_file();
829 #endif
831 /* Background build, dircache has been previously allocated */
832 if (dircache_size > 0)
834 d_names_start = d_names_end;
835 dircache_size = 0;
836 reserve_used = 0;
837 thread_enabled = true;
838 dircache_initializing = true;
839 generate_dot_d_names();
841 queue_post(&dircache_queue, DIRCACHE_BUILD, 0);
842 return 2;
845 if (last_size > DIRCACHE_RESERVE && last_size < DIRCACHE_LIMIT )
847 allocated_size = last_size + DIRCACHE_RESERVE;
848 dircache_root = buffer_alloc(allocated_size);
849 ALIGN_BUFFER(dircache_root, allocated_size, sizeof(struct dircache_entry));
850 d_names_start = d_names_end = ((char*)dircache_root)+allocated_size-1;
851 dircache_size = 0;
852 thread_enabled = true;
853 generate_dot_d_names();
855 /* Start a transparent rebuild. */
856 queue_post(&dircache_queue, DIRCACHE_BUILD, 0);
857 return 3;
860 /* We'll use the entire audiobuf to allocate the dircache
861 * struct dircache_entrys are allocated from the beginning
862 * and their corresponding d_name from the end
863 * after generation the buffer will be compacted with DIRCACHE_RESERVE
864 * free bytes inbetween */
865 size_t got_size;
866 char* buf = buffer_get_buffer(&got_size);
867 ALIGN_BUFFER(buf, got_size, sizeof(struct dircache_entry));
868 d_names_start = d_names_end = (char*)dircache_root + got_size - 1;
869 dircache_size = 0;
870 generate_dot_d_names();
872 /* Start a non-transparent rebuild. */
873 int res = dircache_do_rebuild();
874 if (res < 0)
875 goto fail;
877 /* now compact the dircache buffer */
878 char* dst = ((char*)&dircache_root[entry_count] + DIRCACHE_RESERVE);
879 ptrdiff_t offset = d_names_start - dst;
880 if (offset <= 0) /* something went wrong */
882 res = -1;
883 goto fail;
886 /* memmove d_names down, there's a possibility of overlap
887 * equivaent to dircache_size - entry_count*sizeof(struct dircache_entry) */
888 ptrdiff_t size_to_move = d_names_end - d_names_start;
889 memmove(dst, d_names_start, size_to_move);
891 /* fix up pointers to the d_names */
892 for(unsigned i = 0; i < entry_count; i++)
893 dircache_root[i].d_name -= offset;
895 d_names_start -= offset;
896 d_names_end -= offset;
897 dot -= offset;
898 dotdot -= offset;
900 /* equivalent to dircache_size + DIRCACHE_RESERVE */
901 allocated_size = (d_names_end - (char*)dircache_root);
902 reserve_used = 0;
904 buffer_release_buffer(allocated_size);
905 return res;
906 fail:
907 dircache_disable();
908 buffer_release_buffer(0);
909 return res;
913 * Steal the allocated dircache buffer and disable dircache.
915 void* dircache_steal_buffer(size_t *size)
917 dircache_disable();
918 if (dircache_size == 0)
920 *size = 0;
921 return NULL;
924 *size = dircache_size + (DIRCACHE_RESERVE-reserve_used);
926 return dircache_root;
930 * Main initialization function that must be called before any other
931 * operations within the dircache.
933 void dircache_init(void)
935 int i;
936 int thread_id __attribute__((unused));
938 dircache_initialized = false;
939 dircache_initializing = false;
941 memset(opendirs, 0, sizeof(opendirs));
942 for (i = 0; i < MAX_OPEN_DIRS; i++)
944 opendirs[i].theent.d_name = buffer_alloc(MAX_PATH);
947 queue_init(&dircache_queue, true);
948 thread_id = create_thread(dircache_thread, dircache_stack,
949 sizeof(dircache_stack), 0, dircache_thread_name
950 IF_PRIO(, PRIORITY_BACKGROUND)
951 IF_COP(, CPU));
952 #ifdef HAVE_IO_PRIORITY
953 thread_set_io_priority(thread_id,IO_PRIORITY_BACKGROUND);
954 #endif
959 * Returns true if dircache has been initialized and is ready to be used.
961 bool dircache_is_enabled(void)
963 return dircache_initialized;
967 * Returns true if dircache is being initialized.
969 bool dircache_is_initializing(void)
971 return dircache_initializing || thread_enabled;
975 * Set application flags used to determine if dircache is still intact.
977 void dircache_set_appflag(long mask)
979 appflags |= mask;
983 * Get application flags used to determine if dircache is still intact.
985 bool dircache_get_appflag(long mask)
987 return dircache_is_enabled() && (appflags & mask);
991 * Returns the current number of entries (directories and files) in the cache.
993 int dircache_get_entry_count(void)
995 return entry_count;
999 * Returns the allocated space for dircache (without reserve space).
1001 int dircache_get_cache_size(void)
1003 return dircache_is_enabled() ? dircache_size : 0;
1007 * Returns how many bytes of the reserve allocation for live cache
1008 * updates have been used.
1010 int dircache_get_reserve_used(void)
1012 return dircache_is_enabled() ? reserve_used : 0;
1016 * Returns the time in kernel ticks that took to build the cache.
1018 int dircache_get_build_ticks(void)
1020 return dircache_is_enabled() ? cache_build_ticks : 0;
1024 * Disables the dircache. Usually called on shutdown or when
1025 * accepting a usb connection.
1027 void dircache_disable(void)
1029 int i;
1030 bool cache_in_use;
1032 if (thread_enabled)
1033 queue_post(&dircache_queue, DIRCACHE_STOP, 0);
1035 while (thread_enabled)
1036 sleep(1);
1037 dircache_initialized = false;
1039 logf("Waiting for cached dirs to release");
1040 do {
1041 cache_in_use = false;
1042 for (i = 0; i < MAX_OPEN_DIRS; i++) {
1043 if (!opendirs[i].regulardir && opendirs[i].busy)
1045 cache_in_use = true;
1046 sleep(1);
1047 break ;
1050 } while (cache_in_use) ;
1052 logf("Cache released");
1053 entry_count = 0;
1057 * Usermode function to return dircache_entry index to the given path.
1059 static int dircache_get_entry_id_ex(const char *filename, bool go_down)
1061 if (!dircache_initialized || filename == NULL)
1062 return -1;
1064 struct dircache_entry* res = dircache_get_entry(filename, go_down);
1065 return res ? res - dircache_root : -1;
1068 int dircache_get_entry_id(const char* filename)
1070 return dircache_get_entry_id_ex(filename, false);
1074 * Internal: Get the startcluster for the index
1076 long _dircache_get_entry_startcluster(int id)
1078 return get_entry(id)->startcluster;
1082 * Internal: Get the struct dirinfo for the index
1084 struct dirinfo* _dircache_get_entry_dirinfo(int id)
1086 return &get_entry(id)->info;
1090 * build a path from an entry upto the root using recursion
1092 * it appends '/' after strlcat, therefore buf[0] needs to be prepared with '/'
1093 * and it will leave a trailing '/'
1095 * returns the position of that trailing '/' so it can be deleted afterwards
1096 * (or, in case of truncation, the position of the nul byte */
1097 static size_t copy_path_helper(const struct dircache_entry *entry, char *buf, size_t size)
1099 int offset = 1;
1100 /* has parent? */
1101 if (entry->up)
1102 offset += copy_path_helper(entry->up, buf, size);
1104 size_t len = strlcpy(buf+offset, entry->d_name, size - offset) + offset;
1105 if (len < size)
1107 buf[len++] = '/';
1108 buf[len] = '\0';
1110 return len-1;
1113 * Function to copy the full absolute path from dircache to the given buffer
1114 * using the given dircache_entry pointer.
1116 * Returns the size of the resulting string, or 0 if an error occured
1118 size_t dircache_copy_path(int index, char *buf, size_t size)
1120 if (!size || !buf || index < 0)
1121 return 0;
1123 buf[0] = '/';
1124 size_t res = copy_path_helper(&dircache_root[index], buf, size - 1);
1125 /* fixup trailing '/' */
1126 buf[res] = '\0';
1127 return res;
1130 /* --- Directory cache live updating functions --- */
1131 static int block_until_ready(void)
1133 /* Block until dircache has been built. */
1134 while (!dircache_initialized && dircache_is_initializing())
1135 sleep(1);
1137 if (!dircache_initialized)
1138 return -1;
1140 return 0;
1143 static struct dircache_entry* dircache_new_entry(const char *path, int attribute)
1145 struct dircache_entry *entry;
1146 char basedir[MAX_PATH*2];
1147 char *new;
1148 long last_cache_size = dircache_size;
1150 strlcpy(basedir, path, sizeof(basedir));
1151 new = strrchr(basedir, '/');
1152 if (new == NULL)
1154 logf("error occurred");
1155 dircache_initialized = false;
1156 return NULL;
1159 *new = '\0';
1160 new++;
1162 entry = dircache_get_entry(basedir, true);
1163 if (entry == NULL)
1165 logf("basedir not found!");
1166 logf("%s", basedir);
1167 dircache_initialized = false;
1168 return NULL;
1171 if (reserve_used + 2*sizeof(struct dircache_entry) + strlen(new)+1
1172 >= DIRCACHE_RESERVE)
1174 logf("not enough space");
1175 dircache_initialized = false;
1176 return NULL;
1179 while (entry->next != NULL)
1180 entry = entry->next;
1182 if (entry->d_name != NULL)
1184 entry = dircache_gen_next(entry);
1185 if (entry == NULL)
1187 dircache_initialized = false;
1188 return NULL;
1192 size_t size = strlen(new) + 1;
1193 entry->d_name = (d_names_start -= size);
1194 entry->startcluster = 0;
1195 memset(&entry->info, 0, sizeof(entry->info));
1196 entry->info.attribute = attribute;
1198 strcpy(entry->d_name, new);
1199 dircache_size += size;
1201 if (attribute & ATTR_DIRECTORY)
1203 logf("gen_down");
1204 dircache_gen_down(entry);
1207 reserve_used += dircache_size - last_cache_size;
1209 return entry;
1212 void dircache_bind(int fd, const char *path)
1214 struct dircache_entry *entry;
1216 /* Queue requests until dircache has been built. */
1217 if (!dircache_initialized && dircache_is_initializing())
1219 if (fdbind_idx >= MAX_PENDING_BINDINGS)
1220 return ;
1221 strlcpy(fdbind_cache[fdbind_idx].path, path,
1222 sizeof(fdbind_cache[fdbind_idx].path));
1223 fdbind_cache[fdbind_idx].fd = fd;
1224 fdbind_idx++;
1225 return ;
1228 if (!dircache_initialized)
1229 return ;
1231 logf("bind: %d/%s", fd, path);
1232 entry = dircache_get_entry(path, false);
1233 if (entry == NULL)
1235 logf("not found!");
1236 dircache_initialized = false;
1237 return ;
1240 fd_bindings[fd] = entry;
1243 void dircache_update_filesize(int fd, long newsize, long startcluster)
1245 if (!dircache_initialized || fd < 0)
1246 return ;
1248 if (fd_bindings[fd] == NULL)
1250 logf("dircache fd(%d) access error", fd);
1251 dircache_initialized = false;
1252 return ;
1255 fd_bindings[fd]->info.size = newsize;
1256 fd_bindings[fd]->startcluster = startcluster;
1258 void dircache_update_filetime(int fd)
1260 #if CONFIG_RTC == 0
1261 (void)fd;
1262 #else
1263 short year;
1264 struct tm *now = get_time();
1265 if (!dircache_initialized || fd < 0)
1266 return ;
1268 if (fd_bindings[fd] == NULL)
1270 logf("dircache fd access error");
1271 dircache_initialized = false;
1272 return ;
1274 year = now->tm_year+1900-1980;
1275 fd_bindings[fd]->info.wrtdate = (((year)&0x7f)<<9) |
1276 (((now->tm_mon+1)&0xf)<<5) |
1277 (((now->tm_mday)&0x1f));
1278 fd_bindings[fd]->info.wrttime = (((now->tm_hour)&0x1f)<<11) |
1279 (((now->tm_min)&0x3f)<<5) |
1280 (((now->tm_sec/2)&0x1f));
1281 #endif
1284 void dircache_mkdir(const char *path)
1285 { /* Test ok. */
1286 if (block_until_ready())
1287 return ;
1290 logf("mkdir: %s", path);
1291 dircache_new_entry(path, ATTR_DIRECTORY);
1294 void dircache_rmdir(const char *path)
1295 { /* Test ok. */
1296 struct dircache_entry *entry;
1298 if (block_until_ready())
1299 return ;
1301 logf("rmdir: %s", path);
1302 entry = dircache_get_entry(path, false);
1303 if (entry == NULL || entry->down == NULL)
1305 logf("not found or not a directory!");
1306 dircache_initialized = false;
1307 return ;
1310 entry->down = NULL;
1311 entry->d_name = NULL;
1314 /* Remove a file from cache */
1315 void dircache_remove(const char *name)
1316 { /* Test ok. */
1317 struct dircache_entry *entry;
1319 if (block_until_ready())
1320 return ;
1322 logf("remove: %s", name);
1324 entry = dircache_get_entry(name, false);
1326 if (entry == NULL)
1328 logf("not found!");
1329 dircache_initialized = false;
1330 return ;
1333 entry->d_name = NULL;
1336 void dircache_rename(const char *oldpath, const char *newpath)
1337 { /* Test ok. */
1338 struct dircache_entry *entry, *newentry;
1339 struct dircache_entry oldentry;
1340 char absolute_path[MAX_PATH*2];
1341 char *p;
1343 if (block_until_ready())
1344 return ;
1346 logf("rename: %s->%s", oldpath, newpath);
1348 entry = dircache_get_entry(oldpath, false);
1349 if (entry == NULL)
1351 logf("not found!");
1352 dircache_initialized = false;
1353 return ;
1356 /* Delete the old entry. */
1357 entry->d_name = NULL;
1359 /** If we rename the same filename twice in a row, we need to
1360 * save the data, because the entry will be re-used. */
1361 oldentry = *entry;
1363 /* Generate the absolute path for destination if necessary. */
1364 if (newpath[0] != '/')
1366 strlcpy(absolute_path, oldpath, sizeof(absolute_path));
1367 p = strrchr(absolute_path, '/');
1368 if (!p)
1370 logf("Invalid path");
1371 dircache_initialized = false;
1372 return ;
1375 *p = '\0';
1376 strlcpy(p, absolute_path, sizeof(absolute_path)-strlen(p));
1377 newpath = absolute_path;
1380 newentry = dircache_new_entry(newpath, entry->info.attribute);
1381 if (newentry == NULL)
1383 dircache_initialized = false;
1384 return ;
1387 newentry->down = oldentry.down;
1388 newentry->startcluster = oldentry.startcluster;
1389 newentry->info.size = oldentry.info.size;
1390 newentry->info.wrtdate = oldentry.info.wrtdate;
1391 newentry->info.wrttime = oldentry.info.wrttime;
1394 void dircache_add_file(const char *path, long startcluster)
1396 struct dircache_entry *entry;
1398 if (block_until_ready())
1399 return ;
1401 logf("add file: %s", path);
1402 entry = dircache_new_entry(path, 0);
1403 if (entry == NULL)
1404 return ;
1406 entry->startcluster = startcluster;
1409 static bool is_disable_msg_pending(void)
1411 return check_event_queue();
1414 DIR_CACHED* opendir_cached(const char* name)
1416 int dd;
1417 DIR_CACHED* pdir = opendirs;
1419 if ( name[0] != '/' )
1421 DEBUGF("Only absolute paths supported right now\n");
1422 return NULL;
1425 /* find a free dir descriptor */
1426 for ( dd=0; dd<MAX_OPEN_DIRS; dd++, pdir++)
1427 if ( !pdir->busy )
1428 break;
1430 if ( dd == MAX_OPEN_DIRS )
1432 DEBUGF("Too many dirs open\n");
1433 errno = EMFILE;
1434 return NULL;
1437 pdir->busy = true;
1439 if (!dircache_initialized || is_disable_msg_pending())
1441 pdir->internal_entry = -1;
1442 pdir->regulardir = opendir_uncached(name);
1444 else
1446 pdir->regulardir = NULL;
1447 pdir->internal_entry = dircache_get_entry_id_ex(name, true);
1448 pdir->theent.info.attribute = -1; /* used to make readdir_cached aware of the first call */
1451 if (pdir->internal_entry == -1 && pdir->regulardir == NULL)
1453 pdir->busy = false;
1454 return NULL;
1457 return pdir;
1460 struct dirent_cached* readdir_cached(DIR_CACHED* dir)
1462 struct dircache_entry *ce = get_entry(dir->internal_entry);
1463 struct dirent_uncached *regentry;
1465 if (!dir->busy)
1466 return NULL;
1468 if (dir->regulardir != NULL)
1470 regentry = readdir_uncached(dir->regulardir);
1471 if (regentry == NULL)
1472 return NULL;
1474 strlcpy(dir->theent.d_name, regentry->d_name, MAX_PATH);
1475 dir->theent.startcluster = regentry->startcluster;
1476 dir->theent.info = regentry->info;
1478 return &dir->theent;
1481 /* if theent.attribute=-1 then this is the first call */
1482 /* otherwise, this is is not so we first take the entry's ->next */
1483 /* NOTE: normal file can't have attribute=-1 */
1484 if(dir->theent.info.attribute != -1)
1485 ce = ce->next;
1486 /* skip unused entries */
1487 while(ce != NULL && ce->d_name == NULL)
1488 ce = ce->next;
1490 if (ce == NULL)
1491 return NULL;
1493 strlcpy(dir->theent.d_name, ce->d_name, MAX_PATH);
1494 /* Can't do `dir->theent = *ce`
1495 because that modifies the d_name pointer. */
1496 dir->theent.startcluster = ce->startcluster;
1497 dir->theent.info = ce->info;
1498 dir->internal_entry = ce - dircache_root;
1500 //logf("-> %s", ce->d_name);
1501 return &dir->theent;
1504 int closedir_cached(DIR_CACHED* dir)
1506 if (!dir->busy)
1507 return -1;
1509 dir->busy=false;
1510 if (dir->regulardir != NULL)
1511 return closedir_uncached(dir->regulardir);
1513 return 0;
1516 int mkdir_cached(const char *name)
1518 int rc=mkdir_uncached(name);
1519 if (rc >= 0)
1520 dircache_mkdir(name);
1521 return(rc);
1524 int rmdir_cached(const char* name)
1526 int rc=rmdir_uncached(name);
1527 if(rc >= 0)
1528 dircache_rmdir(name);
1529 return(rc);