util/disk_cache: check cache exists before calling munmap()
[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 if (cache)
381 munmap(cache->index_mmap, cache->index_mmap_size);
382
383 ralloc_free(cache);
384 }
385
386 /* Return a filename within the cache's directory corresponding to 'key'. The
387 * returned filename is ralloced with 'cache' as the parent context.
388 *
389 * Returns NULL if out of memory.
390 */
391 static char *
392 get_cache_file(struct disk_cache *cache, cache_key key)
393 {
394 char buf[41];
395 char *filename;
396
397 _mesa_sha1_format(buf, key);
398 if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
399 buf[1], buf + 2) == -1)
400 return NULL;
401
402 return filename;
403 }
404
405 /* Create the directory that will be needed for the cache file for \key.
406 *
407 * Obviously, the implementation here must closely match
408 * _get_cache_file above.
409 */
410 static void
411 make_cache_file_directory(struct disk_cache *cache, cache_key key)
412 {
413 char *dir;
414 char buf[41];
415
416 _mesa_sha1_format(buf, key);
417 if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
418 return;
419
420 mkdir_if_needed(dir);
421 free(dir);
422 }
423
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.
427 *
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
430 * finished.
431 */
432 static char *
433 choose_random_file_matching(const char *dir_path,
434 bool (*predicate)(struct dirent *,
435 const char *dir_path))
436 {
437 DIR *dir;
438 struct dirent *entry;
439 unsigned int count, victim;
440 char *filename;
441
442 dir = opendir(dir_path);
443 if (dir == NULL)
444 return NULL;
445
446 count = 0;
447
448 while (1) {
449 entry = readdir(dir);
450 if (entry == NULL)
451 break;
452 if (!predicate(entry, dir_path))
453 continue;
454
455 count++;
456 }
457
458 if (count == 0) {
459 closedir(dir);
460 return NULL;
461 }
462
463 victim = rand() % count;
464
465 rewinddir(dir);
466 count = 0;
467
468 while (1) {
469 entry = readdir(dir);
470 if (entry == NULL)
471 break;
472 if (!predicate(entry, dir_path))
473 continue;
474 if (count == victim)
475 break;
476
477 count++;
478 }
479
480 if (entry == NULL) {
481 closedir(dir);
482 return NULL;
483 }
484
485 if (asprintf(&filename, "%s/%s", dir_path, entry->d_name) < 0)
486 filename = NULL;
487
488 closedir(dir);
489
490 return filename;
491 }
492
493 /* Is entry a regular file, and not having a name with a trailing
494 * ".tmp"
495 */
496 static bool
497 is_regular_non_tmp_file(struct dirent *entry, const char *path)
498 {
499 char *filename;
500 if (asprintf(&filename, "%s/%s", path, entry->d_name) == -1)
501 return false;
502
503 struct stat sb;
504 int res = stat(filename, &sb);
505 free(filename);
506
507 if (res == -1 || !S_ISREG(sb.st_mode))
508 return false;
509
510 size_t len = strlen (entry->d_name);
511 if (len >= 4 && strcmp(&entry->d_name[len-4], ".tmp") == 0)
512 return false;
513
514 return true;
515 }
516
517 /* Returns the size of the deleted file, (or 0 on any error). */
518 static size_t
519 unlink_random_file_from_directory(const char *path)
520 {
521 struct stat sb;
522 char *filename;
523
524 filename = choose_random_file_matching(path, is_regular_non_tmp_file);
525 if (filename == NULL)
526 return 0;
527
528 if (stat(filename, &sb) == -1) {
529 free (filename);
530 return 0;
531 }
532
533 unlink(filename);
534
535 free (filename);
536
537 return sb.st_size;
538 }
539
540 /* Is entry a directory with a two-character name, (and not the
541 * special name of "..")
542 */
543 static bool
544 is_two_character_sub_directory(struct dirent *entry, const char *path)
545 {
546 char *subdir;
547 if (asprintf(&subdir, "%s/%s", path, entry->d_name) == -1)
548 return false;
549
550 struct stat sb;
551 int res = stat(subdir, &sb);
552 free(subdir);
553
554 if (res == -1 || !S_ISDIR(sb.st_mode))
555 return false;
556
557 if (strlen(entry->d_name) != 2)
558 return false;
559
560 if (strcmp(entry->d_name, "..") == 0)
561 return false;
562
563 return true;
564 }
565
566 static void
567 evict_random_item(struct disk_cache *cache)
568 {
569 const char hex[] = "0123456789abcde";
570 char *dir_path;
571 int a, b;
572 size_t size;
573
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.
577 */
578 a = rand() % 16;
579 b = rand() % 16;
580
581 if (asprintf(&dir_path, "%s/%c%c", cache->path, hex[a], hex[b]) < 0)
582 return;
583
584 size = unlink_random_file_from_directory(dir_path);
585
586 free(dir_path);
587
588 if (size) {
589 p_atomic_add(cache->size, - size);
590 return;
591 }
592
593 /* In the case where the random choice of directory didn't find
594 * something, we choose randomly from the existing directories.
595 *
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).
599 */
600 dir_path = choose_random_file_matching(cache->path,
601 is_two_character_sub_directory);
602 if (dir_path == NULL)
603 return;
604
605 size = unlink_random_file_from_directory(dir_path);
606
607 free(dir_path);
608
609 if (size)
610 p_atomic_add(cache->size, - size);
611 }
612
613 void
614 disk_cache_remove(struct disk_cache *cache, cache_key key)
615 {
616 struct stat sb;
617
618 char *filename = get_cache_file(cache, key);
619 if (filename == NULL) {
620 return;
621 }
622
623 if (stat(filename, &sb) == -1) {
624 free(filename);
625 return;
626 }
627
628 unlink(filename);
629 free(filename);
630
631 if (sb.st_size)
632 p_atomic_add(cache->size, - sb.st_size);
633 }
634
635 void
636 disk_cache_put(struct disk_cache *cache,
637 cache_key key,
638 const void *data,
639 size_t size)
640 {
641 int fd = -1, fd_final = -1, err, ret;
642 size_t len;
643 char *filename = NULL, *filename_tmp = NULL;
644 const char *p = data;
645
646 filename = get_cache_file(cache, key);
647 if (filename == NULL)
648 goto done;
649
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).
653 */
654 if (asprintf(&filename_tmp, "%s.tmp", filename) == -1)
655 goto done;
656
657 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
658
659 /* Make the two-character subdirectory within the cache as needed. */
660 if (fd == -1) {
661 if (errno != ENOENT)
662 goto done;
663
664 make_cache_file_directory(cache, key);
665
666 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
667 if (fd == -1)
668 goto done;
669 }
670
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.
675 */
676 err = flock(fd, LOCK_EX | LOCK_NB);
677 if (err == -1)
678 goto done;
679
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).
685 */
686 fd_final = open(filename, O_RDONLY | O_CLOEXEC);
687 if (fd_final != -1)
688 goto done;
689
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.
693 *
694 * Before we do that, if the cache is too large, evict something
695 * else first.
696 */
697 if (*cache->size + size > cache->max_size)
698 evict_random_item(cache);
699
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.
703 */
704 for (len = 0; len < size; len += ret) {
705 ret = write(fd, p + len, size - len);
706 if (ret == -1) {
707 unlink(filename_tmp);
708 goto done;
709 }
710 }
711
712 rename(filename_tmp, filename);
713
714 p_atomic_add(cache->size, size);
715
716 done:
717 if (fd_final != -1)
718 close(fd_final);
719 /* This close finally releases the flock, (now that the final dile
720 * has been renamed into place and the size has been added).
721 */
722 if (fd != -1)
723 close(fd);
724 if (filename_tmp)
725 free(filename_tmp);
726 if (filename)
727 free(filename);
728 }
729
730 void *
731 disk_cache_get(struct disk_cache *cache, cache_key key, size_t *size)
732 {
733 int fd = -1, ret, len;
734 struct stat sb;
735 char *filename = NULL;
736 uint8_t *data = NULL;
737
738 if (size)
739 *size = 0;
740
741 filename = get_cache_file(cache, key);
742 if (filename == NULL)
743 goto fail;
744
745 fd = open(filename, O_RDONLY | O_CLOEXEC);
746 if (fd == -1)
747 goto fail;
748
749 if (fstat(fd, &sb) == -1)
750 goto fail;
751
752 data = malloc(sb.st_size);
753 if (data == NULL)
754 goto fail;
755
756 for (len = 0; len < sb.st_size; len += ret) {
757 ret = read(fd, data + len, sb.st_size - len);
758 if (ret == -1)
759 goto fail;
760 }
761
762 free(filename);
763 close(fd);
764
765 if (size)
766 *size = sb.st_size;
767
768 return data;
769
770 fail:
771 if (data)
772 free(data);
773 if (filename)
774 free(filename);
775 if (fd != -1)
776 close(fd);
777
778 return NULL;
779 }
780
781 void
782 disk_cache_put_key(struct disk_cache *cache, cache_key key)
783 {
784 uint32_t *key_chunk = (uint32_t *) key;
785 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
786 unsigned char *entry;
787
788 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
789
790 memcpy(entry, key, CACHE_KEY_SIZE);
791 }
792
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
798 * extra recompile.
799 */
800 bool
801 disk_cache_has_key(struct disk_cache *cache, cache_key key)
802 {
803 uint32_t *key_chunk = (uint32_t *) key;
804 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
805 unsigned char *entry;
806
807 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
808
809 return memcmp(entry, key, CACHE_KEY_SIZE) == 0;
810 }
811
812 #endif /* ENABLE_SHADER_CACHE */