util/disk_cache: support caches for multiple architectures
[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 /* As a temporary measure, (while the shader cache is under
246 * development, and known to not be fully functional), also require
247 * the MESA_GLSL_CACHE_ENABLE variable to be set.
248 */
249 if (!getenv("MESA_GLSL_CACHE_ENABLE"))
250 goto fail;
251
252 /* Determine path for cache based on the first defined name as follows:
253 *
254 * $MESA_GLSL_CACHE_DIR
255 * $XDG_CACHE_HOME/mesa
256 * <pwd.pw_dir>/.cache/mesa
257 */
258 path = getenv("MESA_GLSL_CACHE_DIR");
259 if (path) {
260 if (mkdir_if_needed(path) == -1)
261 goto fail;
262
263 path = create_mesa_cache_dir(local, path, timestamp,
264 gpu_name);
265 if (path == NULL)
266 goto fail;
267 }
268
269 if (path == NULL) {
270 char *xdg_cache_home = getenv("XDG_CACHE_HOME");
271
272 if (xdg_cache_home) {
273 if (mkdir_if_needed(xdg_cache_home) == -1)
274 goto fail;
275
276 path = create_mesa_cache_dir(local, xdg_cache_home, timestamp,
277 gpu_name);
278 if (path == NULL)
279 goto fail;
280 }
281 }
282
283 if (path == NULL) {
284 char *buf;
285 size_t buf_size;
286 struct passwd pwd, *result;
287
288 buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
289 if (buf_size == -1)
290 buf_size = 512;
291
292 /* Loop until buf_size is large enough to query the directory */
293 while (1) {
294 buf = ralloc_size(local, buf_size);
295
296 getpwuid_r(getuid(), &pwd, buf, buf_size, &result);
297 if (result)
298 break;
299
300 if (errno == ERANGE) {
301 ralloc_free(buf);
302 buf = NULL;
303 buf_size *= 2;
304 } else {
305 goto fail;
306 }
307 }
308
309 path = concatenate_and_mkdir(local, pwd.pw_dir, ".cache");
310 if (path == NULL)
311 goto fail;
312
313 path = create_mesa_cache_dir(local, path, timestamp, gpu_name);
314 if (path == NULL)
315 goto fail;
316 }
317
318 cache = ralloc(NULL, struct disk_cache);
319 if (cache == NULL)
320 goto fail;
321
322 cache->path = ralloc_strdup(cache, path);
323 if (cache->path == NULL)
324 goto fail;
325
326 path = ralloc_asprintf(local, "%s/index", cache->path);
327 if (path == NULL)
328 goto fail;
329
330 fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
331 if (fd == -1)
332 goto fail;
333
334 if (fstat(fd, &sb) == -1)
335 goto fail;
336
337 /* Force the index file to be the expected size. */
338 size = sizeof(*cache->size) + CACHE_INDEX_MAX_KEYS * CACHE_KEY_SIZE;
339 if (sb.st_size != size) {
340 if (ftruncate(fd, size) == -1)
341 goto fail;
342 }
343
344 /* We map this shared so that other processes see updates that we
345 * make.
346 *
347 * Note: We do use atomic addition to ensure that multiple
348 * processes don't scramble the cache size recorded in the
349 * index. But we don't use any locking to prevent multiple
350 * processes from updating the same entry simultaneously. The idea
351 * is that if either result lands entirely in the index, then
352 * that's equivalent to a well-ordered write followed by an
353 * eviction and a write. On the other hand, if the simultaneous
354 * writes result in a corrupt entry, that's not really any
355 * different than both entries being evicted, (since within the
356 * guarantees of the cryptographic hash, a corrupt entry is
357 * unlikely to ever match a real cache key).
358 */
359 cache->index_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE,
360 MAP_SHARED, fd, 0);
361 if (cache->index_mmap == MAP_FAILED)
362 goto fail;
363 cache->index_mmap_size = size;
364
365 close(fd);
366
367 cache->size = (uint64_t *) cache->index_mmap;
368 cache->stored_keys = cache->index_mmap + sizeof(uint64_t);
369
370 max_size = 0;
371
372 max_size_str = getenv("MESA_GLSL_CACHE_MAX_SIZE");
373 if (max_size_str) {
374 char *end;
375 max_size = strtoul(max_size_str, &end, 10);
376 if (end == max_size_str) {
377 max_size = 0;
378 } else {
379 switch (*end) {
380 case 'K':
381 case 'k':
382 max_size *= 1024;
383 break;
384 case 'M':
385 case 'm':
386 max_size *= 1024*1024;
387 break;
388 case '\0':
389 case 'G':
390 case 'g':
391 default:
392 max_size *= 1024*1024*1024;
393 break;
394 }
395 }
396 }
397
398 /* Default to 1GB for maximum cache size. */
399 if (max_size == 0)
400 max_size = 1024*1024*1024;
401
402 cache->max_size = max_size;
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 munmap(cache->index_mmap, cache->index_mmap_size);
423
424 ralloc_free(cache);
425 }
426
427 /* Return a filename within the cache's directory corresponding to 'key'. The
428 * returned filename is ralloced with 'cache' as the parent context.
429 *
430 * Returns NULL if out of memory.
431 */
432 static char *
433 get_cache_file(struct disk_cache *cache, const cache_key key)
434 {
435 char buf[41];
436 char *filename;
437
438 _mesa_sha1_format(buf, key);
439 if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
440 buf[1], buf + 2) == -1)
441 return NULL;
442
443 return filename;
444 }
445
446 /* Create the directory that will be needed for the cache file for \key.
447 *
448 * Obviously, the implementation here must closely match
449 * _get_cache_file above.
450 */
451 static void
452 make_cache_file_directory(struct disk_cache *cache, const cache_key key)
453 {
454 char *dir;
455 char buf[41];
456
457 _mesa_sha1_format(buf, key);
458 if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
459 return;
460
461 mkdir_if_needed(dir);
462 free(dir);
463 }
464
465 /* Given a directory path and predicate function, count all entries in
466 * that directory for which the predicate returns true. Then choose a
467 * random entry from among those counted.
468 *
469 * Returns: A malloc'ed string for the path to the chosen file, (or
470 * NULL on any error). The caller should free the string when
471 * finished.
472 */
473 static char *
474 choose_random_file_matching(const char *dir_path,
475 bool (*predicate)(const struct dirent *,
476 const char *dir_path))
477 {
478 DIR *dir;
479 struct dirent *entry;
480 unsigned int count, victim;
481 char *filename;
482
483 dir = opendir(dir_path);
484 if (dir == NULL)
485 return NULL;
486
487 count = 0;
488
489 while (1) {
490 entry = readdir(dir);
491 if (entry == NULL)
492 break;
493 if (!predicate(entry, dir_path))
494 continue;
495
496 count++;
497 }
498
499 if (count == 0) {
500 closedir(dir);
501 return NULL;
502 }
503
504 victim = rand() % count;
505
506 rewinddir(dir);
507 count = 0;
508
509 while (1) {
510 entry = readdir(dir);
511 if (entry == NULL)
512 break;
513 if (!predicate(entry, dir_path))
514 continue;
515 if (count == victim)
516 break;
517
518 count++;
519 }
520
521 if (entry == NULL) {
522 closedir(dir);
523 return NULL;
524 }
525
526 if (asprintf(&filename, "%s/%s", dir_path, entry->d_name) < 0)
527 filename = NULL;
528
529 closedir(dir);
530
531 return filename;
532 }
533
534 /* Is entry a regular file, and not having a name with a trailing
535 * ".tmp"
536 */
537 static bool
538 is_regular_non_tmp_file(const struct dirent *entry, const char *path)
539 {
540 char *filename;
541 if (asprintf(&filename, "%s/%s", path, entry->d_name) == -1)
542 return false;
543
544 struct stat sb;
545 int res = stat(filename, &sb);
546 free(filename);
547
548 if (res == -1 || !S_ISREG(sb.st_mode))
549 return false;
550
551 size_t len = strlen (entry->d_name);
552 if (len >= 4 && strcmp(&entry->d_name[len-4], ".tmp") == 0)
553 return false;
554
555 return true;
556 }
557
558 /* Returns the size of the deleted file, (or 0 on any error). */
559 static size_t
560 unlink_random_file_from_directory(const char *path)
561 {
562 struct stat sb;
563 char *filename;
564
565 filename = choose_random_file_matching(path, is_regular_non_tmp_file);
566 if (filename == NULL)
567 return 0;
568
569 if (stat(filename, &sb) == -1) {
570 free (filename);
571 return 0;
572 }
573
574 unlink(filename);
575
576 free (filename);
577
578 return sb.st_size;
579 }
580
581 /* Is entry a directory with a two-character name, (and not the
582 * special name of "..")
583 */
584 static bool
585 is_two_character_sub_directory(const struct dirent *entry, const char *path)
586 {
587 char *subdir;
588 if (asprintf(&subdir, "%s/%s", path, entry->d_name) == -1)
589 return false;
590
591 struct stat sb;
592 int res = stat(subdir, &sb);
593 free(subdir);
594
595 if (res == -1 || !S_ISDIR(sb.st_mode))
596 return false;
597
598 if (strlen(entry->d_name) != 2)
599 return false;
600
601 if (strcmp(entry->d_name, "..") == 0)
602 return false;
603
604 return true;
605 }
606
607 static void
608 evict_random_item(struct disk_cache *cache)
609 {
610 const char hex[] = "0123456789abcde";
611 char *dir_path;
612 int a, b;
613 size_t size;
614
615 /* With a reasonably-sized, full cache, (and with keys generated
616 * from a cryptographic hash), we can choose two random hex digits
617 * and reasonably expect the directory to exist with a file in it.
618 */
619 a = rand() % 16;
620 b = rand() % 16;
621
622 if (asprintf(&dir_path, "%s/%c%c", cache->path, hex[a], hex[b]) < 0)
623 return;
624
625 size = unlink_random_file_from_directory(dir_path);
626
627 free(dir_path);
628
629 if (size) {
630 p_atomic_add(cache->size, - size);
631 return;
632 }
633
634 /* In the case where the random choice of directory didn't find
635 * something, we choose randomly from the existing directories.
636 *
637 * Really, the only reason this code exists is to allow the unit
638 * tests to work, (which use an artificially-small cache to be able
639 * to force a single cached item to be evicted).
640 */
641 dir_path = choose_random_file_matching(cache->path,
642 is_two_character_sub_directory);
643 if (dir_path == NULL)
644 return;
645
646 size = unlink_random_file_from_directory(dir_path);
647
648 free(dir_path);
649
650 if (size)
651 p_atomic_add(cache->size, - size);
652 }
653
654 void
655 disk_cache_remove(struct disk_cache *cache, const cache_key key)
656 {
657 struct stat sb;
658
659 char *filename = get_cache_file(cache, key);
660 if (filename == NULL) {
661 return;
662 }
663
664 if (stat(filename, &sb) == -1) {
665 free(filename);
666 return;
667 }
668
669 unlink(filename);
670 free(filename);
671
672 if (sb.st_size)
673 p_atomic_add(cache->size, - sb.st_size);
674 }
675
676 /* From the zlib docs:
677 * "If the memory is available, buffers sizes on the order of 128K or 256K
678 * bytes should be used."
679 */
680 #define BUFSIZE 256 * 1024
681
682 /**
683 * Compresses cache entry in memory and writes it to disk. Returns the size
684 * of the data written to disk.
685 */
686 static size_t
687 deflate_and_write_to_disk(const void *in_data, size_t in_data_size, int dest,
688 const char *filename)
689 {
690 unsigned char out[BUFSIZE];
691
692 /* allocate deflate state */
693 z_stream strm;
694 strm.zalloc = Z_NULL;
695 strm.zfree = Z_NULL;
696 strm.opaque = Z_NULL;
697 strm.next_in = (uint8_t *) in_data;
698 strm.avail_in = in_data_size;
699
700 int ret = deflateInit(&strm, Z_BEST_COMPRESSION);
701 if (ret != Z_OK)
702 return 0;
703
704 /* compress until end of in_data */
705 size_t compressed_size = 0;
706 int flush;
707 do {
708 int remaining = in_data_size - BUFSIZE;
709 flush = remaining > 0 ? Z_NO_FLUSH : Z_FINISH;
710 in_data_size -= BUFSIZE;
711
712 /* Run deflate() on input until the output buffer is not full (which
713 * means there is no more data to deflate).
714 */
715 do {
716 strm.avail_out = BUFSIZE;
717 strm.next_out = out;
718
719 ret = deflate(&strm, flush); /* no bad return value */
720 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
721
722 size_t have = BUFSIZE - strm.avail_out;
723 compressed_size += compressed_size + have;
724
725 size_t written = 0;
726 for (size_t len = 0; len < have; len += written) {
727 written = write(dest, out + len, have - len);
728 if (written == -1) {
729 (void)deflateEnd(&strm);
730 return 0;
731 }
732 }
733 } while (strm.avail_out == 0);
734
735 /* all input should be used */
736 assert(strm.avail_in == 0);
737
738 } while (flush != Z_FINISH);
739
740 /* stream should be complete */
741 assert(ret == Z_STREAM_END);
742
743 /* clean up and return */
744 (void)deflateEnd(&strm);
745 return compressed_size;
746 }
747
748 struct cache_entry_file_data {
749 uint32_t crc32;
750 uint32_t uncompressed_size;
751 };
752
753 void
754 disk_cache_put(struct disk_cache *cache,
755 const cache_key key,
756 const void *data,
757 size_t size)
758 {
759 int fd = -1, fd_final = -1, err, ret;
760 size_t len;
761 char *filename = NULL, *filename_tmp = NULL;
762
763 filename = get_cache_file(cache, key);
764 if (filename == NULL)
765 goto done;
766
767 /* Write to a temporary file to allow for an atomic rename to the
768 * final destination filename, (to prevent any readers from seeing
769 * a partially written file).
770 */
771 if (asprintf(&filename_tmp, "%s.tmp", filename) == -1)
772 goto done;
773
774 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
775
776 /* Make the two-character subdirectory within the cache as needed. */
777 if (fd == -1) {
778 if (errno != ENOENT)
779 goto done;
780
781 make_cache_file_directory(cache, key);
782
783 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
784 if (fd == -1)
785 goto done;
786 }
787
788 /* With the temporary file open, we take an exclusive flock on
789 * it. If the flock fails, then another process still has the file
790 * open with the flock held. So just let that file be responsible
791 * for writing the file.
792 */
793 err = flock(fd, LOCK_EX | LOCK_NB);
794 if (err == -1)
795 goto done;
796
797 /* Now that we have the lock on the open temporary file, we can
798 * check to see if the destination file already exists. If so,
799 * another process won the race between when we saw that the file
800 * didn't exist and now. In this case, we don't do anything more,
801 * (to ensure the size accounting of the cache doesn't get off).
802 */
803 fd_final = open(filename, O_RDONLY | O_CLOEXEC);
804 if (fd_final != -1)
805 goto done;
806
807 /* OK, we're now on the hook to write out a file that we know is
808 * not in the cache, and is also not being written out to the cache
809 * by some other process.
810 *
811 * Before we do that, if the cache is too large, evict something
812 * else first.
813 */
814 if (*cache->size + size > cache->max_size)
815 evict_random_item(cache);
816
817 /* Create CRC of the data and store at the start of the file. We will
818 * read this when restoring the cache and use it to check for corruption.
819 */
820 struct cache_entry_file_data cf_data;
821 cf_data.crc32 = util_hash_crc32(data, size);
822 cf_data.uncompressed_size = size;
823
824 size_t cf_data_size = sizeof(cf_data);
825 for (len = 0; len < cf_data_size; len += ret) {
826 ret = write(fd, ((uint8_t *) &cf_data) + len, cf_data_size - len);
827 if (ret == -1) {
828 unlink(filename_tmp);
829 goto done;
830 }
831 }
832
833 /* Now, finally, write out the contents to the temporary file, then
834 * rename them atomically to the destination filename, and also
835 * perform an atomic increment of the total cache size.
836 */
837 size_t file_size = deflate_and_write_to_disk(data, size, fd, filename_tmp);
838 if (file_size == 0) {
839 unlink(filename_tmp);
840 goto done;
841 }
842 rename(filename_tmp, filename);
843
844 file_size += cf_data_size;
845 p_atomic_add(cache->size, file_size);
846
847 done:
848 if (fd_final != -1)
849 close(fd_final);
850 /* This close finally releases the flock, (now that the final dile
851 * has been renamed into place and the size has been added).
852 */
853 if (fd != -1)
854 close(fd);
855 if (filename_tmp)
856 free(filename_tmp);
857 if (filename)
858 free(filename);
859 }
860
861 /**
862 * Decompresses cache entry, returns true if successful.
863 */
864 static bool
865 inflate_cache_data(uint8_t *in_data, size_t in_data_size,
866 uint8_t *out_data, size_t out_data_size)
867 {
868 z_stream strm;
869
870 /* allocate inflate state */
871 strm.zalloc = Z_NULL;
872 strm.zfree = Z_NULL;
873 strm.opaque = Z_NULL;
874 strm.next_in = in_data;
875 strm.avail_in = in_data_size;
876 strm.next_out = out_data;
877 strm.avail_out = out_data_size;
878
879 int ret = inflateInit(&strm);
880 if (ret != Z_OK)
881 return false;
882
883 ret = inflate(&strm, Z_NO_FLUSH);
884 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
885
886 /* Unless there was an error we should have decompressed everything in one
887 * go as we know the uncompressed file size.
888 */
889 if (ret != Z_STREAM_END) {
890 (void)inflateEnd(&strm);
891 return false;
892 }
893 assert(strm.avail_out == 0);
894
895 /* clean up and return */
896 (void)inflateEnd(&strm);
897 return true;
898 }
899
900 void *
901 disk_cache_get(struct disk_cache *cache, const cache_key key, size_t *size)
902 {
903 int fd = -1, ret, len;
904 struct stat sb;
905 char *filename = NULL;
906 uint8_t *data = NULL;
907 uint8_t *uncompressed_data = NULL;
908
909 if (size)
910 *size = 0;
911
912 filename = get_cache_file(cache, key);
913 if (filename == NULL)
914 goto fail;
915
916 fd = open(filename, O_RDONLY | O_CLOEXEC);
917 if (fd == -1)
918 goto fail;
919
920 if (fstat(fd, &sb) == -1)
921 goto fail;
922
923 data = malloc(sb.st_size);
924 if (data == NULL)
925 goto fail;
926
927 /* Load the CRC that was created when the file was written. */
928 struct cache_entry_file_data cf_data;
929 size_t cf_data_size = sizeof(cf_data);
930 assert(sb.st_size > cf_data_size);
931 for (len = 0; len < cf_data_size; len += ret) {
932 ret = read(fd, ((uint8_t *) &cf_data) + len, cf_data_size - len);
933 if (ret == -1)
934 goto fail;
935 }
936
937 /* Load the actual cache data. */
938 size_t cache_data_size = sb.st_size - cf_data_size;
939 for (len = 0; len < cache_data_size; len += ret) {
940 ret = read(fd, data + len, cache_data_size - len);
941 if (ret == -1)
942 goto fail;
943 }
944
945 /* Uncompress the cache data */
946 uncompressed_data = malloc(cf_data.uncompressed_size);
947 if (!inflate_cache_data(data, cache_data_size, uncompressed_data,
948 cf_data.uncompressed_size))
949 goto fail;
950
951 /* Check the data for corruption */
952 if (cf_data.crc32 != util_hash_crc32(uncompressed_data,
953 cf_data.uncompressed_size))
954 goto fail;
955
956 free(data);
957 free(filename);
958 close(fd);
959
960 if (size)
961 *size = cf_data.uncompressed_size;
962
963 return uncompressed_data;
964
965 fail:
966 if (data)
967 free(data);
968 if (uncompressed_data)
969 free(uncompressed_data);
970 if (filename)
971 free(filename);
972 if (fd != -1)
973 close(fd);
974
975 return NULL;
976 }
977
978 void
979 disk_cache_put_key(struct disk_cache *cache, const cache_key key)
980 {
981 const uint32_t *key_chunk = (const uint32_t *) key;
982 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
983 unsigned char *entry;
984
985 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
986
987 memcpy(entry, key, CACHE_KEY_SIZE);
988 }
989
990 /* This function lets us test whether a given key was previously
991 * stored in the cache with disk_cache_put_key(). The implement is
992 * efficient by not using syscalls or hitting the disk. It's not
993 * race-free, but the races are benign. If we race with someone else
994 * calling disk_cache_put_key, then that's just an extra cache miss and an
995 * extra recompile.
996 */
997 bool
998 disk_cache_has_key(struct disk_cache *cache, const cache_key key)
999 {
1000 const uint32_t *key_chunk = (const uint32_t *) key;
1001 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
1002 unsigned char *entry;
1003
1004 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
1005
1006 return memcmp(entry, key, CACHE_KEY_SIZE) == 0;
1007 }
1008
1009 #endif /* ENABLE_SHADER_CACHE */