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