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"
85 #include "eeprom_settings.h"
89 #define yield() do { } while(0)
90 #define sim_sleep(timeout) do { } while(0)
91 #define do_timed_yield() do { } while(0)
95 /* Tag Cache thread. */
96 static struct event_queue tagcache_queue
;
97 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
98 static const char tagcache_thread_name
[] = "tagcache";
101 #define UNTAGGED "<Untagged>"
103 /* Previous path when scanning directory tree recursively. */
104 static char curpath
[TAG_MAXLEN
+32];
106 /* Used when removing duplicates. */
107 static char *tempbuf
; /* Allocated when needed. */
108 static long tempbufidx
; /* Current location in buffer. */
109 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
110 static long tempbuf_left
; /* Buffer space left. */
111 static long tempbuf_pos
;
113 /* Tags we want to get sorted (loaded to the tempbuf). */
114 static const int sorted_tags
[] = { tag_artist
, tag_album
, tag_genre
,
115 tag_composer
, tag_comment
, tag_albumartist
, tag_grouping
, tag_title
};
117 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
118 static const int unique_tags
[] = { tag_artist
, tag_album
, tag_genre
,
119 tag_composer
, tag_comment
, tag_albumartist
, tag_grouping
};
121 /* Numeric tags (we can use these tags with conditional clauses). */
122 static const int numeric_tags
[] = { tag_year
, tag_discnumber
,
123 tag_tracknumber
, tag_length
, tag_bitrate
, tag_playcount
, tag_rating
,
124 tag_playtime
, tag_lastplayed
, tag_commitid
, tag_mtime
,
125 tag_virt_length_min
, tag_virt_length_sec
,
126 tag_virt_playtime_min
, tag_virt_playtime_sec
,
127 tag_virt_entryage
, tag_virt_autoscore
};
129 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
130 static const char *tags_str
[] = { "artist", "album", "genre", "title",
131 "filename", "composer", "comment", "albumartist", "grouping", "year",
132 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
133 "playtime", "lastplayed", "commitid", "mtime" };
135 /* Status information of the tagcache. */
136 static struct tagcache_stat tc_stat
;
138 /* Queue commands. */
139 enum tagcache_queue
{
146 /* Internal tagcache command queue. */
147 CMD_UPDATE_MASTER_HEADER
,
151 struct tagcache_command_entry
{
159 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
160 static volatile int command_queue_widx
= 0;
161 static volatile int command_queue_ridx
= 0;
162 static struct mutex command_queue_mutex
;
165 /* Tag database structures. */
167 /* Variable-length tag entry in tag files. */
168 struct tagfile_entry
{
169 short tag_length
; /* Length of the data in bytes including '\0' */
170 short idx_id
; /* Corresponding entry location in index file of not unique tags */
171 char tag_data
[0]; /* Begin of the tag data */
174 /* Fixed-size tag entry in master db index. */
176 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
177 int32_t flag
; /* Status flags */
180 /* Header is the same in every file. */
181 struct tagcache_header
{
182 int32_t magic
; /* Header version number */
183 int32_t datasize
; /* Data size in bytes */
184 int32_t entry_count
; /* Number of entries in this file */
187 struct master_header
{
188 struct tagcache_header tch
;
189 int32_t serial
; /* Increasing counting number */
190 int32_t commitid
; /* Number of commits so far */
194 /* For the endianess correction */
195 static const char *tagfile_entry_ec
= "ss";
197 Note: This should be (1 + TAG_COUNT) amount of l's.
199 static const char *index_entry_ec
= "lllllllllllllllllllll";
201 static const char *tagcache_header_ec
= "lll";
202 static const char *master_header_ec
= "llllll";
204 static struct master_header current_tcmh
;
206 #ifdef HAVE_TC_RAMCACHE
207 /* Header is created when loading database to ram. */
208 struct ramcache_header
{
209 struct master_header h
; /* Header from the master index */
210 struct index_entry
*indices
; /* Master index file content */
211 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
212 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
215 # ifdef HAVE_EEPROM_SETTINGS
216 struct statefile_header
{
217 struct ramcache_header
*hdr
;
218 struct tagcache_stat tc_stat
;
222 /* Pointer to allocated ramcache_header */
223 static struct ramcache_header
*hdr
;
227 * Full tag entries stored in a temporary file waiting
228 * for commit to the cache. */
229 struct temp_file_entry
{
230 long tag_offset
[TAG_COUNT
];
231 short tag_length
[TAG_COUNT
];
237 struct tempbuf_id_list
{
239 struct tempbuf_id_list
*next
;
242 struct tempbuf_searchidx
{
246 struct tempbuf_id_list idlist
;
249 /* Lookup buffer for fixing messed up index while after sorting. */
250 static long commit_entry_count
;
251 static long lookup_buffer_depth
;
252 static struct tempbuf_searchidx
**lookup
;
254 /* Used when building the temporary file. */
255 static int cachefd
= -1, filenametag_fd
;
256 static int total_entry_count
= 0;
257 static int data_size
= 0;
258 static int processed_dir_count
;
260 /* Thread safe locking */
261 static volatile int write_lock
;
262 static volatile int read_lock
;
264 static bool delete_entry(long idx_id
);
266 const char* tagcache_tag_to_str(int tag
)
268 return tags_str
[tag
];
271 bool tagcache_is_numeric_tag(int type
)
275 for (i
= 0; i
< (int)(sizeof(numeric_tags
)/sizeof(numeric_tags
[0])); i
++)
277 if (type
== numeric_tags
[i
])
284 bool tagcache_is_unique_tag(int type
)
288 for (i
= 0; i
< (int)(sizeof(unique_tags
)/sizeof(unique_tags
[0])); i
++)
290 if (type
== unique_tags
[i
])
297 bool tagcache_is_sorted_tag(int type
)
301 for (i
= 0; i
< (int)(sizeof(sorted_tags
)/sizeof(sorted_tags
[0])); i
++)
303 if (type
== sorted_tags
[i
])
312 * Returns true if specified flag is still present, i.e., dircache
313 * has not been reloaded.
315 static bool is_dircache_intact(void)
317 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
321 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
327 if (tagcache_is_numeric_tag(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
330 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
332 fd
= open(buf
, write
? O_RDWR
: O_RDONLY
);
335 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
336 tc_stat
.ready
= false;
340 /* Check the header. */
341 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
342 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
344 logf("header error");
345 tc_stat
.ready
= false;
353 static int open_master_fd(struct master_header
*hdr
, bool write
)
358 fd
= open(TAGCACHE_FILE_MASTER
, write
? O_RDWR
: O_RDONLY
);
361 logf("master file open failed for R/W");
362 tc_stat
.ready
= false;
366 tc_stat
.econ
= false;
368 /* Check the header. */
369 rc
= read(fd
, hdr
, sizeof(struct master_header
));
370 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
376 /* Trying to read again, this time with endianess correction enabled. */
377 lseek(fd
, 0, SEEK_SET
);
379 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
380 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
382 logf("header error");
383 tc_stat
.ready
= false;
394 static bool do_timed_yield(void)
396 /* Sorting can lock up for quite a while, so yield occasionally */
397 static long wakeup_tick
= 0;
398 if (current_tick
>= wakeup_tick
)
400 wakeup_tick
= current_tick
+ (HZ
/4);
408 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
409 static long find_entry_ram(const char *filename
,
410 const struct dirent
*dc
)
412 static long last_pos
= 0;
415 /* Check if we tagcache is loaded into ram. */
416 if (!tc_stat
.ramcache
)
420 dc
= dircache_get_entry_ptr(filename
);
424 logf("tagcache: file not found.");
435 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
437 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
439 last_pos
= MAX(0, i
- 3);
456 static long find_entry_disk(const char *filename
)
458 struct tagcache_header tch
;
459 static long last_pos
= -1;
460 long pos_history
[POS_HISTORY_COUNT
];
461 long pos_history_idx
= 0;
463 struct tagfile_entry tfe
;
465 char buf
[TAG_MAXLEN
+32];
476 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
483 lseek(fd
, last_pos
, SEEK_SET
);
485 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
489 pos
= lseek(fd
, 0, SEEK_CUR
);
490 for (i
= pos_history_idx
-1; i
>= 0; i
--)
491 pos_history
[i
+1] = pos_history
[i
];
492 pos_history
[0] = pos
;
494 if (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
495 != sizeof(struct tagfile_entry
))
500 if (tfe
.tag_length
>= (long)sizeof(buf
))
502 logf("too long tag #1");
508 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
510 logf("read error #2");
516 if (!strcasecmp(filename
, buf
))
518 last_pos
= pos_history
[pos_history_idx
];
523 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
537 if (fd
!= filenametag_fd
)
542 if (fd
!= filenametag_fd
)
548 static int find_index(const char *filename
)
552 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
553 if (tc_stat
.ramcache
&& is_dircache_intact())
554 idx_id
= find_entry_ram(filename
, NULL
);
558 idx_id
= find_entry_disk(filename
);
563 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
570 idx_id
= find_index(filename
);
574 if (!tagcache_search(tcs
, tag_filename
))
577 tcs
->entry_count
= 0;
578 tcs
->idx_id
= idx_id
;
583 static bool get_index(int masterfd
, int idxid
,
584 struct index_entry
*idx
, bool use_ram
)
586 bool localfd
= false;
590 logf("Incorrect idxid: %d", idxid
);
594 #ifdef HAVE_TC_RAMCACHE
595 if (tc_stat
.ramcache
&& use_ram
)
597 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
600 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
609 struct master_header tcmh
;
612 masterfd
= open_master_fd(&tcmh
, false);
617 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
618 + sizeof(struct master_header
), SEEK_SET
);
619 if (ecread(masterfd
, idx
, 1, index_entry_ec
, tc_stat
.econ
)
620 != sizeof(struct index_entry
))
622 logf("read error #3");
632 if (idx
->flag
& FLAG_DELETED
)
640 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
642 /* We need to exclude all memory only flags & tags when writing to disk. */
643 if (idx
->flag
& FLAG_DIRCACHE
)
645 logf("memory only flags!");
649 #ifdef HAVE_TC_RAMCACHE
650 /* Only update numeric data. Writing the whole index to RAM by memcpy
651 * destroys dircache pointers!
653 if (tc_stat
.ramcache
)
656 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
658 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
660 if (tagcache_is_numeric_tag(tag
))
662 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
666 /* Don't touch the dircache flag or attributes. */
667 idx_ram
->flag
= (idx
->flag
& 0x0000ffff)
668 | (idx_ram
->flag
& (0xffff0000 | FLAG_DIRCACHE
));
672 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
673 + sizeof(struct master_header
), SEEK_SET
);
674 if (ecwrite(masterfd
, idx
, 1, index_entry_ec
, tc_stat
.econ
)
675 != sizeof(struct index_entry
))
677 logf("write error #3");
678 logf("idxid: %d", idxid
);
685 #endif /* !__PCTOOL__ */
687 static bool open_files(struct tagcache_search
*tcs
, int tag
)
689 if (tcs
->idxfd
[tag
] < 0)
693 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
694 tcs
->idxfd
[tag
] = open(fn
, O_RDONLY
);
697 if (tcs
->idxfd
[tag
] < 0)
699 logf("File not open!");
706 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
707 int tag
, char *buf
, long size
)
709 struct tagfile_entry tfe
;
714 if (tagcache_is_numeric_tag(tag
))
717 seek
= idx
->tag_seek
[tag
];
720 logf("Retrieve failed");
724 #ifdef HAVE_TC_RAMCACHE
727 struct tagfile_entry
*ep
;
729 # ifdef HAVE_DIRCACHE
730 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
731 && is_dircache_intact())
733 dircache_copy_path((struct dirent
*)seek
,
739 if (tag
!= tag_filename
)
741 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
742 strncpy(buf
, ep
->tag_data
, size
-1);
749 if (!open_files(tcs
, tag
))
752 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
753 if (ecread(tcs
->idxfd
[tag
], &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
754 != sizeof(struct tagfile_entry
))
756 logf("read error #5");
760 if (tfe
.tag_length
>= size
)
762 logf("too small buffer");
766 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
769 logf("read error #6");
773 buf
[tfe
.tag_length
] = '\0';
778 static long check_virtual_tags(int tag
, const struct index_entry
*idx
)
784 case tag_virt_length_sec
:
785 data
= (idx
->tag_seek
[tag_length
]/1000) % 60;
788 case tag_virt_length_min
:
789 data
= (idx
->tag_seek
[tag_length
]/1000) / 60;
792 case tag_virt_playtime_sec
:
793 data
= (idx
->tag_seek
[tag_playtime
]/1000) % 60;
796 case tag_virt_playtime_min
:
797 data
= (idx
->tag_seek
[tag_playtime
]/1000) / 60;
800 case tag_virt_autoscore
:
801 if (idx
->tag_seek
[tag_length
] == 0
802 || idx
->tag_seek
[tag_playcount
] == 0)
808 data
= 100 * idx
->tag_seek
[tag_playtime
]
809 / idx
->tag_seek
[tag_length
]
810 / idx
->tag_seek
[tag_playcount
];
814 /* How many commits before the file has been added to the DB. */
815 case tag_virt_entryage
:
816 data
= current_tcmh
.commitid
- idx
->tag_seek
[tag_commitid
] - 1;
820 data
= idx
->tag_seek
[tag
];
826 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
828 struct index_entry idx
;
833 if (!tagcache_is_numeric_tag(tag
))
836 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
839 return check_virtual_tags(tag
, &idx
);
842 inline static bool str_ends_with(const char *str1
, const char *str2
)
844 int str_len
= strlen(str1
);
845 int clause_len
= strlen(str2
);
847 if (clause_len
> str_len
)
850 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
853 inline static bool str_oneof(const char *str
, const char *list
)
856 int l
, len
= strlen(str
);
860 sep
= strchr(list
, '|');
861 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
862 if ((l
==len
) && !strncasecmp(str
, list
, len
))
864 list
+= sep
? l
+ 1 : l
;
870 static bool check_against_clause(long numeric
, const char *str
,
871 const struct tagcache_search_clause
*clause
)
875 switch (clause
->type
)
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 return numeric
<= clause
->numeric_data
;
890 logf("Incorrect numeric tag: %d", clause
->type
);
895 switch (clause
->type
)
898 return !strcasecmp(clause
->str
, str
);
900 return 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
);
908 return 0<=strcasecmp(clause
->str
, str
);
909 case clause_contains
:
910 return (strcasestr(str
, clause
->str
) != NULL
);
911 case clause_not_contains
:
912 return (strcasestr(str
, clause
->str
) == NULL
);
913 case clause_begins_with
:
914 return (strcasestr(str
, clause
->str
) == str
);
915 case clause_not_begins_with
:
916 return (strcasestr(str
, clause
->str
) != str
);
917 case clause_ends_with
:
918 return str_ends_with(str
, clause
->str
);
919 case clause_not_ends_with
:
920 return !str_ends_with(str
, clause
->str
);
922 return str_oneof(str
, clause
->str
);
925 logf("Incorrect tag: %d", clause
->type
);
932 static bool check_clauses(struct tagcache_search
*tcs
,
933 struct index_entry
*idx
,
934 struct tagcache_search_clause
**clause
, int count
)
938 #ifdef HAVE_TC_RAMCACHE
941 /* Go through all conditional clauses. */
942 for (i
= 0; i
< count
; i
++)
944 struct tagfile_entry
*tfe
;
949 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
951 if (!tagcache_is_numeric_tag(clause
[i
]->tag
))
953 if (clause
[i
]->tag
== tag_filename
)
955 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
960 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
965 if (!check_against_clause(seek
, str
, clause
[i
]))
972 /* Check for conditions. */
973 for (i
= 0; i
< count
; i
++)
975 struct tagfile_entry tfe
;
979 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
981 memset(str
, 0, sizeof str
);
982 if (!tagcache_is_numeric_tag(clause
[i
]->tag
))
984 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
985 lseek(fd
, seek
, SEEK_SET
);
986 ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
987 if (tfe
.tag_length
>= (int)sizeof(str
))
989 logf("Too long tag read!");
993 read(fd
, str
, tfe
.tag_length
);
995 /* Check if entry has been deleted. */
1000 if (!check_against_clause(seek
, str
, clause
[i
]))
1008 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
1009 struct tagcache_search_clause
**clause
, int count
)
1011 struct index_entry idx
;
1016 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
1019 return check_clauses(tcs
, &idx
, clause
, count
);
1022 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1026 /* If uniq buffer is not defined we must return true for search to work. */
1027 if (tcs
->unique_list
== NULL
1028 || (!tagcache_is_unique_tag(tcs
->type
)
1029 && !tagcache_is_numeric_tag(tcs
->type
)))
1034 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1036 /* Return false if entry is found. */
1037 if (tcs
->unique_list
[i
] == id
)
1041 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1043 tcs
->unique_list
[i
] = id
;
1044 tcs
->unique_list_count
++;
1050 static bool build_lookup_list(struct tagcache_search
*tcs
)
1052 struct index_entry entry
;
1055 tcs
->seek_list_count
= 0;
1057 #ifdef HAVE_TC_RAMCACHE
1062 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
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 tcs
->seek_list
[tcs
->seek_list_count
] = idx
->tag_seek
[tcs
->type
];
1094 tcs
->seek_flags
[tcs
->seek_list_count
] = idx
->flag
;
1095 tcs
->seek_list_count
++;
1100 return tcs
->seek_list_count
> 0;
1104 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1105 sizeof(struct master_header
), SEEK_SET
);
1107 while (ecread(tcs
->masterfd
, &entry
, 1, index_entry_ec
, tc_stat
.econ
)
1108 == sizeof(struct index_entry
))
1110 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1115 /* Check if entry has been deleted. */
1116 if (entry
.flag
& FLAG_DELETED
)
1119 /* Go through all filters.. */
1120 for (i
= 0; i
< tcs
->filter_count
; i
++)
1122 if (entry
.tag_seek
[tcs
->filter_tag
[i
]] != tcs
->filter_seek
[i
])
1126 if (i
< tcs
->filter_count
)
1129 /* Check for conditions. */
1130 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1133 /* Add to the seek list if not already in uniq buffer. */
1134 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1138 tcs
->seek_list
[tcs
->seek_list_count
] = entry
.tag_seek
[tcs
->type
];
1139 tcs
->seek_flags
[tcs
->seek_list_count
] = entry
.flag
;
1140 tcs
->seek_list_count
++;
1145 return tcs
->seek_list_count
> 0;
1149 static void remove_files(void)
1154 tc_stat
.ready
= false;
1155 tc_stat
.ramcache
= false;
1156 tc_stat
.econ
= false;
1157 remove(TAGCACHE_FILE_MASTER
);
1158 for (i
= 0; i
< TAG_COUNT
; i
++)
1160 if (tagcache_is_numeric_tag(i
))
1163 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1169 static bool check_all_headers(void)
1171 struct master_header myhdr
;
1172 struct tagcache_header tch
;
1176 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1182 logf("tagcache is dirty!");
1186 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1188 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1190 if (tagcache_is_numeric_tag(tag
))
1193 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1202 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1204 struct tagcache_header tag_hdr
;
1205 struct master_header master_hdr
;
1208 if (tcs
->initialized
)
1209 tagcache_search_finish(tcs
);
1214 memset(tcs
, 0, sizeof(struct tagcache_search
));
1215 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1218 tcs
->position
= sizeof(struct tagcache_header
);
1221 tcs
->seek_list_count
= 0;
1222 tcs
->filter_count
= 0;
1225 for (i
= 0; i
< TAG_COUNT
; i
++)
1228 #ifndef HAVE_TC_RAMCACHE
1229 tcs
->ramsearch
= false;
1231 tcs
->ramsearch
= tc_stat
.ramcache
;
1234 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1239 if (!tagcache_is_numeric_tag(tcs
->type
))
1241 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1242 if (tcs
->idxfd
[tcs
->type
] < 0)
1246 /* Always open as R/W so we can pass tcs to functions that modify data also
1247 * without failing. */
1248 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1250 if (tcs
->masterfd
< 0)
1255 tcs
->initialized
= true;
1261 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1262 void *buffer
, long length
)
1264 tcs
->unique_list
= (unsigned long *)buffer
;
1265 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1266 tcs
->unique_list_count
= 0;
1269 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1272 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1275 if (!tagcache_is_unique_tag(tag
) || tagcache_is_numeric_tag(tag
))
1278 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1279 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1280 tcs
->filter_count
++;
1285 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1286 struct tagcache_search_clause
*clause
)
1290 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1292 logf("Too many clauses");
1296 /* Check if there is already a similar filter in present (filters are
1297 * much faster than clauses).
1299 for (i
= 0; i
< tcs
->filter_count
; i
++)
1301 if (tcs
->filter_tag
[i
] == clause
->tag
)
1305 if (!tagcache_is_numeric_tag(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1309 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1310 tcs
->idxfd
[clause
->tag
] = open(buf
, O_RDONLY
);
1313 tcs
->clause
[tcs
->clause_count
] = clause
;
1314 tcs
->clause_count
++;
1319 /* TODO: Remove this mess. */
1320 #ifdef HAVE_DIRCACHE
1321 #define TAG_FILENAME_RAM(tcs) ((tcs->type == tag_filename) \
1322 ? ((flag & FLAG_DIRCACHE) && is_dircache_intact()) : 1)
1324 #define TAG_FILENAME_RAM(tcs) (tcs->type != tag_filename)
1327 static bool get_next(struct tagcache_search
*tcs
)
1329 static char buf
[TAG_MAXLEN
+32];
1330 struct tagfile_entry entry
;
1333 if (!tcs
->valid
|| !tc_stat
.ready
)
1336 if (tcs
->idxfd
[tcs
->type
] < 0 && !tagcache_is_numeric_tag(tcs
->type
)
1337 #ifdef HAVE_TC_RAMCACHE
1343 /* Relative fetch. */
1344 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1345 || tagcache_is_numeric_tag(tcs
->type
))
1347 /* Check for end of list. */
1348 if (tcs
->seek_list_count
== 0)
1350 /* Try to fetch more. */
1351 if (!build_lookup_list(tcs
))
1358 tcs
->seek_list_count
--;
1359 flag
= tcs
->seek_flags
[tcs
->seek_list_count
];
1361 /* Seek stream to the correct position and continue to direct fetch. */
1362 if ((!tcs
->ramsearch
|| !TAG_FILENAME_RAM(tcs
))
1363 && !tagcache_is_numeric_tag(tcs
->type
))
1365 if (!open_files(tcs
, tcs
->type
))
1368 lseek(tcs
->idxfd
[tcs
->type
], tcs
->seek_list
[tcs
->seek_list_count
], SEEK_SET
);
1371 tcs
->position
= tcs
->seek_list
[tcs
->seek_list_count
];
1374 if (tagcache_is_numeric_tag(tcs
->type
))
1376 snprintf(buf
, sizeof(buf
), "%d", tcs
->position
);
1377 tcs
->result_seek
= tcs
->position
;
1379 tcs
->result_len
= strlen(buf
) + 1;
1384 #ifdef HAVE_TC_RAMCACHE
1385 if (tcs
->ramsearch
&& TAG_FILENAME_RAM(tcs
))
1387 struct tagfile_entry
*ep
;
1389 if (tcs
->entry_count
== 0)
1396 tcs
->result_seek
= tcs
->position
;
1398 # ifdef HAVE_DIRCACHE
1399 if (tcs
->type
== tag_filename
)
1401 dircache_copy_path((struct dirent
*)tcs
->position
,
1404 tcs
->result_len
= strlen(buf
) + 1;
1405 tcs
->idx_id
= FLAG_GET_ATTR(flag
);
1406 tcs
->ramresult
= false;
1412 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1413 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1414 tcs
->result
= ep
->tag_data
;
1415 tcs
->result_len
= strlen(tcs
->result
) + 1;
1416 tcs
->idx_id
= ep
->idx_id
;
1417 tcs
->ramresult
= true;
1424 if (!open_files(tcs
, tcs
->type
))
1427 tcs
->result_seek
= lseek(tcs
->idxfd
[tcs
->type
], 0, SEEK_CUR
);
1428 if (ecread(tcs
->idxfd
[tcs
->type
], &entry
, 1,
1429 tagfile_entry_ec
, tc_stat
.econ
) != sizeof(struct tagfile_entry
))
1437 if (entry
.tag_length
> (long)sizeof(buf
))
1440 logf("too long tag #2");
1444 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1447 logf("read error #4");
1452 tcs
->result_len
= strlen(tcs
->result
) + 1;
1453 tcs
->idx_id
= entry
.idx_id
;
1454 tcs
->ramresult
= false;
1459 bool tagcache_get_next(struct tagcache_search
*tcs
)
1461 while (get_next(tcs
))
1463 if (tcs
->result_len
> 1)
1470 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1471 int tag
, char *buf
, long size
)
1473 struct index_entry idx
;
1476 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1479 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1482 static bool update_master_header(void)
1484 struct master_header myhdr
;
1490 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1493 myhdr
.serial
= current_tcmh
.serial
;
1494 myhdr
.commitid
= current_tcmh
.commitid
;
1497 lseek(fd
, 0, SEEK_SET
);
1498 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1501 #ifdef HAVE_TC_RAMCACHE
1504 hdr
->h
.serial
= current_tcmh
.serial
;
1505 hdr
->h
.commitid
= current_tcmh
.commitid
;
1514 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1516 struct tagentry
*entry
;
1518 if (tcs
->type
!= tag_title
)
1521 /* We will need reserve buffer for this. */
1524 struct tagfile_entry
*ep
;
1526 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1527 tcs
->seek_list
[tcs
->seek_list_count
];
1530 entry
= find_entry_ram();
1535 void tagcache_search_finish(struct tagcache_search
*tcs
)
1539 if (!tcs
->initialized
)
1542 if (tcs
->masterfd
>= 0)
1544 close(tcs
->masterfd
);
1548 for (i
= 0; i
< TAG_COUNT
; i
++)
1550 if (tcs
->idxfd
[i
] >= 0)
1552 close(tcs
->idxfd
[i
]);
1557 tcs
->ramsearch
= false;
1559 tcs
->initialized
= 0;
1564 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1565 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1567 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1570 static long get_tag_numeric(const struct index_entry
*entry
, int tag
)
1572 return check_virtual_tags(tag
, entry
);
1575 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1577 char* s
= get_tag(entry
, tag
)->tag_data
;
1578 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1581 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1583 struct index_entry
*entry
;
1589 /* Find the corresponding entry in tagcache. */
1590 idx_id
= find_entry_ram(filename
, NULL
);
1591 if (idx_id
< 0 || !tc_stat
.ramcache
)
1594 entry
= &hdr
->indices
[idx_id
];
1596 id3
->title
= get_tag_string(entry
, tag_title
);
1597 id3
->artist
= get_tag_string(entry
, tag_artist
);
1598 id3
->album
= get_tag_string(entry
, tag_album
);
1599 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1600 id3
->composer
= get_tag_string(entry
, tag_composer
);
1601 id3
->comment
= get_tag_string(entry
, tag_comment
);
1602 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1603 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1605 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
);
1606 id3
->rating
= get_tag_numeric(entry
, tag_rating
);
1607 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
);
1608 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
) / 10;
1609 id3
->year
= get_tag_numeric(entry
, tag_year
);
1611 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
);
1612 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
);
1613 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
);
1614 if (id3
->bitrate
== 0)
1621 static inline void write_item(const char *item
)
1623 int len
= strlen(item
) + 1;
1626 write(cachefd
, item
, len
);
1629 static int check_if_empty(char **tag
)
1633 if (*tag
== NULL
|| **tag
== '\0')
1636 return sizeof(UNTAGGED
); /* Tag length */
1639 length
= strlen(*tag
);
1640 if (length
> TAG_MAXLEN
)
1642 logf("over length tag: %s", *tag
);
1643 length
= TAG_MAXLEN
;
1644 (*tag
)[length
] = '\0';
1650 #define ADD_TAG(entry,tag,data) \
1652 entry.tag_offset[tag] = offset; \
1653 entry.tag_length[tag] = check_if_empty(data); \
1654 offset += entry.tag_length[tag]
1656 static void add_tagcache(char *path
, unsigned long mtime
1657 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1658 ,const struct dirent
*dc
1662 struct mp3entry id3
;
1663 struct temp_file_entry entry
;
1667 char tracknumfix
[3];
1669 int path_length
= strlen(path
);
1670 bool has_albumartist
;
1676 /* Check for overlength file path. */
1677 if (path_length
> TAG_MAXLEN
)
1679 /* Path can't be shortened. */
1680 logf("Too long path: %s", path
);
1684 /* Check if the file is supported. */
1685 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1688 /* Check if the file is already cached. */
1689 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1690 if (tc_stat
.ramcache
&& is_dircache_intact())
1692 idx_id
= find_entry_ram(path
, dc
);
1697 if (filenametag_fd
>= 0)
1699 idx_id
= find_entry_disk(path
);
1703 /* Check if file has been modified. */
1706 struct index_entry idx
;
1708 /* TODO: Mark that the index exists (for fast reverse scan) */
1709 //found_idx[idx_id/8] |= idx_id%8;
1711 if (!get_index(-1, idx_id
, &idx
, true))
1713 logf("failed to retrieve index entry");
1717 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1719 /* No changes to file. */
1723 /* Metadata might have been changed. Delete the entry. */
1724 logf("Re-adding: %s", path
);
1725 if (!delete_entry(idx_id
))
1727 logf("delete_entry failed: %d", idx_id
);
1732 fd
= open(path
, O_RDONLY
);
1735 logf("open fail: %s", path
);
1739 memset(&id3
, 0, sizeof(struct mp3entry
));
1740 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1741 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1742 ret
= get_metadata(&id3
, fd
, path
);
1748 logf("-> %s", path
);
1750 /* Generate track number if missing. */
1751 if (id3
.tracknum
<= 0)
1753 const char *p
= strrchr(path
, '.');
1756 p
= &path
[strlen(path
)-1];
1760 if (isdigit(*p
) && isdigit(*(p
-1)))
1762 tracknumfix
[1] = *p
--;
1763 tracknumfix
[0] = *p
;
1769 if (tracknumfix
[0] != '\0')
1771 id3
.tracknum
= atoi(tracknumfix
);
1772 /* Set a flag to indicate track number has been generated. */
1773 entry
.flag
|= FLAG_TRKNUMGEN
;
1777 /* Unable to generate track number. */
1783 entry
.tag_offset
[tag_year
] = id3
.year
;
1784 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1785 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1786 entry
.tag_offset
[tag_length
] = id3
.length
;
1787 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1788 entry
.tag_offset
[tag_mtime
] = mtime
;
1791 has_albumartist
= id3
.albumartist
!= NULL
1792 && strlen(id3
.albumartist
) > 0;
1793 has_grouping
= id3
.grouping
!= NULL
1794 && strlen(id3
.grouping
) > 0;
1796 ADD_TAG(entry
, tag_filename
, &path
);
1797 ADD_TAG(entry
, tag_title
, &id3
.title
);
1798 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1799 ADD_TAG(entry
, tag_album
, &id3
.album
);
1800 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1801 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1802 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1803 if (has_albumartist
)
1805 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1809 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1813 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1817 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1819 entry
.data_length
= offset
;
1821 /* Write the header */
1822 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1824 /* And tags also... Correct order is critical */
1826 write_item(id3
.title
);
1827 write_item(id3
.artist
);
1828 write_item(id3
.album
);
1829 write_item(id3
.genre_string
);
1830 write_item(id3
.composer
);
1831 write_item(id3
.comment
);
1832 if (has_albumartist
)
1834 write_item(id3
.albumartist
);
1838 write_item(id3
.artist
);
1842 write_item(id3
.grouping
);
1846 write_item(id3
.title
);
1848 total_entry_count
++;
1851 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1853 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1854 int len
= strlen(str
)+1;
1857 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1858 char buf
[TAG_MAXLEN
+32];
1860 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1861 buf
[i
] = tolower(str
[i
]);
1864 crc32
= crc_32(buf
, i
, 0xffffffff);
1868 /* Check if the crc does not exist -> entry does not exist for sure. */
1869 for (i
= 0; i
< tempbufidx
; i
++)
1871 if (crcbuf
[-i
] != crc32
)
1874 if (!strcasecmp(str
, index
[i
].str
))
1876 if (id
< 0 || id
>= lookup_buffer_depth
)
1878 logf("lookup buf overf.: %d", id
);
1882 lookup
[id
] = &index
[i
];
1888 /* Insert to CRC buffer. */
1889 crcbuf
[-tempbufidx
] = crc32
;
1892 /* Insert it to the buffer. */
1893 tempbuf_left
-= len
;
1894 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1897 if (id
>= lookup_buffer_depth
)
1899 logf("lookup buf overf. #2: %d", id
);
1905 lookup
[id
] = &index
[tempbufidx
];
1906 index
[tempbufidx
].idlist
.id
= id
;
1909 index
[tempbufidx
].idlist
.id
= -1;
1911 index
[tempbufidx
].idlist
.next
= NULL
;
1912 index
[tempbufidx
].idx_id
= idx_id
;
1913 index
[tempbufidx
].seek
= -1;
1914 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
1915 memcpy(index
[tempbufidx
].str
, str
, len
);
1922 static int compare(const void *p1
, const void *p2
)
1926 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
1927 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
1929 if (strcmp(e1
->str
, UNTAGGED
) == 0)
1931 if (strcmp(e2
->str
, UNTAGGED
) == 0)
1935 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
1938 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
1941 static int tempbuf_sort(int fd
)
1943 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1944 struct tagfile_entry fe
;
1948 /* Generate reverse lookup entries. */
1949 for (i
= 0; i
< lookup_buffer_depth
; i
++)
1951 struct tempbuf_id_list
*idlist
;
1956 if (lookup
[i
]->idlist
.id
== i
)
1959 idlist
= &lookup
[i
]->idlist
;
1960 while (idlist
->next
!= NULL
)
1961 idlist
= idlist
->next
;
1963 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
1964 if (tempbuf_left
- 4 < 0)
1967 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
1968 if (tempbuf_pos
& 0x03)
1970 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
1972 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
1974 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
1976 idlist
= idlist
->next
;
1978 idlist
->next
= NULL
;
1983 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
1984 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
1986 for (i
= 0; i
< tempbufidx
; i
++)
1988 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
1990 /* Fix the lookup list. */
1991 while (idlist
!= NULL
)
1993 if (idlist
->id
>= 0)
1994 lookup
[idlist
->id
] = &index
[i
];
1995 idlist
= idlist
->next
;
1998 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
1999 length
= strlen(index
[i
].str
) + 1;
2000 fe
.tag_length
= length
;
2001 fe
.idx_id
= index
[i
].idx_id
;
2003 /* Check the chunk alignment. */
2004 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2005 % TAGFILE_ENTRY_CHUNK_LENGTH
)
2007 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
2008 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
2009 % TAGFILE_ENTRY_CHUNK_LENGTH
);
2012 #ifdef TAGCACHE_STRICT_ALIGN
2013 /* Make sure the entry is long aligned. */
2014 if (index
[i
].seek
& 0x03)
2016 logf("tempbuf_sort: alignment error!");
2021 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2022 sizeof(struct tagfile_entry
))
2024 logf("tempbuf_sort: write error #1");
2028 if (write(fd
, index
[i
].str
, length
) != length
)
2030 logf("tempbuf_sort: write error #2");
2034 /* Write some padding. */
2035 if (fe
.tag_length
- length
> 0)
2036 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2042 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2044 if (id
< 0 || id
>= lookup_buffer_depth
)
2051 inline static int tempbuf_find_location(int id
)
2053 struct tempbuf_searchidx
*entry
;
2055 entry
= tempbuf_locate(id
);
2062 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2064 struct master_header tcmh
;
2065 struct index_entry idx
;
2068 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2070 int entries_processed
= 0;
2072 char buf
[TAG_MAXLEN
];
2074 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2076 logf("Building numeric indices...");
2077 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2079 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2082 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2084 if (masterfd_pos
== filesize(masterfd
))
2086 logf("we can't append!");
2091 while (entries_processed
< h
->entry_count
)
2093 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2095 /* Read in as many entries as possible. */
2096 for (i
= 0; i
< count
; i
++)
2098 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2101 /* Read in numeric data. */
2102 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2103 sizeof(struct temp_file_entry
))
2105 logf("read fail #1");
2110 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2113 * Read string data from the following tags:
2119 * A crc32 hash is calculated from the read data
2120 * and stored back to the data offset field kept in memory.
2122 #define tmpdb_read_string_tag(tag) \
2123 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2124 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2126 logf("read fail: buffer overflow"); \
2131 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2132 tfe->tag_length[tag]) \
2134 logf("read fail #2"); \
2139 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2140 lseek(tmpfd, datastart, SEEK_SET)
2142 tmpdb_read_string_tag(tag_filename
);
2143 tmpdb_read_string_tag(tag_artist
);
2144 tmpdb_read_string_tag(tag_album
);
2145 tmpdb_read_string_tag(tag_title
);
2147 /* Seek to the end of the string data. */
2148 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2151 /* Backup the master index position. */
2152 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2153 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2155 /* Check if we can resurrect some deleted runtime statistics data. */
2156 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2158 /* Read the index entry. */
2159 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2160 != sizeof(struct index_entry
))
2162 logf("read fail #3");
2168 * Skip unless the entry is marked as being deleted
2169 * or the data has already been resurrected.
2171 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2174 /* Now try to match the entry. */
2176 * To succesfully match a song, the following conditions
2179 * For numeric fields: tag_length
2180 * - Full identical match is required
2182 * If tag_filename matches, no further checking necessary.
2184 * For string hashes: tag_artist, tag_album, tag_title
2185 * - Two of these must match
2187 for (j
= 0; j
< count
; j
++)
2189 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2191 /* Try to match numeric fields first. */
2192 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2195 /* Now it's time to do the hash matching. */
2196 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2198 int match_count
= 0;
2200 /* No filename match, check if we can match two other tags. */
2201 #define tmpdb_match(tag) \
2202 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2205 tmpdb_match(tag_artist
);
2206 tmpdb_match(tag_album
);
2207 tmpdb_match(tag_title
);
2209 if (match_count
< 2)
2211 /* Still no match found, give up. */
2216 /* A match found, now copy & resurrect the statistical data. */
2217 #define tmpdb_copy_tag(tag) \
2218 tfe->tag_offset[tag] = idx.tag_seek[tag]
2220 tmpdb_copy_tag(tag_playcount
);
2221 tmpdb_copy_tag(tag_rating
);
2222 tmpdb_copy_tag(tag_playtime
);
2223 tmpdb_copy_tag(tag_lastplayed
);
2224 tmpdb_copy_tag(tag_commitid
);
2226 /* Avoid processing this entry again. */
2227 idx
.flag
|= FLAG_RESURRECTED
;
2229 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2230 if (ecwrite(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2231 != sizeof(struct index_entry
))
2233 logf("masterfd writeback fail #1");
2238 logf("Entry resurrected");
2243 /* Restore the master index position. */
2244 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2246 /* Commit the data to the index. */
2247 for (i
= 0; i
< count
; i
++)
2249 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2251 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2252 != sizeof(struct index_entry
))
2254 logf("read fail #3");
2259 for (j
= 0; j
< TAG_COUNT
; j
++)
2261 if (!tagcache_is_numeric_tag(j
))
2264 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2266 idx
.flag
= entrybuf
[i
].flag
;
2268 if (idx
.tag_seek
[tag_commitid
])
2270 /* Data has been resurrected. */
2271 idx
.flag
|= FLAG_DIRTYNUM
;
2273 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2275 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2276 idx
.flag
|= FLAG_DIRTYNUM
;
2279 /* Write back the updated index. */
2280 lseek(masterfd
, loc
, SEEK_SET
);
2281 if (ecwrite(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2282 != sizeof(struct index_entry
))
2290 entries_processed
+= count
;
2291 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2302 * == 0 temporary failure
2305 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2308 struct tagcache_header tch
;
2309 struct master_header tcmh
;
2310 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2312 char buf
[TAG_MAXLEN
+32];
2313 int fd
= -1, masterfd
;
2318 logf("Building index: %d", index_type
);
2320 /* Check the number of entries we need to allocate ram for. */
2321 commit_entry_count
= h
->entry_count
+ 1;
2323 masterfd
= open_master_fd(&tcmh
, false);
2326 commit_entry_count
+= tcmh
.tch
.entry_count
;
2330 remove_files(); /* Just to be sure we are clean. */
2332 /* Open the index file, which contains the tag names. */
2333 fd
= open_tag_fd(&tch
, index_type
, true);
2336 logf("tch.datasize=%ld", tch
.datasize
);
2337 lookup_buffer_depth
= 1 +
2338 /* First part */ commit_entry_count
+
2339 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2343 lookup_buffer_depth
= 1 +
2344 /* First part */ commit_entry_count
+
2345 /* Second part */ 0;
2348 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2349 logf("commit_entry_count=%ld", commit_entry_count
);
2351 /* Allocate buffer for all index entries from both old and new
2354 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2356 /* Allocate lookup buffer. The first portion of commit_entry_count
2357 * contains the new tags in the temporary file and the second
2358 * part for locating entries already in the db.
2361 * +---------+---------------------------+
2362 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2363 * +---------+---------------------------+
2365 * Old tags are inserted to a temporary buffer with position:
2366 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2367 * And new tags with index:
2368 * tempbuf_insert(idx, ...);
2370 * The buffer is sorted and written into tag file:
2371 * tempbuf_sort(...);
2372 * leaving master index locations messed up.
2374 * That is fixed using the lookup buffer for old tags:
2375 * new_seek = tempbuf_find_location(old_seek, ...);
2377 * new_seek = tempbuf_find_location(idx);
2379 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2380 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2381 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2383 /* And calculate the remaining data space used mainly for storing
2384 * tag data (strings). */
2385 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2386 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2388 logf("Buffer way too small!");
2395 * If tag file contains unique tags (sorted index), we will load
2396 * it entirely into memory so we can resort it later for use with
2399 if (tagcache_is_sorted_tag(index_type
))
2401 logf("loading tags...");
2402 for (i
= 0; i
< tch
.entry_count
; i
++)
2404 struct tagfile_entry entry
;
2405 int loc
= lseek(fd
, 0, SEEK_CUR
);
2408 if (ecread(fd
, &entry
, 1, tagfile_entry_ec
, tc_stat
.econ
)
2409 != sizeof(struct tagfile_entry
))
2411 logf("read error #7");
2416 if (entry
.tag_length
>= (int)sizeof(buf
))
2418 logf("too long tag #3");
2423 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2425 logf("read error #8");
2430 /* Skip deleted entries. */
2435 * Save the tag and tag id in the memory buffer. Tag id
2436 * is saved so we can later reindex the master lookup
2437 * table when the index gets resorted.
2439 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2440 + commit_entry_count
, entry
.idx_id
,
2441 tagcache_is_unique_tag(index_type
));
2452 tempbufidx
= tch
.entry_count
;
2457 * Creating new index file to store the tags. No need to preload
2458 * anything whether the index type is sorted or not.
2460 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2461 fd
= open(buf
, O_WRONLY
| O_CREAT
| O_TRUNC
);
2464 logf("%s open fail", buf
);
2468 tch
.magic
= TAGCACHE_MAGIC
;
2469 tch
.entry_count
= 0;
2472 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2473 != sizeof(struct tagcache_header
))
2475 logf("header write failed");
2481 /* Loading the tag lookup file as "master file". */
2482 logf("Loading index file");
2483 masterfd
= open(TAGCACHE_FILE_MASTER
, O_RDWR
);
2487 logf("Creating new DB");
2488 masterfd
= open(TAGCACHE_FILE_MASTER
, O_WRONLY
| O_CREAT
| O_TRUNC
);
2492 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER
);
2497 /* Write the header (write real values later). */
2498 memset(&tcmh
, 0, sizeof(struct master_header
));
2500 tcmh
.tch
.entry_count
= 0;
2501 tcmh
.tch
.datasize
= 0;
2503 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2505 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2510 * Master file already exists so we need to process the current
2515 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2516 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2518 logf("header error");
2525 * If we reach end of the master file, we need to expand it to
2526 * hold new tags. If the current index is not sorted, we can
2527 * simply append new data to end of the file.
2528 * However, if the index is sorted, we need to update all tag
2529 * pointers in the master file for the current index.
2531 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2533 if (masterfd_pos
== filesize(masterfd
))
2535 logf("appending...");
2541 * Load new unique tags in memory to be sorted later and added
2542 * to the master lookup file.
2544 if (tagcache_is_sorted_tag(index_type
))
2546 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2547 /* h is the header of the temporary file containing new tags. */
2548 logf("inserting new tags...");
2549 for (i
= 0; i
< h
->entry_count
; i
++)
2551 struct temp_file_entry entry
;
2553 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2554 sizeof(struct temp_file_entry
))
2556 logf("read fail #3");
2562 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2564 logf("too long entry!");
2569 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2570 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2571 entry
.tag_length
[index_type
])
2573 logf("read fail #4");
2578 if (tagcache_is_unique_tag(index_type
))
2579 error
= !tempbuf_insert(buf
, i
, -1, true);
2581 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2585 logf("insert error");
2590 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2591 entry
.tag_length
[index_type
], SEEK_CUR
);
2596 /* Sort the buffer data and write it to the index file. */
2597 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2598 i
= tempbuf_sort(fd
);
2601 logf("sorted %d tags", i
);
2604 * Now update all indexes in the master lookup file.
2606 logf("updating indices...");
2607 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2608 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2611 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2613 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2615 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2616 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2618 logf("read fail #5");
2622 lseek(masterfd
, loc
, SEEK_SET
);
2624 for (j
= 0; j
< idxbuf_pos
; j
++)
2626 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2628 /* We can just ignore deleted entries. */
2629 // idxbuf[j].tag_seek[index_type] = 0;
2633 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2634 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2635 + commit_entry_count
);
2637 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2639 logf("update error: %d/%d/%d",
2640 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2648 /* Write back the updated index. */
2649 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2650 index_entry_ec
, tc_stat
.econ
) !=
2651 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2662 * Walk through the temporary file containing the new tags.
2664 // build_normal_index(h, tmpfd, masterfd, idx);
2665 logf("updating new indices...");
2666 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2667 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2668 lseek(fd
, 0, SEEK_END
);
2669 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2673 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2676 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2680 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2682 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2683 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2685 logf("read fail #6");
2689 lseek(masterfd
, loc
, SEEK_SET
);
2692 /* Read entry headers. */
2693 for (j
= 0; j
< idxbuf_pos
; j
++)
2695 if (!tagcache_is_sorted_tag(index_type
))
2697 struct temp_file_entry entry
;
2698 struct tagfile_entry fe
;
2700 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2701 sizeof(struct temp_file_entry
))
2703 logf("read fail #7");
2709 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2711 logf("too long entry!");
2712 logf("length=%d", entry
.tag_length
[index_type
]);
2713 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2718 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2719 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2720 entry
.tag_length
[index_type
])
2722 logf("read fail #8");
2723 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2724 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2729 /* Write to index file. */
2730 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2731 fe
.tag_length
= entry
.tag_length
[index_type
];
2732 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2733 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2734 write(fd
, buf
, fe
.tag_length
);
2738 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2739 entry
.tag_length
[index_type
], SEEK_CUR
);
2743 /* Locate the correct entry from the sorted array. */
2744 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2745 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2747 logf("entry not found (%d)", j
);
2755 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2756 index_entry_ec
, tc_stat
.econ
) !=
2757 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2759 logf("tagcache: write fail #4");
2768 /* Finally write the header. */
2769 tch
.magic
= TAGCACHE_MAGIC
;
2770 tch
.entry_count
= tempbufidx
;
2771 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2772 lseek(fd
, 0, SEEK_SET
);
2773 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2775 if (index_type
!= tag_filename
)
2776 h
->datasize
+= tch
.datasize
;
2777 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2789 static bool commit(void)
2791 struct tagcache_header tch
;
2792 struct master_header tcmh
;
2796 #ifdef HAVE_DIRCACHE
2797 bool dircache_buffer_stolen
= false;
2799 bool local_allocation
= false;
2801 logf("committing tagcache");
2806 tmpfd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
2809 logf("nothing to commit");
2814 /* Load the header. */
2815 len
= sizeof(struct tagcache_header
);
2816 rc
= read(tmpfd
, &tch
, len
);
2818 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2820 logf("incorrect header");
2822 remove(TAGCACHE_FILE_TEMP
);
2826 if (tch
.entry_count
== 0)
2828 logf("nothing to commit");
2830 remove(TAGCACHE_FILE_TEMP
);
2834 #ifdef HAVE_EEPROM_SETTINGS
2835 remove(TAGCACHE_STATEFILE
);
2838 /* At first be sure to unload the ramcache! */
2839 #ifdef HAVE_TC_RAMCACHE
2840 tc_stat
.ramcache
= false;
2845 /* Try to steal every buffer we can :) */
2846 if (tempbuf_size
== 0)
2847 local_allocation
= true;
2849 #ifdef HAVE_DIRCACHE
2850 if (tempbuf_size
== 0)
2852 /* Try to steal the dircache buffer. */
2853 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2854 tempbuf_size
&= ~0x03;
2856 if (tempbuf_size
> 0)
2858 dircache_buffer_stolen
= true;
2863 #ifdef HAVE_TC_RAMCACHE
2864 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2866 tempbuf
= (char *)(hdr
+ 1);
2867 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2868 tempbuf_size
&= ~0x03;
2872 /* And finally fail if there are no buffers available. */
2873 if (tempbuf_size
== 0)
2875 logf("delaying commit until next boot");
2876 tc_stat
.commit_delayed
= true;
2882 logf("commit %ld entries...", tch
.entry_count
);
2884 /* Mark DB dirty so it will stay disabled if commit fails. */
2885 current_tcmh
.dirty
= true;
2886 update_master_header();
2888 /* Now create the index files. */
2889 tc_stat
.commit_step
= 0;
2891 tc_stat
.commit_delayed
= false;
2893 for (i
= 0; i
< TAG_COUNT
; i
++)
2897 if (tagcache_is_numeric_tag(i
))
2900 tc_stat
.commit_step
++;
2901 ret
= build_index(i
, &tch
, tmpfd
);
2905 logf("tagcache failed init");
2909 tc_stat
.commit_delayed
= true;
2910 tc_stat
.commit_step
= 0;
2916 if (!build_numeric_indices(&tch
, tmpfd
))
2918 logf("Failure to commit numeric indices");
2921 tc_stat
.commit_step
= 0;
2927 tc_stat
.commit_step
= 0;
2929 /* Update the master index headers. */
2930 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2936 tcmh
.tch
.entry_count
+= tch
.entry_count
;
2937 tcmh
.tch
.datasize
= sizeof(struct master_header
)
2938 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
2943 lseek(masterfd
, 0, SEEK_SET
);
2944 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2947 logf("tagcache committed");
2948 remove(TAGCACHE_FILE_TEMP
);
2949 tc_stat
.ready
= check_all_headers();
2950 tc_stat
.readyvalid
= true;
2952 if (local_allocation
)
2958 #ifdef HAVE_DIRCACHE
2959 /* Rebuild the dircache, if we stole the buffer. */
2960 if (dircache_buffer_stolen
)
2964 #ifdef HAVE_TC_RAMCACHE
2965 /* Reload tagcache. */
2966 if (tc_stat
.ramcache_allocated
> 0)
2967 tagcache_start_scan();
2975 static void allocate_tempbuf(void)
2977 /* Yeah, malloc would be really nice now :) */
2979 tempbuf_size
= 32*1024*1024;
2980 tempbuf
= malloc(tempbuf_size
);
2982 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
2983 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
2984 audiobuf
+= tempbuf_size
;
2988 static void free_tempbuf(void)
2990 if (tempbuf_size
== 0)
2996 audiobuf
-= tempbuf_size
;
3004 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
3006 struct index_entry idx
;
3011 if (!tagcache_is_numeric_tag(tag
))
3014 if (!get_index(masterfd
, idx_id
, &idx
, false))
3017 idx
.tag_seek
[tag
] = data
;
3018 idx
.flag
|= FLAG_DIRTYNUM
;
3020 return write_index(masterfd
, idx_id
, &idx
);
3024 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3027 struct master_header myhdr
;
3029 if (tcs
->masterfd
< 0)
3031 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3035 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3039 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
3041 static bool command_queue_is_full(void)
3045 next
= command_queue_widx
+ 1;
3046 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3049 return (next
== command_queue_ridx
);
3052 static bool command_queue_sync_callback(void)
3055 struct master_header myhdr
;
3058 mutex_lock(&command_queue_mutex
);
3060 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3063 while (command_queue_ridx
!= command_queue_widx
)
3065 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3067 switch (ce
->command
)
3069 case CMD_UPDATE_MASTER_HEADER
:
3072 update_master_header();
3074 /* Re-open the masterfd. */
3075 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3080 case CMD_UPDATE_NUMERIC
:
3082 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3087 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3088 command_queue_ridx
= 0;
3093 tc_stat
.queue_length
= 0;
3094 mutex_unlock(&command_queue_mutex
);
3098 static void run_command_queue(bool force
)
3100 if (COMMAND_QUEUE_IS_EMPTY
)
3103 if (force
|| command_queue_is_full())
3104 command_queue_sync_callback();
3106 register_storage_idle_func(command_queue_sync_callback
);
3109 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3115 mutex_lock(&command_queue_mutex
);
3116 next
= command_queue_widx
+ 1;
3117 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3120 /* Make sure queue is not full. */
3121 if (next
!= command_queue_ridx
)
3123 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3126 ce
->idx_id
= idx_id
;
3130 command_queue_widx
= next
;
3132 tc_stat
.queue_length
++;
3134 mutex_unlock(&command_queue_mutex
);
3138 /* Queue is full, try again later... */
3139 mutex_unlock(&command_queue_mutex
);
3144 long tagcache_increase_serial(void)
3154 old
= current_tcmh
.serial
++;
3155 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3160 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3162 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3164 #endif /* !__PCTOOL__ */
3166 long tagcache_get_serial(void)
3168 return current_tcmh
.serial
;
3171 long tagcache_get_commitid(void)
3173 return current_tcmh
.commitid
;
3176 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3181 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3182 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3184 if (*datastr
== '\0')
3187 if (*datastr
== '"' || *datastr
== '\\')
3190 buf
[i
] = *(datastr
++);
3193 strcpy(&buf
[i
], "\" ");
3195 write(fd
, buf
, i
+ 2);
3202 static bool read_tag(char *dest
, long size
,
3203 const char *src
, const char *tagstr
)
3206 char current_tag
[32];
3208 while (*src
!= '\0')
3210 /* Skip all whitespace */
3218 /* Read in tag name */
3219 while (*src
!= '=' && *src
!= ' ')
3221 current_tag
[pos
] = *src
;
3225 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3228 current_tag
[pos
] = '\0';
3230 /* Read in tag data */
3232 /* Find the start. */
3233 while (*src
!= '"' && *src
!= '\0')
3236 if (*src
== '\0' || *(++src
) == '\0')
3239 /* Read the data. */
3240 for (pos
= 0; pos
< size
; pos
++)
3247 dest
[pos
] = *(src
+1);
3267 if (!strcasecmp(tagstr
, current_tag
))
3274 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3276 struct index_entry idx
;
3277 char tag_data
[TAG_MAXLEN
+32];
3279 long masterfd
= (long)parameters
;
3280 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3288 logf("%d/%s", line_n
, buf
);
3289 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3291 logf("filename missing");
3296 idx_id
= find_index(tag_data
);
3299 logf("entry not found");
3303 if (!get_index(masterfd
, idx_id
, &idx
, false))
3305 logf("failed to retrieve index entry");
3309 /* Stop if tag has already been modified. */
3310 if (idx
.flag
& FLAG_DIRTYNUM
)
3313 logf("import: %s", tag_data
);
3315 idx
.flag
|= FLAG_DIRTYNUM
;
3316 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3320 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3321 tagcache_tag_to_str(import_tags
[i
])))
3326 data
= atoi(tag_data
);
3330 idx
.tag_seek
[import_tags
[i
]] = data
;
3332 if (import_tags
[i
] == tag_lastplayed
&& data
>= current_tcmh
.serial
)
3333 current_tcmh
.serial
= data
+ 1;
3334 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3335 current_tcmh
.commitid
= data
+ 1;
3338 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3341 bool tagcache_import_changelog(void)
3343 struct master_header myhdr
;
3344 struct tagcache_header tch
;
3355 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_RDONLY
);
3358 logf("failure to open changelog");
3362 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3370 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3372 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3373 parse_changelog_line
);
3378 if (filenametag_fd
>= 0)
3379 close(filenametag_fd
);
3383 update_master_header();
3388 #endif /* !__PCTOOL__ */
3390 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3392 struct master_header myhdr
;
3393 struct index_entry idx
;
3394 char buf
[TAG_MAXLEN
+32];
3402 if (!tagcache_search(tcs
, tag_filename
))
3405 /* Initialize the changelog */
3406 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_WRONLY
| O_CREAT
| O_TRUNC
);
3409 logf("failure to open changelog");
3413 if (tcs
->masterfd
< 0)
3415 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3420 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3421 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3424 write(clfd
, "## Changelog version 1\n", 23);
3426 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3428 if (ecread(tcs
->masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
3429 != sizeof(struct index_entry
))
3431 logf("read error #9");
3432 tagcache_search_finish(tcs
);
3437 /* Skip until the entry found has been modified. */
3438 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3441 /* Skip deleted entries too. */
3442 if (idx
.flag
& FLAG_DELETED
)
3445 /* Now retrieve all tags. */
3446 for (j
= 0; j
< TAG_COUNT
; j
++)
3448 if (tagcache_is_numeric_tag(j
))
3450 snprintf(temp
, sizeof temp
, "%d", idx
.tag_seek
[j
]);
3451 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3456 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3457 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3460 write(clfd
, "\n", 1);
3466 tagcache_search_finish(tcs
);
3471 static bool delete_entry(long idx_id
)
3476 struct index_entry idx
, myidx
;
3477 struct master_header myhdr
;
3478 char buf
[TAG_MAXLEN
+32];
3479 int in_use
[TAG_COUNT
];
3481 logf("delete_entry(): %ld", idx_id
);
3483 #ifdef HAVE_TC_RAMCACHE
3484 /* At first mark the entry removed from ram cache. */
3485 if (tc_stat
.ramcache
)
3486 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3489 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3492 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3493 if (ecread(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3494 != sizeof(struct index_entry
))
3496 logf("delete_entry(): read error");
3500 if (myidx
.flag
& FLAG_DELETED
)
3502 logf("delete_entry(): already deleted!");
3506 myidx
.flag
|= FLAG_DELETED
;
3507 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3508 if (ecwrite(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3509 != sizeof(struct index_entry
))
3511 logf("delete_entry(): write_error #1");
3515 /* Now check which tags are no longer in use (if any) */
3516 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3519 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3520 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3522 struct index_entry
*idxp
;
3524 #ifdef HAVE_TC_RAMCACHE
3525 /* Use RAM DB if available for greater speed */
3526 if (tc_stat
.ramcache
)
3527 idxp
= &hdr
->indices
[i
];
3531 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
3532 != sizeof(struct index_entry
))
3534 logf("delete_entry(): read error #2");
3540 if (idxp
->flag
& FLAG_DELETED
)
3543 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3545 if (tagcache_is_numeric_tag(tag
))
3548 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3553 /* Now delete all tags no longer in use. */
3554 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3556 struct tagcache_header tch
;
3557 int oldseek
= myidx
.tag_seek
[tag
];
3559 if (tagcache_is_numeric_tag(tag
))
3563 * Replace tag seek with a hash value of the field string data.
3564 * That way runtime statistics of moved or altered files can be
3567 #ifdef HAVE_TC_RAMCACHE
3568 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3570 struct tagfile_entry
*tfe
;
3571 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3573 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3574 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3575 myidx
.tag_seek
[tag
] = *seek
;
3580 struct tagfile_entry tfe
;
3582 /* Open the index file, which contains the tag names. */
3583 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3586 /* Skip the header block */
3587 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3588 if (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
3589 != sizeof(struct tagfile_entry
))
3591 logf("delete_entry(): read error #3");
3595 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3597 logf("delete_entry(): read error #4");
3601 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3606 logf("in use: %d/%d", tag
, in_use
[tag
]);
3615 #ifdef HAVE_TC_RAMCACHE
3616 /* Delete from ram. */
3617 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3619 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3620 tagentry
->tag_data
[0] = '\0';
3624 /* Open the index file, which contains the tag names. */
3627 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3631 /* Skip the header block */
3632 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3634 /* Debug, print 10 first characters of the tag
3637 logf("TAG:%s", buf);
3638 lseek(fd, -10, SEEK_CUR);
3641 /* Write first data byte in tag as \0 */
3644 /* Now tag data has been removed */
3649 /* Write index entry back into master index. */
3650 lseek(masterfd
, sizeof(struct master_header
) +
3651 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3652 if (ecwrite(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3653 != sizeof(struct index_entry
))
3655 logf("delete_entry(): write_error #2");
3674 * Returns true if there is an event waiting in the queue
3675 * that requires the current operation to be aborted.
3677 static bool check_event_queue(void)
3679 struct queue_event ev
;
3681 queue_wait_w_tmo(&tagcache_queue
, &ev
, 0);
3686 case SYS_USB_CONNECTED
:
3687 /* Put the event back into the queue. */
3688 queue_post(&tagcache_queue
, ev
.id
, ev
.data
);
3696 #ifdef HAVE_TC_RAMCACHE
3697 static bool allocate_tagcache(void)
3699 struct master_header tcmh
;
3702 /* Load the header. */
3703 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3712 * Now calculate the required cache size plus
3713 * some extra space for alignment fixes.
3715 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3716 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3717 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3718 memset(hdr
, 0, sizeof(struct ramcache_header
));
3719 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3720 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3721 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3726 # ifdef HAVE_EEPROM_SETTINGS
3727 static bool tagcache_dumpload(void)
3729 struct statefile_header shdr
;
3734 fd
= open(TAGCACHE_STATEFILE
, O_RDONLY
);
3737 logf("no tagcache statedump");
3741 /* Check the statefile memory placement */
3742 hdr
= buffer_alloc(0);
3743 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3744 if (rc
!= sizeof(struct statefile_header
)
3745 /* || (long)hdr != (long)shdr.hdr */)
3747 logf("incorrect statefile");
3753 offpos
= (long)hdr
- (long)shdr
.hdr
;
3755 /* Lets allocate real memory and load it */
3756 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3757 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3760 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3762 logf("read failure!");
3767 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3769 /* Now fix the pointers */
3770 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3771 for (i
= 0; i
< TAG_COUNT
; i
++)
3772 hdr
->tags
[i
] += offpos
;
3777 static bool tagcache_dumpsave(void)
3779 struct statefile_header shdr
;
3782 if (!tc_stat
.ramcache
)
3785 fd
= open(TAGCACHE_STATEFILE
, O_WRONLY
| O_CREAT
| O_TRUNC
);
3788 logf("failed to create a statedump");
3792 /* Create the header */
3794 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3795 write(fd
, &shdr
, sizeof(struct statefile_header
));
3797 /* And dump the data too */
3798 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3805 static bool load_tagcache(void)
3807 struct tagcache_header
*tch
;
3808 long bytesleft
= tc_stat
.ramcache_allocated
;
3809 struct index_entry
*idx
;
3814 # ifdef HAVE_DIRCACHE
3815 while (dircache_is_initializing())
3818 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3821 logf("loading tagcache to ram...");
3823 fd
= open(TAGCACHE_FILE_MASTER
, O_RDONLY
);
3826 logf("tagcache open failed");
3830 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3831 != sizeof(struct master_header
)
3832 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3834 logf("incorrect header");
3840 /* Load the master index table. */
3841 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3843 rc
= ecread(fd
, idx
, 1, index_entry_ec
, tc_stat
.econ
);
3844 if (rc
!= sizeof(struct index_entry
))
3846 logf("read error #10");
3851 bytesleft
-= sizeof(struct index_entry
);
3852 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3854 logf("too big tagcache.");
3864 /* Load the tags. */
3866 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3868 struct tagfile_entry
*fe
;
3869 char buf
[TAG_MAXLEN
+32];
3871 if (tagcache_is_numeric_tag(tag
))
3874 //p = ((void *)p+1);
3875 p
= (char *)((long)p
& ~0x03) + 0x04;
3878 /* Check the header. */
3879 tch
= (struct tagcache_header
*)p
;
3880 p
+= sizeof(struct tagcache_header
);
3882 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3885 for (hdr
->entry_count
[tag
] = 0;
3886 hdr
->entry_count
[tag
] < tch
->entry_count
;
3887 hdr
->entry_count
[tag
]++)
3891 if (do_timed_yield())
3893 /* Abort if we got a critical event in queue */
3894 if (check_event_queue())
3898 fe
= (struct tagfile_entry
*)p
;
3899 pos
= lseek(fd
, 0, SEEK_CUR
);
3900 rc
= ecread(fd
, fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
3901 if (rc
!= sizeof(struct tagfile_entry
))
3903 /* End of lookup table. */
3904 logf("read error #11");
3909 /* We have a special handling for the filename tags. */
3910 if (tag
== tag_filename
)
3912 # ifdef HAVE_DIRCACHE
3913 const struct dirent
*dc
;
3916 // FIXME: This is wrong!
3917 // idx = &hdr->indices[hdr->entry_count[i]];
3918 idx
= &hdr
->indices
[fe
->idx_id
];
3920 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
3924 logf("TAG:%s", buf
);
3925 logf("too long filename");
3930 rc
= read(fd
, buf
, fe
->tag_length
);
3931 if (rc
!= fe
->tag_length
)
3933 logf("read error #12");
3938 /* Check if the entry has already been removed */
3939 if (idx
->flag
& FLAG_DELETED
)
3942 /* This flag must not be used yet. */
3943 if (idx
->flag
& FLAG_DIRCACHE
)
3945 logf("internal error!");
3950 if (idx
->tag_seek
[tag
] != pos
)
3952 logf("corrupt data structures!");
3957 # ifdef HAVE_DIRCACHE
3958 if (dircache_is_enabled())
3960 dc
= dircache_get_entry_ptr(buf
);
3963 logf("Entry no longer valid.");
3965 delete_entry(fe
->idx_id
);
3969 idx
->flag
|= FLAG_DIRCACHE
;
3970 FLAG_SET_ATTR(idx
->flag
, fe
->idx_id
);
3971 idx
->tag_seek
[tag_filename
] = (long)dc
;
3976 /* This will be very slow unless dircache is enabled
3977 or target is flash based, but do it anyway for
3979 /* Check if entry has been removed. */
3980 if (global_settings
.tagcache_autoupdate
)
3982 if (!file_exists(buf
))
3984 logf("Entry no longer valid.");
3986 delete_entry(fe
->idx_id
);
3995 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
3998 logf("too big tagcache #2");
3999 logf("tl: %d", fe
->tag_length
);
4000 logf("bl: %ld", bytesleft
);
4006 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
4009 if (rc
!= fe
->tag_length
)
4011 logf("read error #13");
4012 logf("rc=0x%04x", rc
); // 0x431
4013 logf("len=0x%04x", fe
->tag_length
); // 0x4000
4014 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
4015 logf("tag=0x%02x", tag
); // 0x00
4023 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4024 logf("tagcache loaded into ram!");
4028 #endif /* HAVE_TC_RAMCACHE */
4030 static bool check_deleted_files(void)
4033 char buf
[TAG_MAXLEN
+32];
4034 struct tagfile_entry tfe
;
4036 logf("reverse scan...");
4037 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4038 fd
= open(buf
, O_RDONLY
);
4042 logf("%s open fail", buf
);
4046 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4047 while (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
4048 == sizeof(struct tagfile_entry
)
4050 && !check_event_queue()
4054 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4056 logf("too long tag");
4061 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4063 logf("read error #14");
4068 /* Check if the file has already deleted from the db. */
4072 /* Now check if the file exists. */
4073 if (!file_exists(buf
))
4075 logf("Entry no longer valid.");
4076 logf("-> %s / %d", buf
, tfe
.tag_length
);
4077 delete_entry(tfe
.idx_id
);
4088 static bool check_dir(const char *dirname
, int add_files
)
4092 int success
= false;
4093 int ignore
, unignore
;
4094 char newpath
[MAX_PATH
];
4096 dir
= opendir(dirname
);
4099 logf("tagcache: opendir() failed");
4103 /* check for a database.ignore file */
4104 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4105 ignore
= file_exists(newpath
);
4106 /* check for a database.unignore file */
4107 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4108 unignore
= file_exists(newpath
);
4110 /* don't do anything if both ignore and unignore are there */
4111 if (ignore
!= unignore
)
4112 add_files
= unignore
;
4114 /* Recursively scan the dir. */
4118 while (!check_event_queue())
4121 struct dirent
*entry
;
4123 entry
= readdir(dir
);
4131 if (!strcmp((char *)entry
->d_name
, ".") ||
4132 !strcmp((char *)entry
->d_name
, ".."))
4137 len
= strlen(curpath
);
4138 snprintf(&curpath
[len
], sizeof(curpath
) - len
, "/%s",
4141 processed_dir_count
++;
4142 if (entry
->attribute
& ATTR_DIRECTORY
)
4143 check_dir(curpath
, add_files
);
4146 tc_stat
.curentry
= curpath
;
4148 /* Add a new entry to the temporary db file. */
4149 add_tagcache(curpath
, (entry
->wrtdate
<< 16) | entry
->wrttime
4150 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4151 , dir
->internal_entry
4155 /* Wait until current path for debug screen is read and unset. */
4156 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4159 tc_stat
.curentry
= NULL
;
4162 curpath
[len
] = '\0';
4170 void tagcache_screensync_event(void)
4172 tc_stat
.curentry
= NULL
;
4175 void tagcache_screensync_enable(bool state
)
4177 tc_stat
.syncscreen
= state
;
4180 void tagcache_build(const char *path
)
4182 struct tagcache_header header
;
4187 total_entry_count
= 0;
4188 processed_dir_count
= 0;
4190 #ifdef HAVE_DIRCACHE
4191 while (dircache_is_initializing())
4195 logf("updating tagcache");
4197 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
4200 logf("skipping, cache already waiting for commit");
4205 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDWR
| O_CREAT
| O_TRUNC
);
4208 logf("master file open failed: %s", TAGCACHE_FILE_TEMP
);
4212 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4216 logf("Scanning files...");
4217 /* Scan for new files. */
4218 memset(&header
, 0, sizeof(struct tagcache_header
));
4219 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4221 if (strcmp("/", path
) != 0)
4222 strcpy(curpath
, path
);
4223 ret
= check_dir(path
, true);
4225 /* Write the header. */
4226 header
.magic
= TAGCACHE_MAGIC
;
4227 header
.datasize
= data_size
;
4228 header
.entry_count
= total_entry_count
;
4229 lseek(cachefd
, 0, SEEK_SET
);
4230 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4233 if (filenametag_fd
>= 0)
4235 close(filenametag_fd
);
4236 filenametag_fd
= -1;
4246 /* Commit changes to the database. */
4252 remove(TAGCACHE_FILE_TEMP
);
4253 logf("tagcache built!");
4259 #ifdef HAVE_TC_RAMCACHE
4262 /* Import runtime statistics if we just initialized the db. */
4263 if (hdr
->h
.serial
== 0)
4264 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4271 #ifdef HAVE_TC_RAMCACHE
4272 static void load_ramcache(void)
4279 /* At first we should load the cache (if exists). */
4280 tc_stat
.ramcache
= load_tagcache();
4282 if (!tc_stat
.ramcache
)
4284 /* If loading failed, it must indicate some problem with the db
4285 * so disable it entirely to prevent further issues. */
4286 tc_stat
.ready
= false;
4293 void tagcache_unload_ramcache(void)
4295 tc_stat
.ramcache
= false;
4296 /* Just to make sure there is no statefile present. */
4297 // remove(TAGCACHE_STATEFILE);
4302 static void tagcache_thread(void)
4304 struct queue_event ev
;
4305 bool check_done
= false;
4307 /* If the previous cache build/update was interrupted, commit
4308 * the changes first in foreground. */
4314 #ifdef HAVE_TC_RAMCACHE
4315 # ifdef HAVE_EEPROM_SETTINGS
4316 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
)
4317 check_done
= tagcache_dumpload();
4319 remove(TAGCACHE_STATEFILE
);
4322 /* Allocate space for the tagcache if found on disk. */
4323 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4324 allocate_tagcache();
4328 tc_stat
.initialized
= true;
4330 /* Don't delay bootup with the header check but do it on background. */
4332 tc_stat
.ready
= check_all_headers();
4333 tc_stat
.readyvalid
= true;
4337 run_command_queue(false);
4339 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4343 case Q_IMPORT_CHANGELOG
:
4344 tagcache_import_changelog();
4349 remove(TAGCACHE_FILE_TEMP
);
4350 tagcache_build("/");
4354 tagcache_build("/");
4355 #ifdef HAVE_TC_RAMCACHE
4358 check_deleted_files();
4364 if (check_done
|| !tc_stat
.ready
)
4367 #ifdef HAVE_TC_RAMCACHE
4368 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4371 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4372 tagcache_build("/");
4376 if (global_settings
.tagcache_autoupdate
)
4378 tagcache_build("/");
4380 /* This will be very slow unless dircache is enabled
4381 or target is flash based, but do it anyway for
4383 check_deleted_files();
4386 logf("tagcache check done");
4398 case SYS_USB_CONNECTED
:
4399 logf("USB: TagCache");
4400 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4401 usb_wait_for_disconnect(&tagcache_queue
);
4408 bool tagcache_prepare_shutdown(void)
4410 if (tagcache_get_commit_step() > 0)
4413 tagcache_stop_scan();
4414 while (read_lock
|| write_lock
)
4420 void tagcache_shutdown(void)
4422 /* Flush the command queue. */
4423 run_command_queue(true);
4425 #ifdef HAVE_EEPROM_SETTINGS
4426 if (tc_stat
.ramcache
)
4427 tagcache_dumpsave();
4431 static int get_progress(void)
4433 int total_count
= -1;
4435 #ifdef HAVE_DIRCACHE
4436 if (dircache_is_enabled())
4438 total_count
= dircache_get_entry_count();
4442 #ifdef HAVE_TC_RAMCACHE
4444 if (hdr
&& tc_stat
.ramcache
)
4445 total_count
= hdr
->h
.tch
.entry_count
;
4449 if (total_count
< 0)
4452 return processed_dir_count
* 100 / total_count
;
4455 struct tagcache_stat
* tagcache_get_stat(void)
4457 tc_stat
.progress
= get_progress();
4458 tc_stat
.processed_entries
= processed_dir_count
;
4463 void tagcache_start_scan(void)
4465 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4468 bool tagcache_update(void)
4473 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4477 bool tagcache_rebuild()
4479 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4483 void tagcache_stop_scan(void)
4485 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4488 #ifdef HAVE_TC_RAMCACHE
4489 bool tagcache_is_ramcache(void)
4491 return tc_stat
.ramcache
;
4495 #endif /* !__PCTOOL__ */
4498 void tagcache_init(void)
4500 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4501 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4502 filenametag_fd
= -1;
4503 write_lock
= read_lock
= 0;
4506 mutex_init(&command_queue_mutex
);
4507 queue_init(&tagcache_queue
, true);
4508 create_thread(tagcache_thread
, tagcache_stack
,
4509 sizeof(tagcache_stack
), 0, tagcache_thread_name
4510 IF_PRIO(, PRIORITY_BACKGROUND
)
4513 tc_stat
.initialized
= true;
4517 tc_stat
.ready
= check_all_headers();
4522 void tagcache_reverse_scan(void)
4524 logf("Checking for deleted files");
4525 check_deleted_files();
4529 bool tagcache_is_initialized(void)
4531 return tc_stat
.initialized
;
4533 bool tagcache_is_usable(void)
4535 return tc_stat
.initialized
&& tc_stat
.ready
;
4537 int tagcache_get_commit_step(void)
4539 return tc_stat
.commit_step
;
4541 int tagcache_get_max_commit_step(void)
4543 return (int)(sizeof(sorted_tags
)/sizeof(sorted_tags
[0]))+1;