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