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). */
78 get_arch_bitness_str(void)
80 if (sizeof(void *) == 4)
86 if (sizeof(void *) == 8)
89 /* paranoia check which will be dropped by the optimiser */
90 assert(!"unknown_arch");
91 return "unknown_arch";
94 /* Create a directory named 'path' if it does not already exist.
96 * Returns: 0 if path already exists as a directory or if created.
97 * -1 in all other cases.
100 mkdir_if_needed(const char *path
)
104 /* If the path exists already, then our work is done if it's a
105 * directory, but it's an error if it is not.
107 if (stat(path
, &sb
) == 0) {
108 if (S_ISDIR(sb
.st_mode
)) {
111 fprintf(stderr
, "Cannot use %s for shader cache (not a directory)"
112 "---disabling.\n", path
);
117 int ret
= mkdir(path
, 0755);
118 if (ret
== 0 || (ret
== -1 && errno
== EEXIST
))
121 fprintf(stderr
, "Failed to create %s for shader cache (%s)---disabling.\n",
122 path
, strerror(errno
));
127 /* Concatenate an existing path and a new name to form a new path. If the new
128 * path does not exist as a directory, create it then return the resulting
129 * name of the new path (ralloc'ed off of 'ctx').
131 * Returns NULL on any error, such as:
133 * <path> does not exist or is not a directory
134 * <path>/<name> exists but is not a directory
135 * <path>/<name> cannot be created as a directory
138 concatenate_and_mkdir(void *ctx
, const char *path
, const char *name
)
143 if (stat(path
, &sb
) != 0 || ! S_ISDIR(sb
.st_mode
))
146 new_path
= ralloc_asprintf(ctx
, "%s/%s", path
, name
);
148 if (mkdir_if_needed(new_path
) == 0)
155 remove_dir(const char *fpath
, const struct stat
*sb
,
156 int typeflag
, struct FTW
*ftwbuf
)
158 if (S_ISREG(sb
->st_mode
))
160 else if (S_ISDIR(sb
->st_mode
))
167 remove_old_cache_directories(void *mem_ctx
, const char *path
,
168 const char *timestamp
)
170 DIR *dir
= opendir(path
);
172 struct dirent
* d_entry
;
173 while((d_entry
= readdir(dir
)) != NULL
)
176 ralloc_asprintf(mem_ctx
, "%s/%s", path
, d_entry
->d_name
);
179 if (stat(full_path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
) &&
180 strcmp(d_entry
->d_name
, timestamp
) != 0 &&
181 strcmp(d_entry
->d_name
, "..") != 0 &&
182 strcmp(d_entry
->d_name
, ".") != 0) {
183 nftw(full_path
, remove_dir
, 20, FTW_DEPTH
);
191 create_mesa_cache_dir(void *mem_ctx
, const char *path
, const char *timestamp
,
192 const char *gpu_name
)
194 char *new_path
= concatenate_and_mkdir(mem_ctx
, path
, "mesa");
195 if (new_path
== NULL
)
198 /* Create a parent architecture directory so that we don't remove cache
199 * files for other architectures. In theory we could share the cache
200 * between architectures but we have no way of knowing if they were created
201 * by a compatible Mesa version.
203 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, get_arch_bitness_str());
204 if (new_path
== NULL
)
207 /* Remove cache directories for old Mesa versions */
208 remove_old_cache_directories(mem_ctx
, new_path
, timestamp
);
210 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, timestamp
);
211 if (new_path
== NULL
)
214 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, gpu_name
);
215 if (new_path
== NULL
)
222 disk_cache_create(const char *gpu_name
, const char *timestamp
)
225 struct disk_cache
*cache
= NULL
;
226 char *path
, *max_size_str
;
232 /* If running as a users other than the real user disable cache */
233 if (geteuid() != getuid())
236 /* A ralloc context for transient data during this invocation. */
237 local
= ralloc_context(NULL
);
241 /* At user request, disable shader cache entirely. */
242 if (getenv("MESA_GLSL_CACHE_DISABLE"))
245 /* Determine path for cache based on the first defined name as follows:
247 * $MESA_GLSL_CACHE_DIR
248 * $XDG_CACHE_HOME/mesa
249 * <pwd.pw_dir>/.cache/mesa
251 path
= getenv("MESA_GLSL_CACHE_DIR");
253 if (mkdir_if_needed(path
) == -1)
256 path
= create_mesa_cache_dir(local
, path
, timestamp
,
263 char *xdg_cache_home
= getenv("XDG_CACHE_HOME");
265 if (xdg_cache_home
) {
266 if (mkdir_if_needed(xdg_cache_home
) == -1)
269 path
= create_mesa_cache_dir(local
, xdg_cache_home
, timestamp
,
279 struct passwd pwd
, *result
;
281 buf_size
= sysconf(_SC_GETPW_R_SIZE_MAX
);
285 /* Loop until buf_size is large enough to query the directory */
287 buf
= ralloc_size(local
, buf_size
);
289 getpwuid_r(getuid(), &pwd
, buf
, buf_size
, &result
);
293 if (errno
== ERANGE
) {
302 path
= concatenate_and_mkdir(local
, pwd
.pw_dir
, ".cache");
306 path
= create_mesa_cache_dir(local
, path
, timestamp
, gpu_name
);
311 cache
= ralloc(NULL
, struct disk_cache
);
315 cache
->path
= ralloc_strdup(cache
, path
);
316 if (cache
->path
== NULL
)
319 path
= ralloc_asprintf(local
, "%s/index", cache
->path
);
323 fd
= open(path
, O_RDWR
| O_CREAT
| O_CLOEXEC
, 0644);
327 if (fstat(fd
, &sb
) == -1)
330 /* Force the index file to be the expected size. */
331 size
= sizeof(*cache
->size
) + CACHE_INDEX_MAX_KEYS
* CACHE_KEY_SIZE
;
332 if (sb
.st_size
!= size
) {
333 if (ftruncate(fd
, size
) == -1)
337 /* We map this shared so that other processes see updates that we
340 * Note: We do use atomic addition to ensure that multiple
341 * processes don't scramble the cache size recorded in the
342 * index. But we don't use any locking to prevent multiple
343 * processes from updating the same entry simultaneously. The idea
344 * is that if either result lands entirely in the index, then
345 * that's equivalent to a well-ordered write followed by an
346 * eviction and a write. On the other hand, if the simultaneous
347 * writes result in a corrupt entry, that's not really any
348 * different than both entries being evicted, (since within the
349 * guarantees of the cryptographic hash, a corrupt entry is
350 * unlikely to ever match a real cache key).
352 cache
->index_mmap
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
354 if (cache
->index_mmap
== MAP_FAILED
)
356 cache
->index_mmap_size
= size
;
360 cache
->size
= (uint64_t *) cache
->index_mmap
;
361 cache
->stored_keys
= cache
->index_mmap
+ sizeof(uint64_t);
365 max_size_str
= getenv("MESA_GLSL_CACHE_MAX_SIZE");
368 max_size
= strtoul(max_size_str
, &end
, 10);
369 if (end
== max_size_str
) {
379 max_size
*= 1024*1024;
385 max_size
*= 1024*1024*1024;
391 /* Default to 1GB for maximum cache size. */
393 max_size
= 1024*1024*1024;
395 cache
->max_size
= max_size
;
412 disk_cache_destroy(struct disk_cache
*cache
)
415 munmap(cache
->index_mmap
, cache
->index_mmap_size
);
420 /* Return a filename within the cache's directory corresponding to 'key'. The
421 * returned filename is ralloced with 'cache' as the parent context.
423 * Returns NULL if out of memory.
426 get_cache_file(struct disk_cache
*cache
, const cache_key key
)
431 _mesa_sha1_format(buf
, key
);
432 if (asprintf(&filename
, "%s/%c%c/%s", cache
->path
, buf
[0],
433 buf
[1], buf
+ 2) == -1)
439 /* Create the directory that will be needed for the cache file for \key.
441 * Obviously, the implementation here must closely match
442 * _get_cache_file above.
445 make_cache_file_directory(struct disk_cache
*cache
, const cache_key key
)
450 _mesa_sha1_format(buf
, key
);
451 if (asprintf(&dir
, "%s/%c%c", cache
->path
, buf
[0], buf
[1]) == -1)
454 mkdir_if_needed(dir
);
458 /* Given a directory path and predicate function, count all entries in
459 * that directory for which the predicate returns true. Then choose a
460 * random entry from among those counted.
462 * Returns: A malloc'ed string for the path to the chosen file, (or
463 * NULL on any error). The caller should free the string when
467 choose_random_file_matching(const char *dir_path
,
468 bool (*predicate
)(const struct dirent
*,
469 const char *dir_path
))
472 struct dirent
*entry
;
473 unsigned int count
, victim
;
476 dir
= opendir(dir_path
);
483 entry
= readdir(dir
);
486 if (!predicate(entry
, dir_path
))
497 victim
= rand() % count
;
503 entry
= readdir(dir
);
506 if (!predicate(entry
, dir_path
))
519 if (asprintf(&filename
, "%s/%s", dir_path
, entry
->d_name
) < 0)
527 /* Is entry a regular file, and not having a name with a trailing
531 is_regular_non_tmp_file(const struct dirent
*entry
, const char *path
)
534 if (asprintf(&filename
, "%s/%s", path
, entry
->d_name
) == -1)
538 int res
= stat(filename
, &sb
);
541 if (res
== -1 || !S_ISREG(sb
.st_mode
))
544 size_t len
= strlen (entry
->d_name
);
545 if (len
>= 4 && strcmp(&entry
->d_name
[len
-4], ".tmp") == 0)
551 /* Returns the size of the deleted file, (or 0 on any error). */
553 unlink_random_file_from_directory(const char *path
)
558 filename
= choose_random_file_matching(path
, is_regular_non_tmp_file
);
559 if (filename
== NULL
)
562 if (stat(filename
, &sb
) == -1) {
574 /* Is entry a directory with a two-character name, (and not the
575 * special name of "..")
578 is_two_character_sub_directory(const struct dirent
*entry
, const char *path
)
581 if (asprintf(&subdir
, "%s/%s", path
, entry
->d_name
) == -1)
585 int res
= stat(subdir
, &sb
);
588 if (res
== -1 || !S_ISDIR(sb
.st_mode
))
591 if (strlen(entry
->d_name
) != 2)
594 if (strcmp(entry
->d_name
, "..") == 0)
601 evict_random_item(struct disk_cache
*cache
)
603 const char hex
[] = "0123456789abcde";
608 /* With a reasonably-sized, full cache, (and with keys generated
609 * from a cryptographic hash), we can choose two random hex digits
610 * and reasonably expect the directory to exist with a file in it.
615 if (asprintf(&dir_path
, "%s/%c%c", cache
->path
, hex
[a
], hex
[b
]) < 0)
618 size
= unlink_random_file_from_directory(dir_path
);
623 p_atomic_add(cache
->size
, - size
);
627 /* In the case where the random choice of directory didn't find
628 * something, we choose randomly from the existing directories.
630 * Really, the only reason this code exists is to allow the unit
631 * tests to work, (which use an artificially-small cache to be able
632 * to force a single cached item to be evicted).
634 dir_path
= choose_random_file_matching(cache
->path
,
635 is_two_character_sub_directory
);
636 if (dir_path
== NULL
)
639 size
= unlink_random_file_from_directory(dir_path
);
644 p_atomic_add(cache
->size
, - size
);
648 disk_cache_remove(struct disk_cache
*cache
, const cache_key key
)
652 char *filename
= get_cache_file(cache
, key
);
653 if (filename
== NULL
) {
657 if (stat(filename
, &sb
) == -1) {
666 p_atomic_add(cache
->size
, - sb
.st_size
);
669 /* From the zlib docs:
670 * "If the memory is available, buffers sizes on the order of 128K or 256K
671 * bytes should be used."
673 #define BUFSIZE 256 * 1024
676 * Compresses cache entry in memory and writes it to disk. Returns the size
677 * of the data written to disk.
680 deflate_and_write_to_disk(const void *in_data
, size_t in_data_size
, int dest
,
681 const char *filename
)
683 unsigned char out
[BUFSIZE
];
685 /* allocate deflate state */
687 strm
.zalloc
= Z_NULL
;
689 strm
.opaque
= Z_NULL
;
690 strm
.next_in
= (uint8_t *) in_data
;
691 strm
.avail_in
= in_data_size
;
693 int ret
= deflateInit(&strm
, Z_BEST_COMPRESSION
);
697 /* compress until end of in_data */
698 size_t compressed_size
= 0;
701 int remaining
= in_data_size
- BUFSIZE
;
702 flush
= remaining
> 0 ? Z_NO_FLUSH
: Z_FINISH
;
703 in_data_size
-= BUFSIZE
;
705 /* Run deflate() on input until the output buffer is not full (which
706 * means there is no more data to deflate).
709 strm
.avail_out
= BUFSIZE
;
712 ret
= deflate(&strm
, flush
); /* no bad return value */
713 assert(ret
!= Z_STREAM_ERROR
); /* state not clobbered */
715 size_t have
= BUFSIZE
- strm
.avail_out
;
716 compressed_size
+= compressed_size
+ have
;
719 for (size_t len
= 0; len
< have
; len
+= written
) {
720 written
= write(dest
, out
+ len
, have
- len
);
722 (void)deflateEnd(&strm
);
726 } while (strm
.avail_out
== 0);
728 /* all input should be used */
729 assert(strm
.avail_in
== 0);
731 } while (flush
!= Z_FINISH
);
733 /* stream should be complete */
734 assert(ret
== Z_STREAM_END
);
736 /* clean up and return */
737 (void)deflateEnd(&strm
);
738 return compressed_size
;
741 struct cache_entry_file_data
{
743 uint32_t uncompressed_size
;
747 disk_cache_put(struct disk_cache
*cache
,
752 int fd
= -1, fd_final
= -1, err
, ret
;
754 char *filename
= NULL
, *filename_tmp
= NULL
;
756 filename
= get_cache_file(cache
, key
);
757 if (filename
== NULL
)
760 /* Write to a temporary file to allow for an atomic rename to the
761 * final destination filename, (to prevent any readers from seeing
762 * a partially written file).
764 if (asprintf(&filename_tmp
, "%s.tmp", filename
) == -1)
767 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
769 /* Make the two-character subdirectory within the cache as needed. */
774 make_cache_file_directory(cache
, key
);
776 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
781 /* With the temporary file open, we take an exclusive flock on
782 * it. If the flock fails, then another process still has the file
783 * open with the flock held. So just let that file be responsible
784 * for writing the file.
786 err
= flock(fd
, LOCK_EX
| LOCK_NB
);
790 /* Now that we have the lock on the open temporary file, we can
791 * check to see if the destination file already exists. If so,
792 * another process won the race between when we saw that the file
793 * didn't exist and now. In this case, we don't do anything more,
794 * (to ensure the size accounting of the cache doesn't get off).
796 fd_final
= open(filename
, O_RDONLY
| O_CLOEXEC
);
800 /* OK, we're now on the hook to write out a file that we know is
801 * not in the cache, and is also not being written out to the cache
802 * by some other process.
804 * Before we do that, if the cache is too large, evict something
807 if (*cache
->size
+ size
> cache
->max_size
)
808 evict_random_item(cache
);
810 /* Create CRC of the data and store at the start of the file. We will
811 * read this when restoring the cache and use it to check for corruption.
813 struct cache_entry_file_data cf_data
;
814 cf_data
.crc32
= util_hash_crc32(data
, size
);
815 cf_data
.uncompressed_size
= size
;
817 size_t cf_data_size
= sizeof(cf_data
);
818 for (len
= 0; len
< cf_data_size
; len
+= ret
) {
819 ret
= write(fd
, ((uint8_t *) &cf_data
) + len
, cf_data_size
- len
);
821 unlink(filename_tmp
);
826 /* Now, finally, write out the contents to the temporary file, then
827 * rename them atomically to the destination filename, and also
828 * perform an atomic increment of the total cache size.
830 size_t file_size
= deflate_and_write_to_disk(data
, size
, fd
, filename_tmp
);
831 if (file_size
== 0) {
832 unlink(filename_tmp
);
835 rename(filename_tmp
, filename
);
837 file_size
+= cf_data_size
;
838 p_atomic_add(cache
->size
, file_size
);
843 /* This close finally releases the flock, (now that the final dile
844 * has been renamed into place and the size has been added).
855 * Decompresses cache entry, returns true if successful.
858 inflate_cache_data(uint8_t *in_data
, size_t in_data_size
,
859 uint8_t *out_data
, size_t out_data_size
)
863 /* allocate inflate state */
864 strm
.zalloc
= Z_NULL
;
866 strm
.opaque
= Z_NULL
;
867 strm
.next_in
= in_data
;
868 strm
.avail_in
= in_data_size
;
869 strm
.next_out
= out_data
;
870 strm
.avail_out
= out_data_size
;
872 int ret
= inflateInit(&strm
);
876 ret
= inflate(&strm
, Z_NO_FLUSH
);
877 assert(ret
!= Z_STREAM_ERROR
); /* state not clobbered */
879 /* Unless there was an error we should have decompressed everything in one
880 * go as we know the uncompressed file size.
882 if (ret
!= Z_STREAM_END
) {
883 (void)inflateEnd(&strm
);
886 assert(strm
.avail_out
== 0);
888 /* clean up and return */
889 (void)inflateEnd(&strm
);
894 disk_cache_get(struct disk_cache
*cache
, const cache_key key
, size_t *size
)
896 int fd
= -1, ret
, len
;
898 char *filename
= NULL
;
899 uint8_t *data
= NULL
;
900 uint8_t *uncompressed_data
= NULL
;
905 filename
= get_cache_file(cache
, key
);
906 if (filename
== NULL
)
909 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
913 if (fstat(fd
, &sb
) == -1)
916 data
= malloc(sb
.st_size
);
920 /* Load the CRC that was created when the file was written. */
921 struct cache_entry_file_data cf_data
;
922 size_t cf_data_size
= sizeof(cf_data
);
923 assert(sb
.st_size
> cf_data_size
);
924 for (len
= 0; len
< cf_data_size
; len
+= ret
) {
925 ret
= read(fd
, ((uint8_t *) &cf_data
) + len
, cf_data_size
- len
);
930 /* Load the actual cache data. */
931 size_t cache_data_size
= sb
.st_size
- cf_data_size
;
932 for (len
= 0; len
< cache_data_size
; len
+= ret
) {
933 ret
= read(fd
, data
+ len
, cache_data_size
- len
);
938 /* Uncompress the cache data */
939 uncompressed_data
= malloc(cf_data
.uncompressed_size
);
940 if (!inflate_cache_data(data
, cache_data_size
, uncompressed_data
,
941 cf_data
.uncompressed_size
))
944 /* Check the data for corruption */
945 if (cf_data
.crc32
!= util_hash_crc32(uncompressed_data
,
946 cf_data
.uncompressed_size
))
954 *size
= cf_data
.uncompressed_size
;
956 return uncompressed_data
;
961 if (uncompressed_data
)
962 free(uncompressed_data
);
972 disk_cache_put_key(struct disk_cache
*cache
, const cache_key key
)
974 const uint32_t *key_chunk
= (const uint32_t *) key
;
975 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
976 unsigned char *entry
;
978 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
980 memcpy(entry
, key
, CACHE_KEY_SIZE
);
983 /* This function lets us test whether a given key was previously
984 * stored in the cache with disk_cache_put_key(). The implement is
985 * efficient by not using syscalls or hitting the disk. It's not
986 * race-free, but the races are benign. If we race with someone else
987 * calling disk_cache_put_key, then that's just an extra cache miss and an
991 disk_cache_has_key(struct disk_cache
*cache
, const cache_key key
)
993 const uint32_t *key_chunk
= (const uint32_t *) key
;
994 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
995 unsigned char *entry
;
997 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
999 return memcmp(entry
, key
, CACHE_KEY_SIZE
) == 0;
1002 #endif /* ENABLE_SHADER_CACHE */