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