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"
82 #include "eeprom_settings.h"
86 #define yield() do { } while(0)
87 #define sim_sleep(timeout) do { } while(0)
88 #define do_timed_yield() do { } while(0)
92 /* Tag Cache thread. */
93 static struct event_queue tagcache_queue
;
94 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
95 static const char tagcache_thread_name
[] = "tagcache";
98 #define UNTAGGED "<Untagged>"
100 /* Previous path when scanning directory tree recursively. */
101 static char curpath
[TAG_MAXLEN
+32];
103 /* Used when removing duplicates. */
104 static char *tempbuf
; /* Allocated when needed. */
105 static long tempbufidx
; /* Current location in buffer. */
106 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
107 static long tempbuf_left
; /* Buffer space left. */
108 static long tempbuf_pos
;
110 #define SORTED_TAGS_COUNT 8
111 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
112 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
113 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
114 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
115 /* Tags we want to get sorted (loaded to the tempbuf). */
116 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
117 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
118 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
120 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
121 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
122 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
123 (1LU << tag_albumartist) | (1LU << tag_grouping))
125 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
126 static const char *tags_str
[] = { "artist", "album", "genre", "title",
127 "filename", "composer", "comment", "albumartist", "grouping", "year",
128 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
129 "playtime", "lastplayed", "commitid", "mtime" };
131 /* Status information of the tagcache. */
132 static struct tagcache_stat tc_stat
;
134 /* Queue commands. */
135 enum tagcache_queue
{
142 /* Internal tagcache command queue. */
143 CMD_UPDATE_MASTER_HEADER
,
147 struct tagcache_command_entry
{
155 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
156 static volatile int command_queue_widx
= 0;
157 static volatile int command_queue_ridx
= 0;
158 static struct mutex command_queue_mutex
;
161 /* Tag database structures. */
163 /* Variable-length tag entry in tag files. */
164 struct tagfile_entry
{
165 int32_t tag_length
; /* Length of the data in bytes including '\0' */
166 int32_t idx_id
; /* Corresponding entry location in index file of not unique tags */
167 char tag_data
[0]; /* Begin of the tag data */
170 /* Fixed-size tag entry in master db index. */
172 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
173 int32_t flag
; /* Status flags */
176 /* Header is the same in every file. */
177 struct tagcache_header
{
178 int32_t magic
; /* Header version number */
179 int32_t datasize
; /* Data size in bytes */
180 int32_t entry_count
; /* Number of entries in this file */
183 struct master_header
{
184 struct tagcache_header tch
;
185 int32_t serial
; /* Increasing counting number */
186 int32_t commitid
; /* Number of commits so far */
190 /* For the endianess correction */
191 static const char *tagfile_entry_ec
= "ll";
193 Note: This should be (1 + TAG_COUNT) amount of l's.
195 static const char *index_entry_ec
= "lllllllllllllllllllll";
197 static const char *tagcache_header_ec
= "lll";
198 static const char *master_header_ec
= "llllll";
200 static struct master_header current_tcmh
;
202 #ifdef HAVE_TC_RAMCACHE
203 /* Header is created when loading database to ram. */
204 struct ramcache_header
{
205 struct master_header h
; /* Header from the master index */
206 struct index_entry
*indices
; /* Master index file content */
207 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
208 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
211 # ifdef HAVE_EEPROM_SETTINGS
212 struct statefile_header
{
213 struct ramcache_header
*hdr
;
214 struct tagcache_stat tc_stat
;
218 /* Pointer to allocated ramcache_header */
219 static struct ramcache_header
*hdr
;
223 * Full tag entries stored in a temporary file waiting
224 * for commit to the cache. */
225 struct temp_file_entry
{
226 long tag_offset
[TAG_COUNT
];
227 short tag_length
[TAG_COUNT
];
233 struct tempbuf_id_list
{
235 struct tempbuf_id_list
*next
;
238 struct tempbuf_searchidx
{
242 struct tempbuf_id_list idlist
;
245 /* Lookup buffer for fixing messed up index while after sorting. */
246 static long commit_entry_count
;
247 static long lookup_buffer_depth
;
248 static struct tempbuf_searchidx
**lookup
;
250 /* Used when building the temporary file. */
251 static int cachefd
= -1, filenametag_fd
;
252 static int total_entry_count
= 0;
253 static int data_size
= 0;
254 static int processed_dir_count
;
256 /* Thread safe locking */
257 static volatile int write_lock
;
258 static volatile int read_lock
;
260 static bool delete_entry(long idx_id
);
262 const char* tagcache_tag_to_str(int tag
)
264 return tags_str
[tag
];
267 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
268 static ssize_t
ecread_tagfile_entry(int fd
, struct tagfile_entry
*buf
)
270 return ecread(fd
, buf
, 1, tagfile_entry_ec
, tc_stat
.econ
);
273 static ssize_t
ecread_index_entry(int fd
, struct index_entry
*buf
)
275 return ecread(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
278 static ssize_t
ecwrite_index_entry(int fd
, struct index_entry
*buf
)
280 return ecwrite(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
285 * Returns true if specified flag is still present, i.e., dircache
286 * has not been reloaded.
288 static bool is_dircache_intact(void)
290 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
294 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
300 if (TAGCACHE_IS_NUMERIC(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
303 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
305 fd
= open(buf
, write
? O_RDWR
: O_RDONLY
);
308 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
309 tc_stat
.ready
= false;
313 /* Check the header. */
314 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
315 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
317 logf("header error");
318 tc_stat
.ready
= false;
326 static int open_master_fd(struct master_header
*hdr
, bool write
)
331 fd
= open(TAGCACHE_FILE_MASTER
, write
? O_RDWR
: O_RDONLY
);
334 logf("master file open failed for R/W");
335 tc_stat
.ready
= false;
339 tc_stat
.econ
= false;
341 /* Check the header. */
342 rc
= read(fd
, hdr
, sizeof(struct master_header
));
343 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
349 /* Trying to read again, this time with endianess correction enabled. */
350 lseek(fd
, 0, SEEK_SET
);
352 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
353 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
355 logf("header error");
356 tc_stat
.ready
= false;
367 static bool do_timed_yield(void)
369 /* Sorting can lock up for quite a while, so yield occasionally */
370 static long wakeup_tick
= 0;
371 if (TIME_AFTER(current_tick
, wakeup_tick
))
373 wakeup_tick
= current_tick
+ (HZ
/4);
381 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
382 static long find_entry_ram(const char *filename
,
383 const struct dircache_entry
*dc
)
385 static long last_pos
= 0;
388 /* Check if we tagcache is loaded into ram. */
389 if (!tc_stat
.ramcache
)
393 dc
= dircache_get_entry_ptr(filename
);
397 logf("tagcache: file not found.");
408 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
410 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
412 last_pos
= MAX(0, i
- 3);
429 static long find_entry_disk(const char *filename
, bool localfd
)
431 struct tagcache_header tch
;
432 static long last_pos
= -1;
433 long pos_history
[POS_HISTORY_COUNT
];
434 long pos_history_idx
= 0;
436 struct tagfile_entry tfe
;
438 char buf
[TAG_MAXLEN
+32];
446 if (fd
< 0 || localfd
)
449 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
456 lseek(fd
, last_pos
, SEEK_SET
);
458 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
462 pos
= lseek(fd
, 0, SEEK_CUR
);
463 for (i
= pos_history_idx
-1; i
>= 0; i
--)
464 pos_history
[i
+1] = pos_history
[i
];
465 pos_history
[0] = pos
;
467 if (ecread_tagfile_entry(fd
, &tfe
)
468 != sizeof(struct tagfile_entry
))
473 if (tfe
.tag_length
>= (long)sizeof(buf
))
475 logf("too long tag #1");
483 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
485 logf("read error #2");
493 if (!strcasecmp(filename
, buf
))
495 last_pos
= pos_history
[pos_history_idx
];
500 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
514 if (fd
!= filenametag_fd
|| localfd
)
519 if (fd
!= filenametag_fd
|| localfd
)
525 static int find_index(const char *filename
)
529 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
530 if (tc_stat
.ramcache
&& is_dircache_intact())
531 idx_id
= find_entry_ram(filename
, NULL
);
535 idx_id
= find_entry_disk(filename
, true);
540 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
547 idx_id
= find_index(filename
);
551 if (!tagcache_search(tcs
, tag_filename
))
554 tcs
->entry_count
= 0;
555 tcs
->idx_id
= idx_id
;
560 static bool get_index(int masterfd
, int idxid
,
561 struct index_entry
*idx
, bool use_ram
)
563 bool localfd
= false;
567 logf("Incorrect idxid: %d", idxid
);
571 #ifdef HAVE_TC_RAMCACHE
572 if (tc_stat
.ramcache
&& use_ram
)
574 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
577 # ifdef HAVE_DIRCACHE
578 if (!(hdr
->indices
[idxid
].flag
& FLAG_DIRCACHE
)
579 || is_dircache_intact())
582 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
592 struct master_header tcmh
;
595 masterfd
= open_master_fd(&tcmh
, false);
600 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
601 + sizeof(struct master_header
), SEEK_SET
);
602 if (ecread_index_entry(masterfd
, idx
)
603 != sizeof(struct index_entry
))
605 logf("read error #3");
615 if (idx
->flag
& FLAG_DELETED
)
623 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
625 /* We need to exclude all memory only flags & tags when writing to disk. */
626 if (idx
->flag
& FLAG_DIRCACHE
)
628 logf("memory only flags!");
632 #ifdef HAVE_TC_RAMCACHE
633 /* Only update numeric data. Writing the whole index to RAM by memcpy
634 * destroys dircache pointers!
636 if (tc_stat
.ramcache
)
639 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
641 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
643 if (TAGCACHE_IS_NUMERIC(tag
))
645 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
649 /* Don't touch the dircache flag or attributes. */
650 idx_ram
->flag
= (idx
->flag
& 0x0000ffff)
651 | (idx_ram
->flag
& (0xffff0000 | FLAG_DIRCACHE
));
655 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
656 + sizeof(struct master_header
), SEEK_SET
);
657 if (ecwrite_index_entry(masterfd
, idx
) != sizeof(struct index_entry
))
659 logf("write error #3");
660 logf("idxid: %d", idxid
);
667 #endif /* !__PCTOOL__ */
669 static bool open_files(struct tagcache_search
*tcs
, int tag
)
671 if (tcs
->idxfd
[tag
] < 0)
675 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
676 tcs
->idxfd
[tag
] = open(fn
, O_RDONLY
);
679 if (tcs
->idxfd
[tag
] < 0)
681 logf("File not open!");
688 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
689 int tag
, char *buf
, long size
)
691 struct tagfile_entry tfe
;
696 if (TAGCACHE_IS_NUMERIC(tag
))
699 seek
= idx
->tag_seek
[tag
];
702 logf("Retrieve failed");
706 #ifdef HAVE_TC_RAMCACHE
709 struct tagfile_entry
*ep
;
711 # ifdef HAVE_DIRCACHE
712 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
713 && is_dircache_intact())
715 dircache_copy_path((struct dircache_entry
*)seek
,
721 if (tag
!= tag_filename
)
723 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
724 strlcpy(buf
, ep
->tag_data
, size
);
731 if (!open_files(tcs
, tag
))
734 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
735 if (ecread_tagfile_entry(tcs
->idxfd
[tag
], &tfe
)
736 != sizeof(struct tagfile_entry
))
738 logf("read error #5");
742 if (tfe
.tag_length
>= size
)
744 logf("too small buffer");
748 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
751 logf("read error #6");
755 buf
[tfe
.tag_length
] = '\0';
760 static long check_virtual_tags(int tag
, const struct index_entry
*idx
)
766 case tag_virt_length_sec
:
767 data
= (idx
->tag_seek
[tag_length
]/1000) % 60;
770 case tag_virt_length_min
:
771 data
= (idx
->tag_seek
[tag_length
]/1000) / 60;
774 case tag_virt_playtime_sec
:
775 data
= (idx
->tag_seek
[tag_playtime
]/1000) % 60;
778 case tag_virt_playtime_min
:
779 data
= (idx
->tag_seek
[tag_playtime
]/1000) / 60;
782 case tag_virt_autoscore
:
783 if (idx
->tag_seek
[tag_length
] == 0
784 || idx
->tag_seek
[tag_playcount
] == 0)
790 /* A straight calculus gives:
791 autoscore = 100 * playtime / length / playcout (1)
792 Now, consider the euclidian division of playtime by length:
793 playtime = alpha * length + beta
797 autoscore = 100 * (alpha / playcout + beta / length / playcount)
798 Both terms should be small enough to avoid any overflow
800 data
= 100 * (idx
->tag_seek
[tag_playtime
] / idx
->tag_seek
[tag_length
])
801 + (100 * (idx
->tag_seek
[tag_playtime
] % idx
->tag_seek
[tag_length
])) / idx
->tag_seek
[tag_length
];
802 data
/= idx
->tag_seek
[tag_playcount
];
806 /* How many commits before the file has been added to the DB. */
807 case tag_virt_entryage
:
808 data
= current_tcmh
.commitid
- idx
->tag_seek
[tag_commitid
] - 1;
812 data
= idx
->tag_seek
[tag
];
818 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
820 struct index_entry idx
;
825 if (!TAGCACHE_IS_NUMERIC(tag
))
828 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
831 return check_virtual_tags(tag
, &idx
);
834 inline static bool str_ends_with(const char *str1
, const char *str2
)
836 int str_len
= strlen(str1
);
837 int clause_len
= strlen(str2
);
839 if (clause_len
> str_len
)
842 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
845 inline static bool str_oneof(const char *str
, const char *list
)
848 int l
, len
= strlen(str
);
852 sep
= strchr(list
, '|');
853 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
854 if ((l
==len
) && !strncasecmp(str
, list
, len
))
856 list
+= sep
? l
+ 1 : l
;
862 static bool check_against_clause(long numeric
, const char *str
,
863 const struct tagcache_search_clause
*clause
)
867 switch (clause
->type
)
870 return numeric
== clause
->numeric_data
;
872 return numeric
!= clause
->numeric_data
;
874 return numeric
> clause
->numeric_data
;
876 return numeric
>= clause
->numeric_data
;
878 return numeric
< clause
->numeric_data
;
880 return numeric
<= clause
->numeric_data
;
882 logf("Incorrect numeric tag: %d", clause
->type
);
887 switch (clause
->type
)
890 return !strcasecmp(clause
->str
, str
);
892 return strcasecmp(clause
->str
, str
);
894 return 0>strcasecmp(clause
->str
, str
);
896 return 0>=strcasecmp(clause
->str
, str
);
898 return 0<strcasecmp(clause
->str
, str
);
900 return 0<=strcasecmp(clause
->str
, str
);
901 case clause_contains
:
902 return (strcasestr(str
, clause
->str
) != NULL
);
903 case clause_not_contains
:
904 return (strcasestr(str
, clause
->str
) == NULL
);
905 case clause_begins_with
:
906 return (strcasestr(str
, clause
->str
) == str
);
907 case clause_not_begins_with
:
908 return (strcasestr(str
, clause
->str
) != str
);
909 case clause_ends_with
:
910 return str_ends_with(str
, clause
->str
);
911 case clause_not_ends_with
:
912 return !str_ends_with(str
, clause
->str
);
914 return str_oneof(str
, clause
->str
);
917 logf("Incorrect tag: %d", clause
->type
);
924 static bool check_clauses(struct tagcache_search
*tcs
,
925 struct index_entry
*idx
,
926 struct tagcache_search_clause
**clause
, int count
)
930 #ifdef HAVE_TC_RAMCACHE
933 /* Go through all conditional clauses. */
934 for (i
= 0; i
< count
; i
++)
936 struct tagfile_entry
*tfe
;
941 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
943 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
945 if (clause
[i
]->tag
== tag_filename
)
947 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
952 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
957 if (!check_against_clause(seek
, str
, clause
[i
]))
964 /* Check for conditions. */
965 for (i
= 0; i
< count
; i
++)
967 struct tagfile_entry tfe
;
971 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
973 memset(str
, 0, sizeof str
);
974 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
976 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
977 lseek(fd
, seek
, SEEK_SET
);
978 ecread_tagfile_entry(fd
, &tfe
);
979 if (tfe
.tag_length
>= (int)sizeof(str
))
981 logf("Too long tag read!");
985 read(fd
, str
, tfe
.tag_length
);
987 /* Check if entry has been deleted. */
992 if (!check_against_clause(seek
, str
, clause
[i
]))
1000 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
1001 struct tagcache_search_clause
**clause
, int count
)
1003 struct index_entry idx
;
1008 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
1011 return check_clauses(tcs
, &idx
, clause
, count
);
1014 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1018 /* If uniq buffer is not defined we must return true for search to work. */
1019 if (tcs
->unique_list
== NULL
|| (!TAGCACHE_IS_UNIQUE(tcs
->type
)
1020 && !TAGCACHE_IS_NUMERIC(tcs
->type
)))
1025 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1027 /* Return false if entry is found. */
1028 if (tcs
->unique_list
[i
] == id
)
1032 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1034 tcs
->unique_list
[i
] = id
;
1035 tcs
->unique_list_count
++;
1041 static bool build_lookup_list(struct tagcache_search
*tcs
)
1043 struct index_entry entry
;
1046 tcs
->seek_list_count
= 0;
1048 #ifdef HAVE_TC_RAMCACHE
1050 # ifdef HAVE_DIRCACHE
1051 && (tcs
->type
!= tag_filename
|| is_dircache_intact())
1055 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
1057 struct tagcache_seeklist_entry
*seeklist
;
1058 struct index_entry
*idx
= &hdr
->indices
[i
];
1059 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1062 /* Skip deleted files. */
1063 if (idx
->flag
& FLAG_DELETED
)
1066 /* Go through all filters.. */
1067 for (j
= 0; j
< tcs
->filter_count
; j
++)
1069 if (idx
->tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1075 if (j
< tcs
->filter_count
)
1078 /* Check for conditions. */
1079 if (!check_clauses(tcs
, idx
, tcs
->clause
, tcs
->clause_count
))
1082 /* Add to the seek list if not already in uniq buffer. */
1083 if (!add_uniqbuf(tcs
, idx
->tag_seek
[tcs
->type
]))
1087 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1088 seeklist
->seek
= idx
->tag_seek
[tcs
->type
];
1089 seeklist
->flag
= idx
->flag
;
1090 seeklist
->idx_id
= i
;
1091 tcs
->seek_list_count
++;
1096 return tcs
->seek_list_count
> 0;
1100 if (tcs
->masterfd
< 0)
1102 struct master_header tcmh
;
1103 tcs
->masterfd
= open_master_fd(&tcmh
, false);
1106 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1107 sizeof(struct master_header
), SEEK_SET
);
1109 while (ecread_index_entry(tcs
->masterfd
, &entry
)
1110 == sizeof(struct index_entry
))
1112 struct tagcache_seeklist_entry
*seeklist
;
1114 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1120 /* Check if entry has been deleted. */
1121 if (entry
.flag
& FLAG_DELETED
)
1124 /* Go through all filters.. */
1125 for (j
= 0; j
< tcs
->filter_count
; j
++)
1127 if (entry
.tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1131 if (j
< tcs
->filter_count
)
1134 /* Check for conditions. */
1135 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1138 /* Add to the seek list if not already in uniq buffer. */
1139 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1143 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1144 seeklist
->seek
= entry
.tag_seek
[tcs
->type
];
1145 seeklist
->flag
= entry
.flag
;
1146 seeklist
->idx_id
= i
;
1147 tcs
->seek_list_count
++;
1152 return tcs
->seek_list_count
> 0;
1156 static void remove_files(void)
1161 tc_stat
.ready
= false;
1162 tc_stat
.ramcache
= false;
1163 tc_stat
.econ
= false;
1164 remove(TAGCACHE_FILE_MASTER
);
1165 for (i
= 0; i
< TAG_COUNT
; i
++)
1167 if (TAGCACHE_IS_NUMERIC(i
))
1170 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1176 static bool check_all_headers(void)
1178 struct master_header myhdr
;
1179 struct tagcache_header tch
;
1183 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1189 logf("tagcache is dirty!");
1193 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1195 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1197 if (TAGCACHE_IS_NUMERIC(tag
))
1200 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1209 bool tagcache_is_busy(void)
1211 return read_lock
|| write_lock
;
1214 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1216 struct tagcache_header tag_hdr
;
1217 struct master_header master_hdr
;
1223 memset(tcs
, 0, sizeof(struct tagcache_search
));
1224 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1227 tcs
->position
= sizeof(struct tagcache_header
);
1230 tcs
->list_position
= 0;
1231 tcs
->seek_list_count
= 0;
1232 tcs
->filter_count
= 0;
1235 for (i
= 0; i
< TAG_COUNT
; i
++)
1238 #ifndef HAVE_TC_RAMCACHE
1239 tcs
->ramsearch
= false;
1241 tcs
->ramsearch
= tc_stat
.ramcache
;
1244 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1249 /* Always open as R/W so we can pass tcs to functions that modify data also
1250 * without failing. */
1251 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1252 if (tcs
->masterfd
< 0)
1255 if (!TAGCACHE_IS_NUMERIC(tcs
->type
))
1257 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1258 if (tcs
->idxfd
[tcs
->type
] < 0)
1261 tcs
->entry_count
= tag_hdr
.entry_count
;
1265 tcs
->entry_count
= master_hdr
.tch
.entry_count
;
1270 tcs
->initialized
= true;
1276 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1277 void *buffer
, long length
)
1279 tcs
->unique_list
= (unsigned long *)buffer
;
1280 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1281 tcs
->unique_list_count
= 0;
1284 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1287 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1290 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag
))
1293 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1294 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1295 tcs
->filter_count
++;
1300 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1301 struct tagcache_search_clause
*clause
)
1305 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1307 logf("Too many clauses");
1311 /* Check if there is already a similar filter in present (filters are
1312 * much faster than clauses).
1314 for (i
= 0; i
< tcs
->filter_count
; i
++)
1316 if (tcs
->filter_tag
[i
] == clause
->tag
)
1320 if (!TAGCACHE_IS_NUMERIC(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1324 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1325 tcs
->idxfd
[clause
->tag
] = open(buf
, O_RDONLY
);
1328 tcs
->clause
[tcs
->clause_count
] = clause
;
1329 tcs
->clause_count
++;
1334 static bool get_next(struct tagcache_search
*tcs
)
1336 static char buf
[TAG_MAXLEN
+32];
1337 struct tagfile_entry entry
;
1340 if (!tcs
->valid
|| !tc_stat
.ready
)
1343 if (tcs
->idxfd
[tcs
->type
] < 0 && !TAGCACHE_IS_NUMERIC(tcs
->type
)
1344 #ifdef HAVE_TC_RAMCACHE
1350 /* Relative fetch. */
1351 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1352 || TAGCACHE_IS_NUMERIC(tcs
->type
)
1353 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1354 /* We need to retrieve flag status for dircache. */
1355 || (tcs
->ramsearch
&& tcs
->type
== tag_filename
)
1359 struct tagcache_seeklist_entry
*seeklist
;
1361 /* Check for end of list. */
1362 if (tcs
->list_position
== tcs
->seek_list_count
)
1364 tcs
->list_position
= 0;
1366 /* Try to fetch more. */
1367 if (!build_lookup_list(tcs
))
1374 seeklist
= &tcs
->seeklist
[tcs
->list_position
];
1375 flag
= seeklist
->flag
;
1376 tcs
->position
= seeklist
->seek
;
1377 tcs
->idx_id
= seeklist
->idx_id
;
1378 tcs
->list_position
++;
1382 if (tcs
->entry_count
== 0)
1391 tcs
->result_seek
= tcs
->position
;
1393 if (TAGCACHE_IS_NUMERIC(tcs
->type
))
1395 snprintf(buf
, sizeof(buf
), "%ld", tcs
->position
);
1397 tcs
->result_len
= strlen(buf
) + 1;
1402 #ifdef HAVE_TC_RAMCACHE
1406 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1407 if (tcs
->type
== tag_filename
&& (flag
& FLAG_DIRCACHE
)
1408 && is_dircache_intact())
1410 dircache_copy_path((struct dircache_entry
*)tcs
->position
,
1413 tcs
->result_len
= strlen(buf
) + 1;
1414 tcs
->ramresult
= false;
1420 if (tcs
->type
!= tag_filename
)
1422 struct tagfile_entry
*ep
;
1424 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1425 tcs
->result
= ep
->tag_data
;
1426 tcs
->result_len
= strlen(tcs
->result
) + 1;
1427 tcs
->idx_id
= ep
->idx_id
;
1428 tcs
->ramresult
= true;
1430 /* Increase position for the next run. This may get overwritten. */
1431 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1438 if (!open_files(tcs
, tcs
->type
))
1444 /* Seek stream to the correct position and continue to direct fetch. */
1445 lseek(tcs
->idxfd
[tcs
->type
], tcs
->position
, SEEK_SET
);
1447 if (ecread_tagfile_entry(tcs
->idxfd
[tcs
->type
], &entry
) != sizeof(struct tagfile_entry
))
1449 logf("read error #5");
1454 if (entry
.tag_length
> (long)sizeof(buf
))
1457 logf("too long tag #2");
1458 logf("P:%lX/%lX", tcs
->position
, entry
.tag_length
);
1462 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1465 logf("read error #4");
1470 Update the position for the next read (this may be overridden
1471 if filters or clauses are being used).
1473 tcs
->position
+= sizeof(struct tagfile_entry
) + entry
.tag_length
;
1475 tcs
->result_len
= strlen(tcs
->result
) + 1;
1476 tcs
->idx_id
= entry
.idx_id
;
1477 tcs
->ramresult
= false;
1482 bool tagcache_get_next(struct tagcache_search
*tcs
)
1484 while (get_next(tcs
))
1486 if (tcs
->result_len
> 1)
1493 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1494 int tag
, char *buf
, long size
)
1496 struct index_entry idx
;
1499 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1502 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1505 static bool update_master_header(void)
1507 struct master_header myhdr
;
1513 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1516 myhdr
.serial
= current_tcmh
.serial
;
1517 myhdr
.commitid
= current_tcmh
.commitid
;
1518 myhdr
.dirty
= current_tcmh
.dirty
;
1521 lseek(fd
, 0, SEEK_SET
);
1522 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1525 #ifdef HAVE_TC_RAMCACHE
1528 hdr
->h
.serial
= current_tcmh
.serial
;
1529 hdr
->h
.commitid
= current_tcmh
.commitid
;
1530 hdr
->h
.dirty
= current_tcmh
.dirty
;
1539 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1541 struct tagentry
*entry
;
1543 if (tcs
->type
!= tag_title
)
1546 /* We will need reserve buffer for this. */
1549 struct tagfile_entry
*ep
;
1551 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1552 tcs
->seek_list
[tcs
->seek_list_count
];
1555 entry
= find_entry_ram();
1560 void tagcache_search_finish(struct tagcache_search
*tcs
)
1564 if (!tcs
->initialized
)
1567 if (tcs
->masterfd
>= 0)
1569 close(tcs
->masterfd
);
1573 for (i
= 0; i
< TAG_COUNT
; i
++)
1575 if (tcs
->idxfd
[i
] >= 0)
1577 close(tcs
->idxfd
[i
]);
1582 tcs
->ramsearch
= false;
1584 tcs
->initialized
= 0;
1589 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1590 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1592 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1595 static long get_tag_numeric(const struct index_entry
*entry
, int tag
)
1597 return check_virtual_tags(tag
, entry
);
1600 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1602 char* s
= get_tag(entry
, tag
)->tag_data
;
1603 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1606 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1608 struct index_entry
*entry
;
1611 if (!tc_stat
.ready
|| !tc_stat
.ramcache
)
1614 /* Find the corresponding entry in tagcache. */
1615 idx_id
= find_entry_ram(filename
, NULL
);
1619 entry
= &hdr
->indices
[idx_id
];
1621 memset(id3
, 0, sizeof(struct mp3entry
));
1623 id3
->title
= get_tag_string(entry
, tag_title
);
1624 id3
->artist
= get_tag_string(entry
, tag_artist
);
1625 id3
->album
= get_tag_string(entry
, tag_album
);
1626 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1627 id3
->composer
= get_tag_string(entry
, tag_composer
);
1628 id3
->comment
= get_tag_string(entry
, tag_comment
);
1629 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1630 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1632 id3
->length
= get_tag_numeric(entry
, tag_length
);
1633 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
);
1634 id3
->rating
= get_tag_numeric(entry
, tag_rating
);
1635 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
);
1636 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
) / 10;
1637 id3
->year
= get_tag_numeric(entry
, tag_year
);
1639 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
);
1640 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
);
1641 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
);
1642 if (id3
->bitrate
== 0)
1649 static inline void write_item(const char *item
)
1651 int len
= strlen(item
) + 1;
1654 write(cachefd
, item
, len
);
1657 static int check_if_empty(char **tag
)
1661 if (*tag
== NULL
|| **tag
== '\0')
1664 return sizeof(UNTAGGED
); /* Tag length */
1667 length
= strlen(*tag
);
1668 if (length
> TAG_MAXLEN
)
1670 logf("over length tag: %s", *tag
);
1671 length
= TAG_MAXLEN
;
1672 (*tag
)[length
] = '\0';
1678 #define ADD_TAG(entry,tag,data) \
1680 entry.tag_offset[tag] = offset; \
1681 entry.tag_length[tag] = check_if_empty(data); \
1682 offset += entry.tag_length[tag]
1683 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1684 * idea, as it uses lots of stack and is called from a recursive function
1687 static void __attribute__ ((noinline
)) add_tagcache(char *path
,
1689 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1690 ,const struct dircache_entry
*dc
1694 struct mp3entry id3
;
1695 struct temp_file_entry entry
;
1699 char tracknumfix
[3];
1701 int path_length
= strlen(path
);
1702 bool has_albumartist
;
1706 /* Crude logging for the sim - to aid in debugging */
1707 int logfd
= open(ROCKBOX_DIR
"/database.log",
1708 O_WRONLY
| O_APPEND
| O_CREAT
, 0666);
1710 write(logfd
, path
, strlen(path
));
1711 write(logfd
, "\n", 1);
1719 /* Check for overlength file path. */
1720 if (path_length
> TAG_MAXLEN
)
1722 /* Path can't be shortened. */
1723 logf("Too long path: %s", path
);
1727 /* Check if the file is supported. */
1728 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1731 /* Check if the file is already cached. */
1732 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1733 if (tc_stat
.ramcache
&& is_dircache_intact())
1735 idx_id
= find_entry_ram(path
, dc
);
1739 /* Be sure the entry doesn't exist. */
1740 if (filenametag_fd
>= 0 && idx_id
< 0)
1741 idx_id
= find_entry_disk(path
, false);
1743 /* Check if file has been modified. */
1746 struct index_entry idx
;
1748 /* TODO: Mark that the index exists (for fast reverse scan) */
1749 //found_idx[idx_id/8] |= idx_id%8;
1751 if (!get_index(-1, idx_id
, &idx
, true))
1753 logf("failed to retrieve index entry");
1757 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1759 /* No changes to file. */
1763 /* Metadata might have been changed. Delete the entry. */
1764 logf("Re-adding: %s", path
);
1765 if (!delete_entry(idx_id
))
1767 logf("delete_entry failed: %d", idx_id
);
1772 fd
= open(path
, O_RDONLY
);
1775 logf("open fail: %s", path
);
1779 memset(&id3
, 0, sizeof(struct mp3entry
));
1780 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1781 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1782 ret
= get_metadata(&id3
, fd
, path
);
1788 logf("-> %s", path
);
1790 /* Generate track number if missing. */
1791 if (id3
.tracknum
<= 0)
1793 const char *p
= strrchr(path
, '.');
1796 p
= &path
[strlen(path
)-1];
1800 if (isdigit(*p
) && isdigit(*(p
-1)))
1802 tracknumfix
[1] = *p
--;
1803 tracknumfix
[0] = *p
;
1809 if (tracknumfix
[0] != '\0')
1811 id3
.tracknum
= atoi(tracknumfix
);
1812 /* Set a flag to indicate track number has been generated. */
1813 entry
.flag
|= FLAG_TRKNUMGEN
;
1817 /* Unable to generate track number. */
1823 entry
.tag_offset
[tag_year
] = id3
.year
;
1824 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1825 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1826 entry
.tag_offset
[tag_length
] = id3
.length
;
1827 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1828 entry
.tag_offset
[tag_mtime
] = mtime
;
1831 has_albumartist
= id3
.albumartist
!= NULL
1832 && strlen(id3
.albumartist
) > 0;
1833 has_grouping
= id3
.grouping
!= NULL
1834 && strlen(id3
.grouping
) > 0;
1836 ADD_TAG(entry
, tag_filename
, &path
);
1837 ADD_TAG(entry
, tag_title
, &id3
.title
);
1838 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1839 ADD_TAG(entry
, tag_album
, &id3
.album
);
1840 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1841 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1842 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1843 if (has_albumartist
)
1845 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1849 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1853 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1857 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1859 entry
.data_length
= offset
;
1861 /* Write the header */
1862 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1864 /* And tags also... Correct order is critical */
1866 write_item(id3
.title
);
1867 write_item(id3
.artist
);
1868 write_item(id3
.album
);
1869 write_item(id3
.genre_string
);
1870 write_item(id3
.composer
);
1871 write_item(id3
.comment
);
1872 if (has_albumartist
)
1874 write_item(id3
.albumartist
);
1878 write_item(id3
.artist
);
1882 write_item(id3
.grouping
);
1886 write_item(id3
.title
);
1888 total_entry_count
++;
1891 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1893 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1894 int len
= strlen(str
)+1;
1897 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1898 char buf
[TAG_MAXLEN
+32];
1900 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1901 buf
[i
] = tolower(str
[i
]);
1904 crc32
= crc_32(buf
, i
, 0xffffffff);
1908 /* Check if the crc does not exist -> entry does not exist for sure. */
1909 for (i
= 0; i
< tempbufidx
; i
++)
1911 if (crcbuf
[-i
] != crc32
)
1914 if (!strcasecmp(str
, index
[i
].str
))
1916 if (id
< 0 || id
>= lookup_buffer_depth
)
1918 logf("lookup buf overf.: %d", id
);
1922 lookup
[id
] = &index
[i
];
1928 /* Insert to CRC buffer. */
1929 crcbuf
[-tempbufidx
] = crc32
;
1932 /* Insert it to the buffer. */
1933 tempbuf_left
-= len
;
1934 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1937 if (id
>= lookup_buffer_depth
)
1939 logf("lookup buf overf. #2: %d", id
);
1945 lookup
[id
] = &index
[tempbufidx
];
1946 index
[tempbufidx
].idlist
.id
= id
;
1949 index
[tempbufidx
].idlist
.id
= -1;
1951 index
[tempbufidx
].idlist
.next
= NULL
;
1952 index
[tempbufidx
].idx_id
= idx_id
;
1953 index
[tempbufidx
].seek
= -1;
1954 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
1955 memcpy(index
[tempbufidx
].str
, str
, len
);
1962 static int compare(const void *p1
, const void *p2
)
1966 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
1967 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
1969 if (strcmp(e1
->str
, UNTAGGED
) == 0)
1971 if (strcmp(e2
->str
, UNTAGGED
) == 0)
1975 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
1978 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
1981 static int tempbuf_sort(int fd
)
1983 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1984 struct tagfile_entry fe
;
1988 /* Generate reverse lookup entries. */
1989 for (i
= 0; i
< lookup_buffer_depth
; i
++)
1991 struct tempbuf_id_list
*idlist
;
1996 if (lookup
[i
]->idlist
.id
== i
)
1999 idlist
= &lookup
[i
]->idlist
;
2000 while (idlist
->next
!= NULL
)
2001 idlist
= idlist
->next
;
2003 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
2004 if (tempbuf_left
- 4 < 0)
2007 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2008 if (tempbuf_pos
& 0x03)
2010 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
2012 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2014 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
2016 idlist
= idlist
->next
;
2018 idlist
->next
= NULL
;
2023 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
2024 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
2026 for (i
= 0; i
< tempbufidx
; i
++)
2028 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
2030 /* Fix the lookup list. */
2031 while (idlist
!= NULL
)
2033 if (idlist
->id
>= 0)
2034 lookup
[idlist
->id
] = &index
[i
];
2035 idlist
= idlist
->next
;
2038 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
2039 length
= strlen(index
[i
].str
) + 1;
2040 fe
.tag_length
= length
;
2041 fe
.idx_id
= index
[i
].idx_id
;
2043 /* Check the chunk alignment. */
2044 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2045 % TAGFILE_ENTRY_CHUNK_LENGTH
)
2047 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
2048 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2049 % TAGFILE_ENTRY_CHUNK_LENGTH
);
2052 #ifdef TAGCACHE_STRICT_ALIGN
2053 /* Make sure the entry is long aligned. */
2054 if (index
[i
].seek
& 0x03)
2056 logf("tempbuf_sort: alignment error!");
2061 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2062 sizeof(struct tagfile_entry
))
2064 logf("tempbuf_sort: write error #1");
2068 if (write(fd
, index
[i
].str
, length
) != length
)
2070 logf("tempbuf_sort: write error #2");
2074 /* Write some padding. */
2075 if (fe
.tag_length
- length
> 0)
2076 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2082 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2084 if (id
< 0 || id
>= lookup_buffer_depth
)
2091 inline static int tempbuf_find_location(int id
)
2093 struct tempbuf_searchidx
*entry
;
2095 entry
= tempbuf_locate(id
);
2102 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2104 struct master_header tcmh
;
2105 struct index_entry idx
;
2108 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2110 int entries_processed
= 0;
2112 char buf
[TAG_MAXLEN
];
2114 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2116 logf("Building numeric indices...");
2117 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2119 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2122 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2124 if (masterfd_pos
== filesize(masterfd
))
2126 logf("we can't append!");
2131 while (entries_processed
< h
->entry_count
)
2133 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2135 /* Read in as many entries as possible. */
2136 for (i
= 0; i
< count
; i
++)
2138 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2141 /* Read in numeric data. */
2142 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2143 sizeof(struct temp_file_entry
))
2145 logf("read fail #1");
2150 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2153 * Read string data from the following tags:
2159 * A crc32 hash is calculated from the read data
2160 * and stored back to the data offset field kept in memory.
2162 #define tmpdb_read_string_tag(tag) \
2163 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2164 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2166 logf("read fail: buffer overflow"); \
2171 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2172 tfe->tag_length[tag]) \
2174 logf("read fail #2"); \
2179 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2180 lseek(tmpfd, datastart, SEEK_SET)
2182 tmpdb_read_string_tag(tag_filename
);
2183 tmpdb_read_string_tag(tag_artist
);
2184 tmpdb_read_string_tag(tag_album
);
2185 tmpdb_read_string_tag(tag_title
);
2187 /* Seek to the end of the string data. */
2188 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2191 /* Backup the master index position. */
2192 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2193 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2195 /* Check if we can resurrect some deleted runtime statistics data. */
2196 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2198 /* Read the index entry. */
2199 if (ecread_index_entry(masterfd
, &idx
)
2200 != sizeof(struct index_entry
))
2202 logf("read fail #3");
2208 * Skip unless the entry is marked as being deleted
2209 * or the data has already been resurrected.
2211 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2214 /* Now try to match the entry. */
2216 * To succesfully match a song, the following conditions
2219 * For numeric fields: tag_length
2220 * - Full identical match is required
2222 * If tag_filename matches, no further checking necessary.
2224 * For string hashes: tag_artist, tag_album, tag_title
2225 * - Two of these must match
2227 for (j
= 0; j
< count
; j
++)
2229 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2231 /* Try to match numeric fields first. */
2232 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2235 /* Now it's time to do the hash matching. */
2236 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2238 int match_count
= 0;
2240 /* No filename match, check if we can match two other tags. */
2241 #define tmpdb_match(tag) \
2242 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2245 tmpdb_match(tag_artist
);
2246 tmpdb_match(tag_album
);
2247 tmpdb_match(tag_title
);
2249 if (match_count
< 2)
2251 /* Still no match found, give up. */
2256 /* A match found, now copy & resurrect the statistical data. */
2257 #define tmpdb_copy_tag(tag) \
2258 tfe->tag_offset[tag] = idx.tag_seek[tag]
2260 tmpdb_copy_tag(tag_playcount
);
2261 tmpdb_copy_tag(tag_rating
);
2262 tmpdb_copy_tag(tag_playtime
);
2263 tmpdb_copy_tag(tag_lastplayed
);
2264 tmpdb_copy_tag(tag_commitid
);
2266 /* Avoid processing this entry again. */
2267 idx
.flag
|= FLAG_RESURRECTED
;
2269 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2270 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2272 logf("masterfd writeback fail #1");
2277 logf("Entry resurrected");
2282 /* Restore the master index position. */
2283 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2285 /* Commit the data to the index. */
2286 for (i
= 0; i
< count
; i
++)
2288 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2290 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2292 logf("read fail #3");
2297 for (j
= 0; j
< TAG_COUNT
; j
++)
2299 if (!TAGCACHE_IS_NUMERIC(j
))
2302 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2304 idx
.flag
= entrybuf
[i
].flag
;
2306 if (idx
.tag_seek
[tag_commitid
])
2308 /* Data has been resurrected. */
2309 idx
.flag
|= FLAG_DIRTYNUM
;
2311 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2313 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2314 idx
.flag
|= FLAG_DIRTYNUM
;
2317 /* Write back the updated index. */
2318 lseek(masterfd
, loc
, SEEK_SET
);
2319 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2327 entries_processed
+= count
;
2328 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2339 * == 0 temporary failure
2342 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2345 struct tagcache_header tch
;
2346 struct master_header tcmh
;
2347 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2349 char buf
[TAG_MAXLEN
+32];
2350 int fd
= -1, masterfd
;
2355 logf("Building index: %d", index_type
);
2357 /* Check the number of entries we need to allocate ram for. */
2358 commit_entry_count
= h
->entry_count
+ 1;
2360 masterfd
= open_master_fd(&tcmh
, false);
2363 commit_entry_count
+= tcmh
.tch
.entry_count
;
2367 remove_files(); /* Just to be sure we are clean. */
2369 /* Open the index file, which contains the tag names. */
2370 fd
= open_tag_fd(&tch
, index_type
, true);
2373 logf("tch.datasize=%ld", tch
.datasize
);
2374 lookup_buffer_depth
= 1 +
2375 /* First part */ commit_entry_count
+
2376 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2380 lookup_buffer_depth
= 1 +
2381 /* First part */ commit_entry_count
+
2382 /* Second part */ 0;
2385 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2386 logf("commit_entry_count=%ld", commit_entry_count
);
2388 /* Allocate buffer for all index entries from both old and new
2391 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2393 /* Allocate lookup buffer. The first portion of commit_entry_count
2394 * contains the new tags in the temporary file and the second
2395 * part for locating entries already in the db.
2398 * +---------+---------------------------+
2399 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2400 * +---------+---------------------------+
2402 * Old tags are inserted to a temporary buffer with position:
2403 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2404 * And new tags with index:
2405 * tempbuf_insert(idx, ...);
2407 * The buffer is sorted and written into tag file:
2408 * tempbuf_sort(...);
2409 * leaving master index locations messed up.
2411 * That is fixed using the lookup buffer for old tags:
2412 * new_seek = tempbuf_find_location(old_seek, ...);
2414 * new_seek = tempbuf_find_location(idx);
2416 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2417 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2418 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2420 /* And calculate the remaining data space used mainly for storing
2421 * tag data (strings). */
2422 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2423 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2425 logf("Buffer way too small!");
2432 * If tag file contains unique tags (sorted index), we will load
2433 * it entirely into memory so we can resort it later for use with
2436 if (TAGCACHE_IS_SORTED(index_type
))
2438 logf("loading tags...");
2439 for (i
= 0; i
< tch
.entry_count
; i
++)
2441 struct tagfile_entry entry
;
2442 int loc
= lseek(fd
, 0, SEEK_CUR
);
2445 if (ecread_tagfile_entry(fd
, &entry
) != sizeof(struct tagfile_entry
))
2447 logf("read error #7");
2452 if (entry
.tag_length
>= (int)sizeof(buf
))
2454 logf("too long tag #3");
2459 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2461 logf("read error #8");
2466 /* Skip deleted entries. */
2471 * Save the tag and tag id in the memory buffer. Tag id
2472 * is saved so we can later reindex the master lookup
2473 * table when the index gets resorted.
2475 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2476 + commit_entry_count
, entry
.idx_id
,
2477 TAGCACHE_IS_UNIQUE(index_type
));
2488 tempbufidx
= tch
.entry_count
;
2493 * Creating new index file to store the tags. No need to preload
2494 * anything whether the index type is sorted or not.
2496 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2497 fd
= open(buf
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2500 logf("%s open fail", buf
);
2504 tch
.magic
= TAGCACHE_MAGIC
;
2505 tch
.entry_count
= 0;
2508 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2509 != sizeof(struct tagcache_header
))
2511 logf("header write failed");
2517 /* Loading the tag lookup file as "master file". */
2518 logf("Loading index file");
2519 masterfd
= open(TAGCACHE_FILE_MASTER
, O_RDWR
);
2523 logf("Creating new DB");
2524 masterfd
= open(TAGCACHE_FILE_MASTER
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2528 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER
);
2533 /* Write the header (write real values later). */
2534 memset(&tcmh
, 0, sizeof(struct master_header
));
2536 tcmh
.tch
.entry_count
= 0;
2537 tcmh
.tch
.datasize
= 0;
2539 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2541 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2546 * Master file already exists so we need to process the current
2551 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2552 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2554 logf("header error");
2561 * If we reach end of the master file, we need to expand it to
2562 * hold new tags. If the current index is not sorted, we can
2563 * simply append new data to end of the file.
2564 * However, if the index is sorted, we need to update all tag
2565 * pointers in the master file for the current index.
2567 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2569 if (masterfd_pos
== filesize(masterfd
))
2571 logf("appending...");
2577 * Load new unique tags in memory to be sorted later and added
2578 * to the master lookup file.
2580 if (TAGCACHE_IS_SORTED(index_type
))
2582 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2583 /* h is the header of the temporary file containing new tags. */
2584 logf("inserting new tags...");
2585 for (i
= 0; i
< h
->entry_count
; i
++)
2587 struct temp_file_entry entry
;
2589 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2590 sizeof(struct temp_file_entry
))
2592 logf("read fail #3");
2598 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2600 logf("too long entry!");
2605 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2606 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2607 entry
.tag_length
[index_type
])
2609 logf("read fail #4");
2614 if (TAGCACHE_IS_UNIQUE(index_type
))
2615 error
= !tempbuf_insert(buf
, i
, -1, true);
2617 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2621 logf("insert error");
2626 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2627 entry
.tag_length
[index_type
], SEEK_CUR
);
2632 /* Sort the buffer data and write it to the index file. */
2633 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2635 * We need to truncate the index file now. There can be junk left
2636 * at the end of file (however, we _should_ always follow the
2637 * entry_count and don't crash with that).
2639 ftruncate(fd
, lseek(fd
, 0, SEEK_CUR
));
2641 i
= tempbuf_sort(fd
);
2644 logf("sorted %d tags", i
);
2647 * Now update all indexes in the master lookup file.
2649 logf("updating indices...");
2650 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2651 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2654 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2656 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2658 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2659 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2661 logf("read fail #5");
2665 lseek(masterfd
, loc
, SEEK_SET
);
2667 for (j
= 0; j
< idxbuf_pos
; j
++)
2669 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2671 /* We can just ignore deleted entries. */
2672 // idxbuf[j].tag_seek[index_type] = 0;
2676 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2677 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2678 + commit_entry_count
);
2680 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2682 logf("update error: %ld/%d/%ld",
2683 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2691 /* Write back the updated index. */
2692 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2693 index_entry_ec
, tc_stat
.econ
) !=
2694 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2705 * Walk through the temporary file containing the new tags.
2707 // build_normal_index(h, tmpfd, masterfd, idx);
2708 logf("updating new indices...");
2709 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2710 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2711 lseek(fd
, 0, SEEK_END
);
2712 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2716 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2719 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2723 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2725 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2726 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2728 logf("read fail #6");
2732 lseek(masterfd
, loc
, SEEK_SET
);
2735 /* Read entry headers. */
2736 for (j
= 0; j
< idxbuf_pos
; j
++)
2738 if (!TAGCACHE_IS_SORTED(index_type
))
2740 struct temp_file_entry entry
;
2741 struct tagfile_entry fe
;
2743 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2744 sizeof(struct temp_file_entry
))
2746 logf("read fail #7");
2752 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2754 logf("too long entry!");
2755 logf("length=%d", entry
.tag_length
[index_type
]);
2756 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2761 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2762 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2763 entry
.tag_length
[index_type
])
2765 logf("read fail #8");
2766 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2767 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2772 /* Write to index file. */
2773 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2774 fe
.tag_length
= entry
.tag_length
[index_type
];
2775 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2776 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2777 write(fd
, buf
, fe
.tag_length
);
2781 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2782 entry
.tag_length
[index_type
], SEEK_CUR
);
2786 /* Locate the correct entry from the sorted array. */
2787 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2788 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2790 logf("entry not found (%d)", j
);
2798 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2799 index_entry_ec
, tc_stat
.econ
) !=
2800 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2802 logf("tagcache: write fail #4");
2811 /* Finally write the header. */
2812 tch
.magic
= TAGCACHE_MAGIC
;
2813 tch
.entry_count
= tempbufidx
;
2814 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2815 lseek(fd
, 0, SEEK_SET
);
2816 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2818 if (index_type
!= tag_filename
)
2819 h
->datasize
+= tch
.datasize
;
2820 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2832 static bool commit(void)
2834 struct tagcache_header tch
;
2835 struct master_header tcmh
;
2839 #ifdef HAVE_DIRCACHE
2840 bool dircache_buffer_stolen
= false;
2842 bool local_allocation
= false;
2844 logf("committing tagcache");
2849 tmpfd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
2852 logf("nothing to commit");
2857 /* Load the header. */
2858 len
= sizeof(struct tagcache_header
);
2859 rc
= read(tmpfd
, &tch
, len
);
2861 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2863 logf("incorrect header");
2865 remove(TAGCACHE_FILE_TEMP
);
2869 if (tch
.entry_count
== 0)
2871 logf("nothing to commit");
2873 remove(TAGCACHE_FILE_TEMP
);
2877 #ifdef HAVE_EEPROM_SETTINGS
2878 remove(TAGCACHE_STATEFILE
);
2881 /* At first be sure to unload the ramcache! */
2882 #ifdef HAVE_TC_RAMCACHE
2883 tc_stat
.ramcache
= false;
2888 /* Try to steal every buffer we can :) */
2889 if (tempbuf_size
== 0)
2890 local_allocation
= true;
2892 #ifdef HAVE_DIRCACHE
2893 if (tempbuf_size
== 0)
2895 /* Try to steal the dircache buffer. */
2896 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2897 tempbuf_size
&= ~0x03;
2899 if (tempbuf_size
> 0)
2901 dircache_buffer_stolen
= true;
2906 #ifdef HAVE_TC_RAMCACHE
2907 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2909 tempbuf
= (char *)(hdr
+ 1);
2910 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2911 tempbuf_size
&= ~0x03;
2915 /* And finally fail if there are no buffers available. */
2916 if (tempbuf_size
== 0)
2918 logf("delaying commit until next boot");
2919 tc_stat
.commit_delayed
= true;
2925 logf("commit %ld entries...", tch
.entry_count
);
2927 /* Mark DB dirty so it will stay disabled if commit fails. */
2928 current_tcmh
.dirty
= true;
2929 update_master_header();
2931 /* Now create the index files. */
2932 tc_stat
.commit_step
= 0;
2934 tc_stat
.commit_delayed
= false;
2936 for (i
= 0; i
< TAG_COUNT
; i
++)
2940 if (TAGCACHE_IS_NUMERIC(i
))
2943 tc_stat
.commit_step
++;
2944 ret
= build_index(i
, &tch
, tmpfd
);
2948 logf("tagcache failed init");
2950 tc_stat
.commit_delayed
= true;
2952 tc_stat
.commit_step
= 0;
2958 if (!build_numeric_indices(&tch
, tmpfd
))
2960 logf("Failure to commit numeric indices");
2962 tc_stat
.commit_step
= 0;
2968 remove(TAGCACHE_FILE_TEMP
);
2970 tc_stat
.commit_step
= 0;
2972 /* Update the master index headers. */
2973 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2979 tcmh
.tch
.entry_count
+= tch
.entry_count
;
2980 tcmh
.tch
.datasize
= sizeof(struct master_header
)
2981 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
2986 lseek(masterfd
, 0, SEEK_SET
);
2987 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2990 logf("tagcache committed");
2991 tc_stat
.ready
= check_all_headers();
2992 tc_stat
.readyvalid
= true;
2994 if (local_allocation
)
3000 #ifdef HAVE_DIRCACHE
3001 /* Rebuild the dircache, if we stole the buffer. */
3002 if (dircache_buffer_stolen
)
3006 #ifdef HAVE_TC_RAMCACHE
3007 /* Reload tagcache. */
3008 if (tc_stat
.ramcache_allocated
> 0)
3009 tagcache_start_scan();
3017 static void allocate_tempbuf(void)
3019 /* Yeah, malloc would be really nice now :) */
3021 tempbuf_size
= 32*1024*1024;
3022 tempbuf
= malloc(tempbuf_size
);
3024 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
3025 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
3026 audiobuf
+= tempbuf_size
;
3030 static void free_tempbuf(void)
3032 if (tempbuf_size
== 0)
3038 audiobuf
-= tempbuf_size
;
3046 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
3048 struct index_entry idx
;
3053 if (!TAGCACHE_IS_NUMERIC(tag
))
3056 if (!get_index(masterfd
, idx_id
, &idx
, false))
3059 idx
.tag_seek
[tag
] = data
;
3060 idx
.flag
|= FLAG_DIRTYNUM
;
3062 return write_index(masterfd
, idx_id
, &idx
);
3066 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3069 struct master_header myhdr
;
3071 if (tcs
->masterfd
< 0)
3073 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3077 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3081 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
3083 static bool command_queue_is_full(void)
3087 next
= command_queue_widx
+ 1;
3088 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3091 return (next
== command_queue_ridx
);
3094 static void command_queue_sync_callback(void *data
)
3097 struct master_header myhdr
;
3100 mutex_lock(&command_queue_mutex
);
3102 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3105 while (command_queue_ridx
!= command_queue_widx
)
3107 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3109 switch (ce
->command
)
3111 case CMD_UPDATE_MASTER_HEADER
:
3114 update_master_header();
3116 /* Re-open the masterfd. */
3117 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3122 case CMD_UPDATE_NUMERIC
:
3124 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3129 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3130 command_queue_ridx
= 0;
3135 tc_stat
.queue_length
= 0;
3136 mutex_unlock(&command_queue_mutex
);
3139 static void run_command_queue(bool force
)
3141 if (COMMAND_QUEUE_IS_EMPTY
)
3144 if (force
|| command_queue_is_full())
3145 command_queue_sync_callback(NULL
);
3147 register_storage_idle_func(command_queue_sync_callback
);
3150 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3156 mutex_lock(&command_queue_mutex
);
3157 next
= command_queue_widx
+ 1;
3158 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3161 /* Make sure queue is not full. */
3162 if (next
!= command_queue_ridx
)
3164 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3167 ce
->idx_id
= idx_id
;
3171 command_queue_widx
= next
;
3173 tc_stat
.queue_length
++;
3175 mutex_unlock(&command_queue_mutex
);
3179 /* Queue is full, try again later... */
3180 mutex_unlock(&command_queue_mutex
);
3185 long tagcache_increase_serial(void)
3195 old
= current_tcmh
.serial
++;
3196 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3201 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3203 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3205 #endif /* !__PCTOOL__ */
3207 long tagcache_get_serial(void)
3209 return current_tcmh
.serial
;
3212 long tagcache_get_commitid(void)
3214 return current_tcmh
.commitid
;
3217 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3222 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3223 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3225 if (*datastr
== '\0')
3228 if (*datastr
== '"' || *datastr
== '\\')
3231 buf
[i
] = *(datastr
++);
3234 strcpy(&buf
[i
], "\" ");
3236 write(fd
, buf
, i
+ 2);
3243 static bool read_tag(char *dest
, long size
,
3244 const char *src
, const char *tagstr
)
3247 char current_tag
[32];
3249 while (*src
!= '\0')
3251 /* Skip all whitespace */
3259 /* Read in tag name */
3260 while (*src
!= '=' && *src
!= ' ')
3262 current_tag
[pos
] = *src
;
3266 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3269 current_tag
[pos
] = '\0';
3271 /* Read in tag data */
3273 /* Find the start. */
3274 while (*src
!= '"' && *src
!= '\0')
3277 if (*src
== '\0' || *(++src
) == '\0')
3280 /* Read the data. */
3281 for (pos
= 0; pos
< size
; pos
++)
3288 dest
[pos
] = *(src
+1);
3308 if (!strcasecmp(tagstr
, current_tag
))
3315 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3317 struct index_entry idx
;
3318 char tag_data
[TAG_MAXLEN
+32];
3320 long masterfd
= (long)parameters
;
3321 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3329 logf("%d/%s", line_n
, buf
);
3330 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3332 logf("filename missing");
3337 idx_id
= find_index(tag_data
);
3340 logf("entry not found");
3344 if (!get_index(masterfd
, idx_id
, &idx
, false))
3346 logf("failed to retrieve index entry");
3350 /* Stop if tag has already been modified. */
3351 if (idx
.flag
& FLAG_DIRTYNUM
)
3354 logf("import: %s", tag_data
);
3356 idx
.flag
|= FLAG_DIRTYNUM
;
3357 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3361 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3362 tagcache_tag_to_str(import_tags
[i
])))
3367 data
= atoi(tag_data
);
3371 idx
.tag_seek
[import_tags
[i
]] = data
;
3373 if (import_tags
[i
] == tag_lastplayed
&& data
>= current_tcmh
.serial
)
3374 current_tcmh
.serial
= data
+ 1;
3375 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3376 current_tcmh
.commitid
= data
+ 1;
3379 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3382 bool tagcache_import_changelog(void)
3384 struct master_header myhdr
;
3385 struct tagcache_header tch
;
3396 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_RDONLY
);
3399 logf("failure to open changelog");
3403 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3411 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3413 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3414 parse_changelog_line
);
3419 if (filenametag_fd
>= 0)
3421 close(filenametag_fd
);
3422 filenametag_fd
= -1;
3427 update_master_header();
3432 #endif /* !__PCTOOL__ */
3434 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3436 struct master_header myhdr
;
3437 struct index_entry idx
;
3438 char buf
[TAG_MAXLEN
+32];
3446 if (!tagcache_search(tcs
, tag_filename
))
3449 /* Initialize the changelog */
3450 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3453 logf("failure to open changelog");
3457 if (tcs
->masterfd
< 0)
3459 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3464 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3465 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3468 write(clfd
, "## Changelog version 1\n", 23);
3470 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3472 if (ecread_index_entry(tcs
->masterfd
, &idx
) != sizeof(struct index_entry
))
3474 logf("read error #9");
3475 tagcache_search_finish(tcs
);
3480 /* Skip until the entry found has been modified. */
3481 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3484 /* Skip deleted entries too. */
3485 if (idx
.flag
& FLAG_DELETED
)
3488 /* Now retrieve all tags. */
3489 for (j
= 0; j
< TAG_COUNT
; j
++)
3491 if (TAGCACHE_IS_NUMERIC(j
))
3493 snprintf(temp
, sizeof temp
, "%d", (int)idx
.tag_seek
[j
]);
3494 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3499 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3500 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3503 write(clfd
, "\n", 1);
3509 tagcache_search_finish(tcs
);
3514 static bool delete_entry(long idx_id
)
3519 struct index_entry idx
, myidx
;
3520 struct master_header myhdr
;
3521 char buf
[TAG_MAXLEN
+32];
3522 int in_use
[TAG_COUNT
];
3524 logf("delete_entry(): %ld", idx_id
);
3526 #ifdef HAVE_TC_RAMCACHE
3527 /* At first mark the entry removed from ram cache. */
3528 if (tc_stat
.ramcache
)
3529 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3532 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3535 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3536 if (ecread_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3538 logf("delete_entry(): read error");
3542 if (myidx
.flag
& FLAG_DELETED
)
3544 logf("delete_entry(): already deleted!");
3548 myidx
.flag
|= FLAG_DELETED
;
3549 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3550 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3552 logf("delete_entry(): write_error #1");
3556 /* Now check which tags are no longer in use (if any) */
3557 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3560 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3561 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3563 struct index_entry
*idxp
;
3565 #ifdef HAVE_TC_RAMCACHE
3566 /* Use RAM DB if available for greater speed */
3567 if (tc_stat
.ramcache
)
3568 idxp
= &hdr
->indices
[i
];
3572 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
3574 logf("delete_entry(): read error #2");
3580 if (idxp
->flag
& FLAG_DELETED
)
3583 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3585 if (TAGCACHE_IS_NUMERIC(tag
))
3588 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3593 /* Now delete all tags no longer in use. */
3594 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3596 struct tagcache_header tch
;
3597 int oldseek
= myidx
.tag_seek
[tag
];
3599 if (TAGCACHE_IS_NUMERIC(tag
))
3603 * Replace tag seek with a hash value of the field string data.
3604 * That way runtime statistics of moved or altered files can be
3607 #ifdef HAVE_TC_RAMCACHE
3608 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3610 struct tagfile_entry
*tfe
;
3611 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3613 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3614 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3615 myidx
.tag_seek
[tag
] = *seek
;
3620 struct tagfile_entry tfe
;
3622 /* Open the index file, which contains the tag names. */
3623 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3626 /* Skip the header block */
3627 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3628 if (ecread_tagfile_entry(fd
, &tfe
) != sizeof(struct tagfile_entry
))
3630 logf("delete_entry(): read error #3");
3634 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3636 logf("delete_entry(): read error #4");
3640 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3645 logf("in use: %d/%d", tag
, in_use
[tag
]);
3654 #ifdef HAVE_TC_RAMCACHE
3655 /* Delete from ram. */
3656 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3658 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3659 tagentry
->tag_data
[0] = '\0';
3663 /* Open the index file, which contains the tag names. */
3666 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3670 /* Skip the header block */
3671 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3673 /* Debug, print 10 first characters of the tag
3676 logf("TAG:%s", buf);
3677 lseek(fd, -10, SEEK_CUR);
3680 /* Write first data byte in tag as \0 */
3683 /* Now tag data has been removed */
3688 /* Write index entry back into master index. */
3689 lseek(masterfd
, sizeof(struct master_header
) +
3690 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3691 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3693 logf("delete_entry(): write_error #2");
3712 * Returns true if there is an event waiting in the queue
3713 * that requires the current operation to be aborted.
3715 static bool check_event_queue(void)
3717 struct queue_event ev
;
3719 queue_wait_w_tmo(&tagcache_queue
, &ev
, 0);
3724 case SYS_USB_CONNECTED
:
3725 /* Put the event back into the queue. */
3726 queue_post(&tagcache_queue
, ev
.id
, ev
.data
);
3734 #ifdef HAVE_TC_RAMCACHE
3735 static bool allocate_tagcache(void)
3737 struct master_header tcmh
;
3740 /* Load the header. */
3741 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3750 * Now calculate the required cache size plus
3751 * some extra space for alignment fixes.
3753 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3754 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3755 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3756 memset(hdr
, 0, sizeof(struct ramcache_header
));
3757 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3758 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3759 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3764 # ifdef HAVE_EEPROM_SETTINGS
3765 static bool tagcache_dumpload(void)
3767 struct statefile_header shdr
;
3772 fd
= open(TAGCACHE_STATEFILE
, O_RDONLY
);
3775 logf("no tagcache statedump");
3779 /* Check the statefile memory placement */
3780 hdr
= buffer_alloc(0);
3781 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3782 if (rc
!= sizeof(struct statefile_header
)
3783 /* || (long)hdr != (long)shdr.hdr */)
3785 logf("incorrect statefile");
3791 offpos
= (long)hdr
- (long)shdr
.hdr
;
3793 /* Lets allocate real memory and load it */
3794 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3795 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3798 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3800 logf("read failure!");
3805 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3807 /* Now fix the pointers */
3808 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3809 for (i
= 0; i
< TAG_COUNT
; i
++)
3810 hdr
->tags
[i
] += offpos
;
3815 static bool tagcache_dumpsave(void)
3817 struct statefile_header shdr
;
3820 if (!tc_stat
.ramcache
)
3823 fd
= open(TAGCACHE_STATEFILE
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3826 logf("failed to create a statedump");
3830 /* Create the header */
3832 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3833 write(fd
, &shdr
, sizeof(struct statefile_header
));
3835 /* And dump the data too */
3836 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3843 static bool load_tagcache(void)
3845 struct tagcache_header
*tch
;
3846 long bytesleft
= tc_stat
.ramcache_allocated
;
3847 struct index_entry
*idx
;
3852 # ifdef HAVE_DIRCACHE
3853 while (dircache_is_initializing())
3856 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3859 logf("loading tagcache to ram...");
3861 fd
= open(TAGCACHE_FILE_MASTER
, O_RDONLY
);
3864 logf("tagcache open failed");
3868 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3869 != sizeof(struct master_header
)
3870 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3872 logf("incorrect header");
3878 /* Load the master index table. */
3879 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3881 rc
= ecread_index_entry(fd
, idx
);
3882 if (rc
!= sizeof(struct index_entry
))
3884 logf("read error #10");
3889 bytesleft
-= sizeof(struct index_entry
);
3890 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3892 logf("too big tagcache.");
3902 /* Load the tags. */
3904 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3906 struct tagfile_entry
*fe
;
3907 char buf
[TAG_MAXLEN
+32];
3909 if (TAGCACHE_IS_NUMERIC(tag
))
3912 //p = ((void *)p+1);
3913 p
= (char *)((long)p
& ~0x03) + 0x04;
3916 /* Check the header. */
3917 tch
= (struct tagcache_header
*)p
;
3918 p
+= sizeof(struct tagcache_header
);
3920 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3923 for (hdr
->entry_count
[tag
] = 0;
3924 hdr
->entry_count
[tag
] < tch
->entry_count
;
3925 hdr
->entry_count
[tag
]++)
3929 if (do_timed_yield())
3931 /* Abort if we got a critical event in queue */
3932 if (check_event_queue())
3936 fe
= (struct tagfile_entry
*)p
;
3937 pos
= lseek(fd
, 0, SEEK_CUR
);
3938 rc
= ecread_tagfile_entry(fd
, fe
);
3939 if (rc
!= sizeof(struct tagfile_entry
))
3941 /* End of lookup table. */
3942 logf("read error #11");
3947 /* We have a special handling for the filename tags. */
3948 if (tag
== tag_filename
)
3950 # ifdef HAVE_DIRCACHE
3951 const struct dircache_entry
*dc
;
3954 // FIXME: This is wrong!
3955 // idx = &hdr->indices[hdr->entry_count[i]];
3956 idx
= &hdr
->indices
[fe
->idx_id
];
3958 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
3962 logf("TAG:%s", buf
);
3963 logf("too long filename");
3968 rc
= read(fd
, buf
, fe
->tag_length
);
3969 if (rc
!= fe
->tag_length
)
3971 logf("read error #12");
3976 /* Check if the entry has already been removed */
3977 if (idx
->flag
& FLAG_DELETED
)
3980 /* This flag must not be used yet. */
3981 if (idx
->flag
& FLAG_DIRCACHE
)
3983 logf("internal error!");
3988 if (idx
->tag_seek
[tag
] != pos
)
3990 logf("corrupt data structures!");
3995 # ifdef HAVE_DIRCACHE
3996 if (dircache_is_enabled())
3998 dc
= dircache_get_entry_ptr(buf
);
4001 logf("Entry no longer valid.");
4003 if (global_settings
.tagcache_autoupdate
)
4004 delete_entry(fe
->idx_id
);
4008 idx
->flag
|= FLAG_DIRCACHE
;
4009 idx
->tag_seek
[tag_filename
] = (long)dc
;
4014 /* This will be very slow unless dircache is enabled
4015 or target is flash based, but do it anyway for
4017 /* Check if entry has been removed. */
4018 if (global_settings
.tagcache_autoupdate
)
4020 if (!file_exists(buf
))
4022 logf("Entry no longer valid.");
4024 delete_entry(fe
->idx_id
);
4033 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
4036 logf("too big tagcache #2");
4037 logf("tl: %ld", fe
->tag_length
);
4038 logf("bl: %ld", bytesleft
);
4044 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
4047 if (rc
!= fe
->tag_length
)
4049 logf("read error #13");
4050 logf("rc=0x%04x", rc
); // 0x431
4051 logf("len=0x%04lx", fe
->tag_length
); // 0x4000
4052 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
4053 logf("tag=0x%02x", tag
); // 0x00
4061 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4062 logf("tagcache loaded into ram!");
4066 #endif /* HAVE_TC_RAMCACHE */
4068 static bool check_deleted_files(void)
4071 char buf
[TAG_MAXLEN
+32];
4072 struct tagfile_entry tfe
;
4074 logf("reverse scan...");
4075 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4076 fd
= open(buf
, O_RDONLY
);
4080 logf("%s open fail", buf
);
4084 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4085 while (ecread_tagfile_entry(fd
, &tfe
) == sizeof(struct tagfile_entry
)
4087 && !check_event_queue()
4091 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4093 logf("too long tag");
4098 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4100 logf("read error #14");
4105 /* Check if the file has already deleted from the db. */
4109 /* Now check if the file exists. */
4110 if (!file_exists(buf
))
4112 logf("Entry no longer valid.");
4113 logf("-> %s / %ld", buf
, tfe
.tag_length
);
4114 delete_entry(tfe
.idx_id
);
4126 /* Note that this function must not be inlined, otherwise the whole point
4127 * of having the code in a separate function is lost.
4129 static void __attribute__ ((noinline
)) check_ignore(const char *dirname
,
4130 int *ignore
, int *unignore
)
4132 char newpath
[MAX_PATH
];
4134 /* check for a database.ignore file */
4135 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4136 *ignore
= file_exists(newpath
);
4137 /* check for a database.unignore file */
4138 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4139 *unignore
= file_exists(newpath
);
4143 static bool check_dir(const char *dirname
, int add_files
)
4147 int success
= false;
4148 int ignore
, unignore
;
4150 dir
= opendir(dirname
);
4153 logf("tagcache: opendir(%s) failed", dirname
);
4157 /* check for a database.ignore and database.unignore */
4158 check_ignore(dirname
, &ignore
, &unignore
);
4160 /* don't do anything if both ignore and unignore are there */
4161 if (ignore
!= unignore
)
4162 add_files
= unignore
;
4164 /* Recursively scan the dir. */
4168 while (!check_event_queue())
4171 struct dirent
*entry
;
4173 entry
= readdir(dir
);
4181 if (!strcmp((char *)entry
->d_name
, ".") ||
4182 !strcmp((char *)entry
->d_name
, ".."))
4187 len
= strlen(curpath
);
4188 snprintf(&curpath
[len
], sizeof(curpath
) - len
, "/%s",
4191 processed_dir_count
++;
4192 if (entry
->attribute
& ATTR_DIRECTORY
)
4193 check_dir(curpath
, add_files
);
4196 tc_stat
.curentry
= curpath
;
4198 /* Add a new entry to the temporary db file. */
4199 add_tagcache(curpath
, (entry
->wrtdate
<< 16) | entry
->wrttime
4200 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4201 , dir
->internal_entry
4205 /* Wait until current path for debug screen is read and unset. */
4206 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4209 tc_stat
.curentry
= NULL
;
4212 curpath
[len
] = '\0';
4220 void tagcache_screensync_event(void)
4222 tc_stat
.curentry
= NULL
;
4225 void tagcache_screensync_enable(bool state
)
4227 tc_stat
.syncscreen
= state
;
4230 void tagcache_build(const char *path
)
4232 struct tagcache_header header
;
4237 total_entry_count
= 0;
4238 processed_dir_count
= 0;
4240 #ifdef HAVE_DIRCACHE
4241 while (dircache_is_initializing())
4245 logf("updating tagcache");
4247 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
4250 logf("skipping, cache already waiting for commit");
4255 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDWR
| O_CREAT
| O_TRUNC
, 0666);
4258 logf("master file open failed: %s", TAGCACHE_FILE_TEMP
);
4262 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4266 logf("Scanning files...");
4267 /* Scan for new files. */
4268 memset(&header
, 0, sizeof(struct tagcache_header
));
4269 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4271 if (strcmp("/", path
) != 0)
4272 strcpy(curpath
, path
);
4273 ret
= check_dir(path
, true);
4275 /* Write the header. */
4276 header
.magic
= TAGCACHE_MAGIC
;
4277 header
.datasize
= data_size
;
4278 header
.entry_count
= total_entry_count
;
4279 lseek(cachefd
, 0, SEEK_SET
);
4280 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4283 if (filenametag_fd
>= 0)
4285 close(filenametag_fd
);
4286 filenametag_fd
= -1;
4296 /* Commit changes to the database. */
4302 remove(TAGCACHE_FILE_TEMP
);
4303 logf("tagcache built!");
4309 #ifdef HAVE_TC_RAMCACHE
4312 /* Import runtime statistics if we just initialized the db. */
4313 if (hdr
->h
.serial
== 0)
4314 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4321 #ifdef HAVE_TC_RAMCACHE
4322 static void load_ramcache(void)
4329 /* At first we should load the cache (if exists). */
4330 tc_stat
.ramcache
= load_tagcache();
4332 if (!tc_stat
.ramcache
)
4334 /* If loading failed, it must indicate some problem with the db
4335 * so disable it entirely to prevent further issues. */
4336 tc_stat
.ready
= false;
4343 void tagcache_unload_ramcache(void)
4345 tc_stat
.ramcache
= false;
4346 /* Just to make sure there is no statefile present. */
4347 // remove(TAGCACHE_STATEFILE);
4352 static void tagcache_thread(void)
4354 struct queue_event ev
;
4355 bool check_done
= false;
4357 /* If the previous cache build/update was interrupted, commit
4358 * the changes first in foreground. */
4364 #ifdef HAVE_TC_RAMCACHE
4365 # ifdef HAVE_EEPROM_SETTINGS
4366 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
)
4367 check_done
= tagcache_dumpload();
4369 remove(TAGCACHE_STATEFILE
);
4372 /* Allocate space for the tagcache if found on disk. */
4373 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4374 allocate_tagcache();
4378 tc_stat
.initialized
= true;
4380 /* Don't delay bootup with the header check but do it on background. */
4382 tc_stat
.ready
= check_all_headers();
4383 tc_stat
.readyvalid
= true;
4387 run_command_queue(false);
4389 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4393 case Q_IMPORT_CHANGELOG
:
4394 tagcache_import_changelog();
4399 remove(TAGCACHE_FILE_TEMP
);
4400 tagcache_build("/");
4404 tagcache_build("/");
4405 #ifdef HAVE_TC_RAMCACHE
4408 check_deleted_files();
4414 if (check_done
|| !tc_stat
.ready
)
4417 #ifdef HAVE_TC_RAMCACHE
4418 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4421 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4422 tagcache_build("/");
4426 if (global_settings
.tagcache_autoupdate
)
4428 tagcache_build("/");
4430 /* This will be very slow unless dircache is enabled
4431 or target is flash based, but do it anyway for
4433 check_deleted_files();
4436 logf("tagcache check done");
4448 case SYS_USB_CONNECTED
:
4449 logf("USB: TagCache");
4450 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4451 usb_wait_for_disconnect(&tagcache_queue
);
4458 bool tagcache_prepare_shutdown(void)
4460 if (tagcache_get_commit_step() > 0)
4463 tagcache_stop_scan();
4464 while (read_lock
|| write_lock
)
4470 void tagcache_shutdown(void)
4472 /* Flush the command queue. */
4473 run_command_queue(true);
4475 #ifdef HAVE_EEPROM_SETTINGS
4476 if (tc_stat
.ramcache
)
4477 tagcache_dumpsave();
4481 static int get_progress(void)
4483 int total_count
= -1;
4485 #ifdef HAVE_DIRCACHE
4486 if (dircache_is_enabled())
4488 total_count
= dircache_get_entry_count();
4492 #ifdef HAVE_TC_RAMCACHE
4494 if (hdr
&& tc_stat
.ramcache
)
4495 total_count
= hdr
->h
.tch
.entry_count
;
4499 if (total_count
< 0)
4502 return processed_dir_count
* 100 / total_count
;
4505 struct tagcache_stat
* tagcache_get_stat(void)
4507 tc_stat
.progress
= get_progress();
4508 tc_stat
.processed_entries
= processed_dir_count
;
4513 void tagcache_start_scan(void)
4515 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4518 bool tagcache_update(void)
4523 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4527 bool tagcache_rebuild()
4529 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4533 void tagcache_stop_scan(void)
4535 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4538 #ifdef HAVE_TC_RAMCACHE
4539 bool tagcache_is_ramcache(void)
4541 return tc_stat
.ramcache
;
4545 #endif /* !__PCTOOL__ */
4548 void tagcache_init(void)
4550 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4551 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4552 filenametag_fd
= -1;
4553 write_lock
= read_lock
= 0;
4556 mutex_init(&command_queue_mutex
);
4557 queue_init(&tagcache_queue
, true);
4558 create_thread(tagcache_thread
, tagcache_stack
,
4559 sizeof(tagcache_stack
), 0, tagcache_thread_name
4560 IF_PRIO(, PRIORITY_BACKGROUND
)
4563 tc_stat
.initialized
= true;
4567 tc_stat
.ready
= check_all_headers();
4572 void tagcache_reverse_scan(void)
4574 logf("Checking for deleted files");
4575 check_deleted_files();
4579 bool tagcache_is_initialized(void)
4581 return tc_stat
.initialized
;
4583 bool tagcache_is_usable(void)
4585 return tc_stat
.initialized
&& tc_stat
.ready
;
4587 int tagcache_get_commit_step(void)
4589 return tc_stat
.commit_step
;
4591 int tagcache_get_max_commit_step(void)
4593 return (int)(SORTED_TAGS_COUNT
)+1;