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