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 ****************************************************************************/
25 * ----------x---------x------------------x-----
27 * +---------------x-------+ | TagCache | Libraries
28 * | Modification routines | | Core |
29 * +-x---------x-----------+ | |
31 * | +------x-------------x-+ +-------------x-----+ |
32 * | | x==x Filters & clauses | |
33 * | | Search routines | +-------------------+ |
34 * | | x============================x DirCache
35 * | +-x--------------------+ | (optional)
37 * | | +-------------------------------+ +---------+ |
38 * | | | DB Commit (sort,unique,index) | | | |
39 * | | +-x--------------------------x--+ | Control | |
40 * | | | (R/W) | (R) | Thread | |
41 * | | | +----------------------+ | | | |
42 * | | | | TagCache DB Builder | | +---------+ |
43 * | | | +-x-------------x------+ | |
44 * | | | | (R) | (W) | |
45 * | | | | +--x--------x---------+ |
46 * | | | | | Temporary Commit DB | |
47 * | | | | +---------------------+ |
48 * +-x----x-------x--+ |
49 * | TagCache RAM DB x==\(W) +-----------------+ |
50 * +-----------------+ \===x | |
51 * | | | | (R) | Ram DB Loader x============x DirCache
52 * +-x----x---x---x---+ /==x | | (optional)
53 * | Tagcache Disk DB x==/ +-----------------+ |
54 * +------------------+ |
58 /*#define LOGF_ENABLE*/
64 #include "ata_idle_notify.h"
69 #include "string-extra.h"
76 #include "filefuncs.h"
83 #include "eeprom_settings.h"
87 #define yield() do { } while(0)
88 #define sim_sleep(timeout) do { } while(0)
89 #define do_timed_yield() do { } while(0)
93 /* Tag Cache thread. */
94 static struct event_queue tagcache_queue
;
95 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
96 static const char tagcache_thread_name
[] = "tagcache";
99 /* Previous path when scanning directory tree recursively. */
100 static char curpath
[TAG_MAXLEN
+32];
102 /* Used when removing duplicates. */
103 static char *tempbuf
; /* Allocated when needed. */
104 static long tempbufidx
; /* Current location in buffer. */
105 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
106 static long tempbuf_left
; /* Buffer space left. */
107 static long tempbuf_pos
;
109 #define SORTED_TAGS_COUNT 8
110 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
111 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
112 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
113 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
114 /* Tags we want to get sorted (loaded to the tempbuf). */
115 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
116 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
117 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
119 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
120 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
121 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
122 (1LU << tag_albumartist) | (1LU << tag_grouping))
124 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
125 static const char *tags_str
[] = { "artist", "album", "genre", "title",
126 "filename", "composer", "comment", "albumartist", "grouping", "year",
127 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
128 "playtime", "lastplayed", "commitid", "mtime" };
130 /* Status information of the tagcache. */
131 static struct tagcache_stat tc_stat
;
133 /* Queue commands. */
134 enum tagcache_queue
{
141 /* Internal tagcache command queue. */
142 CMD_UPDATE_MASTER_HEADER
,
146 struct tagcache_command_entry
{
154 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
155 static volatile int command_queue_widx
= 0;
156 static volatile int command_queue_ridx
= 0;
157 static struct mutex command_queue_mutex
;
160 /* Tag database structures. */
162 /* Variable-length tag entry in tag files. */
163 struct tagfile_entry
{
164 int32_t tag_length
; /* Length of the data in bytes including '\0' */
165 int32_t idx_id
; /* Corresponding entry location in index file of not unique tags */
166 char tag_data
[0]; /* Begin of the tag data */
169 /* Fixed-size tag entry in master db index. */
171 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
172 int32_t flag
; /* Status flags */
175 /* Header is the same in every file. */
176 struct tagcache_header
{
177 int32_t magic
; /* Header version number */
178 int32_t datasize
; /* Data size in bytes */
179 int32_t entry_count
; /* Number of entries in this file */
182 struct master_header
{
183 struct tagcache_header tch
;
184 int32_t serial
; /* Increasing counting number */
185 int32_t commitid
; /* Number of commits so far */
189 /* For the endianess correction */
190 static const char *tagfile_entry_ec
= "ll";
192 Note: This should be (1 + TAG_COUNT) amount of l's.
194 static const char *index_entry_ec
= "lllllllllllllllllllll";
196 static const char *tagcache_header_ec
= "lll";
197 static const char *master_header_ec
= "llllll";
199 static struct master_header current_tcmh
;
201 #ifdef HAVE_TC_RAMCACHE
202 /* Header is created when loading database to ram. */
203 struct ramcache_header
{
204 struct master_header h
; /* Header from the master index */
205 struct index_entry
*indices
; /* Master index file content */
206 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
207 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
210 # ifdef HAVE_EEPROM_SETTINGS
211 struct statefile_header
{
212 struct ramcache_header
*hdr
;
213 struct tagcache_stat tc_stat
;
217 /* Pointer to allocated ramcache_header */
218 static struct ramcache_header
*hdr
;
222 * Full tag entries stored in a temporary file waiting
223 * for commit to the cache. */
224 struct temp_file_entry
{
225 long tag_offset
[TAG_COUNT
];
226 short tag_length
[TAG_COUNT
];
232 struct tempbuf_id_list
{
234 struct tempbuf_id_list
*next
;
237 struct tempbuf_searchidx
{
241 struct tempbuf_id_list idlist
;
244 /* Lookup buffer for fixing messed up index while after sorting. */
245 static long commit_entry_count
;
246 static long lookup_buffer_depth
;
247 static struct tempbuf_searchidx
**lookup
;
249 /* Used when building the temporary file. */
250 static int cachefd
= -1, filenametag_fd
;
251 static int total_entry_count
= 0;
252 static int data_size
= 0;
253 static int processed_dir_count
;
255 /* Thread safe locking */
256 static volatile int write_lock
;
257 static volatile int read_lock
;
259 static bool delete_entry(long idx_id
);
261 const char* tagcache_tag_to_str(int tag
)
263 return tags_str
[tag
];
266 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
267 static ssize_t
ecread_tagfile_entry(int fd
, struct tagfile_entry
*buf
)
269 return ecread(fd
, buf
, 1, tagfile_entry_ec
, tc_stat
.econ
);
272 static ssize_t
ecread_index_entry(int fd
, struct index_entry
*buf
)
274 return ecread(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
277 static ssize_t
ecwrite_index_entry(int fd
, struct index_entry
*buf
)
279 return ecwrite(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
284 * Returns true if specified flag is still present, i.e., dircache
285 * has not been reloaded.
287 static bool is_dircache_intact(void)
289 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
293 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
296 char buf
[MAX_PATH
], path
[MAX_PATH
];
300 if (TAGCACHE_IS_NUMERIC(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
303 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
304 file
= get_user_file_path(buf
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
306 fd
= open(file
, write
? O_RDWR
: O_RDONLY
);
309 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
310 tc_stat
.ready
= false;
314 /* Check the header. */
315 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
316 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
318 logf("header error");
319 tc_stat
.ready
= false;
327 static int open_master_fd(struct master_header
*hdr
, bool write
)
333 fd
= open(get_user_file_path(TAGCACHE_FILE_MASTER
,
336 write
? O_RDWR
: O_RDONLY
);
339 logf("master file open failed for R/W");
340 tc_stat
.ready
= false;
344 tc_stat
.econ
= false;
346 /* Check the header. */
347 rc
= read(fd
, hdr
, sizeof(struct master_header
));
348 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
354 /* Trying to read again, this time with endianess correction enabled. */
355 lseek(fd
, 0, SEEK_SET
);
357 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
358 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
360 logf("header error");
361 tc_stat
.ready
= false;
372 static bool do_timed_yield(void)
374 /* Sorting can lock up for quite a while, so yield occasionally */
375 static long wakeup_tick
= 0;
376 if (TIME_AFTER(current_tick
, wakeup_tick
))
378 wakeup_tick
= current_tick
+ (HZ
/4);
386 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
387 static long find_entry_ram(const char *filename
,
388 const struct dircache_entry
*dc
)
390 static long last_pos
= 0;
393 /* Check if we tagcache is loaded into ram. */
394 if (!tc_stat
.ramcache
)
398 dc
= dircache_get_entry_ptr(filename
);
402 logf("tagcache: file not found.");
413 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
415 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
417 last_pos
= MAX(0, i
- 3);
434 static long find_entry_disk(const char *filename
, bool localfd
)
436 struct tagcache_header tch
;
437 static long last_pos
= -1;
438 long pos_history
[POS_HISTORY_COUNT
];
439 long pos_history_idx
= 0;
441 struct tagfile_entry tfe
;
443 char buf
[TAG_MAXLEN
+32];
451 if (fd
< 0 || localfd
)
454 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
461 lseek(fd
, last_pos
, SEEK_SET
);
463 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
467 pos
= lseek(fd
, 0, SEEK_CUR
);
468 for (i
= pos_history_idx
-1; i
>= 0; i
--)
469 pos_history
[i
+1] = pos_history
[i
];
470 pos_history
[0] = pos
;
472 if (ecread_tagfile_entry(fd
, &tfe
)
473 != sizeof(struct tagfile_entry
))
478 if (tfe
.tag_length
>= (long)sizeof(buf
))
480 logf("too long tag #1");
488 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
490 logf("read error #2");
498 if (!strcasecmp(filename
, buf
))
500 last_pos
= pos_history
[pos_history_idx
];
505 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
519 if (fd
!= filenametag_fd
|| localfd
)
524 if (fd
!= filenametag_fd
|| localfd
)
530 static int find_index(const char *filename
)
534 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
535 if (tc_stat
.ramcache
&& is_dircache_intact())
536 idx_id
= find_entry_ram(filename
, NULL
);
540 idx_id
= find_entry_disk(filename
, true);
545 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
552 idx_id
= find_index(filename
);
556 if (!tagcache_search(tcs
, tag_filename
))
559 tcs
->entry_count
= 0;
560 tcs
->idx_id
= idx_id
;
565 static bool get_index(int masterfd
, int idxid
,
566 struct index_entry
*idx
, bool use_ram
)
568 bool localfd
= false;
572 logf("Incorrect idxid: %d", idxid
);
576 #ifdef HAVE_TC_RAMCACHE
577 if (tc_stat
.ramcache
&& use_ram
)
579 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
582 # ifdef HAVE_DIRCACHE
583 if (!(hdr
->indices
[idxid
].flag
& FLAG_DIRCACHE
)
584 || is_dircache_intact())
587 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
597 struct master_header tcmh
;
600 masterfd
= open_master_fd(&tcmh
, false);
605 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
606 + sizeof(struct master_header
), SEEK_SET
);
607 if (ecread_index_entry(masterfd
, idx
)
608 != sizeof(struct index_entry
))
610 logf("read error #3");
620 if (idx
->flag
& FLAG_DELETED
)
628 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
630 /* We need to exclude all memory only flags & tags when writing to disk. */
631 if (idx
->flag
& FLAG_DIRCACHE
)
633 logf("memory only flags!");
637 #ifdef HAVE_TC_RAMCACHE
638 /* Only update numeric data. Writing the whole index to RAM by memcpy
639 * destroys dircache pointers!
641 if (tc_stat
.ramcache
)
644 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
646 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
648 if (TAGCACHE_IS_NUMERIC(tag
))
650 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
654 /* Don't touch the dircache flag or attributes. */
655 idx_ram
->flag
= (idx
->flag
& 0x0000ffff)
656 | (idx_ram
->flag
& (0xffff0000 | FLAG_DIRCACHE
));
660 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
661 + sizeof(struct master_header
), SEEK_SET
);
662 if (ecwrite_index_entry(masterfd
, idx
) != sizeof(struct index_entry
))
664 logf("write error #3");
665 logf("idxid: %d", idxid
);
672 #endif /* !__PCTOOL__ */
674 static bool open_files(struct tagcache_search
*tcs
, int tag
)
676 if (tcs
->idxfd
[tag
] < 0)
678 char fn
[MAX_PATH
], path
[MAX_PATH
];
681 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
682 file
= get_user_file_path(fn
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
683 tcs
->idxfd
[tag
] = open(file
, O_RDONLY
);
686 if (tcs
->idxfd
[tag
] < 0)
688 logf("File not open!");
695 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
696 int tag
, char *buf
, long size
)
698 struct tagfile_entry tfe
;
703 if (TAGCACHE_IS_NUMERIC(tag
))
706 seek
= idx
->tag_seek
[tag
];
709 logf("Retrieve failed");
713 #ifdef HAVE_TC_RAMCACHE
716 struct tagfile_entry
*ep
;
718 # ifdef HAVE_DIRCACHE
719 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
720 && is_dircache_intact())
722 dircache_copy_path((struct dircache_entry
*)seek
,
728 if (tag
!= tag_filename
)
730 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
731 strlcpy(buf
, ep
->tag_data
, size
);
738 if (!open_files(tcs
, tag
))
741 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
742 if (ecread_tagfile_entry(tcs
->idxfd
[tag
], &tfe
)
743 != sizeof(struct tagfile_entry
))
745 logf("read error #5");
749 if (tfe
.tag_length
>= size
)
751 logf("too small buffer");
755 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
758 logf("read error #6");
762 buf
[tfe
.tag_length
] = '\0';
767 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
769 static long read_numeric_tag(int tag
, int idx_id
, const struct index_entry
*idx
)
771 if (! COMMAND_QUEUE_IS_EMPTY
)
773 /* Attempt to find tag data through store-to-load forwarding in
777 mutex_lock(&command_queue_mutex
);
779 int ridx
= command_queue_widx
;
781 while (ridx
!= command_queue_ridx
)
784 ridx
= TAGCACHE_COMMAND_QUEUE_LENGTH
- 1;
786 if (command_queue
[ridx
].command
== CMD_UPDATE_NUMERIC
787 && command_queue
[ridx
].idx_id
== idx_id
788 && command_queue
[ridx
].tag
== tag
)
790 result
= command_queue
[ridx
].data
;
795 mutex_unlock(&command_queue_mutex
);
799 logf("read_numeric_tag: "
800 "Recovered tag %d value %lX from write queue",
806 return idx
->tag_seek
[tag
];
810 static long check_virtual_tags(int tag
, int idx_id
,
811 const struct index_entry
*idx
)
817 case tag_virt_length_sec
:
818 data
= (read_numeric_tag(tag_length
, idx_id
, idx
)/1000) % 60;
821 case tag_virt_length_min
:
822 data
= (read_numeric_tag(tag_length
, idx_id
, idx
)/1000) / 60;
825 case tag_virt_playtime_sec
:
826 data
= (read_numeric_tag(tag_playtime
, idx_id
, idx
)/1000) % 60;
829 case tag_virt_playtime_min
:
830 data
= (read_numeric_tag(tag_playtime
, idx_id
, idx
)/1000) / 60;
833 case tag_virt_autoscore
:
834 if (read_numeric_tag(tag_length
, idx_id
, idx
) == 0
835 || read_numeric_tag(tag_playcount
, idx_id
, idx
) == 0)
841 /* A straight calculus gives:
842 autoscore = 100 * playtime / length / playcout (1)
843 Now, consider the euclidian division of playtime by length:
844 playtime = alpha * length + beta
848 autoscore = 100 * (alpha / playcout + beta / length / playcount)
849 Both terms should be small enough to avoid any overflow
851 data
= 100 * (read_numeric_tag(tag_playtime
, idx_id
, idx
)
852 / read_numeric_tag(tag_length
, idx_id
, idx
))
853 + (100 * (read_numeric_tag(tag_playtime
, idx_id
, idx
)
854 % read_numeric_tag(tag_length
, idx_id
, idx
)))
855 / read_numeric_tag(tag_length
, idx_id
, idx
);
856 data
/= read_numeric_tag(tag_playcount
, idx_id
, idx
);
860 /* How many commits before the file has been added to the DB. */
861 case tag_virt_entryage
:
862 data
= current_tcmh
.commitid
863 - read_numeric_tag(tag_commitid
, idx_id
, idx
) - 1;
867 data
= read_numeric_tag(tag
, idx_id
, idx
);
873 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
875 struct index_entry idx
;
880 if (!TAGCACHE_IS_NUMERIC(tag
))
883 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
886 return check_virtual_tags(tag
, tcs
->idx_id
, &idx
);
889 inline static bool str_ends_with(const char *str1
, const char *str2
)
891 int str_len
= strlen(str1
);
892 int clause_len
= strlen(str2
);
894 if (clause_len
> str_len
)
897 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
900 inline static bool str_oneof(const char *str
, const char *list
)
903 int l
, len
= strlen(str
);
907 sep
= strchr(list
, '|');
908 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
909 if ((l
==len
) && !strncasecmp(str
, list
, len
))
911 list
+= sep
? l
+ 1 : l
;
917 static bool check_against_clause(long numeric
, const char *str
,
918 const struct tagcache_search_clause
*clause
)
922 switch (clause
->type
)
925 return numeric
== clause
->numeric_data
;
927 return numeric
!= clause
->numeric_data
;
929 return numeric
> clause
->numeric_data
;
931 return numeric
>= clause
->numeric_data
;
933 return numeric
< clause
->numeric_data
;
935 return numeric
<= clause
->numeric_data
;
937 logf("Incorrect numeric tag: %d", clause
->type
);
942 switch (clause
->type
)
945 return !strcasecmp(clause
->str
, str
);
947 return strcasecmp(clause
->str
, str
);
949 return 0>strcasecmp(clause
->str
, str
);
951 return 0>=strcasecmp(clause
->str
, str
);
953 return 0<strcasecmp(clause
->str
, str
);
955 return 0<=strcasecmp(clause
->str
, str
);
956 case clause_contains
:
957 return (strcasestr(str
, clause
->str
) != NULL
);
958 case clause_not_contains
:
959 return (strcasestr(str
, clause
->str
) == NULL
);
960 case clause_begins_with
:
961 return (strcasestr(str
, clause
->str
) == str
);
962 case clause_not_begins_with
:
963 return (strcasestr(str
, clause
->str
) != str
);
964 case clause_ends_with
:
965 return str_ends_with(str
, clause
->str
);
966 case clause_not_ends_with
:
967 return !str_ends_with(str
, clause
->str
);
969 return str_oneof(str
, clause
->str
);
972 logf("Incorrect tag: %d", clause
->type
);
979 static bool check_clauses(struct tagcache_search
*tcs
,
980 struct index_entry
*idx
,
981 struct tagcache_search_clause
**clause
, int count
)
985 #ifdef HAVE_TC_RAMCACHE
988 /* Go through all conditional clauses. */
989 for (i
= 0; i
< count
; i
++)
991 struct tagfile_entry
*tfe
;
996 seek
= check_virtual_tags(clause
[i
]->tag
, tcs
->idx_id
, idx
);
998 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
1000 if (clause
[i
]->tag
== tag_filename
)
1002 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
1007 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
1008 str
= tfe
->tag_data
;
1012 if (!check_against_clause(seek
, str
, clause
[i
]))
1019 /* Check for conditions. */
1020 for (i
= 0; i
< count
; i
++)
1022 struct tagfile_entry tfe
;
1026 seek
= check_virtual_tags(clause
[i
]->tag
, tcs
->idx_id
, idx
);
1028 memset(str
, 0, sizeof str
);
1029 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
1031 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
1032 lseek(fd
, seek
, SEEK_SET
);
1033 ecread_tagfile_entry(fd
, &tfe
);
1034 if (tfe
.tag_length
>= (int)sizeof(str
))
1036 logf("Too long tag read!");
1040 read(fd
, str
, tfe
.tag_length
);
1042 /* Check if entry has been deleted. */
1047 if (!check_against_clause(seek
, str
, clause
[i
]))
1055 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
1056 struct tagcache_search_clause
**clause
, int count
)
1058 struct index_entry idx
;
1063 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
1066 return check_clauses(tcs
, &idx
, clause
, count
);
1069 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1073 /* If uniq buffer is not defined we must return true for search to work. */
1074 if (tcs
->unique_list
== NULL
|| (!TAGCACHE_IS_UNIQUE(tcs
->type
)
1075 && !TAGCACHE_IS_NUMERIC(tcs
->type
)))
1080 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1082 /* Return false if entry is found. */
1083 if (tcs
->unique_list
[i
] == id
)
1087 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1089 tcs
->unique_list
[i
] = id
;
1090 tcs
->unique_list_count
++;
1096 static bool build_lookup_list(struct tagcache_search
*tcs
)
1098 struct index_entry entry
;
1101 tcs
->seek_list_count
= 0;
1103 #ifdef HAVE_TC_RAMCACHE
1105 # ifdef HAVE_DIRCACHE
1106 && (tcs
->type
!= tag_filename
|| is_dircache_intact())
1110 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
1112 struct tagcache_seeklist_entry
*seeklist
;
1113 struct index_entry
*idx
= &hdr
->indices
[i
];
1114 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1117 /* Skip deleted files. */
1118 if (idx
->flag
& FLAG_DELETED
)
1121 /* Go through all filters.. */
1122 for (j
= 0; j
< tcs
->filter_count
; j
++)
1124 if (idx
->tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1130 if (j
< tcs
->filter_count
)
1133 /* Check for conditions. */
1134 if (!check_clauses(tcs
, idx
, tcs
->clause
, tcs
->clause_count
))
1137 /* Add to the seek list if not already in uniq buffer. */
1138 if (!add_uniqbuf(tcs
, idx
->tag_seek
[tcs
->type
]))
1142 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1143 seeklist
->seek
= idx
->tag_seek
[tcs
->type
];
1144 seeklist
->flag
= idx
->flag
;
1145 seeklist
->idx_id
= i
;
1146 tcs
->seek_list_count
++;
1151 return tcs
->seek_list_count
> 0;
1155 if (tcs
->masterfd
< 0)
1157 struct master_header tcmh
;
1158 tcs
->masterfd
= open_master_fd(&tcmh
, false);
1161 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1162 sizeof(struct master_header
), SEEK_SET
);
1164 while (ecread_index_entry(tcs
->masterfd
, &entry
)
1165 == sizeof(struct index_entry
))
1167 struct tagcache_seeklist_entry
*seeklist
;
1169 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1175 /* Check if entry has been deleted. */
1176 if (entry
.flag
& FLAG_DELETED
)
1179 /* Go through all filters.. */
1180 for (j
= 0; j
< tcs
->filter_count
; j
++)
1182 if (entry
.tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1186 if (j
< tcs
->filter_count
)
1189 /* Check for conditions. */
1190 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1193 /* Add to the seek list if not already in uniq buffer. */
1194 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1198 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1199 seeklist
->seek
= entry
.tag_seek
[tcs
->type
];
1200 seeklist
->flag
= entry
.flag
;
1201 seeklist
->idx_id
= i
;
1202 tcs
->seek_list_count
++;
1207 return tcs
->seek_list_count
> 0;
1211 static void remove_files(void)
1216 tc_stat
.ready
= false;
1217 tc_stat
.ramcache
= false;
1218 tc_stat
.econ
= false;
1219 remove(get_user_file_path(TAGCACHE_FILE_MASTER
, NEED_WRITE
|IS_FILE
,
1221 for (i
= 0; i
< TAG_COUNT
; i
++)
1223 char buf2
[MAX_PATH
];
1224 if (TAGCACHE_IS_NUMERIC(i
))
1227 /* database_%d.tcd -> database_0.tcd */
1228 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1229 remove(get_user_file_path(buf
, NEED_WRITE
| IS_FILE
, buf2
, sizeof(buf2
)));
1234 static bool check_all_headers(void)
1236 struct master_header myhdr
;
1237 struct tagcache_header tch
;
1241 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1247 logf("tagcache is dirty!");
1251 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1253 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1255 if (TAGCACHE_IS_NUMERIC(tag
))
1258 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1267 bool tagcache_is_busy(void)
1269 return read_lock
|| write_lock
;
1272 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1274 struct tagcache_header tag_hdr
;
1275 struct master_header master_hdr
;
1281 memset(tcs
, 0, sizeof(struct tagcache_search
));
1282 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1285 tcs
->position
= sizeof(struct tagcache_header
);
1288 tcs
->list_position
= 0;
1289 tcs
->seek_list_count
= 0;
1290 tcs
->filter_count
= 0;
1293 for (i
= 0; i
< TAG_COUNT
; i
++)
1296 #ifndef HAVE_TC_RAMCACHE
1297 tcs
->ramsearch
= false;
1299 tcs
->ramsearch
= tc_stat
.ramcache
;
1302 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1307 /* Always open as R/W so we can pass tcs to functions that modify data also
1308 * without failing. */
1309 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1310 if (tcs
->masterfd
< 0)
1313 if (!TAGCACHE_IS_NUMERIC(tcs
->type
))
1315 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1316 if (tcs
->idxfd
[tcs
->type
] < 0)
1319 tcs
->entry_count
= tag_hdr
.entry_count
;
1323 tcs
->entry_count
= master_hdr
.tch
.entry_count
;
1328 tcs
->initialized
= true;
1334 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1335 void *buffer
, long length
)
1337 tcs
->unique_list
= (unsigned long *)buffer
;
1338 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1339 tcs
->unique_list_count
= 0;
1342 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1345 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1348 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag
))
1351 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1352 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1353 tcs
->filter_count
++;
1358 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1359 struct tagcache_search_clause
*clause
)
1363 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1365 logf("Too many clauses");
1369 /* Check if there is already a similar filter in present (filters are
1370 * much faster than clauses).
1372 for (i
= 0; i
< tcs
->filter_count
; i
++)
1374 if (tcs
->filter_tag
[i
] == clause
->tag
)
1378 if (!TAGCACHE_IS_NUMERIC(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1380 char buf
[MAX_PATH
], path
[MAX_PATH
];
1382 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1383 file
= get_user_file_path(buf
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
1384 tcs
->idxfd
[clause
->tag
] = open(file
, O_RDONLY
);
1387 tcs
->clause
[tcs
->clause_count
] = clause
;
1388 tcs
->clause_count
++;
1393 static bool get_next(struct tagcache_search
*tcs
)
1395 static char buf
[TAG_MAXLEN
+32];
1396 struct tagfile_entry entry
;
1399 if (!tcs
->valid
|| !tc_stat
.ready
)
1402 if (tcs
->idxfd
[tcs
->type
] < 0 && !TAGCACHE_IS_NUMERIC(tcs
->type
)
1403 #ifdef HAVE_TC_RAMCACHE
1409 /* Relative fetch. */
1410 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1411 || TAGCACHE_IS_NUMERIC(tcs
->type
)
1412 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1413 /* We need to retrieve flag status for dircache. */
1414 || (tcs
->ramsearch
&& tcs
->type
== tag_filename
)
1418 struct tagcache_seeklist_entry
*seeklist
;
1420 /* Check for end of list. */
1421 if (tcs
->list_position
== tcs
->seek_list_count
)
1423 tcs
->list_position
= 0;
1425 /* Try to fetch more. */
1426 if (!build_lookup_list(tcs
))
1433 seeklist
= &tcs
->seeklist
[tcs
->list_position
];
1434 flag
= seeklist
->flag
;
1435 tcs
->position
= seeklist
->seek
;
1436 tcs
->idx_id
= seeklist
->idx_id
;
1437 tcs
->list_position
++;
1441 if (tcs
->entry_count
== 0)
1450 tcs
->result_seek
= tcs
->position
;
1452 if (TAGCACHE_IS_NUMERIC(tcs
->type
))
1454 snprintf(buf
, sizeof(buf
), "%ld", tcs
->position
);
1456 tcs
->result_len
= strlen(buf
) + 1;
1461 #ifdef HAVE_TC_RAMCACHE
1465 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1466 if (tcs
->type
== tag_filename
&& (flag
& FLAG_DIRCACHE
)
1467 && is_dircache_intact())
1469 dircache_copy_path((struct dircache_entry
*)tcs
->position
,
1472 tcs
->result_len
= strlen(buf
) + 1;
1473 tcs
->ramresult
= false;
1479 if (tcs
->type
!= tag_filename
)
1481 struct tagfile_entry
*ep
;
1483 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1484 tcs
->result
= ep
->tag_data
;
1485 tcs
->result_len
= strlen(tcs
->result
) + 1;
1486 tcs
->idx_id
= ep
->idx_id
;
1487 tcs
->ramresult
= true;
1489 /* Increase position for the next run. This may get overwritten. */
1490 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1497 if (!open_files(tcs
, tcs
->type
))
1503 /* Seek stream to the correct position and continue to direct fetch. */
1504 lseek(tcs
->idxfd
[tcs
->type
], tcs
->position
, SEEK_SET
);
1506 if (ecread_tagfile_entry(tcs
->idxfd
[tcs
->type
], &entry
) != sizeof(struct tagfile_entry
))
1508 logf("read error #5");
1513 if (entry
.tag_length
> (long)sizeof(buf
))
1516 logf("too long tag #2");
1517 logf("P:%lX/%lX", tcs
->position
, entry
.tag_length
);
1521 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1524 logf("read error #4");
1529 Update the position for the next read (this may be overridden
1530 if filters or clauses are being used).
1532 tcs
->position
+= sizeof(struct tagfile_entry
) + entry
.tag_length
;
1534 tcs
->result_len
= strlen(tcs
->result
) + 1;
1535 tcs
->idx_id
= entry
.idx_id
;
1536 tcs
->ramresult
= false;
1541 bool tagcache_get_next(struct tagcache_search
*tcs
)
1543 while (get_next(tcs
))
1545 if (tcs
->result_len
> 1)
1552 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1553 int tag
, char *buf
, long size
)
1555 struct index_entry idx
;
1558 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1561 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1564 static bool update_master_header(void)
1566 struct master_header myhdr
;
1572 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1575 myhdr
.serial
= current_tcmh
.serial
;
1576 myhdr
.commitid
= current_tcmh
.commitid
;
1577 myhdr
.dirty
= current_tcmh
.dirty
;
1580 lseek(fd
, 0, SEEK_SET
);
1581 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1584 #ifdef HAVE_TC_RAMCACHE
1587 hdr
->h
.serial
= current_tcmh
.serial
;
1588 hdr
->h
.commitid
= current_tcmh
.commitid
;
1589 hdr
->h
.dirty
= current_tcmh
.dirty
;
1598 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1600 struct tagentry
*entry
;
1602 if (tcs
->type
!= tag_title
)
1605 /* We will need reserve buffer for this. */
1608 struct tagfile_entry
*ep
;
1610 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1611 tcs
->seek_list
[tcs
->seek_list_count
];
1614 entry
= find_entry_ram();
1619 void tagcache_search_finish(struct tagcache_search
*tcs
)
1623 if (!tcs
->initialized
)
1626 if (tcs
->masterfd
>= 0)
1628 close(tcs
->masterfd
);
1632 for (i
= 0; i
< TAG_COUNT
; i
++)
1634 if (tcs
->idxfd
[i
] >= 0)
1636 close(tcs
->idxfd
[i
]);
1641 tcs
->ramsearch
= false;
1643 tcs
->initialized
= 0;
1648 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1649 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1651 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1654 static long get_tag_numeric(const struct index_entry
*entry
, int tag
, int idx_id
)
1656 return check_virtual_tags(tag
, idx_id
, entry
);
1659 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1661 char* s
= get_tag(entry
, tag
)->tag_data
;
1662 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1665 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1667 struct index_entry
*entry
;
1670 if (!tc_stat
.ready
|| !tc_stat
.ramcache
)
1673 /* Find the corresponding entry in tagcache. */
1674 idx_id
= find_entry_ram(filename
, NULL
);
1678 entry
= &hdr
->indices
[idx_id
];
1680 memset(id3
, 0, sizeof(struct mp3entry
));
1682 id3
->title
= get_tag_string(entry
, tag_title
);
1683 id3
->artist
= get_tag_string(entry
, tag_artist
);
1684 id3
->album
= get_tag_string(entry
, tag_album
);
1685 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1686 id3
->composer
= get_tag_string(entry
, tag_composer
);
1687 id3
->comment
= get_tag_string(entry
, tag_comment
);
1688 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1689 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1691 id3
->length
= get_tag_numeric(entry
, tag_length
, idx_id
);
1692 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
, idx_id
);
1693 id3
->rating
= get_tag_numeric(entry
, tag_rating
, idx_id
);
1694 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
, idx_id
);
1695 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
, idx_id
) / 10;
1696 id3
->year
= get_tag_numeric(entry
, tag_year
, idx_id
);
1698 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
, idx_id
);
1699 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
, idx_id
);
1700 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
, idx_id
);
1701 if (id3
->bitrate
== 0)
1708 static inline void write_item(const char *item
)
1710 int len
= strlen(item
) + 1;
1713 write(cachefd
, item
, len
);
1716 static int check_if_empty(char **tag
)
1720 if (*tag
== NULL
|| **tag
== '\0')
1723 return sizeof(UNTAGGED
); /* Tag length */
1726 length
= strlen(*tag
);
1727 if (length
> TAG_MAXLEN
)
1729 logf("over length tag: %s", *tag
);
1730 length
= TAG_MAXLEN
;
1731 (*tag
)[length
] = '\0';
1737 #define ADD_TAG(entry,tag,data) \
1739 entry.tag_offset[tag] = offset; \
1740 entry.tag_length[tag] = check_if_empty(data); \
1741 offset += entry.tag_length[tag]
1742 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1743 * idea, as it uses lots of stack and is called from a recursive function
1746 static void __attribute__ ((noinline
)) add_tagcache(char *path
,
1748 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1749 ,const struct dircache_entry
*dc
1753 struct mp3entry id3
;
1754 struct temp_file_entry entry
;
1758 char tracknumfix
[3];
1760 int path_length
= strlen(path
);
1761 bool has_albumartist
;
1765 /* Crude logging for the sim - to aid in debugging */
1766 int logfd
= open(ROCKBOX_DIR
"/database.log",
1767 O_WRONLY
| O_APPEND
| O_CREAT
, 0666);
1769 write(logfd
, path
, strlen(path
));
1770 write(logfd
, "\n", 1);
1778 /* Check for overlength file path. */
1779 if (path_length
> TAG_MAXLEN
)
1781 /* Path can't be shortened. */
1782 logf("Too long path: %s", path
);
1786 /* Check if the file is supported. */
1787 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1790 /* Check if the file is already cached. */
1791 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1792 if (tc_stat
.ramcache
&& is_dircache_intact())
1794 idx_id
= find_entry_ram(path
, dc
);
1798 /* Be sure the entry doesn't exist. */
1799 if (filenametag_fd
>= 0 && idx_id
< 0)
1800 idx_id
= find_entry_disk(path
, false);
1802 /* Check if file has been modified. */
1805 struct index_entry idx
;
1807 /* TODO: Mark that the index exists (for fast reverse scan) */
1808 //found_idx[idx_id/8] |= idx_id%8;
1810 if (!get_index(-1, idx_id
, &idx
, true))
1812 logf("failed to retrieve index entry");
1816 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1818 /* No changes to file. */
1822 /* Metadata might have been changed. Delete the entry. */
1823 logf("Re-adding: %s", path
);
1824 if (!delete_entry(idx_id
))
1826 logf("delete_entry failed: %d", idx_id
);
1831 fd
= open(path
, O_RDONLY
);
1834 logf("open fail: %s", path
);
1838 memset(&id3
, 0, sizeof(struct mp3entry
));
1839 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1840 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1841 ret
= get_metadata(&id3
, fd
, path
);
1847 logf("-> %s", path
);
1849 /* Generate track number if missing. */
1850 if (id3
.tracknum
<= 0)
1852 const char *p
= strrchr(path
, '.');
1855 p
= &path
[strlen(path
)-1];
1859 if (isdigit(*p
) && isdigit(*(p
-1)))
1861 tracknumfix
[1] = *p
--;
1862 tracknumfix
[0] = *p
;
1868 if (tracknumfix
[0] != '\0')
1870 id3
.tracknum
= atoi(tracknumfix
);
1871 /* Set a flag to indicate track number has been generated. */
1872 entry
.flag
|= FLAG_TRKNUMGEN
;
1876 /* Unable to generate track number. */
1882 entry
.tag_offset
[tag_year
] = id3
.year
;
1883 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1884 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1885 entry
.tag_offset
[tag_length
] = id3
.length
;
1886 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1887 entry
.tag_offset
[tag_mtime
] = mtime
;
1890 has_albumartist
= id3
.albumartist
!= NULL
1891 && strlen(id3
.albumartist
) > 0;
1892 has_grouping
= id3
.grouping
!= NULL
1893 && strlen(id3
.grouping
) > 0;
1895 ADD_TAG(entry
, tag_filename
, &path
);
1896 ADD_TAG(entry
, tag_title
, &id3
.title
);
1897 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1898 ADD_TAG(entry
, tag_album
, &id3
.album
);
1899 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1900 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1901 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1902 if (has_albumartist
)
1904 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1908 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1912 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1916 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1918 entry
.data_length
= offset
;
1920 /* Write the header */
1921 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1923 /* And tags also... Correct order is critical */
1925 write_item(id3
.title
);
1926 write_item(id3
.artist
);
1927 write_item(id3
.album
);
1928 write_item(id3
.genre_string
);
1929 write_item(id3
.composer
);
1930 write_item(id3
.comment
);
1931 if (has_albumartist
)
1933 write_item(id3
.albumartist
);
1937 write_item(id3
.artist
);
1941 write_item(id3
.grouping
);
1945 write_item(id3
.title
);
1947 total_entry_count
++;
1950 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1952 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1953 int len
= strlen(str
)+1;
1956 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1957 char buf
[TAG_MAXLEN
+32];
1959 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1960 buf
[i
] = tolower(str
[i
]);
1963 crc32
= crc_32(buf
, i
, 0xffffffff);
1967 /* Check if the crc does not exist -> entry does not exist for sure. */
1968 for (i
= 0; i
< tempbufidx
; i
++)
1970 if (crcbuf
[-i
] != crc32
)
1973 if (!strcasecmp(str
, index
[i
].str
))
1975 if (id
< 0 || id
>= lookup_buffer_depth
)
1977 logf("lookup buf overf.: %d", id
);
1981 lookup
[id
] = &index
[i
];
1987 /* Insert to CRC buffer. */
1988 crcbuf
[-tempbufidx
] = crc32
;
1991 /* Insert it to the buffer. */
1992 tempbuf_left
-= len
;
1993 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1996 if (id
>= lookup_buffer_depth
)
1998 logf("lookup buf overf. #2: %d", id
);
2004 lookup
[id
] = &index
[tempbufidx
];
2005 index
[tempbufidx
].idlist
.id
= id
;
2008 index
[tempbufidx
].idlist
.id
= -1;
2010 index
[tempbufidx
].idlist
.next
= NULL
;
2011 index
[tempbufidx
].idx_id
= idx_id
;
2012 index
[tempbufidx
].seek
= -1;
2013 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
2014 memcpy(index
[tempbufidx
].str
, str
, len
);
2021 static int compare(const void *p1
, const void *p2
)
2025 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
2026 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
2028 if (strcmp(e1
->str
, UNTAGGED
) == 0)
2030 if (strcmp(e2
->str
, UNTAGGED
) == 0)
2034 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
2037 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
2040 static int tempbuf_sort(int fd
)
2042 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
2043 struct tagfile_entry fe
;
2047 /* Generate reverse lookup entries. */
2048 for (i
= 0; i
< lookup_buffer_depth
; i
++)
2050 struct tempbuf_id_list
*idlist
;
2055 if (lookup
[i
]->idlist
.id
== i
)
2058 idlist
= &lookup
[i
]->idlist
;
2059 while (idlist
->next
!= NULL
)
2060 idlist
= idlist
->next
;
2062 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
2063 if (tempbuf_left
- 4 < 0)
2066 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2067 if (tempbuf_pos
& 0x03)
2069 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
2071 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2073 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
2075 idlist
= idlist
->next
;
2077 idlist
->next
= NULL
;
2082 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
2083 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
2085 for (i
= 0; i
< tempbufidx
; i
++)
2087 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
2089 /* Fix the lookup list. */
2090 while (idlist
!= NULL
)
2092 if (idlist
->id
>= 0)
2093 lookup
[idlist
->id
] = &index
[i
];
2094 idlist
= idlist
->next
;
2097 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
2098 length
= strlen(index
[i
].str
) + 1;
2099 fe
.tag_length
= length
;
2100 fe
.idx_id
= index
[i
].idx_id
;
2102 /* Check the chunk alignment. */
2103 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2104 % TAGFILE_ENTRY_CHUNK_LENGTH
)
2106 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
2107 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2108 % TAGFILE_ENTRY_CHUNK_LENGTH
);
2111 #ifdef TAGCACHE_STRICT_ALIGN
2112 /* Make sure the entry is long aligned. */
2113 if (index
[i
].seek
& 0x03)
2115 logf("tempbuf_sort: alignment error!");
2120 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2121 sizeof(struct tagfile_entry
))
2123 logf("tempbuf_sort: write error #1");
2127 if (write(fd
, index
[i
].str
, length
) != length
)
2129 logf("tempbuf_sort: write error #2");
2133 /* Write some padding. */
2134 if (fe
.tag_length
- length
> 0)
2135 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2141 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2143 if (id
< 0 || id
>= lookup_buffer_depth
)
2150 inline static int tempbuf_find_location(int id
)
2152 struct tempbuf_searchidx
*entry
;
2154 entry
= tempbuf_locate(id
);
2161 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2163 struct master_header tcmh
;
2164 struct index_entry idx
;
2167 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2169 int entries_processed
= 0;
2171 char buf
[TAG_MAXLEN
];
2173 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2175 logf("Building numeric indices...");
2176 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2178 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2181 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2183 if (masterfd_pos
== filesize(masterfd
))
2185 logf("we can't append!");
2190 while (entries_processed
< h
->entry_count
)
2192 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2194 /* Read in as many entries as possible. */
2195 for (i
= 0; i
< count
; i
++)
2197 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2200 /* Read in numeric data. */
2201 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2202 sizeof(struct temp_file_entry
))
2204 logf("read fail #1");
2209 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2212 * Read string data from the following tags:
2218 * A crc32 hash is calculated from the read data
2219 * and stored back to the data offset field kept in memory.
2221 #define tmpdb_read_string_tag(tag) \
2222 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2223 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2225 logf("read fail: buffer overflow"); \
2230 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2231 tfe->tag_length[tag]) \
2233 logf("read fail #2"); \
2238 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2239 lseek(tmpfd, datastart, SEEK_SET)
2241 tmpdb_read_string_tag(tag_filename
);
2242 tmpdb_read_string_tag(tag_artist
);
2243 tmpdb_read_string_tag(tag_album
);
2244 tmpdb_read_string_tag(tag_title
);
2246 /* Seek to the end of the string data. */
2247 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2250 /* Backup the master index position. */
2251 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2252 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2254 /* Check if we can resurrect some deleted runtime statistics data. */
2255 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2257 /* Read the index entry. */
2258 if (ecread_index_entry(masterfd
, &idx
)
2259 != sizeof(struct index_entry
))
2261 logf("read fail #3");
2267 * Skip unless the entry is marked as being deleted
2268 * or the data has already been resurrected.
2270 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2273 /* Now try to match the entry. */
2275 * To succesfully match a song, the following conditions
2278 * For numeric fields: tag_length
2279 * - Full identical match is required
2281 * If tag_filename matches, no further checking necessary.
2283 * For string hashes: tag_artist, tag_album, tag_title
2284 * - Two of these must match
2286 for (j
= 0; j
< count
; j
++)
2288 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2290 /* Try to match numeric fields first. */
2291 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2294 /* Now it's time to do the hash matching. */
2295 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2297 int match_count
= 0;
2299 /* No filename match, check if we can match two other tags. */
2300 #define tmpdb_match(tag) \
2301 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2304 tmpdb_match(tag_artist
);
2305 tmpdb_match(tag_album
);
2306 tmpdb_match(tag_title
);
2308 if (match_count
< 2)
2310 /* Still no match found, give up. */
2315 /* A match found, now copy & resurrect the statistical data. */
2316 #define tmpdb_copy_tag(tag) \
2317 tfe->tag_offset[tag] = idx.tag_seek[tag]
2319 tmpdb_copy_tag(tag_playcount
);
2320 tmpdb_copy_tag(tag_rating
);
2321 tmpdb_copy_tag(tag_playtime
);
2322 tmpdb_copy_tag(tag_lastplayed
);
2323 tmpdb_copy_tag(tag_commitid
);
2325 /* Avoid processing this entry again. */
2326 idx
.flag
|= FLAG_RESURRECTED
;
2328 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2329 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2331 logf("masterfd writeback fail #1");
2336 logf("Entry resurrected");
2341 /* Restore the master index position. */
2342 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2344 /* Commit the data to the index. */
2345 for (i
= 0; i
< count
; i
++)
2347 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2349 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2351 logf("read fail #3");
2356 for (j
= 0; j
< TAG_COUNT
; j
++)
2358 if (!TAGCACHE_IS_NUMERIC(j
))
2361 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2363 idx
.flag
= entrybuf
[i
].flag
;
2365 if (idx
.tag_seek
[tag_commitid
])
2367 /* Data has been resurrected. */
2368 idx
.flag
|= FLAG_DIRTYNUM
;
2370 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2372 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2373 idx
.flag
|= FLAG_DIRTYNUM
;
2376 /* Write back the updated index. */
2377 lseek(masterfd
, loc
, SEEK_SET
);
2378 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2386 entries_processed
+= count
;
2387 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2398 * == 0 temporary failure
2401 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2404 struct tagcache_header tch
;
2405 struct master_header tcmh
;
2406 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2408 char buf
[TAG_MAXLEN
+32], path
[MAX_PATH
];
2410 int fd
= -1, masterfd
;
2415 logf("Building index: %d", index_type
);
2417 /* Check the number of entries we need to allocate ram for. */
2418 commit_entry_count
= h
->entry_count
+ 1;
2420 masterfd
= open_master_fd(&tcmh
, false);
2423 commit_entry_count
+= tcmh
.tch
.entry_count
;
2427 remove_files(); /* Just to be sure we are clean. */
2429 /* Open the index file, which contains the tag names. */
2430 fd
= open_tag_fd(&tch
, index_type
, true);
2433 logf("tch.datasize=%ld", tch
.datasize
);
2434 lookup_buffer_depth
= 1 +
2435 /* First part */ commit_entry_count
+
2436 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2440 lookup_buffer_depth
= 1 +
2441 /* First part */ commit_entry_count
+
2442 /* Second part */ 0;
2445 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2446 logf("commit_entry_count=%ld", commit_entry_count
);
2448 /* Allocate buffer for all index entries from both old and new
2451 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2453 /* Allocate lookup buffer. The first portion of commit_entry_count
2454 * contains the new tags in the temporary file and the second
2455 * part for locating entries already in the db.
2458 * +---------+---------------------------+
2459 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2460 * +---------+---------------------------+
2462 * Old tags are inserted to a temporary buffer with position:
2463 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2464 * And new tags with index:
2465 * tempbuf_insert(idx, ...);
2467 * The buffer is sorted and written into tag file:
2468 * tempbuf_sort(...);
2469 * leaving master index locations messed up.
2471 * That is fixed using the lookup buffer for old tags:
2472 * new_seek = tempbuf_find_location(old_seek, ...);
2474 * new_seek = tempbuf_find_location(idx);
2476 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2477 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2478 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2480 /* And calculate the remaining data space used mainly for storing
2481 * tag data (strings). */
2482 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2483 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2485 logf("Buffer way too small!");
2492 * If tag file contains unique tags (sorted index), we will load
2493 * it entirely into memory so we can resort it later for use with
2496 if (TAGCACHE_IS_SORTED(index_type
))
2498 logf("loading tags...");
2499 for (i
= 0; i
< tch
.entry_count
; i
++)
2501 struct tagfile_entry entry
;
2502 int loc
= lseek(fd
, 0, SEEK_CUR
);
2505 if (ecread_tagfile_entry(fd
, &entry
) != sizeof(struct tagfile_entry
))
2507 logf("read error #7");
2512 if (entry
.tag_length
>= (int)sizeof(buf
))
2514 logf("too long tag #3");
2519 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2521 logf("read error #8");
2526 /* Skip deleted entries. */
2531 * Save the tag and tag id in the memory buffer. Tag id
2532 * is saved so we can later reindex the master lookup
2533 * table when the index gets resorted.
2535 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2536 + commit_entry_count
, entry
.idx_id
,
2537 TAGCACHE_IS_UNIQUE(index_type
));
2548 tempbufidx
= tch
.entry_count
;
2553 * Creating new index file to store the tags. No need to preload
2554 * anything whether the index type is sorted or not.
2556 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2557 file
= get_user_file_path(buf
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
2558 fd
= open(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2561 logf("%s open fail", buf
);
2565 tch
.magic
= TAGCACHE_MAGIC
;
2566 tch
.entry_count
= 0;
2569 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2570 != sizeof(struct tagcache_header
))
2572 logf("header write failed");
2578 file
= get_user_file_path(TAGCACHE_FILE_MASTER
,
2581 /* Loading the tag lookup file as "master file". */
2582 logf("Loading index file");
2583 masterfd
= open(file
, O_RDWR
);
2587 logf("Creating new DB");
2588 masterfd
= open(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2592 logf("Failure to create index file (%s)", file
);
2597 /* Write the header (write real values later). */
2598 memset(&tcmh
, 0, sizeof(struct master_header
));
2600 tcmh
.tch
.entry_count
= 0;
2601 tcmh
.tch
.datasize
= 0;
2603 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2605 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2610 * Master file already exists so we need to process the current
2615 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2616 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2618 logf("header error");
2625 * If we reach end of the master file, we need to expand it to
2626 * hold new tags. If the current index is not sorted, we can
2627 * simply append new data to end of the file.
2628 * However, if the index is sorted, we need to update all tag
2629 * pointers in the master file for the current index.
2631 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2633 if (masterfd_pos
== filesize(masterfd
))
2635 logf("appending...");
2641 * Load new unique tags in memory to be sorted later and added
2642 * to the master lookup file.
2644 if (TAGCACHE_IS_SORTED(index_type
))
2646 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2647 /* h is the header of the temporary file containing new tags. */
2648 logf("inserting new tags...");
2649 for (i
= 0; i
< h
->entry_count
; i
++)
2651 struct temp_file_entry entry
;
2653 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2654 sizeof(struct temp_file_entry
))
2656 logf("read fail #3");
2662 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2664 logf("too long entry!");
2669 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2670 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2671 entry
.tag_length
[index_type
])
2673 logf("read fail #4");
2678 if (TAGCACHE_IS_UNIQUE(index_type
))
2679 error
= !tempbuf_insert(buf
, i
, -1, true);
2681 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2685 logf("insert error");
2690 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2691 entry
.tag_length
[index_type
], SEEK_CUR
);
2696 /* Sort the buffer data and write it to the index file. */
2697 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2699 * We need to truncate the index file now. There can be junk left
2700 * at the end of file (however, we _should_ always follow the
2701 * entry_count and don't crash with that).
2703 ftruncate(fd
, lseek(fd
, 0, SEEK_CUR
));
2705 i
= tempbuf_sort(fd
);
2708 logf("sorted %d tags", i
);
2711 * Now update all indexes in the master lookup file.
2713 logf("updating indices...");
2714 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2715 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2718 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2720 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2722 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2723 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2725 logf("read fail #5");
2729 lseek(masterfd
, loc
, SEEK_SET
);
2731 for (j
= 0; j
< idxbuf_pos
; j
++)
2733 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2735 /* We can just ignore deleted entries. */
2736 // idxbuf[j].tag_seek[index_type] = 0;
2740 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2741 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2742 + commit_entry_count
);
2744 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2746 logf("update error: %ld/%d/%ld",
2747 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2755 /* Write back the updated index. */
2756 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2757 index_entry_ec
, tc_stat
.econ
) !=
2758 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2769 * Walk through the temporary file containing the new tags.
2771 // build_normal_index(h, tmpfd, masterfd, idx);
2772 logf("updating new indices...");
2773 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2774 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2775 lseek(fd
, 0, SEEK_END
);
2776 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2780 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2783 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2787 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2789 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2790 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2792 logf("read fail #6");
2796 lseek(masterfd
, loc
, SEEK_SET
);
2799 /* Read entry headers. */
2800 for (j
= 0; j
< idxbuf_pos
; j
++)
2802 if (!TAGCACHE_IS_SORTED(index_type
))
2804 struct temp_file_entry entry
;
2805 struct tagfile_entry fe
;
2807 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2808 sizeof(struct temp_file_entry
))
2810 logf("read fail #7");
2816 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2818 logf("too long entry!");
2819 logf("length=%d", entry
.tag_length
[index_type
]);
2820 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2825 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2826 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2827 entry
.tag_length
[index_type
])
2829 logf("read fail #8");
2830 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2831 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2836 /* Write to index file. */
2837 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2838 fe
.tag_length
= entry
.tag_length
[index_type
];
2839 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2840 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2841 write(fd
, buf
, fe
.tag_length
);
2845 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2846 entry
.tag_length
[index_type
], SEEK_CUR
);
2850 /* Locate the correct entry from the sorted array. */
2851 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2852 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2854 logf("entry not found (%d)", j
);
2862 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2863 index_entry_ec
, tc_stat
.econ
) !=
2864 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2866 logf("tagcache: write fail #4");
2875 /* Finally write the header. */
2876 tch
.magic
= TAGCACHE_MAGIC
;
2877 tch
.entry_count
= tempbufidx
;
2878 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2879 lseek(fd
, 0, SEEK_SET
);
2880 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2882 if (index_type
!= tag_filename
)
2883 h
->datasize
+= tch
.datasize
;
2884 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2896 static bool commit(void)
2898 struct tagcache_header tch
;
2899 struct master_header tcmh
;
2900 char path
[MAX_PATH
];
2905 #ifdef HAVE_DIRCACHE
2906 bool dircache_buffer_stolen
= false;
2908 bool local_allocation
= false;
2910 logf("committing tagcache");
2915 file
= get_user_file_path(TAGCACHE_FILE_TEMP
,
2916 IS_FILE
|NEED_WRITE
, path
, sizeof(path
));
2918 tmpfd
= open(file
, O_RDONLY
);
2921 logf("nothing to commit");
2926 /* Load the header. */
2927 len
= sizeof(struct tagcache_header
);
2928 rc
= read(tmpfd
, &tch
, len
);
2930 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2932 logf("incorrect tmpheader");
2938 if (tch
.entry_count
== 0)
2940 logf("nothing to commit");
2946 /* Fully initialize existing headers (if any) before going further. */
2947 tc_stat
.ready
= check_all_headers();
2949 #ifdef HAVE_EEPROM_SETTINGS
2950 remove(get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
2951 path
, sizeof(path
)));
2954 /* At first be sure to unload the ramcache! */
2955 #ifdef HAVE_TC_RAMCACHE
2956 tc_stat
.ramcache
= false;
2961 /* Try to steal every buffer we can :) */
2962 if (tempbuf_size
== 0)
2963 local_allocation
= true;
2965 #ifdef HAVE_DIRCACHE
2966 if (tempbuf_size
== 0)
2968 /* Try to steal the dircache buffer. */
2969 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2970 tempbuf_size
&= ~0x03;
2972 if (tempbuf_size
> 0)
2974 dircache_buffer_stolen
= true;
2979 #ifdef HAVE_TC_RAMCACHE
2980 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2982 tempbuf
= (char *)(hdr
+ 1);
2983 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2984 tempbuf_size
&= ~0x03;
2988 /* And finally fail if there are no buffers available. */
2989 if (tempbuf_size
== 0)
2991 logf("delaying commit until next boot");
2992 tc_stat
.commit_delayed
= true;
2998 logf("commit %ld entries...", tch
.entry_count
);
3000 /* Mark DB dirty so it will stay disabled if commit fails. */
3001 current_tcmh
.dirty
= true;
3002 update_master_header();
3004 /* Now create the index files. */
3005 tc_stat
.commit_step
= 0;
3007 tc_stat
.commit_delayed
= false;
3009 for (i
= 0; i
< TAG_COUNT
; i
++)
3013 if (TAGCACHE_IS_NUMERIC(i
))
3016 tc_stat
.commit_step
++;
3017 ret
= build_index(i
, &tch
, tmpfd
);
3021 logf("tagcache failed init");
3023 tc_stat
.commit_delayed
= true;
3025 tc_stat
.commit_step
= 0;
3031 if (!build_numeric_indices(&tch
, tmpfd
))
3033 logf("Failure to commit numeric indices");
3035 tc_stat
.commit_step
= 0;
3043 tc_stat
.commit_step
= 0;
3045 /* Update the master index headers. */
3046 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
3052 tcmh
.tch
.entry_count
+= tch
.entry_count
;
3053 tcmh
.tch
.datasize
= sizeof(struct master_header
)
3054 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
3059 lseek(masterfd
, 0, SEEK_SET
);
3060 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
3063 logf("tagcache committed");
3064 tc_stat
.ready
= check_all_headers();
3065 tc_stat
.readyvalid
= true;
3067 if (local_allocation
)
3073 #ifdef HAVE_DIRCACHE
3074 /* Rebuild the dircache, if we stole the buffer. */
3075 if (dircache_buffer_stolen
)
3079 #ifdef HAVE_TC_RAMCACHE
3080 /* Reload tagcache. */
3081 if (tc_stat
.ramcache_allocated
> 0)
3082 tagcache_start_scan();
3090 static void allocate_tempbuf(void)
3092 /* Yeah, malloc would be really nice now :) */
3094 tempbuf_size
= 32*1024*1024;
3095 tempbuf
= malloc(tempbuf_size
);
3097 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
3098 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
3099 audiobuf
+= tempbuf_size
;
3103 static void free_tempbuf(void)
3105 if (tempbuf_size
== 0)
3111 audiobuf
-= tempbuf_size
;
3119 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
3121 struct index_entry idx
;
3126 if (!TAGCACHE_IS_NUMERIC(tag
))
3129 if (!get_index(masterfd
, idx_id
, &idx
, false))
3132 idx
.tag_seek
[tag
] = data
;
3133 idx
.flag
|= FLAG_DIRTYNUM
;
3135 return write_index(masterfd
, idx_id
, &idx
);
3139 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3142 struct master_header myhdr
;
3144 if (tcs
->masterfd
< 0)
3146 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3150 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3154 static bool command_queue_is_full(void)
3158 next
= command_queue_widx
+ 1;
3159 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3162 return (next
== command_queue_ridx
);
3165 static void command_queue_sync_callback(void *data
)
3168 struct master_header myhdr
;
3171 mutex_lock(&command_queue_mutex
);
3173 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3176 while (command_queue_ridx
!= command_queue_widx
)
3178 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3180 switch (ce
->command
)
3182 case CMD_UPDATE_MASTER_HEADER
:
3185 update_master_header();
3187 /* Re-open the masterfd. */
3188 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3193 case CMD_UPDATE_NUMERIC
:
3195 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3200 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3201 command_queue_ridx
= 0;
3206 tc_stat
.queue_length
= 0;
3207 mutex_unlock(&command_queue_mutex
);
3210 static void run_command_queue(bool force
)
3212 if (COMMAND_QUEUE_IS_EMPTY
)
3215 if (force
|| command_queue_is_full())
3216 command_queue_sync_callback(NULL
);
3218 register_storage_idle_func(command_queue_sync_callback
);
3221 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3227 mutex_lock(&command_queue_mutex
);
3228 next
= command_queue_widx
+ 1;
3229 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3232 /* Make sure queue is not full. */
3233 if (next
!= command_queue_ridx
)
3235 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3238 ce
->idx_id
= idx_id
;
3242 command_queue_widx
= next
;
3244 tc_stat
.queue_length
++;
3246 mutex_unlock(&command_queue_mutex
);
3250 /* Queue is full, try again later... */
3251 mutex_unlock(&command_queue_mutex
);
3256 long tagcache_increase_serial(void)
3266 old
= current_tcmh
.serial
++;
3267 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3272 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3274 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3276 #endif /* !__PCTOOL__ */
3278 long tagcache_get_serial(void)
3280 return current_tcmh
.serial
;
3283 long tagcache_get_commitid(void)
3285 return current_tcmh
.commitid
;
3288 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3293 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3294 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3296 if (*datastr
== '\0')
3299 if (*datastr
== '"' || *datastr
== '\\')
3302 buf
[i
] = *(datastr
++);
3305 strcpy(&buf
[i
], "\" ");
3307 write(fd
, buf
, i
+ 2);
3314 static bool read_tag(char *dest
, long size
,
3315 const char *src
, const char *tagstr
)
3318 char current_tag
[32];
3320 while (*src
!= '\0')
3322 /* Skip all whitespace */
3330 /* Read in tag name */
3331 while (*src
!= '=' && *src
!= ' ')
3333 current_tag
[pos
] = *src
;
3337 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3340 current_tag
[pos
] = '\0';
3342 /* Read in tag data */
3344 /* Find the start. */
3345 while (*src
!= '"' && *src
!= '\0')
3348 if (*src
== '\0' || *(++src
) == '\0')
3351 /* Read the data. */
3352 for (pos
= 0; pos
< size
; pos
++)
3359 dest
[pos
] = *(src
+1);
3379 if (!strcasecmp(tagstr
, current_tag
))
3386 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3388 struct index_entry idx
;
3389 char tag_data
[TAG_MAXLEN
+32];
3391 long masterfd
= (long)parameters
;
3392 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3400 logf("%d/%s", line_n
, buf
);
3401 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3403 logf("filename missing");
3408 idx_id
= find_index(tag_data
);
3411 logf("entry not found");
3415 if (!get_index(masterfd
, idx_id
, &idx
, false))
3417 logf("failed to retrieve index entry");
3421 /* Stop if tag has already been modified. */
3422 if (idx
.flag
& FLAG_DIRTYNUM
)
3425 logf("import: %s", tag_data
);
3427 idx
.flag
|= FLAG_DIRTYNUM
;
3428 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3432 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3433 tagcache_tag_to_str(import_tags
[i
])))
3438 data
= atoi(tag_data
);
3442 idx
.tag_seek
[import_tags
[i
]] = data
;
3444 if (import_tags
[i
] == tag_lastplayed
&& data
>= current_tcmh
.serial
)
3445 current_tcmh
.serial
= data
+ 1;
3446 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3447 current_tcmh
.commitid
= data
+ 1;
3450 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3453 bool tagcache_import_changelog(void)
3455 struct master_header myhdr
;
3456 struct tagcache_header tch
;
3459 char buf
[MAX(MAX_PATH
, 2048)];
3468 file
= get_user_file_path(TAGCACHE_FILE_CHANGELOG
,
3469 IS_FILE
|NEED_WRITE
, buf
, sizeof(buf
));
3470 clfd
= open(file
, O_RDONLY
);
3473 logf("failure to open changelog");
3477 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3485 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3487 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3488 parse_changelog_line
);
3493 if (filenametag_fd
>= 0)
3495 close(filenametag_fd
);
3496 filenametag_fd
= -1;
3501 update_master_header();
3506 #endif /* !__PCTOOL__ */
3508 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3510 struct master_header myhdr
;
3511 struct index_entry idx
;
3513 char buf
[MAX(TAG_MAXLEN
+32, MAX_PATH
)];
3521 if (!tagcache_search(tcs
, tag_filename
))
3524 /* Initialize the changelog */
3525 file
= get_user_file_path(TAGCACHE_FILE_CHANGELOG
, IS_FILE
| NEED_WRITE
,
3527 clfd
= open(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3530 logf("failure to open changelog");
3534 if (tcs
->masterfd
< 0)
3536 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3541 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3542 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3545 write(clfd
, "## Changelog version 1\n", 23);
3547 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3549 if (ecread_index_entry(tcs
->masterfd
, &idx
) != sizeof(struct index_entry
))
3551 logf("read error #9");
3552 tagcache_search_finish(tcs
);
3557 /* Skip until the entry found has been modified. */
3558 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3561 /* Skip deleted entries too. */
3562 if (idx
.flag
& FLAG_DELETED
)
3565 /* Now retrieve all tags. */
3566 for (j
= 0; j
< TAG_COUNT
; j
++)
3568 if (TAGCACHE_IS_NUMERIC(j
))
3570 snprintf(temp
, sizeof temp
, "%d", (int)idx
.tag_seek
[j
]);
3571 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3576 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3577 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3580 write(clfd
, "\n", 1);
3586 tagcache_search_finish(tcs
);
3591 static bool delete_entry(long idx_id
)
3596 struct index_entry idx
, myidx
;
3597 struct master_header myhdr
;
3598 char buf
[TAG_MAXLEN
+32];
3599 int in_use
[TAG_COUNT
];
3601 logf("delete_entry(): %ld", idx_id
);
3603 #ifdef HAVE_TC_RAMCACHE
3604 /* At first mark the entry removed from ram cache. */
3605 if (tc_stat
.ramcache
)
3606 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3609 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3612 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3613 if (ecread_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3615 logf("delete_entry(): read error");
3619 if (myidx
.flag
& FLAG_DELETED
)
3621 logf("delete_entry(): already deleted!");
3625 myidx
.flag
|= FLAG_DELETED
;
3626 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3627 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3629 logf("delete_entry(): write_error #1");
3633 /* Now check which tags are no longer in use (if any) */
3634 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3637 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3638 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3640 struct index_entry
*idxp
;
3642 #ifdef HAVE_TC_RAMCACHE
3643 /* Use RAM DB if available for greater speed */
3644 if (tc_stat
.ramcache
)
3645 idxp
= &hdr
->indices
[i
];
3649 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
3651 logf("delete_entry(): read error #2");
3657 if (idxp
->flag
& FLAG_DELETED
)
3660 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3662 if (TAGCACHE_IS_NUMERIC(tag
))
3665 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3670 /* Now delete all tags no longer in use. */
3671 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3673 struct tagcache_header tch
;
3674 int oldseek
= myidx
.tag_seek
[tag
];
3676 if (TAGCACHE_IS_NUMERIC(tag
))
3680 * Replace tag seek with a hash value of the field string data.
3681 * That way runtime statistics of moved or altered files can be
3684 #ifdef HAVE_TC_RAMCACHE
3685 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3687 struct tagfile_entry
*tfe
;
3688 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3690 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3691 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3692 myidx
.tag_seek
[tag
] = *seek
;
3697 struct tagfile_entry tfe
;
3699 /* Open the index file, which contains the tag names. */
3700 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3703 /* Skip the header block */
3704 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3705 if (ecread_tagfile_entry(fd
, &tfe
) != sizeof(struct tagfile_entry
))
3707 logf("delete_entry(): read error #3");
3711 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3713 logf("delete_entry(): read error #4");
3717 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3722 logf("in use: %d/%d", tag
, in_use
[tag
]);
3731 #ifdef HAVE_TC_RAMCACHE
3732 /* Delete from ram. */
3733 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3735 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3736 tagentry
->tag_data
[0] = '\0';
3740 /* Open the index file, which contains the tag names. */
3743 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3747 /* Skip the header block */
3748 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3750 /* Debug, print 10 first characters of the tag
3753 logf("TAG:%s", buf);
3754 lseek(fd, -10, SEEK_CUR);
3757 /* Write first data byte in tag as \0 */
3760 /* Now tag data has been removed */
3765 /* Write index entry back into master index. */
3766 lseek(masterfd
, sizeof(struct master_header
) +
3767 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3768 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3770 logf("delete_entry(): write_error #2");
3789 * Returns true if there is an event waiting in the queue
3790 * that requires the current operation to be aborted.
3792 static bool check_event_queue(void)
3794 struct queue_event ev
;
3796 if(!queue_peek(&tagcache_queue
, &ev
))
3803 case SYS_USB_CONNECTED
:
3811 #ifdef HAVE_TC_RAMCACHE
3812 static bool allocate_tagcache(void)
3814 struct master_header tcmh
;
3817 /* Load the header. */
3818 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3827 * Now calculate the required cache size plus
3828 * some extra space for alignment fixes.
3830 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3831 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3832 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3833 memset(hdr
, 0, sizeof(struct ramcache_header
));
3834 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3835 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3836 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3841 # ifdef HAVE_EEPROM_SETTINGS
3842 static bool tagcache_dumpload(void)
3844 struct statefile_header shdr
;
3845 char path
[MAX_PATH
];
3851 file
= get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
3852 path
, sizeof(path
));
3853 fd
= open(file
, O_RDONLY
);
3856 logf("no tagcache statedump");
3860 /* Check the statefile memory placement */
3861 hdr
= buffer_alloc(0);
3862 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3863 if (rc
!= sizeof(struct statefile_header
)
3864 /* || (long)hdr != (long)shdr.hdr */)
3866 logf("incorrect statefile");
3872 offpos
= (long)hdr
- (long)shdr
.hdr
;
3874 /* Lets allocate real memory and load it */
3875 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3876 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3879 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3881 logf("read failure!");
3886 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3888 /* Now fix the pointers */
3889 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3890 for (i
= 0; i
< TAG_COUNT
; i
++)
3891 hdr
->tags
[i
] += offpos
;
3896 static bool tagcache_dumpsave(void)
3898 struct statefile_header shdr
;
3899 char path
[MAX_PATH
];
3903 if (!tc_stat
.ramcache
)
3906 file
= get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
3907 path
, sizeof(path
));
3908 fd
= open(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3911 logf("failed to create a statedump");
3915 /* Create the header */
3917 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3918 write(fd
, &shdr
, sizeof(struct statefile_header
));
3920 /* And dump the data too */
3921 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3928 static bool load_tagcache(void)
3930 struct tagcache_header
*tch
;
3931 long bytesleft
= tc_stat
.ramcache_allocated
;
3932 struct index_entry
*idx
;
3934 char *p
, path
[MAX_PATH
];
3938 # ifdef HAVE_DIRCACHE
3939 while (dircache_is_initializing())
3942 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3945 logf("loading tagcache to ram...");
3947 file
= get_user_file_path(TAGCACHE_FILE_MASTER
,
3949 path
, sizeof(path
));
3950 fd
= open(file
, O_RDONLY
);
3953 logf("tagcache open failed");
3957 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3958 != sizeof(struct master_header
)
3959 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3961 logf("incorrect header");
3967 /* Load the master index table. */
3968 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3970 rc
= ecread_index_entry(fd
, idx
);
3971 if (rc
!= sizeof(struct index_entry
))
3973 logf("read error #10");
3978 bytesleft
-= sizeof(struct index_entry
);
3979 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3981 logf("too big tagcache.");
3991 /* Load the tags. */
3993 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3995 struct tagfile_entry
*fe
;
3996 char buf
[TAG_MAXLEN
+32];
3998 if (TAGCACHE_IS_NUMERIC(tag
))
4001 //p = ((void *)p+1);
4002 p
= (char *)((long)p
& ~0x03) + 0x04;
4005 /* Check the header. */
4006 tch
= (struct tagcache_header
*)p
;
4007 p
+= sizeof(struct tagcache_header
);
4009 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
4012 for (hdr
->entry_count
[tag
] = 0;
4013 hdr
->entry_count
[tag
] < tch
->entry_count
;
4014 hdr
->entry_count
[tag
]++)
4018 if (do_timed_yield())
4020 /* Abort if we got a critical event in queue */
4021 if (check_event_queue())
4025 fe
= (struct tagfile_entry
*)p
;
4026 pos
= lseek(fd
, 0, SEEK_CUR
);
4027 rc
= ecread_tagfile_entry(fd
, fe
);
4028 if (rc
!= sizeof(struct tagfile_entry
))
4030 /* End of lookup table. */
4031 logf("read error #11");
4036 /* We have a special handling for the filename tags. */
4037 if (tag
== tag_filename
)
4039 # ifdef HAVE_DIRCACHE
4040 const struct dircache_entry
*dc
;
4043 // FIXME: This is wrong!
4044 // idx = &hdr->indices[hdr->entry_count[i]];
4045 idx
= &hdr
->indices
[fe
->idx_id
];
4047 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
4051 logf("TAG:%s", buf
);
4052 logf("too long filename");
4057 rc
= read(fd
, buf
, fe
->tag_length
);
4058 if (rc
!= fe
->tag_length
)
4060 logf("read error #12");
4065 /* Check if the entry has already been removed */
4066 if (idx
->flag
& FLAG_DELETED
)
4069 /* This flag must not be used yet. */
4070 if (idx
->flag
& FLAG_DIRCACHE
)
4072 logf("internal error!");
4077 if (idx
->tag_seek
[tag
] != pos
)
4079 logf("corrupt data structures!");
4084 # ifdef HAVE_DIRCACHE
4085 if (dircache_is_enabled())
4087 dc
= dircache_get_entry_ptr(buf
);
4090 logf("Entry no longer valid.");
4092 if (global_settings
.tagcache_autoupdate
)
4093 delete_entry(fe
->idx_id
);
4097 idx
->flag
|= FLAG_DIRCACHE
;
4098 idx
->tag_seek
[tag_filename
] = (long)dc
;
4103 /* This will be very slow unless dircache is enabled
4104 or target is flash based, but do it anyway for
4106 /* Check if entry has been removed. */
4107 if (global_settings
.tagcache_autoupdate
)
4109 if (!file_exists(buf
))
4111 logf("Entry no longer valid.");
4113 delete_entry(fe
->idx_id
);
4122 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
4125 logf("too big tagcache #2");
4126 logf("tl: %ld", fe
->tag_length
);
4127 logf("bl: %ld", bytesleft
);
4133 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
4136 if (rc
!= fe
->tag_length
)
4138 logf("read error #13");
4139 logf("rc=0x%04x", rc
); // 0x431
4140 logf("len=0x%04lx", fe
->tag_length
); // 0x4000
4141 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
4142 logf("tag=0x%02x", tag
); // 0x00
4150 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4151 logf("tagcache loaded into ram!");
4155 #endif /* HAVE_TC_RAMCACHE */
4157 static bool check_deleted_files(void)
4160 char buf
[TAG_MAXLEN
+32], path
[MAX_PATH
];
4162 struct tagfile_entry tfe
;
4164 logf("reverse scan...");
4165 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4166 file
= get_user_file_path(buf
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
4167 fd
= open(file
, O_RDONLY
);
4171 logf("%s open fail", buf
);
4175 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4176 while (ecread_tagfile_entry(fd
, &tfe
) == sizeof(struct tagfile_entry
)
4178 && !check_event_queue()
4182 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4184 logf("too long tag");
4189 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4191 logf("read error #14");
4196 /* Check if the file has already deleted from the db. */
4200 /* Now check if the file exists. */
4201 if (!file_exists(buf
))
4203 logf("Entry no longer valid.");
4204 logf("-> %s / %ld", buf
, tfe
.tag_length
);
4205 delete_entry(tfe
.idx_id
);
4217 /* Note that this function must not be inlined, otherwise the whole point
4218 * of having the code in a separate function is lost.
4220 static void __attribute__ ((noinline
)) check_ignore(const char *dirname
,
4221 int *ignore
, int *unignore
)
4223 char newpath
[MAX_PATH
];
4225 /* check for a database.ignore file */
4226 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4227 *ignore
= file_exists(newpath
);
4228 /* check for a database.unignore file */
4229 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4230 *unignore
= file_exists(newpath
);
4234 static bool check_dir(const char *dirname
, int add_files
)
4238 int success
= false;
4239 int ignore
, unignore
;
4241 dir
= opendir(dirname
);
4244 logf("tagcache: opendir(%s) failed", dirname
);
4248 /* check for a database.ignore and database.unignore */
4249 check_ignore(dirname
, &ignore
, &unignore
);
4251 /* don't do anything if both ignore and unignore are there */
4252 if (ignore
!= unignore
)
4253 add_files
= unignore
;
4255 /* Recursively scan the dir. */
4259 while (!check_event_queue())
4262 struct dirent
*entry
;
4264 entry
= readdir(dir
);
4272 struct dirinfo info
= dir_get_info(dir
, entry
);
4274 if (!strcmp((char *)entry
->d_name
, ".") ||
4275 !strcmp((char *)entry
->d_name
, ".."))
4280 len
= strlen(curpath
);
4281 snprintf(&curpath
[len
], sizeof(curpath
) - len
, "/%s",
4284 processed_dir_count
++;
4285 if (info
.attribute
& ATTR_DIRECTORY
)
4286 check_dir(curpath
, add_files
);
4289 tc_stat
.curentry
= curpath
;
4291 /* Add a new entry to the temporary db file. */
4292 add_tagcache(curpath
, (info
.wrtdate
<< 16) | info
.wrttime
4293 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4294 , dir
->internal_entry
4298 /* Wait until current path for debug screen is read and unset. */
4299 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4302 tc_stat
.curentry
= NULL
;
4305 curpath
[len
] = '\0';
4313 void tagcache_screensync_event(void)
4315 tc_stat
.curentry
= NULL
;
4318 void tagcache_screensync_enable(bool state
)
4320 tc_stat
.syncscreen
= state
;
4323 void tagcache_build(const char *path
)
4325 struct tagcache_header header
;
4332 total_entry_count
= 0;
4333 processed_dir_count
= 0;
4335 #ifdef HAVE_DIRCACHE
4336 while (dircache_is_initializing())
4340 logf("updating tagcache");
4342 file
= get_user_file_path(TAGCACHE_FILE_TEMP
,
4343 IS_FILE
|NEED_WRITE
, buf
, sizeof(buf
));
4346 if (file_exists(file
))
4348 logf("skipping, cache already waiting for commit");
4352 cachefd
= open(file
, O_RDWR
| O_CREAT
| O_TRUNC
, 0666);
4355 logf("master file open failed: %s", file
);
4359 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4363 logf("Scanning files...");
4364 /* Scan for new files. */
4365 memset(&header
, 0, sizeof(struct tagcache_header
));
4366 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4368 if (strcmp("/", path
) != 0)
4369 strcpy(curpath
, path
);
4370 ret
= check_dir(path
, true);
4372 /* Write the header. */
4373 header
.magic
= TAGCACHE_MAGIC
;
4374 header
.datasize
= data_size
;
4375 header
.entry_count
= total_entry_count
;
4376 lseek(cachefd
, 0, SEEK_SET
);
4377 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4380 if (filenametag_fd
>= 0)
4382 close(filenametag_fd
);
4383 filenametag_fd
= -1;
4393 /* Commit changes to the database. */
4400 logf("tagcache built!");
4406 #ifdef HAVE_TC_RAMCACHE
4409 /* Import runtime statistics if we just initialized the db. */
4410 if (hdr
->h
.serial
== 0)
4411 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4418 #ifdef HAVE_TC_RAMCACHE
4419 static void load_ramcache(void)
4426 /* At first we should load the cache (if exists). */
4427 tc_stat
.ramcache
= load_tagcache();
4429 if (!tc_stat
.ramcache
)
4431 /* If loading failed, it must indicate some problem with the db
4432 * so disable it entirely to prevent further issues. */
4433 tc_stat
.ready
= false;
4440 void tagcache_unload_ramcache(void)
4442 tc_stat
.ramcache
= false;
4443 /* Just to make sure there is no statefile present. */
4446 char path
[MAX_PATH
];
4447 remove(get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
4448 path
, sizeof(path
)));
4454 static void tagcache_thread(void)
4456 struct queue_event ev
;
4457 bool check_done
= false;
4458 char path
[MAX_PATH
];
4460 /* If the previous cache build/update was interrupted, commit
4461 * the changes first in foreground. */
4467 #ifdef HAVE_TC_RAMCACHE
4468 # ifdef HAVE_EEPROM_SETTINGS
4469 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
4470 && global_settings
.tagcache_ram
)
4472 check_done
= tagcache_dumpload();
4475 remove(get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
4476 path
, sizeof(path
)));
4479 /* Allocate space for the tagcache if found on disk. */
4480 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4481 allocate_tagcache();
4485 tc_stat
.initialized
= true;
4487 /* Don't delay bootup with the header check but do it on background. */
4491 tc_stat
.ready
= check_all_headers();
4492 tc_stat
.readyvalid
= true;
4497 run_command_queue(false);
4499 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4503 case Q_IMPORT_CHANGELOG
:
4504 tagcache_import_changelog();
4509 remove(get_user_file_path(TAGCACHE_FILE_TEMP
,
4510 IS_FILE
|NEED_WRITE
, path
, sizeof(path
)));
4511 tagcache_build("/");
4515 tagcache_build("/");
4516 #ifdef HAVE_TC_RAMCACHE
4519 check_deleted_files();
4525 if (check_done
|| !tc_stat
.ready
)
4528 #ifdef HAVE_TC_RAMCACHE
4529 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4532 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4533 tagcache_build("/");
4537 if (global_settings
.tagcache_autoupdate
)
4539 tagcache_build("/");
4541 /* This will be very slow unless dircache is enabled
4542 or target is flash based, but do it anyway for
4544 check_deleted_files();
4547 logf("tagcache check done");
4558 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4559 case SYS_USB_CONNECTED
:
4560 logf("USB: TagCache");
4561 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4562 usb_wait_for_disconnect(&tagcache_queue
);
4569 bool tagcache_prepare_shutdown(void)
4571 if (tagcache_get_commit_step() > 0)
4574 tagcache_stop_scan();
4575 while (read_lock
|| write_lock
)
4581 void tagcache_shutdown(void)
4583 /* Flush the command queue. */
4584 run_command_queue(true);
4586 #ifdef HAVE_EEPROM_SETTINGS
4587 if (tc_stat
.ramcache
)
4588 tagcache_dumpsave();
4592 static int get_progress(void)
4594 int total_count
= -1;
4596 #ifdef HAVE_DIRCACHE
4597 if (dircache_is_enabled())
4599 total_count
= dircache_get_entry_count();
4603 #ifdef HAVE_TC_RAMCACHE
4605 if (hdr
&& tc_stat
.ramcache
)
4606 total_count
= hdr
->h
.tch
.entry_count
;
4610 if (total_count
< 0)
4613 return processed_dir_count
* 100 / total_count
;
4616 struct tagcache_stat
* tagcache_get_stat(void)
4618 tc_stat
.progress
= get_progress();
4619 tc_stat
.processed_entries
= processed_dir_count
;
4624 void tagcache_start_scan(void)
4626 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4629 bool tagcache_update(void)
4634 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4638 bool tagcache_rebuild()
4640 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4644 void tagcache_stop_scan(void)
4646 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4649 #ifdef HAVE_TC_RAMCACHE
4650 bool tagcache_is_ramcache(void)
4652 return tc_stat
.ramcache
;
4656 #endif /* !__PCTOOL__ */
4659 void tagcache_init(void)
4661 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4662 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4663 filenametag_fd
= -1;
4664 write_lock
= read_lock
= 0;
4667 mutex_init(&command_queue_mutex
);
4668 queue_init(&tagcache_queue
, true);
4669 create_thread(tagcache_thread
, tagcache_stack
,
4670 sizeof(tagcache_stack
), 0, tagcache_thread_name
4671 IF_PRIO(, PRIORITY_BACKGROUND
)
4674 tc_stat
.initialized
= true;
4678 tc_stat
.ready
= check_all_headers();
4683 void tagcache_reverse_scan(void)
4685 logf("Checking for deleted files");
4686 check_deleted_files();
4690 bool tagcache_is_initialized(void)
4692 return tc_stat
.initialized
;
4694 bool tagcache_is_usable(void)
4696 return tc_stat
.initialized
&& tc_stat
.ready
;
4698 int tagcache_get_commit_step(void)
4700 return tc_stat
.commit_step
;
4702 int tagcache_get_max_commit_step(void)
4704 return (int)(SORTED_TAGS_COUNT
)+1;