1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
23 * ----------x---------x------------------x-----
25 * +---------------x-------+ | TagCache | Libraries
26 * | Modification routines | | Core |
27 * +-x---------x-----------+ | |
29 * | +------x-------------x-+ +-------------x-----+ |
30 * | | x==x Filters & clauses | |
31 * | | Search routines | +-------------------+ |
32 * | | x============================x DirCache
33 * | +-x--------------------+ | (optional)
35 * | | +-------------------------------+ +---------+ |
36 * | | | DB Commit (sort,unique,index) | | | |
37 * | | +-x--------------------------x--+ | Control | |
38 * | | | (R/W) | (R) | Thread | |
39 * | | | +----------------------+ | | | |
40 * | | | | TagCache DB Builder | | +---------+ |
41 * | | | +-x-------------x------+ | |
42 * | | | | (R) | (W) | |
43 * | | | | +--x--------x---------+ |
44 * | | | | | Temporary Commit DB | |
45 * | | | | +---------------------+ |
46 * +-x----x-------x--+ |
47 * | TagCache RAM DB x==\(W) +-----------------+ |
48 * +-----------------+ \===x | |
49 * | | | | (R) | Ram DB Loader x============x DirCache
50 * +-x----x---x---x---+ /==x | | (optional)
51 * | Tagcache Disk DB x==/ +-----------------+ |
52 * +------------------+ |
60 #include "ata_idle_notify.h"
79 #include "eeprom_settings.h"
83 #define yield() do { } while(0)
84 #define sim_sleep(timeout) do { } while(0)
85 #define do_timed_yield() do { } while(0)
89 /* Tag Cache thread. */
90 static struct event_queue tagcache_queue
;
91 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
92 static const char tagcache_thread_name
[] = "tagcache";
95 #define UNTAGGED "<Untagged>"
97 /* Previous path when scanning directory tree recursively. */
98 static char curpath
[TAG_MAXLEN
+32];
99 static long curpath_size
= sizeof(curpath
);
101 /* Used when removing duplicates. */
102 static char *tempbuf
; /* Allocated when needed. */
103 static long tempbufidx
; /* Current location in buffer. */
104 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
105 static long tempbuf_left
; /* Buffer space left. */
106 static long tempbuf_pos
;
108 /* Tags we want to get sorted (loaded to the tempbuf). */
109 static const int sorted_tags
[] = { tag_artist
, tag_album
, tag_genre
,
110 tag_composer
, tag_comment
, tag_albumartist
, tag_grouping
, tag_title
};
112 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
113 static const int unique_tags
[] = { tag_artist
, tag_album
, tag_genre
,
114 tag_composer
, tag_comment
, tag_albumartist
, tag_grouping
};
116 /* Numeric tags (we can use these tags with conditional clauses). */
117 static const int numeric_tags
[] = { tag_year
, tag_discnumber
,
118 tag_tracknumber
, tag_length
, tag_bitrate
, tag_playcount
, tag_rating
,
119 tag_playtime
, tag_lastplayed
, tag_commitid
, tag_mtime
,
120 tag_virt_length_min
, tag_virt_length_sec
,
121 tag_virt_playtime_min
, tag_virt_playtime_sec
,
122 tag_virt_entryage
, tag_virt_autoscore
};
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
{
153 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
154 static volatile int command_queue_widx
= 0;
155 static volatile int command_queue_ridx
= 0;
156 static struct mutex command_queue_mutex
;
158 /* Tag database structures. */
160 /* Variable-length tag entry in tag files. */
161 struct tagfile_entry
{
162 short tag_length
; /* Length of the data in bytes including '\0' */
163 short idx_id
; /* Corresponding entry location in index file of not unique tags */
164 char tag_data
[0]; /* Begin of the tag data */
167 /* Fixed-size tag entry in master db index. */
169 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
170 int32_t flag
; /* Status flags */
173 /* Header is the same in every file. */
174 struct tagcache_header
{
175 int32_t magic
; /* Header version number */
176 int32_t datasize
; /* Data size in bytes */
177 int32_t entry_count
; /* Number of entries in this file */
180 struct master_header
{
181 struct tagcache_header tch
;
182 int32_t serial
; /* Increasing counting number */
183 int32_t commitid
; /* Number of commits so far */
187 /* For the endianess correction */
188 static const char *tagfile_entry_ec
= "ss";
189 static const char *index_entry_ec
= "lllllllllllllllllllll"; /* (1 + TAG_COUNT) * l */
190 static const char *tagcache_header_ec
= "lll";
191 static const char *master_header_ec
= "llllll";
193 static struct master_header current_tcmh
;
195 #ifdef HAVE_TC_RAMCACHE
196 /* Header is created when loading database to ram. */
197 struct ramcache_header
{
198 struct master_header h
; /* Header from the master index */
199 struct index_entry
*indices
; /* Master index file content */
200 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
201 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
204 # ifdef HAVE_EEPROM_SETTINGS
205 struct statefile_header
{
206 struct ramcache_header
*hdr
;
207 struct tagcache_stat tc_stat
;
211 /* Pointer to allocated ramcache_header */
212 static struct ramcache_header
*hdr
;
216 * Full tag entries stored in a temporary file waiting
217 * for commit to the cache. */
218 struct temp_file_entry
{
219 long tag_offset
[TAG_COUNT
];
220 short tag_length
[TAG_COUNT
];
226 struct tempbuf_id_list
{
228 struct tempbuf_id_list
*next
;
231 struct tempbuf_searchidx
{
235 struct tempbuf_id_list idlist
;
238 /* Lookup buffer for fixing messed up index while after sorting. */
239 static long commit_entry_count
;
240 static long lookup_buffer_depth
;
241 static struct tempbuf_searchidx
**lookup
;
243 /* Used when building the temporary file. */
244 static int cachefd
= -1, filenametag_fd
;
245 static int total_entry_count
= 0;
246 static int data_size
= 0;
247 static int processed_dir_count
;
249 /* Thread safe locking */
250 static volatile int write_lock
;
251 static volatile int read_lock
;
253 static bool delete_entry(long idx_id
);
255 const char* tagcache_tag_to_str(int tag
)
257 return tags_str
[tag
];
260 bool tagcache_is_numeric_tag(int type
)
264 for (i
= 0; i
< (int)(sizeof(numeric_tags
)/sizeof(numeric_tags
[0])); i
++)
266 if (type
== numeric_tags
[i
])
273 bool tagcache_is_unique_tag(int type
)
277 for (i
= 0; i
< (int)(sizeof(unique_tags
)/sizeof(unique_tags
[0])); i
++)
279 if (type
== unique_tags
[i
])
286 bool tagcache_is_sorted_tag(int type
)
290 for (i
= 0; i
< (int)(sizeof(sorted_tags
)/sizeof(sorted_tags
[0])); i
++)
292 if (type
== sorted_tags
[i
])
301 * Returns true if specified flag is still present, i.e., dircache
302 * has not been reloaded.
304 static bool is_dircache_intact(void)
306 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
310 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
316 if (tagcache_is_numeric_tag(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
319 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
321 fd
= open(buf
, write
? O_RDWR
: O_RDONLY
);
324 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
325 tc_stat
.ready
= false;
329 /* Check the header. */
330 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
331 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
333 logf("header error");
334 tc_stat
.ready
= false;
342 static int open_master_fd(struct master_header
*hdr
, bool write
)
347 fd
= open(TAGCACHE_FILE_MASTER
, write
? O_RDWR
: O_RDONLY
);
350 logf("master file open failed for R/W");
351 tc_stat
.ready
= false;
355 tc_stat
.econ
= false;
357 /* Check the header. */
358 rc
= read(fd
, hdr
, sizeof(struct master_header
));
359 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
365 /* Trying to read again, this time with endianess correction enabled. */
366 lseek(fd
, 0, SEEK_SET
);
368 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
369 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
371 logf("header error");
372 tc_stat
.ready
= false;
383 static bool do_timed_yield(void)
385 /* Sorting can lock up for quite a while, so yield occasionally */
386 static long wakeup_tick
= 0;
387 if (current_tick
>= wakeup_tick
)
389 wakeup_tick
= current_tick
+ (HZ
/4);
397 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
398 static long find_entry_ram(const char *filename
,
399 const struct dirent
*dc
)
401 static long last_pos
= 0;
404 /* Check if we tagcache is loaded into ram. */
405 if (!tc_stat
.ramcache
)
409 dc
= dircache_get_entry_ptr(filename
);
413 logf("tagcache: file not found.");
424 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
426 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
428 last_pos
= MAX(0, i
- 3);
445 static long find_entry_disk(const char *filename
)
447 struct tagcache_header tch
;
448 static long last_pos
= -1;
449 long pos_history
[POS_HISTORY_COUNT
];
450 long pos_history_idx
= 0;
452 struct tagfile_entry tfe
;
454 char buf
[TAG_MAXLEN
+32];
465 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
472 lseek(fd
, last_pos
, SEEK_SET
);
474 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
478 pos
= lseek(fd
, 0, SEEK_CUR
);
479 for (i
= pos_history_idx
-1; i
>= 0; i
--)
480 pos_history
[i
+1] = pos_history
[i
];
481 pos_history
[0] = pos
;
483 if (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
484 != sizeof(struct tagfile_entry
))
489 if (tfe
.tag_length
>= (long)sizeof(buf
))
491 logf("too long tag #1");
497 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
499 logf("read error #2");
505 if (!strcasecmp(filename
, buf
))
507 last_pos
= pos_history
[pos_history_idx
];
512 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
526 if (fd
!= filenametag_fd
)
531 if (fd
!= filenametag_fd
)
537 static int find_index(const char *filename
)
541 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
542 if (tc_stat
.ramcache
&& is_dircache_intact())
543 idx_id
= find_entry_ram(filename
, NULL
);
547 idx_id
= find_entry_disk(filename
);
552 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
559 idx_id
= find_index(filename
);
563 if (!tagcache_search(tcs
, tag_filename
))
566 tcs
->entry_count
= 0;
567 tcs
->idx_id
= idx_id
;
572 static bool get_index(int masterfd
, int idxid
,
573 struct index_entry
*idx
, bool use_ram
)
575 bool localfd
= false;
579 logf("Incorrect idxid: %d", idxid
);
583 #ifdef HAVE_TC_RAMCACHE
584 if (tc_stat
.ramcache
&& use_ram
)
586 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
589 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
598 struct master_header tcmh
;
601 masterfd
= open_master_fd(&tcmh
, false);
606 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
607 + sizeof(struct master_header
), SEEK_SET
);
608 if (ecread(masterfd
, idx
, 1, index_entry_ec
, tc_stat
.econ
)
609 != sizeof(struct index_entry
))
611 logf("read error #3");
621 if (idx
->flag
& FLAG_DELETED
)
627 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
629 /* We need to exclude all memory only flags & tags when writing to disk. */
630 if (idx
->flag
& FLAG_DIRCACHE
)
632 logf("memory only flags!");
636 #ifdef HAVE_TC_RAMCACHE
637 /* Only update numeric data. Writing the whole index to RAM by memcpy
638 * destroys dircache pointers!
640 if (tc_stat
.ramcache
)
643 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
645 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
647 if (tagcache_is_numeric_tag(tag
))
649 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
653 /* Don't touch the dircache flag. */
654 idx_ram
->flag
= idx
->flag
| (idx_ram
->flag
& FLAG_DIRCACHE
);
658 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
659 + sizeof(struct master_header
), SEEK_SET
);
660 if (ecwrite(masterfd
, idx
, 1, index_entry_ec
, tc_stat
.econ
)
661 != sizeof(struct index_entry
))
663 logf("write error #3");
664 logf("idxid: %d", idxid
);
671 static bool open_files(struct tagcache_search
*tcs
, int tag
)
673 if (tcs
->idxfd
[tag
] < 0)
677 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
678 tcs
->idxfd
[tag
] = open(fn
, O_RDONLY
);
681 if (tcs
->idxfd
[tag
] < 0)
683 logf("File not open!");
690 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
691 int tag
, char *buf
, long size
)
693 struct tagfile_entry tfe
;
698 if (tagcache_is_numeric_tag(tag
))
701 seek
= idx
->tag_seek
[tag
];
704 logf("Retrieve failed");
708 #ifdef HAVE_TC_RAMCACHE
711 struct tagfile_entry
*ep
;
713 # ifdef HAVE_DIRCACHE
714 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
715 && is_dircache_intact())
717 dircache_copy_path((struct dirent
*)seek
,
723 if (tag
!= tag_filename
)
725 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
726 strncpy(buf
, ep
->tag_data
, size
-1);
733 if (!open_files(tcs
, tag
))
736 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
737 if (ecread(tcs
->idxfd
[tag
], &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
738 != sizeof(struct tagfile_entry
))
740 logf("read error #5");
744 if (tfe
.tag_length
>= size
)
746 logf("too small buffer");
750 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
753 logf("read error #6");
757 buf
[tfe
.tag_length
] = '\0';
762 static long check_virtual_tags(int tag
, const struct index_entry
*idx
)
768 case tag_virt_length_sec
:
769 data
= (idx
->tag_seek
[tag_length
]/1000) % 60;
772 case tag_virt_length_min
:
773 data
= (idx
->tag_seek
[tag_length
]/1000) / 60;
776 case tag_virt_playtime_sec
:
777 data
= (idx
->tag_seek
[tag_playtime
]/1000) % 60;
780 case tag_virt_playtime_min
:
781 data
= (idx
->tag_seek
[tag_playtime
]/1000) / 60;
784 case tag_virt_autoscore
:
785 if (idx
->tag_seek
[tag_length
] == 0
786 || idx
->tag_seek
[tag_playcount
] == 0)
792 data
= 100 * idx
->tag_seek
[tag_playtime
]
793 / idx
->tag_seek
[tag_length
]
794 / idx
->tag_seek
[tag_playcount
];
798 /* How many commits before the file has been added to the DB. */
799 case tag_virt_entryage
:
800 data
= current_tcmh
.commitid
- idx
->tag_seek
[tag_commitid
] - 1;
804 data
= idx
->tag_seek
[tag
];
810 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
812 struct index_entry idx
;
817 if (!tagcache_is_numeric_tag(tag
))
820 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
823 return check_virtual_tags(tag
, &idx
);
826 inline static bool str_ends_with(const char *str1
, const char *str2
)
828 int str_len
= strlen(str1
);
829 int clause_len
= strlen(str2
);
831 if (clause_len
> str_len
)
834 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
837 inline static bool str_oneof(const char *str
, const char *list
)
840 int l
, len
= strlen(str
);
844 sep
= strchr(list
, '|');
845 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
846 if ((l
==len
) && !strncasecmp(str
, list
, len
))
848 list
+= sep
? l
+ 1 : l
;
854 static bool check_against_clause(long numeric
, const char *str
,
855 const struct tagcache_search_clause
*clause
)
859 switch (clause
->type
)
862 return numeric
== clause
->numeric_data
;
864 return numeric
!= clause
->numeric_data
;
866 return numeric
> clause
->numeric_data
;
868 return numeric
>= clause
->numeric_data
;
870 return numeric
< clause
->numeric_data
;
872 return numeric
<= clause
->numeric_data
;
874 logf("Incorrect numeric tag: %d", clause
->type
);
879 switch (clause
->type
)
882 return !strcasecmp(clause
->str
, str
);
884 return strcasecmp(clause
->str
, str
);
886 return 0>strcasecmp(clause
->str
, str
);
888 return 0>=strcasecmp(clause
->str
, str
);
890 return 0<strcasecmp(clause
->str
, str
);
892 return 0<=strcasecmp(clause
->str
, str
);
893 case clause_contains
:
894 return (strcasestr(str
, clause
->str
) != NULL
);
895 case clause_not_contains
:
896 return (strcasestr(str
, clause
->str
) == NULL
);
897 case clause_begins_with
:
898 return (strcasestr(str
, clause
->str
) == str
);
899 case clause_not_begins_with
:
900 return (strcasestr(str
, clause
->str
) != str
);
901 case clause_ends_with
:
902 return str_ends_with(str
, clause
->str
);
903 case clause_not_ends_with
:
904 return !str_ends_with(str
, clause
->str
);
906 return str_oneof(str
, clause
->str
);
909 logf("Incorrect tag: %d", clause
->type
);
916 static bool check_clauses(struct tagcache_search
*tcs
,
917 struct index_entry
*idx
,
918 struct tagcache_search_clause
**clause
, int count
)
922 #ifdef HAVE_TC_RAMCACHE
925 /* Go through all conditional clauses. */
926 for (i
= 0; i
< count
; i
++)
928 struct tagfile_entry
*tfe
;
933 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
935 if (!tagcache_is_numeric_tag(clause
[i
]->tag
))
937 if (clause
[i
]->tag
== tag_filename
)
939 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
944 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
949 if (!check_against_clause(seek
, str
, clause
[i
]))
956 /* Check for conditions. */
957 for (i
= 0; i
< count
; i
++)
959 struct tagfile_entry tfe
;
963 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
965 memset(str
, 0, sizeof str
);
966 if (!tagcache_is_numeric_tag(clause
[i
]->tag
))
968 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
969 lseek(fd
, seek
, SEEK_SET
);
970 ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
971 if (tfe
.tag_length
>= (int)sizeof(str
))
973 logf("Too long tag read!");
977 read(fd
, str
, tfe
.tag_length
);
979 /* Check if entry has been deleted. */
984 if (!check_against_clause(seek
, str
, clause
[i
]))
992 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
993 struct tagcache_search_clause
**clause
, int count
)
995 struct index_entry idx
;
1000 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
1003 return check_clauses(tcs
, &idx
, clause
, count
);
1006 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1010 /* If uniq buffer is not defined we must return true for search to work. */
1011 if (tcs
->unique_list
== NULL
1012 || (!tagcache_is_unique_tag(tcs
->type
)
1013 && !tagcache_is_numeric_tag(tcs
->type
)))
1018 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1020 /* Return false if entry is found. */
1021 if (tcs
->unique_list
[i
] == id
)
1025 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1027 tcs
->unique_list
[i
] = id
;
1028 tcs
->unique_list_count
++;
1034 static bool build_lookup_list(struct tagcache_search
*tcs
)
1036 struct index_entry entry
;
1039 tcs
->seek_list_count
= 0;
1041 #ifdef HAVE_TC_RAMCACHE
1046 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
1048 struct index_entry
*idx
= &hdr
->indices
[i
];
1049 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1052 /* Skip deleted files. */
1053 if (idx
->flag
& FLAG_DELETED
)
1056 /* Go through all filters.. */
1057 for (j
= 0; j
< tcs
->filter_count
; j
++)
1059 if (idx
->tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1065 if (j
< tcs
->filter_count
)
1068 /* Check for conditions. */
1069 if (!check_clauses(tcs
, idx
, tcs
->clause
, tcs
->clause_count
))
1072 /* Add to the seek list if not already in uniq buffer. */
1073 if (!add_uniqbuf(tcs
, idx
->tag_seek
[tcs
->type
]))
1077 tcs
->seek_list
[tcs
->seek_list_count
] = idx
->tag_seek
[tcs
->type
];
1078 tcs
->seek_flags
[tcs
->seek_list_count
] = idx
->flag
;
1079 tcs
->seek_list_count
++;
1084 return tcs
->seek_list_count
> 0;
1088 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1089 sizeof(struct master_header
), SEEK_SET
);
1091 while (ecread(tcs
->masterfd
, &entry
, 1, index_entry_ec
, tc_stat
.econ
)
1092 == sizeof(struct index_entry
))
1094 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1099 /* Check if entry has been deleted. */
1100 if (entry
.flag
& FLAG_DELETED
)
1103 /* Go through all filters.. */
1104 for (i
= 0; i
< tcs
->filter_count
; i
++)
1106 if (entry
.tag_seek
[tcs
->filter_tag
[i
]] != tcs
->filter_seek
[i
])
1110 if (i
< tcs
->filter_count
)
1113 /* Check for conditions. */
1114 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1117 /* Add to the seek list if not already in uniq buffer. */
1118 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1122 tcs
->seek_list
[tcs
->seek_list_count
] = entry
.tag_seek
[tcs
->type
];
1123 tcs
->seek_flags
[tcs
->seek_list_count
] = entry
.flag
;
1124 tcs
->seek_list_count
++;
1129 return tcs
->seek_list_count
> 0;
1133 static void remove_files(void)
1138 tc_stat
.ready
= false;
1139 tc_stat
.ramcache
= false;
1140 tc_stat
.econ
= false;
1141 remove(TAGCACHE_FILE_MASTER
);
1142 for (i
= 0; i
< TAG_COUNT
; i
++)
1144 if (tagcache_is_numeric_tag(i
))
1147 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1153 static bool check_all_headers(void)
1155 struct master_header myhdr
;
1156 struct tagcache_header tch
;
1160 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1166 logf("tagcache is dirty!");
1170 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1172 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1174 if (tagcache_is_numeric_tag(tag
))
1177 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1186 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1188 struct tagcache_header tag_hdr
;
1189 struct master_header master_hdr
;
1192 if (tcs
->initialized
)
1193 tagcache_search_finish(tcs
);
1198 memset(tcs
, 0, sizeof(struct tagcache_search
));
1199 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1202 tcs
->position
= sizeof(struct tagcache_header
);
1205 tcs
->seek_list_count
= 0;
1206 tcs
->filter_count
= 0;
1209 for (i
= 0; i
< TAG_COUNT
; i
++)
1212 #ifndef HAVE_TC_RAMCACHE
1213 tcs
->ramsearch
= false;
1215 tcs
->ramsearch
= tc_stat
.ramcache
;
1218 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1223 if (!tagcache_is_numeric_tag(tcs
->type
))
1225 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1226 if (tcs
->idxfd
[tcs
->type
] < 0)
1230 /* Always open as R/W so we can pass tcs to functions that modify data also
1231 * without failing. */
1232 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1234 if (tcs
->masterfd
< 0)
1239 tcs
->initialized
= true;
1245 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1246 void *buffer
, long length
)
1248 tcs
->unique_list
= (unsigned long *)buffer
;
1249 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1250 tcs
->unique_list_count
= 0;
1253 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1256 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1259 if (!tagcache_is_unique_tag(tag
) || tagcache_is_numeric_tag(tag
))
1262 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1263 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1264 tcs
->filter_count
++;
1269 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1270 struct tagcache_search_clause
*clause
)
1274 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1276 logf("Too many clauses");
1280 /* Check if there is already a similar filter in present (filters are
1281 * much faster than clauses).
1283 for (i
= 0; i
< tcs
->filter_count
; i
++)
1285 if (tcs
->filter_tag
[i
] == clause
->tag
)
1289 if (!tagcache_is_numeric_tag(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1293 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1294 tcs
->idxfd
[clause
->tag
] = open(buf
, O_RDONLY
);
1297 tcs
->clause
[tcs
->clause_count
] = clause
;
1298 tcs
->clause_count
++;
1303 /* TODO: Remove this mess. */
1304 #ifdef HAVE_DIRCACHE
1305 #define TAG_FILENAME_RAM(tcs) ((tcs->type == tag_filename) \
1306 ? ((flag & FLAG_DIRCACHE) && is_dircache_intact()) : 1)
1308 #define TAG_FILENAME_RAM(tcs) (tcs->type != tag_filename)
1311 static bool get_next(struct tagcache_search
*tcs
)
1313 static char buf
[TAG_MAXLEN
+32];
1314 struct tagfile_entry entry
;
1317 if (!tcs
->valid
|| !tc_stat
.ready
)
1320 if (tcs
->idxfd
[tcs
->type
] < 0 && !tagcache_is_numeric_tag(tcs
->type
)
1321 #ifdef HAVE_TC_RAMCACHE
1327 /* Relative fetch. */
1328 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1329 || tagcache_is_numeric_tag(tcs
->type
))
1331 /* Check for end of list. */
1332 if (tcs
->seek_list_count
== 0)
1334 /* Try to fetch more. */
1335 if (!build_lookup_list(tcs
))
1342 tcs
->seek_list_count
--;
1343 flag
= tcs
->seek_flags
[tcs
->seek_list_count
];
1345 /* Seek stream to the correct position and continue to direct fetch. */
1346 if ((!tcs
->ramsearch
|| !TAG_FILENAME_RAM(tcs
))
1347 && !tagcache_is_numeric_tag(tcs
->type
))
1349 if (!open_files(tcs
, tcs
->type
))
1352 lseek(tcs
->idxfd
[tcs
->type
], tcs
->seek_list
[tcs
->seek_list_count
], SEEK_SET
);
1355 tcs
->position
= tcs
->seek_list
[tcs
->seek_list_count
];
1358 if (tagcache_is_numeric_tag(tcs
->type
))
1360 snprintf(buf
, sizeof(buf
), "%d", tcs
->position
);
1361 tcs
->result_seek
= tcs
->position
;
1363 tcs
->result_len
= strlen(buf
) + 1;
1368 #ifdef HAVE_TC_RAMCACHE
1369 if (tcs
->ramsearch
&& TAG_FILENAME_RAM(tcs
))
1371 struct tagfile_entry
*ep
;
1373 if (tcs
->entry_count
== 0)
1380 tcs
->result_seek
= tcs
->position
;
1382 # ifdef HAVE_DIRCACHE
1383 if (tcs
->type
== tag_filename
)
1385 dircache_copy_path((struct dirent
*)tcs
->position
,
1388 tcs
->result_len
= strlen(buf
) + 1;
1389 tcs
->idx_id
= FLAG_GET_ATTR(flag
);
1390 tcs
->ramresult
= false;
1396 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1397 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1398 tcs
->result
= ep
->tag_data
;
1399 tcs
->result_len
= strlen(tcs
->result
) + 1;
1400 tcs
->idx_id
= ep
->idx_id
;
1401 tcs
->ramresult
= true;
1408 if (!open_files(tcs
, tcs
->type
))
1411 tcs
->result_seek
= lseek(tcs
->idxfd
[tcs
->type
], 0, SEEK_CUR
);
1412 if (ecread(tcs
->idxfd
[tcs
->type
], &entry
, 1,
1413 tagfile_entry_ec
, tc_stat
.econ
) != sizeof(struct tagfile_entry
))
1421 if (entry
.tag_length
> (long)sizeof(buf
))
1424 logf("too long tag #2");
1428 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1431 logf("read error #4");
1436 tcs
->result_len
= strlen(tcs
->result
) + 1;
1437 tcs
->idx_id
= entry
.idx_id
;
1438 tcs
->ramresult
= false;
1443 bool tagcache_get_next(struct tagcache_search
*tcs
)
1445 while (get_next(tcs
))
1447 if (tcs
->result_len
> 1)
1454 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1455 int tag
, char *buf
, long size
)
1457 struct index_entry idx
;
1460 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1463 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1466 static bool update_master_header(void)
1468 struct master_header myhdr
;
1474 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1477 myhdr
.serial
= current_tcmh
.serial
;
1478 myhdr
.commitid
= current_tcmh
.commitid
;
1481 lseek(fd
, 0, SEEK_SET
);
1482 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1485 #ifdef HAVE_TC_RAMCACHE
1488 hdr
->h
.serial
= current_tcmh
.serial
;
1489 hdr
->h
.commitid
= current_tcmh
.commitid
;
1498 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1500 struct tagentry
*entry
;
1502 if (tcs
->type
!= tag_title
)
1505 /* We will need reserve buffer for this. */
1508 struct tagfile_entry
*ep
;
1510 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1511 tcs
->seek_list
[tcs
->seek_list_count
];
1514 entry
= find_entry_ram();
1519 void tagcache_search_finish(struct tagcache_search
*tcs
)
1523 if (!tcs
->initialized
)
1526 if (tcs
->masterfd
>= 0)
1528 close(tcs
->masterfd
);
1532 for (i
= 0; i
< TAG_COUNT
; i
++)
1534 if (tcs
->idxfd
[i
] >= 0)
1536 close(tcs
->idxfd
[i
]);
1541 tcs
->ramsearch
= false;
1543 tcs
->initialized
= 0;
1548 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1549 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1551 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1554 static long get_tag_numeric(const struct index_entry
*entry
, int tag
)
1556 return check_virtual_tags(tag
, entry
);
1559 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1561 char* s
= get_tag(entry
, tag
)->tag_data
;
1562 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1565 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1567 struct index_entry
*entry
;
1573 /* Find the corresponding entry in tagcache. */
1574 idx_id
= find_entry_ram(filename
, NULL
);
1575 if (idx_id
< 0 || !tc_stat
.ramcache
)
1578 entry
= &hdr
->indices
[idx_id
];
1580 id3
->title
= get_tag_string(entry
, tag_title
);
1581 id3
->artist
= get_tag_string(entry
, tag_artist
);
1582 id3
->album
= get_tag_string(entry
, tag_album
);
1583 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1584 id3
->composer
= get_tag_string(entry
, tag_composer
);
1585 id3
->comment
= get_tag_string(entry
, tag_comment
);
1586 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1587 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1589 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
);
1590 id3
->rating
= get_tag_numeric(entry
, tag_rating
);
1591 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
);
1592 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
) / 10;
1593 id3
->year
= get_tag_numeric(entry
, tag_year
);
1595 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
);
1596 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
);
1597 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
);
1598 if (id3
->bitrate
== 0)
1605 static inline void write_item(const char *item
)
1607 int len
= strlen(item
) + 1;
1610 write(cachefd
, item
, len
);
1613 static int check_if_empty(char **tag
)
1617 if (*tag
== NULL
|| **tag
== '\0')
1620 return sizeof(UNTAGGED
); /* Tag length */
1623 length
= strlen(*tag
);
1624 if (length
> TAG_MAXLEN
)
1626 logf("over length tag: %s", *tag
);
1627 length
= TAG_MAXLEN
;
1628 (*tag
)[length
] = '\0';
1634 #define ADD_TAG(entry,tag,data) \
1636 entry.tag_offset[tag] = offset; \
1637 entry.tag_length[tag] = check_if_empty(data); \
1638 offset += entry.tag_length[tag]
1640 static void add_tagcache(char *path
, unsigned long mtime
1641 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1642 ,const struct dirent
*dc
1646 struct mp3entry id3
;
1647 struct temp_file_entry entry
;
1651 char tracknumfix
[3];
1653 int path_length
= strlen(path
);
1654 bool has_albumartist
;
1660 /* Check for overlength file path. */
1661 if (path_length
> TAG_MAXLEN
)
1663 /* Path can't be shortened. */
1664 logf("Too long path: %s", path
);
1668 /* Check if the file is supported. */
1669 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1672 /* Check if the file is already cached. */
1673 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1674 if (tc_stat
.ramcache
&& is_dircache_intact())
1676 idx_id
= find_entry_ram(path
, dc
);
1681 if (filenametag_fd
>= 0)
1683 idx_id
= find_entry_disk(path
);
1687 /* Check if file has been modified. */
1690 struct index_entry idx
;
1692 if (!get_index(-1, idx_id
, &idx
, true))
1694 logf("failed to retrieve index entry");
1698 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1700 /* No changes to file. */
1704 /* Metadata might have been changed. Delete the entry. */
1705 logf("Re-adding: %s", path
);
1706 if (!delete_entry(idx_id
))
1708 logf("delete_entry failed: %d", idx_id
);
1713 fd
= open(path
, O_RDONLY
);
1716 logf("open fail: %s", path
);
1720 memset(&id3
, 0, sizeof(struct mp3entry
));
1721 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1722 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1723 ret
= get_metadata(&id3
, fd
, path
);
1729 logf("-> %s", path
);
1731 /* Generate track number if missing. */
1732 if (id3
.tracknum
<= 0)
1734 const char *p
= strrchr(path
, '.');
1737 p
= &path
[strlen(path
)-1];
1741 if (isdigit(*p
) && isdigit(*(p
-1)))
1743 tracknumfix
[1] = *p
--;
1744 tracknumfix
[0] = *p
;
1750 if (tracknumfix
[0] != '\0')
1752 id3
.tracknum
= atoi(tracknumfix
);
1753 /* Set a flag to indicate track number has been generated. */
1754 entry
.flag
|= FLAG_TRKNUMGEN
;
1758 /* Unable to generate track number. */
1764 entry
.tag_offset
[tag_year
] = id3
.year
;
1765 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1766 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1767 entry
.tag_offset
[tag_length
] = id3
.length
;
1768 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1769 entry
.tag_offset
[tag_mtime
] = mtime
;
1772 has_albumartist
= id3
.albumartist
!= NULL
1773 && strlen(id3
.albumartist
) > 0;
1774 has_grouping
= id3
.grouping
!= NULL
1775 && strlen(id3
.grouping
) > 0;
1777 ADD_TAG(entry
, tag_filename
, &path
);
1778 ADD_TAG(entry
, tag_title
, &id3
.title
);
1779 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1780 ADD_TAG(entry
, tag_album
, &id3
.album
);
1781 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1782 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1783 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1784 if (has_albumartist
)
1786 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1790 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1794 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1798 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1800 entry
.data_length
= offset
;
1802 /* Write the header */
1803 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1805 /* And tags also... Correct order is critical */
1807 write_item(id3
.title
);
1808 write_item(id3
.artist
);
1809 write_item(id3
.album
);
1810 write_item(id3
.genre_string
);
1811 write_item(id3
.composer
);
1812 write_item(id3
.comment
);
1813 if (has_albumartist
)
1815 write_item(id3
.albumartist
);
1819 write_item(id3
.artist
);
1823 write_item(id3
.grouping
);
1827 write_item(id3
.title
);
1829 total_entry_count
++;
1832 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1834 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1835 int len
= strlen(str
)+1;
1838 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1839 char buf
[TAG_MAXLEN
+32];
1841 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1842 buf
[i
] = tolower(str
[i
]);
1845 crc32
= crc_32(buf
, i
, 0xffffffff);
1849 /* Check if the crc does not exist -> entry does not exist for sure. */
1850 for (i
= 0; i
< tempbufidx
; i
++)
1852 if (crcbuf
[-i
] != crc32
)
1855 if (!strcasecmp(str
, index
[i
].str
))
1857 if (id
< 0 || id
>= lookup_buffer_depth
)
1859 logf("lookup buf overf.: %d", id
);
1863 lookup
[id
] = &index
[i
];
1869 /* Insert to CRC buffer. */
1870 crcbuf
[-tempbufidx
] = crc32
;
1873 /* Insert it to the buffer. */
1874 tempbuf_left
-= len
;
1875 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1878 if (id
>= lookup_buffer_depth
)
1880 logf("lookup buf overf. #2: %d", id
);
1886 lookup
[id
] = &index
[tempbufidx
];
1887 index
[tempbufidx
].idlist
.id
= id
;
1890 index
[tempbufidx
].idlist
.id
= -1;
1892 index
[tempbufidx
].idlist
.next
= NULL
;
1893 index
[tempbufidx
].idx_id
= idx_id
;
1894 index
[tempbufidx
].seek
= -1;
1895 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
1896 memcpy(index
[tempbufidx
].str
, str
, len
);
1903 static int compare(const void *p1
, const void *p2
)
1907 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
1908 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
1910 if (strcmp(e1
->str
, UNTAGGED
) == 0)
1912 if (strcmp(e2
->str
, UNTAGGED
) == 0)
1916 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
1919 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
1922 static int tempbuf_sort(int fd
)
1924 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1925 struct tagfile_entry fe
;
1929 /* Generate reverse lookup entries. */
1930 for (i
= 0; i
< lookup_buffer_depth
; i
++)
1932 struct tempbuf_id_list
*idlist
;
1937 if (lookup
[i
]->idlist
.id
== i
)
1940 idlist
= &lookup
[i
]->idlist
;
1941 while (idlist
->next
!= NULL
)
1942 idlist
= idlist
->next
;
1944 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
1945 if (tempbuf_left
- 4 < 0)
1948 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
1949 if (tempbuf_pos
& 0x03)
1951 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
1953 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
1955 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
1957 idlist
= idlist
->next
;
1959 idlist
->next
= NULL
;
1964 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
1965 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
1967 for (i
= 0; i
< tempbufidx
; i
++)
1969 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
1971 /* Fix the lookup list. */
1972 while (idlist
!= NULL
)
1974 if (idlist
->id
>= 0)
1975 lookup
[idlist
->id
] = &index
[i
];
1976 idlist
= idlist
->next
;
1979 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
1980 length
= strlen(index
[i
].str
) + 1;
1981 fe
.tag_length
= length
;
1982 fe
.idx_id
= index
[i
].idx_id
;
1984 /* Check the chunk alignment. */
1985 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
1986 % TAGFILE_ENTRY_CHUNK_LENGTH
)
1988 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
1989 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
1990 % TAGFILE_ENTRY_CHUNK_LENGTH
);
1993 #ifdef TAGCACHE_STRICT_ALIGN
1994 /* Make sure the entry is long aligned. */
1995 if (index
[i
].seek
& 0x03)
1997 logf("tempbuf_sort: alignment error!");
2002 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2003 sizeof(struct tagfile_entry
))
2005 logf("tempbuf_sort: write error #1");
2009 if (write(fd
, index
[i
].str
, length
) != length
)
2011 logf("tempbuf_sort: write error #2");
2015 /* Write some padding. */
2016 if (fe
.tag_length
- length
> 0)
2017 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2023 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2025 if (id
< 0 || id
>= lookup_buffer_depth
)
2032 inline static int tempbuf_find_location(int id
)
2034 struct tempbuf_searchidx
*entry
;
2036 entry
= tempbuf_locate(id
);
2043 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2045 struct master_header tcmh
;
2046 struct index_entry idx
;
2049 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2051 int entries_processed
= 0;
2053 char buf
[TAG_MAXLEN
];
2055 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2057 logf("Building numeric indices...");
2058 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2060 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2063 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2065 if (masterfd_pos
== filesize(masterfd
))
2067 logf("we can't append!");
2072 while (entries_processed
< h
->entry_count
)
2074 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2076 /* Read in as many entries as possible. */
2077 for (i
= 0; i
< count
; i
++)
2079 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2082 /* Read in numeric data. */
2083 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2084 sizeof(struct temp_file_entry
))
2086 logf("read fail #1");
2091 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2094 * Read string data from the following tags:
2100 * A crc32 hash is calculated from the read data
2101 * and stored back to the data offset field kept in memory.
2103 #define tmpdb_read_string_tag(tag) \
2104 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2105 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2107 logf("read fail: buffer overflow"); \
2112 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2113 tfe->tag_length[tag]) \
2115 logf("read fail #2"); \
2120 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2121 lseek(tmpfd, datastart, SEEK_SET)
2123 tmpdb_read_string_tag(tag_filename
);
2124 tmpdb_read_string_tag(tag_artist
);
2125 tmpdb_read_string_tag(tag_album
);
2126 tmpdb_read_string_tag(tag_title
);
2128 /* Seek to the end of the string data. */
2129 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2132 /* Backup the master index position. */
2133 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2134 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2136 /* Check if we can resurrect some deleted runtime statistics data. */
2137 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2139 /* Read the index entry. */
2140 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2141 != sizeof(struct index_entry
))
2143 logf("read fail #3");
2149 * Skip unless the entry is marked as being deleted
2150 * or the data has already been resurrected.
2152 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2155 /* Now try to match the entry. */
2157 * To succesfully match a song, the following conditions
2160 * For numeric fields: tag_length
2161 * - Full identical match is required
2163 * If tag_filename matches, no further checking necessary.
2165 * For string hashes: tag_artist, tag_album, tag_title
2166 * - Two of these must match
2168 for (j
= 0; j
< count
; j
++)
2170 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2172 /* Try to match numeric fields first. */
2173 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2176 /* Now it's time to do the hash matching. */
2177 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2179 int match_count
= 0;
2181 /* No filename match, check if we can match two other tags. */
2182 #define tmpdb_match(tag) \
2183 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2186 tmpdb_match(tag_artist
);
2187 tmpdb_match(tag_album
);
2188 tmpdb_match(tag_title
);
2190 if (match_count
< 2)
2192 /* Still no match found, give up. */
2197 /* A match found, now copy & resurrect the statistical data. */
2198 #define tmpdb_copy_tag(tag) \
2199 tfe->tag_offset[tag] = idx.tag_seek[tag]
2201 tmpdb_copy_tag(tag_playcount
);
2202 tmpdb_copy_tag(tag_rating
);
2203 tmpdb_copy_tag(tag_playtime
);
2204 tmpdb_copy_tag(tag_lastplayed
);
2205 tmpdb_copy_tag(tag_commitid
);
2207 /* Avoid processing this entry again. */
2208 idx
.flag
|= FLAG_RESURRECTED
;
2210 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2211 if (ecwrite(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2212 != sizeof(struct index_entry
))
2214 logf("masterfd writeback fail #1");
2219 logf("Entry resurrected");
2224 /* Restore the master index position. */
2225 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2227 /* Commit the data to the index. */
2228 for (i
= 0; i
< count
; i
++)
2230 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2232 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2233 != sizeof(struct index_entry
))
2235 logf("read fail #3");
2240 for (j
= 0; j
< TAG_COUNT
; j
++)
2242 if (!tagcache_is_numeric_tag(j
))
2245 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2247 idx
.flag
= entrybuf
[i
].flag
;
2249 if (idx
.tag_seek
[tag_commitid
])
2251 /* Data has been resurrected. */
2252 idx
.flag
|= FLAG_DIRTYNUM
;
2254 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2256 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2257 idx
.flag
|= FLAG_DIRTYNUM
;
2260 /* Write back the updated index. */
2261 lseek(masterfd
, loc
, SEEK_SET
);
2262 if (ecwrite(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2263 != sizeof(struct index_entry
))
2271 entries_processed
+= count
;
2272 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2283 * == 0 temporary failure
2286 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2289 struct tagcache_header tch
;
2290 struct master_header tcmh
;
2291 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2293 char buf
[TAG_MAXLEN
+32];
2294 int fd
= -1, masterfd
;
2299 logf("Building index: %d", index_type
);
2301 /* Check the number of entries we need to allocate ram for. */
2302 commit_entry_count
= h
->entry_count
+ 1;
2304 masterfd
= open_master_fd(&tcmh
, false);
2307 commit_entry_count
+= tcmh
.tch
.entry_count
;
2311 remove_files(); /* Just to be sure we are clean. */
2313 /* Open the index file, which contains the tag names. */
2314 fd
= open_tag_fd(&tch
, index_type
, true);
2317 logf("tch.datasize=%ld", tch
.datasize
);
2318 lookup_buffer_depth
= 1 +
2319 /* First part */ commit_entry_count
+
2320 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2324 lookup_buffer_depth
= 1 +
2325 /* First part */ commit_entry_count
+
2326 /* Second part */ 0;
2329 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2330 logf("commit_entry_count=%ld", commit_entry_count
);
2332 /* Allocate buffer for all index entries from both old and new
2335 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2337 /* Allocate lookup buffer. The first portion of commit_entry_count
2338 * contains the new tags in the temporary file and the second
2339 * part for locating entries already in the db.
2342 * +---------+---------------------------+
2343 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2344 * +---------+---------------------------+
2346 * Old tags are inserted to a temporary buffer with position:
2347 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2348 * And new tags with index:
2349 * tempbuf_insert(idx, ...);
2351 * The buffer is sorted and written into tag file:
2352 * tempbuf_sort(...);
2353 * leaving master index locations messed up.
2355 * That is fixed using the lookup buffer for old tags:
2356 * new_seek = tempbuf_find_location(old_seek, ...);
2358 * new_seek = tempbuf_find_location(idx);
2360 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2361 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2362 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2364 /* And calculate the remaining data space used mainly for storing
2365 * tag data (strings). */
2366 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2367 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2369 logf("Buffer way too small!");
2376 * If tag file contains unique tags (sorted index), we will load
2377 * it entirely into memory so we can resort it later for use with
2380 if (tagcache_is_sorted_tag(index_type
))
2382 logf("loading tags...");
2383 for (i
= 0; i
< tch
.entry_count
; i
++)
2385 struct tagfile_entry entry
;
2386 int loc
= lseek(fd
, 0, SEEK_CUR
);
2389 if (ecread(fd
, &entry
, 1, tagfile_entry_ec
, tc_stat
.econ
)
2390 != sizeof(struct tagfile_entry
))
2392 logf("read error #7");
2397 if (entry
.tag_length
>= (int)sizeof(buf
))
2399 logf("too long tag #3");
2404 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2406 logf("read error #8");
2411 /* Skip deleted entries. */
2416 * Save the tag and tag id in the memory buffer. Tag id
2417 * is saved so we can later reindex the master lookup
2418 * table when the index gets resorted.
2420 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2421 + commit_entry_count
, entry
.idx_id
,
2422 tagcache_is_unique_tag(index_type
));
2433 tempbufidx
= tch
.entry_count
;
2438 * Creating new index file to store the tags. No need to preload
2439 * anything whether the index type is sorted or not.
2441 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2442 fd
= open(buf
, O_WRONLY
| O_CREAT
| O_TRUNC
);
2445 logf("%s open fail", buf
);
2449 tch
.magic
= TAGCACHE_MAGIC
;
2450 tch
.entry_count
= 0;
2453 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2454 != sizeof(struct tagcache_header
))
2456 logf("header write failed");
2462 /* Loading the tag lookup file as "master file". */
2463 logf("Loading index file");
2464 masterfd
= open(TAGCACHE_FILE_MASTER
, O_RDWR
);
2468 logf("Creating new DB");
2469 masterfd
= open(TAGCACHE_FILE_MASTER
, O_WRONLY
| O_CREAT
| O_TRUNC
);
2473 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER
);
2478 /* Write the header (write real values later). */
2479 memset(&tcmh
, 0, sizeof(struct master_header
));
2481 tcmh
.tch
.entry_count
= 0;
2482 tcmh
.tch
.datasize
= 0;
2484 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2486 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2491 * Master file already exists so we need to process the current
2496 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2497 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2499 logf("header error");
2506 * If we reach end of the master file, we need to expand it to
2507 * hold new tags. If the current index is not sorted, we can
2508 * simply append new data to end of the file.
2509 * However, if the index is sorted, we need to update all tag
2510 * pointers in the master file for the current index.
2512 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2514 if (masterfd_pos
== filesize(masterfd
))
2516 logf("appending...");
2522 * Load new unique tags in memory to be sorted later and added
2523 * to the master lookup file.
2525 if (tagcache_is_sorted_tag(index_type
))
2527 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2528 /* h is the header of the temporary file containing new tags. */
2529 logf("inserting new tags...");
2530 for (i
= 0; i
< h
->entry_count
; i
++)
2532 struct temp_file_entry entry
;
2534 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2535 sizeof(struct temp_file_entry
))
2537 logf("read fail #3");
2543 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2545 logf("too long entry!");
2550 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2551 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2552 entry
.tag_length
[index_type
])
2554 logf("read fail #4");
2559 if (tagcache_is_unique_tag(index_type
))
2560 error
= !tempbuf_insert(buf
, i
, -1, true);
2562 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2566 logf("insert error");
2571 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2572 entry
.tag_length
[index_type
], SEEK_CUR
);
2577 /* Sort the buffer data and write it to the index file. */
2578 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2579 i
= tempbuf_sort(fd
);
2582 logf("sorted %d tags", i
);
2585 * Now update all indexes in the master lookup file.
2587 logf("updating indices...");
2588 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2589 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2592 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2594 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2596 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2597 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2599 logf("read fail #5");
2603 lseek(masterfd
, loc
, SEEK_SET
);
2605 for (j
= 0; j
< idxbuf_pos
; j
++)
2607 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2609 /* We can just ignore deleted entries. */
2610 // idxbuf[j].tag_seek[index_type] = 0;
2614 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2615 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2616 + commit_entry_count
);
2618 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2620 logf("update error: %d/%d/%ld",
2621 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2629 /* Write back the updated index. */
2630 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2631 index_entry_ec
, tc_stat
.econ
) !=
2632 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2643 * Walk through the temporary file containing the new tags.
2645 // build_normal_index(h, tmpfd, masterfd, idx);
2646 logf("updating new indices...");
2647 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2648 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2649 lseek(fd
, 0, SEEK_END
);
2650 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2654 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2657 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2661 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2663 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2664 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2666 logf("read fail #6");
2670 lseek(masterfd
, loc
, SEEK_SET
);
2673 /* Read entry headers. */
2674 for (j
= 0; j
< idxbuf_pos
; j
++)
2676 if (!tagcache_is_sorted_tag(index_type
))
2678 struct temp_file_entry entry
;
2679 struct tagfile_entry fe
;
2681 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2682 sizeof(struct temp_file_entry
))
2684 logf("read fail #7");
2690 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2692 logf("too long entry!");
2693 logf("length=%d", entry
.tag_length
[index_type
]);
2694 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2699 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2700 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2701 entry
.tag_length
[index_type
])
2703 logf("read fail #8");
2704 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2705 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2710 /* Write to index file. */
2711 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2712 fe
.tag_length
= entry
.tag_length
[index_type
];
2713 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2714 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2715 write(fd
, buf
, fe
.tag_length
);
2719 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2720 entry
.tag_length
[index_type
], SEEK_CUR
);
2724 /* Locate the correct entry from the sorted array. */
2725 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2726 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2728 logf("entry not found (%d)", j
);
2736 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2737 index_entry_ec
, tc_stat
.econ
) !=
2738 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2740 logf("tagcache: write fail #4");
2749 /* Finally write the header. */
2750 tch
.magic
= TAGCACHE_MAGIC
;
2751 tch
.entry_count
= tempbufidx
;
2752 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2753 lseek(fd
, 0, SEEK_SET
);
2754 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2756 if (index_type
!= tag_filename
)
2757 h
->datasize
+= tch
.datasize
;
2758 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2770 static bool commit(void)
2772 struct tagcache_header tch
;
2773 struct master_header tcmh
;
2777 #ifdef HAVE_DIRCACHE
2778 bool dircache_buffer_stolen
= false;
2780 bool local_allocation
= false;
2782 logf("committing tagcache");
2787 tmpfd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
2790 logf("nothing to commit");
2795 /* Load the header. */
2796 len
= sizeof(struct tagcache_header
);
2797 rc
= read(tmpfd
, &tch
, len
);
2799 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2801 logf("incorrect header");
2803 remove(TAGCACHE_FILE_TEMP
);
2807 if (tch
.entry_count
== 0)
2809 logf("nothing to commit");
2811 remove(TAGCACHE_FILE_TEMP
);
2815 #ifdef HAVE_EEPROM_SETTINGS
2816 remove(TAGCACHE_STATEFILE
);
2819 /* At first be sure to unload the ramcache! */
2820 #ifdef HAVE_TC_RAMCACHE
2821 tc_stat
.ramcache
= false;
2826 /* Try to steal every buffer we can :) */
2827 if (tempbuf_size
== 0)
2828 local_allocation
= true;
2830 #ifdef HAVE_DIRCACHE
2831 if (tempbuf_size
== 0)
2833 /* Try to steal the dircache buffer. */
2834 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2835 tempbuf_size
&= ~0x03;
2837 if (tempbuf_size
> 0)
2839 dircache_buffer_stolen
= true;
2844 #ifdef HAVE_TC_RAMCACHE
2845 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2847 tempbuf
= (char *)(hdr
+ 1);
2848 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2849 tempbuf_size
&= ~0x03;
2853 /* And finally fail if there are no buffers available. */
2854 if (tempbuf_size
== 0)
2856 logf("delaying commit until next boot");
2857 tc_stat
.commit_delayed
= true;
2863 logf("commit %ld entries...", tch
.entry_count
);
2865 /* Mark DB dirty so it will stay disabled if commit fails. */
2866 current_tcmh
.dirty
= true;
2867 update_master_header();
2869 /* Now create the index files. */
2870 tc_stat
.commit_step
= 0;
2872 tc_stat
.commit_delayed
= false;
2874 for (i
= 0; i
< TAG_COUNT
; i
++)
2878 if (tagcache_is_numeric_tag(i
))
2881 tc_stat
.commit_step
++;
2882 ret
= build_index(i
, &tch
, tmpfd
);
2886 logf("tagcache failed init");
2890 tc_stat
.commit_delayed
= true;
2891 tc_stat
.commit_step
= 0;
2897 if (!build_numeric_indices(&tch
, tmpfd
))
2899 logf("Failure to commit numeric indices");
2902 tc_stat
.commit_step
= 0;
2908 tc_stat
.commit_step
= 0;
2910 /* Update the master index headers. */
2911 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2917 tcmh
.tch
.entry_count
+= tch
.entry_count
;
2918 tcmh
.tch
.datasize
= sizeof(struct master_header
)
2919 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
2924 lseek(masterfd
, 0, SEEK_SET
);
2925 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2928 logf("tagcache committed");
2929 remove(TAGCACHE_FILE_TEMP
);
2930 tc_stat
.ready
= check_all_headers();
2931 tc_stat
.readyvalid
= true;
2933 if (local_allocation
)
2939 #ifdef HAVE_DIRCACHE
2940 /* Rebuild the dircache, if we stole the buffer. */
2941 if (dircache_buffer_stolen
)
2945 #ifdef HAVE_TC_RAMCACHE
2946 /* Reload tagcache. */
2947 if (tc_stat
.ramcache_allocated
> 0)
2948 tagcache_start_scan();
2956 static void allocate_tempbuf(void)
2958 /* Yeah, malloc would be really nice now :) */
2960 tempbuf_size
= 32*1024*1024;
2961 tempbuf
= malloc(tempbuf_size
);
2963 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
2964 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
2965 audiobuf
+= tempbuf_size
;
2969 static void free_tempbuf(void)
2971 if (tempbuf_size
== 0)
2977 audiobuf
-= tempbuf_size
;
2983 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
2985 struct index_entry idx
;
2990 if (!tagcache_is_numeric_tag(tag
))
2993 if (!get_index(masterfd
, idx_id
, &idx
, false))
2996 idx
.tag_seek
[tag
] = data
;
2997 idx
.flag
|= FLAG_DIRTYNUM
;
2999 return write_index(masterfd
, idx_id
, &idx
);
3003 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3006 struct master_header myhdr
;
3008 if (tcs
->masterfd
< 0)
3010 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3014 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3018 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
3020 static bool command_queue_is_full(void)
3024 next
= command_queue_widx
+ 1;
3025 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3028 return (next
== command_queue_ridx
);
3030 static bool command_queue_sync_callback(void)
3033 struct master_header myhdr
;
3036 mutex_lock(&command_queue_mutex
);
3038 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3041 while (command_queue_ridx
!= command_queue_widx
)
3043 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3045 switch (ce
->command
)
3047 case CMD_UPDATE_MASTER_HEADER
:
3050 update_master_header();
3052 /* Re-open the masterfd. */
3053 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3058 case CMD_UPDATE_NUMERIC
:
3060 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3065 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3066 command_queue_ridx
= 0;
3071 tc_stat
.queue_length
= 0;
3072 mutex_unlock(&command_queue_mutex
);
3076 static void run_command_queue(bool force
)
3078 if (COMMAND_QUEUE_IS_EMPTY
)
3081 if (force
|| command_queue_is_full())
3082 command_queue_sync_callback();
3084 register_ata_idle_func(command_queue_sync_callback
);
3087 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3093 mutex_lock(&command_queue_mutex
);
3094 next
= command_queue_widx
+ 1;
3095 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3098 /* Make sure queue is not full. */
3099 if (next
!= command_queue_ridx
)
3101 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3104 ce
->idx_id
= idx_id
;
3108 command_queue_widx
= next
;
3110 tc_stat
.queue_length
++;
3112 mutex_unlock(&command_queue_mutex
);
3116 /* Queue is full, try again later... */
3117 mutex_unlock(&command_queue_mutex
);
3122 long tagcache_increase_serial(void)
3132 old
= current_tcmh
.serial
++;
3133 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3138 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3140 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3143 long tagcache_get_serial(void)
3145 return current_tcmh
.serial
;
3148 long tagcache_get_commitid(void)
3150 return current_tcmh
.commitid
;
3153 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3158 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3159 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3161 if (*datastr
== '\0')
3164 if (*datastr
== '"' || *datastr
== '\\')
3167 buf
[i
] = *(datastr
++);
3170 strcpy(&buf
[i
], "\" ");
3172 write(fd
, buf
, i
+ 2);
3177 static bool read_tag(char *dest
, long size
,
3178 const char *src
, const char *tagstr
)
3181 char current_tag
[32];
3183 while (*src
!= '\0')
3185 /* Skip all whitespace */
3193 /* Read in tag name */
3194 while (*src
!= '=' && *src
!= ' ')
3196 current_tag
[pos
] = *src
;
3200 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3203 current_tag
[pos
] = '\0';
3205 /* Read in tag data */
3207 /* Find the start. */
3208 while (*src
!= '"' && *src
!= '\0')
3211 if (*src
== '\0' || *(++src
) == '\0')
3214 /* Read the data. */
3215 for (pos
= 0; pos
< size
; pos
++)
3222 dest
[pos
] = *(src
+1);
3242 if (!strcasecmp(tagstr
, current_tag
))
3249 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3251 struct index_entry idx
;
3252 char tag_data
[TAG_MAXLEN
+32];
3254 long masterfd
= (long)parameters
;
3255 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3263 logf("%d/%s", line_n
, buf
);
3264 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3266 logf("filename missing");
3271 idx_id
= find_index(tag_data
);
3274 logf("entry not found");
3278 if (!get_index(masterfd
, idx_id
, &idx
, false))
3280 logf("failed to retrieve index entry");
3284 /* Stop if tag has already been modified. */
3285 if (idx
.flag
& FLAG_DIRTYNUM
)
3288 logf("import: %s", tag_data
);
3290 idx
.flag
|= FLAG_DIRTYNUM
;
3291 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3295 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3296 tagcache_tag_to_str(import_tags
[i
])))
3301 data
= atoi(tag_data
);
3305 idx
.tag_seek
[import_tags
[i
]] = data
;
3307 if (import_tags
[i
] == tag_lastplayed
&& data
> current_tcmh
.serial
)
3308 current_tcmh
.serial
= data
;
3309 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3310 current_tcmh
.commitid
= data
+ 1;
3313 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3317 bool tagcache_import_changelog(void)
3319 struct master_header myhdr
;
3320 struct tagcache_header tch
;
3331 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_RDONLY
);
3334 logf("failure to open changelog");
3338 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3346 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3348 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3349 parse_changelog_line
);
3354 if (filenametag_fd
>= 0)
3355 close(filenametag_fd
);
3359 update_master_header();
3365 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3367 struct master_header myhdr
;
3368 struct index_entry idx
;
3369 char buf
[TAG_MAXLEN
+32];
3377 if (!tagcache_search(tcs
, tag_filename
))
3380 /* Initialize the changelog */
3381 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_WRONLY
| O_CREAT
| O_TRUNC
);
3384 logf("failure to open changelog");
3388 if (tcs
->masterfd
< 0)
3390 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3395 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3396 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3399 write(clfd
, "## Changelog version 1\n", 23);
3401 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3403 if (ecread(tcs
->masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
3404 != sizeof(struct index_entry
))
3406 logf("read error #9");
3407 tagcache_search_finish(tcs
);
3412 /* Skip until the entry found has been modified. */
3413 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3416 /* Skip deleted entries too. */
3417 if (idx
.flag
& FLAG_DELETED
)
3420 /* Now retrieve all tags. */
3421 for (j
= 0; j
< TAG_COUNT
; j
++)
3423 if (tagcache_is_numeric_tag(j
))
3425 snprintf(temp
, sizeof temp
, "%d", idx
.tag_seek
[j
]);
3426 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3431 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3432 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3435 write(clfd
, "\n", 1);
3441 tagcache_search_finish(tcs
);
3446 static bool delete_entry(long idx_id
)
3451 struct index_entry idx
, myidx
;
3452 struct master_header myhdr
;
3453 char buf
[TAG_MAXLEN
+32];
3454 int in_use
[TAG_COUNT
];
3456 logf("delete_entry(): %ld", idx_id
);
3458 #ifdef HAVE_TC_RAMCACHE
3459 /* At first mark the entry removed from ram cache. */
3460 if (tc_stat
.ramcache
)
3461 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3464 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3467 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3468 if (ecread(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3469 != sizeof(struct index_entry
))
3471 logf("delete_entry(): read error");
3475 if (myidx
.flag
& FLAG_DELETED
)
3477 logf("delete_entry(): already deleted!");
3481 myidx
.flag
|= FLAG_DELETED
;
3482 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3483 if (ecwrite(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3484 != sizeof(struct index_entry
))
3486 logf("delete_entry(): write_error #1");
3490 /* Now check which tags are no longer in use (if any) */
3491 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3494 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3495 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3497 struct index_entry
*idxp
;
3499 #ifdef HAVE_TC_RAMCACHE
3500 /* Use RAM DB if available for greater speed */
3501 if (tc_stat
.ramcache
)
3502 idxp
= &hdr
->indices
[i
];
3506 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
3507 != sizeof(struct index_entry
))
3509 logf("delete_entry(): read error #2");
3515 if (idxp
->flag
& FLAG_DELETED
)
3518 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3520 if (tagcache_is_numeric_tag(tag
))
3523 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3528 /* Now delete all tags no longer in use. */
3529 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3531 struct tagcache_header tch
;
3532 int oldseek
= myidx
.tag_seek
[tag
];
3534 if (tagcache_is_numeric_tag(tag
))
3538 * Replace tag seek with a hash value of the field string data.
3539 * That way runtime statistics of moved or altered files can be
3542 #ifdef HAVE_TC_RAMCACHE
3543 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3545 struct tagfile_entry
*tfe
;
3546 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3548 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3549 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3550 myidx
.tag_seek
[tag
] = *seek
;
3555 struct tagfile_entry tfe
;
3557 /* Open the index file, which contains the tag names. */
3558 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3561 /* Skip the header block */
3562 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3563 if (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
3564 != sizeof(struct tagfile_entry
))
3566 logf("delete_entry(): read error #3");
3570 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3572 logf("delete_entry(): read error #4");
3576 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3581 logf("in use: %d/%d", tag
, in_use
[tag
]);
3590 #ifdef HAVE_TC_RAMCACHE
3591 /* Delete from ram. */
3592 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3594 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3595 tagentry
->tag_data
[0] = '\0';
3599 /* Open the index file, which contains the tag names. */
3602 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3606 /* Skip the header block */
3607 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3609 /* Debug, print 10 first characters of the tag
3612 logf("TAG:%s", buf);
3613 lseek(fd, -10, SEEK_CUR);
3616 /* Write first data byte in tag as \0 */
3619 /* Now tag data has been removed */
3624 /* Write index entry back into master index. */
3625 lseek(masterfd
, sizeof(struct master_header
) +
3626 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3627 if (ecwrite(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3628 != sizeof(struct index_entry
))
3630 logf("delete_entry(): write_error #2");
3649 * Returns true if there is an event waiting in the queue
3650 * that requires the current operation to be aborted.
3652 static bool check_event_queue(void)
3654 struct queue_event ev
;
3656 queue_wait_w_tmo(&tagcache_queue
, &ev
, 0);
3661 case SYS_USB_CONNECTED
:
3662 /* Put the event back into the queue. */
3663 queue_post(&tagcache_queue
, ev
.id
, ev
.data
);
3671 #ifdef HAVE_TC_RAMCACHE
3672 static bool allocate_tagcache(void)
3674 struct master_header tcmh
;
3677 /* Load the header. */
3678 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3687 * Now calculate the required cache size plus
3688 * some extra space for alignment fixes.
3690 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3691 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3692 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3693 memset(hdr
, 0, sizeof(struct ramcache_header
));
3694 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3695 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3696 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3701 # ifdef HAVE_EEPROM_SETTINGS
3702 static bool tagcache_dumpload(void)
3704 struct statefile_header shdr
;
3709 fd
= open(TAGCACHE_STATEFILE
, O_RDONLY
);
3712 logf("no tagcache statedump");
3716 /* Check the statefile memory placement */
3717 hdr
= buffer_alloc(0);
3718 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3719 if (rc
!= sizeof(struct statefile_header
)
3720 /* || (long)hdr != (long)shdr.hdr */)
3722 logf("incorrect statefile");
3728 offpos
= (long)hdr
- (long)shdr
.hdr
;
3730 /* Lets allocate real memory and load it */
3731 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3732 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3735 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3737 logf("read failure!");
3742 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3744 /* Now fix the pointers */
3745 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3746 for (i
= 0; i
< TAG_COUNT
; i
++)
3747 hdr
->tags
[i
] += offpos
;
3752 static bool tagcache_dumpsave(void)
3754 struct statefile_header shdr
;
3757 if (!tc_stat
.ramcache
)
3760 fd
= open(TAGCACHE_STATEFILE
, O_WRONLY
| O_CREAT
| O_TRUNC
);
3763 logf("failed to create a statedump");
3767 /* Create the header */
3769 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3770 write(fd
, &shdr
, sizeof(struct statefile_header
));
3772 /* And dump the data too */
3773 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3780 static bool load_tagcache(void)
3782 struct tagcache_header
*tch
;
3783 long bytesleft
= tc_stat
.ramcache_allocated
;
3784 struct index_entry
*idx
;
3789 # ifdef HAVE_DIRCACHE
3790 while (dircache_is_initializing())
3793 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3796 logf("loading tagcache to ram...");
3798 fd
= open(TAGCACHE_FILE_MASTER
, O_RDONLY
);
3801 logf("tagcache open failed");
3805 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3806 != sizeof(struct master_header
)
3807 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3809 logf("incorrect header");
3815 /* Load the master index table. */
3816 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3818 rc
= ecread(fd
, idx
, 1, index_entry_ec
, tc_stat
.econ
);
3819 if (rc
!= sizeof(struct index_entry
))
3821 logf("read error #10");
3826 bytesleft
-= sizeof(struct index_entry
);
3827 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3829 logf("too big tagcache.");
3839 /* Load the tags. */
3841 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3843 struct tagfile_entry
*fe
;
3844 char buf
[TAG_MAXLEN
+32];
3846 if (tagcache_is_numeric_tag(tag
))
3849 //p = ((void *)p+1);
3850 p
= (char *)((long)p
& ~0x03) + 0x04;
3853 /* Check the header. */
3854 tch
= (struct tagcache_header
*)p
;
3855 p
+= sizeof(struct tagcache_header
);
3857 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3860 for (hdr
->entry_count
[tag
] = 0;
3861 hdr
->entry_count
[tag
] < tch
->entry_count
;
3862 hdr
->entry_count
[tag
]++)
3866 if (do_timed_yield())
3868 /* Abort if we got a critical event in queue */
3869 if (check_event_queue())
3873 fe
= (struct tagfile_entry
*)p
;
3874 pos
= lseek(fd
, 0, SEEK_CUR
);
3875 rc
= ecread(fd
, fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
3876 if (rc
!= sizeof(struct tagfile_entry
))
3878 /* End of lookup table. */
3879 logf("read error #11");
3884 /* We have a special handling for the filename tags. */
3885 if (tag
== tag_filename
)
3887 # ifdef HAVE_DIRCACHE
3888 const struct dirent
*dc
;
3891 // FIXME: This is wrong!
3892 // idx = &hdr->indices[hdr->entry_count[i]];
3893 idx
= &hdr
->indices
[fe
->idx_id
];
3895 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
3899 logf("TAG:%s", buf
);
3900 logf("too long filename");
3905 rc
= read(fd
, buf
, fe
->tag_length
);
3906 if (rc
!= fe
->tag_length
)
3908 logf("read error #12");
3913 /* Check if the entry has already been removed */
3914 if (idx
->flag
& FLAG_DELETED
)
3917 /* This flag must not be used yet. */
3918 if (idx
->flag
& FLAG_DIRCACHE
)
3920 logf("internal error!");
3925 if (idx
->tag_seek
[tag
] != pos
)
3927 logf("corrupt data structures!");
3932 # ifdef HAVE_DIRCACHE
3933 if (dircache_is_enabled())
3935 dc
= dircache_get_entry_ptr(buf
);
3938 logf("Entry no longer valid.");
3940 delete_entry(fe
->idx_id
);
3944 idx
->flag
|= FLAG_DIRCACHE
;
3945 FLAG_SET_ATTR(idx
->flag
, fe
->idx_id
);
3946 idx
->tag_seek
[tag_filename
] = (long)dc
;
3951 /* This will be very slow unless dircache is enabled
3952 or target is flash based, but do it anyway for
3954 /* Check if entry has been removed. */
3955 if (global_settings
.tagcache_autoupdate
)
3957 if (!file_exists(buf
))
3959 logf("Entry no longer valid.");
3961 delete_entry(fe
->idx_id
);
3970 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
3973 logf("too big tagcache #2");
3974 logf("tl: %d", fe
->tag_length
);
3975 logf("bl: %ld", bytesleft
);
3981 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
3984 if (rc
!= fe
->tag_length
)
3986 logf("read error #13");
3987 logf("rc=0x%04x", rc
); // 0x431
3988 logf("len=0x%04x", fe
->tag_length
); // 0x4000
3989 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
3990 logf("tag=0x%02x", tag
); // 0x00
3998 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
3999 logf("tagcache loaded into ram!");
4003 #endif /* HAVE_TC_RAMCACHE */
4005 static bool check_deleted_files(void)
4008 char buf
[TAG_MAXLEN
+32];
4009 struct tagfile_entry tfe
;
4011 logf("reverse scan...");
4012 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4013 fd
= open(buf
, O_RDONLY
);
4017 logf("%s open fail", buf
);
4021 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4022 while (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
4023 == sizeof(struct tagfile_entry
)
4025 && !check_event_queue()
4029 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4031 logf("too long tag");
4036 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4038 logf("read error #14");
4043 /* Check if the file has already deleted from the db. */
4047 /* Now check if the file exists. */
4048 if (!file_exists(buf
))
4050 logf("Entry no longer valid.");
4051 logf("-> %s / %d", buf
, tfe
.tag_length
);
4052 delete_entry(tfe
.idx_id
);
4063 static bool check_dir(const char *dirname
, int add_files
)
4067 int success
= false;
4068 int ignore
, unignore
;
4069 char newpath
[MAX_PATH
];
4071 dir
= opendir(dirname
);
4074 logf("tagcache: opendir() failed");
4078 /* check for a database.ignore file */
4079 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4080 ignore
= file_exists(newpath
);
4081 /* check for a database.unignore file */
4082 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4083 unignore
= file_exists(newpath
);
4085 /* don't do anything if both ignore and unignore are there */
4086 if (ignore
!= unignore
)
4087 add_files
= unignore
;
4089 /* Recursively scan the dir. */
4093 while (!check_event_queue())
4096 struct dirent
*entry
;
4098 entry
= readdir(dir
);
4106 if (!strcmp((char *)entry
->d_name
, ".") ||
4107 !strcmp((char *)entry
->d_name
, ".."))
4112 len
= strlen(curpath
);
4113 snprintf(&curpath
[len
], curpath_size
- len
, "/%s",
4116 processed_dir_count
++;
4117 if (entry
->attribute
& ATTR_DIRECTORY
)
4118 check_dir(curpath
, add_files
);
4121 tc_stat
.curentry
= curpath
;
4123 /* Add a new entry to the temporary db file. */
4124 add_tagcache(curpath
, (entry
->wrtdate
<< 16) | entry
->wrttime
4125 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4126 , dir
->internal_entry
4130 /* Wait until current path for debug screen is read and unset. */
4131 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4134 tc_stat
.curentry
= NULL
;
4137 curpath
[len
] = '\0';
4145 void tagcache_screensync_event(void)
4147 tc_stat
.curentry
= NULL
;
4150 void tagcache_screensync_enable(bool state
)
4152 tc_stat
.syncscreen
= state
;
4155 void build_tagcache(const char *path
)
4157 struct tagcache_header header
;
4162 total_entry_count
= 0;
4163 processed_dir_count
= 0;
4165 #ifdef HAVE_DIRCACHE
4166 while (dircache_is_initializing())
4170 logf("updating tagcache");
4172 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
4175 logf("skipping, cache already waiting for commit");
4180 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDWR
| O_CREAT
| O_TRUNC
);
4183 logf("master file open failed: %s", TAGCACHE_FILE_TEMP
);
4187 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4191 logf("Scanning files...");
4192 /* Scan for new files. */
4193 memset(&header
, 0, sizeof(struct tagcache_header
));
4194 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4196 if (strcmp("/", path
) != 0)
4197 strcpy(curpath
, path
);
4198 ret
= check_dir(path
, true);
4200 /* Write the header. */
4201 header
.magic
= TAGCACHE_MAGIC
;
4202 header
.datasize
= data_size
;
4203 header
.entry_count
= total_entry_count
;
4204 lseek(cachefd
, 0, SEEK_SET
);
4205 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4208 if (filenametag_fd
>= 0)
4210 close(filenametag_fd
);
4211 filenametag_fd
= -1;
4221 /* Commit changes to the database. */
4227 remove(TAGCACHE_FILE_TEMP
);
4228 logf("tagcache built!");
4234 #ifdef HAVE_TC_RAMCACHE
4237 /* Import runtime statistics if we just initialized the db. */
4238 if (hdr
->h
.serial
== 0)
4239 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4246 #ifdef HAVE_TC_RAMCACHE
4247 static void load_ramcache(void)
4254 /* At first we should load the cache (if exists). */
4255 tc_stat
.ramcache
= load_tagcache();
4257 if (!tc_stat
.ramcache
)
4259 /* If loading failed, it must indicate some problem with the db
4260 * so disable it entirely to prevent further issues. */
4261 tc_stat
.ready
= false;
4268 void tagcache_unload_ramcache(void)
4270 tc_stat
.ramcache
= false;
4271 /* Just to make sure there is no statefile present. */
4272 // remove(TAGCACHE_STATEFILE);
4277 static void tagcache_thread(void)
4279 struct queue_event ev
;
4280 bool check_done
= false;
4282 /* If the previous cache build/update was interrupted, commit
4283 * the changes first in foreground. */
4289 #ifdef HAVE_TC_RAMCACHE
4290 # ifdef HAVE_EEPROM_SETTINGS
4291 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
)
4292 check_done
= tagcache_dumpload();
4294 remove(TAGCACHE_STATEFILE
);
4297 /* Allocate space for the tagcache if found on disk. */
4298 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4299 allocate_tagcache();
4303 tc_stat
.initialized
= true;
4305 /* Don't delay bootup with the header check but do it on background. */
4307 tc_stat
.ready
= check_all_headers();
4308 tc_stat
.readyvalid
= true;
4312 run_command_queue(false);
4314 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4318 case Q_IMPORT_CHANGELOG
:
4319 tagcache_import_changelog();
4324 build_tagcache("/");
4328 build_tagcache("/");
4329 #ifdef HAVE_TC_RAMCACHE
4332 check_deleted_files();
4338 if (check_done
|| !tc_stat
.ready
)
4341 #ifdef HAVE_TC_RAMCACHE
4342 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4345 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4346 build_tagcache("/");
4350 if (global_settings
.tagcache_autoupdate
)
4352 build_tagcache("/");
4354 /* This will be very slow unless dircache is enabled
4355 or target is flash based, but do it anyway for
4357 check_deleted_files();
4360 logf("tagcache check done");
4372 case SYS_USB_CONNECTED
:
4373 logf("USB: TagCache");
4374 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4375 usb_wait_for_disconnect(&tagcache_queue
);
4382 bool tagcache_prepare_shutdown(void)
4384 if (tagcache_get_commit_step() > 0)
4387 tagcache_stop_scan();
4388 while (read_lock
|| write_lock
)
4394 void tagcache_shutdown(void)
4396 /* Flush the command queue. */
4397 run_command_queue(true);
4399 #ifdef HAVE_EEPROM_SETTINGS
4400 if (tc_stat
.ramcache
)
4401 tagcache_dumpsave();
4405 static int get_progress(void)
4407 int total_count
= -1;
4409 #ifdef HAVE_DIRCACHE
4410 if (dircache_is_enabled())
4412 total_count
= dircache_get_entry_count();
4416 #ifdef HAVE_TC_RAMCACHE
4418 if (hdr
&& tc_stat
.ramcache
)
4419 total_count
= hdr
->h
.tch
.entry_count
;
4423 if (total_count
< 0)
4426 return processed_dir_count
* 100 / total_count
;
4429 struct tagcache_stat
* tagcache_get_stat(void)
4431 tc_stat
.progress
= get_progress();
4432 tc_stat
.processed_entries
= processed_dir_count
;
4437 void tagcache_start_scan(void)
4439 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4442 bool tagcache_update(void)
4447 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4451 bool tagcache_rebuild()
4453 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4457 void tagcache_stop_scan(void)
4459 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4462 #ifdef HAVE_TC_RAMCACHE
4463 bool tagcache_is_ramcache(void)
4465 return tc_stat
.ramcache
;
4469 #endif /* !__PCTOOL__ */
4472 void tagcache_init(void)
4474 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4475 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4476 filenametag_fd
= -1;
4477 write_lock
= read_lock
= 0;
4480 mutex_init(&command_queue_mutex
);
4481 queue_init(&tagcache_queue
, true);
4482 create_thread(tagcache_thread
, tagcache_stack
,
4483 sizeof(tagcache_stack
), 0, tagcache_thread_name
4484 IF_PRIO(, PRIORITY_BACKGROUND
)
4487 tc_stat
.initialized
= true;
4491 tc_stat
.ready
= check_all_headers();
4496 void tagcache_reverse_scan(void)
4498 logf("Checking for deleted files");
4499 check_deleted_files();
4503 bool tagcache_is_initialized(void)
4505 return tc_stat
.initialized
;
4507 bool tagcache_is_usable(void)
4509 return tc_stat
.initialized
&& tc_stat
.ready
;
4511 int tagcache_get_commit_step(void)
4513 return tc_stat
.commit_step
;
4515 int tagcache_get_max_commit_step(void)
4517 return (int)(sizeof(sorted_tags
)/sizeof(sorted_tags
[0]))+1;