util/disk_cache: add thread queue to disk cache
[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/u_atomic.h"
44 #include "util/u_queue.h"
45 #include "util/mesa-sha1.h"
46 #include "util/ralloc.h"
47 #include "main/errors.h"
48
49 #include "disk_cache.h"
50
51 /* Number of bits to mask off from a cache key to get an index. */
52 #define CACHE_INDEX_KEY_BITS 16
53
54 /* Mask for computing an index from a key. */
55 #define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
56
57 /* The number of keys that can be stored in the index. */
58 #define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
59
60 struct disk_cache {
61 /* The path to the cache directory. */
62 char *path;
63
64 /* Thread queue for compressing and writing cache entries to disk */
65 struct util_queue cache_queue;
66
67 /* A pointer to the mmapped index file within the cache directory. */
68 uint8_t *index_mmap;
69 size_t index_mmap_size;
70
71 /* Pointer to total size of all objects in cache (within index_mmap) */
72 uint64_t *size;
73
74 /* Pointer to stored keys, (within index_mmap). */
75 uint8_t *stored_keys;
76
77 /* Maximum size of all cached objects (in bytes). */
78 uint64_t max_size;
79 };
80
81 /* Create a directory named 'path' if it does not already exist.
82 *
83 * Returns: 0 if path already exists as a directory or if created.
84 * -1 in all other cases.
85 */
86 static int
87 mkdir_if_needed(const char *path)
88 {
89 struct stat sb;
90
91 /* If the path exists already, then our work is done if it's a
92 * directory, but it's an error if it is not.
93 */
94 if (stat(path, &sb) == 0) {
95 if (S_ISDIR(sb.st_mode)) {
96 return 0;
97 } else {
98 fprintf(stderr, "Cannot use %s for shader cache (not a directory)"
99 "---disabling.\n", path);
100 return -1;
101 }
102 }
103
104 int ret = mkdir(path, 0755);
105 if (ret == 0 || (ret == -1 && errno == EEXIST))
106 return 0;
107
108 fprintf(stderr, "Failed to create %s for shader cache (%s)---disabling.\n",
109 path, strerror(errno));
110
111 return -1;
112 }
113
114 /* Concatenate an existing path and a new name to form a new path. If the new
115 * path does not exist as a directory, create it then return the resulting
116 * name of the new path (ralloc'ed off of 'ctx').
117 *
118 * Returns NULL on any error, such as:
119 *
120 * <path> does not exist or is not a directory
121 * <path>/<name> exists but is not a directory
122 * <path>/<name> cannot be created as a directory
123 */
124 static char *
125 concatenate_and_mkdir(void *ctx, const char *path, const char *name)
126 {
127 char *new_path;
128 struct stat sb;
129
130 if (stat(path, &sb) != 0 || ! S_ISDIR(sb.st_mode))
131 return NULL;
132
133 new_path = ralloc_asprintf(ctx, "%s/%s", path, name);
134
135 if (mkdir_if_needed(new_path) == 0)
136 return new_path;
137 else
138 return NULL;
139 }
140
141 static int
142 remove_dir(const char *fpath, const struct stat *sb,
143 int typeflag, struct FTW *ftwbuf)
144 {
145 if (S_ISREG(sb->st_mode))
146 unlink(fpath);
147 else if (S_ISDIR(sb->st_mode))
148 rmdir(fpath);
149
150 return 0;
151 }
152
153 static void
154 remove_old_cache_directories(void *mem_ctx, const char *path,
155 const char *timestamp)
156 {
157 DIR *dir = opendir(path);
158
159 struct dirent* d_entry;
160 while((d_entry = readdir(dir)) != NULL)
161 {
162 char *full_path =
163 ralloc_asprintf(mem_ctx, "%s/%s", path, d_entry->d_name);
164
165 struct stat sb;
166 if (stat(full_path, &sb) == 0 && S_ISDIR(sb.st_mode) &&
167 strcmp(d_entry->d_name, timestamp) != 0 &&
168 strcmp(d_entry->d_name, "..") != 0 &&
169 strcmp(d_entry->d_name, ".") != 0) {
170 nftw(full_path, remove_dir, 20, FTW_DEPTH);
171 }
172 }
173
174 closedir(dir);
175 }
176
177 static char *
178 create_mesa_cache_dir(void *mem_ctx, const char *path, const char *timestamp,
179 const char *gpu_name)
180 {
181 char *new_path = concatenate_and_mkdir(mem_ctx, path, "mesa");
182 if (new_path == NULL)
183 return NULL;
184
185 /* Create a parent architecture directory so that we don't remove cache
186 * files for other architectures. In theory we could share the cache
187 * between architectures but we have no way of knowing if they were created
188 * by a compatible Mesa version.
189 */
190 new_path = concatenate_and_mkdir(mem_ctx, new_path, get_arch_bitness_str());
191 if (new_path == NULL)
192 return NULL;
193
194 /* Remove cache directories for old Mesa versions */
195 remove_old_cache_directories(mem_ctx, new_path, timestamp);
196
197 new_path = concatenate_and_mkdir(mem_ctx, new_path, timestamp);
198 if (new_path == NULL)
199 return NULL;
200
201 new_path = concatenate_and_mkdir(mem_ctx, new_path, gpu_name);
202 if (new_path == NULL)
203 return NULL;
204
205 return new_path;
206 }
207
208 struct disk_cache *
209 disk_cache_create(const char *gpu_name, const char *timestamp)
210 {
211 void *local;
212 struct disk_cache *cache = NULL;
213 char *path, *max_size_str;
214 uint64_t max_size;
215 int fd = -1;
216 struct stat sb;
217 size_t size;
218
219 /* If running as a users other than the real user disable cache */
220 if (geteuid() != getuid())
221 return NULL;
222
223 /* A ralloc context for transient data during this invocation. */
224 local = ralloc_context(NULL);
225 if (local == NULL)
226 goto fail;
227
228 /* At user request, disable shader cache entirely. */
229 if (getenv("MESA_GLSL_CACHE_DISABLE"))
230 goto fail;
231
232 /* Determine path for cache based on the first defined name as follows:
233 *
234 * $MESA_GLSL_CACHE_DIR
235 * $XDG_CACHE_HOME/mesa
236 * <pwd.pw_dir>/.cache/mesa
237 */
238 path = getenv("MESA_GLSL_CACHE_DIR");
239 if (path) {
240 if (mkdir_if_needed(path) == -1)
241 goto fail;
242
243 path = create_mesa_cache_dir(local, path, timestamp,
244 gpu_name);
245 if (path == NULL)
246 goto fail;
247 }
248
249 if (path == NULL) {
250 char *xdg_cache_home = getenv("XDG_CACHE_HOME");
251
252 if (xdg_cache_home) {
253 if (mkdir_if_needed(xdg_cache_home) == -1)
254 goto fail;
255
256 path = create_mesa_cache_dir(local, xdg_cache_home, timestamp,
257 gpu_name);
258 if (path == NULL)
259 goto fail;
260 }
261 }
262
263 if (path == NULL) {
264 char *buf;
265 size_t buf_size;
266 struct passwd pwd, *result;
267
268 buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
269 if (buf_size == -1)
270 buf_size = 512;
271
272 /* Loop until buf_size is large enough to query the directory */
273 while (1) {
274 buf = ralloc_size(local, buf_size);
275
276 getpwuid_r(getuid(), &pwd, buf, buf_size, &result);
277 if (result)
278 break;
279
280 if (errno == ERANGE) {
281 ralloc_free(buf);
282 buf = NULL;
283 buf_size *= 2;
284 } else {
285 goto fail;
286 }
287 }
288
289 path = concatenate_and_mkdir(local, pwd.pw_dir, ".cache");
290 if (path == NULL)
291 goto fail;
292
293 path = create_mesa_cache_dir(local, path, timestamp, gpu_name);
294 if (path == NULL)
295 goto fail;
296 }
297
298 cache = ralloc(NULL, struct disk_cache);
299 if (cache == NULL)
300 goto fail;
301
302 cache->path = ralloc_strdup(cache, path);
303 if (cache->path == NULL)
304 goto fail;
305
306 path = ralloc_asprintf(local, "%s/index", cache->path);
307 if (path == NULL)
308 goto fail;
309
310 fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
311 if (fd == -1)
312 goto fail;
313
314 if (fstat(fd, &sb) == -1)
315 goto fail;
316
317 /* Force the index file to be the expected size. */
318 size = sizeof(*cache->size) + CACHE_INDEX_MAX_KEYS * CACHE_KEY_SIZE;
319 if (sb.st_size != size) {
320 if (ftruncate(fd, size) == -1)
321 goto fail;
322 }
323
324 /* We map this shared so that other processes see updates that we
325 * make.
326 *
327 * Note: We do use atomic addition to ensure that multiple
328 * processes don't scramble the cache size recorded in the
329 * index. But we don't use any locking to prevent multiple
330 * processes from updating the same entry simultaneously. The idea
331 * is that if either result lands entirely in the index, then
332 * that's equivalent to a well-ordered write followed by an
333 * eviction and a write. On the other hand, if the simultaneous
334 * writes result in a corrupt entry, that's not really any
335 * different than both entries being evicted, (since within the
336 * guarantees of the cryptographic hash, a corrupt entry is
337 * unlikely to ever match a real cache key).
338 */
339 cache->index_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE,
340 MAP_SHARED, fd, 0);
341 if (cache->index_mmap == MAP_FAILED)
342 goto fail;
343 cache->index_mmap_size = size;
344
345 close(fd);
346
347 cache->size = (uint64_t *) cache->index_mmap;
348 cache->stored_keys = cache->index_mmap + sizeof(uint64_t);
349
350 max_size = 0;
351
352 max_size_str = getenv("MESA_GLSL_CACHE_MAX_SIZE");
353 if (max_size_str) {
354 char *end;
355 max_size = strtoul(max_size_str, &end, 10);
356 if (end == max_size_str) {
357 max_size = 0;
358 } else {
359 switch (*end) {
360 case 'K':
361 case 'k':
362 max_size *= 1024;
363 break;
364 case 'M':
365 case 'm':
366 max_size *= 1024*1024;
367 break;
368 case '\0':
369 case 'G':
370 case 'g':
371 default:
372 max_size *= 1024*1024*1024;
373 break;
374 }
375 }
376 }
377
378 /* Default to 1GB for maximum cache size. */
379 if (max_size == 0)
380 max_size = 1024*1024*1024;
381
382 cache->max_size = max_size;
383
384 /* A limit of 32 jobs was choosen as observations of Deus Ex start-up times
385 * showed that we reached at most 11 jobs on an Intel i5-6400 CPU@2.70GHz
386 * (a fairly modest desktop CPU). 1 thread was chosen because we don't
387 * really care about getting things to disk quickly just that it's not
388 * blocking other tasks.
389 */
390 util_queue_init(&cache->cache_queue, "disk_cache", 32, 1);
391
392 ralloc_free(local);
393
394 return cache;
395
396 fail:
397 if (fd != -1)
398 close(fd);
399 if (cache)
400 ralloc_free(cache);
401 ralloc_free(local);
402
403 return NULL;
404 }
405
406 void
407 disk_cache_destroy(struct disk_cache *cache)
408 {
409 if (cache) {
410 util_queue_destroy(&cache->cache_queue);
411 munmap(cache->index_mmap, cache->index_mmap_size);
412 }
413
414 ralloc_free(cache);
415 }
416
417 /* Return a filename within the cache's directory corresponding to 'key'. The
418 * returned filename is ralloced with 'cache' as the parent context.
419 *
420 * Returns NULL if out of memory.
421 */
422 static char *
423 get_cache_file(struct disk_cache *cache, const cache_key key)
424 {
425 char buf[41];
426 char *filename;
427
428 _mesa_sha1_format(buf, key);
429 if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
430 buf[1], buf + 2) == -1)
431 return NULL;
432
433 return filename;
434 }
435
436 /* Create the directory that will be needed for the cache file for \key.
437 *
438 * Obviously, the implementation here must closely match
439 * _get_cache_file above.
440 */
441 static void
442 make_cache_file_directory(struct disk_cache *cache, const cache_key key)
443 {
444 char *dir;
445 char buf[41];
446
447 _mesa_sha1_format(buf, key);
448 if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
449 return;
450
451 mkdir_if_needed(dir);
452 free(dir);
453 }
454
455 /* Given a directory path and predicate function, count all entries in
456 * that directory for which the predicate returns true. Then choose a
457 * random entry from among those counted.
458 *
459 * Returns: A malloc'ed string for the path to the chosen file, (or
460 * NULL on any error). The caller should free the string when
461 * finished.
462 */
463 static char *
464 choose_random_file_matching(const char *dir_path,
465 bool (*predicate)(const struct dirent *,
466 const char *dir_path))
467 {
468 DIR *dir;
469 struct dirent *entry;
470 unsigned int count, victim;
471 char *filename;
472
473 dir = opendir(dir_path);
474 if (dir == NULL)
475 return NULL;
476
477 count = 0;
478
479 while (1) {
480 entry = readdir(dir);
481 if (entry == NULL)
482 break;
483 if (!predicate(entry, dir_path))
484 continue;
485
486 count++;
487 }
488
489 if (count == 0) {
490 closedir(dir);
491 return NULL;
492 }
493
494 victim = rand() % count;
495
496 rewinddir(dir);
497 count = 0;
498
499 while (1) {
500 entry = readdir(dir);
501 if (entry == NULL)
502 break;
503 if (!predicate(entry, dir_path))
504 continue;
505 if (count == victim)
506 break;
507
508 count++;
509 }
510
511 if (entry == NULL) {
512 closedir(dir);
513 return NULL;
514 }
515
516 if (asprintf(&filename, "%s/%s", dir_path, entry->d_name) < 0)
517 filename = NULL;
518
519 closedir(dir);
520
521 return filename;
522 }
523
524 /* Is entry a regular file, and not having a name with a trailing
525 * ".tmp"
526 */
527 static bool
528 is_regular_non_tmp_file(const struct dirent *entry, const char *path)
529 {
530 char *filename;
531 if (asprintf(&filename, "%s/%s", path, entry->d_name) == -1)
532 return false;
533
534 struct stat sb;
535 int res = stat(filename, &sb);
536 free(filename);
537
538 if (res == -1 || !S_ISREG(sb.st_mode))
539 return false;
540
541 size_t len = strlen (entry->d_name);
542 if (len >= 4 && strcmp(&entry->d_name[len-4], ".tmp") == 0)
543 return false;
544
545 return true;
546 }
547
548 /* Returns the size of the deleted file, (or 0 on any error). */
549 static size_t
550 unlink_random_file_from_directory(const char *path)
551 {
552 struct stat sb;
553 char *filename;
554
555 filename = choose_random_file_matching(path, is_regular_non_tmp_file);
556 if (filename == NULL)
557 return 0;
558
559 if (stat(filename, &sb) == -1) {
560 free (filename);
561 return 0;
562 }
563
564 unlink(filename);
565
566 free (filename);
567
568 return sb.st_size;
569 }
570
571 /* Is entry a directory with a two-character name, (and not the
572 * special name of "..")
573 */
574 static bool
575 is_two_character_sub_directory(const struct dirent *entry, const char *path)
576 {
577 char *subdir;
578 if (asprintf(&subdir, "%s/%s", path, entry->d_name) == -1)
579 return false;
580
581 struct stat sb;
582 int res = stat(subdir, &sb);
583 free(subdir);
584
585 if (res == -1 || !S_ISDIR(sb.st_mode))
586 return false;
587
588 if (strlen(entry->d_name) != 2)
589 return false;
590
591 if (strcmp(entry->d_name, "..") == 0)
592 return false;
593
594 return true;
595 }
596
597 static void
598 evict_random_item(struct disk_cache *cache)
599 {
600 const char hex[] = "0123456789abcde";
601 char *dir_path;
602 int a, b;
603 size_t size;
604
605 /* With a reasonably-sized, full cache, (and with keys generated
606 * from a cryptographic hash), we can choose two random hex digits
607 * and reasonably expect the directory to exist with a file in it.
608 */
609 a = rand() % 16;
610 b = rand() % 16;
611
612 if (asprintf(&dir_path, "%s/%c%c", cache->path, hex[a], hex[b]) < 0)
613 return;
614
615 size = unlink_random_file_from_directory(dir_path);
616
617 free(dir_path);
618
619 if (size) {
620 p_atomic_add(cache->size, - (uint64_t)size);
621 return;
622 }
623
624 /* In the case where the random choice of directory didn't find
625 * something, we choose randomly from the existing directories.
626 *
627 * Really, the only reason this code exists is to allow the unit
628 * tests to work, (which use an artificially-small cache to be able
629 * to force a single cached item to be evicted).
630 */
631 dir_path = choose_random_file_matching(cache->path,
632 is_two_character_sub_directory);
633 if (dir_path == NULL)
634 return;
635
636 size = unlink_random_file_from_directory(dir_path);
637
638 free(dir_path);
639
640 if (size)
641 p_atomic_add(cache->size, - (uint64_t)size);
642 }
643
644 void
645 disk_cache_remove(struct disk_cache *cache, const cache_key key)
646 {
647 struct stat sb;
648
649 char *filename = get_cache_file(cache, key);
650 if (filename == NULL) {
651 return;
652 }
653
654 if (stat(filename, &sb) == -1) {
655 free(filename);
656 return;
657 }
658
659 unlink(filename);
660 free(filename);
661
662 if (sb.st_size)
663 p_atomic_add(cache->size, - (uint64_t)sb.st_size);
664 }
665
666 /* From the zlib docs:
667 * "If the memory is available, buffers sizes on the order of 128K or 256K
668 * bytes should be used."
669 */
670 #define BUFSIZE 256 * 1024
671
672 /**
673 * Compresses cache entry in memory and writes it to disk. Returns the size
674 * of the data written to disk.
675 */
676 static size_t
677 deflate_and_write_to_disk(const void *in_data, size_t in_data_size, int dest,
678 const char *filename)
679 {
680 unsigned char out[BUFSIZE];
681
682 /* allocate deflate state */
683 z_stream strm;
684 strm.zalloc = Z_NULL;
685 strm.zfree = Z_NULL;
686 strm.opaque = Z_NULL;
687 strm.next_in = (uint8_t *) in_data;
688 strm.avail_in = in_data_size;
689
690 int ret = deflateInit(&strm, Z_BEST_COMPRESSION);
691 if (ret != Z_OK)
692 return 0;
693
694 /* compress until end of in_data */
695 size_t compressed_size = 0;
696 int flush;
697 do {
698 int remaining = in_data_size - BUFSIZE;
699 flush = remaining > 0 ? Z_NO_FLUSH : Z_FINISH;
700 in_data_size -= BUFSIZE;
701
702 /* Run deflate() on input until the output buffer is not full (which
703 * means there is no more data to deflate).
704 */
705 do {
706 strm.avail_out = BUFSIZE;
707 strm.next_out = out;
708
709 ret = deflate(&strm, flush); /* no bad return value */
710 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
711
712 size_t have = BUFSIZE - strm.avail_out;
713 compressed_size += have;
714
715 size_t written = 0;
716 for (size_t len = 0; len < have; len += written) {
717 written = write(dest, out + len, have - len);
718 if (written == -1) {
719 (void)deflateEnd(&strm);
720 return 0;
721 }
722 }
723 } while (strm.avail_out == 0);
724
725 /* all input should be used */
726 assert(strm.avail_in == 0);
727
728 } while (flush != Z_FINISH);
729
730 /* stream should be complete */
731 assert(ret == Z_STREAM_END);
732
733 /* clean up and return */
734 (void)deflateEnd(&strm);
735 return compressed_size;
736 }
737
738 struct cache_entry_file_data {
739 uint32_t crc32;
740 uint32_t uncompressed_size;
741 };
742
743 void
744 disk_cache_put(struct disk_cache *cache,
745 const cache_key key,
746 const void *data,
747 size_t size)
748 {
749 int fd = -1, fd_final = -1, err, ret;
750 size_t len;
751 char *filename = NULL, *filename_tmp = NULL;
752
753 filename = get_cache_file(cache, key);
754 if (filename == NULL)
755 goto done;
756
757 /* Write to a temporary file to allow for an atomic rename to the
758 * final destination filename, (to prevent any readers from seeing
759 * a partially written file).
760 */
761 if (asprintf(&filename_tmp, "%s.tmp", filename) == -1)
762 goto done;
763
764 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
765
766 /* Make the two-character subdirectory within the cache as needed. */
767 if (fd == -1) {
768 if (errno != ENOENT)
769 goto done;
770
771 make_cache_file_directory(cache, key);
772
773 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
774 if (fd == -1)
775 goto done;
776 }
777
778 /* With the temporary file open, we take an exclusive flock on
779 * it. If the flock fails, then another process still has the file
780 * open with the flock held. So just let that file be responsible
781 * for writing the file.
782 */
783 err = flock(fd, LOCK_EX | LOCK_NB);
784 if (err == -1)
785 goto done;
786
787 /* Now that we have the lock on the open temporary file, we can
788 * check to see if the destination file already exists. If so,
789 * another process won the race between when we saw that the file
790 * didn't exist and now. In this case, we don't do anything more,
791 * (to ensure the size accounting of the cache doesn't get off).
792 */
793 fd_final = open(filename, O_RDONLY | O_CLOEXEC);
794 if (fd_final != -1)
795 goto done;
796
797 /* OK, we're now on the hook to write out a file that we know is
798 * not in the cache, and is also not being written out to the cache
799 * by some other process.
800 *
801 * Before we do that, if the cache is too large, evict something
802 * else first.
803 */
804 if (*cache->size + size > cache->max_size)
805 evict_random_item(cache);
806
807 /* Create CRC of the data and store at the start of the file. We will
808 * read this when restoring the cache and use it to check for corruption.
809 */
810 struct cache_entry_file_data cf_data;
811 cf_data.crc32 = util_hash_crc32(data, size);
812 cf_data.uncompressed_size = size;
813
814 size_t cf_data_size = sizeof(cf_data);
815 for (len = 0; len < cf_data_size; len += ret) {
816 ret = write(fd, ((uint8_t *) &cf_data) + len, cf_data_size - len);
817 if (ret == -1) {
818 unlink(filename_tmp);
819 goto done;
820 }
821 }
822
823 /* Now, finally, write out the contents to the temporary file, then
824 * rename them atomically to the destination filename, and also
825 * perform an atomic increment of the total cache size.
826 */
827 size_t file_size = deflate_and_write_to_disk(data, size, fd, filename_tmp);
828 if (file_size == 0) {
829 unlink(filename_tmp);
830 goto done;
831 }
832 rename(filename_tmp, filename);
833
834 file_size += cf_data_size;
835 p_atomic_add(cache->size, file_size);
836
837 done:
838 if (fd_final != -1)
839 close(fd_final);
840 /* This close finally releases the flock, (now that the final dile
841 * has been renamed into place and the size has been added).
842 */
843 if (fd != -1)
844 close(fd);
845 if (filename_tmp)
846 free(filename_tmp);
847 if (filename)
848 free(filename);
849 }
850
851 /**
852 * Decompresses cache entry, returns true if successful.
853 */
854 static bool
855 inflate_cache_data(uint8_t *in_data, size_t in_data_size,
856 uint8_t *out_data, size_t out_data_size)
857 {
858 z_stream strm;
859
860 /* allocate inflate state */
861 strm.zalloc = Z_NULL;
862 strm.zfree = Z_NULL;
863 strm.opaque = Z_NULL;
864 strm.next_in = in_data;
865 strm.avail_in = in_data_size;
866 strm.next_out = out_data;
867 strm.avail_out = out_data_size;
868
869 int ret = inflateInit(&strm);
870 if (ret != Z_OK)
871 return false;
872
873 ret = inflate(&strm, Z_NO_FLUSH);
874 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
875
876 /* Unless there was an error we should have decompressed everything in one
877 * go as we know the uncompressed file size.
878 */
879 if (ret != Z_STREAM_END) {
880 (void)inflateEnd(&strm);
881 return false;
882 }
883 assert(strm.avail_out == 0);
884
885 /* clean up and return */
886 (void)inflateEnd(&strm);
887 return true;
888 }
889
890 void *
891 disk_cache_get(struct disk_cache *cache, const cache_key key, size_t *size)
892 {
893 int fd = -1, ret, len;
894 struct stat sb;
895 char *filename = NULL;
896 uint8_t *data = NULL;
897 uint8_t *uncompressed_data = NULL;
898
899 if (size)
900 *size = 0;
901
902 filename = get_cache_file(cache, key);
903 if (filename == NULL)
904 goto fail;
905
906 fd = open(filename, O_RDONLY | O_CLOEXEC);
907 if (fd == -1)
908 goto fail;
909
910 if (fstat(fd, &sb) == -1)
911 goto fail;
912
913 data = malloc(sb.st_size);
914 if (data == NULL)
915 goto fail;
916
917 /* Load the CRC that was created when the file was written. */
918 struct cache_entry_file_data cf_data;
919 size_t cf_data_size = sizeof(cf_data);
920 assert(sb.st_size > cf_data_size);
921 for (len = 0; len < cf_data_size; len += ret) {
922 ret = read(fd, ((uint8_t *) &cf_data) + len, cf_data_size - len);
923 if (ret == -1)
924 goto fail;
925 }
926
927 /* Load the actual cache data. */
928 size_t cache_data_size = sb.st_size - cf_data_size;
929 for (len = 0; len < cache_data_size; len += ret) {
930 ret = read(fd, data + len, cache_data_size - len);
931 if (ret == -1)
932 goto fail;
933 }
934
935 /* Uncompress the cache data */
936 uncompressed_data = malloc(cf_data.uncompressed_size);
937 if (!inflate_cache_data(data, cache_data_size, uncompressed_data,
938 cf_data.uncompressed_size))
939 goto fail;
940
941 /* Check the data for corruption */
942 if (cf_data.crc32 != util_hash_crc32(uncompressed_data,
943 cf_data.uncompressed_size))
944 goto fail;
945
946 free(data);
947 free(filename);
948 close(fd);
949
950 if (size)
951 *size = cf_data.uncompressed_size;
952
953 return uncompressed_data;
954
955 fail:
956 if (data)
957 free(data);
958 if (uncompressed_data)
959 free(uncompressed_data);
960 if (filename)
961 free(filename);
962 if (fd != -1)
963 close(fd);
964
965 return NULL;
966 }
967
968 void
969 disk_cache_put_key(struct disk_cache *cache, const cache_key key)
970 {
971 const uint32_t *key_chunk = (const uint32_t *) key;
972 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
973 unsigned char *entry;
974
975 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
976
977 memcpy(entry, key, CACHE_KEY_SIZE);
978 }
979
980 /* This function lets us test whether a given key was previously
981 * stored in the cache with disk_cache_put_key(). The implement is
982 * efficient by not using syscalls or hitting the disk. It's not
983 * race-free, but the races are benign. If we race with someone else
984 * calling disk_cache_put_key, then that's just an extra cache miss and an
985 * extra recompile.
986 */
987 bool
988 disk_cache_has_key(struct disk_cache *cache, const cache_key key)
989 {
990 const uint32_t *key_chunk = (const uint32_t *) key;
991 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
992 unsigned char *entry;
993
994 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
995
996 return memcmp(entry, key, CACHE_KEY_SIZE) == 0;
997 }
998
999 #endif /* ENABLE_SHADER_CACHE */