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>
41 #include "util/crc32.h"
42 #include "util/u_atomic.h"
43 #include "util/mesa-sha1.h"
44 #include "util/ralloc.h"
45 #include "main/errors.h"
47 #include "disk_cache.h"
49 /* Number of bits to mask off from a cache key to get an index. */
50 #define CACHE_INDEX_KEY_BITS 16
52 /* Mask for computing an index from a key. */
53 #define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
55 /* The number of keys that can be stored in the index. */
56 #define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
59 /* The path to the cache directory. */
62 /* A pointer to the mmapped index file within the cache directory. */
64 size_t index_mmap_size
;
66 /* Pointer to total size of all objects in cache (within index_mmap) */
69 /* Pointer to stored keys, (within index_mmap). */
72 /* Maximum size of all cached objects (in bytes). */
76 /* Create a directory named 'path' if it does not already exist.
78 * Returns: 0 if path already exists as a directory or if created.
79 * -1 in all other cases.
82 mkdir_if_needed(char *path
)
86 /* If the path exists already, then our work is done if it's a
87 * directory, but it's an error if it is not.
89 if (stat(path
, &sb
) == 0) {
90 if (S_ISDIR(sb
.st_mode
)) {
93 fprintf(stderr
, "Cannot use %s for shader cache (not a directory)"
94 "---disabling.\n", path
);
99 int ret
= mkdir(path
, 0755);
100 if (ret
== 0 || (ret
== -1 && errno
== EEXIST
))
103 fprintf(stderr
, "Failed to create %s for shader cache (%s)---disabling.\n",
104 path
, strerror(errno
));
109 /* Concatenate an existing path and a new name to form a new path. If the new
110 * path does not exist as a directory, create it then return the resulting
111 * name of the new path (ralloc'ed off of 'ctx').
113 * Returns NULL on any error, such as:
115 * <path> does not exist or is not a directory
116 * <path>/<name> exists but is not a directory
117 * <path>/<name> cannot be created as a directory
120 concatenate_and_mkdir(void *ctx
, char *path
, const char *name
)
125 if (stat(path
, &sb
) != 0 || ! S_ISDIR(sb
.st_mode
))
128 new_path
= ralloc_asprintf(ctx
, "%s/%s", path
, name
);
130 if (mkdir_if_needed(new_path
) == 0)
137 remove_dir(const char *fpath
, const struct stat
*sb
,
138 int typeflag
, struct FTW
*ftwbuf
)
140 if (S_ISREG(sb
->st_mode
))
142 else if (S_ISDIR(sb
->st_mode
))
149 remove_old_cache_directories(void *mem_ctx
, char *path
, const char *timestamp
)
151 DIR *dir
= opendir(path
);
153 struct dirent
* d_entry
;
154 while((d_entry
= readdir(dir
)) != NULL
)
157 ralloc_asprintf(mem_ctx
, "%s/%s", path
, d_entry
->d_name
);
160 if (stat(full_path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
) &&
161 strcmp(d_entry
->d_name
, timestamp
) != 0 &&
162 strcmp(d_entry
->d_name
, "..") != 0 &&
163 strcmp(d_entry
->d_name
, ".") != 0) {
164 nftw(full_path
, remove_dir
, 20, FTW_DEPTH
);
172 create_mesa_cache_dir(void *mem_ctx
, char *path
, const char *timestamp
,
173 const char *gpu_name
)
175 char *new_path
= concatenate_and_mkdir(mem_ctx
, path
, "mesa");
176 if (new_path
== NULL
)
179 /* Remove cache directories for old Mesa versions */
180 remove_old_cache_directories(mem_ctx
, new_path
, timestamp
);
182 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, timestamp
);
183 if (new_path
== NULL
)
186 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, gpu_name
);
187 if (new_path
== NULL
)
194 disk_cache_create(const char *gpu_name
, const char *timestamp
)
197 struct disk_cache
*cache
= NULL
;
198 char *path
, *max_size_str
;
204 /* If running as a users other than the real user disable cache */
205 if (geteuid() != getuid())
208 /* A ralloc context for transient data during this invocation. */
209 local
= ralloc_context(NULL
);
213 /* At user request, disable shader cache entirely. */
214 if (getenv("MESA_GLSL_CACHE_DISABLE"))
217 /* As a temporary measure, (while the shader cache is under
218 * development, and known to not be fully functional), also require
219 * the MESA_GLSL_CACHE_ENABLE variable to be set.
221 if (!getenv("MESA_GLSL_CACHE_ENABLE"))
224 /* Determine path for cache based on the first defined name as follows:
226 * $MESA_GLSL_CACHE_DIR
227 * $XDG_CACHE_HOME/mesa
228 * <pwd.pw_dir>/.cache/mesa
230 path
= getenv("MESA_GLSL_CACHE_DIR");
232 if (mkdir_if_needed(path
) == -1)
235 path
= create_mesa_cache_dir(local
, path
, timestamp
,
242 char *xdg_cache_home
= getenv("XDG_CACHE_HOME");
244 if (xdg_cache_home
) {
245 if (mkdir_if_needed(xdg_cache_home
) == -1)
248 path
= create_mesa_cache_dir(local
, xdg_cache_home
, timestamp
,
258 struct passwd pwd
, *result
;
260 buf_size
= sysconf(_SC_GETPW_R_SIZE_MAX
);
264 /* Loop until buf_size is large enough to query the directory */
266 buf
= ralloc_size(local
, buf_size
);
268 getpwuid_r(getuid(), &pwd
, buf
, buf_size
, &result
);
272 if (errno
== ERANGE
) {
281 path
= concatenate_and_mkdir(local
, pwd
.pw_dir
, ".cache");
285 path
= create_mesa_cache_dir(local
, path
, timestamp
, gpu_name
);
290 cache
= ralloc(NULL
, struct disk_cache
);
294 cache
->path
= ralloc_strdup(cache
, path
);
295 if (cache
->path
== NULL
)
298 path
= ralloc_asprintf(local
, "%s/index", cache
->path
);
302 fd
= open(path
, O_RDWR
| O_CREAT
| O_CLOEXEC
, 0644);
306 if (fstat(fd
, &sb
) == -1)
309 /* Force the index file to be the expected size. */
310 size
= sizeof(*cache
->size
) + CACHE_INDEX_MAX_KEYS
* CACHE_KEY_SIZE
;
311 if (sb
.st_size
!= size
) {
312 if (ftruncate(fd
, size
) == -1)
316 /* We map this shared so that other processes see updates that we
319 * Note: We do use atomic addition to ensure that multiple
320 * processes don't scramble the cache size recorded in the
321 * index. But we don't use any locking to prevent multiple
322 * processes from updating the same entry simultaneously. The idea
323 * is that if either result lands entirely in the index, then
324 * that's equivalent to a well-ordered write followed by an
325 * eviction and a write. On the other hand, if the simultaneous
326 * writes result in a corrupt entry, that's not really any
327 * different than both entries being evicted, (since within the
328 * guarantees of the cryptographic hash, a corrupt entry is
329 * unlikely to ever match a real cache key).
331 cache
->index_mmap
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
333 if (cache
->index_mmap
== MAP_FAILED
)
335 cache
->index_mmap_size
= size
;
339 cache
->size
= (uint64_t *) cache
->index_mmap
;
340 cache
->stored_keys
= cache
->index_mmap
+ sizeof(uint64_t);
344 max_size_str
= getenv("MESA_GLSL_CACHE_MAX_SIZE");
347 max_size
= strtoul(max_size_str
, &end
, 10);
348 if (end
== max_size_str
) {
358 max_size
*= 1024*1024;
364 max_size
*= 1024*1024*1024;
370 /* Default to 1GB for maximum cache size. */
372 max_size
= 1024*1024*1024;
374 cache
->max_size
= max_size
;
391 disk_cache_destroy(struct disk_cache
*cache
)
394 munmap(cache
->index_mmap
, cache
->index_mmap_size
);
399 /* Return a filename within the cache's directory corresponding to 'key'. The
400 * returned filename is ralloced with 'cache' as the parent context.
402 * Returns NULL if out of memory.
405 get_cache_file(struct disk_cache
*cache
, cache_key key
)
410 _mesa_sha1_format(buf
, key
);
411 if (asprintf(&filename
, "%s/%c%c/%s", cache
->path
, buf
[0],
412 buf
[1], buf
+ 2) == -1)
418 /* Create the directory that will be needed for the cache file for \key.
420 * Obviously, the implementation here must closely match
421 * _get_cache_file above.
424 make_cache_file_directory(struct disk_cache
*cache
, cache_key key
)
429 _mesa_sha1_format(buf
, key
);
430 if (asprintf(&dir
, "%s/%c%c", cache
->path
, buf
[0], buf
[1]) == -1)
433 mkdir_if_needed(dir
);
437 /* Given a directory path and predicate function, count all entries in
438 * that directory for which the predicate returns true. Then choose a
439 * random entry from among those counted.
441 * Returns: A malloc'ed string for the path to the chosen file, (or
442 * NULL on any error). The caller should free the string when
446 choose_random_file_matching(const char *dir_path
,
447 bool (*predicate
)(struct dirent
*,
448 const char *dir_path
))
451 struct dirent
*entry
;
452 unsigned int count
, victim
;
455 dir
= opendir(dir_path
);
462 entry
= readdir(dir
);
465 if (!predicate(entry
, dir_path
))
476 victim
= rand() % count
;
482 entry
= readdir(dir
);
485 if (!predicate(entry
, dir_path
))
498 if (asprintf(&filename
, "%s/%s", dir_path
, entry
->d_name
) < 0)
506 /* Is entry a regular file, and not having a name with a trailing
510 is_regular_non_tmp_file(struct dirent
*entry
, const char *path
)
513 if (asprintf(&filename
, "%s/%s", path
, entry
->d_name
) == -1)
517 int res
= stat(filename
, &sb
);
520 if (res
== -1 || !S_ISREG(sb
.st_mode
))
523 size_t len
= strlen (entry
->d_name
);
524 if (len
>= 4 && strcmp(&entry
->d_name
[len
-4], ".tmp") == 0)
530 /* Returns the size of the deleted file, (or 0 on any error). */
532 unlink_random_file_from_directory(const char *path
)
537 filename
= choose_random_file_matching(path
, is_regular_non_tmp_file
);
538 if (filename
== NULL
)
541 if (stat(filename
, &sb
) == -1) {
553 /* Is entry a directory with a two-character name, (and not the
554 * special name of "..")
557 is_two_character_sub_directory(struct dirent
*entry
, const char *path
)
560 if (asprintf(&subdir
, "%s/%s", path
, entry
->d_name
) == -1)
564 int res
= stat(subdir
, &sb
);
567 if (res
== -1 || !S_ISDIR(sb
.st_mode
))
570 if (strlen(entry
->d_name
) != 2)
573 if (strcmp(entry
->d_name
, "..") == 0)
580 evict_random_item(struct disk_cache
*cache
)
582 const char hex
[] = "0123456789abcde";
587 /* With a reasonably-sized, full cache, (and with keys generated
588 * from a cryptographic hash), we can choose two random hex digits
589 * and reasonably expect the directory to exist with a file in it.
594 if (asprintf(&dir_path
, "%s/%c%c", cache
->path
, hex
[a
], hex
[b
]) < 0)
597 size
= unlink_random_file_from_directory(dir_path
);
602 p_atomic_add(cache
->size
, - size
);
606 /* In the case where the random choice of directory didn't find
607 * something, we choose randomly from the existing directories.
609 * Really, the only reason this code exists is to allow the unit
610 * tests to work, (which use an artificially-small cache to be able
611 * to force a single cached item to be evicted).
613 dir_path
= choose_random_file_matching(cache
->path
,
614 is_two_character_sub_directory
);
615 if (dir_path
== NULL
)
618 size
= unlink_random_file_from_directory(dir_path
);
623 p_atomic_add(cache
->size
, - size
);
627 disk_cache_remove(struct disk_cache
*cache
, cache_key key
)
631 char *filename
= get_cache_file(cache
, key
);
632 if (filename
== NULL
) {
636 if (stat(filename
, &sb
) == -1) {
645 p_atomic_add(cache
->size
, - sb
.st_size
);
649 disk_cache_put(struct disk_cache
*cache
,
654 int fd
= -1, fd_final
= -1, err
, ret
;
656 char *filename
= NULL
, *filename_tmp
= NULL
;
657 const char *p
= data
;
659 filename
= get_cache_file(cache
, key
);
660 if (filename
== NULL
)
663 /* Write to a temporary file to allow for an atomic rename to the
664 * final destination filename, (to prevent any readers from seeing
665 * a partially written file).
667 if (asprintf(&filename_tmp
, "%s.tmp", filename
) == -1)
670 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
672 /* Make the two-character subdirectory within the cache as needed. */
677 make_cache_file_directory(cache
, key
);
679 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
684 /* With the temporary file open, we take an exclusive flock on
685 * it. If the flock fails, then another process still has the file
686 * open with the flock held. So just let that file be responsible
687 * for writing the file.
689 err
= flock(fd
, LOCK_EX
| LOCK_NB
);
693 /* Now that we have the lock on the open temporary file, we can
694 * check to see if the destination file already exists. If so,
695 * another process won the race between when we saw that the file
696 * didn't exist and now. In this case, we don't do anything more,
697 * (to ensure the size accounting of the cache doesn't get off).
699 fd_final
= open(filename
, O_RDONLY
| O_CLOEXEC
);
703 /* OK, we're now on the hook to write out a file that we know is
704 * not in the cache, and is also not being written out to the cache
705 * by some other process.
707 * Before we do that, if the cache is too large, evict something
710 if (*cache
->size
+ size
> cache
->max_size
)
711 evict_random_item(cache
);
713 /* Create CRC of the data and store at the start of the file. We will
714 * read this when restoring the cache and use it to check for corruption.
716 uint32_t crc32
= util_hash_crc32(data
, size
);
717 size_t crc_size
= sizeof(crc32
);
718 for (len
= 0; len
< crc_size
; len
+= ret
) {
719 ret
= write(fd
, ((uint8_t *) &crc32
) + len
, crc_size
- len
);
721 unlink(filename_tmp
);
726 /* Now, finally, write out the contents to the temporary file, then
727 * rename them atomically to the destination filename, and also
728 * perform an atomic increment of the total cache size.
730 for (len
= 0; len
< size
; len
+= ret
) {
731 ret
= write(fd
, p
+ len
, size
- len
);
733 unlink(filename_tmp
);
738 rename(filename_tmp
, filename
);
741 p_atomic_add(cache
->size
, size
);
746 /* This close finally releases the flock, (now that the final dile
747 * has been renamed into place and the size has been added).
758 disk_cache_get(struct disk_cache
*cache
, cache_key key
, size_t *size
)
760 int fd
= -1, ret
, len
;
762 char *filename
= NULL
;
763 uint8_t *data
= NULL
;
768 filename
= get_cache_file(cache
, key
);
769 if (filename
== NULL
)
772 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
776 if (fstat(fd
, &sb
) == -1)
779 data
= malloc(sb
.st_size
);
783 /* Load the CRC that was created when the file was written. */
785 size_t crc_size
= sizeof(crc32
);
786 assert(sb
.st_size
> crc_size
);
787 for (len
= 0; len
< crc_size
; len
+= ret
) {
788 ret
= read(fd
, ((uint8_t *) &crc32
) + len
, crc_size
- len
);
793 /* Load the actual cache data. */
794 size_t cache_data_size
= sb
.st_size
- crc_size
;
795 for (len
= 0; len
< cache_data_size
; len
+= ret
) {
796 ret
= read(fd
, data
+ len
, cache_data_size
- len
);
801 /* Check the data for corruption */
802 if (crc32
!= util_hash_crc32(data
, cache_data_size
))
809 *size
= cache_data_size
;
825 disk_cache_put_key(struct disk_cache
*cache
, cache_key key
)
827 uint32_t *key_chunk
= (uint32_t *) key
;
828 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
829 unsigned char *entry
;
831 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
833 memcpy(entry
, key
, CACHE_KEY_SIZE
);
836 /* This function lets us test whether a given key was previously
837 * stored in the cache with disk_cache_put_key(). The implement is
838 * efficient by not using syscalls or hitting the disk. It's not
839 * race-free, but the races are benign. If we race with someone else
840 * calling disk_cache_put_key, then that's just an extra cache miss and an
844 disk_cache_has_key(struct disk_cache
*cache
, cache_key key
)
846 uint32_t *key_chunk
= (uint32_t *) key
;
847 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
848 unsigned char *entry
;
850 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
852 return memcmp(entry
, key
, CACHE_KEY_SIZE
) == 0;
855 #endif /* ENABLE_SHADER_CACHE */