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