1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
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 ****************************************************************************/
23 - Allow cache live updating while transparent rebuild is running.
30 #include "string-extra.h"
41 #include "core_alloc.h"
47 #include "timefuncs.h"
53 #define DIRCACHE_BUILD 1
54 #define DIRCACHE_STOP 2
57 #define MAX_OPEN_DIRS 12
59 #define MAX_OPEN_DIRS 8
61 static DIR_CACHED opendirs
[MAX_OPEN_DIRS
];
62 static char opendir_dnames
[MAX_OPEN_DIRS
][MAX_PATH
];
64 #define MAX_PENDING_BINDINGS 2
70 /* Unions with char to make pointer arithmetic simpler and avoid casting */
71 struct dircache_entry
{
74 struct dircache_entry
*next
;
78 struct dircache_entry
*up
;
82 struct dircache_entry
*down
;
91 * x - array of struct dircache_entry
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
;
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)
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
);
164 UPDATE(d_names_start
);
169 for(unsigned i
= 0; i
< MAX_OPEN_FILES
; i
++)
170 UPDATE(fd_bindings
[i
]);
172 #ifdef HAVE_MULTIVOLUME
173 UPDATE(append_position
);
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
);
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");
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
);
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
)
237 next_entry
->up
= ce
->up
;
238 ce
->next
= 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
)
254 ce
->down
= 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
))
273 case SYS_USB_CONNECTED
:
283 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
284 /* scan and build static data (avoid redundancy on stack) */
287 #ifdef HAVE_MULTIVOLUME
291 struct fat_direntry
*direntry
;
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 */
303 sab
.dir
->entrycount
= 0;
304 sab
.dir
->file
.firstcluster
= 0;
306 int rc
= fat_opendir(IF_MV2(sab
.volume
,) sab
.dir
, startcluster
, sab
.dir
);
309 logf("fat_opendir failed: %d", 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
))
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
);
341 /* When simulator is used, it's only safe to yield here. */
344 /* Stop if we got an external signal. */
345 if(check_event_queue())
351 /* add "." and ".." */
353 ce
->info
.attribute
= FAT_ATTR_DIRECTORY
;
354 ce
->startcluster
= startcluster
;
358 ce
= dircache_gen_next(ce
);
361 ce
->info
.attribute
= FAT_ATTR_DIRECTORY
;
362 ce
->startcluster
= (first_ce
->up
? first_ce
->up
->startcluster
: 0);
364 ce
->down
= first_ce
->up
;
366 /* second pass: recurse ! */
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
);
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
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
;
399 append_position
= dircache_gen_next(ce
);
400 ce
= dircache_gen_down(ce
);
404 struct fat_direntry direntry
; /* ditto */
405 #ifdef HAVE_MULTIVOLUME
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
);
423 logf("Failed to opendir_uncached(%s)", sab_path
);
427 while((entry
= readdir_uncached(dir
)))
429 if(!strcmp(".", entry
->d_name
) ||
430 !strcmp("..", entry
->d_name
))
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
);
445 closedir_uncached(dir
);
448 /* save current paths size */
449 int pathpos
= strlen(sab_path
);
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
);
456 sab_path
[pathpos
] = '\0';
460 closedir_uncached(dir
);
465 ce
= dircache_gen_next(ce
);
469 /* When simulator is used, it's only safe to yield here. */
472 /* Stop if we got an external signal. */
473 if(check_event_queue())
479 /* add "." and ".." */
481 ce
->info
.attribute
= ATTR_DIRECTORY
;
485 ce
= dircache_gen_next(ce
);
488 ce
->info
.attribute
= ATTR_DIRECTORY
;
490 ce
->down
= first_ce
->up
;
492 closedir_uncached(dir
);
496 static int dircache_scan_and_build(IF_MV2(int volume
,) struct dircache_entry
*ce
)
498 #ifdef HAVE_MULTIVOLUME
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)
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
];
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 */
551 cache_entry
= cache_entry
->down
;
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
;
565 if(!strcasecmp(part
, cache_entry
->d_name
))
567 /* go to next entry */
568 cache_entry
= cache_entry
->next
;
571 /* handle not found case */
572 if(cache_entry
== NULL
)
576 /* NOTE: here cache_entry!=NULL so taking ->down is safe */
578 return at_root
? cache_entry
: cache_entry
->down
;
580 return at_root
? NULL
: cache_entry
;
583 #ifdef HAVE_EEPROM_SETTINGS
585 #define DIRCACHE_MAGIC 0x00d0c0a1
586 struct dircache_maindata
{
591 struct dircache_entry
*root_entry
;
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
;
605 if (dircache_initialized
)
608 logf("Loading directory cache");
611 fd
= open_dircache_file(O_RDONLY
, 0);
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");
621 remove_dircache_file();
625 allocated_size
= maindata
.size
+ DIRCACHE_RESERVE
;
626 dircache_handle
= core_alloc_ex("dircache", allocated_size
, &ops
);
627 /* block movement during upcoming I/O */
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");
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
);
650 remove_dircache_file();
651 if (bytes_read
!= bytes_to_read
)
653 logf("Dircache read failed #2");
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
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)
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
;
692 logf("Done, %ld KiB used", dircache_size
/ 1024);
693 dircache_initialized
= true;
694 memset(fd_bindings
, 0, sizeof(fd_bindings
));
701 * Function to save the internal cache stucture to disk for fast loading
704 int dircache_save(void)
706 struct dircache_maindata maindata
;
708 unsigned long bytes_written
;
710 remove_dircache_file();
712 if (!dircache_initialized
)
715 logf("Saving directory cache");
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
))
731 logf("dircache: write failed #1");
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");
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
);
749 if (bytes_written
!= bytes_to_write
)
751 logf("dircache: write failed #3");
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
;
769 /* Measure how long it takes build the cache. */
770 start_tick
= current_tick
;
771 dircache_initializing
= true;
774 /* reset dircache and alloc root entry */
776 root_entry
= allocate_entry();
779 #ifdef HAVE_MULTIVOLUME
780 append_position
= root_entry
;
782 for (i
= NUM_VOLUMES
; i
>= 0; i
--)
784 if (fat_ismounted(i
))
788 #ifdef HAVE_MULTIVOLUME
789 if (dircache_scan_and_build(IF_MV2(i
,) append_position
) < 0)
791 if (dircache_scan_and_build(IF_MV2(0,) root_entry
) < 0)
792 #endif /* HAVE_MULTIVOLUME */
794 logf("dircache_scan_and_build failed");
797 dircache_initializing
= false;
802 #ifdef HAVE_MULTIVOLUME
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
);
821 if (allocated_size
- dircache_size
< DIRCACHE_RESERVE
)
822 reserve_used
= DIRCACHE_RESERVE
- (allocated_size
- dircache_size
);
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
;
847 queue_wait(&dircache_queue
, &ev
);
853 if (!dircache_initialized
)
855 dircache_initialized
= false;
858 thread_enabled
= true;
859 if (dircache_do_rebuild() < 0)
861 thread_enabled
= false;
865 logf("Stopped the rebuilding.");
866 dircache_initialized
= false;
869 case SYS_USB_CONNECTED
:
870 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
871 usb_wait_for_disconnect(&dircache_queue
);
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("..");
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
)
895 logf("Building directory cache");
896 #ifdef HAVE_EEPROM_SETTINGS
897 remove_dircache_file();
900 /* Background build, dircache has been previously allocated and */
901 if (allocated_size
> MAX(last_size
, 0))
903 d_names_start
= d_names_end
;
906 thread_enabled
= true;
907 dircache_initializing
= true;
908 generate_dot_d_names();
910 queue_post(&dircache_queue
, DIRCACHE_BUILD
, 0);
914 /* start by freeing, as we possibly re-allocate */
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;
925 thread_enabled
= true;
926 generate_dot_d_names();
928 /* Start a transparent rebuild. */
929 queue_post(&dircache_queue
, DIRCACHE_BUILD
, 0);
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;
951 generate_dot_d_names();
953 /* Start a non-transparent rebuild. */
954 int res
= dircache_do_rebuild();
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 */
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
;
981 /* equivalent to dircache_size + DIRCACHE_RESERVE + align */
982 allocated_size
= (d_names_end
- buf
);
985 core_shrink(dircache_handle
, dircache_root
, allocated_size
);
993 * Main initialization function that must be called before any other
994 * operations within the dircache.
996 void dircache_init(void)
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
)
1015 #ifdef HAVE_IO_PRIORITY
1016 thread_set_io_priority(thread_id
,IO_PRIORITY_BACKGROUND
);
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
)
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)
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)
1096 queue_post(&dircache_queue
, DIRCACHE_STOP
, 0);
1098 while (thread_enabled
)
1100 dircache_initialized
= false;
1102 logf("Waiting for cached dirs to release");
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;
1113 } while (cache_in_use
) ;
1115 logf("Cache released");
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
1139 void dircache_disable(void)
1146 * Steal the allocated dircache buffer and disable dircache.
1148 void* dircache_steal_buffer(size_t *size
)
1151 if (dircache_size
== 0)
1157 /* since we give up the buffer (without freeing), it must not move anymore */
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
)
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
)
1210 offset
+= copy_path_helper(entry
->up
, buf
, size
);
1212 size_t len
= strlcpy(buf
+offset
, entry
->d_name
, size
- offset
) + offset
;
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)
1232 size_t res
= copy_path_helper(&dircache_root
[index
], buf
, size
- 1);
1233 /* fixup trailing '/' */
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())
1245 if (!dircache_initialized
)
1251 static struct dircache_entry
* dircache_new_entry(const char *path
, int attribute
)
1253 struct dircache_entry
*entry
;
1254 char basedir
[MAX_PATH
*2];
1256 long last_cache_size
= dircache_size
;
1258 strlcpy(basedir
, path
, sizeof(basedir
));
1259 new = strrchr(basedir
, '/');
1262 logf("error occurred");
1263 dircache_initialized
= false;
1270 entry
= dircache_get_entry(basedir
, true);
1273 logf("basedir not found!");
1274 logf("%s", basedir
);
1275 dircache_initialized
= false;
1279 if (reserve_used
+ 2*sizeof(struct dircache_entry
) + strlen(new)+1
1280 >= DIRCACHE_RESERVE
)
1282 logf("not enough space");
1283 dircache_initialized
= false;
1287 while (entry
->next
!= NULL
)
1288 entry
= entry
->next
;
1290 if (entry
->d_name
!= NULL
)
1292 entry
= dircache_gen_next(entry
);
1295 dircache_initialized
= false;
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
)
1312 dircache_gen_down(entry
);
1315 reserve_used
+= dircache_size
- last_cache_size
;
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
)
1329 strlcpy(fdbind_cache
[fdbind_idx
].path
, path
,
1330 sizeof(fdbind_cache
[fdbind_idx
].path
));
1331 fdbind_cache
[fdbind_idx
].fd
= fd
;
1336 if (!dircache_initialized
)
1339 logf("bind: %d/%s", fd
, path
);
1340 entry
= dircache_get_entry(path
, false);
1344 dircache_initialized
= false;
1348 fd_bindings
[fd
] = entry
;
1351 void dircache_update_filesize(int fd
, long newsize
, long startcluster
)
1353 if (!dircache_initialized
|| fd
< 0)
1356 if (fd_bindings
[fd
] == NULL
)
1358 logf("dircache fd(%d) access error", fd
);
1359 dircache_initialized
= false;
1363 fd_bindings
[fd
]->info
.size
= newsize
;
1364 fd_bindings
[fd
]->startcluster
= startcluster
;
1366 void dircache_update_filetime(int fd
)
1372 struct tm
*now
= get_time();
1373 if (!dircache_initialized
|| fd
< 0)
1376 if (fd_bindings
[fd
] == NULL
)
1378 logf("dircache fd access error");
1379 dircache_initialized
= false;
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));
1392 void dircache_mkdir(const char *path
)
1394 if (block_until_ready())
1398 logf("mkdir: %s", path
);
1399 dircache_new_entry(path
, ATTR_DIRECTORY
);
1402 void dircache_rmdir(const char *path
)
1404 struct dircache_entry
*entry
;
1406 if (block_until_ready())
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;
1419 entry
->d_name
= NULL
;
1422 /* Remove a file from cache */
1423 void dircache_remove(const char *name
)
1425 struct dircache_entry
*entry
;
1427 if (block_until_ready())
1430 logf("remove: %s", name
);
1432 entry
= dircache_get_entry(name
, false);
1437 dircache_initialized
= false;
1441 entry
->d_name
= NULL
;
1444 void dircache_rename(const char *oldpath
, const char *newpath
)
1446 struct dircache_entry
*entry
, *newentry
;
1447 struct dircache_entry oldentry
;
1448 char absolute_path
[MAX_PATH
*2];
1451 if (block_until_ready())
1454 logf("rename: %s->%s", oldpath
, newpath
);
1456 entry
= dircache_get_entry(oldpath
, false);
1460 dircache_initialized
= false;
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. */
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
, '/');
1478 logf("Invalid path");
1479 dircache_initialized
= false;
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;
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())
1509 logf("add file: %s", path
);
1510 entry
= dircache_new_entry(path
, 0);
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
)
1525 DIR_CACHED
* pdir
= opendirs
;
1527 if ( name
[0] != '/' )
1529 DEBUGF("Only absolute paths supported right now\n");
1533 /* find a free dir descriptor */
1534 for ( dd
=0; dd
<MAX_OPEN_DIRS
; dd
++, pdir
++)
1538 if ( dd
== MAX_OPEN_DIRS
)
1540 DEBUGF("Too many dirs open\n");
1547 if (!dircache_initialized
|| is_disable_msg_pending())
1549 pdir
->internal_entry
= -1;
1550 pdir
->regulardir
= opendir_uncached(name
);
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
)
1568 struct dirent_cached
* readdir_cached(DIR_CACHED
* dir
)
1570 struct dircache_entry
*ce
= get_entry(dir
->internal_entry
);
1571 struct dirent_uncached
*regentry
;
1576 if (dir
->regulardir
!= NULL
)
1578 regentry
= readdir_uncached(dir
->regulardir
);
1579 if (regentry
== 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)
1594 /* skip unused entries */
1595 while(ce
!= NULL
&& ce
->d_name
== 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
)
1618 if (dir
->regulardir
!= NULL
)
1619 return closedir_uncached(dir
->regulardir
);
1624 int mkdir_cached(const char *name
)
1626 int rc
=mkdir_uncached(name
);
1628 dircache_mkdir(name
);
1632 int rmdir_cached(const char* name
)
1634 int rc
=rmdir_uncached(name
);
1636 dircache_rmdir(name
);