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