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