2 * Copyright © 2014 Intel Corporation
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:
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
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
24 #ifdef ENABLE_SHADER_CACHE
32 #include <sys/types.h>
42 #include "util/crc32.h"
43 #include "util/u_atomic.h"
44 #include "util/mesa-sha1.h"
45 #include "util/ralloc.h"
46 #include "main/errors.h"
48 #include "disk_cache.h"
50 /* Number of bits to mask off from a cache key to get an index. */
51 #define CACHE_INDEX_KEY_BITS 16
53 /* Mask for computing an index from a key. */
54 #define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
56 /* The number of keys that can be stored in the index. */
57 #define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
60 /* The path to the cache directory. */
63 /* A pointer to the mmapped index file within the cache directory. */
65 size_t index_mmap_size
;
67 /* Pointer to total size of all objects in cache (within index_mmap) */
70 /* Pointer to stored keys, (within index_mmap). */
73 /* Maximum size of all cached objects (in bytes). */
77 /* Create a directory named 'path' if it does not already exist.
79 * Returns: 0 if path already exists as a directory or if created.
80 * -1 in all other cases.
83 mkdir_if_needed(const char *path
)
87 /* If the path exists already, then our work is done if it's a
88 * directory, but it's an error if it is not.
90 if (stat(path
, &sb
) == 0) {
91 if (S_ISDIR(sb
.st_mode
)) {
94 fprintf(stderr
, "Cannot use %s for shader cache (not a directory)"
95 "---disabling.\n", path
);
100 int ret
= mkdir(path
, 0755);
101 if (ret
== 0 || (ret
== -1 && errno
== EEXIST
))
104 fprintf(stderr
, "Failed to create %s for shader cache (%s)---disabling.\n",
105 path
, strerror(errno
));
110 /* Concatenate an existing path and a new name to form a new path. If the new
111 * path does not exist as a directory, create it then return the resulting
112 * name of the new path (ralloc'ed off of 'ctx').
114 * Returns NULL on any error, such as:
116 * <path> does not exist or is not a directory
117 * <path>/<name> exists but is not a directory
118 * <path>/<name> cannot be created as a directory
121 concatenate_and_mkdir(void *ctx
, const char *path
, const char *name
)
126 if (stat(path
, &sb
) != 0 || ! S_ISDIR(sb
.st_mode
))
129 new_path
= ralloc_asprintf(ctx
, "%s/%s", path
, name
);
131 if (mkdir_if_needed(new_path
) == 0)
138 remove_dir(const char *fpath
, const struct stat
*sb
,
139 int typeflag
, struct FTW
*ftwbuf
)
141 if (S_ISREG(sb
->st_mode
))
143 else if (S_ISDIR(sb
->st_mode
))
150 remove_old_cache_directories(void *mem_ctx
, const char *path
,
151 const char *timestamp
)
153 DIR *dir
= opendir(path
);
155 struct dirent
* d_entry
;
156 while((d_entry
= readdir(dir
)) != NULL
)
159 ralloc_asprintf(mem_ctx
, "%s/%s", path
, d_entry
->d_name
);
162 if (stat(full_path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
) &&
163 strcmp(d_entry
->d_name
, timestamp
) != 0 &&
164 strcmp(d_entry
->d_name
, "..") != 0 &&
165 strcmp(d_entry
->d_name
, ".") != 0) {
166 nftw(full_path
, remove_dir
, 20, FTW_DEPTH
);
174 create_mesa_cache_dir(void *mem_ctx
, const char *path
, const char *timestamp
,
175 const char *gpu_name
)
177 char *new_path
= concatenate_and_mkdir(mem_ctx
, path
, "mesa");
178 if (new_path
== NULL
)
181 /* Create a parent architecture directory so that we don't remove cache
182 * files for other architectures. In theory we could share the cache
183 * between architectures but we have no way of knowing if they were created
184 * by a compatible Mesa version.
186 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, get_arch_bitness_str());
187 if (new_path
== NULL
)
190 /* Remove cache directories for old Mesa versions */
191 remove_old_cache_directories(mem_ctx
, new_path
, timestamp
);
193 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, timestamp
);
194 if (new_path
== NULL
)
197 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, gpu_name
);
198 if (new_path
== NULL
)
205 disk_cache_create(const char *gpu_name
, const char *timestamp
)
208 struct disk_cache
*cache
= NULL
;
209 char *path
, *max_size_str
;
215 /* If running as a users other than the real user disable cache */
216 if (geteuid() != getuid())
219 /* A ralloc context for transient data during this invocation. */
220 local
= ralloc_context(NULL
);
224 /* At user request, disable shader cache entirely. */
225 if (getenv("MESA_GLSL_CACHE_DISABLE"))
228 /* Determine path for cache based on the first defined name as follows:
230 * $MESA_GLSL_CACHE_DIR
231 * $XDG_CACHE_HOME/mesa
232 * <pwd.pw_dir>/.cache/mesa
234 path
= getenv("MESA_GLSL_CACHE_DIR");
236 if (mkdir_if_needed(path
) == -1)
239 path
= create_mesa_cache_dir(local
, path
, timestamp
,
246 char *xdg_cache_home
= getenv("XDG_CACHE_HOME");
248 if (xdg_cache_home
) {
249 if (mkdir_if_needed(xdg_cache_home
) == -1)
252 path
= create_mesa_cache_dir(local
, xdg_cache_home
, timestamp
,
262 struct passwd pwd
, *result
;
264 buf_size
= sysconf(_SC_GETPW_R_SIZE_MAX
);
268 /* Loop until buf_size is large enough to query the directory */
270 buf
= ralloc_size(local
, buf_size
);
272 getpwuid_r(getuid(), &pwd
, buf
, buf_size
, &result
);
276 if (errno
== ERANGE
) {
285 path
= concatenate_and_mkdir(local
, pwd
.pw_dir
, ".cache");
289 path
= create_mesa_cache_dir(local
, path
, timestamp
, gpu_name
);
294 cache
= ralloc(NULL
, struct disk_cache
);
298 cache
->path
= ralloc_strdup(cache
, path
);
299 if (cache
->path
== NULL
)
302 path
= ralloc_asprintf(local
, "%s/index", cache
->path
);
306 fd
= open(path
, O_RDWR
| O_CREAT
| O_CLOEXEC
, 0644);
310 if (fstat(fd
, &sb
) == -1)
313 /* Force the index file to be the expected size. */
314 size
= sizeof(*cache
->size
) + CACHE_INDEX_MAX_KEYS
* CACHE_KEY_SIZE
;
315 if (sb
.st_size
!= size
) {
316 if (ftruncate(fd
, size
) == -1)
320 /* We map this shared so that other processes see updates that we
323 * Note: We do use atomic addition to ensure that multiple
324 * processes don't scramble the cache size recorded in the
325 * index. But we don't use any locking to prevent multiple
326 * processes from updating the same entry simultaneously. The idea
327 * is that if either result lands entirely in the index, then
328 * that's equivalent to a well-ordered write followed by an
329 * eviction and a write. On the other hand, if the simultaneous
330 * writes result in a corrupt entry, that's not really any
331 * different than both entries being evicted, (since within the
332 * guarantees of the cryptographic hash, a corrupt entry is
333 * unlikely to ever match a real cache key).
335 cache
->index_mmap
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
337 if (cache
->index_mmap
== MAP_FAILED
)
339 cache
->index_mmap_size
= size
;
343 cache
->size
= (uint64_t *) cache
->index_mmap
;
344 cache
->stored_keys
= cache
->index_mmap
+ sizeof(uint64_t);
348 max_size_str
= getenv("MESA_GLSL_CACHE_MAX_SIZE");
351 max_size
= strtoul(max_size_str
, &end
, 10);
352 if (end
== max_size_str
) {
362 max_size
*= 1024*1024;
368 max_size
*= 1024*1024*1024;
374 /* Default to 1GB for maximum cache size. */
376 max_size
= 1024*1024*1024;
378 cache
->max_size
= max_size
;
395 disk_cache_destroy(struct disk_cache
*cache
)
398 munmap(cache
->index_mmap
, cache
->index_mmap_size
);
403 /* Return a filename within the cache's directory corresponding to 'key'. The
404 * returned filename is ralloced with 'cache' as the parent context.
406 * Returns NULL if out of memory.
409 get_cache_file(struct disk_cache
*cache
, const cache_key key
)
414 _mesa_sha1_format(buf
, key
);
415 if (asprintf(&filename
, "%s/%c%c/%s", cache
->path
, buf
[0],
416 buf
[1], buf
+ 2) == -1)
422 /* Create the directory that will be needed for the cache file for \key.
424 * Obviously, the implementation here must closely match
425 * _get_cache_file above.
428 make_cache_file_directory(struct disk_cache
*cache
, const cache_key key
)
433 _mesa_sha1_format(buf
, key
);
434 if (asprintf(&dir
, "%s/%c%c", cache
->path
, buf
[0], buf
[1]) == -1)
437 mkdir_if_needed(dir
);
441 /* Given a directory path and predicate function, count all entries in
442 * that directory for which the predicate returns true. Then choose a
443 * random entry from among those counted.
445 * Returns: A malloc'ed string for the path to the chosen file, (or
446 * NULL on any error). The caller should free the string when
450 choose_random_file_matching(const char *dir_path
,
451 bool (*predicate
)(const struct dirent
*,
452 const char *dir_path
))
455 struct dirent
*entry
;
456 unsigned int count
, victim
;
459 dir
= opendir(dir_path
);
466 entry
= readdir(dir
);
469 if (!predicate(entry
, dir_path
))
480 victim
= rand() % count
;
486 entry
= readdir(dir
);
489 if (!predicate(entry
, dir_path
))
502 if (asprintf(&filename
, "%s/%s", dir_path
, entry
->d_name
) < 0)
510 /* Is entry a regular file, and not having a name with a trailing
514 is_regular_non_tmp_file(const struct dirent
*entry
, const char *path
)
517 if (asprintf(&filename
, "%s/%s", path
, entry
->d_name
) == -1)
521 int res
= stat(filename
, &sb
);
524 if (res
== -1 || !S_ISREG(sb
.st_mode
))
527 size_t len
= strlen (entry
->d_name
);
528 if (len
>= 4 && strcmp(&entry
->d_name
[len
-4], ".tmp") == 0)
534 /* Returns the size of the deleted file, (or 0 on any error). */
536 unlink_random_file_from_directory(const char *path
)
541 filename
= choose_random_file_matching(path
, is_regular_non_tmp_file
);
542 if (filename
== NULL
)
545 if (stat(filename
, &sb
) == -1) {
557 /* Is entry a directory with a two-character name, (and not the
558 * special name of "..")
561 is_two_character_sub_directory(const struct dirent
*entry
, const char *path
)
564 if (asprintf(&subdir
, "%s/%s", path
, entry
->d_name
) == -1)
568 int res
= stat(subdir
, &sb
);
571 if (res
== -1 || !S_ISDIR(sb
.st_mode
))
574 if (strlen(entry
->d_name
) != 2)
577 if (strcmp(entry
->d_name
, "..") == 0)
584 evict_random_item(struct disk_cache
*cache
)
586 const char hex
[] = "0123456789abcde";
591 /* With a reasonably-sized, full cache, (and with keys generated
592 * from a cryptographic hash), we can choose two random hex digits
593 * and reasonably expect the directory to exist with a file in it.
598 if (asprintf(&dir_path
, "%s/%c%c", cache
->path
, hex
[a
], hex
[b
]) < 0)
601 size
= unlink_random_file_from_directory(dir_path
);
606 p_atomic_add(cache
->size
, - size
);
610 /* In the case where the random choice of directory didn't find
611 * something, we choose randomly from the existing directories.
613 * Really, the only reason this code exists is to allow the unit
614 * tests to work, (which use an artificially-small cache to be able
615 * to force a single cached item to be evicted).
617 dir_path
= choose_random_file_matching(cache
->path
,
618 is_two_character_sub_directory
);
619 if (dir_path
== NULL
)
622 size
= unlink_random_file_from_directory(dir_path
);
627 p_atomic_add(cache
->size
, - size
);
631 disk_cache_remove(struct disk_cache
*cache
, const cache_key key
)
635 char *filename
= get_cache_file(cache
, key
);
636 if (filename
== NULL
) {
640 if (stat(filename
, &sb
) == -1) {
649 p_atomic_add(cache
->size
, - sb
.st_size
);
652 /* From the zlib docs:
653 * "If the memory is available, buffers sizes on the order of 128K or 256K
654 * bytes should be used."
656 #define BUFSIZE 256 * 1024
659 * Compresses cache entry in memory and writes it to disk. Returns the size
660 * of the data written to disk.
663 deflate_and_write_to_disk(const void *in_data
, size_t in_data_size
, int dest
,
664 const char *filename
)
666 unsigned char out
[BUFSIZE
];
668 /* allocate deflate state */
670 strm
.zalloc
= Z_NULL
;
672 strm
.opaque
= Z_NULL
;
673 strm
.next_in
= (uint8_t *) in_data
;
674 strm
.avail_in
= in_data_size
;
676 int ret
= deflateInit(&strm
, Z_BEST_COMPRESSION
);
680 /* compress until end of in_data */
681 size_t compressed_size
= 0;
684 int remaining
= in_data_size
- BUFSIZE
;
685 flush
= remaining
> 0 ? Z_NO_FLUSH
: Z_FINISH
;
686 in_data_size
-= BUFSIZE
;
688 /* Run deflate() on input until the output buffer is not full (which
689 * means there is no more data to deflate).
692 strm
.avail_out
= BUFSIZE
;
695 ret
= deflate(&strm
, flush
); /* no bad return value */
696 assert(ret
!= Z_STREAM_ERROR
); /* state not clobbered */
698 size_t have
= BUFSIZE
- strm
.avail_out
;
699 compressed_size
+= compressed_size
+ have
;
702 for (size_t len
= 0; len
< have
; len
+= written
) {
703 written
= write(dest
, out
+ len
, have
- len
);
705 (void)deflateEnd(&strm
);
709 } while (strm
.avail_out
== 0);
711 /* all input should be used */
712 assert(strm
.avail_in
== 0);
714 } while (flush
!= Z_FINISH
);
716 /* stream should be complete */
717 assert(ret
== Z_STREAM_END
);
719 /* clean up and return */
720 (void)deflateEnd(&strm
);
721 return compressed_size
;
724 struct cache_entry_file_data
{
726 uint32_t uncompressed_size
;
730 disk_cache_put(struct disk_cache
*cache
,
735 int fd
= -1, fd_final
= -1, err
, ret
;
737 char *filename
= NULL
, *filename_tmp
= NULL
;
739 filename
= get_cache_file(cache
, key
);
740 if (filename
== NULL
)
743 /* Write to a temporary file to allow for an atomic rename to the
744 * final destination filename, (to prevent any readers from seeing
745 * a partially written file).
747 if (asprintf(&filename_tmp
, "%s.tmp", filename
) == -1)
750 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
752 /* Make the two-character subdirectory within the cache as needed. */
757 make_cache_file_directory(cache
, key
);
759 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
764 /* With the temporary file open, we take an exclusive flock on
765 * it. If the flock fails, then another process still has the file
766 * open with the flock held. So just let that file be responsible
767 * for writing the file.
769 err
= flock(fd
, LOCK_EX
| LOCK_NB
);
773 /* Now that we have the lock on the open temporary file, we can
774 * check to see if the destination file already exists. If so,
775 * another process won the race between when we saw that the file
776 * didn't exist and now. In this case, we don't do anything more,
777 * (to ensure the size accounting of the cache doesn't get off).
779 fd_final
= open(filename
, O_RDONLY
| O_CLOEXEC
);
783 /* OK, we're now on the hook to write out a file that we know is
784 * not in the cache, and is also not being written out to the cache
785 * by some other process.
787 * Before we do that, if the cache is too large, evict something
790 if (*cache
->size
+ size
> cache
->max_size
)
791 evict_random_item(cache
);
793 /* Create CRC of the data and store at the start of the file. We will
794 * read this when restoring the cache and use it to check for corruption.
796 struct cache_entry_file_data cf_data
;
797 cf_data
.crc32
= util_hash_crc32(data
, size
);
798 cf_data
.uncompressed_size
= size
;
800 size_t cf_data_size
= sizeof(cf_data
);
801 for (len
= 0; len
< cf_data_size
; len
+= ret
) {
802 ret
= write(fd
, ((uint8_t *) &cf_data
) + len
, cf_data_size
- len
);
804 unlink(filename_tmp
);
809 /* Now, finally, write out the contents to the temporary file, then
810 * rename them atomically to the destination filename, and also
811 * perform an atomic increment of the total cache size.
813 size_t file_size
= deflate_and_write_to_disk(data
, size
, fd
, filename_tmp
);
814 if (file_size
== 0) {
815 unlink(filename_tmp
);
818 rename(filename_tmp
, filename
);
820 file_size
+= cf_data_size
;
821 p_atomic_add(cache
->size
, file_size
);
826 /* This close finally releases the flock, (now that the final dile
827 * has been renamed into place and the size has been added).
838 * Decompresses cache entry, returns true if successful.
841 inflate_cache_data(uint8_t *in_data
, size_t in_data_size
,
842 uint8_t *out_data
, size_t out_data_size
)
846 /* allocate inflate state */
847 strm
.zalloc
= Z_NULL
;
849 strm
.opaque
= Z_NULL
;
850 strm
.next_in
= in_data
;
851 strm
.avail_in
= in_data_size
;
852 strm
.next_out
= out_data
;
853 strm
.avail_out
= out_data_size
;
855 int ret
= inflateInit(&strm
);
859 ret
= inflate(&strm
, Z_NO_FLUSH
);
860 assert(ret
!= Z_STREAM_ERROR
); /* state not clobbered */
862 /* Unless there was an error we should have decompressed everything in one
863 * go as we know the uncompressed file size.
865 if (ret
!= Z_STREAM_END
) {
866 (void)inflateEnd(&strm
);
869 assert(strm
.avail_out
== 0);
871 /* clean up and return */
872 (void)inflateEnd(&strm
);
877 disk_cache_get(struct disk_cache
*cache
, const cache_key key
, size_t *size
)
879 int fd
= -1, ret
, len
;
881 char *filename
= NULL
;
882 uint8_t *data
= NULL
;
883 uint8_t *uncompressed_data
= NULL
;
888 filename
= get_cache_file(cache
, key
);
889 if (filename
== NULL
)
892 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
896 if (fstat(fd
, &sb
) == -1)
899 data
= malloc(sb
.st_size
);
903 /* Load the CRC that was created when the file was written. */
904 struct cache_entry_file_data cf_data
;
905 size_t cf_data_size
= sizeof(cf_data
);
906 assert(sb
.st_size
> cf_data_size
);
907 for (len
= 0; len
< cf_data_size
; len
+= ret
) {
908 ret
= read(fd
, ((uint8_t *) &cf_data
) + len
, cf_data_size
- len
);
913 /* Load the actual cache data. */
914 size_t cache_data_size
= sb
.st_size
- cf_data_size
;
915 for (len
= 0; len
< cache_data_size
; len
+= ret
) {
916 ret
= read(fd
, data
+ len
, cache_data_size
- len
);
921 /* Uncompress the cache data */
922 uncompressed_data
= malloc(cf_data
.uncompressed_size
);
923 if (!inflate_cache_data(data
, cache_data_size
, uncompressed_data
,
924 cf_data
.uncompressed_size
))
927 /* Check the data for corruption */
928 if (cf_data
.crc32
!= util_hash_crc32(uncompressed_data
,
929 cf_data
.uncompressed_size
))
937 *size
= cf_data
.uncompressed_size
;
939 return uncompressed_data
;
944 if (uncompressed_data
)
945 free(uncompressed_data
);
955 disk_cache_put_key(struct disk_cache
*cache
, const cache_key key
)
957 const uint32_t *key_chunk
= (const uint32_t *) key
;
958 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
959 unsigned char *entry
;
961 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
963 memcpy(entry
, key
, CACHE_KEY_SIZE
);
966 /* This function lets us test whether a given key was previously
967 * stored in the cache with disk_cache_put_key(). The implement is
968 * efficient by not using syscalls or hitting the disk. It's not
969 * race-free, but the races are benign. If we race with someone else
970 * calling disk_cache_put_key, then that's just an extra cache miss and an
974 disk_cache_has_key(struct disk_cache
*cache
, const cache_key key
)
976 const uint32_t *key_chunk
= (const uint32_t *) key
;
977 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
978 unsigned char *entry
;
980 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
982 return memcmp(entry
, key
, CACHE_KEY_SIZE
) == 0;
985 #endif /* ENABLE_SHADER_CACHE */