2 * The PCI Library -- ID to Name Cache
4 * Copyright (c) 2008 Martin Mares <mj@ucw.cz>
6 * Can be freely distributed and used under the terms of the GNU GPL.
13 #include <sys/types.h>
20 static const char cache_version[] = "#PCI-CACHE-1.0";
23 pci_id_cache_load(struct pci_access *a, int flags)
27 const char default_name[] = "/.pciids-cache";
31 a->id_cache_status = 1;
32 if (!a->id_cache_file)
34 /* Construct the default ID cache name */
36 struct passwd *pw = getpwuid(uid);
39 name = pci_malloc(a, strlen(pw->pw_dir) + sizeof(default_name));
40 sprintf(name, "%s%s", pw->pw_dir, default_name);
41 pci_set_id_cache(a, name, 1);
43 a->debug("Using cache %s\n", a->id_cache_file);
44 if (flags & PCI_LOOKUP_REFRESH_CACHE)
46 a->debug("Not loading cache, will refresh everything\n");
47 a->id_cache_status = 2;
51 f = fopen(a->id_cache_file, "rb");
54 a->debug("Cache file does not exist\n");
57 /* FIXME: Compare timestamp with the pci.ids file? */
60 while (fgets(line, sizeof(line), f))
62 char *p = strchr(line, '\n');
69 if (strcmp(line, cache_version))
71 a->debug("Unrecognized cache version %s, ignoring\n", line);
78 int cat, id1, id2, id3, id4, cnt;
79 if (sscanf(line, "%d%x%x%x%x%n", &cat, &id1, &id2, &id3, &id4, &cnt) >= 5)
82 while (*p && *p == ' ')
84 pci_id_insert(a, cat, id1, id2, id3, id4, p, SRC_CACHE);
89 a->warning("Malformed cache file %s (line %d), ignoring", a->id_cache_file, lino);
94 a->warning("Error while reading %s", a->id_cache_file);
100 pci_id_cache_dirty(struct pci_access *a)
102 if (a->id_cache_status >= 1)
103 a->id_cache_status = 2;
107 pci_id_cache_flush(struct pci_access *a)
109 int orig_status = a->id_cache_status;
112 struct id_entry *e, *e2;
114 a->id_cache_status = 0;
117 if (!a->id_cache_file)
119 f = fopen(a->id_cache_file, "wb");
122 a->warning("Cannot write %s: %s", a->id_cache_file, strerror(errno));
125 a->debug("Writing cache to %s\n", a->id_cache_file);
126 fprintf(f, "%s\n", cache_version);
128 for (h=0; h<HASH_SIZE; h++)
129 for (e=a->id_hash[h]; e; e=e->next)
130 if (e->src == SRC_CACHE || e->src == SRC_NET)
132 /* Verify that every entry is written at most once */
133 for (e2=a->id_hash[h]; e2 != e; e2=e2->next)
134 if ((e2->src == SRC_CACHE || e2->src == SRC_NET) &&
136 e2->id12 == e->id12 && e2->id34 == e->id34)
139 fprintf(f, "%d %x %x %x %x %s\n",
141 pair_first(e->id12), pair_second(e->id12),
142 pair_first(e->id34), pair_second(e->id34),
148 a->warning("Error writing %s", a->id_cache_file);
153 pci_set_id_cache(struct pci_access *a, char *name, int to_be_freed)
155 if (a->free_id_cache_file)
156 free(a->id_cache_file);
157 a->id_cache_file = name;
158 a->free_id_cache_file = to_be_freed;