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