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"
78 #include "filefuncs.h"
83 #include "eeprom_settings.h"
87 #define yield() do { } while(0)
88 #define sim_sleep(timeout) do { } while(0)
89 #define do_timed_yield() do { } while(0)
93 /* Tag Cache thread. */
94 static struct event_queue tagcache_queue
;
95 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
96 static const char tagcache_thread_name
[] = "tagcache";
99 /* Previous path when scanning directory tree recursively. */
100 static char curpath
[TAG_MAXLEN
+32];
102 /* Used when removing duplicates. */
103 static char *tempbuf
; /* Allocated when needed. */
104 static long tempbufidx
; /* Current location in buffer. */
105 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
106 static long tempbuf_left
; /* Buffer space left. */
107 static long tempbuf_pos
;
109 #define SORTED_TAGS_COUNT 8
110 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
111 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
112 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
113 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
114 /* Tags we want to get sorted (loaded to the tempbuf). */
115 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
116 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
117 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
119 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
120 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
121 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
122 (1LU << tag_albumartist) | (1LU << tag_grouping))
124 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
125 static const char *tags_str
[] = { "artist", "album", "genre", "title",
126 "filename", "composer", "comment", "albumartist", "grouping", "year",
127 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
128 "playtime", "lastplayed", "commitid", "mtime" };
130 /* Status information of the tagcache. */
131 static struct tagcache_stat tc_stat
;
133 /* Queue commands. */
134 enum tagcache_queue
{
141 /* Internal tagcache command queue. */
142 CMD_UPDATE_MASTER_HEADER
,
146 struct tagcache_command_entry
{
154 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
155 static volatile int command_queue_widx
= 0;
156 static volatile int command_queue_ridx
= 0;
157 static struct mutex command_queue_mutex
;
160 /* Tag database structures. */
162 /* Variable-length tag entry in tag files. */
163 struct tagfile_entry
{
164 int32_t tag_length
; /* Length of the data in bytes including '\0' */
165 int32_t idx_id
; /* Corresponding entry location in index file of not unique tags */
166 char tag_data
[0]; /* Begin of the tag data */
169 /* Fixed-size tag entry in master db index. */
171 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
172 int32_t flag
; /* Status flags */
175 /* Header is the same in every file. */
176 struct tagcache_header
{
177 int32_t magic
; /* Header version number */
178 int32_t datasize
; /* Data size in bytes */
179 int32_t entry_count
; /* Number of entries in this file */
182 struct master_header
{
183 struct tagcache_header tch
;
184 int32_t serial
; /* Increasing counting number */
185 int32_t commitid
; /* Number of commits so far */
189 /* For the endianess correction */
190 static const char *tagfile_entry_ec
= "ll";
192 Note: This should be (1 + TAG_COUNT) amount of l's.
194 static const char *index_entry_ec
= "lllllllllllllllllllll";
196 static const char *tagcache_header_ec
= "lll";
197 static const char *master_header_ec
= "llllll";
199 static struct master_header current_tcmh
;
201 #ifdef HAVE_TC_RAMCACHE
202 /* Header is created when loading database to ram. */
203 struct ramcache_header
{
204 struct master_header h
; /* Header from the master index */
205 struct index_entry
*indices
; /* Master index file content */
206 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
207 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
210 # ifdef HAVE_EEPROM_SETTINGS
211 struct statefile_header
{
212 struct ramcache_header
*hdr
;
213 struct tagcache_stat tc_stat
;
217 /* Pointer to allocated ramcache_header */
218 static struct ramcache_header
*hdr
;
222 * Full tag entries stored in a temporary file waiting
223 * for commit to the cache. */
224 struct temp_file_entry
{
225 long tag_offset
[TAG_COUNT
];
226 short tag_length
[TAG_COUNT
];
232 struct tempbuf_id_list
{
234 struct tempbuf_id_list
*next
;
237 struct tempbuf_searchidx
{
241 struct tempbuf_id_list idlist
;
244 /* Lookup buffer for fixing messed up index while after sorting. */
245 static long commit_entry_count
;
246 static long lookup_buffer_depth
;
247 static struct tempbuf_searchidx
**lookup
;
249 /* Used when building the temporary file. */
250 static int cachefd
= -1, filenametag_fd
;
251 static int total_entry_count
= 0;
252 static int data_size
= 0;
253 static int processed_dir_count
;
255 /* Thread safe locking */
256 static volatile int write_lock
;
257 static volatile int read_lock
;
259 static bool delete_entry(long idx_id
);
261 const char* tagcache_tag_to_str(int tag
)
263 return tags_str
[tag
];
266 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
267 static ssize_t
ecread_tagfile_entry(int fd
, struct tagfile_entry
*buf
)
269 return ecread(fd
, buf
, 1, tagfile_entry_ec
, tc_stat
.econ
);
272 static ssize_t
ecread_index_entry(int fd
, struct index_entry
*buf
)
274 return ecread(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
277 static ssize_t
ecwrite_index_entry(int fd
, struct index_entry
*buf
)
279 return ecwrite(fd
, buf
, 1, index_entry_ec
, tc_stat
.econ
);
284 * Returns true if specified flag is still present, i.e., dircache
285 * has not been reloaded.
287 static bool is_dircache_intact(void)
289 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
293 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
299 if (TAGCACHE_IS_NUMERIC(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
302 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
304 fd
= open(buf
, write
? O_RDWR
: O_RDONLY
);
307 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
308 tc_stat
.ready
= false;
312 /* Check the header. */
313 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
314 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
316 logf("header error");
317 tc_stat
.ready
= false;
325 static int open_master_fd(struct master_header
*hdr
, bool write
)
330 fd
= open(TAGCACHE_FILE_MASTER
, write
? O_RDWR
: O_RDONLY
);
333 logf("master file open failed for R/W");
334 tc_stat
.ready
= false;
338 tc_stat
.econ
= false;
340 /* Check the header. */
341 rc
= read(fd
, hdr
, sizeof(struct master_header
));
342 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
348 /* Trying to read again, this time with endianess correction enabled. */
349 lseek(fd
, 0, SEEK_SET
);
351 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
352 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
354 logf("header error");
355 tc_stat
.ready
= false;
366 static bool do_timed_yield(void)
368 /* Sorting can lock up for quite a while, so yield occasionally */
369 static long wakeup_tick
= 0;
370 if (TIME_AFTER(current_tick
, wakeup_tick
))
372 wakeup_tick
= current_tick
+ (HZ
/4);
380 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
381 static long find_entry_ram(const char *filename
,
382 const struct dircache_entry
*dc
)
384 static long last_pos
= 0;
387 /* Check if tagcache is loaded into ram. */
388 if (!tc_stat
.ramcache
)
392 dc
= dircache_get_entry_ptr(filename
);
396 logf("tagcache: file not found.");
407 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
409 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
411 last_pos
= MAX(0, i
- 3);
428 static long find_entry_disk(const char *filename
, bool localfd
)
430 struct tagcache_header tch
;
431 static long last_pos
= -1;
432 long pos_history
[POS_HISTORY_COUNT
];
433 long pos_history_idx
= 0;
435 struct tagfile_entry tfe
;
437 char buf
[TAG_MAXLEN
+32];
445 if (fd
< 0 || localfd
)
448 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
455 lseek(fd
, last_pos
, SEEK_SET
);
457 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
461 pos
= lseek(fd
, 0, SEEK_CUR
);
462 for (i
= pos_history_idx
-1; i
>= 0; i
--)
463 pos_history
[i
+1] = pos_history
[i
];
464 pos_history
[0] = pos
;
466 if (ecread_tagfile_entry(fd
, &tfe
)
467 != sizeof(struct tagfile_entry
))
472 if (tfe
.tag_length
>= (long)sizeof(buf
))
474 logf("too long tag #1");
482 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
484 logf("read error #2");
492 if (!strcasecmp(filename
, buf
))
494 last_pos
= pos_history
[pos_history_idx
];
499 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
513 if (fd
!= filenametag_fd
|| localfd
)
518 if (fd
!= filenametag_fd
|| localfd
)
524 static int find_index(const char *filename
)
528 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
529 if (tc_stat
.ramcache
&& is_dircache_intact())
530 idx_id
= find_entry_ram(filename
, NULL
);
534 idx_id
= find_entry_disk(filename
, true);
539 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
546 idx_id
= find_index(filename
);
550 if (!tagcache_search(tcs
, tag_filename
))
553 tcs
->entry_count
= 0;
554 tcs
->idx_id
= idx_id
;
559 static bool get_index(int masterfd
, int idxid
,
560 struct index_entry
*idx
, bool use_ram
)
562 bool localfd
= false;
566 logf("Incorrect idxid: %d", idxid
);
570 #ifdef HAVE_TC_RAMCACHE
571 if (tc_stat
.ramcache
&& use_ram
)
573 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
576 # ifdef HAVE_DIRCACHE
577 if (!(hdr
->indices
[idxid
].flag
& FLAG_DIRCACHE
)
578 || is_dircache_intact())
581 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
591 struct master_header tcmh
;
594 masterfd
= open_master_fd(&tcmh
, false);
599 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
600 + sizeof(struct master_header
), SEEK_SET
);
601 if (ecread_index_entry(masterfd
, idx
)
602 != sizeof(struct index_entry
))
604 logf("read error #3");
614 if (idx
->flag
& FLAG_DELETED
)
622 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
624 /* We need to exclude all memory only flags & tags when writing to disk. */
625 if (idx
->flag
& FLAG_DIRCACHE
)
627 logf("memory only flags!");
631 #ifdef HAVE_TC_RAMCACHE
632 /* Only update numeric data. Writing the whole index to RAM by memcpy
633 * destroys dircache pointers!
635 if (tc_stat
.ramcache
)
638 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
640 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
642 if (TAGCACHE_IS_NUMERIC(tag
))
644 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
648 /* Don't touch the dircache flag or attributes. */
649 idx_ram
->flag
= (idx
->flag
& 0x0000ffff)
650 | (idx_ram
->flag
& (0xffff0000 | FLAG_DIRCACHE
));
654 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
655 + sizeof(struct master_header
), SEEK_SET
);
656 if (ecwrite_index_entry(masterfd
, idx
) != sizeof(struct index_entry
))
658 logf("write error #3");
659 logf("idxid: %d", idxid
);
666 #endif /* !__PCTOOL__ */
668 static bool open_files(struct tagcache_search
*tcs
, int tag
)
670 if (tcs
->idxfd
[tag
] < 0)
674 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
675 tcs
->idxfd
[tag
] = open(fn
, O_RDONLY
);
678 if (tcs
->idxfd
[tag
] < 0)
680 logf("File not open!");
687 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
688 int tag
, char *buf
, long size
)
690 struct tagfile_entry tfe
;
695 if (TAGCACHE_IS_NUMERIC(tag
))
698 seek
= idx
->tag_seek
[tag
];
701 logf("Retrieve failed");
705 #ifdef HAVE_TC_RAMCACHE
708 struct tagfile_entry
*ep
;
710 # ifdef HAVE_DIRCACHE
711 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
712 && is_dircache_intact())
714 dircache_copy_path((struct dircache_entry
*)seek
,
720 if (tag
!= tag_filename
)
722 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
723 strlcpy(buf
, ep
->tag_data
, size
);
730 if (!open_files(tcs
, tag
))
733 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
734 if (ecread_tagfile_entry(tcs
->idxfd
[tag
], &tfe
)
735 != sizeof(struct tagfile_entry
))
737 logf("read error #5");
741 if (tfe
.tag_length
>= size
)
743 logf("too small buffer");
747 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
750 logf("read error #6");
754 buf
[tfe
.tag_length
] = '\0';
759 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
761 static long read_numeric_tag(int tag
, int idx_id
, const struct index_entry
*idx
)
764 if (! COMMAND_QUEUE_IS_EMPTY
)
766 /* Attempt to find tag data through store-to-load forwarding in
770 mutex_lock(&command_queue_mutex
);
772 int ridx
= command_queue_widx
;
774 while (ridx
!= command_queue_ridx
)
777 ridx
= TAGCACHE_COMMAND_QUEUE_LENGTH
- 1;
779 if (command_queue
[ridx
].command
== CMD_UPDATE_NUMERIC
780 && command_queue
[ridx
].idx_id
== idx_id
781 && command_queue
[ridx
].tag
== tag
)
783 result
= command_queue
[ridx
].data
;
788 mutex_unlock(&command_queue_mutex
);
792 logf("read_numeric_tag: "
793 "Recovered tag %d value %lX from write queue",
800 return idx
->tag_seek
[tag
];
804 static long check_virtual_tags(int tag
, int idx_id
,
805 const struct index_entry
*idx
)
811 case tag_virt_length_sec
:
812 data
= (read_numeric_tag(tag_length
, idx_id
, idx
)/1000) % 60;
815 case tag_virt_length_min
:
816 data
= (read_numeric_tag(tag_length
, idx_id
, idx
)/1000) / 60;
819 case tag_virt_playtime_sec
:
820 data
= (read_numeric_tag(tag_playtime
, idx_id
, idx
)/1000) % 60;
823 case tag_virt_playtime_min
:
824 data
= (read_numeric_tag(tag_playtime
, idx_id
, idx
)/1000) / 60;
827 case tag_virt_autoscore
:
828 if (read_numeric_tag(tag_length
, idx_id
, idx
) == 0
829 || read_numeric_tag(tag_playcount
, idx_id
, idx
) == 0)
835 /* A straight calculus gives:
836 autoscore = 100 * playtime / length / playcout (1)
837 Now, consider the euclidian division of playtime by length:
838 playtime = alpha * length + beta
842 autoscore = 100 * (alpha / playcout + beta / length / playcount)
843 Both terms should be small enough to avoid any overflow
845 data
= 100 * (read_numeric_tag(tag_playtime
, idx_id
, idx
)
846 / read_numeric_tag(tag_length
, idx_id
, idx
))
847 + (100 * (read_numeric_tag(tag_playtime
, idx_id
, idx
)
848 % read_numeric_tag(tag_length
, idx_id
, idx
)))
849 / read_numeric_tag(tag_length
, idx_id
, idx
);
850 data
/= read_numeric_tag(tag_playcount
, idx_id
, idx
);
854 /* How many commits before the file has been added to the DB. */
855 case tag_virt_entryage
:
856 data
= current_tcmh
.commitid
857 - read_numeric_tag(tag_commitid
, idx_id
, idx
) - 1;
861 data
= read_numeric_tag(tag
, idx_id
, idx
);
867 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
869 struct index_entry idx
;
874 if (!TAGCACHE_IS_NUMERIC(tag
))
877 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
880 return check_virtual_tags(tag
, tcs
->idx_id
, &idx
);
883 inline static bool str_ends_with(const char *str1
, const char *str2
)
885 int str_len
= strlen(str1
);
886 int clause_len
= strlen(str2
);
888 if (clause_len
> str_len
)
891 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
894 inline static bool str_oneof(const char *str
, const char *list
)
897 int l
, len
= strlen(str
);
901 sep
= strchr(list
, '|');
902 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
903 if ((l
==len
) && !strncasecmp(str
, list
, len
))
905 list
+= sep
? l
+ 1 : l
;
911 static bool check_against_clause(long numeric
, const char *str
,
912 const struct tagcache_search_clause
*clause
)
916 switch (clause
->type
)
919 return numeric
== clause
->numeric_data
;
921 return numeric
!= clause
->numeric_data
;
923 return numeric
> clause
->numeric_data
;
925 return numeric
>= clause
->numeric_data
;
927 return numeric
< clause
->numeric_data
;
929 return numeric
<= clause
->numeric_data
;
931 logf("Incorrect numeric tag: %d", clause
->type
);
936 switch (clause
->type
)
939 return !strcasecmp(clause
->str
, str
);
941 return strcasecmp(clause
->str
, str
);
943 return 0>strcasecmp(clause
->str
, str
);
945 return 0>=strcasecmp(clause
->str
, str
);
947 return 0<strcasecmp(clause
->str
, str
);
949 return 0<=strcasecmp(clause
->str
, str
);
950 case clause_contains
:
951 return (strcasestr(str
, clause
->str
) != NULL
);
952 case clause_not_contains
:
953 return (strcasestr(str
, clause
->str
) == NULL
);
954 case clause_begins_with
:
955 return (strcasestr(str
, clause
->str
) == str
);
956 case clause_not_begins_with
:
957 return (strcasestr(str
, clause
->str
) != str
);
958 case clause_ends_with
:
959 return str_ends_with(str
, clause
->str
);
960 case clause_not_ends_with
:
961 return !str_ends_with(str
, clause
->str
);
963 return str_oneof(str
, clause
->str
);
966 logf("Incorrect tag: %d", clause
->type
);
973 static bool check_clauses(struct tagcache_search
*tcs
,
974 struct index_entry
*idx
,
975 struct tagcache_search_clause
**clause
, int count
)
979 #ifdef HAVE_TC_RAMCACHE
982 /* Go through all conditional clauses. */
983 for (i
= 0; i
< count
; i
++)
985 struct tagfile_entry
*tfe
;
990 seek
= check_virtual_tags(clause
[i
]->tag
, tcs
->idx_id
, idx
);
992 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
994 if (clause
[i
]->tag
== tag_filename
)
996 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
1001 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
1002 str
= tfe
->tag_data
;
1006 if (!check_against_clause(seek
, str
, clause
[i
]))
1013 /* Check for conditions. */
1014 for (i
= 0; i
< count
; i
++)
1016 struct tagfile_entry tfe
;
1020 seek
= check_virtual_tags(clause
[i
]->tag
, tcs
->idx_id
, idx
);
1022 memset(str
, 0, sizeof str
);
1023 if (!TAGCACHE_IS_NUMERIC(clause
[i
]->tag
))
1025 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
1026 lseek(fd
, seek
, SEEK_SET
);
1027 ecread_tagfile_entry(fd
, &tfe
);
1028 if (tfe
.tag_length
>= (int)sizeof(str
))
1030 logf("Too long tag read!");
1034 read(fd
, str
, tfe
.tag_length
);
1036 /* Check if entry has been deleted. */
1041 if (!check_against_clause(seek
, str
, clause
[i
]))
1049 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
1050 struct tagcache_search_clause
**clause
, int count
)
1052 struct index_entry idx
;
1057 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
1060 return check_clauses(tcs
, &idx
, clause
, count
);
1063 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1067 /* If uniq buffer is not defined we must return true for search to work. */
1068 if (tcs
->unique_list
== NULL
|| (!TAGCACHE_IS_UNIQUE(tcs
->type
)
1069 && !TAGCACHE_IS_NUMERIC(tcs
->type
)))
1074 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1076 /* Return false if entry is found. */
1077 if (tcs
->unique_list
[i
] == id
)
1081 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1083 tcs
->unique_list
[i
] = id
;
1084 tcs
->unique_list_count
++;
1090 static bool build_lookup_list(struct tagcache_search
*tcs
)
1092 struct index_entry entry
;
1095 tcs
->seek_list_count
= 0;
1097 #ifdef HAVE_TC_RAMCACHE
1099 # ifdef HAVE_DIRCACHE
1100 && (tcs
->type
!= tag_filename
|| is_dircache_intact())
1104 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
1106 struct tagcache_seeklist_entry
*seeklist
;
1107 struct index_entry
*idx
= &hdr
->indices
[i
];
1108 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1111 /* Skip deleted files. */
1112 if (idx
->flag
& FLAG_DELETED
)
1115 /* Go through all filters.. */
1116 for (j
= 0; j
< tcs
->filter_count
; j
++)
1118 if (idx
->tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1124 if (j
< tcs
->filter_count
)
1127 /* Check for conditions. */
1128 if (!check_clauses(tcs
, idx
, tcs
->clause
, tcs
->clause_count
))
1131 /* Add to the seek list if not already in uniq buffer. */
1132 if (!add_uniqbuf(tcs
, idx
->tag_seek
[tcs
->type
]))
1136 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1137 seeklist
->seek
= idx
->tag_seek
[tcs
->type
];
1138 seeklist
->flag
= idx
->flag
;
1139 seeklist
->idx_id
= i
;
1140 tcs
->seek_list_count
++;
1145 return tcs
->seek_list_count
> 0;
1149 if (tcs
->masterfd
< 0)
1151 struct master_header tcmh
;
1152 tcs
->masterfd
= open_master_fd(&tcmh
, false);
1155 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1156 sizeof(struct master_header
), SEEK_SET
);
1158 while (ecread_index_entry(tcs
->masterfd
, &entry
)
1159 == sizeof(struct index_entry
))
1161 struct tagcache_seeklist_entry
*seeklist
;
1163 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1169 /* Check if entry has been deleted. */
1170 if (entry
.flag
& FLAG_DELETED
)
1173 /* Go through all filters.. */
1174 for (j
= 0; j
< tcs
->filter_count
; j
++)
1176 if (entry
.tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1180 if (j
< tcs
->filter_count
)
1183 /* Check for conditions. */
1184 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1187 /* Add to the seek list if not already in uniq buffer. */
1188 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1192 seeklist
= &tcs
->seeklist
[tcs
->seek_list_count
];
1193 seeklist
->seek
= entry
.tag_seek
[tcs
->type
];
1194 seeklist
->flag
= entry
.flag
;
1195 seeklist
->idx_id
= i
;
1196 tcs
->seek_list_count
++;
1201 return tcs
->seek_list_count
> 0;
1205 static void remove_files(void)
1210 tc_stat
.ready
= false;
1211 tc_stat
.ramcache
= false;
1212 tc_stat
.econ
= false;
1213 remove(TAGCACHE_FILE_MASTER
);
1214 for (i
= 0; i
< TAG_COUNT
; i
++)
1216 if (TAGCACHE_IS_NUMERIC(i
))
1219 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1225 static bool check_all_headers(void)
1227 struct master_header myhdr
;
1228 struct tagcache_header tch
;
1232 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1238 logf("tagcache is dirty!");
1242 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1244 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1246 if (TAGCACHE_IS_NUMERIC(tag
))
1249 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1258 bool tagcache_is_busy(void)
1260 return read_lock
|| write_lock
;
1263 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1265 struct tagcache_header tag_hdr
;
1266 struct master_header master_hdr
;
1272 memset(tcs
, 0, sizeof(struct tagcache_search
));
1273 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1276 tcs
->position
= sizeof(struct tagcache_header
);
1279 tcs
->list_position
= 0;
1280 tcs
->seek_list_count
= 0;
1281 tcs
->filter_count
= 0;
1284 for (i
= 0; i
< TAG_COUNT
; i
++)
1287 #ifndef HAVE_TC_RAMCACHE
1288 tcs
->ramsearch
= false;
1290 tcs
->ramsearch
= tc_stat
.ramcache
;
1293 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1298 /* Always open as R/W so we can pass tcs to functions that modify data also
1299 * without failing. */
1300 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1301 if (tcs
->masterfd
< 0)
1304 if (!TAGCACHE_IS_NUMERIC(tcs
->type
))
1306 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1307 if (tcs
->idxfd
[tcs
->type
] < 0)
1310 tcs
->entry_count
= tag_hdr
.entry_count
;
1314 tcs
->entry_count
= master_hdr
.tch
.entry_count
;
1319 tcs
->initialized
= true;
1325 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1326 void *buffer
, long length
)
1328 tcs
->unique_list
= (unsigned long *)buffer
;
1329 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1330 tcs
->unique_list_count
= 0;
1333 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1336 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1339 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag
))
1342 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1343 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1344 tcs
->filter_count
++;
1349 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1350 struct tagcache_search_clause
*clause
)
1354 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1356 logf("Too many clauses");
1360 /* Check if there is already a similar filter in present (filters are
1361 * much faster than clauses).
1363 for (i
= 0; i
< tcs
->filter_count
; i
++)
1365 if (tcs
->filter_tag
[i
] == clause
->tag
)
1369 if (!TAGCACHE_IS_NUMERIC(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1373 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1374 tcs
->idxfd
[clause
->tag
] = open(buf
, O_RDONLY
);
1377 tcs
->clause
[tcs
->clause_count
] = clause
;
1378 tcs
->clause_count
++;
1383 static bool get_next(struct tagcache_search
*tcs
)
1385 static char buf
[TAG_MAXLEN
+32];
1386 struct tagfile_entry entry
;
1389 if (!tcs
->valid
|| !tc_stat
.ready
)
1392 if (tcs
->idxfd
[tcs
->type
] < 0 && !TAGCACHE_IS_NUMERIC(tcs
->type
)
1393 #ifdef HAVE_TC_RAMCACHE
1399 /* Relative fetch. */
1400 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1401 || TAGCACHE_IS_NUMERIC(tcs
->type
)
1402 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1403 /* We need to retrieve flag status for dircache. */
1404 || (tcs
->ramsearch
&& tcs
->type
== tag_filename
)
1408 struct tagcache_seeklist_entry
*seeklist
;
1410 /* Check for end of list. */
1411 if (tcs
->list_position
== tcs
->seek_list_count
)
1413 tcs
->list_position
= 0;
1415 /* Try to fetch more. */
1416 if (!build_lookup_list(tcs
))
1423 seeklist
= &tcs
->seeklist
[tcs
->list_position
];
1424 flag
= seeklist
->flag
;
1425 tcs
->position
= seeklist
->seek
;
1426 tcs
->idx_id
= seeklist
->idx_id
;
1427 tcs
->list_position
++;
1431 if (tcs
->entry_count
== 0)
1440 tcs
->result_seek
= tcs
->position
;
1442 if (TAGCACHE_IS_NUMERIC(tcs
->type
))
1444 snprintf(buf
, sizeof(buf
), "%ld", tcs
->position
);
1446 tcs
->result_len
= strlen(buf
) + 1;
1451 #ifdef HAVE_TC_RAMCACHE
1455 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1456 if (tcs
->type
== tag_filename
&& (flag
& FLAG_DIRCACHE
)
1457 && is_dircache_intact())
1459 dircache_copy_path((struct dircache_entry
*)tcs
->position
,
1462 tcs
->result_len
= strlen(buf
) + 1;
1463 tcs
->ramresult
= false;
1469 if (tcs
->type
!= tag_filename
)
1471 struct tagfile_entry
*ep
;
1473 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1474 tcs
->result
= ep
->tag_data
;
1475 tcs
->result_len
= strlen(tcs
->result
) + 1;
1476 tcs
->idx_id
= ep
->idx_id
;
1477 tcs
->ramresult
= true;
1479 /* Increase position for the next run. This may get overwritten. */
1480 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1487 if (!open_files(tcs
, tcs
->type
))
1493 /* Seek stream to the correct position and continue to direct fetch. */
1494 lseek(tcs
->idxfd
[tcs
->type
], tcs
->position
, SEEK_SET
);
1496 if (ecread_tagfile_entry(tcs
->idxfd
[tcs
->type
], &entry
) != sizeof(struct tagfile_entry
))
1498 logf("read error #5");
1503 if (entry
.tag_length
> (long)sizeof(buf
))
1506 logf("too long tag #2");
1507 logf("P:%lX/%lX", tcs
->position
, entry
.tag_length
);
1511 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1514 logf("read error #4");
1519 Update the position for the next read (this may be overridden
1520 if filters or clauses are being used).
1522 tcs
->position
+= sizeof(struct tagfile_entry
) + entry
.tag_length
;
1524 tcs
->result_len
= strlen(tcs
->result
) + 1;
1525 tcs
->idx_id
= entry
.idx_id
;
1526 tcs
->ramresult
= false;
1531 bool tagcache_get_next(struct tagcache_search
*tcs
)
1533 while (get_next(tcs
))
1535 if (tcs
->result_len
> 1)
1542 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1543 int tag
, char *buf
, long size
)
1545 struct index_entry idx
;
1548 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1551 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1554 static bool update_master_header(void)
1556 struct master_header myhdr
;
1562 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1565 myhdr
.serial
= current_tcmh
.serial
;
1566 myhdr
.commitid
= current_tcmh
.commitid
;
1567 myhdr
.dirty
= current_tcmh
.dirty
;
1570 lseek(fd
, 0, SEEK_SET
);
1571 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1574 #ifdef HAVE_TC_RAMCACHE
1577 hdr
->h
.serial
= current_tcmh
.serial
;
1578 hdr
->h
.commitid
= current_tcmh
.commitid
;
1579 hdr
->h
.dirty
= current_tcmh
.dirty
;
1588 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1590 struct tagentry
*entry
;
1592 if (tcs
->type
!= tag_title
)
1595 /* We will need reserve buffer for this. */
1598 struct tagfile_entry
*ep
;
1600 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1601 tcs
->seek_list
[tcs
->seek_list_count
];
1604 entry
= find_entry_ram();
1609 void tagcache_search_finish(struct tagcache_search
*tcs
)
1613 if (!tcs
->initialized
)
1616 if (tcs
->masterfd
>= 0)
1618 close(tcs
->masterfd
);
1622 for (i
= 0; i
< TAG_COUNT
; i
++)
1624 if (tcs
->idxfd
[i
] >= 0)
1626 close(tcs
->idxfd
[i
]);
1631 tcs
->ramsearch
= false;
1633 tcs
->initialized
= 0;
1638 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1639 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1641 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1644 static long get_tag_numeric(const struct index_entry
*entry
, int tag
, int idx_id
)
1646 return check_virtual_tags(tag
, idx_id
, entry
);
1649 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1651 char* s
= get_tag(entry
, tag
)->tag_data
;
1652 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1655 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1657 struct index_entry
*entry
;
1660 if (!tc_stat
.ready
|| !tc_stat
.ramcache
)
1663 /* Find the corresponding entry in tagcache. */
1664 idx_id
= find_entry_ram(filename
, NULL
);
1668 entry
= &hdr
->indices
[idx_id
];
1670 memset(id3
, 0, sizeof(struct mp3entry
));
1672 id3
->title
= get_tag_string(entry
, tag_title
);
1673 id3
->artist
= get_tag_string(entry
, tag_artist
);
1674 id3
->album
= get_tag_string(entry
, tag_album
);
1675 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1676 id3
->composer
= get_tag_string(entry
, tag_composer
);
1677 id3
->comment
= get_tag_string(entry
, tag_comment
);
1678 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1679 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1681 id3
->length
= get_tag_numeric(entry
, tag_length
, idx_id
);
1682 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
, idx_id
);
1683 id3
->rating
= get_tag_numeric(entry
, tag_rating
, idx_id
);
1684 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
, idx_id
);
1685 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
, idx_id
) / 10;
1686 id3
->year
= get_tag_numeric(entry
, tag_year
, idx_id
);
1688 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
, idx_id
);
1689 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
, idx_id
);
1690 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
, idx_id
);
1691 if (id3
->bitrate
== 0)
1698 static inline void write_item(const char *item
)
1700 int len
= strlen(item
) + 1;
1703 write(cachefd
, item
, len
);
1706 static int check_if_empty(char **tag
)
1710 if (*tag
== NULL
|| **tag
== '\0')
1713 return sizeof(UNTAGGED
); /* Tag length */
1716 length
= strlen(*tag
);
1717 if (length
> TAG_MAXLEN
)
1719 logf("over length tag: %s", *tag
);
1720 length
= TAG_MAXLEN
;
1721 (*tag
)[length
] = '\0';
1727 #define ADD_TAG(entry,tag,data) \
1729 entry.tag_offset[tag] = offset; \
1730 entry.tag_length[tag] = check_if_empty(data); \
1731 offset += entry.tag_length[tag]
1732 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1733 * idea, as it uses lots of stack and is called from a recursive function
1736 static void __attribute__ ((noinline
)) add_tagcache(char *path
,
1738 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1739 ,const struct dircache_entry
*dc
1743 struct mp3entry id3
;
1744 struct temp_file_entry entry
;
1748 char tracknumfix
[3];
1750 int path_length
= strlen(path
);
1751 bool has_albumartist
;
1755 /* Crude logging for the sim - to aid in debugging */
1756 int logfd
= open(ROCKBOX_DIR
"/database.log",
1757 O_WRONLY
| O_APPEND
| O_CREAT
, 0666);
1759 write(logfd
, path
, strlen(path
));
1760 write(logfd
, "\n", 1);
1768 /* Check for overlength file path. */
1769 if (path_length
> TAG_MAXLEN
)
1771 /* Path can't be shortened. */
1772 logf("Too long path: %s", path
);
1776 /* Check if the file is supported. */
1777 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1780 /* Check if the file is already cached. */
1781 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1782 if (tc_stat
.ramcache
&& is_dircache_intact())
1784 idx_id
= find_entry_ram(path
, dc
);
1788 /* Be sure the entry doesn't exist. */
1789 if (filenametag_fd
>= 0 && idx_id
< 0)
1790 idx_id
= find_entry_disk(path
, false);
1792 /* Check if file has been modified. */
1795 struct index_entry idx
;
1797 /* TODO: Mark that the index exists (for fast reverse scan) */
1798 //found_idx[idx_id/8] |= idx_id%8;
1800 if (!get_index(-1, idx_id
, &idx
, true))
1802 logf("failed to retrieve index entry");
1806 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1808 /* No changes to file. */
1812 /* Metadata might have been changed. Delete the entry. */
1813 logf("Re-adding: %s", path
);
1814 if (!delete_entry(idx_id
))
1816 logf("delete_entry failed: %d", idx_id
);
1821 fd
= open(path
, O_RDONLY
);
1824 logf("open fail: %s", path
);
1828 memset(&id3
, 0, sizeof(struct mp3entry
));
1829 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1830 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1831 ret
= get_metadata(&id3
, fd
, path
);
1837 logf("-> %s", path
);
1839 /* Generate track number if missing. */
1840 if (id3
.tracknum
<= 0)
1842 const char *p
= strrchr(path
, '.');
1845 p
= &path
[strlen(path
)-1];
1849 if (isdigit(*p
) && isdigit(*(p
-1)))
1851 tracknumfix
[1] = *p
--;
1852 tracknumfix
[0] = *p
;
1858 if (tracknumfix
[0] != '\0')
1860 id3
.tracknum
= atoi(tracknumfix
);
1861 /* Set a flag to indicate track number has been generated. */
1862 entry
.flag
|= FLAG_TRKNUMGEN
;
1866 /* Unable to generate track number. */
1872 entry
.tag_offset
[tag_year
] = id3
.year
;
1873 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1874 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1875 entry
.tag_offset
[tag_length
] = id3
.length
;
1876 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1877 entry
.tag_offset
[tag_mtime
] = mtime
;
1880 has_albumartist
= id3
.albumartist
!= NULL
1881 && strlen(id3
.albumartist
) > 0;
1882 has_grouping
= id3
.grouping
!= NULL
1883 && strlen(id3
.grouping
) > 0;
1885 ADD_TAG(entry
, tag_filename
, &path
);
1886 ADD_TAG(entry
, tag_title
, &id3
.title
);
1887 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1888 ADD_TAG(entry
, tag_album
, &id3
.album
);
1889 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1890 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1891 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1892 if (has_albumartist
)
1894 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1898 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1902 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1906 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1908 entry
.data_length
= offset
;
1910 /* Write the header */
1911 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1913 /* And tags also... Correct order is critical */
1915 write_item(id3
.title
);
1916 write_item(id3
.artist
);
1917 write_item(id3
.album
);
1918 write_item(id3
.genre_string
);
1919 write_item(id3
.composer
);
1920 write_item(id3
.comment
);
1921 if (has_albumartist
)
1923 write_item(id3
.albumartist
);
1927 write_item(id3
.artist
);
1931 write_item(id3
.grouping
);
1935 write_item(id3
.title
);
1937 total_entry_count
++;
1940 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1942 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1943 int len
= strlen(str
)+1;
1946 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1947 char buf
[TAG_MAXLEN
+32];
1949 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1950 buf
[i
] = tolower(str
[i
]);
1953 crc32
= crc_32(buf
, i
, 0xffffffff);
1957 /* Check if the crc does not exist -> entry does not exist for sure. */
1958 for (i
= 0; i
< tempbufidx
; i
++)
1960 if (crcbuf
[-i
] != crc32
)
1963 if (!strcasecmp(str
, index
[i
].str
))
1965 if (id
< 0 || id
>= lookup_buffer_depth
)
1967 logf("lookup buf overf.: %d", id
);
1971 lookup
[id
] = &index
[i
];
1977 /* Insert to CRC buffer. */
1978 crcbuf
[-tempbufidx
] = crc32
;
1981 /* Insert it to the buffer. */
1982 tempbuf_left
-= len
;
1983 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1986 if (id
>= lookup_buffer_depth
)
1988 logf("lookup buf overf. #2: %d", id
);
1994 lookup
[id
] = &index
[tempbufidx
];
1995 index
[tempbufidx
].idlist
.id
= id
;
1998 index
[tempbufidx
].idlist
.id
= -1;
2000 index
[tempbufidx
].idlist
.next
= NULL
;
2001 index
[tempbufidx
].idx_id
= idx_id
;
2002 index
[tempbufidx
].seek
= -1;
2003 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
2004 memcpy(index
[tempbufidx
].str
, str
, len
);
2011 static int compare(const void *p1
, const void *p2
)
2015 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
2016 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
2018 if (strcmp(e1
->str
, UNTAGGED
) == 0)
2020 if (strcmp(e2
->str
, UNTAGGED
) == 0)
2024 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
2027 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
2030 static int tempbuf_sort(int fd
)
2032 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
2033 struct tagfile_entry fe
;
2037 /* Generate reverse lookup entries. */
2038 for (i
= 0; i
< lookup_buffer_depth
; i
++)
2040 struct tempbuf_id_list
*idlist
;
2045 if (lookup
[i
]->idlist
.id
== i
)
2048 idlist
= &lookup
[i
]->idlist
;
2049 while (idlist
->next
!= NULL
)
2050 idlist
= idlist
->next
;
2052 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
2053 if (tempbuf_left
- 4 < 0)
2056 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2057 if (tempbuf_pos
& 0x03)
2059 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
2061 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
2063 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
2065 idlist
= idlist
->next
;
2067 idlist
->next
= NULL
;
2072 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
2073 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
2075 for (i
= 0; i
< tempbufidx
; i
++)
2077 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
2079 /* Fix the lookup list. */
2080 while (idlist
!= NULL
)
2082 if (idlist
->id
>= 0)
2083 lookup
[idlist
->id
] = &index
[i
];
2084 idlist
= idlist
->next
;
2087 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
2088 length
= strlen(index
[i
].str
) + 1;
2089 fe
.tag_length
= length
;
2090 fe
.idx_id
= index
[i
].idx_id
;
2092 /* Check the chunk alignment. */
2093 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2094 % TAGFILE_ENTRY_CHUNK_LENGTH
)
2096 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
2097 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2098 % TAGFILE_ENTRY_CHUNK_LENGTH
);
2101 #ifdef TAGCACHE_STRICT_ALIGN
2102 /* Make sure the entry is long aligned. */
2103 if (index
[i
].seek
& 0x03)
2105 logf("tempbuf_sort: alignment error!");
2110 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2111 sizeof(struct tagfile_entry
))
2113 logf("tempbuf_sort: write error #1");
2117 if (write(fd
, index
[i
].str
, length
) != length
)
2119 logf("tempbuf_sort: write error #2");
2123 /* Write some padding. */
2124 if (fe
.tag_length
- length
> 0)
2125 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2131 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2133 if (id
< 0 || id
>= lookup_buffer_depth
)
2140 inline static int tempbuf_find_location(int id
)
2142 struct tempbuf_searchidx
*entry
;
2144 entry
= tempbuf_locate(id
);
2151 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2153 struct master_header tcmh
;
2154 struct index_entry idx
;
2157 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2159 int entries_processed
= 0;
2161 char buf
[TAG_MAXLEN
];
2163 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2165 logf("Building numeric indices...");
2166 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2168 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2171 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2173 if (masterfd_pos
== filesize(masterfd
))
2175 logf("we can't append!");
2180 while (entries_processed
< h
->entry_count
)
2182 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2184 /* Read in as many entries as possible. */
2185 for (i
= 0; i
< count
; i
++)
2187 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2190 /* Read in numeric data. */
2191 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2192 sizeof(struct temp_file_entry
))
2194 logf("read fail #1");
2199 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2202 * Read string data from the following tags:
2208 * A crc32 hash is calculated from the read data
2209 * and stored back to the data offset field kept in memory.
2211 #define tmpdb_read_string_tag(tag) \
2212 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2213 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2215 logf("read fail: buffer overflow"); \
2220 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2221 tfe->tag_length[tag]) \
2223 logf("read fail #2"); \
2228 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2229 lseek(tmpfd, datastart, SEEK_SET)
2231 tmpdb_read_string_tag(tag_filename
);
2232 tmpdb_read_string_tag(tag_artist
);
2233 tmpdb_read_string_tag(tag_album
);
2234 tmpdb_read_string_tag(tag_title
);
2236 /* Seek to the end of the string data. */
2237 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2240 /* Backup the master index position. */
2241 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2242 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2244 /* Check if we can resurrect some deleted runtime statistics data. */
2245 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2247 /* Read the index entry. */
2248 if (ecread_index_entry(masterfd
, &idx
)
2249 != sizeof(struct index_entry
))
2251 logf("read fail #3");
2257 * Skip unless the entry is marked as being deleted
2258 * or the data has already been resurrected.
2260 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2263 /* Now try to match the entry. */
2265 * To succesfully match a song, the following conditions
2268 * For numeric fields: tag_length
2269 * - Full identical match is required
2271 * If tag_filename matches, no further checking necessary.
2273 * For string hashes: tag_artist, tag_album, tag_title
2274 * - Two of these must match
2276 for (j
= 0; j
< count
; j
++)
2278 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2280 /* Try to match numeric fields first. */
2281 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2284 /* Now it's time to do the hash matching. */
2285 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2287 int match_count
= 0;
2289 /* No filename match, check if we can match two other tags. */
2290 #define tmpdb_match(tag) \
2291 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2294 tmpdb_match(tag_artist
);
2295 tmpdb_match(tag_album
);
2296 tmpdb_match(tag_title
);
2298 if (match_count
< 2)
2300 /* Still no match found, give up. */
2305 /* A match found, now copy & resurrect the statistical data. */
2306 #define tmpdb_copy_tag(tag) \
2307 tfe->tag_offset[tag] = idx.tag_seek[tag]
2309 tmpdb_copy_tag(tag_playcount
);
2310 tmpdb_copy_tag(tag_rating
);
2311 tmpdb_copy_tag(tag_playtime
);
2312 tmpdb_copy_tag(tag_lastplayed
);
2313 tmpdb_copy_tag(tag_commitid
);
2315 /* Avoid processing this entry again. */
2316 idx
.flag
|= FLAG_RESURRECTED
;
2318 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2319 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2321 logf("masterfd writeback fail #1");
2326 logf("Entry resurrected");
2331 /* Restore the master index position. */
2332 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2334 /* Commit the data to the index. */
2335 for (i
= 0; i
< count
; i
++)
2337 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2339 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2341 logf("read fail #3");
2346 for (j
= 0; j
< TAG_COUNT
; j
++)
2348 if (!TAGCACHE_IS_NUMERIC(j
))
2351 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2353 idx
.flag
= entrybuf
[i
].flag
;
2355 if (idx
.tag_seek
[tag_commitid
])
2357 /* Data has been resurrected. */
2358 idx
.flag
|= FLAG_DIRTYNUM
;
2360 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2362 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2363 idx
.flag
|= FLAG_DIRTYNUM
;
2366 /* Write back the updated index. */
2367 lseek(masterfd
, loc
, SEEK_SET
);
2368 if (ecwrite_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
2376 entries_processed
+= count
;
2377 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2388 * == 0 temporary failure
2391 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2394 struct tagcache_header tch
;
2395 struct master_header tcmh
;
2396 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2398 char buf
[TAG_MAXLEN
+32];
2399 int fd
= -1, masterfd
;
2404 logf("Building index: %d", index_type
);
2406 /* Check the number of entries we need to allocate ram for. */
2407 commit_entry_count
= h
->entry_count
+ 1;
2409 masterfd
= open_master_fd(&tcmh
, false);
2412 commit_entry_count
+= tcmh
.tch
.entry_count
;
2416 remove_files(); /* Just to be sure we are clean. */
2418 /* Open the index file, which contains the tag names. */
2419 fd
= open_tag_fd(&tch
, index_type
, true);
2422 logf("tch.datasize=%ld", tch
.datasize
);
2423 lookup_buffer_depth
= 1 +
2424 /* First part */ commit_entry_count
+
2425 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2429 lookup_buffer_depth
= 1 +
2430 /* First part */ commit_entry_count
+
2431 /* Second part */ 0;
2434 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2435 logf("commit_entry_count=%ld", commit_entry_count
);
2437 /* Allocate buffer for all index entries from both old and new
2440 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2442 /* Allocate lookup buffer. The first portion of commit_entry_count
2443 * contains the new tags in the temporary file and the second
2444 * part for locating entries already in the db.
2447 * +---------+---------------------------+
2448 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2449 * +---------+---------------------------+
2451 * Old tags are inserted to a temporary buffer with position:
2452 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2453 * And new tags with index:
2454 * tempbuf_insert(idx, ...);
2456 * The buffer is sorted and written into tag file:
2457 * tempbuf_sort(...);
2458 * leaving master index locations messed up.
2460 * That is fixed using the lookup buffer for old tags:
2461 * new_seek = tempbuf_find_location(old_seek, ...);
2463 * new_seek = tempbuf_find_location(idx);
2465 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2466 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2467 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2469 /* And calculate the remaining data space used mainly for storing
2470 * tag data (strings). */
2471 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2472 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2474 logf("Buffer way too small!");
2481 * If tag file contains unique tags (sorted index), we will load
2482 * it entirely into memory so we can resort it later for use with
2485 if (TAGCACHE_IS_SORTED(index_type
))
2487 logf("loading tags...");
2488 for (i
= 0; i
< tch
.entry_count
; i
++)
2490 struct tagfile_entry entry
;
2491 int loc
= lseek(fd
, 0, SEEK_CUR
);
2494 if (ecread_tagfile_entry(fd
, &entry
) != sizeof(struct tagfile_entry
))
2496 logf("read error #7");
2501 if (entry
.tag_length
>= (int)sizeof(buf
))
2503 logf("too long tag #3");
2508 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2510 logf("read error #8");
2515 /* Skip deleted entries. */
2520 * Save the tag and tag id in the memory buffer. Tag id
2521 * is saved so we can later reindex the master lookup
2522 * table when the index gets resorted.
2524 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2525 + commit_entry_count
, entry
.idx_id
,
2526 TAGCACHE_IS_UNIQUE(index_type
));
2537 tempbufidx
= tch
.entry_count
;
2542 * Creating new index file to store the tags. No need to preload
2543 * anything whether the index type is sorted or not.
2545 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2546 fd
= open(buf
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2549 logf("%s open fail", buf
);
2553 tch
.magic
= TAGCACHE_MAGIC
;
2554 tch
.entry_count
= 0;
2557 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2558 != sizeof(struct tagcache_header
))
2560 logf("header write failed");
2566 /* Loading the tag lookup file as "master file". */
2567 logf("Loading index file");
2568 masterfd
= open(TAGCACHE_FILE_MASTER
, O_RDWR
);
2572 logf("Creating new DB");
2573 masterfd
= open(TAGCACHE_FILE_MASTER
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
2577 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER
);
2582 /* Write the header (write real values later). */
2583 memset(&tcmh
, 0, sizeof(struct master_header
));
2585 tcmh
.tch
.entry_count
= 0;
2586 tcmh
.tch
.datasize
= 0;
2588 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2590 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2595 * Master file already exists so we need to process the current
2600 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2601 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2603 logf("header error");
2610 * If we reach end of the master file, we need to expand it to
2611 * hold new tags. If the current index is not sorted, we can
2612 * simply append new data to end of the file.
2613 * However, if the index is sorted, we need to update all tag
2614 * pointers in the master file for the current index.
2616 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2618 if (masterfd_pos
== filesize(masterfd
))
2620 logf("appending...");
2626 * Load new unique tags in memory to be sorted later and added
2627 * to the master lookup file.
2629 if (TAGCACHE_IS_SORTED(index_type
))
2631 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2632 /* h is the header of the temporary file containing new tags. */
2633 logf("inserting new tags...");
2634 for (i
= 0; i
< h
->entry_count
; i
++)
2636 struct temp_file_entry entry
;
2638 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2639 sizeof(struct temp_file_entry
))
2641 logf("read fail #3");
2647 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2649 logf("too long entry!");
2654 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2655 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2656 entry
.tag_length
[index_type
])
2658 logf("read fail #4");
2663 if (TAGCACHE_IS_UNIQUE(index_type
))
2664 error
= !tempbuf_insert(buf
, i
, -1, true);
2666 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2670 logf("insert error");
2675 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2676 entry
.tag_length
[index_type
], SEEK_CUR
);
2681 /* Sort the buffer data and write it to the index file. */
2682 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2684 * We need to truncate the index file now. There can be junk left
2685 * at the end of file (however, we _should_ always follow the
2686 * entry_count and don't crash with that).
2688 ftruncate(fd
, lseek(fd
, 0, SEEK_CUR
));
2690 i
= tempbuf_sort(fd
);
2693 logf("sorted %d tags", i
);
2696 * Now update all indexes in the master lookup file.
2698 logf("updating indices...");
2699 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2700 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2703 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2705 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2707 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2708 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2710 logf("read fail #5");
2714 lseek(masterfd
, loc
, SEEK_SET
);
2716 for (j
= 0; j
< idxbuf_pos
; j
++)
2718 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2720 /* We can just ignore deleted entries. */
2721 // idxbuf[j].tag_seek[index_type] = 0;
2725 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2726 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2727 + commit_entry_count
);
2729 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2731 logf("update error: %ld/%d/%ld",
2732 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2740 /* Write back the updated index. */
2741 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2742 index_entry_ec
, tc_stat
.econ
) !=
2743 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2754 * Walk through the temporary file containing the new tags.
2756 // build_normal_index(h, tmpfd, masterfd, idx);
2757 logf("updating new indices...");
2758 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2759 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2760 lseek(fd
, 0, SEEK_END
);
2761 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2765 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2768 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2772 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2774 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2775 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2777 logf("read fail #6");
2781 lseek(masterfd
, loc
, SEEK_SET
);
2784 /* Read entry headers. */
2785 for (j
= 0; j
< idxbuf_pos
; j
++)
2787 if (!TAGCACHE_IS_SORTED(index_type
))
2789 struct temp_file_entry entry
;
2790 struct tagfile_entry fe
;
2792 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2793 sizeof(struct temp_file_entry
))
2795 logf("read fail #7");
2801 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2803 logf("too long entry!");
2804 logf("length=%d", entry
.tag_length
[index_type
]);
2805 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2810 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2811 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2812 entry
.tag_length
[index_type
])
2814 logf("read fail #8");
2815 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2816 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2821 /* Write to index file. */
2822 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2823 fe
.tag_length
= entry
.tag_length
[index_type
];
2824 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2825 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2826 write(fd
, buf
, fe
.tag_length
);
2830 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2831 entry
.tag_length
[index_type
], SEEK_CUR
);
2835 /* Locate the correct entry from the sorted array. */
2836 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2837 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2839 logf("entry not found (%d)", j
);
2847 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2848 index_entry_ec
, tc_stat
.econ
) !=
2849 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2851 logf("tagcache: write fail #4");
2860 /* Finally write the header. */
2861 tch
.magic
= TAGCACHE_MAGIC
;
2862 tch
.entry_count
= tempbufidx
;
2863 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2864 lseek(fd
, 0, SEEK_SET
);
2865 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2867 if (index_type
!= tag_filename
)
2868 h
->datasize
+= tch
.datasize
;
2869 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2881 static bool commit(void)
2883 struct tagcache_header tch
;
2884 struct master_header tcmh
;
2888 #ifdef HAVE_DIRCACHE
2889 bool dircache_buffer_stolen
= false;
2891 bool local_allocation
= false;
2893 logf("committing tagcache");
2898 tmpfd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
2901 logf("nothing to commit");
2906 /* Load the header. */
2907 len
= sizeof(struct tagcache_header
);
2908 rc
= read(tmpfd
, &tch
, len
);
2910 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2912 logf("incorrect tmpheader");
2914 remove(TAGCACHE_FILE_TEMP
);
2918 if (tch
.entry_count
== 0)
2920 logf("nothing to commit");
2922 remove(TAGCACHE_FILE_TEMP
);
2926 /* Fully initialize existing headers (if any) before going further. */
2927 tc_stat
.ready
= check_all_headers();
2929 #ifdef HAVE_EEPROM_SETTINGS
2930 remove(TAGCACHE_STATEFILE
);
2933 /* At first be sure to unload the ramcache! */
2934 #ifdef HAVE_TC_RAMCACHE
2935 tc_stat
.ramcache
= false;
2940 /* Try to steal every buffer we can :) */
2941 if (tempbuf_size
== 0)
2942 local_allocation
= true;
2944 #ifdef HAVE_DIRCACHE
2945 if (tempbuf_size
== 0)
2947 /* Try to steal the dircache buffer. */
2948 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2949 tempbuf_size
&= ~0x03;
2951 if (tempbuf_size
> 0)
2953 dircache_buffer_stolen
= true;
2958 #ifdef HAVE_TC_RAMCACHE
2959 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2961 tempbuf
= (char *)(hdr
+ 1);
2962 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2963 tempbuf_size
&= ~0x03;
2967 /* And finally fail if there are no buffers available. */
2968 if (tempbuf_size
== 0)
2970 logf("delaying commit until next boot");
2971 tc_stat
.commit_delayed
= true;
2977 logf("commit %ld entries...", tch
.entry_count
);
2979 /* Mark DB dirty so it will stay disabled if commit fails. */
2980 current_tcmh
.dirty
= true;
2981 update_master_header();
2983 /* Now create the index files. */
2984 tc_stat
.commit_step
= 0;
2986 tc_stat
.commit_delayed
= false;
2988 for (i
= 0; i
< TAG_COUNT
; i
++)
2992 if (TAGCACHE_IS_NUMERIC(i
))
2995 tc_stat
.commit_step
++;
2996 ret
= build_index(i
, &tch
, tmpfd
);
3000 logf("tagcache failed init");
3002 tc_stat
.commit_delayed
= true;
3004 tc_stat
.commit_step
= 0;
3010 if (!build_numeric_indices(&tch
, tmpfd
))
3012 logf("Failure to commit numeric indices");
3014 tc_stat
.commit_step
= 0;
3020 remove(TAGCACHE_FILE_TEMP
);
3022 tc_stat
.commit_step
= 0;
3024 /* Update the master index headers. */
3025 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
3031 tcmh
.tch
.entry_count
+= tch
.entry_count
;
3032 tcmh
.tch
.datasize
= sizeof(struct master_header
)
3033 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
3038 lseek(masterfd
, 0, SEEK_SET
);
3039 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
3042 logf("tagcache committed");
3043 tc_stat
.ready
= check_all_headers();
3044 tc_stat
.readyvalid
= true;
3046 if (local_allocation
)
3052 #ifdef HAVE_DIRCACHE
3053 /* Rebuild the dircache, if we stole the buffer. */
3054 if (dircache_buffer_stolen
)
3058 #ifdef HAVE_TC_RAMCACHE
3059 /* Reload tagcache. */
3060 if (tc_stat
.ramcache_allocated
> 0)
3061 tagcache_start_scan();
3069 static void allocate_tempbuf(void)
3071 /* Yeah, malloc would be really nice now :) */
3073 tempbuf_size
= 32*1024*1024;
3074 tempbuf
= malloc(tempbuf_size
);
3076 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
3077 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
3078 audiobuf
+= tempbuf_size
;
3082 static void free_tempbuf(void)
3084 if (tempbuf_size
== 0)
3090 audiobuf
-= tempbuf_size
;
3098 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
3100 struct index_entry idx
;
3105 if (!TAGCACHE_IS_NUMERIC(tag
))
3108 if (!get_index(masterfd
, idx_id
, &idx
, false))
3111 idx
.tag_seek
[tag
] = data
;
3112 idx
.flag
|= FLAG_DIRTYNUM
;
3114 return write_index(masterfd
, idx_id
, &idx
);
3118 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3121 struct master_header myhdr
;
3123 if (tcs
->masterfd
< 0)
3125 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3129 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3133 static bool command_queue_is_full(void)
3137 next
= command_queue_widx
+ 1;
3138 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3141 return (next
== command_queue_ridx
);
3144 static void command_queue_sync_callback(void *data
)
3147 struct master_header myhdr
;
3150 mutex_lock(&command_queue_mutex
);
3152 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3155 while (command_queue_ridx
!= command_queue_widx
)
3157 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3159 switch (ce
->command
)
3161 case CMD_UPDATE_MASTER_HEADER
:
3164 update_master_header();
3166 /* Re-open the masterfd. */
3167 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3172 case CMD_UPDATE_NUMERIC
:
3174 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3179 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3180 command_queue_ridx
= 0;
3185 tc_stat
.queue_length
= 0;
3186 mutex_unlock(&command_queue_mutex
);
3189 static void run_command_queue(bool force
)
3191 if (COMMAND_QUEUE_IS_EMPTY
)
3194 if (force
|| command_queue_is_full())
3195 command_queue_sync_callback(NULL
);
3197 register_storage_idle_func(command_queue_sync_callback
);
3200 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3206 mutex_lock(&command_queue_mutex
);
3207 next
= command_queue_widx
+ 1;
3208 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3211 /* Make sure queue is not full. */
3212 if (next
!= command_queue_ridx
)
3214 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3217 ce
->idx_id
= idx_id
;
3221 command_queue_widx
= next
;
3223 tc_stat
.queue_length
++;
3225 mutex_unlock(&command_queue_mutex
);
3229 /* Queue is full, try again later... */
3230 mutex_unlock(&command_queue_mutex
);
3235 long tagcache_increase_serial(void)
3245 old
= current_tcmh
.serial
++;
3246 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3251 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3253 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3255 #endif /* !__PCTOOL__ */
3257 long tagcache_get_serial(void)
3259 return current_tcmh
.serial
;
3262 long tagcache_get_commitid(void)
3264 return current_tcmh
.commitid
;
3267 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3272 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3273 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3275 if (*datastr
== '\0')
3278 if (*datastr
== '"' || *datastr
== '\\')
3281 buf
[i
] = *(datastr
++);
3284 strcpy(&buf
[i
], "\" ");
3286 write(fd
, buf
, i
+ 2);
3293 static bool read_tag(char *dest
, long size
,
3294 const char *src
, const char *tagstr
)
3297 char current_tag
[32];
3299 while (*src
!= '\0')
3301 /* Skip all whitespace */
3309 /* Read in tag name */
3310 while (*src
!= '=' && *src
!= ' ')
3312 current_tag
[pos
] = *src
;
3316 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3319 current_tag
[pos
] = '\0';
3321 /* Read in tag data */
3323 /* Find the start. */
3324 while (*src
!= '"' && *src
!= '\0')
3327 if (*src
== '\0' || *(++src
) == '\0')
3330 /* Read the data. */
3331 for (pos
= 0; pos
< size
; pos
++)
3338 dest
[pos
] = *(src
+1);
3358 if (!strcasecmp(tagstr
, current_tag
))
3365 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3367 struct index_entry idx
;
3368 char tag_data
[TAG_MAXLEN
+32];
3370 long masterfd
= (long)parameters
;
3371 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3379 logf("%d/%s", line_n
, buf
);
3380 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3382 logf("filename missing");
3387 idx_id
= find_index(tag_data
);
3390 logf("entry not found");
3394 if (!get_index(masterfd
, idx_id
, &idx
, false))
3396 logf("failed to retrieve index entry");
3400 /* Stop if tag has already been modified. */
3401 if (idx
.flag
& FLAG_DIRTYNUM
)
3404 logf("import: %s", tag_data
);
3406 idx
.flag
|= FLAG_DIRTYNUM
;
3407 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3411 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3412 tagcache_tag_to_str(import_tags
[i
])))
3417 data
= atoi(tag_data
);
3421 idx
.tag_seek
[import_tags
[i
]] = data
;
3423 if (import_tags
[i
] == tag_lastplayed
&& data
>= current_tcmh
.serial
)
3424 current_tcmh
.serial
= data
+ 1;
3425 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3426 current_tcmh
.commitid
= data
+ 1;
3429 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3432 bool tagcache_import_changelog(void)
3434 struct master_header myhdr
;
3435 struct tagcache_header tch
;
3446 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_RDONLY
);
3449 logf("failure to open changelog");
3453 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3461 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3463 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3464 parse_changelog_line
);
3469 if (filenametag_fd
>= 0)
3471 close(filenametag_fd
);
3472 filenametag_fd
= -1;
3477 update_master_header();
3482 #endif /* !__PCTOOL__ */
3484 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3486 struct master_header myhdr
;
3487 struct index_entry idx
;
3488 char buf
[TAG_MAXLEN
+32];
3496 if (!tagcache_search(tcs
, tag_filename
))
3499 /* Initialize the changelog */
3500 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3503 logf("failure to open changelog");
3507 if (tcs
->masterfd
< 0)
3509 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3514 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3515 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3518 write(clfd
, "## Changelog version 1\n", 23);
3520 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3522 if (ecread_index_entry(tcs
->masterfd
, &idx
) != sizeof(struct index_entry
))
3524 logf("read error #9");
3525 tagcache_search_finish(tcs
);
3530 /* Skip until the entry found has been modified. */
3531 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3534 /* Skip deleted entries too. */
3535 if (idx
.flag
& FLAG_DELETED
)
3538 /* Now retrieve all tags. */
3539 for (j
= 0; j
< TAG_COUNT
; j
++)
3541 if (TAGCACHE_IS_NUMERIC(j
))
3543 snprintf(temp
, sizeof temp
, "%d", (int)idx
.tag_seek
[j
]);
3544 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3549 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3550 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3553 write(clfd
, "\n", 1);
3559 tagcache_search_finish(tcs
);
3564 static bool delete_entry(long idx_id
)
3569 struct index_entry idx
, myidx
;
3570 struct master_header myhdr
;
3571 char buf
[TAG_MAXLEN
+32];
3572 int in_use
[TAG_COUNT
];
3574 logf("delete_entry(): %ld", idx_id
);
3576 #ifdef HAVE_TC_RAMCACHE
3577 /* At first mark the entry removed from ram cache. */
3578 if (tc_stat
.ramcache
)
3579 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3582 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3585 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3586 if (ecread_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3588 logf("delete_entry(): read error");
3592 if (myidx
.flag
& FLAG_DELETED
)
3594 logf("delete_entry(): already deleted!");
3598 myidx
.flag
|= FLAG_DELETED
;
3599 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3600 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3602 logf("delete_entry(): write_error #1");
3606 /* Now check which tags are no longer in use (if any) */
3607 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3610 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3611 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3613 struct index_entry
*idxp
;
3615 #ifdef HAVE_TC_RAMCACHE
3616 /* Use RAM DB if available for greater speed */
3617 if (tc_stat
.ramcache
)
3618 idxp
= &hdr
->indices
[i
];
3622 if (ecread_index_entry(masterfd
, &idx
) != sizeof(struct index_entry
))
3624 logf("delete_entry(): read error #2");
3630 if (idxp
->flag
& FLAG_DELETED
)
3633 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3635 if (TAGCACHE_IS_NUMERIC(tag
))
3638 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3643 /* Now delete all tags no longer in use. */
3644 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3646 struct tagcache_header tch
;
3647 int oldseek
= myidx
.tag_seek
[tag
];
3649 if (TAGCACHE_IS_NUMERIC(tag
))
3653 * Replace tag seek with a hash value of the field string data.
3654 * That way runtime statistics of moved or altered files can be
3657 #ifdef HAVE_TC_RAMCACHE
3658 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3660 struct tagfile_entry
*tfe
;
3661 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3663 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3664 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3665 myidx
.tag_seek
[tag
] = *seek
;
3670 struct tagfile_entry tfe
;
3672 /* Open the index file, which contains the tag names. */
3673 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3676 /* Skip the header block */
3677 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3678 if (ecread_tagfile_entry(fd
, &tfe
) != sizeof(struct tagfile_entry
))
3680 logf("delete_entry(): read error #3");
3684 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3686 logf("delete_entry(): read error #4");
3690 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3695 logf("in use: %d/%d", tag
, in_use
[tag
]);
3704 #ifdef HAVE_TC_RAMCACHE
3705 /* Delete from ram. */
3706 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3708 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3709 tagentry
->tag_data
[0] = '\0';
3713 /* Open the index file, which contains the tag names. */
3716 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3720 /* Skip the header block */
3721 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3723 /* Debug, print 10 first characters of the tag
3726 logf("TAG:%s", buf);
3727 lseek(fd, -10, SEEK_CUR);
3730 /* Write first data byte in tag as \0 */
3733 /* Now tag data has been removed */
3738 /* Write index entry back into master index. */
3739 lseek(masterfd
, sizeof(struct master_header
) +
3740 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3741 if (ecwrite_index_entry(masterfd
, &myidx
) != sizeof(struct index_entry
))
3743 logf("delete_entry(): write_error #2");
3762 * Returns true if there is an event waiting in the queue
3763 * that requires the current operation to be aborted.
3765 static bool check_event_queue(void)
3767 struct queue_event ev
;
3769 if(!queue_peek(&tagcache_queue
, &ev
))
3776 case SYS_USB_CONNECTED
:
3784 #ifdef HAVE_TC_RAMCACHE
3785 static bool allocate_tagcache(void)
3787 struct master_header tcmh
;
3790 /* Load the header. */
3791 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3800 * Now calculate the required cache size plus
3801 * some extra space for alignment fixes.
3803 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3804 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3805 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3806 memset(hdr
, 0, sizeof(struct ramcache_header
));
3807 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3808 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3809 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3814 # ifdef HAVE_EEPROM_SETTINGS
3815 static bool tagcache_dumpload(void)
3817 struct statefile_header shdr
;
3822 fd
= open(TAGCACHE_STATEFILE
, O_RDONLY
);
3825 logf("no tagcache statedump");
3829 /* Check the statefile memory placement */
3830 hdr
= buffer_alloc(0);
3831 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3832 if (rc
!= sizeof(struct statefile_header
)
3833 /* || (long)hdr != (long)shdr.hdr */)
3835 logf("incorrect statefile");
3841 offpos
= (long)hdr
- (long)shdr
.hdr
;
3843 /* Lets allocate real memory and load it */
3844 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3845 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3848 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3850 logf("read failure!");
3855 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3857 /* Now fix the pointers */
3858 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3859 for (i
= 0; i
< TAG_COUNT
; i
++)
3860 hdr
->tags
[i
] += offpos
;
3865 static bool tagcache_dumpsave(void)
3867 struct statefile_header shdr
;
3870 if (!tc_stat
.ramcache
)
3873 fd
= open(TAGCACHE_STATEFILE
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
3876 logf("failed to create a statedump");
3880 /* Create the header */
3882 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3883 write(fd
, &shdr
, sizeof(struct statefile_header
));
3885 /* And dump the data too */
3886 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3893 static bool load_tagcache(void)
3895 struct tagcache_header
*tch
;
3896 long bytesleft
= tc_stat
.ramcache_allocated
;
3897 struct index_entry
*idx
;
3902 # ifdef HAVE_DIRCACHE
3903 while (dircache_is_initializing())
3906 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3909 logf("loading tagcache to ram...");
3911 fd
= open(TAGCACHE_FILE_MASTER
, O_RDONLY
);
3914 logf("tagcache open failed");
3918 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3919 != sizeof(struct master_header
)
3920 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3922 logf("incorrect header");
3928 /* Load the master index table. */
3929 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3931 rc
= ecread_index_entry(fd
, idx
);
3932 if (rc
!= sizeof(struct index_entry
))
3934 logf("read error #10");
3939 bytesleft
-= sizeof(struct index_entry
);
3940 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3942 logf("too big tagcache.");
3952 /* Load the tags. */
3954 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3956 struct tagfile_entry
*fe
;
3957 char buf
[TAG_MAXLEN
+32];
3959 if (TAGCACHE_IS_NUMERIC(tag
))
3962 //p = ((void *)p+1);
3963 p
= (char *)((long)p
& ~0x03) + 0x04;
3966 /* Check the header. */
3967 tch
= (struct tagcache_header
*)p
;
3968 p
+= sizeof(struct tagcache_header
);
3970 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3973 for (hdr
->entry_count
[tag
] = 0;
3974 hdr
->entry_count
[tag
] < tch
->entry_count
;
3975 hdr
->entry_count
[tag
]++)
3979 if (do_timed_yield())
3981 /* Abort if we got a critical event in queue */
3982 if (check_event_queue())
3986 fe
= (struct tagfile_entry
*)p
;
3987 pos
= lseek(fd
, 0, SEEK_CUR
);
3988 rc
= ecread_tagfile_entry(fd
, fe
);
3989 if (rc
!= sizeof(struct tagfile_entry
))
3991 /* End of lookup table. */
3992 logf("read error #11");
3997 /* We have a special handling for the filename tags. */
3998 if (tag
== tag_filename
)
4000 # ifdef HAVE_DIRCACHE
4001 const struct dircache_entry
*dc
;
4004 // FIXME: This is wrong!
4005 // idx = &hdr->indices[hdr->entry_count[i]];
4006 idx
= &hdr
->indices
[fe
->idx_id
];
4008 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
4012 logf("TAG:%s", buf
);
4013 logf("too long filename");
4018 rc
= read(fd
, buf
, fe
->tag_length
);
4019 if (rc
!= fe
->tag_length
)
4021 logf("read error #12");
4026 /* Check if the entry has already been removed */
4027 if (idx
->flag
& FLAG_DELETED
)
4030 /* This flag must not be used yet. */
4031 if (idx
->flag
& FLAG_DIRCACHE
)
4033 logf("internal error!");
4038 if (idx
->tag_seek
[tag
] != pos
)
4040 logf("corrupt data structures!");
4045 # ifdef HAVE_DIRCACHE
4046 if (dircache_is_enabled())
4048 dc
= dircache_get_entry_ptr(buf
);
4051 logf("Entry no longer valid.");
4053 if (global_settings
.tagcache_autoupdate
)
4054 delete_entry(fe
->idx_id
);
4058 idx
->flag
|= FLAG_DIRCACHE
;
4059 idx
->tag_seek
[tag_filename
] = (long)dc
;
4064 /* This will be very slow unless dircache is enabled
4065 or target is flash based, but do it anyway for
4067 /* Check if entry has been removed. */
4068 if (global_settings
.tagcache_autoupdate
)
4070 if (!file_exists(buf
))
4072 logf("Entry no longer valid.");
4074 delete_entry(fe
->idx_id
);
4083 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
4086 logf("too big tagcache #2");
4087 logf("tl: %ld", fe
->tag_length
);
4088 logf("bl: %ld", bytesleft
);
4094 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
4097 if (rc
!= fe
->tag_length
)
4099 logf("read error #13");
4100 logf("rc=0x%04x", rc
); // 0x431
4101 logf("len=0x%04lx", fe
->tag_length
); // 0x4000
4102 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
4103 logf("tag=0x%02x", tag
); // 0x00
4111 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4112 logf("tagcache loaded into ram!");
4116 #endif /* HAVE_TC_RAMCACHE */
4118 static bool check_deleted_files(void)
4121 char buf
[TAG_MAXLEN
+32];
4122 struct tagfile_entry tfe
;
4124 logf("reverse scan...");
4125 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4126 fd
= open(buf
, O_RDONLY
);
4130 logf("%s open fail", buf
);
4134 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4135 while (ecread_tagfile_entry(fd
, &tfe
) == sizeof(struct tagfile_entry
)
4137 && !check_event_queue()
4141 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4143 logf("too long tag");
4148 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4150 logf("read error #14");
4155 /* Check if the file has already deleted from the db. */
4159 /* Now check if the file exists. */
4160 if (!file_exists(buf
))
4162 logf("Entry no longer valid.");
4163 logf("-> %s / %ld", buf
, tfe
.tag_length
);
4164 delete_entry(tfe
.idx_id
);
4176 /* Note that this function must not be inlined, otherwise the whole point
4177 * of having the code in a separate function is lost.
4179 static void __attribute__ ((noinline
)) check_ignore(const char *dirname
,
4180 int *ignore
, int *unignore
)
4182 char newpath
[MAX_PATH
];
4184 /* check for a database.ignore file */
4185 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4186 *ignore
= file_exists(newpath
);
4187 /* check for a database.unignore file */
4188 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4189 *unignore
= file_exists(newpath
);
4193 static bool check_dir(const char *dirname
, int add_files
)
4197 int success
= false;
4198 int ignore
, unignore
;
4200 dir
= opendir(dirname
);
4203 logf("tagcache: opendir(%s) failed", dirname
);
4207 /* check for a database.ignore and database.unignore */
4208 check_ignore(dirname
, &ignore
, &unignore
);
4210 /* don't do anything if both ignore and unignore are there */
4211 if (ignore
!= unignore
)
4212 add_files
= unignore
;
4214 /* Recursively scan the dir. */
4218 while (!check_event_queue())
4221 struct dirent
*entry
;
4223 entry
= readdir(dir
);
4231 struct dirinfo info
= dir_get_info(dir
, entry
);
4233 if (!strcmp((char *)entry
->d_name
, ".") ||
4234 !strcmp((char *)entry
->d_name
, ".."))
4239 len
= strlen(curpath
);
4240 snprintf(&curpath
[len
], sizeof(curpath
) - len
, "/%s",
4243 processed_dir_count
++;
4244 if (info
.attribute
& ATTR_DIRECTORY
)
4245 check_dir(curpath
, add_files
);
4248 tc_stat
.curentry
= curpath
;
4250 /* Add a new entry to the temporary db file. */
4251 add_tagcache(curpath
, (info
.wrtdate
<< 16) | info
.wrttime
4252 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4253 , dir
->internal_entry
4257 /* Wait until current path for debug screen is read and unset. */
4258 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4261 tc_stat
.curentry
= NULL
;
4264 curpath
[len
] = '\0';
4272 void tagcache_screensync_event(void)
4274 tc_stat
.curentry
= NULL
;
4277 void tagcache_screensync_enable(bool state
)
4279 tc_stat
.syncscreen
= state
;
4282 void tagcache_build(const char *path
)
4284 struct tagcache_header header
;
4289 total_entry_count
= 0;
4290 processed_dir_count
= 0;
4292 #ifdef HAVE_DIRCACHE
4293 while (dircache_is_initializing())
4297 logf("updating tagcache");
4299 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
4302 logf("skipping, cache already waiting for commit");
4307 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDWR
| O_CREAT
| O_TRUNC
, 0666);
4310 logf("master file open failed: %s", TAGCACHE_FILE_TEMP
);
4314 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4318 logf("Scanning files...");
4319 /* Scan for new files. */
4320 memset(&header
, 0, sizeof(struct tagcache_header
));
4321 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4323 if (strcmp("/", path
) != 0)
4324 strcpy(curpath
, path
);
4325 ret
= check_dir(path
, true);
4327 /* Write the header. */
4328 header
.magic
= TAGCACHE_MAGIC
;
4329 header
.datasize
= data_size
;
4330 header
.entry_count
= total_entry_count
;
4331 lseek(cachefd
, 0, SEEK_SET
);
4332 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4335 if (filenametag_fd
>= 0)
4337 close(filenametag_fd
);
4338 filenametag_fd
= -1;
4348 /* Commit changes to the database. */
4354 remove(TAGCACHE_FILE_TEMP
);
4355 logf("tagcache built!");
4361 #ifdef HAVE_TC_RAMCACHE
4364 /* Import runtime statistics if we just initialized the db. */
4365 if (hdr
->h
.serial
== 0)
4366 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4373 #ifdef HAVE_TC_RAMCACHE
4374 static void load_ramcache(void)
4381 /* At first we should load the cache (if exists). */
4382 tc_stat
.ramcache
= load_tagcache();
4384 if (!tc_stat
.ramcache
)
4386 /* If loading failed, it must indicate some problem with the db
4387 * so disable it entirely to prevent further issues. */
4388 tc_stat
.ready
= false;
4395 void tagcache_unload_ramcache(void)
4397 tc_stat
.ramcache
= false;
4398 /* Just to make sure there is no statefile present. */
4399 // remove(TAGCACHE_STATEFILE);
4404 static void tagcache_thread(void)
4406 struct queue_event ev
;
4407 bool check_done
= false;
4409 /* If the previous cache build/update was interrupted, commit
4410 * the changes first in foreground. */
4416 #ifdef HAVE_TC_RAMCACHE
4417 # ifdef HAVE_EEPROM_SETTINGS
4418 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
4419 && global_settings
.tagcache_ram
)
4421 check_done
= tagcache_dumpload();
4424 remove(TAGCACHE_STATEFILE
);
4427 /* Allocate space for the tagcache if found on disk. */
4428 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4429 allocate_tagcache();
4433 tc_stat
.initialized
= true;
4435 /* Don't delay bootup with the header check but do it on background. */
4439 tc_stat
.ready
= check_all_headers();
4440 tc_stat
.readyvalid
= true;
4445 run_command_queue(false);
4447 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4451 case Q_IMPORT_CHANGELOG
:
4452 tagcache_import_changelog();
4457 remove(TAGCACHE_FILE_TEMP
);
4458 tagcache_build("/");
4462 tagcache_build("/");
4463 #ifdef HAVE_TC_RAMCACHE
4466 check_deleted_files();
4472 if (check_done
|| !tc_stat
.ready
)
4475 #ifdef HAVE_TC_RAMCACHE
4476 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4479 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4480 tagcache_build("/");
4484 if (global_settings
.tagcache_autoupdate
)
4486 tagcache_build("/");
4488 /* This will be very slow unless dircache is enabled
4489 or target is flash based, but do it anyway for
4491 check_deleted_files();
4494 logf("tagcache check done");
4505 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4506 case SYS_USB_CONNECTED
:
4507 logf("USB: TagCache");
4508 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4509 usb_wait_for_disconnect(&tagcache_queue
);
4516 bool tagcache_prepare_shutdown(void)
4518 if (tagcache_get_commit_step() > 0)
4521 tagcache_stop_scan();
4522 while (read_lock
|| write_lock
)
4528 void tagcache_shutdown(void)
4530 /* Flush the command queue. */
4531 run_command_queue(true);
4533 #ifdef HAVE_EEPROM_SETTINGS
4534 if (tc_stat
.ramcache
)
4535 tagcache_dumpsave();
4539 static int get_progress(void)
4541 int total_count
= -1;
4543 #ifdef HAVE_DIRCACHE
4544 if (dircache_is_enabled())
4546 total_count
= dircache_get_entry_count();
4550 #ifdef HAVE_TC_RAMCACHE
4552 if (hdr
&& tc_stat
.ramcache
)
4553 total_count
= hdr
->h
.tch
.entry_count
;
4557 if (total_count
< 0)
4560 return processed_dir_count
* 100 / total_count
;
4563 struct tagcache_stat
* tagcache_get_stat(void)
4565 tc_stat
.progress
= get_progress();
4566 tc_stat
.processed_entries
= processed_dir_count
;
4571 void tagcache_start_scan(void)
4573 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4576 bool tagcache_update(void)
4581 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4585 bool tagcache_rebuild()
4587 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4591 void tagcache_stop_scan(void)
4593 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4596 #ifdef HAVE_TC_RAMCACHE
4597 bool tagcache_is_ramcache(void)
4599 return tc_stat
.ramcache
;
4603 #endif /* !__PCTOOL__ */
4606 void tagcache_init(void)
4608 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4609 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4610 filenametag_fd
= -1;
4611 write_lock
= read_lock
= 0;
4614 mutex_init(&command_queue_mutex
);
4615 queue_init(&tagcache_queue
, true);
4616 create_thread(tagcache_thread
, tagcache_stack
,
4617 sizeof(tagcache_stack
), 0, tagcache_thread_name
4618 IF_PRIO(, PRIORITY_BACKGROUND
)
4621 tc_stat
.initialized
= true;
4625 tc_stat
.ready
= check_all_headers();
4630 void tagcache_reverse_scan(void)
4632 logf("Checking for deleted files");
4633 check_deleted_files();
4637 bool tagcache_is_initialized(void)
4639 return tc_stat
.initialized
;
4641 bool tagcache_is_usable(void)
4643 return tc_stat
.initialized
&& tc_stat
.ready
;
4645 int tagcache_get_commit_step(void)
4647 return tc_stat
.commit_step
;
4649 int tagcache_get_max_commit_step(void)
4651 return (int)(SORTED_TAGS_COUNT
)+1;