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
81 /* Thread queue for compressing and writing cache entries to disk */
82 struct util_queue cache_queue;
83
84 /* Seed for rand, which is used to pick a random directory */
85 uint64_t seed_xorshift128plus[2];
86
87 /* A pointer to the mmapped index file within the cache directory. */
88 uint8_t *index_mmap;
89 size_t index_mmap_size;
90
91 /* Pointer to total size of all objects in cache (within index_mmap) */
92 uint64_t *size;
93
94 /* Pointer to stored keys, (within index_mmap). */
95 uint8_t *stored_keys;
96
97 /* Maximum size of all cached objects (in bytes). */
98 uint64_t max_size;
99
100 /* Driver cache keys. */
101 uint8_t *driver_keys_blob;
102 size_t driver_keys_blob_size;
103 };
104
105 struct disk_cache_put_job {
106 struct util_queue_fence fence;
107
108 struct disk_cache *cache;
109
110 cache_key key;
111
112 /* Copy of cache data to be compressed and written. */
113 void *data;
114
115 /* Size of data to be compressed and written. */
116 size_t size;
117
118 struct cache_item_metadata cache_item_metadata;
119 };
120
121 /* Create a directory named 'path' if it does not already exist.
122 *
123 * Returns: 0 if path already exists as a directory or if created.
124 * -1 in all other cases.
125 */
126 static int
mkdir_if_needed(const char * path)127 mkdir_if_needed(const char *path)
128 {
129 struct stat sb;
130
131 /* If the path exists already, then our work is done if it's a
132 * directory, but it's an error if it is not.
133 */
134 if (stat(path, &sb) == 0) {
135 if (S_ISDIR(sb.st_mode)) {
136 return 0;
137 } else {
138 fprintf(stderr, "Cannot use %s for shader cache (not a directory)"
139 "---disabling.\n", path);
140 return -1;
141 }
142 }
143
144 int ret = mkdir(path, 0755);
145 if (ret == 0 || (ret == -1 && errno == EEXIST))
146 return 0;
147
148 fprintf(stderr, "Failed to create %s for shader cache (%s)---disabling.\n",
149 path, strerror(errno));
150
151 return -1;
152 }
153
154 /* Concatenate an existing path and a new name to form a new path. If the new
155 * path does not exist as a directory, create it then return the resulting
156 * name of the new path (ralloc'ed off of 'ctx').
157 *
158 * Returns NULL on any error, such as:
159 *
160 * <path> does not exist or is not a directory
161 * <path>/<name> exists but is not a directory
162 * <path>/<name> cannot be created as a directory
163 */
164 static char *
concatenate_and_mkdir(void * ctx,const char * path,const char * name)165 concatenate_and_mkdir(void *ctx, const char *path, const char *name)
166 {
167 char *new_path;
168 struct stat sb;
169
170 if (stat(path, &sb) != 0 || ! S_ISDIR(sb.st_mode))
171 return NULL;
172
173 new_path = ralloc_asprintf(ctx, "%s/%s", path, name);
174
175 if (mkdir_if_needed(new_path) == 0)
176 return new_path;
177 else
178 return NULL;
179 }
180
181 #define DRV_KEY_CPY(_dst, _src, _src_size) \
182 do { \
183 memcpy(_dst, _src, _src_size); \
184 _dst += _src_size; \
185 } while (0);
186
187 struct disk_cache *
disk_cache_create(const char * gpu_name,const char * timestamp,uint64_t driver_flags)188 disk_cache_create(const char *gpu_name, const char *timestamp,
189 uint64_t driver_flags)
190 {
191 void *local;
192 struct disk_cache *cache = NULL;
193 char *path, *max_size_str;
194 uint64_t max_size;
195 int fd = -1;
196 struct stat sb;
197 size_t size;
198
199 /* If running as a users other than the real user disable cache */
200 if (geteuid() != getuid())
201 return NULL;
202
203 /* A ralloc context for transient data during this invocation. */
204 local = ralloc_context(NULL);
205 if (local == NULL)
206 goto fail;
207
208 /* At user request, disable shader cache entirely. */
209 if (env_var_as_boolean("MESA_GLSL_CACHE_DISABLE", false))
210 goto fail;
211
212 /* Determine path for cache based on the first defined name as follows:
213 *
214 * $MESA_GLSL_CACHE_DIR
215 * $XDG_CACHE_HOME/mesa_shader_cache
216 * <pwd.pw_dir>/.cache/mesa_shader_cache
217 */
218 path = getenv("MESA_GLSL_CACHE_DIR");
219 if (path) {
220 if (mkdir_if_needed(path) == -1)
221 goto fail;
222
223 path = concatenate_and_mkdir(local, path, CACHE_DIR_NAME);
224 if (path == NULL)
225 goto fail;
226 }
227
228 if (path == NULL) {
229 char *xdg_cache_home = getenv("XDG_CACHE_HOME");
230
231 if (xdg_cache_home) {
232 if (mkdir_if_needed(xdg_cache_home) == -1)
233 goto fail;
234
235 path = concatenate_and_mkdir(local, xdg_cache_home, CACHE_DIR_NAME);
236 if (path == NULL)
237 goto fail;
238 }
239 }
240
241 if (path == NULL) {
242 char *buf;
243 size_t buf_size;
244 struct passwd pwd, *result;
245
246 buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
247 if (buf_size == -1)
248 buf_size = 512;
249
250 /* Loop until buf_size is large enough to query the directory */
251 while (1) {
252 buf = ralloc_size(local, buf_size);
253
254 getpwuid_r(getuid(), &pwd, buf, buf_size, &result);
255 if (result)
256 break;
257
258 if (errno == ERANGE) {
259 ralloc_free(buf);
260 buf = NULL;
261 buf_size *= 2;
262 } else {
263 goto fail;
264 }
265 }
266
267 path = concatenate_and_mkdir(local, pwd.pw_dir, ".cache");
268 if (path == NULL)
269 goto fail;
270
271 path = concatenate_and_mkdir(local, path, CACHE_DIR_NAME);
272 if (path == NULL)
273 goto fail;
274 }
275
276 cache = ralloc(NULL, struct disk_cache);
277 if (cache == NULL)
278 goto fail;
279
280 cache->path = ralloc_strdup(cache, path);
281 if (cache->path == NULL)
282 goto fail;
283
284 path = ralloc_asprintf(local, "%s/index", cache->path);
285 if (path == NULL)
286 goto fail;
287
288 fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
289 if (fd == -1)
290 goto fail;
291
292 if (fstat(fd, &sb) == -1)
293 goto fail;
294
295 /* Force the index file to be the expected size. */
296 size = sizeof(*cache->size) + CACHE_INDEX_MAX_KEYS * CACHE_KEY_SIZE;
297 if (sb.st_size != size) {
298 if (ftruncate(fd, size) == -1)
299 goto fail;
300 }
301
302 /* We map this shared so that other processes see updates that we
303 * make.
304 *
305 * Note: We do use atomic addition to ensure that multiple
306 * processes don't scramble the cache size recorded in the
307 * index. But we don't use any locking to prevent multiple
308 * processes from updating the same entry simultaneously. The idea
309 * is that if either result lands entirely in the index, then
310 * that's equivalent to a well-ordered write followed by an
311 * eviction and a write. On the other hand, if the simultaneous
312 * writes result in a corrupt entry, that's not really any
313 * different than both entries being evicted, (since within the
314 * guarantees of the cryptographic hash, a corrupt entry is
315 * unlikely to ever match a real cache key).
316 */
317 cache->index_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE,
318 MAP_SHARED, fd, 0);
319 if (cache->index_mmap == MAP_FAILED)
320 goto fail;
321 cache->index_mmap_size = size;
322
323 close(fd);
324
325 cache->size = (uint64_t *) cache->index_mmap;
326 cache->stored_keys = cache->index_mmap + sizeof(uint64_t);
327
328 max_size = 0;
329
330 max_size_str = getenv("MESA_GLSL_CACHE_MAX_SIZE");
331 if (max_size_str) {
332 char *end;
333 max_size = strtoul(max_size_str, &end, 10);
334 if (end == max_size_str) {
335 max_size = 0;
336 } else {
337 switch (*end) {
338 case 'K':
339 case 'k':
340 max_size *= 1024;
341 break;
342 case 'M':
343 case 'm':
344 max_size *= 1024*1024;
345 break;
346 case '\0':
347 case 'G':
348 case 'g':
349 default:
350 max_size *= 1024*1024*1024;
351 break;
352 }
353 }
354 }
355
356 /* Default to 1GB for maximum cache size. */
357 if (max_size == 0) {
358 max_size = 1024*1024*1024;
359 }
360
361 cache->max_size = max_size;
362
363 /* 1 thread was chosen because we don't really care about getting things
364 * to disk quickly just that it's not blocking other tasks.
365 *
366 * The queue will resize automatically when it's full, so adding new jobs
367 * doesn't stall.
368 */
369 util_queue_init(&cache->cache_queue, "disk_cache", 32, 1,
370 UTIL_QUEUE_INIT_RESIZE_IF_FULL |
371 UTIL_QUEUE_INIT_USE_MINIMUM_PRIORITY);
372
373 uint8_t cache_version = CACHE_VERSION;
374 size_t cv_size = sizeof(cache_version);
375 cache->driver_keys_blob_size = cv_size;
376
377 /* Create driver id keys */
378 size_t ts_size = strlen(timestamp) + 1;
379 size_t gpu_name_size = strlen(gpu_name) + 1;
380 cache->driver_keys_blob_size += ts_size;
381 cache->driver_keys_blob_size += gpu_name_size;
382
383 /* We sometimes store entire structs that contains a pointers in the cache,
384 * use pointer size as a key to avoid hard to debug issues.
385 */
386 uint8_t ptr_size = sizeof(void *);
387 size_t ptr_size_size = sizeof(ptr_size);
388 cache->driver_keys_blob_size += ptr_size_size;
389
390 size_t driver_flags_size = sizeof(driver_flags);
391 cache->driver_keys_blob_size += driver_flags_size;
392
393 cache->driver_keys_blob =
394 ralloc_size(cache, cache->driver_keys_blob_size);
395 if (!cache->driver_keys_blob)
396 goto fail;
397
398 uint8_t *drv_key_blob = cache->driver_keys_blob;
399 DRV_KEY_CPY(drv_key_blob, &cache_version, cv_size)
400 DRV_KEY_CPY(drv_key_blob, timestamp, ts_size)
401 DRV_KEY_CPY(drv_key_blob, gpu_name, gpu_name_size)
402 DRV_KEY_CPY(drv_key_blob, &ptr_size, ptr_size_size)
403 DRV_KEY_CPY(drv_key_blob, &driver_flags, driver_flags_size)
404
405 /* Seed our rand function */
406 s_rand_xorshift128plus(cache->seed_xorshift128plus, true);
407
408 ralloc_free(local);
409
410 return cache;
411
412 fail:
413 if (fd != -1)
414 close(fd);
415 if (cache)
416 ralloc_free(cache);
417 ralloc_free(local);
418
419 return NULL;
420 }
421
422 void
disk_cache_destroy(struct disk_cache * cache)423 disk_cache_destroy(struct disk_cache *cache)
424 {
425 if (cache) {
426 util_queue_destroy(&cache->cache_queue);
427 munmap(cache->index_mmap, cache->index_mmap_size);
428 }
429
430 ralloc_free(cache);
431 }
432
433 /* Return a filename within the cache's directory corresponding to 'key'. The
434 * returned filename is ralloced with 'cache' as the parent context.
435 *
436 * Returns NULL if out of memory.
437 */
438 static char *
get_cache_file(struct disk_cache * cache,const cache_key key)439 get_cache_file(struct disk_cache *cache, const cache_key key)
440 {
441 char buf[41];
442 char *filename;
443
444 _mesa_sha1_format(buf, key);
445 if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
446 buf[1], buf + 2) == -1)
447 return NULL;
448
449 return filename;
450 }
451
452 /* Create the directory that will be needed for the cache file for \key.
453 *
454 * Obviously, the implementation here must closely match
455 * _get_cache_file above.
456 */
457 static void
make_cache_file_directory(struct disk_cache * cache,const cache_key key)458 make_cache_file_directory(struct disk_cache *cache, const cache_key key)
459 {
460 char *dir;
461 char buf[41];
462
463 _mesa_sha1_format(buf, key);
464 if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
465 return;
466
467 mkdir_if_needed(dir);
468 free(dir);
469 }
470
471 /* Given a directory path and predicate function, find the entry with
472 * the oldest access time in that directory for which the predicate
473 * returns true.
474 *
475 * Returns: A malloc'ed string for the path to the chosen file, (or
476 * NULL on any error). The caller should free the string when
477 * finished.
478 */
479 static char *
choose_lru_file_matching(const char * dir_path,bool (* predicate)(const char * dir_path,const struct stat *,const char *,const size_t))480 choose_lru_file_matching(const char *dir_path,
481 bool (*predicate)(const char *dir_path,
482 const struct stat *,
483 const char *, const size_t))
484 {
485 DIR *dir;
486 struct dirent *entry;
487 char *filename;
488 char *lru_name = NULL;
489 time_t lru_atime = 0;
490
491 dir = opendir(dir_path);
492 if (dir == NULL)
493 return NULL;
494
495 while (1) {
496 entry = readdir(dir);
497 if (entry == NULL)
498 break;
499
500 struct stat sb;
501 if (fstatat(dirfd(dir), entry->d_name, &sb, 0) == 0) {
502 if (!lru_atime || (sb.st_atime < lru_atime)) {
503 size_t len = strlen(entry->d_name);
504
505 if (!predicate(dir_path, &sb, entry->d_name, len))
506 continue;
507
508 char *tmp = realloc(lru_name, len + 1);
509 if (tmp) {
510 lru_name = tmp;
511 memcpy(lru_name, entry->d_name, len + 1);
512 lru_atime = sb.st_atime;
513 }
514 }
515 }
516 }
517
518 if (lru_name == NULL) {
519 closedir(dir);
520 return NULL;
521 }
522
523 if (asprintf(&filename, "%s/%s", dir_path, lru_name) < 0)
524 filename = NULL;
525
526 free(lru_name);
527 closedir(dir);
528
529 return filename;
530 }
531
532 /* Is entry a regular file, and not having a name with a trailing
533 * ".tmp"
534 */
535 static bool
is_regular_non_tmp_file(const char * path,const struct stat * sb,const char * d_name,const size_t len)536 is_regular_non_tmp_file(const char *path, const struct stat *sb,
537 const char *d_name, const size_t len)
538 {
539 if (!S_ISREG(sb->st_mode))
540 return false;
541
542 if (len >= 4 && strcmp(&d_name[len-4], ".tmp") == 0)
543 return false;
544
545 return true;
546 }
547
548 /* Returns the size of the deleted file, (or 0 on any error). */
549 static size_t
unlink_lru_file_from_directory(const char * path)550 unlink_lru_file_from_directory(const char *path)
551 {
552 struct stat sb;
553 char *filename;
554
555 filename = choose_lru_file_matching(path, is_regular_non_tmp_file);
556 if (filename == NULL)
557 return 0;
558
559 if (stat(filename, &sb) == -1) {
560 free (filename);
561 return 0;
562 }
563
564 unlink(filename);
565 free (filename);
566
567 return sb.st_blocks * 512;
568 }
569
570 /* Is entry a directory with a two-character name, (and not the
571 * special name of ".."). We also return false if the dir is empty.
572 */
573 static bool
is_two_character_sub_directory(const char * path,const struct stat * sb,const char * d_name,const size_t len)574 is_two_character_sub_directory(const char *path, const struct stat *sb,
575 const char *d_name, const size_t len)
576 {
577 if (!S_ISDIR(sb->st_mode))
578 return false;
579
580 if (len != 2)
581 return false;
582
583 if (strcmp(d_name, "..") == 0)
584 return false;
585
586 char *subdir;
587 if (asprintf(&subdir, "%s/%s", path, d_name) == -1)
588 return false;
589 DIR *dir = opendir(subdir);
590 free(subdir);
591
592 if (dir == NULL)
593 return false;
594
595 unsigned subdir_entries = 0;
596 struct dirent *d;
597 while ((d = readdir(dir)) != NULL) {
598 if(++subdir_entries > 2)
599 break;
600 }
601 closedir(dir);
602
603 /* If dir only contains '.' and '..' it must be empty */
604 if (subdir_entries <= 2)
605 return false;
606
607 return true;
608 }
609
610 static void
evict_lru_item(struct disk_cache * cache)611 evict_lru_item(struct disk_cache *cache)
612 {
613 char *dir_path;
614
615 /* With a reasonably-sized, full cache, (and with keys generated
616 * from a cryptographic hash), we can choose two random hex digits
617 * and reasonably expect the directory to exist with a file in it.
618 * Provides pseudo-LRU eviction to reduce checking all cache files.
619 */
620 uint64_t rand64 = rand_xorshift128plus(cache->seed_xorshift128plus);
621 if (asprintf(&dir_path, "%s/%02" PRIx64 , cache->path, rand64 & 0xff) < 0)
622 return;
623
624 size_t size = unlink_lru_file_from_directory(dir_path);
625
626 free(dir_path);
627
628 if (size) {
629 p_atomic_add(cache->size, - (uint64_t)size);
630 return;
631 }
632
633 /* In the case where the random choice of directory didn't find
634 * something, we choose the least recently accessed from the
635 * existing directories.
636 *
637 * Really, the only reason this code exists is to allow the unit
638 * tests to work, (which use an artificially-small cache to be able
639 * to force a single cached item to be evicted).
640 */
641 dir_path = choose_lru_file_matching(cache->path,
642 is_two_character_sub_directory);
643 if (dir_path == NULL)
644 return;
645
646 size = unlink_lru_file_from_directory(dir_path);
647
648 free(dir_path);
649
650 if (size)
651 p_atomic_add(cache->size, - (uint64_t)size);
652 }
653
654 void
disk_cache_remove(struct disk_cache * cache,const cache_key key)655 disk_cache_remove(struct disk_cache *cache, const cache_key key)
656 {
657 struct stat sb;
658
659 char *filename = get_cache_file(cache, key);
660 if (filename == NULL) {
661 return;
662 }
663
664 if (stat(filename, &sb) == -1) {
665 free(filename);
666 return;
667 }
668
669 unlink(filename);
670 free(filename);
671
672 if (sb.st_blocks)
673 p_atomic_add(cache->size, - (uint64_t)sb.st_blocks * 512);
674 }
675
676 static ssize_t
read_all(int fd,void * buf,size_t count)677 read_all(int fd, void *buf, size_t count)
678 {
679 char *in = buf;
680 ssize_t read_ret;
681 size_t done;
682
683 for (done = 0; done < count; done += read_ret) {
684 read_ret = read(fd, in + done, count - done);
685 if (read_ret == -1 || read_ret == 0)
686 return -1;
687 }
688 return done;
689 }
690
691 static ssize_t
write_all(int fd,const void * buf,size_t count)692 write_all(int fd, const void *buf, size_t count)
693 {
694 const char *out = buf;
695 ssize_t written;
696 size_t done;
697
698 for (done = 0; done < count; done += written) {
699 written = write(fd, out + done, count - done);
700 if (written == -1)
701 return -1;
702 }
703 return done;
704 }
705
706 /* From the zlib docs:
707 * "If the memory is available, buffers sizes on the order of 128K or 256K
708 * bytes should be used."
709 */
710 #define BUFSIZE 256 * 1024
711
712 /**
713 * Compresses cache entry in memory and writes it to disk. Returns the size
714 * of the data written to disk.
715 */
716 static size_t
deflate_and_write_to_disk(const void * in_data,size_t in_data_size,int dest,const char * filename)717 deflate_and_write_to_disk(const void *in_data, size_t in_data_size, int dest,
718 const char *filename)
719 {
720 unsigned char out[BUFSIZE];
721
722 /* allocate deflate state */
723 z_stream strm;
724 strm.zalloc = Z_NULL;
725 strm.zfree = Z_NULL;
726 strm.opaque = Z_NULL;
727 strm.next_in = (uint8_t *) in_data;
728 strm.avail_in = in_data_size;
729
730 int ret = deflateInit(&strm, Z_BEST_COMPRESSION);
731 if (ret != Z_OK)
732 return 0;
733
734 /* compress until end of in_data */
735 size_t compressed_size = 0;
736 int flush;
737 do {
738 int remaining = in_data_size - BUFSIZE;
739 flush = remaining > 0 ? Z_NO_FLUSH : Z_FINISH;
740 in_data_size -= BUFSIZE;
741
742 /* Run deflate() on input until the output buffer is not full (which
743 * means there is no more data to deflate).
744 */
745 do {
746 strm.avail_out = BUFSIZE;
747 strm.next_out = out;
748
749 ret = deflate(&strm, flush); /* no bad return value */
750 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
751
752 size_t have = BUFSIZE - strm.avail_out;
753 compressed_size += have;
754
755 ssize_t written = write_all(dest, out, have);
756 if (written == -1) {
757 (void)deflateEnd(&strm);
758 return 0;
759 }
760 } while (strm.avail_out == 0);
761
762 /* all input should be used */
763 assert(strm.avail_in == 0);
764
765 } while (flush != Z_FINISH);
766
767 /* stream should be complete */
768 assert(ret == Z_STREAM_END);
769
770 /* clean up and return */
771 (void)deflateEnd(&strm);
772 return compressed_size;
773 }
774
775 static struct disk_cache_put_job *
create_put_job(struct disk_cache * cache,const cache_key key,const void * data,size_t size,struct cache_item_metadata * cache_item_metadata)776 create_put_job(struct disk_cache *cache, const cache_key key,
777 const void *data, size_t size,
778 struct cache_item_metadata *cache_item_metadata)
779 {
780 struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *)
781 malloc(sizeof(struct disk_cache_put_job) + size);
782
783 if (dc_job) {
784 dc_job->cache = cache;
785 memcpy(dc_job->key, key, sizeof(cache_key));
786 dc_job->data = dc_job + 1;
787 memcpy(dc_job->data, data, size);
788 dc_job->size = size;
789
790 /* Copy the cache item metadata */
791 if (cache_item_metadata) {
792 dc_job->cache_item_metadata.type = cache_item_metadata->type;
793 if (cache_item_metadata->type == CACHE_ITEM_TYPE_GLSL) {
794 dc_job->cache_item_metadata.num_keys =
795 cache_item_metadata->num_keys;
796 dc_job->cache_item_metadata.keys = (cache_key *)
797 malloc(cache_item_metadata->num_keys * sizeof(cache_key));
798
799 if (!dc_job->cache_item_metadata.keys)
800 goto fail;
801
802 memcpy(dc_job->cache_item_metadata.keys,
803 cache_item_metadata->keys,
804 sizeof(cache_key) * cache_item_metadata->num_keys);
805 }
806 } else {
807 dc_job->cache_item_metadata.type = CACHE_ITEM_TYPE_UNKNOWN;
808 dc_job->cache_item_metadata.keys = NULL;
809 }
810 }
811
812 return dc_job;
813
814 fail:
815 free(dc_job);
816
817 return NULL;
818 }
819
820 static void
destroy_put_job(void * job,int thread_index)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
cache_put(void * job,int thread_index)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 free(filename_tmp);
991 free(filename);
992 }
993
994 void
disk_cache_put(struct disk_cache * cache,const cache_key key,const void * data,size_t size,struct cache_item_metadata * cache_item_metadata)995 disk_cache_put(struct disk_cache *cache, const cache_key key,
996 const void *data, size_t size,
997 struct cache_item_metadata *cache_item_metadata)
998 {
999 struct disk_cache_put_job *dc_job =
1000 create_put_job(cache, key, data, size, cache_item_metadata);
1001
1002 if (dc_job) {
1003 util_queue_fence_init(&dc_job->fence);
1004 util_queue_add_job(&cache->cache_queue, dc_job, &dc_job->fence,
1005 cache_put, destroy_put_job);
1006 }
1007 }
1008
1009 /**
1010 * Decompresses cache entry, returns true if successful.
1011 */
1012 static bool
inflate_cache_data(uint8_t * in_data,size_t in_data_size,uint8_t * out_data,size_t out_data_size)1013 inflate_cache_data(uint8_t *in_data, size_t in_data_size,
1014 uint8_t *out_data, size_t out_data_size)
1015 {
1016 z_stream strm;
1017
1018 /* allocate inflate state */
1019 strm.zalloc = Z_NULL;
1020 strm.zfree = Z_NULL;
1021 strm.opaque = Z_NULL;
1022 strm.next_in = in_data;
1023 strm.avail_in = in_data_size;
1024 strm.next_out = out_data;
1025 strm.avail_out = out_data_size;
1026
1027 int ret = inflateInit(&strm);
1028 if (ret != Z_OK)
1029 return false;
1030
1031 ret = inflate(&strm, Z_NO_FLUSH);
1032 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
1033
1034 /* Unless there was an error we should have decompressed everything in one
1035 * go as we know the uncompressed file size.
1036 */
1037 if (ret != Z_STREAM_END) {
1038 (void)inflateEnd(&strm);
1039 return false;
1040 }
1041 assert(strm.avail_out == 0);
1042
1043 /* clean up and return */
1044 (void)inflateEnd(&strm);
1045 return true;
1046 }
1047
1048 void *
disk_cache_get(struct disk_cache * cache,const cache_key key,size_t * size)1049 disk_cache_get(struct disk_cache *cache, const cache_key key, size_t *size)
1050 {
1051 int fd = -1, ret;
1052 struct stat sb;
1053 char *filename = NULL;
1054 uint8_t *data = NULL;
1055 uint8_t *uncompressed_data = NULL;
1056 uint8_t *file_header = NULL;
1057
1058 if (size)
1059 *size = 0;
1060
1061 filename = get_cache_file(cache, key);
1062 if (filename == NULL)
1063 goto fail;
1064
1065 fd = open(filename, O_RDONLY | O_CLOEXEC);
1066 if (fd == -1)
1067 goto fail;
1068
1069 if (fstat(fd, &sb) == -1)
1070 goto fail;
1071
1072 data = malloc(sb.st_size);
1073 if (data == NULL)
1074 goto fail;
1075
1076 size_t ck_size = cache->driver_keys_blob_size;
1077 file_header = malloc(ck_size);
1078 if (!file_header)
1079 goto fail;
1080
1081 if (sb.st_size < ck_size)
1082 goto fail;
1083
1084 ret = read_all(fd, file_header, ck_size);
1085 if (ret == -1)
1086 goto fail;
1087
1088 /* Check for extremely unlikely hash collisions */
1089 if (memcmp(cache->driver_keys_blob, file_header, ck_size) != 0) {
1090 assert(!"Mesa cache keys mismatch!");
1091 goto fail;
1092 }
1093
1094 size_t cache_item_md_size = sizeof(uint32_t);
1095 uint32_t md_type;
1096 ret = read_all(fd, &md_type, cache_item_md_size);
1097 if (ret == -1)
1098 goto fail;
1099
1100 if (md_type == CACHE_ITEM_TYPE_GLSL) {
1101 uint32_t num_keys;
1102 cache_item_md_size += sizeof(uint32_t);
1103 ret = read_all(fd, &num_keys, sizeof(uint32_t));
1104 if (ret == -1)
1105 goto fail;
1106
1107 /* The cache item metadata is currently just used for distributing
1108 * precompiled shaders, they are not used by Mesa so just skip them for
1109 * now.
1110 * TODO: pass the metadata back to the caller and do some basic
1111 * validation.
1112 */
1113 cache_item_md_size += num_keys * sizeof(cache_key);
1114 ret = lseek(fd, num_keys * sizeof(cache_key), SEEK_CUR);
1115 if (ret == -1)
1116 goto fail;
1117 }
1118
1119 /* Load the CRC that was created when the file was written. */
1120 struct cache_entry_file_data cf_data;
1121 size_t cf_data_size = sizeof(cf_data);
1122 ret = read_all(fd, &cf_data, cf_data_size);
1123 if (ret == -1)
1124 goto fail;
1125
1126 /* Load the actual cache data. */
1127 size_t cache_data_size =
1128 sb.st_size - cf_data_size - ck_size - cache_item_md_size;
1129 ret = read_all(fd, data, cache_data_size);
1130 if (ret == -1)
1131 goto fail;
1132
1133 /* Uncompress the cache data */
1134 uncompressed_data = malloc(cf_data.uncompressed_size);
1135 if (!inflate_cache_data(data, cache_data_size, uncompressed_data,
1136 cf_data.uncompressed_size))
1137 goto fail;
1138
1139 /* Check the data for corruption */
1140 if (cf_data.crc32 != util_hash_crc32(uncompressed_data,
1141 cf_data.uncompressed_size))
1142 goto fail;
1143
1144 free(data);
1145 free(filename);
1146 free(file_header);
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
disk_cache_put_key(struct disk_cache * cache,const cache_key key)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 = CPU_TO_LE32(*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
disk_cache_has_key(struct disk_cache * cache,const cache_key key)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 = CPU_TO_LE32(*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
disk_cache_compute_key(struct disk_cache * cache,const void * data,size_t size,cache_key key)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 */
1214