util/disk_cache: add support for removing old versions of the cache
[mesa.git] / src / util / disk_cache.c
1 /*
2 * Copyright © 2014 Intel Corporation
3 *
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:
10 *
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
13 * Software.
14 *
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
21 * IN THE SOFTWARE.
22 */
23
24 #ifdef ENABLE_SHADER_CACHE
25
26 #include <ctype.h>
27 #include <ftw.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <sys/file.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/mman.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <errno.h>
39 #include <dirent.h>
40
41 #include "util/u_atomic.h"
42 #include "util/mesa-sha1.h"
43 #include "util/ralloc.h"
44 #include "main/errors.h"
45
46 #include "disk_cache.h"
47
48 /* Number of bits to mask off from a cache key to get an index. */
49 #define CACHE_INDEX_KEY_BITS 16
50
51 /* Mask for computing an index from a key. */
52 #define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
53
54 /* The number of keys that can be stored in the index. */
55 #define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
56
57 struct disk_cache {
58 /* The path to the cache directory. */
59 char *path;
60
61 /* A pointer to the mmapped index file within the cache directory. */
62 uint8_t *index_mmap;
63 size_t index_mmap_size;
64
65 /* Pointer to total size of all objects in cache (within index_mmap) */
66 uint64_t *size;
67
68 /* Pointer to stored keys, (within index_mmap). */
69 uint8_t *stored_keys;
70
71 /* Maximum size of all cached objects (in bytes). */
72 uint64_t max_size;
73 };
74
75 /* Create a directory named 'path' if it does not already exist.
76 *
77 * Returns: 0 if path already exists as a directory or if created.
78 * -1 in all other cases.
79 */
80 static int
81 mkdir_if_needed(char *path)
82 {
83 struct stat sb;
84
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.
87 */
88 if (stat(path, &sb) == 0) {
89 if (S_ISDIR(sb.st_mode)) {
90 return 0;
91 } else {
92 fprintf(stderr, "Cannot use %s for shader cache (not a directory)"
93 "---disabling.\n", path);
94 return -1;
95 }
96 }
97
98 int ret = mkdir(path, 0755);
99 if (ret == 0 || (ret == -1 && errno == EEXIST))
100 return 0;
101
102 fprintf(stderr, "Failed to create %s for shader cache (%s)---disabling.\n",
103 path, strerror(errno));
104
105 return -1;
106 }
107
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').
111 *
112 * Returns NULL on any error, such as:
113 *
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
117 */
118 static char *
119 concatenate_and_mkdir(void *ctx, char *path, const char *name)
120 {
121 char *new_path;
122 struct stat sb;
123
124 if (stat(path, &sb) != 0 || ! S_ISDIR(sb.st_mode))
125 return NULL;
126
127 new_path = ralloc_asprintf(ctx, "%s/%s", path, name);
128
129 if (mkdir_if_needed(new_path) == 0)
130 return new_path;
131 else
132 return NULL;
133 }
134
135 static int
136 remove_dir(const char *fpath, const struct stat *sb,
137 int typeflag, struct FTW *ftwbuf)
138 {
139 if (S_ISREG(sb->st_mode))
140 unlink(fpath);
141 else if (S_ISDIR(sb->st_mode))
142 rmdir(fpath);
143
144 return 0;
145 }
146
147 static void
148 remove_old_cache_directories(void *mem_ctx, char *path, const char *timestamp)
149 {
150 DIR *dir = opendir(path);
151
152 struct dirent* d_entry;
153 while((d_entry = readdir(dir)) != NULL)
154 {
155 struct stat sb;
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) {
161 char *full_path =
162 ralloc_asprintf(mem_ctx, "%s/%s", path, d_entry->d_name);
163 nftw(full_path, remove_dir, 20, FTW_DEPTH);
164 }
165 }
166 }
167
168 static char *
169 create_mesa_cache_dir(void *mem_ctx, char *path, const char *timestamp,
170 const char *gpu_name)
171 {
172 char *new_path = concatenate_and_mkdir(mem_ctx, path, "mesa");
173 if (new_path == NULL)
174 return NULL;
175
176 /* Remove cache directories for old Mesa versions */
177 remove_old_cache_directories(mem_ctx, new_path, timestamp);
178
179 new_path = concatenate_and_mkdir(mem_ctx, new_path, timestamp);
180 if (new_path == NULL)
181 return NULL;
182
183 new_path = concatenate_and_mkdir(mem_ctx, new_path, gpu_name);
184 if (new_path == NULL)
185 return NULL;
186
187 return new_path;
188 }
189
190 struct disk_cache *
191 disk_cache_create(const char *gpu_name, const char *timestamp)
192 {
193 void *local;
194 struct disk_cache *cache = NULL;
195 char *path, *max_size_str;
196 uint64_t max_size;
197 int fd = -1;
198 struct stat sb;
199 size_t size;
200
201 /* A ralloc context for transient data during this invocation. */
202 local = ralloc_context(NULL);
203 if (local == NULL)
204 goto fail;
205
206 /* At user request, disable shader cache entirely. */
207 if (getenv("MESA_GLSL_CACHE_DISABLE"))
208 goto fail;
209
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.
213 */
214 if (!getenv("MESA_GLSL_CACHE_ENABLE"))
215 goto fail;
216
217 /* Determine path for cache based on the first defined name as follows:
218 *
219 * $MESA_GLSL_CACHE_DIR
220 * $XDG_CACHE_HOME/mesa
221 * <pwd.pw_dir>/.cache/mesa
222 */
223 path = getenv("MESA_GLSL_CACHE_DIR");
224 if (path && mkdir_if_needed(path) == -1) {
225 goto fail;
226 }
227
228 if (path == NULL) {
229 char *xdg_cache_home = getenv("XDG_CACHE_HOME");
230
231 if (xdg_cache_home) {
232 if (mkdir_if_needed(xdg_cache_home) == -1)
233 goto fail;
234
235 path = create_mesa_cache_dir(local, xdg_cache_home, timestamp,
236 gpu_name);
237 if (path == NULL)
238 goto fail;
239 }
240 }
241
242 if (path == NULL) {
243 char *buf;
244 size_t buf_size;
245 struct passwd pwd, *result;
246
247 buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
248 if (buf_size == -1)
249 buf_size = 512;
250
251 /* Loop until buf_size is large enough to query the directory */
252 while (1) {
253 buf = ralloc_size(local, buf_size);
254
255 getpwuid_r(getuid(), &pwd, buf, buf_size, &result);
256 if (result)
257 break;
258
259 if (errno == ERANGE) {
260 ralloc_free(buf);
261 buf = NULL;
262 buf_size *= 2;
263 } else {
264 goto fail;
265 }
266 }
267
268 path = concatenate_and_mkdir(local, pwd.pw_dir, ".cache");
269 if (path == NULL)
270 goto fail;
271
272 path = create_mesa_cache_dir(local, path, timestamp, gpu_name);
273 if (path == NULL)
274 goto fail;
275 }
276
277 cache = ralloc(NULL, struct disk_cache);
278 if (cache == NULL)
279 goto fail;
280
281 cache->path = ralloc_strdup(cache, path);
282 if (cache->path == NULL)
283 goto fail;
284
285 path = ralloc_asprintf(local, "%s/index", cache->path);
286 if (path == NULL)
287 goto fail;
288
289 fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
290 if (fd == -1)
291 goto fail;
292
293 if (fstat(fd, &sb) == -1)
294 goto fail;
295
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)
300 goto fail;
301 }
302
303 /* We map this shared so that other processes see updates that we
304 * make.
305 *
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).
317 */
318 cache->index_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE,
319 MAP_SHARED, fd, 0);
320 if (cache->index_mmap == MAP_FAILED)
321 goto fail;
322 cache->index_mmap_size = size;
323
324 close(fd);
325
326 cache->size = (uint64_t *) cache->index_mmap;
327 cache->stored_keys = cache->index_mmap + sizeof(uint64_t);
328
329 max_size = 0;
330
331 max_size_str = getenv("MESA_GLSL_CACHE_MAX_SIZE");
332 if (max_size_str) {
333 char *end;
334 max_size = strtoul(max_size_str, &end, 10);
335 if (end == max_size_str) {
336 max_size = 0;
337 } else {
338 switch (*end) {
339 case 'K':
340 case 'k':
341 max_size *= 1024;
342 break;
343 case 'M':
344 case 'm':
345 max_size *= 1024*1024;
346 break;
347 case '\0':
348 case 'G':
349 case 'g':
350 default:
351 max_size *= 1024*1024*1024;
352 break;
353 }
354 }
355 }
356
357 /* Default to 1GB for maximum cache size. */
358 if (max_size == 0)
359 max_size = 1024*1024*1024;
360
361 cache->max_size = max_size;
362
363 ralloc_free(local);
364
365 return cache;
366
367 fail:
368 if (fd != -1)
369 close(fd);
370 if (cache)
371 ralloc_free(cache);
372 ralloc_free(local);
373
374 return NULL;
375 }
376
377 void
378 disk_cache_destroy(struct disk_cache *cache)
379 {
380 munmap(cache->index_mmap, cache->index_mmap_size);
381
382 ralloc_free(cache);
383 }
384
385 /* Return a filename within the cache's directory corresponding to 'key'. The
386 * returned filename is ralloced with 'cache' as the parent context.
387 *
388 * Returns NULL if out of memory.
389 */
390 static char *
391 get_cache_file(struct disk_cache *cache, cache_key key)
392 {
393 char buf[41];
394 char *filename;
395
396 _mesa_sha1_format(buf, key);
397 if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
398 buf[1], buf + 2) == -1)
399 return NULL;
400
401 return filename;
402 }
403
404 /* Create the directory that will be needed for the cache file for \key.
405 *
406 * Obviously, the implementation here must closely match
407 * _get_cache_file above.
408 */
409 static void
410 make_cache_file_directory(struct disk_cache *cache, cache_key key)
411 {
412 char *dir;
413 char buf[41];
414
415 _mesa_sha1_format(buf, key);
416 if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
417 return;
418
419 mkdir_if_needed(dir);
420 free(dir);
421 }
422
423 /* Given a directory path and predicate function, count all entries in
424 * that directory for which the predicate returns true. Then choose a
425 * random entry from among those counted.
426 *
427 * Returns: A malloc'ed string for the path to the chosen file, (or
428 * NULL on any error). The caller should free the string when
429 * finished.
430 */
431 static char *
432 choose_random_file_matching(const char *dir_path,
433 bool (*predicate)(struct dirent *,
434 const char *dir_path))
435 {
436 DIR *dir;
437 struct dirent *entry;
438 unsigned int count, victim;
439 char *filename;
440
441 dir = opendir(dir_path);
442 if (dir == NULL)
443 return NULL;
444
445 count = 0;
446
447 while (1) {
448 entry = readdir(dir);
449 if (entry == NULL)
450 break;
451 if (!predicate(entry, dir_path))
452 continue;
453
454 count++;
455 }
456
457 if (count == 0) {
458 closedir(dir);
459 return NULL;
460 }
461
462 victim = rand() % count;
463
464 rewinddir(dir);
465 count = 0;
466
467 while (1) {
468 entry = readdir(dir);
469 if (entry == NULL)
470 break;
471 if (!predicate(entry, dir_path))
472 continue;
473 if (count == victim)
474 break;
475
476 count++;
477 }
478
479 if (entry == NULL) {
480 closedir(dir);
481 return NULL;
482 }
483
484 if (asprintf(&filename, "%s/%s", dir_path, entry->d_name) < 0)
485 filename = NULL;
486
487 closedir(dir);
488
489 return filename;
490 }
491
492 /* Is entry a regular file, and not having a name with a trailing
493 * ".tmp"
494 */
495 static bool
496 is_regular_non_tmp_file(struct dirent *entry, const char *path)
497 {
498 char *filename;
499 if (asprintf(&filename, "%s/%s", path, entry->d_name) == -1)
500 return false;
501
502 struct stat sb;
503 int res = stat(filename, &sb);
504 free(filename);
505
506 if (res == -1 || !S_ISREG(sb.st_mode))
507 return false;
508
509 size_t len = strlen (entry->d_name);
510 if (len >= 4 && strcmp(&entry->d_name[len-4], ".tmp") == 0)
511 return false;
512
513 return true;
514 }
515
516 /* Returns the size of the deleted file, (or 0 on any error). */
517 static size_t
518 unlink_random_file_from_directory(const char *path)
519 {
520 struct stat sb;
521 char *filename;
522
523 filename = choose_random_file_matching(path, is_regular_non_tmp_file);
524 if (filename == NULL)
525 return 0;
526
527 if (stat(filename, &sb) == -1) {
528 free (filename);
529 return 0;
530 }
531
532 unlink(filename);
533
534 free (filename);
535
536 return sb.st_size;
537 }
538
539 /* Is entry a directory with a two-character name, (and not the
540 * special name of "..")
541 */
542 static bool
543 is_two_character_sub_directory(struct dirent *entry, const char *path)
544 {
545 char *subdir;
546 if (asprintf(&subdir, "%s/%s", path, entry->d_name) == -1)
547 return false;
548
549 struct stat sb;
550 int res = stat(subdir, &sb);
551 free(subdir);
552
553 if (res == -1 || !S_ISDIR(sb.st_mode))
554 return false;
555
556 if (strlen(entry->d_name) != 2)
557 return false;
558
559 if (strcmp(entry->d_name, "..") == 0)
560 return false;
561
562 return true;
563 }
564
565 static void
566 evict_random_item(struct disk_cache *cache)
567 {
568 const char hex[] = "0123456789abcde";
569 char *dir_path;
570 int a, b;
571 size_t size;
572
573 /* With a reasonably-sized, full cache, (and with keys generated
574 * from a cryptographic hash), we can choose two random hex digits
575 * and reasonably expect the directory to exist with a file in it.
576 */
577 a = rand() % 16;
578 b = rand() % 16;
579
580 if (asprintf(&dir_path, "%s/%c%c", cache->path, hex[a], hex[b]) < 0)
581 return;
582
583 size = unlink_random_file_from_directory(dir_path);
584
585 free(dir_path);
586
587 if (size) {
588 p_atomic_add(cache->size, - size);
589 return;
590 }
591
592 /* In the case where the random choice of directory didn't find
593 * something, we choose randomly from the existing directories.
594 *
595 * Really, the only reason this code exists is to allow the unit
596 * tests to work, (which use an artificially-small cache to be able
597 * to force a single cached item to be evicted).
598 */
599 dir_path = choose_random_file_matching(cache->path,
600 is_two_character_sub_directory);
601 if (dir_path == NULL)
602 return;
603
604 size = unlink_random_file_from_directory(dir_path);
605
606 free(dir_path);
607
608 if (size)
609 p_atomic_add(cache->size, - size);
610 }
611
612 void
613 disk_cache_remove(struct disk_cache *cache, cache_key key)
614 {
615 struct stat sb;
616
617 char *filename = get_cache_file(cache, key);
618 if (filename == NULL) {
619 return;
620 }
621
622 if (stat(filename, &sb) == -1) {
623 free(filename);
624 return;
625 }
626
627 unlink(filename);
628 free(filename);
629
630 if (sb.st_size)
631 p_atomic_add(cache->size, - sb.st_size);
632 }
633
634 void
635 disk_cache_put(struct disk_cache *cache,
636 cache_key key,
637 const void *data,
638 size_t size)
639 {
640 int fd = -1, fd_final = -1, err, ret;
641 size_t len;
642 char *filename = NULL, *filename_tmp = NULL;
643 const char *p = data;
644
645 filename = get_cache_file(cache, key);
646 if (filename == NULL)
647 goto done;
648
649 /* Write to a temporary file to allow for an atomic rename to the
650 * final destination filename, (to prevent any readers from seeing
651 * a partially written file).
652 */
653 if (asprintf(&filename_tmp, "%s.tmp", filename) == -1)
654 goto done;
655
656 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
657
658 /* Make the two-character subdirectory within the cache as needed. */
659 if (fd == -1) {
660 if (errno != ENOENT)
661 goto done;
662
663 make_cache_file_directory(cache, key);
664
665 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
666 if (fd == -1)
667 goto done;
668 }
669
670 /* With the temporary file open, we take an exclusive flock on
671 * it. If the flock fails, then another process still has the file
672 * open with the flock held. So just let that file be responsible
673 * for writing the file.
674 */
675 err = flock(fd, LOCK_EX | LOCK_NB);
676 if (err == -1)
677 goto done;
678
679 /* Now that we have the lock on the open temporary file, we can
680 * check to see if the destination file already exists. If so,
681 * another process won the race between when we saw that the file
682 * didn't exist and now. In this case, we don't do anything more,
683 * (to ensure the size accounting of the cache doesn't get off).
684 */
685 fd_final = open(filename, O_RDONLY | O_CLOEXEC);
686 if (fd_final != -1)
687 goto done;
688
689 /* OK, we're now on the hook to write out a file that we know is
690 * not in the cache, and is also not being written out to the cache
691 * by some other process.
692 *
693 * Before we do that, if the cache is too large, evict something
694 * else first.
695 */
696 if (*cache->size + size > cache->max_size)
697 evict_random_item(cache);
698
699 /* Now, finally, write out the contents to the temporary file, then
700 * rename them atomically to the destination filename, and also
701 * perform an atomic increment of the total cache size.
702 */
703 for (len = 0; len < size; len += ret) {
704 ret = write(fd, p + len, size - len);
705 if (ret == -1) {
706 unlink(filename_tmp);
707 goto done;
708 }
709 }
710
711 rename(filename_tmp, filename);
712
713 p_atomic_add(cache->size, size);
714
715 done:
716 if (fd_final != -1)
717 close(fd_final);
718 /* This close finally releases the flock, (now that the final dile
719 * has been renamed into place and the size has been added).
720 */
721 if (fd != -1)
722 close(fd);
723 if (filename_tmp)
724 free(filename_tmp);
725 if (filename)
726 free(filename);
727 }
728
729 void *
730 disk_cache_get(struct disk_cache *cache, cache_key key, size_t *size)
731 {
732 int fd = -1, ret, len;
733 struct stat sb;
734 char *filename = NULL;
735 uint8_t *data = NULL;
736
737 if (size)
738 *size = 0;
739
740 filename = get_cache_file(cache, key);
741 if (filename == NULL)
742 goto fail;
743
744 fd = open(filename, O_RDONLY | O_CLOEXEC);
745 if (fd == -1)
746 goto fail;
747
748 if (fstat(fd, &sb) == -1)
749 goto fail;
750
751 data = malloc(sb.st_size);
752 if (data == NULL)
753 goto fail;
754
755 for (len = 0; len < sb.st_size; len += ret) {
756 ret = read(fd, data + len, sb.st_size - len);
757 if (ret == -1)
758 goto fail;
759 }
760
761 free(filename);
762 close(fd);
763
764 if (size)
765 *size = sb.st_size;
766
767 return data;
768
769 fail:
770 if (data)
771 free(data);
772 if (filename)
773 free(filename);
774 if (fd != -1)
775 close(fd);
776
777 return NULL;
778 }
779
780 void
781 disk_cache_put_key(struct disk_cache *cache, cache_key key)
782 {
783 uint32_t *key_chunk = (uint32_t *) key;
784 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
785 unsigned char *entry;
786
787 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
788
789 memcpy(entry, key, CACHE_KEY_SIZE);
790 }
791
792 /* This function lets us test whether a given key was previously
793 * stored in the cache with disk_cache_put_key(). The implement is
794 * efficient by not using syscalls or hitting the disk. It's not
795 * race-free, but the races are benign. If we race with someone else
796 * calling disk_cache_put_key, then that's just an extra cache miss and an
797 * extra recompile.
798 */
799 bool
800 disk_cache_has_key(struct disk_cache *cache, cache_key key)
801 {
802 uint32_t *key_chunk = (uint32_t *) key;
803 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
804 unsigned char *entry;
805
806 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
807
808 return memcmp(entry, key, CACHE_KEY_SIZE) == 0;
809 }
810
811 #endif /* ENABLE_SHADER_CACHE */