Few more fixes, notably make audiobufend static.
[kugel-rb.git] / apps / tagcache.c
blob34f38ad9b6066ce495f2d241bc081f44a99fb13a
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
23 * TagCache API
25 * ----------x---------x------------------x-----
26 * | | | External
27 * +---------------x-------+ | TagCache | Libraries
28 * | Modification routines | | Core |
29 * +-x---------x-----------+ | |
30 * | (R/W) | | | |
31 * | +------x-------------x-+ +-------------x-----+ |
32 * | | x==x Filters & clauses | |
33 * | | Search routines | +-------------------+ |
34 * | | x============================x DirCache
35 * | +-x--------------------+ | (optional)
36 * | | (R) |
37 * | | +-------------------------------+ +---------+ |
38 * | | | DB Commit (sort,unique,index) | | | |
39 * | | +-x--------------------------x--+ | Control | |
40 * | | | (R/W) | (R) | Thread | |
41 * | | | +----------------------+ | | | |
42 * | | | | TagCache DB Builder | | +---------+ |
43 * | | | +-x-------------x------+ | |
44 * | | | | (R) | (W) | |
45 * | | | | +--x--------x---------+ |
46 * | | | | | Temporary Commit DB | |
47 * | | | | +---------------------+ |
48 * +-x----x-------x--+ |
49 * | TagCache RAM DB x==\(W) +-----------------+ |
50 * +-----------------+ \===x | |
51 * | | | | (R) | Ram DB Loader x============x DirCache
52 * +-x----x---x---x---+ /==x | | (optional)
53 * | Tagcache Disk DB x==/ +-----------------+ |
54 * +------------------+ |
58 /*#define LOGF_ENABLE*/
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <ctype.h>
63 #ifdef APPLICATION
64 #include <unistd.h> /* readlink() */
65 #include <limits.h> /* PATH_MAX */
66 #endif
67 #include "config.h"
68 #include "ata_idle_notify.h"
69 #include "thread.h"
70 #include "kernel.h"
71 #include "system.h"
72 #include "logf.h"
73 #include "string-extra.h"
74 #include "usb.h"
75 #include "metadata.h"
76 #include "tagcache.h"
77 #include "buffer.h"
78 #include "crc32.h"
79 #include "misc.h"
80 #include "settings.h"
81 #include "dir.h"
82 #include "filefuncs.h"
83 #include "structec.h"
84 #include "debug.h"
86 #ifndef __PCTOOL__
87 #include "lang.h"
88 #include "eeprom_settings.h"
89 #endif
91 #ifdef __PCTOOL__
92 #define yield() do { } while(0)
93 #define sim_sleep(timeout) do { } while(0)
94 #define do_timed_yield() do { } while(0)
95 #endif
97 #ifndef __PCTOOL__
98 /* Tag Cache thread. */
99 static struct event_queue tagcache_queue SHAREDBSS_ATTR;
100 static long tagcache_stack[(DEFAULT_STACK_SIZE + 0x4000)/sizeof(long)];
101 static const char tagcache_thread_name[] = "tagcache";
102 #endif
104 /* Previous path when scanning directory tree recursively. */
105 static char curpath[TAG_MAXLEN+32];
107 /* Used when removing duplicates. */
108 static char *tempbuf; /* Allocated when needed. */
109 static long tempbufidx; /* Current location in buffer. */
110 static size_t tempbuf_size; /* Buffer size (TEMPBUF_SIZE). */
111 static long tempbuf_left; /* Buffer space left. */
112 static long tempbuf_pos;
114 #define SORTED_TAGS_COUNT 8
115 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
116 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
117 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
118 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
119 /* Tags we want to get sorted (loaded to the tempbuf). */
120 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
121 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
122 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
124 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
125 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
126 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
127 (1LU << tag_albumartist) | (1LU << tag_grouping))
129 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
130 static const char *tags_str[] = { "artist", "album", "genre", "title",
131 "filename", "composer", "comment", "albumartist", "grouping", "year",
132 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
133 "playtime", "lastplayed", "commitid", "mtime", "lastoffset" };
135 /* Status information of the tagcache. */
136 static struct tagcache_stat tc_stat;
138 /* Queue commands. */
139 enum tagcache_queue {
140 Q_STOP_SCAN = 0,
141 Q_START_SCAN,
142 Q_IMPORT_CHANGELOG,
143 Q_UPDATE,
144 Q_REBUILD,
146 /* Internal tagcache command queue. */
147 CMD_UPDATE_MASTER_HEADER,
148 CMD_UPDATE_NUMERIC,
151 struct tagcache_command_entry {
152 int32_t command;
153 int32_t idx_id;
154 int32_t tag;
155 int32_t data;
158 #ifndef __PCTOOL__
159 static struct tagcache_command_entry command_queue[TAGCACHE_COMMAND_QUEUE_LENGTH];
160 static volatile int command_queue_widx = 0;
161 static volatile int command_queue_ridx = 0;
162 static struct mutex command_queue_mutex SHAREDBSS_ATTR;
163 #endif
165 /* Tag database structures. */
167 /* Variable-length tag entry in tag files. */
168 struct tagfile_entry {
169 int32_t tag_length; /* Length of the data in bytes including '\0' */
170 int32_t idx_id; /* Corresponding entry location in index file of not unique tags */
171 char tag_data[0]; /* Begin of the tag data */
174 /* Fixed-size tag entry in master db index. */
175 struct index_entry {
176 int32_t tag_seek[TAG_COUNT]; /* Location of tag data or numeric tag data */
177 int32_t flag; /* Status flags */
180 /* Header is the same in every file. */
181 struct tagcache_header {
182 int32_t magic; /* Header version number */
183 int32_t datasize; /* Data size in bytes */
184 int32_t entry_count; /* Number of entries in this file */
187 struct master_header {
188 struct tagcache_header tch;
189 int32_t serial; /* Increasing counting number */
190 int32_t commitid; /* Number of commits so far */
191 int32_t dirty;
194 /* For the endianess correction */
195 static const char *tagfile_entry_ec = "ll";
197 Note: This should be (1 + TAG_COUNT) amount of l's.
199 static const char *index_entry_ec = "llllllllllllllllllllll";
201 static const char *tagcache_header_ec = "lll";
202 static const char *master_header_ec = "llllll";
204 static struct master_header current_tcmh;
206 #ifdef HAVE_TC_RAMCACHE
207 /* Header is created when loading database to ram. */
208 struct ramcache_header {
209 struct master_header h; /* Header from the master index */
210 struct index_entry *indices; /* Master index file content */
211 char *tags[TAG_COUNT]; /* Tag file content (not including filename tag) */
212 int entry_count[TAG_COUNT]; /* Number of entries in the indices. */
215 # ifdef HAVE_EEPROM_SETTINGS
216 struct statefile_header {
217 struct ramcache_header *hdr;
218 struct tagcache_stat tc_stat;
220 # endif
222 /* Pointer to allocated ramcache_header */
223 static struct ramcache_header *hdr;
224 #endif
226 /**
227 * Full tag entries stored in a temporary file waiting
228 * for commit to the cache. */
229 struct temp_file_entry {
230 long tag_offset[TAG_COUNT];
231 short tag_length[TAG_COUNT];
232 long flag;
234 long data_length;
237 struct tempbuf_id_list {
238 long id;
239 struct tempbuf_id_list *next;
242 struct tempbuf_searchidx {
243 long idx_id;
244 char *str;
245 int seek;
246 struct tempbuf_id_list idlist;
249 /* Lookup buffer for fixing messed up index while after sorting. */
250 static long commit_entry_count;
251 static long lookup_buffer_depth;
252 static struct tempbuf_searchidx **lookup;
254 /* Used when building the temporary file. */
255 static int cachefd = -1, filenametag_fd;
256 static int total_entry_count = 0;
257 static int data_size = 0;
258 static int processed_dir_count;
260 /* Thread safe locking */
261 static volatile int write_lock;
262 static volatile int read_lock;
264 static bool delete_entry(long idx_id);
266 const char* tagcache_tag_to_str(int tag)
268 return tags_str[tag];
271 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
272 static ssize_t ecread_tagfile_entry(int fd, struct tagfile_entry *buf)
274 return ecread(fd, buf, 1, tagfile_entry_ec, tc_stat.econ);
277 static ssize_t ecread_index_entry(int fd, struct index_entry *buf)
279 return ecread(fd, buf, 1, index_entry_ec, tc_stat.econ);
282 static ssize_t ecwrite_index_entry(int fd, struct index_entry *buf)
284 return ecwrite(fd, buf, 1, index_entry_ec, tc_stat.econ);
287 #ifdef HAVE_DIRCACHE
289 * Returns true if specified flag is still present, i.e., dircache
290 * has not been reloaded.
292 static bool is_dircache_intact(void)
294 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE);
296 #endif
298 static int open_tag_fd(struct tagcache_header *hdr, int tag, bool write)
300 int fd;
301 char buf[MAX_PATH];
302 int rc;
304 if (TAGCACHE_IS_NUMERIC(tag) || tag < 0 || tag >= TAG_COUNT)
305 return -1;
307 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag);
309 fd = open(buf, write ? O_RDWR : O_RDONLY);
310 if (fd < 0)
312 logf("tag file open failed: tag=%d write=%d file=%s", tag, write, buf);
313 tc_stat.ready = false;
314 return fd;
317 /* Check the header. */
318 rc = ecread(fd, hdr, 1, tagcache_header_ec, tc_stat.econ);
319 if (hdr->magic != TAGCACHE_MAGIC || rc != sizeof(struct tagcache_header))
321 logf("header error");
322 tc_stat.ready = false;
323 close(fd);
324 return -2;
327 return fd;
330 static int open_master_fd(struct master_header *hdr, bool write)
332 int fd;
333 int rc;
335 fd = open(TAGCACHE_FILE_MASTER, write ? O_RDWR : O_RDONLY);
336 if (fd < 0)
338 logf("master file open failed for R/W");
339 tc_stat.ready = false;
340 return fd;
343 tc_stat.econ = false;
345 /* Check the header. */
346 rc = read(fd, hdr, sizeof(struct master_header));
347 if (hdr->tch.magic == TAGCACHE_MAGIC && rc == sizeof(struct master_header))
349 /* Success. */
350 return fd;
353 /* Trying to read again, this time with endianess correction enabled. */
354 lseek(fd, 0, SEEK_SET);
356 rc = ecread(fd, hdr, 1, master_header_ec, true);
357 if (hdr->tch.magic != TAGCACHE_MAGIC || rc != sizeof(struct master_header))
359 logf("header error");
360 tc_stat.ready = false;
361 close(fd);
362 return -2;
365 tc_stat.econ = true;
367 return fd;
370 #ifndef __PCTOOL__
371 static bool do_timed_yield(void)
373 /* Sorting can lock up for quite a while, so yield occasionally */
374 static long wakeup_tick = 0;
375 if (TIME_AFTER(current_tick, wakeup_tick))
377 wakeup_tick = current_tick + (HZ/4);
378 yield();
379 return true;
381 return false;
383 #endif
385 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
386 static long find_entry_ram(const char *filename,
387 const struct dircache_entry *dc)
389 static long last_pos = 0;
390 int i;
392 /* Check if tagcache is loaded into ram. */
393 if (!tc_stat.ramcache)
394 return -1;
396 if (dc == NULL)
397 dc = dircache_get_entry_ptr(filename);
399 if (dc == NULL)
401 logf("tagcache: file not found.");
402 return -1;
405 try_again:
407 if (last_pos > 0)
408 i = last_pos;
409 else
410 i = 0;
412 for (; i < hdr->h.tch.entry_count; i++)
414 if (hdr->indices[i].tag_seek[tag_filename] == (long)dc)
416 last_pos = MAX(0, i - 3);
417 return i;
420 do_timed_yield();
423 if (last_pos > 0)
425 last_pos = 0;
426 goto try_again;
429 return -1;
431 #endif
433 static long find_entry_disk(const char *filename_raw, bool localfd)
435 struct tagcache_header tch;
436 static long last_pos = -1;
437 long pos_history[POS_HISTORY_COUNT];
438 long pos_history_idx = 0;
439 bool found = false;
440 struct tagfile_entry tfe;
441 int fd;
442 char buf[TAG_MAXLEN+32];
443 int i;
444 int pos = -1;
446 const char *filename = filename_raw;
447 #ifdef APPLICATION
448 char pathbuf[PATH_MAX]; /* Note: Don't use MAX_PATH here, it's too small */
449 if (realpath(filename, pathbuf) == pathbuf)
450 filename = pathbuf;
451 #endif
453 if (!tc_stat.ready)
454 return -2;
456 fd = filenametag_fd;
457 if (fd < 0 || localfd)
459 last_pos = -1;
460 if ( (fd = open_tag_fd(&tch, tag_filename, false)) < 0)
461 return -1;
464 check_again:
466 if (last_pos > 0)
467 lseek(fd, last_pos, SEEK_SET);
468 else
469 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
471 while (true)
473 pos = lseek(fd, 0, SEEK_CUR);
474 for (i = pos_history_idx-1; i >= 0; i--)
475 pos_history[i+1] = pos_history[i];
476 pos_history[0] = pos;
478 if (ecread_tagfile_entry(fd, &tfe)
479 != sizeof(struct tagfile_entry))
481 break ;
484 if (tfe.tag_length >= (long)sizeof(buf))
486 logf("too long tag #1");
487 close(fd);
488 if (!localfd)
489 filenametag_fd = -1;
490 last_pos = -1;
491 return -2;
494 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
496 logf("read error #2");
497 close(fd);
498 if (!localfd)
499 filenametag_fd = -1;
500 last_pos = -1;
501 return -3;
504 if (!strcasecmp(filename, buf))
506 last_pos = pos_history[pos_history_idx];
507 found = true;
508 break ;
511 if (pos_history_idx < POS_HISTORY_COUNT - 1)
512 pos_history_idx++;
515 /* Not found? */
516 if (!found)
518 if (last_pos > 0)
520 last_pos = -1;
521 logf("seek again");
522 goto check_again;
525 if (fd != filenametag_fd || localfd)
526 close(fd);
527 return -4;
530 if (fd != filenametag_fd || localfd)
531 close(fd);
533 return tfe.idx_id;
536 static int find_index(const char *filename)
538 long idx_id = -1;
540 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
541 if (tc_stat.ramcache && is_dircache_intact())
542 idx_id = find_entry_ram(filename, NULL);
543 #endif
545 if (idx_id < 0)
546 idx_id = find_entry_disk(filename, true);
548 return idx_id;
551 bool tagcache_find_index(struct tagcache_search *tcs, const char *filename)
553 int idx_id;
555 if (!tc_stat.ready)
556 return false;
558 idx_id = find_index(filename);
559 if (idx_id < 0)
560 return false;
562 if (!tagcache_search(tcs, tag_filename))
563 return false;
565 tcs->entry_count = 0;
566 tcs->idx_id = idx_id;
568 return true;
571 static bool get_index(int masterfd, int idxid,
572 struct index_entry *idx, bool use_ram)
574 bool localfd = false;
576 if (idxid < 0)
578 logf("Incorrect idxid: %d", idxid);
579 return false;
582 #ifdef HAVE_TC_RAMCACHE
583 if (tc_stat.ramcache && use_ram)
585 if (hdr->indices[idxid].flag & FLAG_DELETED)
586 return false;
588 # ifdef HAVE_DIRCACHE
589 if (!(hdr->indices[idxid].flag & FLAG_DIRCACHE)
590 || is_dircache_intact())
591 #endif
593 memcpy(idx, &hdr->indices[idxid], sizeof(struct index_entry));
594 return true;
597 #else
598 (void)use_ram;
599 #endif
601 if (masterfd < 0)
603 struct master_header tcmh;
605 localfd = true;
606 masterfd = open_master_fd(&tcmh, false);
607 if (masterfd < 0)
608 return false;
611 lseek(masterfd, idxid * sizeof(struct index_entry)
612 + sizeof(struct master_header), SEEK_SET);
613 if (ecread_index_entry(masterfd, idx)
614 != sizeof(struct index_entry))
616 logf("read error #3");
617 if (localfd)
618 close(masterfd);
620 return false;
623 if (localfd)
624 close(masterfd);
626 if (idx->flag & FLAG_DELETED)
627 return false;
629 return true;
632 #ifndef __PCTOOL__
634 static bool write_index(int masterfd, int idxid, struct index_entry *idx)
636 /* We need to exclude all memory only flags & tags when writing to disk. */
637 if (idx->flag & FLAG_DIRCACHE)
639 logf("memory only flags!");
640 return false;
643 #ifdef HAVE_TC_RAMCACHE
644 /* Only update numeric data. Writing the whole index to RAM by memcpy
645 * destroys dircache pointers!
647 if (tc_stat.ramcache)
649 int tag;
650 struct index_entry *idx_ram = &hdr->indices[idxid];
652 for (tag = 0; tag < TAG_COUNT; tag++)
654 if (TAGCACHE_IS_NUMERIC(tag))
656 idx_ram->tag_seek[tag] = idx->tag_seek[tag];
660 /* Don't touch the dircache flag or attributes. */
661 idx_ram->flag = (idx->flag & 0x0000ffff)
662 | (idx_ram->flag & (0xffff0000 | FLAG_DIRCACHE));
664 #endif
666 lseek(masterfd, idxid * sizeof(struct index_entry)
667 + sizeof(struct master_header), SEEK_SET);
668 if (ecwrite_index_entry(masterfd, idx) != sizeof(struct index_entry))
670 logf("write error #3");
671 logf("idxid: %d", idxid);
672 return false;
675 return true;
678 #endif /* !__PCTOOL__ */
680 static bool open_files(struct tagcache_search *tcs, int tag)
682 if (tcs->idxfd[tag] < 0)
684 char fn[MAX_PATH];
686 snprintf(fn, sizeof fn, TAGCACHE_FILE_INDEX, tag);
687 tcs->idxfd[tag] = open(fn, O_RDONLY);
690 if (tcs->idxfd[tag] < 0)
692 logf("File not open!");
693 return false;
696 return true;
699 static bool retrieve(struct tagcache_search *tcs, struct index_entry *idx,
700 int tag, char *buf, long size)
702 struct tagfile_entry tfe;
703 long seek;
705 *buf = '\0';
707 if (TAGCACHE_IS_NUMERIC(tag))
708 return false;
710 seek = idx->tag_seek[tag];
711 if (seek < 0)
713 logf("Retrieve failed");
714 return false;
717 #ifdef HAVE_TC_RAMCACHE
718 if (tcs->ramsearch)
720 struct tagfile_entry *ep;
722 # ifdef HAVE_DIRCACHE
723 if (tag == tag_filename && (idx->flag & FLAG_DIRCACHE)
724 && is_dircache_intact())
726 dircache_copy_path((struct dircache_entry *)seek,
727 buf, size);
728 return true;
730 else
731 # endif
732 if (tag != tag_filename)
734 ep = (struct tagfile_entry *)&hdr->tags[tag][seek];
735 strlcpy(buf, ep->tag_data, size);
737 return true;
740 #endif
742 if (!open_files(tcs, tag))
743 return false;
745 lseek(tcs->idxfd[tag], seek, SEEK_SET);
746 if (ecread_tagfile_entry(tcs->idxfd[tag], &tfe)
747 != sizeof(struct tagfile_entry))
749 logf("read error #5");
750 return false;
753 if (tfe.tag_length >= size)
755 logf("too small buffer");
756 return false;
759 if (read(tcs->idxfd[tag], buf, tfe.tag_length) !=
760 tfe.tag_length)
762 logf("read error #6");
763 return false;
766 buf[tfe.tag_length] = '\0';
768 return true;
771 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
773 static long read_numeric_tag(int tag, int idx_id, const struct index_entry *idx)
775 #ifndef __PCTOOL__
776 if (! COMMAND_QUEUE_IS_EMPTY)
778 /* Attempt to find tag data through store-to-load forwarding in
779 command queue */
780 long result = -1;
782 mutex_lock(&command_queue_mutex);
784 int ridx = command_queue_widx;
786 while (ridx != command_queue_ridx)
788 if (--ridx < 0)
789 ridx = TAGCACHE_COMMAND_QUEUE_LENGTH - 1;
791 if (command_queue[ridx].command == CMD_UPDATE_NUMERIC
792 && command_queue[ridx].idx_id == idx_id
793 && command_queue[ridx].tag == tag)
795 result = command_queue[ridx].data;
796 break;
800 mutex_unlock(&command_queue_mutex);
802 if (result >= 0)
804 logf("read_numeric_tag: "
805 "Recovered tag %d value %lX from write queue",
806 tag, result);
807 return result;
810 #endif
812 return idx->tag_seek[tag];
816 static long check_virtual_tags(int tag, int idx_id,
817 const struct index_entry *idx)
819 long data = 0;
821 switch (tag)
823 case tag_virt_length_sec:
824 data = (read_numeric_tag(tag_length, idx_id, idx)/1000) % 60;
825 break;
827 case tag_virt_length_min:
828 data = (read_numeric_tag(tag_length, idx_id, idx)/1000) / 60;
829 break;
831 case tag_virt_playtime_sec:
832 data = (read_numeric_tag(tag_playtime, idx_id, idx)/1000) % 60;
833 break;
835 case tag_virt_playtime_min:
836 data = (read_numeric_tag(tag_playtime, idx_id, idx)/1000) / 60;
837 break;
839 case tag_virt_autoscore:
840 if (read_numeric_tag(tag_length, idx_id, idx) == 0
841 || read_numeric_tag(tag_playcount, idx_id, idx) == 0)
843 data = 0;
845 else
847 /* A straight calculus gives:
848 autoscore = 100 * playtime / length / playcout (1)
849 Now, consider the euclidian division of playtime by length:
850 playtime = alpha * length + beta
851 With:
852 0 <= beta < length
853 Now, (1) becomes:
854 autoscore = 100 * (alpha / playcout + beta / length / playcount)
855 Both terms should be small enough to avoid any overflow
857 data = 100 * (read_numeric_tag(tag_playtime, idx_id, idx)
858 / read_numeric_tag(tag_length, idx_id, idx))
859 + (100 * (read_numeric_tag(tag_playtime, idx_id, idx)
860 % read_numeric_tag(tag_length, idx_id, idx)))
861 / read_numeric_tag(tag_length, idx_id, idx);
862 data /= read_numeric_tag(tag_playcount, idx_id, idx);
864 break;
866 /* How many commits before the file has been added to the DB. */
867 case tag_virt_entryage:
868 data = current_tcmh.commitid
869 - read_numeric_tag(tag_commitid, idx_id, idx) - 1;
870 break;
872 default:
873 data = read_numeric_tag(tag, idx_id, idx);
876 return data;
879 long tagcache_get_numeric(const struct tagcache_search *tcs, int tag)
881 struct index_entry idx;
883 if (!tc_stat.ready)
884 return false;
886 if (!TAGCACHE_IS_NUMERIC(tag))
887 return -1;
889 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
890 return -2;
892 return check_virtual_tags(tag, tcs->idx_id, &idx);
895 inline static bool str_ends_with(const char *str1, const char *str2)
897 int str_len = strlen(str1);
898 int clause_len = strlen(str2);
900 if (clause_len > str_len)
901 return false;
903 return !strcasecmp(&str1[str_len - clause_len], str2);
906 inline static bool str_oneof(const char *str, const char *list)
908 const char *sep;
909 int l, len = strlen(str);
911 while (*list)
913 sep = strchr(list, '|');
914 l = sep ? (long)sep - (long)list : (int)strlen(list);
915 if ((l==len) && !strncasecmp(str, list, len))
916 return true;
917 list += sep ? l + 1 : l;
920 return false;
923 static bool check_against_clause(long numeric, const char *str,
924 const struct tagcache_search_clause *clause)
926 if (clause->numeric)
928 switch (clause->type)
930 case clause_is:
931 return numeric == clause->numeric_data;
932 case clause_is_not:
933 return numeric != clause->numeric_data;
934 case clause_gt:
935 return numeric > clause->numeric_data;
936 case clause_gteq:
937 return numeric >= clause->numeric_data;
938 case clause_lt:
939 return numeric < clause->numeric_data;
940 case clause_lteq:
941 return numeric <= clause->numeric_data;
942 default:
943 logf("Incorrect numeric tag: %d", clause->type);
946 else
948 switch (clause->type)
950 case clause_is:
951 return !strcasecmp(clause->str, str);
952 case clause_is_not:
953 return strcasecmp(clause->str, str);
954 case clause_gt:
955 return 0>strcasecmp(clause->str, str);
956 case clause_gteq:
957 return 0>=strcasecmp(clause->str, str);
958 case clause_lt:
959 return 0<strcasecmp(clause->str, str);
960 case clause_lteq:
961 return 0<=strcasecmp(clause->str, str);
962 case clause_contains:
963 return (strcasestr(str, clause->str) != NULL);
964 case clause_not_contains:
965 return (strcasestr(str, clause->str) == NULL);
966 case clause_begins_with:
967 return (strcasestr(str, clause->str) == str);
968 case clause_not_begins_with:
969 return (strcasestr(str, clause->str) != str);
970 case clause_ends_with:
971 return str_ends_with(str, clause->str);
972 case clause_not_ends_with:
973 return !str_ends_with(str, clause->str);
974 case clause_oneof:
975 return str_oneof(str, clause->str);
977 default:
978 logf("Incorrect tag: %d", clause->type);
982 return false;
985 static bool check_clauses(struct tagcache_search *tcs,
986 struct index_entry *idx,
987 struct tagcache_search_clause **clauses, int count)
989 int i;
991 /* Go through all conditional clauses. */
992 for (i = 0; i < count; i++)
994 int seek;
995 char buf[256];
996 char *str;
997 struct tagcache_search_clause *clause = clauses[i];
999 if (clause->type == clause_logical_or)
1000 break; /* all conditions before logical-or satisfied --
1001 stop processing clauses */
1003 #ifdef HAVE_TC_RAMCACHE
1004 str = NULL;
1006 if (tcs->ramsearch)
1008 struct tagfile_entry *tfe;
1010 seek = check_virtual_tags(clause->tag, tcs->idx_id, idx);
1012 if (!TAGCACHE_IS_NUMERIC(clause->tag))
1014 if (clause->tag == tag_filename)
1016 retrieve(tcs, idx, tag_filename, buf, sizeof buf);
1017 str = buf;
1019 else
1021 tfe = (struct tagfile_entry *)&hdr->tags[clause->tag][seek];
1022 str = tfe->tag_data;
1026 else
1027 #endif
1029 struct tagfile_entry tfe;
1030 str = buf;
1032 seek = check_virtual_tags(clause->tag, tcs->idx_id, idx);
1034 memset(buf, 0, sizeof buf);
1035 if (!TAGCACHE_IS_NUMERIC(clause->tag))
1037 int fd = tcs->idxfd[clause->tag];
1038 lseek(fd, seek, SEEK_SET);
1039 ecread_tagfile_entry(fd, &tfe);
1040 if (tfe.tag_length >= (int)sizeof(buf))
1042 logf("Too long tag read!");
1043 return false;
1046 read(fd, str, tfe.tag_length);
1048 /* Check if entry has been deleted. */
1049 if (str[0] == '\0')
1050 return false;
1054 if (!check_against_clause(seek, str, clause))
1056 /* Clause failed -- try finding a logical-or clause */
1057 while (++i < count)
1059 if (clauses[i]->type == clause_logical_or)
1060 break;
1063 if (i < count) /* Found logical-or? */
1064 continue; /* Check clauses after logical-or */
1066 return false;
1070 return true;
1073 bool tagcache_check_clauses(struct tagcache_search *tcs,
1074 struct tagcache_search_clause **clause, int count)
1076 struct index_entry idx;
1078 if (count == 0)
1079 return true;
1081 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
1082 return false;
1084 return check_clauses(tcs, &idx, clause, count);
1087 static bool add_uniqbuf(struct tagcache_search *tcs, unsigned long id)
1089 int i;
1091 /* If uniq buffer is not defined we must return true for search to work. */
1092 if (tcs->unique_list == NULL || (!TAGCACHE_IS_UNIQUE(tcs->type)
1093 && !TAGCACHE_IS_NUMERIC(tcs->type)))
1095 return true;
1098 for (i = 0; i < tcs->unique_list_count; i++)
1100 /* Return false if entry is found. */
1101 if (tcs->unique_list[i] == id)
1102 return false;
1105 if (tcs->unique_list_count < tcs->unique_list_capacity)
1107 tcs->unique_list[i] = id;
1108 tcs->unique_list_count++;
1111 return true;
1114 static bool build_lookup_list(struct tagcache_search *tcs)
1116 struct index_entry entry;
1117 int i, j;
1119 tcs->seek_list_count = 0;
1121 #ifdef HAVE_TC_RAMCACHE
1122 if (tcs->ramsearch
1123 # ifdef HAVE_DIRCACHE
1124 && (tcs->type != tag_filename || is_dircache_intact())
1125 # endif
1128 for (i = tcs->seek_pos; i < hdr->h.tch.entry_count; i++)
1130 struct tagcache_seeklist_entry *seeklist;
1131 struct index_entry *idx = &hdr->indices[i];
1132 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1133 break ;
1135 /* Skip deleted files. */
1136 if (idx->flag & FLAG_DELETED)
1137 continue;
1139 /* Go through all filters.. */
1140 for (j = 0; j < tcs->filter_count; j++)
1142 if (idx->tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1144 break ;
1148 if (j < tcs->filter_count)
1149 continue ;
1151 /* Check for conditions. */
1152 if (!check_clauses(tcs, idx, tcs->clause, tcs->clause_count))
1153 continue;
1155 /* Add to the seek list if not already in uniq buffer. */
1156 if (!add_uniqbuf(tcs, idx->tag_seek[tcs->type]))
1157 continue;
1159 /* Lets add it. */
1160 seeklist = &tcs->seeklist[tcs->seek_list_count];
1161 seeklist->seek = idx->tag_seek[tcs->type];
1162 seeklist->flag = idx->flag;
1163 seeklist->idx_id = i;
1164 tcs->seek_list_count++;
1167 tcs->seek_pos = i;
1169 return tcs->seek_list_count > 0;
1171 #endif
1173 if (tcs->masterfd < 0)
1175 struct master_header tcmh;
1176 tcs->masterfd = open_master_fd(&tcmh, false);
1179 lseek(tcs->masterfd, tcs->seek_pos * sizeof(struct index_entry) +
1180 sizeof(struct master_header), SEEK_SET);
1182 while (ecread_index_entry(tcs->masterfd, &entry)
1183 == sizeof(struct index_entry))
1185 struct tagcache_seeklist_entry *seeklist;
1187 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1188 break ;
1190 i = tcs->seek_pos;
1191 tcs->seek_pos++;
1193 /* Check if entry has been deleted. */
1194 if (entry.flag & FLAG_DELETED)
1195 continue;
1197 /* Go through all filters.. */
1198 for (j = 0; j < tcs->filter_count; j++)
1200 if (entry.tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1201 break ;
1204 if (j < tcs->filter_count)
1205 continue ;
1207 /* Check for conditions. */
1208 if (!check_clauses(tcs, &entry, tcs->clause, tcs->clause_count))
1209 continue;
1211 /* Add to the seek list if not already in uniq buffer. */
1212 if (!add_uniqbuf(tcs, entry.tag_seek[tcs->type]))
1213 continue;
1215 /* Lets add it. */
1216 seeklist = &tcs->seeklist[tcs->seek_list_count];
1217 seeklist->seek = entry.tag_seek[tcs->type];
1218 seeklist->flag = entry.flag;
1219 seeklist->idx_id = i;
1220 tcs->seek_list_count++;
1222 yield();
1225 return tcs->seek_list_count > 0;
1229 static void remove_files(void)
1231 int i;
1232 char buf[MAX_PATH];
1234 tc_stat.ready = false;
1235 tc_stat.ramcache = false;
1236 tc_stat.econ = false;
1237 remove(TAGCACHE_FILE_MASTER);
1238 for (i = 0; i < TAG_COUNT; i++)
1240 if (TAGCACHE_IS_NUMERIC(i))
1241 continue;
1243 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, i);
1244 remove(buf);
1249 static bool check_all_headers(void)
1251 struct master_header myhdr;
1252 struct tagcache_header tch;
1253 int tag;
1254 int fd;
1256 if ( (fd = open_master_fd(&myhdr, false)) < 0)
1257 return false;
1259 close(fd);
1260 if (myhdr.dirty)
1262 logf("tagcache is dirty!");
1263 return false;
1266 memcpy(&current_tcmh, &myhdr, sizeof(struct master_header));
1268 for (tag = 0; tag < TAG_COUNT; tag++)
1270 if (TAGCACHE_IS_NUMERIC(tag))
1271 continue;
1273 if ( (fd = open_tag_fd(&tch, tag, false)) < 0)
1274 return false;
1276 close(fd);
1279 return true;
1282 bool tagcache_is_busy(void)
1284 return read_lock || write_lock;
1287 bool tagcache_search(struct tagcache_search *tcs, int tag)
1289 struct tagcache_header tag_hdr;
1290 struct master_header master_hdr;
1291 int i;
1293 while (read_lock)
1294 sleep(1);
1296 memset(tcs, 0, sizeof(struct tagcache_search));
1297 if (tc_stat.commit_step > 0 || !tc_stat.ready)
1298 return false;
1300 tcs->position = sizeof(struct tagcache_header);
1301 tcs->type = tag;
1302 tcs->seek_pos = 0;
1303 tcs->list_position = 0;
1304 tcs->seek_list_count = 0;
1305 tcs->filter_count = 0;
1306 tcs->masterfd = -1;
1308 for (i = 0; i < TAG_COUNT; i++)
1309 tcs->idxfd[i] = -1;
1311 #ifndef HAVE_TC_RAMCACHE
1312 tcs->ramsearch = false;
1313 #else
1314 tcs->ramsearch = tc_stat.ramcache;
1315 if (tcs->ramsearch)
1317 tcs->entry_count = hdr->entry_count[tcs->type];
1319 else
1320 #endif
1322 /* Always open as R/W so we can pass tcs to functions that modify data also
1323 * without failing. */
1324 tcs->masterfd = open_master_fd(&master_hdr, true);
1325 if (tcs->masterfd < 0)
1326 return false;
1328 if (!TAGCACHE_IS_NUMERIC(tcs->type))
1330 tcs->idxfd[tcs->type] = open_tag_fd(&tag_hdr, tcs->type, false);
1331 if (tcs->idxfd[tcs->type] < 0)
1332 return false;
1334 tcs->entry_count = tag_hdr.entry_count;
1336 else
1338 tcs->entry_count = master_hdr.tch.entry_count;
1342 tcs->valid = true;
1343 tcs->initialized = true;
1344 write_lock++;
1346 return true;
1349 void tagcache_search_set_uniqbuf(struct tagcache_search *tcs,
1350 void *buffer, long length)
1352 tcs->unique_list = (unsigned long *)buffer;
1353 tcs->unique_list_capacity = length / sizeof(*tcs->unique_list);
1354 tcs->unique_list_count = 0;
1357 bool tagcache_search_add_filter(struct tagcache_search *tcs,
1358 int tag, int seek)
1360 if (tcs->filter_count == TAGCACHE_MAX_FILTERS)
1361 return false;
1363 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag))
1364 return false;
1366 tcs->filter_tag[tcs->filter_count] = tag;
1367 tcs->filter_seek[tcs->filter_count] = seek;
1368 tcs->filter_count++;
1370 return true;
1373 bool tagcache_search_add_clause(struct tagcache_search *tcs,
1374 struct tagcache_search_clause *clause)
1376 int i;
1378 if (tcs->clause_count >= TAGCACHE_MAX_CLAUSES)
1380 logf("Too many clauses");
1381 return false;
1384 if (clause->type != clause_logical_or)
1386 /* Check if there is already a similar filter in present (filters are
1387 * much faster than clauses).
1389 for (i = 0; i < tcs->filter_count; i++)
1391 if (tcs->filter_tag[i] == clause->tag)
1392 return true;
1395 if (!TAGCACHE_IS_NUMERIC(clause->tag) && tcs->idxfd[clause->tag] < 0)
1397 char buf[MAX_PATH];
1399 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, clause->tag);
1400 tcs->idxfd[clause->tag] = open(buf, O_RDONLY);
1404 tcs->clause[tcs->clause_count] = clause;
1405 tcs->clause_count++;
1407 return true;
1410 static bool get_next(struct tagcache_search *tcs)
1412 static char buf[TAG_MAXLEN+32];
1413 struct tagfile_entry entry;
1414 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1415 long flag = 0;
1416 #endif
1418 if (!tcs->valid || !tc_stat.ready)
1419 return false;
1421 if (tcs->idxfd[tcs->type] < 0 && !TAGCACHE_IS_NUMERIC(tcs->type)
1422 #ifdef HAVE_TC_RAMCACHE
1423 && !tcs->ramsearch
1424 #endif
1426 return false;
1428 /* Relative fetch. */
1429 if (tcs->filter_count > 0 || tcs->clause_count > 0
1430 || TAGCACHE_IS_NUMERIC(tcs->type)
1431 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1432 /* We need to retrieve flag status for dircache. */
1433 || (tcs->ramsearch && tcs->type == tag_filename)
1434 #endif
1437 struct tagcache_seeklist_entry *seeklist;
1439 /* Check for end of list. */
1440 if (tcs->list_position == tcs->seek_list_count)
1442 tcs->list_position = 0;
1444 /* Try to fetch more. */
1445 if (!build_lookup_list(tcs))
1447 tcs->valid = false;
1448 return false;
1452 seeklist = &tcs->seeklist[tcs->list_position];
1453 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1454 flag = seeklist->flag;
1455 #endif
1456 tcs->position = seeklist->seek;
1457 tcs->idx_id = seeklist->idx_id;
1458 tcs->list_position++;
1460 else
1462 if (tcs->entry_count == 0)
1464 tcs->valid = false;
1465 return false;
1468 tcs->entry_count--;
1471 tcs->result_seek = tcs->position;
1473 if (TAGCACHE_IS_NUMERIC(tcs->type))
1475 snprintf(buf, sizeof(buf), "%ld", tcs->position);
1476 tcs->result = buf;
1477 tcs->result_len = strlen(buf) + 1;
1478 return true;
1481 /* Direct fetch. */
1482 #ifdef HAVE_TC_RAMCACHE
1483 if (tcs->ramsearch)
1486 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1487 if (tcs->type == tag_filename && (flag & FLAG_DIRCACHE)
1488 && is_dircache_intact())
1490 dircache_copy_path((struct dircache_entry *)tcs->position,
1491 buf, sizeof buf);
1492 tcs->result = buf;
1493 tcs->result_len = strlen(buf) + 1;
1494 tcs->ramresult = false;
1496 return true;
1498 else
1499 #endif
1500 if (tcs->type != tag_filename)
1502 struct tagfile_entry *ep;
1504 ep = (struct tagfile_entry *)&hdr->tags[tcs->type][tcs->position];
1505 tcs->result = ep->tag_data;
1506 tcs->result_len = strlen(tcs->result) + 1;
1507 tcs->idx_id = ep->idx_id;
1508 tcs->ramresult = true;
1510 /* Increase position for the next run. This may get overwritten. */
1511 tcs->position += sizeof(struct tagfile_entry) + ep->tag_length;
1513 return true;
1516 #endif
1518 if (!open_files(tcs, tcs->type))
1520 tcs->valid = false;
1521 return false;
1524 /* Seek stream to the correct position and continue to direct fetch. */
1525 lseek(tcs->idxfd[tcs->type], tcs->position, SEEK_SET);
1527 if (ecread_tagfile_entry(tcs->idxfd[tcs->type], &entry) != sizeof(struct tagfile_entry))
1529 logf("read error #5");
1530 tcs->valid = false;
1531 return false;
1534 if (entry.tag_length > (long)sizeof(buf))
1536 tcs->valid = false;
1537 logf("too long tag #2");
1538 logf("P:%lX/%lX", tcs->position, entry.tag_length);
1539 return false;
1542 if (read(tcs->idxfd[tcs->type], buf, entry.tag_length) != entry.tag_length)
1544 tcs->valid = false;
1545 logf("read error #4");
1546 return false;
1550 Update the position for the next read (this may be overridden
1551 if filters or clauses are being used).
1553 tcs->position += sizeof(struct tagfile_entry) + entry.tag_length;
1554 tcs->result = buf;
1555 tcs->result_len = strlen(tcs->result) + 1;
1556 tcs->idx_id = entry.idx_id;
1557 tcs->ramresult = false;
1559 return true;
1562 bool tagcache_get_next(struct tagcache_search *tcs)
1564 while (get_next(tcs))
1566 if (tcs->result_len > 1)
1567 return true;
1570 return false;
1573 bool tagcache_retrieve(struct tagcache_search *tcs, int idxid,
1574 int tag, char *buf, long size)
1576 struct index_entry idx;
1578 *buf = '\0';
1579 if (!get_index(tcs->masterfd, idxid, &idx, true))
1580 return false;
1582 return retrieve(tcs, &idx, tag, buf, size);
1585 static bool update_master_header(void)
1587 struct master_header myhdr;
1588 int fd;
1590 if (!tc_stat.ready)
1591 return false;
1593 if ( (fd = open_master_fd(&myhdr, true)) < 0)
1594 return false;
1596 myhdr.serial = current_tcmh.serial;
1597 myhdr.commitid = current_tcmh.commitid;
1598 myhdr.dirty = current_tcmh.dirty;
1600 /* Write it back */
1601 lseek(fd, 0, SEEK_SET);
1602 ecwrite(fd, &myhdr, 1, master_header_ec, tc_stat.econ);
1603 close(fd);
1605 #ifdef HAVE_TC_RAMCACHE
1606 if (hdr)
1608 hdr->h.serial = current_tcmh.serial;
1609 hdr->h.commitid = current_tcmh.commitid;
1610 hdr->h.dirty = current_tcmh.dirty;
1612 #endif
1614 return true;
1617 #if 0
1619 void tagcache_modify(struct tagcache_search *tcs, int type, const char *text)
1621 struct tagentry *entry;
1623 if (tcs->type != tag_title)
1624 return ;
1626 /* We will need reserve buffer for this. */
1627 if (tcs->ramcache)
1629 struct tagfile_entry *ep;
1631 ep = (struct tagfile_entry *)&hdr->tags[tcs->type][tcs->result_seek];
1632 tcs->seek_list[tcs->seek_list_count];
1635 entry = find_entry_ram();
1638 #endif
1640 void tagcache_search_finish(struct tagcache_search *tcs)
1642 int i;
1644 if (!tcs->initialized)
1645 return;
1647 if (tcs->masterfd >= 0)
1649 close(tcs->masterfd);
1650 tcs->masterfd = -1;
1653 for (i = 0; i < TAG_COUNT; i++)
1655 if (tcs->idxfd[i] >= 0)
1657 close(tcs->idxfd[i]);
1658 tcs->idxfd[i] = -1;
1662 tcs->ramsearch = false;
1663 tcs->valid = false;
1664 tcs->initialized = 0;
1665 if (write_lock > 0)
1666 write_lock--;
1669 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1670 static struct tagfile_entry *get_tag(const struct index_entry *entry, int tag)
1672 return (struct tagfile_entry *)&hdr->tags[tag][entry->tag_seek[tag]];
1675 static long get_tag_numeric(const struct index_entry *entry, int tag, int idx_id)
1677 return check_virtual_tags(tag, idx_id, entry);
1680 static char* get_tag_string(const struct index_entry *entry, int tag)
1682 char* s = get_tag(entry, tag)->tag_data;
1683 return strcmp(s, UNTAGGED) ? s : NULL;
1686 bool tagcache_fill_tags(struct mp3entry *id3, const char *filename)
1688 struct index_entry *entry;
1689 int idx_id;
1691 if (!tc_stat.ready || !tc_stat.ramcache)
1692 return false;
1694 /* Find the corresponding entry in tagcache. */
1695 idx_id = find_entry_ram(filename, NULL);
1696 if (idx_id < 0)
1697 return false;
1699 entry = &hdr->indices[idx_id];
1701 memset(id3, 0, sizeof(struct mp3entry));
1703 id3->title = get_tag_string(entry, tag_title);
1704 id3->artist = get_tag_string(entry, tag_artist);
1705 id3->album = get_tag_string(entry, tag_album);
1706 id3->genre_string = get_tag_string(entry, tag_genre);
1707 id3->composer = get_tag_string(entry, tag_composer);
1708 id3->comment = get_tag_string(entry, tag_comment);
1709 id3->albumartist = get_tag_string(entry, tag_albumartist);
1710 id3->grouping = get_tag_string(entry, tag_grouping);
1712 id3->length = get_tag_numeric(entry, tag_length, idx_id);
1713 id3->playcount = get_tag_numeric(entry, tag_playcount, idx_id);
1714 id3->rating = get_tag_numeric(entry, tag_rating, idx_id);
1715 id3->lastplayed = get_tag_numeric(entry, tag_lastplayed, idx_id);
1716 id3->score = get_tag_numeric(entry, tag_virt_autoscore, idx_id) / 10;
1717 id3->year = get_tag_numeric(entry, tag_year, idx_id);
1719 id3->discnum = get_tag_numeric(entry, tag_discnumber, idx_id);
1720 id3->tracknum = get_tag_numeric(entry, tag_tracknumber, idx_id);
1721 id3->bitrate = get_tag_numeric(entry, tag_bitrate, idx_id);
1722 if (id3->bitrate == 0)
1723 id3->bitrate = 1;
1725 #if CONFIG_CODEC == SWCODEC
1726 if (global_settings.autoresume_enable)
1728 id3->offset = get_tag_numeric(entry, tag_lastoffset, idx_id);
1729 logf("tagcache_fill_tags: Set offset for %s to %lX\n",
1730 id3->title, id3->offset);
1732 #endif
1734 return true;
1736 #endif
1738 static inline void write_item(const char *item)
1740 int len = strlen(item) + 1;
1742 data_size += len;
1743 write(cachefd, item, len);
1746 static int check_if_empty(char **tag)
1748 int length;
1750 if (*tag == NULL || **tag == '\0')
1752 *tag = UNTAGGED;
1753 return sizeof(UNTAGGED); /* Tag length */
1756 length = strlen(*tag);
1757 if (length > TAG_MAXLEN)
1759 logf("over length tag: %s", *tag);
1760 length = TAG_MAXLEN;
1761 (*tag)[length] = '\0';
1764 return length + 1;
1767 #define ADD_TAG(entry,tag,data) \
1768 /* Adding tag */ \
1769 entry.tag_offset[tag] = offset; \
1770 entry.tag_length[tag] = check_if_empty(data); \
1771 offset += entry.tag_length[tag]
1772 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1773 * idea, as it uses lots of stack and is called from a recursive function
1774 * (check_dir).
1776 static void __attribute__ ((noinline)) add_tagcache(char *path,
1777 unsigned long mtime
1778 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1779 ,const struct dircache_entry *dc
1780 #endif
1783 struct mp3entry id3;
1784 struct temp_file_entry entry;
1785 bool ret;
1786 int fd;
1787 int idx_id = -1;
1788 char tracknumfix[3];
1789 int offset = 0;
1790 int path_length = strlen(path);
1791 bool has_albumartist;
1792 bool has_grouping;
1794 #ifdef SIMULATOR
1795 /* Crude logging for the sim - to aid in debugging */
1796 int logfd = open(ROCKBOX_DIR "/database.log",
1797 O_WRONLY | O_APPEND | O_CREAT, 0666);
1798 if (logfd >= 0) {
1799 write(logfd, path, strlen(path));
1800 write(logfd, "\n", 1);
1801 close(logfd);
1803 #endif
1805 if (cachefd < 0)
1806 return ;
1808 /* Check for overlength file path. */
1809 if (path_length > TAG_MAXLEN)
1811 /* Path can't be shortened. */
1812 logf("Too long path: %s", path);
1813 return ;
1816 /* Check if the file is supported. */
1817 if (probe_file_format(path) == AFMT_UNKNOWN)
1818 return ;
1820 /* Check if the file is already cached. */
1821 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1822 if (tc_stat.ramcache && is_dircache_intact())
1824 idx_id = find_entry_ram(path, dc);
1826 #endif
1828 /* Be sure the entry doesn't exist. */
1829 if (filenametag_fd >= 0 && idx_id < 0)
1830 idx_id = find_entry_disk(path, false);
1832 /* Check if file has been modified. */
1833 if (idx_id >= 0)
1835 struct index_entry idx;
1837 /* TODO: Mark that the index exists (for fast reverse scan) */
1838 //found_idx[idx_id/8] |= idx_id%8;
1840 if (!get_index(-1, idx_id, &idx, true))
1842 logf("failed to retrieve index entry");
1843 return ;
1846 if ((unsigned long)idx.tag_seek[tag_mtime] == mtime)
1848 /* No changes to file. */
1849 return ;
1852 /* Metadata might have been changed. Delete the entry. */
1853 logf("Re-adding: %s", path);
1854 if (!delete_entry(idx_id))
1856 logf("delete_entry failed: %d", idx_id);
1857 return ;
1861 fd = open(path, O_RDONLY);
1862 if (fd < 0)
1864 logf("open fail: %s", path);
1865 return ;
1868 memset(&id3, 0, sizeof(struct mp3entry));
1869 memset(&entry, 0, sizeof(struct temp_file_entry));
1870 memset(&tracknumfix, 0, sizeof(tracknumfix));
1871 ret = get_metadata(&id3, fd, path);
1872 close(fd);
1874 if (!ret)
1875 return ;
1877 logf("-> %s", path);
1879 /* Generate track number if missing. */
1880 if (id3.tracknum <= 0)
1882 const char *p = strrchr(path, '.');
1884 if (p == NULL)
1885 p = &path[strlen(path)-1];
1887 while (*p != '/')
1889 if (isdigit(*p) && isdigit(*(p-1)))
1891 tracknumfix[1] = *p--;
1892 tracknumfix[0] = *p;
1893 break;
1895 p--;
1898 if (tracknumfix[0] != '\0')
1900 id3.tracknum = atoi(tracknumfix);
1901 /* Set a flag to indicate track number has been generated. */
1902 entry.flag |= FLAG_TRKNUMGEN;
1904 else
1906 /* Unable to generate track number. */
1907 id3.tracknum = -1;
1911 /* Numeric tags */
1912 entry.tag_offset[tag_year] = id3.year;
1913 entry.tag_offset[tag_discnumber] = id3.discnum;
1914 entry.tag_offset[tag_tracknumber] = id3.tracknum;
1915 entry.tag_offset[tag_length] = id3.length;
1916 entry.tag_offset[tag_bitrate] = id3.bitrate;
1917 entry.tag_offset[tag_mtime] = mtime;
1919 /* String tags. */
1920 has_albumartist = id3.albumartist != NULL
1921 && strlen(id3.albumartist) > 0;
1922 has_grouping = id3.grouping != NULL
1923 && strlen(id3.grouping) > 0;
1925 ADD_TAG(entry, tag_filename, &path);
1926 ADD_TAG(entry, tag_title, &id3.title);
1927 ADD_TAG(entry, tag_artist, &id3.artist);
1928 ADD_TAG(entry, tag_album, &id3.album);
1929 ADD_TAG(entry, tag_genre, &id3.genre_string);
1930 ADD_TAG(entry, tag_composer, &id3.composer);
1931 ADD_TAG(entry, tag_comment, &id3.comment);
1932 if (has_albumartist)
1934 ADD_TAG(entry, tag_albumartist, &id3.albumartist);
1936 else
1938 ADD_TAG(entry, tag_albumartist, &id3.artist);
1940 if (has_grouping)
1942 ADD_TAG(entry, tag_grouping, &id3.grouping);
1944 else
1946 ADD_TAG(entry, tag_grouping, &id3.title);
1948 entry.data_length = offset;
1950 /* Write the header */
1951 write(cachefd, &entry, sizeof(struct temp_file_entry));
1953 /* And tags also... Correct order is critical */
1954 write_item(path);
1955 write_item(id3.title);
1956 write_item(id3.artist);
1957 write_item(id3.album);
1958 write_item(id3.genre_string);
1959 write_item(id3.composer);
1960 write_item(id3.comment);
1961 if (has_albumartist)
1963 write_item(id3.albumartist);
1965 else
1967 write_item(id3.artist);
1969 if (has_grouping)
1971 write_item(id3.grouping);
1973 else
1975 write_item(id3.title);
1977 total_entry_count++;
1980 static bool tempbuf_insert(char *str, int id, int idx_id, bool unique)
1982 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
1983 int len = strlen(str)+1;
1984 int i;
1985 unsigned crc32;
1986 unsigned *crcbuf = (unsigned *)&tempbuf[tempbuf_size-4];
1987 char buf[TAG_MAXLEN+32];
1989 for (i = 0; str[i] != '\0' && i < (int)sizeof(buf)-1; i++)
1990 buf[i] = tolower(str[i]);
1991 buf[i] = '\0';
1993 crc32 = crc_32(buf, i, 0xffffffff);
1995 if (unique)
1997 /* Check if the crc does not exist -> entry does not exist for sure. */
1998 for (i = 0; i < tempbufidx; i++)
2000 if (crcbuf[-i] != crc32)
2001 continue;
2003 if (!strcasecmp(str, index[i].str))
2005 if (id < 0 || id >= lookup_buffer_depth)
2007 logf("lookup buf overf.: %d", id);
2008 return false;
2011 lookup[id] = &index[i];
2012 return true;
2017 /* Insert to CRC buffer. */
2018 crcbuf[-tempbufidx] = crc32;
2019 tempbuf_left -= 4;
2021 /* Insert it to the buffer. */
2022 tempbuf_left -= len;
2023 if (tempbuf_left - 4 < 0 || tempbufidx >= commit_entry_count-1)
2024 return false;
2026 if (id >= lookup_buffer_depth)
2028 logf("lookup buf overf. #2: %d", id);
2029 return false;
2032 if (id >= 0)
2034 lookup[id] = &index[tempbufidx];
2035 index[tempbufidx].idlist.id = id;
2037 else
2038 index[tempbufidx].idlist.id = -1;
2040 index[tempbufidx].idlist.next = NULL;
2041 index[tempbufidx].idx_id = idx_id;
2042 index[tempbufidx].seek = -1;
2043 index[tempbufidx].str = &tempbuf[tempbuf_pos];
2044 memcpy(index[tempbufidx].str, str, len);
2045 tempbuf_pos += len;
2046 tempbufidx++;
2048 return true;
2051 static int compare(const void *p1, const void *p2)
2053 do_timed_yield();
2055 struct tempbuf_searchidx *e1 = (struct tempbuf_searchidx *)p1;
2056 struct tempbuf_searchidx *e2 = (struct tempbuf_searchidx *)p2;
2058 if (strcmp(e1->str, UNTAGGED) == 0)
2060 if (strcmp(e2->str, UNTAGGED) == 0)
2061 return 0;
2062 return -1;
2064 else if (strcmp(e2->str, UNTAGGED) == 0)
2065 return 1;
2067 return strncasecmp(e1->str, e2->str, TAG_MAXLEN);
2070 static int tempbuf_sort(int fd)
2072 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
2073 struct tagfile_entry fe;
2074 int i;
2075 int length;
2077 /* Generate reverse lookup entries. */
2078 for (i = 0; i < lookup_buffer_depth; i++)
2080 struct tempbuf_id_list *idlist;
2082 if (!lookup[i])
2083 continue;
2085 if (lookup[i]->idlist.id == i)
2086 continue;
2088 idlist = &lookup[i]->idlist;
2089 while (idlist->next != NULL)
2090 idlist = idlist->next;
2092 tempbuf_left -= sizeof(struct tempbuf_id_list);
2093 if (tempbuf_left - 4 < 0)
2094 return -1;
2096 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2097 if (tempbuf_pos & 0x03)
2099 tempbuf_pos = (tempbuf_pos & ~0x03) + 0x04;
2100 tempbuf_left -= 3;
2101 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2103 tempbuf_pos += sizeof(struct tempbuf_id_list);
2105 idlist = idlist->next;
2106 idlist->id = i;
2107 idlist->next = NULL;
2109 do_timed_yield();
2112 qsort(index, tempbufidx, sizeof(struct tempbuf_searchidx), compare);
2113 memset(lookup, 0, lookup_buffer_depth * sizeof(struct tempbuf_searchidx **));
2115 for (i = 0; i < tempbufidx; i++)
2117 struct tempbuf_id_list *idlist = &index[i].idlist;
2119 /* Fix the lookup list. */
2120 while (idlist != NULL)
2122 if (idlist->id >= 0)
2123 lookup[idlist->id] = &index[i];
2124 idlist = idlist->next;
2127 index[i].seek = lseek(fd, 0, SEEK_CUR);
2128 length = strlen(index[i].str) + 1;
2129 fe.tag_length = length;
2130 fe.idx_id = index[i].idx_id;
2132 /* Check the chunk alignment. */
2133 if ((fe.tag_length + sizeof(struct tagfile_entry))
2134 % TAGFILE_ENTRY_CHUNK_LENGTH)
2136 fe.tag_length += TAGFILE_ENTRY_CHUNK_LENGTH -
2137 ((fe.tag_length + sizeof(struct tagfile_entry))
2138 % TAGFILE_ENTRY_CHUNK_LENGTH);
2141 #ifdef TAGCACHE_STRICT_ALIGN
2142 /* Make sure the entry is long aligned. */
2143 if (index[i].seek & 0x03)
2145 logf("tempbuf_sort: alignment error!");
2146 return -3;
2148 #endif
2150 if (ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ) !=
2151 sizeof(struct tagfile_entry))
2153 logf("tempbuf_sort: write error #1");
2154 return -1;
2157 if (write(fd, index[i].str, length) != length)
2159 logf("tempbuf_sort: write error #2");
2160 return -2;
2163 /* Write some padding. */
2164 if (fe.tag_length - length > 0)
2165 write(fd, "XXXXXXXX", fe.tag_length - length);
2168 return i;
2171 inline static struct tempbuf_searchidx* tempbuf_locate(int id)
2173 if (id < 0 || id >= lookup_buffer_depth)
2174 return NULL;
2176 return lookup[id];
2180 inline static int tempbuf_find_location(int id)
2182 struct tempbuf_searchidx *entry;
2184 entry = tempbuf_locate(id);
2185 if (entry == NULL)
2186 return -1;
2188 return entry->seek;
2191 static bool build_numeric_indices(struct tagcache_header *h, int tmpfd)
2193 struct master_header tcmh;
2194 struct index_entry idx;
2195 int masterfd;
2196 int masterfd_pos;
2197 struct temp_file_entry *entrybuf = (struct temp_file_entry *)tempbuf;
2198 int max_entries;
2199 int entries_processed = 0;
2200 int i, j;
2201 char buf[TAG_MAXLEN];
2203 max_entries = tempbuf_size / sizeof(struct temp_file_entry) - 1;
2205 logf("Building numeric indices...");
2206 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2208 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
2209 return false;
2211 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2212 SEEK_CUR);
2213 if (masterfd_pos == filesize(masterfd))
2215 logf("we can't append!");
2216 close(masterfd);
2217 return false;
2220 while (entries_processed < h->entry_count)
2222 int count = MIN(h->entry_count - entries_processed, max_entries);
2224 /* Read in as many entries as possible. */
2225 for (i = 0; i < count; i++)
2227 struct temp_file_entry *tfe = &entrybuf[i];
2228 int datastart;
2230 /* Read in numeric data. */
2231 if (read(tmpfd, tfe, sizeof(struct temp_file_entry)) !=
2232 sizeof(struct temp_file_entry))
2234 logf("read fail #1");
2235 close(masterfd);
2236 return false;
2239 datastart = lseek(tmpfd, 0, SEEK_CUR);
2242 * Read string data from the following tags:
2243 * - tag_filename
2244 * - tag_artist
2245 * - tag_album
2246 * - tag_title
2248 * A crc32 hash is calculated from the read data
2249 * and stored back to the data offset field kept in memory.
2251 #define tmpdb_read_string_tag(tag) \
2252 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2253 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2255 logf("read fail: buffer overflow"); \
2256 close(masterfd); \
2257 return false; \
2260 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2261 tfe->tag_length[tag]) \
2263 logf("read fail #2"); \
2264 close(masterfd); \
2265 return false; \
2268 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2269 lseek(tmpfd, datastart, SEEK_SET)
2271 tmpdb_read_string_tag(tag_filename);
2272 tmpdb_read_string_tag(tag_artist);
2273 tmpdb_read_string_tag(tag_album);
2274 tmpdb_read_string_tag(tag_title);
2276 /* Seek to the end of the string data. */
2277 lseek(tmpfd, tfe->data_length, SEEK_CUR);
2280 /* Backup the master index position. */
2281 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2282 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2284 /* Check if we can resurrect some deleted runtime statistics data. */
2285 for (i = 0; i < tcmh.tch.entry_count; i++)
2287 /* Read the index entry. */
2288 if (ecread_index_entry(masterfd, &idx)
2289 != sizeof(struct index_entry))
2291 logf("read fail #3");
2292 close(masterfd);
2293 return false;
2297 * Skip unless the entry is marked as being deleted
2298 * or the data has already been resurrected.
2300 if (!(idx.flag & FLAG_DELETED) || idx.flag & FLAG_RESURRECTED)
2301 continue;
2303 /* Now try to match the entry. */
2305 * To succesfully match a song, the following conditions
2306 * must apply:
2308 * For numeric fields: tag_length
2309 * - Full identical match is required
2311 * If tag_filename matches, no further checking necessary.
2313 * For string hashes: tag_artist, tag_album, tag_title
2314 * - All three of these must match
2316 for (j = 0; j < count; j++)
2318 struct temp_file_entry *tfe = &entrybuf[j];
2320 /* Try to match numeric fields first. */
2321 if (tfe->tag_offset[tag_length] != idx.tag_seek[tag_length])
2322 continue;
2324 /* Now it's time to do the hash matching. */
2325 if (tfe->tag_offset[tag_filename] != idx.tag_seek[tag_filename])
2327 int match_count = 0;
2329 /* No filename match, check if we can match two other tags. */
2330 #define tmpdb_match(tag) \
2331 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2332 match_count++
2334 tmpdb_match(tag_artist);
2335 tmpdb_match(tag_album);
2336 tmpdb_match(tag_title);
2338 if (match_count < 3)
2340 /* Still no match found, give up. */
2341 continue;
2345 /* A match found, now copy & resurrect the statistical data. */
2346 #define tmpdb_copy_tag(tag) \
2347 tfe->tag_offset[tag] = idx.tag_seek[tag]
2349 tmpdb_copy_tag(tag_playcount);
2350 tmpdb_copy_tag(tag_rating);
2351 tmpdb_copy_tag(tag_playtime);
2352 tmpdb_copy_tag(tag_lastplayed);
2353 tmpdb_copy_tag(tag_commitid);
2354 tmpdb_copy_tag(tag_lastoffset);
2356 /* Avoid processing this entry again. */
2357 idx.flag |= FLAG_RESURRECTED;
2359 lseek(masterfd, -sizeof(struct index_entry), SEEK_CUR);
2360 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2362 logf("masterfd writeback fail #1");
2363 close(masterfd);
2364 return false;
2367 logf("Entry resurrected");
2372 /* Restore the master index position. */
2373 lseek(masterfd, masterfd_pos, SEEK_SET);
2375 /* Commit the data to the index. */
2376 for (i = 0; i < count; i++)
2378 int loc = lseek(masterfd, 0, SEEK_CUR);
2380 if (ecread_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2382 logf("read fail #3");
2383 close(masterfd);
2384 return false;
2387 for (j = 0; j < TAG_COUNT; j++)
2389 if (!TAGCACHE_IS_NUMERIC(j))
2390 continue;
2392 idx.tag_seek[j] = entrybuf[i].tag_offset[j];
2394 idx.flag = entrybuf[i].flag;
2396 if (idx.tag_seek[tag_commitid])
2398 /* Data has been resurrected. */
2399 idx.flag |= FLAG_DIRTYNUM;
2401 else if (tc_stat.ready && current_tcmh.commitid > 0)
2403 idx.tag_seek[tag_commitid] = current_tcmh.commitid;
2404 idx.flag |= FLAG_DIRTYNUM;
2407 /* Write back the updated index. */
2408 lseek(masterfd, loc, SEEK_SET);
2409 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2411 logf("write fail");
2412 close(masterfd);
2413 return false;
2417 entries_processed += count;
2418 logf("%d/%ld entries processed", entries_processed, h->entry_count);
2421 close(masterfd);
2423 return true;
2427 * Return values:
2428 * > 0 success
2429 * == 0 temporary failure
2430 * < 0 fatal error
2432 static int build_index(int index_type, struct tagcache_header *h, int tmpfd)
2434 int i;
2435 struct tagcache_header tch;
2436 struct master_header tcmh;
2437 struct index_entry idxbuf[IDX_BUF_DEPTH];
2438 int idxbuf_pos;
2439 char buf[TAG_MAXLEN+32];
2440 int fd = -1, masterfd;
2441 bool error = false;
2442 int init;
2443 int masterfd_pos;
2445 logf("Building index: %d", index_type);
2447 /* Check the number of entries we need to allocate ram for. */
2448 commit_entry_count = h->entry_count + 1;
2450 masterfd = open_master_fd(&tcmh, false);
2451 if (masterfd >= 0)
2453 commit_entry_count += tcmh.tch.entry_count;
2454 close(masterfd);
2456 else
2457 remove_files(); /* Just to be sure we are clean. */
2459 /* Open the index file, which contains the tag names. */
2460 fd = open_tag_fd(&tch, index_type, true);
2461 if (fd >= 0)
2463 logf("tch.datasize=%ld", tch.datasize);
2464 lookup_buffer_depth = 1 +
2465 /* First part */ commit_entry_count +
2466 /* Second part */ (tch.datasize / TAGFILE_ENTRY_CHUNK_LENGTH);
2468 else
2470 lookup_buffer_depth = 1 +
2471 /* First part */ commit_entry_count +
2472 /* Second part */ 0;
2475 logf("lookup_buffer_depth=%ld", lookup_buffer_depth);
2476 logf("commit_entry_count=%ld", commit_entry_count);
2478 /* Allocate buffer for all index entries from both old and new
2479 * tag files. */
2480 tempbufidx = 0;
2481 tempbuf_pos = commit_entry_count * sizeof(struct tempbuf_searchidx);
2483 /* Allocate lookup buffer. The first portion of commit_entry_count
2484 * contains the new tags in the temporary file and the second
2485 * part for locating entries already in the db.
2487 * New tags Old tags
2488 * +---------+---------------------------+
2489 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2490 * +---------+---------------------------+
2492 * Old tags are inserted to a temporary buffer with position:
2493 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2494 * And new tags with index:
2495 * tempbuf_insert(idx, ...);
2497 * The buffer is sorted and written into tag file:
2498 * tempbuf_sort(...);
2499 * leaving master index locations messed up.
2501 * That is fixed using the lookup buffer for old tags:
2502 * new_seek = tempbuf_find_location(old_seek, ...);
2503 * and for new tags:
2504 * new_seek = tempbuf_find_location(idx);
2506 lookup = (struct tempbuf_searchidx **)&tempbuf[tempbuf_pos];
2507 tempbuf_pos += lookup_buffer_depth * sizeof(void **);
2508 memset(lookup, 0, lookup_buffer_depth * sizeof(void **));
2510 /* And calculate the remaining data space used mainly for storing
2511 * tag data (strings). */
2512 tempbuf_left = tempbuf_size - tempbuf_pos - 8;
2513 if (tempbuf_left - TAGFILE_ENTRY_AVG_LENGTH * commit_entry_count < 0)
2515 logf("Buffer way too small!");
2516 return 0;
2519 if (fd >= 0)
2522 * If tag file contains unique tags (sorted index), we will load
2523 * it entirely into memory so we can resort it later for use with
2524 * chunked browsing.
2526 if (TAGCACHE_IS_SORTED(index_type))
2528 logf("loading tags...");
2529 for (i = 0; i < tch.entry_count; i++)
2531 struct tagfile_entry entry;
2532 int loc = lseek(fd, 0, SEEK_CUR);
2533 bool ret;
2535 if (ecread_tagfile_entry(fd, &entry) != sizeof(struct tagfile_entry))
2537 logf("read error #7");
2538 close(fd);
2539 return -2;
2542 if (entry.tag_length >= (int)sizeof(buf))
2544 logf("too long tag #3");
2545 close(fd);
2546 return -2;
2549 if (read(fd, buf, entry.tag_length) != entry.tag_length)
2551 logf("read error #8");
2552 close(fd);
2553 return -2;
2556 /* Skip deleted entries. */
2557 if (buf[0] == '\0')
2558 continue;
2561 * Save the tag and tag id in the memory buffer. Tag id
2562 * is saved so we can later reindex the master lookup
2563 * table when the index gets resorted.
2565 ret = tempbuf_insert(buf, loc/TAGFILE_ENTRY_CHUNK_LENGTH
2566 + commit_entry_count, entry.idx_id,
2567 TAGCACHE_IS_UNIQUE(index_type));
2568 if (!ret)
2570 close(fd);
2571 return -3;
2573 do_timed_yield();
2575 logf("done");
2577 else
2578 tempbufidx = tch.entry_count;
2580 else
2583 * Creating new index file to store the tags. No need to preload
2584 * anything whether the index type is sorted or not.
2586 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, index_type);
2587 fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2588 if (fd < 0)
2590 logf("%s open fail", buf);
2591 return -2;
2594 tch.magic = TAGCACHE_MAGIC;
2595 tch.entry_count = 0;
2596 tch.datasize = 0;
2598 if (ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ)
2599 != sizeof(struct tagcache_header))
2601 logf("header write failed");
2602 close(fd);
2603 return -2;
2607 /* Loading the tag lookup file as "master file". */
2608 logf("Loading index file");
2609 masterfd = open(TAGCACHE_FILE_MASTER, O_RDWR);
2611 if (masterfd < 0)
2613 logf("Creating new DB");
2614 masterfd = open(TAGCACHE_FILE_MASTER, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2616 if (masterfd < 0)
2618 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER);
2619 close(fd);
2620 return -2;
2623 /* Write the header (write real values later). */
2624 memset(&tcmh, 0, sizeof(struct master_header));
2625 tcmh.tch = *h;
2626 tcmh.tch.entry_count = 0;
2627 tcmh.tch.datasize = 0;
2628 tcmh.dirty = true;
2629 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
2630 init = true;
2631 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2633 else
2636 * Master file already exists so we need to process the current
2637 * file first.
2639 init = false;
2641 if (ecread(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ) !=
2642 sizeof(struct master_header) || tcmh.tch.magic != TAGCACHE_MAGIC)
2644 logf("header error");
2645 close(fd);
2646 close(masterfd);
2647 return -2;
2651 * If we reach end of the master file, we need to expand it to
2652 * hold new tags. If the current index is not sorted, we can
2653 * simply append new data to end of the file.
2654 * However, if the index is sorted, we need to update all tag
2655 * pointers in the master file for the current index.
2657 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2658 SEEK_CUR);
2659 if (masterfd_pos == filesize(masterfd))
2661 logf("appending...");
2662 init = true;
2667 * Load new unique tags in memory to be sorted later and added
2668 * to the master lookup file.
2670 if (TAGCACHE_IS_SORTED(index_type))
2672 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2673 /* h is the header of the temporary file containing new tags. */
2674 logf("inserting new tags...");
2675 for (i = 0; i < h->entry_count; i++)
2677 struct temp_file_entry entry;
2679 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2680 sizeof(struct temp_file_entry))
2682 logf("read fail #3");
2683 error = true;
2684 goto error_exit;
2687 /* Read data. */
2688 if (entry.tag_length[index_type] >= (long)sizeof(buf))
2690 logf("too long entry!");
2691 error = true;
2692 goto error_exit;
2695 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2696 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2697 entry.tag_length[index_type])
2699 logf("read fail #4");
2700 error = true;
2701 goto error_exit;
2704 if (TAGCACHE_IS_UNIQUE(index_type))
2705 error = !tempbuf_insert(buf, i, -1, true);
2706 else
2707 error = !tempbuf_insert(buf, i, tcmh.tch.entry_count + i, false);
2709 if (error)
2711 logf("insert error");
2712 goto error_exit;
2715 /* Skip to next. */
2716 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2717 entry.tag_length[index_type], SEEK_CUR);
2718 do_timed_yield();
2720 logf("done");
2722 /* Sort the buffer data and write it to the index file. */
2723 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
2725 * We need to truncate the index file now. There can be junk left
2726 * at the end of file (however, we _should_ always follow the
2727 * entry_count and don't crash with that).
2729 ftruncate(fd, lseek(fd, 0, SEEK_CUR));
2731 i = tempbuf_sort(fd);
2732 if (i < 0)
2733 goto error_exit;
2734 logf("sorted %d tags", i);
2737 * Now update all indexes in the master lookup file.
2739 logf("updating indices...");
2740 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2741 for (i = 0; i < tcmh.tch.entry_count; i += idxbuf_pos)
2743 int j;
2744 int loc = lseek(masterfd, 0, SEEK_CUR);
2746 idxbuf_pos = MIN(tcmh.tch.entry_count - i, IDX_BUF_DEPTH);
2748 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2749 != (int)sizeof(struct index_entry)*idxbuf_pos)
2751 logf("read fail #5");
2752 error = true;
2753 goto error_exit ;
2755 lseek(masterfd, loc, SEEK_SET);
2757 for (j = 0; j < idxbuf_pos; j++)
2759 if (idxbuf[j].flag & FLAG_DELETED)
2761 /* We can just ignore deleted entries. */
2762 // idxbuf[j].tag_seek[index_type] = 0;
2763 continue;
2766 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(
2767 idxbuf[j].tag_seek[index_type]/TAGFILE_ENTRY_CHUNK_LENGTH
2768 + commit_entry_count);
2770 if (idxbuf[j].tag_seek[index_type] < 0)
2772 logf("update error: %ld/%d/%ld",
2773 idxbuf[j].flag, i+j, tcmh.tch.entry_count);
2774 error = true;
2775 goto error_exit;
2778 do_timed_yield();
2781 /* Write back the updated index. */
2782 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2783 index_entry_ec, tc_stat.econ) !=
2784 (int)sizeof(struct index_entry)*idxbuf_pos)
2786 logf("write fail");
2787 error = true;
2788 goto error_exit;
2791 logf("done");
2795 * Walk through the temporary file containing the new tags.
2797 // build_normal_index(h, tmpfd, masterfd, idx);
2798 logf("updating new indices...");
2799 lseek(masterfd, masterfd_pos, SEEK_SET);
2800 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2801 lseek(fd, 0, SEEK_END);
2802 for (i = 0; i < h->entry_count; i += idxbuf_pos)
2804 int j;
2806 idxbuf_pos = MIN(h->entry_count - i, IDX_BUF_DEPTH);
2807 if (init)
2809 memset(idxbuf, 0, sizeof(struct index_entry)*IDX_BUF_DEPTH);
2811 else
2813 int loc = lseek(masterfd, 0, SEEK_CUR);
2815 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2816 != (int)sizeof(struct index_entry)*idxbuf_pos)
2818 logf("read fail #6");
2819 error = true;
2820 break ;
2822 lseek(masterfd, loc, SEEK_SET);
2825 /* Read entry headers. */
2826 for (j = 0; j < idxbuf_pos; j++)
2828 if (!TAGCACHE_IS_SORTED(index_type))
2830 struct temp_file_entry entry;
2831 struct tagfile_entry fe;
2833 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2834 sizeof(struct temp_file_entry))
2836 logf("read fail #7");
2837 error = true;
2838 break ;
2841 /* Read data. */
2842 if (entry.tag_length[index_type] >= (int)sizeof(buf))
2844 logf("too long entry!");
2845 logf("length=%d", entry.tag_length[index_type]);
2846 logf("pos=0x%02lx", lseek(tmpfd, 0, SEEK_CUR));
2847 error = true;
2848 break ;
2851 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2852 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2853 entry.tag_length[index_type])
2855 logf("read fail #8");
2856 logf("offset=0x%02lx", entry.tag_offset[index_type]);
2857 logf("length=0x%02x", entry.tag_length[index_type]);
2858 error = true;
2859 break ;
2862 /* Write to index file. */
2863 idxbuf[j].tag_seek[index_type] = lseek(fd, 0, SEEK_CUR);
2864 fe.tag_length = entry.tag_length[index_type];
2865 fe.idx_id = tcmh.tch.entry_count + i + j;
2866 ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ);
2867 write(fd, buf, fe.tag_length);
2868 tempbufidx++;
2870 /* Skip to next. */
2871 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2872 entry.tag_length[index_type], SEEK_CUR);
2874 else
2876 /* Locate the correct entry from the sorted array. */
2877 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(i + j);
2878 if (idxbuf[j].tag_seek[index_type] < 0)
2880 logf("entry not found (%d)", j);
2881 error = true;
2882 break ;
2887 /* Write index. */
2888 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2889 index_entry_ec, tc_stat.econ) !=
2890 (int)sizeof(struct index_entry)*idxbuf_pos)
2892 logf("tagcache: write fail #4");
2893 error = true;
2894 break ;
2897 do_timed_yield();
2899 logf("done");
2901 /* Finally write the header. */
2902 tch.magic = TAGCACHE_MAGIC;
2903 tch.entry_count = tempbufidx;
2904 tch.datasize = lseek(fd, 0, SEEK_END) - sizeof(struct tagcache_header);
2905 lseek(fd, 0, SEEK_SET);
2906 ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ);
2908 if (index_type != tag_filename)
2909 h->datasize += tch.datasize;
2910 logf("s:%d/%ld/%ld", index_type, tch.datasize, h->datasize);
2911 error_exit:
2913 close(fd);
2914 close(masterfd);
2916 if (error)
2917 return -2;
2919 return 1;
2922 static bool commit(void)
2924 struct tagcache_header tch;
2925 struct master_header tcmh;
2926 int i, len, rc;
2927 int tmpfd;
2928 int masterfd;
2929 #ifdef HAVE_DIRCACHE
2930 bool dircache_buffer_stolen = false;
2931 #endif
2932 bool local_allocation = false;
2934 logf("committing tagcache");
2936 while (write_lock)
2937 sleep(1);
2939 tmpfd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
2940 if (tmpfd < 0)
2942 logf("nothing to commit");
2943 return true;
2947 /* Load the header. */
2948 len = sizeof(struct tagcache_header);
2949 rc = read(tmpfd, &tch, len);
2951 if (tch.magic != TAGCACHE_MAGIC || rc != len)
2953 logf("incorrect tmpheader");
2954 close(tmpfd);
2955 remove(TAGCACHE_FILE_TEMP);
2956 return false;
2959 if (tch.entry_count == 0)
2961 logf("nothing to commit");
2962 close(tmpfd);
2963 remove(TAGCACHE_FILE_TEMP);
2964 return true;
2967 /* Fully initialize existing headers (if any) before going further. */
2968 tc_stat.ready = check_all_headers();
2970 #ifdef HAVE_EEPROM_SETTINGS
2971 remove(TAGCACHE_STATEFILE);
2972 #endif
2974 /* At first be sure to unload the ramcache! */
2975 #ifdef HAVE_TC_RAMCACHE
2976 tc_stat.ramcache = false;
2977 #endif
2979 read_lock++;
2981 /* Try to steal every buffer we can :) */
2982 if (tempbuf_size == 0)
2983 local_allocation = true;
2985 #ifdef HAVE_DIRCACHE
2986 if (tempbuf_size == 0)
2988 /* Try to steal the dircache buffer. */
2989 tempbuf = dircache_steal_buffer(&tempbuf_size);
2990 tempbuf_size &= ~0x03;
2992 if (tempbuf_size > 0)
2994 dircache_buffer_stolen = true;
2997 #endif
2999 #ifdef HAVE_TC_RAMCACHE
3000 if (tempbuf_size == 0 && tc_stat.ramcache_allocated > 0)
3002 tempbuf = (char *)(hdr + 1);
3003 tempbuf_size = tc_stat.ramcache_allocated - sizeof(struct ramcache_header) - 128;
3004 tempbuf_size &= ~0x03;
3006 #endif
3008 /* And finally fail if there are no buffers available. */
3009 if (tempbuf_size == 0)
3011 logf("delaying commit until next boot");
3012 tc_stat.commit_delayed = true;
3013 close(tmpfd);
3014 read_lock--;
3015 return false;
3018 logf("commit %ld entries...", tch.entry_count);
3020 /* Mark DB dirty so it will stay disabled if commit fails. */
3021 current_tcmh.dirty = true;
3022 update_master_header();
3024 /* Now create the index files. */
3025 tc_stat.commit_step = 0;
3026 tch.datasize = 0;
3027 tc_stat.commit_delayed = false;
3029 for (i = 0; i < TAG_COUNT; i++)
3031 int ret;
3033 if (TAGCACHE_IS_NUMERIC(i))
3034 continue;
3036 tc_stat.commit_step++;
3037 ret = build_index(i, &tch, tmpfd);
3038 if (ret <= 0)
3040 close(tmpfd);
3041 logf("tagcache failed init");
3042 if (ret == 0)
3043 tc_stat.commit_delayed = true;
3045 tc_stat.commit_step = 0;
3046 read_lock--;
3047 return false;
3051 if (!build_numeric_indices(&tch, tmpfd))
3053 logf("Failure to commit numeric indices");
3054 close(tmpfd);
3055 tc_stat.commit_step = 0;
3056 read_lock--;
3057 return false;
3060 close(tmpfd);
3062 tc_stat.commit_step = 0;
3064 /* Update the master index headers. */
3065 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
3067 read_lock--;
3068 return false;
3071 remove(TAGCACHE_FILE_TEMP);
3073 tcmh.tch.entry_count += tch.entry_count;
3074 tcmh.tch.datasize = sizeof(struct master_header)
3075 + sizeof(struct index_entry) * tcmh.tch.entry_count
3076 + tch.datasize;
3077 tcmh.dirty = false;
3078 tcmh.commitid++;
3080 lseek(masterfd, 0, SEEK_SET);
3081 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
3082 close(masterfd);
3084 logf("tagcache committed");
3085 tc_stat.ready = check_all_headers();
3086 tc_stat.readyvalid = true;
3088 if (local_allocation)
3090 tempbuf = NULL;
3091 tempbuf_size = 0;
3094 #ifdef HAVE_DIRCACHE
3095 /* Rebuild the dircache, if we stole the buffer. */
3096 if (dircache_buffer_stolen)
3097 dircache_build(0);
3098 #endif
3100 #ifdef HAVE_TC_RAMCACHE
3101 /* Reload tagcache. */
3102 if (tc_stat.ramcache_allocated > 0)
3103 tagcache_start_scan();
3104 #endif
3106 read_lock--;
3108 return true;
3111 static void allocate_tempbuf(void)
3113 /* Yeah, malloc would be really nice now :) */
3114 #ifdef __PCTOOL__
3115 tempbuf_size = 32*1024*1024;
3116 tempbuf = malloc(tempbuf_size);
3117 #else
3118 buffer_get_buffer(&tempbuf_size);
3119 #endif
3122 static void free_tempbuf(void)
3124 if (tempbuf_size == 0)
3125 return ;
3127 #ifdef __PCTOOL__
3128 free(tempbuf);
3129 #else
3130 buffer_release_buffer(0);
3131 #endif
3132 tempbuf = NULL;
3133 tempbuf_size = 0;
3136 #ifndef __PCTOOL__
3138 static bool modify_numeric_entry(int masterfd, int idx_id, int tag, long data)
3140 struct index_entry idx;
3142 if (!tc_stat.ready)
3143 return false;
3145 if (!TAGCACHE_IS_NUMERIC(tag))
3146 return false;
3148 if (!get_index(masterfd, idx_id, &idx, false))
3149 return false;
3151 idx.tag_seek[tag] = data;
3152 idx.flag |= FLAG_DIRTYNUM;
3154 return write_index(masterfd, idx_id, &idx);
3157 #if 0
3158 bool tagcache_modify_numeric_entry(struct tagcache_search *tcs,
3159 int tag, long data)
3161 struct master_header myhdr;
3163 if (tcs->masterfd < 0)
3165 if ( (tcs->masterfd = open_master_fd(&myhdr, true)) < 0)
3166 return false;
3169 return modify_numeric_entry(tcs->masterfd, tcs->idx_id, tag, data);
3171 #endif
3173 static bool command_queue_is_full(void)
3175 int next;
3177 next = command_queue_widx + 1;
3178 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3179 next = 0;
3181 return (next == command_queue_ridx);
3184 static void command_queue_sync_callback(void *data)
3186 (void)data;
3187 struct master_header myhdr;
3188 int masterfd;
3190 mutex_lock(&command_queue_mutex);
3192 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3193 return;
3195 while (command_queue_ridx != command_queue_widx)
3197 struct tagcache_command_entry *ce = &command_queue[command_queue_ridx];
3199 switch (ce->command)
3201 case CMD_UPDATE_MASTER_HEADER:
3203 close(masterfd);
3204 update_master_header();
3206 /* Re-open the masterfd. */
3207 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3208 return;
3210 break;
3212 case CMD_UPDATE_NUMERIC:
3214 modify_numeric_entry(masterfd, ce->idx_id, ce->tag, ce->data);
3215 break;
3219 if (++command_queue_ridx >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3220 command_queue_ridx = 0;
3223 close(masterfd);
3225 tc_stat.queue_length = 0;
3226 mutex_unlock(&command_queue_mutex);
3229 static void run_command_queue(bool force)
3231 if (COMMAND_QUEUE_IS_EMPTY)
3232 return;
3234 if (force || command_queue_is_full())
3235 command_queue_sync_callback(NULL);
3236 else
3237 register_storage_idle_func(command_queue_sync_callback);
3240 static void queue_command(int cmd, long idx_id, int tag, long data)
3242 while (1)
3244 int next;
3246 mutex_lock(&command_queue_mutex);
3247 next = command_queue_widx + 1;
3248 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3249 next = 0;
3251 /* Make sure queue is not full. */
3252 if (next != command_queue_ridx)
3254 struct tagcache_command_entry *ce = &command_queue[command_queue_widx];
3256 ce->command = cmd;
3257 ce->idx_id = idx_id;
3258 ce->tag = tag;
3259 ce->data = data;
3261 command_queue_widx = next;
3263 tc_stat.queue_length++;
3265 mutex_unlock(&command_queue_mutex);
3266 break;
3269 /* Queue is full, try again later... */
3270 mutex_unlock(&command_queue_mutex);
3271 sleep(1);
3275 long tagcache_increase_serial(void)
3277 long old;
3279 if (!tc_stat.ready)
3280 return -2;
3282 while (read_lock)
3283 sleep(1);
3285 old = current_tcmh.serial++;
3286 queue_command(CMD_UPDATE_MASTER_HEADER, 0, 0, 0);
3288 return old;
3291 void tagcache_update_numeric(int idx_id, int tag, long data)
3293 queue_command(CMD_UPDATE_NUMERIC, idx_id, tag, data);
3295 #endif /* !__PCTOOL__ */
3297 long tagcache_get_serial(void)
3299 return current_tcmh.serial;
3302 long tagcache_get_commitid(void)
3304 return current_tcmh.commitid;
3307 static bool write_tag(int fd, const char *tagstr, const char *datastr)
3309 char buf[512];
3310 int i;
3312 snprintf(buf, sizeof buf, "%s=\"", tagstr);
3313 for (i = strlen(buf); i < (long)sizeof(buf)-4; i++)
3315 if (*datastr == '\0')
3316 break;
3318 if (*datastr == '"' || *datastr == '\\')
3319 buf[i++] = '\\';
3321 buf[i] = *(datastr++);
3324 strcpy(&buf[i], "\" ");
3326 write(fd, buf, i + 2);
3328 return true;
3331 #ifndef __PCTOOL__
3333 static bool read_tag(char *dest, long size,
3334 const char *src, const char *tagstr)
3336 int pos;
3337 char current_tag[32];
3339 while (*src != '\0')
3341 /* Skip all whitespace */
3342 while (*src == ' ')
3343 src++;
3345 if (*src == '\0')
3346 break;
3348 pos = 0;
3349 /* Read in tag name */
3350 while (*src != '=' && *src != ' ')
3352 current_tag[pos] = *src;
3353 src++;
3354 pos++;
3356 if (*src == '\0' || pos >= (long)sizeof(current_tag))
3357 return false;
3359 current_tag[pos] = '\0';
3361 /* Read in tag data */
3363 /* Find the start. */
3364 while (*src != '"' && *src != '\0')
3365 src++;
3367 if (*src == '\0' || *(++src) == '\0')
3368 return false;
3370 /* Read the data. */
3371 for (pos = 0; pos < size; pos++)
3373 if (*src == '\0')
3374 break;
3376 if (*src == '\\')
3378 dest[pos] = *(src+1);
3379 src += 2;
3380 continue;
3383 dest[pos] = *src;
3385 if (*src == '"')
3387 src++;
3388 break;
3391 if (*src == '\0')
3392 break;
3394 src++;
3396 dest[pos] = '\0';
3398 if (!strcasecmp(tagstr, current_tag))
3399 return true;
3402 return false;
3405 static int parse_changelog_line(int line_n, const char *buf, void *parameters)
3407 struct index_entry idx;
3408 char tag_data[TAG_MAXLEN+32];
3409 int idx_id;
3410 long masterfd = (long)parameters;
3411 const int import_tags[] = { tag_playcount, tag_rating, tag_playtime,
3412 tag_lastplayed, tag_commitid, tag_lastoffset };
3413 int i;
3414 (void)line_n;
3416 if (*buf == '#')
3417 return 0;
3419 logf("%d/%s", line_n, buf);
3420 if (!read_tag(tag_data, sizeof tag_data, buf, "filename"))
3422 logf("filename missing");
3423 logf("-> %s", buf);
3424 return 0;
3427 idx_id = find_index(tag_data);
3428 if (idx_id < 0)
3430 logf("entry not found");
3431 return 0;
3434 if (!get_index(masterfd, idx_id, &idx, false))
3436 logf("failed to retrieve index entry");
3437 return 0;
3440 /* Stop if tag has already been modified. */
3441 if (idx.flag & FLAG_DIRTYNUM)
3442 return 0;
3444 logf("import: %s", tag_data);
3446 idx.flag |= FLAG_DIRTYNUM;
3447 for (i = 0; i < (long)(sizeof(import_tags)/sizeof(import_tags[0])); i++)
3449 int data;
3451 if (!read_tag(tag_data, sizeof tag_data, buf,
3452 tagcache_tag_to_str(import_tags[i])))
3454 continue;
3457 data = atoi(tag_data);
3458 if (data < 0)
3459 continue;
3461 idx.tag_seek[import_tags[i]] = data;
3463 if (import_tags[i] == tag_lastplayed && data >= current_tcmh.serial)
3464 current_tcmh.serial = data + 1;
3465 else if (import_tags[i] == tag_commitid && data >= current_tcmh.commitid)
3466 current_tcmh.commitid = data + 1;
3469 return write_index(masterfd, idx_id, &idx) ? 0 : -5;
3472 bool tagcache_import_changelog(void)
3474 struct master_header myhdr;
3475 struct tagcache_header tch;
3476 int clfd;
3477 long masterfd;
3478 char buf[2048];
3480 if (!tc_stat.ready)
3481 return false;
3483 while (read_lock)
3484 sleep(1);
3486 clfd = open(TAGCACHE_FILE_CHANGELOG, O_RDONLY);
3487 if (clfd < 0)
3489 logf("failure to open changelog");
3490 return false;
3493 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3495 close(clfd);
3496 return false;
3499 write_lock++;
3501 filenametag_fd = open_tag_fd(&tch, tag_filename, false);
3503 fast_readline(clfd, buf, sizeof buf, (long *)masterfd,
3504 parse_changelog_line);
3506 close(clfd);
3507 close(masterfd);
3509 if (filenametag_fd >= 0)
3511 close(filenametag_fd);
3512 filenametag_fd = -1;
3515 write_lock--;
3517 update_master_header();
3519 return true;
3522 #endif /* !__PCTOOL__ */
3524 bool tagcache_create_changelog(struct tagcache_search *tcs)
3526 struct master_header myhdr;
3527 struct index_entry idx;
3528 char buf[TAG_MAXLEN+32];
3529 char temp[32];
3530 int clfd;
3531 int i, j;
3533 if (!tc_stat.ready)
3534 return false;
3536 if (!tagcache_search(tcs, tag_filename))
3537 return false;
3539 /* Initialize the changelog */
3540 clfd = open(TAGCACHE_FILE_CHANGELOG, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3541 if (clfd < 0)
3543 logf("failure to open changelog");
3544 return false;
3547 if (tcs->masterfd < 0)
3549 if ( (tcs->masterfd = open_master_fd(&myhdr, false)) < 0)
3550 return false;
3552 else
3554 lseek(tcs->masterfd, 0, SEEK_SET);
3555 ecread(tcs->masterfd, &myhdr, 1, master_header_ec, tc_stat.econ);
3558 write(clfd, "## Changelog version 1\n", 23);
3560 for (i = 0; i < myhdr.tch.entry_count; i++)
3562 if (ecread_index_entry(tcs->masterfd, &idx) != sizeof(struct index_entry))
3564 logf("read error #9");
3565 tagcache_search_finish(tcs);
3566 close(clfd);
3567 return false;
3570 /* Skip until the entry found has been modified. */
3571 if (! (idx.flag & FLAG_DIRTYNUM) )
3572 continue;
3574 /* Skip deleted entries too. */
3575 if (idx.flag & FLAG_DELETED)
3576 continue;
3578 /* Now retrieve all tags. */
3579 for (j = 0; j < TAG_COUNT; j++)
3581 if (TAGCACHE_IS_NUMERIC(j))
3583 snprintf(temp, sizeof temp, "%d", (int)idx.tag_seek[j]);
3584 write_tag(clfd, tagcache_tag_to_str(j), temp);
3585 continue;
3588 tcs->type = j;
3589 tagcache_retrieve(tcs, i, tcs->type, buf, sizeof buf);
3590 write_tag(clfd, tagcache_tag_to_str(j), buf);
3593 write(clfd, "\n", 1);
3594 do_timed_yield();
3597 close(clfd);
3599 tagcache_search_finish(tcs);
3601 return true;
3604 static bool delete_entry(long idx_id)
3606 int fd = -1;
3607 int masterfd = -1;
3608 int tag, i;
3609 struct index_entry idx, myidx;
3610 struct master_header myhdr;
3611 char buf[TAG_MAXLEN+32];
3612 int in_use[TAG_COUNT];
3614 logf("delete_entry(): %ld", idx_id);
3616 #ifdef HAVE_TC_RAMCACHE
3617 /* At first mark the entry removed from ram cache. */
3618 if (tc_stat.ramcache)
3619 hdr->indices[idx_id].flag |= FLAG_DELETED;
3620 #endif
3622 if ( (masterfd = open_master_fd(&myhdr, true) ) < 0)
3623 return false;
3625 lseek(masterfd, idx_id * sizeof(struct index_entry), SEEK_CUR);
3626 if (ecread_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3628 logf("delete_entry(): read error");
3629 goto cleanup;
3632 if (myidx.flag & FLAG_DELETED)
3634 logf("delete_entry(): already deleted!");
3635 goto cleanup;
3638 myidx.flag |= FLAG_DELETED;
3639 lseek(masterfd, -sizeof(struct index_entry), SEEK_CUR);
3640 if (ecwrite_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3642 logf("delete_entry(): write_error #1");
3643 goto cleanup;
3646 /* Now check which tags are no longer in use (if any) */
3647 for (tag = 0; tag < TAG_COUNT; tag++)
3648 in_use[tag] = 0;
3650 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
3651 for (i = 0; i < myhdr.tch.entry_count; i++)
3653 struct index_entry *idxp;
3655 #ifdef HAVE_TC_RAMCACHE
3656 /* Use RAM DB if available for greater speed */
3657 if (tc_stat.ramcache)
3658 idxp = &hdr->indices[i];
3659 else
3660 #endif
3662 if (ecread_index_entry(masterfd, &idx) != sizeof(struct index_entry))
3664 logf("delete_entry(): read error #2");
3665 goto cleanup;
3667 idxp = &idx;
3670 if (idxp->flag & FLAG_DELETED)
3671 continue;
3673 for (tag = 0; tag < TAG_COUNT; tag++)
3675 if (TAGCACHE_IS_NUMERIC(tag))
3676 continue;
3678 if (idxp->tag_seek[tag] == myidx.tag_seek[tag])
3679 in_use[tag]++;
3683 /* Now delete all tags no longer in use. */
3684 for (tag = 0; tag < TAG_COUNT; tag++)
3686 struct tagcache_header tch;
3687 int oldseek = myidx.tag_seek[tag];
3689 if (TAGCACHE_IS_NUMERIC(tag))
3690 continue;
3692 /**
3693 * Replace tag seek with a hash value of the field string data.
3694 * That way runtime statistics of moved or altered files can be
3695 * resurrected.
3697 #ifdef HAVE_TC_RAMCACHE
3698 if (tc_stat.ramcache && tag != tag_filename)
3700 struct tagfile_entry *tfe;
3701 int32_t *seek = &hdr->indices[idx_id].tag_seek[tag];
3703 tfe = (struct tagfile_entry *)&hdr->tags[tag][*seek];
3704 *seek = crc_32(tfe->tag_data, strlen(tfe->tag_data), 0xffffffff);
3705 myidx.tag_seek[tag] = *seek;
3707 else
3708 #endif
3710 struct tagfile_entry tfe;
3712 /* Open the index file, which contains the tag names. */
3713 if ((fd = open_tag_fd(&tch, tag, true)) < 0)
3714 goto cleanup;
3716 /* Skip the header block */
3717 lseek(fd, myidx.tag_seek[tag], SEEK_SET);
3718 if (ecread_tagfile_entry(fd, &tfe) != sizeof(struct tagfile_entry))
3720 logf("delete_entry(): read error #3");
3721 goto cleanup;
3724 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
3726 logf("delete_entry(): read error #4");
3727 goto cleanup;
3730 myidx.tag_seek[tag] = crc_32(buf, strlen(buf), 0xffffffff);
3733 if (in_use[tag])
3735 logf("in use: %d/%d", tag, in_use[tag]);
3736 if (fd >= 0)
3738 close(fd);
3739 fd = -1;
3741 continue;
3744 #ifdef HAVE_TC_RAMCACHE
3745 /* Delete from ram. */
3746 if (tc_stat.ramcache && tag != tag_filename)
3748 struct tagfile_entry *tagentry = (struct tagfile_entry *)&hdr->tags[tag][oldseek];
3749 tagentry->tag_data[0] = '\0';
3751 #endif
3753 /* Open the index file, which contains the tag names. */
3754 if (fd < 0)
3756 if ((fd = open_tag_fd(&tch, tag, true)) < 0)
3757 goto cleanup;
3760 /* Skip the header block */
3761 lseek(fd, oldseek + sizeof(struct tagfile_entry), SEEK_SET);
3763 /* Debug, print 10 first characters of the tag
3764 read(fd, buf, 10);
3765 buf[10]='\0';
3766 logf("TAG:%s", buf);
3767 lseek(fd, -10, SEEK_CUR);
3770 /* Write first data byte in tag as \0 */
3771 write(fd, "", 1);
3773 /* Now tag data has been removed */
3774 close(fd);
3775 fd = -1;
3778 /* Write index entry back into master index. */
3779 lseek(masterfd, sizeof(struct master_header) +
3780 (idx_id * sizeof(struct index_entry)), SEEK_SET);
3781 if (ecwrite_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3783 logf("delete_entry(): write_error #2");
3784 goto cleanup;
3787 close(masterfd);
3789 return true;
3791 cleanup:
3792 if (fd >= 0)
3793 close(fd);
3794 if (masterfd >= 0)
3795 close(masterfd);
3797 return false;
3800 #ifndef __PCTOOL__
3802 * Returns true if there is an event waiting in the queue
3803 * that requires the current operation to be aborted.
3805 static bool check_event_queue(void)
3807 struct queue_event ev;
3809 if(!queue_peek(&tagcache_queue, &ev))
3810 return false;
3812 switch (ev.id)
3814 case Q_STOP_SCAN:
3815 case SYS_POWEROFF:
3816 case SYS_USB_CONNECTED:
3817 return true;
3820 return false;
3822 #endif
3824 #ifdef HAVE_TC_RAMCACHE
3825 static bool allocate_tagcache(void)
3827 struct master_header tcmh;
3828 int fd;
3830 /* Load the header. */
3831 if ( (fd = open_master_fd(&tcmh, false)) < 0)
3833 hdr = NULL;
3834 return false;
3837 close(fd);
3839 /**
3840 * Now calculate the required cache size plus
3841 * some extra space for alignment fixes.
3843 tc_stat.ramcache_allocated = tcmh.tch.datasize + 128 + TAGCACHE_RESERVE +
3844 sizeof(struct ramcache_header) + TAG_COUNT*sizeof(void *);
3845 hdr = buffer_alloc(tc_stat.ramcache_allocated + 128);
3846 memset(hdr, 0, sizeof(struct ramcache_header));
3847 memcpy(&hdr->h, &tcmh, sizeof(struct master_header));
3848 hdr->indices = (struct index_entry *)(hdr + 1);
3849 logf("tagcache: %d bytes allocated.", tc_stat.ramcache_allocated);
3851 return true;
3854 # ifdef HAVE_EEPROM_SETTINGS
3855 static bool tagcache_dumpload(void)
3857 struct statefile_header shdr;
3858 int fd, rc;
3859 long offpos;
3860 int i;
3862 fd = open(TAGCACHE_STATEFILE, O_RDONLY);
3863 if (fd < 0)
3865 logf("no tagcache statedump");
3866 return false;
3869 /* Check the statefile memory placement */
3870 hdr = buffer_alloc(0);
3871 rc = read(fd, &shdr, sizeof(struct statefile_header));
3872 if (rc != sizeof(struct statefile_header)
3873 /* || (long)hdr != (long)shdr.hdr */)
3875 logf("incorrect statefile");
3876 hdr = NULL;
3877 close(fd);
3878 return false;
3881 offpos = (long)hdr - (long)shdr.hdr;
3883 /* Lets allocate real memory and load it */
3884 hdr = buffer_alloc(shdr.tc_stat.ramcache_allocated);
3885 rc = read(fd, hdr, shdr.tc_stat.ramcache_allocated);
3886 close(fd);
3888 if (rc != shdr.tc_stat.ramcache_allocated)
3890 logf("read failure!");
3891 hdr = NULL;
3892 return false;
3895 memcpy(&tc_stat, &shdr.tc_stat, sizeof(struct tagcache_stat));
3897 /* Now fix the pointers */
3898 hdr->indices = (struct index_entry *)((long)hdr->indices + offpos);
3899 for (i = 0; i < TAG_COUNT; i++)
3900 hdr->tags[i] += offpos;
3902 return true;
3905 static bool tagcache_dumpsave(void)
3907 struct statefile_header shdr;
3908 int fd;
3910 if (!tc_stat.ramcache)
3911 return false;
3913 fd = open(TAGCACHE_STATEFILE, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3914 if (fd < 0)
3916 logf("failed to create a statedump");
3917 return false;
3920 /* Create the header */
3921 shdr.hdr = hdr;
3922 memcpy(&shdr.tc_stat, &tc_stat, sizeof(struct tagcache_stat));
3923 write(fd, &shdr, sizeof(struct statefile_header));
3925 /* And dump the data too */
3926 write(fd, hdr, tc_stat.ramcache_allocated);
3927 close(fd);
3929 return true;
3931 # endif
3933 static bool load_tagcache(void)
3935 struct tagcache_header *tch;
3936 long bytesleft = tc_stat.ramcache_allocated;
3937 struct index_entry *idx;
3938 int rc, fd;
3939 char *p;
3940 int i, tag;
3942 # ifdef HAVE_DIRCACHE
3943 while (dircache_is_initializing())
3944 sleep(1);
3946 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE);
3947 # endif
3949 logf("loading tagcache to ram...");
3951 fd = open(TAGCACHE_FILE_MASTER, O_RDONLY);
3952 if (fd < 0)
3954 logf("tagcache open failed");
3955 return false;
3958 if (ecread(fd, &hdr->h, 1, master_header_ec, tc_stat.econ)
3959 != sizeof(struct master_header)
3960 || hdr->h.tch.magic != TAGCACHE_MAGIC)
3962 logf("incorrect header");
3963 return false;
3966 idx = hdr->indices;
3968 /* Load the master index table. */
3969 for (i = 0; i < hdr->h.tch.entry_count; i++)
3971 rc = ecread_index_entry(fd, idx);
3972 if (rc != sizeof(struct index_entry))
3974 logf("read error #10");
3975 close(fd);
3976 return false;
3979 bytesleft -= sizeof(struct index_entry);
3980 if (bytesleft < 0 || ((long)idx - (long)hdr->indices) >= tc_stat.ramcache_allocated)
3982 logf("too big tagcache.");
3983 close(fd);
3984 return false;
3987 idx++;
3990 close(fd);
3992 /* Load the tags. */
3993 p = (char *)idx;
3994 for (tag = 0; tag < TAG_COUNT; tag++)
3996 struct tagfile_entry *fe;
3997 char buf[TAG_MAXLEN+32];
3999 if (TAGCACHE_IS_NUMERIC(tag))
4000 continue ;
4002 //p = ((void *)p+1);
4003 p = (char *)((long)p & ~0x03) + 0x04;
4004 hdr->tags[tag] = p;
4006 /* Check the header. */
4007 tch = (struct tagcache_header *)p;
4008 p += sizeof(struct tagcache_header);
4010 if ( (fd = open_tag_fd(tch, tag, false)) < 0)
4011 return false;
4013 for (hdr->entry_count[tag] = 0;
4014 hdr->entry_count[tag] < tch->entry_count;
4015 hdr->entry_count[tag]++)
4017 long pos;
4019 if (do_timed_yield())
4021 /* Abort if we got a critical event in queue */
4022 if (check_event_queue())
4023 return false;
4026 fe = (struct tagfile_entry *)p;
4027 pos = lseek(fd, 0, SEEK_CUR);
4028 rc = ecread_tagfile_entry(fd, fe);
4029 if (rc != sizeof(struct tagfile_entry))
4031 /* End of lookup table. */
4032 logf("read error #11");
4033 close(fd);
4034 return false;
4037 /* We have a special handling for the filename tags. */
4038 if (tag == tag_filename)
4040 # ifdef HAVE_DIRCACHE
4041 const struct dircache_entry *dc;
4042 # endif
4044 // FIXME: This is wrong!
4045 // idx = &hdr->indices[hdr->entry_count[i]];
4046 idx = &hdr->indices[fe->idx_id];
4048 if (fe->tag_length >= (long)sizeof(buf)-1)
4050 read(fd, buf, 10);
4051 buf[10] = '\0';
4052 logf("TAG:%s", buf);
4053 logf("too long filename");
4054 close(fd);
4055 return false;
4058 rc = read(fd, buf, fe->tag_length);
4059 if (rc != fe->tag_length)
4061 logf("read error #12");
4062 close(fd);
4063 return false;
4066 /* Check if the entry has already been removed */
4067 if (idx->flag & FLAG_DELETED)
4068 continue;
4070 /* This flag must not be used yet. */
4071 if (idx->flag & FLAG_DIRCACHE)
4073 logf("internal error!");
4074 close(fd);
4075 return false;
4078 if (idx->tag_seek[tag] != pos)
4080 logf("corrupt data structures!");
4081 close(fd);
4082 return false;
4085 # ifdef HAVE_DIRCACHE
4086 if (dircache_is_enabled())
4088 dc = dircache_get_entry_ptr(buf);
4089 if (dc == NULL)
4091 logf("Entry no longer valid.");
4092 logf("-> %s", buf);
4093 if (global_settings.tagcache_autoupdate)
4094 delete_entry(fe->idx_id);
4095 continue ;
4098 idx->flag |= FLAG_DIRCACHE;
4099 idx->tag_seek[tag_filename] = (long)dc;
4101 else
4102 # endif
4104 /* This will be very slow unless dircache is enabled
4105 or target is flash based, but do it anyway for
4106 consistency. */
4107 /* Check if entry has been removed. */
4108 if (global_settings.tagcache_autoupdate)
4110 if (!file_exists(buf))
4112 logf("Entry no longer valid.");
4113 logf("-> %s", buf);
4114 delete_entry(fe->idx_id);
4115 continue;
4120 continue ;
4123 bytesleft -= sizeof(struct tagfile_entry) + fe->tag_length;
4124 if (bytesleft < 0)
4126 logf("too big tagcache #2");
4127 logf("tl: %ld", fe->tag_length);
4128 logf("bl: %ld", bytesleft);
4129 close(fd);
4130 return false;
4133 p = fe->tag_data;
4134 rc = read(fd, fe->tag_data, fe->tag_length);
4135 p += rc;
4137 if (rc != fe->tag_length)
4139 logf("read error #13");
4140 logf("rc=0x%04x", rc); // 0x431
4141 logf("len=0x%04lx", fe->tag_length); // 0x4000
4142 logf("pos=0x%04lx", lseek(fd, 0, SEEK_CUR)); // 0x433
4143 logf("tag=0x%02x", tag); // 0x00
4144 close(fd);
4145 return false;
4148 close(fd);
4151 tc_stat.ramcache_used = tc_stat.ramcache_allocated - bytesleft;
4152 logf("tagcache loaded into ram!");
4154 return true;
4156 #endif /* HAVE_TC_RAMCACHE */
4158 static bool check_deleted_files(void)
4160 int fd;
4161 char buf[TAG_MAXLEN+32];
4162 struct tagfile_entry tfe;
4164 logf("reverse scan...");
4165 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag_filename);
4166 fd = open(buf, O_RDONLY);
4168 if (fd < 0)
4170 logf("%s open fail", buf);
4171 return false;
4174 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
4175 while (ecread_tagfile_entry(fd, &tfe) == sizeof(struct tagfile_entry)
4176 #ifndef __PCTOOL__
4177 && !check_event_queue()
4178 #endif
4181 if (tfe.tag_length >= (long)sizeof(buf)-1)
4183 logf("too long tag");
4184 close(fd);
4185 return false;
4188 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
4190 logf("read error #14");
4191 close(fd);
4192 return false;
4195 /* Check if the file has already deleted from the db. */
4196 if (*buf == '\0')
4197 continue;
4199 /* Now check if the file exists. */
4200 if (!file_exists(buf))
4202 logf("Entry no longer valid.");
4203 logf("-> %s / %ld", buf, tfe.tag_length);
4204 delete_entry(tfe.idx_id);
4208 close(fd);
4210 logf("done");
4212 return true;
4216 /* Note that this function must not be inlined, otherwise the whole point
4217 * of having the code in a separate function is lost.
4219 static void __attribute__ ((noinline)) check_ignore(const char *dirname,
4220 int *ignore, int *unignore)
4222 char newpath[MAX_PATH];
4224 /* check for a database.ignore file */
4225 snprintf(newpath, MAX_PATH, "%s/database.ignore", dirname);
4226 *ignore = file_exists(newpath);
4227 /* check for a database.unignore file */
4228 snprintf(newpath, MAX_PATH, "%s/database.unignore", dirname);
4229 *unignore = file_exists(newpath);
4232 static struct search_roots_ll {
4233 const char *path;
4234 struct search_roots_ll * next;
4235 } roots_ll;
4237 #ifdef APPLICATION
4239 * This adds a path to the search roots, possibly during traveling through
4240 * the filesystem. It only adds if the path is not inside an already existing
4241 * search root.
4243 * Returns true if it added the path to the search roots
4245 * Windows 2000 and greater supports symlinks, but they don't provide
4246 * realpath() or readlink(), and symlinks are rarely used on them so
4247 * ignore this for windows for now
4249 static bool add_search_root(const char *name)
4251 (void)name;
4252 #ifndef WIN32
4253 struct search_roots_ll *this, *prev = NULL;
4254 char target[MAX_PATH];
4255 /* Okay, realpath() is almost completely broken on android
4257 * It doesn't accept NULL for resolved_name to dynamically allocate
4258 * the resulting path; and it assumes resolved_name to be PATH_MAX
4259 * (actually MAXPATHLEN, but it's the same [as of 2.3]) long
4260 * and blindly writes to the end if it
4262 * therefore use sufficiently large static storage here
4263 * Note that PATH_MAX != MAX_PATH
4265 static char abs_target[PATH_MAX];
4266 ssize_t len;
4268 len = readlink(name, target, sizeof(target));
4269 if (len < 0)
4270 return false;
4272 target[len] = '\0';
4273 if (realpath(target, abs_target) == NULL)
4274 return false;
4276 for(this = &roots_ll; this; prev = this, this = this->next)
4278 size_t root_len = strlen(this->path);
4279 /* check if the link target is inside of an existing search root
4280 * don't add if target is inside, we'll scan it later */
4281 if (!strncmp(this->path, abs_target, root_len))
4282 return false;
4285 if (prev)
4287 size_t len = strlen(abs_target) + 1; /* count \0 */
4288 this = malloc(sizeof(struct search_roots_ll) + len );
4289 if (!this || len > MAX_PATH)
4291 logf("Error at adding a search root: %s", this ? "path too long":"OOM");
4292 free(this);
4293 prev->next = NULL;
4294 return false;
4296 this->path = ((char*)this) + sizeof(struct search_roots_ll);
4297 strcpy((char*)this->path, abs_target); /* ok to cast const away here */
4298 this->next = NULL;
4299 prev->next = this;
4300 logf("Added %s to the search roots\n", abs_target);
4301 return true;
4303 #endif
4304 return false;
4307 static int free_search_roots(struct search_roots_ll * start)
4309 int ret = 0;
4310 if (start->next)
4312 ret += free_search_roots(start->next);
4313 ret += sizeof(struct search_roots_ll);
4314 free(start->next);
4316 return ret;
4318 #else /* native, simulator */
4319 #define add_search_root(a) do {} while(0)
4320 #define free_search_roots(a) do {} while(0)
4321 #endif
4323 static bool check_dir(const char *dirname, int add_files)
4325 DIR *dir;
4326 int len;
4327 int success = false;
4328 int ignore, unignore;
4330 dir = opendir(dirname);
4331 if (!dir)
4333 logf("tagcache: opendir(%s) failed", dirname);
4334 return false;
4336 /* check for a database.ignore and database.unignore */
4337 check_ignore(dirname, &ignore, &unignore);
4339 /* don't do anything if both ignore and unignore are there */
4340 if (ignore != unignore)
4341 add_files = unignore;
4343 /* Recursively scan the dir. */
4344 #ifdef __PCTOOL__
4345 while (1)
4346 #else
4347 while (!check_event_queue())
4348 #endif
4350 struct dirent *entry = readdir(dir);
4351 if (entry == NULL)
4353 success = true;
4354 break;
4357 if (!strcmp((char *)entry->d_name, ".") ||
4358 !strcmp((char *)entry->d_name, ".."))
4359 continue;
4361 struct dirinfo info = dir_get_info(dir, entry);
4363 yield();
4365 len = strlen(curpath);
4366 /* don't add an extra / for curpath == / */
4367 if (len <= 1) len = 0;
4368 snprintf(&curpath[len], sizeof(curpath) - len, "/%s", entry->d_name);
4370 processed_dir_count++;
4371 if (info.attribute & ATTR_DIRECTORY)
4372 #ifndef SIMULATOR
4373 { /* don't follow symlinks to dirs, but try to add it as a search root
4374 * this makes able to avoid looping in recursive symlinks */
4375 if (info.attribute & ATTR_LINK)
4376 add_search_root(curpath);
4377 else
4378 check_dir(curpath, add_files);
4380 #else
4381 check_dir(curpath, add_files);
4382 #endif
4383 else if (add_files)
4385 tc_stat.curentry = curpath;
4387 /* Add a new entry to the temporary db file. */
4388 add_tagcache(curpath, (info.wrtdate << 16) | info.wrttime
4389 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4390 , dir->internal_entry
4391 #endif
4394 /* Wait until current path for debug screen is read and unset. */
4395 while (tc_stat.syncscreen && tc_stat.curentry != NULL)
4396 yield();
4398 tc_stat.curentry = NULL;
4401 curpath[len] = '\0';
4404 closedir(dir);
4406 return success;
4409 void tagcache_screensync_event(void)
4411 tc_stat.curentry = NULL;
4414 void tagcache_screensync_enable(bool state)
4416 tc_stat.syncscreen = state;
4419 void tagcache_build(const char *path)
4421 struct tagcache_header header;
4422 bool ret;
4424 curpath[0] = '\0';
4425 data_size = 0;
4426 total_entry_count = 0;
4427 processed_dir_count = 0;
4429 #ifdef HAVE_DIRCACHE
4430 while (dircache_is_initializing())
4431 sleep(1);
4432 #endif
4434 logf("updating tagcache");
4436 cachefd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
4437 if (cachefd >= 0)
4439 logf("skipping, cache already waiting for commit");
4440 close(cachefd);
4441 return ;
4444 cachefd = open(TAGCACHE_FILE_TEMP, O_RDWR | O_CREAT | O_TRUNC, 0666);
4445 if (cachefd < 0)
4447 logf("master file open failed: %s", TAGCACHE_FILE_TEMP);
4448 return ;
4451 filenametag_fd = open_tag_fd(&header, tag_filename, false);
4453 cpu_boost(true);
4455 logf("Scanning files...");
4456 /* Scan for new files. */
4457 memset(&header, 0, sizeof(struct tagcache_header));
4458 write(cachefd, &header, sizeof(struct tagcache_header));
4460 ret = true;
4461 roots_ll.path = path;
4462 roots_ll.next = NULL;
4463 struct search_roots_ll * this;
4464 /* check_dir might add new roots */
4465 for(this = &roots_ll; this; this = this->next)
4467 strcpy(curpath, this->path);
4468 ret = ret && check_dir(this->path, true);
4470 if (roots_ll.next)
4471 free_search_roots(roots_ll.next);
4473 /* Write the header. */
4474 header.magic = TAGCACHE_MAGIC;
4475 header.datasize = data_size;
4476 header.entry_count = total_entry_count;
4477 lseek(cachefd, 0, SEEK_SET);
4478 write(cachefd, &header, sizeof(struct tagcache_header));
4479 close(cachefd);
4481 if (filenametag_fd >= 0)
4483 close(filenametag_fd);
4484 filenametag_fd = -1;
4487 if (!ret)
4489 logf("Aborted.");
4490 cpu_boost(false);
4491 return ;
4494 /* Commit changes to the database. */
4495 #ifdef __PCTOOL__
4496 allocate_tempbuf();
4497 #endif
4498 if (commit())
4500 logf("tagcache built!");
4502 #ifdef __PCTOOL__
4503 free_tempbuf();
4504 #endif
4506 #ifdef HAVE_TC_RAMCACHE
4507 if (hdr)
4509 /* Import runtime statistics if we just initialized the db. */
4510 if (hdr->h.serial == 0)
4511 queue_post(&tagcache_queue, Q_IMPORT_CHANGELOG, 0);
4513 #endif
4515 cpu_boost(false);
4518 #ifdef HAVE_TC_RAMCACHE
4519 static void load_ramcache(void)
4521 if (!hdr)
4522 return ;
4524 cpu_boost(true);
4526 /* At first we should load the cache (if exists). */
4527 tc_stat.ramcache = load_tagcache();
4529 if (!tc_stat.ramcache)
4531 /* If loading failed, it must indicate some problem with the db
4532 * so disable it entirely to prevent further issues. */
4533 tc_stat.ready = false;
4534 hdr = NULL;
4537 cpu_boost(false);
4540 void tagcache_unload_ramcache(void)
4542 tc_stat.ramcache = false;
4543 /* Just to make sure there is no statefile present. */
4544 // remove(TAGCACHE_STATEFILE);
4546 #endif
4548 #ifndef __PCTOOL__
4549 static void tagcache_thread(void)
4551 struct queue_event ev;
4552 bool check_done = false;
4554 /* If the previous cache build/update was interrupted, commit
4555 * the changes first in foreground. */
4556 cpu_boost(true);
4557 allocate_tempbuf();
4558 commit();
4559 free_tempbuf();
4561 #ifdef HAVE_TC_RAMCACHE
4562 # ifdef HAVE_EEPROM_SETTINGS
4563 if (firmware_settings.initialized && firmware_settings.disk_clean
4564 && global_settings.tagcache_ram)
4566 check_done = tagcache_dumpload();
4569 remove(TAGCACHE_STATEFILE);
4570 # endif
4572 /* Allocate space for the tagcache if found on disk. */
4573 if (global_settings.tagcache_ram && !tc_stat.ramcache)
4574 allocate_tagcache();
4575 #endif
4577 cpu_boost(false);
4578 tc_stat.initialized = true;
4580 /* Don't delay bootup with the header check but do it on background. */
4581 if (!tc_stat.ready)
4583 sleep(HZ);
4584 tc_stat.ready = check_all_headers();
4585 tc_stat.readyvalid = true;
4588 while (1)
4590 run_command_queue(false);
4592 queue_wait_w_tmo(&tagcache_queue, &ev, HZ);
4594 switch (ev.id)
4596 case Q_IMPORT_CHANGELOG:
4597 tagcache_import_changelog();
4598 break;
4600 case Q_REBUILD:
4601 remove_files();
4602 remove(TAGCACHE_FILE_TEMP);
4603 tagcache_build("/");
4604 break;
4606 case Q_UPDATE:
4607 tagcache_build("/");
4608 #ifdef HAVE_TC_RAMCACHE
4609 load_ramcache();
4610 #endif
4611 check_deleted_files();
4612 break ;
4614 case Q_START_SCAN:
4615 check_done = false;
4616 case SYS_TIMEOUT:
4617 if (check_done || !tc_stat.ready)
4618 break ;
4620 #ifdef HAVE_TC_RAMCACHE
4621 if (!tc_stat.ramcache && global_settings.tagcache_ram)
4623 load_ramcache();
4624 if (tc_stat.ramcache && global_settings.tagcache_autoupdate)
4625 tagcache_build("/");
4627 else
4628 #endif
4629 if (global_settings.tagcache_autoupdate)
4631 tagcache_build("/");
4633 /* This will be very slow unless dircache is enabled
4634 or target is flash based, but do it anyway for
4635 consistency. */
4636 check_deleted_files();
4639 logf("tagcache check done");
4641 check_done = true;
4642 break ;
4644 case Q_STOP_SCAN:
4645 break ;
4647 case SYS_POWEROFF:
4648 break ;
4650 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4651 case SYS_USB_CONNECTED:
4652 logf("USB: TagCache");
4653 usb_acknowledge(SYS_USB_CONNECTED_ACK);
4654 usb_wait_for_disconnect(&tagcache_queue);
4655 break ;
4656 #endif
4661 bool tagcache_prepare_shutdown(void)
4663 if (tagcache_get_commit_step() > 0)
4664 return false;
4666 tagcache_stop_scan();
4667 while (read_lock || write_lock)
4668 sleep(1);
4670 return true;
4673 void tagcache_shutdown(void)
4675 /* Flush the command queue. */
4676 run_command_queue(true);
4678 #ifdef HAVE_EEPROM_SETTINGS
4679 if (tc_stat.ramcache)
4680 tagcache_dumpsave();
4681 #endif
4684 static int get_progress(void)
4686 int total_count = -1;
4688 #ifdef HAVE_DIRCACHE
4689 if (dircache_is_enabled())
4691 total_count = dircache_get_entry_count();
4693 else
4694 #endif
4695 #ifdef HAVE_TC_RAMCACHE
4697 if (hdr && tc_stat.ramcache)
4698 total_count = hdr->h.tch.entry_count;
4700 #endif
4702 if (total_count < 0)
4703 return -1;
4705 return processed_dir_count * 100 / total_count;
4708 struct tagcache_stat* tagcache_get_stat(void)
4710 tc_stat.progress = get_progress();
4711 tc_stat.processed_entries = processed_dir_count;
4713 return &tc_stat;
4716 void tagcache_start_scan(void)
4718 queue_post(&tagcache_queue, Q_START_SCAN, 0);
4721 bool tagcache_update(void)
4723 if (!tc_stat.ready)
4724 return false;
4726 queue_post(&tagcache_queue, Q_UPDATE, 0);
4727 return false;
4730 bool tagcache_rebuild()
4732 queue_post(&tagcache_queue, Q_REBUILD, 0);
4733 return false;
4736 void tagcache_stop_scan(void)
4738 queue_post(&tagcache_queue, Q_STOP_SCAN, 0);
4741 #ifdef HAVE_TC_RAMCACHE
4742 bool tagcache_is_ramcache(void)
4744 return tc_stat.ramcache;
4746 #endif
4748 #endif /* !__PCTOOL__ */
4751 void tagcache_init(void)
4753 memset(&tc_stat, 0, sizeof(struct tagcache_stat));
4754 memset(&current_tcmh, 0, sizeof(struct master_header));
4755 filenametag_fd = -1;
4756 write_lock = read_lock = 0;
4758 #ifndef __PCTOOL__
4759 mutex_init(&command_queue_mutex);
4760 queue_init(&tagcache_queue, true);
4761 create_thread(tagcache_thread, tagcache_stack,
4762 sizeof(tagcache_stack), 0, tagcache_thread_name
4763 IF_PRIO(, PRIORITY_BACKGROUND)
4764 IF_COP(, CPU));
4765 #else
4766 tc_stat.initialized = true;
4767 allocate_tempbuf();
4768 commit();
4769 free_tempbuf();
4770 tc_stat.ready = check_all_headers();
4771 #endif
4774 #ifdef __PCTOOL__
4775 void tagcache_reverse_scan(void)
4777 logf("Checking for deleted files");
4778 check_deleted_files();
4780 #endif
4782 bool tagcache_is_initialized(void)
4784 return tc_stat.initialized;
4786 bool tagcache_is_fully_initialized(void)
4788 return tc_stat.readyvalid;
4790 bool tagcache_is_usable(void)
4792 return tc_stat.initialized && tc_stat.ready;
4794 int tagcache_get_commit_step(void)
4796 return tc_stat.commit_step;
4798 int tagcache_get_max_commit_step(void)
4800 return (int)(SORTED_TAGS_COUNT)+1;