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(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
, 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
, char *path
, const char *timestamp
)
152 DIR *dir
= opendir(path
);
154 struct dirent
* d_entry
;
155 while((d_entry
= readdir(dir
)) != NULL
)
158 ralloc_asprintf(mem_ctx
, "%s/%s", path
, d_entry
->d_name
);
161 if (stat(full_path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
) &&
162 strcmp(d_entry
->d_name
, timestamp
) != 0 &&
163 strcmp(d_entry
->d_name
, "..") != 0 &&
164 strcmp(d_entry
->d_name
, ".") != 0) {
165 nftw(full_path
, remove_dir
, 20, FTW_DEPTH
);
173 create_mesa_cache_dir(void *mem_ctx
, char *path
, const char *timestamp
,
174 const char *gpu_name
)
176 char *new_path
= concatenate_and_mkdir(mem_ctx
, path
, "mesa");
177 if (new_path
== NULL
)
180 /* Remove cache directories for old Mesa versions */
181 remove_old_cache_directories(mem_ctx
, new_path
, timestamp
);
183 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, timestamp
);
184 if (new_path
== NULL
)
187 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, gpu_name
);
188 if (new_path
== NULL
)
195 disk_cache_create(const char *gpu_name
, const char *timestamp
)
198 struct disk_cache
*cache
= NULL
;
199 char *path
, *max_size_str
;
205 /* If running as a users other than the real user disable cache */
206 if (geteuid() != getuid())
209 /* A ralloc context for transient data during this invocation. */
210 local
= ralloc_context(NULL
);
214 /* At user request, disable shader cache entirely. */
215 if (getenv("MESA_GLSL_CACHE_DISABLE"))
218 /* As a temporary measure, (while the shader cache is under
219 * development, and known to not be fully functional), also require
220 * the MESA_GLSL_CACHE_ENABLE variable to be set.
222 if (!getenv("MESA_GLSL_CACHE_ENABLE"))
225 /* Determine path for cache based on the first defined name as follows:
227 * $MESA_GLSL_CACHE_DIR
228 * $XDG_CACHE_HOME/mesa
229 * <pwd.pw_dir>/.cache/mesa
231 path
= getenv("MESA_GLSL_CACHE_DIR");
233 if (mkdir_if_needed(path
) == -1)
236 path
= create_mesa_cache_dir(local
, path
, timestamp
,
243 char *xdg_cache_home
= getenv("XDG_CACHE_HOME");
245 if (xdg_cache_home
) {
246 if (mkdir_if_needed(xdg_cache_home
) == -1)
249 path
= create_mesa_cache_dir(local
, xdg_cache_home
, timestamp
,
259 struct passwd pwd
, *result
;
261 buf_size
= sysconf(_SC_GETPW_R_SIZE_MAX
);
265 /* Loop until buf_size is large enough to query the directory */
267 buf
= ralloc_size(local
, buf_size
);
269 getpwuid_r(getuid(), &pwd
, buf
, buf_size
, &result
);
273 if (errno
== ERANGE
) {
282 path
= concatenate_and_mkdir(local
, pwd
.pw_dir
, ".cache");
286 path
= create_mesa_cache_dir(local
, path
, timestamp
, gpu_name
);
291 cache
= ralloc(NULL
, struct disk_cache
);
295 cache
->path
= ralloc_strdup(cache
, path
);
296 if (cache
->path
== NULL
)
299 path
= ralloc_asprintf(local
, "%s/index", cache
->path
);
303 fd
= open(path
, O_RDWR
| O_CREAT
| O_CLOEXEC
, 0644);
307 if (fstat(fd
, &sb
) == -1)
310 /* Force the index file to be the expected size. */
311 size
= sizeof(*cache
->size
) + CACHE_INDEX_MAX_KEYS
* CACHE_KEY_SIZE
;
312 if (sb
.st_size
!= size
) {
313 if (ftruncate(fd
, size
) == -1)
317 /* We map this shared so that other processes see updates that we
320 * Note: We do use atomic addition to ensure that multiple
321 * processes don't scramble the cache size recorded in the
322 * index. But we don't use any locking to prevent multiple
323 * processes from updating the same entry simultaneously. The idea
324 * is that if either result lands entirely in the index, then
325 * that's equivalent to a well-ordered write followed by an
326 * eviction and a write. On the other hand, if the simultaneous
327 * writes result in a corrupt entry, that's not really any
328 * different than both entries being evicted, (since within the
329 * guarantees of the cryptographic hash, a corrupt entry is
330 * unlikely to ever match a real cache key).
332 cache
->index_mmap
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
334 if (cache
->index_mmap
== MAP_FAILED
)
336 cache
->index_mmap_size
= size
;
340 cache
->size
= (uint64_t *) cache
->index_mmap
;
341 cache
->stored_keys
= cache
->index_mmap
+ sizeof(uint64_t);
345 max_size_str
= getenv("MESA_GLSL_CACHE_MAX_SIZE");
348 max_size
= strtoul(max_size_str
, &end
, 10);
349 if (end
== max_size_str
) {
359 max_size
*= 1024*1024;
365 max_size
*= 1024*1024*1024;
371 /* Default to 1GB for maximum cache size. */
373 max_size
= 1024*1024*1024;
375 cache
->max_size
= max_size
;
392 disk_cache_destroy(struct disk_cache
*cache
)
395 munmap(cache
->index_mmap
, cache
->index_mmap_size
);
400 /* Return a filename within the cache's directory corresponding to 'key'. The
401 * returned filename is ralloced with 'cache' as the parent context.
403 * Returns NULL if out of memory.
406 get_cache_file(struct disk_cache
*cache
, cache_key key
)
411 _mesa_sha1_format(buf
, key
);
412 if (asprintf(&filename
, "%s/%c%c/%s", cache
->path
, buf
[0],
413 buf
[1], buf
+ 2) == -1)
419 /* Create the directory that will be needed for the cache file for \key.
421 * Obviously, the implementation here must closely match
422 * _get_cache_file above.
425 make_cache_file_directory(struct disk_cache
*cache
, cache_key key
)
430 _mesa_sha1_format(buf
, key
);
431 if (asprintf(&dir
, "%s/%c%c", cache
->path
, buf
[0], buf
[1]) == -1)
434 mkdir_if_needed(dir
);
438 /* Given a directory path and predicate function, count all entries in
439 * that directory for which the predicate returns true. Then choose a
440 * random entry from among those counted.
442 * Returns: A malloc'ed string for the path to the chosen file, (or
443 * NULL on any error). The caller should free the string when
447 choose_random_file_matching(const char *dir_path
,
448 bool (*predicate
)(struct dirent
*,
449 const char *dir_path
))
452 struct dirent
*entry
;
453 unsigned int count
, victim
;
456 dir
= opendir(dir_path
);
463 entry
= readdir(dir
);
466 if (!predicate(entry
, dir_path
))
477 victim
= rand() % count
;
483 entry
= readdir(dir
);
486 if (!predicate(entry
, dir_path
))
499 if (asprintf(&filename
, "%s/%s", dir_path
, entry
->d_name
) < 0)
507 /* Is entry a regular file, and not having a name with a trailing
511 is_regular_non_tmp_file(struct dirent
*entry
, const char *path
)
514 if (asprintf(&filename
, "%s/%s", path
, entry
->d_name
) == -1)
518 int res
= stat(filename
, &sb
);
521 if (res
== -1 || !S_ISREG(sb
.st_mode
))
524 size_t len
= strlen (entry
->d_name
);
525 if (len
>= 4 && strcmp(&entry
->d_name
[len
-4], ".tmp") == 0)
531 /* Returns the size of the deleted file, (or 0 on any error). */
533 unlink_random_file_from_directory(const char *path
)
538 filename
= choose_random_file_matching(path
, is_regular_non_tmp_file
);
539 if (filename
== NULL
)
542 if (stat(filename
, &sb
) == -1) {
554 /* Is entry a directory with a two-character name, (and not the
555 * special name of "..")
558 is_two_character_sub_directory(struct dirent
*entry
, const char *path
)
561 if (asprintf(&subdir
, "%s/%s", path
, entry
->d_name
) == -1)
565 int res
= stat(subdir
, &sb
);
568 if (res
== -1 || !S_ISDIR(sb
.st_mode
))
571 if (strlen(entry
->d_name
) != 2)
574 if (strcmp(entry
->d_name
, "..") == 0)
581 evict_random_item(struct disk_cache
*cache
)
583 const char hex
[] = "0123456789abcde";
588 /* With a reasonably-sized, full cache, (and with keys generated
589 * from a cryptographic hash), we can choose two random hex digits
590 * and reasonably expect the directory to exist with a file in it.
595 if (asprintf(&dir_path
, "%s/%c%c", cache
->path
, hex
[a
], hex
[b
]) < 0)
598 size
= unlink_random_file_from_directory(dir_path
);
603 p_atomic_add(cache
->size
, - size
);
607 /* In the case where the random choice of directory didn't find
608 * something, we choose randomly from the existing directories.
610 * Really, the only reason this code exists is to allow the unit
611 * tests to work, (which use an artificially-small cache to be able
612 * to force a single cached item to be evicted).
614 dir_path
= choose_random_file_matching(cache
->path
,
615 is_two_character_sub_directory
);
616 if (dir_path
== NULL
)
619 size
= unlink_random_file_from_directory(dir_path
);
624 p_atomic_add(cache
->size
, - size
);
628 disk_cache_remove(struct disk_cache
*cache
, cache_key key
)
632 char *filename
= get_cache_file(cache
, key
);
633 if (filename
== NULL
) {
637 if (stat(filename
, &sb
) == -1) {
646 p_atomic_add(cache
->size
, - sb
.st_size
);
649 /* From the zlib docs:
650 * "If the memory is available, buffers sizes on the order of 128K or 256K
651 * bytes should be used."
653 #define BUFSIZE 256 * 1024
656 * Compresses cache entry in memory and writes it to disk. Returns the size
657 * of the data written to disk.
660 deflate_and_write_to_disk(const void *in_data
, size_t in_data_size
, int dest
,
663 unsigned char out
[BUFSIZE
];
665 /* allocate deflate state */
667 strm
.zalloc
= Z_NULL
;
669 strm
.opaque
= Z_NULL
;
670 strm
.next_in
= (uint8_t *) in_data
;
671 strm
.avail_in
= in_data_size
;
673 int ret
= deflateInit(&strm
, Z_BEST_COMPRESSION
);
677 /* compress until end of in_data */
678 size_t compressed_size
= 0;
681 int remaining
= in_data_size
- BUFSIZE
;
682 flush
= remaining
> 0 ? Z_NO_FLUSH
: Z_FINISH
;
683 in_data_size
-= BUFSIZE
;
685 /* Run deflate() on input until the output buffer is not full (which
686 * means there is no more data to deflate).
689 strm
.avail_out
= BUFSIZE
;
692 ret
= deflate(&strm
, flush
); /* no bad return value */
693 assert(ret
!= Z_STREAM_ERROR
); /* state not clobbered */
695 size_t have
= BUFSIZE
- strm
.avail_out
;
696 compressed_size
+= compressed_size
+ have
;
699 for (size_t len
= 0; len
< have
; len
+= written
) {
700 written
= write(dest
, out
+ len
, have
- len
);
702 (void)deflateEnd(&strm
);
706 } while (strm
.avail_out
== 0);
708 /* all input should be used */
709 assert(strm
.avail_in
== 0);
711 } while (flush
!= Z_FINISH
);
713 /* stream should be complete */
714 assert(ret
== Z_STREAM_END
);
716 /* clean up and return */
717 (void)deflateEnd(&strm
);
718 return compressed_size
;
721 struct cache_entry_file_data
{
723 uint32_t uncompressed_size
;
727 disk_cache_put(struct disk_cache
*cache
,
732 int fd
= -1, fd_final
= -1, err
, ret
;
734 char *filename
= NULL
, *filename_tmp
= NULL
;
736 filename
= get_cache_file(cache
, key
);
737 if (filename
== NULL
)
740 /* Write to a temporary file to allow for an atomic rename to the
741 * final destination filename, (to prevent any readers from seeing
742 * a partially written file).
744 if (asprintf(&filename_tmp
, "%s.tmp", filename
) == -1)
747 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
749 /* Make the two-character subdirectory within the cache as needed. */
754 make_cache_file_directory(cache
, key
);
756 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
761 /* With the temporary file open, we take an exclusive flock on
762 * it. If the flock fails, then another process still has the file
763 * open with the flock held. So just let that file be responsible
764 * for writing the file.
766 err
= flock(fd
, LOCK_EX
| LOCK_NB
);
770 /* Now that we have the lock on the open temporary file, we can
771 * check to see if the destination file already exists. If so,
772 * another process won the race between when we saw that the file
773 * didn't exist and now. In this case, we don't do anything more,
774 * (to ensure the size accounting of the cache doesn't get off).
776 fd_final
= open(filename
, O_RDONLY
| O_CLOEXEC
);
780 /* OK, we're now on the hook to write out a file that we know is
781 * not in the cache, and is also not being written out to the cache
782 * by some other process.
784 * Before we do that, if the cache is too large, evict something
787 if (*cache
->size
+ size
> cache
->max_size
)
788 evict_random_item(cache
);
790 /* Create CRC of the data and store at the start of the file. We will
791 * read this when restoring the cache and use it to check for corruption.
793 struct cache_entry_file_data cf_data
;
794 cf_data
.crc32
= util_hash_crc32(data
, size
);
795 cf_data
.uncompressed_size
= size
;
797 size_t cf_data_size
= sizeof(cf_data
);
798 for (len
= 0; len
< cf_data_size
; len
+= ret
) {
799 ret
= write(fd
, ((uint8_t *) &cf_data
) + len
, cf_data_size
- len
);
801 unlink(filename_tmp
);
806 /* Now, finally, write out the contents to the temporary file, then
807 * rename them atomically to the destination filename, and also
808 * perform an atomic increment of the total cache size.
810 size_t file_size
= deflate_and_write_to_disk(data
, size
, fd
, filename_tmp
);
811 if (file_size
== 0) {
812 unlink(filename_tmp
);
815 rename(filename_tmp
, filename
);
817 file_size
+= cf_data_size
;
818 p_atomic_add(cache
->size
, file_size
);
823 /* This close finally releases the flock, (now that the final dile
824 * has been renamed into place and the size has been added).
835 * Decompresses cache entry, returns true if successful.
838 inflate_cache_data(uint8_t *in_data
, size_t in_data_size
,
839 uint8_t *out_data
, size_t out_data_size
)
843 /* allocate inflate state */
844 strm
.zalloc
= Z_NULL
;
846 strm
.opaque
= Z_NULL
;
847 strm
.next_in
= in_data
;
848 strm
.avail_in
= in_data_size
;
849 strm
.next_out
= out_data
;
850 strm
.avail_out
= out_data_size
;
852 int ret
= inflateInit(&strm
);
856 ret
= inflate(&strm
, Z_NO_FLUSH
);
857 assert(ret
!= Z_STREAM_ERROR
); /* state not clobbered */
859 /* Unless there was an error we should have decompressed everything in one
860 * go as we know the uncompressed file size.
862 if (ret
!= Z_STREAM_END
) {
863 (void)inflateEnd(&strm
);
866 assert(strm
.avail_out
== 0);
868 /* clean up and return */
869 (void)inflateEnd(&strm
);
874 disk_cache_get(struct disk_cache
*cache
, cache_key key
, size_t *size
)
876 int fd
= -1, ret
, len
;
878 char *filename
= NULL
;
879 uint8_t *data
= NULL
;
880 uint8_t *uncompressed_data
= NULL
;
885 filename
= get_cache_file(cache
, key
);
886 if (filename
== NULL
)
889 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
893 if (fstat(fd
, &sb
) == -1)
896 data
= malloc(sb
.st_size
);
900 /* Load the CRC that was created when the file was written. */
901 struct cache_entry_file_data cf_data
;
902 size_t cf_data_size
= sizeof(cf_data
);
903 assert(sb
.st_size
> cf_data_size
);
904 for (len
= 0; len
< cf_data_size
; len
+= ret
) {
905 ret
= read(fd
, ((uint8_t *) &cf_data
) + len
, cf_data_size
- len
);
910 /* Load the actual cache data. */
911 size_t cache_data_size
= sb
.st_size
- cf_data_size
;
912 for (len
= 0; len
< cache_data_size
; len
+= ret
) {
913 ret
= read(fd
, data
+ len
, cache_data_size
- len
);
918 /* Uncompress the cache data */
919 uncompressed_data
= malloc(cf_data
.uncompressed_size
);
920 if (!inflate_cache_data(data
, cache_data_size
, uncompressed_data
,
921 cf_data
.uncompressed_size
))
924 /* Check the data for corruption */
925 if (cf_data
.crc32
!= util_hash_crc32(uncompressed_data
,
926 cf_data
.uncompressed_size
))
934 *size
= cf_data
.uncompressed_size
;
936 return uncompressed_data
;
941 if (uncompressed_data
)
942 free(uncompressed_data
);
952 disk_cache_put_key(struct disk_cache
*cache
, cache_key key
)
954 uint32_t *key_chunk
= (uint32_t *) key
;
955 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
956 unsigned char *entry
;
958 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
960 memcpy(entry
, key
, CACHE_KEY_SIZE
);
963 /* This function lets us test whether a given key was previously
964 * stored in the cache with disk_cache_put_key(). The implement is
965 * efficient by not using syscalls or hitting the disk. It's not
966 * race-free, but the races are benign. If we race with someone else
967 * calling disk_cache_put_key, then that's just an extra cache miss and an
971 disk_cache_has_key(struct disk_cache
*cache
, cache_key key
)
973 uint32_t *key_chunk
= (uint32_t *) key
;
974 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
975 unsigned char *entry
;
977 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
979 return memcmp(entry
, key
, CACHE_KEY_SIZE
) == 0;
982 #endif /* ENABLE_SHADER_CACHE */