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