Extract config file saving code to a function; Do not write the NUL character to...
[kugel-rb.git] / apps / tagcache.c
blob0831bab32d7da7fb74e8722a01e49ea126ebfb7b
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 #endif
66 #include "config.h"
67 #include "ata_idle_notify.h"
68 #include "thread.h"
69 #include "kernel.h"
70 #include "system.h"
71 #include "logf.h"
72 #include "string-extra.h"
73 #include "usb.h"
74 #include "metadata.h"
75 #include "tagcache.h"
76 #include "buffer.h"
77 #include "crc32.h"
78 #include "misc.h"
79 #include "settings.h"
80 #include "dir.h"
81 #include "filefuncs.h"
82 #include "structec.h"
83 #include "debug.h"
85 #ifndef __PCTOOL__
86 #include "lang.h"
87 #include "eeprom_settings.h"
88 #endif
90 #ifdef __PCTOOL__
91 #define yield() do { } while(0)
92 #define sim_sleep(timeout) do { } while(0)
93 #define do_timed_yield() do { } while(0)
94 #endif
96 #ifndef __PCTOOL__
97 /* Tag Cache thread. */
98 static struct event_queue tagcache_queue;
99 static long tagcache_stack[(DEFAULT_STACK_SIZE + 0x4000)/sizeof(long)];
100 static const char tagcache_thread_name[] = "tagcache";
101 #endif
103 /* Previous path when scanning directory tree recursively. */
104 static char curpath[TAG_MAXLEN+32];
106 /* Used when removing duplicates. */
107 static char *tempbuf; /* Allocated when needed. */
108 static long tempbufidx; /* Current location in buffer. */
109 static long tempbuf_size; /* Buffer size (TEMPBUF_SIZE). */
110 static long tempbuf_left; /* Buffer space left. */
111 static long tempbuf_pos;
113 #define SORTED_TAGS_COUNT 8
114 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
115 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
116 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
117 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
118 /* Tags we want to get sorted (loaded to the tempbuf). */
119 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
120 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
121 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
123 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
124 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
125 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
126 (1LU << tag_albumartist) | (1LU << tag_grouping))
128 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
129 static const char *tags_str[] = { "artist", "album", "genre", "title",
130 "filename", "composer", "comment", "albumartist", "grouping", "year",
131 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
132 "playtime", "lastplayed", "commitid", "mtime" };
134 /* Status information of the tagcache. */
135 static struct tagcache_stat tc_stat;
137 /* Queue commands. */
138 enum tagcache_queue {
139 Q_STOP_SCAN = 0,
140 Q_START_SCAN,
141 Q_IMPORT_CHANGELOG,
142 Q_UPDATE,
143 Q_REBUILD,
145 /* Internal tagcache command queue. */
146 CMD_UPDATE_MASTER_HEADER,
147 CMD_UPDATE_NUMERIC,
150 struct tagcache_command_entry {
151 int32_t command;
152 int32_t idx_id;
153 int32_t tag;
154 int32_t data;
157 #ifndef __PCTOOL__
158 static struct tagcache_command_entry command_queue[TAGCACHE_COMMAND_QUEUE_LENGTH];
159 static volatile int command_queue_widx = 0;
160 static volatile int command_queue_ridx = 0;
161 static struct mutex command_queue_mutex;
162 #endif
164 /* Tag database structures. */
166 /* Variable-length tag entry in tag files. */
167 struct tagfile_entry {
168 int32_t tag_length; /* Length of the data in bytes including '\0' */
169 int32_t idx_id; /* Corresponding entry location in index file of not unique tags */
170 char tag_data[0]; /* Begin of the tag data */
173 /* Fixed-size tag entry in master db index. */
174 struct index_entry {
175 int32_t tag_seek[TAG_COUNT]; /* Location of tag data or numeric tag data */
176 int32_t flag; /* Status flags */
179 /* Header is the same in every file. */
180 struct tagcache_header {
181 int32_t magic; /* Header version number */
182 int32_t datasize; /* Data size in bytes */
183 int32_t entry_count; /* Number of entries in this file */
186 struct master_header {
187 struct tagcache_header tch;
188 int32_t serial; /* Increasing counting number */
189 int32_t commitid; /* Number of commits so far */
190 int32_t dirty;
193 /* For the endianess correction */
194 static const char *tagfile_entry_ec = "ll";
196 Note: This should be (1 + TAG_COUNT) amount of l's.
198 static const char *index_entry_ec = "lllllllllllllllllllll";
200 static const char *tagcache_header_ec = "lll";
201 static const char *master_header_ec = "llllll";
203 static struct master_header current_tcmh;
205 #ifdef HAVE_TC_RAMCACHE
206 /* Header is created when loading database to ram. */
207 struct ramcache_header {
208 struct master_header h; /* Header from the master index */
209 struct index_entry *indices; /* Master index file content */
210 char *tags[TAG_COUNT]; /* Tag file content (not including filename tag) */
211 int entry_count[TAG_COUNT]; /* Number of entries in the indices. */
214 # ifdef HAVE_EEPROM_SETTINGS
215 struct statefile_header {
216 struct ramcache_header *hdr;
217 struct tagcache_stat tc_stat;
219 # endif
221 /* Pointer to allocated ramcache_header */
222 static struct ramcache_header *hdr;
223 #endif
225 /**
226 * Full tag entries stored in a temporary file waiting
227 * for commit to the cache. */
228 struct temp_file_entry {
229 long tag_offset[TAG_COUNT];
230 short tag_length[TAG_COUNT];
231 long flag;
233 long data_length;
236 struct tempbuf_id_list {
237 long id;
238 struct tempbuf_id_list *next;
241 struct tempbuf_searchidx {
242 long idx_id;
243 char *str;
244 int seek;
245 struct tempbuf_id_list idlist;
248 /* Lookup buffer for fixing messed up index while after sorting. */
249 static long commit_entry_count;
250 static long lookup_buffer_depth;
251 static struct tempbuf_searchidx **lookup;
253 /* Used when building the temporary file. */
254 static int cachefd = -1, filenametag_fd;
255 static int total_entry_count = 0;
256 static int data_size = 0;
257 static int processed_dir_count;
259 /* Thread safe locking */
260 static volatile int write_lock;
261 static volatile int read_lock;
263 static bool delete_entry(long idx_id);
265 const char* tagcache_tag_to_str(int tag)
267 return tags_str[tag];
270 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
271 static ssize_t ecread_tagfile_entry(int fd, struct tagfile_entry *buf)
273 return ecread(fd, buf, 1, tagfile_entry_ec, tc_stat.econ);
276 static ssize_t ecread_index_entry(int fd, struct index_entry *buf)
278 return ecread(fd, buf, 1, index_entry_ec, tc_stat.econ);
281 static ssize_t ecwrite_index_entry(int fd, struct index_entry *buf)
283 return ecwrite(fd, buf, 1, index_entry_ec, tc_stat.econ);
286 #ifdef HAVE_DIRCACHE
288 * Returns true if specified flag is still present, i.e., dircache
289 * has not been reloaded.
291 static bool is_dircache_intact(void)
293 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE);
295 #endif
297 static int open_tag_fd(struct tagcache_header *hdr, int tag, bool write)
299 int fd;
300 char buf[MAX_PATH];
301 int rc;
303 if (TAGCACHE_IS_NUMERIC(tag) || tag < 0 || tag >= TAG_COUNT)
304 return -1;
306 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag);
308 fd = open(buf, write ? O_RDWR : O_RDONLY);
309 if (fd < 0)
311 logf("tag file open failed: tag=%d write=%d file=%s", tag, write, buf);
312 tc_stat.ready = false;
313 return fd;
316 /* Check the header. */
317 rc = ecread(fd, hdr, 1, tagcache_header_ec, tc_stat.econ);
318 if (hdr->magic != TAGCACHE_MAGIC || rc != sizeof(struct tagcache_header))
320 logf("header error");
321 tc_stat.ready = false;
322 close(fd);
323 return -2;
326 return fd;
329 static int open_master_fd(struct master_header *hdr, bool write)
331 int fd;
332 int rc;
334 fd = open(TAGCACHE_FILE_MASTER, write ? O_RDWR : O_RDONLY);
335 if (fd < 0)
337 logf("master file open failed for R/W");
338 tc_stat.ready = false;
339 return fd;
342 tc_stat.econ = false;
344 /* Check the header. */
345 rc = read(fd, hdr, sizeof(struct master_header));
346 if (hdr->tch.magic == TAGCACHE_MAGIC && rc == sizeof(struct master_header))
348 /* Success. */
349 return fd;
352 /* Trying to read again, this time with endianess correction enabled. */
353 lseek(fd, 0, SEEK_SET);
355 rc = ecread(fd, hdr, 1, master_header_ec, true);
356 if (hdr->tch.magic != TAGCACHE_MAGIC || rc != sizeof(struct master_header))
358 logf("header error");
359 tc_stat.ready = false;
360 close(fd);
361 return -2;
364 tc_stat.econ = true;
366 return fd;
369 #ifndef __PCTOOL__
370 static bool do_timed_yield(void)
372 /* Sorting can lock up for quite a while, so yield occasionally */
373 static long wakeup_tick = 0;
374 if (TIME_AFTER(current_tick, wakeup_tick))
376 wakeup_tick = current_tick + (HZ/4);
377 yield();
378 return true;
380 return false;
382 #endif
384 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
385 static long find_entry_ram(const char *filename,
386 const struct dircache_entry *dc)
388 static long last_pos = 0;
389 int i;
391 /* Check if tagcache is loaded into ram. */
392 if (!tc_stat.ramcache)
393 return -1;
395 if (dc == NULL)
396 dc = dircache_get_entry_ptr(filename);
398 if (dc == NULL)
400 logf("tagcache: file not found.");
401 return -1;
404 try_again:
406 if (last_pos > 0)
407 i = last_pos;
408 else
409 i = 0;
411 for (; i < hdr->h.tch.entry_count; i++)
413 if (hdr->indices[i].tag_seek[tag_filename] == (long)dc)
415 last_pos = MAX(0, i - 3);
416 return i;
419 do_timed_yield();
422 if (last_pos > 0)
424 last_pos = 0;
425 goto try_again;
428 return -1;
430 #endif
432 static long find_entry_disk(const char *filename, bool localfd)
434 struct tagcache_header tch;
435 static long last_pos = -1;
436 long pos_history[POS_HISTORY_COUNT];
437 long pos_history_idx = 0;
438 bool found = false;
439 struct tagfile_entry tfe;
440 int fd;
441 char buf[TAG_MAXLEN+32];
442 int i;
443 int pos = -1;
445 if (!tc_stat.ready)
446 return -2;
448 fd = filenametag_fd;
449 if (fd < 0 || localfd)
451 last_pos = -1;
452 if ( (fd = open_tag_fd(&tch, tag_filename, false)) < 0)
453 return -1;
456 check_again:
458 if (last_pos > 0)
459 lseek(fd, last_pos, SEEK_SET);
460 else
461 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
463 while (true)
465 pos = lseek(fd, 0, SEEK_CUR);
466 for (i = pos_history_idx-1; i >= 0; i--)
467 pos_history[i+1] = pos_history[i];
468 pos_history[0] = pos;
470 if (ecread_tagfile_entry(fd, &tfe)
471 != sizeof(struct tagfile_entry))
473 break ;
476 if (tfe.tag_length >= (long)sizeof(buf))
478 logf("too long tag #1");
479 close(fd);
480 if (!localfd)
481 filenametag_fd = -1;
482 last_pos = -1;
483 return -2;
486 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
488 logf("read error #2");
489 close(fd);
490 if (!localfd)
491 filenametag_fd = -1;
492 last_pos = -1;
493 return -3;
496 if (!strcasecmp(filename, buf))
498 last_pos = pos_history[pos_history_idx];
499 found = true;
500 break ;
503 if (pos_history_idx < POS_HISTORY_COUNT - 1)
504 pos_history_idx++;
507 /* Not found? */
508 if (!found)
510 if (last_pos > 0)
512 last_pos = -1;
513 logf("seek again");
514 goto check_again;
517 if (fd != filenametag_fd || localfd)
518 close(fd);
519 return -4;
522 if (fd != filenametag_fd || localfd)
523 close(fd);
525 return tfe.idx_id;
528 static int find_index(const char *filename)
530 long idx_id = -1;
532 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
533 if (tc_stat.ramcache && is_dircache_intact())
534 idx_id = find_entry_ram(filename, NULL);
535 #endif
537 if (idx_id < 0)
538 idx_id = find_entry_disk(filename, true);
540 return idx_id;
543 bool tagcache_find_index(struct tagcache_search *tcs, const char *filename)
545 int idx_id;
547 if (!tc_stat.ready)
548 return false;
550 idx_id = find_index(filename);
551 if (idx_id < 0)
552 return false;
554 if (!tagcache_search(tcs, tag_filename))
555 return false;
557 tcs->entry_count = 0;
558 tcs->idx_id = idx_id;
560 return true;
563 static bool get_index(int masterfd, int idxid,
564 struct index_entry *idx, bool use_ram)
566 bool localfd = false;
568 if (idxid < 0)
570 logf("Incorrect idxid: %d", idxid);
571 return false;
574 #ifdef HAVE_TC_RAMCACHE
575 if (tc_stat.ramcache && use_ram)
577 if (hdr->indices[idxid].flag & FLAG_DELETED)
578 return false;
580 # ifdef HAVE_DIRCACHE
581 if (!(hdr->indices[idxid].flag & FLAG_DIRCACHE)
582 || is_dircache_intact())
583 #endif
585 memcpy(idx, &hdr->indices[idxid], sizeof(struct index_entry));
586 return true;
589 #else
590 (void)use_ram;
591 #endif
593 if (masterfd < 0)
595 struct master_header tcmh;
597 localfd = true;
598 masterfd = open_master_fd(&tcmh, false);
599 if (masterfd < 0)
600 return false;
603 lseek(masterfd, idxid * sizeof(struct index_entry)
604 + sizeof(struct master_header), SEEK_SET);
605 if (ecread_index_entry(masterfd, idx)
606 != sizeof(struct index_entry))
608 logf("read error #3");
609 if (localfd)
610 close(masterfd);
612 return false;
615 if (localfd)
616 close(masterfd);
618 if (idx->flag & FLAG_DELETED)
619 return false;
621 return true;
624 #ifndef __PCTOOL__
626 static bool write_index(int masterfd, int idxid, struct index_entry *idx)
628 /* We need to exclude all memory only flags & tags when writing to disk. */
629 if (idx->flag & FLAG_DIRCACHE)
631 logf("memory only flags!");
632 return false;
635 #ifdef HAVE_TC_RAMCACHE
636 /* Only update numeric data. Writing the whole index to RAM by memcpy
637 * destroys dircache pointers!
639 if (tc_stat.ramcache)
641 int tag;
642 struct index_entry *idx_ram = &hdr->indices[idxid];
644 for (tag = 0; tag < TAG_COUNT; tag++)
646 if (TAGCACHE_IS_NUMERIC(tag))
648 idx_ram->tag_seek[tag] = idx->tag_seek[tag];
652 /* Don't touch the dircache flag or attributes. */
653 idx_ram->flag = (idx->flag & 0x0000ffff)
654 | (idx_ram->flag & (0xffff0000 | FLAG_DIRCACHE));
656 #endif
658 lseek(masterfd, idxid * sizeof(struct index_entry)
659 + sizeof(struct master_header), SEEK_SET);
660 if (ecwrite_index_entry(masterfd, idx) != sizeof(struct index_entry))
662 logf("write error #3");
663 logf("idxid: %d", idxid);
664 return false;
667 return true;
670 #endif /* !__PCTOOL__ */
672 static bool open_files(struct tagcache_search *tcs, int tag)
674 if (tcs->idxfd[tag] < 0)
676 char fn[MAX_PATH];
678 snprintf(fn, sizeof fn, TAGCACHE_FILE_INDEX, tag);
679 tcs->idxfd[tag] = open(fn, O_RDONLY);
682 if (tcs->idxfd[tag] < 0)
684 logf("File not open!");
685 return false;
688 return true;
691 static bool retrieve(struct tagcache_search *tcs, struct index_entry *idx,
692 int tag, char *buf, long size)
694 struct tagfile_entry tfe;
695 long seek;
697 *buf = '\0';
699 if (TAGCACHE_IS_NUMERIC(tag))
700 return false;
702 seek = idx->tag_seek[tag];
703 if (seek < 0)
705 logf("Retrieve failed");
706 return false;
709 #ifdef HAVE_TC_RAMCACHE
710 if (tcs->ramsearch)
712 struct tagfile_entry *ep;
714 # ifdef HAVE_DIRCACHE
715 if (tag == tag_filename && (idx->flag & FLAG_DIRCACHE)
716 && is_dircache_intact())
718 dircache_copy_path((struct dircache_entry *)seek,
719 buf, size);
720 return true;
722 else
723 # endif
724 if (tag != tag_filename)
726 ep = (struct tagfile_entry *)&hdr->tags[tag][seek];
727 strlcpy(buf, ep->tag_data, size);
729 return true;
732 #endif
734 if (!open_files(tcs, tag))
735 return false;
737 lseek(tcs->idxfd[tag], seek, SEEK_SET);
738 if (ecread_tagfile_entry(tcs->idxfd[tag], &tfe)
739 != sizeof(struct tagfile_entry))
741 logf("read error #5");
742 return false;
745 if (tfe.tag_length >= size)
747 logf("too small buffer");
748 return false;
751 if (read(tcs->idxfd[tag], buf, tfe.tag_length) !=
752 tfe.tag_length)
754 logf("read error #6");
755 return false;
758 buf[tfe.tag_length] = '\0';
760 return true;
763 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
765 static long read_numeric_tag(int tag, int idx_id, const struct index_entry *idx)
767 #ifndef __PCTOOL__
768 if (! COMMAND_QUEUE_IS_EMPTY)
770 /* Attempt to find tag data through store-to-load forwarding in
771 command queue */
772 long result = -1;
774 mutex_lock(&command_queue_mutex);
776 int ridx = command_queue_widx;
778 while (ridx != command_queue_ridx)
780 if (--ridx < 0)
781 ridx = TAGCACHE_COMMAND_QUEUE_LENGTH - 1;
783 if (command_queue[ridx].command == CMD_UPDATE_NUMERIC
784 && command_queue[ridx].idx_id == idx_id
785 && command_queue[ridx].tag == tag)
787 result = command_queue[ridx].data;
788 break;
792 mutex_unlock(&command_queue_mutex);
794 if (result >= 0)
796 logf("read_numeric_tag: "
797 "Recovered tag %d value %lX from write queue",
798 tag, result);
799 return result;
802 #endif
804 return idx->tag_seek[tag];
808 static long check_virtual_tags(int tag, int idx_id,
809 const struct index_entry *idx)
811 long data = 0;
813 switch (tag)
815 case tag_virt_length_sec:
816 data = (read_numeric_tag(tag_length, idx_id, idx)/1000) % 60;
817 break;
819 case tag_virt_length_min:
820 data = (read_numeric_tag(tag_length, idx_id, idx)/1000) / 60;
821 break;
823 case tag_virt_playtime_sec:
824 data = (read_numeric_tag(tag_playtime, idx_id, idx)/1000) % 60;
825 break;
827 case tag_virt_playtime_min:
828 data = (read_numeric_tag(tag_playtime, idx_id, idx)/1000) / 60;
829 break;
831 case tag_virt_autoscore:
832 if (read_numeric_tag(tag_length, idx_id, idx) == 0
833 || read_numeric_tag(tag_playcount, idx_id, idx) == 0)
835 data = 0;
837 else
839 /* A straight calculus gives:
840 autoscore = 100 * playtime / length / playcout (1)
841 Now, consider the euclidian division of playtime by length:
842 playtime = alpha * length + beta
843 With:
844 0 <= beta < length
845 Now, (1) becomes:
846 autoscore = 100 * (alpha / playcout + beta / length / playcount)
847 Both terms should be small enough to avoid any overflow
849 data = 100 * (read_numeric_tag(tag_playtime, idx_id, idx)
850 / read_numeric_tag(tag_length, idx_id, idx))
851 + (100 * (read_numeric_tag(tag_playtime, idx_id, idx)
852 % read_numeric_tag(tag_length, idx_id, idx)))
853 / read_numeric_tag(tag_length, idx_id, idx);
854 data /= read_numeric_tag(tag_playcount, idx_id, idx);
856 break;
858 /* How many commits before the file has been added to the DB. */
859 case tag_virt_entryage:
860 data = current_tcmh.commitid
861 - read_numeric_tag(tag_commitid, idx_id, idx) - 1;
862 break;
864 default:
865 data = read_numeric_tag(tag, idx_id, idx);
868 return data;
871 long tagcache_get_numeric(const struct tagcache_search *tcs, int tag)
873 struct index_entry idx;
875 if (!tc_stat.ready)
876 return false;
878 if (!TAGCACHE_IS_NUMERIC(tag))
879 return -1;
881 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
882 return -2;
884 return check_virtual_tags(tag, tcs->idx_id, &idx);
887 inline static bool str_ends_with(const char *str1, const char *str2)
889 int str_len = strlen(str1);
890 int clause_len = strlen(str2);
892 if (clause_len > str_len)
893 return false;
895 return !strcasecmp(&str1[str_len - clause_len], str2);
898 inline static bool str_oneof(const char *str, const char *list)
900 const char *sep;
901 int l, len = strlen(str);
903 while (*list)
905 sep = strchr(list, '|');
906 l = sep ? (long)sep - (long)list : (int)strlen(list);
907 if ((l==len) && !strncasecmp(str, list, len))
908 return true;
909 list += sep ? l + 1 : l;
912 return false;
915 static bool check_against_clause(long numeric, const char *str,
916 const struct tagcache_search_clause *clause)
918 if (clause->numeric)
920 switch (clause->type)
922 case clause_is:
923 return numeric == clause->numeric_data;
924 case clause_is_not:
925 return numeric != clause->numeric_data;
926 case clause_gt:
927 return numeric > clause->numeric_data;
928 case clause_gteq:
929 return numeric >= clause->numeric_data;
930 case clause_lt:
931 return numeric < clause->numeric_data;
932 case clause_lteq:
933 return numeric <= clause->numeric_data;
934 default:
935 logf("Incorrect numeric tag: %d", clause->type);
938 else
940 switch (clause->type)
942 case clause_is:
943 return !strcasecmp(clause->str, str);
944 case clause_is_not:
945 return strcasecmp(clause->str, str);
946 case clause_gt:
947 return 0>strcasecmp(clause->str, str);
948 case clause_gteq:
949 return 0>=strcasecmp(clause->str, str);
950 case clause_lt:
951 return 0<strcasecmp(clause->str, str);
952 case clause_lteq:
953 return 0<=strcasecmp(clause->str, str);
954 case clause_contains:
955 return (strcasestr(str, clause->str) != NULL);
956 case clause_not_contains:
957 return (strcasestr(str, clause->str) == NULL);
958 case clause_begins_with:
959 return (strcasestr(str, clause->str) == str);
960 case clause_not_begins_with:
961 return (strcasestr(str, clause->str) != str);
962 case clause_ends_with:
963 return str_ends_with(str, clause->str);
964 case clause_not_ends_with:
965 return !str_ends_with(str, clause->str);
966 case clause_oneof:
967 return str_oneof(str, clause->str);
969 default:
970 logf("Incorrect tag: %d", clause->type);
974 return false;
977 static bool check_clauses(struct tagcache_search *tcs,
978 struct index_entry *idx,
979 struct tagcache_search_clause **clause, int count)
981 int i;
983 #ifdef HAVE_TC_RAMCACHE
984 if (tcs->ramsearch)
986 /* Go through all conditional clauses. */
987 for (i = 0; i < count; i++)
989 struct tagfile_entry *tfe;
990 int seek;
991 char buf[256];
992 char *str = NULL;
994 seek = check_virtual_tags(clause[i]->tag, tcs->idx_id, idx);
996 if (!TAGCACHE_IS_NUMERIC(clause[i]->tag))
998 if (clause[i]->tag == tag_filename)
1000 retrieve(tcs, idx, tag_filename, buf, sizeof buf);
1001 str = buf;
1003 else
1005 tfe = (struct tagfile_entry *)&hdr->tags[clause[i]->tag][seek];
1006 str = tfe->tag_data;
1010 if (!check_against_clause(seek, str, clause[i]))
1011 return false;
1014 else
1015 #endif
1017 /* Check for conditions. */
1018 for (i = 0; i < count; i++)
1020 struct tagfile_entry tfe;
1021 int seek;
1022 char str[256];
1024 seek = check_virtual_tags(clause[i]->tag, tcs->idx_id, idx);
1026 memset(str, 0, sizeof str);
1027 if (!TAGCACHE_IS_NUMERIC(clause[i]->tag))
1029 int fd = tcs->idxfd[clause[i]->tag];
1030 lseek(fd, seek, SEEK_SET);
1031 ecread_tagfile_entry(fd, &tfe);
1032 if (tfe.tag_length >= (int)sizeof(str))
1034 logf("Too long tag read!");
1035 break ;
1038 read(fd, str, tfe.tag_length);
1040 /* Check if entry has been deleted. */
1041 if (str[0] == '\0')
1042 break;
1045 if (!check_against_clause(seek, str, clause[i]))
1046 return false;
1050 return true;
1053 bool tagcache_check_clauses(struct tagcache_search *tcs,
1054 struct tagcache_search_clause **clause, int count)
1056 struct index_entry idx;
1058 if (count == 0)
1059 return true;
1061 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
1062 return false;
1064 return check_clauses(tcs, &idx, clause, count);
1067 static bool add_uniqbuf(struct tagcache_search *tcs, unsigned long id)
1069 int i;
1071 /* If uniq buffer is not defined we must return true for search to work. */
1072 if (tcs->unique_list == NULL || (!TAGCACHE_IS_UNIQUE(tcs->type)
1073 && !TAGCACHE_IS_NUMERIC(tcs->type)))
1075 return true;
1078 for (i = 0; i < tcs->unique_list_count; i++)
1080 /* Return false if entry is found. */
1081 if (tcs->unique_list[i] == id)
1082 return false;
1085 if (tcs->unique_list_count < tcs->unique_list_capacity)
1087 tcs->unique_list[i] = id;
1088 tcs->unique_list_count++;
1091 return true;
1094 static bool build_lookup_list(struct tagcache_search *tcs)
1096 struct index_entry entry;
1097 int i, j;
1099 tcs->seek_list_count = 0;
1101 #ifdef HAVE_TC_RAMCACHE
1102 if (tcs->ramsearch
1103 # ifdef HAVE_DIRCACHE
1104 && (tcs->type != tag_filename || is_dircache_intact())
1105 # endif
1108 for (i = tcs->seek_pos; i < hdr->h.tch.entry_count; i++)
1110 struct tagcache_seeklist_entry *seeklist;
1111 struct index_entry *idx = &hdr->indices[i];
1112 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1113 break ;
1115 /* Skip deleted files. */
1116 if (idx->flag & FLAG_DELETED)
1117 continue;
1119 /* Go through all filters.. */
1120 for (j = 0; j < tcs->filter_count; j++)
1122 if (idx->tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1124 break ;
1128 if (j < tcs->filter_count)
1129 continue ;
1131 /* Check for conditions. */
1132 if (!check_clauses(tcs, idx, tcs->clause, tcs->clause_count))
1133 continue;
1135 /* Add to the seek list if not already in uniq buffer. */
1136 if (!add_uniqbuf(tcs, idx->tag_seek[tcs->type]))
1137 continue;
1139 /* Lets add it. */
1140 seeklist = &tcs->seeklist[tcs->seek_list_count];
1141 seeklist->seek = idx->tag_seek[tcs->type];
1142 seeklist->flag = idx->flag;
1143 seeklist->idx_id = i;
1144 tcs->seek_list_count++;
1147 tcs->seek_pos = i;
1149 return tcs->seek_list_count > 0;
1151 #endif
1153 if (tcs->masterfd < 0)
1155 struct master_header tcmh;
1156 tcs->masterfd = open_master_fd(&tcmh, false);
1159 lseek(tcs->masterfd, tcs->seek_pos * sizeof(struct index_entry) +
1160 sizeof(struct master_header), SEEK_SET);
1162 while (ecread_index_entry(tcs->masterfd, &entry)
1163 == sizeof(struct index_entry))
1165 struct tagcache_seeklist_entry *seeklist;
1167 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1168 break ;
1170 i = tcs->seek_pos;
1171 tcs->seek_pos++;
1173 /* Check if entry has been deleted. */
1174 if (entry.flag & FLAG_DELETED)
1175 continue;
1177 /* Go through all filters.. */
1178 for (j = 0; j < tcs->filter_count; j++)
1180 if (entry.tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1181 break ;
1184 if (j < tcs->filter_count)
1185 continue ;
1187 /* Check for conditions. */
1188 if (!check_clauses(tcs, &entry, tcs->clause, tcs->clause_count))
1189 continue;
1191 /* Add to the seek list if not already in uniq buffer. */
1192 if (!add_uniqbuf(tcs, entry.tag_seek[tcs->type]))
1193 continue;
1195 /* Lets add it. */
1196 seeklist = &tcs->seeklist[tcs->seek_list_count];
1197 seeklist->seek = entry.tag_seek[tcs->type];
1198 seeklist->flag = entry.flag;
1199 seeklist->idx_id = i;
1200 tcs->seek_list_count++;
1202 yield();
1205 return tcs->seek_list_count > 0;
1209 static void remove_files(void)
1211 int i;
1212 char buf[MAX_PATH];
1214 tc_stat.ready = false;
1215 tc_stat.ramcache = false;
1216 tc_stat.econ = false;
1217 remove(TAGCACHE_FILE_MASTER);
1218 for (i = 0; i < TAG_COUNT; i++)
1220 if (TAGCACHE_IS_NUMERIC(i))
1221 continue;
1223 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, i);
1224 remove(buf);
1229 static bool check_all_headers(void)
1231 struct master_header myhdr;
1232 struct tagcache_header tch;
1233 int tag;
1234 int fd;
1236 if ( (fd = open_master_fd(&myhdr, false)) < 0)
1237 return false;
1239 close(fd);
1240 if (myhdr.dirty)
1242 logf("tagcache is dirty!");
1243 return false;
1246 memcpy(&current_tcmh, &myhdr, sizeof(struct master_header));
1248 for (tag = 0; tag < TAG_COUNT; tag++)
1250 if (TAGCACHE_IS_NUMERIC(tag))
1251 continue;
1253 if ( (fd = open_tag_fd(&tch, tag, false)) < 0)
1254 return false;
1256 close(fd);
1259 return true;
1262 bool tagcache_is_busy(void)
1264 return read_lock || write_lock;
1267 bool tagcache_search(struct tagcache_search *tcs, int tag)
1269 struct tagcache_header tag_hdr;
1270 struct master_header master_hdr;
1271 int i;
1273 while (read_lock)
1274 sleep(1);
1276 memset(tcs, 0, sizeof(struct tagcache_search));
1277 if (tc_stat.commit_step > 0 || !tc_stat.ready)
1278 return false;
1280 tcs->position = sizeof(struct tagcache_header);
1281 tcs->type = tag;
1282 tcs->seek_pos = 0;
1283 tcs->list_position = 0;
1284 tcs->seek_list_count = 0;
1285 tcs->filter_count = 0;
1286 tcs->masterfd = -1;
1288 for (i = 0; i < TAG_COUNT; i++)
1289 tcs->idxfd[i] = -1;
1291 #ifndef HAVE_TC_RAMCACHE
1292 tcs->ramsearch = false;
1293 #else
1294 tcs->ramsearch = tc_stat.ramcache;
1295 if (tcs->ramsearch)
1297 tcs->entry_count = hdr->entry_count[tcs->type];
1299 else
1300 #endif
1302 /* Always open as R/W so we can pass tcs to functions that modify data also
1303 * without failing. */
1304 tcs->masterfd = open_master_fd(&master_hdr, true);
1305 if (tcs->masterfd < 0)
1306 return false;
1308 if (!TAGCACHE_IS_NUMERIC(tcs->type))
1310 tcs->idxfd[tcs->type] = open_tag_fd(&tag_hdr, tcs->type, false);
1311 if (tcs->idxfd[tcs->type] < 0)
1312 return false;
1314 tcs->entry_count = tag_hdr.entry_count;
1316 else
1318 tcs->entry_count = master_hdr.tch.entry_count;
1322 tcs->valid = true;
1323 tcs->initialized = true;
1324 write_lock++;
1326 return true;
1329 void tagcache_search_set_uniqbuf(struct tagcache_search *tcs,
1330 void *buffer, long length)
1332 tcs->unique_list = (unsigned long *)buffer;
1333 tcs->unique_list_capacity = length / sizeof(*tcs->unique_list);
1334 tcs->unique_list_count = 0;
1337 bool tagcache_search_add_filter(struct tagcache_search *tcs,
1338 int tag, int seek)
1340 if (tcs->filter_count == TAGCACHE_MAX_FILTERS)
1341 return false;
1343 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag))
1344 return false;
1346 tcs->filter_tag[tcs->filter_count] = tag;
1347 tcs->filter_seek[tcs->filter_count] = seek;
1348 tcs->filter_count++;
1350 return true;
1353 bool tagcache_search_add_clause(struct tagcache_search *tcs,
1354 struct tagcache_search_clause *clause)
1356 int i;
1358 if (tcs->clause_count >= TAGCACHE_MAX_CLAUSES)
1360 logf("Too many clauses");
1361 return false;
1364 /* Check if there is already a similar filter in present (filters are
1365 * much faster than clauses).
1367 for (i = 0; i < tcs->filter_count; i++)
1369 if (tcs->filter_tag[i] == clause->tag)
1370 return true;
1373 if (!TAGCACHE_IS_NUMERIC(clause->tag) && tcs->idxfd[clause->tag] < 0)
1375 char buf[MAX_PATH];
1377 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, clause->tag);
1378 tcs->idxfd[clause->tag] = open(buf, O_RDONLY);
1381 tcs->clause[tcs->clause_count] = clause;
1382 tcs->clause_count++;
1384 return true;
1387 static bool get_next(struct tagcache_search *tcs)
1389 static char buf[TAG_MAXLEN+32];
1390 struct tagfile_entry entry;
1391 long flag = 0;
1393 if (!tcs->valid || !tc_stat.ready)
1394 return false;
1396 if (tcs->idxfd[tcs->type] < 0 && !TAGCACHE_IS_NUMERIC(tcs->type)
1397 #ifdef HAVE_TC_RAMCACHE
1398 && !tcs->ramsearch
1399 #endif
1401 return false;
1403 /* Relative fetch. */
1404 if (tcs->filter_count > 0 || tcs->clause_count > 0
1405 || TAGCACHE_IS_NUMERIC(tcs->type)
1406 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1407 /* We need to retrieve flag status for dircache. */
1408 || (tcs->ramsearch && tcs->type == tag_filename)
1409 #endif
1412 struct tagcache_seeklist_entry *seeklist;
1414 /* Check for end of list. */
1415 if (tcs->list_position == tcs->seek_list_count)
1417 tcs->list_position = 0;
1419 /* Try to fetch more. */
1420 if (!build_lookup_list(tcs))
1422 tcs->valid = false;
1423 return false;
1427 seeklist = &tcs->seeklist[tcs->list_position];
1428 flag = seeklist->flag;
1429 tcs->position = seeklist->seek;
1430 tcs->idx_id = seeklist->idx_id;
1431 tcs->list_position++;
1433 else
1435 if (tcs->entry_count == 0)
1437 tcs->valid = false;
1438 return false;
1441 tcs->entry_count--;
1444 tcs->result_seek = tcs->position;
1446 if (TAGCACHE_IS_NUMERIC(tcs->type))
1448 snprintf(buf, sizeof(buf), "%ld", tcs->position);
1449 tcs->result = buf;
1450 tcs->result_len = strlen(buf) + 1;
1451 return true;
1454 /* Direct fetch. */
1455 #ifdef HAVE_TC_RAMCACHE
1456 if (tcs->ramsearch)
1459 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1460 if (tcs->type == tag_filename && (flag & FLAG_DIRCACHE)
1461 && is_dircache_intact())
1463 dircache_copy_path((struct dircache_entry *)tcs->position,
1464 buf, sizeof buf);
1465 tcs->result = buf;
1466 tcs->result_len = strlen(buf) + 1;
1467 tcs->ramresult = false;
1469 return true;
1471 else
1472 #endif
1473 if (tcs->type != tag_filename)
1475 struct tagfile_entry *ep;
1477 ep = (struct tagfile_entry *)&hdr->tags[tcs->type][tcs->position];
1478 tcs->result = ep->tag_data;
1479 tcs->result_len = strlen(tcs->result) + 1;
1480 tcs->idx_id = ep->idx_id;
1481 tcs->ramresult = true;
1483 /* Increase position for the next run. This may get overwritten. */
1484 tcs->position += sizeof(struct tagfile_entry) + ep->tag_length;
1486 return true;
1489 #endif
1491 if (!open_files(tcs, tcs->type))
1493 tcs->valid = false;
1494 return false;
1497 /* Seek stream to the correct position and continue to direct fetch. */
1498 lseek(tcs->idxfd[tcs->type], tcs->position, SEEK_SET);
1500 if (ecread_tagfile_entry(tcs->idxfd[tcs->type], &entry) != sizeof(struct tagfile_entry))
1502 logf("read error #5");
1503 tcs->valid = false;
1504 return false;
1507 if (entry.tag_length > (long)sizeof(buf))
1509 tcs->valid = false;
1510 logf("too long tag #2");
1511 logf("P:%lX/%lX", tcs->position, entry.tag_length);
1512 return false;
1515 if (read(tcs->idxfd[tcs->type], buf, entry.tag_length) != entry.tag_length)
1517 tcs->valid = false;
1518 logf("read error #4");
1519 return false;
1523 Update the position for the next read (this may be overridden
1524 if filters or clauses are being used).
1526 tcs->position += sizeof(struct tagfile_entry) + entry.tag_length;
1527 tcs->result = buf;
1528 tcs->result_len = strlen(tcs->result) + 1;
1529 tcs->idx_id = entry.idx_id;
1530 tcs->ramresult = false;
1532 return true;
1535 bool tagcache_get_next(struct tagcache_search *tcs)
1537 while (get_next(tcs))
1539 if (tcs->result_len > 1)
1540 return true;
1543 return false;
1546 bool tagcache_retrieve(struct tagcache_search *tcs, int idxid,
1547 int tag, char *buf, long size)
1549 struct index_entry idx;
1551 *buf = '\0';
1552 if (!get_index(tcs->masterfd, idxid, &idx, true))
1553 return false;
1555 return retrieve(tcs, &idx, tag, buf, size);
1558 static bool update_master_header(void)
1560 struct master_header myhdr;
1561 int fd;
1563 if (!tc_stat.ready)
1564 return false;
1566 if ( (fd = open_master_fd(&myhdr, true)) < 0)
1567 return false;
1569 myhdr.serial = current_tcmh.serial;
1570 myhdr.commitid = current_tcmh.commitid;
1571 myhdr.dirty = current_tcmh.dirty;
1573 /* Write it back */
1574 lseek(fd, 0, SEEK_SET);
1575 ecwrite(fd, &myhdr, 1, master_header_ec, tc_stat.econ);
1576 close(fd);
1578 #ifdef HAVE_TC_RAMCACHE
1579 if (hdr)
1581 hdr->h.serial = current_tcmh.serial;
1582 hdr->h.commitid = current_tcmh.commitid;
1583 hdr->h.dirty = current_tcmh.dirty;
1585 #endif
1587 return true;
1590 #if 0
1592 void tagcache_modify(struct tagcache_search *tcs, int type, const char *text)
1594 struct tagentry *entry;
1596 if (tcs->type != tag_title)
1597 return ;
1599 /* We will need reserve buffer for this. */
1600 if (tcs->ramcache)
1602 struct tagfile_entry *ep;
1604 ep = (struct tagfile_entry *)&hdr->tags[tcs->type][tcs->result_seek];
1605 tcs->seek_list[tcs->seek_list_count];
1608 entry = find_entry_ram();
1611 #endif
1613 void tagcache_search_finish(struct tagcache_search *tcs)
1615 int i;
1617 if (!tcs->initialized)
1618 return;
1620 if (tcs->masterfd >= 0)
1622 close(tcs->masterfd);
1623 tcs->masterfd = -1;
1626 for (i = 0; i < TAG_COUNT; i++)
1628 if (tcs->idxfd[i] >= 0)
1630 close(tcs->idxfd[i]);
1631 tcs->idxfd[i] = -1;
1635 tcs->ramsearch = false;
1636 tcs->valid = false;
1637 tcs->initialized = 0;
1638 if (write_lock > 0)
1639 write_lock--;
1642 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1643 static struct tagfile_entry *get_tag(const struct index_entry *entry, int tag)
1645 return (struct tagfile_entry *)&hdr->tags[tag][entry->tag_seek[tag]];
1648 static long get_tag_numeric(const struct index_entry *entry, int tag, int idx_id)
1650 return check_virtual_tags(tag, idx_id, entry);
1653 static char* get_tag_string(const struct index_entry *entry, int tag)
1655 char* s = get_tag(entry, tag)->tag_data;
1656 return strcmp(s, UNTAGGED) ? s : NULL;
1659 bool tagcache_fill_tags(struct mp3entry *id3, const char *filename)
1661 struct index_entry *entry;
1662 int idx_id;
1664 if (!tc_stat.ready || !tc_stat.ramcache)
1665 return false;
1667 /* Find the corresponding entry in tagcache. */
1668 idx_id = find_entry_ram(filename, NULL);
1669 if (idx_id < 0)
1670 return false;
1672 entry = &hdr->indices[idx_id];
1674 memset(id3, 0, sizeof(struct mp3entry));
1676 id3->title = get_tag_string(entry, tag_title);
1677 id3->artist = get_tag_string(entry, tag_artist);
1678 id3->album = get_tag_string(entry, tag_album);
1679 id3->genre_string = get_tag_string(entry, tag_genre);
1680 id3->composer = get_tag_string(entry, tag_composer);
1681 id3->comment = get_tag_string(entry, tag_comment);
1682 id3->albumartist = get_tag_string(entry, tag_albumartist);
1683 id3->grouping = get_tag_string(entry, tag_grouping);
1685 id3->length = get_tag_numeric(entry, tag_length, idx_id);
1686 id3->playcount = get_tag_numeric(entry, tag_playcount, idx_id);
1687 id3->rating = get_tag_numeric(entry, tag_rating, idx_id);
1688 id3->lastplayed = get_tag_numeric(entry, tag_lastplayed, idx_id);
1689 id3->score = get_tag_numeric(entry, tag_virt_autoscore, idx_id) / 10;
1690 id3->year = get_tag_numeric(entry, tag_year, idx_id);
1692 id3->discnum = get_tag_numeric(entry, tag_discnumber, idx_id);
1693 id3->tracknum = get_tag_numeric(entry, tag_tracknumber, idx_id);
1694 id3->bitrate = get_tag_numeric(entry, tag_bitrate, idx_id);
1695 if (id3->bitrate == 0)
1696 id3->bitrate = 1;
1698 return true;
1700 #endif
1702 static inline void write_item(const char *item)
1704 int len = strlen(item) + 1;
1706 data_size += len;
1707 write(cachefd, item, len);
1710 static int check_if_empty(char **tag)
1712 int length;
1714 if (*tag == NULL || **tag == '\0')
1716 *tag = UNTAGGED;
1717 return sizeof(UNTAGGED); /* Tag length */
1720 length = strlen(*tag);
1721 if (length > TAG_MAXLEN)
1723 logf("over length tag: %s", *tag);
1724 length = TAG_MAXLEN;
1725 (*tag)[length] = '\0';
1728 return length + 1;
1731 #define ADD_TAG(entry,tag,data) \
1732 /* Adding tag */ \
1733 entry.tag_offset[tag] = offset; \
1734 entry.tag_length[tag] = check_if_empty(data); \
1735 offset += entry.tag_length[tag]
1736 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1737 * idea, as it uses lots of stack and is called from a recursive function
1738 * (check_dir).
1740 static void __attribute__ ((noinline)) add_tagcache(char *path,
1741 unsigned long mtime
1742 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1743 ,const struct dircache_entry *dc
1744 #endif
1747 struct mp3entry id3;
1748 struct temp_file_entry entry;
1749 bool ret;
1750 int fd;
1751 int idx_id = -1;
1752 char tracknumfix[3];
1753 int offset = 0;
1754 int path_length = strlen(path);
1755 bool has_albumartist;
1756 bool has_grouping;
1758 #ifdef SIMULATOR
1759 /* Crude logging for the sim - to aid in debugging */
1760 int logfd = open(ROCKBOX_DIR "/database.log",
1761 O_WRONLY | O_APPEND | O_CREAT, 0666);
1762 if (logfd >= 0) {
1763 write(logfd, path, strlen(path));
1764 write(logfd, "\n", 1);
1765 close(logfd);
1767 #endif
1769 if (cachefd < 0)
1770 return ;
1772 /* Check for overlength file path. */
1773 if (path_length > TAG_MAXLEN)
1775 /* Path can't be shortened. */
1776 logf("Too long path: %s", path);
1777 return ;
1780 /* Check if the file is supported. */
1781 if (probe_file_format(path) == AFMT_UNKNOWN)
1782 return ;
1784 /* Check if the file is already cached. */
1785 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1786 if (tc_stat.ramcache && is_dircache_intact())
1788 idx_id = find_entry_ram(path, dc);
1790 #endif
1792 /* Be sure the entry doesn't exist. */
1793 if (filenametag_fd >= 0 && idx_id < 0)
1794 idx_id = find_entry_disk(path, false);
1796 /* Check if file has been modified. */
1797 if (idx_id >= 0)
1799 struct index_entry idx;
1801 /* TODO: Mark that the index exists (for fast reverse scan) */
1802 //found_idx[idx_id/8] |= idx_id%8;
1804 if (!get_index(-1, idx_id, &idx, true))
1806 logf("failed to retrieve index entry");
1807 return ;
1810 if ((unsigned long)idx.tag_seek[tag_mtime] == mtime)
1812 /* No changes to file. */
1813 return ;
1816 /* Metadata might have been changed. Delete the entry. */
1817 logf("Re-adding: %s", path);
1818 if (!delete_entry(idx_id))
1820 logf("delete_entry failed: %d", idx_id);
1821 return ;
1825 fd = open(path, O_RDONLY);
1826 if (fd < 0)
1828 logf("open fail: %s", path);
1829 return ;
1832 memset(&id3, 0, sizeof(struct mp3entry));
1833 memset(&entry, 0, sizeof(struct temp_file_entry));
1834 memset(&tracknumfix, 0, sizeof(tracknumfix));
1835 ret = get_metadata(&id3, fd, path);
1836 close(fd);
1838 if (!ret)
1839 return ;
1841 logf("-> %s", path);
1843 /* Generate track number if missing. */
1844 if (id3.tracknum <= 0)
1846 const char *p = strrchr(path, '.');
1848 if (p == NULL)
1849 p = &path[strlen(path)-1];
1851 while (*p != '/')
1853 if (isdigit(*p) && isdigit(*(p-1)))
1855 tracknumfix[1] = *p--;
1856 tracknumfix[0] = *p;
1857 break;
1859 p--;
1862 if (tracknumfix[0] != '\0')
1864 id3.tracknum = atoi(tracknumfix);
1865 /* Set a flag to indicate track number has been generated. */
1866 entry.flag |= FLAG_TRKNUMGEN;
1868 else
1870 /* Unable to generate track number. */
1871 id3.tracknum = -1;
1875 /* Numeric tags */
1876 entry.tag_offset[tag_year] = id3.year;
1877 entry.tag_offset[tag_discnumber] = id3.discnum;
1878 entry.tag_offset[tag_tracknumber] = id3.tracknum;
1879 entry.tag_offset[tag_length] = id3.length;
1880 entry.tag_offset[tag_bitrate] = id3.bitrate;
1881 entry.tag_offset[tag_mtime] = mtime;
1883 /* String tags. */
1884 has_albumartist = id3.albumartist != NULL
1885 && strlen(id3.albumartist) > 0;
1886 has_grouping = id3.grouping != NULL
1887 && strlen(id3.grouping) > 0;
1889 ADD_TAG(entry, tag_filename, &path);
1890 ADD_TAG(entry, tag_title, &id3.title);
1891 ADD_TAG(entry, tag_artist, &id3.artist);
1892 ADD_TAG(entry, tag_album, &id3.album);
1893 ADD_TAG(entry, tag_genre, &id3.genre_string);
1894 ADD_TAG(entry, tag_composer, &id3.composer);
1895 ADD_TAG(entry, tag_comment, &id3.comment);
1896 if (has_albumartist)
1898 ADD_TAG(entry, tag_albumartist, &id3.albumartist);
1900 else
1902 ADD_TAG(entry, tag_albumartist, &id3.artist);
1904 if (has_grouping)
1906 ADD_TAG(entry, tag_grouping, &id3.grouping);
1908 else
1910 ADD_TAG(entry, tag_grouping, &id3.title);
1912 entry.data_length = offset;
1914 /* Write the header */
1915 write(cachefd, &entry, sizeof(struct temp_file_entry));
1917 /* And tags also... Correct order is critical */
1918 write_item(path);
1919 write_item(id3.title);
1920 write_item(id3.artist);
1921 write_item(id3.album);
1922 write_item(id3.genre_string);
1923 write_item(id3.composer);
1924 write_item(id3.comment);
1925 if (has_albumartist)
1927 write_item(id3.albumartist);
1929 else
1931 write_item(id3.artist);
1933 if (has_grouping)
1935 write_item(id3.grouping);
1937 else
1939 write_item(id3.title);
1941 total_entry_count++;
1944 static bool tempbuf_insert(char *str, int id, int idx_id, bool unique)
1946 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
1947 int len = strlen(str)+1;
1948 int i;
1949 unsigned crc32;
1950 unsigned *crcbuf = (unsigned *)&tempbuf[tempbuf_size-4];
1951 char buf[TAG_MAXLEN+32];
1953 for (i = 0; str[i] != '\0' && i < (int)sizeof(buf)-1; i++)
1954 buf[i] = tolower(str[i]);
1955 buf[i] = '\0';
1957 crc32 = crc_32(buf, i, 0xffffffff);
1959 if (unique)
1961 /* Check if the crc does not exist -> entry does not exist for sure. */
1962 for (i = 0; i < tempbufidx; i++)
1964 if (crcbuf[-i] != crc32)
1965 continue;
1967 if (!strcasecmp(str, index[i].str))
1969 if (id < 0 || id >= lookup_buffer_depth)
1971 logf("lookup buf overf.: %d", id);
1972 return false;
1975 lookup[id] = &index[i];
1976 return true;
1981 /* Insert to CRC buffer. */
1982 crcbuf[-tempbufidx] = crc32;
1983 tempbuf_left -= 4;
1985 /* Insert it to the buffer. */
1986 tempbuf_left -= len;
1987 if (tempbuf_left - 4 < 0 || tempbufidx >= commit_entry_count-1)
1988 return false;
1990 if (id >= lookup_buffer_depth)
1992 logf("lookup buf overf. #2: %d", id);
1993 return false;
1996 if (id >= 0)
1998 lookup[id] = &index[tempbufidx];
1999 index[tempbufidx].idlist.id = id;
2001 else
2002 index[tempbufidx].idlist.id = -1;
2004 index[tempbufidx].idlist.next = NULL;
2005 index[tempbufidx].idx_id = idx_id;
2006 index[tempbufidx].seek = -1;
2007 index[tempbufidx].str = &tempbuf[tempbuf_pos];
2008 memcpy(index[tempbufidx].str, str, len);
2009 tempbuf_pos += len;
2010 tempbufidx++;
2012 return true;
2015 static int compare(const void *p1, const void *p2)
2017 do_timed_yield();
2019 struct tempbuf_searchidx *e1 = (struct tempbuf_searchidx *)p1;
2020 struct tempbuf_searchidx *e2 = (struct tempbuf_searchidx *)p2;
2022 if (strcmp(e1->str, UNTAGGED) == 0)
2024 if (strcmp(e2->str, UNTAGGED) == 0)
2025 return 0;
2026 return -1;
2028 else if (strcmp(e2->str, UNTAGGED) == 0)
2029 return 1;
2031 return strncasecmp(e1->str, e2->str, TAG_MAXLEN);
2034 static int tempbuf_sort(int fd)
2036 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
2037 struct tagfile_entry fe;
2038 int i;
2039 int length;
2041 /* Generate reverse lookup entries. */
2042 for (i = 0; i < lookup_buffer_depth; i++)
2044 struct tempbuf_id_list *idlist;
2046 if (!lookup[i])
2047 continue;
2049 if (lookup[i]->idlist.id == i)
2050 continue;
2052 idlist = &lookup[i]->idlist;
2053 while (idlist->next != NULL)
2054 idlist = idlist->next;
2056 tempbuf_left -= sizeof(struct tempbuf_id_list);
2057 if (tempbuf_left - 4 < 0)
2058 return -1;
2060 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2061 if (tempbuf_pos & 0x03)
2063 tempbuf_pos = (tempbuf_pos & ~0x03) + 0x04;
2064 tempbuf_left -= 3;
2065 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2067 tempbuf_pos += sizeof(struct tempbuf_id_list);
2069 idlist = idlist->next;
2070 idlist->id = i;
2071 idlist->next = NULL;
2073 do_timed_yield();
2076 qsort(index, tempbufidx, sizeof(struct tempbuf_searchidx), compare);
2077 memset(lookup, 0, lookup_buffer_depth * sizeof(struct tempbuf_searchidx **));
2079 for (i = 0; i < tempbufidx; i++)
2081 struct tempbuf_id_list *idlist = &index[i].idlist;
2083 /* Fix the lookup list. */
2084 while (idlist != NULL)
2086 if (idlist->id >= 0)
2087 lookup[idlist->id] = &index[i];
2088 idlist = idlist->next;
2091 index[i].seek = lseek(fd, 0, SEEK_CUR);
2092 length = strlen(index[i].str) + 1;
2093 fe.tag_length = length;
2094 fe.idx_id = index[i].idx_id;
2096 /* Check the chunk alignment. */
2097 if ((fe.tag_length + sizeof(struct tagfile_entry))
2098 % TAGFILE_ENTRY_CHUNK_LENGTH)
2100 fe.tag_length += TAGFILE_ENTRY_CHUNK_LENGTH -
2101 ((fe.tag_length + sizeof(struct tagfile_entry))
2102 % TAGFILE_ENTRY_CHUNK_LENGTH);
2105 #ifdef TAGCACHE_STRICT_ALIGN
2106 /* Make sure the entry is long aligned. */
2107 if (index[i].seek & 0x03)
2109 logf("tempbuf_sort: alignment error!");
2110 return -3;
2112 #endif
2114 if (ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ) !=
2115 sizeof(struct tagfile_entry))
2117 logf("tempbuf_sort: write error #1");
2118 return -1;
2121 if (write(fd, index[i].str, length) != length)
2123 logf("tempbuf_sort: write error #2");
2124 return -2;
2127 /* Write some padding. */
2128 if (fe.tag_length - length > 0)
2129 write(fd, "XXXXXXXX", fe.tag_length - length);
2132 return i;
2135 inline static struct tempbuf_searchidx* tempbuf_locate(int id)
2137 if (id < 0 || id >= lookup_buffer_depth)
2138 return NULL;
2140 return lookup[id];
2144 inline static int tempbuf_find_location(int id)
2146 struct tempbuf_searchidx *entry;
2148 entry = tempbuf_locate(id);
2149 if (entry == NULL)
2150 return -1;
2152 return entry->seek;
2155 static bool build_numeric_indices(struct tagcache_header *h, int tmpfd)
2157 struct master_header tcmh;
2158 struct index_entry idx;
2159 int masterfd;
2160 int masterfd_pos;
2161 struct temp_file_entry *entrybuf = (struct temp_file_entry *)tempbuf;
2162 int max_entries;
2163 int entries_processed = 0;
2164 int i, j;
2165 char buf[TAG_MAXLEN];
2167 max_entries = tempbuf_size / sizeof(struct temp_file_entry) - 1;
2169 logf("Building numeric indices...");
2170 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2172 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
2173 return false;
2175 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2176 SEEK_CUR);
2177 if (masterfd_pos == filesize(masterfd))
2179 logf("we can't append!");
2180 close(masterfd);
2181 return false;
2184 while (entries_processed < h->entry_count)
2186 int count = MIN(h->entry_count - entries_processed, max_entries);
2188 /* Read in as many entries as possible. */
2189 for (i = 0; i < count; i++)
2191 struct temp_file_entry *tfe = &entrybuf[i];
2192 int datastart;
2194 /* Read in numeric data. */
2195 if (read(tmpfd, tfe, sizeof(struct temp_file_entry)) !=
2196 sizeof(struct temp_file_entry))
2198 logf("read fail #1");
2199 close(masterfd);
2200 return false;
2203 datastart = lseek(tmpfd, 0, SEEK_CUR);
2206 * Read string data from the following tags:
2207 * - tag_filename
2208 * - tag_artist
2209 * - tag_album
2210 * - tag_title
2212 * A crc32 hash is calculated from the read data
2213 * and stored back to the data offset field kept in memory.
2215 #define tmpdb_read_string_tag(tag) \
2216 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2217 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2219 logf("read fail: buffer overflow"); \
2220 close(masterfd); \
2221 return false; \
2224 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2225 tfe->tag_length[tag]) \
2227 logf("read fail #2"); \
2228 close(masterfd); \
2229 return false; \
2232 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2233 lseek(tmpfd, datastart, SEEK_SET)
2235 tmpdb_read_string_tag(tag_filename);
2236 tmpdb_read_string_tag(tag_artist);
2237 tmpdb_read_string_tag(tag_album);
2238 tmpdb_read_string_tag(tag_title);
2240 /* Seek to the end of the string data. */
2241 lseek(tmpfd, tfe->data_length, SEEK_CUR);
2244 /* Backup the master index position. */
2245 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2246 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2248 /* Check if we can resurrect some deleted runtime statistics data. */
2249 for (i = 0; i < tcmh.tch.entry_count; i++)
2251 /* Read the index entry. */
2252 if (ecread_index_entry(masterfd, &idx)
2253 != sizeof(struct index_entry))
2255 logf("read fail #3");
2256 close(masterfd);
2257 return false;
2261 * Skip unless the entry is marked as being deleted
2262 * or the data has already been resurrected.
2264 if (!(idx.flag & FLAG_DELETED) || idx.flag & FLAG_RESURRECTED)
2265 continue;
2267 /* Now try to match the entry. */
2269 * To succesfully match a song, the following conditions
2270 * must apply:
2272 * For numeric fields: tag_length
2273 * - Full identical match is required
2275 * If tag_filename matches, no further checking necessary.
2277 * For string hashes: tag_artist, tag_album, tag_title
2278 * - Two of these must match
2280 for (j = 0; j < count; j++)
2282 struct temp_file_entry *tfe = &entrybuf[j];
2284 /* Try to match numeric fields first. */
2285 if (tfe->tag_offset[tag_length] != idx.tag_seek[tag_length])
2286 continue;
2288 /* Now it's time to do the hash matching. */
2289 if (tfe->tag_offset[tag_filename] != idx.tag_seek[tag_filename])
2291 int match_count = 0;
2293 /* No filename match, check if we can match two other tags. */
2294 #define tmpdb_match(tag) \
2295 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2296 match_count++
2298 tmpdb_match(tag_artist);
2299 tmpdb_match(tag_album);
2300 tmpdb_match(tag_title);
2302 if (match_count < 2)
2304 /* Still no match found, give up. */
2305 continue;
2309 /* A match found, now copy & resurrect the statistical data. */
2310 #define tmpdb_copy_tag(tag) \
2311 tfe->tag_offset[tag] = idx.tag_seek[tag]
2313 tmpdb_copy_tag(tag_playcount);
2314 tmpdb_copy_tag(tag_rating);
2315 tmpdb_copy_tag(tag_playtime);
2316 tmpdb_copy_tag(tag_lastplayed);
2317 tmpdb_copy_tag(tag_commitid);
2319 /* Avoid processing this entry again. */
2320 idx.flag |= FLAG_RESURRECTED;
2322 lseek(masterfd, -sizeof(struct index_entry), SEEK_CUR);
2323 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2325 logf("masterfd writeback fail #1");
2326 close(masterfd);
2327 return false;
2330 logf("Entry resurrected");
2335 /* Restore the master index position. */
2336 lseek(masterfd, masterfd_pos, SEEK_SET);
2338 /* Commit the data to the index. */
2339 for (i = 0; i < count; i++)
2341 int loc = lseek(masterfd, 0, SEEK_CUR);
2343 if (ecread_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2345 logf("read fail #3");
2346 close(masterfd);
2347 return false;
2350 for (j = 0; j < TAG_COUNT; j++)
2352 if (!TAGCACHE_IS_NUMERIC(j))
2353 continue;
2355 idx.tag_seek[j] = entrybuf[i].tag_offset[j];
2357 idx.flag = entrybuf[i].flag;
2359 if (idx.tag_seek[tag_commitid])
2361 /* Data has been resurrected. */
2362 idx.flag |= FLAG_DIRTYNUM;
2364 else if (tc_stat.ready && current_tcmh.commitid > 0)
2366 idx.tag_seek[tag_commitid] = current_tcmh.commitid;
2367 idx.flag |= FLAG_DIRTYNUM;
2370 /* Write back the updated index. */
2371 lseek(masterfd, loc, SEEK_SET);
2372 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2374 logf("write fail");
2375 close(masterfd);
2376 return false;
2380 entries_processed += count;
2381 logf("%d/%ld entries processed", entries_processed, h->entry_count);
2384 close(masterfd);
2386 return true;
2390 * Return values:
2391 * > 0 success
2392 * == 0 temporary failure
2393 * < 0 fatal error
2395 static int build_index(int index_type, struct tagcache_header *h, int tmpfd)
2397 int i;
2398 struct tagcache_header tch;
2399 struct master_header tcmh;
2400 struct index_entry idxbuf[IDX_BUF_DEPTH];
2401 int idxbuf_pos;
2402 char buf[TAG_MAXLEN+32];
2403 int fd = -1, masterfd;
2404 bool error = false;
2405 int init;
2406 int masterfd_pos;
2408 logf("Building index: %d", index_type);
2410 /* Check the number of entries we need to allocate ram for. */
2411 commit_entry_count = h->entry_count + 1;
2413 masterfd = open_master_fd(&tcmh, false);
2414 if (masterfd >= 0)
2416 commit_entry_count += tcmh.tch.entry_count;
2417 close(masterfd);
2419 else
2420 remove_files(); /* Just to be sure we are clean. */
2422 /* Open the index file, which contains the tag names. */
2423 fd = open_tag_fd(&tch, index_type, true);
2424 if (fd >= 0)
2426 logf("tch.datasize=%ld", tch.datasize);
2427 lookup_buffer_depth = 1 +
2428 /* First part */ commit_entry_count +
2429 /* Second part */ (tch.datasize / TAGFILE_ENTRY_CHUNK_LENGTH);
2431 else
2433 lookup_buffer_depth = 1 +
2434 /* First part */ commit_entry_count +
2435 /* Second part */ 0;
2438 logf("lookup_buffer_depth=%ld", lookup_buffer_depth);
2439 logf("commit_entry_count=%ld", commit_entry_count);
2441 /* Allocate buffer for all index entries from both old and new
2442 * tag files. */
2443 tempbufidx = 0;
2444 tempbuf_pos = commit_entry_count * sizeof(struct tempbuf_searchidx);
2446 /* Allocate lookup buffer. The first portion of commit_entry_count
2447 * contains the new tags in the temporary file and the second
2448 * part for locating entries already in the db.
2450 * New tags Old tags
2451 * +---------+---------------------------+
2452 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2453 * +---------+---------------------------+
2455 * Old tags are inserted to a temporary buffer with position:
2456 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2457 * And new tags with index:
2458 * tempbuf_insert(idx, ...);
2460 * The buffer is sorted and written into tag file:
2461 * tempbuf_sort(...);
2462 * leaving master index locations messed up.
2464 * That is fixed using the lookup buffer for old tags:
2465 * new_seek = tempbuf_find_location(old_seek, ...);
2466 * and for new tags:
2467 * new_seek = tempbuf_find_location(idx);
2469 lookup = (struct tempbuf_searchidx **)&tempbuf[tempbuf_pos];
2470 tempbuf_pos += lookup_buffer_depth * sizeof(void **);
2471 memset(lookup, 0, lookup_buffer_depth * sizeof(void **));
2473 /* And calculate the remaining data space used mainly for storing
2474 * tag data (strings). */
2475 tempbuf_left = tempbuf_size - tempbuf_pos - 8;
2476 if (tempbuf_left - TAGFILE_ENTRY_AVG_LENGTH * commit_entry_count < 0)
2478 logf("Buffer way too small!");
2479 return 0;
2482 if (fd >= 0)
2485 * If tag file contains unique tags (sorted index), we will load
2486 * it entirely into memory so we can resort it later for use with
2487 * chunked browsing.
2489 if (TAGCACHE_IS_SORTED(index_type))
2491 logf("loading tags...");
2492 for (i = 0; i < tch.entry_count; i++)
2494 struct tagfile_entry entry;
2495 int loc = lseek(fd, 0, SEEK_CUR);
2496 bool ret;
2498 if (ecread_tagfile_entry(fd, &entry) != sizeof(struct tagfile_entry))
2500 logf("read error #7");
2501 close(fd);
2502 return -2;
2505 if (entry.tag_length >= (int)sizeof(buf))
2507 logf("too long tag #3");
2508 close(fd);
2509 return -2;
2512 if (read(fd, buf, entry.tag_length) != entry.tag_length)
2514 logf("read error #8");
2515 close(fd);
2516 return -2;
2519 /* Skip deleted entries. */
2520 if (buf[0] == '\0')
2521 continue;
2524 * Save the tag and tag id in the memory buffer. Tag id
2525 * is saved so we can later reindex the master lookup
2526 * table when the index gets resorted.
2528 ret = tempbuf_insert(buf, loc/TAGFILE_ENTRY_CHUNK_LENGTH
2529 + commit_entry_count, entry.idx_id,
2530 TAGCACHE_IS_UNIQUE(index_type));
2531 if (!ret)
2533 close(fd);
2534 return -3;
2536 do_timed_yield();
2538 logf("done");
2540 else
2541 tempbufidx = tch.entry_count;
2543 else
2546 * Creating new index file to store the tags. No need to preload
2547 * anything whether the index type is sorted or not.
2549 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, index_type);
2550 fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2551 if (fd < 0)
2553 logf("%s open fail", buf);
2554 return -2;
2557 tch.magic = TAGCACHE_MAGIC;
2558 tch.entry_count = 0;
2559 tch.datasize = 0;
2561 if (ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ)
2562 != sizeof(struct tagcache_header))
2564 logf("header write failed");
2565 close(fd);
2566 return -2;
2570 /* Loading the tag lookup file as "master file". */
2571 logf("Loading index file");
2572 masterfd = open(TAGCACHE_FILE_MASTER, O_RDWR);
2574 if (masterfd < 0)
2576 logf("Creating new DB");
2577 masterfd = open(TAGCACHE_FILE_MASTER, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2579 if (masterfd < 0)
2581 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER);
2582 close(fd);
2583 return -2;
2586 /* Write the header (write real values later). */
2587 memset(&tcmh, 0, sizeof(struct master_header));
2588 tcmh.tch = *h;
2589 tcmh.tch.entry_count = 0;
2590 tcmh.tch.datasize = 0;
2591 tcmh.dirty = true;
2592 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
2593 init = true;
2594 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2596 else
2599 * Master file already exists so we need to process the current
2600 * file first.
2602 init = false;
2604 if (ecread(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ) !=
2605 sizeof(struct master_header) || tcmh.tch.magic != TAGCACHE_MAGIC)
2607 logf("header error");
2608 close(fd);
2609 close(masterfd);
2610 return -2;
2614 * If we reach end of the master file, we need to expand it to
2615 * hold new tags. If the current index is not sorted, we can
2616 * simply append new data to end of the file.
2617 * However, if the index is sorted, we need to update all tag
2618 * pointers in the master file for the current index.
2620 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2621 SEEK_CUR);
2622 if (masterfd_pos == filesize(masterfd))
2624 logf("appending...");
2625 init = true;
2630 * Load new unique tags in memory to be sorted later and added
2631 * to the master lookup file.
2633 if (TAGCACHE_IS_SORTED(index_type))
2635 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2636 /* h is the header of the temporary file containing new tags. */
2637 logf("inserting new tags...");
2638 for (i = 0; i < h->entry_count; i++)
2640 struct temp_file_entry entry;
2642 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2643 sizeof(struct temp_file_entry))
2645 logf("read fail #3");
2646 error = true;
2647 goto error_exit;
2650 /* Read data. */
2651 if (entry.tag_length[index_type] >= (long)sizeof(buf))
2653 logf("too long entry!");
2654 error = true;
2655 goto error_exit;
2658 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2659 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2660 entry.tag_length[index_type])
2662 logf("read fail #4");
2663 error = true;
2664 goto error_exit;
2667 if (TAGCACHE_IS_UNIQUE(index_type))
2668 error = !tempbuf_insert(buf, i, -1, true);
2669 else
2670 error = !tempbuf_insert(buf, i, tcmh.tch.entry_count + i, false);
2672 if (error)
2674 logf("insert error");
2675 goto error_exit;
2678 /* Skip to next. */
2679 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2680 entry.tag_length[index_type], SEEK_CUR);
2681 do_timed_yield();
2683 logf("done");
2685 /* Sort the buffer data and write it to the index file. */
2686 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
2688 * We need to truncate the index file now. There can be junk left
2689 * at the end of file (however, we _should_ always follow the
2690 * entry_count and don't crash with that).
2692 ftruncate(fd, lseek(fd, 0, SEEK_CUR));
2694 i = tempbuf_sort(fd);
2695 if (i < 0)
2696 goto error_exit;
2697 logf("sorted %d tags", i);
2700 * Now update all indexes in the master lookup file.
2702 logf("updating indices...");
2703 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2704 for (i = 0; i < tcmh.tch.entry_count; i += idxbuf_pos)
2706 int j;
2707 int loc = lseek(masterfd, 0, SEEK_CUR);
2709 idxbuf_pos = MIN(tcmh.tch.entry_count - i, IDX_BUF_DEPTH);
2711 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2712 != (int)sizeof(struct index_entry)*idxbuf_pos)
2714 logf("read fail #5");
2715 error = true;
2716 goto error_exit ;
2718 lseek(masterfd, loc, SEEK_SET);
2720 for (j = 0; j < idxbuf_pos; j++)
2722 if (idxbuf[j].flag & FLAG_DELETED)
2724 /* We can just ignore deleted entries. */
2725 // idxbuf[j].tag_seek[index_type] = 0;
2726 continue;
2729 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(
2730 idxbuf[j].tag_seek[index_type]/TAGFILE_ENTRY_CHUNK_LENGTH
2731 + commit_entry_count);
2733 if (idxbuf[j].tag_seek[index_type] < 0)
2735 logf("update error: %ld/%d/%ld",
2736 idxbuf[j].flag, i+j, tcmh.tch.entry_count);
2737 error = true;
2738 goto error_exit;
2741 do_timed_yield();
2744 /* Write back the updated index. */
2745 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2746 index_entry_ec, tc_stat.econ) !=
2747 (int)sizeof(struct index_entry)*idxbuf_pos)
2749 logf("write fail");
2750 error = true;
2751 goto error_exit;
2754 logf("done");
2758 * Walk through the temporary file containing the new tags.
2760 // build_normal_index(h, tmpfd, masterfd, idx);
2761 logf("updating new indices...");
2762 lseek(masterfd, masterfd_pos, SEEK_SET);
2763 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2764 lseek(fd, 0, SEEK_END);
2765 for (i = 0; i < h->entry_count; i += idxbuf_pos)
2767 int j;
2769 idxbuf_pos = MIN(h->entry_count - i, IDX_BUF_DEPTH);
2770 if (init)
2772 memset(idxbuf, 0, sizeof(struct index_entry)*IDX_BUF_DEPTH);
2774 else
2776 int loc = lseek(masterfd, 0, SEEK_CUR);
2778 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2779 != (int)sizeof(struct index_entry)*idxbuf_pos)
2781 logf("read fail #6");
2782 error = true;
2783 break ;
2785 lseek(masterfd, loc, SEEK_SET);
2788 /* Read entry headers. */
2789 for (j = 0; j < idxbuf_pos; j++)
2791 if (!TAGCACHE_IS_SORTED(index_type))
2793 struct temp_file_entry entry;
2794 struct tagfile_entry fe;
2796 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2797 sizeof(struct temp_file_entry))
2799 logf("read fail #7");
2800 error = true;
2801 break ;
2804 /* Read data. */
2805 if (entry.tag_length[index_type] >= (int)sizeof(buf))
2807 logf("too long entry!");
2808 logf("length=%d", entry.tag_length[index_type]);
2809 logf("pos=0x%02lx", lseek(tmpfd, 0, SEEK_CUR));
2810 error = true;
2811 break ;
2814 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2815 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2816 entry.tag_length[index_type])
2818 logf("read fail #8");
2819 logf("offset=0x%02lx", entry.tag_offset[index_type]);
2820 logf("length=0x%02x", entry.tag_length[index_type]);
2821 error = true;
2822 break ;
2825 /* Write to index file. */
2826 idxbuf[j].tag_seek[index_type] = lseek(fd, 0, SEEK_CUR);
2827 fe.tag_length = entry.tag_length[index_type];
2828 fe.idx_id = tcmh.tch.entry_count + i + j;
2829 ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ);
2830 write(fd, buf, fe.tag_length);
2831 tempbufidx++;
2833 /* Skip to next. */
2834 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2835 entry.tag_length[index_type], SEEK_CUR);
2837 else
2839 /* Locate the correct entry from the sorted array. */
2840 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(i + j);
2841 if (idxbuf[j].tag_seek[index_type] < 0)
2843 logf("entry not found (%d)", j);
2844 error = true;
2845 break ;
2850 /* Write index. */
2851 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2852 index_entry_ec, tc_stat.econ) !=
2853 (int)sizeof(struct index_entry)*idxbuf_pos)
2855 logf("tagcache: write fail #4");
2856 error = true;
2857 break ;
2860 do_timed_yield();
2862 logf("done");
2864 /* Finally write the header. */
2865 tch.magic = TAGCACHE_MAGIC;
2866 tch.entry_count = tempbufidx;
2867 tch.datasize = lseek(fd, 0, SEEK_END) - sizeof(struct tagcache_header);
2868 lseek(fd, 0, SEEK_SET);
2869 ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ);
2871 if (index_type != tag_filename)
2872 h->datasize += tch.datasize;
2873 logf("s:%d/%ld/%ld", index_type, tch.datasize, h->datasize);
2874 error_exit:
2876 close(fd);
2877 close(masterfd);
2879 if (error)
2880 return -2;
2882 return 1;
2885 static bool commit(void)
2887 struct tagcache_header tch;
2888 struct master_header tcmh;
2889 int i, len, rc;
2890 int tmpfd;
2891 int masterfd;
2892 #ifdef HAVE_DIRCACHE
2893 bool dircache_buffer_stolen = false;
2894 #endif
2895 bool local_allocation = false;
2897 logf("committing tagcache");
2899 while (write_lock)
2900 sleep(1);
2902 tmpfd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
2903 if (tmpfd < 0)
2905 logf("nothing to commit");
2906 return true;
2910 /* Load the header. */
2911 len = sizeof(struct tagcache_header);
2912 rc = read(tmpfd, &tch, len);
2914 if (tch.magic != TAGCACHE_MAGIC || rc != len)
2916 logf("incorrect tmpheader");
2917 close(tmpfd);
2918 remove(TAGCACHE_FILE_TEMP);
2919 return false;
2922 if (tch.entry_count == 0)
2924 logf("nothing to commit");
2925 close(tmpfd);
2926 remove(TAGCACHE_FILE_TEMP);
2927 return true;
2930 /* Fully initialize existing headers (if any) before going further. */
2931 tc_stat.ready = check_all_headers();
2933 #ifdef HAVE_EEPROM_SETTINGS
2934 remove(TAGCACHE_STATEFILE);
2935 #endif
2937 /* At first be sure to unload the ramcache! */
2938 #ifdef HAVE_TC_RAMCACHE
2939 tc_stat.ramcache = false;
2940 #endif
2942 read_lock++;
2944 /* Try to steal every buffer we can :) */
2945 if (tempbuf_size == 0)
2946 local_allocation = true;
2948 #ifdef HAVE_DIRCACHE
2949 if (tempbuf_size == 0)
2951 /* Try to steal the dircache buffer. */
2952 tempbuf = dircache_steal_buffer(&tempbuf_size);
2953 tempbuf_size &= ~0x03;
2955 if (tempbuf_size > 0)
2957 dircache_buffer_stolen = true;
2960 #endif
2962 #ifdef HAVE_TC_RAMCACHE
2963 if (tempbuf_size == 0 && tc_stat.ramcache_allocated > 0)
2965 tempbuf = (char *)(hdr + 1);
2966 tempbuf_size = tc_stat.ramcache_allocated - sizeof(struct ramcache_header) - 128;
2967 tempbuf_size &= ~0x03;
2969 #endif
2971 /* And finally fail if there are no buffers available. */
2972 if (tempbuf_size == 0)
2974 logf("delaying commit until next boot");
2975 tc_stat.commit_delayed = true;
2976 close(tmpfd);
2977 read_lock--;
2978 return false;
2981 logf("commit %ld entries...", tch.entry_count);
2983 /* Mark DB dirty so it will stay disabled if commit fails. */
2984 current_tcmh.dirty = true;
2985 update_master_header();
2987 /* Now create the index files. */
2988 tc_stat.commit_step = 0;
2989 tch.datasize = 0;
2990 tc_stat.commit_delayed = false;
2992 for (i = 0; i < TAG_COUNT; i++)
2994 int ret;
2996 if (TAGCACHE_IS_NUMERIC(i))
2997 continue;
2999 tc_stat.commit_step++;
3000 ret = build_index(i, &tch, tmpfd);
3001 if (ret <= 0)
3003 close(tmpfd);
3004 logf("tagcache failed init");
3005 if (ret == 0)
3006 tc_stat.commit_delayed = true;
3008 tc_stat.commit_step = 0;
3009 read_lock--;
3010 return false;
3014 if (!build_numeric_indices(&tch, tmpfd))
3016 logf("Failure to commit numeric indices");
3017 close(tmpfd);
3018 tc_stat.commit_step = 0;
3019 read_lock--;
3020 return false;
3023 close(tmpfd);
3024 remove(TAGCACHE_FILE_TEMP);
3026 tc_stat.commit_step = 0;
3028 /* Update the master index headers. */
3029 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
3031 read_lock--;
3032 return false;
3035 tcmh.tch.entry_count += tch.entry_count;
3036 tcmh.tch.datasize = sizeof(struct master_header)
3037 + sizeof(struct index_entry) * tcmh.tch.entry_count
3038 + tch.datasize;
3039 tcmh.dirty = false;
3040 tcmh.commitid++;
3042 lseek(masterfd, 0, SEEK_SET);
3043 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
3044 close(masterfd);
3046 logf("tagcache committed");
3047 tc_stat.ready = check_all_headers();
3048 tc_stat.readyvalid = true;
3050 if (local_allocation)
3052 tempbuf = NULL;
3053 tempbuf_size = 0;
3056 #ifdef HAVE_DIRCACHE
3057 /* Rebuild the dircache, if we stole the buffer. */
3058 if (dircache_buffer_stolen)
3059 dircache_build(0);
3060 #endif
3062 #ifdef HAVE_TC_RAMCACHE
3063 /* Reload tagcache. */
3064 if (tc_stat.ramcache_allocated > 0)
3065 tagcache_start_scan();
3066 #endif
3068 read_lock--;
3070 return true;
3073 static void allocate_tempbuf(void)
3075 /* Yeah, malloc would be really nice now :) */
3076 #ifdef __PCTOOL__
3077 tempbuf_size = 32*1024*1024;
3078 tempbuf = malloc(tempbuf_size);
3079 #else
3080 tempbuf = (char *)(((long)audiobuf & ~0x03) + 0x04);
3081 tempbuf_size = (long)audiobufend - (long)audiobuf - 4;
3082 audiobuf += tempbuf_size;
3083 #endif
3086 static void free_tempbuf(void)
3088 if (tempbuf_size == 0)
3089 return ;
3091 #ifdef __PCTOOL__
3092 free(tempbuf);
3093 #else
3094 audiobuf -= tempbuf_size;
3095 #endif
3096 tempbuf = NULL;
3097 tempbuf_size = 0;
3100 #ifndef __PCTOOL__
3102 static bool modify_numeric_entry(int masterfd, int idx_id, int tag, long data)
3104 struct index_entry idx;
3106 if (!tc_stat.ready)
3107 return false;
3109 if (!TAGCACHE_IS_NUMERIC(tag))
3110 return false;
3112 if (!get_index(masterfd, idx_id, &idx, false))
3113 return false;
3115 idx.tag_seek[tag] = data;
3116 idx.flag |= FLAG_DIRTYNUM;
3118 return write_index(masterfd, idx_id, &idx);
3121 #if 0
3122 bool tagcache_modify_numeric_entry(struct tagcache_search *tcs,
3123 int tag, long data)
3125 struct master_header myhdr;
3127 if (tcs->masterfd < 0)
3129 if ( (tcs->masterfd = open_master_fd(&myhdr, true)) < 0)
3130 return false;
3133 return modify_numeric_entry(tcs->masterfd, tcs->idx_id, tag, data);
3135 #endif
3137 static bool command_queue_is_full(void)
3139 int next;
3141 next = command_queue_widx + 1;
3142 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3143 next = 0;
3145 return (next == command_queue_ridx);
3148 static void command_queue_sync_callback(void *data)
3150 (void)data;
3151 struct master_header myhdr;
3152 int masterfd;
3154 mutex_lock(&command_queue_mutex);
3156 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3157 return;
3159 while (command_queue_ridx != command_queue_widx)
3161 struct tagcache_command_entry *ce = &command_queue[command_queue_ridx];
3163 switch (ce->command)
3165 case CMD_UPDATE_MASTER_HEADER:
3167 close(masterfd);
3168 update_master_header();
3170 /* Re-open the masterfd. */
3171 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3172 return;
3174 break;
3176 case CMD_UPDATE_NUMERIC:
3178 modify_numeric_entry(masterfd, ce->idx_id, ce->tag, ce->data);
3179 break;
3183 if (++command_queue_ridx >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3184 command_queue_ridx = 0;
3187 close(masterfd);
3189 tc_stat.queue_length = 0;
3190 mutex_unlock(&command_queue_mutex);
3193 static void run_command_queue(bool force)
3195 if (COMMAND_QUEUE_IS_EMPTY)
3196 return;
3198 if (force || command_queue_is_full())
3199 command_queue_sync_callback(NULL);
3200 else
3201 register_storage_idle_func(command_queue_sync_callback);
3204 static void queue_command(int cmd, long idx_id, int tag, long data)
3206 while (1)
3208 int next;
3210 mutex_lock(&command_queue_mutex);
3211 next = command_queue_widx + 1;
3212 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3213 next = 0;
3215 /* Make sure queue is not full. */
3216 if (next != command_queue_ridx)
3218 struct tagcache_command_entry *ce = &command_queue[command_queue_widx];
3220 ce->command = cmd;
3221 ce->idx_id = idx_id;
3222 ce->tag = tag;
3223 ce->data = data;
3225 command_queue_widx = next;
3227 tc_stat.queue_length++;
3229 mutex_unlock(&command_queue_mutex);
3230 break;
3233 /* Queue is full, try again later... */
3234 mutex_unlock(&command_queue_mutex);
3235 sleep(1);
3239 long tagcache_increase_serial(void)
3241 long old;
3243 if (!tc_stat.ready)
3244 return -2;
3246 while (read_lock)
3247 sleep(1);
3249 old = current_tcmh.serial++;
3250 queue_command(CMD_UPDATE_MASTER_HEADER, 0, 0, 0);
3252 return old;
3255 void tagcache_update_numeric(int idx_id, int tag, long data)
3257 queue_command(CMD_UPDATE_NUMERIC, idx_id, tag, data);
3259 #endif /* !__PCTOOL__ */
3261 long tagcache_get_serial(void)
3263 return current_tcmh.serial;
3266 long tagcache_get_commitid(void)
3268 return current_tcmh.commitid;
3271 static bool write_tag(int fd, const char *tagstr, const char *datastr)
3273 char buf[512];
3274 int i;
3276 snprintf(buf, sizeof buf, "%s=\"", tagstr);
3277 for (i = strlen(buf); i < (long)sizeof(buf)-4; i++)
3279 if (*datastr == '\0')
3280 break;
3282 if (*datastr == '"' || *datastr == '\\')
3283 buf[i++] = '\\';
3285 buf[i] = *(datastr++);
3288 strcpy(&buf[i], "\" ");
3290 write(fd, buf, i + 2);
3292 return true;
3295 #ifndef __PCTOOL__
3297 static bool read_tag(char *dest, long size,
3298 const char *src, const char *tagstr)
3300 int pos;
3301 char current_tag[32];
3303 while (*src != '\0')
3305 /* Skip all whitespace */
3306 while (*src == ' ')
3307 src++;
3309 if (*src == '\0')
3310 break;
3312 pos = 0;
3313 /* Read in tag name */
3314 while (*src != '=' && *src != ' ')
3316 current_tag[pos] = *src;
3317 src++;
3318 pos++;
3320 if (*src == '\0' || pos >= (long)sizeof(current_tag))
3321 return false;
3323 current_tag[pos] = '\0';
3325 /* Read in tag data */
3327 /* Find the start. */
3328 while (*src != '"' && *src != '\0')
3329 src++;
3331 if (*src == '\0' || *(++src) == '\0')
3332 return false;
3334 /* Read the data. */
3335 for (pos = 0; pos < size; pos++)
3337 if (*src == '\0')
3338 break;
3340 if (*src == '\\')
3342 dest[pos] = *(src+1);
3343 src += 2;
3344 continue;
3347 dest[pos] = *src;
3349 if (*src == '"')
3351 src++;
3352 break;
3355 if (*src == '\0')
3356 break;
3358 src++;
3360 dest[pos] = '\0';
3362 if (!strcasecmp(tagstr, current_tag))
3363 return true;
3366 return false;
3369 static int parse_changelog_line(int line_n, const char *buf, void *parameters)
3371 struct index_entry idx;
3372 char tag_data[TAG_MAXLEN+32];
3373 int idx_id;
3374 long masterfd = (long)parameters;
3375 const int import_tags[] = { tag_playcount, tag_rating, tag_playtime, tag_lastplayed,
3376 tag_commitid };
3377 int i;
3378 (void)line_n;
3380 if (*buf == '#')
3381 return 0;
3383 logf("%d/%s", line_n, buf);
3384 if (!read_tag(tag_data, sizeof tag_data, buf, "filename"))
3386 logf("filename missing");
3387 logf("-> %s", buf);
3388 return 0;
3391 idx_id = find_index(tag_data);
3392 if (idx_id < 0)
3394 logf("entry not found");
3395 return 0;
3398 if (!get_index(masterfd, idx_id, &idx, false))
3400 logf("failed to retrieve index entry");
3401 return 0;
3404 /* Stop if tag has already been modified. */
3405 if (idx.flag & FLAG_DIRTYNUM)
3406 return 0;
3408 logf("import: %s", tag_data);
3410 idx.flag |= FLAG_DIRTYNUM;
3411 for (i = 0; i < (long)(sizeof(import_tags)/sizeof(import_tags[0])); i++)
3413 int data;
3415 if (!read_tag(tag_data, sizeof tag_data, buf,
3416 tagcache_tag_to_str(import_tags[i])))
3418 continue;
3421 data = atoi(tag_data);
3422 if (data < 0)
3423 continue;
3425 idx.tag_seek[import_tags[i]] = data;
3427 if (import_tags[i] == tag_lastplayed && data >= current_tcmh.serial)
3428 current_tcmh.serial = data + 1;
3429 else if (import_tags[i] == tag_commitid && data >= current_tcmh.commitid)
3430 current_tcmh.commitid = data + 1;
3433 return write_index(masterfd, idx_id, &idx) ? 0 : -5;
3436 bool tagcache_import_changelog(void)
3438 struct master_header myhdr;
3439 struct tagcache_header tch;
3440 int clfd;
3441 long masterfd;
3442 char buf[2048];
3444 if (!tc_stat.ready)
3445 return false;
3447 while (read_lock)
3448 sleep(1);
3450 clfd = open(TAGCACHE_FILE_CHANGELOG, O_RDONLY);
3451 if (clfd < 0)
3453 logf("failure to open changelog");
3454 return false;
3457 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3459 close(clfd);
3460 return false;
3463 write_lock++;
3465 filenametag_fd = open_tag_fd(&tch, tag_filename, false);
3467 fast_readline(clfd, buf, sizeof buf, (long *)masterfd,
3468 parse_changelog_line);
3470 close(clfd);
3471 close(masterfd);
3473 if (filenametag_fd >= 0)
3475 close(filenametag_fd);
3476 filenametag_fd = -1;
3479 write_lock--;
3481 update_master_header();
3483 return true;
3486 #endif /* !__PCTOOL__ */
3488 bool tagcache_create_changelog(struct tagcache_search *tcs)
3490 struct master_header myhdr;
3491 struct index_entry idx;
3492 char buf[TAG_MAXLEN+32];
3493 char temp[32];
3494 int clfd;
3495 int i, j;
3497 if (!tc_stat.ready)
3498 return false;
3500 if (!tagcache_search(tcs, tag_filename))
3501 return false;
3503 /* Initialize the changelog */
3504 clfd = open(TAGCACHE_FILE_CHANGELOG, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3505 if (clfd < 0)
3507 logf("failure to open changelog");
3508 return false;
3511 if (tcs->masterfd < 0)
3513 if ( (tcs->masterfd = open_master_fd(&myhdr, false)) < 0)
3514 return false;
3516 else
3518 lseek(tcs->masterfd, 0, SEEK_SET);
3519 ecread(tcs->masterfd, &myhdr, 1, master_header_ec, tc_stat.econ);
3522 write(clfd, "## Changelog version 1\n", 23);
3524 for (i = 0; i < myhdr.tch.entry_count; i++)
3526 if (ecread_index_entry(tcs->masterfd, &idx) != sizeof(struct index_entry))
3528 logf("read error #9");
3529 tagcache_search_finish(tcs);
3530 close(clfd);
3531 return false;
3534 /* Skip until the entry found has been modified. */
3535 if (! (idx.flag & FLAG_DIRTYNUM) )
3536 continue;
3538 /* Skip deleted entries too. */
3539 if (idx.flag & FLAG_DELETED)
3540 continue;
3542 /* Now retrieve all tags. */
3543 for (j = 0; j < TAG_COUNT; j++)
3545 if (TAGCACHE_IS_NUMERIC(j))
3547 snprintf(temp, sizeof temp, "%d", (int)idx.tag_seek[j]);
3548 write_tag(clfd, tagcache_tag_to_str(j), temp);
3549 continue;
3552 tcs->type = j;
3553 tagcache_retrieve(tcs, i, tcs->type, buf, sizeof buf);
3554 write_tag(clfd, tagcache_tag_to_str(j), buf);
3557 write(clfd, "\n", 1);
3558 do_timed_yield();
3561 close(clfd);
3563 tagcache_search_finish(tcs);
3565 return true;
3568 static bool delete_entry(long idx_id)
3570 int fd = -1;
3571 int masterfd = -1;
3572 int tag, i;
3573 struct index_entry idx, myidx;
3574 struct master_header myhdr;
3575 char buf[TAG_MAXLEN+32];
3576 int in_use[TAG_COUNT];
3578 logf("delete_entry(): %ld", idx_id);
3580 #ifdef HAVE_TC_RAMCACHE
3581 /* At first mark the entry removed from ram cache. */
3582 if (tc_stat.ramcache)
3583 hdr->indices[idx_id].flag |= FLAG_DELETED;
3584 #endif
3586 if ( (masterfd = open_master_fd(&myhdr, true) ) < 0)
3587 return false;
3589 lseek(masterfd, idx_id * sizeof(struct index_entry), SEEK_CUR);
3590 if (ecread_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3592 logf("delete_entry(): read error");
3593 goto cleanup;
3596 if (myidx.flag & FLAG_DELETED)
3598 logf("delete_entry(): already deleted!");
3599 goto cleanup;
3602 myidx.flag |= FLAG_DELETED;
3603 lseek(masterfd, -sizeof(struct index_entry), SEEK_CUR);
3604 if (ecwrite_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3606 logf("delete_entry(): write_error #1");
3607 goto cleanup;
3610 /* Now check which tags are no longer in use (if any) */
3611 for (tag = 0; tag < TAG_COUNT; tag++)
3612 in_use[tag] = 0;
3614 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
3615 for (i = 0; i < myhdr.tch.entry_count; i++)
3617 struct index_entry *idxp;
3619 #ifdef HAVE_TC_RAMCACHE
3620 /* Use RAM DB if available for greater speed */
3621 if (tc_stat.ramcache)
3622 idxp = &hdr->indices[i];
3623 else
3624 #endif
3626 if (ecread_index_entry(masterfd, &idx) != sizeof(struct index_entry))
3628 logf("delete_entry(): read error #2");
3629 goto cleanup;
3631 idxp = &idx;
3634 if (idxp->flag & FLAG_DELETED)
3635 continue;
3637 for (tag = 0; tag < TAG_COUNT; tag++)
3639 if (TAGCACHE_IS_NUMERIC(tag))
3640 continue;
3642 if (idxp->tag_seek[tag] == myidx.tag_seek[tag])
3643 in_use[tag]++;
3647 /* Now delete all tags no longer in use. */
3648 for (tag = 0; tag < TAG_COUNT; tag++)
3650 struct tagcache_header tch;
3651 int oldseek = myidx.tag_seek[tag];
3653 if (TAGCACHE_IS_NUMERIC(tag))
3654 continue;
3656 /**
3657 * Replace tag seek with a hash value of the field string data.
3658 * That way runtime statistics of moved or altered files can be
3659 * resurrected.
3661 #ifdef HAVE_TC_RAMCACHE
3662 if (tc_stat.ramcache && tag != tag_filename)
3664 struct tagfile_entry *tfe;
3665 int32_t *seek = &hdr->indices[idx_id].tag_seek[tag];
3667 tfe = (struct tagfile_entry *)&hdr->tags[tag][*seek];
3668 *seek = crc_32(tfe->tag_data, strlen(tfe->tag_data), 0xffffffff);
3669 myidx.tag_seek[tag] = *seek;
3671 else
3672 #endif
3674 struct tagfile_entry tfe;
3676 /* Open the index file, which contains the tag names. */
3677 if ((fd = open_tag_fd(&tch, tag, true)) < 0)
3678 goto cleanup;
3680 /* Skip the header block */
3681 lseek(fd, myidx.tag_seek[tag], SEEK_SET);
3682 if (ecread_tagfile_entry(fd, &tfe) != sizeof(struct tagfile_entry))
3684 logf("delete_entry(): read error #3");
3685 goto cleanup;
3688 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
3690 logf("delete_entry(): read error #4");
3691 goto cleanup;
3694 myidx.tag_seek[tag] = crc_32(buf, strlen(buf), 0xffffffff);
3697 if (in_use[tag])
3699 logf("in use: %d/%d", tag, in_use[tag]);
3700 if (fd >= 0)
3702 close(fd);
3703 fd = -1;
3705 continue;
3708 #ifdef HAVE_TC_RAMCACHE
3709 /* Delete from ram. */
3710 if (tc_stat.ramcache && tag != tag_filename)
3712 struct tagfile_entry *tagentry = (struct tagfile_entry *)&hdr->tags[tag][oldseek];
3713 tagentry->tag_data[0] = '\0';
3715 #endif
3717 /* Open the index file, which contains the tag names. */
3718 if (fd < 0)
3720 if ((fd = open_tag_fd(&tch, tag, true)) < 0)
3721 goto cleanup;
3724 /* Skip the header block */
3725 lseek(fd, oldseek + sizeof(struct tagfile_entry), SEEK_SET);
3727 /* Debug, print 10 first characters of the tag
3728 read(fd, buf, 10);
3729 buf[10]='\0';
3730 logf("TAG:%s", buf);
3731 lseek(fd, -10, SEEK_CUR);
3734 /* Write first data byte in tag as \0 */
3735 write(fd, "", 1);
3737 /* Now tag data has been removed */
3738 close(fd);
3739 fd = -1;
3742 /* Write index entry back into master index. */
3743 lseek(masterfd, sizeof(struct master_header) +
3744 (idx_id * sizeof(struct index_entry)), SEEK_SET);
3745 if (ecwrite_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3747 logf("delete_entry(): write_error #2");
3748 goto cleanup;
3751 close(masterfd);
3753 return true;
3755 cleanup:
3756 if (fd >= 0)
3757 close(fd);
3758 if (masterfd >= 0)
3759 close(masterfd);
3761 return false;
3764 #ifndef __PCTOOL__
3766 * Returns true if there is an event waiting in the queue
3767 * that requires the current operation to be aborted.
3769 static bool check_event_queue(void)
3771 struct queue_event ev;
3773 if(!queue_peek(&tagcache_queue, &ev))
3774 return false;
3776 switch (ev.id)
3778 case Q_STOP_SCAN:
3779 case SYS_POWEROFF:
3780 case SYS_USB_CONNECTED:
3781 return true;
3784 return false;
3786 #endif
3788 #ifdef HAVE_TC_RAMCACHE
3789 static bool allocate_tagcache(void)
3791 struct master_header tcmh;
3792 int fd;
3794 /* Load the header. */
3795 if ( (fd = open_master_fd(&tcmh, false)) < 0)
3797 hdr = NULL;
3798 return false;
3801 close(fd);
3803 /**
3804 * Now calculate the required cache size plus
3805 * some extra space for alignment fixes.
3807 tc_stat.ramcache_allocated = tcmh.tch.datasize + 128 + TAGCACHE_RESERVE +
3808 sizeof(struct ramcache_header) + TAG_COUNT*sizeof(void *);
3809 hdr = buffer_alloc(tc_stat.ramcache_allocated + 128);
3810 memset(hdr, 0, sizeof(struct ramcache_header));
3811 memcpy(&hdr->h, &tcmh, sizeof(struct master_header));
3812 hdr->indices = (struct index_entry *)(hdr + 1);
3813 logf("tagcache: %d bytes allocated.", tc_stat.ramcache_allocated);
3815 return true;
3818 # ifdef HAVE_EEPROM_SETTINGS
3819 static bool tagcache_dumpload(void)
3821 struct statefile_header shdr;
3822 int fd, rc;
3823 long offpos;
3824 int i;
3826 fd = open(TAGCACHE_STATEFILE, O_RDONLY);
3827 if (fd < 0)
3829 logf("no tagcache statedump");
3830 return false;
3833 /* Check the statefile memory placement */
3834 hdr = buffer_alloc(0);
3835 rc = read(fd, &shdr, sizeof(struct statefile_header));
3836 if (rc != sizeof(struct statefile_header)
3837 /* || (long)hdr != (long)shdr.hdr */)
3839 logf("incorrect statefile");
3840 hdr = NULL;
3841 close(fd);
3842 return false;
3845 offpos = (long)hdr - (long)shdr.hdr;
3847 /* Lets allocate real memory and load it */
3848 hdr = buffer_alloc(shdr.tc_stat.ramcache_allocated);
3849 rc = read(fd, hdr, shdr.tc_stat.ramcache_allocated);
3850 close(fd);
3852 if (rc != shdr.tc_stat.ramcache_allocated)
3854 logf("read failure!");
3855 hdr = NULL;
3856 return false;
3859 memcpy(&tc_stat, &shdr.tc_stat, sizeof(struct tagcache_stat));
3861 /* Now fix the pointers */
3862 hdr->indices = (struct index_entry *)((long)hdr->indices + offpos);
3863 for (i = 0; i < TAG_COUNT; i++)
3864 hdr->tags[i] += offpos;
3866 return true;
3869 static bool tagcache_dumpsave(void)
3871 struct statefile_header shdr;
3872 int fd;
3874 if (!tc_stat.ramcache)
3875 return false;
3877 fd = open(TAGCACHE_STATEFILE, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3878 if (fd < 0)
3880 logf("failed to create a statedump");
3881 return false;
3884 /* Create the header */
3885 shdr.hdr = hdr;
3886 memcpy(&shdr.tc_stat, &tc_stat, sizeof(struct tagcache_stat));
3887 write(fd, &shdr, sizeof(struct statefile_header));
3889 /* And dump the data too */
3890 write(fd, hdr, tc_stat.ramcache_allocated);
3891 close(fd);
3893 return true;
3895 # endif
3897 static bool load_tagcache(void)
3899 struct tagcache_header *tch;
3900 long bytesleft = tc_stat.ramcache_allocated;
3901 struct index_entry *idx;
3902 int rc, fd;
3903 char *p;
3904 int i, tag;
3906 # ifdef HAVE_DIRCACHE
3907 while (dircache_is_initializing())
3908 sleep(1);
3910 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE);
3911 # endif
3913 logf("loading tagcache to ram...");
3915 fd = open(TAGCACHE_FILE_MASTER, O_RDONLY);
3916 if (fd < 0)
3918 logf("tagcache open failed");
3919 return false;
3922 if (ecread(fd, &hdr->h, 1, master_header_ec, tc_stat.econ)
3923 != sizeof(struct master_header)
3924 || hdr->h.tch.magic != TAGCACHE_MAGIC)
3926 logf("incorrect header");
3927 return false;
3930 idx = hdr->indices;
3932 /* Load the master index table. */
3933 for (i = 0; i < hdr->h.tch.entry_count; i++)
3935 rc = ecread_index_entry(fd, idx);
3936 if (rc != sizeof(struct index_entry))
3938 logf("read error #10");
3939 close(fd);
3940 return false;
3943 bytesleft -= sizeof(struct index_entry);
3944 if (bytesleft < 0 || ((long)idx - (long)hdr->indices) >= tc_stat.ramcache_allocated)
3946 logf("too big tagcache.");
3947 close(fd);
3948 return false;
3951 idx++;
3954 close(fd);
3956 /* Load the tags. */
3957 p = (char *)idx;
3958 for (tag = 0; tag < TAG_COUNT; tag++)
3960 struct tagfile_entry *fe;
3961 char buf[TAG_MAXLEN+32];
3963 if (TAGCACHE_IS_NUMERIC(tag))
3964 continue ;
3966 //p = ((void *)p+1);
3967 p = (char *)((long)p & ~0x03) + 0x04;
3968 hdr->tags[tag] = p;
3970 /* Check the header. */
3971 tch = (struct tagcache_header *)p;
3972 p += sizeof(struct tagcache_header);
3974 if ( (fd = open_tag_fd(tch, tag, false)) < 0)
3975 return false;
3977 for (hdr->entry_count[tag] = 0;
3978 hdr->entry_count[tag] < tch->entry_count;
3979 hdr->entry_count[tag]++)
3981 long pos;
3983 if (do_timed_yield())
3985 /* Abort if we got a critical event in queue */
3986 if (check_event_queue())
3987 return false;
3990 fe = (struct tagfile_entry *)p;
3991 pos = lseek(fd, 0, SEEK_CUR);
3992 rc = ecread_tagfile_entry(fd, fe);
3993 if (rc != sizeof(struct tagfile_entry))
3995 /* End of lookup table. */
3996 logf("read error #11");
3997 close(fd);
3998 return false;
4001 /* We have a special handling for the filename tags. */
4002 if (tag == tag_filename)
4004 # ifdef HAVE_DIRCACHE
4005 const struct dircache_entry *dc;
4006 # endif
4008 // FIXME: This is wrong!
4009 // idx = &hdr->indices[hdr->entry_count[i]];
4010 idx = &hdr->indices[fe->idx_id];
4012 if (fe->tag_length >= (long)sizeof(buf)-1)
4014 read(fd, buf, 10);
4015 buf[10] = '\0';
4016 logf("TAG:%s", buf);
4017 logf("too long filename");
4018 close(fd);
4019 return false;
4022 rc = read(fd, buf, fe->tag_length);
4023 if (rc != fe->tag_length)
4025 logf("read error #12");
4026 close(fd);
4027 return false;
4030 /* Check if the entry has already been removed */
4031 if (idx->flag & FLAG_DELETED)
4032 continue;
4034 /* This flag must not be used yet. */
4035 if (idx->flag & FLAG_DIRCACHE)
4037 logf("internal error!");
4038 close(fd);
4039 return false;
4042 if (idx->tag_seek[tag] != pos)
4044 logf("corrupt data structures!");
4045 close(fd);
4046 return false;
4049 # ifdef HAVE_DIRCACHE
4050 if (dircache_is_enabled())
4052 dc = dircache_get_entry_ptr(buf);
4053 if (dc == NULL)
4055 logf("Entry no longer valid.");
4056 logf("-> %s", buf);
4057 if (global_settings.tagcache_autoupdate)
4058 delete_entry(fe->idx_id);
4059 continue ;
4062 idx->flag |= FLAG_DIRCACHE;
4063 idx->tag_seek[tag_filename] = (long)dc;
4065 else
4066 # endif
4068 /* This will be very slow unless dircache is enabled
4069 or target is flash based, but do it anyway for
4070 consistency. */
4071 /* Check if entry has been removed. */
4072 if (global_settings.tagcache_autoupdate)
4074 if (!file_exists(buf))
4076 logf("Entry no longer valid.");
4077 logf("-> %s", buf);
4078 delete_entry(fe->idx_id);
4079 continue;
4084 continue ;
4087 bytesleft -= sizeof(struct tagfile_entry) + fe->tag_length;
4088 if (bytesleft < 0)
4090 logf("too big tagcache #2");
4091 logf("tl: %ld", fe->tag_length);
4092 logf("bl: %ld", bytesleft);
4093 close(fd);
4094 return false;
4097 p = fe->tag_data;
4098 rc = read(fd, fe->tag_data, fe->tag_length);
4099 p += rc;
4101 if (rc != fe->tag_length)
4103 logf("read error #13");
4104 logf("rc=0x%04x", rc); // 0x431
4105 logf("len=0x%04lx", fe->tag_length); // 0x4000
4106 logf("pos=0x%04lx", lseek(fd, 0, SEEK_CUR)); // 0x433
4107 logf("tag=0x%02x", tag); // 0x00
4108 close(fd);
4109 return false;
4112 close(fd);
4115 tc_stat.ramcache_used = tc_stat.ramcache_allocated - bytesleft;
4116 logf("tagcache loaded into ram!");
4118 return true;
4120 #endif /* HAVE_TC_RAMCACHE */
4122 static bool check_deleted_files(void)
4124 int fd;
4125 char buf[TAG_MAXLEN+32];
4126 struct tagfile_entry tfe;
4128 logf("reverse scan...");
4129 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag_filename);
4130 fd = open(buf, O_RDONLY);
4132 if (fd < 0)
4134 logf("%s open fail", buf);
4135 return false;
4138 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
4139 while (ecread_tagfile_entry(fd, &tfe) == sizeof(struct tagfile_entry)
4140 #ifndef __PCTOOL__
4141 && !check_event_queue()
4142 #endif
4145 if (tfe.tag_length >= (long)sizeof(buf)-1)
4147 logf("too long tag");
4148 close(fd);
4149 return false;
4152 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
4154 logf("read error #14");
4155 close(fd);
4156 return false;
4159 /* Check if the file has already deleted from the db. */
4160 if (*buf == '\0')
4161 continue;
4163 /* Now check if the file exists. */
4164 if (!file_exists(buf))
4166 logf("Entry no longer valid.");
4167 logf("-> %s / %ld", buf, tfe.tag_length);
4168 delete_entry(tfe.idx_id);
4172 close(fd);
4174 logf("done");
4176 return true;
4180 /* Note that this function must not be inlined, otherwise the whole point
4181 * of having the code in a separate function is lost.
4183 static void __attribute__ ((noinline)) check_ignore(const char *dirname,
4184 int *ignore, int *unignore)
4186 char newpath[MAX_PATH];
4188 /* check for a database.ignore file */
4189 snprintf(newpath, MAX_PATH, "%s/database.ignore", dirname);
4190 *ignore = file_exists(newpath);
4191 /* check for a database.unignore file */
4192 snprintf(newpath, MAX_PATH, "%s/database.unignore", dirname);
4193 *unignore = file_exists(newpath);
4196 static struct search_roots_ll {
4197 const char *path;
4198 struct search_roots_ll * next;
4199 } roots_ll;
4201 #ifdef APPLICATION
4203 * This adds a path to the search roots, possibly during traveling through
4204 * the filesystem. It only adds if the path is not inside an already existing
4205 * search root.
4207 * Returns true if it added the path to the search roots
4209 * Windows 2000 and greater supports symlinks, but they don't provide
4210 * realpath() or readlink(), and symlinks are rarely used on them so
4211 * ignore this for windows for now
4213 static bool add_search_root(const char *name)
4215 (void)name;
4216 #ifndef WIN32
4217 struct search_roots_ll *this, *prev = NULL;
4218 char target[MAX_PATH];
4219 char _abs_target[MAX_PATH];
4220 char * abs_target;
4221 ssize_t len;
4223 len = readlink(name, target, sizeof(target));
4224 if (len < 0)
4225 return false;
4227 target[len] = '\0';
4228 /* realpath(target, NULL) doesn't work on android ... */
4229 abs_target = realpath(target, _abs_target);
4230 if (abs_target == NULL)
4231 return false;
4233 for(this = &roots_ll; this; prev = this, this = this->next)
4235 size_t root_len = strlen(this->path);
4236 /* check if the link target is inside of an existing search root
4237 * don't add if target is inside, we'll scan it later */
4238 if (!strncmp(this->path, abs_target, root_len))
4239 return false;
4242 if (prev)
4244 size_t len = strlen(abs_target) + 1; /* count \0 */
4245 this = malloc(sizeof(struct search_roots_ll) + len );
4246 if (!this || len > MAX_PATH)
4248 logf("Error at adding a search root: %s", this ? "path too long":"OOM");
4249 free(this);
4250 prev->next = NULL;
4252 this->path = ((char*)this) + sizeof(struct search_roots_ll);
4253 strcpy((char*)this->path, abs_target); /* ok to cast const away here */
4254 this->next = NULL;
4255 prev->next = this;
4256 logf("Added %s to the search roots\n", abs_target);
4257 return true;
4259 #endif
4260 return false;
4263 static int free_search_roots(struct search_roots_ll * start)
4265 int ret = 0;
4266 if (start->next)
4268 ret += free_search_roots(start->next);
4269 ret += sizeof(struct search_roots_ll);
4270 free(start->next);
4272 return ret;
4274 #else /* native, simulator */
4275 #define add_search_root(a) do {} while(0)
4276 #define free_search_roots(a) do {} while(0)
4277 #endif
4279 static bool check_dir(const char *dirname, int add_files)
4281 DIR *dir;
4282 int len;
4283 int success = false;
4284 int ignore, unignore;
4286 dir = opendir(dirname);
4287 if (!dir)
4289 logf("tagcache: opendir(%s) failed", dirname);
4290 return false;
4292 /* check for a database.ignore and database.unignore */
4293 check_ignore(dirname, &ignore, &unignore);
4295 /* don't do anything if both ignore and unignore are there */
4296 if (ignore != unignore)
4297 add_files = unignore;
4299 /* Recursively scan the dir. */
4300 #ifdef __PCTOOL__
4301 while (1)
4302 #else
4303 while (!check_event_queue())
4304 #endif
4306 struct dirent *entry = readdir(dir);
4307 if (entry == NULL)
4309 success = true;
4310 break;
4313 if (!strcmp((char *)entry->d_name, ".") ||
4314 !strcmp((char *)entry->d_name, ".."))
4315 continue;
4317 struct dirinfo info = dir_get_info(dir, entry);
4319 yield();
4321 len = strlen(curpath);
4322 /* don't add an extra / for curpath == / */
4323 if (len <= 1) len = 0;
4324 snprintf(&curpath[len], sizeof(curpath) - len, "/%s", entry->d_name);
4326 processed_dir_count++;
4327 if (info.attribute & ATTR_DIRECTORY)
4328 { /* don't follow symlinks to dirs, but try to add it as a search root
4329 * this makes able to avoid looping in recursive symlinks */
4330 if (info.attribute & ATTR_LINK)
4331 add_search_root(curpath);
4332 else
4333 check_dir(curpath, add_files);
4335 else if (add_files)
4337 tc_stat.curentry = curpath;
4339 /* Add a new entry to the temporary db file. */
4340 add_tagcache(curpath, (info.wrtdate << 16) | info.wrttime
4341 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4342 , dir->internal_entry
4343 #endif
4346 /* Wait until current path for debug screen is read and unset. */
4347 while (tc_stat.syncscreen && tc_stat.curentry != NULL)
4348 yield();
4350 tc_stat.curentry = NULL;
4353 curpath[len] = '\0';
4356 closedir(dir);
4358 return success;
4361 void tagcache_screensync_event(void)
4363 tc_stat.curentry = NULL;
4366 void tagcache_screensync_enable(bool state)
4368 tc_stat.syncscreen = state;
4371 void tagcache_build(const char *path)
4373 struct tagcache_header header;
4374 bool ret;
4376 curpath[0] = '\0';
4377 data_size = 0;
4378 total_entry_count = 0;
4379 processed_dir_count = 0;
4381 #ifdef HAVE_DIRCACHE
4382 while (dircache_is_initializing())
4383 sleep(1);
4384 #endif
4386 logf("updating tagcache");
4388 cachefd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
4389 if (cachefd >= 0)
4391 logf("skipping, cache already waiting for commit");
4392 close(cachefd);
4393 return ;
4396 cachefd = open(TAGCACHE_FILE_TEMP, O_RDWR | O_CREAT | O_TRUNC, 0666);
4397 if (cachefd < 0)
4399 logf("master file open failed: %s", TAGCACHE_FILE_TEMP);
4400 return ;
4403 filenametag_fd = open_tag_fd(&header, tag_filename, false);
4405 cpu_boost(true);
4407 logf("Scanning files...");
4408 /* Scan for new files. */
4409 memset(&header, 0, sizeof(struct tagcache_header));
4410 write(cachefd, &header, sizeof(struct tagcache_header));
4412 ret = true;
4413 roots_ll.path = path;
4414 roots_ll.next = NULL;
4415 struct search_roots_ll * this;
4416 /* check_dir might add new roots */
4417 for(this = &roots_ll; this; this = this->next)
4419 strcpy(curpath, this->path);
4420 ret = ret && check_dir(this->path, true);
4422 if (roots_ll.next)
4423 free_search_roots(roots_ll.next);
4425 /* Write the header. */
4426 header.magic = TAGCACHE_MAGIC;
4427 header.datasize = data_size;
4428 header.entry_count = total_entry_count;
4429 lseek(cachefd, 0, SEEK_SET);
4430 write(cachefd, &header, sizeof(struct tagcache_header));
4431 close(cachefd);
4433 if (filenametag_fd >= 0)
4435 close(filenametag_fd);
4436 filenametag_fd = -1;
4439 if (!ret)
4441 logf("Aborted.");
4442 cpu_boost(false);
4443 return ;
4446 /* Commit changes to the database. */
4447 #ifdef __PCTOOL__
4448 allocate_tempbuf();
4449 #endif
4450 if (commit())
4452 remove(TAGCACHE_FILE_TEMP);
4453 logf("tagcache built!");
4455 #ifdef __PCTOOL__
4456 free_tempbuf();
4457 #endif
4459 #ifdef HAVE_TC_RAMCACHE
4460 if (hdr)
4462 /* Import runtime statistics if we just initialized the db. */
4463 if (hdr->h.serial == 0)
4464 queue_post(&tagcache_queue, Q_IMPORT_CHANGELOG, 0);
4466 #endif
4468 cpu_boost(false);
4471 #ifdef HAVE_TC_RAMCACHE
4472 static void load_ramcache(void)
4474 if (!hdr)
4475 return ;
4477 cpu_boost(true);
4479 /* At first we should load the cache (if exists). */
4480 tc_stat.ramcache = load_tagcache();
4482 if (!tc_stat.ramcache)
4484 /* If loading failed, it must indicate some problem with the db
4485 * so disable it entirely to prevent further issues. */
4486 tc_stat.ready = false;
4487 hdr = NULL;
4490 cpu_boost(false);
4493 void tagcache_unload_ramcache(void)
4495 tc_stat.ramcache = false;
4496 /* Just to make sure there is no statefile present. */
4497 // remove(TAGCACHE_STATEFILE);
4499 #endif
4501 #ifndef __PCTOOL__
4502 static void tagcache_thread(void)
4504 struct queue_event ev;
4505 bool check_done = false;
4507 /* If the previous cache build/update was interrupted, commit
4508 * the changes first in foreground. */
4509 cpu_boost(true);
4510 allocate_tempbuf();
4511 commit();
4512 free_tempbuf();
4514 #ifdef HAVE_TC_RAMCACHE
4515 # ifdef HAVE_EEPROM_SETTINGS
4516 if (firmware_settings.initialized && firmware_settings.disk_clean
4517 && global_settings.tagcache_ram)
4519 check_done = tagcache_dumpload();
4522 remove(TAGCACHE_STATEFILE);
4523 # endif
4525 /* Allocate space for the tagcache if found on disk. */
4526 if (global_settings.tagcache_ram && !tc_stat.ramcache)
4527 allocate_tagcache();
4528 #endif
4530 cpu_boost(false);
4531 tc_stat.initialized = true;
4533 /* Don't delay bootup with the header check but do it on background. */
4534 if (!tc_stat.ready)
4536 sleep(HZ);
4537 tc_stat.ready = check_all_headers();
4538 tc_stat.readyvalid = true;
4541 while (1)
4543 run_command_queue(false);
4545 queue_wait_w_tmo(&tagcache_queue, &ev, HZ);
4547 switch (ev.id)
4549 case Q_IMPORT_CHANGELOG:
4550 tagcache_import_changelog();
4551 break;
4553 case Q_REBUILD:
4554 remove_files();
4555 remove(TAGCACHE_FILE_TEMP);
4556 tagcache_build("/");
4557 break;
4559 case Q_UPDATE:
4560 tagcache_build("/");
4561 #ifdef HAVE_TC_RAMCACHE
4562 load_ramcache();
4563 #endif
4564 check_deleted_files();
4565 break ;
4567 case Q_START_SCAN:
4568 check_done = false;
4569 case SYS_TIMEOUT:
4570 if (check_done || !tc_stat.ready)
4571 break ;
4573 #ifdef HAVE_TC_RAMCACHE
4574 if (!tc_stat.ramcache && global_settings.tagcache_ram)
4576 load_ramcache();
4577 if (tc_stat.ramcache && global_settings.tagcache_autoupdate)
4578 tagcache_build("/");
4580 else
4581 #endif
4582 if (global_settings.tagcache_autoupdate)
4584 tagcache_build("/");
4586 /* This will be very slow unless dircache is enabled
4587 or target is flash based, but do it anyway for
4588 consistency. */
4589 check_deleted_files();
4592 logf("tagcache check done");
4594 check_done = true;
4595 break ;
4597 case Q_STOP_SCAN:
4598 break ;
4600 case SYS_POWEROFF:
4601 break ;
4603 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4604 case SYS_USB_CONNECTED:
4605 logf("USB: TagCache");
4606 usb_acknowledge(SYS_USB_CONNECTED_ACK);
4607 usb_wait_for_disconnect(&tagcache_queue);
4608 break ;
4609 #endif
4614 bool tagcache_prepare_shutdown(void)
4616 if (tagcache_get_commit_step() > 0)
4617 return false;
4619 tagcache_stop_scan();
4620 while (read_lock || write_lock)
4621 sleep(1);
4623 return true;
4626 void tagcache_shutdown(void)
4628 /* Flush the command queue. */
4629 run_command_queue(true);
4631 #ifdef HAVE_EEPROM_SETTINGS
4632 if (tc_stat.ramcache)
4633 tagcache_dumpsave();
4634 #endif
4637 static int get_progress(void)
4639 int total_count = -1;
4641 #ifdef HAVE_DIRCACHE
4642 if (dircache_is_enabled())
4644 total_count = dircache_get_entry_count();
4646 else
4647 #endif
4648 #ifdef HAVE_TC_RAMCACHE
4650 if (hdr && tc_stat.ramcache)
4651 total_count = hdr->h.tch.entry_count;
4653 #endif
4655 if (total_count < 0)
4656 return -1;
4658 return processed_dir_count * 100 / total_count;
4661 struct tagcache_stat* tagcache_get_stat(void)
4663 tc_stat.progress = get_progress();
4664 tc_stat.processed_entries = processed_dir_count;
4666 return &tc_stat;
4669 void tagcache_start_scan(void)
4671 queue_post(&tagcache_queue, Q_START_SCAN, 0);
4674 bool tagcache_update(void)
4676 if (!tc_stat.ready)
4677 return false;
4679 queue_post(&tagcache_queue, Q_UPDATE, 0);
4680 return false;
4683 bool tagcache_rebuild()
4685 queue_post(&tagcache_queue, Q_REBUILD, 0);
4686 return false;
4689 void tagcache_stop_scan(void)
4691 queue_post(&tagcache_queue, Q_STOP_SCAN, 0);
4694 #ifdef HAVE_TC_RAMCACHE
4695 bool tagcache_is_ramcache(void)
4697 return tc_stat.ramcache;
4699 #endif
4701 #endif /* !__PCTOOL__ */
4704 void tagcache_init(void)
4706 memset(&tc_stat, 0, sizeof(struct tagcache_stat));
4707 memset(&current_tcmh, 0, sizeof(struct master_header));
4708 filenametag_fd = -1;
4709 write_lock = read_lock = 0;
4711 #ifndef __PCTOOL__
4712 mutex_init(&command_queue_mutex);
4713 queue_init(&tagcache_queue, true);
4714 create_thread(tagcache_thread, tagcache_stack,
4715 sizeof(tagcache_stack), 0, tagcache_thread_name
4716 IF_PRIO(, PRIORITY_BACKGROUND)
4717 IF_COP(, CPU));
4718 #else
4719 tc_stat.initialized = true;
4720 allocate_tempbuf();
4721 commit();
4722 free_tempbuf();
4723 tc_stat.ready = check_all_headers();
4724 #endif
4727 #ifdef __PCTOOL__
4728 void tagcache_reverse_scan(void)
4730 logf("Checking for deleted files");
4731 check_deleted_files();
4733 #endif
4735 bool tagcache_is_initialized(void)
4737 return tc_stat.initialized;
4739 bool tagcache_is_usable(void)
4741 return tc_stat.initialized && tc_stat.ready;
4743 int tagcache_get_commit_step(void)
4745 return tc_stat.commit_step;
4747 int tagcache_get_max_commit_step(void)
4749 return (int)(SORTED_TAGS_COUNT)+1;