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