1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
25 * ----------x---------x------------------x-----
27 * +---------------x-------+ | TagCache | Libraries
28 * | Modification routines | | Core |
29 * +-x---------x-----------+ | |
31 * | +------x-------------x-+ +-------------x-----+ |
32 * | | x==x Filters & clauses | |
33 * | | Search routines | +-------------------+ |
34 * | | x============================x DirCache
35 * | +-x--------------------+ | (optional)
37 * | | +-------------------------------+ +---------+ |
38 * | | | DB Commit (sort,unique,index) | | | |
39 * | | +-x--------------------------x--+ | Control | |
40 * | | | (R/W) | (R) | Thread | |
41 * | | | +----------------------+ | | | |
42 * | | | | TagCache DB Builder | | +---------+ |
43 * | | | +-x-------------x------+ | |
44 * | | | | (R) | (W) | |
45 * | | | | +--x--------x---------+ |
46 * | | | | | Temporary Commit DB | |
47 * | | | | +---------------------+ |
48 * +-x----x-------x--+ |
49 * | TagCache RAM DB x==\(W) +-----------------+ |
50 * +-----------------+ \===x | |
51 * | | | | (R) | Ram DB Loader x============x DirCache
52 * +-x----x---x---x---+ /==x | | (optional)
53 * | Tagcache Disk DB x==/ +-----------------+ |
54 * +------------------+ |
58 /*#define LOGF_ENABLE*/
64 #include "ata_idle_notify.h"
82 #include "eeprom_settings.h"
86 #define yield() do { } while(0)
87 #define sim_sleep(timeout) do { } while(0)
88 #define do_timed_yield() do { } while(0)
92 /* Tag Cache thread. */
93 static struct event_queue tagcache_queue
;
94 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
95 static const char tagcache_thread_name
[] = "tagcache";
98 #define UNTAGGED "<Untagged>"
100 /* Previous path when scanning directory tree recursively. */
101 static char curpath
[TAG_MAXLEN
+32];
103 /* Used when removing duplicates. */
104 static char *tempbuf
; /* Allocated when needed. */
105 static long tempbufidx
; /* Current location in buffer. */
106 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
107 static long tempbuf_left
; /* Buffer space left. */
108 static long tempbuf_pos
;
110 #define SORTED_TAGS_COUNT 8
111 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
112 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
113 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
114 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
115 /* Tags we want to get sorted (loaded to the tempbuf). */
116 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
117 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
118 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
120 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
121 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
122 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
123 (1LU << tag_albumartist) | (1LU << tag_grouping))
125 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
126 static const char *tags_str
[] = { "artist", "album", "genre", "title",
127 "filename", "composer", "comment", "albumartist", "grouping", "year",
128 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
129 "playtime", "lastplayed", "commitid", "mtime" };
131 /* Status information of the tagcache. */
132 static struct tagcache_stat tc_stat
;
134 /* Queue commands. */
135 enum tagcache_queue
{
142 /* Internal tagcache command queue. */
143 CMD_UPDATE_MASTER_HEADER
,
147 struct tagcache_command_entry
{
155 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
156 static volatile int command_queue_widx
= 0;
157 static volatile int command_queue_ridx
= 0;
158 static struct mutex command_queue_mutex
;
161 /* Tag database structures. */
163 /* Variable-length tag entry in tag files. */
164 struct tagfile_entry
{
165 int32_t tag_length
; /* Length of the data in bytes including '\0' */
166 int32_t idx_id
; /* Corresponding entry location in index file of not unique tags */
167 char tag_data
[0]; /* Begin of the tag data */
170 /* Fixed-size tag entry in master db index. */
172 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
173 int32_t flag
; /* Status flags */
176 /* Header is the same in every file. */
177 struct tagcache_header
{
178 int32_t magic
; /* Header version number */
179 int32_t datasize
; /* Data size in bytes */
180 int32_t entry_count
; /* Number of entries in this file */
183 struct master_header
{
184 struct tagcache_header tch
;
185 int32_t serial
; /* Increasing counting number */
186 int32_t commitid
; /* Number of commits so far */
190 /* For the endianess correction */
191 static const char *tagfile_entry_ec
= "ll";
193 Note: This should be (1 + TAG_COUNT) amount of l's.
195 static const char *index_entry_ec
= "lllllllllllllllllllll";
197 static const char *tagcache_header_ec
= "lll";
198 static const char *master_header_ec
= "llllll";
200 static struct master_header current_tcmh
;
202 #ifdef HAVE_TC_RAMCACHE
203 /* Header is created when loading database to ram. */
204 struct ramcache_header
{
205 struct master_header h
; /* Header from the master index */
206 struct index_entry
*indices
; /* Master index file content */
207 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
208 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
211 # ifdef HAVE_EEPROM_SETTINGS
212 struct statefile_header
{
213 struct ramcache_header
*hdr
;
214 struct tagcache_stat tc_stat
;
218 /* Pointer to allocated ramcache_header */
219 static struct ramcache_header
*hdr
;
223 * Full tag entries stored in a temporary file waiting
224 * for commit to the cache. */
225 struct temp_file_entry
{
226 long tag_offset
[TAG_COUNT
];
227 short tag_length
[TAG_COUNT
];
233 struct tempbuf_id_list
{
235 struct tempbuf_id_list
*next
;
238 struct tempbuf_searchidx
{
242 struct tempbuf_id_list idlist
;
245 /* Lookup buffer for fixing messed up index while after sorting. */
246 static long commit_entry_count
;
247 static long lookup_buffer_depth
;
248 static struct tempbuf_searchidx
**lookup
;
250 /* Used when building the temporary file. */
251 static int cachefd
= -1, filenametag_fd
;
252 static int total_entry_count
= 0;
253 static int data_size
= 0;
254 static int processed_dir_count
;
256 /* Thread safe locking */
257 static volatile int write_lock
;
258 static volatile int read_lock
;
260 static bool delete_entry(long idx_id
);
262 const char* tagcache_tag_to_str(int tag
)
264 return tags_str
[tag
];
269 * Returns true if specified flag is still present, i.e., dircache
270 * has not been reloaded.
272 static bool is_dircache_intact(void)
274 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
278 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
284 if (TAGCACHE_IS_NUMERIC(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
287 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
289 fd
= open(buf
, write
? O_RDWR
: O_RDONLY
);
292 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
293 tc_stat
.ready
= false;
297 /* Check the header. */
298 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
299 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
301 logf("header error");
302 tc_stat
.ready
= false;
310 static int open_master_fd(struct master_header
*hdr
, bool write
)
315 fd
= open(TAGCACHE_FILE_MASTER
, write
? O_RDWR
: O_RDONLY
);
318 logf("master file open failed for R/W");
319 tc_stat
.ready
= false;
323 tc_stat
.econ
= false;
325 /* Check the header. */
326 rc
= read(fd
, hdr
, sizeof(struct master_header
));
327 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
333 /* Trying to read again, this time with endianess correction enabled. */
334 lseek(fd
, 0, SEEK_SET
);
336 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
337 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
339 logf("header error");
340 tc_stat
.ready
= false;
351 static bool do_timed_yield(void)
353 /* Sorting can lock up for quite a while, so yield occasionally */
354 static long wakeup_tick
= 0;
355 if (TIME_AFTER(current_tick
, wakeup_tick
))
357 wakeup_tick
= current_tick
+ (HZ
/4);
365 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
366 static long find_entry_ram(const char *filename
,
367 const struct dirent
*dc
)
369 static long last_pos
= 0;
372 /* Check if we tagcache is loaded into ram. */
373 if (!tc_stat
.ramcache
)
377 dc
= dircache_get_entry_ptr(filename
);
381 logf("tagcache: file not found.");
392 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
394 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
396 last_pos
= MAX(0, i
- 3);
413 static long find_entry_disk(const char *filename
, bool localfd
)
415 struct tagcache_header tch
;
416 static long last_pos
= -1;
417 long pos_history
[POS_HISTORY_COUNT
];
418 long pos_history_idx
= 0;
420 struct tagfile_entry tfe
;
422 char buf
[TAG_MAXLEN
+32];
430 if (fd
< 0 || localfd
)
433 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
440 lseek(fd
, last_pos
, SEEK_SET
);
442 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
446 pos
= lseek(fd
, 0, SEEK_CUR
);
447 for (i
= pos_history_idx
-1; i
>= 0; i
--)
448 pos_history
[i
+1] = pos_history
[i
];
449 pos_history
[0] = pos
;
451 if (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
452 != sizeof(struct tagfile_entry
))
457 if (tfe
.tag_length
>= (long)sizeof(buf
))
459 logf("too long tag #1");
467 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
469 logf("read error #2");
477 if (!strcasecmp(filename
, buf
))
479 last_pos
= pos_history
[pos_history_idx
];
484 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
498 if (fd
!= filenametag_fd
|| localfd
)
503 if (fd
!= filenametag_fd
|| localfd
)
509 static int find_index(const char *filename
)
513 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
514 if (tc_stat
.ramcache
&& is_dircache_intact())
515 idx_id
= find_entry_ram(filename
, NULL
);
519 idx_id
= find_entry_disk(filename
, true);
524 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
531 idx_id
= find_index(filename
);
535 if (!tagcache_search(tcs
, tag_filename
))
538 tcs
->entry_count
= 0;
539 tcs
->idx_id
= idx_id
;
544 static bool get_index(int masterfd
, int idxid
,
545 struct index_entry
*idx
, bool use_ram
)
547 bool localfd
= false;
551 logf("Incorrect idxid: %d", idxid
);
555 #ifdef HAVE_TC_RAMCACHE
556 if (tc_stat
.ramcache
&& use_ram
)
558 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
561 # ifdef HAVE_DIRCACHE
562 if (!(hdr
->indices
[idxid
].flag
& FLAG_DIRCACHE
)
563 || is_dircache_intact())
566 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
576 struct master_header tcmh
;
579 masterfd
= open_master_fd(&tcmh
, false);
584 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
585 + sizeof(struct master_header
), SEEK_SET
);
586 if (ecread(masterfd
, idx
, 1, index_entry_ec
, tc_stat
.econ
)
587 != sizeof(struct index_entry
))
589 logf("read error #3");
599 if (idx
->flag
& FLAG_DELETED
)
607 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
609 /* We need to exclude all memory only flags & tags when writing to disk. */
610 if (idx
->flag
& FLAG_DIRCACHE
)
612 logf("memory only flags!");
616 #ifdef HAVE_TC_RAMCACHE
617 /* Only update numeric data. Writing the whole index to RAM by memcpy
618 * destroys dircache pointers!
620 if (tc_stat
.ramcache
)
623 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
625 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
627 if (TAGCACHE_IS_NUMERIC(tag
))
629 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
633 /* Don't touch the dircache flag or attributes. */
634 idx_ram
->flag
= (idx
->flag
& 0x0000ffff)
635 | (idx_ram
->flag
& (0xffff0000 | FLAG_DIRCACHE
));
639 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
640 + sizeof(struct master_header
), SEEK_SET
);
641 if (ecwrite(masterfd
, idx
, 1, index_entry_ec
, tc_stat
.econ
)
642 != sizeof(struct index_entry
))
644 logf("write error #3");
645 logf("idxid: %d", idxid
);
652 #endif /* !__PCTOOL__ */
654 static bool open_files(struct tagcache_search
*tcs
, int tag
)
656 if (tcs
->idxfd
[tag
] < 0)
660 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
661 tcs
->idxfd
[tag
] = open(fn
, O_RDONLY
);
664 if (tcs
->idxfd
[tag
] < 0)
666 logf("File not open!");
673 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
674 int tag
, char *buf
, long size
)
676 struct tagfile_entry tfe
;
681 if (TAGCACHE_IS_NUMERIC(tag
))
684 seek
= idx
->tag_seek
[tag
];
687 logf("Retrieve failed");
691 #ifdef HAVE_TC_RAMCACHE
694 struct tagfile_entry
*ep
;
696 # ifdef HAVE_DIRCACHE
697 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
698 && is_dircache_intact())
700 dircache_copy_path((struct dirent
*)seek
,
706 if (tag
!= tag_filename
)
708 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
709 strlcpy(buf
, ep
->tag_data
, size
);
716 if (!open_files(tcs
, tag
))
719 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
720 if (ecread(tcs
->idxfd
[tag
], &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
721 != sizeof(struct tagfile_entry
))
723 logf("read error #5");
727 if (tfe
.tag_length
>= size
)
729 logf("too small buffer");
733 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
736 logf("read error #6");
740 buf
[tfe
.tag_length
] = '\0';
745 static long check_virtual_tags(int tag
, const struct index_entry
*idx
)
751 case tag_virt_length_sec
:
752 data
= (idx
->tag_seek
[tag_length
]/1000) % 60;
755 case tag_virt_length_min
:
756 data
= (idx
->tag_seek
[tag_length
]/1000) / 60;
759 case tag_virt_playtime_sec
:
760 data
= (idx
->tag_seek
[tag_playtime
]/1000) % 60;
763 case tag_virt_playtime_min
:
764 data
= (idx
->tag_seek
[tag_playtime
]/1000) / 60;
767 case tag_virt_autoscore
:
768 if (idx
->tag_seek
[tag_length
] == 0
769 || idx
->tag_seek
[tag_playcount
] == 0)
775 /* A straight calculus gives:
776 autoscore = 100 * playtime / length / playcout (1)
777 Now, consider the euclidian division of playtime by length:
778 playtime = alpha * length + beta
782 autoscore = 100 * (alpha / playcout + beta / length / playcount)
783 Both terms should be small enough to avoid any overflow
785 data
= 100 * (idx
->tag_seek
[tag_playtime
] / idx
->tag_seek
[tag_length
])
786 + (100 * (idx
->tag_seek
[tag_playtime
] % idx
->tag_seek
[tag_length
])) / idx
->tag_seek
[tag_length
];
787 data
/= idx
->tag_seek
[tag_playcount
];
791 /* How many commits before the file has been added to the DB. */
792 case tag_virt_entryage
:
793 data
= current_tcmh
.commitid
- idx
->tag_seek
[tag_commitid
] - 1;
797 data
= idx
->tag_seek
[tag
];
803 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
805 struct index_entry idx
;
810 if (!TAGCACHE_IS_NUMERIC(tag
))
813 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
816 return check_virtual_tags(tag
, &idx
);
819 inline static bool str_ends_with(const char *str1
, const char *str2
)
821 int str_len
= strlen(str1
);
822 int clause_len
= strlen(str2
);
824 if (clause_len
> str_len
)
827 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
830 inline static bool str_oneof(const char *str
, const char *list
)
833 int l
, len
= strlen(str
);
837 sep
= strchr(list
, '|');
838 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
839 if ((l
==len
) && !strncasecmp(str
, list
, len
))
841 list
+= sep
? l
+ 1 : l
;
847 static bool check_against_clause(long numeric
, const char *str
,
848 const struct tagcache_search_clause
*clause
)
852 switch (clause
->type
)
855 return numeric
== clause
->numeric_data
;
857 return numeric
!= clause
->numeric_data
;
859 return numeric
> clause
->numeric_data
;
861 return numeric
>= clause
->numeric_data
;
863 return numeric
< clause
->numeric_data
;
865 return numeric
<= clause
->numeric_data
;
867 logf("Incorrect numeric tag: %d", clause
->type
);
872 switch (clause
->type
)
875 return !strcasecmp(clause
->str
, str
);
877 return strcasecmp(clause
->str
, str
);
879 return 0>strcasecmp(clause
->str
, str
);
881 return 0>=strcasecmp(clause
->str
, str
);
883 return 0<strcasecmp(clause
->str
, str
);
885 return 0<=strcasecmp(clause
->str
, str
);
886 case clause_contains
:
887 return (strcasestr(str
, clause
->str
) != NULL
);
888 case clause_not_contains
:
889 return (strcasestr(str
, clause
->str
) == NULL
);
890 case clause_begins_with
:
891 return (strcasestr(str
, clause
->str
) == str
);
892 case clause_not_begins_with
:
893 return (strcasestr(str
, clause
->str
) != str
);
894 case clause_ends_with
:
895 return str_ends_with(str
, clause
->str
);
896 case clause_not_ends_with
:
897 return !str_ends_with(str
, clause
->str
);
899 return str_oneof(str
, clause
->str
);
902 logf("Incorrect tag: %d", clause
->type
);
909 static bool check_clauses(struct tagcache_search
*tcs
,
910 struct index_entry
*idx
,
911 struct tagcache_search_clause
**clause
, int count
)
915 #ifdef HAVE_TC_RAMCACHE
918 /* Go through all conditional clauses. */
919 for (i
= 0; i
< count
; i
++)
921 struct tagfile_entry
*tfe
;
926 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
928 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
930 if (clause
[i
]->tag
== tag_filename
)
932 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
937 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
942 if (!check_against_clause(seek
, str
, clause
[i
]))
949 /* Check for conditions. */
950 for (i
= 0; i
< count
; i
++)
952 struct tagfile_entry tfe
;
956 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
958 memset(str
, 0, sizeof str
);
959 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
961 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
962 lseek(fd
, seek
, SEEK_SET
);
963 ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
964 if (tfe
.tag_length
>= (int)sizeof(str
))
966 logf("Too long tag read!");
970 read(fd
, str
, tfe
.tag_length
);
972 /* Check if entry has been deleted. */
977 if (!check_against_clause(seek
, str
, clause
[i
]))
985 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
986 struct tagcache_search_clause
**clause
, int count
)
988 struct index_entry idx
;
993 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
996 return check_clauses(tcs
, &idx
, clause
, count
);
999 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1003 /* If uniq buffer is not defined we must return true for search to work. */
1004 if (tcs
->unique_list
== NULL
|| (!TAGCACHE_IS_UNIQUE(tcs
->type
)
1005 && !TAGCACHE_IS_NUMERIC(tcs
->type
)))
1010 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1012 /* Return false if entry is found. */
1013 if (tcs
->unique_list
[i
] == id
)
1017 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1019 tcs
->unique_list
[i
] = id
;
1020 tcs
->unique_list_count
++;
1026 static bool build_lookup_list(struct tagcache_search
*tcs
)
1028 struct index_entry entry
;
1031 tcs
->seek_list_count
= 0;
1033 #ifdef HAVE_TC_RAMCACHE
1035 # ifdef HAVE_DIRCACHE
1036 && (tcs
->type
!= tag_filename
|| is_dircache_intact())
1040 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
1042 struct tagcache_seeklist_entry
*seeklist
;
1043 struct index_entry
*idx
= &hdr
->indices
[i
];
1044 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1047 /* Skip deleted files. */
1048 if (idx
->flag
& FLAG_DELETED
)
1051 /* Go through all filters.. */
1052 for (j
= 0; j
< tcs
->filter_count
; j
++)
1054 if (idx
->tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1060 if (j
< tcs
->filter_count
)
1063 /* Check for conditions. */
1064 if (!check_clauses(tcs
, idx
, tcs
->clause
, tcs
->clause_count
))
1067 /* Add to the seek list if not already in uniq buffer. */
1068 if (!add_uniqbuf(tcs
, idx
->tag_seek
[tcs
->type
]))
1072 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1073 seeklist
->seek
= idx
->tag_seek
[tcs
->type
];
1074 seeklist
->flag
= idx
->flag
;
1075 seeklist
->idx_id
= i
;
1076 tcs
->seek_list_count
++;
1081 return tcs
->seek_list_count
> 0;
1085 if (tcs
->masterfd
< 0)
1087 struct master_header tcmh
;
1088 tcs
->masterfd
= open_master_fd(&tcmh
, false);
1091 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1092 sizeof(struct master_header
), SEEK_SET
);
1094 while (ecread(tcs
->masterfd
, &entry
, 1, index_entry_ec
, tc_stat
.econ
)
1095 == sizeof(struct index_entry
))
1097 struct tagcache_seeklist_entry
*seeklist
;
1099 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1105 /* Check if entry has been deleted. */
1106 if (entry
.flag
& FLAG_DELETED
)
1109 /* Go through all filters.. */
1110 for (j
= 0; j
< tcs
->filter_count
; j
++)
1112 if (entry
.tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1116 if (j
< tcs
->filter_count
)
1119 /* Check for conditions. */
1120 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1123 /* Add to the seek list if not already in uniq buffer. */
1124 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1128 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1129 seeklist
->seek
= entry
.tag_seek
[tcs
->type
];
1130 seeklist
->flag
= entry
.flag
;
1131 seeklist
->idx_id
= i
;
1132 tcs
->seek_list_count
++;
1137 return tcs
->seek_list_count
> 0;
1141 static void remove_files(void)
1146 tc_stat
.ready
= false;
1147 tc_stat
.ramcache
= false;
1148 tc_stat
.econ
= false;
1149 remove(TAGCACHE_FILE_MASTER
);
1150 for (i
= 0; i
< TAG_COUNT
; i
++)
1152 if (TAGCACHE_IS_NUMERIC(i
))
1155 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1161 static bool check_all_headers(void)
1163 struct master_header myhdr
;
1164 struct tagcache_header tch
;
1168 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1174 logf("tagcache is dirty!");
1178 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1180 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1182 if (TAGCACHE_IS_NUMERIC(tag
))
1185 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1194 bool tagcache_is_busy(void)
1196 return read_lock
|| write_lock
;
1199 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1201 struct tagcache_header tag_hdr
;
1202 struct master_header master_hdr
;
1208 memset(tcs
, 0, sizeof(struct tagcache_search
));
1209 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1212 tcs
->position
= sizeof(struct tagcache_header
);
1215 tcs
->list_position
= 0;
1216 tcs
->seek_list_count
= 0;
1217 tcs
->filter_count
= 0;
1220 for (i
= 0; i
< TAG_COUNT
; i
++)
1223 #ifndef HAVE_TC_RAMCACHE
1224 tcs
->ramsearch
= false;
1226 tcs
->ramsearch
= tc_stat
.ramcache
;
1229 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1234 /* Always open as R/W so we can pass tcs to functions that modify data also
1235 * without failing. */
1236 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1237 if (tcs
->masterfd
< 0)
1240 if (!TAGCACHE_IS_NUMERIC(tcs
->type
))
1242 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1243 if (tcs
->idxfd
[tcs
->type
] < 0)
1246 tcs
->entry_count
= tag_hdr
.entry_count
;
1250 tcs
->entry_count
= master_hdr
.tch
.entry_count
;
1255 tcs
->initialized
= true;
1261 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1262 void *buffer
, long length
)
1264 tcs
->unique_list
= (unsigned long *)buffer
;
1265 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1266 tcs
->unique_list_count
= 0;
1269 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1272 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1275 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag
))
1278 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1279 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1280 tcs
->filter_count
++;
1285 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1286 struct tagcache_search_clause
*clause
)
1290 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1292 logf("Too many clauses");
1296 /* Check if there is already a similar filter in present (filters are
1297 * much faster than clauses).
1299 for (i
= 0; i
< tcs
->filter_count
; i
++)
1301 if (tcs
->filter_tag
[i
] == clause
->tag
)
1305 if (!TAGCACHE_IS_NUMERIC(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1309 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1310 tcs
->idxfd
[clause
->tag
] = open(buf
, O_RDONLY
);
1313 tcs
->clause
[tcs
->clause_count
] = clause
;
1314 tcs
->clause_count
++;
1319 static bool get_next(struct tagcache_search
*tcs
)
1321 static char buf
[TAG_MAXLEN
+32];
1322 struct tagfile_entry entry
;
1325 if (!tcs
->valid
|| !tc_stat
.ready
)
1328 if (tcs
->idxfd
[tcs
->type
] < 0 && !TAGCACHE_IS_NUMERIC(tcs
->type
)
1329 #ifdef HAVE_TC_RAMCACHE
1335 /* Relative fetch. */
1336 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1337 || TAGCACHE_IS_NUMERIC(tcs
->type
)
1338 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1339 /* We need to retrieve flag status for dircache. */
1340 || (tcs
->ramsearch
&& tcs
->type
== tag_filename
)
1344 struct tagcache_seeklist_entry
*seeklist
;
1346 /* Check for end of list. */
1347 if (tcs
->list_position
== tcs
->seek_list_count
)
1349 tcs
->list_position
= 0;
1351 /* Try to fetch more. */
1352 if (!build_lookup_list(tcs
))
1359 seeklist
= &tcs
->seeklist
[tcs
->list_position
];
1360 flag
= seeklist
->flag
;
1361 tcs
->position
= seeklist
->seek
;
1362 tcs
->idx_id
= seeklist
->idx_id
;
1363 tcs
->list_position
++;
1367 if (tcs
->entry_count
== 0)
1376 tcs
->result_seek
= tcs
->position
;
1378 if (TAGCACHE_IS_NUMERIC(tcs
->type
))
1380 snprintf(buf
, sizeof(buf
), "%d", tcs
->position
);
1382 tcs
->result_len
= strlen(buf
) + 1;
1387 #ifdef HAVE_TC_RAMCACHE
1391 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1392 if (tcs
->type
== tag_filename
&& (flag
& FLAG_DIRCACHE
)
1393 && is_dircache_intact())
1395 dircache_copy_path((struct dirent
*)tcs
->position
,
1398 tcs
->result_len
= strlen(buf
) + 1;
1399 tcs
->ramresult
= false;
1405 if (tcs
->type
!= tag_filename
)
1407 struct tagfile_entry
*ep
;
1409 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1410 tcs
->result
= ep
->tag_data
;
1411 tcs
->result_len
= strlen(tcs
->result
) + 1;
1412 tcs
->idx_id
= ep
->idx_id
;
1413 tcs
->ramresult
= true;
1415 /* Increase position for the next run. This may get overwritten. */
1416 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1423 if (!open_files(tcs
, tcs
->type
))
1429 /* Seek stream to the correct position and continue to direct fetch. */
1430 lseek(tcs
->idxfd
[tcs
->type
], tcs
->position
, SEEK_SET
);
1432 if (ecread(tcs
->idxfd
[tcs
->type
], &entry
, 1,
1433 tagfile_entry_ec
, tc_stat
.econ
) != sizeof(struct tagfile_entry
))
1435 logf("read error #5");
1440 if (entry
.tag_length
> (long)sizeof(buf
))
1443 logf("too long tag #2");
1444 logf("P:%X/%X", tcs
->position
, entry
.tag_length
);
1448 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1451 logf("read error #4");
1456 Update the position for the next read (this may be overridden
1457 if filters or clauses are being used).
1459 tcs
->position
+= sizeof(struct tagfile_entry
) + entry
.tag_length
;
1461 tcs
->result_len
= strlen(tcs
->result
) + 1;
1462 tcs
->idx_id
= entry
.idx_id
;
1463 tcs
->ramresult
= false;
1468 bool tagcache_get_next(struct tagcache_search
*tcs
)
1470 while (get_next(tcs
))
1472 if (tcs
->result_len
> 1)
1479 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1480 int tag
, char *buf
, long size
)
1482 struct index_entry idx
;
1485 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1488 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1491 static bool update_master_header(void)
1493 struct master_header myhdr
;
1499 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1502 myhdr
.serial
= current_tcmh
.serial
;
1503 myhdr
.commitid
= current_tcmh
.commitid
;
1504 myhdr
.dirty
= current_tcmh
.dirty
;
1507 lseek(fd
, 0, SEEK_SET
);
1508 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1511 #ifdef HAVE_TC_RAMCACHE
1514 hdr
->h
.serial
= current_tcmh
.serial
;
1515 hdr
->h
.commitid
= current_tcmh
.commitid
;
1516 hdr
->h
.dirty
= current_tcmh
.dirty
;
1525 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1527 struct tagentry
*entry
;
1529 if (tcs
->type
!= tag_title
)
1532 /* We will need reserve buffer for this. */
1535 struct tagfile_entry
*ep
;
1537 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1538 tcs
->seek_list
[tcs
->seek_list_count
];
1541 entry
= find_entry_ram();
1546 void tagcache_search_finish(struct tagcache_search
*tcs
)
1550 if (!tcs
->initialized
)
1553 if (tcs
->masterfd
>= 0)
1555 close(tcs
->masterfd
);
1559 for (i
= 0; i
< TAG_COUNT
; i
++)
1561 if (tcs
->idxfd
[i
] >= 0)
1563 close(tcs
->idxfd
[i
]);
1568 tcs
->ramsearch
= false;
1570 tcs
->initialized
= 0;
1575 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1576 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1578 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1581 static long get_tag_numeric(const struct index_entry
*entry
, int tag
)
1583 return check_virtual_tags(tag
, entry
);
1586 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1588 char* s
= get_tag(entry
, tag
)->tag_data
;
1589 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1592 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1594 struct index_entry
*entry
;
1597 if (!tc_stat
.ready
|| !tc_stat
.ramcache
)
1600 /* Find the corresponding entry in tagcache. */
1601 idx_id
= find_entry_ram(filename
, NULL
);
1605 entry
= &hdr
->indices
[idx_id
];
1607 id3
->title
= get_tag_string(entry
, tag_title
);
1608 id3
->artist
= get_tag_string(entry
, tag_artist
);
1609 id3
->album
= get_tag_string(entry
, tag_album
);
1610 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1611 id3
->composer
= get_tag_string(entry
, tag_composer
);
1612 id3
->comment
= get_tag_string(entry
, tag_comment
);
1613 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1614 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1616 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
);
1617 id3
->rating
= get_tag_numeric(entry
, tag_rating
);
1618 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
);
1619 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
) / 10;
1620 id3
->year
= get_tag_numeric(entry
, tag_year
);
1622 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
);
1623 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
);
1624 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
);
1625 if (id3
->bitrate
== 0)
1632 static inline void write_item(const char *item
)
1634 int len
= strlen(item
) + 1;
1637 write(cachefd
, item
, len
);
1640 static int check_if_empty(char **tag
)
1644 if (*tag
== NULL
|| **tag
== '\0')
1647 return sizeof(UNTAGGED
); /* Tag length */
1650 length
= strlen(*tag
);
1651 if (length
> TAG_MAXLEN
)
1653 logf("over length tag: %s", *tag
);
1654 length
= TAG_MAXLEN
;
1655 (*tag
)[length
] = '\0';
1661 #define ADD_TAG(entry,tag,data) \
1663 entry.tag_offset[tag] = offset; \
1664 entry.tag_length[tag] = check_if_empty(data); \
1665 offset += entry.tag_length[tag]
1666 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1667 * idea, as it uses lots of stack and is called from a recursive function
1670 static void __attribute__ ((noinline
)) add_tagcache(char *path
,
1672 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1673 ,const struct dirent
*dc
1677 struct mp3entry id3
;
1678 struct temp_file_entry entry
;
1682 char tracknumfix
[3];
1684 int path_length
= strlen(path
);
1685 bool has_albumartist
;
1689 /* Crude logging for the sim - to aid in debugging */
1690 int logfd
= open(ROCKBOX_DIR
"/database.log",
1691 O_WRONLY
| O_APPEND
| O_CREAT
);
1693 write(logfd
, path
, strlen(path
));
1694 write(logfd
, "\n", 1);
1702 /* Check for overlength file path. */
1703 if (path_length
> TAG_MAXLEN
)
1705 /* Path can't be shortened. */
1706 logf("Too long path: %s", path
);
1710 /* Check if the file is supported. */
1711 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1714 /* Check if the file is already cached. */
1715 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1716 if (tc_stat
.ramcache
&& is_dircache_intact())
1718 idx_id
= find_entry_ram(path
, dc
);
1722 /* Be sure the entry doesn't exist. */
1723 if (filenametag_fd
>= 0 && idx_id
< 0)
1724 idx_id
= find_entry_disk(path
, false);
1726 /* Check if file has been modified. */
1729 struct index_entry idx
;
1731 /* TODO: Mark that the index exists (for fast reverse scan) */
1732 //found_idx[idx_id/8] |= idx_id%8;
1734 if (!get_index(-1, idx_id
, &idx
, true))
1736 logf("failed to retrieve index entry");
1740 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1742 /* No changes to file. */
1746 /* Metadata might have been changed. Delete the entry. */
1747 logf("Re-adding: %s", path
);
1748 if (!delete_entry(idx_id
))
1750 logf("delete_entry failed: %d", idx_id
);
1755 fd
= open(path
, O_RDONLY
);
1758 logf("open fail: %s", path
);
1762 memset(&id3
, 0, sizeof(struct mp3entry
));
1763 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1764 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1765 ret
= get_metadata(&id3
, fd
, path
);
1771 logf("-> %s", path
);
1773 /* Generate track number if missing. */
1774 if (id3
.tracknum
<= 0)
1776 const char *p
= strrchr(path
, '.');
1779 p
= &path
[strlen(path
)-1];
1783 if (isdigit(*p
) && isdigit(*(p
-1)))
1785 tracknumfix
[1] = *p
--;
1786 tracknumfix
[0] = *p
;
1792 if (tracknumfix
[0] != '\0')
1794 id3
.tracknum
= atoi(tracknumfix
);
1795 /* Set a flag to indicate track number has been generated. */
1796 entry
.flag
|= FLAG_TRKNUMGEN
;
1800 /* Unable to generate track number. */
1806 entry
.tag_offset
[tag_year
] = id3
.year
;
1807 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1808 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1809 entry
.tag_offset
[tag_length
] = id3
.length
;
1810 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1811 entry
.tag_offset
[tag_mtime
] = mtime
;
1814 has_albumartist
= id3
.albumartist
!= NULL
1815 && strlen(id3
.albumartist
) > 0;
1816 has_grouping
= id3
.grouping
!= NULL
1817 && strlen(id3
.grouping
) > 0;
1819 ADD_TAG(entry
, tag_filename
, &path
);
1820 ADD_TAG(entry
, tag_title
, &id3
.title
);
1821 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1822 ADD_TAG(entry
, tag_album
, &id3
.album
);
1823 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1824 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1825 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1826 if (has_albumartist
)
1828 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1832 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1836 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1840 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1842 entry
.data_length
= offset
;
1844 /* Write the header */
1845 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1847 /* And tags also... Correct order is critical */
1849 write_item(id3
.title
);
1850 write_item(id3
.artist
);
1851 write_item(id3
.album
);
1852 write_item(id3
.genre_string
);
1853 write_item(id3
.composer
);
1854 write_item(id3
.comment
);
1855 if (has_albumartist
)
1857 write_item(id3
.albumartist
);
1861 write_item(id3
.artist
);
1865 write_item(id3
.grouping
);
1869 write_item(id3
.title
);
1871 total_entry_count
++;
1874 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1876 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1877 int len
= strlen(str
)+1;
1880 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1881 char buf
[TAG_MAXLEN
+32];
1883 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1884 buf
[i
] = tolower(str
[i
]);
1887 crc32
= crc_32(buf
, i
, 0xffffffff);
1891 /* Check if the crc does not exist -> entry does not exist for sure. */
1892 for (i
= 0; i
< tempbufidx
; i
++)
1894 if (crcbuf
[-i
] != crc32
)
1897 if (!strcasecmp(str
, index
[i
].str
))
1899 if (id
< 0 || id
>= lookup_buffer_depth
)
1901 logf("lookup buf overf.: %d", id
);
1905 lookup
[id
] = &index
[i
];
1911 /* Insert to CRC buffer. */
1912 crcbuf
[-tempbufidx
] = crc32
;
1915 /* Insert it to the buffer. */
1916 tempbuf_left
-= len
;
1917 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1920 if (id
>= lookup_buffer_depth
)
1922 logf("lookup buf overf. #2: %d", id
);
1928 lookup
[id
] = &index
[tempbufidx
];
1929 index
[tempbufidx
].idlist
.id
= id
;
1932 index
[tempbufidx
].idlist
.id
= -1;
1934 index
[tempbufidx
].idlist
.next
= NULL
;
1935 index
[tempbufidx
].idx_id
= idx_id
;
1936 index
[tempbufidx
].seek
= -1;
1937 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
1938 memcpy(index
[tempbufidx
].str
, str
, len
);
1945 static int compare(const void *p1
, const void *p2
)
1949 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
1950 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
1952 if (strcmp(e1
->str
, UNTAGGED
) == 0)
1954 if (strcmp(e2
->str
, UNTAGGED
) == 0)
1958 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
1961 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
1964 static int tempbuf_sort(int fd
)
1966 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1967 struct tagfile_entry fe
;
1971 /* Generate reverse lookup entries. */
1972 for (i
= 0; i
< lookup_buffer_depth
; i
++)
1974 struct tempbuf_id_list
*idlist
;
1979 if (lookup
[i
]->idlist
.id
== i
)
1982 idlist
= &lookup
[i
]->idlist
;
1983 while (idlist
->next
!= NULL
)
1984 idlist
= idlist
->next
;
1986 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
1987 if (tempbuf_left
- 4 < 0)
1990 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
1991 if (tempbuf_pos
& 0x03)
1993 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
1995 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
1997 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
1999 idlist
= idlist
->next
;
2001 idlist
->next
= NULL
;
2006 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
2007 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
2009 for (i
= 0; i
< tempbufidx
; i
++)
2011 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
2013 /* Fix the lookup list. */
2014 while (idlist
!= NULL
)
2016 if (idlist
->id
>= 0)
2017 lookup
[idlist
->id
] = &index
[i
];
2018 idlist
= idlist
->next
;
2021 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
2022 length
= strlen(index
[i
].str
) + 1;
2023 fe
.tag_length
= length
;
2024 fe
.idx_id
= index
[i
].idx_id
;
2026 /* Check the chunk alignment. */
2027 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2028 % TAGFILE_ENTRY_CHUNK_LENGTH
)
2030 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
2031 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2032 % TAGFILE_ENTRY_CHUNK_LENGTH
);
2035 #ifdef TAGCACHE_STRICT_ALIGN
2036 /* Make sure the entry is long aligned. */
2037 if (index
[i
].seek
& 0x03)
2039 logf("tempbuf_sort: alignment error!");
2044 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2045 sizeof(struct tagfile_entry
))
2047 logf("tempbuf_sort: write error #1");
2051 if (write(fd
, index
[i
].str
, length
) != length
)
2053 logf("tempbuf_sort: write error #2");
2057 /* Write some padding. */
2058 if (fe
.tag_length
- length
> 0)
2059 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2065 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2067 if (id
< 0 || id
>= lookup_buffer_depth
)
2074 inline static int tempbuf_find_location(int id
)
2076 struct tempbuf_searchidx
*entry
;
2078 entry
= tempbuf_locate(id
);
2085 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2087 struct master_header tcmh
;
2088 struct index_entry idx
;
2091 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2093 int entries_processed
= 0;
2095 char buf
[TAG_MAXLEN
];
2097 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2099 logf("Building numeric indices...");
2100 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2102 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2105 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2107 if (masterfd_pos
== filesize(masterfd
))
2109 logf("we can't append!");
2114 while (entries_processed
< h
->entry_count
)
2116 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2118 /* Read in as many entries as possible. */
2119 for (i
= 0; i
< count
; i
++)
2121 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2124 /* Read in numeric data. */
2125 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2126 sizeof(struct temp_file_entry
))
2128 logf("read fail #1");
2133 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2136 * Read string data from the following tags:
2142 * A crc32 hash is calculated from the read data
2143 * and stored back to the data offset field kept in memory.
2145 #define tmpdb_read_string_tag(tag) \
2146 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2147 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2149 logf("read fail: buffer overflow"); \
2154 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2155 tfe->tag_length[tag]) \
2157 logf("read fail #2"); \
2162 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2163 lseek(tmpfd, datastart, SEEK_SET)
2165 tmpdb_read_string_tag(tag_filename
);
2166 tmpdb_read_string_tag(tag_artist
);
2167 tmpdb_read_string_tag(tag_album
);
2168 tmpdb_read_string_tag(tag_title
);
2170 /* Seek to the end of the string data. */
2171 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2174 /* Backup the master index position. */
2175 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2176 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2178 /* Check if we can resurrect some deleted runtime statistics data. */
2179 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2181 /* Read the index entry. */
2182 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2183 != sizeof(struct index_entry
))
2185 logf("read fail #3");
2191 * Skip unless the entry is marked as being deleted
2192 * or the data has already been resurrected.
2194 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2197 /* Now try to match the entry. */
2199 * To succesfully match a song, the following conditions
2202 * For numeric fields: tag_length
2203 * - Full identical match is required
2205 * If tag_filename matches, no further checking necessary.
2207 * For string hashes: tag_artist, tag_album, tag_title
2208 * - Two of these must match
2210 for (j
= 0; j
< count
; j
++)
2212 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2214 /* Try to match numeric fields first. */
2215 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2218 /* Now it's time to do the hash matching. */
2219 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2221 int match_count
= 0;
2223 /* No filename match, check if we can match two other tags. */
2224 #define tmpdb_match(tag) \
2225 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2228 tmpdb_match(tag_artist
);
2229 tmpdb_match(tag_album
);
2230 tmpdb_match(tag_title
);
2232 if (match_count
< 2)
2234 /* Still no match found, give up. */
2239 /* A match found, now copy & resurrect the statistical data. */
2240 #define tmpdb_copy_tag(tag) \
2241 tfe->tag_offset[tag] = idx.tag_seek[tag]
2243 tmpdb_copy_tag(tag_playcount
);
2244 tmpdb_copy_tag(tag_rating
);
2245 tmpdb_copy_tag(tag_playtime
);
2246 tmpdb_copy_tag(tag_lastplayed
);
2247 tmpdb_copy_tag(tag_commitid
);
2249 /* Avoid processing this entry again. */
2250 idx
.flag
|= FLAG_RESURRECTED
;
2252 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2253 if (ecwrite(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2254 != sizeof(struct index_entry
))
2256 logf("masterfd writeback fail #1");
2261 logf("Entry resurrected");
2266 /* Restore the master index position. */
2267 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2269 /* Commit the data to the index. */
2270 for (i
= 0; i
< count
; i
++)
2272 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2274 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2275 != sizeof(struct index_entry
))
2277 logf("read fail #3");
2282 for (j
= 0; j
< TAG_COUNT
; j
++)
2284 if (!TAGCACHE_IS_NUMERIC(j
))
2287 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2289 idx
.flag
= entrybuf
[i
].flag
;
2291 if (idx
.tag_seek
[tag_commitid
])
2293 /* Data has been resurrected. */
2294 idx
.flag
|= FLAG_DIRTYNUM
;
2296 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2298 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2299 idx
.flag
|= FLAG_DIRTYNUM
;
2302 /* Write back the updated index. */
2303 lseek(masterfd
, loc
, SEEK_SET
);
2304 if (ecwrite(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2305 != sizeof(struct index_entry
))
2313 entries_processed
+= count
;
2314 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2325 * == 0 temporary failure
2328 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2331 struct tagcache_header tch
;
2332 struct master_header tcmh
;
2333 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2335 char buf
[TAG_MAXLEN
+32];
2336 int fd
= -1, masterfd
;
2341 logf("Building index: %d", index_type
);
2343 /* Check the number of entries we need to allocate ram for. */
2344 commit_entry_count
= h
->entry_count
+ 1;
2346 masterfd
= open_master_fd(&tcmh
, false);
2349 commit_entry_count
+= tcmh
.tch
.entry_count
;
2353 remove_files(); /* Just to be sure we are clean. */
2355 /* Open the index file, which contains the tag names. */
2356 fd
= open_tag_fd(&tch
, index_type
, true);
2359 logf("tch.datasize=%ld", tch
.datasize
);
2360 lookup_buffer_depth
= 1 +
2361 /* First part */ commit_entry_count
+
2362 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2366 lookup_buffer_depth
= 1 +
2367 /* First part */ commit_entry_count
+
2368 /* Second part */ 0;
2371 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2372 logf("commit_entry_count=%ld", commit_entry_count
);
2374 /* Allocate buffer for all index entries from both old and new
2377 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2379 /* Allocate lookup buffer. The first portion of commit_entry_count
2380 * contains the new tags in the temporary file and the second
2381 * part for locating entries already in the db.
2384 * +---------+---------------------------+
2385 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2386 * +---------+---------------------------+
2388 * Old tags are inserted to a temporary buffer with position:
2389 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2390 * And new tags with index:
2391 * tempbuf_insert(idx, ...);
2393 * The buffer is sorted and written into tag file:
2394 * tempbuf_sort(...);
2395 * leaving master index locations messed up.
2397 * That is fixed using the lookup buffer for old tags:
2398 * new_seek = tempbuf_find_location(old_seek, ...);
2400 * new_seek = tempbuf_find_location(idx);
2402 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2403 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2404 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2406 /* And calculate the remaining data space used mainly for storing
2407 * tag data (strings). */
2408 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2409 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2411 logf("Buffer way too small!");
2418 * If tag file contains unique tags (sorted index), we will load
2419 * it entirely into memory so we can resort it later for use with
2422 if (TAGCACHE_IS_SORTED(index_type
))
2424 logf("loading tags...");
2425 for (i
= 0; i
< tch
.entry_count
; i
++)
2427 struct tagfile_entry entry
;
2428 int loc
= lseek(fd
, 0, SEEK_CUR
);
2431 if (ecread(fd
, &entry
, 1, tagfile_entry_ec
, tc_stat
.econ
)
2432 != sizeof(struct tagfile_entry
))
2434 logf("read error #7");
2439 if (entry
.tag_length
>= (int)sizeof(buf
))
2441 logf("too long tag #3");
2446 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2448 logf("read error #8");
2453 /* Skip deleted entries. */
2458 * Save the tag and tag id in the memory buffer. Tag id
2459 * is saved so we can later reindex the master lookup
2460 * table when the index gets resorted.
2462 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2463 + commit_entry_count
, entry
.idx_id
,
2464 TAGCACHE_IS_UNIQUE(index_type
));
2475 tempbufidx
= tch
.entry_count
;
2480 * Creating new index file to store the tags. No need to preload
2481 * anything whether the index type is sorted or not.
2483 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2484 fd
= open(buf
, O_WRONLY
| O_CREAT
| O_TRUNC
);
2487 logf("%s open fail", buf
);
2491 tch
.magic
= TAGCACHE_MAGIC
;
2492 tch
.entry_count
= 0;
2495 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2496 != sizeof(struct tagcache_header
))
2498 logf("header write failed");
2504 /* Loading the tag lookup file as "master file". */
2505 logf("Loading index file");
2506 masterfd
= open(TAGCACHE_FILE_MASTER
, O_RDWR
);
2510 logf("Creating new DB");
2511 masterfd
= open(TAGCACHE_FILE_MASTER
, O_WRONLY
| O_CREAT
| O_TRUNC
);
2515 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER
);
2520 /* Write the header (write real values later). */
2521 memset(&tcmh
, 0, sizeof(struct master_header
));
2523 tcmh
.tch
.entry_count
= 0;
2524 tcmh
.tch
.datasize
= 0;
2526 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2528 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2533 * Master file already exists so we need to process the current
2538 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2539 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2541 logf("header error");
2548 * If we reach end of the master file, we need to expand it to
2549 * hold new tags. If the current index is not sorted, we can
2550 * simply append new data to end of the file.
2551 * However, if the index is sorted, we need to update all tag
2552 * pointers in the master file for the current index.
2554 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2556 if (masterfd_pos
== filesize(masterfd
))
2558 logf("appending...");
2564 * Load new unique tags in memory to be sorted later and added
2565 * to the master lookup file.
2567 if (TAGCACHE_IS_SORTED(index_type
))
2569 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2570 /* h is the header of the temporary file containing new tags. */
2571 logf("inserting new tags...");
2572 for (i
= 0; i
< h
->entry_count
; i
++)
2574 struct temp_file_entry entry
;
2576 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2577 sizeof(struct temp_file_entry
))
2579 logf("read fail #3");
2585 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2587 logf("too long entry!");
2592 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2593 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2594 entry
.tag_length
[index_type
])
2596 logf("read fail #4");
2601 if (TAGCACHE_IS_UNIQUE(index_type
))
2602 error
= !tempbuf_insert(buf
, i
, -1, true);
2604 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2608 logf("insert error");
2613 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2614 entry
.tag_length
[index_type
], SEEK_CUR
);
2619 /* Sort the buffer data and write it to the index file. */
2620 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2622 * We need to truncate the index file now. There can be junk left
2623 * at the end of file (however, we _should_ always follow the
2624 * entry_count and don't crash with that).
2626 ftruncate(fd
, lseek(fd
, 0, SEEK_CUR
));
2628 i
= tempbuf_sort(fd
);
2631 logf("sorted %d tags", i
);
2634 * Now update all indexes in the master lookup file.
2636 logf("updating indices...");
2637 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2638 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2641 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2643 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2645 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2646 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2648 logf("read fail #5");
2652 lseek(masterfd
, loc
, SEEK_SET
);
2654 for (j
= 0; j
< idxbuf_pos
; j
++)
2656 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2658 /* We can just ignore deleted entries. */
2659 // idxbuf[j].tag_seek[index_type] = 0;
2663 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2664 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2665 + commit_entry_count
);
2667 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2669 logf("update error: %d/%d/%d",
2670 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2678 /* Write back the updated index. */
2679 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2680 index_entry_ec
, tc_stat
.econ
) !=
2681 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2692 * Walk through the temporary file containing the new tags.
2694 // build_normal_index(h, tmpfd, masterfd, idx);
2695 logf("updating new indices...");
2696 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2697 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2698 lseek(fd
, 0, SEEK_END
);
2699 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2703 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2706 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2710 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2712 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2713 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2715 logf("read fail #6");
2719 lseek(masterfd
, loc
, SEEK_SET
);
2722 /* Read entry headers. */
2723 for (j
= 0; j
< idxbuf_pos
; j
++)
2725 if (!TAGCACHE_IS_SORTED(index_type
))
2727 struct temp_file_entry entry
;
2728 struct tagfile_entry fe
;
2730 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2731 sizeof(struct temp_file_entry
))
2733 logf("read fail #7");
2739 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2741 logf("too long entry!");
2742 logf("length=%d", entry
.tag_length
[index_type
]);
2743 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2748 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2749 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2750 entry
.tag_length
[index_type
])
2752 logf("read fail #8");
2753 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2754 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2759 /* Write to index file. */
2760 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2761 fe
.tag_length
= entry
.tag_length
[index_type
];
2762 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2763 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2764 write(fd
, buf
, fe
.tag_length
);
2768 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2769 entry
.tag_length
[index_type
], SEEK_CUR
);
2773 /* Locate the correct entry from the sorted array. */
2774 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2775 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2777 logf("entry not found (%d)", j
);
2785 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2786 index_entry_ec
, tc_stat
.econ
) !=
2787 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2789 logf("tagcache: write fail #4");
2798 /* Finally write the header. */
2799 tch
.magic
= TAGCACHE_MAGIC
;
2800 tch
.entry_count
= tempbufidx
;
2801 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2802 lseek(fd
, 0, SEEK_SET
);
2803 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2805 if (index_type
!= tag_filename
)
2806 h
->datasize
+= tch
.datasize
;
2807 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2819 static bool commit(void)
2821 struct tagcache_header tch
;
2822 struct master_header tcmh
;
2826 #ifdef HAVE_DIRCACHE
2827 bool dircache_buffer_stolen
= false;
2829 bool local_allocation
= false;
2831 logf("committing tagcache");
2836 tmpfd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
2839 logf("nothing to commit");
2844 /* Load the header. */
2845 len
= sizeof(struct tagcache_header
);
2846 rc
= read(tmpfd
, &tch
, len
);
2848 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2850 logf("incorrect header");
2852 remove(TAGCACHE_FILE_TEMP
);
2856 if (tch
.entry_count
== 0)
2858 logf("nothing to commit");
2860 remove(TAGCACHE_FILE_TEMP
);
2864 #ifdef HAVE_EEPROM_SETTINGS
2865 remove(TAGCACHE_STATEFILE
);
2868 /* At first be sure to unload the ramcache! */
2869 #ifdef HAVE_TC_RAMCACHE
2870 tc_stat
.ramcache
= false;
2875 /* Try to steal every buffer we can :) */
2876 if (tempbuf_size
== 0)
2877 local_allocation
= true;
2879 #ifdef HAVE_DIRCACHE
2880 if (tempbuf_size
== 0)
2882 /* Try to steal the dircache buffer. */
2883 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2884 tempbuf_size
&= ~0x03;
2886 if (tempbuf_size
> 0)
2888 dircache_buffer_stolen
= true;
2893 #ifdef HAVE_TC_RAMCACHE
2894 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2896 tempbuf
= (char *)(hdr
+ 1);
2897 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2898 tempbuf_size
&= ~0x03;
2902 /* And finally fail if there are no buffers available. */
2903 if (tempbuf_size
== 0)
2905 logf("delaying commit until next boot");
2906 tc_stat
.commit_delayed
= true;
2912 logf("commit %ld entries...", tch
.entry_count
);
2914 /* Mark DB dirty so it will stay disabled if commit fails. */
2915 current_tcmh
.dirty
= true;
2916 update_master_header();
2918 /* Now create the index files. */
2919 tc_stat
.commit_step
= 0;
2921 tc_stat
.commit_delayed
= false;
2923 for (i
= 0; i
< TAG_COUNT
; i
++)
2927 if (TAGCACHE_IS_NUMERIC(i
))
2930 tc_stat
.commit_step
++;
2931 ret
= build_index(i
, &tch
, tmpfd
);
2935 logf("tagcache failed init");
2937 tc_stat
.commit_delayed
= true;
2939 tc_stat
.commit_step
= 0;
2945 if (!build_numeric_indices(&tch
, tmpfd
))
2947 logf("Failure to commit numeric indices");
2949 tc_stat
.commit_step
= 0;
2955 remove(TAGCACHE_FILE_TEMP
);
2957 tc_stat
.commit_step
= 0;
2959 /* Update the master index headers. */
2960 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2966 tcmh
.tch
.entry_count
+= tch
.entry_count
;
2967 tcmh
.tch
.datasize
= sizeof(struct master_header
)
2968 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
2973 lseek(masterfd
, 0, SEEK_SET
);
2974 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2977 logf("tagcache committed");
2978 tc_stat
.ready
= check_all_headers();
2979 tc_stat
.readyvalid
= true;
2981 if (local_allocation
)
2987 #ifdef HAVE_DIRCACHE
2988 /* Rebuild the dircache, if we stole the buffer. */
2989 if (dircache_buffer_stolen
)
2993 #ifdef HAVE_TC_RAMCACHE
2994 /* Reload tagcache. */
2995 if (tc_stat
.ramcache_allocated
> 0)
2996 tagcache_start_scan();
3004 static void allocate_tempbuf(void)
3006 /* Yeah, malloc would be really nice now :) */
3008 tempbuf_size
= 32*1024*1024;
3009 tempbuf
= malloc(tempbuf_size
);
3011 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
3012 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
3013 audiobuf
+= tempbuf_size
;
3017 static void free_tempbuf(void)
3019 if (tempbuf_size
== 0)
3025 audiobuf
-= tempbuf_size
;
3033 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
3035 struct index_entry idx
;
3040 if (!TAGCACHE_IS_NUMERIC(tag
))
3043 if (!get_index(masterfd
, idx_id
, &idx
, false))
3046 idx
.tag_seek
[tag
] = data
;
3047 idx
.flag
|= FLAG_DIRTYNUM
;
3049 return write_index(masterfd
, idx_id
, &idx
);
3053 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3056 struct master_header myhdr
;
3058 if (tcs
->masterfd
< 0)
3060 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3064 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3068 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
3070 static bool command_queue_is_full(void)
3074 next
= command_queue_widx
+ 1;
3075 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3078 return (next
== command_queue_ridx
);
3081 static void command_queue_sync_callback(void *data
)
3084 struct master_header myhdr
;
3087 mutex_lock(&command_queue_mutex
);
3089 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3092 while (command_queue_ridx
!= command_queue_widx
)
3094 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3096 switch (ce
->command
)
3098 case CMD_UPDATE_MASTER_HEADER
:
3101 update_master_header();
3103 /* Re-open the masterfd. */
3104 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3109 case CMD_UPDATE_NUMERIC
:
3111 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3116 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3117 command_queue_ridx
= 0;
3122 tc_stat
.queue_length
= 0;
3123 mutex_unlock(&command_queue_mutex
);
3126 static void run_command_queue(bool force
)
3128 if (COMMAND_QUEUE_IS_EMPTY
)
3131 if (force
|| command_queue_is_full())
3132 command_queue_sync_callback(NULL
);
3134 register_storage_idle_func(command_queue_sync_callback
);
3137 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3143 mutex_lock(&command_queue_mutex
);
3144 next
= command_queue_widx
+ 1;
3145 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3148 /* Make sure queue is not full. */
3149 if (next
!= command_queue_ridx
)
3151 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3154 ce
->idx_id
= idx_id
;
3158 command_queue_widx
= next
;
3160 tc_stat
.queue_length
++;
3162 mutex_unlock(&command_queue_mutex
);
3166 /* Queue is full, try again later... */
3167 mutex_unlock(&command_queue_mutex
);
3172 long tagcache_increase_serial(void)
3182 old
= current_tcmh
.serial
++;
3183 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3188 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3190 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3192 #endif /* !__PCTOOL__ */
3194 long tagcache_get_serial(void)
3196 return current_tcmh
.serial
;
3199 long tagcache_get_commitid(void)
3201 return current_tcmh
.commitid
;
3204 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3209 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3210 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3212 if (*datastr
== '\0')
3215 if (*datastr
== '"' || *datastr
== '\\')
3218 buf
[i
] = *(datastr
++);
3221 strcpy(&buf
[i
], "\" ");
3223 write(fd
, buf
, i
+ 2);
3230 static bool read_tag(char *dest
, long size
,
3231 const char *src
, const char *tagstr
)
3234 char current_tag
[32];
3236 while (*src
!= '\0')
3238 /* Skip all whitespace */
3246 /* Read in tag name */
3247 while (*src
!= '=' && *src
!= ' ')
3249 current_tag
[pos
] = *src
;
3253 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3256 current_tag
[pos
] = '\0';
3258 /* Read in tag data */
3260 /* Find the start. */
3261 while (*src
!= '"' && *src
!= '\0')
3264 if (*src
== '\0' || *(++src
) == '\0')
3267 /* Read the data. */
3268 for (pos
= 0; pos
< size
; pos
++)
3275 dest
[pos
] = *(src
+1);
3295 if (!strcasecmp(tagstr
, current_tag
))
3302 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3304 struct index_entry idx
;
3305 char tag_data
[TAG_MAXLEN
+32];
3307 long masterfd
= (long)parameters
;
3308 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3316 logf("%d/%s", line_n
, buf
);
3317 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3319 logf("filename missing");
3324 idx_id
= find_index(tag_data
);
3327 logf("entry not found");
3331 if (!get_index(masterfd
, idx_id
, &idx
, false))
3333 logf("failed to retrieve index entry");
3337 /* Stop if tag has already been modified. */
3338 if (idx
.flag
& FLAG_DIRTYNUM
)
3341 logf("import: %s", tag_data
);
3343 idx
.flag
|= FLAG_DIRTYNUM
;
3344 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3348 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3349 tagcache_tag_to_str(import_tags
[i
])))
3354 data
= atoi(tag_data
);
3358 idx
.tag_seek
[import_tags
[i
]] = data
;
3360 if (import_tags
[i
] == tag_lastplayed
&& data
>= current_tcmh
.serial
)
3361 current_tcmh
.serial
= data
+ 1;
3362 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3363 current_tcmh
.commitid
= data
+ 1;
3366 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3369 bool tagcache_import_changelog(void)
3371 struct master_header myhdr
;
3372 struct tagcache_header tch
;
3383 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_RDONLY
);
3386 logf("failure to open changelog");
3390 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3398 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3400 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3401 parse_changelog_line
);
3406 if (filenametag_fd
>= 0)
3408 close(filenametag_fd
);
3409 filenametag_fd
= -1;
3414 update_master_header();
3419 #endif /* !__PCTOOL__ */
3421 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3423 struct master_header myhdr
;
3424 struct index_entry idx
;
3425 char buf
[TAG_MAXLEN
+32];
3433 if (!tagcache_search(tcs
, tag_filename
))
3436 /* Initialize the changelog */
3437 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_WRONLY
| O_CREAT
| O_TRUNC
);
3440 logf("failure to open changelog");
3444 if (tcs
->masterfd
< 0)
3446 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3451 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3452 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3455 write(clfd
, "## Changelog version 1\n", 23);
3457 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3459 if (ecread(tcs
->masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
3460 != sizeof(struct index_entry
))
3462 logf("read error #9");
3463 tagcache_search_finish(tcs
);
3468 /* Skip until the entry found has been modified. */
3469 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3472 /* Skip deleted entries too. */
3473 if (idx
.flag
& FLAG_DELETED
)
3476 /* Now retrieve all tags. */
3477 for (j
= 0; j
< TAG_COUNT
; j
++)
3479 if (TAGCACHE_IS_NUMERIC(j
))
3481 snprintf(temp
, sizeof temp
, "%d", idx
.tag_seek
[j
]);
3482 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3487 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3488 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3491 write(clfd
, "\n", 1);
3497 tagcache_search_finish(tcs
);
3502 static bool delete_entry(long idx_id
)
3507 struct index_entry idx
, myidx
;
3508 struct master_header myhdr
;
3509 char buf
[TAG_MAXLEN
+32];
3510 int in_use
[TAG_COUNT
];
3512 logf("delete_entry(): %ld", idx_id
);
3514 #ifdef HAVE_TC_RAMCACHE
3515 /* At first mark the entry removed from ram cache. */
3516 if (tc_stat
.ramcache
)
3517 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3520 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3523 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3524 if (ecread(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3525 != sizeof(struct index_entry
))
3527 logf("delete_entry(): read error");
3531 if (myidx
.flag
& FLAG_DELETED
)
3533 logf("delete_entry(): already deleted!");
3537 myidx
.flag
|= FLAG_DELETED
;
3538 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3539 if (ecwrite(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3540 != sizeof(struct index_entry
))
3542 logf("delete_entry(): write_error #1");
3546 /* Now check which tags are no longer in use (if any) */
3547 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3550 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3551 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3553 struct index_entry
*idxp
;
3555 #ifdef HAVE_TC_RAMCACHE
3556 /* Use RAM DB if available for greater speed */
3557 if (tc_stat
.ramcache
)
3558 idxp
= &hdr
->indices
[i
];
3562 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
3563 != sizeof(struct index_entry
))
3565 logf("delete_entry(): read error #2");
3571 if (idxp
->flag
& FLAG_DELETED
)
3574 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3576 if (TAGCACHE_IS_NUMERIC(tag
))
3579 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3584 /* Now delete all tags no longer in use. */
3585 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3587 struct tagcache_header tch
;
3588 int oldseek
= myidx
.tag_seek
[tag
];
3590 if (TAGCACHE_IS_NUMERIC(tag
))
3594 * Replace tag seek with a hash value of the field string data.
3595 * That way runtime statistics of moved or altered files can be
3598 #ifdef HAVE_TC_RAMCACHE
3599 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3601 struct tagfile_entry
*tfe
;
3602 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3604 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3605 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3606 myidx
.tag_seek
[tag
] = *seek
;
3611 struct tagfile_entry tfe
;
3613 /* Open the index file, which contains the tag names. */
3614 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3617 /* Skip the header block */
3618 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3619 if (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
3620 != sizeof(struct tagfile_entry
))
3622 logf("delete_entry(): read error #3");
3626 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3628 logf("delete_entry(): read error #4");
3632 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3637 logf("in use: %d/%d", tag
, in_use
[tag
]);
3646 #ifdef HAVE_TC_RAMCACHE
3647 /* Delete from ram. */
3648 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3650 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3651 tagentry
->tag_data
[0] = '\0';
3655 /* Open the index file, which contains the tag names. */
3658 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3662 /* Skip the header block */
3663 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3665 /* Debug, print 10 first characters of the tag
3668 logf("TAG:%s", buf);
3669 lseek(fd, -10, SEEK_CUR);
3672 /* Write first data byte in tag as \0 */
3675 /* Now tag data has been removed */
3680 /* Write index entry back into master index. */
3681 lseek(masterfd
, sizeof(struct master_header
) +
3682 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3683 if (ecwrite(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3684 != sizeof(struct index_entry
))
3686 logf("delete_entry(): write_error #2");
3705 * Returns true if there is an event waiting in the queue
3706 * that requires the current operation to be aborted.
3708 static bool check_event_queue(void)
3710 struct queue_event ev
;
3712 queue_wait_w_tmo(&tagcache_queue
, &ev
, 0);
3717 case SYS_USB_CONNECTED
:
3718 /* Put the event back into the queue. */
3719 queue_post(&tagcache_queue
, ev
.id
, ev
.data
);
3727 #ifdef HAVE_TC_RAMCACHE
3728 static bool allocate_tagcache(void)
3730 struct master_header tcmh
;
3733 /* Load the header. */
3734 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3743 * Now calculate the required cache size plus
3744 * some extra space for alignment fixes.
3746 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3747 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3748 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3749 memset(hdr
, 0, sizeof(struct ramcache_header
));
3750 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3751 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3752 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3757 # ifdef HAVE_EEPROM_SETTINGS
3758 static bool tagcache_dumpload(void)
3760 struct statefile_header shdr
;
3765 fd
= open(TAGCACHE_STATEFILE
, O_RDONLY
);
3768 logf("no tagcache statedump");
3772 /* Check the statefile memory placement */
3773 hdr
= buffer_alloc(0);
3774 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3775 if (rc
!= sizeof(struct statefile_header
)
3776 /* || (long)hdr != (long)shdr.hdr */)
3778 logf("incorrect statefile");
3784 offpos
= (long)hdr
- (long)shdr
.hdr
;
3786 /* Lets allocate real memory and load it */
3787 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3788 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3791 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3793 logf("read failure!");
3798 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3800 /* Now fix the pointers */
3801 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3802 for (i
= 0; i
< TAG_COUNT
; i
++)
3803 hdr
->tags
[i
] += offpos
;
3808 static bool tagcache_dumpsave(void)
3810 struct statefile_header shdr
;
3813 if (!tc_stat
.ramcache
)
3816 fd
= open(TAGCACHE_STATEFILE
, O_WRONLY
| O_CREAT
| O_TRUNC
);
3819 logf("failed to create a statedump");
3823 /* Create the header */
3825 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3826 write(fd
, &shdr
, sizeof(struct statefile_header
));
3828 /* And dump the data too */
3829 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3836 static bool load_tagcache(void)
3838 struct tagcache_header
*tch
;
3839 long bytesleft
= tc_stat
.ramcache_allocated
;
3840 struct index_entry
*idx
;
3845 # ifdef HAVE_DIRCACHE
3846 while (dircache_is_initializing())
3849 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3852 logf("loading tagcache to ram...");
3854 fd
= open(TAGCACHE_FILE_MASTER
, O_RDONLY
);
3857 logf("tagcache open failed");
3861 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3862 != sizeof(struct master_header
)
3863 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3865 logf("incorrect header");
3871 /* Load the master index table. */
3872 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3874 rc
= ecread(fd
, idx
, 1, index_entry_ec
, tc_stat
.econ
);
3875 if (rc
!= sizeof(struct index_entry
))
3877 logf("read error #10");
3882 bytesleft
-= sizeof(struct index_entry
);
3883 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3885 logf("too big tagcache.");
3895 /* Load the tags. */
3897 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3899 struct tagfile_entry
*fe
;
3900 char buf
[TAG_MAXLEN
+32];
3902 if (TAGCACHE_IS_NUMERIC(tag
))
3905 //p = ((void *)p+1);
3906 p
= (char *)((long)p
& ~0x03) + 0x04;
3909 /* Check the header. */
3910 tch
= (struct tagcache_header
*)p
;
3911 p
+= sizeof(struct tagcache_header
);
3913 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3916 for (hdr
->entry_count
[tag
] = 0;
3917 hdr
->entry_count
[tag
] < tch
->entry_count
;
3918 hdr
->entry_count
[tag
]++)
3922 if (do_timed_yield())
3924 /* Abort if we got a critical event in queue */
3925 if (check_event_queue())
3929 fe
= (struct tagfile_entry
*)p
;
3930 pos
= lseek(fd
, 0, SEEK_CUR
);
3931 rc
= ecread(fd
, fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
3932 if (rc
!= sizeof(struct tagfile_entry
))
3934 /* End of lookup table. */
3935 logf("read error #11");
3940 /* We have a special handling for the filename tags. */
3941 if (tag
== tag_filename
)
3943 # ifdef HAVE_DIRCACHE
3944 const struct dirent
*dc
;
3947 // FIXME: This is wrong!
3948 // idx = &hdr->indices[hdr->entry_count[i]];
3949 idx
= &hdr
->indices
[fe
->idx_id
];
3951 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
3955 logf("TAG:%s", buf
);
3956 logf("too long filename");
3961 rc
= read(fd
, buf
, fe
->tag_length
);
3962 if (rc
!= fe
->tag_length
)
3964 logf("read error #12");
3969 /* Check if the entry has already been removed */
3970 if (idx
->flag
& FLAG_DELETED
)
3973 /* This flag must not be used yet. */
3974 if (idx
->flag
& FLAG_DIRCACHE
)
3976 logf("internal error!");
3981 if (idx
->tag_seek
[tag
] != pos
)
3983 logf("corrupt data structures!");
3988 # ifdef HAVE_DIRCACHE
3989 if (dircache_is_enabled())
3991 dc
= dircache_get_entry_ptr(buf
);
3994 logf("Entry no longer valid.");
3996 if (global_settings
.tagcache_autoupdate
)
3997 delete_entry(fe
->idx_id
);
4001 idx
->flag
|= FLAG_DIRCACHE
;
4002 idx
->tag_seek
[tag_filename
] = (long)dc
;
4007 /* This will be very slow unless dircache is enabled
4008 or target is flash based, but do it anyway for
4010 /* Check if entry has been removed. */
4011 if (global_settings
.tagcache_autoupdate
)
4013 if (!file_exists(buf
))
4015 logf("Entry no longer valid.");
4017 delete_entry(fe
->idx_id
);
4026 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
4029 logf("too big tagcache #2");
4030 logf("tl: %d", fe
->tag_length
);
4031 logf("bl: %ld", bytesleft
);
4037 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
4040 if (rc
!= fe
->tag_length
)
4042 logf("read error #13");
4043 logf("rc=0x%04x", rc
); // 0x431
4044 logf("len=0x%04x", fe
->tag_length
); // 0x4000
4045 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
4046 logf("tag=0x%02x", tag
); // 0x00
4054 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4055 logf("tagcache loaded into ram!");
4059 #endif /* HAVE_TC_RAMCACHE */
4061 static bool check_deleted_files(void)
4064 char buf
[TAG_MAXLEN
+32];
4065 struct tagfile_entry tfe
;
4067 logf("reverse scan...");
4068 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4069 fd
= open(buf
, O_RDONLY
);
4073 logf("%s open fail", buf
);
4077 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4078 while (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
4079 == sizeof(struct tagfile_entry
)
4081 && !check_event_queue()
4085 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4087 logf("too long tag");
4092 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4094 logf("read error #14");
4099 /* Check if the file has already deleted from the db. */
4103 /* Now check if the file exists. */
4104 if (!file_exists(buf
))
4106 logf("Entry no longer valid.");
4107 logf("-> %s / %d", buf
, tfe
.tag_length
);
4108 delete_entry(tfe
.idx_id
);
4120 /* Note that this function must not be inlined, otherwise the whole point
4121 * of having the code in a separate function is lost.
4123 static void __attribute__ ((noinline
)) check_ignore(const char *dirname
,
4124 int *ignore
, int *unignore
)
4126 char newpath
[MAX_PATH
];
4128 /* check for a database.ignore file */
4129 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4130 *ignore
= file_exists(newpath
);
4131 /* check for a database.unignore file */
4132 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4133 *unignore
= file_exists(newpath
);
4137 static bool check_dir(const char *dirname
, int add_files
)
4141 int success
= false;
4142 int ignore
, unignore
;
4144 dir
= opendir(dirname
);
4147 logf("tagcache: opendir() failed");
4151 /* check for a database.ignore and database.unignore */
4152 check_ignore(dirname
, &ignore
, &unignore
);
4154 /* don't do anything if both ignore and unignore are there */
4155 if (ignore
!= unignore
)
4156 add_files
= unignore
;
4158 /* Recursively scan the dir. */
4162 while (!check_event_queue())
4165 struct dirent
*entry
;
4167 entry
= readdir(dir
);
4175 if (!strcmp((char *)entry
->d_name
, ".") ||
4176 !strcmp((char *)entry
->d_name
, ".."))
4181 len
= strlen(curpath
);
4182 snprintf(&curpath
[len
], sizeof(curpath
) - len
, "/%s",
4185 processed_dir_count
++;
4186 if (entry
->attribute
& ATTR_DIRECTORY
)
4187 check_dir(curpath
, add_files
);
4190 tc_stat
.curentry
= curpath
;
4192 /* Add a new entry to the temporary db file. */
4193 add_tagcache(curpath
, (entry
->wrtdate
<< 16) | entry
->wrttime
4194 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4195 , dir
->internal_entry
4199 /* Wait until current path for debug screen is read and unset. */
4200 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4203 tc_stat
.curentry
= NULL
;
4206 curpath
[len
] = '\0';
4214 void tagcache_screensync_event(void)
4216 tc_stat
.curentry
= NULL
;
4219 void tagcache_screensync_enable(bool state
)
4221 tc_stat
.syncscreen
= state
;
4224 void tagcache_build(const char *path
)
4226 struct tagcache_header header
;
4231 total_entry_count
= 0;
4232 processed_dir_count
= 0;
4234 #ifdef HAVE_DIRCACHE
4235 while (dircache_is_initializing())
4239 logf("updating tagcache");
4241 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
4244 logf("skipping, cache already waiting for commit");
4249 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDWR
| O_CREAT
| O_TRUNC
);
4252 logf("master file open failed: %s", TAGCACHE_FILE_TEMP
);
4256 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4260 logf("Scanning files...");
4261 /* Scan for new files. */
4262 memset(&header
, 0, sizeof(struct tagcache_header
));
4263 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4265 if (strcmp("/", path
) != 0)
4266 strcpy(curpath
, path
);
4267 ret
= check_dir(path
, true);
4269 /* Write the header. */
4270 header
.magic
= TAGCACHE_MAGIC
;
4271 header
.datasize
= data_size
;
4272 header
.entry_count
= total_entry_count
;
4273 lseek(cachefd
, 0, SEEK_SET
);
4274 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4277 if (filenametag_fd
>= 0)
4279 close(filenametag_fd
);
4280 filenametag_fd
= -1;
4290 /* Commit changes to the database. */
4296 remove(TAGCACHE_FILE_TEMP
);
4297 logf("tagcache built!");
4303 #ifdef HAVE_TC_RAMCACHE
4306 /* Import runtime statistics if we just initialized the db. */
4307 if (hdr
->h
.serial
== 0)
4308 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4315 #ifdef HAVE_TC_RAMCACHE
4316 static void load_ramcache(void)
4323 /* At first we should load the cache (if exists). */
4324 tc_stat
.ramcache
= load_tagcache();
4326 if (!tc_stat
.ramcache
)
4328 /* If loading failed, it must indicate some problem with the db
4329 * so disable it entirely to prevent further issues. */
4330 tc_stat
.ready
= false;
4337 void tagcache_unload_ramcache(void)
4339 tc_stat
.ramcache
= false;
4340 /* Just to make sure there is no statefile present. */
4341 // remove(TAGCACHE_STATEFILE);
4346 static void tagcache_thread(void)
4348 struct queue_event ev
;
4349 bool check_done
= false;
4351 /* If the previous cache build/update was interrupted, commit
4352 * the changes first in foreground. */
4358 #ifdef HAVE_TC_RAMCACHE
4359 # ifdef HAVE_EEPROM_SETTINGS
4360 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
)
4361 check_done
= tagcache_dumpload();
4363 remove(TAGCACHE_STATEFILE
);
4366 /* Allocate space for the tagcache if found on disk. */
4367 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4368 allocate_tagcache();
4372 tc_stat
.initialized
= true;
4374 /* Don't delay bootup with the header check but do it on background. */
4376 tc_stat
.ready
= check_all_headers();
4377 tc_stat
.readyvalid
= true;
4381 run_command_queue(false);
4383 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4387 case Q_IMPORT_CHANGELOG
:
4388 tagcache_import_changelog();
4393 remove(TAGCACHE_FILE_TEMP
);
4394 tagcache_build("/");
4398 tagcache_build("/");
4399 #ifdef HAVE_TC_RAMCACHE
4402 check_deleted_files();
4408 if (check_done
|| !tc_stat
.ready
)
4411 #ifdef HAVE_TC_RAMCACHE
4412 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4415 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4416 tagcache_build("/");
4420 if (global_settings
.tagcache_autoupdate
)
4422 tagcache_build("/");
4424 /* This will be very slow unless dircache is enabled
4425 or target is flash based, but do it anyway for
4427 check_deleted_files();
4430 logf("tagcache check done");
4442 case SYS_USB_CONNECTED
:
4443 logf("USB: TagCache");
4444 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4445 usb_wait_for_disconnect(&tagcache_queue
);
4452 bool tagcache_prepare_shutdown(void)
4454 if (tagcache_get_commit_step() > 0)
4457 tagcache_stop_scan();
4458 while (read_lock
|| write_lock
)
4464 void tagcache_shutdown(void)
4466 /* Flush the command queue. */
4467 run_command_queue(true);
4469 #ifdef HAVE_EEPROM_SETTINGS
4470 if (tc_stat
.ramcache
)
4471 tagcache_dumpsave();
4475 static int get_progress(void)
4477 int total_count
= -1;
4479 #ifdef HAVE_DIRCACHE
4480 if (dircache_is_enabled())
4482 total_count
= dircache_get_entry_count();
4486 #ifdef HAVE_TC_RAMCACHE
4488 if (hdr
&& tc_stat
.ramcache
)
4489 total_count
= hdr
->h
.tch
.entry_count
;
4493 if (total_count
< 0)
4496 return processed_dir_count
* 100 / total_count
;
4499 struct tagcache_stat
* tagcache_get_stat(void)
4501 tc_stat
.progress
= get_progress();
4502 tc_stat
.processed_entries
= processed_dir_count
;
4507 void tagcache_start_scan(void)
4509 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4512 bool tagcache_update(void)
4517 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4521 bool tagcache_rebuild()
4523 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4527 void tagcache_stop_scan(void)
4529 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4532 #ifdef HAVE_TC_RAMCACHE
4533 bool tagcache_is_ramcache(void)
4535 return tc_stat
.ramcache
;
4539 #endif /* !__PCTOOL__ */
4542 void tagcache_init(void)
4544 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4545 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4546 filenametag_fd
= -1;
4547 write_lock
= read_lock
= 0;
4550 mutex_init(&command_queue_mutex
);
4551 queue_init(&tagcache_queue
, true);
4552 create_thread(tagcache_thread
, tagcache_stack
,
4553 sizeof(tagcache_stack
), 0, tagcache_thread_name
4554 IF_PRIO(, PRIORITY_BACKGROUND
)
4557 tc_stat
.initialized
= true;
4561 tc_stat
.ready
= check_all_headers();
4566 void tagcache_reverse_scan(void)
4568 logf("Checking for deleted files");
4569 check_deleted_files();
4573 bool tagcache_is_initialized(void)
4575 return tc_stat
.initialized
;
4577 bool tagcache_is_usable(void)
4579 return tc_stat
.initialized
&& tc_stat
.ready
;
4581 int tagcache_get_commit_step(void)
4583 return tc_stat
.commit_step
;
4585 int tagcache_get_max_commit_step(void)
4587 return (int)(SORTED_TAGS_COUNT
)+1;