Adapt tagcache ramcache hibernation to buflib.
[kugel-rb.git] / apps / tagcache.c
blob78405f7ac7c4ee3b8b3c7ff3ca4f07f97a3a9745
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 "core_alloc.h"
78 #include "crc32.h"
79 #include "misc.h"
80 #include "settings.h"
81 #include "dir.h"
82 #include "filefuncs.h"
83 #include "structec.h"
84 #include "debug.h"
86 #ifndef __PCTOOL__
87 #include "lang.h"
88 #include "eeprom_settings.h"
89 #endif
91 #ifdef __PCTOOL__
92 #define yield() do { } while(0)
93 #define sim_sleep(timeout) do { } while(0)
94 #define do_timed_yield() do { } while(0)
95 #endif
97 #ifndef __PCTOOL__
98 /* Tag Cache thread. */
99 static struct event_queue tagcache_queue SHAREDBSS_ATTR;
100 static long tagcache_stack[(DEFAULT_STACK_SIZE + 0x4000)/sizeof(long)];
101 static const char tagcache_thread_name[] = "tagcache";
102 #endif
104 /* Previous path when scanning directory tree recursively. */
105 static char curpath[TAG_MAXLEN+32];
107 /* Used when removing duplicates. */
108 static char *tempbuf; /* Allocated when needed. */
109 static long tempbufidx; /* Current location in buffer. */
110 static size_t tempbuf_size; /* Buffer size (TEMPBUF_SIZE). */
111 static long tempbuf_left; /* Buffer space left. */
112 static long tempbuf_pos;
114 #define SORTED_TAGS_COUNT 8
115 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
116 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
117 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
118 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
119 /* Tags we want to get sorted (loaded to the tempbuf). */
120 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
121 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
122 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
124 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
125 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
126 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
127 (1LU << tag_albumartist) | (1LU << tag_grouping))
129 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
130 static const char *tags_str[] = { "artist", "album", "genre", "title",
131 "filename", "composer", "comment", "albumartist", "grouping", "year",
132 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
133 "playtime", "lastplayed", "commitid", "mtime", "lastoffset" };
135 /* Status information of the tagcache. */
136 static struct tagcache_stat tc_stat;
138 /* Queue commands. */
139 enum tagcache_queue {
140 Q_STOP_SCAN = 0,
141 Q_START_SCAN,
142 Q_IMPORT_CHANGELOG,
143 Q_UPDATE,
144 Q_REBUILD,
146 /* Internal tagcache command queue. */
147 CMD_UPDATE_MASTER_HEADER,
148 CMD_UPDATE_NUMERIC,
151 struct tagcache_command_entry {
152 int32_t command;
153 int32_t idx_id;
154 int32_t tag;
155 int32_t data;
158 #ifndef __PCTOOL__
159 static struct tagcache_command_entry command_queue[TAGCACHE_COMMAND_QUEUE_LENGTH];
160 static volatile int command_queue_widx = 0;
161 static volatile int command_queue_ridx = 0;
162 static struct mutex command_queue_mutex SHAREDBSS_ATTR;
163 #endif
165 /* Tag database structures. */
167 /* Variable-length tag entry in tag files. */
168 struct tagfile_entry {
169 int32_t tag_length; /* Length of the data in bytes including '\0' */
170 int32_t idx_id; /* Corresponding entry location in index file of not unique tags */
171 char tag_data[0]; /* Begin of the tag data */
174 /* Fixed-size tag entry in master db index. */
175 struct index_entry {
176 int32_t tag_seek[TAG_COUNT]; /* Location of tag data or numeric tag data */
177 int32_t flag; /* Status flags */
180 /* Header is the same in every file. */
181 struct tagcache_header {
182 int32_t magic; /* Header version number */
183 int32_t datasize; /* Data size in bytes */
184 int32_t entry_count; /* Number of entries in this file */
187 struct master_header {
188 struct tagcache_header tch;
189 int32_t serial; /* Increasing counting number */
190 int32_t commitid; /* Number of commits so far */
191 int32_t dirty;
194 /* For the endianess correction */
195 static const char *tagfile_entry_ec = "ll";
197 Note: This should be (1 + TAG_COUNT) amount of l's.
199 static const char *index_entry_ec = "llllllllllllllllllllll";
201 static const char *tagcache_header_ec = "lll";
202 static const char *master_header_ec = "llllll";
204 static struct master_header current_tcmh;
206 #ifdef HAVE_TC_RAMCACHE
207 /* Header is created when loading database to ram. */
208 struct ramcache_header {
209 char *tags[TAG_COUNT]; /* Tag file content (not including filename tag) */
210 int entry_count[TAG_COUNT]; /* Number of entries in the indices. */
211 struct index_entry indices[0]; /* Master index file content */
214 # ifdef HAVE_EEPROM_SETTINGS
215 struct statefile_header {
216 int32_t magic; /* Statefile version number */
217 struct master_header mh; /* Header from the master index */
218 struct ramcache_header *hdr; /* Old load address of hdr for relocation */
219 struct tagcache_stat tc_stat;
221 # endif
223 /* Pointer to allocated ramcache_header */
224 static struct ramcache_header *ramcache_hdr;
225 #endif
227 /**
228 * Full tag entries stored in a temporary file waiting
229 * for commit to the cache. */
230 struct temp_file_entry {
231 long tag_offset[TAG_COUNT];
232 short tag_length[TAG_COUNT];
233 long flag;
235 long data_length;
238 struct tempbuf_id_list {
239 long id;
240 struct tempbuf_id_list *next;
243 struct tempbuf_searchidx {
244 long idx_id;
245 char *str;
246 int seek;
247 struct tempbuf_id_list idlist;
250 /* Lookup buffer for fixing messed up index while after sorting. */
251 static long commit_entry_count;
252 static long lookup_buffer_depth;
253 static struct tempbuf_searchidx **lookup;
255 /* Used when building the temporary file. */
256 static int cachefd = -1, filenametag_fd;
257 static int total_entry_count = 0;
258 static int data_size = 0;
259 static int processed_dir_count;
261 /* Thread safe locking */
262 static volatile int write_lock;
263 static volatile int read_lock;
265 static bool delete_entry(long idx_id);
267 const char* tagcache_tag_to_str(int tag)
269 return tags_str[tag];
272 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
273 static ssize_t ecread_tagfile_entry(int fd, struct tagfile_entry *buf)
275 return ecread(fd, buf, 1, tagfile_entry_ec, tc_stat.econ);
278 static ssize_t ecread_index_entry(int fd, struct index_entry *buf)
280 return ecread(fd, buf, 1, index_entry_ec, tc_stat.econ);
283 static ssize_t ecwrite_index_entry(int fd, struct index_entry *buf)
285 return ecwrite(fd, buf, 1, index_entry_ec, tc_stat.econ);
288 #ifdef HAVE_DIRCACHE
290 * Returns true if specified flag is still present, i.e., dircache
291 * has not been reloaded.
293 static bool is_dircache_intact(void)
295 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE);
297 #endif
299 static int open_tag_fd(struct tagcache_header *hdr, int tag, bool write)
301 int fd;
302 char buf[MAX_PATH];
303 int rc;
305 if (TAGCACHE_IS_NUMERIC(tag) || tag < 0 || tag >= TAG_COUNT)
306 return -1;
308 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag);
310 fd = open(buf, write ? O_RDWR : O_RDONLY);
311 if (fd < 0)
313 logf("tag file open failed: tag=%d write=%d file=%s", tag, write, buf);
314 tc_stat.ready = false;
315 return fd;
318 /* Check the header. */
319 rc = ecread(fd, hdr, 1, tagcache_header_ec, tc_stat.econ);
320 if (hdr->magic != TAGCACHE_MAGIC || rc != sizeof(struct tagcache_header))
322 logf("header error");
323 tc_stat.ready = false;
324 close(fd);
325 return -2;
328 return fd;
331 static int open_master_fd(struct master_header *hdr, bool write)
333 int fd;
334 int rc;
336 fd = open(TAGCACHE_FILE_MASTER, write ? O_RDWR : O_RDONLY);
337 if (fd < 0)
339 logf("master file open failed for R/W");
340 tc_stat.ready = false;
341 return fd;
344 tc_stat.econ = false;
346 /* Check the header. */
347 rc = read(fd, hdr, sizeof(struct master_header));
348 if (hdr->tch.magic == TAGCACHE_MAGIC && rc == sizeof(struct master_header))
350 /* Success. */
351 return fd;
354 /* Trying to read again, this time with endianess correction enabled. */
355 lseek(fd, 0, SEEK_SET);
357 rc = ecread(fd, hdr, 1, master_header_ec, true);
358 if (hdr->tch.magic != TAGCACHE_MAGIC || rc != sizeof(struct master_header))
360 logf("header error");
361 tc_stat.ready = false;
362 close(fd);
363 return -2;
366 tc_stat.econ = true;
368 return fd;
371 #ifndef __PCTOOL__
372 static bool do_timed_yield(void)
374 /* Sorting can lock up for quite a while, so yield occasionally */
375 static long wakeup_tick = 0;
376 if (TIME_AFTER(current_tick, wakeup_tick))
378 wakeup_tick = current_tick + (HZ/4);
379 yield();
380 return true;
382 return false;
384 #endif
386 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
387 /* find the ramcache entry corresponding to the file indicated by
388 * filename and dc (it's corresponding dircache id). */
389 static long find_entry_ram(const char *filename, int dc)
391 static long last_pos = 0;
392 int i;
394 /* Check if tagcache is loaded into ram. */
395 if (!tc_stat.ramcache || !is_dircache_intact())
396 return -1;
398 if (dc < 0)
399 dc = dircache_get_entry_id(filename);
401 if (dc < 0)
403 logf("tagcache: file not found.");
404 return -1;
407 try_again:
409 if (last_pos > 0)
410 i = last_pos;
411 else
412 i = 0;
414 for (; i < current_tcmh.tch.entry_count; i++)
416 if (ramcache_hdr->indices[i].tag_seek[tag_filename] == dc)
418 last_pos = MAX(0, i - 3);
419 return i;
422 do_timed_yield();
425 if (last_pos > 0)
427 last_pos = 0;
428 goto try_again;
431 return -1;
433 #endif
435 static long find_entry_disk(const char *filename_raw, bool localfd)
437 struct tagcache_header tch;
438 static long last_pos = -1;
439 long pos_history[POS_HISTORY_COUNT];
440 long pos_history_idx = 0;
441 bool found = false;
442 struct tagfile_entry tfe;
443 int fd;
444 char buf[TAG_MAXLEN+32];
445 int i;
446 int pos = -1;
448 const char *filename = filename_raw;
449 #ifdef APPLICATION
450 char pathbuf[PATH_MAX]; /* Note: Don't use MAX_PATH here, it's too small */
451 if (realpath(filename, pathbuf) == pathbuf)
452 filename = pathbuf;
453 #endif
455 if (!tc_stat.ready)
456 return -2;
458 fd = filenametag_fd;
459 if (fd < 0 || localfd)
461 last_pos = -1;
462 if ( (fd = open_tag_fd(&tch, tag_filename, false)) < 0)
463 return -1;
466 check_again:
468 if (last_pos > 0)
469 lseek(fd, last_pos, SEEK_SET);
470 else
471 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
473 while (true)
475 pos = lseek(fd, 0, SEEK_CUR);
476 for (i = pos_history_idx-1; i >= 0; i--)
477 pos_history[i+1] = pos_history[i];
478 pos_history[0] = pos;
480 if (ecread_tagfile_entry(fd, &tfe)
481 != sizeof(struct tagfile_entry))
483 break ;
486 if (tfe.tag_length >= (long)sizeof(buf))
488 logf("too long tag #1");
489 close(fd);
490 if (!localfd)
491 filenametag_fd = -1;
492 last_pos = -1;
493 return -2;
496 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
498 logf("read error #2");
499 close(fd);
500 if (!localfd)
501 filenametag_fd = -1;
502 last_pos = -1;
503 return -3;
506 if (!strcmp(filename, buf))
508 last_pos = pos_history[pos_history_idx];
509 found = true;
510 break ;
513 if (pos_history_idx < POS_HISTORY_COUNT - 1)
514 pos_history_idx++;
517 /* Not found? */
518 if (!found)
520 if (last_pos > 0)
522 last_pos = -1;
523 logf("seek again");
524 goto check_again;
527 if (fd != filenametag_fd || localfd)
528 close(fd);
529 return -4;
532 if (fd != filenametag_fd || localfd)
533 close(fd);
535 return tfe.idx_id;
538 static int find_index(const char *filename)
540 long idx_id = -1;
542 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
543 idx_id = find_entry_ram(filename, -1);
544 #endif
546 if (idx_id < 0)
547 idx_id = find_entry_disk(filename, true);
549 return idx_id;
552 bool tagcache_find_index(struct tagcache_search *tcs, const char *filename)
554 int idx_id;
556 if (!tc_stat.ready)
557 return false;
559 idx_id = find_index(filename);
560 if (idx_id < 0)
561 return false;
563 if (!tagcache_search(tcs, tag_filename))
564 return false;
566 tcs->entry_count = 0;
567 tcs->idx_id = idx_id;
569 return true;
572 static bool get_index(int masterfd, int idxid,
573 struct index_entry *idx, bool use_ram)
575 bool localfd = false;
577 if (idxid < 0)
579 logf("Incorrect idxid: %d", idxid);
580 return false;
583 #ifdef HAVE_TC_RAMCACHE
584 if (tc_stat.ramcache && use_ram)
586 if (ramcache_hdr->indices[idxid].flag & FLAG_DELETED)
587 return false;
589 # ifdef HAVE_DIRCACHE
590 if (!(ramcache_hdr->indices[idxid].flag & FLAG_DIRCACHE)
591 || is_dircache_intact())
592 #endif
594 memcpy(idx, &ramcache_hdr->indices[idxid], sizeof(struct index_entry));
595 return true;
598 #else
599 (void)use_ram;
600 #endif
602 if (masterfd < 0)
604 struct master_header tcmh;
606 localfd = true;
607 masterfd = open_master_fd(&tcmh, false);
608 if (masterfd < 0)
609 return false;
612 lseek(masterfd, idxid * sizeof(struct index_entry)
613 + sizeof(struct master_header), SEEK_SET);
614 if (ecread_index_entry(masterfd, idx)
615 != sizeof(struct index_entry))
617 logf("read error #3");
618 if (localfd)
619 close(masterfd);
621 return false;
624 if (localfd)
625 close(masterfd);
627 if (idx->flag & FLAG_DELETED)
628 return false;
630 return true;
633 #ifndef __PCTOOL__
635 static bool write_index(int masterfd, int idxid, struct index_entry *idx)
637 /* We need to exclude all memory only flags & tags when writing to disk. */
638 if (idx->flag & FLAG_DIRCACHE)
640 logf("memory only flags!");
641 return false;
644 #ifdef HAVE_TC_RAMCACHE
645 /* Only update numeric data. Writing the whole index to RAM by memcpy
646 * destroys dircache pointers!
648 if (tc_stat.ramcache)
650 int tag;
651 struct index_entry *idx_ram = &ramcache_hdr->indices[idxid];
653 for (tag = 0; tag < TAG_COUNT; tag++)
655 if (TAGCACHE_IS_NUMERIC(tag))
657 idx_ram->tag_seek[tag] = idx->tag_seek[tag];
661 /* Don't touch the dircache flag or attributes. */
662 idx_ram->flag = (idx->flag & 0x0000ffff)
663 | (idx_ram->flag & (0xffff0000 | FLAG_DIRCACHE));
665 #endif
667 lseek(masterfd, idxid * sizeof(struct index_entry)
668 + sizeof(struct master_header), SEEK_SET);
669 if (ecwrite_index_entry(masterfd, idx) != sizeof(struct index_entry))
671 logf("write error #3");
672 logf("idxid: %d", idxid);
673 return false;
676 return true;
679 #endif /* !__PCTOOL__ */
681 static bool open_files(struct tagcache_search *tcs, int tag)
683 if (tcs->idxfd[tag] < 0)
685 char fn[MAX_PATH];
687 snprintf(fn, sizeof fn, TAGCACHE_FILE_INDEX, tag);
688 tcs->idxfd[tag] = open(fn, O_RDONLY);
691 if (tcs->idxfd[tag] < 0)
693 logf("File not open!");
694 return false;
697 return true;
700 static bool retrieve(struct tagcache_search *tcs, struct index_entry *idx,
701 int tag, char *buf, long size)
703 struct tagfile_entry tfe;
704 long seek;
706 *buf = '\0';
708 if (TAGCACHE_IS_NUMERIC(tag))
709 return false;
711 seek = idx->tag_seek[tag];
712 if (seek < 0)
714 logf("Retrieve failed");
715 return false;
718 #ifdef HAVE_TC_RAMCACHE
719 if (tcs->ramsearch)
721 struct tagfile_entry *ep;
723 # ifdef HAVE_DIRCACHE
724 if (tag == tag_filename && (idx->flag & FLAG_DIRCACHE))
726 /* for tag_filename, seek is a dircache index */
727 if (is_dircache_intact())
729 dircache_copy_path(seek, buf, size);
730 return true;
732 else
734 /* The seek is useless now, there's nothing we can return. */
735 logf("retrieve: dircache gone, cannot read file name");
736 tagcache_unload_ramcache();
737 // XXX do this when there's a way to not trigger an
738 // update before reloading:
739 // tagcache_start_scan();
740 return false;
743 else
744 # endif
745 if (tag != tag_filename)
747 ep = (struct tagfile_entry *)&ramcache_hdr->tags[tag][seek];
748 strlcpy(buf, ep->tag_data, size);
750 return true;
753 #endif
755 if (!open_files(tcs, tag))
756 return false;
758 lseek(tcs->idxfd[tag], seek, SEEK_SET);
759 if (ecread_tagfile_entry(tcs->idxfd[tag], &tfe)
760 != sizeof(struct tagfile_entry))
762 logf("read error #5");
763 return false;
766 if (tfe.tag_length >= size)
768 logf("too small buffer");
769 return false;
772 if (read(tcs->idxfd[tag], buf, tfe.tag_length) !=
773 tfe.tag_length)
775 logf("read error #6");
776 return false;
779 buf[tfe.tag_length] = '\0';
781 return true;
784 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
786 static long find_tag(int tag, int idx_id, const struct index_entry *idx)
788 #ifndef __PCTOOL__
789 if (! COMMAND_QUEUE_IS_EMPTY && TAGCACHE_IS_NUMERIC(tag))
791 /* Attempt to find tag data through store-to-load forwarding in
792 command queue */
793 long result = -1;
795 mutex_lock(&command_queue_mutex);
797 int ridx = command_queue_widx;
799 while (ridx != command_queue_ridx)
801 if (--ridx < 0)
802 ridx = TAGCACHE_COMMAND_QUEUE_LENGTH - 1;
804 if (command_queue[ridx].command == CMD_UPDATE_NUMERIC
805 && command_queue[ridx].idx_id == idx_id
806 && command_queue[ridx].tag == tag)
808 result = command_queue[ridx].data;
809 break;
813 mutex_unlock(&command_queue_mutex);
815 if (result >= 0)
817 logf("find_tag: "
818 "Recovered tag %d value %lX from write queue",
819 tag, result);
820 return result;
823 #endif
825 return idx->tag_seek[tag];
829 static long check_virtual_tags(int tag, int idx_id,
830 const struct index_entry *idx)
832 long data = 0;
834 switch (tag)
836 case tag_virt_length_sec:
837 data = (find_tag(tag_length, idx_id, idx)/1000) % 60;
838 break;
840 case tag_virt_length_min:
841 data = (find_tag(tag_length, idx_id, idx)/1000) / 60;
842 break;
844 case tag_virt_playtime_sec:
845 data = (find_tag(tag_playtime, idx_id, idx)/1000) % 60;
846 break;
848 case tag_virt_playtime_min:
849 data = (find_tag(tag_playtime, idx_id, idx)/1000) / 60;
850 break;
852 case tag_virt_autoscore:
853 if (find_tag(tag_length, idx_id, idx) == 0
854 || find_tag(tag_playcount, idx_id, idx) == 0)
856 data = 0;
858 else
860 /* A straight calculus gives:
861 autoscore = 100 * playtime / length / playcout (1)
862 Now, consider the euclidian division of playtime by length:
863 playtime = alpha * length + beta
864 With:
865 0 <= beta < length
866 Now, (1) becomes:
867 autoscore = 100 * (alpha / playcout + beta / length / playcount)
868 Both terms should be small enough to avoid any overflow
870 data = 100 * (find_tag(tag_playtime, idx_id, idx)
871 / find_tag(tag_length, idx_id, idx))
872 + (100 * (find_tag(tag_playtime, idx_id, idx)
873 % find_tag(tag_length, idx_id, idx)))
874 / find_tag(tag_length, idx_id, idx);
875 data /= find_tag(tag_playcount, idx_id, idx);
877 break;
879 /* How many commits before the file has been added to the DB. */
880 case tag_virt_entryage:
881 data = current_tcmh.commitid
882 - find_tag(tag_commitid, idx_id, idx) - 1;
883 break;
885 case tag_virt_basename:
886 tag = tag_filename; /* return filename; caller handles basename */
887 /* FALLTHRU */
889 default:
890 data = find_tag(tag, idx_id, idx);
893 return data;
896 long tagcache_get_numeric(const struct tagcache_search *tcs, int tag)
898 struct index_entry idx;
900 if (!tc_stat.ready)
901 return false;
903 if (!TAGCACHE_IS_NUMERIC(tag))
904 return -1;
906 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
907 return -2;
909 return check_virtual_tags(tag, tcs->idx_id, &idx);
912 inline static bool str_ends_with(const char *str1, const char *str2)
914 int str_len = strlen(str1);
915 int clause_len = strlen(str2);
917 if (clause_len > str_len)
918 return false;
920 return !strcasecmp(&str1[str_len - clause_len], str2);
923 inline static bool str_oneof(const char *str, const char *list)
925 const char *sep;
926 int l, len = strlen(str);
928 while (*list)
930 sep = strchr(list, '|');
931 l = sep ? (long)sep - (long)list : (int)strlen(list);
932 if ((l==len) && !strncasecmp(str, list, len))
933 return true;
934 list += sep ? l + 1 : l;
937 return false;
940 static bool check_against_clause(long numeric, const char *str,
941 const struct tagcache_search_clause *clause)
943 if (clause->numeric)
945 switch (clause->type)
947 case clause_is:
948 return numeric == clause->numeric_data;
949 case clause_is_not:
950 return numeric != clause->numeric_data;
951 case clause_gt:
952 return numeric > clause->numeric_data;
953 case clause_gteq:
954 return numeric >= clause->numeric_data;
955 case clause_lt:
956 return numeric < clause->numeric_data;
957 case clause_lteq:
958 return numeric <= clause->numeric_data;
959 default:
960 logf("Incorrect numeric tag: %d", clause->type);
963 else
965 switch (clause->type)
967 case clause_is:
968 return !strcasecmp(clause->str, str);
969 case clause_is_not:
970 return strcasecmp(clause->str, str);
971 case clause_gt:
972 return 0>strcasecmp(clause->str, str);
973 case clause_gteq:
974 return 0>=strcasecmp(clause->str, str);
975 case clause_lt:
976 return 0<strcasecmp(clause->str, str);
977 case clause_lteq:
978 return 0<=strcasecmp(clause->str, str);
979 case clause_contains:
980 return (strcasestr(str, clause->str) != NULL);
981 case clause_not_contains:
982 return (strcasestr(str, clause->str) == NULL);
983 case clause_begins_with:
984 return (strcasestr(str, clause->str) == str);
985 case clause_not_begins_with:
986 return (strcasestr(str, clause->str) != str);
987 case clause_ends_with:
988 return str_ends_with(str, clause->str);
989 case clause_not_ends_with:
990 return !str_ends_with(str, clause->str);
991 case clause_oneof:
992 return str_oneof(str, clause->str);
994 default:
995 logf("Incorrect tag: %d", clause->type);
999 return false;
1002 static bool check_clauses(struct tagcache_search *tcs,
1003 struct index_entry *idx,
1004 struct tagcache_search_clause **clauses, int count)
1006 int i;
1008 /* Go through all conditional clauses. */
1009 for (i = 0; i < count; i++)
1011 int seek;
1012 char buf[256];
1013 char *str = buf;
1014 struct tagcache_search_clause *clause = clauses[i];
1016 if (clause->type == clause_logical_or)
1017 break; /* all conditions before logical-or satisfied --
1018 stop processing clauses */
1020 seek = check_virtual_tags(clause->tag, tcs->idx_id, idx);
1022 #ifdef HAVE_TC_RAMCACHE
1023 if (tcs->ramsearch)
1025 struct tagfile_entry *tfe;
1027 if (!TAGCACHE_IS_NUMERIC(clause->tag))
1029 if (clause->tag == tag_filename
1030 || clause->tag == tag_virt_basename)
1032 retrieve(tcs, idx, tag_filename, buf, sizeof buf);
1034 else
1036 tfe = (struct tagfile_entry *)
1037 &ramcache_hdr->tags[clause->tag][seek];
1038 str = tfe->tag_data;
1042 else
1043 #endif
1045 struct tagfile_entry tfe;
1047 if (!TAGCACHE_IS_NUMERIC(clause->tag))
1049 int tag = clause->tag;
1050 if (tag == tag_virt_basename)
1051 tag = tag_filename;
1053 int fd = tcs->idxfd[tag];
1054 lseek(fd, seek, SEEK_SET);
1055 ecread_tagfile_entry(fd, &tfe);
1056 if (tfe.tag_length >= (int)sizeof(buf))
1058 logf("Too long tag read!");
1059 return false;
1062 read(fd, str, tfe.tag_length);
1063 str[tfe.tag_length] = '\0';
1065 /* Check if entry has been deleted. */
1066 if (str[0] == '\0')
1067 return false;
1071 if (clause->tag == tag_virt_basename)
1073 char *basename = strrchr(str, '/');
1074 if (basename)
1075 str = basename + 1;
1078 if (!check_against_clause(seek, str, clause))
1080 /* Clause failed -- try finding a logical-or clause */
1081 while (++i < count)
1083 if (clauses[i]->type == clause_logical_or)
1084 break;
1087 if (i < count) /* Found logical-or? */
1088 continue; /* Check clauses after logical-or */
1090 return false;
1094 return true;
1097 bool tagcache_check_clauses(struct tagcache_search *tcs,
1098 struct tagcache_search_clause **clause, int count)
1100 struct index_entry idx;
1102 if (count == 0)
1103 return true;
1105 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
1106 return false;
1108 return check_clauses(tcs, &idx, clause, count);
1111 static bool add_uniqbuf(struct tagcache_search *tcs, unsigned long id)
1113 int i;
1115 /* If uniq buffer is not defined we must return true for search to work. */
1116 if (tcs->unique_list == NULL || (!TAGCACHE_IS_UNIQUE(tcs->type)
1117 && !TAGCACHE_IS_NUMERIC(tcs->type)))
1119 return true;
1122 for (i = 0; i < tcs->unique_list_count; i++)
1124 /* Return false if entry is found. */
1125 if (tcs->unique_list[i] == id)
1126 return false;
1129 if (tcs->unique_list_count < tcs->unique_list_capacity)
1131 tcs->unique_list[i] = id;
1132 tcs->unique_list_count++;
1135 return true;
1138 static bool build_lookup_list(struct tagcache_search *tcs)
1140 struct index_entry entry;
1141 int i, j;
1143 tcs->seek_list_count = 0;
1145 #ifdef HAVE_TC_RAMCACHE
1146 if (tcs->ramsearch
1147 # ifdef HAVE_DIRCACHE
1148 && (tcs->type != tag_filename || is_dircache_intact())
1149 # endif
1152 for (i = tcs->seek_pos; i < current_tcmh.tch.entry_count; i++)
1154 struct tagcache_seeklist_entry *seeklist;
1155 struct index_entry *idx = &ramcache_hdr->indices[i];
1156 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1157 break ;
1159 /* Skip deleted files. */
1160 if (idx->flag & FLAG_DELETED)
1161 continue;
1163 /* Go through all filters.. */
1164 for (j = 0; j < tcs->filter_count; j++)
1166 if (idx->tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1168 break ;
1172 if (j < tcs->filter_count)
1173 continue ;
1175 /* Check for conditions. */
1176 if (!check_clauses(tcs, idx, tcs->clause, tcs->clause_count))
1177 continue;
1179 /* Add to the seek list if not already in uniq buffer. */
1180 if (!add_uniqbuf(tcs, idx->tag_seek[tcs->type]))
1181 continue;
1183 /* Lets add it. */
1184 seeklist = &tcs->seeklist[tcs->seek_list_count];
1185 seeklist->seek = idx->tag_seek[tcs->type];
1186 seeklist->flag = idx->flag;
1187 seeklist->idx_id = i;
1188 tcs->seek_list_count++;
1191 tcs->seek_pos = i;
1193 return tcs->seek_list_count > 0;
1195 #endif
1197 if (tcs->masterfd < 0)
1199 struct master_header tcmh;
1200 tcs->masterfd = open_master_fd(&tcmh, false);
1203 lseek(tcs->masterfd, tcs->seek_pos * sizeof(struct index_entry) +
1204 sizeof(struct master_header), SEEK_SET);
1206 while (ecread_index_entry(tcs->masterfd, &entry)
1207 == sizeof(struct index_entry))
1209 struct tagcache_seeklist_entry *seeklist;
1211 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1212 break ;
1214 i = tcs->seek_pos;
1215 tcs->seek_pos++;
1217 /* Check if entry has been deleted. */
1218 if (entry.flag & FLAG_DELETED)
1219 continue;
1221 /* Go through all filters.. */
1222 for (j = 0; j < tcs->filter_count; j++)
1224 if (entry.tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1225 break ;
1228 if (j < tcs->filter_count)
1229 continue ;
1231 /* Check for conditions. */
1232 if (!check_clauses(tcs, &entry, tcs->clause, tcs->clause_count))
1233 continue;
1235 /* Add to the seek list if not already in uniq buffer. */
1236 if (!add_uniqbuf(tcs, entry.tag_seek[tcs->type]))
1237 continue;
1239 /* Lets add it. */
1240 seeklist = &tcs->seeklist[tcs->seek_list_count];
1241 seeklist->seek = entry.tag_seek[tcs->type];
1242 seeklist->flag = entry.flag;
1243 seeklist->idx_id = i;
1244 tcs->seek_list_count++;
1246 yield();
1249 return tcs->seek_list_count > 0;
1253 static void remove_files(void)
1255 int i;
1256 char buf[MAX_PATH];
1258 tc_stat.ready = false;
1259 tc_stat.ramcache = false;
1260 tc_stat.econ = false;
1261 remove(TAGCACHE_FILE_MASTER);
1262 for (i = 0; i < TAG_COUNT; i++)
1264 if (TAGCACHE_IS_NUMERIC(i))
1265 continue;
1267 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, i);
1268 remove(buf);
1273 static bool check_all_headers(void)
1275 struct master_header myhdr;
1276 struct tagcache_header tch;
1277 int tag;
1278 int fd;
1280 if ( (fd = open_master_fd(&myhdr, false)) < 0)
1281 return false;
1283 close(fd);
1284 if (myhdr.dirty)
1286 logf("tagcache is dirty!");
1287 return false;
1290 memcpy(&current_tcmh, &myhdr, sizeof(struct master_header));
1292 for (tag = 0; tag < TAG_COUNT; tag++)
1294 if (TAGCACHE_IS_NUMERIC(tag))
1295 continue;
1297 if ( (fd = open_tag_fd(&tch, tag, false)) < 0)
1298 return false;
1300 close(fd);
1303 return true;
1306 bool tagcache_is_busy(void)
1308 return read_lock || write_lock;
1311 bool tagcache_search(struct tagcache_search *tcs, int tag)
1313 struct tagcache_header tag_hdr;
1314 struct master_header master_hdr;
1315 int i;
1317 while (read_lock)
1318 sleep(1);
1320 memset(tcs, 0, sizeof(struct tagcache_search));
1321 if (tc_stat.commit_step > 0 || !tc_stat.ready)
1322 return false;
1324 tcs->position = sizeof(struct tagcache_header);
1325 tcs->type = tag;
1326 tcs->seek_pos = 0;
1327 tcs->list_position = 0;
1328 tcs->seek_list_count = 0;
1329 tcs->filter_count = 0;
1330 tcs->masterfd = -1;
1332 for (i = 0; i < TAG_COUNT; i++)
1333 tcs->idxfd[i] = -1;
1335 #ifndef HAVE_TC_RAMCACHE
1336 tcs->ramsearch = false;
1337 #else
1338 tcs->ramsearch = tc_stat.ramcache;
1339 if (tcs->ramsearch)
1341 tcs->entry_count = ramcache_hdr->entry_count[tcs->type];
1343 else
1344 #endif
1346 /* Always open as R/W so we can pass tcs to functions that modify data also
1347 * without failing. */
1348 tcs->masterfd = open_master_fd(&master_hdr, true);
1349 if (tcs->masterfd < 0)
1350 return false;
1352 if (!TAGCACHE_IS_NUMERIC(tcs->type))
1354 tcs->idxfd[tcs->type] = open_tag_fd(&tag_hdr, tcs->type, false);
1355 if (tcs->idxfd[tcs->type] < 0)
1356 return false;
1358 tcs->entry_count = tag_hdr.entry_count;
1360 else
1362 tcs->entry_count = master_hdr.tch.entry_count;
1366 tcs->valid = true;
1367 tcs->initialized = true;
1368 write_lock++;
1370 return true;
1373 void tagcache_search_set_uniqbuf(struct tagcache_search *tcs,
1374 void *buffer, long length)
1376 tcs->unique_list = (unsigned long *)buffer;
1377 tcs->unique_list_capacity = length / sizeof(*tcs->unique_list);
1378 tcs->unique_list_count = 0;
1381 bool tagcache_search_add_filter(struct tagcache_search *tcs,
1382 int tag, int seek)
1384 if (tcs->filter_count == TAGCACHE_MAX_FILTERS)
1385 return false;
1387 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag))
1388 return false;
1390 tcs->filter_tag[tcs->filter_count] = tag;
1391 tcs->filter_seek[tcs->filter_count] = seek;
1392 tcs->filter_count++;
1394 return true;
1397 bool tagcache_search_add_clause(struct tagcache_search *tcs,
1398 struct tagcache_search_clause *clause)
1400 int i;
1402 if (tcs->clause_count >= TAGCACHE_MAX_CLAUSES)
1404 logf("Too many clauses");
1405 return false;
1408 if (clause->type != clause_logical_or)
1410 /* Check if there is already a similar filter in present (filters are
1411 * much faster than clauses).
1413 for (i = 0; i < tcs->filter_count; i++)
1415 if (tcs->filter_tag[i] == clause->tag)
1416 return true;
1419 if (!TAGCACHE_IS_NUMERIC(clause->tag) && tcs->idxfd[clause->tag] < 0)
1421 char buf[MAX_PATH];
1423 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, clause->tag);
1424 tcs->idxfd[clause->tag] = open(buf, O_RDONLY);
1428 tcs->clause[tcs->clause_count] = clause;
1429 tcs->clause_count++;
1431 return true;
1434 static bool get_next(struct tagcache_search *tcs)
1436 static char buf[TAG_MAXLEN+32];
1437 struct tagfile_entry entry;
1438 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1439 long flag = 0;
1440 #endif
1442 if (!tcs->valid || !tc_stat.ready)
1443 return false;
1445 if (tcs->idxfd[tcs->type] < 0 && !TAGCACHE_IS_NUMERIC(tcs->type)
1446 #ifdef HAVE_TC_RAMCACHE
1447 && !tcs->ramsearch
1448 #endif
1450 return false;
1452 /* Relative fetch. */
1453 if (tcs->filter_count > 0 || tcs->clause_count > 0
1454 || TAGCACHE_IS_NUMERIC(tcs->type)
1455 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1456 /* We need to retrieve flag status for dircache. */
1457 || (tcs->ramsearch && tcs->type == tag_filename)
1458 #endif
1461 struct tagcache_seeklist_entry *seeklist;
1463 /* Check for end of list. */
1464 if (tcs->list_position == tcs->seek_list_count)
1466 tcs->list_position = 0;
1468 /* Try to fetch more. */
1469 if (!build_lookup_list(tcs))
1471 tcs->valid = false;
1472 return false;
1476 seeklist = &tcs->seeklist[tcs->list_position];
1477 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1478 flag = seeklist->flag;
1479 #endif
1480 tcs->position = seeklist->seek;
1481 tcs->idx_id = seeklist->idx_id;
1482 tcs->list_position++;
1484 else
1486 if (tcs->entry_count == 0)
1488 tcs->valid = false;
1489 return false;
1492 tcs->entry_count--;
1495 tcs->result_seek = tcs->position;
1497 if (TAGCACHE_IS_NUMERIC(tcs->type))
1499 snprintf(buf, sizeof(buf), "%ld", tcs->position);
1500 tcs->result = buf;
1501 tcs->result_len = strlen(buf) + 1;
1502 return true;
1505 /* Direct fetch. */
1506 #ifdef HAVE_TC_RAMCACHE
1507 if (tcs->ramsearch)
1510 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1511 if (tcs->type == tag_filename && (flag & FLAG_DIRCACHE))
1513 if (is_dircache_intact())
1515 size_t len = dircache_copy_path(tcs->position, buf, sizeof buf);
1516 tcs->result_len = len + 1;
1517 tcs->result = buf;
1518 tcs->ramresult = false;
1520 return true;
1522 else
1524 /* The seek is useless now, there's nothing we can return. */
1525 logf("get_next: dircache gone, cannot read file name");
1526 tagcache_unload_ramcache();
1527 // XXX do this when there's a way to not trigger an
1528 // update before reloading:
1529 // tagcache_start_scan();
1530 tcs->valid = false;
1531 return false;
1534 else
1535 #endif
1536 if (tcs->type != tag_filename)
1538 struct tagfile_entry *ep;
1540 ep = (struct tagfile_entry *)&ramcache_hdr->tags[tcs->type][tcs->position];
1541 tcs->result = ep->tag_data;
1542 tcs->result_len = strlen(tcs->result) + 1;
1543 tcs->idx_id = ep->idx_id;
1544 tcs->ramresult = true;
1546 /* Increase position for the next run. This may get overwritten. */
1547 tcs->position += sizeof(struct tagfile_entry) + ep->tag_length;
1549 return true;
1552 #endif
1554 if (!open_files(tcs, tcs->type))
1556 tcs->valid = false;
1557 return false;
1560 /* Seek stream to the correct position and continue to direct fetch. */
1561 lseek(tcs->idxfd[tcs->type], tcs->position, SEEK_SET);
1563 if (ecread_tagfile_entry(tcs->idxfd[tcs->type], &entry) != sizeof(struct tagfile_entry))
1565 logf("read error #5");
1566 tcs->valid = false;
1567 return false;
1570 if (entry.tag_length > (long)sizeof(buf))
1572 tcs->valid = false;
1573 logf("too long tag #2");
1574 logf("P:%lX/%lX", tcs->position, entry.tag_length);
1575 return false;
1578 if (read(tcs->idxfd[tcs->type], buf, entry.tag_length) != entry.tag_length)
1580 tcs->valid = false;
1581 logf("read error #4");
1582 return false;
1586 Update the position for the next read (this may be overridden
1587 if filters or clauses are being used).
1589 tcs->position += sizeof(struct tagfile_entry) + entry.tag_length;
1590 tcs->result = buf;
1591 tcs->result_len = strlen(tcs->result) + 1;
1592 tcs->idx_id = entry.idx_id;
1593 tcs->ramresult = false;
1595 return true;
1598 bool tagcache_get_next(struct tagcache_search *tcs)
1600 while (get_next(tcs))
1602 if (tcs->result_len > 1)
1603 return true;
1606 return false;
1609 bool tagcache_retrieve(struct tagcache_search *tcs, int idxid,
1610 int tag, char *buf, long size)
1612 struct index_entry idx;
1614 *buf = '\0';
1615 if (!get_index(tcs->masterfd, idxid, &idx, true))
1616 return false;
1618 return retrieve(tcs, &idx, tag, buf, size);
1621 static bool update_master_header(void)
1623 struct master_header myhdr;
1624 int fd;
1626 if (!tc_stat.ready)
1627 return false;
1629 if ( (fd = open_master_fd(&myhdr, true)) < 0)
1630 return false;
1632 myhdr.serial = current_tcmh.serial;
1633 myhdr.commitid = current_tcmh.commitid;
1634 myhdr.dirty = current_tcmh.dirty;
1636 /* Write it back */
1637 lseek(fd, 0, SEEK_SET);
1638 ecwrite(fd, &myhdr, 1, master_header_ec, tc_stat.econ);
1639 close(fd);
1641 return true;
1644 void tagcache_search_finish(struct tagcache_search *tcs)
1646 int i;
1648 if (!tcs->initialized)
1649 return;
1651 if (tcs->masterfd >= 0)
1653 close(tcs->masterfd);
1654 tcs->masterfd = -1;
1657 for (i = 0; i < TAG_COUNT; i++)
1659 if (tcs->idxfd[i] >= 0)
1661 close(tcs->idxfd[i]);
1662 tcs->idxfd[i] = -1;
1666 tcs->ramsearch = false;
1667 tcs->valid = false;
1668 tcs->initialized = 0;
1669 if (write_lock > 0)
1670 write_lock--;
1673 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1674 static struct tagfile_entry *get_tag(const struct index_entry *entry, int tag)
1676 return (struct tagfile_entry *)&ramcache_hdr->tags[tag][entry->tag_seek[tag]];
1679 static long get_tag_numeric(const struct index_entry *entry, int tag, int idx_id)
1681 return check_virtual_tags(tag, idx_id, entry);
1684 static char* get_tag_string(const struct index_entry *entry, int tag)
1686 char* s = get_tag(entry, tag)->tag_data;
1687 return strcmp(s, UNTAGGED) ? s : NULL;
1690 bool tagcache_fill_tags(struct mp3entry *id3, const char *filename)
1692 struct index_entry *entry;
1693 int idx_id;
1695 if (!tc_stat.ready || !tc_stat.ramcache)
1696 return false;
1698 /* Find the corresponding entry in tagcache. */
1699 idx_id = find_entry_ram(filename, -1);
1700 if (idx_id < 0)
1701 return false;
1703 entry = &ramcache_hdr->indices[idx_id];
1705 memset(id3, 0, sizeof(struct mp3entry));
1707 id3->title = get_tag_string(entry, tag_title);
1708 id3->artist = get_tag_string(entry, tag_artist);
1709 id3->album = get_tag_string(entry, tag_album);
1710 id3->genre_string = get_tag_string(entry, tag_genre);
1711 id3->composer = get_tag_string(entry, tag_composer);
1712 id3->comment = get_tag_string(entry, tag_comment);
1713 id3->albumartist = get_tag_string(entry, tag_albumartist);
1714 id3->grouping = get_tag_string(entry, tag_grouping);
1716 id3->length = get_tag_numeric(entry, tag_length, idx_id);
1717 id3->playcount = get_tag_numeric(entry, tag_playcount, idx_id);
1718 id3->rating = get_tag_numeric(entry, tag_rating, idx_id);
1719 id3->lastplayed = get_tag_numeric(entry, tag_lastplayed, idx_id);
1720 id3->score = get_tag_numeric(entry, tag_virt_autoscore, idx_id) / 10;
1721 id3->year = get_tag_numeric(entry, tag_year, idx_id);
1723 id3->discnum = get_tag_numeric(entry, tag_discnumber, idx_id);
1724 id3->tracknum = get_tag_numeric(entry, tag_tracknumber, idx_id);
1725 id3->bitrate = get_tag_numeric(entry, tag_bitrate, idx_id);
1726 if (id3->bitrate == 0)
1727 id3->bitrate = 1;
1729 #if CONFIG_CODEC == SWCODEC
1730 if (global_settings.autoresume_enable)
1732 id3->offset = get_tag_numeric(entry, tag_lastoffset, idx_id);
1733 logf("tagcache_fill_tags: Set offset for %s to %lX\n",
1734 id3->title, id3->offset);
1736 #endif
1738 return true;
1740 #endif
1742 static inline void write_item(const char *item)
1744 int len = strlen(item) + 1;
1746 data_size += len;
1747 write(cachefd, item, len);
1750 static int check_if_empty(char **tag)
1752 int length;
1754 if (*tag == NULL || **tag == '\0')
1756 *tag = UNTAGGED;
1757 return sizeof(UNTAGGED); /* Tag length */
1760 length = strlen(*tag);
1761 if (length > TAG_MAXLEN)
1763 logf("over length tag: %s", *tag);
1764 length = TAG_MAXLEN;
1765 (*tag)[length] = '\0';
1768 return length + 1;
1771 #define ADD_TAG(entry,tag,data) \
1772 /* Adding tag */ \
1773 entry.tag_offset[tag] = offset; \
1774 entry.tag_length[tag] = check_if_empty(data); \
1775 offset += entry.tag_length[tag]
1776 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1777 * idea, as it uses lots of stack and is called from a recursive function
1778 * (check_dir).
1780 static void __attribute__ ((noinline)) add_tagcache(char *path,
1781 unsigned long mtime
1782 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1783 ,int dc
1784 #endif
1787 struct mp3entry id3;
1788 struct temp_file_entry entry;
1789 bool ret;
1790 int fd;
1791 int idx_id = -1;
1792 char tracknumfix[3];
1793 int offset = 0;
1794 int path_length = strlen(path);
1795 bool has_albumartist;
1796 bool has_grouping;
1798 #ifdef SIMULATOR
1799 /* Crude logging for the sim - to aid in debugging */
1800 int logfd = open(ROCKBOX_DIR "/database.log",
1801 O_WRONLY | O_APPEND | O_CREAT, 0666);
1802 if (logfd >= 0) {
1803 write(logfd, path, strlen(path));
1804 write(logfd, "\n", 1);
1805 close(logfd);
1807 #endif
1809 if (cachefd < 0)
1810 return ;
1812 /* Check for overlength file path. */
1813 if (path_length > TAG_MAXLEN)
1815 /* Path can't be shortened. */
1816 logf("Too long path: %s", path);
1817 return ;
1820 /* Check if the file is supported. */
1821 if (probe_file_format(path) == AFMT_UNKNOWN)
1822 return ;
1824 /* Check if the file is already cached. */
1825 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1826 idx_id = find_entry_ram(path, dc);
1827 #endif
1829 /* Be sure the entry doesn't exist. */
1830 if (filenametag_fd >= 0 && idx_id < 0)
1831 idx_id = find_entry_disk(path, false);
1833 /* Check if file has been modified. */
1834 if (idx_id >= 0)
1836 struct index_entry idx;
1838 /* TODO: Mark that the index exists (for fast reverse scan) */
1839 //found_idx[idx_id/8] |= idx_id%8;
1841 if (!get_index(-1, idx_id, &idx, true))
1843 logf("failed to retrieve index entry");
1844 return ;
1847 if ((unsigned long)idx.tag_seek[tag_mtime] == mtime)
1849 /* No changes to file. */
1850 return ;
1853 /* Metadata might have been changed. Delete the entry. */
1854 logf("Re-adding: %s", path);
1855 if (!delete_entry(idx_id))
1857 logf("delete_entry failed: %d", idx_id);
1858 return ;
1862 fd = open(path, O_RDONLY);
1863 if (fd < 0)
1865 logf("open fail: %s", path);
1866 return ;
1869 memset(&id3, 0, sizeof(struct mp3entry));
1870 memset(&entry, 0, sizeof(struct temp_file_entry));
1871 memset(&tracknumfix, 0, sizeof(tracknumfix));
1872 ret = get_metadata(&id3, fd, path);
1873 close(fd);
1875 if (!ret)
1876 return ;
1878 logf("-> %s", path);
1880 if (id3.tracknum <= 0) /* Track number missing? */
1882 id3.tracknum = -1;
1885 /* Numeric tags */
1886 entry.tag_offset[tag_year] = id3.year;
1887 entry.tag_offset[tag_discnumber] = id3.discnum;
1888 entry.tag_offset[tag_tracknumber] = id3.tracknum;
1889 entry.tag_offset[tag_length] = id3.length;
1890 entry.tag_offset[tag_bitrate] = id3.bitrate;
1891 entry.tag_offset[tag_mtime] = mtime;
1893 /* String tags. */
1894 has_albumartist = id3.albumartist != NULL
1895 && strlen(id3.albumartist) > 0;
1896 has_grouping = id3.grouping != NULL
1897 && strlen(id3.grouping) > 0;
1899 ADD_TAG(entry, tag_filename, &path);
1900 ADD_TAG(entry, tag_title, &id3.title);
1901 ADD_TAG(entry, tag_artist, &id3.artist);
1902 ADD_TAG(entry, tag_album, &id3.album);
1903 ADD_TAG(entry, tag_genre, &id3.genre_string);
1904 ADD_TAG(entry, tag_composer, &id3.composer);
1905 ADD_TAG(entry, tag_comment, &id3.comment);
1906 if (has_albumartist)
1908 ADD_TAG(entry, tag_albumartist, &id3.albumartist);
1910 else
1912 ADD_TAG(entry, tag_albumartist, &id3.artist);
1914 if (has_grouping)
1916 ADD_TAG(entry, tag_grouping, &id3.grouping);
1918 else
1920 ADD_TAG(entry, tag_grouping, &id3.title);
1922 entry.data_length = offset;
1924 /* Write the header */
1925 write(cachefd, &entry, sizeof(struct temp_file_entry));
1927 /* And tags also... Correct order is critical */
1928 write_item(path);
1929 write_item(id3.title);
1930 write_item(id3.artist);
1931 write_item(id3.album);
1932 write_item(id3.genre_string);
1933 write_item(id3.composer);
1934 write_item(id3.comment);
1935 if (has_albumartist)
1937 write_item(id3.albumartist);
1939 else
1941 write_item(id3.artist);
1943 if (has_grouping)
1945 write_item(id3.grouping);
1947 else
1949 write_item(id3.title);
1951 total_entry_count++;
1954 static bool tempbuf_insert(char *str, int id, int idx_id, bool unique)
1956 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
1957 int len = strlen(str)+1;
1958 int i;
1959 unsigned crc32;
1960 unsigned *crcbuf = (unsigned *)&tempbuf[tempbuf_size-4];
1961 char buf[TAG_MAXLEN+32];
1963 for (i = 0; str[i] != '\0' && i < (int)sizeof(buf)-1; i++)
1964 buf[i] = tolower(str[i]);
1965 buf[i] = '\0';
1967 crc32 = crc_32(buf, i, 0xffffffff);
1969 if (unique)
1971 /* Check if the crc does not exist -> entry does not exist for sure. */
1972 for (i = 0; i < tempbufidx; i++)
1974 if (crcbuf[-i] != crc32)
1975 continue;
1977 if (!strcasecmp(str, index[i].str))
1979 if (id < 0 || id >= lookup_buffer_depth)
1981 logf("lookup buf overf.: %d", id);
1982 return false;
1985 lookup[id] = &index[i];
1986 return true;
1991 /* Insert to CRC buffer. */
1992 crcbuf[-tempbufidx] = crc32;
1993 tempbuf_left -= 4;
1995 /* Insert it to the buffer. */
1996 tempbuf_left -= len;
1997 if (tempbuf_left - 4 < 0 || tempbufidx >= commit_entry_count-1)
1998 return false;
2000 if (id >= lookup_buffer_depth)
2002 logf("lookup buf overf. #2: %d", id);
2003 return false;
2006 if (id >= 0)
2008 lookup[id] = &index[tempbufidx];
2009 index[tempbufidx].idlist.id = id;
2011 else
2012 index[tempbufidx].idlist.id = -1;
2014 index[tempbufidx].idlist.next = NULL;
2015 index[tempbufidx].idx_id = idx_id;
2016 index[tempbufidx].seek = -1;
2017 index[tempbufidx].str = &tempbuf[tempbuf_pos];
2018 memcpy(index[tempbufidx].str, str, len);
2019 tempbuf_pos += len;
2020 tempbufidx++;
2022 return true;
2025 static int compare(const void *p1, const void *p2)
2027 do_timed_yield();
2029 struct tempbuf_searchidx *e1 = (struct tempbuf_searchidx *)p1;
2030 struct tempbuf_searchidx *e2 = (struct tempbuf_searchidx *)p2;
2032 if (strcmp(e1->str, UNTAGGED) == 0)
2034 if (strcmp(e2->str, UNTAGGED) == 0)
2035 return 0;
2036 return -1;
2038 else if (strcmp(e2->str, UNTAGGED) == 0)
2039 return 1;
2041 return strncasecmp(e1->str, e2->str, TAG_MAXLEN);
2044 static int tempbuf_sort(int fd)
2046 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
2047 struct tagfile_entry fe;
2048 int i;
2049 int length;
2051 /* Generate reverse lookup entries. */
2052 for (i = 0; i < lookup_buffer_depth; i++)
2054 struct tempbuf_id_list *idlist;
2056 if (!lookup[i])
2057 continue;
2059 if (lookup[i]->idlist.id == i)
2060 continue;
2062 idlist = &lookup[i]->idlist;
2063 while (idlist->next != NULL)
2064 idlist = idlist->next;
2066 tempbuf_left -= sizeof(struct tempbuf_id_list);
2067 if (tempbuf_left - 4 < 0)
2068 return -1;
2070 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2071 if (tempbuf_pos & 0x03)
2073 tempbuf_pos = (tempbuf_pos & ~0x03) + 0x04;
2074 tempbuf_left -= 3;
2075 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2077 tempbuf_pos += sizeof(struct tempbuf_id_list);
2079 idlist = idlist->next;
2080 idlist->id = i;
2081 idlist->next = NULL;
2083 do_timed_yield();
2086 qsort(index, tempbufidx, sizeof(struct tempbuf_searchidx), compare);
2087 memset(lookup, 0, lookup_buffer_depth * sizeof(struct tempbuf_searchidx **));
2089 for (i = 0; i < tempbufidx; i++)
2091 struct tempbuf_id_list *idlist = &index[i].idlist;
2093 /* Fix the lookup list. */
2094 while (idlist != NULL)
2096 if (idlist->id >= 0)
2097 lookup[idlist->id] = &index[i];
2098 idlist = idlist->next;
2101 index[i].seek = lseek(fd, 0, SEEK_CUR);
2102 length = strlen(index[i].str) + 1;
2103 fe.tag_length = length;
2104 fe.idx_id = index[i].idx_id;
2106 /* Check the chunk alignment. */
2107 if ((fe.tag_length + sizeof(struct tagfile_entry))
2108 % TAGFILE_ENTRY_CHUNK_LENGTH)
2110 fe.tag_length += TAGFILE_ENTRY_CHUNK_LENGTH -
2111 ((fe.tag_length + sizeof(struct tagfile_entry))
2112 % TAGFILE_ENTRY_CHUNK_LENGTH);
2115 #ifdef TAGCACHE_STRICT_ALIGN
2116 /* Make sure the entry is long aligned. */
2117 if (index[i].seek & 0x03)
2119 logf("tempbuf_sort: alignment error!");
2120 return -3;
2122 #endif
2124 if (ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ) !=
2125 sizeof(struct tagfile_entry))
2127 logf("tempbuf_sort: write error #1");
2128 return -1;
2131 if (write(fd, index[i].str, length) != length)
2133 logf("tempbuf_sort: write error #2");
2134 return -2;
2137 /* Write some padding. */
2138 if (fe.tag_length - length > 0)
2139 write(fd, "XXXXXXXX", fe.tag_length - length);
2142 return i;
2145 inline static struct tempbuf_searchidx* tempbuf_locate(int id)
2147 if (id < 0 || id >= lookup_buffer_depth)
2148 return NULL;
2150 return lookup[id];
2154 inline static int tempbuf_find_location(int id)
2156 struct tempbuf_searchidx *entry;
2158 entry = tempbuf_locate(id);
2159 if (entry == NULL)
2160 return -1;
2162 return entry->seek;
2165 static bool build_numeric_indices(struct tagcache_header *h, int tmpfd)
2167 struct master_header tcmh;
2168 struct index_entry idx;
2169 int masterfd;
2170 int masterfd_pos;
2171 struct temp_file_entry *entrybuf = (struct temp_file_entry *)tempbuf;
2172 int max_entries;
2173 int entries_processed = 0;
2174 int i, j;
2175 char buf[TAG_MAXLEN];
2177 max_entries = tempbuf_size / sizeof(struct temp_file_entry) - 1;
2179 logf("Building numeric indices...");
2180 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2182 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
2183 return false;
2185 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2186 SEEK_CUR);
2187 if (masterfd_pos == filesize(masterfd))
2189 logf("we can't append!");
2190 close(masterfd);
2191 return false;
2194 while (entries_processed < h->entry_count)
2196 int count = MIN(h->entry_count - entries_processed, max_entries);
2198 /* Read in as many entries as possible. */
2199 for (i = 0; i < count; i++)
2201 struct temp_file_entry *tfe = &entrybuf[i];
2202 int datastart;
2204 /* Read in numeric data. */
2205 if (read(tmpfd, tfe, sizeof(struct temp_file_entry)) !=
2206 sizeof(struct temp_file_entry))
2208 logf("read fail #1");
2209 close(masterfd);
2210 return false;
2213 datastart = lseek(tmpfd, 0, SEEK_CUR);
2216 * Read string data from the following tags:
2217 * - tag_filename
2218 * - tag_artist
2219 * - tag_album
2220 * - tag_title
2222 * A crc32 hash is calculated from the read data
2223 * and stored back to the data offset field kept in memory.
2225 #define tmpdb_read_string_tag(tag) \
2226 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2227 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2229 logf("read fail: buffer overflow"); \
2230 close(masterfd); \
2231 return false; \
2234 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2235 tfe->tag_length[tag]) \
2237 logf("read fail #2"); \
2238 close(masterfd); \
2239 return false; \
2242 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2243 lseek(tmpfd, datastart, SEEK_SET)
2245 tmpdb_read_string_tag(tag_filename);
2246 tmpdb_read_string_tag(tag_artist);
2247 tmpdb_read_string_tag(tag_album);
2248 tmpdb_read_string_tag(tag_title);
2250 /* Seek to the end of the string data. */
2251 lseek(tmpfd, tfe->data_length, SEEK_CUR);
2254 /* Backup the master index position. */
2255 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2256 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2258 /* Check if we can resurrect some deleted runtime statistics data. */
2259 for (i = 0; i < tcmh.tch.entry_count; i++)
2261 /* Read the index entry. */
2262 if (ecread_index_entry(masterfd, &idx)
2263 != sizeof(struct index_entry))
2265 logf("read fail #3");
2266 close(masterfd);
2267 return false;
2271 * Skip unless the entry is marked as being deleted
2272 * or the data has already been resurrected.
2274 if (!(idx.flag & FLAG_DELETED) || idx.flag & FLAG_RESURRECTED)
2275 continue;
2277 /* Now try to match the entry. */
2279 * To succesfully match a song, the following conditions
2280 * must apply:
2282 * For numeric fields: tag_length
2283 * - Full identical match is required
2285 * If tag_filename matches, no further checking necessary.
2287 * For string hashes: tag_artist, tag_album, tag_title
2288 * - All three of these must match
2290 for (j = 0; j < count; j++)
2292 struct temp_file_entry *tfe = &entrybuf[j];
2294 /* Try to match numeric fields first. */
2295 if (tfe->tag_offset[tag_length] != idx.tag_seek[tag_length])
2296 continue;
2298 /* Now it's time to do the hash matching. */
2299 if (tfe->tag_offset[tag_filename] != idx.tag_seek[tag_filename])
2301 int match_count = 0;
2303 /* No filename match, check if we can match two other tags. */
2304 #define tmpdb_match(tag) \
2305 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2306 match_count++
2308 tmpdb_match(tag_artist);
2309 tmpdb_match(tag_album);
2310 tmpdb_match(tag_title);
2312 if (match_count < 3)
2314 /* Still no match found, give up. */
2315 continue;
2319 /* A match found, now copy & resurrect the statistical data. */
2320 #define tmpdb_copy_tag(tag) \
2321 tfe->tag_offset[tag] = idx.tag_seek[tag]
2323 tmpdb_copy_tag(tag_playcount);
2324 tmpdb_copy_tag(tag_rating);
2325 tmpdb_copy_tag(tag_playtime);
2326 tmpdb_copy_tag(tag_lastplayed);
2327 tmpdb_copy_tag(tag_commitid);
2328 tmpdb_copy_tag(tag_lastoffset);
2330 /* Avoid processing this entry again. */
2331 idx.flag |= FLAG_RESURRECTED;
2333 lseek(masterfd, -sizeof(struct index_entry), SEEK_CUR);
2334 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2336 logf("masterfd writeback fail #1");
2337 close(masterfd);
2338 return false;
2341 logf("Entry resurrected");
2346 /* Restore the master index position. */
2347 lseek(masterfd, masterfd_pos, SEEK_SET);
2349 /* Commit the data to the index. */
2350 for (i = 0; i < count; i++)
2352 int loc = lseek(masterfd, 0, SEEK_CUR);
2354 if (ecread_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2356 logf("read fail #3");
2357 close(masterfd);
2358 return false;
2361 for (j = 0; j < TAG_COUNT; j++)
2363 if (!TAGCACHE_IS_NUMERIC(j))
2364 continue;
2366 idx.tag_seek[j] = entrybuf[i].tag_offset[j];
2368 idx.flag = entrybuf[i].flag;
2370 if (idx.tag_seek[tag_commitid])
2372 /* Data has been resurrected. */
2373 idx.flag |= FLAG_DIRTYNUM;
2375 else if (tc_stat.ready && current_tcmh.commitid > 0)
2377 idx.tag_seek[tag_commitid] = current_tcmh.commitid;
2378 idx.flag |= FLAG_DIRTYNUM;
2381 /* Write back the updated index. */
2382 lseek(masterfd, loc, SEEK_SET);
2383 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2385 logf("write fail");
2386 close(masterfd);
2387 return false;
2391 entries_processed += count;
2392 logf("%d/%ld entries processed", entries_processed, h->entry_count);
2395 close(masterfd);
2397 return true;
2401 * Return values:
2402 * > 0 success
2403 * == 0 temporary failure
2404 * < 0 fatal error
2406 static int build_index(int index_type, struct tagcache_header *h, int tmpfd)
2408 int i;
2409 struct tagcache_header tch;
2410 struct master_header tcmh;
2411 struct index_entry idxbuf[IDX_BUF_DEPTH];
2412 int idxbuf_pos;
2413 char buf[TAG_MAXLEN+32];
2414 int fd = -1, masterfd;
2415 bool error = false;
2416 int init;
2417 int masterfd_pos;
2419 logf("Building index: %d", index_type);
2421 /* Check the number of entries we need to allocate ram for. */
2422 commit_entry_count = h->entry_count + 1;
2424 masterfd = open_master_fd(&tcmh, false);
2425 if (masterfd >= 0)
2427 commit_entry_count += tcmh.tch.entry_count;
2428 close(masterfd);
2430 else
2431 remove_files(); /* Just to be sure we are clean. */
2433 /* Open the index file, which contains the tag names. */
2434 fd = open_tag_fd(&tch, index_type, true);
2435 if (fd >= 0)
2437 logf("tch.datasize=%ld", tch.datasize);
2438 lookup_buffer_depth = 1 +
2439 /* First part */ commit_entry_count +
2440 /* Second part */ (tch.datasize / TAGFILE_ENTRY_CHUNK_LENGTH);
2442 else
2444 lookup_buffer_depth = 1 +
2445 /* First part */ commit_entry_count +
2446 /* Second part */ 0;
2449 logf("lookup_buffer_depth=%ld", lookup_buffer_depth);
2450 logf("commit_entry_count=%ld", commit_entry_count);
2452 /* Allocate buffer for all index entries from both old and new
2453 * tag files. */
2454 tempbufidx = 0;
2455 tempbuf_pos = commit_entry_count * sizeof(struct tempbuf_searchidx);
2457 /* Allocate lookup buffer. The first portion of commit_entry_count
2458 * contains the new tags in the temporary file and the second
2459 * part for locating entries already in the db.
2461 * New tags Old tags
2462 * +---------+---------------------------+
2463 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2464 * +---------+---------------------------+
2466 * Old tags are inserted to a temporary buffer with position:
2467 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2468 * And new tags with index:
2469 * tempbuf_insert(idx, ...);
2471 * The buffer is sorted and written into tag file:
2472 * tempbuf_sort(...);
2473 * leaving master index locations messed up.
2475 * That is fixed using the lookup buffer for old tags:
2476 * new_seek = tempbuf_find_location(old_seek, ...);
2477 * and for new tags:
2478 * new_seek = tempbuf_find_location(idx);
2480 lookup = (struct tempbuf_searchidx **)&tempbuf[tempbuf_pos];
2481 tempbuf_pos += lookup_buffer_depth * sizeof(void **);
2482 memset(lookup, 0, lookup_buffer_depth * sizeof(void **));
2484 /* And calculate the remaining data space used mainly for storing
2485 * tag data (strings). */
2486 tempbuf_left = tempbuf_size - tempbuf_pos - 8;
2487 if (tempbuf_left - TAGFILE_ENTRY_AVG_LENGTH * commit_entry_count < 0)
2489 logf("Buffer way too small!");
2490 return 0;
2493 if (fd >= 0)
2496 * If tag file contains unique tags (sorted index), we will load
2497 * it entirely into memory so we can resort it later for use with
2498 * chunked browsing.
2500 if (TAGCACHE_IS_SORTED(index_type))
2502 logf("loading tags...");
2503 for (i = 0; i < tch.entry_count; i++)
2505 struct tagfile_entry entry;
2506 int loc = lseek(fd, 0, SEEK_CUR);
2507 bool ret;
2509 if (ecread_tagfile_entry(fd, &entry) != sizeof(struct tagfile_entry))
2511 logf("read error #7");
2512 close(fd);
2513 return -2;
2516 if (entry.tag_length >= (int)sizeof(buf))
2518 logf("too long tag #3");
2519 close(fd);
2520 return -2;
2523 if (read(fd, buf, entry.tag_length) != entry.tag_length)
2525 logf("read error #8");
2526 close(fd);
2527 return -2;
2530 /* Skip deleted entries. */
2531 if (buf[0] == '\0')
2532 continue;
2535 * Save the tag and tag id in the memory buffer. Tag id
2536 * is saved so we can later reindex the master lookup
2537 * table when the index gets resorted.
2539 ret = tempbuf_insert(buf, loc/TAGFILE_ENTRY_CHUNK_LENGTH
2540 + commit_entry_count, entry.idx_id,
2541 TAGCACHE_IS_UNIQUE(index_type));
2542 if (!ret)
2544 close(fd);
2545 return -3;
2547 do_timed_yield();
2549 logf("done");
2551 else
2552 tempbufidx = tch.entry_count;
2554 else
2557 * Creating new index file to store the tags. No need to preload
2558 * anything whether the index type is sorted or not.
2560 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, index_type);
2561 fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2562 if (fd < 0)
2564 logf("%s open fail", buf);
2565 return -2;
2568 tch.magic = TAGCACHE_MAGIC;
2569 tch.entry_count = 0;
2570 tch.datasize = 0;
2572 if (ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ)
2573 != sizeof(struct tagcache_header))
2575 logf("header write failed");
2576 close(fd);
2577 return -2;
2581 /* Loading the tag lookup file as "master file". */
2582 logf("Loading index file");
2583 masterfd = open(TAGCACHE_FILE_MASTER, O_RDWR);
2585 if (masterfd < 0)
2587 logf("Creating new DB");
2588 masterfd = open(TAGCACHE_FILE_MASTER, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2590 if (masterfd < 0)
2592 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER);
2593 close(fd);
2594 return -2;
2597 /* Write the header (write real values later). */
2598 memset(&tcmh, 0, sizeof(struct master_header));
2599 tcmh.tch = *h;
2600 tcmh.tch.entry_count = 0;
2601 tcmh.tch.datasize = 0;
2602 tcmh.dirty = true;
2603 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
2604 init = true;
2605 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2607 else
2610 * Master file already exists so we need to process the current
2611 * file first.
2613 init = false;
2615 if (ecread(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ) !=
2616 sizeof(struct master_header) || tcmh.tch.magic != TAGCACHE_MAGIC)
2618 logf("header error");
2619 close(fd);
2620 close(masterfd);
2621 return -2;
2625 * If we reach end of the master file, we need to expand it to
2626 * hold new tags. If the current index is not sorted, we can
2627 * simply append new data to end of the file.
2628 * However, if the index is sorted, we need to update all tag
2629 * pointers in the master file for the current index.
2631 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2632 SEEK_CUR);
2633 if (masterfd_pos == filesize(masterfd))
2635 logf("appending...");
2636 init = true;
2641 * Load new unique tags in memory to be sorted later and added
2642 * to the master lookup file.
2644 if (TAGCACHE_IS_SORTED(index_type))
2646 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2647 /* h is the header of the temporary file containing new tags. */
2648 logf("inserting new tags...");
2649 for (i = 0; i < h->entry_count; i++)
2651 struct temp_file_entry entry;
2653 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2654 sizeof(struct temp_file_entry))
2656 logf("read fail #3");
2657 error = true;
2658 goto error_exit;
2661 /* Read data. */
2662 if (entry.tag_length[index_type] >= (long)sizeof(buf))
2664 logf("too long entry!");
2665 error = true;
2666 goto error_exit;
2669 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2670 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2671 entry.tag_length[index_type])
2673 logf("read fail #4");
2674 error = true;
2675 goto error_exit;
2678 if (TAGCACHE_IS_UNIQUE(index_type))
2679 error = !tempbuf_insert(buf, i, -1, true);
2680 else
2681 error = !tempbuf_insert(buf, i, tcmh.tch.entry_count + i, false);
2683 if (error)
2685 logf("insert error");
2686 goto error_exit;
2689 /* Skip to next. */
2690 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2691 entry.tag_length[index_type], SEEK_CUR);
2692 do_timed_yield();
2694 logf("done");
2696 /* Sort the buffer data and write it to the index file. */
2697 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
2699 * We need to truncate the index file now. There can be junk left
2700 * at the end of file (however, we _should_ always follow the
2701 * entry_count and don't crash with that).
2703 ftruncate(fd, lseek(fd, 0, SEEK_CUR));
2705 i = tempbuf_sort(fd);
2706 if (i < 0)
2707 goto error_exit;
2708 logf("sorted %d tags", i);
2711 * Now update all indexes in the master lookup file.
2713 logf("updating indices...");
2714 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2715 for (i = 0; i < tcmh.tch.entry_count; i += idxbuf_pos)
2717 int j;
2718 int loc = lseek(masterfd, 0, SEEK_CUR);
2720 idxbuf_pos = MIN(tcmh.tch.entry_count - i, IDX_BUF_DEPTH);
2722 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2723 != (int)sizeof(struct index_entry)*idxbuf_pos)
2725 logf("read fail #5");
2726 error = true;
2727 goto error_exit ;
2729 lseek(masterfd, loc, SEEK_SET);
2731 for (j = 0; j < idxbuf_pos; j++)
2733 if (idxbuf[j].flag & FLAG_DELETED)
2735 /* We can just ignore deleted entries. */
2736 // idxbuf[j].tag_seek[index_type] = 0;
2737 continue;
2740 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(
2741 idxbuf[j].tag_seek[index_type]/TAGFILE_ENTRY_CHUNK_LENGTH
2742 + commit_entry_count);
2744 if (idxbuf[j].tag_seek[index_type] < 0)
2746 logf("update error: %ld/%d/%ld",
2747 idxbuf[j].flag, i+j, tcmh.tch.entry_count);
2748 error = true;
2749 goto error_exit;
2752 do_timed_yield();
2755 /* Write back the updated index. */
2756 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2757 index_entry_ec, tc_stat.econ) !=
2758 (int)sizeof(struct index_entry)*idxbuf_pos)
2760 logf("write fail");
2761 error = true;
2762 goto error_exit;
2765 logf("done");
2769 * Walk through the temporary file containing the new tags.
2771 // build_normal_index(h, tmpfd, masterfd, idx);
2772 logf("updating new indices...");
2773 lseek(masterfd, masterfd_pos, SEEK_SET);
2774 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2775 lseek(fd, 0, SEEK_END);
2776 for (i = 0; i < h->entry_count; i += idxbuf_pos)
2778 int j;
2780 idxbuf_pos = MIN(h->entry_count - i, IDX_BUF_DEPTH);
2781 if (init)
2783 memset(idxbuf, 0, sizeof(struct index_entry)*IDX_BUF_DEPTH);
2785 else
2787 int loc = lseek(masterfd, 0, SEEK_CUR);
2789 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2790 != (int)sizeof(struct index_entry)*idxbuf_pos)
2792 logf("read fail #6");
2793 error = true;
2794 break ;
2796 lseek(masterfd, loc, SEEK_SET);
2799 /* Read entry headers. */
2800 for (j = 0; j < idxbuf_pos; j++)
2802 if (!TAGCACHE_IS_SORTED(index_type))
2804 struct temp_file_entry entry;
2805 struct tagfile_entry fe;
2807 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2808 sizeof(struct temp_file_entry))
2810 logf("read fail #7");
2811 error = true;
2812 break ;
2815 /* Read data. */
2816 if (entry.tag_length[index_type] >= (int)sizeof(buf))
2818 logf("too long entry!");
2819 logf("length=%d", entry.tag_length[index_type]);
2820 logf("pos=0x%02lx", lseek(tmpfd, 0, SEEK_CUR));
2821 error = true;
2822 break ;
2825 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2826 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2827 entry.tag_length[index_type])
2829 logf("read fail #8");
2830 logf("offset=0x%02lx", entry.tag_offset[index_type]);
2831 logf("length=0x%02x", entry.tag_length[index_type]);
2832 error = true;
2833 break ;
2836 /* Write to index file. */
2837 idxbuf[j].tag_seek[index_type] = lseek(fd, 0, SEEK_CUR);
2838 fe.tag_length = entry.tag_length[index_type];
2839 fe.idx_id = tcmh.tch.entry_count + i + j;
2840 ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ);
2841 write(fd, buf, fe.tag_length);
2842 tempbufidx++;
2844 /* Skip to next. */
2845 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2846 entry.tag_length[index_type], SEEK_CUR);
2848 else
2850 /* Locate the correct entry from the sorted array. */
2851 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(i + j);
2852 if (idxbuf[j].tag_seek[index_type] < 0)
2854 logf("entry not found (%d)", j);
2855 error = true;
2856 break ;
2861 /* Write index. */
2862 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2863 index_entry_ec, tc_stat.econ) !=
2864 (int)sizeof(struct index_entry)*idxbuf_pos)
2866 logf("tagcache: write fail #4");
2867 error = true;
2868 break ;
2871 do_timed_yield();
2873 logf("done");
2875 /* Finally write the header. */
2876 tch.magic = TAGCACHE_MAGIC;
2877 tch.entry_count = tempbufidx;
2878 tch.datasize = lseek(fd, 0, SEEK_END) - sizeof(struct tagcache_header);
2879 lseek(fd, 0, SEEK_SET);
2880 ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ);
2882 if (index_type != tag_filename)
2883 h->datasize += tch.datasize;
2884 logf("s:%d/%ld/%ld", index_type, tch.datasize, h->datasize);
2885 error_exit:
2887 close(fd);
2888 close(masterfd);
2890 if (error)
2891 return -2;
2893 return 1;
2896 static bool commit(void)
2898 struct tagcache_header tch;
2899 struct master_header tcmh;
2900 int i, len, rc;
2901 int tmpfd;
2902 int masterfd;
2903 #ifdef HAVE_DIRCACHE
2904 bool dircache_buffer_stolen = false;
2905 #endif
2906 bool local_allocation = false;
2908 logf("committing tagcache");
2910 while (write_lock)
2911 sleep(1);
2913 tmpfd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
2914 if (tmpfd < 0)
2916 logf("nothing to commit");
2917 return true;
2921 /* Load the header. */
2922 len = sizeof(struct tagcache_header);
2923 rc = read(tmpfd, &tch, len);
2925 if (tch.magic != TAGCACHE_MAGIC || rc != len)
2927 logf("incorrect tmpheader");
2928 close(tmpfd);
2929 remove(TAGCACHE_FILE_TEMP);
2930 return false;
2933 if (tch.entry_count == 0)
2935 logf("nothing to commit");
2936 close(tmpfd);
2937 remove(TAGCACHE_FILE_TEMP);
2938 return true;
2941 /* Fully initialize existing headers (if any) before going further. */
2942 tc_stat.ready = check_all_headers();
2944 #ifdef HAVE_EEPROM_SETTINGS
2945 remove(TAGCACHE_STATEFILE);
2946 #endif
2948 /* At first be sure to unload the ramcache! */
2949 #ifdef HAVE_TC_RAMCACHE
2950 tc_stat.ramcache = false;
2951 #endif
2953 read_lock++;
2955 /* Try to steal every buffer we can :) */
2956 if (tempbuf_size == 0)
2957 local_allocation = true;
2959 #ifdef HAVE_DIRCACHE
2960 if (tempbuf_size == 0)
2962 /* Try to steal the dircache buffer. */
2963 tempbuf = dircache_steal_buffer(&tempbuf_size);
2964 tempbuf_size &= ~0x03;
2966 if (tempbuf_size > 0)
2968 dircache_buffer_stolen = true;
2971 #endif
2973 #ifdef HAVE_TC_RAMCACHE
2974 if (tempbuf_size == 0 && tc_stat.ramcache_allocated > 0)
2976 tempbuf = (char *)(ramcache_hdr + 1);
2977 tempbuf_size = tc_stat.ramcache_allocated - sizeof(struct ramcache_header) - 128;
2978 tempbuf_size &= ~0x03;
2980 #endif
2982 /* And finally fail if there are no buffers available. */
2983 if (tempbuf_size == 0)
2985 logf("delaying commit until next boot");
2986 tc_stat.commit_delayed = true;
2987 close(tmpfd);
2988 read_lock--;
2989 return false;
2992 logf("commit %ld entries...", tch.entry_count);
2994 /* Mark DB dirty so it will stay disabled if commit fails. */
2995 current_tcmh.dirty = true;
2996 update_master_header();
2998 /* Now create the index files. */
2999 tc_stat.commit_step = 0;
3000 tch.datasize = 0;
3001 tc_stat.commit_delayed = false;
3003 for (i = 0; i < TAG_COUNT; i++)
3005 int ret;
3007 if (TAGCACHE_IS_NUMERIC(i))
3008 continue;
3010 tc_stat.commit_step++;
3011 ret = build_index(i, &tch, tmpfd);
3012 if (ret <= 0)
3014 close(tmpfd);
3015 logf("tagcache failed init");
3016 if (ret == 0)
3017 tc_stat.commit_delayed = true;
3019 tc_stat.commit_step = 0;
3020 read_lock--;
3021 return false;
3025 if (!build_numeric_indices(&tch, tmpfd))
3027 logf("Failure to commit numeric indices");
3028 close(tmpfd);
3029 tc_stat.commit_step = 0;
3030 read_lock--;
3031 return false;
3034 close(tmpfd);
3036 tc_stat.commit_step = 0;
3038 /* Update the master index headers. */
3039 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
3041 read_lock--;
3042 return false;
3045 remove(TAGCACHE_FILE_TEMP);
3047 tcmh.tch.entry_count += tch.entry_count;
3048 tcmh.tch.datasize = sizeof(struct master_header)
3049 + sizeof(struct index_entry) * tcmh.tch.entry_count
3050 + tch.datasize;
3051 tcmh.dirty = false;
3052 tcmh.commitid++;
3054 lseek(masterfd, 0, SEEK_SET);
3055 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
3056 close(masterfd);
3058 logf("tagcache committed");
3059 tc_stat.ready = check_all_headers();
3060 tc_stat.readyvalid = true;
3062 if (local_allocation)
3064 tempbuf = NULL;
3065 tempbuf_size = 0;
3068 #ifdef HAVE_DIRCACHE
3069 /* Rebuild the dircache, if we stole the buffer. */
3070 if (dircache_buffer_stolen)
3071 dircache_build(0);
3072 #endif
3074 #ifdef HAVE_TC_RAMCACHE
3075 /* Reload tagcache. */
3076 if (tc_stat.ramcache_allocated > 0)
3077 tagcache_start_scan();
3078 #endif
3080 read_lock--;
3082 return true;
3085 static int tempbuf_handle;
3086 static void allocate_tempbuf(void)
3088 /* Yeah, malloc would be really nice now :) */
3089 #ifdef __PCTOOL__
3090 tempbuf_size = 32*1024*1024;
3091 tempbuf = malloc(tempbuf_size);
3092 #else
3093 tempbuf_handle = core_alloc_maximum("tc tempbuf", &tempbuf_size, NULL);
3094 tempbuf = core_get_data(tempbuf_handle);
3095 #endif
3098 static void free_tempbuf(void)
3100 if (tempbuf_size == 0)
3101 return ;
3103 #ifdef __PCTOOL__
3104 free(tempbuf);
3105 #else
3106 core_free(tempbuf_handle);
3107 #endif
3108 tempbuf = NULL;
3109 tempbuf_size = 0;
3112 #ifndef __PCTOOL__
3114 static bool modify_numeric_entry(int masterfd, int idx_id, int tag, long data)
3116 struct index_entry idx;
3118 if (!tc_stat.ready)
3119 return false;
3121 if (!TAGCACHE_IS_NUMERIC(tag))
3122 return false;
3124 if (!get_index(masterfd, idx_id, &idx, false))
3125 return false;
3127 idx.tag_seek[tag] = data;
3128 idx.flag |= FLAG_DIRTYNUM;
3130 return write_index(masterfd, idx_id, &idx);
3133 #if 0
3134 bool tagcache_modify_numeric_entry(struct tagcache_search *tcs,
3135 int tag, long data)
3137 struct master_header myhdr;
3139 if (tcs->masterfd < 0)
3141 if ( (tcs->masterfd = open_master_fd(&myhdr, true)) < 0)
3142 return false;
3145 return modify_numeric_entry(tcs->masterfd, tcs->idx_id, tag, data);
3147 #endif
3149 static bool command_queue_is_full(void)
3151 int next;
3153 next = command_queue_widx + 1;
3154 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3155 next = 0;
3157 return (next == command_queue_ridx);
3160 static void command_queue_sync_callback(void *data)
3162 (void)data;
3163 struct master_header myhdr;
3164 int masterfd;
3166 mutex_lock(&command_queue_mutex);
3168 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3169 return;
3171 while (command_queue_ridx != command_queue_widx)
3173 struct tagcache_command_entry *ce = &command_queue[command_queue_ridx];
3175 switch (ce->command)
3177 case CMD_UPDATE_MASTER_HEADER:
3179 close(masterfd);
3180 update_master_header();
3182 /* Re-open the masterfd. */
3183 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3184 return;
3186 break;
3188 case CMD_UPDATE_NUMERIC:
3190 modify_numeric_entry(masterfd, ce->idx_id, ce->tag, ce->data);
3191 break;
3195 if (++command_queue_ridx >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3196 command_queue_ridx = 0;
3199 close(masterfd);
3201 tc_stat.queue_length = 0;
3202 mutex_unlock(&command_queue_mutex);
3205 static void run_command_queue(bool force)
3207 if (COMMAND_QUEUE_IS_EMPTY)
3208 return;
3210 if (force || command_queue_is_full())
3211 command_queue_sync_callback(NULL);
3212 else
3213 register_storage_idle_func(command_queue_sync_callback);
3216 static void queue_command(int cmd, long idx_id, int tag, long data)
3218 while (1)
3220 int next;
3222 mutex_lock(&command_queue_mutex);
3223 next = command_queue_widx + 1;
3224 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3225 next = 0;
3227 /* Make sure queue is not full. */
3228 if (next != command_queue_ridx)
3230 struct tagcache_command_entry *ce = &command_queue[command_queue_widx];
3232 ce->command = cmd;
3233 ce->idx_id = idx_id;
3234 ce->tag = tag;
3235 ce->data = data;
3237 command_queue_widx = next;
3239 tc_stat.queue_length++;
3241 mutex_unlock(&command_queue_mutex);
3242 break;
3245 /* Queue is full, try again later... */
3246 mutex_unlock(&command_queue_mutex);
3247 sleep(1);
3251 long tagcache_increase_serial(void)
3253 long old;
3255 if (!tc_stat.ready)
3256 return -2;
3258 while (read_lock)
3259 sleep(1);
3261 old = current_tcmh.serial++;
3262 queue_command(CMD_UPDATE_MASTER_HEADER, 0, 0, 0);
3264 return old;
3267 void tagcache_update_numeric(int idx_id, int tag, long data)
3269 queue_command(CMD_UPDATE_NUMERIC, idx_id, tag, data);
3271 #endif /* !__PCTOOL__ */
3273 long tagcache_get_serial(void)
3275 return current_tcmh.serial;
3278 long tagcache_get_commitid(void)
3280 return current_tcmh.commitid;
3283 static bool write_tag(int fd, const char *tagstr, const char *datastr)
3285 char buf[512];
3286 int i;
3288 snprintf(buf, sizeof buf, "%s=\"", tagstr);
3289 for (i = strlen(buf); i < (long)sizeof(buf)-4; i++)
3291 if (*datastr == '\0')
3292 break;
3294 if (*datastr == '"' || *datastr == '\\')
3295 buf[i++] = '\\';
3297 else if (*datastr == '\n')
3299 buf[i++] = '\\';
3300 buf[i] = 'n';
3301 continue;
3304 buf[i] = *(datastr++);
3307 strcpy(&buf[i], "\" ");
3309 write(fd, buf, i + 2);
3311 return true;
3314 #ifndef __PCTOOL__
3316 static bool read_tag(char *dest, long size,
3317 const char *src, const char *tagstr)
3319 int pos;
3320 char current_tag[32];
3322 while (*src != '\0')
3324 /* Skip all whitespace */
3325 while (*src == ' ')
3326 src++;
3328 if (*src == '\0')
3329 break;
3331 pos = 0;
3332 /* Read in tag name */
3333 while (*src != '=' && *src != ' ')
3335 current_tag[pos] = *src;
3336 src++;
3337 pos++;
3339 if (*src == '\0' || pos >= (long)sizeof(current_tag))
3340 return false;
3342 current_tag[pos] = '\0';
3344 /* Read in tag data */
3346 /* Find the start. */
3347 while (*src != '"' && *src != '\0')
3348 src++;
3350 if (*src == '\0' || *(++src) == '\0')
3351 return false;
3353 /* Read the data. */
3354 for (pos = 0; pos < size; pos++)
3356 if (*src == '\0')
3357 break;
3359 if (*src == '\\')
3361 src++;
3362 if (*src == 'n')
3363 dest[pos] = '\n';
3364 else
3365 dest[pos] = *src;
3367 src++;
3368 continue;
3371 if (*src == '\0')
3372 break;
3374 if (*src == '"')
3376 src++;
3377 break;
3380 dest[pos] = *(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, 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("%d/filename missing", line_n);
3410 logf("-> %s", buf);
3411 return 0;
3414 idx_id = find_index(tag_data);
3415 if (idx_id < 0)
3417 logf("%d/entry not found", line_n);
3418 return 0;
3421 if (!get_index(masterfd, idx_id, &idx, false))
3423 logf("%d/failed to retrieve index entry", line_n);
3424 return 0;
3427 /* Stop if tag has already been modified. */
3428 if (idx.flag & FLAG_DIRTYNUM)
3429 return 0;
3431 logf("%d/import: %s", line_n, 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 ramcache_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 = &ramcache_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 = &ramcache_hdr->indices[idx_id].tag_seek[tag];
3690 tfe = (struct tagfile_entry *)&ramcache_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 =
3736 (struct tagfile_entry *)&ramcache_hdr->tags[tag][oldseek];
3737 tagentry->tag_data[0] = '\0';
3739 #endif
3741 /* Open the index file, which contains the tag names. */
3742 if (fd < 0)
3744 if ((fd = open_tag_fd(&tch, tag, true)) < 0)
3745 goto cleanup;
3748 /* Skip the header block */
3749 lseek(fd, oldseek + sizeof(struct tagfile_entry), SEEK_SET);
3751 /* Debug, print 10 first characters of the tag
3752 read(fd, buf, 10);
3753 buf[10]='\0';
3754 logf("TAG:%s", buf);
3755 lseek(fd, -10, SEEK_CUR);
3758 /* Write first data byte in tag as \0 */
3759 write(fd, "", 1);
3761 /* Now tag data has been removed */
3762 close(fd);
3763 fd = -1;
3766 /* Write index entry back into master index. */
3767 lseek(masterfd, sizeof(struct master_header) +
3768 (idx_id * sizeof(struct index_entry)), SEEK_SET);
3769 if (ecwrite_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3771 logf("delete_entry(): write_error #2");
3772 goto cleanup;
3775 close(masterfd);
3777 return true;
3779 cleanup:
3780 if (fd >= 0)
3781 close(fd);
3782 if (masterfd >= 0)
3783 close(masterfd);
3785 return false;
3788 #ifndef __PCTOOL__
3790 * Returns true if there is an event waiting in the queue
3791 * that requires the current operation to be aborted.
3793 static bool check_event_queue(void)
3795 struct queue_event ev;
3797 if(!queue_peek(&tagcache_queue, &ev))
3798 return false;
3800 switch (ev.id)
3802 case Q_STOP_SCAN:
3803 case SYS_POWEROFF:
3804 case SYS_USB_CONNECTED:
3805 return true;
3808 return false;
3810 #endif
3812 #ifdef HAVE_TC_RAMCACHE
3813 static bool allocate_tagcache(void)
3815 struct master_header tcmh;
3816 int fd;
3818 /* Load the header. */
3819 if ( (fd = open_master_fd(&tcmh, false)) < 0)
3821 ramcache_hdr = NULL;
3822 return false;
3825 close(fd);
3827 /**
3828 * Now calculate the required cache size plus
3829 * some extra space for alignment fixes.
3831 tc_stat.ramcache_allocated = tcmh.tch.datasize + 256 + TAGCACHE_RESERVE +
3832 sizeof(struct ramcache_header) + TAG_COUNT*sizeof(void *);
3833 int handle = core_alloc("tc ramcache", tc_stat.ramcache_allocated);
3834 ramcache_hdr = core_get_data(handle);
3835 memset(ramcache_hdr, 0, sizeof(struct ramcache_header));
3836 memcpy(&current_tcmh, &tcmh, sizeof current_tcmh);
3837 logf("tagcache: %d bytes allocated.", tc_stat.ramcache_allocated);
3839 return true;
3842 # ifdef HAVE_EEPROM_SETTINGS
3843 static bool tagcache_dumpload(void)
3845 struct statefile_header shdr;
3846 int fd, rc;
3847 long offpos;
3848 int i, handle;
3850 fd = open(TAGCACHE_STATEFILE, O_RDONLY);
3851 if (fd < 0)
3853 logf("no tagcache statedump");
3854 return false;
3857 /* Check the statefile memory placement */
3858 rc = read(fd, &shdr, sizeof(struct statefile_header));
3859 if (rc != sizeof(struct statefile_header)
3860 || shdr.magic != TAGCACHE_STATEFILE_MAGIC
3861 || shdr.mh.tch.magic != TAGCACHE_MAGIC)
3863 logf("incorrect statefile");
3864 ramcache_hdr = NULL;
3865 close(fd);
3866 return false;
3870 /* Lets allocate real memory and load it */
3871 handle = core_alloc("tc ramcache", shdr.tc_stat.ramcache_allocated);
3872 ramcache_hdr = core_get_data(handle);
3873 rc = read(fd, ramcache_hdr, shdr.tc_stat.ramcache_allocated);
3874 close(fd);
3876 offpos = (long)ramcache_hdr - (long)shdr.hdr;
3877 if (rc != shdr.tc_stat.ramcache_allocated)
3879 logf("read failure!");
3880 ramcache_hdr = NULL;
3881 return false;
3884 memcpy(&tc_stat, &shdr.tc_stat, sizeof(struct tagcache_stat));
3886 /* Now fix the pointers */
3887 for (i = 0; i < TAG_COUNT; i++)
3888 ramcache_hdr->tags[i] += offpos;
3890 /* Load the tagcache master header (should match the actual DB file header). */
3891 memcpy(&current_tcmh, &shdr.mh, sizeof current_tcmh);
3893 return true;
3896 static bool tagcache_dumpsave(void)
3898 struct statefile_header shdr;
3899 int fd;
3901 if (!tc_stat.ramcache)
3902 return false;
3904 fd = open(TAGCACHE_STATEFILE, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3905 if (fd < 0)
3907 logf("failed to create a statedump");
3908 return false;
3911 /* Create the header */
3912 shdr.magic = TAGCACHE_STATEFILE_MAGIC;
3913 shdr.hdr = ramcache_hdr;
3914 memcpy(&shdr.mh, &current_tcmh, sizeof current_tcmh);
3915 memcpy(&shdr.tc_stat, &tc_stat, sizeof tc_stat);
3916 write(fd, &shdr, sizeof shdr);
3918 /* And dump the data too */
3919 write(fd, ramcache_hdr, tc_stat.ramcache_allocated);
3920 close(fd);
3922 return true;
3924 # endif
3926 static bool load_tagcache(void)
3928 struct tagcache_header *tch;
3929 struct master_header tcmh;
3930 long bytesleft = tc_stat.ramcache_allocated - sizeof(struct ramcache_header);
3931 struct index_entry *idx;
3932 int rc, fd;
3933 char *p;
3934 int i, tag;
3936 # ifdef HAVE_DIRCACHE
3937 while (dircache_is_initializing())
3938 sleep(1);
3940 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE);
3941 # endif
3943 logf("loading tagcache to ram...");
3945 fd = open(TAGCACHE_FILE_MASTER, O_RDONLY);
3946 if (fd < 0)
3948 logf("tagcache open failed");
3949 return false;
3952 if (ecread(fd, &tcmh, 1, master_header_ec, tc_stat.econ)
3953 != sizeof(struct master_header)
3954 || tcmh.tch.magic != TAGCACHE_MAGIC)
3956 logf("incorrect header");
3957 return false;
3960 /* Master header copy should already match, this can be redundant to do. */
3961 memcpy(&current_tcmh, &tcmh, sizeof current_tcmh);
3963 idx = ramcache_hdr->indices;
3965 /* Load the master index table. */
3966 for (i = 0; i < tcmh.tch.entry_count; i++)
3968 bytesleft -= sizeof(struct index_entry);
3969 if (bytesleft < 0)
3971 logf("too big tagcache.");
3972 close(fd);
3973 return false;
3976 /* DEBUG: After tagcache commit and dircache rebuild, hdr-sturcture
3977 * may become corrupt. */
3978 rc = ecread_index_entry(fd, idx);
3979 if (rc != sizeof(struct index_entry))
3981 logf("read error #10");
3982 close(fd);
3983 return false;
3986 idx++;
3989 close(fd);
3991 /* Load the tags. */
3992 p = (char *)idx;
3993 for (tag = 0; tag < TAG_COUNT; tag++)
3995 struct tagfile_entry *fe;
3996 char buf[TAG_MAXLEN+32];
3998 if (TAGCACHE_IS_NUMERIC(tag))
3999 continue ;
4001 //p = ((void *)p+1);
4002 p = (char *)((long)p & ~0x03) + 0x04;
4003 ramcache_hdr->tags[tag] = p;
4005 /* Check the header. */
4006 tch = (struct tagcache_header *)p;
4007 p += sizeof(struct tagcache_header);
4009 if ( (fd = open_tag_fd(tch, tag, false)) < 0)
4010 return false;
4012 for (ramcache_hdr->entry_count[tag] = 0;
4013 ramcache_hdr->entry_count[tag] < tch->entry_count;
4014 ramcache_hdr->entry_count[tag]++)
4016 long pos;
4018 if (do_timed_yield())
4020 /* Abort if we got a critical event in queue */
4021 if (check_event_queue())
4022 return false;
4025 fe = (struct tagfile_entry *)p;
4026 pos = lseek(fd, 0, SEEK_CUR);
4027 rc = ecread_tagfile_entry(fd, fe);
4028 if (rc != sizeof(struct tagfile_entry))
4030 /* End of lookup table. */
4031 logf("read error #11");
4032 close(fd);
4033 return false;
4036 /* We have a special handling for the filename tags. */
4037 if (tag == tag_filename)
4039 # ifdef HAVE_DIRCACHE
4040 int dc;
4041 # endif
4043 idx = &ramcache_hdr->indices[fe->idx_id];
4045 if (fe->tag_length >= (long)sizeof(buf)-1)
4047 read(fd, buf, 10);
4048 buf[10] = '\0';
4049 logf("TAG:%s", buf);
4050 logf("too long filename");
4051 close(fd);
4052 return false;
4055 rc = read(fd, buf, fe->tag_length);
4056 if (rc != fe->tag_length)
4058 logf("read error #12");
4059 close(fd);
4060 return false;
4063 /* Check if the entry has already been removed */
4064 if (idx->flag & FLAG_DELETED)
4065 continue;
4067 /* This flag must not be used yet. */
4068 if (idx->flag & FLAG_DIRCACHE)
4070 logf("internal error!");
4071 close(fd);
4072 return false;
4075 if (idx->tag_seek[tag] != pos)
4077 logf("corrupt data structures!");
4078 close(fd);
4079 return false;
4082 # ifdef HAVE_DIRCACHE
4083 if (dircache_is_enabled())
4085 dc = dircache_get_entry_id(buf);
4086 if (dc < 0)
4088 logf("Entry no longer valid.");
4089 logf("-> %s", buf);
4090 if (global_settings.tagcache_autoupdate)
4091 delete_entry(fe->idx_id);
4092 continue ;
4095 idx->flag |= FLAG_DIRCACHE;
4096 idx->tag_seek[tag_filename] = dc;
4098 else
4099 # endif
4101 /* This will be very slow unless dircache is enabled
4102 or target is flash based, but do it anyway for
4103 consistency. */
4104 /* Check if entry has been removed. */
4105 if (global_settings.tagcache_autoupdate)
4107 if (!file_exists(buf))
4109 logf("Entry no longer valid.");
4110 logf("-> %s", buf);
4111 delete_entry(fe->idx_id);
4112 continue;
4117 continue ;
4120 bytesleft -= sizeof(struct tagfile_entry) + fe->tag_length;
4121 if (bytesleft < 0)
4123 logf("too big tagcache #2");
4124 logf("tl: %ld", fe->tag_length);
4125 logf("bl: %ld", bytesleft);
4126 close(fd);
4127 return false;
4130 p = fe->tag_data;
4131 rc = read(fd, fe->tag_data, fe->tag_length);
4132 p += rc;
4134 if (rc != fe->tag_length)
4136 logf("read error #13");
4137 logf("rc=0x%04x", rc); // 0x431
4138 logf("len=0x%04lx", fe->tag_length); // 0x4000
4139 logf("pos=0x%04lx", lseek(fd, 0, SEEK_CUR)); // 0x433
4140 logf("tag=0x%02x", tag); // 0x00
4141 close(fd);
4142 return false;
4145 close(fd);
4148 tc_stat.ramcache_used = tc_stat.ramcache_allocated - bytesleft;
4149 logf("tagcache loaded into ram!");
4151 return true;
4153 #endif /* HAVE_TC_RAMCACHE */
4155 static bool check_deleted_files(void)
4157 int fd;
4158 char buf[TAG_MAXLEN+32];
4159 struct tagfile_entry tfe;
4161 logf("reverse scan...");
4162 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag_filename);
4163 fd = open(buf, O_RDONLY);
4165 if (fd < 0)
4167 logf("%s open fail", buf);
4168 return false;
4171 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
4172 while (ecread_tagfile_entry(fd, &tfe) == sizeof(struct tagfile_entry)
4173 #ifndef __PCTOOL__
4174 && !check_event_queue()
4175 #endif
4178 if (tfe.tag_length >= (long)sizeof(buf)-1)
4180 logf("too long tag");
4181 close(fd);
4182 return false;
4185 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
4187 logf("read error #14");
4188 close(fd);
4189 return false;
4192 /* Check if the file has already deleted from the db. */
4193 if (*buf == '\0')
4194 continue;
4196 /* Now check if the file exists. */
4197 if (!file_exists(buf))
4199 logf("Entry no longer valid.");
4200 logf("-> %s / %ld", buf, tfe.tag_length);
4201 delete_entry(tfe.idx_id);
4205 close(fd);
4207 logf("done");
4209 return true;
4213 /* Note that this function must not be inlined, otherwise the whole point
4214 * of having the code in a separate function is lost.
4216 static void __attribute__ ((noinline)) check_ignore(const char *dirname,
4217 int *ignore, int *unignore)
4219 char newpath[MAX_PATH];
4221 /* check for a database.ignore file */
4222 snprintf(newpath, MAX_PATH, "%s/database.ignore", dirname);
4223 *ignore = file_exists(newpath);
4224 /* check for a database.unignore file */
4225 snprintf(newpath, MAX_PATH, "%s/database.unignore", dirname);
4226 *unignore = file_exists(newpath);
4229 static struct search_roots_ll {
4230 const char *path;
4231 struct search_roots_ll * next;
4232 } roots_ll;
4234 #ifdef APPLICATION
4236 * This adds a path to the search roots, possibly during traveling through
4237 * the filesystem. It only adds if the path is not inside an already existing
4238 * search root.
4240 * Returns true if it added the path to the search roots
4242 * Windows 2000 and greater supports symlinks, but they don't provide
4243 * realpath() or readlink(), and symlinks are rarely used on them so
4244 * ignore this for windows for now
4246 static bool add_search_root(const char *name)
4248 (void)name;
4249 #ifndef WIN32
4250 struct search_roots_ll *this, *prev = NULL;
4251 char target[MAX_PATH];
4252 /* Okay, realpath() is almost completely broken on android
4254 * It doesn't accept NULL for resolved_name to dynamically allocate
4255 * the resulting path; and it assumes resolved_name to be PATH_MAX
4256 * (actually MAXPATHLEN, but it's the same [as of 2.3]) long
4257 * and blindly writes to the end if it
4259 * therefore use sufficiently large static storage here
4260 * Note that PATH_MAX != MAX_PATH
4262 static char abs_target[PATH_MAX];
4263 ssize_t len;
4265 len = readlink(name, target, sizeof(target));
4266 if (len < 0)
4267 return false;
4269 target[len] = '\0';
4270 if (realpath(target, abs_target) == NULL)
4271 return false;
4273 for(this = &roots_ll; this; prev = this, this = this->next)
4275 size_t root_len = strlen(this->path);
4276 /* check if the link target is inside of an existing search root
4277 * don't add if target is inside, we'll scan it later */
4278 if (!strncmp(this->path, abs_target, root_len))
4279 return false;
4282 if (prev)
4284 size_t len = strlen(abs_target) + 1; /* count \0 */
4285 this = malloc(sizeof(struct search_roots_ll) + len );
4286 if (!this || len > MAX_PATH)
4288 logf("Error at adding a search root: %s", this ? "path too long":"OOM");
4289 free(this);
4290 prev->next = NULL;
4291 return false;
4293 this->path = ((char*)this) + sizeof(struct search_roots_ll);
4294 strcpy((char*)this->path, abs_target); /* ok to cast const away here */
4295 this->next = NULL;
4296 prev->next = this;
4297 logf("Added %s to the search roots\n", abs_target);
4298 return true;
4300 #endif
4301 return false;
4304 static int free_search_roots(struct search_roots_ll * start)
4306 int ret = 0;
4307 if (start->next)
4309 ret += free_search_roots(start->next);
4310 ret += sizeof(struct search_roots_ll);
4311 free(start->next);
4313 return ret;
4315 #else /* native, simulator */
4316 #define add_search_root(a) do {} while(0)
4317 #define free_search_roots(a) do {} while(0)
4318 #endif
4320 static bool check_dir(const char *dirname, int add_files)
4322 DIR *dir;
4323 int len;
4324 int success = false;
4325 int ignore, unignore;
4327 dir = opendir(dirname);
4328 if (!dir)
4330 logf("tagcache: opendir(%s) failed", dirname);
4331 return false;
4333 /* check for a database.ignore and database.unignore */
4334 check_ignore(dirname, &ignore, &unignore);
4336 /* don't do anything if both ignore and unignore are there */
4337 if (ignore != unignore)
4338 add_files = unignore;
4340 /* Recursively scan the dir. */
4341 #ifdef __PCTOOL__
4342 while (1)
4343 #else
4344 while (!check_event_queue())
4345 #endif
4347 struct dirent *entry = readdir(dir);
4348 if (entry == NULL)
4350 success = true;
4351 break;
4354 if (!strcmp((char *)entry->d_name, ".") ||
4355 !strcmp((char *)entry->d_name, ".."))
4356 continue;
4358 struct dirinfo info = dir_get_info(dir, entry);
4360 yield();
4362 len = strlen(curpath);
4363 /* don't add an extra / for curpath == / */
4364 if (len <= 1) len = 0;
4365 snprintf(&curpath[len], sizeof(curpath) - len, "/%s", entry->d_name);
4367 processed_dir_count++;
4368 if (info.attribute & ATTR_DIRECTORY)
4369 #ifndef SIMULATOR
4370 { /* don't follow symlinks to dirs, but try to add it as a search root
4371 * this makes able to avoid looping in recursive symlinks */
4372 if (info.attribute & ATTR_LINK)
4373 add_search_root(curpath);
4374 else
4375 check_dir(curpath, add_files);
4377 #else
4378 check_dir(curpath, add_files);
4379 #endif
4380 else if (add_files)
4382 tc_stat.curentry = curpath;
4384 /* Add a new entry to the temporary db file. */
4385 add_tagcache(curpath, (info.wrtdate << 16) | info.wrttime
4386 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4387 , dir->internal_entry
4388 #endif
4391 /* Wait until current path for debug screen is read and unset. */
4392 while (tc_stat.syncscreen && tc_stat.curentry != NULL)
4393 yield();
4395 tc_stat.curentry = NULL;
4398 curpath[len] = '\0';
4401 closedir(dir);
4403 return success;
4406 void tagcache_screensync_event(void)
4408 tc_stat.curentry = NULL;
4411 void tagcache_screensync_enable(bool state)
4413 tc_stat.syncscreen = state;
4416 void tagcache_build(const char *path)
4418 struct tagcache_header header;
4419 bool ret;
4421 curpath[0] = '\0';
4422 data_size = 0;
4423 total_entry_count = 0;
4424 processed_dir_count = 0;
4426 #ifdef HAVE_DIRCACHE
4427 while (dircache_is_initializing())
4428 sleep(1);
4429 #endif
4431 logf("updating tagcache");
4433 cachefd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
4434 if (cachefd >= 0)
4436 logf("skipping, cache already waiting for commit");
4437 close(cachefd);
4438 return ;
4441 cachefd = open(TAGCACHE_FILE_TEMP, O_RDWR | O_CREAT | O_TRUNC, 0666);
4442 if (cachefd < 0)
4444 logf("master file open failed: %s", TAGCACHE_FILE_TEMP);
4445 return ;
4448 filenametag_fd = open_tag_fd(&header, tag_filename, false);
4450 cpu_boost(true);
4452 logf("Scanning files...");
4453 /* Scan for new files. */
4454 memset(&header, 0, sizeof(struct tagcache_header));
4455 write(cachefd, &header, sizeof(struct tagcache_header));
4457 ret = true;
4458 roots_ll.path = path;
4459 roots_ll.next = NULL;
4460 struct search_roots_ll * this;
4461 /* check_dir might add new roots */
4462 for(this = &roots_ll; this; this = this->next)
4464 strcpy(curpath, this->path);
4465 ret = ret && check_dir(this->path, true);
4467 if (roots_ll.next)
4468 free_search_roots(roots_ll.next);
4470 /* Write the header. */
4471 header.magic = TAGCACHE_MAGIC;
4472 header.datasize = data_size;
4473 header.entry_count = total_entry_count;
4474 lseek(cachefd, 0, SEEK_SET);
4475 write(cachefd, &header, sizeof(struct tagcache_header));
4476 close(cachefd);
4478 if (filenametag_fd >= 0)
4480 close(filenametag_fd);
4481 filenametag_fd = -1;
4484 if (!ret)
4486 logf("Aborted.");
4487 cpu_boost(false);
4488 return ;
4491 /* Commit changes to the database. */
4492 #ifdef __PCTOOL__
4493 allocate_tempbuf();
4494 #endif
4495 if (commit())
4497 logf("tagcache built!");
4499 #ifdef __PCTOOL__
4500 free_tempbuf();
4501 #endif
4503 #ifdef HAVE_TC_RAMCACHE
4504 if (ramcache_hdr)
4506 /* Import runtime statistics if we just initialized the db. */
4507 if (current_tcmh.serial == 0)
4508 queue_post(&tagcache_queue, Q_IMPORT_CHANGELOG, 0);
4510 #endif
4512 cpu_boost(false);
4515 #ifdef HAVE_TC_RAMCACHE
4516 static void load_ramcache(void)
4518 if (!ramcache_hdr)
4519 return ;
4521 cpu_boost(true);
4523 /* At first we should load the cache (if exists). */
4524 tc_stat.ramcache = load_tagcache();
4526 if (!tc_stat.ramcache)
4528 /* If loading failed, it must indicate some problem with the db
4529 * so disable it entirely to prevent further issues. */
4530 tc_stat.ready = false;
4531 ramcache_hdr = NULL;
4534 cpu_boost(false);
4537 void tagcache_unload_ramcache(void)
4539 tc_stat.ramcache = false;
4540 /* Just to make sure there is no statefile present. */
4541 // remove(TAGCACHE_STATEFILE);
4543 #endif
4545 #ifndef __PCTOOL__
4546 static void tagcache_thread(void)
4548 struct queue_event ev;
4549 bool check_done = false;
4551 /* If the previous cache build/update was interrupted, commit
4552 * the changes first in foreground. */
4553 cpu_boost(true);
4554 allocate_tempbuf();
4555 commit();
4556 free_tempbuf();
4558 #ifdef HAVE_TC_RAMCACHE
4559 # ifdef HAVE_EEPROM_SETTINGS
4560 if (firmware_settings.initialized && firmware_settings.disk_clean
4561 && global_settings.tagcache_ram)
4563 check_done = tagcache_dumpload();
4566 remove(TAGCACHE_STATEFILE);
4567 # endif
4569 /* Allocate space for the tagcache if found on disk. */
4570 if (global_settings.tagcache_ram && !tc_stat.ramcache)
4571 allocate_tagcache();
4572 #endif
4574 cpu_boost(false);
4575 tc_stat.initialized = true;
4577 /* Don't delay bootup with the header check but do it on background. */
4578 if (!tc_stat.ready)
4580 sleep(HZ);
4581 tc_stat.ready = check_all_headers();
4582 tc_stat.readyvalid = true;
4585 while (1)
4587 run_command_queue(false);
4589 queue_wait_w_tmo(&tagcache_queue, &ev, HZ);
4591 switch (ev.id)
4593 case Q_IMPORT_CHANGELOG:
4594 tagcache_import_changelog();
4595 break;
4597 case Q_REBUILD:
4598 remove_files();
4599 remove(TAGCACHE_FILE_TEMP);
4600 tagcache_build("/");
4601 break;
4603 case Q_UPDATE:
4604 tagcache_build("/");
4605 #ifdef HAVE_TC_RAMCACHE
4606 load_ramcache();
4607 #endif
4608 check_deleted_files();
4609 break ;
4611 case Q_START_SCAN:
4612 check_done = false;
4613 case SYS_TIMEOUT:
4614 if (check_done || !tc_stat.ready)
4615 break ;
4617 #ifdef HAVE_TC_RAMCACHE
4618 if (!tc_stat.ramcache && global_settings.tagcache_ram)
4620 load_ramcache();
4621 if (tc_stat.ramcache && global_settings.tagcache_autoupdate)
4622 tagcache_build("/");
4624 else
4625 #endif
4626 if (global_settings.tagcache_autoupdate)
4628 tagcache_build("/");
4630 /* This will be very slow unless dircache is enabled
4631 or target is flash based, but do it anyway for
4632 consistency. */
4633 check_deleted_files();
4636 logf("tagcache check done");
4638 check_done = true;
4639 break ;
4641 case Q_STOP_SCAN:
4642 break ;
4644 case SYS_POWEROFF:
4645 break ;
4647 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4648 case SYS_USB_CONNECTED:
4649 logf("USB: TagCache");
4650 usb_acknowledge(SYS_USB_CONNECTED_ACK);
4651 usb_wait_for_disconnect(&tagcache_queue);
4652 break ;
4653 #endif
4658 bool tagcache_prepare_shutdown(void)
4660 if (tagcache_get_commit_step() > 0)
4661 return false;
4663 tagcache_stop_scan();
4664 while (read_lock || write_lock)
4665 sleep(1);
4667 return true;
4670 void tagcache_shutdown(void)
4672 /* Flush the command queue. */
4673 run_command_queue(true);
4675 #ifdef HAVE_EEPROM_SETTINGS
4676 if (tc_stat.ramcache)
4677 tagcache_dumpsave();
4678 #endif
4681 static int get_progress(void)
4683 int total_count = -1;
4685 #ifdef HAVE_DIRCACHE
4686 if (dircache_is_enabled())
4688 total_count = dircache_get_entry_count();
4690 else
4691 #endif
4692 #ifdef HAVE_TC_RAMCACHE
4694 if (ramcache_hdr && tc_stat.ramcache)
4695 total_count = current_tcmh.tch.entry_count;
4697 #endif
4699 if (total_count < 0)
4700 return -1;
4702 return processed_dir_count * 100 / total_count;
4705 struct tagcache_stat* tagcache_get_stat(void)
4707 tc_stat.progress = get_progress();
4708 tc_stat.processed_entries = processed_dir_count;
4710 return &tc_stat;
4713 void tagcache_start_scan(void)
4715 queue_post(&tagcache_queue, Q_START_SCAN, 0);
4718 bool tagcache_update(void)
4720 if (!tc_stat.ready)
4721 return false;
4723 queue_post(&tagcache_queue, Q_UPDATE, 0);
4724 return false;
4727 bool tagcache_rebuild()
4729 queue_post(&tagcache_queue, Q_REBUILD, 0);
4730 return false;
4733 void tagcache_stop_scan(void)
4735 queue_post(&tagcache_queue, Q_STOP_SCAN, 0);
4738 #ifdef HAVE_TC_RAMCACHE
4739 bool tagcache_is_ramcache(void)
4741 return tc_stat.ramcache;
4743 #endif
4745 #endif /* !__PCTOOL__ */
4748 void tagcache_init(void)
4750 memset(&tc_stat, 0, sizeof(struct tagcache_stat));
4751 memset(&current_tcmh, 0, sizeof(struct master_header));
4752 filenametag_fd = -1;
4753 write_lock = read_lock = 0;
4755 #ifndef __PCTOOL__
4756 mutex_init(&command_queue_mutex);
4757 queue_init(&tagcache_queue, true);
4758 create_thread(tagcache_thread, tagcache_stack,
4759 sizeof(tagcache_stack), 0, tagcache_thread_name
4760 IF_PRIO(, PRIORITY_BACKGROUND)
4761 IF_COP(, CPU));
4762 #else
4763 tc_stat.initialized = true;
4764 allocate_tempbuf();
4765 commit();
4766 free_tempbuf();
4767 tc_stat.ready = check_all_headers();
4768 #endif
4771 #ifdef __PCTOOL__
4772 void tagcache_reverse_scan(void)
4774 logf("Checking for deleted files");
4775 check_deleted_files();
4777 #endif
4779 bool tagcache_is_initialized(void)
4781 return tc_stat.initialized;
4783 bool tagcache_is_fully_initialized(void)
4785 return tc_stat.readyvalid;
4787 bool tagcache_is_usable(void)
4789 return tc_stat.initialized && tc_stat.ready;
4791 int tagcache_get_commit_step(void)
4793 return tc_stat.commit_step;
4795 int tagcache_get_max_commit_step(void)
4797 return (int)(SORTED_TAGS_COUNT)+1;