util/macros: Add ATTRIBUTE_NOINLINE definition for MSVC
[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 <inttypes.h>
41 #include "zlib.h"
42
43 #ifdef HAVE_ZSTD
44 #include "zstd.h"
45 #endif
46
47 #include "util/crc32.h"
48 #include "util/debug.h"
49 #include "util/rand_xor.h"
50 #include "util/u_atomic.h"
51 #include "util/u_queue.h"
52 #include "util/mesa-sha1.h"
53 #include "util/ralloc.h"
54 #include "util/compiler.h"
55
56 #include "disk_cache.h"
57
58 /* Number of bits to mask off from a cache key to get an index. */
59 #define CACHE_INDEX_KEY_BITS 16
60
61 /* Mask for computing an index from a key. */
62 #define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
63
64 /* The number of keys that can be stored in the index. */
65 #define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
66
67 /* The cache version should be bumped whenever a change is made to the
68 * structure of cache entries or the index. This will give any 3rd party
69 * applications reading the cache entries a chance to adjust to the changes.
70 *
71 * - The cache version is checked internally when reading a cache entry. If we
72 * ever have a mismatch we are in big trouble as this means we had a cache
73 * collision. In case of such an event please check the skys for giant
74 * asteroids and that the entire Mesa team hasn't been eaten by wolves.
75 *
76 * - There is no strict requirement that cache versions be backwards
77 * compatible but effort should be taken to limit disruption where possible.
78 */
79 #define CACHE_VERSION 1
80
81 /* 3 is the recomended level, with 22 as the absolute maximum */
82 #define ZSTD_COMPRESSION_LEVEL 3
83
84 struct disk_cache {
85 /* The path to the cache directory. */
86 char *path;
87 bool path_init_failed;
88
89 /* Thread queue for compressing and writing cache entries to disk */
90 struct util_queue cache_queue;
91
92 /* Seed for rand, which is used to pick a random directory */
93 uint64_t seed_xorshift128plus[2];
94
95 /* A pointer to the mmapped index file within the cache directory. */
96 uint8_t *index_mmap;
97 size_t index_mmap_size;
98
99 /* Pointer to total size of all objects in cache (within index_mmap) */
100 uint64_t *size;
101
102 /* Pointer to stored keys, (within index_mmap). */
103 uint8_t *stored_keys;
104
105 /* Maximum size of all cached objects (in bytes). */
106 uint64_t max_size;
107
108 /* Driver cache keys. */
109 uint8_t *driver_keys_blob;
110 size_t driver_keys_blob_size;
111
112 disk_cache_put_cb blob_put_cb;
113 disk_cache_get_cb blob_get_cb;
114 };
115
116 struct disk_cache_put_job {
117 struct util_queue_fence fence;
118
119 struct disk_cache *cache;
120
121 cache_key key;
122
123 /* Copy of cache data to be compressed and written. */
124 void *data;
125
126 /* Size of data to be compressed and written. */
127 size_t size;
128
129 struct cache_item_metadata cache_item_metadata;
130 };
131
132 /* Create a directory named 'path' if it does not already exist.
133 *
134 * Returns: 0 if path already exists as a directory or if created.
135 * -1 in all other cases.
136 */
137 static int
138 mkdir_if_needed(const char *path)
139 {
140 struct stat sb;
141
142 /* If the path exists already, then our work is done if it's a
143 * directory, but it's an error if it is not.
144 */
145 if (stat(path, &sb) == 0) {
146 if (S_ISDIR(sb.st_mode)) {
147 return 0;
148 } else {
149 fprintf(stderr, "Cannot use %s for shader cache (not a directory)"
150 "---disabling.\n", path);
151 return -1;
152 }
153 }
154
155 int ret = mkdir(path, 0755);
156 if (ret == 0 || (ret == -1 && errno == EEXIST))
157 return 0;
158
159 fprintf(stderr, "Failed to create %s for shader cache (%s)---disabling.\n",
160 path, strerror(errno));
161
162 return -1;
163 }
164
165 /* Concatenate an existing path and a new name to form a new path. If the new
166 * path does not exist as a directory, create it then return the resulting
167 * name of the new path (ralloc'ed off of 'ctx').
168 *
169 * Returns NULL on any error, such as:
170 *
171 * <path> does not exist or is not a directory
172 * <path>/<name> exists but is not a directory
173 * <path>/<name> cannot be created as a directory
174 */
175 static char *
176 concatenate_and_mkdir(void *ctx, const char *path, const char *name)
177 {
178 char *new_path;
179 struct stat sb;
180
181 if (stat(path, &sb) != 0 || ! S_ISDIR(sb.st_mode))
182 return NULL;
183
184 new_path = ralloc_asprintf(ctx, "%s/%s", path, name);
185
186 if (mkdir_if_needed(new_path) == 0)
187 return new_path;
188 else
189 return NULL;
190 }
191
192 #define DRV_KEY_CPY(_dst, _src, _src_size) \
193 do { \
194 memcpy(_dst, _src, _src_size); \
195 _dst += _src_size; \
196 } while (0);
197
198 struct disk_cache *
199 disk_cache_create(const char *gpu_name, const char *driver_id,
200 uint64_t driver_flags)
201 {
202 void *local;
203 struct disk_cache *cache = NULL;
204 char *path, *max_size_str;
205 uint64_t max_size;
206 int fd = -1;
207 struct stat sb;
208 size_t size;
209
210 uint8_t cache_version = CACHE_VERSION;
211 size_t cv_size = sizeof(cache_version);
212
213 /* If running as a users other than the real user disable cache */
214 if (geteuid() != getuid())
215 return NULL;
216
217 /* A ralloc context for transient data during this invocation. */
218 local = ralloc_context(NULL);
219 if (local == NULL)
220 goto fail;
221
222 /* At user request, disable shader cache entirely. */
223 if (env_var_as_boolean("MESA_GLSL_CACHE_DISABLE", false))
224 goto fail;
225
226 cache = rzalloc(NULL, struct disk_cache);
227 if (cache == NULL)
228 goto fail;
229
230 /* Assume failure. */
231 cache->path_init_failed = true;
232
233 /* Determine path for cache based on the first defined name as follows:
234 *
235 * $MESA_GLSL_CACHE_DIR
236 * $XDG_CACHE_HOME/mesa_shader_cache
237 * <pwd.pw_dir>/.cache/mesa_shader_cache
238 */
239 path = getenv("MESA_GLSL_CACHE_DIR");
240 if (path) {
241 if (mkdir_if_needed(path) == -1)
242 goto path_fail;
243
244 path = concatenate_and_mkdir(local, path, CACHE_DIR_NAME);
245 if (path == NULL)
246 goto path_fail;
247 }
248
249 if (path == NULL) {
250 char *xdg_cache_home = getenv("XDG_CACHE_HOME");
251
252 if (xdg_cache_home) {
253 if (mkdir_if_needed(xdg_cache_home) == -1)
254 goto path_fail;
255
256 path = concatenate_and_mkdir(local, xdg_cache_home, CACHE_DIR_NAME);
257 if (path == NULL)
258 goto path_fail;
259 }
260 }
261
262 if (path == NULL) {
263 char *buf;
264 size_t buf_size;
265 struct passwd pwd, *result;
266
267 buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
268 if (buf_size == -1)
269 buf_size = 512;
270
271 /* Loop until buf_size is large enough to query the directory */
272 while (1) {
273 buf = ralloc_size(local, buf_size);
274
275 getpwuid_r(getuid(), &pwd, buf, buf_size, &result);
276 if (result)
277 break;
278
279 if (errno == ERANGE) {
280 ralloc_free(buf);
281 buf = NULL;
282 buf_size *= 2;
283 } else {
284 goto path_fail;
285 }
286 }
287
288 path = concatenate_and_mkdir(local, pwd.pw_dir, ".cache");
289 if (path == NULL)
290 goto path_fail;
291
292 path = concatenate_and_mkdir(local, path, CACHE_DIR_NAME);
293 if (path == NULL)
294 goto path_fail;
295 }
296
297 cache->path = ralloc_strdup(cache, path);
298 if (cache->path == NULL)
299 goto path_fail;
300
301 path = ralloc_asprintf(local, "%s/index", cache->path);
302 if (path == NULL)
303 goto path_fail;
304
305 fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
306 if (fd == -1)
307 goto path_fail;
308
309 if (fstat(fd, &sb) == -1)
310 goto path_fail;
311
312 /* Force the index file to be the expected size. */
313 size = sizeof(*cache->size) + CACHE_INDEX_MAX_KEYS * CACHE_KEY_SIZE;
314 if (sb.st_size != size) {
315 if (ftruncate(fd, size) == -1)
316 goto path_fail;
317 }
318
319 /* We map this shared so that other processes see updates that we
320 * make.
321 *
322 * Note: We do use atomic addition to ensure that multiple
323 * processes don't scramble the cache size recorded in the
324 * index. But we don't use any locking to prevent multiple
325 * processes from updating the same entry simultaneously. The idea
326 * is that if either result lands entirely in the index, then
327 * that's equivalent to a well-ordered write followed by an
328 * eviction and a write. On the other hand, if the simultaneous
329 * writes result in a corrupt entry, that's not really any
330 * different than both entries being evicted, (since within the
331 * guarantees of the cryptographic hash, a corrupt entry is
332 * unlikely to ever match a real cache key).
333 */
334 cache->index_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE,
335 MAP_SHARED, fd, 0);
336 if (cache->index_mmap == MAP_FAILED)
337 goto path_fail;
338 cache->index_mmap_size = size;
339
340 cache->size = (uint64_t *) cache->index_mmap;
341 cache->stored_keys = cache->index_mmap + sizeof(uint64_t);
342
343 max_size = 0;
344
345 max_size_str = getenv("MESA_GLSL_CACHE_MAX_SIZE");
346 if (max_size_str) {
347 char *end;
348 max_size = strtoul(max_size_str, &end, 10);
349 if (end == max_size_str) {
350 max_size = 0;
351 } else {
352 switch (*end) {
353 case 'K':
354 case 'k':
355 max_size *= 1024;
356 break;
357 case 'M':
358 case 'm':
359 max_size *= 1024*1024;
360 break;
361 case '\0':
362 case 'G':
363 case 'g':
364 default:
365 max_size *= 1024*1024*1024;
366 break;
367 }
368 }
369 }
370
371 /* Default to 1GB for maximum cache size. */
372 if (max_size == 0) {
373 max_size = 1024*1024*1024;
374 }
375
376 cache->max_size = max_size;
377
378 /* 4 threads were chosen below because just about all modern CPUs currently
379 * available that run Mesa have *at least* 4 cores. For these CPUs allowing
380 * more threads can result in the queue being processed faster, thus
381 * avoiding excessive memory use due to a backlog of cache entrys building
382 * up in the queue. Since we set the UTIL_QUEUE_INIT_USE_MINIMUM_PRIORITY
383 * flag this should have little negative impact on low core systems.
384 *
385 * The queue will resize automatically when it's full, so adding new jobs
386 * doesn't stall.
387 */
388 util_queue_init(&cache->cache_queue, "disk$", 32, 4,
389 UTIL_QUEUE_INIT_RESIZE_IF_FULL |
390 UTIL_QUEUE_INIT_USE_MINIMUM_PRIORITY |
391 UTIL_QUEUE_INIT_SET_FULL_THREAD_AFFINITY);
392
393 cache->path_init_failed = false;
394
395 path_fail:
396
397 if (fd != -1)
398 close(fd);
399
400 cache->driver_keys_blob_size = cv_size;
401
402 /* Create driver id keys */
403 size_t id_size = strlen(driver_id) + 1;
404 size_t gpu_name_size = strlen(gpu_name) + 1;
405 cache->driver_keys_blob_size += id_size;
406 cache->driver_keys_blob_size += gpu_name_size;
407
408 /* We sometimes store entire structs that contains a pointers in the cache,
409 * use pointer size as a key to avoid hard to debug issues.
410 */
411 uint8_t ptr_size = sizeof(void *);
412 size_t ptr_size_size = sizeof(ptr_size);
413 cache->driver_keys_blob_size += ptr_size_size;
414
415 size_t driver_flags_size = sizeof(driver_flags);
416 cache->driver_keys_blob_size += driver_flags_size;
417
418 cache->driver_keys_blob =
419 ralloc_size(cache, cache->driver_keys_blob_size);
420 if (!cache->driver_keys_blob)
421 goto fail;
422
423 uint8_t *drv_key_blob = cache->driver_keys_blob;
424 DRV_KEY_CPY(drv_key_blob, &cache_version, cv_size)
425 DRV_KEY_CPY(drv_key_blob, driver_id, id_size)
426 DRV_KEY_CPY(drv_key_blob, gpu_name, gpu_name_size)
427 DRV_KEY_CPY(drv_key_blob, &ptr_size, ptr_size_size)
428 DRV_KEY_CPY(drv_key_blob, &driver_flags, driver_flags_size)
429
430 /* Seed our rand function */
431 s_rand_xorshift128plus(cache->seed_xorshift128plus, true);
432
433 ralloc_free(local);
434
435 return cache;
436
437 fail:
438 if (cache)
439 ralloc_free(cache);
440 ralloc_free(local);
441
442 return NULL;
443 }
444
445 void
446 disk_cache_destroy(struct disk_cache *cache)
447 {
448 if (cache && !cache->path_init_failed) {
449 util_queue_finish(&cache->cache_queue);
450 util_queue_destroy(&cache->cache_queue);
451 munmap(cache->index_mmap, cache->index_mmap_size);
452 }
453
454 ralloc_free(cache);
455 }
456
457 void
458 disk_cache_wait_for_idle(struct disk_cache *cache)
459 {
460 util_queue_finish(&cache->cache_queue);
461 }
462
463 /* Return a filename within the cache's directory corresponding to 'key'. The
464 * returned filename is ralloced with 'cache' as the parent context.
465 *
466 * Returns NULL if out of memory.
467 */
468 static char *
469 get_cache_file(struct disk_cache *cache, const cache_key key)
470 {
471 char buf[41];
472 char *filename;
473
474 if (cache->path_init_failed)
475 return NULL;
476
477 _mesa_sha1_format(buf, key);
478 if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
479 buf[1], buf + 2) == -1)
480 return NULL;
481
482 return filename;
483 }
484
485 /* Create the directory that will be needed for the cache file for \key.
486 *
487 * Obviously, the implementation here must closely match
488 * _get_cache_file above.
489 */
490 static void
491 make_cache_file_directory(struct disk_cache *cache, const cache_key key)
492 {
493 char *dir;
494 char buf[41];
495
496 _mesa_sha1_format(buf, key);
497 if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
498 return;
499
500 mkdir_if_needed(dir);
501 free(dir);
502 }
503
504 /* Given a directory path and predicate function, find the entry with
505 * the oldest access time in that directory for which the predicate
506 * returns true.
507 *
508 * Returns: A malloc'ed string for the path to the chosen file, (or
509 * NULL on any error). The caller should free the string when
510 * finished.
511 */
512 static char *
513 choose_lru_file_matching(const char *dir_path,
514 bool (*predicate)(const char *dir_path,
515 const struct stat *,
516 const char *, const size_t))
517 {
518 DIR *dir;
519 struct dirent *entry;
520 char *filename;
521 char *lru_name = NULL;
522 time_t lru_atime = 0;
523
524 dir = opendir(dir_path);
525 if (dir == NULL)
526 return NULL;
527
528 while (1) {
529 entry = readdir(dir);
530 if (entry == NULL)
531 break;
532
533 struct stat sb;
534 if (fstatat(dirfd(dir), entry->d_name, &sb, 0) == 0) {
535 if (!lru_atime || (sb.st_atime < lru_atime)) {
536 size_t len = strlen(entry->d_name);
537
538 if (!predicate(dir_path, &sb, entry->d_name, len))
539 continue;
540
541 char *tmp = realloc(lru_name, len + 1);
542 if (tmp) {
543 lru_name = tmp;
544 memcpy(lru_name, entry->d_name, len + 1);
545 lru_atime = sb.st_atime;
546 }
547 }
548 }
549 }
550
551 if (lru_name == NULL) {
552 closedir(dir);
553 return NULL;
554 }
555
556 if (asprintf(&filename, "%s/%s", dir_path, lru_name) < 0)
557 filename = NULL;
558
559 free(lru_name);
560 closedir(dir);
561
562 return filename;
563 }
564
565 /* Is entry a regular file, and not having a name with a trailing
566 * ".tmp"
567 */
568 static bool
569 is_regular_non_tmp_file(const char *path, const struct stat *sb,
570 const char *d_name, const size_t len)
571 {
572 if (!S_ISREG(sb->st_mode))
573 return false;
574
575 if (len >= 4 && strcmp(&d_name[len-4], ".tmp") == 0)
576 return false;
577
578 return true;
579 }
580
581 /* Returns the size of the deleted file, (or 0 on any error). */
582 static size_t
583 unlink_lru_file_from_directory(const char *path)
584 {
585 struct stat sb;
586 char *filename;
587
588 filename = choose_lru_file_matching(path, is_regular_non_tmp_file);
589 if (filename == NULL)
590 return 0;
591
592 if (stat(filename, &sb) == -1) {
593 free (filename);
594 return 0;
595 }
596
597 unlink(filename);
598 free (filename);
599
600 return sb.st_blocks * 512;
601 }
602
603 /* Is entry a directory with a two-character name, (and not the
604 * special name of ".."). We also return false if the dir is empty.
605 */
606 static bool
607 is_two_character_sub_directory(const char *path, const struct stat *sb,
608 const char *d_name, const size_t len)
609 {
610 if (!S_ISDIR(sb->st_mode))
611 return false;
612
613 if (len != 2)
614 return false;
615
616 if (strcmp(d_name, "..") == 0)
617 return false;
618
619 char *subdir;
620 if (asprintf(&subdir, "%s/%s", path, d_name) == -1)
621 return false;
622 DIR *dir = opendir(subdir);
623 free(subdir);
624
625 if (dir == NULL)
626 return false;
627
628 unsigned subdir_entries = 0;
629 struct dirent *d;
630 while ((d = readdir(dir)) != NULL) {
631 if(++subdir_entries > 2)
632 break;
633 }
634 closedir(dir);
635
636 /* If dir only contains '.' and '..' it must be empty */
637 if (subdir_entries <= 2)
638 return false;
639
640 return true;
641 }
642
643 static void
644 evict_lru_item(struct disk_cache *cache)
645 {
646 char *dir_path;
647
648 /* With a reasonably-sized, full cache, (and with keys generated
649 * from a cryptographic hash), we can choose two random hex digits
650 * and reasonably expect the directory to exist with a file in it.
651 * Provides pseudo-LRU eviction to reduce checking all cache files.
652 */
653 uint64_t rand64 = rand_xorshift128plus(cache->seed_xorshift128plus);
654 if (asprintf(&dir_path, "%s/%02" PRIx64 , cache->path, rand64 & 0xff) < 0)
655 return;
656
657 size_t size = unlink_lru_file_from_directory(dir_path);
658
659 free(dir_path);
660
661 if (size) {
662 p_atomic_add(cache->size, - (uint64_t)size);
663 return;
664 }
665
666 /* In the case where the random choice of directory didn't find
667 * something, we choose the least recently accessed from the
668 * existing directories.
669 *
670 * Really, the only reason this code exists is to allow the unit
671 * tests to work, (which use an artificially-small cache to be able
672 * to force a single cached item to be evicted).
673 */
674 dir_path = choose_lru_file_matching(cache->path,
675 is_two_character_sub_directory);
676 if (dir_path == NULL)
677 return;
678
679 size = unlink_lru_file_from_directory(dir_path);
680
681 free(dir_path);
682
683 if (size)
684 p_atomic_add(cache->size, - (uint64_t)size);
685 }
686
687 void
688 disk_cache_remove(struct disk_cache *cache, const cache_key key)
689 {
690 struct stat sb;
691
692 char *filename = get_cache_file(cache, key);
693 if (filename == NULL) {
694 return;
695 }
696
697 if (stat(filename, &sb) == -1) {
698 free(filename);
699 return;
700 }
701
702 unlink(filename);
703 free(filename);
704
705 if (sb.st_blocks)
706 p_atomic_add(cache->size, - (uint64_t)sb.st_blocks * 512);
707 }
708
709 static ssize_t
710 read_all(int fd, void *buf, size_t count)
711 {
712 char *in = buf;
713 ssize_t read_ret;
714 size_t done;
715
716 for (done = 0; done < count; done += read_ret) {
717 read_ret = read(fd, in + done, count - done);
718 if (read_ret == -1 || read_ret == 0)
719 return -1;
720 }
721 return done;
722 }
723
724 static ssize_t
725 write_all(int fd, const void *buf, size_t count)
726 {
727 const char *out = buf;
728 ssize_t written;
729 size_t done;
730
731 for (done = 0; done < count; done += written) {
732 written = write(fd, out + done, count - done);
733 if (written == -1)
734 return -1;
735 }
736 return done;
737 }
738
739 /* From the zlib docs:
740 * "If the memory is available, buffers sizes on the order of 128K or 256K
741 * bytes should be used."
742 */
743 #define BUFSIZE 256 * 1024
744
745 /**
746 * Compresses cache entry in memory and writes it to disk. Returns the size
747 * of the data written to disk.
748 */
749 static size_t
750 deflate_and_write_to_disk(const void *in_data, size_t in_data_size, int dest,
751 const char *filename)
752 {
753 #ifdef HAVE_ZSTD
754 /* from the zstd docs (https://facebook.github.io/zstd/zstd_manual.html):
755 * compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`.
756 */
757 size_t out_size = ZSTD_compressBound(in_data_size);
758 void * out = malloc(out_size);
759
760 size_t ret = ZSTD_compress(out, out_size, in_data, in_data_size,
761 ZSTD_COMPRESSION_LEVEL);
762 if (ZSTD_isError(ret)) {
763 free(out);
764 return 0;
765 }
766 ssize_t written = write_all(dest, out, ret);
767 if (written == -1) {
768 free(out);
769 return 0;
770 }
771 free(out);
772 return ret;
773 #else
774 unsigned char *out;
775
776 /* allocate deflate state */
777 z_stream strm;
778 strm.zalloc = Z_NULL;
779 strm.zfree = Z_NULL;
780 strm.opaque = Z_NULL;
781 strm.next_in = (uint8_t *) in_data;
782 strm.avail_in = in_data_size;
783
784 int ret = deflateInit(&strm, Z_BEST_COMPRESSION);
785 if (ret != Z_OK)
786 return 0;
787
788 /* compress until end of in_data */
789 size_t compressed_size = 0;
790 int flush;
791
792 out = malloc(BUFSIZE * sizeof(unsigned char));
793 if (out == NULL)
794 return 0;
795
796 do {
797 int remaining = in_data_size - BUFSIZE;
798 flush = remaining > 0 ? Z_NO_FLUSH : Z_FINISH;
799 in_data_size -= BUFSIZE;
800
801 /* Run deflate() on input until the output buffer is not full (which
802 * means there is no more data to deflate).
803 */
804 do {
805 strm.avail_out = BUFSIZE;
806 strm.next_out = out;
807
808 ret = deflate(&strm, flush); /* no bad return value */
809 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
810
811 size_t have = BUFSIZE - strm.avail_out;
812 compressed_size += have;
813
814 ssize_t written = write_all(dest, out, have);
815 if (written == -1) {
816 (void)deflateEnd(&strm);
817 free(out);
818 return 0;
819 }
820 } while (strm.avail_out == 0);
821
822 /* all input should be used */
823 assert(strm.avail_in == 0);
824
825 } while (flush != Z_FINISH);
826
827 /* stream should be complete */
828 assert(ret == Z_STREAM_END);
829
830 /* clean up and return */
831 (void)deflateEnd(&strm);
832 free(out);
833 return compressed_size;
834 # endif
835 }
836
837 static struct disk_cache_put_job *
838 create_put_job(struct disk_cache *cache, const cache_key key,
839 const void *data, size_t size,
840 struct cache_item_metadata *cache_item_metadata)
841 {
842 struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *)
843 malloc(sizeof(struct disk_cache_put_job) + size);
844
845 if (dc_job) {
846 dc_job->cache = cache;
847 memcpy(dc_job->key, key, sizeof(cache_key));
848 dc_job->data = dc_job + 1;
849 memcpy(dc_job->data, data, size);
850 dc_job->size = size;
851
852 /* Copy the cache item metadata */
853 if (cache_item_metadata) {
854 dc_job->cache_item_metadata.type = cache_item_metadata->type;
855 if (cache_item_metadata->type == CACHE_ITEM_TYPE_GLSL) {
856 dc_job->cache_item_metadata.num_keys =
857 cache_item_metadata->num_keys;
858 dc_job->cache_item_metadata.keys = (cache_key *)
859 malloc(cache_item_metadata->num_keys * sizeof(cache_key));
860
861 if (!dc_job->cache_item_metadata.keys)
862 goto fail;
863
864 memcpy(dc_job->cache_item_metadata.keys,
865 cache_item_metadata->keys,
866 sizeof(cache_key) * cache_item_metadata->num_keys);
867 }
868 } else {
869 dc_job->cache_item_metadata.type = CACHE_ITEM_TYPE_UNKNOWN;
870 dc_job->cache_item_metadata.keys = NULL;
871 }
872 }
873
874 return dc_job;
875
876 fail:
877 free(dc_job);
878
879 return NULL;
880 }
881
882 static void
883 destroy_put_job(void *job, int thread_index)
884 {
885 if (job) {
886 struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *) job;
887 free(dc_job->cache_item_metadata.keys);
888
889 free(job);
890 }
891 }
892
893 struct cache_entry_file_data {
894 uint32_t crc32;
895 uint32_t uncompressed_size;
896 };
897
898 static void
899 cache_put(void *job, int thread_index)
900 {
901 assert(job);
902
903 int fd = -1, fd_final = -1, err, ret;
904 unsigned i = 0;
905 char *filename = NULL, *filename_tmp = NULL;
906 struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *) job;
907
908 filename = get_cache_file(dc_job->cache, dc_job->key);
909 if (filename == NULL)
910 goto done;
911
912 /* If the cache is too large, evict something else first. */
913 while (*dc_job->cache->size + dc_job->size > dc_job->cache->max_size &&
914 i < 8) {
915 evict_lru_item(dc_job->cache);
916 i++;
917 }
918
919 /* Write to a temporary file to allow for an atomic rename to the
920 * final destination filename, (to prevent any readers from seeing
921 * a partially written file).
922 */
923 if (asprintf(&filename_tmp, "%s.tmp", filename) == -1)
924 goto done;
925
926 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
927
928 /* Make the two-character subdirectory within the cache as needed. */
929 if (fd == -1) {
930 if (errno != ENOENT)
931 goto done;
932
933 make_cache_file_directory(dc_job->cache, dc_job->key);
934
935 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
936 if (fd == -1)
937 goto done;
938 }
939
940 /* With the temporary file open, we take an exclusive flock on
941 * it. If the flock fails, then another process still has the file
942 * open with the flock held. So just let that file be responsible
943 * for writing the file.
944 */
945 #ifdef HAVE_FLOCK
946 err = flock(fd, LOCK_EX | LOCK_NB);
947 #else
948 struct flock lock = {
949 .l_start = 0,
950 .l_len = 0, /* entire file */
951 .l_type = F_WRLCK,
952 .l_whence = SEEK_SET
953 };
954 err = fcntl(fd, F_SETLK, &lock);
955 #endif
956 if (err == -1)
957 goto done;
958
959 /* Now that we have the lock on the open temporary file, we can
960 * check to see if the destination file already exists. If so,
961 * another process won the race between when we saw that the file
962 * didn't exist and now. In this case, we don't do anything more,
963 * (to ensure the size accounting of the cache doesn't get off).
964 */
965 fd_final = open(filename, O_RDONLY | O_CLOEXEC);
966 if (fd_final != -1) {
967 unlink(filename_tmp);
968 goto done;
969 }
970
971 /* OK, we're now on the hook to write out a file that we know is
972 * not in the cache, and is also not being written out to the cache
973 * by some other process.
974 */
975
976 /* Write the driver_keys_blob, this can be used find information about the
977 * mesa version that produced the entry or deal with hash collisions,
978 * should that ever become a real problem.
979 */
980 ret = write_all(fd, dc_job->cache->driver_keys_blob,
981 dc_job->cache->driver_keys_blob_size);
982 if (ret == -1) {
983 unlink(filename_tmp);
984 goto done;
985 }
986
987 /* Write the cache item metadata. This data can be used to deal with
988 * hash collisions, as well as providing useful information to 3rd party
989 * tools reading the cache files.
990 */
991 ret = write_all(fd, &dc_job->cache_item_metadata.type,
992 sizeof(uint32_t));
993 if (ret == -1) {
994 unlink(filename_tmp);
995 goto done;
996 }
997
998 if (dc_job->cache_item_metadata.type == CACHE_ITEM_TYPE_GLSL) {
999 ret = write_all(fd, &dc_job->cache_item_metadata.num_keys,
1000 sizeof(uint32_t));
1001 if (ret == -1) {
1002 unlink(filename_tmp);
1003 goto done;
1004 }
1005
1006 ret = write_all(fd, dc_job->cache_item_metadata.keys[0],
1007 dc_job->cache_item_metadata.num_keys *
1008 sizeof(cache_key));
1009 if (ret == -1) {
1010 unlink(filename_tmp);
1011 goto done;
1012 }
1013 }
1014
1015 /* Create CRC of the data. We will read this when restoring the cache and
1016 * use it to check for corruption.
1017 */
1018 struct cache_entry_file_data cf_data;
1019 cf_data.crc32 = util_hash_crc32(dc_job->data, dc_job->size);
1020 cf_data.uncompressed_size = dc_job->size;
1021
1022 size_t cf_data_size = sizeof(cf_data);
1023 ret = write_all(fd, &cf_data, cf_data_size);
1024 if (ret == -1) {
1025 unlink(filename_tmp);
1026 goto done;
1027 }
1028
1029 /* Now, finally, write out the contents to the temporary file, then
1030 * rename them atomically to the destination filename, and also
1031 * perform an atomic increment of the total cache size.
1032 */
1033 size_t file_size = deflate_and_write_to_disk(dc_job->data, dc_job->size,
1034 fd, filename_tmp);
1035 if (file_size == 0) {
1036 unlink(filename_tmp);
1037 goto done;
1038 }
1039 ret = rename(filename_tmp, filename);
1040 if (ret == -1) {
1041 unlink(filename_tmp);
1042 goto done;
1043 }
1044
1045 struct stat sb;
1046 if (stat(filename, &sb) == -1) {
1047 /* Something went wrong remove the file */
1048 unlink(filename);
1049 goto done;
1050 }
1051
1052 p_atomic_add(dc_job->cache->size, sb.st_blocks * 512);
1053
1054 done:
1055 if (fd_final != -1)
1056 close(fd_final);
1057 /* This close finally releases the flock, (now that the final file
1058 * has been renamed into place and the size has been added).
1059 */
1060 if (fd != -1)
1061 close(fd);
1062 free(filename_tmp);
1063 free(filename);
1064 }
1065
1066 void
1067 disk_cache_put(struct disk_cache *cache, const cache_key key,
1068 const void *data, size_t size,
1069 struct cache_item_metadata *cache_item_metadata)
1070 {
1071 if (cache->blob_put_cb) {
1072 cache->blob_put_cb(key, CACHE_KEY_SIZE, data, size);
1073 return;
1074 }
1075
1076 if (cache->path_init_failed)
1077 return;
1078
1079 struct disk_cache_put_job *dc_job =
1080 create_put_job(cache, key, data, size, cache_item_metadata);
1081
1082 if (dc_job) {
1083 util_queue_fence_init(&dc_job->fence);
1084 util_queue_add_job(&cache->cache_queue, dc_job, &dc_job->fence,
1085 cache_put, destroy_put_job, dc_job->size);
1086 }
1087 }
1088
1089 /**
1090 * Decompresses cache entry, returns true if successful.
1091 */
1092 static bool
1093 inflate_cache_data(uint8_t *in_data, size_t in_data_size,
1094 uint8_t *out_data, size_t out_data_size)
1095 {
1096 #ifdef HAVE_ZSTD
1097 size_t ret = ZSTD_decompress(out_data, out_data_size, in_data, in_data_size);
1098 return !ZSTD_isError(ret);
1099 #else
1100 z_stream strm;
1101
1102 /* allocate inflate state */
1103 strm.zalloc = Z_NULL;
1104 strm.zfree = Z_NULL;
1105 strm.opaque = Z_NULL;
1106 strm.next_in = in_data;
1107 strm.avail_in = in_data_size;
1108 strm.next_out = out_data;
1109 strm.avail_out = out_data_size;
1110
1111 int ret = inflateInit(&strm);
1112 if (ret != Z_OK)
1113 return false;
1114
1115 ret = inflate(&strm, Z_NO_FLUSH);
1116 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
1117
1118 /* Unless there was an error we should have decompressed everything in one
1119 * go as we know the uncompressed file size.
1120 */
1121 if (ret != Z_STREAM_END) {
1122 (void)inflateEnd(&strm);
1123 return false;
1124 }
1125 assert(strm.avail_out == 0);
1126
1127 /* clean up and return */
1128 (void)inflateEnd(&strm);
1129 return true;
1130 #endif
1131 }
1132
1133 void *
1134 disk_cache_get(struct disk_cache *cache, const cache_key key, size_t *size)
1135 {
1136 int fd = -1, ret;
1137 struct stat sb;
1138 char *filename = NULL;
1139 uint8_t *data = NULL;
1140 uint8_t *uncompressed_data = NULL;
1141 uint8_t *file_header = NULL;
1142
1143 if (size)
1144 *size = 0;
1145
1146 if (cache->blob_get_cb) {
1147 /* This is what Android EGL defines as the maxValueSize in egl_cache_t
1148 * class implementation.
1149 */
1150 const signed long max_blob_size = 64 * 1024;
1151 void *blob = malloc(max_blob_size);
1152 if (!blob)
1153 return NULL;
1154
1155 signed long bytes =
1156 cache->blob_get_cb(key, CACHE_KEY_SIZE, blob, max_blob_size);
1157
1158 if (!bytes) {
1159 free(blob);
1160 return NULL;
1161 }
1162
1163 if (size)
1164 *size = bytes;
1165 return blob;
1166 }
1167
1168 filename = get_cache_file(cache, key);
1169 if (filename == NULL)
1170 goto fail;
1171
1172 fd = open(filename, O_RDONLY | O_CLOEXEC);
1173 if (fd == -1)
1174 goto fail;
1175
1176 if (fstat(fd, &sb) == -1)
1177 goto fail;
1178
1179 data = malloc(sb.st_size);
1180 if (data == NULL)
1181 goto fail;
1182
1183 size_t ck_size = cache->driver_keys_blob_size;
1184 file_header = malloc(ck_size);
1185 if (!file_header)
1186 goto fail;
1187
1188 if (sb.st_size < ck_size)
1189 goto fail;
1190
1191 ret = read_all(fd, file_header, ck_size);
1192 if (ret == -1)
1193 goto fail;
1194
1195 /* Check for extremely unlikely hash collisions */
1196 if (memcmp(cache->driver_keys_blob, file_header, ck_size) != 0) {
1197 assert(!"Mesa cache keys mismatch!");
1198 goto fail;
1199 }
1200
1201 size_t cache_item_md_size = sizeof(uint32_t);
1202 uint32_t md_type;
1203 ret = read_all(fd, &md_type, cache_item_md_size);
1204 if (ret == -1)
1205 goto fail;
1206
1207 if (md_type == CACHE_ITEM_TYPE_GLSL) {
1208 uint32_t num_keys;
1209 cache_item_md_size += sizeof(uint32_t);
1210 ret = read_all(fd, &num_keys, sizeof(uint32_t));
1211 if (ret == -1)
1212 goto fail;
1213
1214 /* The cache item metadata is currently just used for distributing
1215 * precompiled shaders, they are not used by Mesa so just skip them for
1216 * now.
1217 * TODO: pass the metadata back to the caller and do some basic
1218 * validation.
1219 */
1220 cache_item_md_size += num_keys * sizeof(cache_key);
1221 ret = lseek(fd, num_keys * sizeof(cache_key), SEEK_CUR);
1222 if (ret == -1)
1223 goto fail;
1224 }
1225
1226 /* Load the CRC that was created when the file was written. */
1227 struct cache_entry_file_data cf_data;
1228 size_t cf_data_size = sizeof(cf_data);
1229 ret = read_all(fd, &cf_data, cf_data_size);
1230 if (ret == -1)
1231 goto fail;
1232
1233 /* Load the actual cache data. */
1234 size_t cache_data_size =
1235 sb.st_size - cf_data_size - ck_size - cache_item_md_size;
1236 ret = read_all(fd, data, cache_data_size);
1237 if (ret == -1)
1238 goto fail;
1239
1240 /* Uncompress the cache data */
1241 uncompressed_data = malloc(cf_data.uncompressed_size);
1242 if (!inflate_cache_data(data, cache_data_size, uncompressed_data,
1243 cf_data.uncompressed_size))
1244 goto fail;
1245
1246 /* Check the data for corruption */
1247 if (cf_data.crc32 != util_hash_crc32(uncompressed_data,
1248 cf_data.uncompressed_size))
1249 goto fail;
1250
1251 free(data);
1252 free(filename);
1253 free(file_header);
1254 close(fd);
1255
1256 if (size)
1257 *size = cf_data.uncompressed_size;
1258
1259 return uncompressed_data;
1260
1261 fail:
1262 if (data)
1263 free(data);
1264 if (uncompressed_data)
1265 free(uncompressed_data);
1266 if (filename)
1267 free(filename);
1268 if (file_header)
1269 free(file_header);
1270 if (fd != -1)
1271 close(fd);
1272
1273 return NULL;
1274 }
1275
1276 void
1277 disk_cache_put_key(struct disk_cache *cache, const cache_key key)
1278 {
1279 const uint32_t *key_chunk = (const uint32_t *) key;
1280 int i = CPU_TO_LE32(*key_chunk) & CACHE_INDEX_KEY_MASK;
1281 unsigned char *entry;
1282
1283 if (cache->blob_put_cb) {
1284 cache->blob_put_cb(key, CACHE_KEY_SIZE, key_chunk, sizeof(uint32_t));
1285 return;
1286 }
1287
1288 if (cache->path_init_failed)
1289 return;
1290
1291 entry = &cache->stored_keys[i * CACHE_KEY_SIZE];
1292
1293 memcpy(entry, key, CACHE_KEY_SIZE);
1294 }
1295
1296 /* This function lets us test whether a given key was previously
1297 * stored in the cache with disk_cache_put_key(). The implement is
1298 * efficient by not using syscalls or hitting the disk. It's not
1299 * race-free, but the races are benign. If we race with someone else
1300 * calling disk_cache_put_key, then that's just an extra cache miss and an
1301 * extra recompile.
1302 */
1303 bool
1304 disk_cache_has_key(struct disk_cache *cache, const cache_key key)
1305 {
1306 const uint32_t *key_chunk = (const uint32_t *) key;
1307 int i = CPU_TO_LE32(*key_chunk) & CACHE_INDEX_KEY_MASK;
1308 unsigned char *entry;
1309
1310 if (cache->blob_get_cb) {
1311 uint32_t blob;
1312 return cache->blob_get_cb(key, CACHE_KEY_SIZE, &blob, sizeof(uint32_t));
1313 }
1314
1315 if (cache->path_init_failed)
1316 return false;
1317
1318 entry = &cache->stored_keys[i * CACHE_KEY_SIZE];
1319
1320 return memcmp(entry, key, CACHE_KEY_SIZE) == 0;
1321 }
1322
1323 void
1324 disk_cache_compute_key(struct disk_cache *cache, const void *data, size_t size,
1325 cache_key key)
1326 {
1327 struct mesa_sha1 ctx;
1328
1329 _mesa_sha1_init(&ctx);
1330 _mesa_sha1_update(&ctx, cache->driver_keys_blob,
1331 cache->driver_keys_blob_size);
1332 _mesa_sha1_update(&ctx, data, size);
1333 _mesa_sha1_final(&ctx, key);
1334 }
1335
1336 void
1337 disk_cache_set_callbacks(struct disk_cache *cache, disk_cache_put_cb put,
1338 disk_cache_get_cb get)
1339 {
1340 cache->blob_put_cb = put;
1341 cache->blob_get_cb = get;
1342 }
1343
1344 #endif /* ENABLE_SHADER_CACHE */