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
29 #include <sys/types.h>
38 #include "util/u_atomic.h"
39 #include "util/mesa-sha1.h"
40 #include "util/ralloc.h"
41 #include "main/errors.h"
43 #include "disk_cache.h"
45 /* Number of bits to mask off from a cache key to get an index. */
46 #define CACHE_INDEX_KEY_BITS 16
48 /* Mask for computing an index from a key. */
49 #define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
51 /* The number of keys that can be stored in the index. */
52 #define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
55 /* The path to the cache directory. */
58 /* A pointer to the mmapped index file within the cache directory. */
60 size_t index_mmap_size
;
62 /* Pointer to total size of all objects in cache (within index_mmap) */
65 /* Pointer to stored keys, (within index_mmap). */
68 /* Maximum size of all cached objects (in bytes). */
72 /* Create a directory named 'path' if it does not already exist.
74 * Returns: 0 if path already exists as a directory or if created.
75 * -1 in all other cases.
78 mkdir_if_needed(char *path
)
82 /* If the path exists already, then our work is done if it's a
83 * directory, but it's an error if it is not.
85 if (stat(path
, &sb
) == 0) {
86 if (S_ISDIR(sb
.st_mode
)) {
89 fprintf(stderr
, "Cannot use %s for shader cache (not a directory)"
90 "---disabling.\n", path
);
95 int ret
= mkdir(path
, 0755);
96 if (ret
== 0 || (ret
== -1 && errno
== EEXIST
))
99 fprintf(stderr
, "Failed to create %s for shader cache (%s)---disabling.\n",
100 path
, strerror(errno
));
105 /* Concatenate an existing path and a new name to form a new path. If the new
106 * path does not exist as a directory, create it then return the resulting
107 * name of the new path (ralloc'ed off of 'ctx').
109 * Returns NULL on any error, such as:
111 * <path> does not exist or is not a directory
112 * <path>/<name> exists but is not a directory
113 * <path>/<name> cannot be created as a directory
116 concatenate_and_mkdir(void *ctx
, char *path
, char *name
)
121 if (stat(path
, &sb
) != 0 || ! S_ISDIR(sb
.st_mode
))
124 new_path
= ralloc_asprintf(ctx
, "%s/%s", path
, name
);
126 if (mkdir_if_needed(new_path
) == 0)
133 disk_cache_create(void)
136 struct disk_cache
*cache
= NULL
;
137 char *path
, *max_size_str
;
143 /* A ralloc context for transient data during this invocation. */
144 local
= ralloc_context(NULL
);
148 /* At user request, disable shader cache entirely. */
149 if (getenv("MESA_GLSL_CACHE_DISABLE"))
152 /* Determine path for cache based on the first defined name as follows:
154 * $MESA_GLSL_CACHE_DIR
155 * $XDG_CACHE_HOME/mesa
156 * <pwd.pw_dir>/.cache/mesa
158 path
= getenv("MESA_GLSL_CACHE_DIR");
159 if (path
&& mkdir_if_needed(path
) == -1) {
164 char *xdg_cache_home
= getenv("XDG_CACHE_HOME");
166 if (xdg_cache_home
) {
167 if (mkdir_if_needed(xdg_cache_home
) == -1)
170 path
= concatenate_and_mkdir(local
, xdg_cache_home
, "mesa");
179 struct passwd pwd
, *result
;
181 buf_size
= sysconf(_SC_GETPW_R_SIZE_MAX
);
185 /* Loop until buf_size is large enough to query the directory */
187 buf
= ralloc_size(local
, buf_size
);
189 getpwuid_r(getuid(), &pwd
, buf
, buf_size
, &result
);
193 if (errno
== ERANGE
) {
202 path
= concatenate_and_mkdir(local
, pwd
.pw_dir
, ".cache");
206 path
= concatenate_and_mkdir(local
, path
, "mesa");
211 cache
= ralloc(NULL
, struct disk_cache
);
215 cache
->path
= ralloc_strdup(cache
, path
);
216 if (cache
->path
== NULL
)
219 path
= ralloc_asprintf(local
, "%s/index", cache
->path
);
223 fd
= open(path
, O_RDWR
| O_CREAT
| O_CLOEXEC
, 0644);
227 if (fstat(fd
, &sb
) == -1)
230 /* Force the index file to be the expected size. */
231 size
= sizeof(*cache
->size
) + CACHE_INDEX_MAX_KEYS
* CACHE_KEY_SIZE
;
232 if (sb
.st_size
!= size
) {
233 if (ftruncate(fd
, size
) == -1)
237 /* We map this shared so that other processes see updates that we
240 * Note: We do use atomic addition to ensure that multiple
241 * processes don't scramble the cache size recorded in the
242 * index. But we don't use any locking to prevent multiple
243 * processes from updating the same entry simultaneously. The idea
244 * is that if either result lands entirely in the index, then
245 * that's equivalent to a well-ordered write followed by an
246 * eviction and a write. On the other hand, if the simultaneous
247 * writes result in a corrupt entry, that's not really any
248 * different than both entries being evicted, (since within the
249 * guarantees of the cryptographic hash, a corrupt entry is
250 * unlikely to ever match a real cache key).
252 cache
->index_mmap
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
254 if (cache
->index_mmap
== MAP_FAILED
)
256 cache
->index_mmap_size
= size
;
260 cache
->size
= (uint64_t *) cache
->index_mmap
;
261 cache
->stored_keys
= cache
->index_mmap
+ sizeof(uint64_t);
265 max_size_str
= getenv("MESA_GLSL_CACHE_MAX_SIZE");
268 max_size
= strtoul(max_size_str
, &end
, 10);
269 if (end
== max_size_str
) {
272 while (*end
&& isspace(*end
))
281 max_size
*= 1024*1024;
287 max_size
*= 1024*1024*1024;
293 /* Default to 1GB for maximum cache size. */
295 max_size
= 1024*1024*1024;
297 cache
->max_size
= max_size
;
314 disk_cache_destroy(struct disk_cache
*cache
)
316 munmap(cache
->index_mmap
, cache
->index_mmap_size
);
321 /* Return a filename within the cache's directory corresponding to 'key'. The
322 * returned filename is ralloced with 'cache' as the parent context.
324 * Returns NULL if out of memory.
327 get_cache_file(struct disk_cache
*cache
, cache_key key
)
331 _mesa_sha1_format(buf
, key
);
333 return ralloc_asprintf(cache
, "%s/%c%c/%s",
334 cache
->path
, buf
[0], buf
[1], buf
+ 2);
337 /* Create the directory that will be needed for the cache file for \key.
339 * Obviously, the implementation here must closely match
340 * _get_cache_file above.
343 make_cache_file_directory(struct disk_cache
*cache
, cache_key key
)
348 _mesa_sha1_format(buf
, key
);
350 dir
= ralloc_asprintf(cache
, "%s/%c%c", cache
->path
, buf
[0], buf
[1]);
352 mkdir_if_needed(dir
);
357 /* Given a directory path and predicate function, count all entries in
358 * that directory for which the predicate returns true. Then choose a
359 * random entry from among those counted.
361 * Returns: A malloc'ed string for the path to the chosen file, (or
362 * NULL on any error). The caller should free the string when
366 choose_random_file_matching(const char *dir_path
,
367 bool (*predicate
)(struct dirent
*))
370 struct dirent
*entry
;
371 unsigned int count
, victim
;
374 dir
= opendir(dir_path
);
381 entry
= readdir(dir
);
384 if (! predicate(entry
))
395 victim
= rand() % count
;
401 entry
= readdir(dir
);
404 if (! predicate(entry
))
417 if (asprintf(&filename
, "%s/%s", dir_path
, entry
->d_name
) < 0)
425 /* Is entry a regular file, and not having a name with a trailing
429 is_regular_non_tmp_file(struct dirent
*entry
)
433 if (entry
->d_type
!= DT_REG
)
436 len
= strlen (entry
->d_name
);
437 if (len
>= 4 && strcmp(&entry
->d_name
[len
-4], ".tmp") == 0)
443 /* Returns the size of the deleted file, (or 0 on any error). */
445 unlink_random_file_from_directory(const char *path
)
450 filename
= choose_random_file_matching(path
, is_regular_non_tmp_file
);
451 if (filename
== NULL
)
454 if (stat(filename
, &sb
) == -1) {
466 /* Is entry a directory with a two-character name, (and not the
467 * special name of "..")
470 is_two_character_sub_directory(struct dirent
*entry
)
472 if (entry
->d_type
!= DT_DIR
)
475 if (strlen(entry
->d_name
) != 2)
478 if (strcmp(entry
->d_name
, "..") == 0)
485 evict_random_item(struct disk_cache
*cache
)
487 const char hex
[] = "0123456789abcde";
492 /* With a reasonably-sized, full cache, (and with keys generated
493 * from a cryptographic hash), we can choose two random hex digits
494 * and reasonably expect the directory to exist with a file in it.
499 if (asprintf(&dir_path
, "%s/%c%c", cache
->path
, hex
[a
], hex
[b
]) < 0)
502 size
= unlink_random_file_from_directory(dir_path
);
507 p_atomic_add(cache
->size
, - size
);
511 /* In the case where the random choice of directory didn't find
512 * something, we choose randomly from the existing directories.
514 * Really, the only reason this code exists is to allow the unit
515 * tests to work, (which use an artificially-small cache to be able
516 * to force a single cached item to be evicted).
518 dir_path
= choose_random_file_matching(cache
->path
,
519 is_two_character_sub_directory
);
520 if (dir_path
== NULL
)
523 size
= unlink_random_file_from_directory(dir_path
);
528 p_atomic_add(cache
->size
, - size
);
532 disk_cache_put(struct disk_cache
*cache
,
537 int fd
= -1, fd_final
= -1, err
, ret
;
539 char *filename
= NULL
, *filename_tmp
= NULL
;
540 const char *p
= data
;
542 filename
= get_cache_file(cache
, key
);
543 if (filename
== NULL
)
546 /* Write to a temporary file to allow for an atomic rename to the
547 * final destination filename, (to prevent any readers from seeing
548 * a partially written file).
550 filename_tmp
= ralloc_asprintf(cache
, "%s.tmp", filename
);
551 if (filename_tmp
== NULL
)
554 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
556 /* Make the two-character subdirectory within the cache as needed. */
561 make_cache_file_directory(cache
, key
);
563 fd
= open(filename_tmp
, O_WRONLY
| O_CLOEXEC
| O_CREAT
, 0644);
568 /* With the temporary file open, we take an exclusive flock on
569 * it. If the flock fails, then another process still has the file
570 * open with the flock held. So just let that file be responsible
571 * for writing the file.
573 err
= flock(fd
, LOCK_EX
| LOCK_NB
);
577 /* Now that we have the lock on the open temporary file, we can
578 * check to see if the destination file already exists. If so,
579 * another process won the race between when we saw that the file
580 * didn't exist and now. In this case, we don't do anything more,
581 * (to ensure the size accounting of the cache doesn't get off).
583 fd_final
= open(filename
, O_RDONLY
| O_CLOEXEC
);
587 /* OK, we're now on the hook to write out a file that we know is
588 * not in the cache, and is also not being written out to the cache
589 * by some other process.
591 * Before we do that, if the cache is too large, evict something
594 if (*cache
->size
+ size
> cache
->max_size
)
595 evict_random_item(cache
);
597 /* Now, finally, write out the contents to the temporary file, then
598 * rename them atomically to the destination filename, and also
599 * perform an atomic increment of the total cache size.
601 for (len
= 0; len
< size
; len
+= ret
) {
602 ret
= write(fd
, p
+ len
, size
- len
);
604 unlink(filename_tmp
);
609 rename(filename_tmp
, filename
);
611 p_atomic_add(cache
->size
, size
);
616 /* This close finally releases the flock, (now that the final dile
617 * has been renamed into place and the size has been added).
622 ralloc_free(filename_tmp
);
624 ralloc_free(filename
);
628 disk_cache_get(struct disk_cache
*cache
, cache_key key
, size_t *size
)
630 int fd
= -1, ret
, len
;
632 char *filename
= NULL
;
633 uint8_t *data
= NULL
;
638 filename
= get_cache_file(cache
, key
);
639 if (filename
== NULL
)
642 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
646 if (fstat(fd
, &sb
) == -1)
649 data
= malloc(sb
.st_size
);
653 for (len
= 0; len
< sb
.st_size
; len
+= ret
) {
654 ret
= read(fd
, data
+ len
, sb
.st_size
- len
);
659 ralloc_free(filename
);
671 ralloc_free(filename
);
679 disk_cache_put_key(struct disk_cache
*cache
, cache_key key
)
681 uint32_t *key_chunk
= (uint32_t *) key
;
682 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
683 unsigned char *entry
;
685 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
687 memcpy(entry
, key
, CACHE_KEY_SIZE
);
690 /* This function lets us test whether a given key was previously
691 * stored in the cache with disk_cache_put_key(). The implement is
692 * efficient by not using syscalls or hitting the disk. It's not
693 * race-free, but the races are benign. If we race with someone else
694 * calling disk_cache_put_key, then that's just an extra cache miss and an
698 disk_cache_has_key(struct disk_cache
*cache
, cache_key key
)
700 uint32_t *key_chunk
= (uint32_t *) key
;
701 int i
= *key_chunk
& CACHE_INDEX_KEY_MASK
;
702 unsigned char *entry
;
704 entry
= &cache
->stored_keys
[i
+ CACHE_KEY_SIZE
];
706 return memcmp(entry
, key
, CACHE_KEY_SIZE
) == 0;