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 <assert.h>
27 #include <inttypes.h>
28 #include <stdbool.h>
29 #include <stddef.h>
30 #include <stdlib.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <dirent.h>
34 #include <fcntl.h>
35
36 #include "zlib.h"
37
38 #ifdef HAVE_ZSTD
39 #include "zstd.h"
40 #endif
41
42 /* 3 is the recomended level, with 22 as the absolute maximum */
43 #define ZSTD_COMPRESSION_LEVEL 3
44
45 /* From the zlib docs:
46 * "If the memory is available, buffers sizes on the order of 128K or 256K
47 * bytes should be used."
48 */
49 #define BUFSIZE 256 * 1024
50
51 static ssize_t
52 write_all(int fd, const void *buf, size_t count);
53
54 /**
55 * Compresses cache entry in memory and writes it to disk. Returns the size
56 * of the data written to disk.
57 */
58 static size_t
deflate_and_write_to_disk(const void * in_data,size_t in_data_size,int dest)59 deflate_and_write_to_disk(const void *in_data, size_t in_data_size, int dest)
60 {
61 #ifdef HAVE_ZSTD
62 /* from the zstd docs (https://facebook.github.io/zstd/zstd_manual.html):
63 * compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`.
64 */
65 size_t out_size = ZSTD_compressBound(in_data_size);
66 void * out = malloc(out_size);
67
68 size_t ret = ZSTD_compress(out, out_size, in_data, in_data_size,
69 ZSTD_COMPRESSION_LEVEL);
70 if (ZSTD_isError(ret)) {
71 free(out);
72 return 0;
73 }
74 ssize_t written = write_all(dest, out, ret);
75 if (written == -1) {
76 free(out);
77 return 0;
78 }
79 free(out);
80 return ret;
81 #else
82 unsigned char *out;
83
84 /* allocate deflate state */
85 z_stream strm;
86 strm.zalloc = Z_NULL;
87 strm.zfree = Z_NULL;
88 strm.opaque = Z_NULL;
89 strm.next_in = (uint8_t *) in_data;
90 strm.avail_in = in_data_size;
91
92 int ret = deflateInit(&strm, Z_BEST_COMPRESSION);
93 if (ret != Z_OK)
94 return 0;
95
96 /* compress until end of in_data */
97 size_t compressed_size = 0;
98 int flush;
99
100 out = malloc(BUFSIZE * sizeof(unsigned char));
101 if (out == NULL)
102 return 0;
103
104 do {
105 int remaining = in_data_size - BUFSIZE;
106 flush = remaining > 0 ? Z_NO_FLUSH : Z_FINISH;
107 in_data_size -= BUFSIZE;
108
109 /* Run deflate() on input until the output buffer is not full (which
110 * means there is no more data to deflate).
111 */
112 do {
113 strm.avail_out = BUFSIZE;
114 strm.next_out = out;
115
116 ret = deflate(&strm, flush); /* no bad return value */
117 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
118
119 size_t have = BUFSIZE - strm.avail_out;
120 compressed_size += have;
121
122 ssize_t written = write_all(dest, out, have);
123 if (written == -1) {
124 (void)deflateEnd(&strm);
125 free(out);
126 return 0;
127 }
128 } while (strm.avail_out == 0);
129
130 /* all input should be used */
131 assert(strm.avail_in == 0);
132
133 } while (flush != Z_FINISH);
134
135 /* stream should be complete */
136 assert(ret == Z_STREAM_END);
137
138 /* clean up and return */
139 (void)deflateEnd(&strm);
140 free(out);
141 return compressed_size;
142 # endif
143 }
144
145 /**
146 * Decompresses cache entry, returns true if successful.
147 */
148 static bool
inflate_cache_data(uint8_t * in_data,size_t in_data_size,uint8_t * out_data,size_t out_data_size)149 inflate_cache_data(uint8_t *in_data, size_t in_data_size,
150 uint8_t *out_data, size_t out_data_size)
151 {
152 #ifdef HAVE_ZSTD
153 size_t ret = ZSTD_decompress(out_data, out_data_size, in_data, in_data_size);
154 return !ZSTD_isError(ret);
155 #else
156 z_stream strm;
157
158 /* allocate inflate state */
159 strm.zalloc = Z_NULL;
160 strm.zfree = Z_NULL;
161 strm.opaque = Z_NULL;
162 strm.next_in = in_data;
163 strm.avail_in = in_data_size;
164 strm.next_out = out_data;
165 strm.avail_out = out_data_size;
166
167 int ret = inflateInit(&strm);
168 if (ret != Z_OK)
169 return false;
170
171 ret = inflate(&strm, Z_NO_FLUSH);
172 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
173
174 /* Unless there was an error we should have decompressed everything in one
175 * go as we know the uncompressed file size.
176 */
177 if (ret != Z_STREAM_END) {
178 (void)inflateEnd(&strm);
179 return false;
180 }
181 assert(strm.avail_out == 0);
182
183 /* clean up and return */
184 (void)inflateEnd(&strm);
185 return true;
186 #endif
187 }
188
189 #if DETECT_OS_WINDOWS
190 /* TODO: implement disk cache support on windows */
191
192 #else
193
194 #include <dirent.h>
195 #include <errno.h>
196 #include <pwd.h>
197 #include <stdio.h>
198 #include <string.h>
199 #include <sys/file.h>
200 #include <sys/mman.h>
201 #include <sys/types.h>
202 #include <sys/stat.h>
203 #include <unistd.h>
204
205 #include "util/crc32.h"
206 #include "util/debug.h"
207 #include "util/disk_cache.h"
208 #include "util/disk_cache_os.h"
209 #include "util/ralloc.h"
210 #include "util/rand_xor.h"
211
212 /* Create a directory named 'path' if it does not already exist.
213 *
214 * Returns: 0 if path already exists as a directory or if created.
215 * -1 in all other cases.
216 */
217 static int
mkdir_if_needed(const char * path)218 mkdir_if_needed(const char *path)
219 {
220 struct stat sb;
221
222 /* If the path exists already, then our work is done if it's a
223 * directory, but it's an error if it is not.
224 */
225 if (stat(path, &sb) == 0) {
226 if (S_ISDIR(sb.st_mode)) {
227 return 0;
228 } else {
229 fprintf(stderr, "Cannot use %s for shader cache (not a directory)"
230 "---disabling.\n", path);
231 return -1;
232 }
233 }
234
235 int ret = mkdir(path, 0755);
236 if (ret == 0 || (ret == -1 && errno == EEXIST))
237 return 0;
238
239 fprintf(stderr, "Failed to create %s for shader cache (%s)---disabling.\n",
240 path, strerror(errno));
241
242 return -1;
243 }
244
245 /* Concatenate an existing path and a new name to form a new path. If the new
246 * path does not exist as a directory, create it then return the resulting
247 * name of the new path (ralloc'ed off of 'ctx').
248 *
249 * Returns NULL on any error, such as:
250 *
251 * <path> does not exist or is not a directory
252 * <path>/<name> exists but is not a directory
253 * <path>/<name> cannot be created as a directory
254 */
255 static char *
concatenate_and_mkdir(void * ctx,const char * path,const char * name)256 concatenate_and_mkdir(void *ctx, const char *path, const char *name)
257 {
258 char *new_path;
259 struct stat sb;
260
261 if (stat(path, &sb) != 0 || ! S_ISDIR(sb.st_mode))
262 return NULL;
263
264 new_path = ralloc_asprintf(ctx, "%s/%s", path, name);
265
266 if (mkdir_if_needed(new_path) == 0)
267 return new_path;
268 else
269 return NULL;
270 }
271
272 /* Given a directory path and predicate function, find the entry with
273 * the oldest access time in that directory for which the predicate
274 * returns true.
275 *
276 * Returns: A malloc'ed string for the path to the chosen file, (or
277 * NULL on any error). The caller should free the string when
278 * finished.
279 */
280 static char *
choose_lru_file_matching(const char * dir_path,bool (* predicate)(const char * dir_path,const struct stat *,const char *,const size_t))281 choose_lru_file_matching(const char *dir_path,
282 bool (*predicate)(const char *dir_path,
283 const struct stat *,
284 const char *, const size_t))
285 {
286 DIR *dir;
287 struct dirent *entry;
288 char *filename;
289 char *lru_name = NULL;
290 time_t lru_atime = 0;
291
292 dir = opendir(dir_path);
293 if (dir == NULL)
294 return NULL;
295
296 while (1) {
297 entry = readdir(dir);
298 if (entry == NULL)
299 break;
300
301 struct stat sb;
302 if (fstatat(dirfd(dir), entry->d_name, &sb, 0) == 0) {
303 if (!lru_atime || (sb.st_atime < lru_atime)) {
304 size_t len = strlen(entry->d_name);
305
306 if (!predicate(dir_path, &sb, entry->d_name, len))
307 continue;
308
309 char *tmp = realloc(lru_name, len + 1);
310 if (tmp) {
311 lru_name = tmp;
312 memcpy(lru_name, entry->d_name, len + 1);
313 lru_atime = sb.st_atime;
314 }
315 }
316 }
317 }
318
319 if (lru_name == NULL) {
320 closedir(dir);
321 return NULL;
322 }
323
324 if (asprintf(&filename, "%s/%s", dir_path, lru_name) < 0)
325 filename = NULL;
326
327 free(lru_name);
328 closedir(dir);
329
330 return filename;
331 }
332
333 /* Is entry a regular file, and not having a name with a trailing
334 * ".tmp"
335 */
336 static bool
is_regular_non_tmp_file(const char * path,const struct stat * sb,const char * d_name,const size_t len)337 is_regular_non_tmp_file(const char *path, const struct stat *sb,
338 const char *d_name, const size_t len)
339 {
340 if (!S_ISREG(sb->st_mode))
341 return false;
342
343 if (len >= 4 && strcmp(&d_name[len-4], ".tmp") == 0)
344 return false;
345
346 return true;
347 }
348
349 /* Returns the size of the deleted file, (or 0 on any error). */
350 static size_t
unlink_lru_file_from_directory(const char * path)351 unlink_lru_file_from_directory(const char *path)
352 {
353 struct stat sb;
354 char *filename;
355
356 filename = choose_lru_file_matching(path, is_regular_non_tmp_file);
357 if (filename == NULL)
358 return 0;
359
360 if (stat(filename, &sb) == -1) {
361 free (filename);
362 return 0;
363 }
364
365 unlink(filename);
366 free (filename);
367
368 return sb.st_blocks * 512;
369 }
370
371 /* Is entry a directory with a two-character name, (and not the
372 * special name of ".."). We also return false if the dir is empty.
373 */
374 static bool
is_two_character_sub_directory(const char * path,const struct stat * sb,const char * d_name,const size_t len)375 is_two_character_sub_directory(const char *path, const struct stat *sb,
376 const char *d_name, const size_t len)
377 {
378 if (!S_ISDIR(sb->st_mode))
379 return false;
380
381 if (len != 2)
382 return false;
383
384 if (strcmp(d_name, "..") == 0)
385 return false;
386
387 char *subdir;
388 if (asprintf(&subdir, "%s/%s", path, d_name) == -1)
389 return false;
390 DIR *dir = opendir(subdir);
391 free(subdir);
392
393 if (dir == NULL)
394 return false;
395
396 unsigned subdir_entries = 0;
397 struct dirent *d;
398 while ((d = readdir(dir)) != NULL) {
399 if(++subdir_entries > 2)
400 break;
401 }
402 closedir(dir);
403
404 /* If dir only contains '.' and '..' it must be empty */
405 if (subdir_entries <= 2)
406 return false;
407
408 return true;
409 }
410
411 /* Create the directory that will be needed for the cache file for \key.
412 *
413 * Obviously, the implementation here must closely match
414 * _get_cache_file above.
415 */
416 static void
make_cache_file_directory(struct disk_cache * cache,const cache_key key)417 make_cache_file_directory(struct disk_cache *cache, const cache_key key)
418 {
419 char *dir;
420 char buf[41];
421
422 _mesa_sha1_format(buf, key);
423 if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
424 return;
425
426 mkdir_if_needed(dir);
427 free(dir);
428 }
429
430 static ssize_t
read_all(int fd,void * buf,size_t count)431 read_all(int fd, void *buf, size_t count)
432 {
433 char *in = buf;
434 ssize_t read_ret;
435 size_t done;
436
437 for (done = 0; done < count; done += read_ret) {
438 read_ret = read(fd, in + done, count - done);
439 if (read_ret == -1 || read_ret == 0)
440 return -1;
441 }
442 return done;
443 }
444
445 static ssize_t
write_all(int fd,const void * buf,size_t count)446 write_all(int fd, const void *buf, size_t count)
447 {
448 const char *out = buf;
449 ssize_t written;
450 size_t done;
451
452 for (done = 0; done < count; done += written) {
453 written = write(fd, out + done, count - done);
454 if (written == -1)
455 return -1;
456 }
457 return done;
458 }
459
460 /* Evict least recently used cache item */
461 void
disk_cache_evict_lru_item(struct disk_cache * cache)462 disk_cache_evict_lru_item(struct disk_cache *cache)
463 {
464 char *dir_path;
465
466 /* With a reasonably-sized, full cache, (and with keys generated
467 * from a cryptographic hash), we can choose two random hex digits
468 * and reasonably expect the directory to exist with a file in it.
469 * Provides pseudo-LRU eviction to reduce checking all cache files.
470 */
471 uint64_t rand64 = rand_xorshift128plus(cache->seed_xorshift128plus);
472 if (asprintf(&dir_path, "%s/%02" PRIx64 , cache->path, rand64 & 0xff) < 0)
473 return;
474
475 size_t size = unlink_lru_file_from_directory(dir_path);
476
477 free(dir_path);
478
479 if (size) {
480 p_atomic_add(cache->size, - (uint64_t)size);
481 return;
482 }
483
484 /* In the case where the random choice of directory didn't find
485 * something, we choose the least recently accessed from the
486 * existing directories.
487 *
488 * Really, the only reason this code exists is to allow the unit
489 * tests to work, (which use an artificially-small cache to be able
490 * to force a single cached item to be evicted).
491 */
492 dir_path = choose_lru_file_matching(cache->path,
493 is_two_character_sub_directory);
494 if (dir_path == NULL)
495 return;
496
497 size = unlink_lru_file_from_directory(dir_path);
498
499 free(dir_path);
500
501 if (size)
502 p_atomic_add(cache->size, - (uint64_t)size);
503 }
504
505 void
disk_cache_evict_item(struct disk_cache * cache,char * filename)506 disk_cache_evict_item(struct disk_cache *cache, char *filename)
507 {
508 struct stat sb;
509 if (stat(filename, &sb) == -1) {
510 free(filename);
511 return;
512 }
513
514 unlink(filename);
515 free(filename);
516
517 if (sb.st_blocks)
518 p_atomic_add(cache->size, - (uint64_t)sb.st_blocks * 512);
519 }
520
521 void *
disk_cache_load_item(struct disk_cache * cache,char * filename,size_t * size)522 disk_cache_load_item(struct disk_cache *cache, char *filename, size_t *size)
523 {
524 int fd = -1, ret;
525 struct stat sb;
526 uint8_t *data = NULL;
527 uint8_t *uncompressed_data = NULL;
528 uint8_t *file_header = NULL;
529
530 fd = open(filename, O_RDONLY | O_CLOEXEC);
531 if (fd == -1)
532 goto fail;
533
534 if (fstat(fd, &sb) == -1)
535 goto fail;
536
537 data = malloc(sb.st_size);
538 if (data == NULL)
539 goto fail;
540
541 size_t ck_size = cache->driver_keys_blob_size;
542 file_header = malloc(ck_size);
543 if (!file_header)
544 goto fail;
545
546 if (sb.st_size < ck_size)
547 goto fail;
548
549 ret = read_all(fd, file_header, ck_size);
550 if (ret == -1)
551 goto fail;
552
553 /* Check for extremely unlikely hash collisions */
554 if (memcmp(cache->driver_keys_blob, file_header, ck_size) != 0) {
555 assert(!"Mesa cache keys mismatch!");
556 goto fail;
557 }
558
559 size_t cache_item_md_size = sizeof(uint32_t);
560 uint32_t md_type;
561 ret = read_all(fd, &md_type, cache_item_md_size);
562 if (ret == -1)
563 goto fail;
564
565 if (md_type == CACHE_ITEM_TYPE_GLSL) {
566 uint32_t num_keys;
567 cache_item_md_size += sizeof(uint32_t);
568 ret = read_all(fd, &num_keys, sizeof(uint32_t));
569 if (ret == -1)
570 goto fail;
571
572 /* The cache item metadata is currently just used for distributing
573 * precompiled shaders, they are not used by Mesa so just skip them for
574 * now.
575 * TODO: pass the metadata back to the caller and do some basic
576 * validation.
577 */
578 cache_item_md_size += num_keys * sizeof(cache_key);
579 ret = lseek(fd, num_keys * sizeof(cache_key), SEEK_CUR);
580 if (ret == -1)
581 goto fail;
582 }
583
584 /* Load the CRC that was created when the file was written. */
585 struct cache_entry_file_data cf_data;
586 size_t cf_data_size = sizeof(cf_data);
587 ret = read_all(fd, &cf_data, cf_data_size);
588 if (ret == -1)
589 goto fail;
590
591 /* Load the actual cache data. */
592 size_t cache_data_size =
593 sb.st_size - cf_data_size - ck_size - cache_item_md_size;
594 ret = read_all(fd, data, cache_data_size);
595 if (ret == -1)
596 goto fail;
597
598 /* Uncompress the cache data */
599 uncompressed_data = malloc(cf_data.uncompressed_size);
600 if (!inflate_cache_data(data, cache_data_size, uncompressed_data,
601 cf_data.uncompressed_size))
602 goto fail;
603
604 /* Check the data for corruption */
605 if (cf_data.crc32 != util_hash_crc32(uncompressed_data,
606 cf_data.uncompressed_size))
607 goto fail;
608
609 free(data);
610 free(filename);
611 free(file_header);
612 close(fd);
613
614 if (size)
615 *size = cf_data.uncompressed_size;
616
617 return uncompressed_data;
618
619 fail:
620 if (data)
621 free(data);
622 if (filename)
623 free(filename);
624 if (uncompressed_data)
625 free(uncompressed_data);
626 if (file_header)
627 free(file_header);
628 if (fd != -1)
629 close(fd);
630
631 return NULL;
632 }
633
634 /* Return a filename within the cache's directory corresponding to 'key'.
635 *
636 * Returns NULL if out of memory.
637 */
638 char *
disk_cache_get_cache_filename(struct disk_cache * cache,const cache_key key)639 disk_cache_get_cache_filename(struct disk_cache *cache, const cache_key key)
640 {
641 char buf[41];
642 char *filename;
643
644 if (cache->path_init_failed)
645 return NULL;
646
647 _mesa_sha1_format(buf, key);
648 if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
649 buf[1], buf + 2) == -1)
650 return NULL;
651
652 return filename;
653 }
654
655 void
disk_cache_write_item_to_disk(struct disk_cache_put_job * dc_job,struct cache_entry_file_data * cf_data,char * filename)656 disk_cache_write_item_to_disk(struct disk_cache_put_job *dc_job,
657 struct cache_entry_file_data *cf_data,
658 char *filename)
659 {
660 int fd = -1, fd_final = -1;
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 char *filename_tmp = NULL;
667 if (asprintf(&filename_tmp, "%s.tmp", filename) == -1)
668 goto done;
669
670 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
671
672 /* Make the two-character subdirectory within the cache as needed. */
673 if (fd == -1) {
674 if (errno != ENOENT)
675 goto done;
676
677 make_cache_file_directory(dc_job->cache, dc_job->key);
678
679 fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
680 if (fd == -1)
681 goto done;
682 }
683
684 /* With the temporary file open, we take an exclusive flock on
685 * it. If the flock fails, then another process still has the file
686 * open with the flock held. So just let that file be responsible
687 * for writing the file.
688 */
689 #ifdef HAVE_FLOCK
690 int err = flock(fd, LOCK_EX | LOCK_NB);
691 #else
692 struct flock lock = {
693 .l_start = 0,
694 .l_len = 0, /* entire file */
695 .l_type = F_WRLCK,
696 .l_whence = SEEK_SET
697 };
698 int err = fcntl(fd, F_SETLK, &lock);
699 #endif
700 if (err == -1)
701 goto done;
702
703 /* Now that we have the lock on the open temporary file, we can
704 * check to see if the destination file already exists. If so,
705 * another process won the race between when we saw that the file
706 * didn't exist and now. In this case, we don't do anything more,
707 * (to ensure the size accounting of the cache doesn't get off).
708 */
709 fd_final = open(filename, O_RDONLY | O_CLOEXEC);
710 if (fd_final != -1) {
711 unlink(filename_tmp);
712 goto done;
713 }
714
715 /* OK, we're now on the hook to write out a file that we know is
716 * not in the cache, and is also not being written out to the cache
717 * by some other process.
718 */
719
720 /* Write the driver_keys_blob, this can be used find information about the
721 * mesa version that produced the entry or deal with hash collisions,
722 * should that ever become a real problem.
723 */
724 int ret = write_all(fd, dc_job->cache->driver_keys_blob,
725 dc_job->cache->driver_keys_blob_size);
726 if (ret == -1) {
727 unlink(filename_tmp);
728 goto done;
729 }
730
731 /* Write the cache item metadata. This data can be used to deal with
732 * hash collisions, as well as providing useful information to 3rd party
733 * tools reading the cache files.
734 */
735 ret = write_all(fd, &dc_job->cache_item_metadata.type,
736 sizeof(uint32_t));
737 if (ret == -1) {
738 unlink(filename_tmp);
739 goto done;
740 }
741
742 if (dc_job->cache_item_metadata.type == CACHE_ITEM_TYPE_GLSL) {
743 ret = write_all(fd, &dc_job->cache_item_metadata.num_keys,
744 sizeof(uint32_t));
745 if (ret == -1) {
746 unlink(filename_tmp);
747 goto done;
748 }
749
750 ret = write_all(fd, dc_job->cache_item_metadata.keys[0],
751 dc_job->cache_item_metadata.num_keys *
752 sizeof(cache_key));
753 if (ret == -1) {
754 unlink(filename_tmp);
755 goto done;
756 }
757 }
758
759 size_t cf_data_size = sizeof(*cf_data);
760 ret = write_all(fd, cf_data, cf_data_size);
761 if (ret == -1) {
762 unlink(filename_tmp);
763 goto done;
764 }
765
766 /* Now, finally, write out the contents to the temporary file, then
767 * rename them atomically to the destination filename, and also
768 * perform an atomic increment of the total cache size.
769 */
770 size_t file_size = deflate_and_write_to_disk(dc_job->data, dc_job->size,
771 fd);
772 if (file_size == 0) {
773 unlink(filename_tmp);
774 goto done;
775 }
776 ret = rename(filename_tmp, filename);
777 if (ret == -1) {
778 unlink(filename_tmp);
779 goto done;
780 }
781
782 struct stat sb;
783 if (stat(filename, &sb) == -1) {
784 /* Something went wrong remove the file */
785 unlink(filename);
786 goto done;
787 }
788
789 p_atomic_add(dc_job->cache->size, sb.st_blocks * 512);
790
791 done:
792 if (fd_final != -1)
793 close(fd_final);
794 /* This close finally releases the flock, (now that the final file
795 * has been renamed into place and the size has been added).
796 */
797 if (fd != -1)
798 close(fd);
799 free(filename_tmp);
800 }
801
802 /* Determine path for cache based on the first defined name as follows:
803 *
804 * $MESA_GLSL_CACHE_DIR
805 * $XDG_CACHE_HOME/mesa_shader_cache
806 * <pwd.pw_dir>/.cache/mesa_shader_cache
807 */
808 char *
disk_cache_generate_cache_dir(void * mem_ctx)809 disk_cache_generate_cache_dir(void *mem_ctx)
810 {
811 char *path = getenv("MESA_GLSL_CACHE_DIR");
812 if (path) {
813 if (mkdir_if_needed(path) == -1)
814 return NULL;
815
816 path = concatenate_and_mkdir(mem_ctx, path, CACHE_DIR_NAME);
817 if (!path)
818 return NULL;
819 }
820
821 if (path == NULL) {
822 char *xdg_cache_home = getenv("XDG_CACHE_HOME");
823
824 if (xdg_cache_home) {
825 if (mkdir_if_needed(xdg_cache_home) == -1)
826 return NULL;
827
828 path = concatenate_and_mkdir(mem_ctx, xdg_cache_home, CACHE_DIR_NAME);
829 if (!path)
830 return NULL;
831 }
832 }
833
834 if (!path) {
835 char *buf;
836 size_t buf_size;
837 struct passwd pwd, *result;
838
839 buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
840 if (buf_size == -1)
841 buf_size = 512;
842
843 /* Loop until buf_size is large enough to query the directory */
844 while (1) {
845 buf = ralloc_size(mem_ctx, buf_size);
846
847 getpwuid_r(getuid(), &pwd, buf, buf_size, &result);
848 if (result)
849 break;
850
851 if (errno == ERANGE) {
852 ralloc_free(buf);
853 buf = NULL;
854 buf_size *= 2;
855 } else {
856 return NULL;
857 }
858 }
859
860 path = concatenate_and_mkdir(mem_ctx, pwd.pw_dir, ".cache");
861 if (!path)
862 return NULL;
863
864 path = concatenate_and_mkdir(mem_ctx, path, CACHE_DIR_NAME);
865 if (!path)
866 return NULL;
867 }
868
869 return path;
870 }
871
872 bool
disk_cache_enabled()873 disk_cache_enabled()
874 {
875 /* If running as a users other than the real user disable cache */
876 if (geteuid() != getuid())
877 return false;
878
879 /* At user request, disable shader cache entirely. */
880 #ifdef SHADER_CACHE_DISABLE_BY_DEFAULT
881 bool disable_by_default = true;
882 #else
883 bool disable_by_default = false;
884 #endif
885 if (env_var_as_boolean("MESA_GLSL_CACHE_DISABLE", disable_by_default))
886 return false;
887
888 return true;
889 }
890
891 bool
disk_cache_mmap_cache_index(void * mem_ctx,struct disk_cache * cache,char * path)892 disk_cache_mmap_cache_index(void *mem_ctx, struct disk_cache *cache,
893 char *path)
894 {
895 int fd = -1;
896 bool mapped = false;
897
898 cache->path = ralloc_strdup(cache, path);
899 if (cache->path == NULL)
900 goto path_fail;
901
902 path = ralloc_asprintf(mem_ctx, "%s/index", cache->path);
903 if (path == NULL)
904 goto path_fail;
905
906 fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
907 if (fd == -1)
908 goto path_fail;
909
910 struct stat sb;
911 if (fstat(fd, &sb) == -1)
912 goto path_fail;
913
914 /* Force the index file to be the expected size. */
915 size_t size = sizeof(*cache->size) + CACHE_INDEX_MAX_KEYS * CACHE_KEY_SIZE;
916 if (sb.st_size != size) {
917 if (ftruncate(fd, size) == -1)
918 goto path_fail;
919 }
920
921 /* We map this shared so that other processes see updates that we
922 * make.
923 *
924 * Note: We do use atomic addition to ensure that multiple
925 * processes don't scramble the cache size recorded in the
926 * index. But we don't use any locking to prevent multiple
927 * processes from updating the same entry simultaneously. The idea
928 * is that if either result lands entirely in the index, then
929 * that's equivalent to a well-ordered write followed by an
930 * eviction and a write. On the other hand, if the simultaneous
931 * writes result in a corrupt entry, that's not really any
932 * different than both entries being evicted, (since within the
933 * guarantees of the cryptographic hash, a corrupt entry is
934 * unlikely to ever match a real cache key).
935 */
936 cache->index_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE,
937 MAP_SHARED, fd, 0);
938 if (cache->index_mmap == MAP_FAILED)
939 goto path_fail;
940 cache->index_mmap_size = size;
941
942 cache->size = (uint64_t *) cache->index_mmap;
943 cache->stored_keys = cache->index_mmap + sizeof(uint64_t);
944 mapped = true;
945
946 path_fail:
947 if (fd != -1)
948 close(fd);
949
950 return mapped;
951 }
952
953 void
disk_cache_destroy_mmap(struct disk_cache * cache)954 disk_cache_destroy_mmap(struct disk_cache *cache)
955 {
956 munmap(cache->index_mmap, cache->index_mmap_size);
957 }
958 #endif
959
960 #endif /* ENABLE_SHADER_CACHE */
961