util/disk_cache: create timestamp and gpu_id dirs when MESA_GLSL_CACHE_DIR is used
[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 /* If running as a users other than the real user disable cache */
202 if (geteuid() != getuid())
203 return NULL;
204
205 /* A ralloc context for transient data during this invocation. */
206 local = ralloc_context(NULL);
207 if (local == NULL)
208 goto fail;
209
210 /* At user request, disable shader cache entirely. */
211 if (getenv("MESA_GLSL_CACHE_DISABLE"))
212 goto fail;
213
214 /* As a temporary measure, (while the shader cache is under
215 * development, and known to not be fully functional), also require
216 * the MESA_GLSL_CACHE_ENABLE variable to be set.
217 */
218 if (!getenv("MESA_GLSL_CACHE_ENABLE"))
219 goto fail;
220
221 /* Determine path for cache based on the first defined name as follows:
222 *
223 * $MESA_GLSL_CACHE_DIR
224 * $XDG_CACHE_HOME/mesa
225 * <pwd.pw_dir>/.cache/mesa
226 */
227 path = getenv("MESA_GLSL_CACHE_DIR");
228 if (path) {
229 if (mkdir_if_needed(path) == -1)
230 goto fail;
231
232 path = create_mesa_cache_dir(local, path, timestamp,
233 gpu_name);
234 if (path == NULL)
235 goto fail;
236 }
237
238 if (path == NULL) {
239 char *xdg_cache_home = getenv("XDG_CACHE_HOME");
240
241 if (xdg_cache_home) {
242 if (mkdir_if_needed(xdg_cache_home) == -1)
243 goto fail;
244
245 path = create_mesa_cache_dir(local, xdg_cache_home, timestamp,
246 gpu_name);
247 if (path == NULL)
248 goto fail;
249 }
250 }
251
252 if (path == NULL) {
253 char *buf;
254 size_t buf_size;
255 struct passwd pwd, *result;
256
257 buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
258 if (buf_size == -1)
259 buf_size = 512;
260
261 /* Loop until buf_size is large enough to query the directory */
262 while (1) {
263 buf = ralloc_size(local, buf_size);
264
265 getpwuid_r(getuid(), &pwd, buf, buf_size, &result);
266 if (result)
267 break;
268
269 if (errno == ERANGE) {
270 ralloc_free(buf);
271 buf = NULL;
272 buf_size *= 2;
273 } else {
274 goto fail;
275 }
276 }
277
278 path = concatenate_and_mkdir(local, pwd.pw_dir, ".cache");
279 if (path == NULL)
280 goto fail;
281
282 path = create_mesa_cache_dir(local, path, timestamp, gpu_name);
283 if (path == NULL)
284 goto fail;
285 }
286
287 cache = ralloc(NULL, struct disk_cache);
288 if (cache == NULL)
289 goto fail;
290
291 cache->path = ralloc_strdup(cache, path);
292 if (cache->path == NULL)
293 goto fail;
294
295 path = ralloc_asprintf(local, "%s/index", cache->path);
296 if (path == NULL)
297 goto fail;
298
299 fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
300 if (fd == -1)
301 goto fail;
302
303 if (fstat(fd, &sb) == -1)
304 goto fail;
305
306 /* Force the index file to be the expected size. */
307 size = sizeof(*cache->size) + CACHE_INDEX_MAX_KEYS * CACHE_KEY_SIZE;
308 if (sb.st_size != size) {
309 if (ftruncate(fd, size) == -1)
310 goto fail;
311 }
312
313 /* We map this shared so that other processes see updates that we
314 * make.
315 *
316 * Note: We do use atomic addition to ensure that multiple
317 * processes don't scramble the cache size recorded in the
318 * index. But we don't use any locking to prevent multiple
319 * processes from updating the same entry simultaneously. The idea
320 * is that if either result lands entirely in the index, then
321 * that's equivalent to a well-ordered write followed by an
322 * eviction and a write. On the other hand, if the simultaneous
323 * writes result in a corrupt entry, that's not really any
324 * different than both entries being evicted, (since within the
325 * guarantees of the cryptographic hash, a corrupt entry is
326 * unlikely to ever match a real cache key).
327 */
328 cache->index_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE,
329 MAP_SHARED, fd, 0);
330 if (cache->index_mmap == MAP_FAILED)
331 goto fail;
332 cache->index_mmap_size = size;
333
334 close(fd);
335
336 cache->size = (uint64_t *) cache->index_mmap;
337 cache->stored_keys = cache->index_mmap + sizeof(uint64_t);
338
339 max_size = 0;
340
341 max_size_str = getenv("MESA_GLSL_CACHE_MAX_SIZE");
342 if (max_size_str) {
343 char *end;
344 max_size = strtoul(max_size_str, &end, 10);
345 if (end == max_size_str) {
346 max_size = 0;
347 } else {
348 switch (*end) {
349 case 'K':
350 case 'k':
351 max_size *= 1024;
352 break;
353 case 'M':
354 case 'm':
355 max_size *= 1024*1024;
356 break;
357 case '\0':
358 case 'G':
359 case 'g':
360 default:
361 max_size *= 1024*1024*1024;
362 break;
363 }
364 }
365 }
366
367 /* Default to 1GB for maximum cache size. */
368 if (max_size == 0)
369 max_size = 1024*1024*1024;
370
371 cache->max_size = max_size;
372
373 ralloc_free(local);
374
375 return cache;
376
377 fail:
378 if (fd != -1)
379 close(fd);
380 if (cache)
381 ralloc_free(cache);
382 ralloc_free(local);
383
384 return NULL;
385 }
386
387 void
388 disk_cache_destroy(struct disk_cache *cache)
389 {
390 if (cache)
391 munmap(cache->index_mmap, cache->index_mmap_size);
392
393 ralloc_free(cache);
394 }
395
396 /* Return a filename within the cache's directory corresponding to 'key'. The
397 * returned filename is ralloced with 'cache' as the parent context.
398 *
399 * Returns NULL if out of memory.
400 */
401 static char *
402 get_cache_file(struct disk_cache *cache, cache_key key)
403 {
404 char buf[41];
405 char *filename;
406
407 _mesa_sha1_format(buf, key);
408 if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
409 buf[1], buf + 2) == -1)
410 return NULL;
411
412 return filename;
413 }
414
415 /* Create the directory that will be needed for the cache file for \key.
416 *
417 * Obviously, the implementation here must closely match
418 * _get_cache_file above.
419 */
420 static void
421 make_cache_file_directory(struct disk_cache *cache, cache_key key)
422 {
423 char *dir;
424 char buf[41];
425
426 _mesa_sha1_format(buf, key);
427 if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
428 return;
429
430 mkdir_if_needed(dir);
431 free(dir);
432 }
433
434 /* Given a directory path and predicate function, count all entries in
435 * that directory for which the predicate returns true. Then choose a
436 * random entry from among those counted.
437 *
438 * Returns: A malloc'ed string for the path to the chosen file, (or
439 * NULL on any error). The caller should free the string when
440 * finished.
441 */
442 static char *
443 choose_random_file_matching(const char *dir_path,
444 bool (*predicate)(struct dirent *,
445 const char *dir_path))
446 {
447 DIR *dir;
448 struct dirent *entry;
449 unsigned int count, victim;
450 char *filename;
451
452 dir = opendir(dir_path);
453 if (dir == NULL)
454 return NULL;
455
456 count = 0;
457
458 while (1) {
459 entry = readdir(dir);
460 if (entry == NULL)
461 break;
462 if (!predicate(entry, dir_path))
463 continue;
464
465 count++;
466 }
467
468 if (count == 0) {
469 closedir(dir);
470 return NULL;
471 }
472
473 victim = rand() % count;
474
475 rewinddir(dir);
476 count = 0;
477
478 while (1) {
479 entry = readdir(dir);
480 if (entry == NULL)
481 break;
482 if (!predicate(entry, dir_path))
483 continue;
484 if (count == victim)
485 break;
486
487 count++;
488 }
489
490 if (entry == NULL) {
491 closedir(dir);
492 return NULL;
493 }
494
495 if (asprintf(&filename, "%s/%s", dir_path, entry->d_name) < 0)
496 filename = NULL;
497
498 closedir(dir);
499
500 return filename;
501 }
502
503 /* Is entry a regular file, and not having a name with a trailing
504 * ".tmp"
505 */
506 static bool
507 is_regular_non_tmp_file(struct dirent *entry, const char *path)
508 {
509 char *filename;
510 if (asprintf(&filename, "%s/%s", path, entry->d_name) == -1)
511 return false;
512
513 struct stat sb;
514 int res = stat(filename, &sb);
515 free(filename);
516
517 if (res == -1 || !S_ISREG(sb.st_mode))
518 return false;
519
520 size_t len = strlen (entry->d_name);
521 if (len >= 4 && strcmp(&entry->d_name[len-4], ".tmp") == 0)
522 return false;
523
524 return true;
525 }
526
527 /* Returns the size of the deleted file, (or 0 on any error). */
528 static size_t
529 unlink_random_file_from_directory(const char *path)
530 {
531 struct stat sb;
532 char *filename;
533
534 filename = choose_random_file_matching(path, is_regular_non_tmp_file);
535 if (filename == NULL)
536 return 0;
537
538 if (stat(filename, &sb) == -1) {
539 free (filename);
540 return 0;
541 }
542
543 unlink(filename);
544
545 free (filename);
546
547 return sb.st_size;
548 }
549
550 /* Is entry a directory with a two-character name, (and not the
551 * special name of "..")
552 */
553 static bool
554 is_two_character_sub_directory(struct dirent *entry, const char *path)
555 {
556 char *subdir;
557 if (asprintf(&subdir, "%s/%s", path, entry->d_name) == -1)
558 return false;
559
560 struct stat sb;
561 int res = stat(subdir, &sb);
562 free(subdir);
563
564 if (res == -1 || !S_ISDIR(sb.st_mode))
565 return false;
566
567 if (strlen(entry->d_name) != 2)
568 return false;
569
570 if (strcmp(entry->d_name, "..") == 0)
571 return false;
572
573 return true;
574 }
575
576 static void
577 evict_random_item(struct disk_cache *cache)
578 {
579 const char hex[] = "0123456789abcde";
580 char *dir_path;
581 int a, b;
582 size_t size;
583
584 /* With a reasonably-sized, full cache, (and with keys generated
585 * from a cryptographic hash), we can choose two random hex digits
586 * and reasonably expect the directory to exist with a file in it.
587 */
588 a = rand() % 16;
589 b = rand() % 16;
590
591 if (asprintf(&dir_path, "%s/%c%c", cache->path, hex[a], hex[b]) < 0)
592 return;
593
594 size = unlink_random_file_from_directory(dir_path);
595
596 free(dir_path);
597
598 if (size) {
599 p_atomic_add(cache->size, - size);
600 return;
601 }
602
603 /* In the case where the random choice of directory didn't find
604 * something, we choose randomly from the existing directories.
605 *
606 * Really, the only reason this code exists is to allow the unit
607 * tests to work, (which use an artificially-small cache to be able
608 * to force a single cached item to be evicted).
609 */
610 dir_path = choose_random_file_matching(cache->path,
611 is_two_character_sub_directory);
612 if (dir_path == NULL)
613 return;
614
615 size = unlink_random_file_from_directory(dir_path);
616
617 free(dir_path);
618
619 if (size)
620 p_atomic_add(cache->size, - size);
621 }
622
623 void
624 disk_cache_remove(struct disk_cache *cache, cache_key key)
625 {
626 struct stat sb;
627
628 char *filename = get_cache_file(cache, key);
629 if (filename == NULL) {
630 return;
631 }
632
633 if (stat(filename, &sb) == -1) {
634 free(filename);
635 return;
636 }
637
638 unlink(filename);
639 free(filename);
640
641 if (sb.st_size)
642 p_atomic_add(cache->size, - sb.st_size);
643 }
644
645 void
646 disk_cache_put(struct disk_cache *cache,
647 cache_key key,
648 const void *data,
649 size_t size)
650 {
651 int fd = -1, fd_final = -1, err, ret;
652 size_t len;
653 char *filename = NULL, *filename_tmp = NULL;
654 const char *p = data;
655
656 filename = get_cache_file(cache, key);
657 if (filename == NULL)
658 goto done;
659
660 /* Write to a temporary file to allow for an atomic rename to the
661 * final destination filename, (to prevent any readers from seeing
662 * a partially written file).
663 */
664 if (asprintf(&filename_tmp, "%s.tmp", filename) == -1)
665 goto done;
666
667 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
668
669 /* Make the two-character subdirectory within the cache as needed. */
670 if (fd == -1) {
671 if (errno != ENOENT)
672 goto done;
673
674 make_cache_file_directory(cache, key);
675
676 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
677 if (fd == -1)
678 goto done;
679 }
680
681 /* With the temporary file open, we take an exclusive flock on
682 * it. If the flock fails, then another process still has the file
683 * open with the flock held. So just let that file be responsible
684 * for writing the file.
685 */
686 err = flock(fd, LOCK_EX | LOCK_NB);
687 if (err == -1)
688 goto done;
689
690 /* Now that we have the lock on the open temporary file, we can
691 * check to see if the destination file already exists. If so,
692 * another process won the race between when we saw that the file
693 * didn't exist and now. In this case, we don't do anything more,
694 * (to ensure the size accounting of the cache doesn't get off).
695 */
696 fd_final = open(filename, O_RDONLY | O_CLOEXEC);
697 if (fd_final != -1)
698 goto done;
699
700 /* OK, we're now on the hook to write out a file that we know is
701 * not in the cache, and is also not being written out to the cache
702 * by some other process.
703 *
704 * Before we do that, if the cache is too large, evict something
705 * else first.
706 */
707 if (*cache->size + size > cache->max_size)
708 evict_random_item(cache);
709
710 /* Now, finally, write out the contents to the temporary file, then
711 * rename them atomically to the destination filename, and also
712 * perform an atomic increment of the total cache size.
713 */
714 for (len = 0; len < size; len += ret) {
715 ret = write(fd, p + len, size - len);
716 if (ret == -1) {
717 unlink(filename_tmp);
718 goto done;
719 }
720 }
721
722 rename(filename_tmp, filename);
723
724 p_atomic_add(cache->size, size);
725
726 done:
727 if (fd_final != -1)
728 close(fd_final);
729 /* This close finally releases the flock, (now that the final dile
730 * has been renamed into place and the size has been added).
731 */
732 if (fd != -1)
733 close(fd);
734 if (filename_tmp)
735 free(filename_tmp);
736 if (filename)
737 free(filename);
738 }
739
740 void *
741 disk_cache_get(struct disk_cache *cache, cache_key key, size_t *size)
742 {
743 int fd = -1, ret, len;
744 struct stat sb;
745 char *filename = NULL;
746 uint8_t *data = NULL;
747
748 if (size)
749 *size = 0;
750
751 filename = get_cache_file(cache, key);
752 if (filename == NULL)
753 goto fail;
754
755 fd = open(filename, O_RDONLY | O_CLOEXEC);
756 if (fd == -1)
757 goto fail;
758
759 if (fstat(fd, &sb) == -1)
760 goto fail;
761
762 data = malloc(sb.st_size);
763 if (data == NULL)
764 goto fail;
765
766 for (len = 0; len < sb.st_size; len += ret) {
767 ret = read(fd, data + len, sb.st_size - len);
768 if (ret == -1)
769 goto fail;
770 }
771
772 free(filename);
773 close(fd);
774
775 if (size)
776 *size = sb.st_size;
777
778 return data;
779
780 fail:
781 if (data)
782 free(data);
783 if (filename)
784 free(filename);
785 if (fd != -1)
786 close(fd);
787
788 return NULL;
789 }
790
791 void
792 disk_cache_put_key(struct disk_cache *cache, cache_key key)
793 {
794 uint32_t *key_chunk = (uint32_t *) key;
795 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
796 unsigned char *entry;
797
798 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
799
800 memcpy(entry, key, CACHE_KEY_SIZE);
801 }
802
803 /* This function lets us test whether a given key was previously
804 * stored in the cache with disk_cache_put_key(). The implement is
805 * efficient by not using syscalls or hitting the disk. It's not
806 * race-free, but the races are benign. If we race with someone else
807 * calling disk_cache_put_key, then that's just an extra cache miss and an
808 * extra recompile.
809 */
810 bool
811 disk_cache_has_key(struct disk_cache *cache, cache_key key)
812 {
813 uint32_t *key_chunk = (uint32_t *) key;
814 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
815 unsigned char *entry;
816
817 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
818
819 return memcmp(entry, key, CACHE_KEY_SIZE) == 0;
820 }
821
822 #endif /* ENABLE_SHADER_CACHE */