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