1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
25 * ----------x---------x------------------x-----
27 * +---------------x-------+ | TagCache | Libraries
28 * | Modification routines | | Core |
29 * +-x---------x-----------+ | |
31 * | +------x-------------x-+ +-------------x-----+ |
32 * | | x==x Filters & clauses | |
33 * | | Search routines | +-------------------+ |
34 * | | x============================x DirCache
35 * | +-x--------------------+ | (optional)
37 * | | +-------------------------------+ +---------+ |
38 * | | | DB Commit (sort,unique,index) | | | |
39 * | | +-x--------------------------x--+ | Control | |
40 * | | | (R/W) | (R) | Thread | |
41 * | | | +----------------------+ | | | |
42 * | | | | TagCache DB Builder | | +---------+ |
43 * | | | +-x-------------x------+ | |
44 * | | | | (R) | (W) | |
45 * | | | | +--x--------x---------+ |
46 * | | | | | Temporary Commit DB | |
47 * | | | | +---------------------+ |
48 * +-x----x-------x--+ |
49 * | TagCache RAM DB x==\(W) +-----------------+ |
50 * +-----------------+ \===x | |
51 * | | | | (R) | Ram DB Loader x============x DirCache
52 * +-x----x---x---x---+ /==x | | (optional)
53 * | Tagcache Disk DB x==/ +-----------------+ |
54 * +------------------+ |
58 /*#define LOGF_ENABLE*/
64 #include "ata_idle_notify.h"
69 #include "string-extra.h"
82 #include "eeprom_settings.h"
86 #define yield() do { } while(0)
87 #define sim_sleep(timeout) do { } while(0)
88 #define do_timed_yield() do { } while(0)
92 /* Tag Cache thread. */
93 static struct event_queue tagcache_queue
;
94 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
95 static const char tagcache_thread_name
[] = "tagcache";
98 /* Previous path when scanning directory tree recursively. */
99 static char curpath
[TAG_MAXLEN
+32];
101 /* Used when removing duplicates. */
102 static char *tempbuf
; /* Allocated when needed. */
103 static long tempbufidx
; /* Current location in buffer. */
104 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
105 static long tempbuf_left
; /* Buffer space left. */
106 static long tempbuf_pos
;
108 #define SORTED_TAGS_COUNT 8
109 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
110 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
111 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
112 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
113 /* Tags we want to get sorted (loaded to the tempbuf). */
114 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
115 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
116 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
118 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
119 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
120 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
121 (1LU << tag_albumartist) | (1LU << tag_grouping))
123 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
124 static const char *tags_str
[] = { "artist", "album", "genre", "title",
125 "filename", "composer", "comment", "albumartist", "grouping", "year",
126 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
127 "playtime", "lastplayed", "commitid", "mtime" };
129 /* Status information of the tagcache. */
130 static struct tagcache_stat tc_stat
;
132 /* Queue commands. */
133 enum tagcache_queue
{
140 /* Internal tagcache command queue. */
141 CMD_UPDATE_MASTER_HEADER
,
145 struct tagcache_command_entry
{
153 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
154 static volatile int command_queue_widx
= 0;
155 static volatile int command_queue_ridx
= 0;
156 static struct mutex command_queue_mutex
;
159 /* Tag database structures. */
161 /* Variable-length tag entry in tag files. */
162 struct tagfile_entry
{
163 int32_t tag_length
; /* Length of the data in bytes including '\0' */
164 int32_t idx_id
; /* Corresponding entry location in index file of not unique tags */
165 char tag_data
[0]; /* Begin of the tag data */
168 /* Fixed-size tag entry in master db index. */
170 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
171 int32_t flag
; /* Status flags */
174 /* Header is the same in every file. */
175 struct tagcache_header
{
176 int32_t magic
; /* Header version number */
177 int32_t datasize
; /* Data size in bytes */
178 int32_t entry_count
; /* Number of entries in this file */
181 struct master_header
{
182 struct tagcache_header tch
;
183 int32_t serial
; /* Increasing counting number */
184 int32_t commitid
; /* Number of commits so far */
188 /* For the endianess correction */
189 static const char *tagfile_entry_ec
= "ll";
191 Note: This should be (1 + TAG_COUNT) amount of l's.
193 static const char *index_entry_ec
= "lllllllllllllllllllll";
195 static const char *tagcache_header_ec
= "lll";
196 static const char *master_header_ec
= "llllll";
198 static struct master_header current_tcmh
;
200 #ifdef HAVE_TC_RAMCACHE
201 /* Header is created when loading database to ram. */
202 struct ramcache_header
{
203 struct master_header h
; /* Header from the master index */
204 struct index_entry
*indices
; /* Master index file content */
205 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
206 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
209 # ifdef HAVE_EEPROM_SETTINGS
210 struct statefile_header
{
211 struct ramcache_header
*hdr
;
212 struct tagcache_stat tc_stat
;
216 /* Pointer to allocated ramcache_header */
217 static struct ramcache_header
*hdr
;
221 * Full tag entries stored in a temporary file waiting
222 * for commit to the cache. */
223 struct temp_file_entry
{
224 long tag_offset
[TAG_COUNT
];
225 short tag_length
[TAG_COUNT
];
231 struct tempbuf_id_list
{
233 struct tempbuf_id_list
*next
;
236 struct tempbuf_searchidx
{
240 struct tempbuf_id_list idlist
;
243 /* Lookup buffer for fixing messed up index while after sorting. */
244 static long commit_entry_count
;
245 static long lookup_buffer_depth
;
246 static struct tempbuf_searchidx
**lookup
;
248 /* Used when building the temporary file. */
249 static int cachefd
= -1, filenametag_fd
;
250 static int total_entry_count
= 0;
251 static int data_size
= 0;
252 static int processed_dir_count
;
254 /* Thread safe locking */
255 static volatile int write_lock
;
256 static volatile int read_lock
;
258 static bool delete_entry(long idx_id
);
260 const char* tagcache_tag_to_str(int tag
)
262 return tags_str
[tag
];
265 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
266 static ssize_t
ecread_tagfile_entry(int fd
, struct tagfile_entry
*buf
)
268 return ecread(fd
, buf
, 1, tagfile_entry_ec
, tc_stat
.econ
);
271 static ssize_t
ecread_index_entry(int fd
, struct index_entry
*buf
)
273 return ecread(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
276 static ssize_t
ecwrite_index_entry(int fd
, struct index_entry
*buf
)
278 return ecwrite(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
283 * Returns true if specified flag is still present, i.e., dircache
284 * has not been reloaded.
286 static bool is_dircache_intact(void)
288 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
292 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
295 char buf
[MAX_PATH
], path
[MAX_PATH
];
299 if (TAGCACHE_IS_NUMERIC(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
302 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
303 file
= get_user_file_path(buf
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
305 fd
= open(file
, write
? O_RDWR
: O_RDONLY
);
308 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
309 tc_stat
.ready
= false;
313 /* Check the header. */
314 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
315 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
317 logf("header error");
318 tc_stat
.ready
= false;
326 static int open_master_fd(struct master_header
*hdr
, bool write
)
332 fd
= open(get_user_file_path(TAGCACHE_FILE_MASTER
,
335 write
? O_RDWR
: O_RDONLY
);
338 logf("master file open failed for R/W");
339 tc_stat
.ready
= false;
343 tc_stat
.econ
= false;
345 /* Check the header. */
346 rc
= read(fd
, hdr
, sizeof(struct master_header
));
347 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
353 /* Trying to read again, this time with endianess correction enabled. */
354 lseek(fd
, 0, SEEK_SET
);
356 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
357 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
359 logf("header error");
360 tc_stat
.ready
= false;
371 static bool do_timed_yield(void)
373 /* Sorting can lock up for quite a while, so yield occasionally */
374 static long wakeup_tick
= 0;
375 if (TIME_AFTER(current_tick
, wakeup_tick
))
377 wakeup_tick
= current_tick
+ (HZ
/4);
385 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
386 static long find_entry_ram(const char *filename
,
387 const struct dircache_entry
*dc
)
389 static long last_pos
= 0;
392 /* Check if we tagcache is loaded into ram. */
393 if (!tc_stat
.ramcache
)
397 dc
= dircache_get_entry_ptr(filename
);
401 logf("tagcache: file not found.");
412 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
414 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
416 last_pos
= MAX(0, i
- 3);
433 static long find_entry_disk(const char *filename
, bool localfd
)
435 struct tagcache_header tch
;
436 static long last_pos
= -1;
437 long pos_history
[POS_HISTORY_COUNT
];
438 long pos_history_idx
= 0;
440 struct tagfile_entry tfe
;
442 char buf
[TAG_MAXLEN
+32];
450 if (fd
< 0 || localfd
)
453 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
460 lseek(fd
, last_pos
, SEEK_SET
);
462 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
466 pos
= lseek(fd
, 0, SEEK_CUR
);
467 for (i
= pos_history_idx
-1; i
>= 0; i
--)
468 pos_history
[i
+1] = pos_history
[i
];
469 pos_history
[0] = pos
;
471 if (ecread_tagfile_entry(fd
, &tfe
)
472 != sizeof(struct tagfile_entry
))
477 if (tfe
.tag_length
>= (long)sizeof(buf
))
479 logf("too long tag #1");
487 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
489 logf("read error #2");
497 if (!strcasecmp(filename
, buf
))
499 last_pos
= pos_history
[pos_history_idx
];
504 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
518 if (fd
!= filenametag_fd
|| localfd
)
523 if (fd
!= filenametag_fd
|| localfd
)
529 static int find_index(const char *filename
)
533 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
534 if (tc_stat
.ramcache
&& is_dircache_intact())
535 idx_id
= find_entry_ram(filename
, NULL
);
539 idx_id
= find_entry_disk(filename
, true);
544 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
551 idx_id
= find_index(filename
);
555 if (!tagcache_search(tcs
, tag_filename
))
558 tcs
->entry_count
= 0;
559 tcs
->idx_id
= idx_id
;
564 static bool get_index(int masterfd
, int idxid
,
565 struct index_entry
*idx
, bool use_ram
)
567 bool localfd
= false;
571 logf("Incorrect idxid: %d", idxid
);
575 #ifdef HAVE_TC_RAMCACHE
576 if (tc_stat
.ramcache
&& use_ram
)
578 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
581 # ifdef HAVE_DIRCACHE
582 if (!(hdr
->indices
[idxid
].flag
& FLAG_DIRCACHE
)
583 || is_dircache_intact())
586 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
596 struct master_header tcmh
;
599 masterfd
= open_master_fd(&tcmh
, false);
604 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
605 + sizeof(struct master_header
), SEEK_SET
);
606 if (ecread_index_entry(masterfd
, idx
)
607 != sizeof(struct index_entry
))
609 logf("read error #3");
619 if (idx
->flag
& FLAG_DELETED
)
627 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
629 /* We need to exclude all memory only flags & tags when writing to disk. */
630 if (idx
->flag
& FLAG_DIRCACHE
)
632 logf("memory only flags!");
636 #ifdef HAVE_TC_RAMCACHE
637 /* Only update numeric data. Writing the whole index to RAM by memcpy
638 * destroys dircache pointers!
640 if (tc_stat
.ramcache
)
643 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
645 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
647 if (TAGCACHE_IS_NUMERIC(tag
))
649 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
653 /* Don't touch the dircache flag or attributes. */
654 idx_ram
->flag
= (idx
->flag
& 0x0000ffff)
655 | (idx_ram
->flag
& (0xffff0000 | FLAG_DIRCACHE
));
659 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
660 + sizeof(struct master_header
), SEEK_SET
);
661 if (ecwrite_index_entry(masterfd
, idx
) != sizeof(struct index_entry
))
663 logf("write error #3");
664 logf("idxid: %d", idxid
);
671 #endif /* !__PCTOOL__ */
673 static bool open_files(struct tagcache_search
*tcs
, int tag
)
675 if (tcs
->idxfd
[tag
] < 0)
677 char fn
[MAX_PATH
], path
[MAX_PATH
];
680 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
681 file
= get_user_file_path(fn
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
682 tcs
->idxfd
[tag
] = open(fn
, O_RDONLY
);
685 if (tcs
->idxfd
[tag
] < 0)
687 logf("File not open!");
694 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
695 int tag
, char *buf
, long size
)
697 struct tagfile_entry tfe
;
702 if (TAGCACHE_IS_NUMERIC(tag
))
705 seek
= idx
->tag_seek
[tag
];
708 logf("Retrieve failed");
712 #ifdef HAVE_TC_RAMCACHE
715 struct tagfile_entry
*ep
;
717 # ifdef HAVE_DIRCACHE
718 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
719 && is_dircache_intact())
721 dircache_copy_path((struct dircache_entry
*)seek
,
727 if (tag
!= tag_filename
)
729 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
730 strlcpy(buf
, ep
->tag_data
, size
);
737 if (!open_files(tcs
, tag
))
740 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
741 if (ecread_tagfile_entry(tcs
->idxfd
[tag
], &tfe
)
742 != sizeof(struct tagfile_entry
))
744 logf("read error #5");
748 if (tfe
.tag_length
>= size
)
750 logf("too small buffer");
754 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
757 logf("read error #6");
761 buf
[tfe
.tag_length
] = '\0';
766 static long check_virtual_tags(int tag
, const struct index_entry
*idx
)
772 case tag_virt_length_sec
:
773 data
= (idx
->tag_seek
[tag_length
]/1000) % 60;
776 case tag_virt_length_min
:
777 data
= (idx
->tag_seek
[tag_length
]/1000) / 60;
780 case tag_virt_playtime_sec
:
781 data
= (idx
->tag_seek
[tag_playtime
]/1000) % 60;
784 case tag_virt_playtime_min
:
785 data
= (idx
->tag_seek
[tag_playtime
]/1000) / 60;
788 case tag_virt_autoscore
:
789 if (idx
->tag_seek
[tag_length
] == 0
790 || idx
->tag_seek
[tag_playcount
] == 0)
796 /* A straight calculus gives:
797 autoscore = 100 * playtime / length / playcout (1)
798 Now, consider the euclidian division of playtime by length:
799 playtime = alpha * length + beta
803 autoscore = 100 * (alpha / playcout + beta / length / playcount)
804 Both terms should be small enough to avoid any overflow
806 data
= 100 * (idx
->tag_seek
[tag_playtime
] / idx
->tag_seek
[tag_length
])
807 + (100 * (idx
->tag_seek
[tag_playtime
] % idx
->tag_seek
[tag_length
])) / idx
->tag_seek
[tag_length
];
808 data
/= idx
->tag_seek
[tag_playcount
];
812 /* How many commits before the file has been added to the DB. */
813 case tag_virt_entryage
:
814 data
= current_tcmh
.commitid
- idx
->tag_seek
[tag_commitid
] - 1;
818 data
= idx
->tag_seek
[tag
];
824 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
826 struct index_entry idx
;
831 if (!TAGCACHE_IS_NUMERIC(tag
))
834 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
837 return check_virtual_tags(tag
, &idx
);
840 inline static bool str_ends_with(const char *str1
, const char *str2
)
842 int str_len
= strlen(str1
);
843 int clause_len
= strlen(str2
);
845 if (clause_len
> str_len
)
848 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
851 inline static bool str_oneof(const char *str
, const char *list
)
854 int l
, len
= strlen(str
);
858 sep
= strchr(list
, '|');
859 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
860 if ((l
==len
) && !strncasecmp(str
, list
, len
))
862 list
+= sep
? l
+ 1 : l
;
868 static bool check_against_clause(long numeric
, const char *str
,
869 const struct tagcache_search_clause
*clause
)
873 switch (clause
->type
)
876 return numeric
== clause
->numeric_data
;
878 return numeric
!= clause
->numeric_data
;
880 return numeric
> clause
->numeric_data
;
882 return numeric
>= clause
->numeric_data
;
884 return numeric
< clause
->numeric_data
;
886 return numeric
<= clause
->numeric_data
;
888 logf("Incorrect numeric tag: %d", clause
->type
);
893 switch (clause
->type
)
896 return !strcasecmp(clause
->str
, str
);
898 return strcasecmp(clause
->str
, str
);
900 return 0>strcasecmp(clause
->str
, str
);
902 return 0>=strcasecmp(clause
->str
, str
);
904 return 0<strcasecmp(clause
->str
, str
);
906 return 0<=strcasecmp(clause
->str
, str
);
907 case clause_contains
:
908 return (strcasestr(str
, clause
->str
) != NULL
);
909 case clause_not_contains
:
910 return (strcasestr(str
, clause
->str
) == NULL
);
911 case clause_begins_with
:
912 return (strcasestr(str
, clause
->str
) == str
);
913 case clause_not_begins_with
:
914 return (strcasestr(str
, clause
->str
) != str
);
915 case clause_ends_with
:
916 return str_ends_with(str
, clause
->str
);
917 case clause_not_ends_with
:
918 return !str_ends_with(str
, clause
->str
);
920 return str_oneof(str
, clause
->str
);
923 logf("Incorrect tag: %d", clause
->type
);
930 static bool check_clauses(struct tagcache_search
*tcs
,
931 struct index_entry
*idx
,
932 struct tagcache_search_clause
**clause
, int count
)
936 #ifdef HAVE_TC_RAMCACHE
939 /* Go through all conditional clauses. */
940 for (i
= 0; i
< count
; i
++)
942 struct tagfile_entry
*tfe
;
947 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
949 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
951 if (clause
[i
]->tag
== tag_filename
)
953 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
958 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
963 if (!check_against_clause(seek
, str
, clause
[i
]))
970 /* Check for conditions. */
971 for (i
= 0; i
< count
; i
++)
973 struct tagfile_entry tfe
;
977 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
979 memset(str
, 0, sizeof str
);
980 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
982 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
983 lseek(fd
, seek
, SEEK_SET
);
984 ecread_tagfile_entry(fd
, &tfe
);
985 if (tfe
.tag_length
>= (int)sizeof(str
))
987 logf("Too long tag read!");
991 read(fd
, str
, tfe
.tag_length
);
993 /* Check if entry has been deleted. */
998 if (!check_against_clause(seek
, str
, clause
[i
]))
1006 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
1007 struct tagcache_search_clause
**clause
, int count
)
1009 struct index_entry idx
;
1014 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
1017 return check_clauses(tcs
, &idx
, clause
, count
);
1020 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1024 /* If uniq buffer is not defined we must return true for search to work. */
1025 if (tcs
->unique_list
== NULL
|| (!TAGCACHE_IS_UNIQUE(tcs
->type
)
1026 && !TAGCACHE_IS_NUMERIC(tcs
->type
)))
1031 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1033 /* Return false if entry is found. */
1034 if (tcs
->unique_list
[i
] == id
)
1038 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1040 tcs
->unique_list
[i
] = id
;
1041 tcs
->unique_list_count
++;
1047 static bool build_lookup_list(struct tagcache_search
*tcs
)
1049 struct index_entry entry
;
1052 tcs
->seek_list_count
= 0;
1054 #ifdef HAVE_TC_RAMCACHE
1056 # ifdef HAVE_DIRCACHE
1057 && (tcs
->type
!= tag_filename
|| is_dircache_intact())
1061 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
1063 struct tagcache_seeklist_entry
*seeklist
;
1064 struct index_entry
*idx
= &hdr
->indices
[i
];
1065 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1068 /* Skip deleted files. */
1069 if (idx
->flag
& FLAG_DELETED
)
1072 /* Go through all filters.. */
1073 for (j
= 0; j
< tcs
->filter_count
; j
++)
1075 if (idx
->tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1081 if (j
< tcs
->filter_count
)
1084 /* Check for conditions. */
1085 if (!check_clauses(tcs
, idx
, tcs
->clause
, tcs
->clause_count
))
1088 /* Add to the seek list if not already in uniq buffer. */
1089 if (!add_uniqbuf(tcs
, idx
->tag_seek
[tcs
->type
]))
1093 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1094 seeklist
->seek
= idx
->tag_seek
[tcs
->type
];
1095 seeklist
->flag
= idx
->flag
;
1096 seeklist
->idx_id
= i
;
1097 tcs
->seek_list_count
++;
1102 return tcs
->seek_list_count
> 0;
1106 if (tcs
->masterfd
< 0)
1108 struct master_header tcmh
;
1109 tcs
->masterfd
= open_master_fd(&tcmh
, false);
1112 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1113 sizeof(struct master_header
), SEEK_SET
);
1115 while (ecread_index_entry(tcs
->masterfd
, &entry
)
1116 == sizeof(struct index_entry
))
1118 struct tagcache_seeklist_entry
*seeklist
;
1120 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1126 /* Check if entry has been deleted. */
1127 if (entry
.flag
& FLAG_DELETED
)
1130 /* Go through all filters.. */
1131 for (j
= 0; j
< tcs
->filter_count
; j
++)
1133 if (entry
.tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1137 if (j
< tcs
->filter_count
)
1140 /* Check for conditions. */
1141 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1144 /* Add to the seek list if not already in uniq buffer. */
1145 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1149 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1150 seeklist
->seek
= entry
.tag_seek
[tcs
->type
];
1151 seeklist
->flag
= entry
.flag
;
1152 seeklist
->idx_id
= i
;
1153 tcs
->seek_list_count
++;
1158 return tcs
->seek_list_count
> 0;
1162 static void remove_files(void)
1167 tc_stat
.ready
= false;
1168 tc_stat
.ramcache
= false;
1169 tc_stat
.econ
= false;
1170 remove(get_user_file_path(TAGCACHE_FILE_MASTER
, NEED_WRITE
|IS_FILE
,
1172 for (i
= 0; i
< TAG_COUNT
; i
++)
1174 char buf2
[MAX_PATH
];
1175 if (TAGCACHE_IS_NUMERIC(i
))
1178 /* database_%d.tcd -> database_0.tcd */
1179 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1180 remove(get_user_file_path(buf
, NEED_WRITE
| IS_FILE
, buf2
, sizeof(buf2
)));
1185 static bool check_all_headers(void)
1187 struct master_header myhdr
;
1188 struct tagcache_header tch
;
1192 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1198 logf("tagcache is dirty!");
1202 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1204 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1206 if (TAGCACHE_IS_NUMERIC(tag
))
1209 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1218 bool tagcache_is_busy(void)
1220 return read_lock
|| write_lock
;
1223 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1225 struct tagcache_header tag_hdr
;
1226 struct master_header master_hdr
;
1232 memset(tcs
, 0, sizeof(struct tagcache_search
));
1233 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1236 tcs
->position
= sizeof(struct tagcache_header
);
1239 tcs
->list_position
= 0;
1240 tcs
->seek_list_count
= 0;
1241 tcs
->filter_count
= 0;
1244 for (i
= 0; i
< TAG_COUNT
; i
++)
1247 #ifndef HAVE_TC_RAMCACHE
1248 tcs
->ramsearch
= false;
1250 tcs
->ramsearch
= tc_stat
.ramcache
;
1253 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1258 /* Always open as R/W so we can pass tcs to functions that modify data also
1259 * without failing. */
1260 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1261 if (tcs
->masterfd
< 0)
1264 if (!TAGCACHE_IS_NUMERIC(tcs
->type
))
1266 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1267 if (tcs
->idxfd
[tcs
->type
] < 0)
1270 tcs
->entry_count
= tag_hdr
.entry_count
;
1274 tcs
->entry_count
= master_hdr
.tch
.entry_count
;
1279 tcs
->initialized
= true;
1285 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1286 void *buffer
, long length
)
1288 tcs
->unique_list
= (unsigned long *)buffer
;
1289 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1290 tcs
->unique_list_count
= 0;
1293 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1296 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1299 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag
))
1302 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1303 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1304 tcs
->filter_count
++;
1309 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1310 struct tagcache_search_clause
*clause
)
1314 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1316 logf("Too many clauses");
1320 /* Check if there is already a similar filter in present (filters are
1321 * much faster than clauses).
1323 for (i
= 0; i
< tcs
->filter_count
; i
++)
1325 if (tcs
->filter_tag
[i
] == clause
->tag
)
1329 if (!TAGCACHE_IS_NUMERIC(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1331 char buf
[MAX_PATH
], path
[MAX_PATH
];
1333 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1334 file
= get_user_file_path(buf
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
1335 tcs
->idxfd
[clause
->tag
] = open(file
, O_RDONLY
);
1338 tcs
->clause
[tcs
->clause_count
] = clause
;
1339 tcs
->clause_count
++;
1344 static bool get_next(struct tagcache_search
*tcs
)
1346 static char buf
[TAG_MAXLEN
+32];
1347 struct tagfile_entry entry
;
1350 if (!tcs
->valid
|| !tc_stat
.ready
)
1353 if (tcs
->idxfd
[tcs
->type
] < 0 && !TAGCACHE_IS_NUMERIC(tcs
->type
)
1354 #ifdef HAVE_TC_RAMCACHE
1360 /* Relative fetch. */
1361 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1362 || TAGCACHE_IS_NUMERIC(tcs
->type
)
1363 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1364 /* We need to retrieve flag status for dircache. */
1365 || (tcs
->ramsearch
&& tcs
->type
== tag_filename
)
1369 struct tagcache_seeklist_entry
*seeklist
;
1371 /* Check for end of list. */
1372 if (tcs
->list_position
== tcs
->seek_list_count
)
1374 tcs
->list_position
= 0;
1376 /* Try to fetch more. */
1377 if (!build_lookup_list(tcs
))
1384 seeklist
= &tcs
->seeklist
[tcs
->list_position
];
1385 flag
= seeklist
->flag
;
1386 tcs
->position
= seeklist
->seek
;
1387 tcs
->idx_id
= seeklist
->idx_id
;
1388 tcs
->list_position
++;
1392 if (tcs
->entry_count
== 0)
1401 tcs
->result_seek
= tcs
->position
;
1403 if (TAGCACHE_IS_NUMERIC(tcs
->type
))
1405 snprintf(buf
, sizeof(buf
), "%ld", tcs
->position
);
1407 tcs
->result_len
= strlen(buf
) + 1;
1412 #ifdef HAVE_TC_RAMCACHE
1416 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1417 if (tcs
->type
== tag_filename
&& (flag
& FLAG_DIRCACHE
)
1418 && is_dircache_intact())
1420 dircache_copy_path((struct dircache_entry
*)tcs
->position
,
1423 tcs
->result_len
= strlen(buf
) + 1;
1424 tcs
->ramresult
= false;
1430 if (tcs
->type
!= tag_filename
)
1432 struct tagfile_entry
*ep
;
1434 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1435 tcs
->result
= ep
->tag_data
;
1436 tcs
->result_len
= strlen(tcs
->result
) + 1;
1437 tcs
->idx_id
= ep
->idx_id
;
1438 tcs
->ramresult
= true;
1440 /* Increase position for the next run. This may get overwritten. */
1441 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1448 if (!open_files(tcs
, tcs
->type
))
1454 /* Seek stream to the correct position and continue to direct fetch. */
1455 lseek(tcs
->idxfd
[tcs
->type
], tcs
->position
, SEEK_SET
);
1457 if (ecread_tagfile_entry(tcs
->idxfd
[tcs
->type
], &entry
) != sizeof(struct tagfile_entry
))
1459 logf("read error #5");
1464 if (entry
.tag_length
> (long)sizeof(buf
))
1467 logf("too long tag #2");
1468 logf("P:%lX/%lX", tcs
->position
, entry
.tag_length
);
1472 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1475 logf("read error #4");
1480 Update the position for the next read (this may be overridden
1481 if filters or clauses are being used).
1483 tcs
->position
+= sizeof(struct tagfile_entry
) + entry
.tag_length
;
1485 tcs
->result_len
= strlen(tcs
->result
) + 1;
1486 tcs
->idx_id
= entry
.idx_id
;
1487 tcs
->ramresult
= false;
1492 bool tagcache_get_next(struct tagcache_search
*tcs
)
1494 while (get_next(tcs
))
1496 if (tcs
->result_len
> 1)
1503 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1504 int tag
, char *buf
, long size
)
1506 struct index_entry idx
;
1509 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1512 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1515 static bool update_master_header(void)
1517 struct master_header myhdr
;
1523 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1526 myhdr
.serial
= current_tcmh
.serial
;
1527 myhdr
.commitid
= current_tcmh
.commitid
;
1528 myhdr
.dirty
= current_tcmh
.dirty
;
1531 lseek(fd
, 0, SEEK_SET
);
1532 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1535 #ifdef HAVE_TC_RAMCACHE
1538 hdr
->h
.serial
= current_tcmh
.serial
;
1539 hdr
->h
.commitid
= current_tcmh
.commitid
;
1540 hdr
->h
.dirty
= current_tcmh
.dirty
;
1549 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1551 struct tagentry
*entry
;
1553 if (tcs
->type
!= tag_title
)
1556 /* We will need reserve buffer for this. */
1559 struct tagfile_entry
*ep
;
1561 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1562 tcs
->seek_list
[tcs
->seek_list_count
];
1565 entry
= find_entry_ram();
1570 void tagcache_search_finish(struct tagcache_search
*tcs
)
1574 if (!tcs
->initialized
)
1577 if (tcs
->masterfd
>= 0)
1579 close(tcs
->masterfd
);
1583 for (i
= 0; i
< TAG_COUNT
; i
++)
1585 if (tcs
->idxfd
[i
] >= 0)
1587 close(tcs
->idxfd
[i
]);
1592 tcs
->ramsearch
= false;
1594 tcs
->initialized
= 0;
1599 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1600 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1602 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1605 static long get_tag_numeric(const struct index_entry
*entry
, int tag
)
1607 return check_virtual_tags(tag
, entry
);
1610 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1612 char* s
= get_tag(entry
, tag
)->tag_data
;
1613 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1616 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1618 struct index_entry
*entry
;
1621 if (!tc_stat
.ready
|| !tc_stat
.ramcache
)
1624 /* Find the corresponding entry in tagcache. */
1625 idx_id
= find_entry_ram(filename
, NULL
);
1629 entry
= &hdr
->indices
[idx_id
];
1631 memset(id3
, 0, sizeof(struct mp3entry
));
1633 id3
->title
= get_tag_string(entry
, tag_title
);
1634 id3
->artist
= get_tag_string(entry
, tag_artist
);
1635 id3
->album
= get_tag_string(entry
, tag_album
);
1636 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1637 id3
->composer
= get_tag_string(entry
, tag_composer
);
1638 id3
->comment
= get_tag_string(entry
, tag_comment
);
1639 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1640 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1642 id3
->length
= get_tag_numeric(entry
, tag_length
);
1643 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
);
1644 id3
->rating
= get_tag_numeric(entry
, tag_rating
);
1645 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
);
1646 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
) / 10;
1647 id3
->year
= get_tag_numeric(entry
, tag_year
);
1649 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
);
1650 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
);
1651 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
);
1652 if (id3
->bitrate
== 0)
1659 static inline void write_item(const char *item
)
1661 int len
= strlen(item
) + 1;
1664 write(cachefd
, item
, len
);
1667 static int check_if_empty(char **tag
)
1671 if (*tag
== NULL
|| **tag
== '\0')
1674 return sizeof(UNTAGGED
); /* Tag length */
1677 length
= strlen(*tag
);
1678 if (length
> TAG_MAXLEN
)
1680 logf("over length tag: %s", *tag
);
1681 length
= TAG_MAXLEN
;
1682 (*tag
)[length
] = '\0';
1688 #define ADD_TAG(entry,tag,data) \
1690 entry.tag_offset[tag] = offset; \
1691 entry.tag_length[tag] = check_if_empty(data); \
1692 offset += entry.tag_length[tag]
1693 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1694 * idea, as it uses lots of stack and is called from a recursive function
1697 static void __attribute__ ((noinline
)) add_tagcache(char *path
,
1699 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1700 ,const struct dircache_entry
*dc
1704 struct mp3entry id3
;
1705 struct temp_file_entry entry
;
1709 char tracknumfix
[3];
1711 int path_length
= strlen(path
);
1712 bool has_albumartist
;
1716 /* Crude logging for the sim - to aid in debugging */
1717 int logfd
= open(ROCKBOX_DIR
"/database.log",
1718 O_WRONLY
| O_APPEND
| O_CREAT
, 0666);
1720 write(logfd
, path
, strlen(path
));
1721 write(logfd
, "\n", 1);
1729 /* Check for overlength file path. */
1730 if (path_length
> TAG_MAXLEN
)
1732 /* Path can't be shortened. */
1733 logf("Too long path: %s", path
);
1737 /* Check if the file is supported. */
1738 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1741 /* Check if the file is already cached. */
1742 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1743 if (tc_stat
.ramcache
&& is_dircache_intact())
1745 idx_id
= find_entry_ram(path
, dc
);
1749 /* Be sure the entry doesn't exist. */
1750 if (filenametag_fd
>= 0 && idx_id
< 0)
1751 idx_id
= find_entry_disk(path
, false);
1753 /* Check if file has been modified. */
1756 struct index_entry idx
;
1758 /* TODO: Mark that the index exists (for fast reverse scan) */
1759 //found_idx[idx_id/8] |= idx_id%8;
1761 if (!get_index(-1, idx_id
, &idx
, true))
1763 logf("failed to retrieve index entry");
1767 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1769 /* No changes to file. */
1773 /* Metadata might have been changed. Delete the entry. */
1774 logf("Re-adding: %s", path
);
1775 if (!delete_entry(idx_id
))
1777 logf("delete_entry failed: %d", idx_id
);
1782 fd
= open(path
, O_RDONLY
);
1785 logf("open fail: %s", path
);
1789 memset(&id3
, 0, sizeof(struct mp3entry
));
1790 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1791 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1792 ret
= get_metadata(&id3
, fd
, path
);
1798 logf("-> %s", path
);
1800 /* Generate track number if missing. */
1801 if (id3
.tracknum
<= 0)
1803 const char *p
= strrchr(path
, '.');
1806 p
= &path
[strlen(path
)-1];
1810 if (isdigit(*p
) && isdigit(*(p
-1)))
1812 tracknumfix
[1] = *p
--;
1813 tracknumfix
[0] = *p
;
1819 if (tracknumfix
[0] != '\0')
1821 id3
.tracknum
= atoi(tracknumfix
);
1822 /* Set a flag to indicate track number has been generated. */
1823 entry
.flag
|= FLAG_TRKNUMGEN
;
1827 /* Unable to generate track number. */
1833 entry
.tag_offset
[tag_year
] = id3
.year
;
1834 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1835 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1836 entry
.tag_offset
[tag_length
] = id3
.length
;
1837 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1838 entry
.tag_offset
[tag_mtime
] = mtime
;
1841 has_albumartist
= id3
.albumartist
!= NULL
1842 && strlen(id3
.albumartist
) > 0;
1843 has_grouping
= id3
.grouping
!= NULL
1844 && strlen(id3
.grouping
) > 0;
1846 ADD_TAG(entry
, tag_filename
, &path
);
1847 ADD_TAG(entry
, tag_title
, &id3
.title
);
1848 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1849 ADD_TAG(entry
, tag_album
, &id3
.album
);
1850 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1851 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1852 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1853 if (has_albumartist
)
1855 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1859 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1863 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1867 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1869 entry
.data_length
= offset
;
1871 /* Write the header */
1872 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1874 /* And tags also... Correct order is critical */
1876 write_item(id3
.title
);
1877 write_item(id3
.artist
);
1878 write_item(id3
.album
);
1879 write_item(id3
.genre_string
);
1880 write_item(id3
.composer
);
1881 write_item(id3
.comment
);
1882 if (has_albumartist
)
1884 write_item(id3
.albumartist
);
1888 write_item(id3
.artist
);
1892 write_item(id3
.grouping
);
1896 write_item(id3
.title
);
1898 total_entry_count
++;
1901 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1903 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1904 int len
= strlen(str
)+1;
1907 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1908 char buf
[TAG_MAXLEN
+32];
1910 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1911 buf
[i
] = tolower(str
[i
]);
1914 crc32
= crc_32(buf
, i
, 0xffffffff);
1918 /* Check if the crc does not exist -> entry does not exist for sure. */
1919 for (i
= 0; i
< tempbufidx
; i
++)
1921 if (crcbuf
[-i
] != crc32
)
1924 if (!strcasecmp(str
, index
[i
].str
))
1926 if (id
< 0 || id
>= lookup_buffer_depth
)
1928 logf("lookup buf overf.: %d", id
);
1932 lookup
[id
] = &index
[i
];
1938 /* Insert to CRC buffer. */
1939 crcbuf
[-tempbufidx
] = crc32
;
1942 /* Insert it to the buffer. */
1943 tempbuf_left
-= len
;
1944 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1947 if (id
>= lookup_buffer_depth
)
1949 logf("lookup buf overf. #2: %d", id
);
1955 lookup
[id
] = &index
[tempbufidx
];
1956 index
[tempbufidx
].idlist
.id
= id
;
1959 index
[tempbufidx
].idlist
.id
= -1;
1961 index
[tempbufidx
].idlist
.next
= NULL
;
1962 index
[tempbufidx
].idx_id
= idx_id
;
1963 index
[tempbufidx
].seek
= -1;
1964 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
1965 memcpy(index
[tempbufidx
].str
, str
, len
);
1972 static int compare(const void *p1
, const void *p2
)
1976 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
1977 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
1979 if (strcmp(e1
->str
, UNTAGGED
) == 0)
1981 if (strcmp(e2
->str
, UNTAGGED
) == 0)
1985 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
1988 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
1991 static int tempbuf_sort(int fd
)
1993 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1994 struct tagfile_entry fe
;
1998 /* Generate reverse lookup entries. */
1999 for (i
= 0; i
< lookup_buffer_depth
; i
++)
2001 struct tempbuf_id_list
*idlist
;
2006 if (lookup
[i
]->idlist
.id
== i
)
2009 idlist
= &lookup
[i
]->idlist
;
2010 while (idlist
->next
!= NULL
)
2011 idlist
= idlist
->next
;
2013 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
2014 if (tempbuf_left
- 4 < 0)
2017 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2018 if (tempbuf_pos
& 0x03)
2020 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
2022 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2024 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
2026 idlist
= idlist
->next
;
2028 idlist
->next
= NULL
;
2033 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
2034 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
2036 for (i
= 0; i
< tempbufidx
; i
++)
2038 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
2040 /* Fix the lookup list. */
2041 while (idlist
!= NULL
)
2043 if (idlist
->id
>= 0)
2044 lookup
[idlist
->id
] = &index
[i
];
2045 idlist
= idlist
->next
;
2048 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
2049 length
= strlen(index
[i
].str
) + 1;
2050 fe
.tag_length
= length
;
2051 fe
.idx_id
= index
[i
].idx_id
;
2053 /* Check the chunk alignment. */
2054 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2055 % TAGFILE_ENTRY_CHUNK_LENGTH
)
2057 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
2058 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2059 % TAGFILE_ENTRY_CHUNK_LENGTH
);
2062 #ifdef TAGCACHE_STRICT_ALIGN
2063 /* Make sure the entry is long aligned. */
2064 if (index
[i
].seek
& 0x03)
2066 logf("tempbuf_sort: alignment error!");
2071 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2072 sizeof(struct tagfile_entry
))
2074 logf("tempbuf_sort: write error #1");
2078 if (write(fd
, index
[i
].str
, length
) != length
)
2080 logf("tempbuf_sort: write error #2");
2084 /* Write some padding. */
2085 if (fe
.tag_length
- length
> 0)
2086 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2092 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2094 if (id
< 0 || id
>= lookup_buffer_depth
)
2101 inline static int tempbuf_find_location(int id
)
2103 struct tempbuf_searchidx
*entry
;
2105 entry
= tempbuf_locate(id
);
2112 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2114 struct master_header tcmh
;
2115 struct index_entry idx
;
2118 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2120 int entries_processed
= 0;
2122 char buf
[TAG_MAXLEN
];
2124 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2126 logf("Building numeric indices...");
2127 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2129 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2132 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2134 if (masterfd_pos
== filesize(masterfd
))
2136 logf("we can't append!");
2141 while (entries_processed
< h
->entry_count
)
2143 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2145 /* Read in as many entries as possible. */
2146 for (i
= 0; i
< count
; i
++)
2148 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2151 /* Read in numeric data. */
2152 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2153 sizeof(struct temp_file_entry
))
2155 logf("read fail #1");
2160 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2163 * Read string data from the following tags:
2169 * A crc32 hash is calculated from the read data
2170 * and stored back to the data offset field kept in memory.
2172 #define tmpdb_read_string_tag(tag) \
2173 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2174 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2176 logf("read fail: buffer overflow"); \
2181 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2182 tfe->tag_length[tag]) \
2184 logf("read fail #2"); \
2189 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2190 lseek(tmpfd, datastart, SEEK_SET)
2192 tmpdb_read_string_tag(tag_filename
);
2193 tmpdb_read_string_tag(tag_artist
);
2194 tmpdb_read_string_tag(tag_album
);
2195 tmpdb_read_string_tag(tag_title
);
2197 /* Seek to the end of the string data. */
2198 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2201 /* Backup the master index position. */
2202 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2203 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2205 /* Check if we can resurrect some deleted runtime statistics data. */
2206 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2208 /* Read the index entry. */
2209 if (ecread_index_entry(masterfd
, &idx
)
2210 != sizeof(struct index_entry
))
2212 logf("read fail #3");
2218 * Skip unless the entry is marked as being deleted
2219 * or the data has already been resurrected.
2221 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2224 /* Now try to match the entry. */
2226 * To succesfully match a song, the following conditions
2229 * For numeric fields: tag_length
2230 * - Full identical match is required
2232 * If tag_filename matches, no further checking necessary.
2234 * For string hashes: tag_artist, tag_album, tag_title
2235 * - Two of these must match
2237 for (j
= 0; j
< count
; j
++)
2239 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2241 /* Try to match numeric fields first. */
2242 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2245 /* Now it's time to do the hash matching. */
2246 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2248 int match_count
= 0;
2250 /* No filename match, check if we can match two other tags. */
2251 #define tmpdb_match(tag) \
2252 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2255 tmpdb_match(tag_artist
);
2256 tmpdb_match(tag_album
);
2257 tmpdb_match(tag_title
);
2259 if (match_count
< 2)
2261 /* Still no match found, give up. */
2266 /* A match found, now copy & resurrect the statistical data. */
2267 #define tmpdb_copy_tag(tag) \
2268 tfe->tag_offset[tag] = idx.tag_seek[tag]
2270 tmpdb_copy_tag(tag_playcount
);
2271 tmpdb_copy_tag(tag_rating
);
2272 tmpdb_copy_tag(tag_playtime
);
2273 tmpdb_copy_tag(tag_lastplayed
);
2274 tmpdb_copy_tag(tag_commitid
);
2276 /* Avoid processing this entry again. */
2277 idx
.flag
|= FLAG_RESURRECTED
;
2279 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2280 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2282 logf("masterfd writeback fail #1");
2287 logf("Entry resurrected");
2292 /* Restore the master index position. */
2293 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2295 /* Commit the data to the index. */
2296 for (i
= 0; i
< count
; i
++)
2298 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2300 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2302 logf("read fail #3");
2307 for (j
= 0; j
< TAG_COUNT
; j
++)
2309 if (!TAGCACHE_IS_NUMERIC(j
))
2312 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2314 idx
.flag
= entrybuf
[i
].flag
;
2316 if (idx
.tag_seek
[tag_commitid
])
2318 /* Data has been resurrected. */
2319 idx
.flag
|= FLAG_DIRTYNUM
;
2321 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2323 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2324 idx
.flag
|= FLAG_DIRTYNUM
;
2327 /* Write back the updated index. */
2328 lseek(masterfd
, loc
, SEEK_SET
);
2329 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2337 entries_processed
+= count
;
2338 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2349 * == 0 temporary failure
2352 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2355 struct tagcache_header tch
;
2356 struct master_header tcmh
;
2357 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2359 char buf
[TAG_MAXLEN
+32], path
[MAX_PATH
];
2361 int fd
= -1, masterfd
;
2366 logf("Building index: %d", index_type
);
2368 /* Check the number of entries we need to allocate ram for. */
2369 commit_entry_count
= h
->entry_count
+ 1;
2371 masterfd
= open_master_fd(&tcmh
, false);
2374 commit_entry_count
+= tcmh
.tch
.entry_count
;
2378 remove_files(); /* Just to be sure we are clean. */
2380 /* Open the index file, which contains the tag names. */
2381 fd
= open_tag_fd(&tch
, index_type
, true);
2384 logf("tch.datasize=%ld", tch
.datasize
);
2385 lookup_buffer_depth
= 1 +
2386 /* First part */ commit_entry_count
+
2387 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2391 lookup_buffer_depth
= 1 +
2392 /* First part */ commit_entry_count
+
2393 /* Second part */ 0;
2396 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2397 logf("commit_entry_count=%ld", commit_entry_count
);
2399 /* Allocate buffer for all index entries from both old and new
2402 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2404 /* Allocate lookup buffer. The first portion of commit_entry_count
2405 * contains the new tags in the temporary file and the second
2406 * part for locating entries already in the db.
2409 * +---------+---------------------------+
2410 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2411 * +---------+---------------------------+
2413 * Old tags are inserted to a temporary buffer with position:
2414 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2415 * And new tags with index:
2416 * tempbuf_insert(idx, ...);
2418 * The buffer is sorted and written into tag file:
2419 * tempbuf_sort(...);
2420 * leaving master index locations messed up.
2422 * That is fixed using the lookup buffer for old tags:
2423 * new_seek = tempbuf_find_location(old_seek, ...);
2425 * new_seek = tempbuf_find_location(idx);
2427 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2428 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2429 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2431 /* And calculate the remaining data space used mainly for storing
2432 * tag data (strings). */
2433 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2434 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2436 logf("Buffer way too small!");
2443 * If tag file contains unique tags (sorted index), we will load
2444 * it entirely into memory so we can resort it later for use with
2447 if (TAGCACHE_IS_SORTED(index_type
))
2449 logf("loading tags...");
2450 for (i
= 0; i
< tch
.entry_count
; i
++)
2452 struct tagfile_entry entry
;
2453 int loc
= lseek(fd
, 0, SEEK_CUR
);
2456 if (ecread_tagfile_entry(fd
, &entry
) != sizeof(struct tagfile_entry
))
2458 logf("read error #7");
2463 if (entry
.tag_length
>= (int)sizeof(buf
))
2465 logf("too long tag #3");
2470 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2472 logf("read error #8");
2477 /* Skip deleted entries. */
2482 * Save the tag and tag id in the memory buffer. Tag id
2483 * is saved so we can later reindex the master lookup
2484 * table when the index gets resorted.
2486 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2487 + commit_entry_count
, entry
.idx_id
,
2488 TAGCACHE_IS_UNIQUE(index_type
));
2499 tempbufidx
= tch
.entry_count
;
2504 * Creating new index file to store the tags. No need to preload
2505 * anything whether the index type is sorted or not.
2507 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2508 file
= get_user_file_path(buf
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
2509 fd
= open(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2512 logf("%s open fail", buf
);
2516 tch
.magic
= TAGCACHE_MAGIC
;
2517 tch
.entry_count
= 0;
2520 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2521 != sizeof(struct tagcache_header
))
2523 logf("header write failed");
2529 file
= get_user_file_path(TAGCACHE_FILE_MASTER
,
2532 /* Loading the tag lookup file as "master file". */
2533 logf("Loading index file");
2534 masterfd
= open(file
, O_RDWR
);
2538 logf("Creating new DB");
2539 masterfd
= open(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2543 logf("Failure to create index file (%s)", file
);
2548 /* Write the header (write real values later). */
2549 memset(&tcmh
, 0, sizeof(struct master_header
));
2551 tcmh
.tch
.entry_count
= 0;
2552 tcmh
.tch
.datasize
= 0;
2554 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2556 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2561 * Master file already exists so we need to process the current
2566 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2567 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2569 logf("header error");
2576 * If we reach end of the master file, we need to expand it to
2577 * hold new tags. If the current index is not sorted, we can
2578 * simply append new data to end of the file.
2579 * However, if the index is sorted, we need to update all tag
2580 * pointers in the master file for the current index.
2582 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2584 if (masterfd_pos
== filesize(masterfd
))
2586 logf("appending...");
2592 * Load new unique tags in memory to be sorted later and added
2593 * to the master lookup file.
2595 if (TAGCACHE_IS_SORTED(index_type
))
2597 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2598 /* h is the header of the temporary file containing new tags. */
2599 logf("inserting new tags...");
2600 for (i
= 0; i
< h
->entry_count
; i
++)
2602 struct temp_file_entry entry
;
2604 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2605 sizeof(struct temp_file_entry
))
2607 logf("read fail #3");
2613 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2615 logf("too long entry!");
2620 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2621 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2622 entry
.tag_length
[index_type
])
2624 logf("read fail #4");
2629 if (TAGCACHE_IS_UNIQUE(index_type
))
2630 error
= !tempbuf_insert(buf
, i
, -1, true);
2632 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2636 logf("insert error");
2641 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2642 entry
.tag_length
[index_type
], SEEK_CUR
);
2647 /* Sort the buffer data and write it to the index file. */
2648 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2650 * We need to truncate the index file now. There can be junk left
2651 * at the end of file (however, we _should_ always follow the
2652 * entry_count and don't crash with that).
2654 ftruncate(fd
, lseek(fd
, 0, SEEK_CUR
));
2656 i
= tempbuf_sort(fd
);
2659 logf("sorted %d tags", i
);
2662 * Now update all indexes in the master lookup file.
2664 logf("updating indices...");
2665 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2666 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2669 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2671 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2673 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2674 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2676 logf("read fail #5");
2680 lseek(masterfd
, loc
, SEEK_SET
);
2682 for (j
= 0; j
< idxbuf_pos
; j
++)
2684 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2686 /* We can just ignore deleted entries. */
2687 // idxbuf[j].tag_seek[index_type] = 0;
2691 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2692 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2693 + commit_entry_count
);
2695 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2697 logf("update error: %ld/%d/%ld",
2698 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2706 /* Write back the updated index. */
2707 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2708 index_entry_ec
, tc_stat
.econ
) !=
2709 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2720 * Walk through the temporary file containing the new tags.
2722 // build_normal_index(h, tmpfd, masterfd, idx);
2723 logf("updating new indices...");
2724 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2725 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2726 lseek(fd
, 0, SEEK_END
);
2727 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2731 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2734 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2738 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2740 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2741 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2743 logf("read fail #6");
2747 lseek(masterfd
, loc
, SEEK_SET
);
2750 /* Read entry headers. */
2751 for (j
= 0; j
< idxbuf_pos
; j
++)
2753 if (!TAGCACHE_IS_SORTED(index_type
))
2755 struct temp_file_entry entry
;
2756 struct tagfile_entry fe
;
2758 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2759 sizeof(struct temp_file_entry
))
2761 logf("read fail #7");
2767 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2769 logf("too long entry!");
2770 logf("length=%d", entry
.tag_length
[index_type
]);
2771 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2776 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2777 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2778 entry
.tag_length
[index_type
])
2780 logf("read fail #8");
2781 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2782 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2787 /* Write to index file. */
2788 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2789 fe
.tag_length
= entry
.tag_length
[index_type
];
2790 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2791 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2792 write(fd
, buf
, fe
.tag_length
);
2796 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2797 entry
.tag_length
[index_type
], SEEK_CUR
);
2801 /* Locate the correct entry from the sorted array. */
2802 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2803 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2805 logf("entry not found (%d)", j
);
2813 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2814 index_entry_ec
, tc_stat
.econ
) !=
2815 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2817 logf("tagcache: write fail #4");
2826 /* Finally write the header. */
2827 tch
.magic
= TAGCACHE_MAGIC
;
2828 tch
.entry_count
= tempbufidx
;
2829 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2830 lseek(fd
, 0, SEEK_SET
);
2831 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2833 if (index_type
!= tag_filename
)
2834 h
->datasize
+= tch
.datasize
;
2835 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2847 static bool commit(void)
2849 struct tagcache_header tch
;
2850 struct master_header tcmh
;
2851 char path
[MAX_PATH
];
2856 #ifdef HAVE_DIRCACHE
2857 bool dircache_buffer_stolen
= false;
2859 bool local_allocation
= false;
2861 logf("committing tagcache");
2866 file
= get_user_file_path(TAGCACHE_FILE_TEMP
,
2867 IS_FILE
|NEED_WRITE
, path
, sizeof(path
));
2869 tmpfd
= open(file
, O_RDONLY
);
2872 logf("nothing to commit");
2877 /* Load the header. */
2878 len
= sizeof(struct tagcache_header
);
2879 rc
= read(tmpfd
, &tch
, len
);
2881 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2883 logf("incorrect tmpheader");
2889 if (tch
.entry_count
== 0)
2891 logf("nothing to commit");
2897 /* Fully initialize existing headers (if any) before going further. */
2898 tc_stat
.ready
= check_all_headers();
2900 #ifdef HAVE_EEPROM_SETTINGS
2901 remove(get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
2902 path
, sizeof(path
)));
2905 /* At first be sure to unload the ramcache! */
2906 #ifdef HAVE_TC_RAMCACHE
2907 tc_stat
.ramcache
= false;
2912 /* Try to steal every buffer we can :) */
2913 if (tempbuf_size
== 0)
2914 local_allocation
= true;
2916 #ifdef HAVE_DIRCACHE
2917 if (tempbuf_size
== 0)
2919 /* Try to steal the dircache buffer. */
2920 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2921 tempbuf_size
&= ~0x03;
2923 if (tempbuf_size
> 0)
2925 dircache_buffer_stolen
= true;
2930 #ifdef HAVE_TC_RAMCACHE
2931 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2933 tempbuf
= (char *)(hdr
+ 1);
2934 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2935 tempbuf_size
&= ~0x03;
2939 /* And finally fail if there are no buffers available. */
2940 if (tempbuf_size
== 0)
2942 logf("delaying commit until next boot");
2943 tc_stat
.commit_delayed
= true;
2949 logf("commit %ld entries...", tch
.entry_count
);
2951 /* Mark DB dirty so it will stay disabled if commit fails. */
2952 current_tcmh
.dirty
= true;
2953 update_master_header();
2955 /* Now create the index files. */
2956 tc_stat
.commit_step
= 0;
2958 tc_stat
.commit_delayed
= false;
2960 for (i
= 0; i
< TAG_COUNT
; i
++)
2964 if (TAGCACHE_IS_NUMERIC(i
))
2967 tc_stat
.commit_step
++;
2968 ret
= build_index(i
, &tch
, tmpfd
);
2972 logf("tagcache failed init");
2974 tc_stat
.commit_delayed
= true;
2976 tc_stat
.commit_step
= 0;
2982 if (!build_numeric_indices(&tch
, tmpfd
))
2984 logf("Failure to commit numeric indices");
2986 tc_stat
.commit_step
= 0;
2994 tc_stat
.commit_step
= 0;
2996 /* Update the master index headers. */
2997 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
3003 tcmh
.tch
.entry_count
+= tch
.entry_count
;
3004 tcmh
.tch
.datasize
= sizeof(struct master_header
)
3005 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
3010 lseek(masterfd
, 0, SEEK_SET
);
3011 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
3014 logf("tagcache committed");
3015 tc_stat
.ready
= check_all_headers();
3016 tc_stat
.readyvalid
= true;
3018 if (local_allocation
)
3024 #ifdef HAVE_DIRCACHE
3025 /* Rebuild the dircache, if we stole the buffer. */
3026 if (dircache_buffer_stolen
)
3030 #ifdef HAVE_TC_RAMCACHE
3031 /* Reload tagcache. */
3032 if (tc_stat
.ramcache_allocated
> 0)
3033 tagcache_start_scan();
3041 static void allocate_tempbuf(void)
3043 /* Yeah, malloc would be really nice now :) */
3045 tempbuf_size
= 32*1024*1024;
3046 tempbuf
= malloc(tempbuf_size
);
3048 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
3049 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
3050 audiobuf
+= tempbuf_size
;
3054 static void free_tempbuf(void)
3056 if (tempbuf_size
== 0)
3062 audiobuf
-= tempbuf_size
;
3070 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
3072 struct index_entry idx
;
3077 if (!TAGCACHE_IS_NUMERIC(tag
))
3080 if (!get_index(masterfd
, idx_id
, &idx
, false))
3083 idx
.tag_seek
[tag
] = data
;
3084 idx
.flag
|= FLAG_DIRTYNUM
;
3086 return write_index(masterfd
, idx_id
, &idx
);
3090 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3093 struct master_header myhdr
;
3095 if (tcs
->masterfd
< 0)
3097 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3101 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3105 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
3107 static bool command_queue_is_full(void)
3111 next
= command_queue_widx
+ 1;
3112 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3115 return (next
== command_queue_ridx
);
3118 static void command_queue_sync_callback(void *data
)
3121 struct master_header myhdr
;
3124 mutex_lock(&command_queue_mutex
);
3126 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3129 while (command_queue_ridx
!= command_queue_widx
)
3131 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3133 switch (ce
->command
)
3135 case CMD_UPDATE_MASTER_HEADER
:
3138 update_master_header();
3140 /* Re-open the masterfd. */
3141 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3146 case CMD_UPDATE_NUMERIC
:
3148 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3153 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3154 command_queue_ridx
= 0;
3159 tc_stat
.queue_length
= 0;
3160 mutex_unlock(&command_queue_mutex
);
3163 static void run_command_queue(bool force
)
3165 if (COMMAND_QUEUE_IS_EMPTY
)
3168 if (force
|| command_queue_is_full())
3169 command_queue_sync_callback(NULL
);
3171 register_storage_idle_func(command_queue_sync_callback
);
3174 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3180 mutex_lock(&command_queue_mutex
);
3181 next
= command_queue_widx
+ 1;
3182 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3185 /* Make sure queue is not full. */
3186 if (next
!= command_queue_ridx
)
3188 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3191 ce
->idx_id
= idx_id
;
3195 command_queue_widx
= next
;
3197 tc_stat
.queue_length
++;
3199 mutex_unlock(&command_queue_mutex
);
3203 /* Queue is full, try again later... */
3204 mutex_unlock(&command_queue_mutex
);
3209 long tagcache_increase_serial(void)
3219 old
= current_tcmh
.serial
++;
3220 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3225 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3227 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3229 #endif /* !__PCTOOL__ */
3231 long tagcache_get_serial(void)
3233 return current_tcmh
.serial
;
3236 long tagcache_get_commitid(void)
3238 return current_tcmh
.commitid
;
3241 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3246 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3247 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3249 if (*datastr
== '\0')
3252 if (*datastr
== '"' || *datastr
== '\\')
3255 buf
[i
] = *(datastr
++);
3258 strcpy(&buf
[i
], "\" ");
3260 write(fd
, buf
, i
+ 2);
3267 static bool read_tag(char *dest
, long size
,
3268 const char *src
, const char *tagstr
)
3271 char current_tag
[32];
3273 while (*src
!= '\0')
3275 /* Skip all whitespace */
3283 /* Read in tag name */
3284 while (*src
!= '=' && *src
!= ' ')
3286 current_tag
[pos
] = *src
;
3290 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3293 current_tag
[pos
] = '\0';
3295 /* Read in tag data */
3297 /* Find the start. */
3298 while (*src
!= '"' && *src
!= '\0')
3301 if (*src
== '\0' || *(++src
) == '\0')
3304 /* Read the data. */
3305 for (pos
= 0; pos
< size
; pos
++)
3312 dest
[pos
] = *(src
+1);
3332 if (!strcasecmp(tagstr
, current_tag
))
3339 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3341 struct index_entry idx
;
3342 char tag_data
[TAG_MAXLEN
+32];
3344 long masterfd
= (long)parameters
;
3345 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3353 logf("%d/%s", line_n
, buf
);
3354 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3356 logf("filename missing");
3361 idx_id
= find_index(tag_data
);
3364 logf("entry not found");
3368 if (!get_index(masterfd
, idx_id
, &idx
, false))
3370 logf("failed to retrieve index entry");
3374 /* Stop if tag has already been modified. */
3375 if (idx
.flag
& FLAG_DIRTYNUM
)
3378 logf("import: %s", tag_data
);
3380 idx
.flag
|= FLAG_DIRTYNUM
;
3381 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3385 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3386 tagcache_tag_to_str(import_tags
[i
])))
3391 data
= atoi(tag_data
);
3395 idx
.tag_seek
[import_tags
[i
]] = data
;
3397 if (import_tags
[i
] == tag_lastplayed
&& data
>= current_tcmh
.serial
)
3398 current_tcmh
.serial
= data
+ 1;
3399 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3400 current_tcmh
.commitid
= data
+ 1;
3403 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3406 bool tagcache_import_changelog(void)
3408 struct master_header myhdr
;
3409 struct tagcache_header tch
;
3412 char buf
[MAX(MAX_PATH
, 2048)];
3421 file
= get_user_file_path(TAGCACHE_FILE_CHANGELOG
,
3422 IS_FILE
|NEED_WRITE
, buf
, sizeof(buf
));
3423 clfd
= open(file
, O_RDONLY
);
3426 logf("failure to open changelog");
3430 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3438 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3440 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3441 parse_changelog_line
);
3446 if (filenametag_fd
>= 0)
3448 close(filenametag_fd
);
3449 filenametag_fd
= -1;
3454 update_master_header();
3459 #endif /* !__PCTOOL__ */
3461 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3463 struct master_header myhdr
;
3464 struct index_entry idx
;
3466 char buf
[MAX(TAG_MAXLEN
+32, MAX_PATH
)];
3474 if (!tagcache_search(tcs
, tag_filename
))
3477 /* Initialize the changelog */
3478 file
= get_user_file_path(TAGCACHE_FILE_CHANGELOG
, IS_FILE
| NEED_WRITE
,
3480 clfd
= open(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3483 logf("failure to open changelog");
3487 if (tcs
->masterfd
< 0)
3489 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3494 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3495 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3498 write(clfd
, "## Changelog version 1\n", 23);
3500 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3502 if (ecread_index_entry(tcs
->masterfd
, &idx
) != sizeof(struct index_entry
))
3504 logf("read error #9");
3505 tagcache_search_finish(tcs
);
3510 /* Skip until the entry found has been modified. */
3511 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3514 /* Skip deleted entries too. */
3515 if (idx
.flag
& FLAG_DELETED
)
3518 /* Now retrieve all tags. */
3519 for (j
= 0; j
< TAG_COUNT
; j
++)
3521 if (TAGCACHE_IS_NUMERIC(j
))
3523 snprintf(temp
, sizeof temp
, "%d", (int)idx
.tag_seek
[j
]);
3524 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3529 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3530 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3533 write(clfd
, "\n", 1);
3539 tagcache_search_finish(tcs
);
3544 static bool delete_entry(long idx_id
)
3549 struct index_entry idx
, myidx
;
3550 struct master_header myhdr
;
3551 char buf
[TAG_MAXLEN
+32];
3552 int in_use
[TAG_COUNT
];
3554 logf("delete_entry(): %ld", idx_id
);
3556 #ifdef HAVE_TC_RAMCACHE
3557 /* At first mark the entry removed from ram cache. */
3558 if (tc_stat
.ramcache
)
3559 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3562 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3565 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3566 if (ecread_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3568 logf("delete_entry(): read error");
3572 if (myidx
.flag
& FLAG_DELETED
)
3574 logf("delete_entry(): already deleted!");
3578 myidx
.flag
|= FLAG_DELETED
;
3579 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3580 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3582 logf("delete_entry(): write_error #1");
3586 /* Now check which tags are no longer in use (if any) */
3587 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3590 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3591 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3593 struct index_entry
*idxp
;
3595 #ifdef HAVE_TC_RAMCACHE
3596 /* Use RAM DB if available for greater speed */
3597 if (tc_stat
.ramcache
)
3598 idxp
= &hdr
->indices
[i
];
3602 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
3604 logf("delete_entry(): read error #2");
3610 if (idxp
->flag
& FLAG_DELETED
)
3613 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3615 if (TAGCACHE_IS_NUMERIC(tag
))
3618 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3623 /* Now delete all tags no longer in use. */
3624 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3626 struct tagcache_header tch
;
3627 int oldseek
= myidx
.tag_seek
[tag
];
3629 if (TAGCACHE_IS_NUMERIC(tag
))
3633 * Replace tag seek with a hash value of the field string data.
3634 * That way runtime statistics of moved or altered files can be
3637 #ifdef HAVE_TC_RAMCACHE
3638 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3640 struct tagfile_entry
*tfe
;
3641 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3643 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3644 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3645 myidx
.tag_seek
[tag
] = *seek
;
3650 struct tagfile_entry tfe
;
3652 /* Open the index file, which contains the tag names. */
3653 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3656 /* Skip the header block */
3657 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3658 if (ecread_tagfile_entry(fd
, &tfe
) != sizeof(struct tagfile_entry
))
3660 logf("delete_entry(): read error #3");
3664 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3666 logf("delete_entry(): read error #4");
3670 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3675 logf("in use: %d/%d", tag
, in_use
[tag
]);
3684 #ifdef HAVE_TC_RAMCACHE
3685 /* Delete from ram. */
3686 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3688 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3689 tagentry
->tag_data
[0] = '\0';
3693 /* Open the index file, which contains the tag names. */
3696 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3700 /* Skip the header block */
3701 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3703 /* Debug, print 10 first characters of the tag
3706 logf("TAG:%s", buf);
3707 lseek(fd, -10, SEEK_CUR);
3710 /* Write first data byte in tag as \0 */
3713 /* Now tag data has been removed */
3718 /* Write index entry back into master index. */
3719 lseek(masterfd
, sizeof(struct master_header
) +
3720 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3721 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3723 logf("delete_entry(): write_error #2");
3742 * Returns true if there is an event waiting in the queue
3743 * that requires the current operation to be aborted.
3745 static bool check_event_queue(void)
3747 struct queue_event ev
;
3749 if(!queue_peek(&tagcache_queue
, &ev
))
3756 case SYS_USB_CONNECTED
:
3764 #ifdef HAVE_TC_RAMCACHE
3765 static bool allocate_tagcache(void)
3767 struct master_header tcmh
;
3770 /* Load the header. */
3771 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3780 * Now calculate the required cache size plus
3781 * some extra space for alignment fixes.
3783 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3784 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3785 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3786 memset(hdr
, 0, sizeof(struct ramcache_header
));
3787 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3788 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3789 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3794 # ifdef HAVE_EEPROM_SETTINGS
3795 static bool tagcache_dumpload(void)
3797 struct statefile_header shdr
;
3798 char path
[MAX_PATH
];
3804 file
= get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
3805 path
, sizeof(path
));
3806 fd
= open(file
, O_RDONLY
);
3809 logf("no tagcache statedump");
3813 /* Check the statefile memory placement */
3814 hdr
= buffer_alloc(0);
3815 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3816 if (rc
!= sizeof(struct statefile_header
)
3817 /* || (long)hdr != (long)shdr.hdr */)
3819 logf("incorrect statefile");
3825 offpos
= (long)hdr
- (long)shdr
.hdr
;
3827 /* Lets allocate real memory and load it */
3828 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3829 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3832 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3834 logf("read failure!");
3839 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3841 /* Now fix the pointers */
3842 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3843 for (i
= 0; i
< TAG_COUNT
; i
++)
3844 hdr
->tags
[i
] += offpos
;
3849 static bool tagcache_dumpsave(void)
3851 struct statefile_header shdr
;
3852 char path
[MAX_PATH
];
3856 if (!tc_stat
.ramcache
)
3859 file
= get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
3860 path
, sizeof(path
));
3861 fd
= open(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3864 logf("failed to create a statedump");
3868 /* Create the header */
3870 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3871 write(fd
, &shdr
, sizeof(struct statefile_header
));
3873 /* And dump the data too */
3874 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3881 static bool load_tagcache(void)
3883 struct tagcache_header
*tch
;
3884 long bytesleft
= tc_stat
.ramcache_allocated
;
3885 struct index_entry
*idx
;
3887 char *p
, path
[MAX_PATH
];
3891 # ifdef HAVE_DIRCACHE
3892 while (dircache_is_initializing())
3895 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3898 logf("loading tagcache to ram...");
3900 file
= get_user_file_path(TAGCACHE_FILE_MASTER
,
3902 path
, sizeof(path
));
3903 fd
= open(file
, O_RDONLY
);
3906 logf("tagcache open failed");
3910 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3911 != sizeof(struct master_header
)
3912 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3914 logf("incorrect header");
3920 /* Load the master index table. */
3921 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3923 rc
= ecread_index_entry(fd
, idx
);
3924 if (rc
!= sizeof(struct index_entry
))
3926 logf("read error #10");
3931 bytesleft
-= sizeof(struct index_entry
);
3932 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3934 logf("too big tagcache.");
3944 /* Load the tags. */
3946 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3948 struct tagfile_entry
*fe
;
3949 char buf
[TAG_MAXLEN
+32];
3951 if (TAGCACHE_IS_NUMERIC(tag
))
3954 //p = ((void *)p+1);
3955 p
= (char *)((long)p
& ~0x03) + 0x04;
3958 /* Check the header. */
3959 tch
= (struct tagcache_header
*)p
;
3960 p
+= sizeof(struct tagcache_header
);
3962 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3965 for (hdr
->entry_count
[tag
] = 0;
3966 hdr
->entry_count
[tag
] < tch
->entry_count
;
3967 hdr
->entry_count
[tag
]++)
3971 if (do_timed_yield())
3973 /* Abort if we got a critical event in queue */
3974 if (check_event_queue())
3978 fe
= (struct tagfile_entry
*)p
;
3979 pos
= lseek(fd
, 0, SEEK_CUR
);
3980 rc
= ecread_tagfile_entry(fd
, fe
);
3981 if (rc
!= sizeof(struct tagfile_entry
))
3983 /* End of lookup table. */
3984 logf("read error #11");
3989 /* We have a special handling for the filename tags. */
3990 if (tag
== tag_filename
)
3992 # ifdef HAVE_DIRCACHE
3993 const struct dircache_entry
*dc
;
3996 // FIXME: This is wrong!
3997 // idx = &hdr->indices[hdr->entry_count[i]];
3998 idx
= &hdr
->indices
[fe
->idx_id
];
4000 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
4004 logf("TAG:%s", buf
);
4005 logf("too long filename");
4010 rc
= read(fd
, buf
, fe
->tag_length
);
4011 if (rc
!= fe
->tag_length
)
4013 logf("read error #12");
4018 /* Check if the entry has already been removed */
4019 if (idx
->flag
& FLAG_DELETED
)
4022 /* This flag must not be used yet. */
4023 if (idx
->flag
& FLAG_DIRCACHE
)
4025 logf("internal error!");
4030 if (idx
->tag_seek
[tag
] != pos
)
4032 logf("corrupt data structures!");
4037 # ifdef HAVE_DIRCACHE
4038 if (dircache_is_enabled())
4040 dc
= dircache_get_entry_ptr(buf
);
4043 logf("Entry no longer valid.");
4045 if (global_settings
.tagcache_autoupdate
)
4046 delete_entry(fe
->idx_id
);
4050 idx
->flag
|= FLAG_DIRCACHE
;
4051 idx
->tag_seek
[tag_filename
] = (long)dc
;
4056 /* This will be very slow unless dircache is enabled
4057 or target is flash based, but do it anyway for
4059 /* Check if entry has been removed. */
4060 if (global_settings
.tagcache_autoupdate
)
4062 if (!file_exists(buf
))
4064 logf("Entry no longer valid.");
4066 delete_entry(fe
->idx_id
);
4075 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
4078 logf("too big tagcache #2");
4079 logf("tl: %ld", fe
->tag_length
);
4080 logf("bl: %ld", bytesleft
);
4086 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
4089 if (rc
!= fe
->tag_length
)
4091 logf("read error #13");
4092 logf("rc=0x%04x", rc
); // 0x431
4093 logf("len=0x%04lx", fe
->tag_length
); // 0x4000
4094 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
4095 logf("tag=0x%02x", tag
); // 0x00
4103 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4104 logf("tagcache loaded into ram!");
4108 #endif /* HAVE_TC_RAMCACHE */
4110 static bool check_deleted_files(void)
4113 char buf
[TAG_MAXLEN
+32], path
[MAX_PATH
];
4115 struct tagfile_entry tfe
;
4117 logf("reverse scan...");
4118 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4119 file
= get_user_file_path(buf
, IS_FILE
| NEED_WRITE
, path
, sizeof(path
));
4120 fd
= open(file
, O_RDONLY
);
4124 logf("%s open fail", buf
);
4128 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4129 while (ecread_tagfile_entry(fd
, &tfe
) == sizeof(struct tagfile_entry
)
4131 && !check_event_queue()
4135 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4137 logf("too long tag");
4142 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4144 logf("read error #14");
4149 /* Check if the file has already deleted from the db. */
4153 /* Now check if the file exists. */
4154 if (!file_exists(buf
))
4156 logf("Entry no longer valid.");
4157 logf("-> %s / %ld", buf
, tfe
.tag_length
);
4158 delete_entry(tfe
.idx_id
);
4170 /* Note that this function must not be inlined, otherwise the whole point
4171 * of having the code in a separate function is lost.
4173 static void __attribute__ ((noinline
)) check_ignore(const char *dirname
,
4174 int *ignore
, int *unignore
)
4176 char newpath
[MAX_PATH
];
4178 /* check for a database.ignore file */
4179 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4180 *ignore
= file_exists(newpath
);
4181 /* check for a database.unignore file */
4182 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4183 *unignore
= file_exists(newpath
);
4187 static bool check_dir(const char *dirname
, int add_files
)
4191 int success
= false;
4192 int ignore
, unignore
;
4194 dir
= opendir(dirname
);
4197 logf("tagcache: opendir(%s) failed", dirname
);
4201 /* check for a database.ignore and database.unignore */
4202 check_ignore(dirname
, &ignore
, &unignore
);
4204 /* don't do anything if both ignore and unignore are there */
4205 if (ignore
!= unignore
)
4206 add_files
= unignore
;
4208 /* Recursively scan the dir. */
4212 while (!check_event_queue())
4215 struct dirent
*entry
;
4217 entry
= readdir(dir
);
4225 if (!strcmp((char *)entry
->d_name
, ".") ||
4226 !strcmp((char *)entry
->d_name
, ".."))
4231 len
= strlen(curpath
);
4232 snprintf(&curpath
[len
], sizeof(curpath
) - len
, "/%s",
4235 processed_dir_count
++;
4236 if (entry
->attribute
& ATTR_DIRECTORY
)
4237 check_dir(curpath
, add_files
);
4240 tc_stat
.curentry
= curpath
;
4242 /* Add a new entry to the temporary db file. */
4243 add_tagcache(curpath
, (entry
->wrtdate
<< 16) | entry
->wrttime
4244 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4245 , dir
->internal_entry
4249 /* Wait until current path for debug screen is read and unset. */
4250 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4253 tc_stat
.curentry
= NULL
;
4256 curpath
[len
] = '\0';
4264 void tagcache_screensync_event(void)
4266 tc_stat
.curentry
= NULL
;
4269 void tagcache_screensync_enable(bool state
)
4271 tc_stat
.syncscreen
= state
;
4274 void tagcache_build(const char *path
)
4276 struct tagcache_header header
;
4283 total_entry_count
= 0;
4284 processed_dir_count
= 0;
4286 #ifdef HAVE_DIRCACHE
4287 while (dircache_is_initializing())
4291 logf("updating tagcache");
4293 file
= get_user_file_path(TAGCACHE_FILE_TEMP
,
4294 IS_FILE
|NEED_WRITE
, buf
, sizeof(buf
));
4297 if (file_exists(file
))
4299 logf("skipping, cache already waiting for commit");
4303 cachefd
= open(file
, O_RDWR
| O_CREAT
| O_TRUNC
, 0666);
4306 logf("master file open failed: %s", file
);
4310 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4314 logf("Scanning files...");
4315 /* Scan for new files. */
4316 memset(&header
, 0, sizeof(struct tagcache_header
));
4317 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4319 if (strcmp("/", path
) != 0)
4320 strcpy(curpath
, path
);
4321 ret
= check_dir(path
, true);
4323 /* Write the header. */
4324 header
.magic
= TAGCACHE_MAGIC
;
4325 header
.datasize
= data_size
;
4326 header
.entry_count
= total_entry_count
;
4327 lseek(cachefd
, 0, SEEK_SET
);
4328 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4331 if (filenametag_fd
>= 0)
4333 close(filenametag_fd
);
4334 filenametag_fd
= -1;
4344 /* Commit changes to the database. */
4351 logf("tagcache built!");
4357 #ifdef HAVE_TC_RAMCACHE
4360 /* Import runtime statistics if we just initialized the db. */
4361 if (hdr
->h
.serial
== 0)
4362 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4369 #ifdef HAVE_TC_RAMCACHE
4370 static void load_ramcache(void)
4377 /* At first we should load the cache (if exists). */
4378 tc_stat
.ramcache
= load_tagcache();
4380 if (!tc_stat
.ramcache
)
4382 /* If loading failed, it must indicate some problem with the db
4383 * so disable it entirely to prevent further issues. */
4384 tc_stat
.ready
= false;
4391 void tagcache_unload_ramcache(void)
4393 tc_stat
.ramcache
= false;
4394 /* Just to make sure there is no statefile present. */
4397 char path
[MAX_PATH
];
4398 remove(get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
4399 path
, sizeof(path
)));
4405 static void tagcache_thread(void)
4407 struct queue_event ev
;
4408 bool check_done
= false;
4409 char path
[MAX_PATH
];
4411 /* If the previous cache build/update was interrupted, commit
4412 * the changes first in foreground. */
4418 #ifdef HAVE_TC_RAMCACHE
4419 # ifdef HAVE_EEPROM_SETTINGS
4420 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
4421 && global_settings
.tagcache_ram
)
4423 check_done
= tagcache_dumpload();
4426 remove(get_user_file_path(TAGCACHE_STATEFILE
, IS_FILE
| NEED_WRITE
,
4430 /* Allocate space for the tagcache if found on disk. */
4431 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4432 allocate_tagcache();
4436 tc_stat
.initialized
= true;
4438 /* Don't delay bootup with the header check but do it on background. */
4442 tc_stat
.ready
= check_all_headers();
4443 tc_stat
.readyvalid
= true;
4448 run_command_queue(false);
4450 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4454 case Q_IMPORT_CHANGELOG
:
4455 tagcache_import_changelog();
4460 remove(get_user_file_path(TAGCACHE_FILE_TEMP
,
4461 IS_FILE
|NEED_WRITE
, path
, sizeof(path
)));
4462 tagcache_build("/");
4466 tagcache_build("/");
4467 #ifdef HAVE_TC_RAMCACHE
4470 check_deleted_files();
4476 if (check_done
|| !tc_stat
.ready
)
4479 #ifdef HAVE_TC_RAMCACHE
4480 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4483 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4484 tagcache_build("/");
4488 if (global_settings
.tagcache_autoupdate
)
4490 tagcache_build("/");
4492 /* This will be very slow unless dircache is enabled
4493 or target is flash based, but do it anyway for
4495 check_deleted_files();
4498 logf("tagcache check done");
4509 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4510 case SYS_USB_CONNECTED
:
4511 logf("USB: TagCache");
4512 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4513 usb_wait_for_disconnect(&tagcache_queue
);
4520 bool tagcache_prepare_shutdown(void)
4522 if (tagcache_get_commit_step() > 0)
4525 tagcache_stop_scan();
4526 while (read_lock
|| write_lock
)
4532 void tagcache_shutdown(void)
4534 /* Flush the command queue. */
4535 run_command_queue(true);
4537 #ifdef HAVE_EEPROM_SETTINGS
4538 if (tc_stat
.ramcache
)
4539 tagcache_dumpsave();
4543 static int get_progress(void)
4545 int total_count
= -1;
4547 #ifdef HAVE_DIRCACHE
4548 if (dircache_is_enabled())
4550 total_count
= dircache_get_entry_count();
4554 #ifdef HAVE_TC_RAMCACHE
4556 if (hdr
&& tc_stat
.ramcache
)
4557 total_count
= hdr
->h
.tch
.entry_count
;
4561 if (total_count
< 0)
4564 return processed_dir_count
* 100 / total_count
;
4567 struct tagcache_stat
* tagcache_get_stat(void)
4569 tc_stat
.progress
= get_progress();
4570 tc_stat
.processed_entries
= processed_dir_count
;
4575 void tagcache_start_scan(void)
4577 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4580 bool tagcache_update(void)
4585 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4589 bool tagcache_rebuild()
4591 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4595 void tagcache_stop_scan(void)
4597 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4600 #ifdef HAVE_TC_RAMCACHE
4601 bool tagcache_is_ramcache(void)
4603 return tc_stat
.ramcache
;
4607 #endif /* !__PCTOOL__ */
4610 void tagcache_init(void)
4612 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4613 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4614 filenametag_fd
= -1;
4615 write_lock
= read_lock
= 0;
4618 mutex_init(&command_queue_mutex
);
4619 queue_init(&tagcache_queue
, true);
4620 create_thread(tagcache_thread
, tagcache_stack
,
4621 sizeof(tagcache_stack
), 0, tagcache_thread_name
4622 IF_PRIO(, PRIORITY_BACKGROUND
)
4625 tc_stat
.initialized
= true;
4629 tc_stat
.ready
= check_all_headers();
4634 void tagcache_reverse_scan(void)
4636 logf("Checking for deleted files");
4637 check_deleted_files();
4641 bool tagcache_is_initialized(void)
4643 return tc_stat
.initialized
;
4645 bool tagcache_is_usable(void)
4647 return tc_stat
.initialized
&& tc_stat
.ready
;
4649 int tagcache_get_commit_step(void)
4651 return tc_stat
.commit_step
;
4653 int tagcache_get_max_commit_step(void)
4655 return (int)(SORTED_TAGS_COUNT
)+1;