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