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() */
67 #include "ata_idle_notify.h"
72 #include "string-extra.h"
81 #include "filefuncs.h"
87 #include "eeprom_settings.h"
91 #define yield() do { } while(0)
92 #define sim_sleep(timeout) do { } while(0)
93 #define do_timed_yield() do { } while(0)
97 /* Tag Cache thread. */
98 static struct event_queue tagcache_queue
;
99 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
100 static const char tagcache_thread_name
[] = "tagcache";
103 /* Previous path when scanning directory tree recursively. */
104 static char curpath
[TAG_MAXLEN
+32];
106 /* Used when removing duplicates. */
107 static char *tempbuf
; /* Allocated when needed. */
108 static long tempbufidx
; /* Current location in buffer. */
109 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
110 static long tempbuf_left
; /* Buffer space left. */
111 static long tempbuf_pos
;
113 #define SORTED_TAGS_COUNT 8
114 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
115 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
116 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
117 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
118 /* Tags we want to get sorted (loaded to the tempbuf). */
119 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
120 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
121 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
123 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
124 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
125 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
126 (1LU << tag_albumartist) | (1LU << tag_grouping))
128 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
129 static const char *tags_str
[] = { "artist", "album", "genre", "title",
130 "filename", "composer", "comment", "albumartist", "grouping", "year",
131 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
132 "playtime", "lastplayed", "commitid", "mtime" };
134 /* Status information of the tagcache. */
135 static struct tagcache_stat tc_stat
;
137 /* Queue commands. */
138 enum tagcache_queue
{
145 /* Internal tagcache command queue. */
146 CMD_UPDATE_MASTER_HEADER
,
150 struct tagcache_command_entry
{
158 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
159 static volatile int command_queue_widx
= 0;
160 static volatile int command_queue_ridx
= 0;
161 static struct mutex command_queue_mutex
;
164 /* Tag database structures. */
166 /* Variable-length tag entry in tag files. */
167 struct tagfile_entry
{
168 int32_t tag_length
; /* Length of the data in bytes including '\0' */
169 int32_t idx_id
; /* Corresponding entry location in index file of not unique tags */
170 char tag_data
[0]; /* Begin of the tag data */
173 /* Fixed-size tag entry in master db index. */
175 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
176 int32_t flag
; /* Status flags */
179 /* Header is the same in every file. */
180 struct tagcache_header
{
181 int32_t magic
; /* Header version number */
182 int32_t datasize
; /* Data size in bytes */
183 int32_t entry_count
; /* Number of entries in this file */
186 struct master_header
{
187 struct tagcache_header tch
;
188 int32_t serial
; /* Increasing counting number */
189 int32_t commitid
; /* Number of commits so far */
193 /* For the endianess correction */
194 static const char *tagfile_entry_ec
= "ll";
196 Note: This should be (1 + TAG_COUNT) amount of l's.
198 static const char *index_entry_ec
= "lllllllllllllllllllll";
200 static const char *tagcache_header_ec
= "lll";
201 static const char *master_header_ec
= "llllll";
203 static struct master_header current_tcmh
;
205 #ifdef HAVE_TC_RAMCACHE
206 /* Header is created when loading database to ram. */
207 struct ramcache_header
{
208 struct master_header h
; /* Header from the master index */
209 struct index_entry
*indices
; /* Master index file content */
210 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
211 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
214 # ifdef HAVE_EEPROM_SETTINGS
215 struct statefile_header
{
216 struct ramcache_header
*hdr
;
217 struct tagcache_stat tc_stat
;
221 /* Pointer to allocated ramcache_header */
222 static struct ramcache_header
*hdr
;
226 * Full tag entries stored in a temporary file waiting
227 * for commit to the cache. */
228 struct temp_file_entry
{
229 long tag_offset
[TAG_COUNT
];
230 short tag_length
[TAG_COUNT
];
236 struct tempbuf_id_list
{
238 struct tempbuf_id_list
*next
;
241 struct tempbuf_searchidx
{
245 struct tempbuf_id_list idlist
;
248 /* Lookup buffer for fixing messed up index while after sorting. */
249 static long commit_entry_count
;
250 static long lookup_buffer_depth
;
251 static struct tempbuf_searchidx
**lookup
;
253 /* Used when building the temporary file. */
254 static int cachefd
= -1, filenametag_fd
;
255 static int total_entry_count
= 0;
256 static int data_size
= 0;
257 static int processed_dir_count
;
259 /* Thread safe locking */
260 static volatile int write_lock
;
261 static volatile int read_lock
;
263 static bool delete_entry(long idx_id
);
265 const char* tagcache_tag_to_str(int tag
)
267 return tags_str
[tag
];
270 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
271 static ssize_t
ecread_tagfile_entry(int fd
, struct tagfile_entry
*buf
)
273 return ecread(fd
, buf
, 1, tagfile_entry_ec
, tc_stat
.econ
);
276 static ssize_t
ecread_index_entry(int fd
, struct index_entry
*buf
)
278 return ecread(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
281 static ssize_t
ecwrite_index_entry(int fd
, struct index_entry
*buf
)
283 return ecwrite(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
288 * Returns true if specified flag is still present, i.e., dircache
289 * has not been reloaded.
291 static bool is_dircache_intact(void)
293 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
297 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
303 if (TAGCACHE_IS_NUMERIC(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
306 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
308 fd
= open(buf
, write
? O_RDWR
: O_RDONLY
);
311 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
312 tc_stat
.ready
= false;
316 /* Check the header. */
317 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
318 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
320 logf("header error");
321 tc_stat
.ready
= false;
329 static int open_master_fd(struct master_header
*hdr
, bool write
)
334 fd
= open(TAGCACHE_FILE_MASTER
, write
? O_RDWR
: O_RDONLY
);
337 logf("master file open failed for R/W");
338 tc_stat
.ready
= false;
342 tc_stat
.econ
= false;
344 /* Check the header. */
345 rc
= read(fd
, hdr
, sizeof(struct master_header
));
346 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
352 /* Trying to read again, this time with endianess correction enabled. */
353 lseek(fd
, 0, SEEK_SET
);
355 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
356 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
358 logf("header error");
359 tc_stat
.ready
= false;
370 static bool do_timed_yield(void)
372 /* Sorting can lock up for quite a while, so yield occasionally */
373 static long wakeup_tick
= 0;
374 if (TIME_AFTER(current_tick
, wakeup_tick
))
376 wakeup_tick
= current_tick
+ (HZ
/4);
384 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
385 static long find_entry_ram(const char *filename
,
386 const struct dircache_entry
*dc
)
388 static long last_pos
= 0;
391 /* Check if tagcache is loaded into ram. */
392 if (!tc_stat
.ramcache
)
396 dc
= dircache_get_entry_ptr(filename
);
400 logf("tagcache: file not found.");
411 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
413 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
415 last_pos
= MAX(0, i
- 3);
432 static long find_entry_disk(const char *filename
, bool localfd
)
434 struct tagcache_header tch
;
435 static long last_pos
= -1;
436 long pos_history
[POS_HISTORY_COUNT
];
437 long pos_history_idx
= 0;
439 struct tagfile_entry tfe
;
441 char buf
[TAG_MAXLEN
+32];
449 if (fd
< 0 || localfd
)
452 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
459 lseek(fd
, last_pos
, SEEK_SET
);
461 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
465 pos
= lseek(fd
, 0, SEEK_CUR
);
466 for (i
= pos_history_idx
-1; i
>= 0; i
--)
467 pos_history
[i
+1] = pos_history
[i
];
468 pos_history
[0] = pos
;
470 if (ecread_tagfile_entry(fd
, &tfe
)
471 != sizeof(struct tagfile_entry
))
476 if (tfe
.tag_length
>= (long)sizeof(buf
))
478 logf("too long tag #1");
486 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
488 logf("read error #2");
496 if (!strcasecmp(filename
, buf
))
498 last_pos
= pos_history
[pos_history_idx
];
503 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
517 if (fd
!= filenametag_fd
|| localfd
)
522 if (fd
!= filenametag_fd
|| localfd
)
528 static int find_index(const char *filename
)
532 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
533 if (tc_stat
.ramcache
&& is_dircache_intact())
534 idx_id
= find_entry_ram(filename
, NULL
);
538 idx_id
= find_entry_disk(filename
, true);
543 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
550 idx_id
= find_index(filename
);
554 if (!tagcache_search(tcs
, tag_filename
))
557 tcs
->entry_count
= 0;
558 tcs
->idx_id
= idx_id
;
563 static bool get_index(int masterfd
, int idxid
,
564 struct index_entry
*idx
, bool use_ram
)
566 bool localfd
= false;
570 logf("Incorrect idxid: %d", idxid
);
574 #ifdef HAVE_TC_RAMCACHE
575 if (tc_stat
.ramcache
&& use_ram
)
577 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
580 # ifdef HAVE_DIRCACHE
581 if (!(hdr
->indices
[idxid
].flag
& FLAG_DIRCACHE
)
582 || is_dircache_intact())
585 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
595 struct master_header tcmh
;
598 masterfd
= open_master_fd(&tcmh
, false);
603 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
604 + sizeof(struct master_header
), SEEK_SET
);
605 if (ecread_index_entry(masterfd
, idx
)
606 != sizeof(struct index_entry
))
608 logf("read error #3");
618 if (idx
->flag
& FLAG_DELETED
)
626 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
628 /* We need to exclude all memory only flags & tags when writing to disk. */
629 if (idx
->flag
& FLAG_DIRCACHE
)
631 logf("memory only flags!");
635 #ifdef HAVE_TC_RAMCACHE
636 /* Only update numeric data. Writing the whole index to RAM by memcpy
637 * destroys dircache pointers!
639 if (tc_stat
.ramcache
)
642 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
644 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
646 if (TAGCACHE_IS_NUMERIC(tag
))
648 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
652 /* Don't touch the dircache flag or attributes. */
653 idx_ram
->flag
= (idx
->flag
& 0x0000ffff)
654 | (idx_ram
->flag
& (0xffff0000 | FLAG_DIRCACHE
));
658 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
659 + sizeof(struct master_header
), SEEK_SET
);
660 if (ecwrite_index_entry(masterfd
, idx
) != sizeof(struct index_entry
))
662 logf("write error #3");
663 logf("idxid: %d", idxid
);
670 #endif /* !__PCTOOL__ */
672 static bool open_files(struct tagcache_search
*tcs
, int tag
)
674 if (tcs
->idxfd
[tag
] < 0)
678 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
679 tcs
->idxfd
[tag
] = open(fn
, O_RDONLY
);
682 if (tcs
->idxfd
[tag
] < 0)
684 logf("File not open!");
691 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
692 int tag
, char *buf
, long size
)
694 struct tagfile_entry tfe
;
699 if (TAGCACHE_IS_NUMERIC(tag
))
702 seek
= idx
->tag_seek
[tag
];
705 logf("Retrieve failed");
709 #ifdef HAVE_TC_RAMCACHE
712 struct tagfile_entry
*ep
;
714 # ifdef HAVE_DIRCACHE
715 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
716 && is_dircache_intact())
718 dircache_copy_path((struct dircache_entry
*)seek
,
724 if (tag
!= tag_filename
)
726 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
727 strlcpy(buf
, ep
->tag_data
, size
);
734 if (!open_files(tcs
, tag
))
737 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
738 if (ecread_tagfile_entry(tcs
->idxfd
[tag
], &tfe
)
739 != sizeof(struct tagfile_entry
))
741 logf("read error #5");
745 if (tfe
.tag_length
>= size
)
747 logf("too small buffer");
751 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
754 logf("read error #6");
758 buf
[tfe
.tag_length
] = '\0';
763 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
765 static long read_numeric_tag(int tag
, int idx_id
, const struct index_entry
*idx
)
768 if (! COMMAND_QUEUE_IS_EMPTY
)
770 /* Attempt to find tag data through store-to-load forwarding in
774 mutex_lock(&command_queue_mutex
);
776 int ridx
= command_queue_widx
;
778 while (ridx
!= command_queue_ridx
)
781 ridx
= TAGCACHE_COMMAND_QUEUE_LENGTH
- 1;
783 if (command_queue
[ridx
].command
== CMD_UPDATE_NUMERIC
784 && command_queue
[ridx
].idx_id
== idx_id
785 && command_queue
[ridx
].tag
== tag
)
787 result
= command_queue
[ridx
].data
;
792 mutex_unlock(&command_queue_mutex
);
796 logf("read_numeric_tag: "
797 "Recovered tag %d value %lX from write queue",
804 return idx
->tag_seek
[tag
];
808 static long check_virtual_tags(int tag
, int idx_id
,
809 const struct index_entry
*idx
)
815 case tag_virt_length_sec
:
816 data
= (read_numeric_tag(tag_length
, idx_id
, idx
)/1000) % 60;
819 case tag_virt_length_min
:
820 data
= (read_numeric_tag(tag_length
, idx_id
, idx
)/1000) / 60;
823 case tag_virt_playtime_sec
:
824 data
= (read_numeric_tag(tag_playtime
, idx_id
, idx
)/1000) % 60;
827 case tag_virt_playtime_min
:
828 data
= (read_numeric_tag(tag_playtime
, idx_id
, idx
)/1000) / 60;
831 case tag_virt_autoscore
:
832 if (read_numeric_tag(tag_length
, idx_id
, idx
) == 0
833 || read_numeric_tag(tag_playcount
, idx_id
, idx
) == 0)
839 /* A straight calculus gives:
840 autoscore = 100 * playtime / length / playcout (1)
841 Now, consider the euclidian division of playtime by length:
842 playtime = alpha * length + beta
846 autoscore = 100 * (alpha / playcout + beta / length / playcount)
847 Both terms should be small enough to avoid any overflow
849 data
= 100 * (read_numeric_tag(tag_playtime
, idx_id
, idx
)
850 / read_numeric_tag(tag_length
, idx_id
, idx
))
851 + (100 * (read_numeric_tag(tag_playtime
, idx_id
, idx
)
852 % read_numeric_tag(tag_length
, idx_id
, idx
)))
853 / read_numeric_tag(tag_length
, idx_id
, idx
);
854 data
/= read_numeric_tag(tag_playcount
, idx_id
, idx
);
858 /* How many commits before the file has been added to the DB. */
859 case tag_virt_entryage
:
860 data
= current_tcmh
.commitid
861 - read_numeric_tag(tag_commitid
, idx_id
, idx
) - 1;
865 data
= read_numeric_tag(tag
, idx_id
, idx
);
871 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
873 struct index_entry idx
;
878 if (!TAGCACHE_IS_NUMERIC(tag
))
881 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
884 return check_virtual_tags(tag
, tcs
->idx_id
, &idx
);
887 inline static bool str_ends_with(const char *str1
, const char *str2
)
889 int str_len
= strlen(str1
);
890 int clause_len
= strlen(str2
);
892 if (clause_len
> str_len
)
895 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
898 inline static bool str_oneof(const char *str
, const char *list
)
901 int l
, len
= strlen(str
);
905 sep
= strchr(list
, '|');
906 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
907 if ((l
==len
) && !strncasecmp(str
, list
, len
))
909 list
+= sep
? l
+ 1 : l
;
915 static bool check_against_clause(long numeric
, const char *str
,
916 const struct tagcache_search_clause
*clause
)
920 switch (clause
->type
)
923 return numeric
== clause
->numeric_data
;
925 return numeric
!= clause
->numeric_data
;
927 return numeric
> clause
->numeric_data
;
929 return numeric
>= clause
->numeric_data
;
931 return numeric
< clause
->numeric_data
;
933 return numeric
<= clause
->numeric_data
;
935 logf("Incorrect numeric tag: %d", clause
->type
);
940 switch (clause
->type
)
943 return !strcasecmp(clause
->str
, str
);
945 return strcasecmp(clause
->str
, str
);
947 return 0>strcasecmp(clause
->str
, str
);
949 return 0>=strcasecmp(clause
->str
, str
);
951 return 0<strcasecmp(clause
->str
, str
);
953 return 0<=strcasecmp(clause
->str
, str
);
954 case clause_contains
:
955 return (strcasestr(str
, clause
->str
) != NULL
);
956 case clause_not_contains
:
957 return (strcasestr(str
, clause
->str
) == NULL
);
958 case clause_begins_with
:
959 return (strcasestr(str
, clause
->str
) == str
);
960 case clause_not_begins_with
:
961 return (strcasestr(str
, clause
->str
) != str
);
962 case clause_ends_with
:
963 return str_ends_with(str
, clause
->str
);
964 case clause_not_ends_with
:
965 return !str_ends_with(str
, clause
->str
);
967 return str_oneof(str
, clause
->str
);
970 logf("Incorrect tag: %d", clause
->type
);
977 static bool check_clauses(struct tagcache_search
*tcs
,
978 struct index_entry
*idx
,
979 struct tagcache_search_clause
**clause
, int count
)
983 #ifdef HAVE_TC_RAMCACHE
986 /* Go through all conditional clauses. */
987 for (i
= 0; i
< count
; i
++)
989 struct tagfile_entry
*tfe
;
994 seek
= check_virtual_tags(clause
[i
]->tag
, tcs
->idx_id
, idx
);
996 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
998 if (clause
[i
]->tag
== tag_filename
)
1000 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
1005 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
1006 str
= tfe
->tag_data
;
1010 if (!check_against_clause(seek
, str
, clause
[i
]))
1017 /* Check for conditions. */
1018 for (i
= 0; i
< count
; i
++)
1020 struct tagfile_entry tfe
;
1024 seek
= check_virtual_tags(clause
[i
]->tag
, tcs
->idx_id
, idx
);
1026 memset(str
, 0, sizeof str
);
1027 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
1029 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
1030 lseek(fd
, seek
, SEEK_SET
);
1031 ecread_tagfile_entry(fd
, &tfe
);
1032 if (tfe
.tag_length
>= (int)sizeof(str
))
1034 logf("Too long tag read!");
1038 read(fd
, str
, tfe
.tag_length
);
1040 /* Check if entry has been deleted. */
1045 if (!check_against_clause(seek
, str
, clause
[i
]))
1053 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
1054 struct tagcache_search_clause
**clause
, int count
)
1056 struct index_entry idx
;
1061 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
1064 return check_clauses(tcs
, &idx
, clause
, count
);
1067 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1071 /* If uniq buffer is not defined we must return true for search to work. */
1072 if (tcs
->unique_list
== NULL
|| (!TAGCACHE_IS_UNIQUE(tcs
->type
)
1073 && !TAGCACHE_IS_NUMERIC(tcs
->type
)))
1078 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1080 /* Return false if entry is found. */
1081 if (tcs
->unique_list
[i
] == id
)
1085 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1087 tcs
->unique_list
[i
] = id
;
1088 tcs
->unique_list_count
++;
1094 static bool build_lookup_list(struct tagcache_search
*tcs
)
1096 struct index_entry entry
;
1099 tcs
->seek_list_count
= 0;
1101 #ifdef HAVE_TC_RAMCACHE
1103 # ifdef HAVE_DIRCACHE
1104 && (tcs
->type
!= tag_filename
|| is_dircache_intact())
1108 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
1110 struct tagcache_seeklist_entry
*seeklist
;
1111 struct index_entry
*idx
= &hdr
->indices
[i
];
1112 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1115 /* Skip deleted files. */
1116 if (idx
->flag
& FLAG_DELETED
)
1119 /* Go through all filters.. */
1120 for (j
= 0; j
< tcs
->filter_count
; j
++)
1122 if (idx
->tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1128 if (j
< tcs
->filter_count
)
1131 /* Check for conditions. */
1132 if (!check_clauses(tcs
, idx
, tcs
->clause
, tcs
->clause_count
))
1135 /* Add to the seek list if not already in uniq buffer. */
1136 if (!add_uniqbuf(tcs
, idx
->tag_seek
[tcs
->type
]))
1140 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1141 seeklist
->seek
= idx
->tag_seek
[tcs
->type
];
1142 seeklist
->flag
= idx
->flag
;
1143 seeklist
->idx_id
= i
;
1144 tcs
->seek_list_count
++;
1149 return tcs
->seek_list_count
> 0;
1153 if (tcs
->masterfd
< 0)
1155 struct master_header tcmh
;
1156 tcs
->masterfd
= open_master_fd(&tcmh
, false);
1159 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1160 sizeof(struct master_header
), SEEK_SET
);
1162 while (ecread_index_entry(tcs
->masterfd
, &entry
)
1163 == sizeof(struct index_entry
))
1165 struct tagcache_seeklist_entry
*seeklist
;
1167 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1173 /* Check if entry has been deleted. */
1174 if (entry
.flag
& FLAG_DELETED
)
1177 /* Go through all filters.. */
1178 for (j
= 0; j
< tcs
->filter_count
; j
++)
1180 if (entry
.tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1184 if (j
< tcs
->filter_count
)
1187 /* Check for conditions. */
1188 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1191 /* Add to the seek list if not already in uniq buffer. */
1192 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1196 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1197 seeklist
->seek
= entry
.tag_seek
[tcs
->type
];
1198 seeklist
->flag
= entry
.flag
;
1199 seeklist
->idx_id
= i
;
1200 tcs
->seek_list_count
++;
1205 return tcs
->seek_list_count
> 0;
1209 static void remove_files(void)
1214 tc_stat
.ready
= false;
1215 tc_stat
.ramcache
= false;
1216 tc_stat
.econ
= false;
1217 remove(TAGCACHE_FILE_MASTER
);
1218 for (i
= 0; i
< TAG_COUNT
; i
++)
1220 if (TAGCACHE_IS_NUMERIC(i
))
1223 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1229 static bool check_all_headers(void)
1231 struct master_header myhdr
;
1232 struct tagcache_header tch
;
1236 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1242 logf("tagcache is dirty!");
1246 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1248 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1250 if (TAGCACHE_IS_NUMERIC(tag
))
1253 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1262 bool tagcache_is_busy(void)
1264 return read_lock
|| write_lock
;
1267 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1269 struct tagcache_header tag_hdr
;
1270 struct master_header master_hdr
;
1276 memset(tcs
, 0, sizeof(struct tagcache_search
));
1277 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1280 tcs
->position
= sizeof(struct tagcache_header
);
1283 tcs
->list_position
= 0;
1284 tcs
->seek_list_count
= 0;
1285 tcs
->filter_count
= 0;
1288 for (i
= 0; i
< TAG_COUNT
; i
++)
1291 #ifndef HAVE_TC_RAMCACHE
1292 tcs
->ramsearch
= false;
1294 tcs
->ramsearch
= tc_stat
.ramcache
;
1297 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1302 /* Always open as R/W so we can pass tcs to functions that modify data also
1303 * without failing. */
1304 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1305 if (tcs
->masterfd
< 0)
1308 if (!TAGCACHE_IS_NUMERIC(tcs
->type
))
1310 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1311 if (tcs
->idxfd
[tcs
->type
] < 0)
1314 tcs
->entry_count
= tag_hdr
.entry_count
;
1318 tcs
->entry_count
= master_hdr
.tch
.entry_count
;
1323 tcs
->initialized
= true;
1329 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1330 void *buffer
, long length
)
1332 tcs
->unique_list
= (unsigned long *)buffer
;
1333 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1334 tcs
->unique_list_count
= 0;
1337 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1340 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1343 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag
))
1346 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1347 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1348 tcs
->filter_count
++;
1353 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1354 struct tagcache_search_clause
*clause
)
1358 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1360 logf("Too many clauses");
1364 /* Check if there is already a similar filter in present (filters are
1365 * much faster than clauses).
1367 for (i
= 0; i
< tcs
->filter_count
; i
++)
1369 if (tcs
->filter_tag
[i
] == clause
->tag
)
1373 if (!TAGCACHE_IS_NUMERIC(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1377 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1378 tcs
->idxfd
[clause
->tag
] = open(buf
, O_RDONLY
);
1381 tcs
->clause
[tcs
->clause_count
] = clause
;
1382 tcs
->clause_count
++;
1387 static bool get_next(struct tagcache_search
*tcs
)
1389 static char buf
[TAG_MAXLEN
+32];
1390 struct tagfile_entry entry
;
1393 if (!tcs
->valid
|| !tc_stat
.ready
)
1396 if (tcs
->idxfd
[tcs
->type
] < 0 && !TAGCACHE_IS_NUMERIC(tcs
->type
)
1397 #ifdef HAVE_TC_RAMCACHE
1403 /* Relative fetch. */
1404 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1405 || TAGCACHE_IS_NUMERIC(tcs
->type
)
1406 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1407 /* We need to retrieve flag status for dircache. */
1408 || (tcs
->ramsearch
&& tcs
->type
== tag_filename
)
1412 struct tagcache_seeklist_entry
*seeklist
;
1414 /* Check for end of list. */
1415 if (tcs
->list_position
== tcs
->seek_list_count
)
1417 tcs
->list_position
= 0;
1419 /* Try to fetch more. */
1420 if (!build_lookup_list(tcs
))
1427 seeklist
= &tcs
->seeklist
[tcs
->list_position
];
1428 flag
= seeklist
->flag
;
1429 tcs
->position
= seeklist
->seek
;
1430 tcs
->idx_id
= seeklist
->idx_id
;
1431 tcs
->list_position
++;
1435 if (tcs
->entry_count
== 0)
1444 tcs
->result_seek
= tcs
->position
;
1446 if (TAGCACHE_IS_NUMERIC(tcs
->type
))
1448 snprintf(buf
, sizeof(buf
), "%ld", tcs
->position
);
1450 tcs
->result_len
= strlen(buf
) + 1;
1455 #ifdef HAVE_TC_RAMCACHE
1459 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1460 if (tcs
->type
== tag_filename
&& (flag
& FLAG_DIRCACHE
)
1461 && is_dircache_intact())
1463 dircache_copy_path((struct dircache_entry
*)tcs
->position
,
1466 tcs
->result_len
= strlen(buf
) + 1;
1467 tcs
->ramresult
= false;
1473 if (tcs
->type
!= tag_filename
)
1475 struct tagfile_entry
*ep
;
1477 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1478 tcs
->result
= ep
->tag_data
;
1479 tcs
->result_len
= strlen(tcs
->result
) + 1;
1480 tcs
->idx_id
= ep
->idx_id
;
1481 tcs
->ramresult
= true;
1483 /* Increase position for the next run. This may get overwritten. */
1484 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1491 if (!open_files(tcs
, tcs
->type
))
1497 /* Seek stream to the correct position and continue to direct fetch. */
1498 lseek(tcs
->idxfd
[tcs
->type
], tcs
->position
, SEEK_SET
);
1500 if (ecread_tagfile_entry(tcs
->idxfd
[tcs
->type
], &entry
) != sizeof(struct tagfile_entry
))
1502 logf("read error #5");
1507 if (entry
.tag_length
> (long)sizeof(buf
))
1510 logf("too long tag #2");
1511 logf("P:%lX/%lX", tcs
->position
, entry
.tag_length
);
1515 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1518 logf("read error #4");
1523 Update the position for the next read (this may be overridden
1524 if filters or clauses are being used).
1526 tcs
->position
+= sizeof(struct tagfile_entry
) + entry
.tag_length
;
1528 tcs
->result_len
= strlen(tcs
->result
) + 1;
1529 tcs
->idx_id
= entry
.idx_id
;
1530 tcs
->ramresult
= false;
1535 bool tagcache_get_next(struct tagcache_search
*tcs
)
1537 while (get_next(tcs
))
1539 if (tcs
->result_len
> 1)
1546 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1547 int tag
, char *buf
, long size
)
1549 struct index_entry idx
;
1552 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1555 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1558 static bool update_master_header(void)
1560 struct master_header myhdr
;
1566 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1569 myhdr
.serial
= current_tcmh
.serial
;
1570 myhdr
.commitid
= current_tcmh
.commitid
;
1571 myhdr
.dirty
= current_tcmh
.dirty
;
1574 lseek(fd
, 0, SEEK_SET
);
1575 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1578 #ifdef HAVE_TC_RAMCACHE
1581 hdr
->h
.serial
= current_tcmh
.serial
;
1582 hdr
->h
.commitid
= current_tcmh
.commitid
;
1583 hdr
->h
.dirty
= current_tcmh
.dirty
;
1592 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1594 struct tagentry
*entry
;
1596 if (tcs
->type
!= tag_title
)
1599 /* We will need reserve buffer for this. */
1602 struct tagfile_entry
*ep
;
1604 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1605 tcs
->seek_list
[tcs
->seek_list_count
];
1608 entry
= find_entry_ram();
1613 void tagcache_search_finish(struct tagcache_search
*tcs
)
1617 if (!tcs
->initialized
)
1620 if (tcs
->masterfd
>= 0)
1622 close(tcs
->masterfd
);
1626 for (i
= 0; i
< TAG_COUNT
; i
++)
1628 if (tcs
->idxfd
[i
] >= 0)
1630 close(tcs
->idxfd
[i
]);
1635 tcs
->ramsearch
= false;
1637 tcs
->initialized
= 0;
1642 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1643 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1645 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1648 static long get_tag_numeric(const struct index_entry
*entry
, int tag
, int idx_id
)
1650 return check_virtual_tags(tag
, idx_id
, entry
);
1653 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1655 char* s
= get_tag(entry
, tag
)->tag_data
;
1656 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1659 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1661 struct index_entry
*entry
;
1664 if (!tc_stat
.ready
|| !tc_stat
.ramcache
)
1667 /* Find the corresponding entry in tagcache. */
1668 idx_id
= find_entry_ram(filename
, NULL
);
1672 entry
= &hdr
->indices
[idx_id
];
1674 memset(id3
, 0, sizeof(struct mp3entry
));
1676 id3
->title
= get_tag_string(entry
, tag_title
);
1677 id3
->artist
= get_tag_string(entry
, tag_artist
);
1678 id3
->album
= get_tag_string(entry
, tag_album
);
1679 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1680 id3
->composer
= get_tag_string(entry
, tag_composer
);
1681 id3
->comment
= get_tag_string(entry
, tag_comment
);
1682 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1683 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1685 id3
->length
= get_tag_numeric(entry
, tag_length
, idx_id
);
1686 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
, idx_id
);
1687 id3
->rating
= get_tag_numeric(entry
, tag_rating
, idx_id
);
1688 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
, idx_id
);
1689 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
, idx_id
) / 10;
1690 id3
->year
= get_tag_numeric(entry
, tag_year
, idx_id
);
1692 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
, idx_id
);
1693 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
, idx_id
);
1694 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
, idx_id
);
1695 if (id3
->bitrate
== 0)
1702 static inline void write_item(const char *item
)
1704 int len
= strlen(item
) + 1;
1707 write(cachefd
, item
, len
);
1710 static int check_if_empty(char **tag
)
1714 if (*tag
== NULL
|| **tag
== '\0')
1717 return sizeof(UNTAGGED
); /* Tag length */
1720 length
= strlen(*tag
);
1721 if (length
> TAG_MAXLEN
)
1723 logf("over length tag: %s", *tag
);
1724 length
= TAG_MAXLEN
;
1725 (*tag
)[length
] = '\0';
1731 #define ADD_TAG(entry,tag,data) \
1733 entry.tag_offset[tag] = offset; \
1734 entry.tag_length[tag] = check_if_empty(data); \
1735 offset += entry.tag_length[tag]
1736 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1737 * idea, as it uses lots of stack and is called from a recursive function
1740 static void __attribute__ ((noinline
)) add_tagcache(char *path
,
1742 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1743 ,const struct dircache_entry
*dc
1747 struct mp3entry id3
;
1748 struct temp_file_entry entry
;
1752 char tracknumfix
[3];
1754 int path_length
= strlen(path
);
1755 bool has_albumartist
;
1759 /* Crude logging for the sim - to aid in debugging */
1760 int logfd
= open(ROCKBOX_DIR
"/database.log",
1761 O_WRONLY
| O_APPEND
| O_CREAT
, 0666);
1763 write(logfd
, path
, strlen(path
));
1764 write(logfd
, "\n", 1);
1772 /* Check for overlength file path. */
1773 if (path_length
> TAG_MAXLEN
)
1775 /* Path can't be shortened. */
1776 logf("Too long path: %s", path
);
1780 /* Check if the file is supported. */
1781 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1784 /* Check if the file is already cached. */
1785 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1786 if (tc_stat
.ramcache
&& is_dircache_intact())
1788 idx_id
= find_entry_ram(path
, dc
);
1792 /* Be sure the entry doesn't exist. */
1793 if (filenametag_fd
>= 0 && idx_id
< 0)
1794 idx_id
= find_entry_disk(path
, false);
1796 /* Check if file has been modified. */
1799 struct index_entry idx
;
1801 /* TODO: Mark that the index exists (for fast reverse scan) */
1802 //found_idx[idx_id/8] |= idx_id%8;
1804 if (!get_index(-1, idx_id
, &idx
, true))
1806 logf("failed to retrieve index entry");
1810 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1812 /* No changes to file. */
1816 /* Metadata might have been changed. Delete the entry. */
1817 logf("Re-adding: %s", path
);
1818 if (!delete_entry(idx_id
))
1820 logf("delete_entry failed: %d", idx_id
);
1825 fd
= open(path
, O_RDONLY
);
1828 logf("open fail: %s", path
);
1832 memset(&id3
, 0, sizeof(struct mp3entry
));
1833 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1834 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1835 ret
= get_metadata(&id3
, fd
, path
);
1841 logf("-> %s", path
);
1843 /* Generate track number if missing. */
1844 if (id3
.tracknum
<= 0)
1846 const char *p
= strrchr(path
, '.');
1849 p
= &path
[strlen(path
)-1];
1853 if (isdigit(*p
) && isdigit(*(p
-1)))
1855 tracknumfix
[1] = *p
--;
1856 tracknumfix
[0] = *p
;
1862 if (tracknumfix
[0] != '\0')
1864 id3
.tracknum
= atoi(tracknumfix
);
1865 /* Set a flag to indicate track number has been generated. */
1866 entry
.flag
|= FLAG_TRKNUMGEN
;
1870 /* Unable to generate track number. */
1876 entry
.tag_offset
[tag_year
] = id3
.year
;
1877 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1878 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1879 entry
.tag_offset
[tag_length
] = id3
.length
;
1880 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1881 entry
.tag_offset
[tag_mtime
] = mtime
;
1884 has_albumartist
= id3
.albumartist
!= NULL
1885 && strlen(id3
.albumartist
) > 0;
1886 has_grouping
= id3
.grouping
!= NULL
1887 && strlen(id3
.grouping
) > 0;
1889 ADD_TAG(entry
, tag_filename
, &path
);
1890 ADD_TAG(entry
, tag_title
, &id3
.title
);
1891 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1892 ADD_TAG(entry
, tag_album
, &id3
.album
);
1893 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1894 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1895 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1896 if (has_albumartist
)
1898 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1902 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1906 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1910 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1912 entry
.data_length
= offset
;
1914 /* Write the header */
1915 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1917 /* And tags also... Correct order is critical */
1919 write_item(id3
.title
);
1920 write_item(id3
.artist
);
1921 write_item(id3
.album
);
1922 write_item(id3
.genre_string
);
1923 write_item(id3
.composer
);
1924 write_item(id3
.comment
);
1925 if (has_albumartist
)
1927 write_item(id3
.albumartist
);
1931 write_item(id3
.artist
);
1935 write_item(id3
.grouping
);
1939 write_item(id3
.title
);
1941 total_entry_count
++;
1944 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1946 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1947 int len
= strlen(str
)+1;
1950 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1951 char buf
[TAG_MAXLEN
+32];
1953 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1954 buf
[i
] = tolower(str
[i
]);
1957 crc32
= crc_32(buf
, i
, 0xffffffff);
1961 /* Check if the crc does not exist -> entry does not exist for sure. */
1962 for (i
= 0; i
< tempbufidx
; i
++)
1964 if (crcbuf
[-i
] != crc32
)
1967 if (!strcasecmp(str
, index
[i
].str
))
1969 if (id
< 0 || id
>= lookup_buffer_depth
)
1971 logf("lookup buf overf.: %d", id
);
1975 lookup
[id
] = &index
[i
];
1981 /* Insert to CRC buffer. */
1982 crcbuf
[-tempbufidx
] = crc32
;
1985 /* Insert it to the buffer. */
1986 tempbuf_left
-= len
;
1987 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1990 if (id
>= lookup_buffer_depth
)
1992 logf("lookup buf overf. #2: %d", id
);
1998 lookup
[id
] = &index
[tempbufidx
];
1999 index
[tempbufidx
].idlist
.id
= id
;
2002 index
[tempbufidx
].idlist
.id
= -1;
2004 index
[tempbufidx
].idlist
.next
= NULL
;
2005 index
[tempbufidx
].idx_id
= idx_id
;
2006 index
[tempbufidx
].seek
= -1;
2007 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
2008 memcpy(index
[tempbufidx
].str
, str
, len
);
2015 static int compare(const void *p1
, const void *p2
)
2019 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
2020 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
2022 if (strcmp(e1
->str
, UNTAGGED
) == 0)
2024 if (strcmp(e2
->str
, UNTAGGED
) == 0)
2028 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
2031 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
2034 static int tempbuf_sort(int fd
)
2036 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
2037 struct tagfile_entry fe
;
2041 /* Generate reverse lookup entries. */
2042 for (i
= 0; i
< lookup_buffer_depth
; i
++)
2044 struct tempbuf_id_list
*idlist
;
2049 if (lookup
[i
]->idlist
.id
== i
)
2052 idlist
= &lookup
[i
]->idlist
;
2053 while (idlist
->next
!= NULL
)
2054 idlist
= idlist
->next
;
2056 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
2057 if (tempbuf_left
- 4 < 0)
2060 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2061 if (tempbuf_pos
& 0x03)
2063 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
2065 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2067 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
2069 idlist
= idlist
->next
;
2071 idlist
->next
= NULL
;
2076 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
2077 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
2079 for (i
= 0; i
< tempbufidx
; i
++)
2081 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
2083 /* Fix the lookup list. */
2084 while (idlist
!= NULL
)
2086 if (idlist
->id
>= 0)
2087 lookup
[idlist
->id
] = &index
[i
];
2088 idlist
= idlist
->next
;
2091 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
2092 length
= strlen(index
[i
].str
) + 1;
2093 fe
.tag_length
= length
;
2094 fe
.idx_id
= index
[i
].idx_id
;
2096 /* Check the chunk alignment. */
2097 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2098 % TAGFILE_ENTRY_CHUNK_LENGTH
)
2100 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
2101 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2102 % TAGFILE_ENTRY_CHUNK_LENGTH
);
2105 #ifdef TAGCACHE_STRICT_ALIGN
2106 /* Make sure the entry is long aligned. */
2107 if (index
[i
].seek
& 0x03)
2109 logf("tempbuf_sort: alignment error!");
2114 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2115 sizeof(struct tagfile_entry
))
2117 logf("tempbuf_sort: write error #1");
2121 if (write(fd
, index
[i
].str
, length
) != length
)
2123 logf("tempbuf_sort: write error #2");
2127 /* Write some padding. */
2128 if (fe
.tag_length
- length
> 0)
2129 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2135 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2137 if (id
< 0 || id
>= lookup_buffer_depth
)
2144 inline static int tempbuf_find_location(int id
)
2146 struct tempbuf_searchidx
*entry
;
2148 entry
= tempbuf_locate(id
);
2155 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2157 struct master_header tcmh
;
2158 struct index_entry idx
;
2161 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2163 int entries_processed
= 0;
2165 char buf
[TAG_MAXLEN
];
2167 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2169 logf("Building numeric indices...");
2170 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2172 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2175 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2177 if (masterfd_pos
== filesize(masterfd
))
2179 logf("we can't append!");
2184 while (entries_processed
< h
->entry_count
)
2186 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2188 /* Read in as many entries as possible. */
2189 for (i
= 0; i
< count
; i
++)
2191 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2194 /* Read in numeric data. */
2195 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2196 sizeof(struct temp_file_entry
))
2198 logf("read fail #1");
2203 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2206 * Read string data from the following tags:
2212 * A crc32 hash is calculated from the read data
2213 * and stored back to the data offset field kept in memory.
2215 #define tmpdb_read_string_tag(tag) \
2216 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2217 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2219 logf("read fail: buffer overflow"); \
2224 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2225 tfe->tag_length[tag]) \
2227 logf("read fail #2"); \
2232 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2233 lseek(tmpfd, datastart, SEEK_SET)
2235 tmpdb_read_string_tag(tag_filename
);
2236 tmpdb_read_string_tag(tag_artist
);
2237 tmpdb_read_string_tag(tag_album
);
2238 tmpdb_read_string_tag(tag_title
);
2240 /* Seek to the end of the string data. */
2241 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2244 /* Backup the master index position. */
2245 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2246 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2248 /* Check if we can resurrect some deleted runtime statistics data. */
2249 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2251 /* Read the index entry. */
2252 if (ecread_index_entry(masterfd
, &idx
)
2253 != sizeof(struct index_entry
))
2255 logf("read fail #3");
2261 * Skip unless the entry is marked as being deleted
2262 * or the data has already been resurrected.
2264 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2267 /* Now try to match the entry. */
2269 * To succesfully match a song, the following conditions
2272 * For numeric fields: tag_length
2273 * - Full identical match is required
2275 * If tag_filename matches, no further checking necessary.
2277 * For string hashes: tag_artist, tag_album, tag_title
2278 * - Two of these must match
2280 for (j
= 0; j
< count
; j
++)
2282 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2284 /* Try to match numeric fields first. */
2285 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2288 /* Now it's time to do the hash matching. */
2289 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2291 int match_count
= 0;
2293 /* No filename match, check if we can match two other tags. */
2294 #define tmpdb_match(tag) \
2295 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2298 tmpdb_match(tag_artist
);
2299 tmpdb_match(tag_album
);
2300 tmpdb_match(tag_title
);
2302 if (match_count
< 2)
2304 /* Still no match found, give up. */
2309 /* A match found, now copy & resurrect the statistical data. */
2310 #define tmpdb_copy_tag(tag) \
2311 tfe->tag_offset[tag] = idx.tag_seek[tag]
2313 tmpdb_copy_tag(tag_playcount
);
2314 tmpdb_copy_tag(tag_rating
);
2315 tmpdb_copy_tag(tag_playtime
);
2316 tmpdb_copy_tag(tag_lastplayed
);
2317 tmpdb_copy_tag(tag_commitid
);
2319 /* Avoid processing this entry again. */
2320 idx
.flag
|= FLAG_RESURRECTED
;
2322 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2323 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2325 logf("masterfd writeback fail #1");
2330 logf("Entry resurrected");
2335 /* Restore the master index position. */
2336 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2338 /* Commit the data to the index. */
2339 for (i
= 0; i
< count
; i
++)
2341 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2343 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2345 logf("read fail #3");
2350 for (j
= 0; j
< TAG_COUNT
; j
++)
2352 if (!TAGCACHE_IS_NUMERIC(j
))
2355 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2357 idx
.flag
= entrybuf
[i
].flag
;
2359 if (idx
.tag_seek
[tag_commitid
])
2361 /* Data has been resurrected. */
2362 idx
.flag
|= FLAG_DIRTYNUM
;
2364 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2366 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2367 idx
.flag
|= FLAG_DIRTYNUM
;
2370 /* Write back the updated index. */
2371 lseek(masterfd
, loc
, SEEK_SET
);
2372 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2380 entries_processed
+= count
;
2381 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2392 * == 0 temporary failure
2395 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2398 struct tagcache_header tch
;
2399 struct master_header tcmh
;
2400 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2402 char buf
[TAG_MAXLEN
+32];
2403 int fd
= -1, masterfd
;
2408 logf("Building index: %d", index_type
);
2410 /* Check the number of entries we need to allocate ram for. */
2411 commit_entry_count
= h
->entry_count
+ 1;
2413 masterfd
= open_master_fd(&tcmh
, false);
2416 commit_entry_count
+= tcmh
.tch
.entry_count
;
2420 remove_files(); /* Just to be sure we are clean. */
2422 /* Open the index file, which contains the tag names. */
2423 fd
= open_tag_fd(&tch
, index_type
, true);
2426 logf("tch.datasize=%ld", tch
.datasize
);
2427 lookup_buffer_depth
= 1 +
2428 /* First part */ commit_entry_count
+
2429 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2433 lookup_buffer_depth
= 1 +
2434 /* First part */ commit_entry_count
+
2435 /* Second part */ 0;
2438 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2439 logf("commit_entry_count=%ld", commit_entry_count
);
2441 /* Allocate buffer for all index entries from both old and new
2444 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2446 /* Allocate lookup buffer. The first portion of commit_entry_count
2447 * contains the new tags in the temporary file and the second
2448 * part for locating entries already in the db.
2451 * +---------+---------------------------+
2452 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2453 * +---------+---------------------------+
2455 * Old tags are inserted to a temporary buffer with position:
2456 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2457 * And new tags with index:
2458 * tempbuf_insert(idx, ...);
2460 * The buffer is sorted and written into tag file:
2461 * tempbuf_sort(...);
2462 * leaving master index locations messed up.
2464 * That is fixed using the lookup buffer for old tags:
2465 * new_seek = tempbuf_find_location(old_seek, ...);
2467 * new_seek = tempbuf_find_location(idx);
2469 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2470 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2471 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2473 /* And calculate the remaining data space used mainly for storing
2474 * tag data (strings). */
2475 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2476 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2478 logf("Buffer way too small!");
2485 * If tag file contains unique tags (sorted index), we will load
2486 * it entirely into memory so we can resort it later for use with
2489 if (TAGCACHE_IS_SORTED(index_type
))
2491 logf("loading tags...");
2492 for (i
= 0; i
< tch
.entry_count
; i
++)
2494 struct tagfile_entry entry
;
2495 int loc
= lseek(fd
, 0, SEEK_CUR
);
2498 if (ecread_tagfile_entry(fd
, &entry
) != sizeof(struct tagfile_entry
))
2500 logf("read error #7");
2505 if (entry
.tag_length
>= (int)sizeof(buf
))
2507 logf("too long tag #3");
2512 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2514 logf("read error #8");
2519 /* Skip deleted entries. */
2524 * Save the tag and tag id in the memory buffer. Tag id
2525 * is saved so we can later reindex the master lookup
2526 * table when the index gets resorted.
2528 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2529 + commit_entry_count
, entry
.idx_id
,
2530 TAGCACHE_IS_UNIQUE(index_type
));
2541 tempbufidx
= tch
.entry_count
;
2546 * Creating new index file to store the tags. No need to preload
2547 * anything whether the index type is sorted or not.
2549 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2550 fd
= open(buf
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2553 logf("%s open fail", buf
);
2557 tch
.magic
= TAGCACHE_MAGIC
;
2558 tch
.entry_count
= 0;
2561 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2562 != sizeof(struct tagcache_header
))
2564 logf("header write failed");
2570 /* Loading the tag lookup file as "master file". */
2571 logf("Loading index file");
2572 masterfd
= open(TAGCACHE_FILE_MASTER
, O_RDWR
);
2576 logf("Creating new DB");
2577 masterfd
= open(TAGCACHE_FILE_MASTER
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2581 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER
);
2586 /* Write the header (write real values later). */
2587 memset(&tcmh
, 0, sizeof(struct master_header
));
2589 tcmh
.tch
.entry_count
= 0;
2590 tcmh
.tch
.datasize
= 0;
2592 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2594 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2599 * Master file already exists so we need to process the current
2604 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2605 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2607 logf("header error");
2614 * If we reach end of the master file, we need to expand it to
2615 * hold new tags. If the current index is not sorted, we can
2616 * simply append new data to end of the file.
2617 * However, if the index is sorted, we need to update all tag
2618 * pointers in the master file for the current index.
2620 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2622 if (masterfd_pos
== filesize(masterfd
))
2624 logf("appending...");
2630 * Load new unique tags in memory to be sorted later and added
2631 * to the master lookup file.
2633 if (TAGCACHE_IS_SORTED(index_type
))
2635 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2636 /* h is the header of the temporary file containing new tags. */
2637 logf("inserting new tags...");
2638 for (i
= 0; i
< h
->entry_count
; i
++)
2640 struct temp_file_entry entry
;
2642 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2643 sizeof(struct temp_file_entry
))
2645 logf("read fail #3");
2651 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2653 logf("too long entry!");
2658 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2659 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2660 entry
.tag_length
[index_type
])
2662 logf("read fail #4");
2667 if (TAGCACHE_IS_UNIQUE(index_type
))
2668 error
= !tempbuf_insert(buf
, i
, -1, true);
2670 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2674 logf("insert error");
2679 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2680 entry
.tag_length
[index_type
], SEEK_CUR
);
2685 /* Sort the buffer data and write it to the index file. */
2686 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2688 * We need to truncate the index file now. There can be junk left
2689 * at the end of file (however, we _should_ always follow the
2690 * entry_count and don't crash with that).
2692 ftruncate(fd
, lseek(fd
, 0, SEEK_CUR
));
2694 i
= tempbuf_sort(fd
);
2697 logf("sorted %d tags", i
);
2700 * Now update all indexes in the master lookup file.
2702 logf("updating indices...");
2703 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2704 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2707 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2709 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2711 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2712 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2714 logf("read fail #5");
2718 lseek(masterfd
, loc
, SEEK_SET
);
2720 for (j
= 0; j
< idxbuf_pos
; j
++)
2722 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2724 /* We can just ignore deleted entries. */
2725 // idxbuf[j].tag_seek[index_type] = 0;
2729 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2730 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2731 + commit_entry_count
);
2733 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2735 logf("update error: %ld/%d/%ld",
2736 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2744 /* Write back the updated index. */
2745 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2746 index_entry_ec
, tc_stat
.econ
) !=
2747 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2758 * Walk through the temporary file containing the new tags.
2760 // build_normal_index(h, tmpfd, masterfd, idx);
2761 logf("updating new indices...");
2762 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2763 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2764 lseek(fd
, 0, SEEK_END
);
2765 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2769 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2772 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2776 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2778 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2779 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2781 logf("read fail #6");
2785 lseek(masterfd
, loc
, SEEK_SET
);
2788 /* Read entry headers. */
2789 for (j
= 0; j
< idxbuf_pos
; j
++)
2791 if (!TAGCACHE_IS_SORTED(index_type
))
2793 struct temp_file_entry entry
;
2794 struct tagfile_entry fe
;
2796 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2797 sizeof(struct temp_file_entry
))
2799 logf("read fail #7");
2805 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2807 logf("too long entry!");
2808 logf("length=%d", entry
.tag_length
[index_type
]);
2809 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2814 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2815 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2816 entry
.tag_length
[index_type
])
2818 logf("read fail #8");
2819 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2820 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2825 /* Write to index file. */
2826 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2827 fe
.tag_length
= entry
.tag_length
[index_type
];
2828 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2829 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2830 write(fd
, buf
, fe
.tag_length
);
2834 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2835 entry
.tag_length
[index_type
], SEEK_CUR
);
2839 /* Locate the correct entry from the sorted array. */
2840 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2841 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2843 logf("entry not found (%d)", j
);
2851 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2852 index_entry_ec
, tc_stat
.econ
) !=
2853 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2855 logf("tagcache: write fail #4");
2864 /* Finally write the header. */
2865 tch
.magic
= TAGCACHE_MAGIC
;
2866 tch
.entry_count
= tempbufidx
;
2867 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2868 lseek(fd
, 0, SEEK_SET
);
2869 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2871 if (index_type
!= tag_filename
)
2872 h
->datasize
+= tch
.datasize
;
2873 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2885 static bool commit(void)
2887 struct tagcache_header tch
;
2888 struct master_header tcmh
;
2892 #ifdef HAVE_DIRCACHE
2893 bool dircache_buffer_stolen
= false;
2895 bool local_allocation
= false;
2897 logf("committing tagcache");
2902 tmpfd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
2905 logf("nothing to commit");
2910 /* Load the header. */
2911 len
= sizeof(struct tagcache_header
);
2912 rc
= read(tmpfd
, &tch
, len
);
2914 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2916 logf("incorrect tmpheader");
2918 remove(TAGCACHE_FILE_TEMP
);
2922 if (tch
.entry_count
== 0)
2924 logf("nothing to commit");
2926 remove(TAGCACHE_FILE_TEMP
);
2930 /* Fully initialize existing headers (if any) before going further. */
2931 tc_stat
.ready
= check_all_headers();
2933 #ifdef HAVE_EEPROM_SETTINGS
2934 remove(TAGCACHE_STATEFILE
);
2937 /* At first be sure to unload the ramcache! */
2938 #ifdef HAVE_TC_RAMCACHE
2939 tc_stat
.ramcache
= false;
2944 /* Try to steal every buffer we can :) */
2945 if (tempbuf_size
== 0)
2946 local_allocation
= true;
2948 #ifdef HAVE_DIRCACHE
2949 if (tempbuf_size
== 0)
2951 /* Try to steal the dircache buffer. */
2952 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2953 tempbuf_size
&= ~0x03;
2955 if (tempbuf_size
> 0)
2957 dircache_buffer_stolen
= true;
2962 #ifdef HAVE_TC_RAMCACHE
2963 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2965 tempbuf
= (char *)(hdr
+ 1);
2966 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2967 tempbuf_size
&= ~0x03;
2971 /* And finally fail if there are no buffers available. */
2972 if (tempbuf_size
== 0)
2974 logf("delaying commit until next boot");
2975 tc_stat
.commit_delayed
= true;
2981 logf("commit %ld entries...", tch
.entry_count
);
2983 /* Mark DB dirty so it will stay disabled if commit fails. */
2984 current_tcmh
.dirty
= true;
2985 update_master_header();
2987 /* Now create the index files. */
2988 tc_stat
.commit_step
= 0;
2990 tc_stat
.commit_delayed
= false;
2992 for (i
= 0; i
< TAG_COUNT
; i
++)
2996 if (TAGCACHE_IS_NUMERIC(i
))
2999 tc_stat
.commit_step
++;
3000 ret
= build_index(i
, &tch
, tmpfd
);
3004 logf("tagcache failed init");
3006 tc_stat
.commit_delayed
= true;
3008 tc_stat
.commit_step
= 0;
3014 if (!build_numeric_indices(&tch
, tmpfd
))
3016 logf("Failure to commit numeric indices");
3018 tc_stat
.commit_step
= 0;
3024 remove(TAGCACHE_FILE_TEMP
);
3026 tc_stat
.commit_step
= 0;
3028 /* Update the master index headers. */
3029 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
3035 tcmh
.tch
.entry_count
+= tch
.entry_count
;
3036 tcmh
.tch
.datasize
= sizeof(struct master_header
)
3037 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
3042 lseek(masterfd
, 0, SEEK_SET
);
3043 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
3046 logf("tagcache committed");
3047 tc_stat
.ready
= check_all_headers();
3048 tc_stat
.readyvalid
= true;
3050 if (local_allocation
)
3056 #ifdef HAVE_DIRCACHE
3057 /* Rebuild the dircache, if we stole the buffer. */
3058 if (dircache_buffer_stolen
)
3062 #ifdef HAVE_TC_RAMCACHE
3063 /* Reload tagcache. */
3064 if (tc_stat
.ramcache_allocated
> 0)
3065 tagcache_start_scan();
3073 static void allocate_tempbuf(void)
3075 /* Yeah, malloc would be really nice now :) */
3077 tempbuf_size
= 32*1024*1024;
3078 tempbuf
= malloc(tempbuf_size
);
3080 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
3081 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
3082 audiobuf
+= tempbuf_size
;
3086 static void free_tempbuf(void)
3088 if (tempbuf_size
== 0)
3094 audiobuf
-= tempbuf_size
;
3102 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
3104 struct index_entry idx
;
3109 if (!TAGCACHE_IS_NUMERIC(tag
))
3112 if (!get_index(masterfd
, idx_id
, &idx
, false))
3115 idx
.tag_seek
[tag
] = data
;
3116 idx
.flag
|= FLAG_DIRTYNUM
;
3118 return write_index(masterfd
, idx_id
, &idx
);
3122 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3125 struct master_header myhdr
;
3127 if (tcs
->masterfd
< 0)
3129 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3133 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3137 static bool command_queue_is_full(void)
3141 next
= command_queue_widx
+ 1;
3142 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3145 return (next
== command_queue_ridx
);
3148 static void command_queue_sync_callback(void *data
)
3151 struct master_header myhdr
;
3154 mutex_lock(&command_queue_mutex
);
3156 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3159 while (command_queue_ridx
!= command_queue_widx
)
3161 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3163 switch (ce
->command
)
3165 case CMD_UPDATE_MASTER_HEADER
:
3168 update_master_header();
3170 /* Re-open the masterfd. */
3171 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3176 case CMD_UPDATE_NUMERIC
:
3178 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3183 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3184 command_queue_ridx
= 0;
3189 tc_stat
.queue_length
= 0;
3190 mutex_unlock(&command_queue_mutex
);
3193 static void run_command_queue(bool force
)
3195 if (COMMAND_QUEUE_IS_EMPTY
)
3198 if (force
|| command_queue_is_full())
3199 command_queue_sync_callback(NULL
);
3201 register_storage_idle_func(command_queue_sync_callback
);
3204 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3210 mutex_lock(&command_queue_mutex
);
3211 next
= command_queue_widx
+ 1;
3212 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3215 /* Make sure queue is not full. */
3216 if (next
!= command_queue_ridx
)
3218 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3221 ce
->idx_id
= idx_id
;
3225 command_queue_widx
= next
;
3227 tc_stat
.queue_length
++;
3229 mutex_unlock(&command_queue_mutex
);
3233 /* Queue is full, try again later... */
3234 mutex_unlock(&command_queue_mutex
);
3239 long tagcache_increase_serial(void)
3249 old
= current_tcmh
.serial
++;
3250 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3255 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3257 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3259 #endif /* !__PCTOOL__ */
3261 long tagcache_get_serial(void)
3263 return current_tcmh
.serial
;
3266 long tagcache_get_commitid(void)
3268 return current_tcmh
.commitid
;
3271 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3276 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3277 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3279 if (*datastr
== '\0')
3282 if (*datastr
== '"' || *datastr
== '\\')
3285 buf
[i
] = *(datastr
++);
3288 strcpy(&buf
[i
], "\" ");
3290 write(fd
, buf
, i
+ 2);
3297 static bool read_tag(char *dest
, long size
,
3298 const char *src
, const char *tagstr
)
3301 char current_tag
[32];
3303 while (*src
!= '\0')
3305 /* Skip all whitespace */
3313 /* Read in tag name */
3314 while (*src
!= '=' && *src
!= ' ')
3316 current_tag
[pos
] = *src
;
3320 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3323 current_tag
[pos
] = '\0';
3325 /* Read in tag data */
3327 /* Find the start. */
3328 while (*src
!= '"' && *src
!= '\0')
3331 if (*src
== '\0' || *(++src
) == '\0')
3334 /* Read the data. */
3335 for (pos
= 0; pos
< size
; pos
++)
3342 dest
[pos
] = *(src
+1);
3362 if (!strcasecmp(tagstr
, current_tag
))
3369 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3371 struct index_entry idx
;
3372 char tag_data
[TAG_MAXLEN
+32];
3374 long masterfd
= (long)parameters
;
3375 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3383 logf("%d/%s", line_n
, buf
);
3384 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3386 logf("filename missing");
3391 idx_id
= find_index(tag_data
);
3394 logf("entry not found");
3398 if (!get_index(masterfd
, idx_id
, &idx
, false))
3400 logf("failed to retrieve index entry");
3404 /* Stop if tag has already been modified. */
3405 if (idx
.flag
& FLAG_DIRTYNUM
)
3408 logf("import: %s", tag_data
);
3410 idx
.flag
|= FLAG_DIRTYNUM
;
3411 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3415 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3416 tagcache_tag_to_str(import_tags
[i
])))
3421 data
= atoi(tag_data
);
3425 idx
.tag_seek
[import_tags
[i
]] = data
;
3427 if (import_tags
[i
] == tag_lastplayed
&& data
>= current_tcmh
.serial
)
3428 current_tcmh
.serial
= data
+ 1;
3429 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3430 current_tcmh
.commitid
= data
+ 1;
3433 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3436 bool tagcache_import_changelog(void)
3438 struct master_header myhdr
;
3439 struct tagcache_header tch
;
3450 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_RDONLY
);
3453 logf("failure to open changelog");
3457 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3465 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3467 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3468 parse_changelog_line
);
3473 if (filenametag_fd
>= 0)
3475 close(filenametag_fd
);
3476 filenametag_fd
= -1;
3481 update_master_header();
3486 #endif /* !__PCTOOL__ */
3488 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3490 struct master_header myhdr
;
3491 struct index_entry idx
;
3492 char buf
[TAG_MAXLEN
+32];
3500 if (!tagcache_search(tcs
, tag_filename
))
3503 /* Initialize the changelog */
3504 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3507 logf("failure to open changelog");
3511 if (tcs
->masterfd
< 0)
3513 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3518 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3519 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3522 write(clfd
, "## Changelog version 1\n", 23);
3524 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3526 if (ecread_index_entry(tcs
->masterfd
, &idx
) != sizeof(struct index_entry
))
3528 logf("read error #9");
3529 tagcache_search_finish(tcs
);
3534 /* Skip until the entry found has been modified. */
3535 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3538 /* Skip deleted entries too. */
3539 if (idx
.flag
& FLAG_DELETED
)
3542 /* Now retrieve all tags. */
3543 for (j
= 0; j
< TAG_COUNT
; j
++)
3545 if (TAGCACHE_IS_NUMERIC(j
))
3547 snprintf(temp
, sizeof temp
, "%d", (int)idx
.tag_seek
[j
]);
3548 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3553 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3554 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3557 write(clfd
, "\n", 1);
3563 tagcache_search_finish(tcs
);
3568 static bool delete_entry(long idx_id
)
3573 struct index_entry idx
, myidx
;
3574 struct master_header myhdr
;
3575 char buf
[TAG_MAXLEN
+32];
3576 int in_use
[TAG_COUNT
];
3578 logf("delete_entry(): %ld", idx_id
);
3580 #ifdef HAVE_TC_RAMCACHE
3581 /* At first mark the entry removed from ram cache. */
3582 if (tc_stat
.ramcache
)
3583 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3586 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3589 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3590 if (ecread_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3592 logf("delete_entry(): read error");
3596 if (myidx
.flag
& FLAG_DELETED
)
3598 logf("delete_entry(): already deleted!");
3602 myidx
.flag
|= FLAG_DELETED
;
3603 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3604 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3606 logf("delete_entry(): write_error #1");
3610 /* Now check which tags are no longer in use (if any) */
3611 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3614 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3615 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3617 struct index_entry
*idxp
;
3619 #ifdef HAVE_TC_RAMCACHE
3620 /* Use RAM DB if available for greater speed */
3621 if (tc_stat
.ramcache
)
3622 idxp
= &hdr
->indices
[i
];
3626 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
3628 logf("delete_entry(): read error #2");
3634 if (idxp
->flag
& FLAG_DELETED
)
3637 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3639 if (TAGCACHE_IS_NUMERIC(tag
))
3642 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3647 /* Now delete all tags no longer in use. */
3648 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3650 struct tagcache_header tch
;
3651 int oldseek
= myidx
.tag_seek
[tag
];
3653 if (TAGCACHE_IS_NUMERIC(tag
))
3657 * Replace tag seek with a hash value of the field string data.
3658 * That way runtime statistics of moved or altered files can be
3661 #ifdef HAVE_TC_RAMCACHE
3662 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3664 struct tagfile_entry
*tfe
;
3665 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3667 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3668 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3669 myidx
.tag_seek
[tag
] = *seek
;
3674 struct tagfile_entry tfe
;
3676 /* Open the index file, which contains the tag names. */
3677 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3680 /* Skip the header block */
3681 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3682 if (ecread_tagfile_entry(fd
, &tfe
) != sizeof(struct tagfile_entry
))
3684 logf("delete_entry(): read error #3");
3688 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3690 logf("delete_entry(): read error #4");
3694 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3699 logf("in use: %d/%d", tag
, in_use
[tag
]);
3708 #ifdef HAVE_TC_RAMCACHE
3709 /* Delete from ram. */
3710 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3712 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3713 tagentry
->tag_data
[0] = '\0';
3717 /* Open the index file, which contains the tag names. */
3720 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3724 /* Skip the header block */
3725 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3727 /* Debug, print 10 first characters of the tag
3730 logf("TAG:%s", buf);
3731 lseek(fd, -10, SEEK_CUR);
3734 /* Write first data byte in tag as \0 */
3737 /* Now tag data has been removed */
3742 /* Write index entry back into master index. */
3743 lseek(masterfd
, sizeof(struct master_header
) +
3744 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3745 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3747 logf("delete_entry(): write_error #2");
3766 * Returns true if there is an event waiting in the queue
3767 * that requires the current operation to be aborted.
3769 static bool check_event_queue(void)
3771 struct queue_event ev
;
3773 if(!queue_peek(&tagcache_queue
, &ev
))
3780 case SYS_USB_CONNECTED
:
3788 #ifdef HAVE_TC_RAMCACHE
3789 static bool allocate_tagcache(void)
3791 struct master_header tcmh
;
3794 /* Load the header. */
3795 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3804 * Now calculate the required cache size plus
3805 * some extra space for alignment fixes.
3807 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3808 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3809 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3810 memset(hdr
, 0, sizeof(struct ramcache_header
));
3811 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3812 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3813 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3818 # ifdef HAVE_EEPROM_SETTINGS
3819 static bool tagcache_dumpload(void)
3821 struct statefile_header shdr
;
3826 fd
= open(TAGCACHE_STATEFILE
, O_RDONLY
);
3829 logf("no tagcache statedump");
3833 /* Check the statefile memory placement */
3834 hdr
= buffer_alloc(0);
3835 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3836 if (rc
!= sizeof(struct statefile_header
)
3837 /* || (long)hdr != (long)shdr.hdr */)
3839 logf("incorrect statefile");
3845 offpos
= (long)hdr
- (long)shdr
.hdr
;
3847 /* Lets allocate real memory and load it */
3848 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3849 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3852 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3854 logf("read failure!");
3859 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3861 /* Now fix the pointers */
3862 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3863 for (i
= 0; i
< TAG_COUNT
; i
++)
3864 hdr
->tags
[i
] += offpos
;
3869 static bool tagcache_dumpsave(void)
3871 struct statefile_header shdr
;
3874 if (!tc_stat
.ramcache
)
3877 fd
= open(TAGCACHE_STATEFILE
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3880 logf("failed to create a statedump");
3884 /* Create the header */
3886 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3887 write(fd
, &shdr
, sizeof(struct statefile_header
));
3889 /* And dump the data too */
3890 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3897 static bool load_tagcache(void)
3899 struct tagcache_header
*tch
;
3900 long bytesleft
= tc_stat
.ramcache_allocated
;
3901 struct index_entry
*idx
;
3906 # ifdef HAVE_DIRCACHE
3907 while (dircache_is_initializing())
3910 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3913 logf("loading tagcache to ram...");
3915 fd
= open(TAGCACHE_FILE_MASTER
, O_RDONLY
);
3918 logf("tagcache open failed");
3922 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3923 != sizeof(struct master_header
)
3924 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3926 logf("incorrect header");
3932 /* Load the master index table. */
3933 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3935 rc
= ecread_index_entry(fd
, idx
);
3936 if (rc
!= sizeof(struct index_entry
))
3938 logf("read error #10");
3943 bytesleft
-= sizeof(struct index_entry
);
3944 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3946 logf("too big tagcache.");
3956 /* Load the tags. */
3958 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3960 struct tagfile_entry
*fe
;
3961 char buf
[TAG_MAXLEN
+32];
3963 if (TAGCACHE_IS_NUMERIC(tag
))
3966 //p = ((void *)p+1);
3967 p
= (char *)((long)p
& ~0x03) + 0x04;
3970 /* Check the header. */
3971 tch
= (struct tagcache_header
*)p
;
3972 p
+= sizeof(struct tagcache_header
);
3974 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3977 for (hdr
->entry_count
[tag
] = 0;
3978 hdr
->entry_count
[tag
] < tch
->entry_count
;
3979 hdr
->entry_count
[tag
]++)
3983 if (do_timed_yield())
3985 /* Abort if we got a critical event in queue */
3986 if (check_event_queue())
3990 fe
= (struct tagfile_entry
*)p
;
3991 pos
= lseek(fd
, 0, SEEK_CUR
);
3992 rc
= ecread_tagfile_entry(fd
, fe
);
3993 if (rc
!= sizeof(struct tagfile_entry
))
3995 /* End of lookup table. */
3996 logf("read error #11");
4001 /* We have a special handling for the filename tags. */
4002 if (tag
== tag_filename
)
4004 # ifdef HAVE_DIRCACHE
4005 const struct dircache_entry
*dc
;
4008 // FIXME: This is wrong!
4009 // idx = &hdr->indices[hdr->entry_count[i]];
4010 idx
= &hdr
->indices
[fe
->idx_id
];
4012 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
4016 logf("TAG:%s", buf
);
4017 logf("too long filename");
4022 rc
= read(fd
, buf
, fe
->tag_length
);
4023 if (rc
!= fe
->tag_length
)
4025 logf("read error #12");
4030 /* Check if the entry has already been removed */
4031 if (idx
->flag
& FLAG_DELETED
)
4034 /* This flag must not be used yet. */
4035 if (idx
->flag
& FLAG_DIRCACHE
)
4037 logf("internal error!");
4042 if (idx
->tag_seek
[tag
] != pos
)
4044 logf("corrupt data structures!");
4049 # ifdef HAVE_DIRCACHE
4050 if (dircache_is_enabled())
4052 dc
= dircache_get_entry_ptr(buf
);
4055 logf("Entry no longer valid.");
4057 if (global_settings
.tagcache_autoupdate
)
4058 delete_entry(fe
->idx_id
);
4062 idx
->flag
|= FLAG_DIRCACHE
;
4063 idx
->tag_seek
[tag_filename
] = (long)dc
;
4068 /* This will be very slow unless dircache is enabled
4069 or target is flash based, but do it anyway for
4071 /* Check if entry has been removed. */
4072 if (global_settings
.tagcache_autoupdate
)
4074 if (!file_exists(buf
))
4076 logf("Entry no longer valid.");
4078 delete_entry(fe
->idx_id
);
4087 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
4090 logf("too big tagcache #2");
4091 logf("tl: %ld", fe
->tag_length
);
4092 logf("bl: %ld", bytesleft
);
4098 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
4101 if (rc
!= fe
->tag_length
)
4103 logf("read error #13");
4104 logf("rc=0x%04x", rc
); // 0x431
4105 logf("len=0x%04lx", fe
->tag_length
); // 0x4000
4106 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
4107 logf("tag=0x%02x", tag
); // 0x00
4115 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4116 logf("tagcache loaded into ram!");
4120 #endif /* HAVE_TC_RAMCACHE */
4122 static bool check_deleted_files(void)
4125 char buf
[TAG_MAXLEN
+32];
4126 struct tagfile_entry tfe
;
4128 logf("reverse scan...");
4129 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4130 fd
= open(buf
, O_RDONLY
);
4134 logf("%s open fail", buf
);
4138 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4139 while (ecread_tagfile_entry(fd
, &tfe
) == sizeof(struct tagfile_entry
)
4141 && !check_event_queue()
4145 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4147 logf("too long tag");
4152 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4154 logf("read error #14");
4159 /* Check if the file has already deleted from the db. */
4163 /* Now check if the file exists. */
4164 if (!file_exists(buf
))
4166 logf("Entry no longer valid.");
4167 logf("-> %s / %ld", buf
, tfe
.tag_length
);
4168 delete_entry(tfe
.idx_id
);
4180 /* Note that this function must not be inlined, otherwise the whole point
4181 * of having the code in a separate function is lost.
4183 static void __attribute__ ((noinline
)) check_ignore(const char *dirname
,
4184 int *ignore
, int *unignore
)
4186 char newpath
[MAX_PATH
];
4188 /* check for a database.ignore file */
4189 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4190 *ignore
= file_exists(newpath
);
4191 /* check for a database.unignore file */
4192 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4193 *unignore
= file_exists(newpath
);
4196 static struct search_roots_ll
{
4198 struct search_roots_ll
* next
;
4203 * This adds a path to the search roots, possibly during traveling through
4204 * the filesystem. It only adds if the path is not inside an already existing
4207 * Returns true if it added the path to the search roots
4209 * Windows 2000 and greater supports symlinks, but they don't provide
4210 * realpath() or readlink(), and symlinks are rarely used on them so
4211 * ignore this for windows for now
4213 static bool add_search_root(const char *name
)
4217 struct search_roots_ll
*this, *prev
= NULL
;
4218 char target
[MAX_PATH
];
4219 char _abs_target
[MAX_PATH
];
4223 len
= readlink(name
, target
, sizeof(target
));
4228 /* realpath(target, NULL) doesn't work on android ... */
4229 abs_target
= realpath(target
, _abs_target
);
4230 if (abs_target
== NULL
)
4233 for(this = &roots_ll
; this; prev
= this, this = this->next
)
4235 size_t root_len
= strlen(this->path
);
4236 /* check if the link target is inside of an existing search root
4237 * don't add if target is inside, we'll scan it later */
4238 if (!strncmp(this->path
, abs_target
, root_len
))
4244 size_t len
= strlen(abs_target
) + 1; /* count \0 */
4245 this = malloc(sizeof(struct search_roots_ll
) + len
);
4246 if (!this || len
> MAX_PATH
)
4248 logf("Error at adding a search root: %s", this ? "path too long":"OOM");
4252 this->path
= ((char*)this) + sizeof(struct search_roots_ll
);
4253 strcpy((char*)this->path
, abs_target
); /* ok to cast const away here */
4256 logf("Added %s to the search roots\n", abs_target
);
4263 static int free_search_roots(struct search_roots_ll
* start
)
4268 ret
+= free_search_roots(start
->next
);
4269 ret
+= sizeof(struct search_roots_ll
);
4274 #else /* native, simulator */
4275 #define add_search_root(a) do {} while(0)
4276 #define free_search_roots(a) do {} while(0)
4279 static bool check_dir(const char *dirname
, int add_files
)
4283 int success
= false;
4284 int ignore
, unignore
;
4286 dir
= opendir(dirname
);
4289 logf("tagcache: opendir(%s) failed", dirname
);
4292 /* check for a database.ignore and database.unignore */
4293 check_ignore(dirname
, &ignore
, &unignore
);
4295 /* don't do anything if both ignore and unignore are there */
4296 if (ignore
!= unignore
)
4297 add_files
= unignore
;
4299 /* Recursively scan the dir. */
4303 while (!check_event_queue())
4306 struct dirent
*entry
= readdir(dir
);
4313 if (!strcmp((char *)entry
->d_name
, ".") ||
4314 !strcmp((char *)entry
->d_name
, ".."))
4317 struct dirinfo info
= dir_get_info(dir
, entry
);
4321 len
= strlen(curpath
);
4322 /* don't add an extra / for curpath == / */
4323 if (len
<= 1) len
= 0;
4324 snprintf(&curpath
[len
], sizeof(curpath
) - len
, "/%s", entry
->d_name
);
4326 processed_dir_count
++;
4327 if (info
.attribute
& ATTR_DIRECTORY
)
4328 { /* don't follow symlinks to dirs, but try to add it as a search root
4329 * this makes able to avoid looping in recursive symlinks */
4330 if (info
.attribute
& ATTR_LINK
)
4331 add_search_root(curpath
);
4333 check_dir(curpath
, add_files
);
4337 tc_stat
.curentry
= curpath
;
4339 /* Add a new entry to the temporary db file. */
4340 add_tagcache(curpath
, (info
.wrtdate
<< 16) | info
.wrttime
4341 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4342 , dir
->internal_entry
4346 /* Wait until current path for debug screen is read and unset. */
4347 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4350 tc_stat
.curentry
= NULL
;
4353 curpath
[len
] = '\0';
4361 void tagcache_screensync_event(void)
4363 tc_stat
.curentry
= NULL
;
4366 void tagcache_screensync_enable(bool state
)
4368 tc_stat
.syncscreen
= state
;
4371 void tagcache_build(const char *path
)
4373 struct tagcache_header header
;
4378 total_entry_count
= 0;
4379 processed_dir_count
= 0;
4381 #ifdef HAVE_DIRCACHE
4382 while (dircache_is_initializing())
4386 logf("updating tagcache");
4388 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
4391 logf("skipping, cache already waiting for commit");
4396 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDWR
| O_CREAT
| O_TRUNC
, 0666);
4399 logf("master file open failed: %s", TAGCACHE_FILE_TEMP
);
4403 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4407 logf("Scanning files...");
4408 /* Scan for new files. */
4409 memset(&header
, 0, sizeof(struct tagcache_header
));
4410 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4413 roots_ll
.path
= path
;
4414 roots_ll
.next
= NULL
;
4415 struct search_roots_ll
* this;
4416 /* check_dir might add new roots */
4417 for(this = &roots_ll
; this; this = this->next
)
4419 strcpy(curpath
, this->path
);
4420 ret
= ret
&& check_dir(this->path
, true);
4423 free_search_roots(roots_ll
.next
);
4425 /* Write the header. */
4426 header
.magic
= TAGCACHE_MAGIC
;
4427 header
.datasize
= data_size
;
4428 header
.entry_count
= total_entry_count
;
4429 lseek(cachefd
, 0, SEEK_SET
);
4430 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4433 if (filenametag_fd
>= 0)
4435 close(filenametag_fd
);
4436 filenametag_fd
= -1;
4446 /* Commit changes to the database. */
4452 remove(TAGCACHE_FILE_TEMP
);
4453 logf("tagcache built!");
4459 #ifdef HAVE_TC_RAMCACHE
4462 /* Import runtime statistics if we just initialized the db. */
4463 if (hdr
->h
.serial
== 0)
4464 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4471 #ifdef HAVE_TC_RAMCACHE
4472 static void load_ramcache(void)
4479 /* At first we should load the cache (if exists). */
4480 tc_stat
.ramcache
= load_tagcache();
4482 if (!tc_stat
.ramcache
)
4484 /* If loading failed, it must indicate some problem with the db
4485 * so disable it entirely to prevent further issues. */
4486 tc_stat
.ready
= false;
4493 void tagcache_unload_ramcache(void)
4495 tc_stat
.ramcache
= false;
4496 /* Just to make sure there is no statefile present. */
4497 // remove(TAGCACHE_STATEFILE);
4502 static void tagcache_thread(void)
4504 struct queue_event ev
;
4505 bool check_done
= false;
4507 /* If the previous cache build/update was interrupted, commit
4508 * the changes first in foreground. */
4514 #ifdef HAVE_TC_RAMCACHE
4515 # ifdef HAVE_EEPROM_SETTINGS
4516 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
4517 && global_settings
.tagcache_ram
)
4519 check_done
= tagcache_dumpload();
4522 remove(TAGCACHE_STATEFILE
);
4525 /* Allocate space for the tagcache if found on disk. */
4526 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4527 allocate_tagcache();
4531 tc_stat
.initialized
= true;
4533 /* Don't delay bootup with the header check but do it on background. */
4537 tc_stat
.ready
= check_all_headers();
4538 tc_stat
.readyvalid
= true;
4543 run_command_queue(false);
4545 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4549 case Q_IMPORT_CHANGELOG
:
4550 tagcache_import_changelog();
4555 remove(TAGCACHE_FILE_TEMP
);
4556 tagcache_build("/");
4560 tagcache_build("/");
4561 #ifdef HAVE_TC_RAMCACHE
4564 check_deleted_files();
4570 if (check_done
|| !tc_stat
.ready
)
4573 #ifdef HAVE_TC_RAMCACHE
4574 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4577 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4578 tagcache_build("/");
4582 if (global_settings
.tagcache_autoupdate
)
4584 tagcache_build("/");
4586 /* This will be very slow unless dircache is enabled
4587 or target is flash based, but do it anyway for
4589 check_deleted_files();
4592 logf("tagcache check done");
4603 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4604 case SYS_USB_CONNECTED
:
4605 logf("USB: TagCache");
4606 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4607 usb_wait_for_disconnect(&tagcache_queue
);
4614 bool tagcache_prepare_shutdown(void)
4616 if (tagcache_get_commit_step() > 0)
4619 tagcache_stop_scan();
4620 while (read_lock
|| write_lock
)
4626 void tagcache_shutdown(void)
4628 /* Flush the command queue. */
4629 run_command_queue(true);
4631 #ifdef HAVE_EEPROM_SETTINGS
4632 if (tc_stat
.ramcache
)
4633 tagcache_dumpsave();
4637 static int get_progress(void)
4639 int total_count
= -1;
4641 #ifdef HAVE_DIRCACHE
4642 if (dircache_is_enabled())
4644 total_count
= dircache_get_entry_count();
4648 #ifdef HAVE_TC_RAMCACHE
4650 if (hdr
&& tc_stat
.ramcache
)
4651 total_count
= hdr
->h
.tch
.entry_count
;
4655 if (total_count
< 0)
4658 return processed_dir_count
* 100 / total_count
;
4661 struct tagcache_stat
* tagcache_get_stat(void)
4663 tc_stat
.progress
= get_progress();
4664 tc_stat
.processed_entries
= processed_dir_count
;
4669 void tagcache_start_scan(void)
4671 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4674 bool tagcache_update(void)
4679 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4683 bool tagcache_rebuild()
4685 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4689 void tagcache_stop_scan(void)
4691 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4694 #ifdef HAVE_TC_RAMCACHE
4695 bool tagcache_is_ramcache(void)
4697 return tc_stat
.ramcache
;
4701 #endif /* !__PCTOOL__ */
4704 void tagcache_init(void)
4706 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4707 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4708 filenametag_fd
= -1;
4709 write_lock
= read_lock
= 0;
4712 mutex_init(&command_queue_mutex
);
4713 queue_init(&tagcache_queue
, true);
4714 create_thread(tagcache_thread
, tagcache_stack
,
4715 sizeof(tagcache_stack
), 0, tagcache_thread_name
4716 IF_PRIO(, PRIORITY_BACKGROUND
)
4719 tc_stat
.initialized
= true;
4723 tc_stat
.ready
= check_all_headers();
4728 void tagcache_reverse_scan(void)
4730 logf("Checking for deleted files");
4731 check_deleted_files();
4735 bool tagcache_is_initialized(void)
4737 return tc_stat
.initialized
;
4739 bool tagcache_is_usable(void)
4741 return tc_stat
.initialized
&& tc_stat
.ready
;
4743 int tagcache_get_commit_step(void)
4745 return tc_stat
.commit_step
;
4747 int tagcache_get_max_commit_step(void)
4749 return (int)(SORTED_TAGS_COUNT
)+1;