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