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