Fix silly mistake
[maemo-rb.git] / apps / tagcache.c
blob8d522b15366ee710058277b8db9628a4af1c5c2b
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
23 * TagCache API
25 * ----------x---------x------------------x-----
26 * | | | External
27 * +---------------x-------+ | TagCache | Libraries
28 * | Modification routines | | Core |
29 * +-x---------x-----------+ | |
30 * | (R/W) | | | |
31 * | +------x-------------x-+ +-------------x-----+ |
32 * | | x==x Filters & clauses | |
33 * | | Search routines | +-------------------+ |
34 * | | x============================x DirCache
35 * | +-x--------------------+ | (optional)
36 * | | (R) |
37 * | | +-------------------------------+ +---------+ |
38 * | | | DB Commit (sort,unique,index) | | | |
39 * | | +-x--------------------------x--+ | Control | |
40 * | | | (R/W) | (R) | Thread | |
41 * | | | +----------------------+ | | | |
42 * | | | | TagCache DB Builder | | +---------+ |
43 * | | | +-x-------------x------+ | |
44 * | | | | (R) | (W) | |
45 * | | | | +--x--------x---------+ |
46 * | | | | | Temporary Commit DB | |
47 * | | | | +---------------------+ |
48 * +-x----x-------x--+ |
49 * | TagCache RAM DB x==\(W) +-----------------+ |
50 * +-----------------+ \===x | |
51 * | | | | (R) | Ram DB Loader x============x DirCache
52 * +-x----x---x---x---+ /==x | | (optional)
53 * | Tagcache Disk DB x==/ +-----------------+ |
54 * +------------------+ |
58 /*#define LOGF_ENABLE*/
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <ctype.h>
63 #ifdef APPLICATION
64 #include <unistd.h> /* readlink() */
65 #include <limits.h> /* PATH_MAX */
66 #endif
67 #include "config.h"
68 #include "ata_idle_notify.h"
69 #include "thread.h"
70 #include "kernel.h"
71 #include "system.h"
72 #include "logf.h"
73 #include "string-extra.h"
74 #include "usb.h"
75 #include "metadata.h"
76 #include "tagcache.h"
77 #include "core_alloc.h"
78 #include "crc32.h"
79 #include "misc.h"
80 #include "settings.h"
81 #include "dir.h"
82 #include "filefuncs.h"
83 #include "structec.h"
84 #include "debug.h"
86 #ifndef __PCTOOL__
87 #include "lang.h"
88 #include "eeprom_settings.h"
89 #endif
91 #ifdef __PCTOOL__
92 #define yield() do { } while(0)
93 #define sim_sleep(timeout) do { } while(0)
94 #define do_timed_yield() do { } while(0)
95 #endif
97 #ifndef __PCTOOL__
98 /* Tag Cache thread. */
99 static struct event_queue tagcache_queue SHAREDBSS_ATTR;
100 static long tagcache_stack[(DEFAULT_STACK_SIZE + 0x4000)/sizeof(long)];
101 static const char tagcache_thread_name[] = "tagcache";
102 #endif
104 /* Previous path when scanning directory tree recursively. */
105 static char curpath[TAG_MAXLEN+32];
107 /* Used when removing duplicates. */
108 static char *tempbuf; /* Allocated when needed. */
109 static long tempbufidx; /* Current location in buffer. */
110 static size_t tempbuf_size; /* Buffer size (TEMPBUF_SIZE). */
111 static long tempbuf_left; /* Buffer space left. */
112 static long tempbuf_pos;
114 #define SORTED_TAGS_COUNT 8
115 #define TAGCACHE_IS_UNIQUE(tag) (BIT_N(tag) & TAGCACHE_UNIQUE_TAGS)
116 #define TAGCACHE_IS_SORTED(tag) (BIT_N(tag) & TAGCACHE_SORTED_TAGS)
117 #define TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag) \
118 (BIT_N(tag) & (TAGCACHE_NUMERIC_TAGS | ~TAGCACHE_UNIQUE_TAGS))
119 /* Tags we want to get sorted (loaded to the tempbuf). */
120 #define TAGCACHE_SORTED_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
121 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
122 (1LU << tag_albumartist) | (1LU << tag_grouping) | (1LU << tag_title))
124 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
125 #define TAGCACHE_UNIQUE_TAGS ((1LU << tag_artist) | (1LU << tag_album) | \
126 (1LU << tag_genre) | (1LU << tag_composer) | (1LU << tag_comment) | \
127 (1LU << tag_albumartist) | (1LU << tag_grouping))
129 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
130 static const char *tags_str[] = { "artist", "album", "genre", "title",
131 "filename", "composer", "comment", "albumartist", "grouping", "year",
132 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
133 "playtime", "lastplayed", "commitid", "mtime", "lastoffset" };
135 /* Status information of the tagcache. */
136 static struct tagcache_stat tc_stat;
138 /* Queue commands. */
139 enum tagcache_queue {
140 Q_STOP_SCAN = 0,
141 Q_START_SCAN,
142 Q_IMPORT_CHANGELOG,
143 Q_UPDATE,
144 Q_REBUILD,
146 /* Internal tagcache command queue. */
147 CMD_UPDATE_MASTER_HEADER,
148 CMD_UPDATE_NUMERIC,
151 struct tagcache_command_entry {
152 int32_t command;
153 int32_t idx_id;
154 int32_t tag;
155 int32_t data;
158 #ifndef __PCTOOL__
159 static struct tagcache_command_entry command_queue[TAGCACHE_COMMAND_QUEUE_LENGTH];
160 static volatile int command_queue_widx = 0;
161 static volatile int command_queue_ridx = 0;
162 static struct mutex command_queue_mutex SHAREDBSS_ATTR;
163 #endif
165 /* Tag database structures. */
167 /* Variable-length tag entry in tag files. */
168 struct tagfile_entry {
169 int32_t tag_length; /* Length of the data in bytes including '\0' */
170 int32_t idx_id; /* Corresponding entry location in index file of not unique tags */
171 char tag_data[0]; /* Begin of the tag data */
174 /* Fixed-size tag entry in master db index. */
175 struct index_entry {
176 int32_t tag_seek[TAG_COUNT]; /* Location of tag data or numeric tag data */
177 int32_t flag; /* Status flags */
180 /* Header is the same in every file. */
181 struct tagcache_header {
182 int32_t magic; /* Header version number */
183 int32_t datasize; /* Data size in bytes */
184 int32_t entry_count; /* Number of entries in this file */
187 struct master_header {
188 struct tagcache_header tch;
189 int32_t serial; /* Increasing counting number */
190 int32_t commitid; /* Number of commits so far */
191 int32_t dirty;
194 /* For the endianess correction */
195 static const char *tagfile_entry_ec = "ll";
197 Note: This should be (1 + TAG_COUNT) amount of l's.
199 static const char *index_entry_ec = "llllllllllllllllllllll";
201 static const char *tagcache_header_ec = "lll";
202 static const char *master_header_ec = "llllll";
204 static struct master_header current_tcmh;
206 #ifdef HAVE_TC_RAMCACHE
207 /* Header is created when loading database to ram. */
208 struct ramcache_header {
209 char *tags[TAG_COUNT]; /* Tag file content (not including filename tag) */
210 int entry_count[TAG_COUNT]; /* Number of entries in the indices. */
211 struct index_entry indices[0]; /* Master index file content */
214 # ifdef HAVE_EEPROM_SETTINGS
215 struct statefile_header {
216 int32_t magic; /* Statefile version number */
217 struct master_header mh; /* Header from the master index */
218 struct ramcache_header *hdr; /* Old load address of hdr for relocation */
219 struct tagcache_stat tc_stat;
221 # endif
223 /* Pointer to allocated ramcache_header */
224 static struct ramcache_header *ramcache_hdr;
225 /* lock entity to temporarily prevent ramcache_hdr from moving */
226 static int move_lock;
227 #endif
229 /**
230 * Full tag entries stored in a temporary file waiting
231 * for commit to the cache. */
232 struct temp_file_entry {
233 long tag_offset[TAG_COUNT];
234 short tag_length[TAG_COUNT];
235 long flag;
237 long data_length;
240 struct tempbuf_id_list {
241 long id;
242 struct tempbuf_id_list *next;
245 struct tempbuf_searchidx {
246 long idx_id;
247 char *str;
248 int seek;
249 struct tempbuf_id_list idlist;
252 /* Lookup buffer for fixing messed up index while after sorting. */
253 static long commit_entry_count;
254 static long lookup_buffer_depth;
255 static struct tempbuf_searchidx **lookup;
257 /* Used when building the temporary file. */
258 static int cachefd = -1, filenametag_fd;
259 static int total_entry_count = 0;
260 static int data_size = 0;
261 static int processed_dir_count;
263 /* Thread safe locking */
264 static volatile int write_lock;
265 static volatile int read_lock;
267 static bool delete_entry(long idx_id);
269 const char* tagcache_tag_to_str(int tag)
271 return tags_str[tag];
274 /* Helper functions for the two most read/write data structure: tagfile_entry and index_entry */
275 static ssize_t ecread_tagfile_entry(int fd, struct tagfile_entry *buf)
277 return ecread(fd, buf, 1, tagfile_entry_ec, tc_stat.econ);
280 static ssize_t ecread_index_entry(int fd, struct index_entry *buf)
282 return ecread(fd, buf, 1, index_entry_ec, tc_stat.econ);
285 static ssize_t ecwrite_index_entry(int fd, struct index_entry *buf)
287 return ecwrite(fd, buf, 1, index_entry_ec, tc_stat.econ);
290 #ifdef HAVE_DIRCACHE
292 * Returns true if specified flag is still present, i.e., dircache
293 * has not been reloaded.
295 static bool is_dircache_intact(void)
297 return dircache_get_appflag(DIRCACHE_APPFLAG_TAGCACHE);
299 #endif
301 static int open_tag_fd(struct tagcache_header *hdr, int tag, bool write)
303 int fd;
304 char buf[MAX_PATH];
305 int rc;
307 if (TAGCACHE_IS_NUMERIC(tag) || tag < 0 || tag >= TAG_COUNT)
308 return -1;
310 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag);
312 fd = open(buf, write ? O_RDWR : O_RDONLY);
313 if (fd < 0)
315 logf("tag file open failed: tag=%d write=%d file=%s", tag, write, buf);
316 tc_stat.ready = false;
317 return fd;
320 /* Check the header. */
321 rc = ecread(fd, hdr, 1, tagcache_header_ec, tc_stat.econ);
322 if (hdr->magic != TAGCACHE_MAGIC || rc != sizeof(struct tagcache_header))
324 logf("header error");
325 tc_stat.ready = false;
326 close(fd);
327 return -2;
330 return fd;
333 static int open_master_fd(struct master_header *hdr, bool write)
335 int fd;
336 int rc;
338 fd = open(TAGCACHE_FILE_MASTER, write ? O_RDWR : O_RDONLY);
339 if (fd < 0)
341 logf("master file open failed for R/W");
342 tc_stat.ready = false;
343 return fd;
346 tc_stat.econ = false;
348 /* Check the header. */
349 rc = read(fd, hdr, sizeof(struct master_header));
350 if (hdr->tch.magic == TAGCACHE_MAGIC && rc == sizeof(struct master_header))
352 /* Success. */
353 return fd;
356 /* Trying to read again, this time with endianess correction enabled. */
357 lseek(fd, 0, SEEK_SET);
359 rc = ecread(fd, hdr, 1, master_header_ec, true);
360 if (hdr->tch.magic != TAGCACHE_MAGIC || rc != sizeof(struct master_header))
362 logf("header error");
363 tc_stat.ready = false;
364 close(fd);
365 return -2;
368 tc_stat.econ = true;
370 return fd;
373 #ifndef __PCTOOL__
374 static bool do_timed_yield(void)
376 /* Sorting can lock up for quite a while, so yield occasionally */
377 static long wakeup_tick = 0;
378 if (TIME_AFTER(current_tick, wakeup_tick))
380 wakeup_tick = current_tick + (HZ/4);
381 yield();
382 return true;
384 return false;
386 #endif
388 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
389 /* find the ramcache entry corresponding to the file indicated by
390 * filename and dc (it's corresponding dircache id). */
391 static long find_entry_ram(const char *filename, int dc)
393 static long last_pos = 0;
394 int i;
396 /* Check if tagcache is loaded into ram. */
397 if (!tc_stat.ramcache || !is_dircache_intact())
398 return -1;
400 if (dc < 0)
401 dc = dircache_get_entry_id(filename);
403 if (dc < 0)
405 logf("tagcache: file not found.");
406 return -1;
409 try_again:
411 if (last_pos > 0)
412 i = last_pos;
413 else
414 i = 0;
416 for (; i < current_tcmh.tch.entry_count; i++)
418 if (ramcache_hdr->indices[i].tag_seek[tag_filename] == dc)
420 last_pos = MAX(0, i - 3);
421 return i;
424 do_timed_yield();
427 if (last_pos > 0)
429 last_pos = 0;
430 goto try_again;
433 return -1;
435 #endif
437 static long find_entry_disk(const char *filename_raw, bool localfd)
439 struct tagcache_header tch;
440 static long last_pos = -1;
441 long pos_history[POS_HISTORY_COUNT];
442 long pos_history_idx = 0;
443 bool found = false;
444 struct tagfile_entry tfe;
445 int fd;
446 char buf[TAG_MAXLEN+32];
447 int i;
448 int pos = -1;
450 const char *filename = filename_raw;
451 #ifdef APPLICATION
452 char pathbuf[PATH_MAX]; /* Note: Don't use MAX_PATH here, it's too small */
453 if (realpath(filename, pathbuf) == pathbuf)
454 filename = pathbuf;
455 #endif
457 if (!tc_stat.ready)
458 return -2;
460 fd = filenametag_fd;
461 if (fd < 0 || localfd)
463 last_pos = -1;
464 if ( (fd = open_tag_fd(&tch, tag_filename, false)) < 0)
465 return -1;
468 check_again:
470 if (last_pos > 0)
471 lseek(fd, last_pos, SEEK_SET);
472 else
473 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
475 while (true)
477 pos = lseek(fd, 0, SEEK_CUR);
478 for (i = pos_history_idx-1; i >= 0; i--)
479 pos_history[i+1] = pos_history[i];
480 pos_history[0] = pos;
482 if (ecread_tagfile_entry(fd, &tfe)
483 != sizeof(struct tagfile_entry))
485 break ;
488 if (tfe.tag_length >= (long)sizeof(buf))
490 logf("too long tag #1");
491 close(fd);
492 if (!localfd)
493 filenametag_fd = -1;
494 last_pos = -1;
495 return -2;
498 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
500 logf("read error #2");
501 close(fd);
502 if (!localfd)
503 filenametag_fd = -1;
504 last_pos = -1;
505 return -3;
508 if (!strcmp(filename, buf))
510 last_pos = pos_history[pos_history_idx];
511 found = true;
512 break ;
515 if (pos_history_idx < POS_HISTORY_COUNT - 1)
516 pos_history_idx++;
519 /* Not found? */
520 if (!found)
522 if (last_pos > 0)
524 last_pos = -1;
525 logf("seek again");
526 goto check_again;
529 if (fd != filenametag_fd || localfd)
530 close(fd);
531 return -4;
534 if (fd != filenametag_fd || localfd)
535 close(fd);
537 return tfe.idx_id;
540 static int find_index(const char *filename)
542 long idx_id = -1;
544 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
545 idx_id = find_entry_ram(filename, -1);
546 #endif
548 if (idx_id < 0)
549 idx_id = find_entry_disk(filename, true);
551 return idx_id;
554 bool tagcache_find_index(struct tagcache_search *tcs, const char *filename)
556 int idx_id;
558 if (!tc_stat.ready)
559 return false;
561 idx_id = find_index(filename);
562 if (idx_id < 0)
563 return false;
565 if (!tagcache_search(tcs, tag_filename))
566 return false;
568 tcs->entry_count = 0;
569 tcs->idx_id = idx_id;
571 return true;
574 static bool get_index(int masterfd, int idxid,
575 struct index_entry *idx, bool use_ram)
577 bool localfd = false;
579 if (idxid < 0)
581 logf("Incorrect idxid: %d", idxid);
582 return false;
585 #ifdef HAVE_TC_RAMCACHE
586 if (tc_stat.ramcache && use_ram)
588 if (ramcache_hdr->indices[idxid].flag & FLAG_DELETED)
589 return false;
591 # ifdef HAVE_DIRCACHE
592 if (!(ramcache_hdr->indices[idxid].flag & FLAG_DIRCACHE)
593 || is_dircache_intact())
594 #endif
596 memcpy(idx, &ramcache_hdr->indices[idxid], sizeof(struct index_entry));
597 return true;
600 #else
601 (void)use_ram;
602 #endif
604 if (masterfd < 0)
606 struct master_header tcmh;
608 localfd = true;
609 masterfd = open_master_fd(&tcmh, false);
610 if (masterfd < 0)
611 return false;
614 lseek(masterfd, idxid * sizeof(struct index_entry)
615 + sizeof(struct master_header), SEEK_SET);
616 if (ecread_index_entry(masterfd, idx)
617 != sizeof(struct index_entry))
619 logf("read error #3");
620 if (localfd)
621 close(masterfd);
623 return false;
626 if (localfd)
627 close(masterfd);
629 if (idx->flag & FLAG_DELETED)
630 return false;
632 return true;
635 #ifndef __PCTOOL__
637 static bool write_index(int masterfd, int idxid, struct index_entry *idx)
639 /* We need to exclude all memory only flags & tags when writing to disk. */
640 if (idx->flag & FLAG_DIRCACHE)
642 logf("memory only flags!");
643 return false;
646 #ifdef HAVE_TC_RAMCACHE
647 /* Only update numeric data. Writing the whole index to RAM by memcpy
648 * destroys dircache pointers!
650 if (tc_stat.ramcache)
652 int tag;
653 struct index_entry *idx_ram = &ramcache_hdr->indices[idxid];
655 for (tag = 0; tag < TAG_COUNT; tag++)
657 if (TAGCACHE_IS_NUMERIC(tag))
659 idx_ram->tag_seek[tag] = idx->tag_seek[tag];
663 /* Don't touch the dircache flag or attributes. */
664 idx_ram->flag = (idx->flag & 0x0000ffff)
665 | (idx_ram->flag & (0xffff0000 | FLAG_DIRCACHE));
667 #endif
669 lseek(masterfd, idxid * sizeof(struct index_entry)
670 + sizeof(struct master_header), SEEK_SET);
671 if (ecwrite_index_entry(masterfd, idx) != sizeof(struct index_entry))
673 logf("write error #3");
674 logf("idxid: %d", idxid);
675 return false;
678 return true;
681 #endif /* !__PCTOOL__ */
683 static bool open_files(struct tagcache_search *tcs, int tag)
685 if (tcs->idxfd[tag] < 0)
687 char fn[MAX_PATH];
689 snprintf(fn, sizeof fn, TAGCACHE_FILE_INDEX, tag);
690 tcs->idxfd[tag] = open(fn, O_RDONLY);
693 if (tcs->idxfd[tag] < 0)
695 logf("File not open!");
696 return false;
699 return true;
702 static bool retrieve(struct tagcache_search *tcs, struct index_entry *idx,
703 int tag, char *buf, long size)
705 struct tagfile_entry tfe;
706 long seek;
708 *buf = '\0';
710 if (TAGCACHE_IS_NUMERIC(tag))
711 return false;
713 seek = idx->tag_seek[tag];
714 if (seek < 0)
716 logf("Retrieve failed");
717 return false;
720 #ifdef HAVE_TC_RAMCACHE
721 if (tcs->ramsearch)
723 struct tagfile_entry *ep;
725 # ifdef HAVE_DIRCACHE
726 if (tag == tag_filename && (idx->flag & FLAG_DIRCACHE))
728 /* for tag_filename, seek is a dircache index */
729 if (is_dircache_intact())
731 dircache_copy_path(seek, buf, size);
732 return true;
734 else
736 /* The seek is useless now, there's nothing we can return. */
737 logf("retrieve: dircache gone, cannot read file name");
738 tagcache_unload_ramcache();
739 // XXX do this when there's a way to not trigger an
740 // update before reloading:
741 // tagcache_start_scan();
742 return false;
745 else
746 # endif
747 if (tag != tag_filename)
749 ep = (struct tagfile_entry *)&ramcache_hdr->tags[tag][seek];
750 strlcpy(buf, ep->tag_data, size);
752 return true;
755 #endif
757 if (!open_files(tcs, tag))
758 return false;
760 lseek(tcs->idxfd[tag], seek, SEEK_SET);
761 if (ecread_tagfile_entry(tcs->idxfd[tag], &tfe)
762 != sizeof(struct tagfile_entry))
764 logf("read error #5");
765 return false;
768 if (tfe.tag_length >= size)
770 logf("too small buffer");
771 return false;
774 if (read(tcs->idxfd[tag], buf, tfe.tag_length) !=
775 tfe.tag_length)
777 logf("read error #6");
778 return false;
781 buf[tfe.tag_length] = '\0';
783 return true;
786 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
788 static long find_tag(int tag, int idx_id, const struct index_entry *idx)
790 #ifndef __PCTOOL__
791 if (! COMMAND_QUEUE_IS_EMPTY && TAGCACHE_IS_NUMERIC(tag))
793 /* Attempt to find tag data through store-to-load forwarding in
794 command queue */
795 long result = -1;
797 mutex_lock(&command_queue_mutex);
799 int ridx = command_queue_widx;
801 while (ridx != command_queue_ridx)
803 if (--ridx < 0)
804 ridx = TAGCACHE_COMMAND_QUEUE_LENGTH - 1;
806 if (command_queue[ridx].command == CMD_UPDATE_NUMERIC
807 && command_queue[ridx].idx_id == idx_id
808 && command_queue[ridx].tag == tag)
810 result = command_queue[ridx].data;
811 break;
815 mutex_unlock(&command_queue_mutex);
817 if (result >= 0)
819 logf("find_tag: "
820 "Recovered tag %d value %lX from write queue",
821 tag, result);
822 return result;
825 #endif
827 return idx->tag_seek[tag];
831 static long check_virtual_tags(int tag, int idx_id,
832 const struct index_entry *idx)
834 long data = 0;
836 switch (tag)
838 case tag_virt_length_sec:
839 data = (find_tag(tag_length, idx_id, idx)/1000) % 60;
840 break;
842 case tag_virt_length_min:
843 data = (find_tag(tag_length, idx_id, idx)/1000) / 60;
844 break;
846 case tag_virt_playtime_sec:
847 data = (find_tag(tag_playtime, idx_id, idx)/1000) % 60;
848 break;
850 case tag_virt_playtime_min:
851 data = (find_tag(tag_playtime, idx_id, idx)/1000) / 60;
852 break;
854 case tag_virt_autoscore:
855 if (find_tag(tag_length, idx_id, idx) == 0
856 || find_tag(tag_playcount, idx_id, idx) == 0)
858 data = 0;
860 else
862 /* A straight calculus gives:
863 autoscore = 100 * playtime / length / playcout (1)
864 Now, consider the euclidian division of playtime by length:
865 playtime = alpha * length + beta
866 With:
867 0 <= beta < length
868 Now, (1) becomes:
869 autoscore = 100 * (alpha / playcout + beta / length / playcount)
870 Both terms should be small enough to avoid any overflow
872 data = 100 * (find_tag(tag_playtime, idx_id, idx)
873 / find_tag(tag_length, idx_id, idx))
874 + (100 * (find_tag(tag_playtime, idx_id, idx)
875 % find_tag(tag_length, idx_id, idx)))
876 / find_tag(tag_length, idx_id, idx);
877 data /= find_tag(tag_playcount, idx_id, idx);
879 break;
881 /* How many commits before the file has been added to the DB. */
882 case tag_virt_entryage:
883 data = current_tcmh.commitid
884 - find_tag(tag_commitid, idx_id, idx) - 1;
885 break;
887 case tag_virt_basename:
888 tag = tag_filename; /* return filename; caller handles basename */
889 /* FALLTHRU */
891 default:
892 data = find_tag(tag, idx_id, idx);
895 return data;
898 long tagcache_get_numeric(const struct tagcache_search *tcs, int tag)
900 struct index_entry idx;
902 if (!tc_stat.ready)
903 return false;
905 if (!TAGCACHE_IS_NUMERIC(tag))
906 return -1;
908 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
909 return -2;
911 return check_virtual_tags(tag, tcs->idx_id, &idx);
914 inline static bool str_ends_with(const char *str1, const char *str2)
916 int str_len = strlen(str1);
917 int clause_len = strlen(str2);
919 if (clause_len > str_len)
920 return false;
922 return !strcasecmp(&str1[str_len - clause_len], str2);
925 inline static bool str_oneof(const char *str, const char *list)
927 const char *sep;
928 int l, len = strlen(str);
930 while (*list)
932 sep = strchr(list, '|');
933 l = sep ? (long)sep - (long)list : (int)strlen(list);
934 if ((l==len) && !strncasecmp(str, list, len))
935 return true;
936 list += sep ? l + 1 : l;
939 return false;
942 static bool check_against_clause(long numeric, const char *str,
943 const struct tagcache_search_clause *clause)
945 if (clause->numeric)
947 switch (clause->type)
949 case clause_is:
950 return numeric == clause->numeric_data;
951 case clause_is_not:
952 return numeric != clause->numeric_data;
953 case clause_gt:
954 return numeric > clause->numeric_data;
955 case clause_gteq:
956 return numeric >= clause->numeric_data;
957 case clause_lt:
958 return numeric < clause->numeric_data;
959 case clause_lteq:
960 return numeric <= clause->numeric_data;
961 default:
962 logf("Incorrect numeric tag: %d", clause->type);
965 else
967 switch (clause->type)
969 case clause_is:
970 return !strcasecmp(clause->str, str);
971 case clause_is_not:
972 return strcasecmp(clause->str, str);
973 case clause_gt:
974 return 0>strcasecmp(clause->str, str);
975 case clause_gteq:
976 return 0>=strcasecmp(clause->str, str);
977 case clause_lt:
978 return 0<strcasecmp(clause->str, str);
979 case clause_lteq:
980 return 0<=strcasecmp(clause->str, str);
981 case clause_contains:
982 return (strcasestr(str, clause->str) != NULL);
983 case clause_not_contains:
984 return (strcasestr(str, clause->str) == NULL);
985 case clause_begins_with:
986 return (strcasestr(str, clause->str) == str);
987 case clause_not_begins_with:
988 return (strcasestr(str, clause->str) != str);
989 case clause_ends_with:
990 return str_ends_with(str, clause->str);
991 case clause_not_ends_with:
992 return !str_ends_with(str, clause->str);
993 case clause_oneof:
994 return str_oneof(str, clause->str);
996 default:
997 logf("Incorrect tag: %d", clause->type);
1001 return false;
1004 static bool check_clauses(struct tagcache_search *tcs,
1005 struct index_entry *idx,
1006 struct tagcache_search_clause **clauses, int count)
1008 int i;
1010 /* Go through all conditional clauses. */
1011 for (i = 0; i < count; i++)
1013 int seek;
1014 char buf[256];
1015 char *str = buf;
1016 struct tagcache_search_clause *clause = clauses[i];
1018 if (clause->type == clause_logical_or)
1019 break; /* all conditions before logical-or satisfied --
1020 stop processing clauses */
1022 seek = check_virtual_tags(clause->tag, tcs->idx_id, idx);
1024 #ifdef HAVE_TC_RAMCACHE
1025 if (tcs->ramsearch)
1027 struct tagfile_entry *tfe;
1029 if (!TAGCACHE_IS_NUMERIC(clause->tag))
1031 if (clause->tag == tag_filename
1032 || clause->tag == tag_virt_basename)
1034 retrieve(tcs, idx, tag_filename, buf, sizeof buf);
1036 else
1038 tfe = (struct tagfile_entry *)
1039 &ramcache_hdr->tags[clause->tag][seek];
1040 /* str points to movable data, but no locking required here,
1041 * as no yield() is following */
1042 str = tfe->tag_data;
1046 else
1047 #endif
1049 struct tagfile_entry tfe;
1051 if (!TAGCACHE_IS_NUMERIC(clause->tag))
1053 int tag = clause->tag;
1054 if (tag == tag_virt_basename)
1055 tag = tag_filename;
1057 int fd = tcs->idxfd[tag];
1058 lseek(fd, seek, SEEK_SET);
1059 ecread_tagfile_entry(fd, &tfe);
1060 if (tfe.tag_length >= (int)sizeof(buf))
1062 logf("Too long tag read!");
1063 return false;
1066 read(fd, str, tfe.tag_length);
1067 str[tfe.tag_length] = '\0';
1069 /* Check if entry has been deleted. */
1070 if (str[0] == '\0')
1071 return false;
1075 if (clause->tag == tag_virt_basename)
1077 char *basename = strrchr(str, '/');
1078 if (basename)
1079 str = basename + 1;
1082 if (!check_against_clause(seek, str, clause))
1084 /* Clause failed -- try finding a logical-or clause */
1085 while (++i < count)
1087 if (clauses[i]->type == clause_logical_or)
1088 break;
1091 if (i < count) /* Found logical-or? */
1092 continue; /* Check clauses after logical-or */
1094 return false;
1098 return true;
1101 bool tagcache_check_clauses(struct tagcache_search *tcs,
1102 struct tagcache_search_clause **clause, int count)
1104 struct index_entry idx;
1106 if (count == 0)
1107 return true;
1109 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
1110 return false;
1112 return check_clauses(tcs, &idx, clause, count);
1115 static bool add_uniqbuf(struct tagcache_search *tcs, unsigned long id)
1117 int i;
1119 /* If uniq buffer is not defined we must return true for search to work. */
1120 if (tcs->unique_list == NULL || (!TAGCACHE_IS_UNIQUE(tcs->type)
1121 && !TAGCACHE_IS_NUMERIC(tcs->type)))
1123 return true;
1126 for (i = 0; i < tcs->unique_list_count; i++)
1128 /* Return false if entry is found. */
1129 if (tcs->unique_list[i] == id)
1130 return false;
1133 if (tcs->unique_list_count < tcs->unique_list_capacity)
1135 tcs->unique_list[i] = id;
1136 tcs->unique_list_count++;
1139 return true;
1142 static bool build_lookup_list(struct tagcache_search *tcs)
1144 struct index_entry entry;
1145 int i, j;
1147 tcs->seek_list_count = 0;
1149 #ifdef HAVE_TC_RAMCACHE
1150 if (tcs->ramsearch
1151 # ifdef HAVE_DIRCACHE
1152 && (tcs->type != tag_filename || is_dircache_intact())
1153 # endif
1156 move_lock++; /* lock because below makes a pointer to movable data */
1157 for (i = tcs->seek_pos; i < current_tcmh.tch.entry_count; i++)
1159 struct tagcache_seeklist_entry *seeklist;
1160 /* idx points to movable data, don't yield or reload */
1161 struct index_entry *idx = &ramcache_hdr->indices[i];
1162 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1163 break ;
1165 /* Skip deleted files. */
1166 if (idx->flag & FLAG_DELETED)
1167 continue;
1169 /* Go through all filters.. */
1170 for (j = 0; j < tcs->filter_count; j++)
1172 if (idx->tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1174 break ;
1178 if (j < tcs->filter_count)
1179 continue ;
1181 /* Check for conditions. */
1182 if (!check_clauses(tcs, idx, tcs->clause, tcs->clause_count))
1183 continue;
1184 /* Add to the seek list if not already in uniq buffer (doesn't yield)*/
1185 if (!add_uniqbuf(tcs, idx->tag_seek[tcs->type]))
1186 continue;
1188 /* Lets add it. */
1189 seeklist = &tcs->seeklist[tcs->seek_list_count];
1190 seeklist->seek = idx->tag_seek[tcs->type];
1191 seeklist->flag = idx->flag;
1192 seeklist->idx_id = i;
1193 tcs->seek_list_count++;
1195 move_lock--;
1197 tcs->seek_pos = i;
1199 return tcs->seek_list_count > 0;
1201 #endif
1203 if (tcs->masterfd < 0)
1205 struct master_header tcmh;
1206 tcs->masterfd = open_master_fd(&tcmh, false);
1209 lseek(tcs->masterfd, tcs->seek_pos * sizeof(struct index_entry) +
1210 sizeof(struct master_header), SEEK_SET);
1212 while (ecread_index_entry(tcs->masterfd, &entry)
1213 == sizeof(struct index_entry))
1215 struct tagcache_seeklist_entry *seeklist;
1217 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1218 break ;
1220 i = tcs->seek_pos;
1221 tcs->seek_pos++;
1223 /* Check if entry has been deleted. */
1224 if (entry.flag & FLAG_DELETED)
1225 continue;
1227 /* Go through all filters.. */
1228 for (j = 0; j < tcs->filter_count; j++)
1230 if (entry.tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1231 break ;
1234 if (j < tcs->filter_count)
1235 continue ;
1237 /* Check for conditions. */
1238 if (!check_clauses(tcs, &entry, tcs->clause, tcs->clause_count))
1239 continue;
1241 /* Add to the seek list if not already in uniq buffer. */
1242 if (!add_uniqbuf(tcs, entry.tag_seek[tcs->type]))
1243 continue;
1245 /* Lets add it. */
1246 seeklist = &tcs->seeklist[tcs->seek_list_count];
1247 seeklist->seek = entry.tag_seek[tcs->type];
1248 seeklist->flag = entry.flag;
1249 seeklist->idx_id = i;
1250 tcs->seek_list_count++;
1252 yield();
1255 return tcs->seek_list_count > 0;
1259 static void remove_files(void)
1261 int i;
1262 char buf[MAX_PATH];
1264 tc_stat.ready = false;
1265 tc_stat.ramcache = false;
1266 tc_stat.econ = false;
1267 remove(TAGCACHE_FILE_MASTER);
1268 for (i = 0; i < TAG_COUNT; i++)
1270 if (TAGCACHE_IS_NUMERIC(i))
1271 continue;
1273 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, i);
1274 remove(buf);
1279 static bool check_all_headers(void)
1281 struct master_header myhdr;
1282 struct tagcache_header tch;
1283 int tag;
1284 int fd;
1286 if ( (fd = open_master_fd(&myhdr, false)) < 0)
1287 return false;
1289 close(fd);
1290 if (myhdr.dirty)
1292 logf("tagcache is dirty!");
1293 return false;
1296 memcpy(&current_tcmh, &myhdr, sizeof(struct master_header));
1298 for (tag = 0; tag < TAG_COUNT; tag++)
1300 if (TAGCACHE_IS_NUMERIC(tag))
1301 continue;
1303 if ( (fd = open_tag_fd(&tch, tag, false)) < 0)
1304 return false;
1306 close(fd);
1309 return true;
1312 bool tagcache_is_busy(void)
1314 return read_lock || write_lock;
1317 bool tagcache_search(struct tagcache_search *tcs, int tag)
1319 struct tagcache_header tag_hdr;
1320 struct master_header master_hdr;
1321 int i;
1323 while (read_lock)
1324 sleep(1);
1326 memset(tcs, 0, sizeof(struct tagcache_search));
1327 if (tc_stat.commit_step > 0 || !tc_stat.ready)
1328 return false;
1330 tcs->position = sizeof(struct tagcache_header);
1331 tcs->type = tag;
1332 tcs->seek_pos = 0;
1333 tcs->list_position = 0;
1334 tcs->seek_list_count = 0;
1335 tcs->filter_count = 0;
1336 tcs->masterfd = -1;
1338 for (i = 0; i < TAG_COUNT; i++)
1339 tcs->idxfd[i] = -1;
1341 #ifndef HAVE_TC_RAMCACHE
1342 tcs->ramsearch = false;
1343 #else
1344 tcs->ramsearch = tc_stat.ramcache;
1345 if (tcs->ramsearch)
1347 tcs->entry_count = ramcache_hdr->entry_count[tcs->type];
1349 else
1350 #endif
1352 /* Always open as R/W so we can pass tcs to functions that modify data also
1353 * without failing. */
1354 tcs->masterfd = open_master_fd(&master_hdr, true);
1355 if (tcs->masterfd < 0)
1356 return false;
1358 if (!TAGCACHE_IS_NUMERIC(tcs->type))
1360 tcs->idxfd[tcs->type] = open_tag_fd(&tag_hdr, tcs->type, false);
1361 if (tcs->idxfd[tcs->type] < 0)
1362 return false;
1364 tcs->entry_count = tag_hdr.entry_count;
1366 else
1368 tcs->entry_count = master_hdr.tch.entry_count;
1372 tcs->valid = true;
1373 tcs->initialized = true;
1374 write_lock++;
1376 return true;
1379 void tagcache_search_set_uniqbuf(struct tagcache_search *tcs,
1380 void *buffer, long length)
1382 tcs->unique_list = (unsigned long *)buffer;
1383 tcs->unique_list_capacity = length / sizeof(*tcs->unique_list);
1384 tcs->unique_list_count = 0;
1387 bool tagcache_search_add_filter(struct tagcache_search *tcs,
1388 int tag, int seek)
1390 if (tcs->filter_count == TAGCACHE_MAX_FILTERS)
1391 return false;
1393 if (TAGCACHE_IS_NUMERIC_OR_NONUNIQUE(tag))
1394 return false;
1396 tcs->filter_tag[tcs->filter_count] = tag;
1397 tcs->filter_seek[tcs->filter_count] = seek;
1398 tcs->filter_count++;
1400 return true;
1403 bool tagcache_search_add_clause(struct tagcache_search *tcs,
1404 struct tagcache_search_clause *clause)
1406 int i;
1408 if (tcs->clause_count >= TAGCACHE_MAX_CLAUSES)
1410 logf("Too many clauses");
1411 return false;
1414 if (clause->type != clause_logical_or)
1416 /* Check if there is already a similar filter in present (filters are
1417 * much faster than clauses).
1419 for (i = 0; i < tcs->filter_count; i++)
1421 if (tcs->filter_tag[i] == clause->tag)
1422 return true;
1425 if (!TAGCACHE_IS_NUMERIC(clause->tag) && tcs->idxfd[clause->tag] < 0)
1427 char buf[MAX_PATH];
1429 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, clause->tag);
1430 tcs->idxfd[clause->tag] = open(buf, O_RDONLY);
1434 tcs->clause[tcs->clause_count] = clause;
1435 tcs->clause_count++;
1437 return true;
1440 static bool get_next(struct tagcache_search *tcs)
1442 static char buf[TAG_MAXLEN+32];
1443 struct tagfile_entry entry;
1444 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1445 long flag = 0;
1446 #endif
1448 if (!tcs->valid || !tc_stat.ready)
1449 return false;
1451 if (tcs->idxfd[tcs->type] < 0 && !TAGCACHE_IS_NUMERIC(tcs->type)
1452 #ifdef HAVE_TC_RAMCACHE
1453 && !tcs->ramsearch
1454 #endif
1456 return false;
1458 /* Relative fetch. */
1459 if (tcs->filter_count > 0 || tcs->clause_count > 0
1460 || TAGCACHE_IS_NUMERIC(tcs->type)
1461 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1462 /* We need to retrieve flag status for dircache. */
1463 || (tcs->ramsearch && tcs->type == tag_filename)
1464 #endif
1467 struct tagcache_seeklist_entry *seeklist;
1469 /* Check for end of list. */
1470 if (tcs->list_position == tcs->seek_list_count)
1472 tcs->list_position = 0;
1474 /* Try to fetch more. */
1475 if (!build_lookup_list(tcs))
1477 tcs->valid = false;
1478 return false;
1482 seeklist = &tcs->seeklist[tcs->list_position];
1483 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1484 flag = seeklist->flag;
1485 #endif
1486 tcs->position = seeklist->seek;
1487 tcs->idx_id = seeklist->idx_id;
1488 tcs->list_position++;
1490 else
1492 if (tcs->entry_count == 0)
1494 tcs->valid = false;
1495 return false;
1498 tcs->entry_count--;
1501 tcs->result_seek = tcs->position;
1503 if (TAGCACHE_IS_NUMERIC(tcs->type))
1505 snprintf(buf, sizeof(buf), "%ld", tcs->position);
1506 tcs->result = buf;
1507 tcs->result_len = strlen(buf) + 1;
1508 return true;
1511 /* Direct fetch. */
1512 #ifdef HAVE_TC_RAMCACHE
1513 if (tcs->ramsearch)
1516 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1517 if (tcs->type == tag_filename && (flag & FLAG_DIRCACHE))
1519 if (is_dircache_intact())
1521 size_t len = dircache_copy_path(tcs->position, buf, sizeof buf);
1522 tcs->result_len = len + 1;
1523 tcs->result = buf;
1524 tcs->ramresult = false;
1526 return true;
1528 else
1530 /* The seek is useless now, there's nothing we can return. */
1531 logf("get_next: dircache gone, cannot read file name");
1532 tagcache_unload_ramcache();
1533 // XXX do this when there's a way to not trigger an
1534 // update before reloading:
1535 // tagcache_start_scan();
1536 tcs->valid = false;
1537 return false;
1540 else
1541 #endif
1542 if (tcs->type != tag_filename)
1544 struct tagfile_entry *ep;
1546 ep = (struct tagfile_entry *)&ramcache_hdr->tags[tcs->type][tcs->position];
1547 /* don't return ep->tag_data directly as it may move */
1548 tcs->result_len = strlcpy(buf, ep->tag_data, sizeof(buf)) + 1;
1549 tcs->result = buf;
1550 tcs->idx_id = ep->idx_id;
1551 tcs->ramresult = false; /* was true before we copied to buf too */
1553 /* Increase position for the next run. This may get overwritten. */
1554 tcs->position += sizeof(struct tagfile_entry) + ep->tag_length;
1556 return true;
1559 #endif
1561 if (!open_files(tcs, tcs->type))
1563 tcs->valid = false;
1564 return false;
1567 /* Seek stream to the correct position and continue to direct fetch. */
1568 lseek(tcs->idxfd[tcs->type], tcs->position, SEEK_SET);
1570 if (ecread_tagfile_entry(tcs->idxfd[tcs->type], &entry) != sizeof(struct tagfile_entry))
1572 logf("read error #5");
1573 tcs->valid = false;
1574 return false;
1577 if (entry.tag_length > (long)sizeof(buf))
1579 tcs->valid = false;
1580 logf("too long tag #2");
1581 logf("P:%lX/%lX", tcs->position, entry.tag_length);
1582 return false;
1585 if (read(tcs->idxfd[tcs->type], buf, entry.tag_length) != entry.tag_length)
1587 tcs->valid = false;
1588 logf("read error #4");
1589 return false;
1593 Update the position for the next read (this may be overridden
1594 if filters or clauses are being used).
1596 tcs->position += sizeof(struct tagfile_entry) + entry.tag_length;
1597 tcs->result = buf;
1598 tcs->result_len = strlen(tcs->result) + 1;
1599 tcs->idx_id = entry.idx_id;
1600 tcs->ramresult = false;
1602 return true;
1605 bool tagcache_get_next(struct tagcache_search *tcs)
1607 while (get_next(tcs))
1609 if (tcs->result_len > 1)
1610 return true;
1613 return false;
1616 bool tagcache_retrieve(struct tagcache_search *tcs, int idxid,
1617 int tag, char *buf, long size)
1619 struct index_entry idx;
1621 *buf = '\0';
1622 if (!get_index(tcs->masterfd, idxid, &idx, true))
1623 return false;
1625 return retrieve(tcs, &idx, tag, buf, size);
1628 static bool update_master_header(void)
1630 struct master_header myhdr;
1631 int fd;
1633 if (!tc_stat.ready)
1634 return false;
1636 if ( (fd = open_master_fd(&myhdr, true)) < 0)
1637 return false;
1639 myhdr.serial = current_tcmh.serial;
1640 myhdr.commitid = current_tcmh.commitid;
1641 myhdr.dirty = current_tcmh.dirty;
1643 /* Write it back */
1644 lseek(fd, 0, SEEK_SET);
1645 ecwrite(fd, &myhdr, 1, master_header_ec, tc_stat.econ);
1646 close(fd);
1648 return true;
1651 void tagcache_search_finish(struct tagcache_search *tcs)
1653 int i;
1655 if (!tcs->initialized)
1656 return;
1658 if (tcs->masterfd >= 0)
1660 close(tcs->masterfd);
1661 tcs->masterfd = -1;
1664 for (i = 0; i < TAG_COUNT; i++)
1666 if (tcs->idxfd[i] >= 0)
1668 close(tcs->idxfd[i]);
1669 tcs->idxfd[i] = -1;
1673 tcs->ramsearch = false;
1674 tcs->valid = false;
1675 tcs->initialized = 0;
1676 if (write_lock > 0)
1677 write_lock--;
1680 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1681 static struct tagfile_entry *get_tag(const struct index_entry *entry, int tag)
1683 return (struct tagfile_entry *)&ramcache_hdr->tags[tag][entry->tag_seek[tag]];
1686 static long get_tag_numeric(const struct index_entry *entry, int tag, int idx_id)
1688 return check_virtual_tags(tag, idx_id, entry);
1691 static char* get_tag_string(const struct index_entry *entry, int tag)
1693 char* s = get_tag(entry, tag)->tag_data;
1694 return strcmp(s, UNTAGGED) ? s : NULL;
1697 bool tagcache_fill_tags(struct mp3entry *id3, const char *filename)
1699 struct index_entry *entry;
1700 int idx_id;
1702 if (!tc_stat.ready || !tc_stat.ramcache)
1703 return false;
1705 /* Find the corresponding entry in tagcache. */
1706 idx_id = find_entry_ram(filename, -1);
1707 if (idx_id < 0)
1708 return false;
1710 entry = &ramcache_hdr->indices[idx_id];
1712 memset(id3, 0, sizeof(struct mp3entry));
1713 char* buf = id3->id3v2buf;
1714 ssize_t remaining = sizeof(id3->id3v2buf);
1716 /* this macro sets id3 strings by copying to the id3v2buf */
1717 #define SET(x, y) do \
1719 if (remaining > 0) \
1721 x = NULL; /* initialize with null if tag doesn't exist */ \
1722 char* src = get_tag_string(entry, y); \
1723 if (src) \
1725 x = buf; \
1726 size_t len = strlcpy(buf, src, remaining) +1; \
1727 buf += len; remaining -= len; \
1730 } while(0)
1733 SET(id3->title, tag_title);
1734 SET(id3->artist, tag_artist);
1735 SET(id3->album, tag_album);
1736 SET(id3->genre_string, tag_genre);
1737 SET(id3->composer, tag_composer);
1738 SET(id3->comment, tag_comment);
1739 SET(id3->albumartist, tag_albumartist);
1740 SET(id3->grouping, tag_grouping);
1742 id3->length = get_tag_numeric(entry, tag_length, idx_id);
1743 id3->playcount = get_tag_numeric(entry, tag_playcount, idx_id);
1744 id3->rating = get_tag_numeric(entry, tag_rating, idx_id);
1745 id3->lastplayed = get_tag_numeric(entry, tag_lastplayed, idx_id);
1746 id3->score = get_tag_numeric(entry, tag_virt_autoscore, idx_id) / 10;
1747 id3->year = get_tag_numeric(entry, tag_year, idx_id);
1749 id3->discnum = get_tag_numeric(entry, tag_discnumber, idx_id);
1750 id3->tracknum = get_tag_numeric(entry, tag_tracknumber, idx_id);
1751 id3->bitrate = get_tag_numeric(entry, tag_bitrate, idx_id);
1752 if (id3->bitrate == 0)
1753 id3->bitrate = 1;
1755 #if CONFIG_CODEC == SWCODEC
1756 if (global_settings.autoresume_enable)
1758 id3->offset = get_tag_numeric(entry, tag_lastoffset, idx_id);
1759 logf("tagcache_fill_tags: Set offset for %s to %lX\n",
1760 id3->title, id3->offset);
1762 #endif
1764 return true;
1766 #endif
1768 static inline void write_item(const char *item)
1770 int len = strlen(item) + 1;
1772 data_size += len;
1773 write(cachefd, item, len);
1776 static int check_if_empty(char **tag)
1778 int length;
1780 if (*tag == NULL || **tag == '\0')
1782 *tag = UNTAGGED;
1783 return sizeof(UNTAGGED); /* Tag length */
1786 length = strlen(*tag);
1787 if (length > TAG_MAXLEN)
1789 logf("over length tag: %s", *tag);
1790 length = TAG_MAXLEN;
1791 (*tag)[length] = '\0';
1794 return length + 1;
1797 #define ADD_TAG(entry,tag,data) \
1798 /* Adding tag */ \
1799 entry.tag_offset[tag] = offset; \
1800 entry.tag_length[tag] = check_if_empty(data); \
1801 offset += entry.tag_length[tag]
1802 /* GCC 3.4.6 for Coldfire can choose to inline this function. Not a good
1803 * idea, as it uses lots of stack and is called from a recursive function
1804 * (check_dir).
1806 static void __attribute__ ((noinline)) add_tagcache(char *path,
1807 unsigned long mtime
1808 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1809 ,int dc
1810 #endif
1813 struct mp3entry id3;
1814 struct temp_file_entry entry;
1815 bool ret;
1816 int fd;
1817 int idx_id = -1;
1818 char tracknumfix[3];
1819 int offset = 0;
1820 int path_length = strlen(path);
1821 bool has_albumartist;
1822 bool has_grouping;
1824 #ifdef SIMULATOR
1825 /* Crude logging for the sim - to aid in debugging */
1826 int logfd = open(ROCKBOX_DIR "/database.log",
1827 O_WRONLY | O_APPEND | O_CREAT, 0666);
1828 if (logfd >= 0) {
1829 write(logfd, path, strlen(path));
1830 write(logfd, "\n", 1);
1831 close(logfd);
1833 #endif
1835 if (cachefd < 0)
1836 return ;
1838 /* Check for overlength file path. */
1839 if (path_length > TAG_MAXLEN)
1841 /* Path can't be shortened. */
1842 logf("Too long path: %s", path);
1843 return ;
1846 /* Check if the file is supported. */
1847 if (probe_file_format(path) == AFMT_UNKNOWN)
1848 return ;
1850 /* Check if the file is already cached. */
1851 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1852 idx_id = find_entry_ram(path, dc);
1853 #endif
1855 /* Be sure the entry doesn't exist. */
1856 if (filenametag_fd >= 0 && idx_id < 0)
1857 idx_id = find_entry_disk(path, false);
1859 /* Check if file has been modified. */
1860 if (idx_id >= 0)
1862 struct index_entry idx;
1864 /* TODO: Mark that the index exists (for fast reverse scan) */
1865 //found_idx[idx_id/8] |= idx_id%8;
1867 if (!get_index(-1, idx_id, &idx, true))
1869 logf("failed to retrieve index entry");
1870 return ;
1873 if ((unsigned long)idx.tag_seek[tag_mtime] == mtime)
1875 /* No changes to file. */
1876 return ;
1879 /* Metadata might have been changed. Delete the entry. */
1880 logf("Re-adding: %s", path);
1881 if (!delete_entry(idx_id))
1883 logf("delete_entry failed: %d", idx_id);
1884 return ;
1888 fd = open(path, O_RDONLY);
1889 if (fd < 0)
1891 logf("open fail: %s", path);
1892 return ;
1895 memset(&id3, 0, sizeof(struct mp3entry));
1896 memset(&entry, 0, sizeof(struct temp_file_entry));
1897 memset(&tracknumfix, 0, sizeof(tracknumfix));
1898 ret = get_metadata(&id3, fd, path);
1899 close(fd);
1901 if (!ret)
1902 return ;
1904 logf("-> %s", path);
1906 if (id3.tracknum <= 0) /* Track number missing? */
1908 id3.tracknum = -1;
1911 /* Numeric tags */
1912 entry.tag_offset[tag_year] = id3.year;
1913 entry.tag_offset[tag_discnumber] = id3.discnum;
1914 entry.tag_offset[tag_tracknumber] = id3.tracknum;
1915 entry.tag_offset[tag_length] = id3.length;
1916 entry.tag_offset[tag_bitrate] = id3.bitrate;
1917 entry.tag_offset[tag_mtime] = mtime;
1919 /* String tags. */
1920 has_albumartist = id3.albumartist != NULL
1921 && strlen(id3.albumartist) > 0;
1922 has_grouping = id3.grouping != NULL
1923 && strlen(id3.grouping) > 0;
1925 ADD_TAG(entry, tag_filename, &path);
1926 ADD_TAG(entry, tag_title, &id3.title);
1927 ADD_TAG(entry, tag_artist, &id3.artist);
1928 ADD_TAG(entry, tag_album, &id3.album);
1929 ADD_TAG(entry, tag_genre, &id3.genre_string);
1930 ADD_TAG(entry, tag_composer, &id3.composer);
1931 ADD_TAG(entry, tag_comment, &id3.comment);
1932 if (has_albumartist)
1934 ADD_TAG(entry, tag_albumartist, &id3.albumartist);
1936 else
1938 ADD_TAG(entry, tag_albumartist, &id3.artist);
1940 if (has_grouping)
1942 ADD_TAG(entry, tag_grouping, &id3.grouping);
1944 else
1946 ADD_TAG(entry, tag_grouping, &id3.title);
1948 entry.data_length = offset;
1950 /* Write the header */
1951 write(cachefd, &entry, sizeof(struct temp_file_entry));
1953 /* And tags also... Correct order is critical */
1954 write_item(path);
1955 write_item(id3.title);
1956 write_item(id3.artist);
1957 write_item(id3.album);
1958 write_item(id3.genre_string);
1959 write_item(id3.composer);
1960 write_item(id3.comment);
1961 if (has_albumartist)
1963 write_item(id3.albumartist);
1965 else
1967 write_item(id3.artist);
1969 if (has_grouping)
1971 write_item(id3.grouping);
1973 else
1975 write_item(id3.title);
1977 total_entry_count++;
1980 static bool tempbuf_insert(char *str, int id, int idx_id, bool unique)
1982 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
1983 int len = strlen(str)+1;
1984 int i;
1985 unsigned crc32;
1986 unsigned *crcbuf = (unsigned *)&tempbuf[tempbuf_size-4];
1987 char buf[TAG_MAXLEN+32];
1989 for (i = 0; str[i] != '\0' && i < (int)sizeof(buf)-1; i++)
1990 buf[i] = tolower(str[i]);
1991 buf[i] = '\0';
1993 crc32 = crc_32(buf, i, 0xffffffff);
1995 if (unique)
1997 /* Check if the crc does not exist -> entry does not exist for sure. */
1998 for (i = 0; i < tempbufidx; i++)
2000 if (crcbuf[-i] != crc32)
2001 continue;
2003 if (!strcasecmp(str, index[i].str))
2005 if (id < 0 || id >= lookup_buffer_depth)
2007 logf("lookup buf overf.: %d", id);
2008 return false;
2011 lookup[id] = &index[i];
2012 return true;
2017 /* Insert to CRC buffer. */
2018 crcbuf[-tempbufidx] = crc32;
2019 tempbuf_left -= 4;
2021 /* Insert it to the buffer. */
2022 tempbuf_left -= len;
2023 if (tempbuf_left - 4 < 0 || tempbufidx >= commit_entry_count-1)
2024 return false;
2026 if (id >= lookup_buffer_depth)
2028 logf("lookup buf overf. #2: %d", id);
2029 return false;
2032 if (id >= 0)
2034 lookup[id] = &index[tempbufidx];
2035 index[tempbufidx].idlist.id = id;
2037 else
2038 index[tempbufidx].idlist.id = -1;
2040 index[tempbufidx].idlist.next = NULL;
2041 index[tempbufidx].idx_id = idx_id;
2042 index[tempbufidx].seek = -1;
2043 index[tempbufidx].str = &tempbuf[tempbuf_pos];
2044 memcpy(index[tempbufidx].str, str, len);
2045 tempbuf_pos += len;
2046 tempbufidx++;
2048 return true;
2051 static int compare(const void *p1, const void *p2)
2053 do_timed_yield();
2055 struct tempbuf_searchidx *e1 = (struct tempbuf_searchidx *)p1;
2056 struct tempbuf_searchidx *e2 = (struct tempbuf_searchidx *)p2;
2058 if (strcmp(e1->str, UNTAGGED) == 0)
2060 if (strcmp(e2->str, UNTAGGED) == 0)
2061 return 0;
2062 return -1;
2064 else if (strcmp(e2->str, UNTAGGED) == 0)
2065 return 1;
2067 return strncasecmp(e1->str, e2->str, TAG_MAXLEN);
2070 static int tempbuf_sort(int fd)
2072 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
2073 struct tagfile_entry fe;
2074 int i;
2075 int length;
2077 /* Generate reverse lookup entries. */
2078 for (i = 0; i < lookup_buffer_depth; i++)
2080 struct tempbuf_id_list *idlist;
2082 if (!lookup[i])
2083 continue;
2085 if (lookup[i]->idlist.id == i)
2086 continue;
2088 idlist = &lookup[i]->idlist;
2089 while (idlist->next != NULL)
2090 idlist = idlist->next;
2092 tempbuf_left -= sizeof(struct tempbuf_id_list);
2093 if (tempbuf_left - 4 < 0)
2094 return -1;
2096 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2097 if (tempbuf_pos & 0x03)
2099 tempbuf_pos = (tempbuf_pos & ~0x03) + 0x04;
2100 tempbuf_left -= 3;
2101 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
2103 tempbuf_pos += sizeof(struct tempbuf_id_list);
2105 idlist = idlist->next;
2106 idlist->id = i;
2107 idlist->next = NULL;
2109 do_timed_yield();
2112 qsort(index, tempbufidx, sizeof(struct tempbuf_searchidx), compare);
2113 memset(lookup, 0, lookup_buffer_depth * sizeof(struct tempbuf_searchidx **));
2115 for (i = 0; i < tempbufidx; i++)
2117 struct tempbuf_id_list *idlist = &index[i].idlist;
2119 /* Fix the lookup list. */
2120 while (idlist != NULL)
2122 if (idlist->id >= 0)
2123 lookup[idlist->id] = &index[i];
2124 idlist = idlist->next;
2127 index[i].seek = lseek(fd, 0, SEEK_CUR);
2128 length = strlen(index[i].str) + 1;
2129 fe.tag_length = length;
2130 fe.idx_id = index[i].idx_id;
2132 /* Check the chunk alignment. */
2133 if ((fe.tag_length + sizeof(struct tagfile_entry))
2134 % TAGFILE_ENTRY_CHUNK_LENGTH)
2136 fe.tag_length += TAGFILE_ENTRY_CHUNK_LENGTH -
2137 ((fe.tag_length + sizeof(struct tagfile_entry))
2138 % TAGFILE_ENTRY_CHUNK_LENGTH);
2141 #ifdef TAGCACHE_STRICT_ALIGN
2142 /* Make sure the entry is long aligned. */
2143 if (index[i].seek & 0x03)
2145 logf("tempbuf_sort: alignment error!");
2146 return -3;
2148 #endif
2150 if (ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ) !=
2151 sizeof(struct tagfile_entry))
2153 logf("tempbuf_sort: write error #1");
2154 return -1;
2157 if (write(fd, index[i].str, length) != length)
2159 logf("tempbuf_sort: write error #2");
2160 return -2;
2163 /* Write some padding. */
2164 if (fe.tag_length - length > 0)
2165 write(fd, "XXXXXXXX", fe.tag_length - length);
2168 return i;
2171 inline static struct tempbuf_searchidx* tempbuf_locate(int id)
2173 if (id < 0 || id >= lookup_buffer_depth)
2174 return NULL;
2176 return lookup[id];
2180 inline static int tempbuf_find_location(int id)
2182 struct tempbuf_searchidx *entry;
2184 entry = tempbuf_locate(id);
2185 if (entry == NULL)
2186 return -1;
2188 return entry->seek;
2191 static bool build_numeric_indices(struct tagcache_header *h, int tmpfd)
2193 struct master_header tcmh;
2194 struct index_entry idx;
2195 int masterfd;
2196 int masterfd_pos;
2197 struct temp_file_entry *entrybuf = (struct temp_file_entry *)tempbuf;
2198 int max_entries;
2199 int entries_processed = 0;
2200 int i, j;
2201 char buf[TAG_MAXLEN];
2203 max_entries = tempbuf_size / sizeof(struct temp_file_entry) - 1;
2205 logf("Building numeric indices...");
2206 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2208 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
2209 return false;
2211 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2212 SEEK_CUR);
2213 if (masterfd_pos == filesize(masterfd))
2215 logf("we can't append!");
2216 close(masterfd);
2217 return false;
2220 while (entries_processed < h->entry_count)
2222 int count = MIN(h->entry_count - entries_processed, max_entries);
2224 /* Read in as many entries as possible. */
2225 for (i = 0; i < count; i++)
2227 struct temp_file_entry *tfe = &entrybuf[i];
2228 int datastart;
2230 /* Read in numeric data. */
2231 if (read(tmpfd, tfe, sizeof(struct temp_file_entry)) !=
2232 sizeof(struct temp_file_entry))
2234 logf("read fail #1");
2235 close(masterfd);
2236 return false;
2239 datastart = lseek(tmpfd, 0, SEEK_CUR);
2242 * Read string data from the following tags:
2243 * - tag_filename
2244 * - tag_artist
2245 * - tag_album
2246 * - tag_title
2248 * A crc32 hash is calculated from the read data
2249 * and stored back to the data offset field kept in memory.
2251 #define tmpdb_read_string_tag(tag) \
2252 lseek(tmpfd, tfe->tag_offset[tag], SEEK_CUR); \
2253 if ((unsigned long)tfe->tag_length[tag] > sizeof buf) \
2255 logf("read fail: buffer overflow"); \
2256 close(masterfd); \
2257 return false; \
2260 if (read(tmpfd, buf, tfe->tag_length[tag]) != \
2261 tfe->tag_length[tag]) \
2263 logf("read fail #2"); \
2264 close(masterfd); \
2265 return false; \
2268 tfe->tag_offset[tag] = crc_32(buf, strlen(buf), 0xffffffff); \
2269 lseek(tmpfd, datastart, SEEK_SET)
2271 tmpdb_read_string_tag(tag_filename);
2272 tmpdb_read_string_tag(tag_artist);
2273 tmpdb_read_string_tag(tag_album);
2274 tmpdb_read_string_tag(tag_title);
2276 /* Seek to the end of the string data. */
2277 lseek(tmpfd, tfe->data_length, SEEK_CUR);
2280 /* Backup the master index position. */
2281 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2282 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2284 /* Check if we can resurrect some deleted runtime statistics data. */
2285 for (i = 0; i < tcmh.tch.entry_count; i++)
2287 /* Read the index entry. */
2288 if (ecread_index_entry(masterfd, &idx)
2289 != sizeof(struct index_entry))
2291 logf("read fail #3");
2292 close(masterfd);
2293 return false;
2297 * Skip unless the entry is marked as being deleted
2298 * or the data has already been resurrected.
2300 if (!(idx.flag & FLAG_DELETED) || idx.flag & FLAG_RESURRECTED)
2301 continue;
2303 /* Now try to match the entry. */
2305 * To succesfully match a song, the following conditions
2306 * must apply:
2308 * For numeric fields: tag_length
2309 * - Full identical match is required
2311 * If tag_filename matches, no further checking necessary.
2313 * For string hashes: tag_artist, tag_album, tag_title
2314 * - All three of these must match
2316 for (j = 0; j < count; j++)
2318 struct temp_file_entry *tfe = &entrybuf[j];
2320 /* Try to match numeric fields first. */
2321 if (tfe->tag_offset[tag_length] != idx.tag_seek[tag_length])
2322 continue;
2324 /* Now it's time to do the hash matching. */
2325 if (tfe->tag_offset[tag_filename] != idx.tag_seek[tag_filename])
2327 int match_count = 0;
2329 /* No filename match, check if we can match two other tags. */
2330 #define tmpdb_match(tag) \
2331 if (tfe->tag_offset[tag] == idx.tag_seek[tag]) \
2332 match_count++
2334 tmpdb_match(tag_artist);
2335 tmpdb_match(tag_album);
2336 tmpdb_match(tag_title);
2338 if (match_count < 3)
2340 /* Still no match found, give up. */
2341 continue;
2345 /* A match found, now copy & resurrect the statistical data. */
2346 #define tmpdb_copy_tag(tag) \
2347 tfe->tag_offset[tag] = idx.tag_seek[tag]
2349 tmpdb_copy_tag(tag_playcount);
2350 tmpdb_copy_tag(tag_rating);
2351 tmpdb_copy_tag(tag_playtime);
2352 tmpdb_copy_tag(tag_lastplayed);
2353 tmpdb_copy_tag(tag_commitid);
2354 tmpdb_copy_tag(tag_lastoffset);
2356 /* Avoid processing this entry again. */
2357 idx.flag |= FLAG_RESURRECTED;
2359 lseek(masterfd, -sizeof(struct index_entry), SEEK_CUR);
2360 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2362 logf("masterfd writeback fail #1");
2363 close(masterfd);
2364 return false;
2367 logf("Entry resurrected");
2372 /* Restore the master index position. */
2373 lseek(masterfd, masterfd_pos, SEEK_SET);
2375 /* Commit the data to the index. */
2376 for (i = 0; i < count; i++)
2378 int loc = lseek(masterfd, 0, SEEK_CUR);
2380 if (ecread_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2382 logf("read fail #3");
2383 close(masterfd);
2384 return false;
2387 for (j = 0; j < TAG_COUNT; j++)
2389 if (!TAGCACHE_IS_NUMERIC(j))
2390 continue;
2392 idx.tag_seek[j] = entrybuf[i].tag_offset[j];
2394 idx.flag = entrybuf[i].flag;
2396 if (idx.tag_seek[tag_commitid])
2398 /* Data has been resurrected. */
2399 idx.flag |= FLAG_DIRTYNUM;
2401 else if (tc_stat.ready && current_tcmh.commitid > 0)
2403 idx.tag_seek[tag_commitid] = current_tcmh.commitid;
2404 idx.flag |= FLAG_DIRTYNUM;
2407 /* Write back the updated index. */
2408 lseek(masterfd, loc, SEEK_SET);
2409 if (ecwrite_index_entry(masterfd, &idx) != sizeof(struct index_entry))
2411 logf("write fail");
2412 close(masterfd);
2413 return false;
2417 entries_processed += count;
2418 logf("%d/%ld entries processed", entries_processed, h->entry_count);
2421 close(masterfd);
2423 return true;
2427 * Return values:
2428 * > 0 success
2429 * == 0 temporary failure
2430 * < 0 fatal error
2432 static int build_index(int index_type, struct tagcache_header *h, int tmpfd)
2434 int i;
2435 struct tagcache_header tch;
2436 struct master_header tcmh;
2437 struct index_entry idxbuf[IDX_BUF_DEPTH];
2438 int idxbuf_pos;
2439 char buf[TAG_MAXLEN+32];
2440 int fd = -1, masterfd;
2441 bool error = false;
2442 int init;
2443 int masterfd_pos;
2445 logf("Building index: %d", index_type);
2447 /* Check the number of entries we need to allocate ram for. */
2448 commit_entry_count = h->entry_count + 1;
2450 masterfd = open_master_fd(&tcmh, false);
2451 if (masterfd >= 0)
2453 commit_entry_count += tcmh.tch.entry_count;
2454 close(masterfd);
2456 else
2457 remove_files(); /* Just to be sure we are clean. */
2459 /* Open the index file, which contains the tag names. */
2460 fd = open_tag_fd(&tch, index_type, true);
2461 if (fd >= 0)
2463 logf("tch.datasize=%ld", tch.datasize);
2464 lookup_buffer_depth = 1 +
2465 /* First part */ commit_entry_count +
2466 /* Second part */ (tch.datasize / TAGFILE_ENTRY_CHUNK_LENGTH);
2468 else
2470 lookup_buffer_depth = 1 +
2471 /* First part */ commit_entry_count +
2472 /* Second part */ 0;
2475 logf("lookup_buffer_depth=%ld", lookup_buffer_depth);
2476 logf("commit_entry_count=%ld", commit_entry_count);
2478 /* Allocate buffer for all index entries from both old and new
2479 * tag files. */
2480 tempbufidx = 0;
2481 tempbuf_pos = commit_entry_count * sizeof(struct tempbuf_searchidx);
2483 /* Allocate lookup buffer. The first portion of commit_entry_count
2484 * contains the new tags in the temporary file and the second
2485 * part for locating entries already in the db.
2487 * New tags Old tags
2488 * +---------+---------------------------+
2489 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2490 * +---------+---------------------------+
2492 * Old tags are inserted to a temporary buffer with position:
2493 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2494 * And new tags with index:
2495 * tempbuf_insert(idx, ...);
2497 * The buffer is sorted and written into tag file:
2498 * tempbuf_sort(...);
2499 * leaving master index locations messed up.
2501 * That is fixed using the lookup buffer for old tags:
2502 * new_seek = tempbuf_find_location(old_seek, ...);
2503 * and for new tags:
2504 * new_seek = tempbuf_find_location(idx);
2506 lookup = (struct tempbuf_searchidx **)&tempbuf[tempbuf_pos];
2507 tempbuf_pos += lookup_buffer_depth * sizeof(void **);
2508 memset(lookup, 0, lookup_buffer_depth * sizeof(void **));
2510 /* And calculate the remaining data space used mainly for storing
2511 * tag data (strings). */
2512 tempbuf_left = tempbuf_size - tempbuf_pos - 8;
2513 if (tempbuf_left - TAGFILE_ENTRY_AVG_LENGTH * commit_entry_count < 0)
2515 logf("Buffer way too small!");
2516 return 0;
2519 if (fd >= 0)
2522 * If tag file contains unique tags (sorted index), we will load
2523 * it entirely into memory so we can resort it later for use with
2524 * chunked browsing.
2526 if (TAGCACHE_IS_SORTED(index_type))
2528 logf("loading tags...");
2529 for (i = 0; i < tch.entry_count; i++)
2531 struct tagfile_entry entry;
2532 int loc = lseek(fd, 0, SEEK_CUR);
2533 bool ret;
2535 if (ecread_tagfile_entry(fd, &entry) != sizeof(struct tagfile_entry))
2537 logf("read error #7");
2538 close(fd);
2539 return -2;
2542 if (entry.tag_length >= (int)sizeof(buf))
2544 logf("too long tag #3");
2545 close(fd);
2546 return -2;
2549 if (read(fd, buf, entry.tag_length) != entry.tag_length)
2551 logf("read error #8");
2552 close(fd);
2553 return -2;
2556 /* Skip deleted entries. */
2557 if (buf[0] == '\0')
2558 continue;
2561 * Save the tag and tag id in the memory buffer. Tag id
2562 * is saved so we can later reindex the master lookup
2563 * table when the index gets resorted.
2565 ret = tempbuf_insert(buf, loc/TAGFILE_ENTRY_CHUNK_LENGTH
2566 + commit_entry_count, entry.idx_id,
2567 TAGCACHE_IS_UNIQUE(index_type));
2568 if (!ret)
2570 close(fd);
2571 return -3;
2573 do_timed_yield();
2575 logf("done");
2577 else
2578 tempbufidx = tch.entry_count;
2580 else
2583 * Creating new index file to store the tags. No need to preload
2584 * anything whether the index type is sorted or not.
2586 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, index_type);
2587 fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2588 if (fd < 0)
2590 logf("%s open fail", buf);
2591 return -2;
2594 tch.magic = TAGCACHE_MAGIC;
2595 tch.entry_count = 0;
2596 tch.datasize = 0;
2598 if (ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ)
2599 != sizeof(struct tagcache_header))
2601 logf("header write failed");
2602 close(fd);
2603 return -2;
2607 /* Loading the tag lookup file as "master file". */
2608 logf("Loading index file");
2609 masterfd = open(TAGCACHE_FILE_MASTER, O_RDWR);
2611 if (masterfd < 0)
2613 logf("Creating new DB");
2614 masterfd = open(TAGCACHE_FILE_MASTER, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2616 if (masterfd < 0)
2618 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER);
2619 close(fd);
2620 return -2;
2623 /* Write the header (write real values later). */
2624 memset(&tcmh, 0, sizeof(struct master_header));
2625 tcmh.tch = *h;
2626 tcmh.tch.entry_count = 0;
2627 tcmh.tch.datasize = 0;
2628 tcmh.dirty = true;
2629 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
2630 init = true;
2631 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2633 else
2636 * Master file already exists so we need to process the current
2637 * file first.
2639 init = false;
2641 if (ecread(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ) !=
2642 sizeof(struct master_header) || tcmh.tch.magic != TAGCACHE_MAGIC)
2644 logf("header error");
2645 close(fd);
2646 close(masterfd);
2647 return -2;
2651 * If we reach end of the master file, we need to expand it to
2652 * hold new tags. If the current index is not sorted, we can
2653 * simply append new data to end of the file.
2654 * However, if the index is sorted, we need to update all tag
2655 * pointers in the master file for the current index.
2657 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2658 SEEK_CUR);
2659 if (masterfd_pos == filesize(masterfd))
2661 logf("appending...");
2662 init = true;
2667 * Load new unique tags in memory to be sorted later and added
2668 * to the master lookup file.
2670 if (TAGCACHE_IS_SORTED(index_type))
2672 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2673 /* h is the header of the temporary file containing new tags. */
2674 logf("inserting new tags...");
2675 for (i = 0; i < h->entry_count; i++)
2677 struct temp_file_entry entry;
2679 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2680 sizeof(struct temp_file_entry))
2682 logf("read fail #3");
2683 error = true;
2684 goto error_exit;
2687 /* Read data. */
2688 if (entry.tag_length[index_type] >= (long)sizeof(buf))
2690 logf("too long entry!");
2691 error = true;
2692 goto error_exit;
2695 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2696 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2697 entry.tag_length[index_type])
2699 logf("read fail #4");
2700 error = true;
2701 goto error_exit;
2704 if (TAGCACHE_IS_UNIQUE(index_type))
2705 error = !tempbuf_insert(buf, i, -1, true);
2706 else
2707 error = !tempbuf_insert(buf, i, tcmh.tch.entry_count + i, false);
2709 if (error)
2711 logf("insert error");
2712 goto error_exit;
2715 /* Skip to next. */
2716 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2717 entry.tag_length[index_type], SEEK_CUR);
2718 do_timed_yield();
2720 logf("done");
2722 /* Sort the buffer data and write it to the index file. */
2723 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
2725 * We need to truncate the index file now. There can be junk left
2726 * at the end of file (however, we _should_ always follow the
2727 * entry_count and don't crash with that).
2729 ftruncate(fd, lseek(fd, 0, SEEK_CUR));
2731 i = tempbuf_sort(fd);
2732 if (i < 0)
2733 goto error_exit;
2734 logf("sorted %d tags", i);
2737 * Now update all indexes in the master lookup file.
2739 logf("updating indices...");
2740 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2741 for (i = 0; i < tcmh.tch.entry_count; i += idxbuf_pos)
2743 int j;
2744 int loc = lseek(masterfd, 0, SEEK_CUR);
2746 idxbuf_pos = MIN(tcmh.tch.entry_count - i, IDX_BUF_DEPTH);
2748 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2749 != (int)sizeof(struct index_entry)*idxbuf_pos)
2751 logf("read fail #5");
2752 error = true;
2753 goto error_exit ;
2755 lseek(masterfd, loc, SEEK_SET);
2757 for (j = 0; j < idxbuf_pos; j++)
2759 if (idxbuf[j].flag & FLAG_DELETED)
2761 /* We can just ignore deleted entries. */
2762 // idxbuf[j].tag_seek[index_type] = 0;
2763 continue;
2766 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(
2767 idxbuf[j].tag_seek[index_type]/TAGFILE_ENTRY_CHUNK_LENGTH
2768 + commit_entry_count);
2770 if (idxbuf[j].tag_seek[index_type] < 0)
2772 logf("update error: %ld/%d/%ld",
2773 idxbuf[j].flag, i+j, tcmh.tch.entry_count);
2774 error = true;
2775 goto error_exit;
2778 do_timed_yield();
2781 /* Write back the updated index. */
2782 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2783 index_entry_ec, tc_stat.econ) !=
2784 (int)sizeof(struct index_entry)*idxbuf_pos)
2786 logf("write fail");
2787 error = true;
2788 goto error_exit;
2791 logf("done");
2795 * Walk through the temporary file containing the new tags.
2797 // build_normal_index(h, tmpfd, masterfd, idx);
2798 logf("updating new indices...");
2799 lseek(masterfd, masterfd_pos, SEEK_SET);
2800 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2801 lseek(fd, 0, SEEK_END);
2802 for (i = 0; i < h->entry_count; i += idxbuf_pos)
2804 int j;
2806 idxbuf_pos = MIN(h->entry_count - i, IDX_BUF_DEPTH);
2807 if (init)
2809 memset(idxbuf, 0, sizeof(struct index_entry)*IDX_BUF_DEPTH);
2811 else
2813 int loc = lseek(masterfd, 0, SEEK_CUR);
2815 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2816 != (int)sizeof(struct index_entry)*idxbuf_pos)
2818 logf("read fail #6");
2819 error = true;
2820 break ;
2822 lseek(masterfd, loc, SEEK_SET);
2825 /* Read entry headers. */
2826 for (j = 0; j < idxbuf_pos; j++)
2828 if (!TAGCACHE_IS_SORTED(index_type))
2830 struct temp_file_entry entry;
2831 struct tagfile_entry fe;
2833 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2834 sizeof(struct temp_file_entry))
2836 logf("read fail #7");
2837 error = true;
2838 break ;
2841 /* Read data. */
2842 if (entry.tag_length[index_type] >= (int)sizeof(buf))
2844 logf("too long entry!");
2845 logf("length=%d", entry.tag_length[index_type]);
2846 logf("pos=0x%02lx", lseek(tmpfd, 0, SEEK_CUR));
2847 error = true;
2848 break ;
2851 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2852 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2853 entry.tag_length[index_type])
2855 logf("read fail #8");
2856 logf("offset=0x%02lx", entry.tag_offset[index_type]);
2857 logf("length=0x%02x", entry.tag_length[index_type]);
2858 error = true;
2859 break ;
2862 /* Write to index file. */
2863 idxbuf[j].tag_seek[index_type] = lseek(fd, 0, SEEK_CUR);
2864 fe.tag_length = entry.tag_length[index_type];
2865 fe.idx_id = tcmh.tch.entry_count + i + j;
2866 ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ);
2867 write(fd, buf, fe.tag_length);
2868 tempbufidx++;
2870 /* Skip to next. */
2871 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2872 entry.tag_length[index_type], SEEK_CUR);
2874 else
2876 /* Locate the correct entry from the sorted array. */
2877 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(i + j);
2878 if (idxbuf[j].tag_seek[index_type] < 0)
2880 logf("entry not found (%d)", j);
2881 error = true;
2882 break ;
2887 /* Write index. */
2888 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2889 index_entry_ec, tc_stat.econ) !=
2890 (int)sizeof(struct index_entry)*idxbuf_pos)
2892 logf("tagcache: write fail #4");
2893 error = true;
2894 break ;
2897 do_timed_yield();
2899 logf("done");
2901 /* Finally write the header. */
2902 tch.magic = TAGCACHE_MAGIC;
2903 tch.entry_count = tempbufidx;
2904 tch.datasize = lseek(fd, 0, SEEK_END) - sizeof(struct tagcache_header);
2905 lseek(fd, 0, SEEK_SET);
2906 ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ);
2908 if (index_type != tag_filename)
2909 h->datasize += tch.datasize;
2910 logf("s:%d/%ld/%ld", index_type, tch.datasize, h->datasize);
2911 error_exit:
2913 close(fd);
2914 close(masterfd);
2916 if (error)
2917 return -2;
2919 return 1;
2922 static bool commit(void)
2924 struct tagcache_header tch;
2925 struct master_header tcmh;
2926 int i, len, rc;
2927 int tmpfd;
2928 int masterfd;
2929 #ifdef HAVE_DIRCACHE
2930 bool dircache_buffer_stolen = false;
2931 #endif
2932 #ifdef HAVE_TC_RAMCACHE
2933 bool ramcache_buffer_stolen = false;
2934 #endif
2935 bool local_allocation = false;
2937 logf("committing tagcache");
2939 while (write_lock)
2940 sleep(1);
2942 tmpfd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
2943 if (tmpfd < 0)
2945 logf("nothing to commit");
2946 return true;
2950 /* Load the header. */
2951 len = sizeof(struct tagcache_header);
2952 rc = read(tmpfd, &tch, len);
2954 if (tch.magic != TAGCACHE_MAGIC || rc != len)
2956 logf("incorrect tmpheader");
2957 close(tmpfd);
2958 remove(TAGCACHE_FILE_TEMP);
2959 return false;
2962 if (tch.entry_count == 0)
2964 logf("nothing to commit");
2965 close(tmpfd);
2966 remove(TAGCACHE_FILE_TEMP);
2967 return true;
2970 /* Fully initialize existing headers (if any) before going further. */
2971 tc_stat.ready = check_all_headers();
2973 #ifdef HAVE_EEPROM_SETTINGS
2974 remove(TAGCACHE_STATEFILE);
2975 #endif
2977 /* At first be sure to unload the ramcache! */
2978 #ifdef HAVE_TC_RAMCACHE
2979 tc_stat.ramcache = false;
2980 #endif
2982 read_lock++;
2984 /* Try to steal every buffer we can :) */
2985 if (tempbuf_size == 0)
2986 local_allocation = true;
2988 #ifdef HAVE_DIRCACHE
2989 if (tempbuf_size == 0)
2991 /* Try to steal the dircache buffer. */
2992 tempbuf = dircache_steal_buffer(&tempbuf_size);
2993 tempbuf_size &= ~0x03;
2995 if (tempbuf_size > 0)
2997 dircache_buffer_stolen = true;
3000 #endif
3002 #ifdef HAVE_TC_RAMCACHE
3003 if (tempbuf_size == 0 && tc_stat.ramcache_allocated > 0)
3005 tempbuf = (char *)(ramcache_hdr + 1);
3006 tempbuf_size = tc_stat.ramcache_allocated - sizeof(struct ramcache_header) - 128;
3007 tempbuf_size &= ~0x03;
3008 move_lock++;
3009 ramcache_buffer_stolen = true;
3011 #endif
3013 /* And finally fail if there are no buffers available. */
3014 if (tempbuf_size == 0)
3016 logf("delaying commit until next boot");
3017 tc_stat.commit_delayed = true;
3018 close(tmpfd);
3019 read_lock--;
3020 return false;
3023 logf("commit %ld entries...", tch.entry_count);
3025 /* Mark DB dirty so it will stay disabled if commit fails. */
3026 current_tcmh.dirty = true;
3027 update_master_header();
3029 /* Now create the index files. */
3030 tc_stat.commit_step = 0;
3031 tch.datasize = 0;
3032 tc_stat.commit_delayed = false;
3034 for (i = 0; i < TAG_COUNT; i++)
3036 int ret;
3038 if (TAGCACHE_IS_NUMERIC(i))
3039 continue;
3041 tc_stat.commit_step++;
3042 ret = build_index(i, &tch, tmpfd);
3043 if (ret <= 0)
3045 close(tmpfd);
3046 logf("tagcache failed init");
3047 if (ret == 0)
3048 tc_stat.commit_delayed = true;
3050 tc_stat.commit_step = 0;
3051 read_lock--;
3052 return false;
3056 if (!build_numeric_indices(&tch, tmpfd))
3058 logf("Failure to commit numeric indices");
3059 close(tmpfd);
3060 tc_stat.commit_step = 0;
3061 read_lock--;
3062 return false;
3065 close(tmpfd);
3067 tc_stat.commit_step = 0;
3069 /* Update the master index headers. */
3070 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
3072 read_lock--;
3073 return false;
3076 remove(TAGCACHE_FILE_TEMP);
3078 tcmh.tch.entry_count += tch.entry_count;
3079 tcmh.tch.datasize = sizeof(struct master_header)
3080 + sizeof(struct index_entry) * tcmh.tch.entry_count
3081 + tch.datasize;
3082 tcmh.dirty = false;
3083 tcmh.commitid++;
3085 lseek(masterfd, 0, SEEK_SET);
3086 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
3087 close(masterfd);
3089 logf("tagcache committed");
3090 tc_stat.ready = check_all_headers();
3091 tc_stat.readyvalid = true;
3093 if (local_allocation)
3095 tempbuf = NULL;
3096 tempbuf_size = 0;
3099 #ifdef HAVE_DIRCACHE
3100 /* Rebuild the dircache, if we stole the buffer. */
3101 if (dircache_buffer_stolen)
3102 dircache_resume();
3103 #endif
3105 #ifdef HAVE_TC_RAMCACHE
3106 if (ramcache_buffer_stolen)
3107 move_lock--;
3108 /* Reload tagcache. */
3109 if (tc_stat.ramcache_allocated > 0)
3110 tagcache_start_scan();
3111 #endif
3113 read_lock--;
3115 return true;
3118 static int tempbuf_handle;
3119 static void allocate_tempbuf(void)
3121 /* Yeah, malloc would be really nice now :) */
3122 #ifdef __PCTOOL__
3123 tempbuf_size = 32*1024*1024;
3124 tempbuf = malloc(tempbuf_size);
3125 #else
3126 tempbuf_handle = core_alloc_maximum("tc tempbuf", &tempbuf_size, NULL);
3127 tempbuf = core_get_data(tempbuf_handle);
3128 #endif
3131 static void free_tempbuf(void)
3133 if (tempbuf_size == 0)
3134 return ;
3136 #ifdef __PCTOOL__
3137 free(tempbuf);
3138 #else
3139 tempbuf_handle = core_free(tempbuf_handle);
3140 #endif
3141 tempbuf = NULL;
3142 tempbuf_size = 0;
3145 #ifndef __PCTOOL__
3147 static bool modify_numeric_entry(int masterfd, int idx_id, int tag, long data)
3149 struct index_entry idx;
3151 if (!tc_stat.ready)
3152 return false;
3154 if (!TAGCACHE_IS_NUMERIC(tag))
3155 return false;
3157 if (!get_index(masterfd, idx_id, &idx, false))
3158 return false;
3160 idx.tag_seek[tag] = data;
3161 idx.flag |= FLAG_DIRTYNUM;
3163 return write_index(masterfd, idx_id, &idx);
3166 #if 0
3167 bool tagcache_modify_numeric_entry(struct tagcache_search *tcs,
3168 int tag, long data)
3170 struct master_header myhdr;
3172 if (tcs->masterfd < 0)
3174 if ( (tcs->masterfd = open_master_fd(&myhdr, true)) < 0)
3175 return false;
3178 return modify_numeric_entry(tcs->masterfd, tcs->idx_id, tag, data);
3180 #endif
3182 static bool command_queue_is_full(void)
3184 int next;
3186 next = command_queue_widx + 1;
3187 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3188 next = 0;
3190 return (next == command_queue_ridx);
3193 static void command_queue_sync_callback(void *data)
3195 (void)data;
3196 struct master_header myhdr;
3197 int masterfd;
3199 mutex_lock(&command_queue_mutex);
3201 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3202 return;
3204 while (command_queue_ridx != command_queue_widx)
3206 struct tagcache_command_entry *ce = &command_queue[command_queue_ridx];
3208 switch (ce->command)
3210 case CMD_UPDATE_MASTER_HEADER:
3212 close(masterfd);
3213 update_master_header();
3215 /* Re-open the masterfd. */
3216 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3217 return;
3219 break;
3221 case CMD_UPDATE_NUMERIC:
3223 modify_numeric_entry(masterfd, ce->idx_id, ce->tag, ce->data);
3224 break;
3228 if (++command_queue_ridx >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3229 command_queue_ridx = 0;
3232 close(masterfd);
3234 tc_stat.queue_length = 0;
3235 mutex_unlock(&command_queue_mutex);
3238 static void run_command_queue(bool force)
3240 if (COMMAND_QUEUE_IS_EMPTY)
3241 return;
3243 if (force || command_queue_is_full())
3244 command_queue_sync_callback(NULL);
3245 else
3246 register_storage_idle_func(command_queue_sync_callback);
3249 static void queue_command(int cmd, long idx_id, int tag, long data)
3251 while (1)
3253 int next;
3255 mutex_lock(&command_queue_mutex);
3256 next = command_queue_widx + 1;
3257 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
3258 next = 0;
3260 /* Make sure queue is not full. */
3261 if (next != command_queue_ridx)
3263 struct tagcache_command_entry *ce = &command_queue[command_queue_widx];
3265 ce->command = cmd;
3266 ce->idx_id = idx_id;
3267 ce->tag = tag;
3268 ce->data = data;
3270 command_queue_widx = next;
3272 tc_stat.queue_length++;
3274 mutex_unlock(&command_queue_mutex);
3275 break;
3278 /* Queue is full, try again later... */
3279 mutex_unlock(&command_queue_mutex);
3280 sleep(1);
3284 long tagcache_increase_serial(void)
3286 long old;
3288 if (!tc_stat.ready)
3289 return -2;
3291 while (read_lock)
3292 sleep(1);
3294 old = current_tcmh.serial++;
3295 queue_command(CMD_UPDATE_MASTER_HEADER, 0, 0, 0);
3297 return old;
3300 void tagcache_update_numeric(int idx_id, int tag, long data)
3302 queue_command(CMD_UPDATE_NUMERIC, idx_id, tag, data);
3304 #endif /* !__PCTOOL__ */
3306 long tagcache_get_serial(void)
3308 return current_tcmh.serial;
3311 long tagcache_get_commitid(void)
3313 return current_tcmh.commitid;
3316 static bool write_tag(int fd, const char *tagstr, const char *datastr)
3318 char buf[512];
3319 int i;
3321 snprintf(buf, sizeof buf, "%s=\"", tagstr);
3322 for (i = strlen(buf); i < (long)sizeof(buf)-4; i++)
3324 if (*datastr == '\0')
3325 break;
3327 if (*datastr == '"' || *datastr == '\\')
3328 buf[i++] = '\\';
3330 else if (*datastr == '\n')
3332 buf[i++] = '\\';
3333 buf[i] = 'n';
3334 continue;
3337 buf[i] = *(datastr++);
3340 strcpy(&buf[i], "\" ");
3342 write(fd, buf, i + 2);
3344 return true;
3347 #ifndef __PCTOOL__
3349 static bool read_tag(char *dest, long size,
3350 const char *src, const char *tagstr)
3352 int pos;
3353 char current_tag[32];
3355 while (*src != '\0')
3357 /* Skip all whitespace */
3358 while (*src == ' ')
3359 src++;
3361 if (*src == '\0')
3362 break;
3364 pos = 0;
3365 /* Read in tag name */
3366 while (*src != '=' && *src != ' ')
3368 current_tag[pos] = *src;
3369 src++;
3370 pos++;
3372 if (*src == '\0' || pos >= (long)sizeof(current_tag))
3373 return false;
3375 current_tag[pos] = '\0';
3377 /* Read in tag data */
3379 /* Find the start. */
3380 while (*src != '"' && *src != '\0')
3381 src++;
3383 if (*src == '\0' || *(++src) == '\0')
3384 return false;
3386 /* Read the data. */
3387 for (pos = 0; pos < size; pos++)
3389 if (*src == '\0')
3390 break;
3392 if (*src == '\\')
3394 src++;
3395 if (*src == 'n')
3396 dest[pos] = '\n';
3397 else
3398 dest[pos] = *src;
3400 src++;
3401 continue;
3404 if (*src == '\0')
3405 break;
3407 if (*src == '"')
3409 src++;
3410 break;
3413 dest[pos] = *(src++);
3416 dest[pos] = '\0';
3418 if (!strcasecmp(tagstr, current_tag))
3419 return true;
3422 return false;
3425 static int parse_changelog_line(int line_n, char *buf, void *parameters)
3427 struct index_entry idx;
3428 char tag_data[TAG_MAXLEN+32];
3429 int idx_id;
3430 long masterfd = (long)parameters;
3431 const int import_tags[] = { tag_playcount, tag_rating, tag_playtime,
3432 tag_lastplayed, tag_commitid, tag_lastoffset };
3433 int i;
3434 (void)line_n;
3436 if (*buf == '#')
3437 return 0;
3439 /* logf("%d/%s", line_n, buf); */
3440 if (!read_tag(tag_data, sizeof tag_data, buf, "filename"))
3442 logf("%d/filename missing", line_n);
3443 logf("-> %s", buf);
3444 return 0;
3447 idx_id = find_index(tag_data);
3448 if (idx_id < 0)
3450 logf("%d/entry not found", line_n);
3451 return 0;
3454 if (!get_index(masterfd, idx_id, &idx, false))
3456 logf("%d/failed to retrieve index entry", line_n);
3457 return 0;
3460 /* Stop if tag has already been modified. */
3461 if (idx.flag & FLAG_DIRTYNUM)
3462 return 0;
3464 logf("%d/import: %s", line_n, tag_data);
3466 idx.flag |= FLAG_DIRTYNUM;
3467 for (i = 0; i < (long)(sizeof(import_tags)/sizeof(import_tags[0])); i++)
3469 int data;
3471 if (!read_tag(tag_data, sizeof tag_data, buf,
3472 tagcache_tag_to_str(import_tags[i])))
3474 continue;
3477 data = atoi(tag_data);
3478 if (data < 0)
3479 continue;
3481 idx.tag_seek[import_tags[i]] = data;
3483 if (import_tags[i] == tag_lastplayed && data >= current_tcmh.serial)
3484 current_tcmh.serial = data + 1;
3485 else if (import_tags[i] == tag_commitid && data >= current_tcmh.commitid)
3486 current_tcmh.commitid = data + 1;
3489 return write_index(masterfd, idx_id, &idx) ? 0 : -5;
3492 bool tagcache_import_changelog(void)
3494 struct master_header myhdr;
3495 struct tagcache_header tch;
3496 int clfd;
3497 long masterfd;
3498 char buf[2048];
3500 if (!tc_stat.ready)
3501 return false;
3503 while (read_lock)
3504 sleep(1);
3506 clfd = open(TAGCACHE_FILE_CHANGELOG, O_RDONLY);
3507 if (clfd < 0)
3509 logf("failure to open changelog");
3510 return false;
3513 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3515 close(clfd);
3516 return false;
3519 write_lock++;
3521 filenametag_fd = open_tag_fd(&tch, tag_filename, false);
3523 fast_readline(clfd, buf, sizeof buf, (long *)masterfd,
3524 parse_changelog_line);
3526 close(clfd);
3527 close(masterfd);
3529 if (filenametag_fd >= 0)
3531 close(filenametag_fd);
3532 filenametag_fd = -1;
3535 write_lock--;
3537 update_master_header();
3539 return true;
3542 #endif /* !__PCTOOL__ */
3544 bool tagcache_create_changelog(struct tagcache_search *tcs)
3546 struct master_header myhdr;
3547 struct index_entry idx;
3548 char buf[TAG_MAXLEN+32];
3549 char temp[32];
3550 int clfd;
3551 int i, j;
3553 if (!tc_stat.ready)
3554 return false;
3556 if (!tagcache_search(tcs, tag_filename))
3557 return false;
3559 /* Initialize the changelog */
3560 clfd = open(TAGCACHE_FILE_CHANGELOG, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3561 if (clfd < 0)
3563 logf("failure to open changelog");
3564 return false;
3567 if (tcs->masterfd < 0)
3569 if ( (tcs->masterfd = open_master_fd(&myhdr, false)) < 0)
3571 close(clfd);
3572 return false;
3575 else
3577 lseek(tcs->masterfd, 0, SEEK_SET);
3578 ecread(tcs->masterfd, &myhdr, 1, master_header_ec, tc_stat.econ);
3581 write(clfd, "## Changelog version 1\n", 23);
3583 for (i = 0; i < myhdr.tch.entry_count; i++)
3585 if (ecread_index_entry(tcs->masterfd, &idx) != sizeof(struct index_entry))
3587 logf("read error #9");
3588 tagcache_search_finish(tcs);
3589 close(clfd);
3590 return false;
3593 /* Skip until the entry found has been modified. */
3594 if (! (idx.flag & FLAG_DIRTYNUM) )
3595 continue;
3597 /* Skip deleted entries too. */
3598 if (idx.flag & FLAG_DELETED)
3599 continue;
3601 /* Now retrieve all tags. */
3602 for (j = 0; j < TAG_COUNT; j++)
3604 if (TAGCACHE_IS_NUMERIC(j))
3606 snprintf(temp, sizeof temp, "%d", (int)idx.tag_seek[j]);
3607 write_tag(clfd, tagcache_tag_to_str(j), temp);
3608 continue;
3611 tcs->type = j;
3612 tagcache_retrieve(tcs, i, tcs->type, buf, sizeof buf);
3613 write_tag(clfd, tagcache_tag_to_str(j), buf);
3616 write(clfd, "\n", 1);
3617 do_timed_yield();
3620 close(clfd);
3622 tagcache_search_finish(tcs);
3624 return true;
3627 static bool delete_entry(long idx_id)
3629 int fd = -1;
3630 int masterfd = -1;
3631 int tag, i;
3632 struct index_entry idx, myidx;
3633 struct master_header myhdr;
3634 char buf[TAG_MAXLEN+32];
3635 int in_use[TAG_COUNT];
3637 logf("delete_entry(): %ld", idx_id);
3639 #ifdef HAVE_TC_RAMCACHE
3640 /* At first mark the entry removed from ram cache. */
3641 if (tc_stat.ramcache)
3642 ramcache_hdr->indices[idx_id].flag |= FLAG_DELETED;
3643 #endif
3645 if ( (masterfd = open_master_fd(&myhdr, true) ) < 0)
3646 return false;
3648 lseek(masterfd, idx_id * sizeof(struct index_entry), SEEK_CUR);
3649 if (ecread_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3651 logf("delete_entry(): read error");
3652 goto cleanup;
3655 if (myidx.flag & FLAG_DELETED)
3657 logf("delete_entry(): already deleted!");
3658 goto cleanup;
3661 myidx.flag |= FLAG_DELETED;
3662 lseek(masterfd, -sizeof(struct index_entry), SEEK_CUR);
3663 if (ecwrite_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3665 logf("delete_entry(): write_error #1");
3666 goto cleanup;
3669 /* Now check which tags are no longer in use (if any) */
3670 for (tag = 0; tag < TAG_COUNT; tag++)
3671 in_use[tag] = 0;
3673 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
3674 for (i = 0; i < myhdr.tch.entry_count; i++)
3676 struct index_entry *idxp;
3678 #ifdef HAVE_TC_RAMCACHE
3679 /* Use RAM DB if available for greater speed */
3680 if (tc_stat.ramcache)
3681 idxp = &ramcache_hdr->indices[i];
3682 else
3683 #endif
3685 if (ecread_index_entry(masterfd, &idx) != sizeof(struct index_entry))
3687 logf("delete_entry(): read error #2");
3688 goto cleanup;
3690 idxp = &idx;
3693 if (idxp->flag & FLAG_DELETED)
3694 continue;
3696 for (tag = 0; tag < TAG_COUNT; tag++)
3698 if (TAGCACHE_IS_NUMERIC(tag))
3699 continue;
3701 if (idxp->tag_seek[tag] == myidx.tag_seek[tag])
3702 in_use[tag]++;
3706 /* Now delete all tags no longer in use. */
3707 for (tag = 0; tag < TAG_COUNT; tag++)
3709 struct tagcache_header tch;
3710 int oldseek = myidx.tag_seek[tag];
3712 if (TAGCACHE_IS_NUMERIC(tag))
3713 continue;
3715 /**
3716 * Replace tag seek with a hash value of the field string data.
3717 * That way runtime statistics of moved or altered files can be
3718 * resurrected.
3720 #ifdef HAVE_TC_RAMCACHE
3721 if (tc_stat.ramcache && tag != tag_filename)
3723 struct tagfile_entry *tfe;
3724 int32_t *seek = &ramcache_hdr->indices[idx_id].tag_seek[tag];
3726 tfe = (struct tagfile_entry *)&ramcache_hdr->tags[tag][*seek];
3727 move_lock++; /* protect tfe and seek if crc_32() yield()s */
3728 *seek = crc_32(tfe->tag_data, strlen(tfe->tag_data), 0xffffffff);
3729 move_lock--;
3730 myidx.tag_seek[tag] = *seek;
3732 else
3733 #endif
3735 struct tagfile_entry tfe;
3737 /* Open the index file, which contains the tag names. */
3738 if ((fd = open_tag_fd(&tch, tag, true)) < 0)
3739 goto cleanup;
3741 /* Skip the header block */
3742 lseek(fd, myidx.tag_seek[tag], SEEK_SET);
3743 if (ecread_tagfile_entry(fd, &tfe) != sizeof(struct tagfile_entry))
3745 logf("delete_entry(): read error #3");
3746 goto cleanup;
3749 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
3751 logf("delete_entry(): read error #4");
3752 goto cleanup;
3755 myidx.tag_seek[tag] = crc_32(buf, strlen(buf), 0xffffffff);
3758 if (in_use[tag])
3760 logf("in use: %d/%d", tag, in_use[tag]);
3761 if (fd >= 0)
3763 close(fd);
3764 fd = -1;
3766 continue;
3769 #ifdef HAVE_TC_RAMCACHE
3770 /* Delete from ram. */
3771 if (tc_stat.ramcache && tag != tag_filename)
3773 struct tagfile_entry *tagentry =
3774 (struct tagfile_entry *)&ramcache_hdr->tags[tag][oldseek];
3775 tagentry->tag_data[0] = '\0';
3777 #endif
3779 /* Open the index file, which contains the tag names. */
3780 if (fd < 0)
3782 if ((fd = open_tag_fd(&tch, tag, true)) < 0)
3783 goto cleanup;
3786 /* Skip the header block */
3787 lseek(fd, oldseek + sizeof(struct tagfile_entry), SEEK_SET);
3789 /* Debug, print 10 first characters of the tag
3790 read(fd, buf, 10);
3791 buf[10]='\0';
3792 logf("TAG:%s", buf);
3793 lseek(fd, -10, SEEK_CUR);
3796 /* Write first data byte in tag as \0 */
3797 write(fd, "", 1);
3799 /* Now tag data has been removed */
3800 close(fd);
3801 fd = -1;
3804 /* Write index entry back into master index. */
3805 lseek(masterfd, sizeof(struct master_header) +
3806 (idx_id * sizeof(struct index_entry)), SEEK_SET);
3807 if (ecwrite_index_entry(masterfd, &myidx) != sizeof(struct index_entry))
3809 logf("delete_entry(): write_error #2");
3810 goto cleanup;
3813 close(masterfd);
3815 return true;
3817 cleanup:
3818 if (fd >= 0)
3819 close(fd);
3820 if (masterfd >= 0)
3821 close(masterfd);
3823 return false;
3826 #ifndef __PCTOOL__
3828 * Returns true if there is an event waiting in the queue
3829 * that requires the current operation to be aborted.
3831 static bool check_event_queue(void)
3833 struct queue_event ev;
3835 if(!queue_peek(&tagcache_queue, &ev))
3836 return false;
3838 switch (ev.id)
3840 case Q_STOP_SCAN:
3841 case SYS_POWEROFF:
3842 case SYS_USB_CONNECTED:
3843 return true;
3846 return false;
3848 #endif
3850 #ifdef HAVE_TC_RAMCACHE
3852 static void fix_ramcache(void* old_addr, void* new_addr)
3854 ptrdiff_t offpos = new_addr - old_addr;
3855 for (int i = 0; i < TAG_COUNT; i++)
3856 ramcache_hdr->tags[i] += offpos;
3859 static int move_cb(int handle, void* current, void* new)
3861 (void)handle;
3862 if (move_lock > 0)
3863 return BUFLIB_CB_CANNOT_MOVE;
3865 fix_ramcache(current, new);
3866 ramcache_hdr = new;
3867 return BUFLIB_CB_OK;
3870 static struct buflib_callbacks ops = {
3871 .move_callback = move_cb,
3872 .shrink_callback = NULL,
3875 static bool allocate_tagcache(void)
3877 struct master_header tcmh;
3878 int fd;
3880 /* Load the header. */
3881 if ( (fd = open_master_fd(&tcmh, false)) < 0)
3883 ramcache_hdr = NULL;
3884 return false;
3887 close(fd);
3889 /**
3890 * Now calculate the required cache size plus
3891 * some extra space for alignment fixes.
3893 tc_stat.ramcache_allocated = tcmh.tch.datasize + 256 + TAGCACHE_RESERVE +
3894 sizeof(struct ramcache_header) + TAG_COUNT*sizeof(void *);
3895 int handle = core_alloc_ex("tc ramcache", tc_stat.ramcache_allocated, &ops);
3896 ramcache_hdr = core_get_data(handle);
3897 memset(ramcache_hdr, 0, sizeof(struct ramcache_header));
3898 memcpy(&current_tcmh, &tcmh, sizeof current_tcmh);
3899 logf("tagcache: %d bytes allocated.", tc_stat.ramcache_allocated);
3901 return true;
3904 # ifdef HAVE_EEPROM_SETTINGS
3905 static bool tagcache_dumpload(void)
3907 struct statefile_header shdr;
3908 int fd, rc, handle;
3910 fd = open(TAGCACHE_STATEFILE, O_RDONLY);
3911 if (fd < 0)
3913 logf("no tagcache statedump");
3914 return false;
3917 /* Check the statefile memory placement */
3918 rc = read(fd, &shdr, sizeof(struct statefile_header));
3919 if (rc != sizeof(struct statefile_header)
3920 || shdr.magic != TAGCACHE_STATEFILE_MAGIC
3921 || shdr.mh.tch.magic != TAGCACHE_MAGIC)
3923 logf("incorrect statefile");
3924 ramcache_hdr = NULL;
3925 close(fd);
3926 return false;
3930 /* Lets allocate real memory and load it */
3931 handle = core_alloc_ex("tc ramcache", shdr.tc_stat.ramcache_allocated, &ops);
3932 ramcache_hdr = core_get_data(handle);
3933 move_lock++;
3934 rc = read(fd, ramcache_hdr, shdr.tc_stat.ramcache_allocated);
3935 move_lock--;
3936 close(fd);
3938 if (rc != shdr.tc_stat.ramcache_allocated)
3940 logf("read failure!");
3941 ramcache_hdr = NULL;
3942 return false;
3945 memcpy(&tc_stat, &shdr.tc_stat, sizeof(struct tagcache_stat));
3947 /* Now fix the pointers */
3948 fix_ramcache(shdr.hdr, ramcache_hdr);
3950 /* Load the tagcache master header (should match the actual DB file header). */
3951 memcpy(&current_tcmh, &shdr.mh, sizeof current_tcmh);
3953 return true;
3956 static bool tagcache_dumpsave(void)
3958 struct statefile_header shdr;
3959 int fd;
3961 if (!tc_stat.ramcache)
3962 return false;
3964 fd = open(TAGCACHE_STATEFILE, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3965 if (fd < 0)
3967 logf("failed to create a statedump");
3968 return false;
3971 /* Create the header */
3972 shdr.magic = TAGCACHE_STATEFILE_MAGIC;
3973 shdr.hdr = ramcache_hdr;
3974 memcpy(&shdr.mh, &current_tcmh, sizeof current_tcmh);
3975 memcpy(&shdr.tc_stat, &tc_stat, sizeof tc_stat);
3976 write(fd, &shdr, sizeof shdr);
3978 /* And dump the data too */
3979 move_lock++;
3980 write(fd, ramcache_hdr, tc_stat.ramcache_allocated);
3981 move_lock--;
3982 close(fd);
3984 return true;
3986 # endif
3988 static bool load_tagcache(void)
3990 struct tagcache_header *tch;
3991 struct master_header tcmh;
3992 long bytesleft = tc_stat.ramcache_allocated - sizeof(struct ramcache_header);
3993 struct index_entry *idx;
3994 int rc, fd;
3995 char *p;
3996 int i, tag;
3998 # ifdef HAVE_DIRCACHE
3999 while (dircache_is_initializing())
4000 sleep(1);
4002 dircache_set_appflag(DIRCACHE_APPFLAG_TAGCACHE);
4003 # endif
4005 logf("loading tagcache to ram...");
4007 fd = open(TAGCACHE_FILE_MASTER, O_RDONLY);
4008 if (fd < 0)
4010 logf("tagcache open failed");
4011 return false;
4014 if (ecread(fd, &tcmh, 1, master_header_ec, tc_stat.econ)
4015 != sizeof(struct master_header)
4016 || tcmh.tch.magic != TAGCACHE_MAGIC)
4018 logf("incorrect header");
4019 return false;
4022 /* Master header copy should already match, this can be redundant to do. */
4023 memcpy(&current_tcmh, &tcmh, sizeof current_tcmh);
4025 move_lock++; /* lock for the reset of the scan, simpler to handle */
4026 idx = ramcache_hdr->indices;
4028 /* Load the master index table. */
4029 for (i = 0; i < tcmh.tch.entry_count; i++)
4031 bytesleft -= sizeof(struct index_entry);
4032 if (bytesleft < 0)
4034 logf("too big tagcache.");
4035 goto failure;
4038 /* DEBUG: After tagcache commit and dircache rebuild, hdr-sturcture
4039 * may become corrupt. */
4040 rc = ecread_index_entry(fd, idx);
4041 if (rc != sizeof(struct index_entry))
4043 logf("read error #10");
4044 goto failure;
4047 idx++;
4050 close(fd);
4052 /* Load the tags. */
4053 p = (char *)idx;
4054 for (tag = 0; tag < TAG_COUNT; tag++)
4056 struct tagfile_entry *fe;
4057 char buf[TAG_MAXLEN+32];
4059 if (TAGCACHE_IS_NUMERIC(tag))
4060 continue ;
4062 //p = ((void *)p+1);
4063 p = (char *)((long)p & ~0x03) + 0x04;
4064 ramcache_hdr->tags[tag] = p;
4066 /* Check the header. */
4067 tch = (struct tagcache_header *)p;
4068 p += sizeof(struct tagcache_header);
4070 if ( (fd = open_tag_fd(tch, tag, false)) < 0)
4071 goto failure_nofd;
4073 for (ramcache_hdr->entry_count[tag] = 0;
4074 ramcache_hdr->entry_count[tag] < tch->entry_count;
4075 ramcache_hdr->entry_count[tag]++)
4077 long pos;
4079 if (do_timed_yield())
4081 /* Abort if we got a critical event in queue */
4082 if (check_event_queue())
4083 goto failure;
4086 fe = (struct tagfile_entry *)p;
4087 pos = lseek(fd, 0, SEEK_CUR);
4088 rc = ecread_tagfile_entry(fd, fe);
4089 if (rc != sizeof(struct tagfile_entry))
4091 /* End of lookup table. */
4092 logf("read error #11");
4093 goto failure;
4096 /* We have a special handling for the filename tags. */
4097 if (tag == tag_filename)
4099 # ifdef HAVE_DIRCACHE
4100 int dc;
4101 # endif
4103 idx = &ramcache_hdr->indices[fe->idx_id];
4105 if (fe->tag_length >= (long)sizeof(buf)-1)
4107 read(fd, buf, 10);
4108 buf[10] = '\0';
4109 logf("TAG:%s", buf);
4110 logf("too long filename");
4111 goto failure;
4114 rc = read(fd, buf, fe->tag_length);
4115 if (rc != fe->tag_length)
4117 logf("read error #12");
4118 goto failure;
4121 /* Check if the entry has already been removed */
4122 if (idx->flag & FLAG_DELETED)
4123 continue;
4125 /* This flag must not be used yet. */
4126 if (idx->flag & FLAG_DIRCACHE)
4128 logf("internal error!");
4129 goto failure;
4132 if (idx->tag_seek[tag] != pos)
4134 logf("corrupt data structures!");
4135 goto failure;
4138 # ifdef HAVE_DIRCACHE
4139 if (dircache_is_enabled())
4141 dc = dircache_get_entry_id(buf);
4142 if (dc < 0)
4144 logf("Entry no longer valid.");
4145 logf("-> %s", buf);
4146 if (global_settings.tagcache_autoupdate)
4147 delete_entry(fe->idx_id);
4148 continue ;
4151 idx->flag |= FLAG_DIRCACHE;
4152 idx->tag_seek[tag_filename] = dc;
4154 else
4155 # endif
4157 /* This will be very slow unless dircache is enabled
4158 or target is flash based, but do it anyway for
4159 consistency. */
4160 /* Check if entry has been removed. */
4161 if (global_settings.tagcache_autoupdate)
4163 if (!file_exists(buf))
4165 logf("Entry no longer valid.");
4166 logf("-> %s", buf);
4167 delete_entry(fe->idx_id);
4168 continue;
4173 continue ;
4176 bytesleft -= sizeof(struct tagfile_entry) + fe->tag_length;
4177 if (bytesleft < 0)
4179 logf("too big tagcache #2");
4180 logf("tl: %ld", fe->tag_length);
4181 logf("bl: %ld", bytesleft);
4182 goto failure;
4185 p = fe->tag_data;
4186 rc = read(fd, fe->tag_data, fe->tag_length);
4187 p += rc;
4189 if (rc != fe->tag_length)
4191 logf("read error #13");
4192 logf("rc=0x%04x", rc); // 0x431
4193 logf("len=0x%04lx", fe->tag_length); // 0x4000
4194 logf("pos=0x%04lx", lseek(fd, 0, SEEK_CUR)); // 0x433
4195 logf("tag=0x%02x", tag); // 0x00
4196 goto failure;
4199 close(fd);
4202 tc_stat.ramcache_used = tc_stat.ramcache_allocated - bytesleft;
4203 logf("tagcache loaded into ram!");
4205 move_lock--;
4206 return true;
4208 failure:
4209 close(fd);
4210 failure_nofd:
4211 move_lock--;
4212 return false;
4214 #endif /* HAVE_TC_RAMCACHE */
4216 static bool check_deleted_files(void)
4218 int fd;
4219 char buf[TAG_MAXLEN+32];
4220 struct tagfile_entry tfe;
4222 logf("reverse scan...");
4223 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag_filename);
4224 fd = open(buf, O_RDONLY);
4226 if (fd < 0)
4228 logf("%s open fail", buf);
4229 return false;
4232 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
4233 while (ecread_tagfile_entry(fd, &tfe) == sizeof(struct tagfile_entry)
4234 #ifndef __PCTOOL__
4235 && !check_event_queue()
4236 #endif
4239 if (tfe.tag_length >= (long)sizeof(buf)-1)
4241 logf("too long tag");
4242 close(fd);
4243 return false;
4246 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
4248 logf("read error #14");
4249 close(fd);
4250 return false;
4253 /* Check if the file has already deleted from the db. */
4254 if (*buf == '\0')
4255 continue;
4257 /* Now check if the file exists. */
4258 if (!file_exists(buf))
4260 logf("Entry no longer valid.");
4261 logf("-> %s / %ld", buf, tfe.tag_length);
4262 delete_entry(tfe.idx_id);
4266 close(fd);
4268 logf("done");
4270 return true;
4274 /* Note that this function must not be inlined, otherwise the whole point
4275 * of having the code in a separate function is lost.
4277 static void __attribute__ ((noinline)) check_ignore(const char *dirname,
4278 int *ignore, int *unignore)
4280 char newpath[MAX_PATH];
4282 /* check for a database.ignore file */
4283 snprintf(newpath, MAX_PATH, "%s/database.ignore", dirname);
4284 *ignore = file_exists(newpath);
4285 /* check for a database.unignore file */
4286 snprintf(newpath, MAX_PATH, "%s/database.unignore", dirname);
4287 *unignore = file_exists(newpath);
4290 static struct search_roots_ll {
4291 const char *path;
4292 struct search_roots_ll * next;
4293 } roots_ll;
4295 #ifdef APPLICATION
4297 * This adds a path to the search roots, possibly during traveling through
4298 * the filesystem. It only adds if the path is not inside an already existing
4299 * search root.
4301 * Returns true if it added the path to the search roots
4303 * Windows 2000 and greater supports symlinks, but they don't provide
4304 * realpath() or readlink(), and symlinks are rarely used on them so
4305 * ignore this for windows for now
4307 static bool add_search_root(const char *name)
4309 (void)name;
4310 #ifndef WIN32
4311 struct search_roots_ll *this, *prev = NULL;
4312 char target[MAX_PATH];
4313 /* Okay, realpath() is almost completely broken on android
4315 * It doesn't accept NULL for resolved_name to dynamically allocate
4316 * the resulting path; and it assumes resolved_name to be PATH_MAX
4317 * (actually MAXPATHLEN, but it's the same [as of 2.3]) long
4318 * and blindly writes to the end if it
4320 * therefore use sufficiently large static storage here
4321 * Note that PATH_MAX != MAX_PATH
4323 static char abs_target[PATH_MAX];
4324 ssize_t len;
4326 len = readlink(name, target, sizeof(target));
4327 if (len < 0)
4328 return false;
4330 target[len] = '\0';
4331 if (realpath(target, abs_target) == NULL)
4332 return false;
4334 for(this = &roots_ll; this; prev = this, this = this->next)
4336 size_t root_len = strlen(this->path);
4337 /* check if the link target is inside of an existing search root
4338 * don't add if target is inside, we'll scan it later */
4339 if (!strncmp(this->path, abs_target, root_len))
4340 return false;
4343 if (prev)
4345 size_t len = strlen(abs_target) + 1; /* count \0 */
4346 this = malloc(sizeof(struct search_roots_ll) + len );
4347 if (!this || len > MAX_PATH)
4349 logf("Error at adding a search root: %s", this ? "path too long":"OOM");
4350 free(this);
4351 prev->next = NULL;
4352 return false;
4354 this->path = ((char*)this) + sizeof(struct search_roots_ll);
4355 strcpy((char*)this->path, abs_target); /* ok to cast const away here */
4356 this->next = NULL;
4357 prev->next = this;
4358 logf("Added %s to the search roots\n", abs_target);
4359 return true;
4361 #endif
4362 return false;
4365 static int free_search_roots(struct search_roots_ll * start)
4367 int ret = 0;
4368 if (start->next)
4370 ret += free_search_roots(start->next);
4371 ret += sizeof(struct search_roots_ll);
4372 free(start->next);
4374 return ret;
4376 #else /* native, simulator */
4377 #define add_search_root(a) do {} while(0)
4378 #define free_search_roots(a) do {} while(0)
4379 #endif
4381 static bool check_dir(const char *dirname, int add_files)
4383 DIR *dir;
4384 int len;
4385 int success = false;
4386 int ignore, unignore;
4388 dir = opendir(dirname);
4389 if (!dir)
4391 logf("tagcache: opendir(%s) failed", dirname);
4392 return false;
4394 /* check for a database.ignore and database.unignore */
4395 check_ignore(dirname, &ignore, &unignore);
4397 /* don't do anything if both ignore and unignore are there */
4398 if (ignore != unignore)
4399 add_files = unignore;
4401 /* Recursively scan the dir. */
4402 #ifdef __PCTOOL__
4403 while (1)
4404 #else
4405 while (!check_event_queue())
4406 #endif
4408 struct dirent *entry = readdir(dir);
4409 if (entry == NULL)
4411 success = true;
4412 break;
4415 if (!strcmp((char *)entry->d_name, ".") ||
4416 !strcmp((char *)entry->d_name, ".."))
4417 continue;
4419 struct dirinfo info = dir_get_info(dir, entry);
4421 yield();
4423 len = strlen(curpath);
4424 /* don't add an extra / for curpath == / */
4425 if (len <= 1) len = 0;
4426 snprintf(&curpath[len], sizeof(curpath) - len, "/%s", entry->d_name);
4428 processed_dir_count++;
4429 if (info.attribute & ATTR_DIRECTORY)
4430 #ifndef SIMULATOR
4431 { /* don't follow symlinks to dirs, but try to add it as a search root
4432 * this makes able to avoid looping in recursive symlinks */
4433 if (info.attribute & ATTR_LINK)
4434 add_search_root(curpath);
4435 else
4436 check_dir(curpath, add_files);
4438 #else
4439 check_dir(curpath, add_files);
4440 #endif
4441 else if (add_files)
4443 tc_stat.curentry = curpath;
4445 /* Add a new entry to the temporary db file. */
4446 add_tagcache(curpath, (info.wrtdate << 16) | info.wrttime
4447 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
4448 , dir->internal_entry
4449 #endif
4452 /* Wait until current path for debug screen is read and unset. */
4453 while (tc_stat.syncscreen && tc_stat.curentry != NULL)
4454 yield();
4456 tc_stat.curentry = NULL;
4459 curpath[len] = '\0';
4462 closedir(dir);
4464 return success;
4467 void tagcache_screensync_event(void)
4469 tc_stat.curentry = NULL;
4472 void tagcache_screensync_enable(bool state)
4474 tc_stat.syncscreen = state;
4477 void tagcache_build(const char *path)
4479 struct tagcache_header header;
4480 bool ret;
4482 curpath[0] = '\0';
4483 data_size = 0;
4484 total_entry_count = 0;
4485 processed_dir_count = 0;
4487 #ifdef HAVE_DIRCACHE
4488 while (dircache_is_initializing())
4489 sleep(1);
4490 #endif
4492 logf("updating tagcache");
4494 cachefd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
4495 if (cachefd >= 0)
4497 logf("skipping, cache already waiting for commit");
4498 close(cachefd);
4499 return ;
4502 cachefd = open(TAGCACHE_FILE_TEMP, O_RDWR | O_CREAT | O_TRUNC, 0666);
4503 if (cachefd < 0)
4505 logf("master file open failed: %s", TAGCACHE_FILE_TEMP);
4506 return ;
4509 filenametag_fd = open_tag_fd(&header, tag_filename, false);
4511 cpu_boost(true);
4513 logf("Scanning files...");
4514 /* Scan for new files. */
4515 memset(&header, 0, sizeof(struct tagcache_header));
4516 write(cachefd, &header, sizeof(struct tagcache_header));
4518 ret = true;
4519 roots_ll.path = path;
4520 roots_ll.next = NULL;
4521 struct search_roots_ll * this;
4522 /* check_dir might add new roots */
4523 for(this = &roots_ll; this; this = this->next)
4525 strcpy(curpath, this->path);
4526 ret = ret && check_dir(this->path, true);
4528 if (roots_ll.next)
4529 free_search_roots(roots_ll.next);
4531 /* Write the header. */
4532 header.magic = TAGCACHE_MAGIC;
4533 header.datasize = data_size;
4534 header.entry_count = total_entry_count;
4535 lseek(cachefd, 0, SEEK_SET);
4536 write(cachefd, &header, sizeof(struct tagcache_header));
4537 close(cachefd);
4539 if (filenametag_fd >= 0)
4541 close(filenametag_fd);
4542 filenametag_fd = -1;
4545 if (!ret)
4547 logf("Aborted.");
4548 cpu_boost(false);
4549 return ;
4552 /* Commit changes to the database. */
4553 #ifdef __PCTOOL__
4554 allocate_tempbuf();
4555 #endif
4556 if (commit())
4558 logf("tagcache built!");
4560 #ifdef __PCTOOL__
4561 free_tempbuf();
4562 #endif
4564 #ifdef HAVE_TC_RAMCACHE
4565 if (ramcache_hdr)
4567 /* Import runtime statistics if we just initialized the db. */
4568 if (current_tcmh.serial == 0)
4569 queue_post(&tagcache_queue, Q_IMPORT_CHANGELOG, 0);
4571 #endif
4573 cpu_boost(false);
4576 #ifdef HAVE_TC_RAMCACHE
4577 static void load_ramcache(void)
4579 if (!ramcache_hdr)
4580 return ;
4582 cpu_boost(true);
4584 /* At first we should load the cache (if exists). */
4585 tc_stat.ramcache = load_tagcache();
4587 if (!tc_stat.ramcache)
4589 /* If loading failed, it must indicate some problem with the db
4590 * so disable it entirely to prevent further issues. */
4591 tc_stat.ready = false;
4592 ramcache_hdr = NULL;
4595 cpu_boost(false);
4598 void tagcache_unload_ramcache(void)
4600 tc_stat.ramcache = false;
4601 /* Just to make sure there is no statefile present. */
4602 // remove(TAGCACHE_STATEFILE);
4604 #endif
4606 #ifndef __PCTOOL__
4607 static void tagcache_thread(void)
4609 struct queue_event ev;
4610 bool check_done = false;
4612 /* If the previous cache build/update was interrupted, commit
4613 * the changes first in foreground. */
4614 cpu_boost(true);
4615 allocate_tempbuf();
4616 commit();
4617 free_tempbuf();
4619 #ifdef HAVE_TC_RAMCACHE
4620 # ifdef HAVE_EEPROM_SETTINGS
4621 if (firmware_settings.initialized && firmware_settings.disk_clean
4622 && global_settings.tagcache_ram)
4624 check_done = tagcache_dumpload();
4627 remove(TAGCACHE_STATEFILE);
4628 # endif
4630 /* Allocate space for the tagcache if found on disk. */
4631 if (global_settings.tagcache_ram && !tc_stat.ramcache)
4632 allocate_tagcache();
4633 #endif
4635 cpu_boost(false);
4636 tc_stat.initialized = true;
4638 /* Don't delay bootup with the header check but do it on background. */
4639 if (!tc_stat.ready)
4641 sleep(HZ);
4642 tc_stat.ready = check_all_headers();
4643 tc_stat.readyvalid = true;
4646 while (1)
4648 run_command_queue(false);
4650 queue_wait_w_tmo(&tagcache_queue, &ev, HZ);
4652 switch (ev.id)
4654 case Q_IMPORT_CHANGELOG:
4655 tagcache_import_changelog();
4656 break;
4658 case Q_REBUILD:
4659 remove_files();
4660 remove(TAGCACHE_FILE_TEMP);
4661 tagcache_build("/");
4662 break;
4664 case Q_UPDATE:
4665 tagcache_build("/");
4666 #ifdef HAVE_TC_RAMCACHE
4667 load_ramcache();
4668 #endif
4669 check_deleted_files();
4670 break ;
4672 case Q_START_SCAN:
4673 check_done = false;
4674 case SYS_TIMEOUT:
4675 if (check_done || !tc_stat.ready)
4676 break ;
4678 #ifdef HAVE_TC_RAMCACHE
4679 if (!tc_stat.ramcache && global_settings.tagcache_ram)
4681 load_ramcache();
4682 if (tc_stat.ramcache && global_settings.tagcache_autoupdate)
4683 tagcache_build("/");
4685 else
4686 #endif
4687 if (global_settings.tagcache_autoupdate)
4689 tagcache_build("/");
4691 /* This will be very slow unless dircache is enabled
4692 or target is flash based, but do it anyway for
4693 consistency. */
4694 check_deleted_files();
4697 logf("tagcache check done");
4699 check_done = true;
4700 break ;
4702 case Q_STOP_SCAN:
4703 break ;
4705 case SYS_POWEROFF:
4706 break ;
4708 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
4709 case SYS_USB_CONNECTED:
4710 logf("USB: TagCache");
4711 usb_acknowledge(SYS_USB_CONNECTED_ACK);
4712 usb_wait_for_disconnect(&tagcache_queue);
4713 break ;
4714 #endif
4719 bool tagcache_prepare_shutdown(void)
4721 if (tagcache_get_commit_step() > 0)
4722 return false;
4724 tagcache_stop_scan();
4725 while (read_lock || write_lock)
4726 sleep(1);
4728 return true;
4731 void tagcache_shutdown(void)
4733 /* Flush the command queue. */
4734 run_command_queue(true);
4736 #ifdef HAVE_EEPROM_SETTINGS
4737 if (tc_stat.ramcache)
4738 tagcache_dumpsave();
4739 #endif
4742 static int get_progress(void)
4744 int total_count = -1;
4746 #ifdef HAVE_DIRCACHE
4747 if (dircache_is_enabled())
4749 total_count = dircache_get_entry_count();
4751 else
4752 #endif
4753 #ifdef HAVE_TC_RAMCACHE
4755 if (ramcache_hdr && tc_stat.ramcache)
4756 total_count = current_tcmh.tch.entry_count;
4758 #endif
4760 if (total_count < 0)
4761 return -1;
4763 return processed_dir_count * 100 / total_count;
4766 struct tagcache_stat* tagcache_get_stat(void)
4768 tc_stat.progress = get_progress();
4769 tc_stat.processed_entries = processed_dir_count;
4771 return &tc_stat;
4774 void tagcache_start_scan(void)
4776 queue_post(&tagcache_queue, Q_START_SCAN, 0);
4779 bool tagcache_update(void)
4781 if (!tc_stat.ready)
4782 return false;
4784 queue_post(&tagcache_queue, Q_UPDATE, 0);
4785 return false;
4788 bool tagcache_rebuild()
4790 queue_post(&tagcache_queue, Q_REBUILD, 0);
4791 return false;
4794 void tagcache_stop_scan(void)
4796 queue_post(&tagcache_queue, Q_STOP_SCAN, 0);
4799 #ifdef HAVE_TC_RAMCACHE
4800 bool tagcache_is_ramcache(void)
4802 return tc_stat.ramcache;
4804 #endif
4806 #endif /* !__PCTOOL__ */
4809 void tagcache_init(void)
4811 memset(&tc_stat, 0, sizeof(struct tagcache_stat));
4812 memset(&current_tcmh, 0, sizeof(struct master_header));
4813 filenametag_fd = -1;
4814 write_lock = read_lock = 0;
4816 #ifndef __PCTOOL__
4817 mutex_init(&command_queue_mutex);
4818 queue_init(&tagcache_queue, true);
4819 create_thread(tagcache_thread, tagcache_stack,
4820 sizeof(tagcache_stack), 0, tagcache_thread_name
4821 IF_PRIO(, PRIORITY_BACKGROUND)
4822 IF_COP(, CPU));
4823 #else
4824 tc_stat.initialized = true;
4825 allocate_tempbuf();
4826 commit();
4827 free_tempbuf();
4828 tc_stat.ready = check_all_headers();
4829 #endif
4832 #ifdef __PCTOOL__
4833 void tagcache_reverse_scan(void)
4835 logf("Checking for deleted files");
4836 check_deleted_files();
4838 #endif
4840 bool tagcache_is_initialized(void)
4842 return tc_stat.initialized;
4844 bool tagcache_is_fully_initialized(void)
4846 return tc_stat.readyvalid;
4848 bool tagcache_is_usable(void)
4850 return tc_stat.initialized && tc_stat.ready;
4852 int tagcache_get_commit_step(void)
4854 return tc_stat.commit_step;
4856 int tagcache_get_max_commit_step(void)
4858 return (int)(SORTED_TAGS_COUNT)+1;