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 <unistd.h> /* readlink() */
65 #include <limits.h> /* PATH_MAX */
68 #include "ata_idle_notify.h"
73 #include "string-extra.h"
82 #include "filefuncs.h"
88 #include "eeprom_settings.h"
92 #define yield() do { } while(0)
93 #define sim_sleep(timeout) do { } while(0)
94 #define do_timed_yield() do { } while(0)
98 /* Tag Cache thread. */
99 static struct event_queue tagcache_queue SHAREDBSS_ATTR
;
100 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
101 static const char tagcache_thread_name
[] = "tagcache";
104 /* Previous path when scanning directory tree recursively. */
105 static char curpath
[TAG_MAXLEN
+32];
107 /* Used when removing duplicates. */
108 static char *tempbuf
; /* Allocated when needed. */
109 static long tempbufidx
; /* Current location in buffer. */
110 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
111 static long tempbuf_left
; /* Buffer space left. */
112 static long tempbuf_pos
;
114 #define SORTED_TAGS_COUNT 8
115 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
116 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
117 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
118 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
119 /* Tags we want to get sorted (loaded to the tempbuf). */
120 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
121 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
122 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
124 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
125 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
126 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
127 (1LU << tag_albumartist) | (1LU << tag_grouping))
129 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
130 static const char *tags_str
[] = { "artist", "album", "genre", "title",
131 "filename", "composer", "comment", "albumartist", "grouping", "year",
132 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
133 "playtime", "lastplayed", "commitid", "mtime", "lastoffset" };
135 /* Status information of the tagcache. */
136 static struct tagcache_stat tc_stat
;
138 /* Queue commands. */
139 enum tagcache_queue
{
146 /* Internal tagcache command queue. */
147 CMD_UPDATE_MASTER_HEADER
,
151 struct tagcache_command_entry
{
159 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
160 static volatile int command_queue_widx
= 0;
161 static volatile int command_queue_ridx
= 0;
162 static struct mutex command_queue_mutex SHAREDBSS_ATTR
;
165 /* Tag database structures. */
167 /* Variable-length tag entry in tag files. */
168 struct tagfile_entry
{
169 int32_t tag_length
; /* Length of the data in bytes including '\0' */
170 int32_t idx_id
; /* Corresponding entry location in index file of not unique tags */
171 char tag_data
[0]; /* Begin of the tag data */
174 /* Fixed-size tag entry in master db index. */
176 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
177 int32_t flag
; /* Status flags */
180 /* Header is the same in every file. */
181 struct tagcache_header
{
182 int32_t magic
; /* Header version number */
183 int32_t datasize
; /* Data size in bytes */
184 int32_t entry_count
; /* Number of entries in this file */
187 struct master_header
{
188 struct tagcache_header tch
;
189 int32_t serial
; /* Increasing counting number */
190 int32_t commitid
; /* Number of commits so far */
194 /* For the endianess correction */
195 static const char *tagfile_entry_ec
= "ll";
197 Note: This should be (1 + TAG_COUNT) amount of l's.
199 static const char *index_entry_ec
= "llllllllllllllllllllll";
201 static const char *tagcache_header_ec
= "lll";
202 static const char *master_header_ec
= "llllll";
204 static struct master_header current_tcmh
;
206 #ifdef HAVE_TC_RAMCACHE
207 /* Header is created when loading database to ram. */
208 struct ramcache_header
{
209 struct master_header h
; /* Header from the master index */
210 struct index_entry
*indices
; /* Master index file content */
211 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
212 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
215 # ifdef HAVE_EEPROM_SETTINGS
216 struct statefile_header
{
217 struct ramcache_header
*hdr
;
218 struct tagcache_stat tc_stat
;
222 /* Pointer to allocated ramcache_header */
223 static struct ramcache_header
*hdr
;
227 * Full tag entries stored in a temporary file waiting
228 * for commit to the cache. */
229 struct temp_file_entry
{
230 long tag_offset
[TAG_COUNT
];
231 short tag_length
[TAG_COUNT
];
237 struct tempbuf_id_list
{
239 struct tempbuf_id_list
*next
;
242 struct tempbuf_searchidx
{
246 struct tempbuf_id_list idlist
;
249 /* Lookup buffer for fixing messed up index while after sorting. */
250 static long commit_entry_count
;
251 static long lookup_buffer_depth
;
252 static struct tempbuf_searchidx
**lookup
;
254 /* Used when building the temporary file. */
255 static int cachefd
= -1, filenametag_fd
;
256 static int total_entry_count
= 0;
257 static int data_size
= 0;
258 static int processed_dir_count
;
260 /* Thread safe locking */
261 static volatile int write_lock
;
262 static volatile int read_lock
;
264 static bool delete_entry(long idx_id
);
266 const char* tagcache_tag_to_str(int tag
)
268 return tags_str
[tag
];
271 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
272 static ssize_t
ecread_tagfile_entry(int fd
, struct tagfile_entry
*buf
)
274 return ecread(fd
, buf
, 1, tagfile_entry_ec
, tc_stat
.econ
);
277 static ssize_t
ecread_index_entry(int fd
, struct index_entry
*buf
)
279 return ecread(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
282 static ssize_t
ecwrite_index_entry(int fd
, struct index_entry
*buf
)
284 return ecwrite(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
289 * Returns true if specified flag is still present, i.e., dircache
290 * has not been reloaded.
292 static bool is_dircache_intact(void)
294 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
298 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
304 if (TAGCACHE_IS_NUMERIC(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
307 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
309 fd
= open(buf
, write
? O_RDWR
: O_RDONLY
);
312 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
313 tc_stat
.ready
= false;
317 /* Check the header. */
318 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
319 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
321 logf("header error");
322 tc_stat
.ready
= false;
330 static int open_master_fd(struct master_header
*hdr
, bool write
)
335 fd
= open(TAGCACHE_FILE_MASTER
, write
? O_RDWR
: O_RDONLY
);
338 logf("master file open failed for R/W");
339 tc_stat
.ready
= false;
343 tc_stat
.econ
= false;
345 /* Check the header. */
346 rc
= read(fd
, hdr
, sizeof(struct master_header
));
347 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
353 /* Trying to read again, this time with endianess correction enabled. */
354 lseek(fd
, 0, SEEK_SET
);
356 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
357 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
359 logf("header error");
360 tc_stat
.ready
= false;
371 static bool do_timed_yield(void)
373 /* Sorting can lock up for quite a while, so yield occasionally */
374 static long wakeup_tick
= 0;
375 if (TIME_AFTER(current_tick
, wakeup_tick
))
377 wakeup_tick
= current_tick
+ (HZ
/4);
385 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
386 static long find_entry_ram(const char *filename
,
387 const struct dircache_entry
*dc
)
389 static long last_pos
= 0;
392 /* Check if tagcache is loaded into ram. */
393 if (!tc_stat
.ramcache
)
397 dc
= dircache_get_entry_ptr(filename
);
401 logf("tagcache: file not found.");
412 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
414 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
416 last_pos
= MAX(0, i
- 3);
433 static long find_entry_disk(const char *filename_raw
, bool localfd
)
435 struct tagcache_header tch
;
436 static long last_pos
= -1;
437 long pos_history
[POS_HISTORY_COUNT
];
438 long pos_history_idx
= 0;
440 struct tagfile_entry tfe
;
442 char buf
[TAG_MAXLEN
+32];
446 const char *filename
= filename_raw
;
448 char pathbuf
[PATH_MAX
]; /* Note: Don't use MAX_PATH here, it's too small */
449 if (realpath(filename
, pathbuf
) == pathbuf
)
457 if (fd
< 0 || localfd
)
460 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
467 lseek(fd
, last_pos
, SEEK_SET
);
469 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
473 pos
= lseek(fd
, 0, SEEK_CUR
);
474 for (i
= pos_history_idx
-1; i
>= 0; i
--)
475 pos_history
[i
+1] = pos_history
[i
];
476 pos_history
[0] = pos
;
478 if (ecread_tagfile_entry(fd
, &tfe
)
479 != sizeof(struct tagfile_entry
))
484 if (tfe
.tag_length
>= (long)sizeof(buf
))
486 logf("too long tag #1");
494 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
496 logf("read error #2");
504 if (!strcasecmp(filename
, buf
))
506 last_pos
= pos_history
[pos_history_idx
];
511 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
525 if (fd
!= filenametag_fd
|| localfd
)
530 if (fd
!= filenametag_fd
|| localfd
)
536 static int find_index(const char *filename
)
540 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
541 if (tc_stat
.ramcache
&& is_dircache_intact())
542 idx_id
= find_entry_ram(filename
, NULL
);
546 idx_id
= find_entry_disk(filename
, true);
551 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
558 idx_id
= find_index(filename
);
562 if (!tagcache_search(tcs
, tag_filename
))
565 tcs
->entry_count
= 0;
566 tcs
->idx_id
= idx_id
;
571 static bool get_index(int masterfd
, int idxid
,
572 struct index_entry
*idx
, bool use_ram
)
574 bool localfd
= false;
578 logf("Incorrect idxid: %d", idxid
);
582 #ifdef HAVE_TC_RAMCACHE
583 if (tc_stat
.ramcache
&& use_ram
)
585 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
588 # ifdef HAVE_DIRCACHE
589 if (!(hdr
->indices
[idxid
].flag
& FLAG_DIRCACHE
)
590 || is_dircache_intact())
593 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
603 struct master_header tcmh
;
606 masterfd
= open_master_fd(&tcmh
, false);
611 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
612 + sizeof(struct master_header
), SEEK_SET
);
613 if (ecread_index_entry(masterfd
, idx
)
614 != sizeof(struct index_entry
))
616 logf("read error #3");
626 if (idx
->flag
& FLAG_DELETED
)
634 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
636 /* We need to exclude all memory only flags & tags when writing to disk. */
637 if (idx
->flag
& FLAG_DIRCACHE
)
639 logf("memory only flags!");
643 #ifdef HAVE_TC_RAMCACHE
644 /* Only update numeric data. Writing the whole index to RAM by memcpy
645 * destroys dircache pointers!
647 if (tc_stat
.ramcache
)
650 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
652 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
654 if (TAGCACHE_IS_NUMERIC(tag
))
656 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
660 /* Don't touch the dircache flag or attributes. */
661 idx_ram
->flag
= (idx
->flag
& 0x0000ffff)
662 | (idx_ram
->flag
& (0xffff0000 | FLAG_DIRCACHE
));
666 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
667 + sizeof(struct master_header
), SEEK_SET
);
668 if (ecwrite_index_entry(masterfd
, idx
) != sizeof(struct index_entry
))
670 logf("write error #3");
671 logf("idxid: %d", idxid
);
678 #endif /* !__PCTOOL__ */
680 static bool open_files(struct tagcache_search
*tcs
, int tag
)
682 if (tcs
->idxfd
[tag
] < 0)
686 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
687 tcs
->idxfd
[tag
] = open(fn
, O_RDONLY
);
690 if (tcs
->idxfd
[tag
] < 0)
692 logf("File not open!");
699 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
700 int tag
, char *buf
, long size
)
702 struct tagfile_entry tfe
;
707 if (TAGCACHE_IS_NUMERIC(tag
))
710 seek
= idx
->tag_seek
[tag
];
713 logf("Retrieve failed");
717 #ifdef HAVE_TC_RAMCACHE
720 struct tagfile_entry
*ep
;
722 # ifdef HAVE_DIRCACHE
723 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
724 && is_dircache_intact())
726 dircache_copy_path((struct dircache_entry
*)seek
,
732 if (tag
!= tag_filename
)
734 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
735 strlcpy(buf
, ep
->tag_data
, size
);
742 if (!open_files(tcs
, tag
))
745 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
746 if (ecread_tagfile_entry(tcs
->idxfd
[tag
], &tfe
)
747 != sizeof(struct tagfile_entry
))
749 logf("read error #5");
753 if (tfe
.tag_length
>= size
)
755 logf("too small buffer");
759 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
762 logf("read error #6");
766 buf
[tfe
.tag_length
] = '\0';
771 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
773 static long read_numeric_tag(int tag
, int idx_id
, const struct index_entry
*idx
)
776 if (! COMMAND_QUEUE_IS_EMPTY
)
778 /* Attempt to find tag data through store-to-load forwarding in
782 mutex_lock(&command_queue_mutex
);
784 int ridx
= command_queue_widx
;
786 while (ridx
!= command_queue_ridx
)
789 ridx
= TAGCACHE_COMMAND_QUEUE_LENGTH
- 1;
791 if (command_queue
[ridx
].command
== CMD_UPDATE_NUMERIC
792 && command_queue
[ridx
].idx_id
== idx_id
793 && command_queue
[ridx
].tag
== tag
)
795 result
= command_queue
[ridx
].data
;
800 mutex_unlock(&command_queue_mutex
);
804 logf("read_numeric_tag: "
805 "Recovered tag %d value %lX from write queue",
812 return idx
->tag_seek
[tag
];
816 static long check_virtual_tags(int tag
, int idx_id
,
817 const struct index_entry
*idx
)
823 case tag_virt_length_sec
:
824 data
= (read_numeric_tag(tag_length
, idx_id
, idx
)/1000) % 60;
827 case tag_virt_length_min
:
828 data
= (read_numeric_tag(tag_length
, idx_id
, idx
)/1000) / 60;
831 case tag_virt_playtime_sec
:
832 data
= (read_numeric_tag(tag_playtime
, idx_id
, idx
)/1000) % 60;
835 case tag_virt_playtime_min
:
836 data
= (read_numeric_tag(tag_playtime
, idx_id
, idx
)/1000) / 60;
839 case tag_virt_autoscore
:
840 if (read_numeric_tag(tag_length
, idx_id
, idx
) == 0
841 || read_numeric_tag(tag_playcount
, idx_id
, idx
) == 0)
847 /* A straight calculus gives:
848 autoscore = 100 * playtime / length / playcout (1)
849 Now, consider the euclidian division of playtime by length:
850 playtime = alpha * length + beta
854 autoscore = 100 * (alpha / playcout + beta / length / playcount)
855 Both terms should be small enough to avoid any overflow
857 data
= 100 * (read_numeric_tag(tag_playtime
, idx_id
, idx
)
858 / read_numeric_tag(tag_length
, idx_id
, idx
))
859 + (100 * (read_numeric_tag(tag_playtime
, idx_id
, idx
)
860 % read_numeric_tag(tag_length
, idx_id
, idx
)))
861 / read_numeric_tag(tag_length
, idx_id
, idx
);
862 data
/= read_numeric_tag(tag_playcount
, idx_id
, idx
);
866 /* How many commits before the file has been added to the DB. */
867 case tag_virt_entryage
:
868 data
= current_tcmh
.commitid
869 - read_numeric_tag(tag_commitid
, idx_id
, idx
) - 1;
873 data
= read_numeric_tag(tag
, idx_id
, idx
);
879 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
881 struct index_entry idx
;
886 if (!TAGCACHE_IS_NUMERIC(tag
))
889 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
892 return check_virtual_tags(tag
, tcs
->idx_id
, &idx
);
895 inline static bool str_ends_with(const char *str1
, const char *str2
)
897 int str_len
= strlen(str1
);
898 int clause_len
= strlen(str2
);
900 if (clause_len
> str_len
)
903 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
906 inline static bool str_oneof(const char *str
, const char *list
)
909 int l
, len
= strlen(str
);
913 sep
= strchr(list
, '|');
914 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
915 if ((l
==len
) && !strncasecmp(str
, list
, len
))
917 list
+= sep
? l
+ 1 : l
;
923 static bool check_against_clause(long numeric
, const char *str
,
924 const struct tagcache_search_clause
*clause
)
928 switch (clause
->type
)
931 return numeric
== clause
->numeric_data
;
933 return numeric
!= clause
->numeric_data
;
935 return numeric
> clause
->numeric_data
;
937 return numeric
>= clause
->numeric_data
;
939 return numeric
< clause
->numeric_data
;
941 return numeric
<= clause
->numeric_data
;
943 logf("Incorrect numeric tag: %d", clause
->type
);
948 switch (clause
->type
)
951 return !strcasecmp(clause
->str
, str
);
953 return strcasecmp(clause
->str
, str
);
955 return 0>strcasecmp(clause
->str
, str
);
957 return 0>=strcasecmp(clause
->str
, str
);
959 return 0<strcasecmp(clause
->str
, str
);
961 return 0<=strcasecmp(clause
->str
, str
);
962 case clause_contains
:
963 return (strcasestr(str
, clause
->str
) != NULL
);
964 case clause_not_contains
:
965 return (strcasestr(str
, clause
->str
) == NULL
);
966 case clause_begins_with
:
967 return (strcasestr(str
, clause
->str
) == str
);
968 case clause_not_begins_with
:
969 return (strcasestr(str
, clause
->str
) != str
);
970 case clause_ends_with
:
971 return str_ends_with(str
, clause
->str
);
972 case clause_not_ends_with
:
973 return !str_ends_with(str
, clause
->str
);
975 return str_oneof(str
, clause
->str
);
978 logf("Incorrect tag: %d", clause
->type
);
985 static bool check_clauses(struct tagcache_search
*tcs
,
986 struct index_entry
*idx
,
987 struct tagcache_search_clause
**clause
, int count
)
991 #ifdef HAVE_TC_RAMCACHE
994 /* Go through all conditional clauses. */
995 for (i
= 0; i
< count
; i
++)
997 struct tagfile_entry
*tfe
;
1002 seek
= check_virtual_tags(clause
[i
]->tag
, tcs
->idx_id
, idx
);
1004 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
1006 if (clause
[i
]->tag
== tag_filename
)
1008 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
1013 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
1014 str
= tfe
->tag_data
;
1018 if (!check_against_clause(seek
, str
, clause
[i
]))
1025 /* Check for conditions. */
1026 for (i
= 0; i
< count
; i
++)
1028 struct tagfile_entry tfe
;
1032 seek
= check_virtual_tags(clause
[i
]->tag
, tcs
->idx_id
, idx
);
1034 memset(str
, 0, sizeof str
);
1035 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
1037 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
1038 lseek(fd
, seek
, SEEK_SET
);
1039 ecread_tagfile_entry(fd
, &tfe
);
1040 if (tfe
.tag_length
>= (int)sizeof(str
))
1042 logf("Too long tag read!");
1046 read(fd
, str
, tfe
.tag_length
);
1048 /* Check if entry has been deleted. */
1053 if (!check_against_clause(seek
, str
, clause
[i
]))
1061 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
1062 struct tagcache_search_clause
**clause
, int count
)
1064 struct index_entry idx
;
1069 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
1072 return check_clauses(tcs
, &idx
, clause
, count
);
1075 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1079 /* If uniq buffer is not defined we must return true for search to work. */
1080 if (tcs
->unique_list
== NULL
|| (!TAGCACHE_IS_UNIQUE(tcs
->type
)
1081 && !TAGCACHE_IS_NUMERIC(tcs
->type
)))
1086 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1088 /* Return false if entry is found. */
1089 if (tcs
->unique_list
[i
] == id
)
1093 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1095 tcs
->unique_list
[i
] = id
;
1096 tcs
->unique_list_count
++;
1102 static bool build_lookup_list(struct tagcache_search
*tcs
)
1104 struct index_entry entry
;
1107 tcs
->seek_list_count
= 0;
1109 #ifdef HAVE_TC_RAMCACHE
1111 # ifdef HAVE_DIRCACHE
1112 && (tcs
->type
!= tag_filename
|| is_dircache_intact())
1116 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
1118 struct tagcache_seeklist_entry
*seeklist
;
1119 struct index_entry
*idx
= &hdr
->indices
[i
];
1120 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1123 /* Skip deleted files. */
1124 if (idx
->flag
& FLAG_DELETED
)
1127 /* Go through all filters.. */
1128 for (j
= 0; j
< tcs
->filter_count
; j
++)
1130 if (idx
->tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1136 if (j
< tcs
->filter_count
)
1139 /* Check for conditions. */
1140 if (!check_clauses(tcs
, idx
, tcs
->clause
, tcs
->clause_count
))
1143 /* Add to the seek list if not already in uniq buffer. */
1144 if (!add_uniqbuf(tcs
, idx
->tag_seek
[tcs
->type
]))
1148 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1149 seeklist
->seek
= idx
->tag_seek
[tcs
->type
];
1150 seeklist
->flag
= idx
->flag
;
1151 seeklist
->idx_id
= i
;
1152 tcs
->seek_list_count
++;
1157 return tcs
->seek_list_count
> 0;
1161 if (tcs
->masterfd
< 0)
1163 struct master_header tcmh
;
1164 tcs
->masterfd
= open_master_fd(&tcmh
, false);
1167 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1168 sizeof(struct master_header
), SEEK_SET
);
1170 while (ecread_index_entry(tcs
->masterfd
, &entry
)
1171 == sizeof(struct index_entry
))
1173 struct tagcache_seeklist_entry
*seeklist
;
1175 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1181 /* Check if entry has been deleted. */
1182 if (entry
.flag
& FLAG_DELETED
)
1185 /* Go through all filters.. */
1186 for (j
= 0; j
< tcs
->filter_count
; j
++)
1188 if (entry
.tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1192 if (j
< tcs
->filter_count
)
1195 /* Check for conditions. */
1196 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1199 /* Add to the seek list if not already in uniq buffer. */
1200 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1204 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1205 seeklist
->seek
= entry
.tag_seek
[tcs
->type
];
1206 seeklist
->flag
= entry
.flag
;
1207 seeklist
->idx_id
= i
;
1208 tcs
->seek_list_count
++;
1213 return tcs
->seek_list_count
> 0;
1217 static void remove_files(void)
1222 tc_stat
.ready
= false;
1223 tc_stat
.ramcache
= false;
1224 tc_stat
.econ
= false;
1225 remove(TAGCACHE_FILE_MASTER
);
1226 for (i
= 0; i
< TAG_COUNT
; i
++)
1228 if (TAGCACHE_IS_NUMERIC(i
))
1231 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1237 static bool check_all_headers(void)
1239 struct master_header myhdr
;
1240 struct tagcache_header tch
;
1244 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1250 logf("tagcache is dirty!");
1254 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1256 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1258 if (TAGCACHE_IS_NUMERIC(tag
))
1261 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1270 bool tagcache_is_busy(void)
1272 return read_lock
|| write_lock
;
1275 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1277 struct tagcache_header tag_hdr
;
1278 struct master_header master_hdr
;
1284 memset(tcs
, 0, sizeof(struct tagcache_search
));
1285 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1288 tcs
->position
= sizeof(struct tagcache_header
);
1291 tcs
->list_position
= 0;
1292 tcs
->seek_list_count
= 0;
1293 tcs
->filter_count
= 0;
1296 for (i
= 0; i
< TAG_COUNT
; i
++)
1299 #ifndef HAVE_TC_RAMCACHE
1300 tcs
->ramsearch
= false;
1302 tcs
->ramsearch
= tc_stat
.ramcache
;
1305 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1310 /* Always open as R/W so we can pass tcs to functions that modify data also
1311 * without failing. */
1312 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1313 if (tcs
->masterfd
< 0)
1316 if (!TAGCACHE_IS_NUMERIC(tcs
->type
))
1318 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1319 if (tcs
->idxfd
[tcs
->type
] < 0)
1322 tcs
->entry_count
= tag_hdr
.entry_count
;
1326 tcs
->entry_count
= master_hdr
.tch
.entry_count
;
1331 tcs
->initialized
= true;
1337 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1338 void *buffer
, long length
)
1340 tcs
->unique_list
= (unsigned long *)buffer
;
1341 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1342 tcs
->unique_list_count
= 0;
1345 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1348 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1351 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag
))
1354 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1355 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1356 tcs
->filter_count
++;
1361 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1362 struct tagcache_search_clause
*clause
)
1366 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1368 logf("Too many clauses");
1372 /* Check if there is already a similar filter in present (filters are
1373 * much faster than clauses).
1375 for (i
= 0; i
< tcs
->filter_count
; i
++)
1377 if (tcs
->filter_tag
[i
] == clause
->tag
)
1381 if (!TAGCACHE_IS_NUMERIC(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1385 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1386 tcs
->idxfd
[clause
->tag
] = open(buf
, O_RDONLY
);
1389 tcs
->clause
[tcs
->clause_count
] = clause
;
1390 tcs
->clause_count
++;
1395 static bool get_next(struct tagcache_search
*tcs
)
1397 static char buf
[TAG_MAXLEN
+32];
1398 struct tagfile_entry entry
;
1401 if (!tcs
->valid
|| !tc_stat
.ready
)
1404 if (tcs
->idxfd
[tcs
->type
] < 0 && !TAGCACHE_IS_NUMERIC(tcs
->type
)
1405 #ifdef HAVE_TC_RAMCACHE
1411 /* Relative fetch. */
1412 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1413 || TAGCACHE_IS_NUMERIC(tcs
->type
)
1414 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1415 /* We need to retrieve flag status for dircache. */
1416 || (tcs
->ramsearch
&& tcs
->type
== tag_filename
)
1420 struct tagcache_seeklist_entry
*seeklist
;
1422 /* Check for end of list. */
1423 if (tcs
->list_position
== tcs
->seek_list_count
)
1425 tcs
->list_position
= 0;
1427 /* Try to fetch more. */
1428 if (!build_lookup_list(tcs
))
1435 seeklist
= &tcs
->seeklist
[tcs
->list_position
];
1436 flag
= seeklist
->flag
;
1437 tcs
->position
= seeklist
->seek
;
1438 tcs
->idx_id
= seeklist
->idx_id
;
1439 tcs
->list_position
++;
1443 if (tcs
->entry_count
== 0)
1452 tcs
->result_seek
= tcs
->position
;
1454 if (TAGCACHE_IS_NUMERIC(tcs
->type
))
1456 snprintf(buf
, sizeof(buf
), "%ld", tcs
->position
);
1458 tcs
->result_len
= strlen(buf
) + 1;
1463 #ifdef HAVE_TC_RAMCACHE
1467 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1468 if (tcs
->type
== tag_filename
&& (flag
& FLAG_DIRCACHE
)
1469 && is_dircache_intact())
1471 dircache_copy_path((struct dircache_entry
*)tcs
->position
,
1474 tcs
->result_len
= strlen(buf
) + 1;
1475 tcs
->ramresult
= false;
1481 if (tcs
->type
!= tag_filename
)
1483 struct tagfile_entry
*ep
;
1485 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1486 tcs
->result
= ep
->tag_data
;
1487 tcs
->result_len
= strlen(tcs
->result
) + 1;
1488 tcs
->idx_id
= ep
->idx_id
;
1489 tcs
->ramresult
= true;
1491 /* Increase position for the next run. This may get overwritten. */
1492 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1499 if (!open_files(tcs
, tcs
->type
))
1505 /* Seek stream to the correct position and continue to direct fetch. */
1506 lseek(tcs
->idxfd
[tcs
->type
], tcs
->position
, SEEK_SET
);
1508 if (ecread_tagfile_entry(tcs
->idxfd
[tcs
->type
], &entry
) != sizeof(struct tagfile_entry
))
1510 logf("read error #5");
1515 if (entry
.tag_length
> (long)sizeof(buf
))
1518 logf("too long tag #2");
1519 logf("P:%lX/%lX", tcs
->position
, entry
.tag_length
);
1523 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1526 logf("read error #4");
1531 Update the position for the next read (this may be overridden
1532 if filters or clauses are being used).
1534 tcs
->position
+= sizeof(struct tagfile_entry
) + entry
.tag_length
;
1536 tcs
->result_len
= strlen(tcs
->result
) + 1;
1537 tcs
->idx_id
= entry
.idx_id
;
1538 tcs
->ramresult
= false;
1543 bool tagcache_get_next(struct tagcache_search
*tcs
)
1545 while (get_next(tcs
))
1547 if (tcs
->result_len
> 1)
1554 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1555 int tag
, char *buf
, long size
)
1557 struct index_entry idx
;
1560 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1563 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1566 static bool update_master_header(void)
1568 struct master_header myhdr
;
1574 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1577 myhdr
.serial
= current_tcmh
.serial
;
1578 myhdr
.commitid
= current_tcmh
.commitid
;
1579 myhdr
.dirty
= current_tcmh
.dirty
;
1582 lseek(fd
, 0, SEEK_SET
);
1583 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1586 #ifdef HAVE_TC_RAMCACHE
1589 hdr
->h
.serial
= current_tcmh
.serial
;
1590 hdr
->h
.commitid
= current_tcmh
.commitid
;
1591 hdr
->h
.dirty
= current_tcmh
.dirty
;
1600 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1602 struct tagentry
*entry
;
1604 if (tcs
->type
!= tag_title
)
1607 /* We will need reserve buffer for this. */
1610 struct tagfile_entry
*ep
;
1612 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1613 tcs
->seek_list
[tcs
->seek_list_count
];
1616 entry
= find_entry_ram();
1621 void tagcache_search_finish(struct tagcache_search
*tcs
)
1625 if (!tcs
->initialized
)
1628 if (tcs
->masterfd
>= 0)
1630 close(tcs
->masterfd
);
1634 for (i
= 0; i
< TAG_COUNT
; i
++)
1636 if (tcs
->idxfd
[i
] >= 0)
1638 close(tcs
->idxfd
[i
]);
1643 tcs
->ramsearch
= false;
1645 tcs
->initialized
= 0;
1650 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1651 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1653 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1656 static long get_tag_numeric(const struct index_entry
*entry
, int tag
, int idx_id
)
1658 return check_virtual_tags(tag
, idx_id
, entry
);
1661 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1663 char* s
= get_tag(entry
, tag
)->tag_data
;
1664 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1667 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1669 struct index_entry
*entry
;
1672 if (!tc_stat
.ready
|| !tc_stat
.ramcache
)
1675 /* Find the corresponding entry in tagcache. */
1676 idx_id
= find_entry_ram(filename
, NULL
);
1680 entry
= &hdr
->indices
[idx_id
];
1682 memset(id3
, 0, sizeof(struct mp3entry
));
1684 id3
->title
= get_tag_string(entry
, tag_title
);
1685 id3
->artist
= get_tag_string(entry
, tag_artist
);
1686 id3
->album
= get_tag_string(entry
, tag_album
);
1687 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1688 id3
->composer
= get_tag_string(entry
, tag_composer
);
1689 id3
->comment
= get_tag_string(entry
, tag_comment
);
1690 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1691 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1693 id3
->length
= get_tag_numeric(entry
, tag_length
, idx_id
);
1694 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
, idx_id
);
1695 id3
->rating
= get_tag_numeric(entry
, tag_rating
, idx_id
);
1696 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
, idx_id
);
1697 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
, idx_id
) / 10;
1698 id3
->year
= get_tag_numeric(entry
, tag_year
, idx_id
);
1700 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
, idx_id
);
1701 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
, idx_id
);
1702 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
, idx_id
);
1703 if (id3
->bitrate
== 0)
1706 #if CONFIG_CODEC == SWCODEC
1707 if (global_settings
.autoresume_enable
)
1709 id3
->offset
= get_tag_numeric(entry
, tag_lastoffset
, idx_id
);
1710 logf("tagcache_fill_tags: Set offset for %s to %lX\n",
1711 id3
->title
, id3
->offset
);
1719 static inline void write_item(const char *item
)
1721 int len
= strlen(item
) + 1;
1724 write(cachefd
, item
, len
);
1727 static int check_if_empty(char **tag
)
1731 if (*tag
== NULL
|| **tag
== '\0')
1734 return sizeof(UNTAGGED
); /* Tag length */
1737 length
= strlen(*tag
);
1738 if (length
> TAG_MAXLEN
)
1740 logf("over length tag: %s", *tag
);
1741 length
= TAG_MAXLEN
;
1742 (*tag
)[length
] = '\0';
1748 #define ADD_TAG(entry,tag,data) \
1750 entry.tag_offset[tag] = offset; \
1751 entry.tag_length[tag] = check_if_empty(data); \
1752 offset += entry.tag_length[tag]
1753 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1754 * idea, as it uses lots of stack and is called from a recursive function
1757 static void __attribute__ ((noinline
)) add_tagcache(char *path
,
1759 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1760 ,const struct dircache_entry
*dc
1764 struct mp3entry id3
;
1765 struct temp_file_entry entry
;
1769 char tracknumfix
[3];
1771 int path_length
= strlen(path
);
1772 bool has_albumartist
;
1776 /* Crude logging for the sim - to aid in debugging */
1777 int logfd
= open(ROCKBOX_DIR
"/database.log",
1778 O_WRONLY
| O_APPEND
| O_CREAT
, 0666);
1780 write(logfd
, path
, strlen(path
));
1781 write(logfd
, "\n", 1);
1789 /* Check for overlength file path. */
1790 if (path_length
> TAG_MAXLEN
)
1792 /* Path can't be shortened. */
1793 logf("Too long path: %s", path
);
1797 /* Check if the file is supported. */
1798 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1801 /* Check if the file is already cached. */
1802 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1803 if (tc_stat
.ramcache
&& is_dircache_intact())
1805 idx_id
= find_entry_ram(path
, dc
);
1809 /* Be sure the entry doesn't exist. */
1810 if (filenametag_fd
>= 0 && idx_id
< 0)
1811 idx_id
= find_entry_disk(path
, false);
1813 /* Check if file has been modified. */
1816 struct index_entry idx
;
1818 /* TODO: Mark that the index exists (for fast reverse scan) */
1819 //found_idx[idx_id/8] |= idx_id%8;
1821 if (!get_index(-1, idx_id
, &idx
, true))
1823 logf("failed to retrieve index entry");
1827 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1829 /* No changes to file. */
1833 /* Metadata might have been changed. Delete the entry. */
1834 logf("Re-adding: %s", path
);
1835 if (!delete_entry(idx_id
))
1837 logf("delete_entry failed: %d", idx_id
);
1842 fd
= open(path
, O_RDONLY
);
1845 logf("open fail: %s", path
);
1849 memset(&id3
, 0, sizeof(struct mp3entry
));
1850 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1851 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1852 ret
= get_metadata(&id3
, fd
, path
);
1858 logf("-> %s", path
);
1860 /* Generate track number if missing. */
1861 if (id3
.tracknum
<= 0)
1863 const char *p
= strrchr(path
, '.');
1866 p
= &path
[strlen(path
)-1];
1870 if (isdigit(*p
) && isdigit(*(p
-1)))
1872 tracknumfix
[1] = *p
--;
1873 tracknumfix
[0] = *p
;
1879 if (tracknumfix
[0] != '\0')
1881 id3
.tracknum
= atoi(tracknumfix
);
1882 /* Set a flag to indicate track number has been generated. */
1883 entry
.flag
|= FLAG_TRKNUMGEN
;
1887 /* Unable to generate track number. */
1893 entry
.tag_offset
[tag_year
] = id3
.year
;
1894 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1895 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1896 entry
.tag_offset
[tag_length
] = id3
.length
;
1897 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1898 entry
.tag_offset
[tag_mtime
] = mtime
;
1901 has_albumartist
= id3
.albumartist
!= NULL
1902 && strlen(id3
.albumartist
) > 0;
1903 has_grouping
= id3
.grouping
!= NULL
1904 && strlen(id3
.grouping
) > 0;
1906 ADD_TAG(entry
, tag_filename
, &path
);
1907 ADD_TAG(entry
, tag_title
, &id3
.title
);
1908 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1909 ADD_TAG(entry
, tag_album
, &id3
.album
);
1910 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1911 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1912 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1913 if (has_albumartist
)
1915 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1919 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1923 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1927 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1929 entry
.data_length
= offset
;
1931 /* Write the header */
1932 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1934 /* And tags also... Correct order is critical */
1936 write_item(id3
.title
);
1937 write_item(id3
.artist
);
1938 write_item(id3
.album
);
1939 write_item(id3
.genre_string
);
1940 write_item(id3
.composer
);
1941 write_item(id3
.comment
);
1942 if (has_albumartist
)
1944 write_item(id3
.albumartist
);
1948 write_item(id3
.artist
);
1952 write_item(id3
.grouping
);
1956 write_item(id3
.title
);
1958 total_entry_count
++;
1961 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1963 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1964 int len
= strlen(str
)+1;
1967 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1968 char buf
[TAG_MAXLEN
+32];
1970 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1971 buf
[i
] = tolower(str
[i
]);
1974 crc32
= crc_32(buf
, i
, 0xffffffff);
1978 /* Check if the crc does not exist -> entry does not exist for sure. */
1979 for (i
= 0; i
< tempbufidx
; i
++)
1981 if (crcbuf
[-i
] != crc32
)
1984 if (!strcasecmp(str
, index
[i
].str
))
1986 if (id
< 0 || id
>= lookup_buffer_depth
)
1988 logf("lookup buf overf.: %d", id
);
1992 lookup
[id
] = &index
[i
];
1998 /* Insert to CRC buffer. */
1999 crcbuf
[-tempbufidx
] = crc32
;
2002 /* Insert it to the buffer. */
2003 tempbuf_left
-= len
;
2004 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
2007 if (id
>= lookup_buffer_depth
)
2009 logf("lookup buf overf. #2: %d", id
);
2015 lookup
[id
] = &index
[tempbufidx
];
2016 index
[tempbufidx
].idlist
.id
= id
;
2019 index
[tempbufidx
].idlist
.id
= -1;
2021 index
[tempbufidx
].idlist
.next
= NULL
;
2022 index
[tempbufidx
].idx_id
= idx_id
;
2023 index
[tempbufidx
].seek
= -1;
2024 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
2025 memcpy(index
[tempbufidx
].str
, str
, len
);
2032 static int compare(const void *p1
, const void *p2
)
2036 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
2037 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
2039 if (strcmp(e1
->str
, UNTAGGED
) == 0)
2041 if (strcmp(e2
->str
, UNTAGGED
) == 0)
2045 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
2048 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
2051 static int tempbuf_sort(int fd
)
2053 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
2054 struct tagfile_entry fe
;
2058 /* Generate reverse lookup entries. */
2059 for (i
= 0; i
< lookup_buffer_depth
; i
++)
2061 struct tempbuf_id_list
*idlist
;
2066 if (lookup
[i
]->idlist
.id
== i
)
2069 idlist
= &lookup
[i
]->idlist
;
2070 while (idlist
->next
!= NULL
)
2071 idlist
= idlist
->next
;
2073 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
2074 if (tempbuf_left
- 4 < 0)
2077 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2078 if (tempbuf_pos
& 0x03)
2080 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
2082 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2084 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
2086 idlist
= idlist
->next
;
2088 idlist
->next
= NULL
;
2093 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
2094 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
2096 for (i
= 0; i
< tempbufidx
; i
++)
2098 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
2100 /* Fix the lookup list. */
2101 while (idlist
!= NULL
)
2103 if (idlist
->id
>= 0)
2104 lookup
[idlist
->id
] = &index
[i
];
2105 idlist
= idlist
->next
;
2108 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
2109 length
= strlen(index
[i
].str
) + 1;
2110 fe
.tag_length
= length
;
2111 fe
.idx_id
= index
[i
].idx_id
;
2113 /* Check the chunk alignment. */
2114 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2115 % TAGFILE_ENTRY_CHUNK_LENGTH
)
2117 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
2118 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2119 % TAGFILE_ENTRY_CHUNK_LENGTH
);
2122 #ifdef TAGCACHE_STRICT_ALIGN
2123 /* Make sure the entry is long aligned. */
2124 if (index
[i
].seek
& 0x03)
2126 logf("tempbuf_sort: alignment error!");
2131 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2132 sizeof(struct tagfile_entry
))
2134 logf("tempbuf_sort: write error #1");
2138 if (write(fd
, index
[i
].str
, length
) != length
)
2140 logf("tempbuf_sort: write error #2");
2144 /* Write some padding. */
2145 if (fe
.tag_length
- length
> 0)
2146 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2152 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2154 if (id
< 0 || id
>= lookup_buffer_depth
)
2161 inline static int tempbuf_find_location(int id
)
2163 struct tempbuf_searchidx
*entry
;
2165 entry
= tempbuf_locate(id
);
2172 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2174 struct master_header tcmh
;
2175 struct index_entry idx
;
2178 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2180 int entries_processed
= 0;
2182 char buf
[TAG_MAXLEN
];
2184 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2186 logf("Building numeric indices...");
2187 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2189 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2192 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2194 if (masterfd_pos
== filesize(masterfd
))
2196 logf("we can't append!");
2201 while (entries_processed
< h
->entry_count
)
2203 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2205 /* Read in as many entries as possible. */
2206 for (i
= 0; i
< count
; i
++)
2208 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2211 /* Read in numeric data. */
2212 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2213 sizeof(struct temp_file_entry
))
2215 logf("read fail #1");
2220 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2223 * Read string data from the following tags:
2229 * A crc32 hash is calculated from the read data
2230 * and stored back to the data offset field kept in memory.
2232 #define tmpdb_read_string_tag(tag) \
2233 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2234 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2236 logf("read fail: buffer overflow"); \
2241 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2242 tfe->tag_length[tag]) \
2244 logf("read fail #2"); \
2249 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2250 lseek(tmpfd, datastart, SEEK_SET)
2252 tmpdb_read_string_tag(tag_filename
);
2253 tmpdb_read_string_tag(tag_artist
);
2254 tmpdb_read_string_tag(tag_album
);
2255 tmpdb_read_string_tag(tag_title
);
2257 /* Seek to the end of the string data. */
2258 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2261 /* Backup the master index position. */
2262 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2263 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2265 /* Check if we can resurrect some deleted runtime statistics data. */
2266 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2268 /* Read the index entry. */
2269 if (ecread_index_entry(masterfd
, &idx
)
2270 != sizeof(struct index_entry
))
2272 logf("read fail #3");
2278 * Skip unless the entry is marked as being deleted
2279 * or the data has already been resurrected.
2281 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2284 /* Now try to match the entry. */
2286 * To succesfully match a song, the following conditions
2289 * For numeric fields: tag_length
2290 * - Full identical match is required
2292 * If tag_filename matches, no further checking necessary.
2294 * For string hashes: tag_artist, tag_album, tag_title
2295 * - Two of these must match
2297 for (j
= 0; j
< count
; j
++)
2299 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2301 /* Try to match numeric fields first. */
2302 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2305 /* Now it's time to do the hash matching. */
2306 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2308 int match_count
= 0;
2310 /* No filename match, check if we can match two other tags. */
2311 #define tmpdb_match(tag) \
2312 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2315 tmpdb_match(tag_artist
);
2316 tmpdb_match(tag_album
);
2317 tmpdb_match(tag_title
);
2319 if (match_count
< 2)
2321 /* Still no match found, give up. */
2326 /* A match found, now copy & resurrect the statistical data. */
2327 #define tmpdb_copy_tag(tag) \
2328 tfe->tag_offset[tag] = idx.tag_seek[tag]
2330 tmpdb_copy_tag(tag_playcount
);
2331 tmpdb_copy_tag(tag_rating
);
2332 tmpdb_copy_tag(tag_playtime
);
2333 tmpdb_copy_tag(tag_lastplayed
);
2334 tmpdb_copy_tag(tag_commitid
);
2335 tmpdb_copy_tag(tag_lastoffset
);
2337 /* Avoid processing this entry again. */
2338 idx
.flag
|= FLAG_RESURRECTED
;
2340 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2341 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2343 logf("masterfd writeback fail #1");
2348 logf("Entry resurrected");
2353 /* Restore the master index position. */
2354 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2356 /* Commit the data to the index. */
2357 for (i
= 0; i
< count
; i
++)
2359 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2361 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2363 logf("read fail #3");
2368 for (j
= 0; j
< TAG_COUNT
; j
++)
2370 if (!TAGCACHE_IS_NUMERIC(j
))
2373 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2375 idx
.flag
= entrybuf
[i
].flag
;
2377 if (idx
.tag_seek
[tag_commitid
])
2379 /* Data has been resurrected. */
2380 idx
.flag
|= FLAG_DIRTYNUM
;
2382 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2384 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2385 idx
.flag
|= FLAG_DIRTYNUM
;
2388 /* Write back the updated index. */
2389 lseek(masterfd
, loc
, SEEK_SET
);
2390 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2398 entries_processed
+= count
;
2399 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2410 * == 0 temporary failure
2413 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2416 struct tagcache_header tch
;
2417 struct master_header tcmh
;
2418 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2420 char buf
[TAG_MAXLEN
+32];
2421 int fd
= -1, masterfd
;
2426 logf("Building index: %d", index_type
);
2428 /* Check the number of entries we need to allocate ram for. */
2429 commit_entry_count
= h
->entry_count
+ 1;
2431 masterfd
= open_master_fd(&tcmh
, false);
2434 commit_entry_count
+= tcmh
.tch
.entry_count
;
2438 remove_files(); /* Just to be sure we are clean. */
2440 /* Open the index file, which contains the tag names. */
2441 fd
= open_tag_fd(&tch
, index_type
, true);
2444 logf("tch.datasize=%ld", tch
.datasize
);
2445 lookup_buffer_depth
= 1 +
2446 /* First part */ commit_entry_count
+
2447 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2451 lookup_buffer_depth
= 1 +
2452 /* First part */ commit_entry_count
+
2453 /* Second part */ 0;
2456 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2457 logf("commit_entry_count=%ld", commit_entry_count
);
2459 /* Allocate buffer for all index entries from both old and new
2462 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2464 /* Allocate lookup buffer. The first portion of commit_entry_count
2465 * contains the new tags in the temporary file and the second
2466 * part for locating entries already in the db.
2469 * +---------+---------------------------+
2470 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2471 * +---------+---------------------------+
2473 * Old tags are inserted to a temporary buffer with position:
2474 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2475 * And new tags with index:
2476 * tempbuf_insert(idx, ...);
2478 * The buffer is sorted and written into tag file:
2479 * tempbuf_sort(...);
2480 * leaving master index locations messed up.
2482 * That is fixed using the lookup buffer for old tags:
2483 * new_seek = tempbuf_find_location(old_seek, ...);
2485 * new_seek = tempbuf_find_location(idx);
2487 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2488 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2489 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2491 /* And calculate the remaining data space used mainly for storing
2492 * tag data (strings). */
2493 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2494 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2496 logf("Buffer way too small!");
2503 * If tag file contains unique tags (sorted index), we will load
2504 * it entirely into memory so we can resort it later for use with
2507 if (TAGCACHE_IS_SORTED(index_type
))
2509 logf("loading tags...");
2510 for (i
= 0; i
< tch
.entry_count
; i
++)
2512 struct tagfile_entry entry
;
2513 int loc
= lseek(fd
, 0, SEEK_CUR
);
2516 if (ecread_tagfile_entry(fd
, &entry
) != sizeof(struct tagfile_entry
))
2518 logf("read error #7");
2523 if (entry
.tag_length
>= (int)sizeof(buf
))
2525 logf("too long tag #3");
2530 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2532 logf("read error #8");
2537 /* Skip deleted entries. */
2542 * Save the tag and tag id in the memory buffer. Tag id
2543 * is saved so we can later reindex the master lookup
2544 * table when the index gets resorted.
2546 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2547 + commit_entry_count
, entry
.idx_id
,
2548 TAGCACHE_IS_UNIQUE(index_type
));
2559 tempbufidx
= tch
.entry_count
;
2564 * Creating new index file to store the tags. No need to preload
2565 * anything whether the index type is sorted or not.
2567 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2568 fd
= open(buf
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2571 logf("%s open fail", buf
);
2575 tch
.magic
= TAGCACHE_MAGIC
;
2576 tch
.entry_count
= 0;
2579 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2580 != sizeof(struct tagcache_header
))
2582 logf("header write failed");
2588 /* Loading the tag lookup file as "master file". */
2589 logf("Loading index file");
2590 masterfd
= open(TAGCACHE_FILE_MASTER
, O_RDWR
);
2594 logf("Creating new DB");
2595 masterfd
= open(TAGCACHE_FILE_MASTER
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2599 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER
);
2604 /* Write the header (write real values later). */
2605 memset(&tcmh
, 0, sizeof(struct master_header
));
2607 tcmh
.tch
.entry_count
= 0;
2608 tcmh
.tch
.datasize
= 0;
2610 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2612 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2617 * Master file already exists so we need to process the current
2622 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2623 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2625 logf("header error");
2632 * If we reach end of the master file, we need to expand it to
2633 * hold new tags. If the current index is not sorted, we can
2634 * simply append new data to end of the file.
2635 * However, if the index is sorted, we need to update all tag
2636 * pointers in the master file for the current index.
2638 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2640 if (masterfd_pos
== filesize(masterfd
))
2642 logf("appending...");
2648 * Load new unique tags in memory to be sorted later and added
2649 * to the master lookup file.
2651 if (TAGCACHE_IS_SORTED(index_type
))
2653 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2654 /* h is the header of the temporary file containing new tags. */
2655 logf("inserting new tags...");
2656 for (i
= 0; i
< h
->entry_count
; i
++)
2658 struct temp_file_entry entry
;
2660 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2661 sizeof(struct temp_file_entry
))
2663 logf("read fail #3");
2669 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2671 logf("too long entry!");
2676 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2677 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2678 entry
.tag_length
[index_type
])
2680 logf("read fail #4");
2685 if (TAGCACHE_IS_UNIQUE(index_type
))
2686 error
= !tempbuf_insert(buf
, i
, -1, true);
2688 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2692 logf("insert error");
2697 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2698 entry
.tag_length
[index_type
], SEEK_CUR
);
2703 /* Sort the buffer data and write it to the index file. */
2704 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2706 * We need to truncate the index file now. There can be junk left
2707 * at the end of file (however, we _should_ always follow the
2708 * entry_count and don't crash with that).
2710 ftruncate(fd
, lseek(fd
, 0, SEEK_CUR
));
2712 i
= tempbuf_sort(fd
);
2715 logf("sorted %d tags", i
);
2718 * Now update all indexes in the master lookup file.
2720 logf("updating indices...");
2721 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2722 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2725 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2727 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2729 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2730 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2732 logf("read fail #5");
2736 lseek(masterfd
, loc
, SEEK_SET
);
2738 for (j
= 0; j
< idxbuf_pos
; j
++)
2740 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2742 /* We can just ignore deleted entries. */
2743 // idxbuf[j].tag_seek[index_type] = 0;
2747 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2748 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2749 + commit_entry_count
);
2751 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2753 logf("update error: %ld/%d/%ld",
2754 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2762 /* Write back the updated index. */
2763 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2764 index_entry_ec
, tc_stat
.econ
) !=
2765 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2776 * Walk through the temporary file containing the new tags.
2778 // build_normal_index(h, tmpfd, masterfd, idx);
2779 logf("updating new indices...");
2780 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2781 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2782 lseek(fd
, 0, SEEK_END
);
2783 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2787 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2790 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2794 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2796 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2797 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2799 logf("read fail #6");
2803 lseek(masterfd
, loc
, SEEK_SET
);
2806 /* Read entry headers. */
2807 for (j
= 0; j
< idxbuf_pos
; j
++)
2809 if (!TAGCACHE_IS_SORTED(index_type
))
2811 struct temp_file_entry entry
;
2812 struct tagfile_entry fe
;
2814 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2815 sizeof(struct temp_file_entry
))
2817 logf("read fail #7");
2823 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2825 logf("too long entry!");
2826 logf("length=%d", entry
.tag_length
[index_type
]);
2827 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2832 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2833 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2834 entry
.tag_length
[index_type
])
2836 logf("read fail #8");
2837 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2838 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2843 /* Write to index file. */
2844 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2845 fe
.tag_length
= entry
.tag_length
[index_type
];
2846 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2847 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2848 write(fd
, buf
, fe
.tag_length
);
2852 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2853 entry
.tag_length
[index_type
], SEEK_CUR
);
2857 /* Locate the correct entry from the sorted array. */
2858 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2859 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2861 logf("entry not found (%d)", j
);
2869 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2870 index_entry_ec
, tc_stat
.econ
) !=
2871 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2873 logf("tagcache: write fail #4");
2882 /* Finally write the header. */
2883 tch
.magic
= TAGCACHE_MAGIC
;
2884 tch
.entry_count
= tempbufidx
;
2885 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2886 lseek(fd
, 0, SEEK_SET
);
2887 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2889 if (index_type
!= tag_filename
)
2890 h
->datasize
+= tch
.datasize
;
2891 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2903 static bool commit(void)
2905 struct tagcache_header tch
;
2906 struct master_header tcmh
;
2910 #ifdef HAVE_DIRCACHE
2911 bool dircache_buffer_stolen
= false;
2913 bool local_allocation
= false;
2915 logf("committing tagcache");
2920 tmpfd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
2923 logf("nothing to commit");
2928 /* Load the header. */
2929 len
= sizeof(struct tagcache_header
);
2930 rc
= read(tmpfd
, &tch
, len
);
2932 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2934 logf("incorrect tmpheader");
2936 remove(TAGCACHE_FILE_TEMP
);
2940 if (tch
.entry_count
== 0)
2942 logf("nothing to commit");
2944 remove(TAGCACHE_FILE_TEMP
);
2948 /* Fully initialize existing headers (if any) before going further. */
2949 tc_stat
.ready
= check_all_headers();
2951 #ifdef HAVE_EEPROM_SETTINGS
2952 remove(TAGCACHE_STATEFILE
);
2955 /* At first be sure to unload the ramcache! */
2956 #ifdef HAVE_TC_RAMCACHE
2957 tc_stat
.ramcache
= false;
2962 /* Try to steal every buffer we can :) */
2963 if (tempbuf_size
== 0)
2964 local_allocation
= true;
2966 #ifdef HAVE_DIRCACHE
2967 if (tempbuf_size
== 0)
2969 /* Try to steal the dircache buffer. */
2970 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2971 tempbuf_size
&= ~0x03;
2973 if (tempbuf_size
> 0)
2975 dircache_buffer_stolen
= true;
2980 #ifdef HAVE_TC_RAMCACHE
2981 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2983 tempbuf
= (char *)(hdr
+ 1);
2984 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2985 tempbuf_size
&= ~0x03;
2989 /* And finally fail if there are no buffers available. */
2990 if (tempbuf_size
== 0)
2992 logf("delaying commit until next boot");
2993 tc_stat
.commit_delayed
= true;
2999 logf("commit %ld entries...", tch
.entry_count
);
3001 /* Mark DB dirty so it will stay disabled if commit fails. */
3002 current_tcmh
.dirty
= true;
3003 update_master_header();
3005 /* Now create the index files. */
3006 tc_stat
.commit_step
= 0;
3008 tc_stat
.commit_delayed
= false;
3010 for (i
= 0; i
< TAG_COUNT
; i
++)
3014 if (TAGCACHE_IS_NUMERIC(i
))
3017 tc_stat
.commit_step
++;
3018 ret
= build_index(i
, &tch
, tmpfd
);
3022 logf("tagcache failed init");
3024 tc_stat
.commit_delayed
= true;
3026 tc_stat
.commit_step
= 0;
3032 if (!build_numeric_indices(&tch
, tmpfd
))
3034 logf("Failure to commit numeric indices");
3036 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 remove(TAGCACHE_FILE_TEMP
);
3054 tcmh
.tch
.entry_count
+= tch
.entry_count
;
3055 tcmh
.tch
.datasize
= sizeof(struct master_header
)
3056 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
3061 lseek(masterfd
, 0, SEEK_SET
);
3062 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
3065 logf("tagcache committed");
3066 tc_stat
.ready
= check_all_headers();
3067 tc_stat
.readyvalid
= true;
3069 if (local_allocation
)
3075 #ifdef HAVE_DIRCACHE
3076 /* Rebuild the dircache, if we stole the buffer. */
3077 if (dircache_buffer_stolen
)
3081 #ifdef HAVE_TC_RAMCACHE
3082 /* Reload tagcache. */
3083 if (tc_stat
.ramcache_allocated
> 0)
3084 tagcache_start_scan();
3092 static void allocate_tempbuf(void)
3094 /* Yeah, malloc would be really nice now :) */
3096 tempbuf_size
= 32*1024*1024;
3097 tempbuf
= malloc(tempbuf_size
);
3099 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
3100 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
3101 audiobuf
+= tempbuf_size
;
3105 static void free_tempbuf(void)
3107 if (tempbuf_size
== 0)
3113 audiobuf
-= tempbuf_size
;
3121 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
3123 struct index_entry idx
;
3128 if (!TAGCACHE_IS_NUMERIC(tag
))
3131 if (!get_index(masterfd
, idx_id
, &idx
, false))
3134 idx
.tag_seek
[tag
] = data
;
3135 idx
.flag
|= FLAG_DIRTYNUM
;
3137 return write_index(masterfd
, idx_id
, &idx
);
3141 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3144 struct master_header myhdr
;
3146 if (tcs
->masterfd
< 0)
3148 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3152 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3156 static bool command_queue_is_full(void)
3160 next
= command_queue_widx
+ 1;
3161 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3164 return (next
== command_queue_ridx
);
3167 static void command_queue_sync_callback(void *data
)
3170 struct master_header myhdr
;
3173 mutex_lock(&command_queue_mutex
);
3175 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3178 while (command_queue_ridx
!= command_queue_widx
)
3180 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3182 switch (ce
->command
)
3184 case CMD_UPDATE_MASTER_HEADER
:
3187 update_master_header();
3189 /* Re-open the masterfd. */
3190 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3195 case CMD_UPDATE_NUMERIC
:
3197 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3202 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3203 command_queue_ridx
= 0;
3208 tc_stat
.queue_length
= 0;
3209 mutex_unlock(&command_queue_mutex
);
3212 static void run_command_queue(bool force
)
3214 if (COMMAND_QUEUE_IS_EMPTY
)
3217 if (force
|| command_queue_is_full())
3218 command_queue_sync_callback(NULL
);
3220 register_storage_idle_func(command_queue_sync_callback
);
3223 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3229 mutex_lock(&command_queue_mutex
);
3230 next
= command_queue_widx
+ 1;
3231 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3234 /* Make sure queue is not full. */
3235 if (next
!= command_queue_ridx
)
3237 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3240 ce
->idx_id
= idx_id
;
3244 command_queue_widx
= next
;
3246 tc_stat
.queue_length
++;
3248 mutex_unlock(&command_queue_mutex
);
3252 /* Queue is full, try again later... */
3253 mutex_unlock(&command_queue_mutex
);
3258 long tagcache_increase_serial(void)
3268 old
= current_tcmh
.serial
++;
3269 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3274 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3276 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3278 #endif /* !__PCTOOL__ */
3280 long tagcache_get_serial(void)
3282 return current_tcmh
.serial
;
3285 long tagcache_get_commitid(void)
3287 return current_tcmh
.commitid
;
3290 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3295 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3296 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3298 if (*datastr
== '\0')
3301 if (*datastr
== '"' || *datastr
== '\\')
3304 buf
[i
] = *(datastr
++);
3307 strcpy(&buf
[i
], "\" ");
3309 write(fd
, buf
, i
+ 2);
3316 static bool read_tag(char *dest
, long size
,
3317 const char *src
, const char *tagstr
)
3320 char current_tag
[32];
3322 while (*src
!= '\0')
3324 /* Skip all whitespace */
3332 /* Read in tag name */
3333 while (*src
!= '=' && *src
!= ' ')
3335 current_tag
[pos
] = *src
;
3339 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3342 current_tag
[pos
] = '\0';
3344 /* Read in tag data */
3346 /* Find the start. */
3347 while (*src
!= '"' && *src
!= '\0')
3350 if (*src
== '\0' || *(++src
) == '\0')
3353 /* Read the data. */
3354 for (pos
= 0; pos
< size
; pos
++)
3361 dest
[pos
] = *(src
+1);
3381 if (!strcasecmp(tagstr
, current_tag
))
3388 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3390 struct index_entry idx
;
3391 char tag_data
[TAG_MAXLEN
+32];
3393 long masterfd
= (long)parameters
;
3394 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
,
3395 tag_lastplayed
, tag_commitid
, tag_lastoffset
};
3402 logf("%d/%s", line_n
, buf
);
3403 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3405 logf("filename missing");
3410 idx_id
= find_index(tag_data
);
3413 logf("entry not found");
3417 if (!get_index(masterfd
, idx_id
, &idx
, false))
3419 logf("failed to retrieve index entry");
3423 /* Stop if tag has already been modified. */
3424 if (idx
.flag
& FLAG_DIRTYNUM
)
3427 logf("import: %s", tag_data
);
3429 idx
.flag
|= FLAG_DIRTYNUM
;
3430 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3434 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3435 tagcache_tag_to_str(import_tags
[i
])))
3440 data
= atoi(tag_data
);
3444 idx
.tag_seek
[import_tags
[i
]] = data
;
3446 if (import_tags
[i
] == tag_lastplayed
&& data
>= current_tcmh
.serial
)
3447 current_tcmh
.serial
= data
+ 1;
3448 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3449 current_tcmh
.commitid
= data
+ 1;
3452 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3455 bool tagcache_import_changelog(void)
3457 struct master_header myhdr
;
3458 struct tagcache_header tch
;
3469 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_RDONLY
);
3472 logf("failure to open changelog");
3476 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3484 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3486 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3487 parse_changelog_line
);
3492 if (filenametag_fd
>= 0)
3494 close(filenametag_fd
);
3495 filenametag_fd
= -1;
3500 update_master_header();
3505 #endif /* !__PCTOOL__ */
3507 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3509 struct master_header myhdr
;
3510 struct index_entry idx
;
3511 char buf
[TAG_MAXLEN
+32];
3519 if (!tagcache_search(tcs
, tag_filename
))
3522 /* Initialize the changelog */
3523 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3526 logf("failure to open changelog");
3530 if (tcs
->masterfd
< 0)
3532 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3537 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3538 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3541 write(clfd
, "## Changelog version 1\n", 23);
3543 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3545 if (ecread_index_entry(tcs
->masterfd
, &idx
) != sizeof(struct index_entry
))
3547 logf("read error #9");
3548 tagcache_search_finish(tcs
);
3553 /* Skip until the entry found has been modified. */
3554 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3557 /* Skip deleted entries too. */
3558 if (idx
.flag
& FLAG_DELETED
)
3561 /* Now retrieve all tags. */
3562 for (j
= 0; j
< TAG_COUNT
; j
++)
3564 if (TAGCACHE_IS_NUMERIC(j
))
3566 snprintf(temp
, sizeof temp
, "%d", (int)idx
.tag_seek
[j
]);
3567 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3572 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3573 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3576 write(clfd
, "\n", 1);
3582 tagcache_search_finish(tcs
);
3587 static bool delete_entry(long idx_id
)
3592 struct index_entry idx
, myidx
;
3593 struct master_header myhdr
;
3594 char buf
[TAG_MAXLEN
+32];
3595 int in_use
[TAG_COUNT
];
3597 logf("delete_entry(): %ld", idx_id
);
3599 #ifdef HAVE_TC_RAMCACHE
3600 /* At first mark the entry removed from ram cache. */
3601 if (tc_stat
.ramcache
)
3602 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3605 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3608 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3609 if (ecread_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3611 logf("delete_entry(): read error");
3615 if (myidx
.flag
& FLAG_DELETED
)
3617 logf("delete_entry(): already deleted!");
3621 myidx
.flag
|= FLAG_DELETED
;
3622 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3623 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3625 logf("delete_entry(): write_error #1");
3629 /* Now check which tags are no longer in use (if any) */
3630 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3633 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3634 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3636 struct index_entry
*idxp
;
3638 #ifdef HAVE_TC_RAMCACHE
3639 /* Use RAM DB if available for greater speed */
3640 if (tc_stat
.ramcache
)
3641 idxp
= &hdr
->indices
[i
];
3645 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
3647 logf("delete_entry(): read error #2");
3653 if (idxp
->flag
& FLAG_DELETED
)
3656 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3658 if (TAGCACHE_IS_NUMERIC(tag
))
3661 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3666 /* Now delete all tags no longer in use. */
3667 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3669 struct tagcache_header tch
;
3670 int oldseek
= myidx
.tag_seek
[tag
];
3672 if (TAGCACHE_IS_NUMERIC(tag
))
3676 * Replace tag seek with a hash value of the field string data.
3677 * That way runtime statistics of moved or altered files can be
3680 #ifdef HAVE_TC_RAMCACHE
3681 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3683 struct tagfile_entry
*tfe
;
3684 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3686 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3687 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3688 myidx
.tag_seek
[tag
] = *seek
;
3693 struct tagfile_entry tfe
;
3695 /* Open the index file, which contains the tag names. */
3696 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3699 /* Skip the header block */
3700 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3701 if (ecread_tagfile_entry(fd
, &tfe
) != sizeof(struct tagfile_entry
))
3703 logf("delete_entry(): read error #3");
3707 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3709 logf("delete_entry(): read error #4");
3713 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3718 logf("in use: %d/%d", tag
, in_use
[tag
]);
3727 #ifdef HAVE_TC_RAMCACHE
3728 /* Delete from ram. */
3729 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3731 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3732 tagentry
->tag_data
[0] = '\0';
3736 /* Open the index file, which contains the tag names. */
3739 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3743 /* Skip the header block */
3744 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3746 /* Debug, print 10 first characters of the tag
3749 logf("TAG:%s", buf);
3750 lseek(fd, -10, SEEK_CUR);
3753 /* Write first data byte in tag as \0 */
3756 /* Now tag data has been removed */
3761 /* Write index entry back into master index. */
3762 lseek(masterfd
, sizeof(struct master_header
) +
3763 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3764 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3766 logf("delete_entry(): write_error #2");
3785 * Returns true if there is an event waiting in the queue
3786 * that requires the current operation to be aborted.
3788 static bool check_event_queue(void)
3790 struct queue_event ev
;
3792 if(!queue_peek(&tagcache_queue
, &ev
))
3799 case SYS_USB_CONNECTED
:
3807 #ifdef HAVE_TC_RAMCACHE
3808 static bool allocate_tagcache(void)
3810 struct master_header tcmh
;
3813 /* Load the header. */
3814 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3823 * Now calculate the required cache size plus
3824 * some extra space for alignment fixes.
3826 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3827 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3828 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3829 memset(hdr
, 0, sizeof(struct ramcache_header
));
3830 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3831 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3832 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3837 # ifdef HAVE_EEPROM_SETTINGS
3838 static bool tagcache_dumpload(void)
3840 struct statefile_header shdr
;
3845 fd
= open(TAGCACHE_STATEFILE
, O_RDONLY
);
3848 logf("no tagcache statedump");
3852 /* Check the statefile memory placement */
3853 hdr
= buffer_alloc(0);
3854 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3855 if (rc
!= sizeof(struct statefile_header
)
3856 /* || (long)hdr != (long)shdr.hdr */)
3858 logf("incorrect statefile");
3864 offpos
= (long)hdr
- (long)shdr
.hdr
;
3866 /* Lets allocate real memory and load it */
3867 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3868 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3871 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3873 logf("read failure!");
3878 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3880 /* Now fix the pointers */
3881 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3882 for (i
= 0; i
< TAG_COUNT
; i
++)
3883 hdr
->tags
[i
] += offpos
;
3888 static bool tagcache_dumpsave(void)
3890 struct statefile_header shdr
;
3893 if (!tc_stat
.ramcache
)
3896 fd
= open(TAGCACHE_STATEFILE
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3899 logf("failed to create a statedump");
3903 /* Create the header */
3905 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3906 write(fd
, &shdr
, sizeof(struct statefile_header
));
3908 /* And dump the data too */
3909 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3916 static bool load_tagcache(void)
3918 struct tagcache_header
*tch
;
3919 long bytesleft
= tc_stat
.ramcache_allocated
;
3920 struct index_entry
*idx
;
3925 # ifdef HAVE_DIRCACHE
3926 while (dircache_is_initializing())
3929 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3932 logf("loading tagcache to ram...");
3934 fd
= open(TAGCACHE_FILE_MASTER
, O_RDONLY
);
3937 logf("tagcache open failed");
3941 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3942 != sizeof(struct master_header
)
3943 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3945 logf("incorrect header");
3951 /* Load the master index table. */
3952 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3954 rc
= ecread_index_entry(fd
, idx
);
3955 if (rc
!= sizeof(struct index_entry
))
3957 logf("read error #10");
3962 bytesleft
-= sizeof(struct index_entry
);
3963 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3965 logf("too big tagcache.");
3975 /* Load the tags. */
3977 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3979 struct tagfile_entry
*fe
;
3980 char buf
[TAG_MAXLEN
+32];
3982 if (TAGCACHE_IS_NUMERIC(tag
))
3985 //p = ((void *)p+1);
3986 p
= (char *)((long)p
& ~0x03) + 0x04;
3989 /* Check the header. */
3990 tch
= (struct tagcache_header
*)p
;
3991 p
+= sizeof(struct tagcache_header
);
3993 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3996 for (hdr
->entry_count
[tag
] = 0;
3997 hdr
->entry_count
[tag
] < tch
->entry_count
;
3998 hdr
->entry_count
[tag
]++)
4002 if (do_timed_yield())
4004 /* Abort if we got a critical event in queue */
4005 if (check_event_queue())
4009 fe
= (struct tagfile_entry
*)p
;
4010 pos
= lseek(fd
, 0, SEEK_CUR
);
4011 rc
= ecread_tagfile_entry(fd
, fe
);
4012 if (rc
!= sizeof(struct tagfile_entry
))
4014 /* End of lookup table. */
4015 logf("read error #11");
4020 /* We have a special handling for the filename tags. */
4021 if (tag
== tag_filename
)
4023 # ifdef HAVE_DIRCACHE
4024 const struct dircache_entry
*dc
;
4027 // FIXME: This is wrong!
4028 // idx = &hdr->indices[hdr->entry_count[i]];
4029 idx
= &hdr
->indices
[fe
->idx_id
];
4031 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
4035 logf("TAG:%s", buf
);
4036 logf("too long filename");
4041 rc
= read(fd
, buf
, fe
->tag_length
);
4042 if (rc
!= fe
->tag_length
)
4044 logf("read error #12");
4049 /* Check if the entry has already been removed */
4050 if (idx
->flag
& FLAG_DELETED
)
4053 /* This flag must not be used yet. */
4054 if (idx
->flag
& FLAG_DIRCACHE
)
4056 logf("internal error!");
4061 if (idx
->tag_seek
[tag
] != pos
)
4063 logf("corrupt data structures!");
4068 # ifdef HAVE_DIRCACHE
4069 if (dircache_is_enabled())
4071 dc
= dircache_get_entry_ptr(buf
);
4074 logf("Entry no longer valid.");
4076 if (global_settings
.tagcache_autoupdate
)
4077 delete_entry(fe
->idx_id
);
4081 idx
->flag
|= FLAG_DIRCACHE
;
4082 idx
->tag_seek
[tag_filename
] = (long)dc
;
4087 /* This will be very slow unless dircache is enabled
4088 or target is flash based, but do it anyway for
4090 /* Check if entry has been removed. */
4091 if (global_settings
.tagcache_autoupdate
)
4093 if (!file_exists(buf
))
4095 logf("Entry no longer valid.");
4097 delete_entry(fe
->idx_id
);
4106 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
4109 logf("too big tagcache #2");
4110 logf("tl: %ld", fe
->tag_length
);
4111 logf("bl: %ld", bytesleft
);
4117 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
4120 if (rc
!= fe
->tag_length
)
4122 logf("read error #13");
4123 logf("rc=0x%04x", rc
); // 0x431
4124 logf("len=0x%04lx", fe
->tag_length
); // 0x4000
4125 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
4126 logf("tag=0x%02x", tag
); // 0x00
4134 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4135 logf("tagcache loaded into ram!");
4139 #endif /* HAVE_TC_RAMCACHE */
4141 static bool check_deleted_files(void)
4144 char buf
[TAG_MAXLEN
+32];
4145 struct tagfile_entry tfe
;
4147 logf("reverse scan...");
4148 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4149 fd
= open(buf
, O_RDONLY
);
4153 logf("%s open fail", buf
);
4157 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4158 while (ecread_tagfile_entry(fd
, &tfe
) == sizeof(struct tagfile_entry
)
4160 && !check_event_queue()
4164 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4166 logf("too long tag");
4171 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4173 logf("read error #14");
4178 /* Check if the file has already deleted from the db. */
4182 /* Now check if the file exists. */
4183 if (!file_exists(buf
))
4185 logf("Entry no longer valid.");
4186 logf("-> %s / %ld", buf
, tfe
.tag_length
);
4187 delete_entry(tfe
.idx_id
);
4199 /* Note that this function must not be inlined, otherwise the whole point
4200 * of having the code in a separate function is lost.
4202 static void __attribute__ ((noinline
)) check_ignore(const char *dirname
,
4203 int *ignore
, int *unignore
)
4205 char newpath
[MAX_PATH
];
4207 /* check for a database.ignore file */
4208 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4209 *ignore
= file_exists(newpath
);
4210 /* check for a database.unignore file */
4211 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4212 *unignore
= file_exists(newpath
);
4215 static struct search_roots_ll
{
4217 struct search_roots_ll
* next
;
4222 * This adds a path to the search roots, possibly during traveling through
4223 * the filesystem. It only adds if the path is not inside an already existing
4226 * Returns true if it added the path to the search roots
4228 * Windows 2000 and greater supports symlinks, but they don't provide
4229 * realpath() or readlink(), and symlinks are rarely used on them so
4230 * ignore this for windows for now
4232 static bool add_search_root(const char *name
)
4236 struct search_roots_ll
*this, *prev
= NULL
;
4237 char target
[MAX_PATH
];
4238 /* Okay, realpath() is almost completely broken on android
4240 * It doesn't accept NULL for resolved_name to dynamically allocate
4241 * the resulting path; and it assumes resolved_name to be PATH_MAX
4242 * (actually MAXPATHLEN, but it's the same [as of 2.3]) long
4243 * and blindly writes to the end if it
4245 * therefore use sufficiently large static storage here
4246 * Note that PATH_MAX != MAX_PATH
4248 static char abs_target
[PATH_MAX
];
4251 len
= readlink(name
, target
, sizeof(target
));
4256 if (realpath(target
, abs_target
) == NULL
)
4259 for(this = &roots_ll
; this; prev
= this, this = this->next
)
4261 size_t root_len
= strlen(this->path
);
4262 /* check if the link target is inside of an existing search root
4263 * don't add if target is inside, we'll scan it later */
4264 if (!strncmp(this->path
, abs_target
, root_len
))
4270 size_t len
= strlen(abs_target
) + 1; /* count \0 */
4271 this = malloc(sizeof(struct search_roots_ll
) + len
);
4272 if (!this || len
> MAX_PATH
)
4274 logf("Error at adding a search root: %s", this ? "path too long":"OOM");
4279 this->path
= ((char*)this) + sizeof(struct search_roots_ll
);
4280 strcpy((char*)this->path
, abs_target
); /* ok to cast const away here */
4283 logf("Added %s to the search roots\n", abs_target
);
4290 static int free_search_roots(struct search_roots_ll
* start
)
4295 ret
+= free_search_roots(start
->next
);
4296 ret
+= sizeof(struct search_roots_ll
);
4301 #else /* native, simulator */
4302 #define add_search_root(a) do {} while(0)
4303 #define free_search_roots(a) do {} while(0)
4306 static bool check_dir(const char *dirname
, int add_files
)
4310 int success
= false;
4311 int ignore
, unignore
;
4313 dir
= opendir(dirname
);
4316 logf("tagcache: opendir(%s) failed", dirname
);
4319 /* check for a database.ignore and database.unignore */
4320 check_ignore(dirname
, &ignore
, &unignore
);
4322 /* don't do anything if both ignore and unignore are there */
4323 if (ignore
!= unignore
)
4324 add_files
= unignore
;
4326 /* Recursively scan the dir. */
4330 while (!check_event_queue())
4333 struct dirent
*entry
= readdir(dir
);
4340 if (!strcmp((char *)entry
->d_name
, ".") ||
4341 !strcmp((char *)entry
->d_name
, ".."))
4344 struct dirinfo info
= dir_get_info(dir
, entry
);
4348 len
= strlen(curpath
);
4349 /* don't add an extra / for curpath == / */
4350 if (len
<= 1) len
= 0;
4351 snprintf(&curpath
[len
], sizeof(curpath
) - len
, "/%s", entry
->d_name
);
4353 processed_dir_count
++;
4354 if (info
.attribute
& ATTR_DIRECTORY
)
4356 { /* don't follow symlinks to dirs, but try to add it as a search root
4357 * this makes able to avoid looping in recursive symlinks */
4358 if (info
.attribute
& ATTR_LINK
)
4359 add_search_root(curpath
);
4361 check_dir(curpath
, add_files
);
4364 check_dir(curpath
, add_files
);
4368 tc_stat
.curentry
= curpath
;
4370 /* Add a new entry to the temporary db file. */
4371 add_tagcache(curpath
, (info
.wrtdate
<< 16) | info
.wrttime
4372 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4373 , dir
->internal_entry
4377 /* Wait until current path for debug screen is read and unset. */
4378 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4381 tc_stat
.curentry
= NULL
;
4384 curpath
[len
] = '\0';
4392 void tagcache_screensync_event(void)
4394 tc_stat
.curentry
= NULL
;
4397 void tagcache_screensync_enable(bool state
)
4399 tc_stat
.syncscreen
= state
;
4402 void tagcache_build(const char *path
)
4404 struct tagcache_header header
;
4409 total_entry_count
= 0;
4410 processed_dir_count
= 0;
4412 #ifdef HAVE_DIRCACHE
4413 while (dircache_is_initializing())
4417 logf("updating tagcache");
4419 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
4422 logf("skipping, cache already waiting for commit");
4427 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDWR
| O_CREAT
| O_TRUNC
, 0666);
4430 logf("master file open failed: %s", TAGCACHE_FILE_TEMP
);
4434 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4438 logf("Scanning files...");
4439 /* Scan for new files. */
4440 memset(&header
, 0, sizeof(struct tagcache_header
));
4441 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4444 roots_ll
.path
= path
;
4445 roots_ll
.next
= NULL
;
4446 struct search_roots_ll
* this;
4447 /* check_dir might add new roots */
4448 for(this = &roots_ll
; this; this = this->next
)
4450 strcpy(curpath
, this->path
);
4451 ret
= ret
&& check_dir(this->path
, true);
4454 free_search_roots(roots_ll
.next
);
4456 /* Write the header. */
4457 header
.magic
= TAGCACHE_MAGIC
;
4458 header
.datasize
= data_size
;
4459 header
.entry_count
= total_entry_count
;
4460 lseek(cachefd
, 0, SEEK_SET
);
4461 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4464 if (filenametag_fd
>= 0)
4466 close(filenametag_fd
);
4467 filenametag_fd
= -1;
4477 /* Commit changes to the database. */
4483 logf("tagcache built!");
4489 #ifdef HAVE_TC_RAMCACHE
4492 /* Import runtime statistics if we just initialized the db. */
4493 if (hdr
->h
.serial
== 0)
4494 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4501 #ifdef HAVE_TC_RAMCACHE
4502 static void load_ramcache(void)
4509 /* At first we should load the cache (if exists). */
4510 tc_stat
.ramcache
= load_tagcache();
4512 if (!tc_stat
.ramcache
)
4514 /* If loading failed, it must indicate some problem with the db
4515 * so disable it entirely to prevent further issues. */
4516 tc_stat
.ready
= false;
4523 void tagcache_unload_ramcache(void)
4525 tc_stat
.ramcache
= false;
4526 /* Just to make sure there is no statefile present. */
4527 // remove(TAGCACHE_STATEFILE);
4532 static void tagcache_thread(void)
4534 struct queue_event ev
;
4535 bool check_done
= false;
4537 /* If the previous cache build/update was interrupted, commit
4538 * the changes first in foreground. */
4544 #ifdef HAVE_TC_RAMCACHE
4545 # ifdef HAVE_EEPROM_SETTINGS
4546 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
4547 && global_settings
.tagcache_ram
)
4549 check_done
= tagcache_dumpload();
4552 remove(TAGCACHE_STATEFILE
);
4555 /* Allocate space for the tagcache if found on disk. */
4556 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4557 allocate_tagcache();
4561 tc_stat
.initialized
= true;
4563 /* Don't delay bootup with the header check but do it on background. */
4567 tc_stat
.ready
= check_all_headers();
4568 tc_stat
.readyvalid
= true;
4573 run_command_queue(false);
4575 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4579 case Q_IMPORT_CHANGELOG
:
4580 tagcache_import_changelog();
4585 remove(TAGCACHE_FILE_TEMP
);
4586 tagcache_build("/");
4590 tagcache_build("/");
4591 #ifdef HAVE_TC_RAMCACHE
4594 check_deleted_files();
4600 if (check_done
|| !tc_stat
.ready
)
4603 #ifdef HAVE_TC_RAMCACHE
4604 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4607 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4608 tagcache_build("/");
4612 if (global_settings
.tagcache_autoupdate
)
4614 tagcache_build("/");
4616 /* This will be very slow unless dircache is enabled
4617 or target is flash based, but do it anyway for
4619 check_deleted_files();
4622 logf("tagcache check done");
4633 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4634 case SYS_USB_CONNECTED
:
4635 logf("USB: TagCache");
4636 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4637 usb_wait_for_disconnect(&tagcache_queue
);
4644 bool tagcache_prepare_shutdown(void)
4646 if (tagcache_get_commit_step() > 0)
4649 tagcache_stop_scan();
4650 while (read_lock
|| write_lock
)
4656 void tagcache_shutdown(void)
4658 /* Flush the command queue. */
4659 run_command_queue(true);
4661 #ifdef HAVE_EEPROM_SETTINGS
4662 if (tc_stat
.ramcache
)
4663 tagcache_dumpsave();
4667 static int get_progress(void)
4669 int total_count
= -1;
4671 #ifdef HAVE_DIRCACHE
4672 if (dircache_is_enabled())
4674 total_count
= dircache_get_entry_count();
4678 #ifdef HAVE_TC_RAMCACHE
4680 if (hdr
&& tc_stat
.ramcache
)
4681 total_count
= hdr
->h
.tch
.entry_count
;
4685 if (total_count
< 0)
4688 return processed_dir_count
* 100 / total_count
;
4691 struct tagcache_stat
* tagcache_get_stat(void)
4693 tc_stat
.progress
= get_progress();
4694 tc_stat
.processed_entries
= processed_dir_count
;
4699 void tagcache_start_scan(void)
4701 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4704 bool tagcache_update(void)
4709 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4713 bool tagcache_rebuild()
4715 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4719 void tagcache_stop_scan(void)
4721 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4724 #ifdef HAVE_TC_RAMCACHE
4725 bool tagcache_is_ramcache(void)
4727 return tc_stat
.ramcache
;
4731 #endif /* !__PCTOOL__ */
4734 void tagcache_init(void)
4736 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4737 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4738 filenametag_fd
= -1;
4739 write_lock
= read_lock
= 0;
4742 mutex_init(&command_queue_mutex
);
4743 queue_init(&tagcache_queue
, true);
4744 create_thread(tagcache_thread
, tagcache_stack
,
4745 sizeof(tagcache_stack
), 0, tagcache_thread_name
4746 IF_PRIO(, PRIORITY_BACKGROUND
)
4749 tc_stat
.initialized
= true;
4753 tc_stat
.ready
= check_all_headers();
4758 void tagcache_reverse_scan(void)
4760 logf("Checking for deleted files");
4761 check_deleted_files();
4765 bool tagcache_is_initialized(void)
4767 return tc_stat
.initialized
;
4769 bool tagcache_is_fully_initialized(void)
4771 return tc_stat
.readyvalid
;
4773 bool tagcache_is_usable(void)
4775 return tc_stat
.initialized
&& tc_stat
.ready
;
4777 int tagcache_get_commit_step(void)
4779 return tc_stat
.commit_step
;
4781 int tagcache_get_max_commit_step(void)
4783 return (int)(SORTED_TAGS_COUNT
)+1;