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"
81 #include "eeprom_settings.h"
85 #define yield() do { } while(0)
86 #define sim_sleep(timeout) do { } while(0)
87 #define do_timed_yield() do { } while(0)
91 /* Tag Cache thread. */
92 static struct event_queue tagcache_queue
;
93 static long tagcache_stack
[(DEFAULT_STACK_SIZE
+ 0x4000)/sizeof(long)];
94 static const char tagcache_thread_name
[] = "tagcache";
97 #define UNTAGGED "<Untagged>"
99 /* Previous path when scanning directory tree recursively. */
100 static char curpath
[TAG_MAXLEN
+32];
101 static long curpath_size
= sizeof(curpath
);
103 /* Used when removing duplicates. */
104 static char *tempbuf
; /* Allocated when needed. */
105 static long tempbufidx
; /* Current location in buffer. */
106 static long tempbuf_size
; /* Buffer size (TEMPBUF_SIZE). */
107 static long tempbuf_left
; /* Buffer space left. */
108 static long tempbuf_pos
;
110 /* Tags we want to get sorted (loaded to the tempbuf). */
111 static const int sorted_tags
[] = { tag_artist
, tag_album
, tag_genre
,
112 tag_composer
, tag_comment
, tag_albumartist
, tag_grouping
, tag_title
};
114 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
115 static const int unique_tags
[] = { tag_artist
, tag_album
, tag_genre
,
116 tag_composer
, tag_comment
, tag_albumartist
, tag_grouping
};
118 /* Numeric tags (we can use these tags with conditional clauses). */
119 static const int numeric_tags
[] = { tag_year
, tag_discnumber
,
120 tag_tracknumber
, tag_length
, tag_bitrate
, tag_playcount
, tag_rating
,
121 tag_playtime
, tag_lastplayed
, tag_commitid
, tag_mtime
,
122 tag_virt_length_min
, tag_virt_length_sec
,
123 tag_virt_playtime_min
, tag_virt_playtime_sec
,
124 tag_virt_entryage
, tag_virt_autoscore
};
126 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
127 static const char *tags_str
[] = { "artist", "album", "genre", "title",
128 "filename", "composer", "comment", "albumartist", "grouping", "year",
129 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
130 "playtime", "lastplayed", "commitid", "mtime" };
132 /* Status information of the tagcache. */
133 static struct tagcache_stat tc_stat
;
135 /* Queue commands. */
136 enum tagcache_queue
{
143 /* Internal tagcache command queue. */
144 CMD_UPDATE_MASTER_HEADER
,
148 struct tagcache_command_entry
{
155 static struct tagcache_command_entry command_queue
[TAGCACHE_COMMAND_QUEUE_LENGTH
];
156 static volatile int command_queue_widx
= 0;
157 static volatile int command_queue_ridx
= 0;
158 static struct mutex command_queue_mutex
;
160 /* Tag database structures. */
162 /* Variable-length tag entry in tag files. */
163 struct tagfile_entry
{
164 short tag_length
; /* Length of the data in bytes including '\0' */
165 short idx_id
; /* Corresponding entry location in index file of not unique tags */
166 char tag_data
[0]; /* Begin of the tag data */
169 /* Fixed-size tag entry in master db index. */
171 int32_t tag_seek
[TAG_COUNT
]; /* Location of tag data or numeric tag data */
172 int32_t flag
; /* Status flags */
175 /* Header is the same in every file. */
176 struct tagcache_header
{
177 int32_t magic
; /* Header version number */
178 int32_t datasize
; /* Data size in bytes */
179 int32_t entry_count
; /* Number of entries in this file */
182 struct master_header
{
183 struct tagcache_header tch
;
184 int32_t serial
; /* Increasing counting number */
185 int32_t commitid
; /* Number of commits so far */
189 /* For the endianess correction */
190 static const char *tagfile_entry_ec
= "ss";
191 static const char *index_entry_ec
= "lllllllllllllllllllll"; /* (1 + TAG_COUNT) * l */
192 static const char *tagcache_header_ec
= "lll";
193 static const char *master_header_ec
= "llllll";
195 static struct master_header current_tcmh
;
197 #ifdef HAVE_TC_RAMCACHE
198 /* Header is created when loading database to ram. */
199 struct ramcache_header
{
200 struct master_header h
; /* Header from the master index */
201 struct index_entry
*indices
; /* Master index file content */
202 char *tags
[TAG_COUNT
]; /* Tag file content (not including filename tag) */
203 int entry_count
[TAG_COUNT
]; /* Number of entries in the indices. */
206 # ifdef HAVE_EEPROM_SETTINGS
207 struct statefile_header
{
208 struct ramcache_header
*hdr
;
209 struct tagcache_stat tc_stat
;
213 /* Pointer to allocated ramcache_header */
214 static struct ramcache_header
*hdr
;
218 * Full tag entries stored in a temporary file waiting
219 * for commit to the cache. */
220 struct temp_file_entry
{
221 long tag_offset
[TAG_COUNT
];
222 short tag_length
[TAG_COUNT
];
228 struct tempbuf_id_list
{
230 struct tempbuf_id_list
*next
;
233 struct tempbuf_searchidx
{
237 struct tempbuf_id_list idlist
;
240 /* Lookup buffer for fixing messed up index while after sorting. */
241 static long commit_entry_count
;
242 static long lookup_buffer_depth
;
243 static struct tempbuf_searchidx
**lookup
;
245 /* Used when building the temporary file. */
246 static int cachefd
= -1, filenametag_fd
;
247 static int total_entry_count
= 0;
248 static int data_size
= 0;
249 static int processed_dir_count
;
251 /* Thread safe locking */
252 static volatile int write_lock
;
253 static volatile int read_lock
;
255 static bool delete_entry(long idx_id
);
257 const char* tagcache_tag_to_str(int tag
)
259 return tags_str
[tag
];
262 bool tagcache_is_numeric_tag(int type
)
266 for (i
= 0; i
< (int)(sizeof(numeric_tags
)/sizeof(numeric_tags
[0])); i
++)
268 if (type
== numeric_tags
[i
])
275 bool tagcache_is_unique_tag(int type
)
279 for (i
= 0; i
< (int)(sizeof(unique_tags
)/sizeof(unique_tags
[0])); i
++)
281 if (type
== unique_tags
[i
])
288 bool tagcache_is_sorted_tag(int type
)
292 for (i
= 0; i
< (int)(sizeof(sorted_tags
)/sizeof(sorted_tags
[0])); i
++)
294 if (type
== sorted_tags
[i
])
303 * Returns true if specified flag is still present, i.e., dircache
304 * has not been reloaded.
306 static bool is_dircache_intact(void)
308 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
312 static int open_tag_fd(struct tagcache_header
*hdr
, int tag
, bool write
)
318 if (tagcache_is_numeric_tag(tag
) || tag
< 0 || tag
>= TAG_COUNT
)
321 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag
);
323 fd
= open(buf
, write
? O_RDWR
: O_RDONLY
);
326 logf("tag file open failed: tag=%d write=%d file=%s", tag
, write
, buf
);
327 tc_stat
.ready
= false;
331 /* Check the header. */
332 rc
= ecread(fd
, hdr
, 1, tagcache_header_ec
, tc_stat
.econ
);
333 if (hdr
->magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct tagcache_header
))
335 logf("header error");
336 tc_stat
.ready
= false;
344 static int open_master_fd(struct master_header
*hdr
, bool write
)
349 fd
= open(TAGCACHE_FILE_MASTER
, write
? O_RDWR
: O_RDONLY
);
352 logf("master file open failed for R/W");
353 tc_stat
.ready
= false;
357 tc_stat
.econ
= false;
359 /* Check the header. */
360 rc
= read(fd
, hdr
, sizeof(struct master_header
));
361 if (hdr
->tch
.magic
== TAGCACHE_MAGIC
&& rc
== sizeof(struct master_header
))
367 /* Trying to read again, this time with endianess correction enabled. */
368 lseek(fd
, 0, SEEK_SET
);
370 rc
= ecread(fd
, hdr
, 1, master_header_ec
, true);
371 if (hdr
->tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= sizeof(struct master_header
))
373 logf("header error");
374 tc_stat
.ready
= false;
385 static bool do_timed_yield(void)
387 /* Sorting can lock up for quite a while, so yield occasionally */
388 static long wakeup_tick
= 0;
389 if (current_tick
>= wakeup_tick
)
391 wakeup_tick
= current_tick
+ (HZ
/4);
399 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
400 static long find_entry_ram(const char *filename
,
401 const struct dirent
*dc
)
403 static long last_pos
= 0;
406 /* Check if we tagcache is loaded into ram. */
407 if (!tc_stat
.ramcache
)
411 dc
= dircache_get_entry_ptr(filename
);
415 logf("tagcache: file not found.");
426 for (; i
< hdr
->h
.tch
.entry_count
; i
++)
428 if (hdr
->indices
[i
].tag_seek
[tag_filename
] == (long)dc
)
430 last_pos
= MAX(0, i
- 3);
447 static long find_entry_disk(const char *filename
)
449 struct tagcache_header tch
;
450 static long last_pos
= -1;
451 long pos_history
[POS_HISTORY_COUNT
];
452 long pos_history_idx
= 0;
454 struct tagfile_entry tfe
;
456 char buf
[TAG_MAXLEN
+32];
467 if ( (fd
= open_tag_fd(&tch
, tag_filename
, false)) < 0)
474 lseek(fd
, last_pos
, SEEK_SET
);
476 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
480 pos
= lseek(fd
, 0, SEEK_CUR
);
481 for (i
= pos_history_idx
-1; i
>= 0; i
--)
482 pos_history
[i
+1] = pos_history
[i
];
483 pos_history
[0] = pos
;
485 if (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
486 != sizeof(struct tagfile_entry
))
491 if (tfe
.tag_length
>= (long)sizeof(buf
))
493 logf("too long tag #1");
499 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
501 logf("read error #2");
507 if (!strcasecmp(filename
, buf
))
509 last_pos
= pos_history
[pos_history_idx
];
514 if (pos_history_idx
< POS_HISTORY_COUNT
- 1)
528 if (fd
!= filenametag_fd
)
533 if (fd
!= filenametag_fd
)
539 static int find_index(const char *filename
)
543 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
544 if (tc_stat
.ramcache
&& is_dircache_intact())
545 idx_id
= find_entry_ram(filename
, NULL
);
549 idx_id
= find_entry_disk(filename
);
554 bool tagcache_find_index(struct tagcache_search
*tcs
, const char *filename
)
561 idx_id
= find_index(filename
);
565 if (!tagcache_search(tcs
, tag_filename
))
568 tcs
->entry_count
= 0;
569 tcs
->idx_id
= idx_id
;
574 static bool get_index(int masterfd
, int idxid
,
575 struct index_entry
*idx
, bool use_ram
)
577 bool localfd
= false;
581 logf("Incorrect idxid: %d", idxid
);
585 #ifdef HAVE_TC_RAMCACHE
586 if (tc_stat
.ramcache
&& use_ram
)
588 if (hdr
->indices
[idxid
].flag
& FLAG_DELETED
)
591 memcpy(idx
, &hdr
->indices
[idxid
], sizeof(struct index_entry
));
600 struct master_header tcmh
;
603 masterfd
= open_master_fd(&tcmh
, false);
608 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
609 + sizeof(struct master_header
), SEEK_SET
);
610 if (ecread(masterfd
, idx
, 1, index_entry_ec
, tc_stat
.econ
)
611 != sizeof(struct index_entry
))
613 logf("read error #3");
623 if (idx
->flag
& FLAG_DELETED
)
629 static bool write_index(int masterfd
, int idxid
, struct index_entry
*idx
)
631 /* We need to exclude all memory only flags & tags when writing to disk. */
632 if (idx
->flag
& FLAG_DIRCACHE
)
634 logf("memory only flags!");
638 #ifdef HAVE_TC_RAMCACHE
639 /* Only update numeric data. Writing the whole index to RAM by memcpy
640 * destroys dircache pointers!
642 if (tc_stat
.ramcache
)
645 struct index_entry
*idx_ram
= &hdr
->indices
[idxid
];
647 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
649 if (tagcache_is_numeric_tag(tag
))
651 idx_ram
->tag_seek
[tag
] = idx
->tag_seek
[tag
];
655 /* Don't touch the dircache flag. */
656 idx_ram
->flag
= idx
->flag
| (idx_ram
->flag
& FLAG_DIRCACHE
);
660 lseek(masterfd
, idxid
* sizeof(struct index_entry
)
661 + sizeof(struct master_header
), SEEK_SET
);
662 if (ecwrite(masterfd
, idx
, 1, index_entry_ec
, tc_stat
.econ
)
663 != sizeof(struct index_entry
))
665 logf("write error #3");
666 logf("idxid: %d", idxid
);
673 static bool open_files(struct tagcache_search
*tcs
, int tag
)
675 if (tcs
->idxfd
[tag
] < 0)
679 snprintf(fn
, sizeof fn
, TAGCACHE_FILE_INDEX
, tag
);
680 tcs
->idxfd
[tag
] = open(fn
, O_RDONLY
);
683 if (tcs
->idxfd
[tag
] < 0)
685 logf("File not open!");
692 static bool retrieve(struct tagcache_search
*tcs
, struct index_entry
*idx
,
693 int tag
, char *buf
, long size
)
695 struct tagfile_entry tfe
;
700 if (tagcache_is_numeric_tag(tag
))
703 seek
= idx
->tag_seek
[tag
];
706 logf("Retrieve failed");
710 #ifdef HAVE_TC_RAMCACHE
713 struct tagfile_entry
*ep
;
715 # ifdef HAVE_DIRCACHE
716 if (tag
== tag_filename
&& (idx
->flag
& FLAG_DIRCACHE
)
717 && is_dircache_intact())
719 dircache_copy_path((struct dirent
*)seek
,
725 if (tag
!= tag_filename
)
727 ep
= (struct tagfile_entry
*)&hdr
->tags
[tag
][seek
];
728 strncpy(buf
, ep
->tag_data
, size
-1);
735 if (!open_files(tcs
, tag
))
738 lseek(tcs
->idxfd
[tag
], seek
, SEEK_SET
);
739 if (ecread(tcs
->idxfd
[tag
], &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
740 != sizeof(struct tagfile_entry
))
742 logf("read error #5");
746 if (tfe
.tag_length
>= size
)
748 logf("too small buffer");
752 if (read(tcs
->idxfd
[tag
], buf
, tfe
.tag_length
) !=
755 logf("read error #6");
759 buf
[tfe
.tag_length
] = '\0';
764 static long check_virtual_tags(int tag
, const struct index_entry
*idx
)
770 case tag_virt_length_sec
:
771 data
= (idx
->tag_seek
[tag_length
]/1000) % 60;
774 case tag_virt_length_min
:
775 data
= (idx
->tag_seek
[tag_length
]/1000) / 60;
778 case tag_virt_playtime_sec
:
779 data
= (idx
->tag_seek
[tag_playtime
]/1000) % 60;
782 case tag_virt_playtime_min
:
783 data
= (idx
->tag_seek
[tag_playtime
]/1000) / 60;
786 case tag_virt_autoscore
:
787 if (idx
->tag_seek
[tag_length
] == 0
788 || idx
->tag_seek
[tag_playcount
] == 0)
794 data
= 100 * idx
->tag_seek
[tag_playtime
]
795 / idx
->tag_seek
[tag_length
]
796 / idx
->tag_seek
[tag_playcount
];
800 /* How many commits before the file has been added to the DB. */
801 case tag_virt_entryage
:
802 data
= current_tcmh
.commitid
- idx
->tag_seek
[tag_commitid
] - 1;
806 data
= idx
->tag_seek
[tag
];
812 long tagcache_get_numeric(const struct tagcache_search
*tcs
, int tag
)
814 struct index_entry idx
;
819 if (!tagcache_is_numeric_tag(tag
))
822 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
825 return check_virtual_tags(tag
, &idx
);
828 inline static bool str_ends_with(const char *str1
, const char *str2
)
830 int str_len
= strlen(str1
);
831 int clause_len
= strlen(str2
);
833 if (clause_len
> str_len
)
836 return !strcasecmp(&str1
[str_len
- clause_len
], str2
);
839 inline static bool str_oneof(const char *str
, const char *list
)
842 int l
, len
= strlen(str
);
846 sep
= strchr(list
, '|');
847 l
= sep
? (long)sep
- (long)list
: (int)strlen(list
);
848 if ((l
==len
) && !strncasecmp(str
, list
, len
))
850 list
+= sep
? l
+ 1 : l
;
856 static bool check_against_clause(long numeric
, const char *str
,
857 const struct tagcache_search_clause
*clause
)
861 switch (clause
->type
)
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 return numeric
<= clause
->numeric_data
;
876 logf("Incorrect numeric tag: %d", clause
->type
);
881 switch (clause
->type
)
884 return !strcasecmp(clause
->str
, str
);
886 return 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
);
894 return 0<=strcasecmp(clause
->str
, str
);
895 case clause_contains
:
896 return (strcasestr(str
, clause
->str
) != NULL
);
897 case clause_not_contains
:
898 return (strcasestr(str
, clause
->str
) == NULL
);
899 case clause_begins_with
:
900 return (strcasestr(str
, clause
->str
) == str
);
901 case clause_not_begins_with
:
902 return (strcasestr(str
, clause
->str
) != str
);
903 case clause_ends_with
:
904 return str_ends_with(str
, clause
->str
);
905 case clause_not_ends_with
:
906 return !str_ends_with(str
, clause
->str
);
908 return str_oneof(str
, clause
->str
);
911 logf("Incorrect tag: %d", clause
->type
);
918 static bool check_clauses(struct tagcache_search
*tcs
,
919 struct index_entry
*idx
,
920 struct tagcache_search_clause
**clause
, int count
)
924 #ifdef HAVE_TC_RAMCACHE
927 /* Go through all conditional clauses. */
928 for (i
= 0; i
< count
; i
++)
930 struct tagfile_entry
*tfe
;
935 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
937 if (!tagcache_is_numeric_tag(clause
[i
]->tag
))
939 if (clause
[i
]->tag
== tag_filename
)
941 retrieve(tcs
, idx
, tag_filename
, buf
, sizeof buf
);
946 tfe
= (struct tagfile_entry
*)&hdr
->tags
[clause
[i
]->tag
][seek
];
951 if (!check_against_clause(seek
, str
, clause
[i
]))
958 /* Check for conditions. */
959 for (i
= 0; i
< count
; i
++)
961 struct tagfile_entry tfe
;
965 seek
= check_virtual_tags(clause
[i
]->tag
, idx
);
967 memset(str
, 0, sizeof str
);
968 if (!tagcache_is_numeric_tag(clause
[i
]->tag
))
970 int fd
= tcs
->idxfd
[clause
[i
]->tag
];
971 lseek(fd
, seek
, SEEK_SET
);
972 ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
973 if (tfe
.tag_length
>= (int)sizeof(str
))
975 logf("Too long tag read!");
979 read(fd
, str
, tfe
.tag_length
);
981 /* Check if entry has been deleted. */
986 if (!check_against_clause(seek
, str
, clause
[i
]))
994 bool tagcache_check_clauses(struct tagcache_search
*tcs
,
995 struct tagcache_search_clause
**clause
, int count
)
997 struct index_entry idx
;
1002 if (!get_index(tcs
->masterfd
, tcs
->idx_id
, &idx
, true))
1005 return check_clauses(tcs
, &idx
, clause
, count
);
1008 static bool add_uniqbuf(struct tagcache_search
*tcs
, unsigned long id
)
1012 /* If uniq buffer is not defined we must return true for search to work. */
1013 if (tcs
->unique_list
== NULL
1014 || (!tagcache_is_unique_tag(tcs
->type
)
1015 && !tagcache_is_numeric_tag(tcs
->type
)))
1020 for (i
= 0; i
< tcs
->unique_list_count
; i
++)
1022 /* Return false if entry is found. */
1023 if (tcs
->unique_list
[i
] == id
)
1027 if (tcs
->unique_list_count
< tcs
->unique_list_capacity
)
1029 tcs
->unique_list
[i
] = id
;
1030 tcs
->unique_list_count
++;
1036 static bool build_lookup_list(struct tagcache_search
*tcs
)
1038 struct index_entry entry
;
1041 tcs
->seek_list_count
= 0;
1043 #ifdef HAVE_TC_RAMCACHE
1048 for (i
= tcs
->seek_pos
; i
< hdr
->h
.tch
.entry_count
; i
++)
1050 struct index_entry
*idx
= &hdr
->indices
[i
];
1051 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1054 /* Skip deleted files. */
1055 if (idx
->flag
& FLAG_DELETED
)
1058 /* Go through all filters.. */
1059 for (j
= 0; j
< tcs
->filter_count
; j
++)
1061 if (idx
->tag_seek
[tcs
->filter_tag
[j
]] != tcs
->filter_seek
[j
])
1067 if (j
< tcs
->filter_count
)
1070 /* Check for conditions. */
1071 if (!check_clauses(tcs
, idx
, tcs
->clause
, tcs
->clause_count
))
1074 /* Add to the seek list if not already in uniq buffer. */
1075 if (!add_uniqbuf(tcs
, idx
->tag_seek
[tcs
->type
]))
1079 tcs
->seek_list
[tcs
->seek_list_count
] = idx
->tag_seek
[tcs
->type
];
1080 tcs
->seek_flags
[tcs
->seek_list_count
] = idx
->flag
;
1081 tcs
->seek_list_count
++;
1086 return tcs
->seek_list_count
> 0;
1090 lseek(tcs
->masterfd
, tcs
->seek_pos
* sizeof(struct index_entry
) +
1091 sizeof(struct master_header
), SEEK_SET
);
1093 while (ecread(tcs
->masterfd
, &entry
, 1, index_entry_ec
, tc_stat
.econ
)
1094 == sizeof(struct index_entry
))
1096 if (tcs
->seek_list_count
== SEEK_LIST_SIZE
)
1101 /* Check if entry has been deleted. */
1102 if (entry
.flag
& FLAG_DELETED
)
1105 /* Go through all filters.. */
1106 for (i
= 0; i
< tcs
->filter_count
; i
++)
1108 if (entry
.tag_seek
[tcs
->filter_tag
[i
]] != tcs
->filter_seek
[i
])
1112 if (i
< tcs
->filter_count
)
1115 /* Check for conditions. */
1116 if (!check_clauses(tcs
, &entry
, tcs
->clause
, tcs
->clause_count
))
1119 /* Add to the seek list if not already in uniq buffer. */
1120 if (!add_uniqbuf(tcs
, entry
.tag_seek
[tcs
->type
]))
1124 tcs
->seek_list
[tcs
->seek_list_count
] = entry
.tag_seek
[tcs
->type
];
1125 tcs
->seek_flags
[tcs
->seek_list_count
] = entry
.flag
;
1126 tcs
->seek_list_count
++;
1131 return tcs
->seek_list_count
> 0;
1135 static void remove_files(void)
1140 tc_stat
.ready
= false;
1141 tc_stat
.ramcache
= false;
1142 tc_stat
.econ
= false;
1143 remove(TAGCACHE_FILE_MASTER
);
1144 for (i
= 0; i
< TAG_COUNT
; i
++)
1146 if (tagcache_is_numeric_tag(i
))
1149 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, i
);
1155 static bool check_all_headers(void)
1157 struct master_header myhdr
;
1158 struct tagcache_header tch
;
1162 if ( (fd
= open_master_fd(&myhdr
, false)) < 0)
1168 logf("tagcache is dirty!");
1172 memcpy(¤t_tcmh
, &myhdr
, sizeof(struct master_header
));
1174 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
1176 if (tagcache_is_numeric_tag(tag
))
1179 if ( (fd
= open_tag_fd(&tch
, tag
, false)) < 0)
1188 bool tagcache_search(struct tagcache_search
*tcs
, int tag
)
1190 struct tagcache_header tag_hdr
;
1191 struct master_header master_hdr
;
1194 if (tcs
->initialized
)
1195 tagcache_search_finish(tcs
);
1200 memset(tcs
, 0, sizeof(struct tagcache_search
));
1201 if (tc_stat
.commit_step
> 0 || !tc_stat
.ready
)
1204 tcs
->position
= sizeof(struct tagcache_header
);
1207 tcs
->seek_list_count
= 0;
1208 tcs
->filter_count
= 0;
1211 for (i
= 0; i
< TAG_COUNT
; i
++)
1214 #ifndef HAVE_TC_RAMCACHE
1215 tcs
->ramsearch
= false;
1217 tcs
->ramsearch
= tc_stat
.ramcache
;
1220 tcs
->entry_count
= hdr
->entry_count
[tcs
->type
];
1225 if (!tagcache_is_numeric_tag(tcs
->type
))
1227 tcs
->idxfd
[tcs
->type
] = open_tag_fd(&tag_hdr
, tcs
->type
, false);
1228 if (tcs
->idxfd
[tcs
->type
] < 0)
1232 /* Always open as R/W so we can pass tcs to functions that modify data also
1233 * without failing. */
1234 tcs
->masterfd
= open_master_fd(&master_hdr
, true);
1236 if (tcs
->masterfd
< 0)
1241 tcs
->initialized
= true;
1247 void tagcache_search_set_uniqbuf(struct tagcache_search
*tcs
,
1248 void *buffer
, long length
)
1250 tcs
->unique_list
= (unsigned long *)buffer
;
1251 tcs
->unique_list_capacity
= length
/ sizeof(*tcs
->unique_list
);
1252 tcs
->unique_list_count
= 0;
1255 bool tagcache_search_add_filter(struct tagcache_search
*tcs
,
1258 if (tcs
->filter_count
== TAGCACHE_MAX_FILTERS
)
1261 if (!tagcache_is_unique_tag(tag
) || tagcache_is_numeric_tag(tag
))
1264 tcs
->filter_tag
[tcs
->filter_count
] = tag
;
1265 tcs
->filter_seek
[tcs
->filter_count
] = seek
;
1266 tcs
->filter_count
++;
1271 bool tagcache_search_add_clause(struct tagcache_search
*tcs
,
1272 struct tagcache_search_clause
*clause
)
1276 if (tcs
->clause_count
>= TAGCACHE_MAX_CLAUSES
)
1278 logf("Too many clauses");
1282 /* Check if there is already a similar filter in present (filters are
1283 * much faster than clauses).
1285 for (i
= 0; i
< tcs
->filter_count
; i
++)
1287 if (tcs
->filter_tag
[i
] == clause
->tag
)
1291 if (!tagcache_is_numeric_tag(clause
->tag
) && tcs
->idxfd
[clause
->tag
] < 0)
1295 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, clause
->tag
);
1296 tcs
->idxfd
[clause
->tag
] = open(buf
, O_RDONLY
);
1299 tcs
->clause
[tcs
->clause_count
] = clause
;
1300 tcs
->clause_count
++;
1305 /* TODO: Remove this mess. */
1306 #ifdef HAVE_DIRCACHE
1307 #define TAG_FILENAME_RAM(tcs) ((tcs->type == tag_filename) \
1308 ? ((flag & FLAG_DIRCACHE) && is_dircache_intact()) : 1)
1310 #define TAG_FILENAME_RAM(tcs) (tcs->type != tag_filename)
1313 static bool get_next(struct tagcache_search
*tcs
)
1315 static char buf
[TAG_MAXLEN
+32];
1316 struct tagfile_entry entry
;
1319 if (!tcs
->valid
|| !tc_stat
.ready
)
1322 if (tcs
->idxfd
[tcs
->type
] < 0 && !tagcache_is_numeric_tag(tcs
->type
)
1323 #ifdef HAVE_TC_RAMCACHE
1329 /* Relative fetch. */
1330 if (tcs
->filter_count
> 0 || tcs
->clause_count
> 0
1331 || tagcache_is_numeric_tag(tcs
->type
))
1333 /* Check for end of list. */
1334 if (tcs
->seek_list_count
== 0)
1336 /* Try to fetch more. */
1337 if (!build_lookup_list(tcs
))
1344 tcs
->seek_list_count
--;
1345 flag
= tcs
->seek_flags
[tcs
->seek_list_count
];
1347 /* Seek stream to the correct position and continue to direct fetch. */
1348 if ((!tcs
->ramsearch
|| !TAG_FILENAME_RAM(tcs
))
1349 && !tagcache_is_numeric_tag(tcs
->type
))
1351 if (!open_files(tcs
, tcs
->type
))
1354 lseek(tcs
->idxfd
[tcs
->type
], tcs
->seek_list
[tcs
->seek_list_count
], SEEK_SET
);
1357 tcs
->position
= tcs
->seek_list
[tcs
->seek_list_count
];
1360 if (tagcache_is_numeric_tag(tcs
->type
))
1362 snprintf(buf
, sizeof(buf
), "%d", tcs
->position
);
1363 tcs
->result_seek
= tcs
->position
;
1365 tcs
->result_len
= strlen(buf
) + 1;
1370 #ifdef HAVE_TC_RAMCACHE
1371 if (tcs
->ramsearch
&& TAG_FILENAME_RAM(tcs
))
1373 struct tagfile_entry
*ep
;
1375 if (tcs
->entry_count
== 0)
1382 tcs
->result_seek
= tcs
->position
;
1384 # ifdef HAVE_DIRCACHE
1385 if (tcs
->type
== tag_filename
)
1387 dircache_copy_path((struct dirent
*)tcs
->position
,
1390 tcs
->result_len
= strlen(buf
) + 1;
1391 tcs
->idx_id
= FLAG_GET_ATTR(flag
);
1392 tcs
->ramresult
= false;
1398 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->position
];
1399 tcs
->position
+= sizeof(struct tagfile_entry
) + ep
->tag_length
;
1400 tcs
->result
= ep
->tag_data
;
1401 tcs
->result_len
= strlen(tcs
->result
) + 1;
1402 tcs
->idx_id
= ep
->idx_id
;
1403 tcs
->ramresult
= true;
1410 if (!open_files(tcs
, tcs
->type
))
1413 tcs
->result_seek
= lseek(tcs
->idxfd
[tcs
->type
], 0, SEEK_CUR
);
1414 if (ecread(tcs
->idxfd
[tcs
->type
], &entry
, 1,
1415 tagfile_entry_ec
, tc_stat
.econ
) != sizeof(struct tagfile_entry
))
1423 if (entry
.tag_length
> (long)sizeof(buf
))
1426 logf("too long tag #2");
1430 if (read(tcs
->idxfd
[tcs
->type
], buf
, entry
.tag_length
) != entry
.tag_length
)
1433 logf("read error #4");
1438 tcs
->result_len
= strlen(tcs
->result
) + 1;
1439 tcs
->idx_id
= entry
.idx_id
;
1440 tcs
->ramresult
= false;
1445 bool tagcache_get_next(struct tagcache_search
*tcs
)
1447 while (get_next(tcs
))
1449 if (tcs
->result_len
> 1)
1456 bool tagcache_retrieve(struct tagcache_search
*tcs
, int idxid
,
1457 int tag
, char *buf
, long size
)
1459 struct index_entry idx
;
1462 if (!get_index(tcs
->masterfd
, idxid
, &idx
, true))
1465 return retrieve(tcs
, &idx
, tag
, buf
, size
);
1468 static bool update_master_header(void)
1470 struct master_header myhdr
;
1476 if ( (fd
= open_master_fd(&myhdr
, true)) < 0)
1479 myhdr
.serial
= current_tcmh
.serial
;
1480 myhdr
.commitid
= current_tcmh
.commitid
;
1483 lseek(fd
, 0, SEEK_SET
);
1484 ecwrite(fd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
1487 #ifdef HAVE_TC_RAMCACHE
1490 hdr
->h
.serial
= current_tcmh
.serial
;
1491 hdr
->h
.commitid
= current_tcmh
.commitid
;
1500 void tagcache_modify(struct tagcache_search
*tcs
, int type
, const char *text
)
1502 struct tagentry
*entry
;
1504 if (tcs
->type
!= tag_title
)
1507 /* We will need reserve buffer for this. */
1510 struct tagfile_entry
*ep
;
1512 ep
= (struct tagfile_entry
*)&hdr
->tags
[tcs
->type
][tcs
->result_seek
];
1513 tcs
->seek_list
[tcs
->seek_list_count
];
1516 entry
= find_entry_ram();
1521 void tagcache_search_finish(struct tagcache_search
*tcs
)
1525 if (!tcs
->initialized
)
1528 if (tcs
->masterfd
>= 0)
1530 close(tcs
->masterfd
);
1534 for (i
= 0; i
< TAG_COUNT
; i
++)
1536 if (tcs
->idxfd
[i
] >= 0)
1538 close(tcs
->idxfd
[i
]);
1543 tcs
->ramsearch
= false;
1545 tcs
->initialized
= 0;
1550 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1551 static struct tagfile_entry
*get_tag(const struct index_entry
*entry
, int tag
)
1553 return (struct tagfile_entry
*)&hdr
->tags
[tag
][entry
->tag_seek
[tag
]];
1556 static long get_tag_numeric(const struct index_entry
*entry
, int tag
)
1558 return check_virtual_tags(tag
, entry
);
1561 static char* get_tag_string(const struct index_entry
*entry
, int tag
)
1563 char* s
= get_tag(entry
, tag
)->tag_data
;
1564 return strcmp(s
, UNTAGGED
) ? s
: NULL
;
1567 bool tagcache_fill_tags(struct mp3entry
*id3
, const char *filename
)
1569 struct index_entry
*entry
;
1575 /* Find the corresponding entry in tagcache. */
1576 idx_id
= find_entry_ram(filename
, NULL
);
1577 if (idx_id
< 0 || !tc_stat
.ramcache
)
1580 entry
= &hdr
->indices
[idx_id
];
1582 id3
->title
= get_tag_string(entry
, tag_title
);
1583 id3
->artist
= get_tag_string(entry
, tag_artist
);
1584 id3
->album
= get_tag_string(entry
, tag_album
);
1585 id3
->genre_string
= get_tag_string(entry
, tag_genre
);
1586 id3
->composer
= get_tag_string(entry
, tag_composer
);
1587 id3
->comment
= get_tag_string(entry
, tag_comment
);
1588 id3
->albumartist
= get_tag_string(entry
, tag_albumartist
);
1589 id3
->grouping
= get_tag_string(entry
, tag_grouping
);
1591 id3
->playcount
= get_tag_numeric(entry
, tag_playcount
);
1592 id3
->rating
= get_tag_numeric(entry
, tag_rating
);
1593 id3
->lastplayed
= get_tag_numeric(entry
, tag_lastplayed
);
1594 id3
->score
= get_tag_numeric(entry
, tag_virt_autoscore
) / 10;
1595 id3
->year
= get_tag_numeric(entry
, tag_year
);
1597 id3
->discnum
= get_tag_numeric(entry
, tag_discnumber
);
1598 id3
->tracknum
= get_tag_numeric(entry
, tag_tracknumber
);
1599 id3
->bitrate
= get_tag_numeric(entry
, tag_bitrate
);
1600 if (id3
->bitrate
== 0)
1607 static inline void write_item(const char *item
)
1609 int len
= strlen(item
) + 1;
1612 write(cachefd
, item
, len
);
1615 static int check_if_empty(char **tag
)
1619 if (*tag
== NULL
|| **tag
== '\0')
1622 return sizeof(UNTAGGED
); /* Tag length */
1625 length
= strlen(*tag
);
1626 if (length
> TAG_MAXLEN
)
1628 logf("over length tag: %s", *tag
);
1629 length
= TAG_MAXLEN
;
1630 (*tag
)[length
] = '\0';
1636 #define ADD_TAG(entry,tag,data) \
1638 entry.tag_offset[tag] = offset; \
1639 entry.tag_length[tag] = check_if_empty(data); \
1640 offset += entry.tag_length[tag]
1642 static void add_tagcache(char *path
, unsigned long mtime
1643 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1644 ,const struct dirent
*dc
1648 struct mp3entry id3
;
1649 struct temp_file_entry entry
;
1653 char tracknumfix
[3];
1655 int path_length
= strlen(path
);
1656 bool has_albumartist
;
1662 /* Check for overlength file path. */
1663 if (path_length
> TAG_MAXLEN
)
1665 /* Path can't be shortened. */
1666 logf("Too long path: %s", path
);
1670 /* Check if the file is supported. */
1671 if (probe_file_format(path
) == AFMT_UNKNOWN
)
1674 /* Check if the file is already cached. */
1675 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1676 if (tc_stat
.ramcache
&& is_dircache_intact())
1678 idx_id
= find_entry_ram(path
, dc
);
1683 if (filenametag_fd
>= 0)
1685 idx_id
= find_entry_disk(path
);
1689 /* Check if file has been modified. */
1692 struct index_entry idx
;
1694 if (!get_index(-1, idx_id
, &idx
, true))
1696 logf("failed to retrieve index entry");
1700 if ((unsigned long)idx
.tag_seek
[tag_mtime
] == mtime
)
1702 /* No changes to file. */
1706 /* Metadata might have been changed. Delete the entry. */
1707 logf("Re-adding: %s", path
);
1708 if (!delete_entry(idx_id
))
1710 logf("delete_entry failed: %d", idx_id
);
1715 fd
= open(path
, O_RDONLY
);
1718 logf("open fail: %s", path
);
1722 memset(&id3
, 0, sizeof(struct mp3entry
));
1723 memset(&entry
, 0, sizeof(struct temp_file_entry
));
1724 memset(&tracknumfix
, 0, sizeof(tracknumfix
));
1725 ret
= get_metadata(&id3
, fd
, path
);
1731 logf("-> %s", path
);
1733 /* Generate track number if missing. */
1734 if (id3
.tracknum
<= 0)
1736 const char *p
= strrchr(path
, '.');
1739 p
= &path
[strlen(path
)-1];
1743 if (isdigit(*p
) && isdigit(*(p
-1)))
1745 tracknumfix
[1] = *p
--;
1746 tracknumfix
[0] = *p
;
1752 if (tracknumfix
[0] != '\0')
1754 id3
.tracknum
= atoi(tracknumfix
);
1755 /* Set a flag to indicate track number has been generated. */
1756 entry
.flag
|= FLAG_TRKNUMGEN
;
1760 /* Unable to generate track number. */
1766 entry
.tag_offset
[tag_year
] = id3
.year
;
1767 entry
.tag_offset
[tag_discnumber
] = id3
.discnum
;
1768 entry
.tag_offset
[tag_tracknumber
] = id3
.tracknum
;
1769 entry
.tag_offset
[tag_length
] = id3
.length
;
1770 entry
.tag_offset
[tag_bitrate
] = id3
.bitrate
;
1771 entry
.tag_offset
[tag_mtime
] = mtime
;
1774 has_albumartist
= id3
.albumartist
!= NULL
1775 && strlen(id3
.albumartist
) > 0;
1776 has_grouping
= id3
.grouping
!= NULL
1777 && strlen(id3
.grouping
) > 0;
1779 ADD_TAG(entry
, tag_filename
, &path
);
1780 ADD_TAG(entry
, tag_title
, &id3
.title
);
1781 ADD_TAG(entry
, tag_artist
, &id3
.artist
);
1782 ADD_TAG(entry
, tag_album
, &id3
.album
);
1783 ADD_TAG(entry
, tag_genre
, &id3
.genre_string
);
1784 ADD_TAG(entry
, tag_composer
, &id3
.composer
);
1785 ADD_TAG(entry
, tag_comment
, &id3
.comment
);
1786 if (has_albumartist
)
1788 ADD_TAG(entry
, tag_albumartist
, &id3
.albumartist
);
1792 ADD_TAG(entry
, tag_albumartist
, &id3
.artist
);
1796 ADD_TAG(entry
, tag_grouping
, &id3
.grouping
);
1800 ADD_TAG(entry
, tag_grouping
, &id3
.title
);
1802 entry
.data_length
= offset
;
1804 /* Write the header */
1805 write(cachefd
, &entry
, sizeof(struct temp_file_entry
));
1807 /* And tags also... Correct order is critical */
1809 write_item(id3
.title
);
1810 write_item(id3
.artist
);
1811 write_item(id3
.album
);
1812 write_item(id3
.genre_string
);
1813 write_item(id3
.composer
);
1814 write_item(id3
.comment
);
1815 if (has_albumartist
)
1817 write_item(id3
.albumartist
);
1821 write_item(id3
.artist
);
1825 write_item(id3
.grouping
);
1829 write_item(id3
.title
);
1831 total_entry_count
++;
1834 static bool tempbuf_insert(char *str
, int id
, int idx_id
, bool unique
)
1836 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1837 int len
= strlen(str
)+1;
1840 unsigned *crcbuf
= (unsigned *)&tempbuf
[tempbuf_size
-4];
1841 char buf
[TAG_MAXLEN
+32];
1843 for (i
= 0; str
[i
] != '\0' && i
< (int)sizeof(buf
)-1; i
++)
1844 buf
[i
] = tolower(str
[i
]);
1847 crc32
= crc_32(buf
, i
, 0xffffffff);
1851 /* Check if the crc does not exist -> entry does not exist for sure. */
1852 for (i
= 0; i
< tempbufidx
; i
++)
1854 if (crcbuf
[-i
] != crc32
)
1857 if (!strcasecmp(str
, index
[i
].str
))
1859 if (id
< 0 || id
>= lookup_buffer_depth
)
1861 logf("lookup buf overf.: %d", id
);
1865 lookup
[id
] = &index
[i
];
1871 /* Insert to CRC buffer. */
1872 crcbuf
[-tempbufidx
] = crc32
;
1875 /* Insert it to the buffer. */
1876 tempbuf_left
-= len
;
1877 if (tempbuf_left
- 4 < 0 || tempbufidx
>= commit_entry_count
-1)
1880 if (id
>= lookup_buffer_depth
)
1882 logf("lookup buf overf. #2: %d", id
);
1888 lookup
[id
] = &index
[tempbufidx
];
1889 index
[tempbufidx
].idlist
.id
= id
;
1892 index
[tempbufidx
].idlist
.id
= -1;
1894 index
[tempbufidx
].idlist
.next
= NULL
;
1895 index
[tempbufidx
].idx_id
= idx_id
;
1896 index
[tempbufidx
].seek
= -1;
1897 index
[tempbufidx
].str
= &tempbuf
[tempbuf_pos
];
1898 memcpy(index
[tempbufidx
].str
, str
, len
);
1905 static int compare(const void *p1
, const void *p2
)
1909 struct tempbuf_searchidx
*e1
= (struct tempbuf_searchidx
*)p1
;
1910 struct tempbuf_searchidx
*e2
= (struct tempbuf_searchidx
*)p2
;
1912 if (strcmp(e1
->str
, UNTAGGED
) == 0)
1914 if (strcmp(e2
->str
, UNTAGGED
) == 0)
1918 else if (strcmp(e2
->str
, UNTAGGED
) == 0)
1921 return strncasecmp(e1
->str
, e2
->str
, TAG_MAXLEN
);
1924 static int tempbuf_sort(int fd
)
1926 struct tempbuf_searchidx
*index
= (struct tempbuf_searchidx
*)tempbuf
;
1927 struct tagfile_entry fe
;
1931 /* Generate reverse lookup entries. */
1932 for (i
= 0; i
< lookup_buffer_depth
; i
++)
1934 struct tempbuf_id_list
*idlist
;
1939 if (lookup
[i
]->idlist
.id
== i
)
1942 idlist
= &lookup
[i
]->idlist
;
1943 while (idlist
->next
!= NULL
)
1944 idlist
= idlist
->next
;
1946 tempbuf_left
-= sizeof(struct tempbuf_id_list
);
1947 if (tempbuf_left
- 4 < 0)
1950 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
1951 if (tempbuf_pos
& 0x03)
1953 tempbuf_pos
= (tempbuf_pos
& ~0x03) + 0x04;
1955 idlist
->next
= (struct tempbuf_id_list
*)&tempbuf
[tempbuf_pos
];
1957 tempbuf_pos
+= sizeof(struct tempbuf_id_list
);
1959 idlist
= idlist
->next
;
1961 idlist
->next
= NULL
;
1966 qsort(index
, tempbufidx
, sizeof(struct tempbuf_searchidx
), compare
);
1967 memset(lookup
, 0, lookup_buffer_depth
* sizeof(struct tempbuf_searchidx
**));
1969 for (i
= 0; i
< tempbufidx
; i
++)
1971 struct tempbuf_id_list
*idlist
= &index
[i
].idlist
;
1973 /* Fix the lookup list. */
1974 while (idlist
!= NULL
)
1976 if (idlist
->id
>= 0)
1977 lookup
[idlist
->id
] = &index
[i
];
1978 idlist
= idlist
->next
;
1981 index
[i
].seek
= lseek(fd
, 0, SEEK_CUR
);
1982 length
= strlen(index
[i
].str
) + 1;
1983 fe
.tag_length
= length
;
1984 fe
.idx_id
= index
[i
].idx_id
;
1986 /* Check the chunk alignment. */
1987 if ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
1988 % TAGFILE_ENTRY_CHUNK_LENGTH
)
1990 fe
.tag_length
+= TAGFILE_ENTRY_CHUNK_LENGTH
-
1991 ((fe
.tag_length
+ sizeof(struct tagfile_entry
))
1992 % TAGFILE_ENTRY_CHUNK_LENGTH
);
1995 #ifdef TAGCACHE_STRICT_ALIGN
1996 /* Make sure the entry is long aligned. */
1997 if (index
[i
].seek
& 0x03)
1999 logf("tempbuf_sort: alignment error!");
2004 if (ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
) !=
2005 sizeof(struct tagfile_entry
))
2007 logf("tempbuf_sort: write error #1");
2011 if (write(fd
, index
[i
].str
, length
) != length
)
2013 logf("tempbuf_sort: write error #2");
2017 /* Write some padding. */
2018 if (fe
.tag_length
- length
> 0)
2019 write(fd
, "XXXXXXXX", fe
.tag_length
- length
);
2025 inline static struct tempbuf_searchidx
* tempbuf_locate(int id
)
2027 if (id
< 0 || id
>= lookup_buffer_depth
)
2034 inline static int tempbuf_find_location(int id
)
2036 struct tempbuf_searchidx
*entry
;
2038 entry
= tempbuf_locate(id
);
2045 static bool build_numeric_indices(struct tagcache_header
*h
, int tmpfd
)
2047 struct master_header tcmh
;
2048 struct index_entry idx
;
2051 struct temp_file_entry
*entrybuf
= (struct temp_file_entry
*)tempbuf
;
2053 int entries_processed
= 0;
2055 char buf
[TAG_MAXLEN
];
2057 max_entries
= tempbuf_size
/ sizeof(struct temp_file_entry
) - 1;
2059 logf("Building numeric indices...");
2060 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2062 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2065 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2067 if (masterfd_pos
== filesize(masterfd
))
2069 logf("we can't append!");
2074 while (entries_processed
< h
->entry_count
)
2076 int count
= MIN(h
->entry_count
- entries_processed
, max_entries
);
2078 /* Read in as many entries as possible. */
2079 for (i
= 0; i
< count
; i
++)
2081 struct temp_file_entry
*tfe
= &entrybuf
[i
];
2084 /* Read in numeric data. */
2085 if (read(tmpfd
, tfe
, sizeof(struct temp_file_entry
)) !=
2086 sizeof(struct temp_file_entry
))
2088 logf("read fail #1");
2093 datastart
= lseek(tmpfd
, 0, SEEK_CUR
);
2096 * Read string data from the following tags:
2102 * A crc32 hash is calculated from the read data
2103 * and stored back to the data offset field kept in memory.
2105 #define tmpdb_read_string_tag(tag) \
2106 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2107 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2109 logf("read fail: buffer overflow"); \
2114 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2115 tfe->tag_length[tag]) \
2117 logf("read fail #2"); \
2122 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2123 lseek(tmpfd, datastart, SEEK_SET)
2125 tmpdb_read_string_tag(tag_filename
);
2126 tmpdb_read_string_tag(tag_artist
);
2127 tmpdb_read_string_tag(tag_album
);
2128 tmpdb_read_string_tag(tag_title
);
2130 /* Seek to the end of the string data. */
2131 lseek(tmpfd
, tfe
->data_length
, SEEK_CUR
);
2134 /* Backup the master index position. */
2135 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2136 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2138 /* Check if we can resurrect some deleted runtime statistics data. */
2139 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
++)
2141 /* Read the index entry. */
2142 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2143 != sizeof(struct index_entry
))
2145 logf("read fail #3");
2151 * Skip unless the entry is marked as being deleted
2152 * or the data has already been resurrected.
2154 if (!(idx
.flag
& FLAG_DELETED
) || idx
.flag
& FLAG_RESURRECTED
)
2157 /* Now try to match the entry. */
2159 * To succesfully match a song, the following conditions
2162 * For numeric fields: tag_length
2163 * - Full identical match is required
2165 * If tag_filename matches, no further checking necessary.
2167 * For string hashes: tag_artist, tag_album, tag_title
2168 * - Two of these must match
2170 for (j
= 0; j
< count
; j
++)
2172 struct temp_file_entry
*tfe
= &entrybuf
[j
];
2174 /* Try to match numeric fields first. */
2175 if (tfe
->tag_offset
[tag_length
] != idx
.tag_seek
[tag_length
])
2178 /* Now it's time to do the hash matching. */
2179 if (tfe
->tag_offset
[tag_filename
] != idx
.tag_seek
[tag_filename
])
2181 int match_count
= 0;
2183 /* No filename match, check if we can match two other tags. */
2184 #define tmpdb_match(tag) \
2185 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2188 tmpdb_match(tag_artist
);
2189 tmpdb_match(tag_album
);
2190 tmpdb_match(tag_title
);
2192 if (match_count
< 2)
2194 /* Still no match found, give up. */
2199 /* A match found, now copy & resurrect the statistical data. */
2200 #define tmpdb_copy_tag(tag) \
2201 tfe->tag_offset[tag] = idx.tag_seek[tag]
2203 tmpdb_copy_tag(tag_playcount
);
2204 tmpdb_copy_tag(tag_rating
);
2205 tmpdb_copy_tag(tag_playtime
);
2206 tmpdb_copy_tag(tag_lastplayed
);
2207 tmpdb_copy_tag(tag_commitid
);
2209 /* Avoid processing this entry again. */
2210 idx
.flag
|= FLAG_RESURRECTED
;
2212 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
2213 if (ecwrite(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2214 != sizeof(struct index_entry
))
2216 logf("masterfd writeback fail #1");
2221 logf("Entry resurrected");
2226 /* Restore the master index position. */
2227 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2229 /* Commit the data to the index. */
2230 for (i
= 0; i
< count
; i
++)
2232 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2234 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2235 != sizeof(struct index_entry
))
2237 logf("read fail #3");
2242 for (j
= 0; j
< TAG_COUNT
; j
++)
2244 if (!tagcache_is_numeric_tag(j
))
2247 idx
.tag_seek
[j
] = entrybuf
[i
].tag_offset
[j
];
2249 idx
.flag
= entrybuf
[i
].flag
;
2251 if (idx
.tag_seek
[tag_commitid
])
2253 /* Data has been resurrected. */
2254 idx
.flag
|= FLAG_DIRTYNUM
;
2256 else if (tc_stat
.ready
&& current_tcmh
.commitid
> 0)
2258 idx
.tag_seek
[tag_commitid
] = current_tcmh
.commitid
;
2259 idx
.flag
|= FLAG_DIRTYNUM
;
2262 /* Write back the updated index. */
2263 lseek(masterfd
, loc
, SEEK_SET
);
2264 if (ecwrite(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
2265 != sizeof(struct index_entry
))
2273 entries_processed
+= count
;
2274 logf("%d/%ld entries processed", entries_processed
, h
->entry_count
);
2285 * == 0 temporary failure
2288 static int build_index(int index_type
, struct tagcache_header
*h
, int tmpfd
)
2291 struct tagcache_header tch
;
2292 struct master_header tcmh
;
2293 struct index_entry idxbuf
[IDX_BUF_DEPTH
];
2295 char buf
[TAG_MAXLEN
+32];
2296 int fd
= -1, masterfd
;
2301 logf("Building index: %d", index_type
);
2303 /* Check the number of entries we need to allocate ram for. */
2304 commit_entry_count
= h
->entry_count
+ 1;
2306 masterfd
= open_master_fd(&tcmh
, false);
2309 commit_entry_count
+= tcmh
.tch
.entry_count
;
2313 remove_files(); /* Just to be sure we are clean. */
2315 /* Open the index file, which contains the tag names. */
2316 fd
= open_tag_fd(&tch
, index_type
, true);
2319 logf("tch.datasize=%ld", tch
.datasize
);
2320 lookup_buffer_depth
= 1 +
2321 /* First part */ commit_entry_count
+
2322 /* Second part */ (tch
.datasize
/ TAGFILE_ENTRY_CHUNK_LENGTH
);
2326 lookup_buffer_depth
= 1 +
2327 /* First part */ commit_entry_count
+
2328 /* Second part */ 0;
2331 logf("lookup_buffer_depth=%ld", lookup_buffer_depth
);
2332 logf("commit_entry_count=%ld", commit_entry_count
);
2334 /* Allocate buffer for all index entries from both old and new
2337 tempbuf_pos
= commit_entry_count
* sizeof(struct tempbuf_searchidx
);
2339 /* Allocate lookup buffer. The first portion of commit_entry_count
2340 * contains the new tags in the temporary file and the second
2341 * part for locating entries already in the db.
2344 * +---------+---------------------------+
2345 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2346 * +---------+---------------------------+
2348 * Old tags are inserted to a temporary buffer with position:
2349 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2350 * And new tags with index:
2351 * tempbuf_insert(idx, ...);
2353 * The buffer is sorted and written into tag file:
2354 * tempbuf_sort(...);
2355 * leaving master index locations messed up.
2357 * That is fixed using the lookup buffer for old tags:
2358 * new_seek = tempbuf_find_location(old_seek, ...);
2360 * new_seek = tempbuf_find_location(idx);
2362 lookup
= (struct tempbuf_searchidx
**)&tempbuf
[tempbuf_pos
];
2363 tempbuf_pos
+= lookup_buffer_depth
* sizeof(void **);
2364 memset(lookup
, 0, lookup_buffer_depth
* sizeof(void **));
2366 /* And calculate the remaining data space used mainly for storing
2367 * tag data (strings). */
2368 tempbuf_left
= tempbuf_size
- tempbuf_pos
- 8;
2369 if (tempbuf_left
- TAGFILE_ENTRY_AVG_LENGTH
* commit_entry_count
< 0)
2371 logf("Buffer way too small!");
2378 * If tag file contains unique tags (sorted index), we will load
2379 * it entirely into memory so we can resort it later for use with
2382 if (tagcache_is_sorted_tag(index_type
))
2384 logf("loading tags...");
2385 for (i
= 0; i
< tch
.entry_count
; i
++)
2387 struct tagfile_entry entry
;
2388 int loc
= lseek(fd
, 0, SEEK_CUR
);
2391 if (ecread(fd
, &entry
, 1, tagfile_entry_ec
, tc_stat
.econ
)
2392 != sizeof(struct tagfile_entry
))
2394 logf("read error #7");
2399 if (entry
.tag_length
>= (int)sizeof(buf
))
2401 logf("too long tag #3");
2406 if (read(fd
, buf
, entry
.tag_length
) != entry
.tag_length
)
2408 logf("read error #8");
2413 /* Skip deleted entries. */
2418 * Save the tag and tag id in the memory buffer. Tag id
2419 * is saved so we can later reindex the master lookup
2420 * table when the index gets resorted.
2422 ret
= tempbuf_insert(buf
, loc
/TAGFILE_ENTRY_CHUNK_LENGTH
2423 + commit_entry_count
, entry
.idx_id
,
2424 tagcache_is_unique_tag(index_type
));
2435 tempbufidx
= tch
.entry_count
;
2440 * Creating new index file to store the tags. No need to preload
2441 * anything whether the index type is sorted or not.
2443 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, index_type
);
2444 fd
= open(buf
, O_WRONLY
| O_CREAT
| O_TRUNC
);
2447 logf("%s open fail", buf
);
2451 tch
.magic
= TAGCACHE_MAGIC
;
2452 tch
.entry_count
= 0;
2455 if (ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
)
2456 != sizeof(struct tagcache_header
))
2458 logf("header write failed");
2464 /* Loading the tag lookup file as "master file". */
2465 logf("Loading index file");
2466 masterfd
= open(TAGCACHE_FILE_MASTER
, O_RDWR
);
2470 logf("Creating new DB");
2471 masterfd
= open(TAGCACHE_FILE_MASTER
, O_WRONLY
| O_CREAT
| O_TRUNC
);
2475 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER
);
2480 /* Write the header (write real values later). */
2481 memset(&tcmh
, 0, sizeof(struct master_header
));
2483 tcmh
.tch
.entry_count
= 0;
2484 tcmh
.tch
.datasize
= 0;
2486 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2488 masterfd_pos
= lseek(masterfd
, 0, SEEK_CUR
);
2493 * Master file already exists so we need to process the current
2498 if (ecread(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
) !=
2499 sizeof(struct master_header
) || tcmh
.tch
.magic
!= TAGCACHE_MAGIC
)
2501 logf("header error");
2508 * If we reach end of the master file, we need to expand it to
2509 * hold new tags. If the current index is not sorted, we can
2510 * simply append new data to end of the file.
2511 * However, if the index is sorted, we need to update all tag
2512 * pointers in the master file for the current index.
2514 masterfd_pos
= lseek(masterfd
, tcmh
.tch
.entry_count
* sizeof(struct index_entry
),
2516 if (masterfd_pos
== filesize(masterfd
))
2518 logf("appending...");
2524 * Load new unique tags in memory to be sorted later and added
2525 * to the master lookup file.
2527 if (tagcache_is_sorted_tag(index_type
))
2529 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2530 /* h is the header of the temporary file containing new tags. */
2531 logf("inserting new tags...");
2532 for (i
= 0; i
< h
->entry_count
; i
++)
2534 struct temp_file_entry entry
;
2536 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2537 sizeof(struct temp_file_entry
))
2539 logf("read fail #3");
2545 if (entry
.tag_length
[index_type
] >= (long)sizeof(buf
))
2547 logf("too long entry!");
2552 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2553 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2554 entry
.tag_length
[index_type
])
2556 logf("read fail #4");
2561 if (tagcache_is_unique_tag(index_type
))
2562 error
= !tempbuf_insert(buf
, i
, -1, true);
2564 error
= !tempbuf_insert(buf
, i
, tcmh
.tch
.entry_count
+ i
, false);
2568 logf("insert error");
2573 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2574 entry
.tag_length
[index_type
], SEEK_CUR
);
2579 /* Sort the buffer data and write it to the index file. */
2580 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
2581 i
= tempbuf_sort(fd
);
2584 logf("sorted %d tags", i
);
2587 * Now update all indexes in the master lookup file.
2589 logf("updating indices...");
2590 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
2591 for (i
= 0; i
< tcmh
.tch
.entry_count
; i
+= idxbuf_pos
)
2594 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2596 idxbuf_pos
= MIN(tcmh
.tch
.entry_count
- i
, IDX_BUF_DEPTH
);
2598 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2599 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2601 logf("read fail #5");
2605 lseek(masterfd
, loc
, SEEK_SET
);
2607 for (j
= 0; j
< idxbuf_pos
; j
++)
2609 if (idxbuf
[j
].flag
& FLAG_DELETED
)
2611 /* We can just ignore deleted entries. */
2612 // idxbuf[j].tag_seek[index_type] = 0;
2616 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(
2617 idxbuf
[j
].tag_seek
[index_type
]/TAGFILE_ENTRY_CHUNK_LENGTH
2618 + commit_entry_count
);
2620 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2622 logf("update error: %d/%d/%ld",
2623 idxbuf
[j
].flag
, i
+j
, tcmh
.tch
.entry_count
);
2631 /* Write back the updated index. */
2632 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2633 index_entry_ec
, tc_stat
.econ
) !=
2634 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2645 * Walk through the temporary file containing the new tags.
2647 // build_normal_index(h, tmpfd, masterfd, idx);
2648 logf("updating new indices...");
2649 lseek(masterfd
, masterfd_pos
, SEEK_SET
);
2650 lseek(tmpfd
, sizeof(struct tagcache_header
), SEEK_SET
);
2651 lseek(fd
, 0, SEEK_END
);
2652 for (i
= 0; i
< h
->entry_count
; i
+= idxbuf_pos
)
2656 idxbuf_pos
= MIN(h
->entry_count
- i
, IDX_BUF_DEPTH
);
2659 memset(idxbuf
, 0, sizeof(struct index_entry
)*IDX_BUF_DEPTH
);
2663 int loc
= lseek(masterfd
, 0, SEEK_CUR
);
2665 if (ecread(masterfd
, idxbuf
, idxbuf_pos
, index_entry_ec
, tc_stat
.econ
)
2666 != (int)sizeof(struct index_entry
)*idxbuf_pos
)
2668 logf("read fail #6");
2672 lseek(masterfd
, loc
, SEEK_SET
);
2675 /* Read entry headers. */
2676 for (j
= 0; j
< idxbuf_pos
; j
++)
2678 if (!tagcache_is_sorted_tag(index_type
))
2680 struct temp_file_entry entry
;
2681 struct tagfile_entry fe
;
2683 if (read(tmpfd
, &entry
, sizeof(struct temp_file_entry
)) !=
2684 sizeof(struct temp_file_entry
))
2686 logf("read fail #7");
2692 if (entry
.tag_length
[index_type
] >= (int)sizeof(buf
))
2694 logf("too long entry!");
2695 logf("length=%d", entry
.tag_length
[index_type
]);
2696 logf("pos=0x%02lx", lseek(tmpfd
, 0, SEEK_CUR
));
2701 lseek(tmpfd
, entry
.tag_offset
[index_type
], SEEK_CUR
);
2702 if (read(tmpfd
, buf
, entry
.tag_length
[index_type
]) !=
2703 entry
.tag_length
[index_type
])
2705 logf("read fail #8");
2706 logf("offset=0x%02lx", entry
.tag_offset
[index_type
]);
2707 logf("length=0x%02x", entry
.tag_length
[index_type
]);
2712 /* Write to index file. */
2713 idxbuf
[j
].tag_seek
[index_type
] = lseek(fd
, 0, SEEK_CUR
);
2714 fe
.tag_length
= entry
.tag_length
[index_type
];
2715 fe
.idx_id
= tcmh
.tch
.entry_count
+ i
+ j
;
2716 ecwrite(fd
, &fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
2717 write(fd
, buf
, fe
.tag_length
);
2721 lseek(tmpfd
, entry
.data_length
- entry
.tag_offset
[index_type
] -
2722 entry
.tag_length
[index_type
], SEEK_CUR
);
2726 /* Locate the correct entry from the sorted array. */
2727 idxbuf
[j
].tag_seek
[index_type
] = tempbuf_find_location(i
+ j
);
2728 if (idxbuf
[j
].tag_seek
[index_type
] < 0)
2730 logf("entry not found (%d)", j
);
2738 if (ecwrite(masterfd
, idxbuf
, idxbuf_pos
,
2739 index_entry_ec
, tc_stat
.econ
) !=
2740 (int)sizeof(struct index_entry
)*idxbuf_pos
)
2742 logf("tagcache: write fail #4");
2751 /* Finally write the header. */
2752 tch
.magic
= TAGCACHE_MAGIC
;
2753 tch
.entry_count
= tempbufidx
;
2754 tch
.datasize
= lseek(fd
, 0, SEEK_END
) - sizeof(struct tagcache_header
);
2755 lseek(fd
, 0, SEEK_SET
);
2756 ecwrite(fd
, &tch
, 1, tagcache_header_ec
, tc_stat
.econ
);
2758 if (index_type
!= tag_filename
)
2759 h
->datasize
+= tch
.datasize
;
2760 logf("s:%d/%ld/%ld", index_type
, tch
.datasize
, h
->datasize
);
2772 static bool commit(void)
2774 struct tagcache_header tch
;
2775 struct master_header tcmh
;
2779 #ifdef HAVE_DIRCACHE
2780 bool dircache_buffer_stolen
= false;
2782 bool local_allocation
= false;
2784 logf("committing tagcache");
2789 tmpfd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
2792 logf("nothing to commit");
2797 /* Load the header. */
2798 len
= sizeof(struct tagcache_header
);
2799 rc
= read(tmpfd
, &tch
, len
);
2801 if (tch
.magic
!= TAGCACHE_MAGIC
|| rc
!= len
)
2803 logf("incorrect header");
2805 remove(TAGCACHE_FILE_TEMP
);
2809 if (tch
.entry_count
== 0)
2811 logf("nothing to commit");
2813 remove(TAGCACHE_FILE_TEMP
);
2817 #ifdef HAVE_EEPROM_SETTINGS
2818 remove(TAGCACHE_STATEFILE
);
2821 /* At first be sure to unload the ramcache! */
2822 #ifdef HAVE_TC_RAMCACHE
2823 tc_stat
.ramcache
= false;
2828 /* Try to steal every buffer we can :) */
2829 if (tempbuf_size
== 0)
2830 local_allocation
= true;
2832 #ifdef HAVE_DIRCACHE
2833 if (tempbuf_size
== 0)
2835 /* Try to steal the dircache buffer. */
2836 tempbuf
= dircache_steal_buffer(&tempbuf_size
);
2837 tempbuf_size
&= ~0x03;
2839 if (tempbuf_size
> 0)
2841 dircache_buffer_stolen
= true;
2846 #ifdef HAVE_TC_RAMCACHE
2847 if (tempbuf_size
== 0 && tc_stat
.ramcache_allocated
> 0)
2849 tempbuf
= (char *)(hdr
+ 1);
2850 tempbuf_size
= tc_stat
.ramcache_allocated
- sizeof(struct ramcache_header
) - 128;
2851 tempbuf_size
&= ~0x03;
2855 /* And finally fail if there are no buffers available. */
2856 if (tempbuf_size
== 0)
2858 logf("delaying commit until next boot");
2859 tc_stat
.commit_delayed
= true;
2865 logf("commit %ld entries...", tch
.entry_count
);
2867 /* Mark DB dirty so it will stay disabled if commit fails. */
2868 current_tcmh
.dirty
= true;
2869 update_master_header();
2871 /* Now create the index files. */
2872 tc_stat
.commit_step
= 0;
2874 tc_stat
.commit_delayed
= false;
2876 for (i
= 0; i
< TAG_COUNT
; i
++)
2880 if (tagcache_is_numeric_tag(i
))
2883 tc_stat
.commit_step
++;
2884 ret
= build_index(i
, &tch
, tmpfd
);
2888 logf("tagcache failed init");
2892 tc_stat
.commit_delayed
= true;
2893 tc_stat
.commit_step
= 0;
2899 if (!build_numeric_indices(&tch
, tmpfd
))
2901 logf("Failure to commit numeric indices");
2904 tc_stat
.commit_step
= 0;
2910 tc_stat
.commit_step
= 0;
2912 /* Update the master index headers. */
2913 if ( (masterfd
= open_master_fd(&tcmh
, true)) < 0)
2919 tcmh
.tch
.entry_count
+= tch
.entry_count
;
2920 tcmh
.tch
.datasize
= sizeof(struct master_header
)
2921 + sizeof(struct index_entry
) * tcmh
.tch
.entry_count
2926 lseek(masterfd
, 0, SEEK_SET
);
2927 ecwrite(masterfd
, &tcmh
, 1, master_header_ec
, tc_stat
.econ
);
2930 logf("tagcache committed");
2931 remove(TAGCACHE_FILE_TEMP
);
2932 tc_stat
.ready
= check_all_headers();
2933 tc_stat
.readyvalid
= true;
2935 if (local_allocation
)
2941 #ifdef HAVE_DIRCACHE
2942 /* Rebuild the dircache, if we stole the buffer. */
2943 if (dircache_buffer_stolen
)
2947 #ifdef HAVE_TC_RAMCACHE
2948 /* Reload tagcache. */
2949 if (tc_stat
.ramcache_allocated
> 0)
2950 tagcache_start_scan();
2958 static void allocate_tempbuf(void)
2960 /* Yeah, malloc would be really nice now :) */
2962 tempbuf_size
= 32*1024*1024;
2963 tempbuf
= malloc(tempbuf_size
);
2965 tempbuf
= (char *)(((long)audiobuf
& ~0x03) + 0x04);
2966 tempbuf_size
= (long)audiobufend
- (long)audiobuf
- 4;
2967 audiobuf
+= tempbuf_size
;
2971 static void free_tempbuf(void)
2973 if (tempbuf_size
== 0)
2979 audiobuf
-= tempbuf_size
;
2985 static bool modify_numeric_entry(int masterfd
, int idx_id
, int tag
, long data
)
2987 struct index_entry idx
;
2992 if (!tagcache_is_numeric_tag(tag
))
2995 if (!get_index(masterfd
, idx_id
, &idx
, false))
2998 idx
.tag_seek
[tag
] = data
;
2999 idx
.flag
|= FLAG_DIRTYNUM
;
3001 return write_index(masterfd
, idx_id
, &idx
);
3005 bool tagcache_modify_numeric_entry(struct tagcache_search
*tcs
,
3008 struct master_header myhdr
;
3010 if (tcs
->masterfd
< 0)
3012 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, true)) < 0)
3016 return modify_numeric_entry(tcs
->masterfd
, tcs
->idx_id
, tag
, data
);
3020 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
3022 static bool command_queue_is_full(void)
3026 next
= command_queue_widx
+ 1;
3027 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3030 return (next
== command_queue_ridx
);
3032 static bool command_queue_sync_callback(void)
3035 struct master_header myhdr
;
3038 mutex_lock(&command_queue_mutex
);
3040 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3043 while (command_queue_ridx
!= command_queue_widx
)
3045 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_ridx
];
3047 switch (ce
->command
)
3049 case CMD_UPDATE_MASTER_HEADER
:
3052 update_master_header();
3054 /* Re-open the masterfd. */
3055 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3060 case CMD_UPDATE_NUMERIC
:
3062 modify_numeric_entry(masterfd
, ce
->idx_id
, ce
->tag
, ce
->data
);
3067 if (++command_queue_ridx
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3068 command_queue_ridx
= 0;
3073 tc_stat
.queue_length
= 0;
3074 mutex_unlock(&command_queue_mutex
);
3078 static void run_command_queue(bool force
)
3080 if (COMMAND_QUEUE_IS_EMPTY
)
3083 if (force
|| command_queue_is_full())
3084 command_queue_sync_callback();
3086 register_ata_idle_func(command_queue_sync_callback
);
3089 static void queue_command(int cmd
, long idx_id
, int tag
, long data
)
3095 mutex_lock(&command_queue_mutex
);
3096 next
= command_queue_widx
+ 1;
3097 if (next
>= TAGCACHE_COMMAND_QUEUE_LENGTH
)
3100 /* Make sure queue is not full. */
3101 if (next
!= command_queue_ridx
)
3103 struct tagcache_command_entry
*ce
= &command_queue
[command_queue_widx
];
3106 ce
->idx_id
= idx_id
;
3110 command_queue_widx
= next
;
3112 tc_stat
.queue_length
++;
3114 mutex_unlock(&command_queue_mutex
);
3118 /* Queue is full, try again later... */
3119 mutex_unlock(&command_queue_mutex
);
3124 long tagcache_increase_serial(void)
3134 old
= current_tcmh
.serial
++;
3135 queue_command(CMD_UPDATE_MASTER_HEADER
, 0, 0, 0);
3140 void tagcache_update_numeric(int idx_id
, int tag
, long data
)
3142 queue_command(CMD_UPDATE_NUMERIC
, idx_id
, tag
, data
);
3145 long tagcache_get_serial(void)
3147 return current_tcmh
.serial
;
3150 long tagcache_get_commitid(void)
3152 return current_tcmh
.commitid
;
3155 static bool write_tag(int fd
, const char *tagstr
, const char *datastr
)
3160 snprintf(buf
, sizeof buf
, "%s=\"", tagstr
);
3161 for (i
= strlen(buf
); i
< (long)sizeof(buf
)-4; i
++)
3163 if (*datastr
== '\0')
3166 if (*datastr
== '"' || *datastr
== '\\')
3169 buf
[i
] = *(datastr
++);
3172 strcpy(&buf
[i
], "\" ");
3174 write(fd
, buf
, i
+ 2);
3179 static bool read_tag(char *dest
, long size
,
3180 const char *src
, const char *tagstr
)
3183 char current_tag
[32];
3185 while (*src
!= '\0')
3187 /* Skip all whitespace */
3195 /* Read in tag name */
3196 while (*src
!= '=' && *src
!= ' ')
3198 current_tag
[pos
] = *src
;
3202 if (*src
== '\0' || pos
>= (long)sizeof(current_tag
))
3205 current_tag
[pos
] = '\0';
3207 /* Read in tag data */
3209 /* Find the start. */
3210 while (*src
!= '"' && *src
!= '\0')
3213 if (*src
== '\0' || *(++src
) == '\0')
3216 /* Read the data. */
3217 for (pos
= 0; pos
< size
; pos
++)
3224 dest
[pos
] = *(src
+1);
3244 if (!strcasecmp(tagstr
, current_tag
))
3251 static int parse_changelog_line(int line_n
, const char *buf
, void *parameters
)
3253 struct index_entry idx
;
3254 char tag_data
[TAG_MAXLEN
+32];
3256 long masterfd
= (long)parameters
;
3257 const int import_tags
[] = { tag_playcount
, tag_rating
, tag_playtime
, tag_lastplayed
,
3265 logf("%d/%s", line_n
, buf
);
3266 if (!read_tag(tag_data
, sizeof tag_data
, buf
, "filename"))
3268 logf("filename missing");
3273 idx_id
= find_index(tag_data
);
3276 logf("entry not found");
3280 if (!get_index(masterfd
, idx_id
, &idx
, false))
3282 logf("failed to retrieve index entry");
3286 /* Stop if tag has already been modified. */
3287 if (idx
.flag
& FLAG_DIRTYNUM
)
3290 logf("import: %s", tag_data
);
3292 idx
.flag
|= FLAG_DIRTYNUM
;
3293 for (i
= 0; i
< (long)(sizeof(import_tags
)/sizeof(import_tags
[0])); i
++)
3297 if (!read_tag(tag_data
, sizeof tag_data
, buf
,
3298 tagcache_tag_to_str(import_tags
[i
])))
3303 data
= atoi(tag_data
);
3307 idx
.tag_seek
[import_tags
[i
]] = data
;
3309 if (import_tags
[i
] == tag_lastplayed
&& data
> current_tcmh
.serial
)
3310 current_tcmh
.serial
= data
;
3311 else if (import_tags
[i
] == tag_commitid
&& data
>= current_tcmh
.commitid
)
3312 current_tcmh
.commitid
= data
+ 1;
3315 return write_index(masterfd
, idx_id
, &idx
) ? 0 : -5;
3319 bool tagcache_import_changelog(void)
3321 struct master_header myhdr
;
3322 struct tagcache_header tch
;
3333 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_RDONLY
);
3336 logf("failure to open changelog");
3340 if ( (masterfd
= open_master_fd(&myhdr
, true)) < 0)
3348 filenametag_fd
= open_tag_fd(&tch
, tag_filename
, false);
3350 fast_readline(clfd
, buf
, sizeof buf
, (long *)masterfd
,
3351 parse_changelog_line
);
3356 if (filenametag_fd
>= 0)
3357 close(filenametag_fd
);
3361 update_master_header();
3367 bool tagcache_create_changelog(struct tagcache_search
*tcs
)
3369 struct master_header myhdr
;
3370 struct index_entry idx
;
3371 char buf
[TAG_MAXLEN
+32];
3379 if (!tagcache_search(tcs
, tag_filename
))
3382 /* Initialize the changelog */
3383 clfd
= open(TAGCACHE_FILE_CHANGELOG
, O_WRONLY
| O_CREAT
| O_TRUNC
);
3386 logf("failure to open changelog");
3390 if (tcs
->masterfd
< 0)
3392 if ( (tcs
->masterfd
= open_master_fd(&myhdr
, false)) < 0)
3397 lseek(tcs
->masterfd
, 0, SEEK_SET
);
3398 ecread(tcs
->masterfd
, &myhdr
, 1, master_header_ec
, tc_stat
.econ
);
3401 write(clfd
, "## Changelog version 1\n", 23);
3403 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3405 if (ecread(tcs
->masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
3406 != sizeof(struct index_entry
))
3408 logf("read error #9");
3409 tagcache_search_finish(tcs
);
3414 /* Skip until the entry found has been modified. */
3415 if (! (idx
.flag
& FLAG_DIRTYNUM
) )
3418 /* Skip deleted entries too. */
3419 if (idx
.flag
& FLAG_DELETED
)
3422 /* Now retrieve all tags. */
3423 for (j
= 0; j
< TAG_COUNT
; j
++)
3425 if (tagcache_is_numeric_tag(j
))
3427 snprintf(temp
, sizeof temp
, "%d", idx
.tag_seek
[j
]);
3428 write_tag(clfd
, tagcache_tag_to_str(j
), temp
);
3433 tagcache_retrieve(tcs
, i
, tcs
->type
, buf
, sizeof buf
);
3434 write_tag(clfd
, tagcache_tag_to_str(j
), buf
);
3437 write(clfd
, "\n", 1);
3443 tagcache_search_finish(tcs
);
3448 static bool delete_entry(long idx_id
)
3453 struct index_entry idx
, myidx
;
3454 struct master_header myhdr
;
3455 char buf
[TAG_MAXLEN
+32];
3456 int in_use
[TAG_COUNT
];
3458 logf("delete_entry(): %ld", idx_id
);
3460 #ifdef HAVE_TC_RAMCACHE
3461 /* At first mark the entry removed from ram cache. */
3462 if (tc_stat
.ramcache
)
3463 hdr
->indices
[idx_id
].flag
|= FLAG_DELETED
;
3466 if ( (masterfd
= open_master_fd(&myhdr
, true) ) < 0)
3469 lseek(masterfd
, idx_id
* sizeof(struct index_entry
), SEEK_CUR
);
3470 if (ecread(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3471 != sizeof(struct index_entry
))
3473 logf("delete_entry(): read error");
3477 if (myidx
.flag
& FLAG_DELETED
)
3479 logf("delete_entry(): already deleted!");
3483 myidx
.flag
|= FLAG_DELETED
;
3484 lseek(masterfd
, -sizeof(struct index_entry
), SEEK_CUR
);
3485 if (ecwrite(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3486 != sizeof(struct index_entry
))
3488 logf("delete_entry(): write_error #1");
3492 /* Now check which tags are no longer in use (if any) */
3493 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3496 lseek(masterfd
, sizeof(struct master_header
), SEEK_SET
);
3497 for (i
= 0; i
< myhdr
.tch
.entry_count
; i
++)
3499 struct index_entry
*idxp
;
3501 #ifdef HAVE_TC_RAMCACHE
3502 /* Use RAM DB if available for greater speed */
3503 if (tc_stat
.ramcache
)
3504 idxp
= &hdr
->indices
[i
];
3508 if (ecread(masterfd
, &idx
, 1, index_entry_ec
, tc_stat
.econ
)
3509 != sizeof(struct index_entry
))
3511 logf("delete_entry(): read error #2");
3517 if (idxp
->flag
& FLAG_DELETED
)
3520 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3522 if (tagcache_is_numeric_tag(tag
))
3525 if (idxp
->tag_seek
[tag
] == myidx
.tag_seek
[tag
])
3530 /* Now delete all tags no longer in use. */
3531 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3533 struct tagcache_header tch
;
3534 int oldseek
= myidx
.tag_seek
[tag
];
3536 if (tagcache_is_numeric_tag(tag
))
3540 * Replace tag seek with a hash value of the field string data.
3541 * That way runtime statistics of moved or altered files can be
3544 #ifdef HAVE_TC_RAMCACHE
3545 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3547 struct tagfile_entry
*tfe
;
3548 int32_t *seek
= &hdr
->indices
[idx_id
].tag_seek
[tag
];
3550 tfe
= (struct tagfile_entry
*)&hdr
->tags
[tag
][*seek
];
3551 *seek
= crc_32(tfe
->tag_data
, strlen(tfe
->tag_data
), 0xffffffff);
3552 myidx
.tag_seek
[tag
] = *seek
;
3557 struct tagfile_entry tfe
;
3559 /* Open the index file, which contains the tag names. */
3560 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3563 /* Skip the header block */
3564 lseek(fd
, myidx
.tag_seek
[tag
], SEEK_SET
);
3565 if (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
3566 != sizeof(struct tagfile_entry
))
3568 logf("delete_entry(): read error #3");
3572 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
3574 logf("delete_entry(): read error #4");
3578 myidx
.tag_seek
[tag
] = crc_32(buf
, strlen(buf
), 0xffffffff);
3583 logf("in use: %d/%d", tag
, in_use
[tag
]);
3592 #ifdef HAVE_TC_RAMCACHE
3593 /* Delete from ram. */
3594 if (tc_stat
.ramcache
&& tag
!= tag_filename
)
3596 struct tagfile_entry
*tagentry
= (struct tagfile_entry
*)&hdr
->tags
[tag
][oldseek
];
3597 tagentry
->tag_data
[0] = '\0';
3601 /* Open the index file, which contains the tag names. */
3604 if ((fd
= open_tag_fd(&tch
, tag
, true)) < 0)
3608 /* Skip the header block */
3609 lseek(fd
, oldseek
+ sizeof(struct tagfile_entry
), SEEK_SET
);
3611 /* Debug, print 10 first characters of the tag
3614 logf("TAG:%s", buf);
3615 lseek(fd, -10, SEEK_CUR);
3618 /* Write first data byte in tag as \0 */
3621 /* Now tag data has been removed */
3626 /* Write index entry back into master index. */
3627 lseek(masterfd
, sizeof(struct master_header
) +
3628 (idx_id
* sizeof(struct index_entry
)), SEEK_SET
);
3629 if (ecwrite(masterfd
, &myidx
, 1, index_entry_ec
, tc_stat
.econ
)
3630 != sizeof(struct index_entry
))
3632 logf("delete_entry(): write_error #2");
3651 * Returns true if there is an event waiting in the queue
3652 * that requires the current operation to be aborted.
3654 static bool check_event_queue(void)
3656 struct queue_event ev
;
3658 queue_wait_w_tmo(&tagcache_queue
, &ev
, 0);
3663 case SYS_USB_CONNECTED
:
3664 /* Put the event back into the queue. */
3665 queue_post(&tagcache_queue
, ev
.id
, ev
.data
);
3673 #ifdef HAVE_TC_RAMCACHE
3674 static bool allocate_tagcache(void)
3676 struct master_header tcmh
;
3679 /* Load the header. */
3680 if ( (fd
= open_master_fd(&tcmh
, false)) < 0)
3689 * Now calculate the required cache size plus
3690 * some extra space for alignment fixes.
3692 tc_stat
.ramcache_allocated
= tcmh
.tch
.datasize
+ 128 + TAGCACHE_RESERVE
+
3693 sizeof(struct ramcache_header
) + TAG_COUNT
*sizeof(void *);
3694 hdr
= buffer_alloc(tc_stat
.ramcache_allocated
+ 128);
3695 memset(hdr
, 0, sizeof(struct ramcache_header
));
3696 memcpy(&hdr
->h
, &tcmh
, sizeof(struct master_header
));
3697 hdr
->indices
= (struct index_entry
*)(hdr
+ 1);
3698 logf("tagcache: %d bytes allocated.", tc_stat
.ramcache_allocated
);
3703 # ifdef HAVE_EEPROM_SETTINGS
3704 static bool tagcache_dumpload(void)
3706 struct statefile_header shdr
;
3711 fd
= open(TAGCACHE_STATEFILE
, O_RDONLY
);
3714 logf("no tagcache statedump");
3718 /* Check the statefile memory placement */
3719 hdr
= buffer_alloc(0);
3720 rc
= read(fd
, &shdr
, sizeof(struct statefile_header
));
3721 if (rc
!= sizeof(struct statefile_header
)
3722 /* || (long)hdr != (long)shdr.hdr */)
3724 logf("incorrect statefile");
3730 offpos
= (long)hdr
- (long)shdr
.hdr
;
3732 /* Lets allocate real memory and load it */
3733 hdr
= buffer_alloc(shdr
.tc_stat
.ramcache_allocated
);
3734 rc
= read(fd
, hdr
, shdr
.tc_stat
.ramcache_allocated
);
3737 if (rc
!= shdr
.tc_stat
.ramcache_allocated
)
3739 logf("read failure!");
3744 memcpy(&tc_stat
, &shdr
.tc_stat
, sizeof(struct tagcache_stat
));
3746 /* Now fix the pointers */
3747 hdr
->indices
= (struct index_entry
*)((long)hdr
->indices
+ offpos
);
3748 for (i
= 0; i
< TAG_COUNT
; i
++)
3749 hdr
->tags
[i
] += offpos
;
3754 static bool tagcache_dumpsave(void)
3756 struct statefile_header shdr
;
3759 if (!tc_stat
.ramcache
)
3762 fd
= open(TAGCACHE_STATEFILE
, O_WRONLY
| O_CREAT
| O_TRUNC
);
3765 logf("failed to create a statedump");
3769 /* Create the header */
3771 memcpy(&shdr
.tc_stat
, &tc_stat
, sizeof(struct tagcache_stat
));
3772 write(fd
, &shdr
, sizeof(struct statefile_header
));
3774 /* And dump the data too */
3775 write(fd
, hdr
, tc_stat
.ramcache_allocated
);
3782 static bool load_tagcache(void)
3784 struct tagcache_header
*tch
;
3785 long bytesleft
= tc_stat
.ramcache_allocated
;
3786 struct index_entry
*idx
;
3791 # ifdef HAVE_DIRCACHE
3792 while (dircache_is_initializing())
3795 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE
);
3798 logf("loading tagcache to ram...");
3800 fd
= open(TAGCACHE_FILE_MASTER
, O_RDONLY
);
3803 logf("tagcache open failed");
3807 if (ecread(fd
, &hdr
->h
, 1, master_header_ec
, tc_stat
.econ
)
3808 != sizeof(struct master_header
)
3809 || hdr
->h
.tch
.magic
!= TAGCACHE_MAGIC
)
3811 logf("incorrect header");
3817 /* Load the master index table. */
3818 for (i
= 0; i
< hdr
->h
.tch
.entry_count
; i
++)
3820 rc
= ecread(fd
, idx
, 1, index_entry_ec
, tc_stat
.econ
);
3821 if (rc
!= sizeof(struct index_entry
))
3823 logf("read error #10");
3828 bytesleft
-= sizeof(struct index_entry
);
3829 if (bytesleft
< 0 || ((long)idx
- (long)hdr
->indices
) >= tc_stat
.ramcache_allocated
)
3831 logf("too big tagcache.");
3841 /* Load the tags. */
3843 for (tag
= 0; tag
< TAG_COUNT
; tag
++)
3845 struct tagfile_entry
*fe
;
3846 char buf
[TAG_MAXLEN
+32];
3848 if (tagcache_is_numeric_tag(tag
))
3851 //p = ((void *)p+1);
3852 p
= (char *)((long)p
& ~0x03) + 0x04;
3855 /* Check the header. */
3856 tch
= (struct tagcache_header
*)p
;
3857 p
+= sizeof(struct tagcache_header
);
3859 if ( (fd
= open_tag_fd(tch
, tag
, false)) < 0)
3862 for (hdr
->entry_count
[tag
] = 0;
3863 hdr
->entry_count
[tag
] < tch
->entry_count
;
3864 hdr
->entry_count
[tag
]++)
3868 if (do_timed_yield())
3870 /* Abort if we got a critical event in queue */
3871 if (check_event_queue())
3875 fe
= (struct tagfile_entry
*)p
;
3876 pos
= lseek(fd
, 0, SEEK_CUR
);
3877 rc
= ecread(fd
, fe
, 1, tagfile_entry_ec
, tc_stat
.econ
);
3878 if (rc
!= sizeof(struct tagfile_entry
))
3880 /* End of lookup table. */
3881 logf("read error #11");
3886 /* We have a special handling for the filename tags. */
3887 if (tag
== tag_filename
)
3889 # ifdef HAVE_DIRCACHE
3890 const struct dirent
*dc
;
3893 // FIXME: This is wrong!
3894 // idx = &hdr->indices[hdr->entry_count[i]];
3895 idx
= &hdr
->indices
[fe
->idx_id
];
3897 if (fe
->tag_length
>= (long)sizeof(buf
)-1)
3901 logf("TAG:%s", buf
);
3902 logf("too long filename");
3907 rc
= read(fd
, buf
, fe
->tag_length
);
3908 if (rc
!= fe
->tag_length
)
3910 logf("read error #12");
3915 /* Check if the entry has already been removed */
3916 if (idx
->flag
& FLAG_DELETED
)
3919 /* This flag must not be used yet. */
3920 if (idx
->flag
& FLAG_DIRCACHE
)
3922 logf("internal error!");
3927 if (idx
->tag_seek
[tag
] != pos
)
3929 logf("corrupt data structures!");
3934 # ifdef HAVE_DIRCACHE
3935 if (dircache_is_enabled())
3937 dc
= dircache_get_entry_ptr(buf
);
3940 logf("Entry no longer valid.");
3942 delete_entry(fe
->idx_id
);
3946 idx
->flag
|= FLAG_DIRCACHE
;
3947 FLAG_SET_ATTR(idx
->flag
, fe
->idx_id
);
3948 idx
->tag_seek
[tag_filename
] = (long)dc
;
3953 /* This will be very slow unless dircache is enabled
3954 or target is flash based, but do it anyway for
3956 /* Check if entry has been removed. */
3957 if (global_settings
.tagcache_autoupdate
)
3959 if (!file_exists(buf
))
3961 logf("Entry no longer valid.");
3963 delete_entry(fe
->idx_id
);
3972 bytesleft
-= sizeof(struct tagfile_entry
) + fe
->tag_length
;
3975 logf("too big tagcache #2");
3976 logf("tl: %d", fe
->tag_length
);
3977 logf("bl: %ld", bytesleft
);
3983 rc
= read(fd
, fe
->tag_data
, fe
->tag_length
);
3986 if (rc
!= fe
->tag_length
)
3988 logf("read error #13");
3989 logf("rc=0x%04x", rc
); // 0x431
3990 logf("len=0x%04x", fe
->tag_length
); // 0x4000
3991 logf("pos=0x%04lx", lseek(fd
, 0, SEEK_CUR
)); // 0x433
3992 logf("tag=0x%02x", tag
); // 0x00
4000 tc_stat
.ramcache_used
= tc_stat
.ramcache_allocated
- bytesleft
;
4001 logf("tagcache loaded into ram!");
4005 #endif /* HAVE_TC_RAMCACHE */
4007 static bool check_deleted_files(void)
4010 char buf
[TAG_MAXLEN
+32];
4011 struct tagfile_entry tfe
;
4013 logf("reverse scan...");
4014 snprintf(buf
, sizeof buf
, TAGCACHE_FILE_INDEX
, tag_filename
);
4015 fd
= open(buf
, O_RDONLY
);
4019 logf("%s open fail", buf
);
4023 lseek(fd
, sizeof(struct tagcache_header
), SEEK_SET
);
4024 while (ecread(fd
, &tfe
, 1, tagfile_entry_ec
, tc_stat
.econ
)
4025 == sizeof(struct tagfile_entry
)
4027 && !check_event_queue()
4031 if (tfe
.tag_length
>= (long)sizeof(buf
)-1)
4033 logf("too long tag");
4038 if (read(fd
, buf
, tfe
.tag_length
) != tfe
.tag_length
)
4040 logf("read error #14");
4045 /* Check if the file has already deleted from the db. */
4049 /* Now check if the file exists. */
4050 if (!file_exists(buf
))
4052 logf("Entry no longer valid.");
4053 logf("-> %s / %d", buf
, tfe
.tag_length
);
4054 delete_entry(tfe
.idx_id
);
4065 static bool check_dir(const char *dirname
, int add_files
)
4069 int success
= false;
4070 int ignore
, unignore
;
4071 char newpath
[MAX_PATH
];
4073 dir
= opendir(dirname
);
4076 logf("tagcache: opendir() failed");
4080 /* check for a database.ignore file */
4081 snprintf(newpath
, MAX_PATH
, "%s/database.ignore", dirname
);
4082 ignore
= file_exists(newpath
);
4083 /* check for a database.unignore file */
4084 snprintf(newpath
, MAX_PATH
, "%s/database.unignore", dirname
);
4085 unignore
= file_exists(newpath
);
4087 /* don't do anything if both ignore and unignore are there */
4088 if (ignore
!= unignore
)
4089 add_files
= unignore
;
4091 /* Recursively scan the dir. */
4095 while (!check_event_queue())
4098 struct dirent
*entry
;
4100 entry
= readdir(dir
);
4108 if (!strcmp((char *)entry
->d_name
, ".") ||
4109 !strcmp((char *)entry
->d_name
, ".."))
4114 len
= strlen(curpath
);
4115 snprintf(&curpath
[len
], curpath_size
- len
, "/%s",
4118 processed_dir_count
++;
4119 if (entry
->attribute
& ATTR_DIRECTORY
)
4120 check_dir(curpath
, add_files
);
4123 tc_stat
.curentry
= curpath
;
4125 /* Add a new entry to the temporary db file. */
4126 add_tagcache(curpath
, (entry
->wrtdate
<< 16) | entry
->wrttime
4127 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4128 , dir
->internal_entry
4132 /* Wait until current path for debug screen is read and unset. */
4133 while (tc_stat
.syncscreen
&& tc_stat
.curentry
!= NULL
)
4136 tc_stat
.curentry
= NULL
;
4139 curpath
[len
] = '\0';
4147 void tagcache_screensync_event(void)
4149 tc_stat
.curentry
= NULL
;
4152 void tagcache_screensync_enable(bool state
)
4154 tc_stat
.syncscreen
= state
;
4157 void tagcache_build(const char *path
)
4159 struct tagcache_header header
;
4164 total_entry_count
= 0;
4165 processed_dir_count
= 0;
4167 #ifdef HAVE_DIRCACHE
4168 while (dircache_is_initializing())
4172 logf("updating tagcache");
4174 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDONLY
);
4177 logf("skipping, cache already waiting for commit");
4182 cachefd
= open(TAGCACHE_FILE_TEMP
, O_RDWR
| O_CREAT
| O_TRUNC
);
4185 logf("master file open failed: %s", TAGCACHE_FILE_TEMP
);
4189 filenametag_fd
= open_tag_fd(&header
, tag_filename
, false);
4193 logf("Scanning files...");
4194 /* Scan for new files. */
4195 memset(&header
, 0, sizeof(struct tagcache_header
));
4196 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4198 if (strcmp("/", path
) != 0)
4199 strcpy(curpath
, path
);
4200 ret
= check_dir(path
, true);
4202 /* Write the header. */
4203 header
.magic
= TAGCACHE_MAGIC
;
4204 header
.datasize
= data_size
;
4205 header
.entry_count
= total_entry_count
;
4206 lseek(cachefd
, 0, SEEK_SET
);
4207 write(cachefd
, &header
, sizeof(struct tagcache_header
));
4210 if (filenametag_fd
>= 0)
4212 close(filenametag_fd
);
4213 filenametag_fd
= -1;
4223 /* Commit changes to the database. */
4229 remove(TAGCACHE_FILE_TEMP
);
4230 logf("tagcache built!");
4236 #ifdef HAVE_TC_RAMCACHE
4239 /* Import runtime statistics if we just initialized the db. */
4240 if (hdr
->h
.serial
== 0)
4241 queue_post(&tagcache_queue
, Q_IMPORT_CHANGELOG
, 0);
4248 #ifdef HAVE_TC_RAMCACHE
4249 static void load_ramcache(void)
4256 /* At first we should load the cache (if exists). */
4257 tc_stat
.ramcache
= load_tagcache();
4259 if (!tc_stat
.ramcache
)
4261 /* If loading failed, it must indicate some problem with the db
4262 * so disable it entirely to prevent further issues. */
4263 tc_stat
.ready
= false;
4270 void tagcache_unload_ramcache(void)
4272 tc_stat
.ramcache
= false;
4273 /* Just to make sure there is no statefile present. */
4274 // remove(TAGCACHE_STATEFILE);
4279 static void tagcache_thread(void)
4281 struct queue_event ev
;
4282 bool check_done
= false;
4284 /* If the previous cache build/update was interrupted, commit
4285 * the changes first in foreground. */
4291 #ifdef HAVE_TC_RAMCACHE
4292 # ifdef HAVE_EEPROM_SETTINGS
4293 if (firmware_settings
.initialized
&& firmware_settings
.disk_clean
)
4294 check_done
= tagcache_dumpload();
4296 remove(TAGCACHE_STATEFILE
);
4299 /* Allocate space for the tagcache if found on disk. */
4300 if (global_settings
.tagcache_ram
&& !tc_stat
.ramcache
)
4301 allocate_tagcache();
4305 tc_stat
.initialized
= true;
4307 /* Don't delay bootup with the header check but do it on background. */
4309 tc_stat
.ready
= check_all_headers();
4310 tc_stat
.readyvalid
= true;
4314 run_command_queue(false);
4316 queue_wait_w_tmo(&tagcache_queue
, &ev
, HZ
);
4320 case Q_IMPORT_CHANGELOG
:
4321 tagcache_import_changelog();
4326 remove(TAGCACHE_FILE_TEMP
);
4327 tagcache_build("/");
4331 tagcache_build("/");
4332 #ifdef HAVE_TC_RAMCACHE
4335 check_deleted_files();
4341 if (check_done
|| !tc_stat
.ready
)
4344 #ifdef HAVE_TC_RAMCACHE
4345 if (!tc_stat
.ramcache
&& global_settings
.tagcache_ram
)
4348 if (tc_stat
.ramcache
&& global_settings
.tagcache_autoupdate
)
4349 tagcache_build("/");
4353 if (global_settings
.tagcache_autoupdate
)
4355 tagcache_build("/");
4357 /* This will be very slow unless dircache is enabled
4358 or target is flash based, but do it anyway for
4360 check_deleted_files();
4363 logf("tagcache check done");
4375 case SYS_USB_CONNECTED
:
4376 logf("USB: TagCache");
4377 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
4378 usb_wait_for_disconnect(&tagcache_queue
);
4385 bool tagcache_prepare_shutdown(void)
4387 if (tagcache_get_commit_step() > 0)
4390 tagcache_stop_scan();
4391 while (read_lock
|| write_lock
)
4397 void tagcache_shutdown(void)
4399 /* Flush the command queue. */
4400 run_command_queue(true);
4402 #ifdef HAVE_EEPROM_SETTINGS
4403 if (tc_stat
.ramcache
)
4404 tagcache_dumpsave();
4408 static int get_progress(void)
4410 int total_count
= -1;
4412 #ifdef HAVE_DIRCACHE
4413 if (dircache_is_enabled())
4415 total_count
= dircache_get_entry_count();
4419 #ifdef HAVE_TC_RAMCACHE
4421 if (hdr
&& tc_stat
.ramcache
)
4422 total_count
= hdr
->h
.tch
.entry_count
;
4426 if (total_count
< 0)
4429 return processed_dir_count
* 100 / total_count
;
4432 struct tagcache_stat
* tagcache_get_stat(void)
4434 tc_stat
.progress
= get_progress();
4435 tc_stat
.processed_entries
= processed_dir_count
;
4440 void tagcache_start_scan(void)
4442 queue_post(&tagcache_queue
, Q_START_SCAN
, 0);
4445 bool tagcache_update(void)
4450 queue_post(&tagcache_queue
, Q_UPDATE
, 0);
4454 bool tagcache_rebuild()
4456 queue_post(&tagcache_queue
, Q_REBUILD
, 0);
4460 void tagcache_stop_scan(void)
4462 queue_post(&tagcache_queue
, Q_STOP_SCAN
, 0);
4465 #ifdef HAVE_TC_RAMCACHE
4466 bool tagcache_is_ramcache(void)
4468 return tc_stat
.ramcache
;
4472 #endif /* !__PCTOOL__ */
4475 void tagcache_init(void)
4477 memset(&tc_stat
, 0, sizeof(struct tagcache_stat
));
4478 memset(¤t_tcmh
, 0, sizeof(struct master_header
));
4479 filenametag_fd
= -1;
4480 write_lock
= read_lock
= 0;
4483 mutex_init(&command_queue_mutex
);
4484 queue_init(&tagcache_queue
, true);
4485 create_thread(tagcache_thread
, tagcache_stack
,
4486 sizeof(tagcache_stack
), 0, tagcache_thread_name
4487 IF_PRIO(, PRIORITY_BACKGROUND
)
4490 tc_stat
.initialized
= true;
4494 tc_stat
.ready
= check_all_headers();
4499 void tagcache_reverse_scan(void)
4501 logf("Checking for deleted files");
4502 check_deleted_files();
4506 bool tagcache_is_initialized(void)
4508 return tc_stat
.initialized
;
4510 bool tagcache_is_usable(void)
4512 return tc_stat
.initialized
&& tc_stat
.ready
;
4514 int tagcache_get_commit_step(void)
4516 return tc_stat
.commit_step
;
4518 int tagcache_get_max_commit_step(void)
4520 return (int)(sizeof(sorted_tags
)/sizeof(sorted_tags
[0]))+1;