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
31 #include <sys/types.h>
40 #include "util/u_atomic.h"
41 #include "util/mesa-sha1.h"
42 #include "util/ralloc.h"
43 #include "main/errors.h"
45 #include "disk_cache.h"
47 /* Number of bits to mask off from a cache key to get an index. */
48 #define CACHE_INDEX_KEY_BITS 16
50 /* Mask for computing an index from a key. */
51 #define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
53 /* The number of keys that can be stored in the index. */
54 #define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
57 /* The path to the cache directory. */
60 /* A pointer to the mmapped index file within the cache directory. */
62 size_t index_mmap_size
;
64 /* Pointer to total size of all objects in cache (within index_mmap) */
67 /* Pointer to stored keys, (within index_mmap). */
70 /* Maximum size of all cached objects (in bytes). */
74 /* Create a directory named 'path' if it does not already exist.
76 * Returns: 0 if path already exists as a directory or if created.
77 * -1 in all other cases.
80 mkdir_if_needed(char *path
)
84 /* If the path exists already, then our work is done if it's a
85 * directory, but it's an error if it is not.
87 if (stat(path
, &sb
) == 0) {
88 if (S_ISDIR(sb
.st_mode
)) {
91 fprintf(stderr
, "Cannot use %s for shader cache (not a directory)"
92 "---disabling.\n", path
);
97 int ret
= mkdir(path
, 0755);
98 if (ret
== 0 || (ret
== -1 && errno
== EEXIST
))
101 fprintf(stderr
, "Failed to create %s for shader cache (%s)---disabling.\n",
102 path
, strerror(errno
));
107 /* Concatenate an existing path and a new name to form a new path. If the new
108 * path does not exist as a directory, create it then return the resulting
109 * name of the new path (ralloc'ed off of 'ctx').
111 * Returns NULL on any error, such as:
113 * <path> does not exist or is not a directory
114 * <path>/<name> exists but is not a directory
115 * <path>/<name> cannot be created as a directory
118 concatenate_and_mkdir(void *ctx
, char *path
, char *name
)
123 if (stat(path
, &sb
) != 0 || ! S_ISDIR(sb
.st_mode
))
126 new_path
= ralloc_asprintf(ctx
, "%s/%s", path
, name
);
128 if (mkdir_if_needed(new_path
) == 0)
135 disk_cache_create(void)
138 struct disk_cache
*cache
= NULL
;
139 char *path
, *max_size_str
;
145 /* A ralloc context for transient data during this invocation. */
146 local
= ralloc_context(NULL
);
150 /* At user request, disable shader cache entirely. */
151 if (getenv("MESA_GLSL_CACHE_DISABLE"))
154 /* Determine path for cache based on the first defined name as follows:
156 * $MESA_GLSL_CACHE_DIR
157 * $XDG_CACHE_HOME/mesa
158 * <pwd.pw_dir>/.cache/mesa
160 path
= getenv("MESA_GLSL_CACHE_DIR");
161 if (path
&& mkdir_if_needed(path
) == -1) {
166 char *xdg_cache_home
= getenv("XDG_CACHE_HOME");
168 if (xdg_cache_home
) {
169 if (mkdir_if_needed(xdg_cache_home
) == -1)
172 path
= concatenate_and_mkdir(local
, xdg_cache_home
, "mesa");
181 struct passwd pwd
, *result
;
183 buf_size
= sysconf(_SC_GETPW_R_SIZE_MAX
);
187 /* Loop until buf_size is large enough to query the directory */
189 buf
= ralloc_size(local
, buf_size
);
191 getpwuid_r(getuid(), &pwd
, buf
, buf_size
, &result
);
195 if (errno
== ERANGE
) {
204 path
= concatenate_and_mkdir(local
, pwd
.pw_dir
, ".cache");
208 path
= concatenate_and_mkdir(local
, path
, "mesa");
213 cache
= ralloc(NULL
, struct disk_cache
);
217 cache
->path
= ralloc_strdup(cache
, path
);
218 if (cache
->path
== NULL
)
221 path
= ralloc_asprintf(local
, "%s/index", cache
->path
);
225 fd
= open(path
, O_RDWR
| O_CREAT
| O_CLOEXEC
, 0644);
229 if (fstat(fd
, &sb
) == -1)
232 /* Force the index file to be the expected size. */
233 size
= sizeof(*cache
->size
) + CACHE_INDEX_MAX_KEYS
* CACHE_KEY_SIZE
;
234 if (sb
.st_size
!= size
) {
235 if (ftruncate(fd
, size
) == -1)
239 /* We map this shared so that other processes see updates that we
242 * Note: We do use atomic addition to ensure that multiple
243 * processes don't scramble the cache size recorded in the
244 * index. But we don't use any locking to prevent multiple
245 * processes from updating the same entry simultaneously. The idea
246 * is that if either result lands entirely in the index, then
247 * that's equivalent to a well-ordered write followed by an
248 * eviction and a write. On the other hand, if the simultaneous
249 * writes result in a corrupt entry, that's not really any
250 * different than both entries being evicted, (since within the
251 * guarantees of the cryptographic hash, a corrupt entry is
252 * unlikely to ever match a real cache key).
254 cache
->index_mmap
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
256 if (cache
->index_mmap
== MAP_FAILED
)
258 cache
->index_mmap_size
= size
;
262 cache
->size
= (uint64_t *) cache
->index_mmap
;
263 cache
->stored_keys
= cache
->index_mmap
+ sizeof(uint64_t);
267 max_size_str
= getenv("MESA_GLSL_CACHE_MAX_SIZE");
270 max_size
= strtoul(max_size_str
, &end
, 10);
271 if (end
== max_size_str
) {
274 while (*end
&& isspace(*end
))
283 max_size
*= 1024*1024;
289 max_size
*= 1024*1024*1024;
295 /* Default to 1GB for maximum cache size. */
297 max_size
= 1024*1024*1024;
299 cache
->max_size
= max_size
;
316 disk_cache_destroy(struct disk_cache
*cache
)
318 munmap(cache
->index_mmap
, cache
->index_mmap_size
);
323 /* Return a filename within the cache's directory corresponding to 'key'. The
324 * returned filename is ralloced with 'cache' as the parent context.
326 * Returns NULL if out of memory.
329 get_cache_file(struct disk_cache
*cache
, cache_key key
)
333 _mesa_sha1_format(buf
, key
);
335 return ralloc_asprintf(cache
, "%s/%c%c/%s",
336 cache
->path
, buf
[0], buf
[1], buf
+ 2);
339 /* Create the directory that will be needed for the cache file for \key.
341 * Obviously, the implementation here must closely match
342 * _get_cache_file above.
345 make_cache_file_directory(struct disk_cache
*cache
, cache_key key
)
350 _mesa_sha1_format(buf
, key
);
352 dir
= ralloc_asprintf(cache
, "%s/%c%c", cache
->path
, buf
[0], buf
[1]);
354 mkdir_if_needed(dir
);
359 /* Given a directory path and predicate function, count all entries in
360 * that directory for which the predicate returns true. Then choose a
361 * random entry from among those counted.
363 * Returns: A malloc'ed string for the path to the chosen file, (or
364 * NULL on any error). The caller should free the string when
368 choose_random_file_matching(const char *dir_path
,
369 bool (*predicate
)(struct dirent
*))
372 struct dirent
*entry
;
373 unsigned int count
, victim
;
376 dir
= opendir(dir_path
);
383 entry
= readdir(dir
);
386 if (! predicate(entry
))
397 victim
= rand() % count
;
403 entry
= readdir(dir
);
406 if (! predicate(entry
))
419 if (asprintf(&filename
, "%s/%s", dir_path
, entry
->d_name
) < 0)
427 /* Is entry a regular file, and not having a name with a trailing
431 is_regular_non_tmp_file(struct dirent
*entry
)
435 if (entry
->d_type
!= DT_REG
)
438 len
= strlen (entry
->d_name
);
439 if (len
>= 4 && strcmp(&entry
->d_name
[len
-4], ".tmp") == 0)
445 /* Returns the size of the deleted file, (or 0 on any error). */
447 unlink_random_file_from_directory(const char *path
)
452 filename
= choose_random_file_matching(path
, is_regular_non_tmp_file
);
453 if (filename
== NULL
)
456 if (stat(filename
, &sb
) == -1) {
468 /* Is entry a directory with a two-character name, (and not the
469 * special name of "..")
472 is_two_character_sub_directory(struct dirent
*entry
)
474 if (entry
->d_type
!= DT_DIR
)
477 if (strlen(entry
->d_name
) != 2)
480 if (strcmp(entry
->d_name
, "..") == 0)
487 evict_random_item(struct disk_cache
*cache
)
489 const char hex
[] = "0123456789abcde";
494 /* With a reasonably-sized, full cache, (and with keys generated
495 * from a cryptographic hash), we can choose two random hex digits
496 * and reasonably expect the directory to exist with a file in it.
501 if (asprintf(&dir_path
, "%s/%c%c", cache
->path
, hex
[a
], hex
[b
]) < 0)
504 size
= unlink_random_file_from_directory(dir_path
);
509 p_atomic_add(cache
->size
, - size
);
513 /* In the case where the random choice of directory didn't find
514 * something, we choose randomly from the existing directories.
516 * Really, the only reason this code exists is to allow the unit
517 * tests to work, (which use an artificially-small cache to be able
518 * to force a single cached item to be evicted).
520 dir_path
= choose_random_file_matching(cache
->path
,
521 is_two_character_sub_directory
);
522 if (dir_path
== NULL
)
525 size
= unlink_random_file_from_directory(dir_path
);
530 p_atomic_add(cache
->size
, - size
);
534 disk_cache_put(struct disk_cache
*cache
,
539 int fd
= -1, fd_final
= -1, err
, ret
;
541 char *filename
= NULL
, *filename_tmp
= NULL
;
542 const char *p
= data
;
544 filename
= get_cache_file(cache
, key
);
545 if (filename
== NULL
)
548 /* Write to a temporary file to allow for an atomic rename to the
549 * final destination filename, (to prevent any readers from seeing
550 * a partially written file).
552 filename_tmp
= ralloc_asprintf(cache
, "%s.tmp", filename
);
553 if (filename_tmp
== NULL
)
556 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
558 /* Make the two-character subdirectory within the cache as needed. */
563 make_cache_file_directory(cache
, key
);
565 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
570 /* With the temporary file open, we take an exclusive flock on
571 * it. If the flock fails, then another process still has the file
572 * open with the flock held. So just let that file be responsible
573 * for writing the file.
575 err
= flock(fd
, LOCK_EX
| LOCK_NB
);
579 /* Now that we have the lock on the open temporary file, we can
580 * check to see if the destination file already exists. If so,
581 * another process won the race between when we saw that the file
582 * didn't exist and now. In this case, we don't do anything more,
583 * (to ensure the size accounting of the cache doesn't get off).
585 fd_final
= open(filename
, O_RDONLY
| O_CLOEXEC
);
589 /* OK, we're now on the hook to write out a file that we know is
590 * not in the cache, and is also not being written out to the cache
591 * by some other process.
593 * Before we do that, if the cache is too large, evict something
596 if (*cache
->size
+ size
> cache
->max_size
)
597 evict_random_item(cache
);
599 /* Now, finally, write out the contents to the temporary file, then
600 * rename them atomically to the destination filename, and also
601 * perform an atomic increment of the total cache size.
603 for (len
= 0; len
< size
; len
+= ret
) {
604 ret
= write(fd
, p
+ len
, size
- len
);
606 unlink(filename_tmp
);
611 rename(filename_tmp
, filename
);
613 p_atomic_add(cache
->size
, size
);
618 /* This close finally releases the flock, (now that the final dile
619 * has been renamed into place and the size has been added).
624 ralloc_free(filename_tmp
);
626 ralloc_free(filename
);
630 disk_cache_get(struct disk_cache
*cache
, cache_key key
, size_t *size
)
632 int fd
= -1, ret
, len
;
634 char *filename
= NULL
;
635 uint8_t *data
= NULL
;
640 filename
= get_cache_file(cache
, key
);
641 if (filename
== NULL
)
644 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
648 if (fstat(fd
, &sb
) == -1)
651 data
= malloc(sb
.st_size
);
655 for (len
= 0; len
< sb
.st_size
; len
+= ret
) {
656 ret
= read(fd
, data
+ len
, sb
.st_size
- len
);
661 ralloc_free(filename
);
673 ralloc_free(filename
);
681 disk_cache_put_key(struct disk_cache
*cache
, cache_key key
)
683 uint32_t *key_chunk
= (uint32_t *) key
;
684 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
685 unsigned char *entry
;
687 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
689 memcpy(entry
, key
, CACHE_KEY_SIZE
);
692 /* This function lets us test whether a given key was previously
693 * stored in the cache with disk_cache_put_key(). The implement is
694 * efficient by not using syscalls or hitting the disk. It's not
695 * race-free, but the races are benign. If we race with someone else
696 * calling disk_cache_put_key, then that's just an extra cache miss and an
700 disk_cache_has_key(struct disk_cache
*cache
, cache_key key
)
702 uint32_t *key_chunk
= (uint32_t *) key
;
703 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
704 unsigned char *entry
;
706 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
708 return memcmp(entry
, key
, CACHE_KEY_SIZE
) == 0;