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/u_atomic.h"
42 #include "util/mesa-sha1.h"
43 #include "util/ralloc.h"
44 #include "main/errors.h"
46 #include "disk_cache.h"
48 /* Number of bits to mask off from a cache key to get an index. */
49 #define CACHE_INDEX_KEY_BITS 16
51 /* Mask for computing an index from a key. */
52 #define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
54 /* The number of keys that can be stored in the index. */
55 #define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
58 /* The path to the cache directory. */
61 /* A pointer to the mmapped index file within the cache directory. */
63 size_t index_mmap_size
;
65 /* Pointer to total size of all objects in cache (within index_mmap) */
68 /* Pointer to stored keys, (within index_mmap). */
71 /* Maximum size of all cached objects (in bytes). */
75 /* Create a directory named 'path' if it does not already exist.
77 * Returns: 0 if path already exists as a directory or if created.
78 * -1 in all other cases.
81 mkdir_if_needed(char *path
)
85 /* If the path exists already, then our work is done if it's a
86 * directory, but it's an error if it is not.
88 if (stat(path
, &sb
) == 0) {
89 if (S_ISDIR(sb
.st_mode
)) {
92 fprintf(stderr
, "Cannot use %s for shader cache (not a directory)"
93 "---disabling.\n", path
);
98 int ret
= mkdir(path
, 0755);
99 if (ret
== 0 || (ret
== -1 && errno
== EEXIST
))
102 fprintf(stderr
, "Failed to create %s for shader cache (%s)---disabling.\n",
103 path
, strerror(errno
));
108 /* Concatenate an existing path and a new name to form a new path. If the new
109 * path does not exist as a directory, create it then return the resulting
110 * name of the new path (ralloc'ed off of 'ctx').
112 * Returns NULL on any error, such as:
114 * <path> does not exist or is not a directory
115 * <path>/<name> exists but is not a directory
116 * <path>/<name> cannot be created as a directory
119 concatenate_and_mkdir(void *ctx
, char *path
, const char *name
)
124 if (stat(path
, &sb
) != 0 || ! S_ISDIR(sb
.st_mode
))
127 new_path
= ralloc_asprintf(ctx
, "%s/%s", path
, name
);
129 if (mkdir_if_needed(new_path
) == 0)
136 remove_dir(const char *fpath
, const struct stat
*sb
,
137 int typeflag
, struct FTW
*ftwbuf
)
139 if (S_ISREG(sb
->st_mode
))
141 else if (S_ISDIR(sb
->st_mode
))
148 remove_old_cache_directories(void *mem_ctx
, char *path
, const char *timestamp
)
150 DIR *dir
= opendir(path
);
152 struct dirent
* d_entry
;
153 while((d_entry
= readdir(dir
)) != NULL
)
156 stat(d_entry
->d_name
, &sb
);
157 if (S_ISDIR(sb
.st_mode
) &&
158 strcmp(d_entry
->d_name
, timestamp
) != 0 &&
159 strcmp(d_entry
->d_name
, "..") != 0 &&
160 strcmp(d_entry
->d_name
, ".") != 0) {
162 ralloc_asprintf(mem_ctx
, "%s/%s", path
, d_entry
->d_name
);
163 nftw(full_path
, remove_dir
, 20, FTW_DEPTH
);
169 create_mesa_cache_dir(void *mem_ctx
, char *path
, const char *timestamp
,
170 const char *gpu_name
)
172 char *new_path
= concatenate_and_mkdir(mem_ctx
, path
, "mesa");
173 if (new_path
== NULL
)
176 /* Remove cache directories for old Mesa versions */
177 remove_old_cache_directories(mem_ctx
, new_path
, timestamp
);
179 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, timestamp
);
180 if (new_path
== NULL
)
183 new_path
= concatenate_and_mkdir(mem_ctx
, new_path
, gpu_name
);
184 if (new_path
== NULL
)
191 disk_cache_create(const char *gpu_name
, const char *timestamp
)
194 struct disk_cache
*cache
= NULL
;
195 char *path
, *max_size_str
;
201 /* A ralloc context for transient data during this invocation. */
202 local
= ralloc_context(NULL
);
206 /* At user request, disable shader cache entirely. */
207 if (getenv("MESA_GLSL_CACHE_DISABLE"))
210 /* As a temporary measure, (while the shader cache is under
211 * development, and known to not be fully functional), also require
212 * the MESA_GLSL_CACHE_ENABLE variable to be set.
214 if (!getenv("MESA_GLSL_CACHE_ENABLE"))
217 /* Determine path for cache based on the first defined name as follows:
219 * $MESA_GLSL_CACHE_DIR
220 * $XDG_CACHE_HOME/mesa
221 * <pwd.pw_dir>/.cache/mesa
223 path
= getenv("MESA_GLSL_CACHE_DIR");
224 if (path
&& mkdir_if_needed(path
) == -1) {
229 char *xdg_cache_home
= getenv("XDG_CACHE_HOME");
231 if (xdg_cache_home
) {
232 if (mkdir_if_needed(xdg_cache_home
) == -1)
235 path
= create_mesa_cache_dir(local
, xdg_cache_home
, timestamp
,
245 struct passwd pwd
, *result
;
247 buf_size
= sysconf(_SC_GETPW_R_SIZE_MAX
);
251 /* Loop until buf_size is large enough to query the directory */
253 buf
= ralloc_size(local
, buf_size
);
255 getpwuid_r(getuid(), &pwd
, buf
, buf_size
, &result
);
259 if (errno
== ERANGE
) {
268 path
= concatenate_and_mkdir(local
, pwd
.pw_dir
, ".cache");
272 path
= create_mesa_cache_dir(local
, path
, timestamp
, gpu_name
);
277 cache
= ralloc(NULL
, struct disk_cache
);
281 cache
->path
= ralloc_strdup(cache
, path
);
282 if (cache
->path
== NULL
)
285 path
= ralloc_asprintf(local
, "%s/index", cache
->path
);
289 fd
= open(path
, O_RDWR
| O_CREAT
| O_CLOEXEC
, 0644);
293 if (fstat(fd
, &sb
) == -1)
296 /* Force the index file to be the expected size. */
297 size
= sizeof(*cache
->size
) + CACHE_INDEX_MAX_KEYS
* CACHE_KEY_SIZE
;
298 if (sb
.st_size
!= size
) {
299 if (ftruncate(fd
, size
) == -1)
303 /* We map this shared so that other processes see updates that we
306 * Note: We do use atomic addition to ensure that multiple
307 * processes don't scramble the cache size recorded in the
308 * index. But we don't use any locking to prevent multiple
309 * processes from updating the same entry simultaneously. The idea
310 * is that if either result lands entirely in the index, then
311 * that's equivalent to a well-ordered write followed by an
312 * eviction and a write. On the other hand, if the simultaneous
313 * writes result in a corrupt entry, that's not really any
314 * different than both entries being evicted, (since within the
315 * guarantees of the cryptographic hash, a corrupt entry is
316 * unlikely to ever match a real cache key).
318 cache
->index_mmap
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
320 if (cache
->index_mmap
== MAP_FAILED
)
322 cache
->index_mmap_size
= size
;
326 cache
->size
= (uint64_t *) cache
->index_mmap
;
327 cache
->stored_keys
= cache
->index_mmap
+ sizeof(uint64_t);
331 max_size_str
= getenv("MESA_GLSL_CACHE_MAX_SIZE");
334 max_size
= strtoul(max_size_str
, &end
, 10);
335 if (end
== max_size_str
) {
345 max_size
*= 1024*1024;
351 max_size
*= 1024*1024*1024;
357 /* Default to 1GB for maximum cache size. */
359 max_size
= 1024*1024*1024;
361 cache
->max_size
= max_size
;
378 disk_cache_destroy(struct disk_cache
*cache
)
381 munmap(cache
->index_mmap
, cache
->index_mmap_size
);
386 /* Return a filename within the cache's directory corresponding to 'key'. The
387 * returned filename is ralloced with 'cache' as the parent context.
389 * Returns NULL if out of memory.
392 get_cache_file(struct disk_cache
*cache
, cache_key key
)
397 _mesa_sha1_format(buf
, key
);
398 if (asprintf(&filename
, "%s/%c%c/%s", cache
->path
, buf
[0],
399 buf
[1], buf
+ 2) == -1)
405 /* Create the directory that will be needed for the cache file for \key.
407 * Obviously, the implementation here must closely match
408 * _get_cache_file above.
411 make_cache_file_directory(struct disk_cache
*cache
, cache_key key
)
416 _mesa_sha1_format(buf
, key
);
417 if (asprintf(&dir
, "%s/%c%c", cache
->path
, buf
[0], buf
[1]) == -1)
420 mkdir_if_needed(dir
);
424 /* Given a directory path and predicate function, count all entries in
425 * that directory for which the predicate returns true. Then choose a
426 * random entry from among those counted.
428 * Returns: A malloc'ed string for the path to the chosen file, (or
429 * NULL on any error). The caller should free the string when
433 choose_random_file_matching(const char *dir_path
,
434 bool (*predicate
)(struct dirent
*,
435 const char *dir_path
))
438 struct dirent
*entry
;
439 unsigned int count
, victim
;
442 dir
= opendir(dir_path
);
449 entry
= readdir(dir
);
452 if (!predicate(entry
, dir_path
))
463 victim
= rand() % count
;
469 entry
= readdir(dir
);
472 if (!predicate(entry
, dir_path
))
485 if (asprintf(&filename
, "%s/%s", dir_path
, entry
->d_name
) < 0)
493 /* Is entry a regular file, and not having a name with a trailing
497 is_regular_non_tmp_file(struct dirent
*entry
, const char *path
)
500 if (asprintf(&filename
, "%s/%s", path
, entry
->d_name
) == -1)
504 int res
= stat(filename
, &sb
);
507 if (res
== -1 || !S_ISREG(sb
.st_mode
))
510 size_t len
= strlen (entry
->d_name
);
511 if (len
>= 4 && strcmp(&entry
->d_name
[len
-4], ".tmp") == 0)
517 /* Returns the size of the deleted file, (or 0 on any error). */
519 unlink_random_file_from_directory(const char *path
)
524 filename
= choose_random_file_matching(path
, is_regular_non_tmp_file
);
525 if (filename
== NULL
)
528 if (stat(filename
, &sb
) == -1) {
540 /* Is entry a directory with a two-character name, (and not the
541 * special name of "..")
544 is_two_character_sub_directory(struct dirent
*entry
, const char *path
)
547 if (asprintf(&subdir
, "%s/%s", path
, entry
->d_name
) == -1)
551 int res
= stat(subdir
, &sb
);
554 if (res
== -1 || !S_ISDIR(sb
.st_mode
))
557 if (strlen(entry
->d_name
) != 2)
560 if (strcmp(entry
->d_name
, "..") == 0)
567 evict_random_item(struct disk_cache
*cache
)
569 const char hex
[] = "0123456789abcde";
574 /* With a reasonably-sized, full cache, (and with keys generated
575 * from a cryptographic hash), we can choose two random hex digits
576 * and reasonably expect the directory to exist with a file in it.
581 if (asprintf(&dir_path
, "%s/%c%c", cache
->path
, hex
[a
], hex
[b
]) < 0)
584 size
= unlink_random_file_from_directory(dir_path
);
589 p_atomic_add(cache
->size
, - size
);
593 /* In the case where the random choice of directory didn't find
594 * something, we choose randomly from the existing directories.
596 * Really, the only reason this code exists is to allow the unit
597 * tests to work, (which use an artificially-small cache to be able
598 * to force a single cached item to be evicted).
600 dir_path
= choose_random_file_matching(cache
->path
,
601 is_two_character_sub_directory
);
602 if (dir_path
== NULL
)
605 size
= unlink_random_file_from_directory(dir_path
);
610 p_atomic_add(cache
->size
, - size
);
614 disk_cache_remove(struct disk_cache
*cache
, cache_key key
)
618 char *filename
= get_cache_file(cache
, key
);
619 if (filename
== NULL
) {
623 if (stat(filename
, &sb
) == -1) {
632 p_atomic_add(cache
->size
, - sb
.st_size
);
636 disk_cache_put(struct disk_cache
*cache
,
641 int fd
= -1, fd_final
= -1, err
, ret
;
643 char *filename
= NULL
, *filename_tmp
= NULL
;
644 const char *p
= data
;
646 filename
= get_cache_file(cache
, key
);
647 if (filename
== NULL
)
650 /* Write to a temporary file to allow for an atomic rename to the
651 * final destination filename, (to prevent any readers from seeing
652 * a partially written file).
654 if (asprintf(&filename_tmp
, "%s.tmp", filename
) == -1)
657 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
659 /* Make the two-character subdirectory within the cache as needed. */
664 make_cache_file_directory(cache
, key
);
666 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
671 /* With the temporary file open, we take an exclusive flock on
672 * it. If the flock fails, then another process still has the file
673 * open with the flock held. So just let that file be responsible
674 * for writing the file.
676 err
= flock(fd
, LOCK_EX
| LOCK_NB
);
680 /* Now that we have the lock on the open temporary file, we can
681 * check to see if the destination file already exists. If so,
682 * another process won the race between when we saw that the file
683 * didn't exist and now. In this case, we don't do anything more,
684 * (to ensure the size accounting of the cache doesn't get off).
686 fd_final
= open(filename
, O_RDONLY
| O_CLOEXEC
);
690 /* OK, we're now on the hook to write out a file that we know is
691 * not in the cache, and is also not being written out to the cache
692 * by some other process.
694 * Before we do that, if the cache is too large, evict something
697 if (*cache
->size
+ size
> cache
->max_size
)
698 evict_random_item(cache
);
700 /* Now, finally, write out the contents to the temporary file, then
701 * rename them atomically to the destination filename, and also
702 * perform an atomic increment of the total cache size.
704 for (len
= 0; len
< size
; len
+= ret
) {
705 ret
= write(fd
, p
+ len
, size
- len
);
707 unlink(filename_tmp
);
712 rename(filename_tmp
, filename
);
714 p_atomic_add(cache
->size
, size
);
719 /* This close finally releases the flock, (now that the final dile
720 * has been renamed into place and the size has been added).
731 disk_cache_get(struct disk_cache
*cache
, cache_key key
, size_t *size
)
733 int fd
= -1, ret
, len
;
735 char *filename
= NULL
;
736 uint8_t *data
= NULL
;
741 filename
= get_cache_file(cache
, key
);
742 if (filename
== NULL
)
745 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
749 if (fstat(fd
, &sb
) == -1)
752 data
= malloc(sb
.st_size
);
756 for (len
= 0; len
< sb
.st_size
; len
+= ret
) {
757 ret
= read(fd
, data
+ len
, sb
.st_size
- len
);
782 disk_cache_put_key(struct disk_cache
*cache
, cache_key key
)
784 uint32_t *key_chunk
= (uint32_t *) key
;
785 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
786 unsigned char *entry
;
788 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
790 memcpy(entry
, key
, CACHE_KEY_SIZE
);
793 /* This function lets us test whether a given key was previously
794 * stored in the cache with disk_cache_put_key(). The implement is
795 * efficient by not using syscalls or hitting the disk. It's not
796 * race-free, but the races are benign. If we race with someone else
797 * calling disk_cache_put_key, then that's just an extra cache miss and an
801 disk_cache_has_key(struct disk_cache
*cache
, cache_key key
)
803 uint32_t *key_chunk
= (uint32_t *) key
;
804 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
805 unsigned char *entry
;
807 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
809 return memcmp(entry
, key
, CACHE_KEY_SIZE
) == 0;
812 #endif /* ENABLE_SHADER_CACHE */