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