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