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
= "llllllllllllllllllllll";
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)
1698 #if CONFIG_CODEC == SWCODEC
1699 if (global_settings
.autoresume_enable
)
1701 id3
->offset
= get_tag_numeric(entry
, tag_lastoffset
, idx_id
);
1702 logf("tagcache_fill_tags: Set offset for %s to %lX\n",
1703 id3
->title
, id3
->offset
);
1711 static inline void write_item(const char *item
)
1713 int len
= strlen(item
) + 1;
1716 write(cachefd
, item
, len
);
1719 static int check_if_empty(char **tag
)
1723 if (*tag
== NULL
|| **tag
== '\0')
1726 return sizeof(UNTAGGED
); /* Tag length */
1729 length
= strlen(*tag
);
1730 if (length
> TAG_MAXLEN
)
1732 logf("over length tag: %s", *tag
);
1733 length
= TAG_MAXLEN
;
1734 (*tag
)[length
] = '\0';
1740 #define ADD_TAG(entry,tag,data) \
1742 entry.tag_offset[tag] = offset; \
1743 entry.tag_length[tag] = check_if_empty(data); \
1744 offset += entry.tag_length[tag]
1745 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1746 * idea, as it uses lots of stack and is called from a recursive function
1749 static void __attribute__ ((noinline
)) add_tagcache(char *path
,
1751 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1752 ,const struct dircache_entry
*dc
1756 struct mp3entry id3
;
1757 struct temp_file_entry entry
;
1761 char tracknumfix
[3];
1763 int path_length
= strlen(path
);
1764 bool has_albumartist
;
1768 /* Crude logging for the sim - to aid in debugging */
1769 int logfd
= open(ROCKBOX_DIR
"/database.log",
1770 O_WRONLY
| O_APPEND
| O_CREAT
, 0666);
1772 write(logfd
, path
, strlen(path
));
1773 write(logfd
, "\n", 1);
1781 /* Check for overlength file path. */
1782 if (path_length
> TAG_MAXLEN
)
1784 /* Path can't be shortened. */
1785 logf("Too long path: %s", path
);
1789 /* Check if the file is supported. */
1790 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1793 /* Check if the file is already cached. */
1794 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1795 if (tc_stat
.ramcache
&& is_dircache_intact())
1797 idx_id
= find_entry_ram(path
, dc
);
1801 /* Be sure the entry doesn't exist. */
1802 if (filenametag_fd
>= 0 && idx_id
< 0)
1803 idx_id
= find_entry_disk(path
, false);
1805 /* Check if file has been modified. */
1808 struct index_entry idx
;
1810 /* TODO: Mark that the index exists (for fast reverse scan) */
1811 //found_idx[idx_id/8] |= idx_id%8;
1813 if (!get_index(-1, idx_id
, &idx
, true))
1815 logf("failed to retrieve index entry");
1819 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1821 /* No changes to file. */
1825 /* Metadata might have been changed. Delete the entry. */
1826 logf("Re-adding: %s", path
);
1827 if (!delete_entry(idx_id
))
1829 logf("delete_entry failed: %d", idx_id
);
1834 fd
= open(path
, O_RDONLY
);
1837 logf("open fail: %s", path
);
1841 memset(&id3
, 0, sizeof(struct mp3entry
));
1842 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1843 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1844 ret
= get_metadata(&id3
, fd
, path
);
1850 logf("-> %s", path
);
1852 /* Generate track number if missing. */
1853 if (id3
.tracknum
<= 0)
1855 const char *p
= strrchr(path
, '.');
1858 p
= &path
[strlen(path
)-1];
1862 if (isdigit(*p
) && isdigit(*(p
-1)))
1864 tracknumfix
[1] = *p
--;
1865 tracknumfix
[0] = *p
;
1871 if (tracknumfix
[0] != '\0')
1873 id3
.tracknum
= atoi(tracknumfix
);
1874 /* Set a flag to indicate track number has been generated. */
1875 entry
.flag
|= FLAG_TRKNUMGEN
;
1879 /* Unable to generate track number. */
1885 entry
.tag_offset
[tag_year
] = id3
.year
;
1886 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1887 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1888 entry
.tag_offset
[tag_length
] = id3
.length
;
1889 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1890 entry
.tag_offset
[tag_mtime
] = mtime
;
1893 has_albumartist
= id3
.albumartist
!= NULL
1894 && strlen(id3
.albumartist
) > 0;
1895 has_grouping
= id3
.grouping
!= NULL
1896 && strlen(id3
.grouping
) > 0;
1898 ADD_TAG(entry
, tag_filename
, &path
);
1899 ADD_TAG(entry
, tag_title
, &id3
.title
);
1900 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1901 ADD_TAG(entry
, tag_album
, &id3
.album
);
1902 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1903 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1904 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1905 if (has_albumartist
)
1907 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1911 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1915 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1919 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1921 entry
.data_length
= offset
;
1923 /* Write the header */
1924 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1926 /* And tags also... Correct order is critical */
1928 write_item(id3
.title
);
1929 write_item(id3
.artist
);
1930 write_item(id3
.album
);
1931 write_item(id3
.genre_string
);
1932 write_item(id3
.composer
);
1933 write_item(id3
.comment
);
1934 if (has_albumartist
)
1936 write_item(id3
.albumartist
);
1940 write_item(id3
.artist
);
1944 write_item(id3
.grouping
);
1948 write_item(id3
.title
);
1950 total_entry_count
++;
1953 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1955 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1956 int len
= strlen(str
)+1;
1959 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1960 char buf
[TAG_MAXLEN
+32];
1962 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1963 buf
[i
] = tolower(str
[i
]);
1966 crc32
= crc_32(buf
, i
, 0xffffffff);
1970 /* Check if the crc does not exist -> entry does not exist for sure. */
1971 for (i
= 0; i
< tempbufidx
; i
++)
1973 if (crcbuf
[-i
] != crc32
)
1976 if (!strcasecmp(str
, index
[i
].str
))
1978 if (id
< 0 || id
>= lookup_buffer_depth
)
1980 logf("lookup buf overf.: %d", id
);
1984 lookup
[id
] = &index
[i
];
1990 /* Insert to CRC buffer. */
1991 crcbuf
[-tempbufidx
] = crc32
;
1994 /* Insert it to the buffer. */
1995 tempbuf_left
-= len
;
1996 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1999 if (id
>= lookup_buffer_depth
)
2001 logf("lookup buf overf. #2: %d", id
);
2007 lookup
[id
] = &index
[tempbufidx
];
2008 index
[tempbufidx
].idlist
.id
= id
;
2011 index
[tempbufidx
].idlist
.id
= -1;
2013 index
[tempbufidx
].idlist
.next
= NULL
;
2014 index
[tempbufidx
].idx_id
= idx_id
;
2015 index
[tempbufidx
].seek
= -1;
2016 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
2017 memcpy(index
[tempbufidx
].str
, str
, len
);
2024 static int compare(const void *p1
, const void *p2
)
2028 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
2029 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
2031 if (strcmp(e1
->str
, UNTAGGED
) == 0)
2033 if (strcmp(e2
->str
, UNTAGGED
) == 0)
2037 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
2040 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
2043 static int tempbuf_sort(int fd
)
2045 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
2046 struct tagfile_entry fe
;
2050 /* Generate reverse lookup entries. */
2051 for (i
= 0; i
< lookup_buffer_depth
; i
++)
2053 struct tempbuf_id_list
*idlist
;
2058 if (lookup
[i
]->idlist
.id
== i
)
2061 idlist
= &lookup
[i
]->idlist
;
2062 while (idlist
->next
!= NULL
)
2063 idlist
= idlist
->next
;
2065 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
2066 if (tempbuf_left
- 4 < 0)
2069 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2070 if (tempbuf_pos
& 0x03)
2072 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
2074 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2076 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
2078 idlist
= idlist
->next
;
2080 idlist
->next
= NULL
;
2085 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
2086 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
2088 for (i
= 0; i
< tempbufidx
; i
++)
2090 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
2092 /* Fix the lookup list. */
2093 while (idlist
!= NULL
)
2095 if (idlist
->id
>= 0)
2096 lookup
[idlist
->id
] = &index
[i
];
2097 idlist
= idlist
->next
;
2100 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
2101 length
= strlen(index
[i
].str
) + 1;
2102 fe
.tag_length
= length
;
2103 fe
.idx_id
= index
[i
].idx_id
;
2105 /* Check the chunk alignment. */
2106 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2107 % TAGFILE_ENTRY_CHUNK_LENGTH
)
2109 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
2110 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2111 % TAGFILE_ENTRY_CHUNK_LENGTH
);
2114 #ifdef TAGCACHE_STRICT_ALIGN
2115 /* Make sure the entry is long aligned. */
2116 if (index
[i
].seek
& 0x03)
2118 logf("tempbuf_sort: alignment error!");
2123 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2124 sizeof(struct tagfile_entry
))
2126 logf("tempbuf_sort: write error #1");
2130 if (write(fd
, index
[i
].str
, length
) != length
)
2132 logf("tempbuf_sort: write error #2");
2136 /* Write some padding. */
2137 if (fe
.tag_length
- length
> 0)
2138 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2144 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2146 if (id
< 0 || id
>= lookup_buffer_depth
)
2153 inline static int tempbuf_find_location(int id
)
2155 struct tempbuf_searchidx
*entry
;
2157 entry
= tempbuf_locate(id
);
2164 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2166 struct master_header tcmh
;
2167 struct index_entry idx
;
2170 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2172 int entries_processed
= 0;
2174 char buf
[TAG_MAXLEN
];
2176 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2178 logf("Building numeric indices...");
2179 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2181 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2184 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2186 if (masterfd_pos
== filesize(masterfd
))
2188 logf("we can't append!");
2193 while (entries_processed
< h
->entry_count
)
2195 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2197 /* Read in as many entries as possible. */
2198 for (i
= 0; i
< count
; i
++)
2200 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2203 /* Read in numeric data. */
2204 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2205 sizeof(struct temp_file_entry
))
2207 logf("read fail #1");
2212 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2215 * Read string data from the following tags:
2221 * A crc32 hash is calculated from the read data
2222 * and stored back to the data offset field kept in memory.
2224 #define tmpdb_read_string_tag(tag) \
2225 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2226 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2228 logf("read fail: buffer overflow"); \
2233 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2234 tfe->tag_length[tag]) \
2236 logf("read fail #2"); \
2241 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2242 lseek(tmpfd, datastart, SEEK_SET)
2244 tmpdb_read_string_tag(tag_filename
);
2245 tmpdb_read_string_tag(tag_artist
);
2246 tmpdb_read_string_tag(tag_album
);
2247 tmpdb_read_string_tag(tag_title
);
2249 /* Seek to the end of the string data. */
2250 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2253 /* Backup the master index position. */
2254 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2255 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2257 /* Check if we can resurrect some deleted runtime statistics data. */
2258 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2260 /* Read the index entry. */
2261 if (ecread_index_entry(masterfd
, &idx
)
2262 != sizeof(struct index_entry
))
2264 logf("read fail #3");
2270 * Skip unless the entry is marked as being deleted
2271 * or the data has already been resurrected.
2273 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2276 /* Now try to match the entry. */
2278 * To succesfully match a song, the following conditions
2281 * For numeric fields: tag_length
2282 * - Full identical match is required
2284 * If tag_filename matches, no further checking necessary.
2286 * For string hashes: tag_artist, tag_album, tag_title
2287 * - Two of these must match
2289 for (j
= 0; j
< count
; j
++)
2291 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2293 /* Try to match numeric fields first. */
2294 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2297 /* Now it's time to do the hash matching. */
2298 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2300 int match_count
= 0;
2302 /* No filename match, check if we can match two other tags. */
2303 #define tmpdb_match(tag) \
2304 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2307 tmpdb_match(tag_artist
);
2308 tmpdb_match(tag_album
);
2309 tmpdb_match(tag_title
);
2311 if (match_count
< 2)
2313 /* Still no match found, give up. */
2318 /* A match found, now copy & resurrect the statistical data. */
2319 #define tmpdb_copy_tag(tag) \
2320 tfe->tag_offset[tag] = idx.tag_seek[tag]
2322 tmpdb_copy_tag(tag_playcount
);
2323 tmpdb_copy_tag(tag_rating
);
2324 tmpdb_copy_tag(tag_playtime
);
2325 tmpdb_copy_tag(tag_lastplayed
);
2326 tmpdb_copy_tag(tag_commitid
);
2327 tmpdb_copy_tag(tag_lastoffset
);
2329 /* Avoid processing this entry again. */
2330 idx
.flag
|= FLAG_RESURRECTED
;
2332 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2333 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2335 logf("masterfd writeback fail #1");
2340 logf("Entry resurrected");
2345 /* Restore the master index position. */
2346 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2348 /* Commit the data to the index. */
2349 for (i
= 0; i
< count
; i
++)
2351 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2353 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2355 logf("read fail #3");
2360 for (j
= 0; j
< TAG_COUNT
; j
++)
2362 if (!TAGCACHE_IS_NUMERIC(j
))
2365 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2367 idx
.flag
= entrybuf
[i
].flag
;
2369 if (idx
.tag_seek
[tag_commitid
])
2371 /* Data has been resurrected. */
2372 idx
.flag
|= FLAG_DIRTYNUM
;
2374 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2376 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2377 idx
.flag
|= FLAG_DIRTYNUM
;
2380 /* Write back the updated index. */
2381 lseek(masterfd
, loc
, SEEK_SET
);
2382 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2390 entries_processed
+= count
;
2391 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2402 * == 0 temporary failure
2405 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2408 struct tagcache_header tch
;
2409 struct master_header tcmh
;
2410 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2412 char buf
[TAG_MAXLEN
+32];
2413 int fd
= -1, masterfd
;
2418 logf("Building index: %d", index_type
);
2420 /* Check the number of entries we need to allocate ram for. */
2421 commit_entry_count
= h
->entry_count
+ 1;
2423 masterfd
= open_master_fd(&tcmh
, false);
2426 commit_entry_count
+= tcmh
.tch
.entry_count
;
2430 remove_files(); /* Just to be sure we are clean. */
2432 /* Open the index file, which contains the tag names. */
2433 fd
= open_tag_fd(&tch
, index_type
, true);
2436 logf("tch.datasize=%ld", tch
.datasize
);
2437 lookup_buffer_depth
= 1 +
2438 /* First part */ commit_entry_count
+
2439 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2443 lookup_buffer_depth
= 1 +
2444 /* First part */ commit_entry_count
+
2445 /* Second part */ 0;
2448 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2449 logf("commit_entry_count=%ld", commit_entry_count
);
2451 /* Allocate buffer for all index entries from both old and new
2454 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2456 /* Allocate lookup buffer. The first portion of commit_entry_count
2457 * contains the new tags in the temporary file and the second
2458 * part for locating entries already in the db.
2461 * +---------+---------------------------+
2462 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2463 * +---------+---------------------------+
2465 * Old tags are inserted to a temporary buffer with position:
2466 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2467 * And new tags with index:
2468 * tempbuf_insert(idx, ...);
2470 * The buffer is sorted and written into tag file:
2471 * tempbuf_sort(...);
2472 * leaving master index locations messed up.
2474 * That is fixed using the lookup buffer for old tags:
2475 * new_seek = tempbuf_find_location(old_seek, ...);
2477 * new_seek = tempbuf_find_location(idx);
2479 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2480 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2481 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2483 /* And calculate the remaining data space used mainly for storing
2484 * tag data (strings). */
2485 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2486 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2488 logf("Buffer way too small!");
2495 * If tag file contains unique tags (sorted index), we will load
2496 * it entirely into memory so we can resort it later for use with
2499 if (TAGCACHE_IS_SORTED(index_type
))
2501 logf("loading tags...");
2502 for (i
= 0; i
< tch
.entry_count
; i
++)
2504 struct tagfile_entry entry
;
2505 int loc
= lseek(fd
, 0, SEEK_CUR
);
2508 if (ecread_tagfile_entry(fd
, &entry
) != sizeof(struct tagfile_entry
))
2510 logf("read error #7");
2515 if (entry
.tag_length
>= (int)sizeof(buf
))
2517 logf("too long tag #3");
2522 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2524 logf("read error #8");
2529 /* Skip deleted entries. */
2534 * Save the tag and tag id in the memory buffer. Tag id
2535 * is saved so we can later reindex the master lookup
2536 * table when the index gets resorted.
2538 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2539 + commit_entry_count
, entry
.idx_id
,
2540 TAGCACHE_IS_UNIQUE(index_type
));
2551 tempbufidx
= tch
.entry_count
;
2556 * Creating new index file to store the tags. No need to preload
2557 * anything whether the index type is sorted or not.
2559 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2560 fd
= open(buf
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2563 logf("%s open fail", buf
);
2567 tch
.magic
= TAGCACHE_MAGIC
;
2568 tch
.entry_count
= 0;
2571 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2572 != sizeof(struct tagcache_header
))
2574 logf("header write failed");
2580 /* Loading the tag lookup file as "master file". */
2581 logf("Loading index file");
2582 masterfd
= open(TAGCACHE_FILE_MASTER
, O_RDWR
);
2586 logf("Creating new DB");
2587 masterfd
= open(TAGCACHE_FILE_MASTER
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2591 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER
);
2596 /* Write the header (write real values later). */
2597 memset(&tcmh
, 0, sizeof(struct master_header
));
2599 tcmh
.tch
.entry_count
= 0;
2600 tcmh
.tch
.datasize
= 0;
2602 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2604 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2609 * Master file already exists so we need to process the current
2614 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2615 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2617 logf("header error");
2624 * If we reach end of the master file, we need to expand it to
2625 * hold new tags. If the current index is not sorted, we can
2626 * simply append new data to end of the file.
2627 * However, if the index is sorted, we need to update all tag
2628 * pointers in the master file for the current index.
2630 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2632 if (masterfd_pos
== filesize(masterfd
))
2634 logf("appending...");
2640 * Load new unique tags in memory to be sorted later and added
2641 * to the master lookup file.
2643 if (TAGCACHE_IS_SORTED(index_type
))
2645 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2646 /* h is the header of the temporary file containing new tags. */
2647 logf("inserting new tags...");
2648 for (i
= 0; i
< h
->entry_count
; i
++)
2650 struct temp_file_entry entry
;
2652 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2653 sizeof(struct temp_file_entry
))
2655 logf("read fail #3");
2661 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2663 logf("too long entry!");
2668 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2669 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2670 entry
.tag_length
[index_type
])
2672 logf("read fail #4");
2677 if (TAGCACHE_IS_UNIQUE(index_type
))
2678 error
= !tempbuf_insert(buf
, i
, -1, true);
2680 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2684 logf("insert error");
2689 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2690 entry
.tag_length
[index_type
], SEEK_CUR
);
2695 /* Sort the buffer data and write it to the index file. */
2696 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2698 * We need to truncate the index file now. There can be junk left
2699 * at the end of file (however, we _should_ always follow the
2700 * entry_count and don't crash with that).
2702 ftruncate(fd
, lseek(fd
, 0, SEEK_CUR
));
2704 i
= tempbuf_sort(fd
);
2707 logf("sorted %d tags", i
);
2710 * Now update all indexes in the master lookup file.
2712 logf("updating indices...");
2713 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2714 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2717 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2719 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2721 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2722 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2724 logf("read fail #5");
2728 lseek(masterfd
, loc
, SEEK_SET
);
2730 for (j
= 0; j
< idxbuf_pos
; j
++)
2732 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2734 /* We can just ignore deleted entries. */
2735 // idxbuf[j].tag_seek[index_type] = 0;
2739 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2740 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2741 + commit_entry_count
);
2743 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2745 logf("update error: %ld/%d/%ld",
2746 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2754 /* Write back the updated index. */
2755 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2756 index_entry_ec
, tc_stat
.econ
) !=
2757 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2768 * Walk through the temporary file containing the new tags.
2770 // build_normal_index(h, tmpfd, masterfd, idx);
2771 logf("updating new indices...");
2772 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2773 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2774 lseek(fd
, 0, SEEK_END
);
2775 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2779 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2782 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2786 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2788 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2789 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2791 logf("read fail #6");
2795 lseek(masterfd
, loc
, SEEK_SET
);
2798 /* Read entry headers. */
2799 for (j
= 0; j
< idxbuf_pos
; j
++)
2801 if (!TAGCACHE_IS_SORTED(index_type
))
2803 struct temp_file_entry entry
;
2804 struct tagfile_entry fe
;
2806 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2807 sizeof(struct temp_file_entry
))
2809 logf("read fail #7");
2815 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2817 logf("too long entry!");
2818 logf("length=%d", entry
.tag_length
[index_type
]);
2819 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2824 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2825 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2826 entry
.tag_length
[index_type
])
2828 logf("read fail #8");
2829 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2830 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2835 /* Write to index file. */
2836 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2837 fe
.tag_length
= entry
.tag_length
[index_type
];
2838 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2839 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2840 write(fd
, buf
, fe
.tag_length
);
2844 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2845 entry
.tag_length
[index_type
], SEEK_CUR
);
2849 /* Locate the correct entry from the sorted array. */
2850 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2851 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2853 logf("entry not found (%d)", j
);
2861 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2862 index_entry_ec
, tc_stat
.econ
) !=
2863 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2865 logf("tagcache: write fail #4");
2874 /* Finally write the header. */
2875 tch
.magic
= TAGCACHE_MAGIC
;
2876 tch
.entry_count
= tempbufidx
;
2877 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2878 lseek(fd
, 0, SEEK_SET
);
2879 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2881 if (index_type
!= tag_filename
)
2882 h
->datasize
+= tch
.datasize
;
2883 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2895 static bool commit(void)
2897 struct tagcache_header tch
;
2898 struct master_header tcmh
;
2902 #ifdef HAVE_DIRCACHE
2903 bool dircache_buffer_stolen
= false;
2905 bool local_allocation
= false;
2907 logf("committing tagcache");
2912 tmpfd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
2915 logf("nothing to commit");
2920 /* Load the header. */
2921 len
= sizeof(struct tagcache_header
);
2922 rc
= read(tmpfd
, &tch
, len
);
2924 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2926 logf("incorrect tmpheader");
2928 remove(TAGCACHE_FILE_TEMP
);
2932 if (tch
.entry_count
== 0)
2934 logf("nothing to commit");
2936 remove(TAGCACHE_FILE_TEMP
);
2940 /* Fully initialize existing headers (if any) before going further. */
2941 tc_stat
.ready
= check_all_headers();
2943 #ifdef HAVE_EEPROM_SETTINGS
2944 remove(TAGCACHE_STATEFILE
);
2947 /* At first be sure to unload the ramcache! */
2948 #ifdef HAVE_TC_RAMCACHE
2949 tc_stat
.ramcache
= false;
2954 /* Try to steal every buffer we can :) */
2955 if (tempbuf_size
== 0)
2956 local_allocation
= true;
2958 #ifdef HAVE_DIRCACHE
2959 if (tempbuf_size
== 0)
2961 /* Try to steal the dircache buffer. */
2962 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2963 tempbuf_size
&= ~0x03;
2965 if (tempbuf_size
> 0)
2967 dircache_buffer_stolen
= true;
2972 #ifdef HAVE_TC_RAMCACHE
2973 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2975 tempbuf
= (char *)(hdr
+ 1);
2976 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2977 tempbuf_size
&= ~0x03;
2981 /* And finally fail if there are no buffers available. */
2982 if (tempbuf_size
== 0)
2984 logf("delaying commit until next boot");
2985 tc_stat
.commit_delayed
= true;
2991 logf("commit %ld entries...", tch
.entry_count
);
2993 /* Mark DB dirty so it will stay disabled if commit fails. */
2994 current_tcmh
.dirty
= true;
2995 update_master_header();
2997 /* Now create the index files. */
2998 tc_stat
.commit_step
= 0;
3000 tc_stat
.commit_delayed
= false;
3002 for (i
= 0; i
< TAG_COUNT
; i
++)
3006 if (TAGCACHE_IS_NUMERIC(i
))
3009 tc_stat
.commit_step
++;
3010 ret
= build_index(i
, &tch
, tmpfd
);
3014 logf("tagcache failed init");
3016 tc_stat
.commit_delayed
= true;
3018 tc_stat
.commit_step
= 0;
3024 if (!build_numeric_indices(&tch
, tmpfd
))
3026 logf("Failure to commit numeric indices");
3028 tc_stat
.commit_step
= 0;
3034 remove(TAGCACHE_FILE_TEMP
);
3036 tc_stat
.commit_step
= 0;
3038 /* Update the master index headers. */
3039 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
3045 tcmh
.tch
.entry_count
+= tch
.entry_count
;
3046 tcmh
.tch
.datasize
= sizeof(struct master_header
)
3047 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
3052 lseek(masterfd
, 0, SEEK_SET
);
3053 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
3056 logf("tagcache committed");
3057 tc_stat
.ready
= check_all_headers();
3058 tc_stat
.readyvalid
= true;
3060 if (local_allocation
)
3066 #ifdef HAVE_DIRCACHE
3067 /* Rebuild the dircache, if we stole the buffer. */
3068 if (dircache_buffer_stolen
)
3072 #ifdef HAVE_TC_RAMCACHE
3073 /* Reload tagcache. */
3074 if (tc_stat
.ramcache_allocated
> 0)
3075 tagcache_start_scan();
3083 static void allocate_tempbuf(void)
3085 /* Yeah, malloc would be really nice now :) */
3087 tempbuf_size
= 32*1024*1024;
3088 tempbuf
= malloc(tempbuf_size
);
3090 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
3091 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
3092 audiobuf
+= tempbuf_size
;
3096 static void free_tempbuf(void)
3098 if (tempbuf_size
== 0)
3104 audiobuf
-= tempbuf_size
;
3112 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
3114 struct index_entry idx
;
3119 if (!TAGCACHE_IS_NUMERIC(tag
))
3122 if (!get_index(masterfd
, idx_id
, &idx
, false))
3125 idx
.tag_seek
[tag
] = data
;
3126 idx
.flag
|= FLAG_DIRTYNUM
;
3128 return write_index(masterfd
, idx_id
, &idx
);
3132 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3135 struct master_header myhdr
;
3137 if (tcs
->masterfd
< 0)
3139 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3143 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3147 static bool command_queue_is_full(void)
3151 next
= command_queue_widx
+ 1;
3152 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3155 return (next
== command_queue_ridx
);
3158 static void command_queue_sync_callback(void *data
)
3161 struct master_header myhdr
;
3164 mutex_lock(&command_queue_mutex
);
3166 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3169 while (command_queue_ridx
!= command_queue_widx
)
3171 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3173 switch (ce
->command
)
3175 case CMD_UPDATE_MASTER_HEADER
:
3178 update_master_header();
3180 /* Re-open the masterfd. */
3181 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3186 case CMD_UPDATE_NUMERIC
:
3188 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3193 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3194 command_queue_ridx
= 0;
3199 tc_stat
.queue_length
= 0;
3200 mutex_unlock(&command_queue_mutex
);
3203 static void run_command_queue(bool force
)
3205 if (COMMAND_QUEUE_IS_EMPTY
)
3208 if (force
|| command_queue_is_full())
3209 command_queue_sync_callback(NULL
);
3211 register_storage_idle_func(command_queue_sync_callback
);
3214 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3220 mutex_lock(&command_queue_mutex
);
3221 next
= command_queue_widx
+ 1;
3222 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3225 /* Make sure queue is not full. */
3226 if (next
!= command_queue_ridx
)
3228 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3231 ce
->idx_id
= idx_id
;
3235 command_queue_widx
= next
;
3237 tc_stat
.queue_length
++;
3239 mutex_unlock(&command_queue_mutex
);
3243 /* Queue is full, try again later... */
3244 mutex_unlock(&command_queue_mutex
);
3249 long tagcache_increase_serial(void)
3259 old
= current_tcmh
.serial
++;
3260 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3265 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3267 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3269 #endif /* !__PCTOOL__ */
3271 long tagcache_get_serial(void)
3273 return current_tcmh
.serial
;
3276 long tagcache_get_commitid(void)
3278 return current_tcmh
.commitid
;
3281 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3286 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3287 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3289 if (*datastr
== '\0')
3292 if (*datastr
== '"' || *datastr
== '\\')
3295 buf
[i
] = *(datastr
++);
3298 strcpy(&buf
[i
], "\" ");
3300 write(fd
, buf
, i
+ 2);
3307 static bool read_tag(char *dest
, long size
,
3308 const char *src
, const char *tagstr
)
3311 char current_tag
[32];
3313 while (*src
!= '\0')
3315 /* Skip all whitespace */
3323 /* Read in tag name */
3324 while (*src
!= '=' && *src
!= ' ')
3326 current_tag
[pos
] = *src
;
3330 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3333 current_tag
[pos
] = '\0';
3335 /* Read in tag data */
3337 /* Find the start. */
3338 while (*src
!= '"' && *src
!= '\0')
3341 if (*src
== '\0' || *(++src
) == '\0')
3344 /* Read the data. */
3345 for (pos
= 0; pos
< size
; pos
++)
3352 dest
[pos
] = *(src
+1);
3372 if (!strcasecmp(tagstr
, current_tag
))
3379 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3381 struct index_entry idx
;
3382 char tag_data
[TAG_MAXLEN
+32];
3384 long masterfd
= (long)parameters
;
3385 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3393 logf("%d/%s", line_n
, buf
);
3394 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3396 logf("filename missing");
3401 idx_id
= find_index(tag_data
);
3404 logf("entry not found");
3408 if (!get_index(masterfd
, idx_id
, &idx
, false))
3410 logf("failed to retrieve index entry");
3414 /* Stop if tag has already been modified. */
3415 if (idx
.flag
& FLAG_DIRTYNUM
)
3418 logf("import: %s", tag_data
);
3420 idx
.flag
|= FLAG_DIRTYNUM
;
3421 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3425 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3426 tagcache_tag_to_str(import_tags
[i
])))
3431 data
= atoi(tag_data
);
3435 idx
.tag_seek
[import_tags
[i
]] = data
;
3437 if (import_tags
[i
] == tag_lastplayed
&& data
>= current_tcmh
.serial
)
3438 current_tcmh
.serial
= data
+ 1;
3439 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3440 current_tcmh
.commitid
= data
+ 1;
3443 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3446 bool tagcache_import_changelog(void)
3448 struct master_header myhdr
;
3449 struct tagcache_header tch
;
3460 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_RDONLY
);
3463 logf("failure to open changelog");
3467 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3475 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3477 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3478 parse_changelog_line
);
3483 if (filenametag_fd
>= 0)
3485 close(filenametag_fd
);
3486 filenametag_fd
= -1;
3491 update_master_header();
3496 #endif /* !__PCTOOL__ */
3498 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3500 struct master_header myhdr
;
3501 struct index_entry idx
;
3502 char buf
[TAG_MAXLEN
+32];
3510 if (!tagcache_search(tcs
, tag_filename
))
3513 /* Initialize the changelog */
3514 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3517 logf("failure to open changelog");
3521 if (tcs
->masterfd
< 0)
3523 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3528 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3529 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3532 write(clfd
, "## Changelog version 1\n", 23);
3534 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3536 if (ecread_index_entry(tcs
->masterfd
, &idx
) != sizeof(struct index_entry
))
3538 logf("read error #9");
3539 tagcache_search_finish(tcs
);
3544 /* Skip until the entry found has been modified. */
3545 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3548 /* Skip deleted entries too. */
3549 if (idx
.flag
& FLAG_DELETED
)
3552 /* Now retrieve all tags. */
3553 for (j
= 0; j
< TAG_COUNT
; j
++)
3555 if (TAGCACHE_IS_NUMERIC(j
))
3557 snprintf(temp
, sizeof temp
, "%d", (int)idx
.tag_seek
[j
]);
3558 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3563 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3564 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3567 write(clfd
, "\n", 1);
3573 tagcache_search_finish(tcs
);
3578 static bool delete_entry(long idx_id
)
3583 struct index_entry idx
, myidx
;
3584 struct master_header myhdr
;
3585 char buf
[TAG_MAXLEN
+32];
3586 int in_use
[TAG_COUNT
];
3588 logf("delete_entry(): %ld", idx_id
);
3590 #ifdef HAVE_TC_RAMCACHE
3591 /* At first mark the entry removed from ram cache. */
3592 if (tc_stat
.ramcache
)
3593 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3596 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3599 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3600 if (ecread_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3602 logf("delete_entry(): read error");
3606 if (myidx
.flag
& FLAG_DELETED
)
3608 logf("delete_entry(): already deleted!");
3612 myidx
.flag
|= FLAG_DELETED
;
3613 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3614 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3616 logf("delete_entry(): write_error #1");
3620 /* Now check which tags are no longer in use (if any) */
3621 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3624 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3625 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3627 struct index_entry
*idxp
;
3629 #ifdef HAVE_TC_RAMCACHE
3630 /* Use RAM DB if available for greater speed */
3631 if (tc_stat
.ramcache
)
3632 idxp
= &hdr
->indices
[i
];
3636 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
3638 logf("delete_entry(): read error #2");
3644 if (idxp
->flag
& FLAG_DELETED
)
3647 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3649 if (TAGCACHE_IS_NUMERIC(tag
))
3652 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3657 /* Now delete all tags no longer in use. */
3658 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3660 struct tagcache_header tch
;
3661 int oldseek
= myidx
.tag_seek
[tag
];
3663 if (TAGCACHE_IS_NUMERIC(tag
))
3667 * Replace tag seek with a hash value of the field string data.
3668 * That way runtime statistics of moved or altered files can be
3671 #ifdef HAVE_TC_RAMCACHE
3672 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3674 struct tagfile_entry
*tfe
;
3675 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3677 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3678 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3679 myidx
.tag_seek
[tag
] = *seek
;
3684 struct tagfile_entry tfe
;
3686 /* Open the index file, which contains the tag names. */
3687 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3690 /* Skip the header block */
3691 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3692 if (ecread_tagfile_entry(fd
, &tfe
) != sizeof(struct tagfile_entry
))
3694 logf("delete_entry(): read error #3");
3698 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3700 logf("delete_entry(): read error #4");
3704 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3709 logf("in use: %d/%d", tag
, in_use
[tag
]);
3718 #ifdef HAVE_TC_RAMCACHE
3719 /* Delete from ram. */
3720 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3722 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3723 tagentry
->tag_data
[0] = '\0';
3727 /* Open the index file, which contains the tag names. */
3730 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3734 /* Skip the header block */
3735 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3737 /* Debug, print 10 first characters of the tag
3740 logf("TAG:%s", buf);
3741 lseek(fd, -10, SEEK_CUR);
3744 /* Write first data byte in tag as \0 */
3747 /* Now tag data has been removed */
3752 /* Write index entry back into master index. */
3753 lseek(masterfd
, sizeof(struct master_header
) +
3754 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3755 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3757 logf("delete_entry(): write_error #2");
3776 * Returns true if there is an event waiting in the queue
3777 * that requires the current operation to be aborted.
3779 static bool check_event_queue(void)
3781 struct queue_event ev
;
3783 if(!queue_peek(&tagcache_queue
, &ev
))
3790 case SYS_USB_CONNECTED
:
3798 #ifdef HAVE_TC_RAMCACHE
3799 static bool allocate_tagcache(void)
3801 struct master_header tcmh
;
3804 /* Load the header. */
3805 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3814 * Now calculate the required cache size plus
3815 * some extra space for alignment fixes.
3817 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3818 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3819 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3820 memset(hdr
, 0, sizeof(struct ramcache_header
));
3821 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3822 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3823 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3828 # ifdef HAVE_EEPROM_SETTINGS
3829 static bool tagcache_dumpload(void)
3831 struct statefile_header shdr
;
3836 fd
= open(TAGCACHE_STATEFILE
, O_RDONLY
);
3839 logf("no tagcache statedump");
3843 /* Check the statefile memory placement */
3844 hdr
= buffer_alloc(0);
3845 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3846 if (rc
!= sizeof(struct statefile_header
)
3847 /* || (long)hdr != (long)shdr.hdr */)
3849 logf("incorrect statefile");
3855 offpos
= (long)hdr
- (long)shdr
.hdr
;
3857 /* Lets allocate real memory and load it */
3858 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3859 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3862 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3864 logf("read failure!");
3869 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3871 /* Now fix the pointers */
3872 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3873 for (i
= 0; i
< TAG_COUNT
; i
++)
3874 hdr
->tags
[i
] += offpos
;
3879 static bool tagcache_dumpsave(void)
3881 struct statefile_header shdr
;
3884 if (!tc_stat
.ramcache
)
3887 fd
= open(TAGCACHE_STATEFILE
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3890 logf("failed to create a statedump");
3894 /* Create the header */
3896 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3897 write(fd
, &shdr
, sizeof(struct statefile_header
));
3899 /* And dump the data too */
3900 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3907 static bool load_tagcache(void)
3909 struct tagcache_header
*tch
;
3910 long bytesleft
= tc_stat
.ramcache_allocated
;
3911 struct index_entry
*idx
;
3916 # ifdef HAVE_DIRCACHE
3917 while (dircache_is_initializing())
3920 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3923 logf("loading tagcache to ram...");
3925 fd
= open(TAGCACHE_FILE_MASTER
, O_RDONLY
);
3928 logf("tagcache open failed");
3932 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3933 != sizeof(struct master_header
)
3934 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3936 logf("incorrect header");
3942 /* Load the master index table. */
3943 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3945 rc
= ecread_index_entry(fd
, idx
);
3946 if (rc
!= sizeof(struct index_entry
))
3948 logf("read error #10");
3953 bytesleft
-= sizeof(struct index_entry
);
3954 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3956 logf("too big tagcache.");
3966 /* Load the tags. */
3968 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3970 struct tagfile_entry
*fe
;
3971 char buf
[TAG_MAXLEN
+32];
3973 if (TAGCACHE_IS_NUMERIC(tag
))
3976 //p = ((void *)p+1);
3977 p
= (char *)((long)p
& ~0x03) + 0x04;
3980 /* Check the header. */
3981 tch
= (struct tagcache_header
*)p
;
3982 p
+= sizeof(struct tagcache_header
);
3984 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3987 for (hdr
->entry_count
[tag
] = 0;
3988 hdr
->entry_count
[tag
] < tch
->entry_count
;
3989 hdr
->entry_count
[tag
]++)
3993 if (do_timed_yield())
3995 /* Abort if we got a critical event in queue */
3996 if (check_event_queue())
4000 fe
= (struct tagfile_entry
*)p
;
4001 pos
= lseek(fd
, 0, SEEK_CUR
);
4002 rc
= ecread_tagfile_entry(fd
, fe
);
4003 if (rc
!= sizeof(struct tagfile_entry
))
4005 /* End of lookup table. */
4006 logf("read error #11");
4011 /* We have a special handling for the filename tags. */
4012 if (tag
== tag_filename
)
4014 # ifdef HAVE_DIRCACHE
4015 const struct dircache_entry
*dc
;
4018 // FIXME: This is wrong!
4019 // idx = &hdr->indices[hdr->entry_count[i]];
4020 idx
= &hdr
->indices
[fe
->idx_id
];
4022 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
4026 logf("TAG:%s", buf
);
4027 logf("too long filename");
4032 rc
= read(fd
, buf
, fe
->tag_length
);
4033 if (rc
!= fe
->tag_length
)
4035 logf("read error #12");
4040 /* Check if the entry has already been removed */
4041 if (idx
->flag
& FLAG_DELETED
)
4044 /* This flag must not be used yet. */
4045 if (idx
->flag
& FLAG_DIRCACHE
)
4047 logf("internal error!");
4052 if (idx
->tag_seek
[tag
] != pos
)
4054 logf("corrupt data structures!");
4059 # ifdef HAVE_DIRCACHE
4060 if (dircache_is_enabled())
4062 dc
= dircache_get_entry_ptr(buf
);
4065 logf("Entry no longer valid.");
4067 if (global_settings
.tagcache_autoupdate
)
4068 delete_entry(fe
->idx_id
);
4072 idx
->flag
|= FLAG_DIRCACHE
;
4073 idx
->tag_seek
[tag_filename
] = (long)dc
;
4078 /* This will be very slow unless dircache is enabled
4079 or target is flash based, but do it anyway for
4081 /* Check if entry has been removed. */
4082 if (global_settings
.tagcache_autoupdate
)
4084 if (!file_exists(buf
))
4086 logf("Entry no longer valid.");
4088 delete_entry(fe
->idx_id
);
4097 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
4100 logf("too big tagcache #2");
4101 logf("tl: %ld", fe
->tag_length
);
4102 logf("bl: %ld", bytesleft
);
4108 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
4111 if (rc
!= fe
->tag_length
)
4113 logf("read error #13");
4114 logf("rc=0x%04x", rc
); // 0x431
4115 logf("len=0x%04lx", fe
->tag_length
); // 0x4000
4116 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
4117 logf("tag=0x%02x", tag
); // 0x00
4125 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4126 logf("tagcache loaded into ram!");
4130 #endif /* HAVE_TC_RAMCACHE */
4132 static bool check_deleted_files(void)
4135 char buf
[TAG_MAXLEN
+32];
4136 struct tagfile_entry tfe
;
4138 logf("reverse scan...");
4139 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4140 fd
= open(buf
, O_RDONLY
);
4144 logf("%s open fail", buf
);
4148 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4149 while (ecread_tagfile_entry(fd
, &tfe
) == sizeof(struct tagfile_entry
)
4151 && !check_event_queue()
4155 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4157 logf("too long tag");
4162 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4164 logf("read error #14");
4169 /* Check if the file has already deleted from the db. */
4173 /* Now check if the file exists. */
4174 if (!file_exists(buf
))
4176 logf("Entry no longer valid.");
4177 logf("-> %s / %ld", buf
, tfe
.tag_length
);
4178 delete_entry(tfe
.idx_id
);
4190 /* Note that this function must not be inlined, otherwise the whole point
4191 * of having the code in a separate function is lost.
4193 static void __attribute__ ((noinline
)) check_ignore(const char *dirname
,
4194 int *ignore
, int *unignore
)
4196 char newpath
[MAX_PATH
];
4198 /* check for a database.ignore file */
4199 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4200 *ignore
= file_exists(newpath
);
4201 /* check for a database.unignore file */
4202 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4203 *unignore
= file_exists(newpath
);
4206 static struct search_roots_ll
{
4208 struct search_roots_ll
* next
;
4213 * This adds a path to the search roots, possibly during traveling through
4214 * the filesystem. It only adds if the path is not inside an already existing
4217 * Returns true if it added the path to the search roots
4219 * Windows 2000 and greater supports symlinks, but they don't provide
4220 * realpath() or readlink(), and symlinks are rarely used on them so
4221 * ignore this for windows for now
4223 static bool add_search_root(const char *name
)
4227 struct search_roots_ll
*this, *prev
= NULL
;
4228 char target
[MAX_PATH
];
4229 char _abs_target
[MAX_PATH
];
4233 len
= readlink(name
, target
, sizeof(target
));
4238 /* realpath(target, NULL) doesn't work on android ... */
4239 abs_target
= realpath(target
, _abs_target
);
4240 if (abs_target
== NULL
)
4243 for(this = &roots_ll
; this; prev
= this, this = this->next
)
4245 size_t root_len
= strlen(this->path
);
4246 /* check if the link target is inside of an existing search root
4247 * don't add if target is inside, we'll scan it later */
4248 if (!strncmp(this->path
, abs_target
, root_len
))
4254 size_t len
= strlen(abs_target
) + 1; /* count \0 */
4255 this = malloc(sizeof(struct search_roots_ll
) + len
);
4256 if (!this || len
> MAX_PATH
)
4258 logf("Error at adding a search root: %s", this ? "path too long":"OOM");
4262 this->path
= ((char*)this) + sizeof(struct search_roots_ll
);
4263 strcpy((char*)this->path
, abs_target
); /* ok to cast const away here */
4266 logf("Added %s to the search roots\n", abs_target
);
4273 static int free_search_roots(struct search_roots_ll
* start
)
4278 ret
+= free_search_roots(start
->next
);
4279 ret
+= sizeof(struct search_roots_ll
);
4284 #else /* native, simulator */
4285 #define add_search_root(a) do {} while(0)
4286 #define free_search_roots(a) do {} while(0)
4289 static bool check_dir(const char *dirname
, int add_files
)
4293 int success
= false;
4294 int ignore
, unignore
;
4296 dir
= opendir(dirname
);
4299 logf("tagcache: opendir(%s) failed", dirname
);
4302 /* check for a database.ignore and database.unignore */
4303 check_ignore(dirname
, &ignore
, &unignore
);
4305 /* don't do anything if both ignore and unignore are there */
4306 if (ignore
!= unignore
)
4307 add_files
= unignore
;
4309 /* Recursively scan the dir. */
4313 while (!check_event_queue())
4316 struct dirent
*entry
= readdir(dir
);
4323 if (!strcmp((char *)entry
->d_name
, ".") ||
4324 !strcmp((char *)entry
->d_name
, ".."))
4327 struct dirinfo info
= dir_get_info(dir
, entry
);
4331 len
= strlen(curpath
);
4332 /* don't add an extra / for curpath == / */
4333 if (len
<= 1) len
= 0;
4334 snprintf(&curpath
[len
], sizeof(curpath
) - len
, "/%s", entry
->d_name
);
4336 processed_dir_count
++;
4337 if (info
.attribute
& ATTR_DIRECTORY
)
4338 { /* don't follow symlinks to dirs, but try to add it as a search root
4339 * this makes able to avoid looping in recursive symlinks */
4340 if (info
.attribute
& ATTR_LINK
)
4341 add_search_root(curpath
);
4343 check_dir(curpath
, add_files
);
4347 tc_stat
.curentry
= curpath
;
4349 /* Add a new entry to the temporary db file. */
4350 add_tagcache(curpath
, (info
.wrtdate
<< 16) | info
.wrttime
4351 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4352 , dir
->internal_entry
4356 /* Wait until current path for debug screen is read and unset. */
4357 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4360 tc_stat
.curentry
= NULL
;
4363 curpath
[len
] = '\0';
4371 void tagcache_screensync_event(void)
4373 tc_stat
.curentry
= NULL
;
4376 void tagcache_screensync_enable(bool state
)
4378 tc_stat
.syncscreen
= state
;
4381 void tagcache_build(const char *path
)
4383 struct tagcache_header header
;
4388 total_entry_count
= 0;
4389 processed_dir_count
= 0;
4391 #ifdef HAVE_DIRCACHE
4392 while (dircache_is_initializing())
4396 logf("updating tagcache");
4398 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
4401 logf("skipping, cache already waiting for commit");
4406 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDWR
| O_CREAT
| O_TRUNC
, 0666);
4409 logf("master file open failed: %s", TAGCACHE_FILE_TEMP
);
4413 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4417 logf("Scanning files...");
4418 /* Scan for new files. */
4419 memset(&header
, 0, sizeof(struct tagcache_header
));
4420 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4423 roots_ll
.path
= path
;
4424 roots_ll
.next
= NULL
;
4425 struct search_roots_ll
* this;
4426 /* check_dir might add new roots */
4427 for(this = &roots_ll
; this; this = this->next
)
4429 strcpy(curpath
, this->path
);
4430 ret
= ret
&& check_dir(this->path
, true);
4433 free_search_roots(roots_ll
.next
);
4435 /* Write the header. */
4436 header
.magic
= TAGCACHE_MAGIC
;
4437 header
.datasize
= data_size
;
4438 header
.entry_count
= total_entry_count
;
4439 lseek(cachefd
, 0, SEEK_SET
);
4440 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4443 if (filenametag_fd
>= 0)
4445 close(filenametag_fd
);
4446 filenametag_fd
= -1;
4456 /* Commit changes to the database. */
4462 remove(TAGCACHE_FILE_TEMP
);
4463 logf("tagcache built!");
4469 #ifdef HAVE_TC_RAMCACHE
4472 /* Import runtime statistics if we just initialized the db. */
4473 if (hdr
->h
.serial
== 0)
4474 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4481 #ifdef HAVE_TC_RAMCACHE
4482 static void load_ramcache(void)
4489 /* At first we should load the cache (if exists). */
4490 tc_stat
.ramcache
= load_tagcache();
4492 if (!tc_stat
.ramcache
)
4494 /* If loading failed, it must indicate some problem with the db
4495 * so disable it entirely to prevent further issues. */
4496 tc_stat
.ready
= false;
4503 void tagcache_unload_ramcache(void)
4505 tc_stat
.ramcache
= false;
4506 /* Just to make sure there is no statefile present. */
4507 // remove(TAGCACHE_STATEFILE);
4512 static void tagcache_thread(void)
4514 struct queue_event ev
;
4515 bool check_done
= false;
4517 /* If the previous cache build/update was interrupted, commit
4518 * the changes first in foreground. */
4524 #ifdef HAVE_TC_RAMCACHE
4525 # ifdef HAVE_EEPROM_SETTINGS
4526 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
4527 && global_settings
.tagcache_ram
)
4529 check_done
= tagcache_dumpload();
4532 remove(TAGCACHE_STATEFILE
);
4535 /* Allocate space for the tagcache if found on disk. */
4536 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4537 allocate_tagcache();
4541 tc_stat
.initialized
= true;
4543 /* Don't delay bootup with the header check but do it on background. */
4547 tc_stat
.ready
= check_all_headers();
4548 tc_stat
.readyvalid
= true;
4553 run_command_queue(false);
4555 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4559 case Q_IMPORT_CHANGELOG
:
4560 tagcache_import_changelog();
4565 remove(TAGCACHE_FILE_TEMP
);
4566 tagcache_build("/");
4570 tagcache_build("/");
4571 #ifdef HAVE_TC_RAMCACHE
4574 check_deleted_files();
4580 if (check_done
|| !tc_stat
.ready
)
4583 #ifdef HAVE_TC_RAMCACHE
4584 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4587 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4588 tagcache_build("/");
4592 if (global_settings
.tagcache_autoupdate
)
4594 tagcache_build("/");
4596 /* This will be very slow unless dircache is enabled
4597 or target is flash based, but do it anyway for
4599 check_deleted_files();
4602 logf("tagcache check done");
4613 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4614 case SYS_USB_CONNECTED
:
4615 logf("USB: TagCache");
4616 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4617 usb_wait_for_disconnect(&tagcache_queue
);
4624 bool tagcache_prepare_shutdown(void)
4626 if (tagcache_get_commit_step() > 0)
4629 tagcache_stop_scan();
4630 while (read_lock
|| write_lock
)
4636 void tagcache_shutdown(void)
4638 /* Flush the command queue. */
4639 run_command_queue(true);
4641 #ifdef HAVE_EEPROM_SETTINGS
4642 if (tc_stat
.ramcache
)
4643 tagcache_dumpsave();
4647 static int get_progress(void)
4649 int total_count
= -1;
4651 #ifdef HAVE_DIRCACHE
4652 if (dircache_is_enabled())
4654 total_count
= dircache_get_entry_count();
4658 #ifdef HAVE_TC_RAMCACHE
4660 if (hdr
&& tc_stat
.ramcache
)
4661 total_count
= hdr
->h
.tch
.entry_count
;
4665 if (total_count
< 0)
4668 return processed_dir_count
* 100 / total_count
;
4671 struct tagcache_stat
* tagcache_get_stat(void)
4673 tc_stat
.progress
= get_progress();
4674 tc_stat
.processed_entries
= processed_dir_count
;
4679 void tagcache_start_scan(void)
4681 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4684 bool tagcache_update(void)
4689 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4693 bool tagcache_rebuild()
4695 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4699 void tagcache_stop_scan(void)
4701 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4704 #ifdef HAVE_TC_RAMCACHE
4705 bool tagcache_is_ramcache(void)
4707 return tc_stat
.ramcache
;
4711 #endif /* !__PCTOOL__ */
4714 void tagcache_init(void)
4716 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4717 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4718 filenametag_fd
= -1;
4719 write_lock
= read_lock
= 0;
4722 mutex_init(&command_queue_mutex
);
4723 queue_init(&tagcache_queue
, true);
4724 create_thread(tagcache_thread
, tagcache_stack
,
4725 sizeof(tagcache_stack
), 0, tagcache_thread_name
4726 IF_PRIO(, PRIORITY_BACKGROUND
)
4729 tc_stat
.initialized
= true;
4733 tc_stat
.ready
= check_all_headers();
4738 void tagcache_reverse_scan(void)
4740 logf("Checking for deleted files");
4741 check_deleted_files();
4745 bool tagcache_is_initialized(void)
4747 return tc_stat
.initialized
;
4749 bool tagcache_is_fully_initialized(void)
4751 return tc_stat
.readyvalid
;
4753 bool tagcache_is_usable(void)
4755 return tc_stat
.initialized
&& tc_stat
.ready
;
4757 int tagcache_get_commit_step(void)
4759 return tc_stat
.commit_step
;
4761 int tagcache_get_max_commit_step(void)
4763 return (int)(SORTED_TAGS_COUNT
)+1;