disk_cache: assert if a cache entries keys don't match mesa
[mesa.git] / src / util / disk_cache.c
1 /*
2 * Copyright © 2014 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #ifdef ENABLE_SHADER_CACHE
25
26 #include <ctype.h>
27 #include <ftw.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <sys/file.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/mman.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <errno.h>
39 #include <dirent.h>
40 #include "zlib.h"
41
42 #include "util/crc32.h"
43 #include "util/rand_xor.h"
44 #include "util/u_atomic.h"
45 #include "util/u_queue.h"
46 #include "util/mesa-sha1.h"
47 #include "util/ralloc.h"
48 #include "main/errors.h"
49
50 #include "disk_cache.h"
51
52 /* Number of bits to mask off from a cache key to get an index. */
53 #define CACHE_INDEX_KEY_BITS 16
54
55 /* Mask for computing an index from a key. */
56 #define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
57
58 /* The number of keys that can be stored in the index. */
59 #define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
60
61 /* The cache version should be bumped whenever a change is made to the
62 * structure of cache entries or the index. This will give any 3rd party
63 * applications reading the cache entries a chance to adjust to the changes.
64 *
65 * - The cache version is checked internally when reading a cache entry. If we
66 * ever have a mismatch we are in big trouble as this means we had a cache
67 * collision. In case of such an event please check the skys for giant
68 * asteroids and that the entire Mesa team hasn't been eaten by wolves.
69 *
70 * - There is no strict requirement that cache versions be backwards
71 * compatible but effort should be taken to limit disruption where possible.
72 */
73 #define CACHE_VERSION 1
74
75 struct disk_cache {
76 /* The path to the cache directory. */
77 char *path;
78
79 /* Thread queue for compressing and writing cache entries to disk */
80 struct util_queue cache_queue;
81
82 /* Seed for rand, which is used to pick a random directory */
83 uint64_t seed_xorshift128plus[2];
84
85 /* A pointer to the mmapped index file within the cache directory. */
86 uint8_t *index_mmap;
87 size_t index_mmap_size;
88
89 /* Pointer to total size of all objects in cache (within index_mmap) */
90 uint64_t *size;
91
92 /* Pointer to stored keys, (within index_mmap). */
93 uint8_t *stored_keys;
94
95 /* Maximum size of all cached objects (in bytes). */
96 uint64_t max_size;
97
98 /* Driver cache keys. */
99 uint8_t *driver_keys_blob;
100 size_t driver_keys_blob_size;
101 };
102
103 struct disk_cache_put_job {
104 struct util_queue_fence fence;
105
106 struct disk_cache *cache;
107
108 cache_key key;
109
110 /* Copy of cache data to be compressed and written. */
111 void *data;
112
113 /* Size of data to be compressed and written. */
114 size_t size;
115
116 struct cache_item_metadata cache_item_metadata;
117 };
118
119 /* Create a directory named 'path' if it does not already exist.
120 *
121 * Returns: 0 if path already exists as a directory or if created.
122 * -1 in all other cases.
123 */
124 static int
125 mkdir_if_needed(const char *path)
126 {
127 struct stat sb;
128
129 /* If the path exists already, then our work is done if it's a
130 * directory, but it's an error if it is not.
131 */
132 if (stat(path, &sb) == 0) {
133 if (S_ISDIR(sb.st_mode)) {
134 return 0;
135 } else {
136 fprintf(stderr, "Cannot use %s for shader cache (not a directory)"
137 "---disabling.\n", path);
138 return -1;
139 }
140 }
141
142 int ret = mkdir(path, 0755);
143 if (ret == 0 || (ret == -1 && errno == EEXIST))
144 return 0;
145
146 fprintf(stderr, "Failed to create %s for shader cache (%s)---disabling.\n",
147 path, strerror(errno));
148
149 return -1;
150 }
151
152 /* Concatenate an existing path and a new name to form a new path. If the new
153 * path does not exist as a directory, create it then return the resulting
154 * name of the new path (ralloc'ed off of 'ctx').
155 *
156 * Returns NULL on any error, such as:
157 *
158 * <path> does not exist or is not a directory
159 * <path>/<name> exists but is not a directory
160 * <path>/<name> cannot be created as a directory
161 */
162 static char *
163 concatenate_and_mkdir(void *ctx, const char *path, const char *name)
164 {
165 char *new_path;
166 struct stat sb;
167
168 if (stat(path, &sb) != 0 || ! S_ISDIR(sb.st_mode))
169 return NULL;
170
171 new_path = ralloc_asprintf(ctx, "%s/%s", path, name);
172
173 if (mkdir_if_needed(new_path) == 0)
174 return new_path;
175 else
176 return NULL;
177 }
178
179 #define DRV_KEY_CPY(_dst, _src, _src_size) \
180 do { \
181 memcpy(_dst, _src, _src_size); \
182 _dst += _src_size; \
183 } while (0);
184
185 struct disk_cache *
186 disk_cache_create(const char *gpu_name, const char *timestamp,
187 uint64_t driver_flags)
188 {
189 void *local;
190 struct disk_cache *cache = NULL;
191 char *path, *max_size_str;
192 uint64_t max_size;
193 int fd = -1;
194 struct stat sb;
195 size_t size;
196
197 /* If running as a users other than the real user disable cache */
198 if (geteuid() != getuid())
199 return NULL;
200
201 /* A ralloc context for transient data during this invocation. */
202 local = ralloc_context(NULL);
203 if (local == NULL)
204 goto fail;
205
206 /* At user request, disable shader cache entirely. */
207 if (getenv("MESA_GLSL_CACHE_DISABLE"))
208 goto fail;
209
210 /* Determine path for cache based on the first defined name as follows:
211 *
212 * $MESA_GLSL_CACHE_DIR
213 * $XDG_CACHE_HOME/mesa_shader_cache
214 * <pwd.pw_dir>/.cache/mesa_shader_cache
215 */
216 path = getenv("MESA_GLSL_CACHE_DIR");
217 if (path) {
218 if (mkdir_if_needed(path) == -1)
219 goto fail;
220
221 path = concatenate_and_mkdir(local, path, CACHE_DIR_NAME);
222 if (path == NULL)
223 goto fail;
224 }
225
226 if (path == NULL) {
227 char *xdg_cache_home = getenv("XDG_CACHE_HOME");
228
229 if (xdg_cache_home) {
230 if (mkdir_if_needed(xdg_cache_home) == -1)
231 goto fail;
232
233 path = concatenate_and_mkdir(local, xdg_cache_home, CACHE_DIR_NAME);
234 if (path == NULL)
235 goto fail;
236 }
237 }
238
239 if (path == NULL) {
240 char *buf;
241 size_t buf_size;
242 struct passwd pwd, *result;
243
244 buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
245 if (buf_size == -1)
246 buf_size = 512;
247
248 /* Loop until buf_size is large enough to query the directory */
249 while (1) {
250 buf = ralloc_size(local, buf_size);
251
252 getpwuid_r(getuid(), &pwd, buf, buf_size, &result);
253 if (result)
254 break;
255
256 if (errno == ERANGE) {
257 ralloc_free(buf);
258 buf = NULL;
259 buf_size *= 2;
260 } else {
261 goto fail;
262 }
263 }
264
265 path = concatenate_and_mkdir(local, pwd.pw_dir, ".cache");
266 if (path == NULL)
267 goto fail;
268
269 path = concatenate_and_mkdir(local, path, CACHE_DIR_NAME);
270 if (path == NULL)
271 goto fail;
272 }
273
274 cache = ralloc(NULL, struct disk_cache);
275 if (cache == NULL)
276 goto fail;
277
278 cache->path = ralloc_strdup(cache, path);
279 if (cache->path == NULL)
280 goto fail;
281
282 path = ralloc_asprintf(local, "%s/index", cache->path);
283 if (path == NULL)
284 goto fail;
285
286 fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
287 if (fd == -1)
288 goto fail;
289
290 if (fstat(fd, &sb) == -1)
291 goto fail;
292
293 /* Force the index file to be the expected size. */
294 size = sizeof(*cache->size) + CACHE_INDEX_MAX_KEYS * CACHE_KEY_SIZE;
295 if (sb.st_size != size) {
296 if (ftruncate(fd, size) == -1)
297 goto fail;
298 }
299
300 /* We map this shared so that other processes see updates that we
301 * make.
302 *
303 * Note: We do use atomic addition to ensure that multiple
304 * processes don't scramble the cache size recorded in the
305 * index. But we don't use any locking to prevent multiple
306 * processes from updating the same entry simultaneously. The idea
307 * is that if either result lands entirely in the index, then
308 * that's equivalent to a well-ordered write followed by an
309 * eviction and a write. On the other hand, if the simultaneous
310 * writes result in a corrupt entry, that's not really any
311 * different than both entries being evicted, (since within the
312 * guarantees of the cryptographic hash, a corrupt entry is
313 * unlikely to ever match a real cache key).
314 */
315 cache->index_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE,
316 MAP_SHARED, fd, 0);
317 if (cache->index_mmap == MAP_FAILED)
318 goto fail;
319 cache->index_mmap_size = size;
320
321 close(fd);
322
323 cache->size = (uint64_t *) cache->index_mmap;
324 cache->stored_keys = cache->index_mmap + sizeof(uint64_t);
325
326 max_size = 0;
327
328 max_size_str = getenv("MESA_GLSL_CACHE_MAX_SIZE");
329 if (max_size_str) {
330 char *end;
331 max_size = strtoul(max_size_str, &end, 10);
332 if (end == max_size_str) {
333 max_size = 0;
334 } else {
335 switch (*end) {
336 case 'K':
337 case 'k':
338 max_size *= 1024;
339 break;
340 case 'M':
341 case 'm':
342 max_size *= 1024*1024;
343 break;
344 case '\0':
345 case 'G':
346 case 'g':
347 default:
348 max_size *= 1024*1024*1024;
349 break;
350 }
351 }
352 }
353
354 /* Default to 1GB for maximum cache size. */
355 if (max_size == 0) {
356 max_size = 1024*1024*1024;
357 }
358
359 cache->max_size = max_size;
360
361 /* A limit of 32 jobs was choosen as observations of Deus Ex start-up times
362 * showed that we reached at most 11 jobs on an Intel i5-6400 CPU@2.70GHz
363 * (a fairly modest desktop CPU). 1 thread was chosen because we don't
364 * really care about getting things to disk quickly just that it's not
365 * blocking other tasks.
366 */
367 util_queue_init(&cache->cache_queue, "disk_cache", 32, 1, 0);
368
369 uint8_t cache_version = CACHE_VERSION;
370 size_t cv_size = sizeof(cache_version);
371 cache->driver_keys_blob_size = cv_size;
372
373 /* Create driver id keys */
374 size_t ts_size = strlen(timestamp) + 1;
375 size_t gpu_name_size = strlen(gpu_name) + 1;
376 cache->driver_keys_blob_size += ts_size;
377 cache->driver_keys_blob_size += gpu_name_size;
378
379 /* We sometimes store entire structs that contains a pointers in the cache,
380 * use pointer size as a key to avoid hard to debug issues.
381 */
382 uint8_t ptr_size = sizeof(void *);
383 size_t ptr_size_size = sizeof(ptr_size);
384 cache->driver_keys_blob_size += ptr_size_size;
385
386 size_t driver_flags_size = sizeof(driver_flags);
387 cache->driver_keys_blob_size += driver_flags_size;
388
389 cache->driver_keys_blob =
390 ralloc_size(cache, cache->driver_keys_blob_size);
391 if (!cache->driver_keys_blob)
392 goto fail;
393
394 uint8_t *drv_key_blob = cache->driver_keys_blob;
395 DRV_KEY_CPY(drv_key_blob, &cache_version, cv_size)
396 DRV_KEY_CPY(drv_key_blob, timestamp, ts_size)
397 DRV_KEY_CPY(drv_key_blob, gpu_name, gpu_name_size)
398 DRV_KEY_CPY(drv_key_blob, &ptr_size, ptr_size_size)
399 DRV_KEY_CPY(drv_key_blob, &driver_flags, driver_flags_size)
400
401 /* Seed our rand function */
402 s_rand_xorshift128plus(cache->seed_xorshift128plus, true);
403
404 ralloc_free(local);
405
406 return cache;
407
408 fail:
409 if (fd != -1)
410 close(fd);
411 if (cache)
412 ralloc_free(cache);
413 ralloc_free(local);
414
415 return NULL;
416 }
417
418 void
419 disk_cache_destroy(struct disk_cache *cache)
420 {
421 if (cache) {
422 util_queue_destroy(&cache->cache_queue);
423 munmap(cache->index_mmap, cache->index_mmap_size);
424 }
425
426 ralloc_free(cache);
427 }
428
429 /* Return a filename within the cache's directory corresponding to 'key'. The
430 * returned filename is ralloced with 'cache' as the parent context.
431 *
432 * Returns NULL if out of memory.
433 */
434 static char *
435 get_cache_file(struct disk_cache *cache, const cache_key key)
436 {
437 char buf[41];
438 char *filename;
439
440 _mesa_sha1_format(buf, key);
441 if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
442 buf[1], buf + 2) == -1)
443 return NULL;
444
445 return filename;
446 }
447
448 /* Create the directory that will be needed for the cache file for \key.
449 *
450 * Obviously, the implementation here must closely match
451 * _get_cache_file above.
452 */
453 static void
454 make_cache_file_directory(struct disk_cache *cache, const cache_key key)
455 {
456 char *dir;
457 char buf[41];
458
459 _mesa_sha1_format(buf, key);
460 if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
461 return;
462
463 mkdir_if_needed(dir);
464 free(dir);
465 }
466
467 /* Given a directory path and predicate function, find the entry with
468 * the oldest access time in that directory for which the predicate
469 * returns true.
470 *
471 * Returns: A malloc'ed string for the path to the chosen file, (or
472 * NULL on any error). The caller should free the string when
473 * finished.
474 */
475 static char *
476 choose_lru_file_matching(const char *dir_path,
477 bool (*predicate)(const char *dir_path,
478 const struct stat *,
479 const char *, const size_t))
480 {
481 DIR *dir;
482 struct dirent *entry;
483 char *filename;
484 char *lru_name = NULL;
485 time_t lru_atime = 0;
486
487 dir = opendir(dir_path);
488 if (dir == NULL)
489 return NULL;
490
491 while (1) {
492 entry = readdir(dir);
493 if (entry == NULL)
494 break;
495
496 struct stat sb;
497 if (fstatat(dirfd(dir), entry->d_name, &sb, 0) == 0) {
498 if (!lru_atime || (sb.st_atime < lru_atime)) {
499 size_t len = strlen(entry->d_name);
500
501 if (!predicate(dir_path, &sb, entry->d_name, len))
502 continue;
503
504 char *tmp = realloc(lru_name, len + 1);
505 if (tmp) {
506 lru_name = tmp;
507 memcpy(lru_name, entry->d_name, len + 1);
508 lru_atime = sb.st_atime;
509 }
510 }
511 }
512 }
513
514 if (lru_name == NULL) {
515 closedir(dir);
516 return NULL;
517 }
518
519 if (asprintf(&filename, "%s/%s", dir_path, lru_name) < 0)
520 filename = NULL;
521
522 free(lru_name);
523 closedir(dir);
524
525 return filename;
526 }
527
528 /* Is entry a regular file, and not having a name with a trailing
529 * ".tmp"
530 */
531 static bool
532 is_regular_non_tmp_file(const char *path, const struct stat *sb,
533 const char *d_name, const size_t len)
534 {
535 if (!S_ISREG(sb->st_mode))
536 return false;
537
538 if (len >= 4 && strcmp(&d_name[len-4], ".tmp") == 0)
539 return false;
540
541 return true;
542 }
543
544 /* Returns the size of the deleted file, (or 0 on any error). */
545 static size_t
546 unlink_lru_file_from_directory(const char *path)
547 {
548 struct stat sb;
549 char *filename;
550
551 filename = choose_lru_file_matching(path, is_regular_non_tmp_file);
552 if (filename == NULL)
553 return 0;
554
555 if (stat(filename, &sb) == -1) {
556 free (filename);
557 return 0;
558 }
559
560 unlink(filename);
561 free (filename);
562
563 return sb.st_blocks * 512;
564 }
565
566 /* Is entry a directory with a two-character name, (and not the
567 * special name of ".."). We also return false if the dir is empty.
568 */
569 static bool
570 is_two_character_sub_directory(const char *path, const struct stat *sb,
571 const char *d_name, const size_t len)
572 {
573 if (!S_ISDIR(sb->st_mode))
574 return false;
575
576 if (len != 2)
577 return false;
578
579 if (strcmp(d_name, "..") == 0)
580 return false;
581
582 char *subdir;
583 if (asprintf(&subdir, "%s/%s", path, d_name) == -1)
584 return false;
585 DIR *dir = opendir(subdir);
586 free(subdir);
587
588 if (dir == NULL)
589 return false;
590
591 unsigned subdir_entries = 0;
592 struct dirent *d;
593 while ((d = readdir(dir)) != NULL) {
594 if(++subdir_entries > 2)
595 break;
596 }
597 closedir(dir);
598
599 /* If dir only contains '.' and '..' it must be empty */
600 if (subdir_entries <= 2)
601 return false;
602
603 return true;
604 }
605
606 static void
607 evict_lru_item(struct disk_cache *cache)
608 {
609 char *dir_path;
610
611 /* With a reasonably-sized, full cache, (and with keys generated
612 * from a cryptographic hash), we can choose two random hex digits
613 * and reasonably expect the directory to exist with a file in it.
614 * Provides pseudo-LRU eviction to reduce checking all cache files.
615 */
616 uint64_t rand64 = rand_xorshift128plus(cache->seed_xorshift128plus);
617 if (asprintf(&dir_path, "%s/%02" PRIx64 , cache->path, rand64 & 0xff) < 0)
618 return;
619
620 size_t size = unlink_lru_file_from_directory(dir_path);
621
622 free(dir_path);
623
624 if (size) {
625 p_atomic_add(cache->size, - (uint64_t)size);
626 return;
627 }
628
629 /* In the case where the random choice of directory didn't find
630 * something, we choose the least recently accessed from the
631 * existing directories.
632 *
633 * Really, the only reason this code exists is to allow the unit
634 * tests to work, (which use an artificially-small cache to be able
635 * to force a single cached item to be evicted).
636 */
637 dir_path = choose_lru_file_matching(cache->path,
638 is_two_character_sub_directory);
639 if (dir_path == NULL)
640 return;
641
642 size = unlink_lru_file_from_directory(dir_path);
643
644 free(dir_path);
645
646 if (size)
647 p_atomic_add(cache->size, - (uint64_t)size);
648 }
649
650 void
651 disk_cache_remove(struct disk_cache *cache, const cache_key key)
652 {
653 struct stat sb;
654
655 char *filename = get_cache_file(cache, key);
656 if (filename == NULL) {
657 return;
658 }
659
660 if (stat(filename, &sb) == -1) {
661 free(filename);
662 return;
663 }
664
665 unlink(filename);
666 free(filename);
667
668 if (sb.st_blocks)
669 p_atomic_add(cache->size, - (uint64_t)sb.st_blocks * 512);
670 }
671
672 static ssize_t
673 read_all(int fd, void *buf, size_t count)
674 {
675 char *in = buf;
676 ssize_t read_ret;
677 size_t done;
678
679 for (done = 0; done < count; done += read_ret) {
680 read_ret = read(fd, in + done, count - done);
681 if (read_ret == -1 || read_ret == 0)
682 return -1;
683 }
684 return done;
685 }
686
687 static ssize_t
688 write_all(int fd, const void *buf, size_t count)
689 {
690 const char *out = buf;
691 ssize_t written;
692 size_t done;
693
694 for (done = 0; done < count; done += written) {
695 written = write(fd, out + done, count - done);
696 if (written == -1)
697 return -1;
698 }
699 return done;
700 }
701
702 /* From the zlib docs:
703 * "If the memory is available, buffers sizes on the order of 128K or 256K
704 * bytes should be used."
705 */
706 #define BUFSIZE 256 * 1024
707
708 /**
709 * Compresses cache entry in memory and writes it to disk. Returns the size
710 * of the data written to disk.
711 */
712 static size_t
713 deflate_and_write_to_disk(const void *in_data, size_t in_data_size, int dest,
714 const char *filename)
715 {
716 unsigned char out[BUFSIZE];
717
718 /* allocate deflate state */
719 z_stream strm;
720 strm.zalloc = Z_NULL;
721 strm.zfree = Z_NULL;
722 strm.opaque = Z_NULL;
723 strm.next_in = (uint8_t *) in_data;
724 strm.avail_in = in_data_size;
725
726 int ret = deflateInit(&strm, Z_BEST_COMPRESSION);
727 if (ret != Z_OK)
728 return 0;
729
730 /* compress until end of in_data */
731 size_t compressed_size = 0;
732 int flush;
733 do {
734 int remaining = in_data_size - BUFSIZE;
735 flush = remaining > 0 ? Z_NO_FLUSH : Z_FINISH;
736 in_data_size -= BUFSIZE;
737
738 /* Run deflate() on input until the output buffer is not full (which
739 * means there is no more data to deflate).
740 */
741 do {
742 strm.avail_out = BUFSIZE;
743 strm.next_out = out;
744
745 ret = deflate(&strm, flush); /* no bad return value */
746 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
747
748 size_t have = BUFSIZE - strm.avail_out;
749 compressed_size += have;
750
751 ssize_t written = write_all(dest, out, have);
752 if (written == -1) {
753 (void)deflateEnd(&strm);
754 return 0;
755 }
756 } while (strm.avail_out == 0);
757
758 /* all input should be used */
759 assert(strm.avail_in == 0);
760
761 } while (flush != Z_FINISH);
762
763 /* stream should be complete */
764 assert(ret == Z_STREAM_END);
765
766 /* clean up and return */
767 (void)deflateEnd(&strm);
768 return compressed_size;
769 }
770
771 static struct disk_cache_put_job *
772 create_put_job(struct disk_cache *cache, const cache_key key,
773 const void *data, size_t size,
774 struct cache_item_metadata *cache_item_metadata)
775 {
776 struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *)
777 malloc(sizeof(struct disk_cache_put_job) + size);
778
779 if (dc_job) {
780 dc_job->cache = cache;
781 memcpy(dc_job->key, key, sizeof(cache_key));
782 dc_job->data = dc_job + 1;
783 memcpy(dc_job->data, data, size);
784 dc_job->size = size;
785
786 /* Copy the cache item metadata */
787 if (cache_item_metadata) {
788 dc_job->cache_item_metadata.type = cache_item_metadata->type;
789 if (cache_item_metadata->type == CACHE_ITEM_TYPE_GLSL) {
790 dc_job->cache_item_metadata.num_keys =
791 cache_item_metadata->num_keys;
792 dc_job->cache_item_metadata.keys = (cache_key *)
793 malloc(cache_item_metadata->num_keys * sizeof(cache_key));
794
795 if (!dc_job->cache_item_metadata.keys)
796 goto fail;
797
798 memcpy(dc_job->cache_item_metadata.keys,
799 cache_item_metadata->keys,
800 sizeof(cache_key) * cache_item_metadata->num_keys);
801 }
802 } else {
803 dc_job->cache_item_metadata.type = CACHE_ITEM_TYPE_UNKNOWN;
804 dc_job->cache_item_metadata.keys = NULL;
805 }
806 }
807
808 return dc_job;
809
810 fail:
811 free(dc_job->cache_item_metadata.keys);
812 free(dc_job);
813
814 return NULL;
815 }
816
817 static void
818 destroy_put_job(void *job, int thread_index)
819 {
820 if (job) {
821 struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *) job;
822 free(dc_job->cache_item_metadata.keys);
823
824 free(job);
825 }
826 }
827
828 struct cache_entry_file_data {
829 uint32_t crc32;
830 uint32_t uncompressed_size;
831 };
832
833 static void
834 cache_put(void *job, int thread_index)
835 {
836 assert(job);
837
838 int fd = -1, fd_final = -1, err, ret;
839 unsigned i = 0;
840 char *filename = NULL, *filename_tmp = NULL;
841 struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *) job;
842
843 filename = get_cache_file(dc_job->cache, dc_job->key);
844 if (filename == NULL)
845 goto done;
846
847 /* If the cache is too large, evict something else first. */
848 while (*dc_job->cache->size + dc_job->size > dc_job->cache->max_size &&
849 i < 8) {
850 evict_lru_item(dc_job->cache);
851 i++;
852 }
853
854 /* Write to a temporary file to allow for an atomic rename to the
855 * final destination filename, (to prevent any readers from seeing
856 * a partially written file).
857 */
858 if (asprintf(&filename_tmp, "%s.tmp", filename) == -1)
859 goto done;
860
861 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
862
863 /* Make the two-character subdirectory within the cache as needed. */
864 if (fd == -1) {
865 if (errno != ENOENT)
866 goto done;
867
868 make_cache_file_directory(dc_job->cache, dc_job->key);
869
870 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
871 if (fd == -1)
872 goto done;
873 }
874
875 /* With the temporary file open, we take an exclusive flock on
876 * it. If the flock fails, then another process still has the file
877 * open with the flock held. So just let that file be responsible
878 * for writing the file.
879 */
880 err = flock(fd, LOCK_EX | LOCK_NB);
881 if (err == -1)
882 goto done;
883
884 /* Now that we have the lock on the open temporary file, we can
885 * check to see if the destination file already exists. If so,
886 * another process won the race between when we saw that the file
887 * didn't exist and now. In this case, we don't do anything more,
888 * (to ensure the size accounting of the cache doesn't get off).
889 */
890 fd_final = open(filename, O_RDONLY | O_CLOEXEC);
891 if (fd_final != -1) {
892 unlink(filename_tmp);
893 goto done;
894 }
895
896 /* OK, we're now on the hook to write out a file that we know is
897 * not in the cache, and is also not being written out to the cache
898 * by some other process.
899 */
900
901 /* Write the driver_keys_blob, this can be used find information about the
902 * mesa version that produced the entry or deal with hash collisions,
903 * should that ever become a real problem.
904 */
905 ret = write_all(fd, dc_job->cache->driver_keys_blob,
906 dc_job->cache->driver_keys_blob_size);
907 if (ret == -1) {
908 unlink(filename_tmp);
909 goto done;
910 }
911
912 /* Write the cache item metadata. This data can be used to deal with
913 * hash collisions, as well as providing useful information to 3rd party
914 * tools reading the cache files.
915 */
916 ret = write_all(fd, &dc_job->cache_item_metadata.type,
917 sizeof(uint32_t));
918 if (ret == -1) {
919 unlink(filename_tmp);
920 goto done;
921 }
922
923 if (dc_job->cache_item_metadata.type == CACHE_ITEM_TYPE_GLSL) {
924 ret = write_all(fd, &dc_job->cache_item_metadata.num_keys,
925 sizeof(uint32_t));
926 if (ret == -1) {
927 unlink(filename_tmp);
928 goto done;
929 }
930
931 ret = write_all(fd, dc_job->cache_item_metadata.keys[0],
932 dc_job->cache_item_metadata.num_keys *
933 sizeof(cache_key));
934 if (ret == -1) {
935 unlink(filename_tmp);
936 goto done;
937 }
938 }
939
940 /* Create CRC of the data. We will read this when restoring the cache and
941 * use it to check for corruption.
942 */
943 struct cache_entry_file_data cf_data;
944 cf_data.crc32 = util_hash_crc32(dc_job->data, dc_job->size);
945 cf_data.uncompressed_size = dc_job->size;
946
947 size_t cf_data_size = sizeof(cf_data);
948 ret = write_all(fd, &cf_data, cf_data_size);
949 if (ret == -1) {
950 unlink(filename_tmp);
951 goto done;
952 }
953
954 /* Now, finally, write out the contents to the temporary file, then
955 * rename them atomically to the destination filename, and also
956 * perform an atomic increment of the total cache size.
957 */
958 size_t file_size = deflate_and_write_to_disk(dc_job->data, dc_job->size,
959 fd, filename_tmp);
960 if (file_size == 0) {
961 unlink(filename_tmp);
962 goto done;
963 }
964 ret = rename(filename_tmp, filename);
965 if (ret == -1) {
966 unlink(filename_tmp);
967 goto done;
968 }
969
970 struct stat sb;
971 if (stat(filename, &sb) == -1) {
972 /* Something went wrong remove the file */
973 unlink(filename);
974 goto done;
975 }
976
977 p_atomic_add(dc_job->cache->size, sb.st_blocks * 512);
978
979 done:
980 if (fd_final != -1)
981 close(fd_final);
982 /* This close finally releases the flock, (now that the final file
983 * has been renamed into place and the size has been added).
984 */
985 if (fd != -1)
986 close(fd);
987 if (filename_tmp)
988 free(filename_tmp);
989 if (filename)
990 free(filename);
991 }
992
993 void
994 disk_cache_put(struct disk_cache *cache, const cache_key key,
995 const void *data, size_t size,
996 struct cache_item_metadata *cache_item_metadata)
997 {
998 struct disk_cache_put_job *dc_job =
999 create_put_job(cache, key, data, size, cache_item_metadata);
1000
1001 if (dc_job) {
1002 util_queue_fence_init(&dc_job->fence);
1003 util_queue_add_job(&cache->cache_queue, dc_job, &dc_job->fence,
1004 cache_put, destroy_put_job);
1005 }
1006 }
1007
1008 /**
1009 * Decompresses cache entry, returns true if successful.
1010 */
1011 static bool
1012 inflate_cache_data(uint8_t *in_data, size_t in_data_size,
1013 uint8_t *out_data, size_t out_data_size)
1014 {
1015 z_stream strm;
1016
1017 /* allocate inflate state */
1018 strm.zalloc = Z_NULL;
1019 strm.zfree = Z_NULL;
1020 strm.opaque = Z_NULL;
1021 strm.next_in = in_data;
1022 strm.avail_in = in_data_size;
1023 strm.next_out = out_data;
1024 strm.avail_out = out_data_size;
1025
1026 int ret = inflateInit(&strm);
1027 if (ret != Z_OK)
1028 return false;
1029
1030 ret = inflate(&strm, Z_NO_FLUSH);
1031 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
1032
1033 /* Unless there was an error we should have decompressed everything in one
1034 * go as we know the uncompressed file size.
1035 */
1036 if (ret != Z_STREAM_END) {
1037 (void)inflateEnd(&strm);
1038 return false;
1039 }
1040 assert(strm.avail_out == 0);
1041
1042 /* clean up and return */
1043 (void)inflateEnd(&strm);
1044 return true;
1045 }
1046
1047 void *
1048 disk_cache_get(struct disk_cache *cache, const cache_key key, size_t *size)
1049 {
1050 int fd = -1, ret;
1051 struct stat sb;
1052 char *filename = NULL;
1053 uint8_t *data = NULL;
1054 uint8_t *uncompressed_data = NULL;
1055 uint8_t *file_header = NULL;
1056
1057 if (size)
1058 *size = 0;
1059
1060 filename = get_cache_file(cache, key);
1061 if (filename == NULL)
1062 goto fail;
1063
1064 fd = open(filename, O_RDONLY | O_CLOEXEC);
1065 if (fd == -1)
1066 goto fail;
1067
1068 if (fstat(fd, &sb) == -1)
1069 goto fail;
1070
1071 data = malloc(sb.st_size);
1072 if (data == NULL)
1073 goto fail;
1074
1075 size_t ck_size = cache->driver_keys_blob_size;
1076 file_header = malloc(ck_size);
1077 if (!file_header)
1078 goto fail;
1079
1080 if (sb.st_size < ck_size)
1081 goto fail;
1082
1083 ret = read_all(fd, file_header, ck_size);
1084 if (ret == -1)
1085 goto fail;
1086
1087 /* Check for extremely unlikely hash collisions */
1088 if (memcmp(cache->driver_keys_blob, file_header, ck_size) != 0) {
1089 assert(!"Mesa cache keys mismatch!");
1090 goto fail;
1091 }
1092
1093 size_t cache_item_md_size = sizeof(uint32_t);
1094 uint32_t md_type;
1095 ret = read_all(fd, &md_type, cache_item_md_size);
1096 if (ret == -1)
1097 goto fail;
1098
1099 if (md_type == CACHE_ITEM_TYPE_GLSL) {
1100 uint32_t num_keys;
1101 cache_item_md_size += sizeof(uint32_t);
1102 ret = read_all(fd, &num_keys, sizeof(uint32_t));
1103 if (ret == -1)
1104 goto fail;
1105
1106 /* The cache item metadata is currently just used for distributing
1107 * precompiled shaders, they are not used by Mesa so just skip them for
1108 * now.
1109 * TODO: pass the metadata back to the caller and do some basic
1110 * validation.
1111 */
1112 cache_item_md_size += sizeof(cache_key);
1113 ret = lseek(fd, num_keys * sizeof(cache_key), SEEK_CUR);
1114 if (ret == -1)
1115 goto fail;
1116 }
1117
1118 /* Load the CRC that was created when the file was written. */
1119 struct cache_entry_file_data cf_data;
1120 size_t cf_data_size = sizeof(cf_data);
1121 ret = read_all(fd, &cf_data, cf_data_size);
1122 if (ret == -1)
1123 goto fail;
1124
1125 /* Load the actual cache data. */
1126 size_t cache_data_size =
1127 sb.st_size - cf_data_size - ck_size - cache_item_md_size;
1128 ret = read_all(fd, data, cache_data_size);
1129 if (ret == -1)
1130 goto fail;
1131
1132 /* Uncompress the cache data */
1133 uncompressed_data = malloc(cf_data.uncompressed_size);
1134 if (!inflate_cache_data(data, cache_data_size, uncompressed_data,
1135 cf_data.uncompressed_size))
1136 goto fail;
1137
1138 /* Check the data for corruption */
1139 if (cf_data.crc32 != util_hash_crc32(uncompressed_data,
1140 cf_data.uncompressed_size))
1141 goto fail;
1142
1143 free(data);
1144 free(filename);
1145 close(fd);
1146
1147 if (size)
1148 *size = cf_data.uncompressed_size;
1149
1150 return uncompressed_data;
1151
1152 fail:
1153 if (data)
1154 free(data);
1155 if (uncompressed_data)
1156 free(uncompressed_data);
1157 if (filename)
1158 free(filename);
1159 if (file_header)
1160 free(file_header);
1161 if (fd != -1)
1162 close(fd);
1163
1164 return NULL;
1165 }
1166
1167 void
1168 disk_cache_put_key(struct disk_cache *cache, const cache_key key)
1169 {
1170 const uint32_t *key_chunk = (const uint32_t *) key;
1171 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
1172 unsigned char *entry;
1173
1174 entry = &cache->stored_keys[i * CACHE_KEY_SIZE];
1175
1176 memcpy(entry, key, CACHE_KEY_SIZE);
1177 }
1178
1179 /* This function lets us test whether a given key was previously
1180 * stored in the cache with disk_cache_put_key(). The implement is
1181 * efficient by not using syscalls or hitting the disk. It's not
1182 * race-free, but the races are benign. If we race with someone else
1183 * calling disk_cache_put_key, then that's just an extra cache miss and an
1184 * extra recompile.
1185 */
1186 bool
1187 disk_cache_has_key(struct disk_cache *cache, const cache_key key)
1188 {
1189 const uint32_t *key_chunk = (const uint32_t *) key;
1190 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
1191 unsigned char *entry;
1192
1193 entry = &cache->stored_keys[i * CACHE_KEY_SIZE];
1194
1195 return memcmp(entry, key, CACHE_KEY_SIZE) == 0;
1196 }
1197
1198 void
1199 disk_cache_compute_key(struct disk_cache *cache, const void *data, size_t size,
1200 cache_key key)
1201 {
1202 struct mesa_sha1 ctx;
1203
1204 _mesa_sha1_init(&ctx);
1205 _mesa_sha1_update(&ctx, cache->driver_keys_blob,
1206 cache->driver_keys_blob_size);
1207 _mesa_sha1_update(&ctx, data, size);
1208 _mesa_sha1_final(&ctx, key);
1209 }
1210
1211 #endif /* ENABLE_SHADER_CACHE */