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