util/disk_cache: stop using ralloc_asprintf() unnecessarily
[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 while (*end && isspace(*end))
282 end++;
283 switch (*end) {
284 case 'K':
285 case 'k':
286 max_size *= 1024;
287 break;
288 case 'M':
289 case 'm':
290 max_size *= 1024*1024;
291 break;
292 case '\0':
293 case 'G':
294 case 'g':
295 default:
296 max_size *= 1024*1024*1024;
297 break;
298 }
299 }
300 }
301
302 /* Default to 1GB for maximum cache size. */
303 if (max_size == 0)
304 max_size = 1024*1024*1024;
305
306 cache->max_size = max_size;
307
308 ralloc_free(local);
309
310 return cache;
311
312 fail:
313 if (fd != -1)
314 close(fd);
315 if (cache)
316 ralloc_free(cache);
317 ralloc_free(local);
318
319 return NULL;
320 }
321
322 void
323 disk_cache_destroy(struct disk_cache *cache)
324 {
325 munmap(cache->index_mmap, cache->index_mmap_size);
326
327 ralloc_free(cache);
328 }
329
330 /* Return a filename within the cache's directory corresponding to 'key'. The
331 * returned filename is ralloced with 'cache' as the parent context.
332 *
333 * Returns NULL if out of memory.
334 */
335 static char *
336 get_cache_file(struct disk_cache *cache, cache_key key)
337 {
338 char buf[41];
339 char *filename;
340
341 _mesa_sha1_format(buf, key);
342 asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0], buf[1], buf + 2);
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 asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]);
360 mkdir_if_needed(dir);
361
362 free(dir);
363 }
364
365 /* Given a directory path and predicate function, count all entries in
366 * that directory for which the predicate returns true. Then choose a
367 * random entry from among those counted.
368 *
369 * Returns: A malloc'ed string for the path to the chosen file, (or
370 * NULL on any error). The caller should free the string when
371 * finished.
372 */
373 static char *
374 choose_random_file_matching(const char *dir_path,
375 bool (*predicate)(struct dirent *))
376 {
377 DIR *dir;
378 struct dirent *entry;
379 unsigned int count, victim;
380 char *filename;
381
382 dir = opendir(dir_path);
383 if (dir == NULL)
384 return NULL;
385
386 count = 0;
387
388 while (1) {
389 entry = readdir(dir);
390 if (entry == NULL)
391 break;
392 if (! predicate(entry))
393 continue;
394
395 count++;
396 }
397
398 if (count == 0) {
399 closedir(dir);
400 return NULL;
401 }
402
403 victim = rand() % count;
404
405 rewinddir(dir);
406 count = 0;
407
408 while (1) {
409 entry = readdir(dir);
410 if (entry == NULL)
411 break;
412 if (! predicate(entry))
413 continue;
414 if (count == victim)
415 break;
416
417 count++;
418 }
419
420 if (entry == NULL) {
421 closedir(dir);
422 return NULL;
423 }
424
425 if (asprintf(&filename, "%s/%s", dir_path, entry->d_name) < 0)
426 filename = NULL;
427
428 closedir(dir);
429
430 return filename;
431 }
432
433 /* Is entry a regular file, and not having a name with a trailing
434 * ".tmp"
435 */
436 static bool
437 is_regular_non_tmp_file(struct dirent *entry)
438 {
439 size_t len;
440
441 if (entry->d_type != DT_REG)
442 return false;
443
444 len = strlen (entry->d_name);
445 if (len >= 4 && strcmp(&entry->d_name[len-4], ".tmp") == 0)
446 return false;
447
448 return true;
449 }
450
451 /* Returns the size of the deleted file, (or 0 on any error). */
452 static size_t
453 unlink_random_file_from_directory(const char *path)
454 {
455 struct stat sb;
456 char *filename;
457
458 filename = choose_random_file_matching(path, is_regular_non_tmp_file);
459 if (filename == NULL)
460 return 0;
461
462 if (stat(filename, &sb) == -1) {
463 free (filename);
464 return 0;
465 }
466
467 unlink(filename);
468
469 free (filename);
470
471 return sb.st_size;
472 }
473
474 /* Is entry a directory with a two-character name, (and not the
475 * special name of "..")
476 */
477 static bool
478 is_two_character_sub_directory(struct dirent *entry)
479 {
480 if (entry->d_type != DT_DIR)
481 return false;
482
483 if (strlen(entry->d_name) != 2)
484 return false;
485
486 if (strcmp(entry->d_name, "..") == 0)
487 return false;
488
489 return true;
490 }
491
492 static void
493 evict_random_item(struct disk_cache *cache)
494 {
495 const char hex[] = "0123456789abcde";
496 char *dir_path;
497 int a, b;
498 size_t size;
499
500 /* With a reasonably-sized, full cache, (and with keys generated
501 * from a cryptographic hash), we can choose two random hex digits
502 * and reasonably expect the directory to exist with a file in it.
503 */
504 a = rand() % 16;
505 b = rand() % 16;
506
507 if (asprintf(&dir_path, "%s/%c%c", cache->path, hex[a], hex[b]) < 0)
508 return;
509
510 size = unlink_random_file_from_directory(dir_path);
511
512 free(dir_path);
513
514 if (size) {
515 p_atomic_add(cache->size, - size);
516 return;
517 }
518
519 /* In the case where the random choice of directory didn't find
520 * something, we choose randomly from the existing directories.
521 *
522 * Really, the only reason this code exists is to allow the unit
523 * tests to work, (which use an artificially-small cache to be able
524 * to force a single cached item to be evicted).
525 */
526 dir_path = choose_random_file_matching(cache->path,
527 is_two_character_sub_directory);
528 if (dir_path == NULL)
529 return;
530
531 size = unlink_random_file_from_directory(dir_path);
532
533 free(dir_path);
534
535 if (size)
536 p_atomic_add(cache->size, - size);
537 }
538
539 void
540 disk_cache_remove(struct disk_cache *cache, cache_key key)
541 {
542 struct stat sb;
543
544 char *filename = get_cache_file(cache, key);
545 if (filename == NULL) {
546 return;
547 }
548
549 if (stat(filename, &sb) == -1) {
550 free(filename);
551 return;
552 }
553
554 unlink(filename);
555 free(filename);
556
557 if (sb.st_size)
558 p_atomic_add(cache->size, - sb.st_size);
559 }
560
561 void
562 disk_cache_put(struct disk_cache *cache,
563 cache_key key,
564 const void *data,
565 size_t size)
566 {
567 int fd = -1, fd_final = -1, err, ret;
568 size_t len;
569 char *filename = NULL, *filename_tmp = NULL;
570 const char *p = data;
571
572 filename = get_cache_file(cache, key);
573 if (filename == NULL)
574 goto done;
575
576 /* Write to a temporary file to allow for an atomic rename to the
577 * final destination filename, (to prevent any readers from seeing
578 * a partially written file).
579 */
580 asprintf(&filename_tmp, "%s.tmp", filename);
581 if (filename_tmp == NULL)
582 goto done;
583
584 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
585
586 /* Make the two-character subdirectory within the cache as needed. */
587 if (fd == -1) {
588 if (errno != ENOENT)
589 goto done;
590
591 make_cache_file_directory(cache, key);
592
593 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
594 if (fd == -1)
595 goto done;
596 }
597
598 /* With the temporary file open, we take an exclusive flock on
599 * it. If the flock fails, then another process still has the file
600 * open with the flock held. So just let that file be responsible
601 * for writing the file.
602 */
603 err = flock(fd, LOCK_EX | LOCK_NB);
604 if (err == -1)
605 goto done;
606
607 /* Now that we have the lock on the open temporary file, we can
608 * check to see if the destination file already exists. If so,
609 * another process won the race between when we saw that the file
610 * didn't exist and now. In this case, we don't do anything more,
611 * (to ensure the size accounting of the cache doesn't get off).
612 */
613 fd_final = open(filename, O_RDONLY | O_CLOEXEC);
614 if (fd_final != -1)
615 goto done;
616
617 /* OK, we're now on the hook to write out a file that we know is
618 * not in the cache, and is also not being written out to the cache
619 * by some other process.
620 *
621 * Before we do that, if the cache is too large, evict something
622 * else first.
623 */
624 if (*cache->size + size > cache->max_size)
625 evict_random_item(cache);
626
627 /* Now, finally, write out the contents to the temporary file, then
628 * rename them atomically to the destination filename, and also
629 * perform an atomic increment of the total cache size.
630 */
631 for (len = 0; len < size; len += ret) {
632 ret = write(fd, p + len, size - len);
633 if (ret == -1) {
634 unlink(filename_tmp);
635 goto done;
636 }
637 }
638
639 rename(filename_tmp, filename);
640
641 p_atomic_add(cache->size, size);
642
643 done:
644 if (fd_final != -1)
645 close(fd_final);
646 /* This close finally releases the flock, (now that the final dile
647 * has been renamed into place and the size has been added).
648 */
649 if (fd != -1)
650 close(fd);
651 if (filename_tmp)
652 free(filename_tmp);
653 if (filename)
654 free(filename);
655 }
656
657 void *
658 disk_cache_get(struct disk_cache *cache, cache_key key, size_t *size)
659 {
660 int fd = -1, ret, len;
661 struct stat sb;
662 char *filename = NULL;
663 uint8_t *data = NULL;
664
665 if (size)
666 *size = 0;
667
668 filename = get_cache_file(cache, key);
669 if (filename == NULL)
670 goto fail;
671
672 fd = open(filename, O_RDONLY | O_CLOEXEC);
673 if (fd == -1)
674 goto fail;
675
676 if (fstat(fd, &sb) == -1)
677 goto fail;
678
679 data = malloc(sb.st_size);
680 if (data == NULL)
681 goto fail;
682
683 for (len = 0; len < sb.st_size; len += ret) {
684 ret = read(fd, data + len, sb.st_size - len);
685 if (ret == -1)
686 goto fail;
687 }
688
689 free(filename);
690 close(fd);
691
692 if (size)
693 *size = sb.st_size;
694
695 return data;
696
697 fail:
698 if (data)
699 free(data);
700 if (filename)
701 free(filename);
702 if (fd != -1)
703 close(fd);
704
705 return NULL;
706 }
707
708 void
709 disk_cache_put_key(struct disk_cache *cache, cache_key key)
710 {
711 uint32_t *key_chunk = (uint32_t *) key;
712 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
713 unsigned char *entry;
714
715 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
716
717 memcpy(entry, key, CACHE_KEY_SIZE);
718 }
719
720 /* This function lets us test whether a given key was previously
721 * stored in the cache with disk_cache_put_key(). The implement is
722 * efficient by not using syscalls or hitting the disk. It's not
723 * race-free, but the races are benign. If we race with someone else
724 * calling disk_cache_put_key, then that's just an extra cache miss and an
725 * extra recompile.
726 */
727 bool
728 disk_cache_has_key(struct disk_cache *cache, cache_key key)
729 {
730 uint32_t *key_chunk = (uint32_t *) key;
731 int i = *key_chunk & CACHE_INDEX_KEY_MASK;
732 unsigned char *entry;
733
734 entry = &cache->stored_keys[i + CACHE_KEY_SIZE];
735
736 return memcmp(entry, key, CACHE_KEY_SIZE) == 0;
737 }
738
739 #endif /* ENABLE_SHADER_CACHE */