Fix even more 'variable set but not used' warnings reported from GCC 4.6.0.
[kugel-rb.git] / apps / tagcache.c
blob75191d678e0fa055ee8b09c01ff33205b5c1e0b6
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 long 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 **clause, int count)
989 int i;
991 #ifdef HAVE_TC_RAMCACHE
992 if (tcs->ramsearch)
994 /* Go through all conditional clauses. */
995 for (i = 0; i < count; i++)
997 struct tagfile_entry *tfe;
998 int seek;
999 char buf[256];
1000 char *str = NULL;
1002 seek = check_virtual_tags(clause[i]->tag, tcs->idx_id, idx);
1004 if (!TAGCACHE_IS_NUMERIC(clause[i]->tag))
1006 if (clause[i]->tag == tag_filename)
1008 retrieve(tcs, idx, tag_filename, buf, sizeof buf);
1009 str = buf;
1011 else
1013 tfe = (struct tagfile_entry *)&hdr->tags[clause[i]->tag][seek];
1014 str = tfe->tag_data;
1018 if (!check_against_clause(seek, str, clause[i]))
1019 return false;
1022 else
1023 #endif
1025 /* Check for conditions. */
1026 for (i = 0; i < count; i++)
1028 struct tagfile_entry tfe;
1029 int seek;
1030 char str[256];
1032 seek = check_virtual_tags(clause[i]->tag, tcs->idx_id, idx);
1034 memset(str, 0, sizeof str);
1035 if (!TAGCACHE_IS_NUMERIC(clause[i]->tag))
1037 int fd = tcs->idxfd[clause[i]->tag];
1038 lseek(fd, seek, SEEK_SET);
1039 ecread_tagfile_entry(fd, &tfe);
1040 if (tfe.tag_length >= (int)sizeof(str))
1042 logf("Too long tag read!");
1043 break ;
1046 read(fd, str, tfe.tag_length);
1048 /* Check if entry has been deleted. */
1049 if (str[0] == '\0')
1050 break;
1053 if (!check_against_clause(seek, str, clause[i]))
1054 return false;
1058 return true;
1061 bool tagcache_check_clauses(struct tagcache_search *tcs,
1062 struct tagcache_search_clause **clause, int count)
1064 struct index_entry idx;
1066 if (count == 0)
1067 return true;
1069 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
1070 return false;
1072 return check_clauses(tcs, &idx, clause, count);
1075 static bool add_uniqbuf(struct tagcache_search *tcs, unsigned long id)
1077 int i;
1079 /* If uniq buffer is not defined we must return true for search to work. */
1080 if (tcs->unique_list == NULL || (!TAGCACHE_IS_UNIQUE(tcs->type)
1081 && !TAGCACHE_IS_NUMERIC(tcs->type)))
1083 return true;
1086 for (i = 0; i < tcs->unique_list_count; i++)
1088 /* Return false if entry is found. */
1089 if (tcs->unique_list[i] == id)
1090 return false;
1093 if (tcs->unique_list_count < tcs->unique_list_capacity)
1095 tcs->unique_list[i] = id;
1096 tcs->unique_list_count++;
1099 return true;
1102 static bool build_lookup_list(struct tagcache_search *tcs)
1104 struct index_entry entry;
1105 int i, j;
1107 tcs->seek_list_count = 0;
1109 #ifdef HAVE_TC_RAMCACHE
1110 if (tcs->ramsearch
1111 # ifdef HAVE_DIRCACHE
1112 && (tcs->type != tag_filename || is_dircache_intact())
1113 # endif
1116 for (i = tcs->seek_pos; i < hdr->h.tch.entry_count; i++)
1118 struct tagcache_seeklist_entry *seeklist;
1119 struct index_entry *idx = &hdr->indices[i];
1120 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1121 break ;
1123 /* Skip deleted files. */
1124 if (idx->flag & FLAG_DELETED)
1125 continue;
1127 /* Go through all filters.. */
1128 for (j = 0; j < tcs->filter_count; j++)
1130 if (idx->tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1132 break ;
1136 if (j < tcs->filter_count)
1137 continue ;
1139 /* Check for conditions. */
1140 if (!check_clauses(tcs, idx, tcs->clause, tcs->clause_count))
1141 continue;
1143 /* Add to the seek list if not already in uniq buffer. */
1144 if (!add_uniqbuf(tcs, idx->tag_seek[tcs->type]))
1145 continue;
1147 /* Lets add it. */
1148 seeklist = &tcs->seeklist[tcs->seek_list_count];
1149 seeklist->seek = idx->tag_seek[tcs->type];
1150 seeklist->flag = idx->flag;
1151 seeklist->idx_id = i;
1152 tcs->seek_list_count++;
1155 tcs->seek_pos = i;
1157 return tcs->seek_list_count > 0;
1159 #endif
1161 if (tcs->masterfd < 0)
1163 struct master_header tcmh;
1164 tcs->masterfd = open_master_fd(&tcmh, false);
1167 lseek(tcs->masterfd, tcs->seek_pos * sizeof(struct index_entry) +
1168 sizeof(struct master_header), SEEK_SET);
1170 while (ecread_index_entry(tcs->masterfd, &entry)
1171 == sizeof(struct index_entry))
1173 struct tagcache_seeklist_entry *seeklist;
1175 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1176 break ;
1178 i = tcs->seek_pos;
1179 tcs->seek_pos++;
1181 /* Check if entry has been deleted. */
1182 if (entry.flag & FLAG_DELETED)
1183 continue;
1185 /* Go through all filters.. */
1186 for (j = 0; j < tcs->filter_count; j++)
1188 if (entry.tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1189 break ;
1192 if (j < tcs->filter_count)
1193 continue ;
1195 /* Check for conditions. */
1196 if (!check_clauses(tcs, &entry, tcs->clause, tcs->clause_count))
1197 continue;
1199 /* Add to the seek list if not already in uniq buffer. */
1200 if (!add_uniqbuf(tcs, entry.tag_seek[tcs->type]))
1201 continue;
1203 /* Lets add it. */
1204 seeklist = &tcs->seeklist[tcs->seek_list_count];
1205 seeklist->seek = entry.tag_seek[tcs->type];
1206 seeklist->flag = entry.flag;
1207 seeklist->idx_id = i;
1208 tcs->seek_list_count++;
1210 yield();
1213 return tcs->seek_list_count > 0;
1217 static void remove_files(void)
1219 int i;
1220 char buf[MAX_PATH];
1222 tc_stat.ready = false;
1223 tc_stat.ramcache = false;
1224 tc_stat.econ = false;
1225 remove(TAGCACHE_FILE_MASTER);
1226 for (i = 0; i < TAG_COUNT; i++)
1228 if (TAGCACHE_IS_NUMERIC(i))
1229 continue;
1231 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, i);
1232 remove(buf);
1237 static bool check_all_headers(void)
1239 struct master_header myhdr;
1240 struct tagcache_header tch;
1241 int tag;
1242 int fd;
1244 if ( (fd = open_master_fd(&myhdr, false)) < 0)
1245 return false;
1247 close(fd);
1248 if (myhdr.dirty)
1250 logf("tagcache is dirty!");
1251 return false;
1254 memcpy(&current_tcmh, &myhdr, sizeof(struct master_header));
1256 for (tag = 0; tag < TAG_COUNT; tag++)
1258 if (TAGCACHE_IS_NUMERIC(tag))
1259 continue;
1261 if ( (fd = open_tag_fd(&tch, tag, false)) < 0)
1262 return false;
1264 close(fd);
1267 return true;
1270 bool tagcache_is_busy(void)
1272 return read_lock || write_lock;
1275 bool tagcache_search(struct tagcache_search *tcs, int tag)
1277 struct tagcache_header tag_hdr;
1278 struct master_header master_hdr;
1279 int i;
1281 while (read_lock)
1282 sleep(1);
1284 memset(tcs, 0, sizeof(struct tagcache_search));
1285 if (tc_stat.commit_step > 0 || !tc_stat.ready)
1286 return false;
1288 tcs->position = sizeof(struct tagcache_header);
1289 tcs->type = tag;
1290 tcs->seek_pos = 0;
1291 tcs->list_position = 0;
1292 tcs->seek_list_count = 0;
1293 tcs->filter_count = 0;
1294 tcs->masterfd = -1;
1296 for (i = 0; i < TAG_COUNT; i++)
1297 tcs->idxfd[i] = -1;
1299 #ifndef HAVE_TC_RAMCACHE
1300 tcs->ramsearch = false;
1301 #else
1302 tcs->ramsearch = tc_stat.ramcache;
1303 if (tcs->ramsearch)
1305 tcs->entry_count = hdr->entry_count[tcs->type];
1307 else
1308 #endif
1310 /* Always open as R/W so we can pass tcs to functions that modify data also
1311 * without failing. */
1312 tcs->masterfd = open_master_fd(&master_hdr, true);
1313 if (tcs->masterfd < 0)
1314 return false;
1316 if (!TAGCACHE_IS_NUMERIC(tcs->type))
1318 tcs->idxfd[tcs->type] = open_tag_fd(&tag_hdr, tcs->type, false);
1319 if (tcs->idxfd[tcs->type] < 0)
1320 return false;
1322 tcs->entry_count = tag_hdr.entry_count;
1324 else
1326 tcs->entry_count = master_hdr.tch.entry_count;
1330 tcs->valid = true;
1331 tcs->initialized = true;
1332 write_lock++;
1334 return true;
1337 void tagcache_search_set_uniqbuf(struct tagcache_search *tcs,
1338 void *buffer, long length)
1340 tcs->unique_list = (unsigned long *)buffer;
1341 tcs->unique_list_capacity = length / sizeof(*tcs->unique_list);
1342 tcs->unique_list_count = 0;
1345 bool tagcache_search_add_filter(struct tagcache_search *tcs,
1346 int tag, int seek)
1348 if (tcs->filter_count == TAGCACHE_MAX_FILTERS)
1349 return false;
1351 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag))
1352 return false;
1354 tcs->filter_tag[tcs->filter_count] = tag;
1355 tcs->filter_seek[tcs->filter_count] = seek;
1356 tcs->filter_count++;
1358 return true;
1361 bool tagcache_search_add_clause(struct tagcache_search *tcs,
1362 struct tagcache_search_clause *clause)
1364 int i;
1366 if (tcs->clause_count >= TAGCACHE_MAX_CLAUSES)
1368 logf("Too many clauses");
1369 return false;
1372 /* Check if there is already a similar filter in present (filters are
1373 * much faster than clauses).
1375 for (i = 0; i < tcs->filter_count; i++)
1377 if (tcs->filter_tag[i] == clause->tag)
1378 return true;
1381 if (!TAGCACHE_IS_NUMERIC(clause->tag) && tcs->idxfd[clause->tag] < 0)
1383 char buf[MAX_PATH];
1385 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, clause->tag);
1386 tcs->idxfd[clause->tag] = open(buf, O_RDONLY);
1389 tcs->clause[tcs->clause_count] = clause;
1390 tcs->clause_count++;
1392 return true;
1395 static bool get_next(struct tagcache_search *tcs)
1397 static char buf[TAG_MAXLEN+32];
1398 struct tagfile_entry entry;
1399 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1400 long flag = 0;
1401 #endif
1403 if (!tcs->valid || !tc_stat.ready)
1404 return false;
1406 if (tcs->idxfd[tcs->type] < 0 && !TAGCACHE_IS_NUMERIC(tcs->type)
1407 #ifdef HAVE_TC_RAMCACHE
1408 && !tcs->ramsearch
1409 #endif
1411 return false;
1413 /* Relative fetch. */
1414 if (tcs->filter_count > 0 || tcs->clause_count > 0
1415 || TAGCACHE_IS_NUMERIC(tcs->type)
1416 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1417 /* We need to retrieve flag status for dircache. */
1418 || (tcs->ramsearch && tcs->type == tag_filename)
1419 #endif
1422 struct tagcache_seeklist_entry *seeklist;
1424 /* Check for end of list. */
1425 if (tcs->list_position == tcs->seek_list_count)
1427 tcs->list_position = 0;
1429 /* Try to fetch more. */
1430 if (!build_lookup_list(tcs))
1432 tcs->valid = false;
1433 return false;
1437 seeklist = &tcs->seeklist[tcs->list_position];
1438 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1439 flag = seeklist->flag;
1440 #endif
1441 tcs->position = seeklist->seek;
1442 tcs->idx_id = seeklist->idx_id;
1443 tcs->list_position++;
1445 else
1447 if (tcs->entry_count == 0)
1449 tcs->valid = false;
1450 return false;
1453 tcs->entry_count--;
1456 tcs->result_seek = tcs->position;
1458 if (TAGCACHE_IS_NUMERIC(tcs->type))
1460 snprintf(buf, sizeof(buf), "%ld", tcs->position);
1461 tcs->result = buf;
1462 tcs->result_len = strlen(buf) + 1;
1463 return true;
1466 /* Direct fetch. */
1467 #ifdef HAVE_TC_RAMCACHE
1468 if (tcs->ramsearch)
1471 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1472 if (tcs->type == tag_filename && (flag & FLAG_DIRCACHE)
1473 && is_dircache_intact())
1475 dircache_copy_path((struct dircache_entry *)tcs->position,
1476 buf, sizeof buf);
1477 tcs->result = buf;
1478 tcs->result_len = strlen(buf) + 1;
1479 tcs->ramresult = false;
1481 return true;
1483 else
1484 #endif
1485 if (tcs->type != tag_filename)
1487 struct tagfile_entry *ep;
1489 ep = (struct tagfile_entry *)&hdr->tags[tcs->type][tcs->position];
1490 tcs->result = ep->tag_data;
1491 tcs->result_len = strlen(tcs->result) + 1;
1492 tcs->idx_id = ep->idx_id;
1493 tcs->ramresult = true;
1495 /* Increase position for the next run. This may get overwritten. */
1496 tcs->position += sizeof(struct tagfile_entry) + ep->tag_length;
1498 return true;
1501 #endif
1503 if (!open_files(tcs, tcs->type))
1505 tcs->valid = false;
1506 return false;
1509 /* Seek stream to the correct position and continue to direct fetch. */
1510 lseek(tcs->idxfd[tcs->type], tcs->position, SEEK_SET);
1512 if (ecread_tagfile_entry(tcs->idxfd[tcs->type], &entry) != sizeof(struct tagfile_entry))
1514 logf("read error #5");
1515 tcs->valid = false;
1516 return false;
1519 if (entry.tag_length > (long)sizeof(buf))
1521 tcs->valid = false;
1522 logf("too long tag #2");
1523 logf("P:%lX/%lX", tcs->position, entry.tag_length);
1524 return false;
1527 if (read(tcs->idxfd[tcs->type], buf, entry.tag_length) != entry.tag_length)
1529 tcs->valid = false;
1530 logf("read error #4");
1531 return false;
1535 Update the position for the next read (this may be overridden
1536 if filters or clauses are being used).
1538 tcs->position += sizeof(struct tagfile_entry) + entry.tag_length;
1539 tcs->result = buf;
1540 tcs->result_len = strlen(tcs->result) + 1;
1541 tcs->idx_id = entry.idx_id;
1542 tcs->ramresult = false;
1544 return true;
1547 bool tagcache_get_next(struct tagcache_search *tcs)
1549 while (get_next(tcs))
1551 if (tcs->result_len > 1)
1552 return true;
1555 return false;
1558 bool tagcache_retrieve(struct tagcache_search *tcs, int idxid,
1559 int tag, char *buf, long size)
1561 struct index_entry idx;
1563 *buf = '\0';
1564 if (!get_index(tcs->masterfd, idxid, &idx, true))
1565 return false;
1567 return retrieve(tcs, &idx, tag, buf, size);
1570 static bool update_master_header(void)
1572 struct master_header myhdr;
1573 int fd;
1575 if (!tc_stat.ready)
1576 return false;
1578 if ( (fd = open_master_fd(&myhdr, true)) < 0)
1579 return false;
1581 myhdr.serial = current_tcmh.serial;
1582 myhdr.commitid = current_tcmh.commitid;
1583 myhdr.dirty = current_tcmh.dirty;
1585 /* Write it back */
1586 lseek(fd, 0, SEEK_SET);
1587 ecwrite(fd, &myhdr, 1, master_header_ec, tc_stat.econ);
1588 close(fd);
1590 #ifdef HAVE_TC_RAMCACHE
1591 if (hdr)
1593 hdr->h.serial = current_tcmh.serial;
1594 hdr->h.commitid = current_tcmh.commitid;
1595 hdr->h.dirty = current_tcmh.dirty;
1597 #endif
1599 return true;
1602 #if 0
1604 void tagcache_modify(struct tagcache_search *tcs, int type, const char *text)
1606 struct tagentry *entry;
1608 if (tcs->type != tag_title)
1609 return ;
1611 /* We will need reserve buffer for this. */
1612 if (tcs->ramcache)
1614 struct tagfile_entry *ep;
1616 ep = (struct tagfile_entry *)&hdr->tags[tcs->type][tcs->result_seek];
1617 tcs->seek_list[tcs->seek_list_count];
1620 entry = find_entry_ram();
1623 #endif
1625 void tagcache_search_finish(struct tagcache_search *tcs)
1627 int i;
1629 if (!tcs->initialized)
1630 return;
1632 if (tcs->masterfd >= 0)
1634 close(tcs->masterfd);
1635 tcs->masterfd = -1;
1638 for (i = 0; i < TAG_COUNT; i++)
1640 if (tcs->idxfd[i] >= 0)
1642 close(tcs->idxfd[i]);
1643 tcs->idxfd[i] = -1;
1647 tcs->ramsearch = false;
1648 tcs->valid = false;
1649 tcs->initialized = 0;
1650 if (write_lock > 0)
1651 write_lock--;
1654 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1655 static struct tagfile_entry *get_tag(const struct index_entry *entry, int tag)
1657 return (struct tagfile_entry *)&hdr->tags[tag][entry->tag_seek[tag]];
1660 static long get_tag_numeric(const struct index_entry *entry, int tag, int idx_id)
1662 return check_virtual_tags(tag, idx_id, entry);
1665 static char* get_tag_string(const struct index_entry *entry, int tag)
1667 char* s = get_tag(entry, tag)->tag_data;
1668 return strcmp(s, UNTAGGED) ? s : NULL;
1671 bool tagcache_fill_tags(struct mp3entry *id3, const char *filename)
1673 struct index_entry *entry;
1674 int idx_id;
1676 if (!tc_stat.ready || !tc_stat.ramcache)
1677 return false;
1679 /* Find the corresponding entry in tagcache. */
1680 idx_id = find_entry_ram(filename, NULL);
1681 if (idx_id < 0)
1682 return false;
1684 entry = &hdr->indices[idx_id];
1686 memset(id3, 0, sizeof(struct mp3entry));
1688 id3->title = get_tag_string(entry, tag_title);
1689 id3->artist = get_tag_string(entry, tag_artist);
1690 id3->album = get_tag_string(entry, tag_album);
1691 id3->genre_string = get_tag_string(entry, tag_genre);
1692 id3->composer = get_tag_string(entry, tag_composer);
1693 id3->comment = get_tag_string(entry, tag_comment);
1694 id3->albumartist = get_tag_string(entry, tag_albumartist);
1695 id3->grouping = get_tag_string(entry, tag_grouping);
1697 id3->length = get_tag_numeric(entry, tag_length, idx_id);
1698 id3->playcount = get_tag_numeric(entry, tag_playcount, idx_id);
1699 id3->rating = get_tag_numeric(entry, tag_rating, idx_id);
1700 id3->lastplayed = get_tag_numeric(entry, tag_lastplayed, idx_id);
1701 id3->score = get_tag_numeric(entry, tag_virt_autoscore, idx_id) / 10;
1702 id3->year = get_tag_numeric(entry, tag_year, idx_id);
1704 id3->discnum = get_tag_numeric(entry, tag_discnumber, idx_id);
1705 id3->tracknum = get_tag_numeric(entry, tag_tracknumber, idx_id);
1706 id3->bitrate = get_tag_numeric(entry, tag_bitrate, idx_id);
1707 if (id3->bitrate == 0)
1708 id3->bitrate = 1;
1710 #if CONFIG_CODEC == SWCODEC
1711 if (global_settings.autoresume_enable)
1713 id3->offset = get_tag_numeric(entry, tag_lastoffset, idx_id);
1714 logf("tagcache_fill_tags: Set offset for %s to %lX\n",
1715 id3->title, id3->offset);
1717 #endif
1719 return true;
1721 #endif
1723 static inline void write_item(const char *item)
1725 int len = strlen(item) + 1;
1727 data_size += len;
1728 write(cachefd, item, len);
1731 static int check_if_empty(char **tag)
1733 int length;
1735 if (*tag == NULL || **tag == '\0')
1737 *tag = UNTAGGED;
1738 return sizeof(UNTAGGED); /* Tag length */
1741 length = strlen(*tag);
1742 if (length > TAG_MAXLEN)
1744 logf("over length tag: %s", *tag);
1745 length = TAG_MAXLEN;
1746 (*tag)[length] = '\0';
1749 return length + 1;
1752 #define ADD_TAG(entry,tag,data) \
1753 /* Adding tag */ \
1754 entry.tag_offset[tag] = offset; \
1755 entry.tag_length[tag] = check_if_empty(data); \
1756 offset += entry.tag_length[tag]
1757 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1758 * idea, as it uses lots of stack and is called from a recursive function
1759 * (check_dir).
1761 static void __attribute__ ((noinline)) add_tagcache(char *path,
1762 unsigned long mtime
1763 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1764 ,const struct dircache_entry *dc
1765 #endif
1768 struct mp3entry id3;
1769 struct temp_file_entry entry;
1770 bool ret;
1771 int fd;
1772 int idx_id = -1;
1773 char tracknumfix[3];
1774 int offset = 0;
1775 int path_length = strlen(path);
1776 bool has_albumartist;
1777 bool has_grouping;
1779 #ifdef SIMULATOR
1780 /* Crude logging for the sim - to aid in debugging */
1781 int logfd = open(ROCKBOX_DIR "/database.log",
1782 O_WRONLY | O_APPEND | O_CREAT, 0666);
1783 if (logfd >= 0) {
1784 write(logfd, path, strlen(path));
1785 write(logfd, "\n", 1);
1786 close(logfd);
1788 #endif
1790 if (cachefd < 0)
1791 return ;
1793 /* Check for overlength file path. */
1794 if (path_length > TAG_MAXLEN)
1796 /* Path can't be shortened. */
1797 logf("Too long path: %s", path);
1798 return ;
1801 /* Check if the file is supported. */
1802 if (probe_file_format(path) == AFMT_UNKNOWN)
1803 return ;
1805 /* Check if the file is already cached. */
1806 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1807 if (tc_stat.ramcache && is_dircache_intact())
1809 idx_id = find_entry_ram(path, dc);
1811 #endif
1813 /* Be sure the entry doesn't exist. */
1814 if (filenametag_fd >= 0 && idx_id < 0)
1815 idx_id = find_entry_disk(path, false);
1817 /* Check if file has been modified. */
1818 if (idx_id >= 0)
1820 struct index_entry idx;
1822 /* TODO: Mark that the index exists (for fast reverse scan) */
1823 //found_idx[idx_id/8] |= idx_id%8;
1825 if (!get_index(-1, idx_id, &idx, true))
1827 logf("failed to retrieve index entry");
1828 return ;
1831 if ((unsigned long)idx.tag_seek[tag_mtime] == mtime)
1833 /* No changes to file. */
1834 return ;
1837 /* Metadata might have been changed. Delete the entry. */
1838 logf("Re-adding: %s", path);
1839 if (!delete_entry(idx_id))
1841 logf("delete_entry failed: %d", idx_id);
1842 return ;
1846 fd = open(path, O_RDONLY);
1847 if (fd < 0)
1849 logf("open fail: %s", path);
1850 return ;
1853 memset(&id3, 0, sizeof(struct mp3entry));
1854 memset(&entry, 0, sizeof(struct temp_file_entry));
1855 memset(&tracknumfix, 0, sizeof(tracknumfix));
1856 ret = get_metadata(&id3, fd, path);
1857 close(fd);
1859 if (!ret)
1860 return ;
1862 logf("-> %s", path);
1864 /* Generate track number if missing. */
1865 if (id3.tracknum <= 0)
1867 const char *p = strrchr(path, '.');
1869 if (p == NULL)
1870 p = &path[strlen(path)-1];
1872 while (*p != '/')
1874 if (isdigit(*p) && isdigit(*(p-1)))
1876 tracknumfix[1] = *p--;
1877 tracknumfix[0] = *p;
1878 break;
1880 p--;
1883 if (tracknumfix[0] != '\0')
1885 id3.tracknum = atoi(tracknumfix);
1886 /* Set a flag to indicate track number has been generated. */
1887 entry.flag |= FLAG_TRKNUMGEN;
1889 else
1891 /* Unable to generate track number. */
1892 id3.tracknum = -1;
1896 /* Numeric tags */
1897 entry.tag_offset[tag_year] = id3.year;
1898 entry.tag_offset[tag_discnumber] = id3.discnum;
1899 entry.tag_offset[tag_tracknumber] = id3.tracknum;
1900 entry.tag_offset[tag_length] = id3.length;
1901 entry.tag_offset[tag_bitrate] = id3.bitrate;
1902 entry.tag_offset[tag_mtime] = mtime;
1904 /* String tags. */
1905 has_albumartist = id3.albumartist != NULL
1906 && strlen(id3.albumartist) > 0;
1907 has_grouping = id3.grouping != NULL
1908 && strlen(id3.grouping) > 0;
1910 ADD_TAG(entry, tag_filename, &path);
1911 ADD_TAG(entry, tag_title, &id3.title);
1912 ADD_TAG(entry, tag_artist, &id3.artist);
1913 ADD_TAG(entry, tag_album, &id3.album);
1914 ADD_TAG(entry, tag_genre, &id3.genre_string);
1915 ADD_TAG(entry, tag_composer, &id3.composer);
1916 ADD_TAG(entry, tag_comment, &id3.comment);
1917 if (has_albumartist)
1919 ADD_TAG(entry, tag_albumartist, &id3.albumartist);
1921 else
1923 ADD_TAG(entry, tag_albumartist, &id3.artist);
1925 if (has_grouping)
1927 ADD_TAG(entry, tag_grouping, &id3.grouping);
1929 else
1931 ADD_TAG(entry, tag_grouping, &id3.title);
1933 entry.data_length = offset;
1935 /* Write the header */
1936 write(cachefd, &entry, sizeof(struct temp_file_entry));
1938 /* And tags also... Correct order is critical */
1939 write_item(path);
1940 write_item(id3.title);
1941 write_item(id3.artist);
1942 write_item(id3.album);
1943 write_item(id3.genre_string);
1944 write_item(id3.composer);
1945 write_item(id3.comment);
1946 if (has_albumartist)
1948 write_item(id3.albumartist);
1950 else
1952 write_item(id3.artist);
1954 if (has_grouping)
1956 write_item(id3.grouping);
1958 else
1960 write_item(id3.title);
1962 total_entry_count++;
1965 static bool tempbuf_insert(char *str, int id, int idx_id, bool unique)
1967 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
1968 int len = strlen(str)+1;
1969 int i;
1970 unsigned crc32;
1971 unsigned *crcbuf = (unsigned *)&tempbuf[tempbuf_size-4];
1972 char buf[TAG_MAXLEN+32];
1974 for (i = 0; str[i] != '\0' && i < (int)sizeof(buf)-1; i++)
1975 buf[i] = tolower(str[i]);
1976 buf[i] = '\0';
1978 crc32 = crc_32(buf, i, 0xffffffff);
1980 if (unique)
1982 /* Check if the crc does not exist -> entry does not exist for sure. */
1983 for (i = 0; i < tempbufidx; i++)
1985 if (crcbuf[-i] != crc32)
1986 continue;
1988 if (!strcasecmp(str, index[i].str))
1990 if (id < 0 || id >= lookup_buffer_depth)
1992 logf("lookup buf overf.: %d", id);
1993 return false;
1996 lookup[id] = &index[i];
1997 return true;
2002 /* Insert to CRC buffer. */
2003 crcbuf[-tempbufidx] = crc32;
2004 tempbuf_left -= 4;
2006 /* Insert it to the buffer. */
2007 tempbuf_left -= len;
2008 if (tempbuf_left - 4 < 0 || tempbufidx >= commit_entry_count-1)
2009 return false;
2011 if (id >= lookup_buffer_depth)
2013 logf("lookup buf overf. #2: %d", id);
2014 return false;
2017 if (id >= 0)
2019 lookup[id] = &index[tempbufidx];
2020 index[tempbufidx].idlist.id = id;
2022 else
2023 index[tempbufidx].idlist.id = -1;
2025 index[tempbufidx].idlist.next = NULL;
2026 index[tempbufidx].idx_id = idx_id;
2027 index[tempbufidx].seek = -1;
2028 index[tempbufidx].str = &tempbuf[tempbuf_pos];
2029 memcpy(index[tempbufidx].str, str, len);
2030 tempbuf_pos += len;
2031 tempbufidx++;
2033 return true;
2036 static int compare(const void *p1, const void *p2)
2038 do_timed_yield();
2040 struct tempbuf_searchidx *e1 = (struct tempbuf_searchidx *)p1;
2041 struct tempbuf_searchidx *e2 = (struct tempbuf_searchidx *)p2;
2043 if (strcmp(e1->str, UNTAGGED) == 0)
2045 if (strcmp(e2->str, UNTAGGED) == 0)
2046 return 0;
2047 return -1;
2049 else if (strcmp(e2->str, UNTAGGED) == 0)
2050 return 1;
2052 return strncasecmp(e1->str, e2->str, TAG_MAXLEN);
2055 static int tempbuf_sort(int fd)
2057 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
2058 struct tagfile_entry fe;
2059 int i;
2060 int length;
2062 /* Generate reverse lookup entries. */
2063 for (i = 0; i < lookup_buffer_depth; i++)
2065 struct tempbuf_id_list *idlist;
2067 if (!lookup[i])
2068 continue;
2070 if (lookup[i]->idlist.id == i)
2071 continue;
2073 idlist = &lookup[i]->idlist;
2074 while (idlist->next != NULL)
2075 idlist = idlist->next;
2077 tempbuf_left -= sizeof(struct tempbuf_id_list);
2078 if (tempbuf_left - 4 < 0)
2079 return -1;
2081 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2082 if (tempbuf_pos & 0x03)
2084 tempbuf_pos = (tempbuf_pos & ~0x03) + 0x04;
2085 tempbuf_left -= 3;
2086 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2088 tempbuf_pos += sizeof(struct tempbuf_id_list);
2090 idlist = idlist->next;
2091 idlist->id = i;
2092 idlist->next = NULL;
2094 do_timed_yield();
2097 qsort(index, tempbufidx, sizeof(struct tempbuf_searchidx), compare);
2098 memset(lookup, 0, lookup_buffer_depth * sizeof(struct tempbuf_searchidx **));
2100 for (i = 0; i < tempbufidx; i++)
2102 struct tempbuf_id_list *idlist = &index[i].idlist;
2104 /* Fix the lookup list. */
2105 while (idlist != NULL)
2107 if (idlist->id >= 0)
2108 lookup[idlist->id] = &index[i];
2109 idlist = idlist->next;
2112 index[i].seek = lseek(fd, 0, SEEK_CUR);
2113 length = strlen(index[i].str) + 1;
2114 fe.tag_length = length;
2115 fe.idx_id = index[i].idx_id;
2117 /* Check the chunk alignment. */
2118 if ((fe.tag_length + sizeof(struct tagfile_entry))
2119 % TAGFILE_ENTRY_CHUNK_LENGTH)
2121 fe.tag_length += TAGFILE_ENTRY_CHUNK_LENGTH -
2122 ((fe.tag_length + sizeof(struct tagfile_entry))
2123 % TAGFILE_ENTRY_CHUNK_LENGTH);
2126 #ifdef TAGCACHE_STRICT_ALIGN
2127 /* Make sure the entry is long aligned. */
2128 if (index[i].seek & 0x03)
2130 logf("tempbuf_sort: alignment error!");
2131 return -3;
2133 #endif
2135 if (ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ) !=
2136 sizeof(struct tagfile_entry))
2138 logf("tempbuf_sort: write error #1");
2139 return -1;
2142 if (write(fd, index[i].str, length) != length)
2144 logf("tempbuf_sort: write error #2");
2145 return -2;
2148 /* Write some padding. */
2149 if (fe.tag_length - length > 0)
2150 write(fd, "XXXXXXXX", fe.tag_length - length);
2153 return i;
2156 inline static struct tempbuf_searchidx* tempbuf_locate(int id)
2158 if (id < 0 || id >= lookup_buffer_depth)
2159 return NULL;
2161 return lookup[id];
2165 inline static int tempbuf_find_location(int id)
2167 struct tempbuf_searchidx *entry;
2169 entry = tempbuf_locate(id);
2170 if (entry == NULL)
2171 return -1;
2173 return entry->seek;
2176 static bool build_numeric_indices(struct tagcache_header *h, int tmpfd)
2178 struct master_header tcmh;
2179 struct index_entry idx;
2180 int masterfd;
2181 int masterfd_pos;
2182 struct temp_file_entry *entrybuf = (struct temp_file_entry *)tempbuf;
2183 int max_entries;
2184 int entries_processed = 0;
2185 int i, j;
2186 char buf[TAG_MAXLEN];
2188 max_entries = tempbuf_size / sizeof(struct temp_file_entry) - 1;
2190 logf("Building numeric indices...");
2191 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2193 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
2194 return false;
2196 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2197 SEEK_CUR);
2198 if (masterfd_pos == filesize(masterfd))
2200 logf("we can't append!");
2201 close(masterfd);
2202 return false;
2205 while (entries_processed < h->entry_count)
2207 int count = MIN(h->entry_count - entries_processed, max_entries);
2209 /* Read in as many entries as possible. */
2210 for (i = 0; i < count; i++)
2212 struct temp_file_entry *tfe = &entrybuf[i];
2213 int datastart;
2215 /* Read in numeric data. */
2216 if (read(tmpfd, tfe, sizeof(struct temp_file_entry)) !=
2217 sizeof(struct temp_file_entry))
2219 logf("read fail #1");
2220 close(masterfd);
2221 return false;
2224 datastart = lseek(tmpfd, 0, SEEK_CUR);
2227 * Read string data from the following tags:
2228 * - tag_filename
2229 * - tag_artist
2230 * - tag_album
2231 * - tag_title
2233 * A crc32 hash is calculated from the read data
2234 * and stored back to the data offset field kept in memory.
2236 #define tmpdb_read_string_tag(tag) \
2237 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2238 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2240 logf("read fail: buffer overflow"); \
2241 close(masterfd); \
2242 return false; \
2245 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2246 tfe->tag_length[tag]) \
2248 logf("read fail #2"); \
2249 close(masterfd); \
2250 return false; \
2253 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2254 lseek(tmpfd, datastart, SEEK_SET)
2256 tmpdb_read_string_tag(tag_filename);
2257 tmpdb_read_string_tag(tag_artist);
2258 tmpdb_read_string_tag(tag_album);
2259 tmpdb_read_string_tag(tag_title);
2261 /* Seek to the end of the string data. */
2262 lseek(tmpfd, tfe->data_length, SEEK_CUR);
2265 /* Backup the master index position. */
2266 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2267 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2269 /* Check if we can resurrect some deleted runtime statistics data. */
2270 for (i = 0; i < tcmh.tch.entry_count; i++)
2272 /* Read the index entry. */
2273 if (ecread_index_entry(masterfd, &idx)
2274 != sizeof(struct index_entry))
2276 logf("read fail #3");
2277 close(masterfd);
2278 return false;
2282 * Skip unless the entry is marked as being deleted
2283 * or the data has already been resurrected.
2285 if (!(idx.flag & FLAG_DELETED) || idx.flag & FLAG_RESURRECTED)
2286 continue;
2288 /* Now try to match the entry. */
2290 * To succesfully match a song, the following conditions
2291 * must apply:
2293 * For numeric fields: tag_length
2294 * - Full identical match is required
2296 * If tag_filename matches, no further checking necessary.
2298 * For string hashes: tag_artist, tag_album, tag_title
2299 * - Two of these must match
2301 for (j = 0; j < count; j++)
2303 struct temp_file_entry *tfe = &entrybuf[j];
2305 /* Try to match numeric fields first. */
2306 if (tfe->tag_offset[tag_length] != idx.tag_seek[tag_length])
2307 continue;
2309 /* Now it's time to do the hash matching. */
2310 if (tfe->tag_offset[tag_filename] != idx.tag_seek[tag_filename])
2312 int match_count = 0;
2314 /* No filename match, check if we can match two other tags. */
2315 #define tmpdb_match(tag) \
2316 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2317 match_count++
2319 tmpdb_match(tag_artist);
2320 tmpdb_match(tag_album);
2321 tmpdb_match(tag_title);
2323 if (match_count < 2)
2325 /* Still no match found, give up. */
2326 continue;
2330 /* A match found, now copy & resurrect the statistical data. */
2331 #define tmpdb_copy_tag(tag) \
2332 tfe->tag_offset[tag] = idx.tag_seek[tag]
2334 tmpdb_copy_tag(tag_playcount);
2335 tmpdb_copy_tag(tag_rating);
2336 tmpdb_copy_tag(tag_playtime);
2337 tmpdb_copy_tag(tag_lastplayed);
2338 tmpdb_copy_tag(tag_commitid);
2339 tmpdb_copy_tag(tag_lastoffset);
2341 /* Avoid processing this entry again. */
2342 idx.flag |= FLAG_RESURRECTED;
2344 lseek(masterfd, -sizeof(struct index_entry), SEEK_CUR);
2345 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2347 logf("masterfd writeback fail #1");
2348 close(masterfd);
2349 return false;
2352 logf("Entry resurrected");
2357 /* Restore the master index position. */
2358 lseek(masterfd, masterfd_pos, SEEK_SET);
2360 /* Commit the data to the index. */
2361 for (i = 0; i < count; i++)
2363 int loc = lseek(masterfd, 0, SEEK_CUR);
2365 if (ecread_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2367 logf("read fail #3");
2368 close(masterfd);
2369 return false;
2372 for (j = 0; j < TAG_COUNT; j++)
2374 if (!TAGCACHE_IS_NUMERIC(j))
2375 continue;
2377 idx.tag_seek[j] = entrybuf[i].tag_offset[j];
2379 idx.flag = entrybuf[i].flag;
2381 if (idx.tag_seek[tag_commitid])
2383 /* Data has been resurrected. */
2384 idx.flag |= FLAG_DIRTYNUM;
2386 else if (tc_stat.ready && current_tcmh.commitid > 0)
2388 idx.tag_seek[tag_commitid] = current_tcmh.commitid;
2389 idx.flag |= FLAG_DIRTYNUM;
2392 /* Write back the updated index. */
2393 lseek(masterfd, loc, SEEK_SET);
2394 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2396 logf("write fail");
2397 close(masterfd);
2398 return false;
2402 entries_processed += count;
2403 logf("%d/%ld entries processed", entries_processed, h->entry_count);
2406 close(masterfd);
2408 return true;
2412 * Return values:
2413 * > 0 success
2414 * == 0 temporary failure
2415 * < 0 fatal error
2417 static int build_index(int index_type, struct tagcache_header *h, int tmpfd)
2419 int i;
2420 struct tagcache_header tch;
2421 struct master_header tcmh;
2422 struct index_entry idxbuf[IDX_BUF_DEPTH];
2423 int idxbuf_pos;
2424 char buf[TAG_MAXLEN+32];
2425 int fd = -1, masterfd;
2426 bool error = false;
2427 int init;
2428 int masterfd_pos;
2430 logf("Building index: %d", index_type);
2432 /* Check the number of entries we need to allocate ram for. */
2433 commit_entry_count = h->entry_count + 1;
2435 masterfd = open_master_fd(&tcmh, false);
2436 if (masterfd >= 0)
2438 commit_entry_count += tcmh.tch.entry_count;
2439 close(masterfd);
2441 else
2442 remove_files(); /* Just to be sure we are clean. */
2444 /* Open the index file, which contains the tag names. */
2445 fd = open_tag_fd(&tch, index_type, true);
2446 if (fd >= 0)
2448 logf("tch.datasize=%ld", tch.datasize);
2449 lookup_buffer_depth = 1 +
2450 /* First part */ commit_entry_count +
2451 /* Second part */ (tch.datasize / TAGFILE_ENTRY_CHUNK_LENGTH);
2453 else
2455 lookup_buffer_depth = 1 +
2456 /* First part */ commit_entry_count +
2457 /* Second part */ 0;
2460 logf("lookup_buffer_depth=%ld", lookup_buffer_depth);
2461 logf("commit_entry_count=%ld", commit_entry_count);
2463 /* Allocate buffer for all index entries from both old and new
2464 * tag files. */
2465 tempbufidx = 0;
2466 tempbuf_pos = commit_entry_count * sizeof(struct tempbuf_searchidx);
2468 /* Allocate lookup buffer. The first portion of commit_entry_count
2469 * contains the new tags in the temporary file and the second
2470 * part for locating entries already in the db.
2472 * New tags Old tags
2473 * +---------+---------------------------+
2474 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2475 * +---------+---------------------------+
2477 * Old tags are inserted to a temporary buffer with position:
2478 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2479 * And new tags with index:
2480 * tempbuf_insert(idx, ...);
2482 * The buffer is sorted and written into tag file:
2483 * tempbuf_sort(...);
2484 * leaving master index locations messed up.
2486 * That is fixed using the lookup buffer for old tags:
2487 * new_seek = tempbuf_find_location(old_seek, ...);
2488 * and for new tags:
2489 * new_seek = tempbuf_find_location(idx);
2491 lookup = (struct tempbuf_searchidx **)&tempbuf[tempbuf_pos];
2492 tempbuf_pos += lookup_buffer_depth * sizeof(void **);
2493 memset(lookup, 0, lookup_buffer_depth * sizeof(void **));
2495 /* And calculate the remaining data space used mainly for storing
2496 * tag data (strings). */
2497 tempbuf_left = tempbuf_size - tempbuf_pos - 8;
2498 if (tempbuf_left - TAGFILE_ENTRY_AVG_LENGTH * commit_entry_count < 0)
2500 logf("Buffer way too small!");
2501 return 0;
2504 if (fd >= 0)
2507 * If tag file contains unique tags (sorted index), we will load
2508 * it entirely into memory so we can resort it later for use with
2509 * chunked browsing.
2511 if (TAGCACHE_IS_SORTED(index_type))
2513 logf("loading tags...");
2514 for (i = 0; i < tch.entry_count; i++)
2516 struct tagfile_entry entry;
2517 int loc = lseek(fd, 0, SEEK_CUR);
2518 bool ret;
2520 if (ecread_tagfile_entry(fd, &entry) != sizeof(struct tagfile_entry))
2522 logf("read error #7");
2523 close(fd);
2524 return -2;
2527 if (entry.tag_length >= (int)sizeof(buf))
2529 logf("too long tag #3");
2530 close(fd);
2531 return -2;
2534 if (read(fd, buf, entry.tag_length) != entry.tag_length)
2536 logf("read error #8");
2537 close(fd);
2538 return -2;
2541 /* Skip deleted entries. */
2542 if (buf[0] == '\0')
2543 continue;
2546 * Save the tag and tag id in the memory buffer. Tag id
2547 * is saved so we can later reindex the master lookup
2548 * table when the index gets resorted.
2550 ret = tempbuf_insert(buf, loc/TAGFILE_ENTRY_CHUNK_LENGTH
2551 + commit_entry_count, entry.idx_id,
2552 TAGCACHE_IS_UNIQUE(index_type));
2553 if (!ret)
2555 close(fd);
2556 return -3;
2558 do_timed_yield();
2560 logf("done");
2562 else
2563 tempbufidx = tch.entry_count;
2565 else
2568 * Creating new index file to store the tags. No need to preload
2569 * anything whether the index type is sorted or not.
2571 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, index_type);
2572 fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2573 if (fd < 0)
2575 logf("%s open fail", buf);
2576 return -2;
2579 tch.magic = TAGCACHE_MAGIC;
2580 tch.entry_count = 0;
2581 tch.datasize = 0;
2583 if (ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ)
2584 != sizeof(struct tagcache_header))
2586 logf("header write failed");
2587 close(fd);
2588 return -2;
2592 /* Loading the tag lookup file as "master file". */
2593 logf("Loading index file");
2594 masterfd = open(TAGCACHE_FILE_MASTER, O_RDWR);
2596 if (masterfd < 0)
2598 logf("Creating new DB");
2599 masterfd = open(TAGCACHE_FILE_MASTER, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2601 if (masterfd < 0)
2603 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER);
2604 close(fd);
2605 return -2;
2608 /* Write the header (write real values later). */
2609 memset(&tcmh, 0, sizeof(struct master_header));
2610 tcmh.tch = *h;
2611 tcmh.tch.entry_count = 0;
2612 tcmh.tch.datasize = 0;
2613 tcmh.dirty = true;
2614 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
2615 init = true;
2616 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2618 else
2621 * Master file already exists so we need to process the current
2622 * file first.
2624 init = false;
2626 if (ecread(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ) !=
2627 sizeof(struct master_header) || tcmh.tch.magic != TAGCACHE_MAGIC)
2629 logf("header error");
2630 close(fd);
2631 close(masterfd);
2632 return -2;
2636 * If we reach end of the master file, we need to expand it to
2637 * hold new tags. If the current index is not sorted, we can
2638 * simply append new data to end of the file.
2639 * However, if the index is sorted, we need to update all tag
2640 * pointers in the master file for the current index.
2642 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2643 SEEK_CUR);
2644 if (masterfd_pos == filesize(masterfd))
2646 logf("appending...");
2647 init = true;
2652 * Load new unique tags in memory to be sorted later and added
2653 * to the master lookup file.
2655 if (TAGCACHE_IS_SORTED(index_type))
2657 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2658 /* h is the header of the temporary file containing new tags. */
2659 logf("inserting new tags...");
2660 for (i = 0; i < h->entry_count; i++)
2662 struct temp_file_entry entry;
2664 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2665 sizeof(struct temp_file_entry))
2667 logf("read fail #3");
2668 error = true;
2669 goto error_exit;
2672 /* Read data. */
2673 if (entry.tag_length[index_type] >= (long)sizeof(buf))
2675 logf("too long entry!");
2676 error = true;
2677 goto error_exit;
2680 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2681 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2682 entry.tag_length[index_type])
2684 logf("read fail #4");
2685 error = true;
2686 goto error_exit;
2689 if (TAGCACHE_IS_UNIQUE(index_type))
2690 error = !tempbuf_insert(buf, i, -1, true);
2691 else
2692 error = !tempbuf_insert(buf, i, tcmh.tch.entry_count + i, false);
2694 if (error)
2696 logf("insert error");
2697 goto error_exit;
2700 /* Skip to next. */
2701 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2702 entry.tag_length[index_type], SEEK_CUR);
2703 do_timed_yield();
2705 logf("done");
2707 /* Sort the buffer data and write it to the index file. */
2708 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
2710 * We need to truncate the index file now. There can be junk left
2711 * at the end of file (however, we _should_ always follow the
2712 * entry_count and don't crash with that).
2714 ftruncate(fd, lseek(fd, 0, SEEK_CUR));
2716 i = tempbuf_sort(fd);
2717 if (i < 0)
2718 goto error_exit;
2719 logf("sorted %d tags", i);
2722 * Now update all indexes in the master lookup file.
2724 logf("updating indices...");
2725 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2726 for (i = 0; i < tcmh.tch.entry_count; i += idxbuf_pos)
2728 int j;
2729 int loc = lseek(masterfd, 0, SEEK_CUR);
2731 idxbuf_pos = MIN(tcmh.tch.entry_count - i, IDX_BUF_DEPTH);
2733 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2734 != (int)sizeof(struct index_entry)*idxbuf_pos)
2736 logf("read fail #5");
2737 error = true;
2738 goto error_exit ;
2740 lseek(masterfd, loc, SEEK_SET);
2742 for (j = 0; j < idxbuf_pos; j++)
2744 if (idxbuf[j].flag & FLAG_DELETED)
2746 /* We can just ignore deleted entries. */
2747 // idxbuf[j].tag_seek[index_type] = 0;
2748 continue;
2751 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(
2752 idxbuf[j].tag_seek[index_type]/TAGFILE_ENTRY_CHUNK_LENGTH
2753 + commit_entry_count);
2755 if (idxbuf[j].tag_seek[index_type] < 0)
2757 logf("update error: %ld/%d/%ld",
2758 idxbuf[j].flag, i+j, tcmh.tch.entry_count);
2759 error = true;
2760 goto error_exit;
2763 do_timed_yield();
2766 /* Write back the updated index. */
2767 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2768 index_entry_ec, tc_stat.econ) !=
2769 (int)sizeof(struct index_entry)*idxbuf_pos)
2771 logf("write fail");
2772 error = true;
2773 goto error_exit;
2776 logf("done");
2780 * Walk through the temporary file containing the new tags.
2782 // build_normal_index(h, tmpfd, masterfd, idx);
2783 logf("updating new indices...");
2784 lseek(masterfd, masterfd_pos, SEEK_SET);
2785 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2786 lseek(fd, 0, SEEK_END);
2787 for (i = 0; i < h->entry_count; i += idxbuf_pos)
2789 int j;
2791 idxbuf_pos = MIN(h->entry_count - i, IDX_BUF_DEPTH);
2792 if (init)
2794 memset(idxbuf, 0, sizeof(struct index_entry)*IDX_BUF_DEPTH);
2796 else
2798 int loc = lseek(masterfd, 0, SEEK_CUR);
2800 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2801 != (int)sizeof(struct index_entry)*idxbuf_pos)
2803 logf("read fail #6");
2804 error = true;
2805 break ;
2807 lseek(masterfd, loc, SEEK_SET);
2810 /* Read entry headers. */
2811 for (j = 0; j < idxbuf_pos; j++)
2813 if (!TAGCACHE_IS_SORTED(index_type))
2815 struct temp_file_entry entry;
2816 struct tagfile_entry fe;
2818 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2819 sizeof(struct temp_file_entry))
2821 logf("read fail #7");
2822 error = true;
2823 break ;
2826 /* Read data. */
2827 if (entry.tag_length[index_type] >= (int)sizeof(buf))
2829 logf("too long entry!");
2830 logf("length=%d", entry.tag_length[index_type]);
2831 logf("pos=0x%02lx", lseek(tmpfd, 0, SEEK_CUR));
2832 error = true;
2833 break ;
2836 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2837 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2838 entry.tag_length[index_type])
2840 logf("read fail #8");
2841 logf("offset=0x%02lx", entry.tag_offset[index_type]);
2842 logf("length=0x%02x", entry.tag_length[index_type]);
2843 error = true;
2844 break ;
2847 /* Write to index file. */
2848 idxbuf[j].tag_seek[index_type] = lseek(fd, 0, SEEK_CUR);
2849 fe.tag_length = entry.tag_length[index_type];
2850 fe.idx_id = tcmh.tch.entry_count + i + j;
2851 ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ);
2852 write(fd, buf, fe.tag_length);
2853 tempbufidx++;
2855 /* Skip to next. */
2856 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2857 entry.tag_length[index_type], SEEK_CUR);
2859 else
2861 /* Locate the correct entry from the sorted array. */
2862 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(i + j);
2863 if (idxbuf[j].tag_seek[index_type] < 0)
2865 logf("entry not found (%d)", j);
2866 error = true;
2867 break ;
2872 /* Write index. */
2873 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2874 index_entry_ec, tc_stat.econ) !=
2875 (int)sizeof(struct index_entry)*idxbuf_pos)
2877 logf("tagcache: write fail #4");
2878 error = true;
2879 break ;
2882 do_timed_yield();
2884 logf("done");
2886 /* Finally write the header. */
2887 tch.magic = TAGCACHE_MAGIC;
2888 tch.entry_count = tempbufidx;
2889 tch.datasize = lseek(fd, 0, SEEK_END) - sizeof(struct tagcache_header);
2890 lseek(fd, 0, SEEK_SET);
2891 ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ);
2893 if (index_type != tag_filename)
2894 h->datasize += tch.datasize;
2895 logf("s:%d/%ld/%ld", index_type, tch.datasize, h->datasize);
2896 error_exit:
2898 close(fd);
2899 close(masterfd);
2901 if (error)
2902 return -2;
2904 return 1;
2907 static bool commit(void)
2909 struct tagcache_header tch;
2910 struct master_header tcmh;
2911 int i, len, rc;
2912 int tmpfd;
2913 int masterfd;
2914 #ifdef HAVE_DIRCACHE
2915 bool dircache_buffer_stolen = false;
2916 #endif
2917 bool local_allocation = false;
2919 logf("committing tagcache");
2921 while (write_lock)
2922 sleep(1);
2924 tmpfd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
2925 if (tmpfd < 0)
2927 logf("nothing to commit");
2928 return true;
2932 /* Load the header. */
2933 len = sizeof(struct tagcache_header);
2934 rc = read(tmpfd, &tch, len);
2936 if (tch.magic != TAGCACHE_MAGIC || rc != len)
2938 logf("incorrect tmpheader");
2939 close(tmpfd);
2940 remove(TAGCACHE_FILE_TEMP);
2941 return false;
2944 if (tch.entry_count == 0)
2946 logf("nothing to commit");
2947 close(tmpfd);
2948 remove(TAGCACHE_FILE_TEMP);
2949 return true;
2952 /* Fully initialize existing headers (if any) before going further. */
2953 tc_stat.ready = check_all_headers();
2955 #ifdef HAVE_EEPROM_SETTINGS
2956 remove(TAGCACHE_STATEFILE);
2957 #endif
2959 /* At first be sure to unload the ramcache! */
2960 #ifdef HAVE_TC_RAMCACHE
2961 tc_stat.ramcache = false;
2962 #endif
2964 read_lock++;
2966 /* Try to steal every buffer we can :) */
2967 if (tempbuf_size == 0)
2968 local_allocation = true;
2970 #ifdef HAVE_DIRCACHE
2971 if (tempbuf_size == 0)
2973 /* Try to steal the dircache buffer. */
2974 tempbuf = dircache_steal_buffer(&tempbuf_size);
2975 tempbuf_size &= ~0x03;
2977 if (tempbuf_size > 0)
2979 dircache_buffer_stolen = true;
2982 #endif
2984 #ifdef HAVE_TC_RAMCACHE
2985 if (tempbuf_size == 0 && tc_stat.ramcache_allocated > 0)
2987 tempbuf = (char *)(hdr + 1);
2988 tempbuf_size = tc_stat.ramcache_allocated - sizeof(struct ramcache_header) - 128;
2989 tempbuf_size &= ~0x03;
2991 #endif
2993 /* And finally fail if there are no buffers available. */
2994 if (tempbuf_size == 0)
2996 logf("delaying commit until next boot");
2997 tc_stat.commit_delayed = true;
2998 close(tmpfd);
2999 read_lock--;
3000 return false;
3003 logf("commit %ld entries...", tch.entry_count);
3005 /* Mark DB dirty so it will stay disabled if commit fails. */
3006 current_tcmh.dirty = true;
3007 update_master_header();
3009 /* Now create the index files. */
3010 tc_stat.commit_step = 0;
3011 tch.datasize = 0;
3012 tc_stat.commit_delayed = false;
3014 for (i = 0; i < TAG_COUNT; i++)
3016 int ret;
3018 if (TAGCACHE_IS_NUMERIC(i))
3019 continue;
3021 tc_stat.commit_step++;
3022 ret = build_index(i, &tch, tmpfd);
3023 if (ret <= 0)
3025 close(tmpfd);
3026 logf("tagcache failed init");
3027 if (ret == 0)
3028 tc_stat.commit_delayed = true;
3030 tc_stat.commit_step = 0;
3031 read_lock--;
3032 return false;
3036 if (!build_numeric_indices(&tch, tmpfd))
3038 logf("Failure to commit numeric indices");
3039 close(tmpfd);
3040 tc_stat.commit_step = 0;
3041 read_lock--;
3042 return false;
3045 close(tmpfd);
3047 tc_stat.commit_step = 0;
3049 /* Update the master index headers. */
3050 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
3052 read_lock--;
3053 return false;
3056 remove(TAGCACHE_FILE_TEMP);
3058 tcmh.tch.entry_count += tch.entry_count;
3059 tcmh.tch.datasize = sizeof(struct master_header)
3060 + sizeof(struct index_entry) * tcmh.tch.entry_count
3061 + tch.datasize;
3062 tcmh.dirty = false;
3063 tcmh.commitid++;
3065 lseek(masterfd, 0, SEEK_SET);
3066 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
3067 close(masterfd);
3069 logf("tagcache committed");
3070 tc_stat.ready = check_all_headers();
3071 tc_stat.readyvalid = true;
3073 if (local_allocation)
3075 tempbuf = NULL;
3076 tempbuf_size = 0;
3079 #ifdef HAVE_DIRCACHE
3080 /* Rebuild the dircache, if we stole the buffer. */
3081 if (dircache_buffer_stolen)
3082 dircache_build(0);
3083 #endif
3085 #ifdef HAVE_TC_RAMCACHE
3086 /* Reload tagcache. */
3087 if (tc_stat.ramcache_allocated > 0)
3088 tagcache_start_scan();
3089 #endif
3091 read_lock--;
3093 return true;
3096 static void allocate_tempbuf(void)
3098 /* Yeah, malloc would be really nice now :) */
3099 #ifdef __PCTOOL__
3100 tempbuf_size = 32*1024*1024;
3101 tempbuf = malloc(tempbuf_size);
3102 #else
3103 tempbuf = (char *)(((long)audiobuf & ~0x03) + 0x04);
3104 tempbuf_size = (long)audiobufend - (long)audiobuf - 4;
3105 audiobuf += tempbuf_size;
3106 #endif
3109 static void free_tempbuf(void)
3111 if (tempbuf_size == 0)
3112 return ;
3114 #ifdef __PCTOOL__
3115 free(tempbuf);
3116 #else
3117 audiobuf -= tempbuf_size;
3118 #endif
3119 tempbuf = NULL;
3120 tempbuf_size = 0;
3123 #ifndef __PCTOOL__
3125 static bool modify_numeric_entry(int masterfd, int idx_id, int tag, long data)
3127 struct index_entry idx;
3129 if (!tc_stat.ready)
3130 return false;
3132 if (!TAGCACHE_IS_NUMERIC(tag))
3133 return false;
3135 if (!get_index(masterfd, idx_id, &idx, false))
3136 return false;
3138 idx.tag_seek[tag] = data;
3139 idx.flag |= FLAG_DIRTYNUM;
3141 return write_index(masterfd, idx_id, &idx);
3144 #if 0
3145 bool tagcache_modify_numeric_entry(struct tagcache_search *tcs,
3146 int tag, long data)
3148 struct master_header myhdr;
3150 if (tcs->masterfd < 0)
3152 if ( (tcs->masterfd = open_master_fd(&myhdr, true)) < 0)
3153 return false;
3156 return modify_numeric_entry(tcs->masterfd, tcs->idx_id, tag, data);
3158 #endif
3160 static bool command_queue_is_full(void)
3162 int next;
3164 next = command_queue_widx + 1;
3165 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3166 next = 0;
3168 return (next == command_queue_ridx);
3171 static void command_queue_sync_callback(void *data)
3173 (void)data;
3174 struct master_header myhdr;
3175 int masterfd;
3177 mutex_lock(&command_queue_mutex);
3179 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3180 return;
3182 while (command_queue_ridx != command_queue_widx)
3184 struct tagcache_command_entry *ce = &command_queue[command_queue_ridx];
3186 switch (ce->command)
3188 case CMD_UPDATE_MASTER_HEADER:
3190 close(masterfd);
3191 update_master_header();
3193 /* Re-open the masterfd. */
3194 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3195 return;
3197 break;
3199 case CMD_UPDATE_NUMERIC:
3201 modify_numeric_entry(masterfd, ce->idx_id, ce->tag, ce->data);
3202 break;
3206 if (++command_queue_ridx >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3207 command_queue_ridx = 0;
3210 close(masterfd);
3212 tc_stat.queue_length = 0;
3213 mutex_unlock(&command_queue_mutex);
3216 static void run_command_queue(bool force)
3218 if (COMMAND_QUEUE_IS_EMPTY)
3219 return;
3221 if (force || command_queue_is_full())
3222 command_queue_sync_callback(NULL);
3223 else
3224 register_storage_idle_func(command_queue_sync_callback);
3227 static void queue_command(int cmd, long idx_id, int tag, long data)
3229 while (1)
3231 int next;
3233 mutex_lock(&command_queue_mutex);
3234 next = command_queue_widx + 1;
3235 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3236 next = 0;
3238 /* Make sure queue is not full. */
3239 if (next != command_queue_ridx)
3241 struct tagcache_command_entry *ce = &command_queue[command_queue_widx];
3243 ce->command = cmd;
3244 ce->idx_id = idx_id;
3245 ce->tag = tag;
3246 ce->data = data;
3248 command_queue_widx = next;
3250 tc_stat.queue_length++;
3252 mutex_unlock(&command_queue_mutex);
3253 break;
3256 /* Queue is full, try again later... */
3257 mutex_unlock(&command_queue_mutex);
3258 sleep(1);
3262 long tagcache_increase_serial(void)
3264 long old;
3266 if (!tc_stat.ready)
3267 return -2;
3269 while (read_lock)
3270 sleep(1);
3272 old = current_tcmh.serial++;
3273 queue_command(CMD_UPDATE_MASTER_HEADER, 0, 0, 0);
3275 return old;
3278 void tagcache_update_numeric(int idx_id, int tag, long data)
3280 queue_command(CMD_UPDATE_NUMERIC, idx_id, tag, data);
3282 #endif /* !__PCTOOL__ */
3284 long tagcache_get_serial(void)
3286 return current_tcmh.serial;
3289 long tagcache_get_commitid(void)
3291 return current_tcmh.commitid;
3294 static bool write_tag(int fd, const char *tagstr, const char *datastr)
3296 char buf[512];
3297 int i;
3299 snprintf(buf, sizeof buf, "%s=\"", tagstr);
3300 for (i = strlen(buf); i < (long)sizeof(buf)-4; i++)
3302 if (*datastr == '\0')
3303 break;
3305 if (*datastr == '"' || *datastr == '\\')
3306 buf[i++] = '\\';
3308 buf[i] = *(datastr++);
3311 strcpy(&buf[i], "\" ");
3313 write(fd, buf, i + 2);
3315 return true;
3318 #ifndef __PCTOOL__
3320 static bool read_tag(char *dest, long size,
3321 const char *src, const char *tagstr)
3323 int pos;
3324 char current_tag[32];
3326 while (*src != '\0')
3328 /* Skip all whitespace */
3329 while (*src == ' ')
3330 src++;
3332 if (*src == '\0')
3333 break;
3335 pos = 0;
3336 /* Read in tag name */
3337 while (*src != '=' && *src != ' ')
3339 current_tag[pos] = *src;
3340 src++;
3341 pos++;
3343 if (*src == '\0' || pos >= (long)sizeof(current_tag))
3344 return false;
3346 current_tag[pos] = '\0';
3348 /* Read in tag data */
3350 /* Find the start. */
3351 while (*src != '"' && *src != '\0')
3352 src++;
3354 if (*src == '\0' || *(++src) == '\0')
3355 return false;
3357 /* Read the data. */
3358 for (pos = 0; pos < size; pos++)
3360 if (*src == '\0')
3361 break;
3363 if (*src == '\\')
3365 dest[pos] = *(src+1);
3366 src += 2;
3367 continue;
3370 dest[pos] = *src;
3372 if (*src == '"')
3374 src++;
3375 break;
3378 if (*src == '\0')
3379 break;
3381 src++;
3383 dest[pos] = '\0';
3385 if (!strcasecmp(tagstr, current_tag))
3386 return true;
3389 return false;
3392 static int parse_changelog_line(int line_n, const char *buf, void *parameters)
3394 struct index_entry idx;
3395 char tag_data[TAG_MAXLEN+32];
3396 int idx_id;
3397 long masterfd = (long)parameters;
3398 const int import_tags[] = { tag_playcount, tag_rating, tag_playtime,
3399 tag_lastplayed, tag_commitid, tag_lastoffset };
3400 int i;
3401 (void)line_n;
3403 if (*buf == '#')
3404 return 0;
3406 logf("%d/%s", line_n, buf);
3407 if (!read_tag(tag_data, sizeof tag_data, buf, "filename"))
3409 logf("filename missing");
3410 logf("-> %s", buf);
3411 return 0;
3414 idx_id = find_index(tag_data);
3415 if (idx_id < 0)
3417 logf("entry not found");
3418 return 0;
3421 if (!get_index(masterfd, idx_id, &idx, false))
3423 logf("failed to retrieve index entry");
3424 return 0;
3427 /* Stop if tag has already been modified. */
3428 if (idx.flag & FLAG_DIRTYNUM)
3429 return 0;
3431 logf("import: %s", tag_data);
3433 idx.flag |= FLAG_DIRTYNUM;
3434 for (i = 0; i < (long)(sizeof(import_tags)/sizeof(import_tags[0])); i++)
3436 int data;
3438 if (!read_tag(tag_data, sizeof tag_data, buf,
3439 tagcache_tag_to_str(import_tags[i])))
3441 continue;
3444 data = atoi(tag_data);
3445 if (data < 0)
3446 continue;
3448 idx.tag_seek[import_tags[i]] = data;
3450 if (import_tags[i] == tag_lastplayed && data >= current_tcmh.serial)
3451 current_tcmh.serial = data + 1;
3452 else if (import_tags[i] == tag_commitid && data >= current_tcmh.commitid)
3453 current_tcmh.commitid = data + 1;
3456 return write_index(masterfd, idx_id, &idx) ? 0 : -5;
3459 bool tagcache_import_changelog(void)
3461 struct master_header myhdr;
3462 struct tagcache_header tch;
3463 int clfd;
3464 long masterfd;
3465 char buf[2048];
3467 if (!tc_stat.ready)
3468 return false;
3470 while (read_lock)
3471 sleep(1);
3473 clfd = open(TAGCACHE_FILE_CHANGELOG, O_RDONLY);
3474 if (clfd < 0)
3476 logf("failure to open changelog");
3477 return false;
3480 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3482 close(clfd);
3483 return false;
3486 write_lock++;
3488 filenametag_fd = open_tag_fd(&tch, tag_filename, false);
3490 fast_readline(clfd, buf, sizeof buf, (long *)masterfd,
3491 parse_changelog_line);
3493 close(clfd);
3494 close(masterfd);
3496 if (filenametag_fd >= 0)
3498 close(filenametag_fd);
3499 filenametag_fd = -1;
3502 write_lock--;
3504 update_master_header();
3506 return true;
3509 #endif /* !__PCTOOL__ */
3511 bool tagcache_create_changelog(struct tagcache_search *tcs)
3513 struct master_header myhdr;
3514 struct index_entry idx;
3515 char buf[TAG_MAXLEN+32];
3516 char temp[32];
3517 int clfd;
3518 int i, j;
3520 if (!tc_stat.ready)
3521 return false;
3523 if (!tagcache_search(tcs, tag_filename))
3524 return false;
3526 /* Initialize the changelog */
3527 clfd = open(TAGCACHE_FILE_CHANGELOG, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3528 if (clfd < 0)
3530 logf("failure to open changelog");
3531 return false;
3534 if (tcs->masterfd < 0)
3536 if ( (tcs->masterfd = open_master_fd(&myhdr, false)) < 0)
3537 return false;
3539 else
3541 lseek(tcs->masterfd, 0, SEEK_SET);
3542 ecread(tcs->masterfd, &myhdr, 1, master_header_ec, tc_stat.econ);
3545 write(clfd, "## Changelog version 1\n", 23);
3547 for (i = 0; i < myhdr.tch.entry_count; i++)
3549 if (ecread_index_entry(tcs->masterfd, &idx) != sizeof(struct index_entry))
3551 logf("read error #9");
3552 tagcache_search_finish(tcs);
3553 close(clfd);
3554 return false;
3557 /* Skip until the entry found has been modified. */
3558 if (! (idx.flag & FLAG_DIRTYNUM) )
3559 continue;
3561 /* Skip deleted entries too. */
3562 if (idx.flag & FLAG_DELETED)
3563 continue;
3565 /* Now retrieve all tags. */
3566 for (j = 0; j < TAG_COUNT; j++)
3568 if (TAGCACHE_IS_NUMERIC(j))
3570 snprintf(temp, sizeof temp, "%d", (int)idx.tag_seek[j]);
3571 write_tag(clfd, tagcache_tag_to_str(j), temp);
3572 continue;
3575 tcs->type = j;
3576 tagcache_retrieve(tcs, i, tcs->type, buf, sizeof buf);
3577 write_tag(clfd, tagcache_tag_to_str(j), buf);
3580 write(clfd, "\n", 1);
3581 do_timed_yield();
3584 close(clfd);
3586 tagcache_search_finish(tcs);
3588 return true;
3591 static bool delete_entry(long idx_id)
3593 int fd = -1;
3594 int masterfd = -1;
3595 int tag, i;
3596 struct index_entry idx, myidx;
3597 struct master_header myhdr;
3598 char buf[TAG_MAXLEN+32];
3599 int in_use[TAG_COUNT];
3601 logf("delete_entry(): %ld", idx_id);
3603 #ifdef HAVE_TC_RAMCACHE
3604 /* At first mark the entry removed from ram cache. */
3605 if (tc_stat.ramcache)
3606 hdr->indices[idx_id].flag |= FLAG_DELETED;
3607 #endif
3609 if ( (masterfd = open_master_fd(&myhdr, true) ) < 0)
3610 return false;
3612 lseek(masterfd, idx_id * sizeof(struct index_entry), SEEK_CUR);
3613 if (ecread_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3615 logf("delete_entry(): read error");
3616 goto cleanup;
3619 if (myidx.flag & FLAG_DELETED)
3621 logf("delete_entry(): already deleted!");
3622 goto cleanup;
3625 myidx.flag |= FLAG_DELETED;
3626 lseek(masterfd, -sizeof(struct index_entry), SEEK_CUR);
3627 if (ecwrite_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3629 logf("delete_entry(): write_error #1");
3630 goto cleanup;
3633 /* Now check which tags are no longer in use (if any) */
3634 for (tag = 0; tag < TAG_COUNT; tag++)
3635 in_use[tag] = 0;
3637 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
3638 for (i = 0; i < myhdr.tch.entry_count; i++)
3640 struct index_entry *idxp;
3642 #ifdef HAVE_TC_RAMCACHE
3643 /* Use RAM DB if available for greater speed */
3644 if (tc_stat.ramcache)
3645 idxp = &hdr->indices[i];
3646 else
3647 #endif
3649 if (ecread_index_entry(masterfd, &idx) != sizeof(struct index_entry))
3651 logf("delete_entry(): read error #2");
3652 goto cleanup;
3654 idxp = &idx;
3657 if (idxp->flag & FLAG_DELETED)
3658 continue;
3660 for (tag = 0; tag < TAG_COUNT; tag++)
3662 if (TAGCACHE_IS_NUMERIC(tag))
3663 continue;
3665 if (idxp->tag_seek[tag] == myidx.tag_seek[tag])
3666 in_use[tag]++;
3670 /* Now delete all tags no longer in use. */
3671 for (tag = 0; tag < TAG_COUNT; tag++)
3673 struct tagcache_header tch;
3674 int oldseek = myidx.tag_seek[tag];
3676 if (TAGCACHE_IS_NUMERIC(tag))
3677 continue;
3679 /**
3680 * Replace tag seek with a hash value of the field string data.
3681 * That way runtime statistics of moved or altered files can be
3682 * resurrected.
3684 #ifdef HAVE_TC_RAMCACHE
3685 if (tc_stat.ramcache && tag != tag_filename)
3687 struct tagfile_entry *tfe;
3688 int32_t *seek = &hdr->indices[idx_id].tag_seek[tag];
3690 tfe = (struct tagfile_entry *)&hdr->tags[tag][*seek];
3691 *seek = crc_32(tfe->tag_data, strlen(tfe->tag_data), 0xffffffff);
3692 myidx.tag_seek[tag] = *seek;
3694 else
3695 #endif
3697 struct tagfile_entry tfe;
3699 /* Open the index file, which contains the tag names. */
3700 if ((fd = open_tag_fd(&tch, tag, true)) < 0)
3701 goto cleanup;
3703 /* Skip the header block */
3704 lseek(fd, myidx.tag_seek[tag], SEEK_SET);
3705 if (ecread_tagfile_entry(fd, &tfe) != sizeof(struct tagfile_entry))
3707 logf("delete_entry(): read error #3");
3708 goto cleanup;
3711 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
3713 logf("delete_entry(): read error #4");
3714 goto cleanup;
3717 myidx.tag_seek[tag] = crc_32(buf, strlen(buf), 0xffffffff);
3720 if (in_use[tag])
3722 logf("in use: %d/%d", tag, in_use[tag]);
3723 if (fd >= 0)
3725 close(fd);
3726 fd = -1;
3728 continue;
3731 #ifdef HAVE_TC_RAMCACHE
3732 /* Delete from ram. */
3733 if (tc_stat.ramcache && tag != tag_filename)
3735 struct tagfile_entry *tagentry = (struct tagfile_entry *)&hdr->tags[tag][oldseek];
3736 tagentry->tag_data[0] = '\0';
3738 #endif
3740 /* Open the index file, which contains the tag names. */
3741 if (fd < 0)
3743 if ((fd = open_tag_fd(&tch, tag, true)) < 0)
3744 goto cleanup;
3747 /* Skip the header block */
3748 lseek(fd, oldseek + sizeof(struct tagfile_entry), SEEK_SET);
3750 /* Debug, print 10 first characters of the tag
3751 read(fd, buf, 10);
3752 buf[10]='\0';
3753 logf("TAG:%s", buf);
3754 lseek(fd, -10, SEEK_CUR);
3757 /* Write first data byte in tag as \0 */
3758 write(fd, "", 1);
3760 /* Now tag data has been removed */
3761 close(fd);
3762 fd = -1;
3765 /* Write index entry back into master index. */
3766 lseek(masterfd, sizeof(struct master_header) +
3767 (idx_id * sizeof(struct index_entry)), SEEK_SET);
3768 if (ecwrite_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3770 logf("delete_entry(): write_error #2");
3771 goto cleanup;
3774 close(masterfd);
3776 return true;
3778 cleanup:
3779 if (fd >= 0)
3780 close(fd);
3781 if (masterfd >= 0)
3782 close(masterfd);
3784 return false;
3787 #ifndef __PCTOOL__
3789 * Returns true if there is an event waiting in the queue
3790 * that requires the current operation to be aborted.
3792 static bool check_event_queue(void)
3794 struct queue_event ev;
3796 if(!queue_peek(&tagcache_queue, &ev))
3797 return false;
3799 switch (ev.id)
3801 case Q_STOP_SCAN:
3802 case SYS_POWEROFF:
3803 case SYS_USB_CONNECTED:
3804 return true;
3807 return false;
3809 #endif
3811 #ifdef HAVE_TC_RAMCACHE
3812 static bool allocate_tagcache(void)
3814 struct master_header tcmh;
3815 int fd;
3817 /* Load the header. */
3818 if ( (fd = open_master_fd(&tcmh, false)) < 0)
3820 hdr = NULL;
3821 return false;
3824 close(fd);
3826 /**
3827 * Now calculate the required cache size plus
3828 * some extra space for alignment fixes.
3830 tc_stat.ramcache_allocated = tcmh.tch.datasize + 128 + TAGCACHE_RESERVE +
3831 sizeof(struct ramcache_header) + TAG_COUNT*sizeof(void *);
3832 hdr = buffer_alloc(tc_stat.ramcache_allocated + 128);
3833 memset(hdr, 0, sizeof(struct ramcache_header));
3834 memcpy(&hdr->h, &tcmh, sizeof(struct master_header));
3835 hdr->indices = (struct index_entry *)(hdr + 1);
3836 logf("tagcache: %d bytes allocated.", tc_stat.ramcache_allocated);
3838 return true;
3841 # ifdef HAVE_EEPROM_SETTINGS
3842 static bool tagcache_dumpload(void)
3844 struct statefile_header shdr;
3845 int fd, rc;
3846 long offpos;
3847 int i;
3849 fd = open(TAGCACHE_STATEFILE, O_RDONLY);
3850 if (fd < 0)
3852 logf("no tagcache statedump");
3853 return false;
3856 /* Check the statefile memory placement */
3857 hdr = buffer_alloc(0);
3858 rc = read(fd, &shdr, sizeof(struct statefile_header));
3859 if (rc != sizeof(struct statefile_header)
3860 /* || (long)hdr != (long)shdr.hdr */)
3862 logf("incorrect statefile");
3863 hdr = NULL;
3864 close(fd);
3865 return false;
3868 offpos = (long)hdr - (long)shdr.hdr;
3870 /* Lets allocate real memory and load it */
3871 hdr = buffer_alloc(shdr.tc_stat.ramcache_allocated);
3872 rc = read(fd, hdr, shdr.tc_stat.ramcache_allocated);
3873 close(fd);
3875 if (rc != shdr.tc_stat.ramcache_allocated)
3877 logf("read failure!");
3878 hdr = NULL;
3879 return false;
3882 memcpy(&tc_stat, &shdr.tc_stat, sizeof(struct tagcache_stat));
3884 /* Now fix the pointers */
3885 hdr->indices = (struct index_entry *)((long)hdr->indices + offpos);
3886 for (i = 0; i < TAG_COUNT; i++)
3887 hdr->tags[i] += offpos;
3889 return true;
3892 static bool tagcache_dumpsave(void)
3894 struct statefile_header shdr;
3895 int fd;
3897 if (!tc_stat.ramcache)
3898 return false;
3900 fd = open(TAGCACHE_STATEFILE, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3901 if (fd < 0)
3903 logf("failed to create a statedump");
3904 return false;
3907 /* Create the header */
3908 shdr.hdr = hdr;
3909 memcpy(&shdr.tc_stat, &tc_stat, sizeof(struct tagcache_stat));
3910 write(fd, &shdr, sizeof(struct statefile_header));
3912 /* And dump the data too */
3913 write(fd, hdr, tc_stat.ramcache_allocated);
3914 close(fd);
3916 return true;
3918 # endif
3920 static bool load_tagcache(void)
3922 struct tagcache_header *tch;
3923 long bytesleft = tc_stat.ramcache_allocated;
3924 struct index_entry *idx;
3925 int rc, fd;
3926 char *p;
3927 int i, tag;
3929 # ifdef HAVE_DIRCACHE
3930 while (dircache_is_initializing())
3931 sleep(1);
3933 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE);
3934 # endif
3936 logf("loading tagcache to ram...");
3938 fd = open(TAGCACHE_FILE_MASTER, O_RDONLY);
3939 if (fd < 0)
3941 logf("tagcache open failed");
3942 return false;
3945 if (ecread(fd, &hdr->h, 1, master_header_ec, tc_stat.econ)
3946 != sizeof(struct master_header)
3947 || hdr->h.tch.magic != TAGCACHE_MAGIC)
3949 logf("incorrect header");
3950 return false;
3953 idx = hdr->indices;
3955 /* Load the master index table. */
3956 for (i = 0; i < hdr->h.tch.entry_count; i++)
3958 rc = ecread_index_entry(fd, idx);
3959 if (rc != sizeof(struct index_entry))
3961 logf("read error #10");
3962 close(fd);
3963 return false;
3966 bytesleft -= sizeof(struct index_entry);
3967 if (bytesleft < 0 || ((long)idx - (long)hdr->indices) >= tc_stat.ramcache_allocated)
3969 logf("too big tagcache.");
3970 close(fd);
3971 return false;
3974 idx++;
3977 close(fd);
3979 /* Load the tags. */
3980 p = (char *)idx;
3981 for (tag = 0; tag < TAG_COUNT; tag++)
3983 struct tagfile_entry *fe;
3984 char buf[TAG_MAXLEN+32];
3986 if (TAGCACHE_IS_NUMERIC(tag))
3987 continue ;
3989 //p = ((void *)p+1);
3990 p = (char *)((long)p & ~0x03) + 0x04;
3991 hdr->tags[tag] = p;
3993 /* Check the header. */
3994 tch = (struct tagcache_header *)p;
3995 p += sizeof(struct tagcache_header);
3997 if ( (fd = open_tag_fd(tch, tag, false)) < 0)
3998 return false;
4000 for (hdr->entry_count[tag] = 0;
4001 hdr->entry_count[tag] < tch->entry_count;
4002 hdr->entry_count[tag]++)
4004 long pos;
4006 if (do_timed_yield())
4008 /* Abort if we got a critical event in queue */
4009 if (check_event_queue())
4010 return false;
4013 fe = (struct tagfile_entry *)p;
4014 pos = lseek(fd, 0, SEEK_CUR);
4015 rc = ecread_tagfile_entry(fd, fe);
4016 if (rc != sizeof(struct tagfile_entry))
4018 /* End of lookup table. */
4019 logf("read error #11");
4020 close(fd);
4021 return false;
4024 /* We have a special handling for the filename tags. */
4025 if (tag == tag_filename)
4027 # ifdef HAVE_DIRCACHE
4028 const struct dircache_entry *dc;
4029 # endif
4031 // FIXME: This is wrong!
4032 // idx = &hdr->indices[hdr->entry_count[i]];
4033 idx = &hdr->indices[fe->idx_id];
4035 if (fe->tag_length >= (long)sizeof(buf)-1)
4037 read(fd, buf, 10);
4038 buf[10] = '\0';
4039 logf("TAG:%s", buf);
4040 logf("too long filename");
4041 close(fd);
4042 return false;
4045 rc = read(fd, buf, fe->tag_length);
4046 if (rc != fe->tag_length)
4048 logf("read error #12");
4049 close(fd);
4050 return false;
4053 /* Check if the entry has already been removed */
4054 if (idx->flag & FLAG_DELETED)
4055 continue;
4057 /* This flag must not be used yet. */
4058 if (idx->flag & FLAG_DIRCACHE)
4060 logf("internal error!");
4061 close(fd);
4062 return false;
4065 if (idx->tag_seek[tag] != pos)
4067 logf("corrupt data structures!");
4068 close(fd);
4069 return false;
4072 # ifdef HAVE_DIRCACHE
4073 if (dircache_is_enabled())
4075 dc = dircache_get_entry_ptr(buf);
4076 if (dc == NULL)
4078 logf("Entry no longer valid.");
4079 logf("-> %s", buf);
4080 if (global_settings.tagcache_autoupdate)
4081 delete_entry(fe->idx_id);
4082 continue ;
4085 idx->flag |= FLAG_DIRCACHE;
4086 idx->tag_seek[tag_filename] = (long)dc;
4088 else
4089 # endif
4091 /* This will be very slow unless dircache is enabled
4092 or target is flash based, but do it anyway for
4093 consistency. */
4094 /* Check if entry has been removed. */
4095 if (global_settings.tagcache_autoupdate)
4097 if (!file_exists(buf))
4099 logf("Entry no longer valid.");
4100 logf("-> %s", buf);
4101 delete_entry(fe->idx_id);
4102 continue;
4107 continue ;
4110 bytesleft -= sizeof(struct tagfile_entry) + fe->tag_length;
4111 if (bytesleft < 0)
4113 logf("too big tagcache #2");
4114 logf("tl: %ld", fe->tag_length);
4115 logf("bl: %ld", bytesleft);
4116 close(fd);
4117 return false;
4120 p = fe->tag_data;
4121 rc = read(fd, fe->tag_data, fe->tag_length);
4122 p += rc;
4124 if (rc != fe->tag_length)
4126 logf("read error #13");
4127 logf("rc=0x%04x", rc); // 0x431
4128 logf("len=0x%04lx", fe->tag_length); // 0x4000
4129 logf("pos=0x%04lx", lseek(fd, 0, SEEK_CUR)); // 0x433
4130 logf("tag=0x%02x", tag); // 0x00
4131 close(fd);
4132 return false;
4135 close(fd);
4138 tc_stat.ramcache_used = tc_stat.ramcache_allocated - bytesleft;
4139 logf("tagcache loaded into ram!");
4141 return true;
4143 #endif /* HAVE_TC_RAMCACHE */
4145 static bool check_deleted_files(void)
4147 int fd;
4148 char buf[TAG_MAXLEN+32];
4149 struct tagfile_entry tfe;
4151 logf("reverse scan...");
4152 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag_filename);
4153 fd = open(buf, O_RDONLY);
4155 if (fd < 0)
4157 logf("%s open fail", buf);
4158 return false;
4161 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
4162 while (ecread_tagfile_entry(fd, &tfe) == sizeof(struct tagfile_entry)
4163 #ifndef __PCTOOL__
4164 && !check_event_queue()
4165 #endif
4168 if (tfe.tag_length >= (long)sizeof(buf)-1)
4170 logf("too long tag");
4171 close(fd);
4172 return false;
4175 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
4177 logf("read error #14");
4178 close(fd);
4179 return false;
4182 /* Check if the file has already deleted from the db. */
4183 if (*buf == '\0')
4184 continue;
4186 /* Now check if the file exists. */
4187 if (!file_exists(buf))
4189 logf("Entry no longer valid.");
4190 logf("-> %s / %ld", buf, tfe.tag_length);
4191 delete_entry(tfe.idx_id);
4195 close(fd);
4197 logf("done");
4199 return true;
4203 /* Note that this function must not be inlined, otherwise the whole point
4204 * of having the code in a separate function is lost.
4206 static void __attribute__ ((noinline)) check_ignore(const char *dirname,
4207 int *ignore, int *unignore)
4209 char newpath[MAX_PATH];
4211 /* check for a database.ignore file */
4212 snprintf(newpath, MAX_PATH, "%s/database.ignore", dirname);
4213 *ignore = file_exists(newpath);
4214 /* check for a database.unignore file */
4215 snprintf(newpath, MAX_PATH, "%s/database.unignore", dirname);
4216 *unignore = file_exists(newpath);
4219 static struct search_roots_ll {
4220 const char *path;
4221 struct search_roots_ll * next;
4222 } roots_ll;
4224 #ifdef APPLICATION
4226 * This adds a path to the search roots, possibly during traveling through
4227 * the filesystem. It only adds if the path is not inside an already existing
4228 * search root.
4230 * Returns true if it added the path to the search roots
4232 * Windows 2000 and greater supports symlinks, but they don't provide
4233 * realpath() or readlink(), and symlinks are rarely used on them so
4234 * ignore this for windows for now
4236 static bool add_search_root(const char *name)
4238 (void)name;
4239 #ifndef WIN32
4240 struct search_roots_ll *this, *prev = NULL;
4241 char target[MAX_PATH];
4242 /* Okay, realpath() is almost completely broken on android
4244 * It doesn't accept NULL for resolved_name to dynamically allocate
4245 * the resulting path; and it assumes resolved_name to be PATH_MAX
4246 * (actually MAXPATHLEN, but it's the same [as of 2.3]) long
4247 * and blindly writes to the end if it
4249 * therefore use sufficiently large static storage here
4250 * Note that PATH_MAX != MAX_PATH
4252 static char abs_target[PATH_MAX];
4253 ssize_t len;
4255 len = readlink(name, target, sizeof(target));
4256 if (len < 0)
4257 return false;
4259 target[len] = '\0';
4260 if (realpath(target, abs_target) == NULL)
4261 return false;
4263 for(this = &roots_ll; this; prev = this, this = this->next)
4265 size_t root_len = strlen(this->path);
4266 /* check if the link target is inside of an existing search root
4267 * don't add if target is inside, we'll scan it later */
4268 if (!strncmp(this->path, abs_target, root_len))
4269 return false;
4272 if (prev)
4274 size_t len = strlen(abs_target) + 1; /* count \0 */
4275 this = malloc(sizeof(struct search_roots_ll) + len );
4276 if (!this || len > MAX_PATH)
4278 logf("Error at adding a search root: %s", this ? "path too long":"OOM");
4279 free(this);
4280 prev->next = NULL;
4281 return false;
4283 this->path = ((char*)this) + sizeof(struct search_roots_ll);
4284 strcpy((char*)this->path, abs_target); /* ok to cast const away here */
4285 this->next = NULL;
4286 prev->next = this;
4287 logf("Added %s to the search roots\n", abs_target);
4288 return true;
4290 #endif
4291 return false;
4294 static int free_search_roots(struct search_roots_ll * start)
4296 int ret = 0;
4297 if (start->next)
4299 ret += free_search_roots(start->next);
4300 ret += sizeof(struct search_roots_ll);
4301 free(start->next);
4303 return ret;
4305 #else /* native, simulator */
4306 #define add_search_root(a) do {} while(0)
4307 #define free_search_roots(a) do {} while(0)
4308 #endif
4310 static bool check_dir(const char *dirname, int add_files)
4312 DIR *dir;
4313 int len;
4314 int success = false;
4315 int ignore, unignore;
4317 dir = opendir(dirname);
4318 if (!dir)
4320 logf("tagcache: opendir(%s) failed", dirname);
4321 return false;
4323 /* check for a database.ignore and database.unignore */
4324 check_ignore(dirname, &ignore, &unignore);
4326 /* don't do anything if both ignore and unignore are there */
4327 if (ignore != unignore)
4328 add_files = unignore;
4330 /* Recursively scan the dir. */
4331 #ifdef __PCTOOL__
4332 while (1)
4333 #else
4334 while (!check_event_queue())
4335 #endif
4337 struct dirent *entry = readdir(dir);
4338 if (entry == NULL)
4340 success = true;
4341 break;
4344 if (!strcmp((char *)entry->d_name, ".") ||
4345 !strcmp((char *)entry->d_name, ".."))
4346 continue;
4348 struct dirinfo info = dir_get_info(dir, entry);
4350 yield();
4352 len = strlen(curpath);
4353 /* don't add an extra / for curpath == / */
4354 if (len <= 1) len = 0;
4355 snprintf(&curpath[len], sizeof(curpath) - len, "/%s", entry->d_name);
4357 processed_dir_count++;
4358 if (info.attribute & ATTR_DIRECTORY)
4359 #ifndef SIMULATOR
4360 { /* don't follow symlinks to dirs, but try to add it as a search root
4361 * this makes able to avoid looping in recursive symlinks */
4362 if (info.attribute & ATTR_LINK)
4363 add_search_root(curpath);
4364 else
4365 check_dir(curpath, add_files);
4367 #else
4368 check_dir(curpath, add_files);
4369 #endif
4370 else if (add_files)
4372 tc_stat.curentry = curpath;
4374 /* Add a new entry to the temporary db file. */
4375 add_tagcache(curpath, (info.wrtdate << 16) | info.wrttime
4376 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4377 , dir->internal_entry
4378 #endif
4381 /* Wait until current path for debug screen is read and unset. */
4382 while (tc_stat.syncscreen && tc_stat.curentry != NULL)
4383 yield();
4385 tc_stat.curentry = NULL;
4388 curpath[len] = '\0';
4391 closedir(dir);
4393 return success;
4396 void tagcache_screensync_event(void)
4398 tc_stat.curentry = NULL;
4401 void tagcache_screensync_enable(bool state)
4403 tc_stat.syncscreen = state;
4406 void tagcache_build(const char *path)
4408 struct tagcache_header header;
4409 bool ret;
4411 curpath[0] = '\0';
4412 data_size = 0;
4413 total_entry_count = 0;
4414 processed_dir_count = 0;
4416 #ifdef HAVE_DIRCACHE
4417 while (dircache_is_initializing())
4418 sleep(1);
4419 #endif
4421 logf("updating tagcache");
4423 cachefd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
4424 if (cachefd >= 0)
4426 logf("skipping, cache already waiting for commit");
4427 close(cachefd);
4428 return ;
4431 cachefd = open(TAGCACHE_FILE_TEMP, O_RDWR | O_CREAT | O_TRUNC, 0666);
4432 if (cachefd < 0)
4434 logf("master file open failed: %s", TAGCACHE_FILE_TEMP);
4435 return ;
4438 filenametag_fd = open_tag_fd(&header, tag_filename, false);
4440 cpu_boost(true);
4442 logf("Scanning files...");
4443 /* Scan for new files. */
4444 memset(&header, 0, sizeof(struct tagcache_header));
4445 write(cachefd, &header, sizeof(struct tagcache_header));
4447 ret = true;
4448 roots_ll.path = path;
4449 roots_ll.next = NULL;
4450 struct search_roots_ll * this;
4451 /* check_dir might add new roots */
4452 for(this = &roots_ll; this; this = this->next)
4454 strcpy(curpath, this->path);
4455 ret = ret && check_dir(this->path, true);
4457 if (roots_ll.next)
4458 free_search_roots(roots_ll.next);
4460 /* Write the header. */
4461 header.magic = TAGCACHE_MAGIC;
4462 header.datasize = data_size;
4463 header.entry_count = total_entry_count;
4464 lseek(cachefd, 0, SEEK_SET);
4465 write(cachefd, &header, sizeof(struct tagcache_header));
4466 close(cachefd);
4468 if (filenametag_fd >= 0)
4470 close(filenametag_fd);
4471 filenametag_fd = -1;
4474 if (!ret)
4476 logf("Aborted.");
4477 cpu_boost(false);
4478 return ;
4481 /* Commit changes to the database. */
4482 #ifdef __PCTOOL__
4483 allocate_tempbuf();
4484 #endif
4485 if (commit())
4487 logf("tagcache built!");
4489 #ifdef __PCTOOL__
4490 free_tempbuf();
4491 #endif
4493 #ifdef HAVE_TC_RAMCACHE
4494 if (hdr)
4496 /* Import runtime statistics if we just initialized the db. */
4497 if (hdr->h.serial == 0)
4498 queue_post(&tagcache_queue, Q_IMPORT_CHANGELOG, 0);
4500 #endif
4502 cpu_boost(false);
4505 #ifdef HAVE_TC_RAMCACHE
4506 static void load_ramcache(void)
4508 if (!hdr)
4509 return ;
4511 cpu_boost(true);
4513 /* At first we should load the cache (if exists). */
4514 tc_stat.ramcache = load_tagcache();
4516 if (!tc_stat.ramcache)
4518 /* If loading failed, it must indicate some problem with the db
4519 * so disable it entirely to prevent further issues. */
4520 tc_stat.ready = false;
4521 hdr = NULL;
4524 cpu_boost(false);
4527 void tagcache_unload_ramcache(void)
4529 tc_stat.ramcache = false;
4530 /* Just to make sure there is no statefile present. */
4531 // remove(TAGCACHE_STATEFILE);
4533 #endif
4535 #ifndef __PCTOOL__
4536 static void tagcache_thread(void)
4538 struct queue_event ev;
4539 bool check_done = false;
4541 /* If the previous cache build/update was interrupted, commit
4542 * the changes first in foreground. */
4543 cpu_boost(true);
4544 allocate_tempbuf();
4545 commit();
4546 free_tempbuf();
4548 #ifdef HAVE_TC_RAMCACHE
4549 # ifdef HAVE_EEPROM_SETTINGS
4550 if (firmware_settings.initialized && firmware_settings.disk_clean
4551 && global_settings.tagcache_ram)
4553 check_done = tagcache_dumpload();
4556 remove(TAGCACHE_STATEFILE);
4557 # endif
4559 /* Allocate space for the tagcache if found on disk. */
4560 if (global_settings.tagcache_ram && !tc_stat.ramcache)
4561 allocate_tagcache();
4562 #endif
4564 cpu_boost(false);
4565 tc_stat.initialized = true;
4567 /* Don't delay bootup with the header check but do it on background. */
4568 if (!tc_stat.ready)
4570 sleep(HZ);
4571 tc_stat.ready = check_all_headers();
4572 tc_stat.readyvalid = true;
4575 while (1)
4577 run_command_queue(false);
4579 queue_wait_w_tmo(&tagcache_queue, &ev, HZ);
4581 switch (ev.id)
4583 case Q_IMPORT_CHANGELOG:
4584 tagcache_import_changelog();
4585 break;
4587 case Q_REBUILD:
4588 remove_files();
4589 remove(TAGCACHE_FILE_TEMP);
4590 tagcache_build("/");
4591 break;
4593 case Q_UPDATE:
4594 tagcache_build("/");
4595 #ifdef HAVE_TC_RAMCACHE
4596 load_ramcache();
4597 #endif
4598 check_deleted_files();
4599 break ;
4601 case Q_START_SCAN:
4602 check_done = false;
4603 case SYS_TIMEOUT:
4604 if (check_done || !tc_stat.ready)
4605 break ;
4607 #ifdef HAVE_TC_RAMCACHE
4608 if (!tc_stat.ramcache && global_settings.tagcache_ram)
4610 load_ramcache();
4611 if (tc_stat.ramcache && global_settings.tagcache_autoupdate)
4612 tagcache_build("/");
4614 else
4615 #endif
4616 if (global_settings.tagcache_autoupdate)
4618 tagcache_build("/");
4620 /* This will be very slow unless dircache is enabled
4621 or target is flash based, but do it anyway for
4622 consistency. */
4623 check_deleted_files();
4626 logf("tagcache check done");
4628 check_done = true;
4629 break ;
4631 case Q_STOP_SCAN:
4632 break ;
4634 case SYS_POWEROFF:
4635 break ;
4637 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4638 case SYS_USB_CONNECTED:
4639 logf("USB: TagCache");
4640 usb_acknowledge(SYS_USB_CONNECTED_ACK);
4641 usb_wait_for_disconnect(&tagcache_queue);
4642 break ;
4643 #endif
4648 bool tagcache_prepare_shutdown(void)
4650 if (tagcache_get_commit_step() > 0)
4651 return false;
4653 tagcache_stop_scan();
4654 while (read_lock || write_lock)
4655 sleep(1);
4657 return true;
4660 void tagcache_shutdown(void)
4662 /* Flush the command queue. */
4663 run_command_queue(true);
4665 #ifdef HAVE_EEPROM_SETTINGS
4666 if (tc_stat.ramcache)
4667 tagcache_dumpsave();
4668 #endif
4671 static int get_progress(void)
4673 int total_count = -1;
4675 #ifdef HAVE_DIRCACHE
4676 if (dircache_is_enabled())
4678 total_count = dircache_get_entry_count();
4680 else
4681 #endif
4682 #ifdef HAVE_TC_RAMCACHE
4684 if (hdr && tc_stat.ramcache)
4685 total_count = hdr->h.tch.entry_count;
4687 #endif
4689 if (total_count < 0)
4690 return -1;
4692 return processed_dir_count * 100 / total_count;
4695 struct tagcache_stat* tagcache_get_stat(void)
4697 tc_stat.progress = get_progress();
4698 tc_stat.processed_entries = processed_dir_count;
4700 return &tc_stat;
4703 void tagcache_start_scan(void)
4705 queue_post(&tagcache_queue, Q_START_SCAN, 0);
4708 bool tagcache_update(void)
4710 if (!tc_stat.ready)
4711 return false;
4713 queue_post(&tagcache_queue, Q_UPDATE, 0);
4714 return false;
4717 bool tagcache_rebuild()
4719 queue_post(&tagcache_queue, Q_REBUILD, 0);
4720 return false;
4723 void tagcache_stop_scan(void)
4725 queue_post(&tagcache_queue, Q_STOP_SCAN, 0);
4728 #ifdef HAVE_TC_RAMCACHE
4729 bool tagcache_is_ramcache(void)
4731 return tc_stat.ramcache;
4733 #endif
4735 #endif /* !__PCTOOL__ */
4738 void tagcache_init(void)
4740 memset(&tc_stat, 0, sizeof(struct tagcache_stat));
4741 memset(&current_tcmh, 0, sizeof(struct master_header));
4742 filenametag_fd = -1;
4743 write_lock = read_lock = 0;
4745 #ifndef __PCTOOL__
4746 mutex_init(&command_queue_mutex);
4747 queue_init(&tagcache_queue, true);
4748 create_thread(tagcache_thread, tagcache_stack,
4749 sizeof(tagcache_stack), 0, tagcache_thread_name
4750 IF_PRIO(, PRIORITY_BACKGROUND)
4751 IF_COP(, CPU));
4752 #else
4753 tc_stat.initialized = true;
4754 allocate_tempbuf();
4755 commit();
4756 free_tempbuf();
4757 tc_stat.ready = check_all_headers();
4758 #endif
4761 #ifdef __PCTOOL__
4762 void tagcache_reverse_scan(void)
4764 logf("Checking for deleted files");
4765 check_deleted_files();
4767 #endif
4769 bool tagcache_is_initialized(void)
4771 return tc_stat.initialized;
4773 bool tagcache_is_fully_initialized(void)
4775 return tc_stat.readyvalid;
4777 bool tagcache_is_usable(void)
4779 return tc_stat.initialized && tc_stat.ready;
4781 int tagcache_get_commit_step(void)
4783 return tc_stat.commit_step;
4785 int tagcache_get_max_commit_step(void)
4787 return (int)(SORTED_TAGS_COUNT)+1;