disk_cache.c revision 7e995a2e
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#include "zlib.h"
41
42#include "util/crc32.h"
43#include "util/debug.h"
44#include "util/rand_xor.h"
45#include "util/u_atomic.h"
46#include "util/u_queue.h"
47#include "util/mesa-sha1.h"
48#include "util/ralloc.h"
49#include "main/compiler.h"
50#include "main/errors.h"
51
52#include "disk_cache.h"
53
54/* Number of bits to mask off from a cache key to get an index. */
55#define CACHE_INDEX_KEY_BITS 16
56
57/* Mask for computing an index from a key. */
58#define CACHE_INDEX_KEY_MASK ((1 << CACHE_INDEX_KEY_BITS) - 1)
59
60/* The number of keys that can be stored in the index. */
61#define CACHE_INDEX_MAX_KEYS (1 << CACHE_INDEX_KEY_BITS)
62
63/* The cache version should be bumped whenever a change is made to the
64 * structure of cache entries or the index. This will give any 3rd party
65 * applications reading the cache entries a chance to adjust to the changes.
66 *
67 * - The cache version is checked internally when reading a cache entry. If we
68 *   ever have a mismatch we are in big trouble as this means we had a cache
69 *   collision. In case of such an event please check the skys for giant
70 *   asteroids and that the entire Mesa team hasn't been eaten by wolves.
71 *
72 * - There is no strict requirement that cache versions be backwards
73 *   compatible but effort should be taken to limit disruption where possible.
74 */
75#define CACHE_VERSION 1
76
77struct disk_cache {
78   /* The path to the cache directory. */
79   char *path;
80   bool path_init_failed;
81
82   /* Thread queue for compressing and writing cache entries to disk */
83   struct util_queue cache_queue;
84
85   /* Seed for rand, which is used to pick a random directory */
86   uint64_t seed_xorshift128plus[2];
87
88   /* A pointer to the mmapped index file within the cache directory. */
89   uint8_t *index_mmap;
90   size_t index_mmap_size;
91
92   /* Pointer to total size of all objects in cache (within index_mmap) */
93   uint64_t *size;
94
95   /* Pointer to stored keys, (within index_mmap). */
96   uint8_t *stored_keys;
97
98   /* Maximum size of all cached objects (in bytes). */
99   uint64_t max_size;
100
101   /* Driver cache keys. */
102   uint8_t *driver_keys_blob;
103   size_t driver_keys_blob_size;
104
105   disk_cache_put_cb blob_put_cb;
106   disk_cache_get_cb blob_get_cb;
107};
108
109struct disk_cache_put_job {
110   struct util_queue_fence fence;
111
112   struct disk_cache *cache;
113
114   cache_key key;
115
116   /* Copy of cache data to be compressed and written. */
117   void *data;
118
119   /* Size of data to be compressed and written. */
120   size_t size;
121
122   struct cache_item_metadata cache_item_metadata;
123};
124
125#ifdef __HAVE_ATOMIC64_OPS
126#define cache_size_adjust(size, val)	p_atomic_add(size, val)
127#else
128	// XXX no locking
129#define cache_size_adjust(size, val)	(size) += (val)
130#endif
131
132
133/* Create a directory named 'path' if it does not already exist.
134 *
135 * Returns: 0 if path already exists as a directory or if created.
136 *         -1 in all other cases.
137 */
138static int
139mkdir_if_needed(const char *path)
140{
141   struct stat sb;
142
143   /* If the path exists already, then our work is done if it's a
144    * directory, but it's an error if it is not.
145    */
146   if (stat(path, &sb) == 0) {
147      if (S_ISDIR(sb.st_mode)) {
148         return 0;
149      } else {
150         fprintf(stderr, "Cannot use %s for shader cache (not a directory)"
151                         "---disabling.\n", path);
152         return -1;
153      }
154   }
155
156   int ret = mkdir(path, 0755);
157   if (ret == 0 || (ret == -1 && errno == EEXIST))
158     return 0;
159
160   fprintf(stderr, "Failed to create %s for shader cache (%s)---disabling.\n",
161           path, strerror(errno));
162
163   return -1;
164}
165
166/* Concatenate an existing path and a new name to form a new path.  If the new
167 * path does not exist as a directory, create it then return the resulting
168 * name of the new path (ralloc'ed off of 'ctx').
169 *
170 * Returns NULL on any error, such as:
171 *
172 *      <path> does not exist or is not a directory
173 *      <path>/<name> exists but is not a directory
174 *      <path>/<name> cannot be created as a directory
175 */
176static char *
177concatenate_and_mkdir(void *ctx, const char *path, const char *name)
178{
179   char *new_path;
180   struct stat sb;
181
182   if (stat(path, &sb) != 0 || ! S_ISDIR(sb.st_mode))
183      return NULL;
184
185   new_path = ralloc_asprintf(ctx, "%s/%s", path, name);
186
187   if (mkdir_if_needed(new_path) == 0)
188      return new_path;
189   else
190      return NULL;
191}
192
193#define DRV_KEY_CPY(_dst, _src, _src_size) \
194do {                                       \
195   memcpy(_dst, _src, _src_size);          \
196   _dst += _src_size;                      \
197} while (0);
198
199struct disk_cache *
200disk_cache_create(const char *gpu_name, const char *driver_id,
201                  uint64_t driver_flags)
202{
203   void *local;
204   struct disk_cache *cache = NULL;
205   char *path, *max_size_str;
206   uint64_t max_size;
207   int fd = -1;
208   struct stat sb;
209   size_t size;
210
211   uint8_t cache_version = CACHE_VERSION;
212   size_t cv_size = sizeof(cache_version);
213
214   /* If running as a users other than the real user disable cache */
215   if (geteuid() != getuid())
216      return NULL;
217
218   /* A ralloc context for transient data during this invocation. */
219   local = ralloc_context(NULL);
220   if (local == NULL)
221      goto fail;
222
223   /* At user request, disable shader cache entirely. */
224   if (env_var_as_boolean("MESA_GLSL_CACHE_DISABLE", false))
225      goto fail;
226
227   cache = rzalloc(NULL, struct disk_cache);
228   if (cache == NULL)
229      goto fail;
230
231   /* Assume failure. */
232   cache->path_init_failed = true;
233
234   /* Determine path for cache based on the first defined name as follows:
235    *
236    *   $MESA_GLSL_CACHE_DIR
237    *   $XDG_CACHE_HOME/mesa_shader_cache
238    *   <pwd.pw_dir>/.cache/mesa_shader_cache
239    */
240   path = getenv("MESA_GLSL_CACHE_DIR");
241   if (path) {
242      if (mkdir_if_needed(path) == -1)
243         goto path_fail;
244
245      path = concatenate_and_mkdir(local, path, CACHE_DIR_NAME);
246      if (path == NULL)
247         goto path_fail;
248   }
249
250   if (path == NULL) {
251      char *xdg_cache_home = getenv("XDG_CACHE_HOME");
252
253      if (xdg_cache_home) {
254         if (mkdir_if_needed(xdg_cache_home) == -1)
255            goto path_fail;
256
257         path = concatenate_and_mkdir(local, xdg_cache_home, CACHE_DIR_NAME);
258         if (path == NULL)
259            goto path_fail;
260      }
261   }
262
263   if (path == NULL) {
264      char *buf;
265      size_t buf_size;
266      struct passwd pwd, *result;
267
268      buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
269      if (buf_size == -1)
270         buf_size = 512;
271
272      /* Loop until buf_size is large enough to query the directory */
273      while (1) {
274         buf = ralloc_size(local, buf_size);
275
276         getpwuid_r(getuid(), &pwd, buf, buf_size, &result);
277         if (result)
278            break;
279
280         if (errno == ERANGE) {
281            ralloc_free(buf);
282            buf = NULL;
283            buf_size *= 2;
284         } else {
285            goto path_fail;
286         }
287      }
288
289      path = concatenate_and_mkdir(local, pwd.pw_dir, ".cache");
290      if (path == NULL)
291         goto path_fail;
292
293      path = concatenate_and_mkdir(local, path, CACHE_DIR_NAME);
294      if (path == NULL)
295         goto path_fail;
296   }
297
298   cache->path = ralloc_strdup(cache, path);
299   if (cache->path == NULL)
300      goto path_fail;
301
302   path = ralloc_asprintf(local, "%s/index", cache->path);
303   if (path == NULL)
304      goto path_fail;
305
306   fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
307   if (fd == -1)
308      goto path_fail;
309
310   if (fstat(fd, &sb) == -1)
311      goto path_fail;
312
313   /* Force the index file to be the expected size. */
314   size = sizeof(*cache->size) + CACHE_INDEX_MAX_KEYS * CACHE_KEY_SIZE;
315   if (sb.st_size != size) {
316      if (ftruncate(fd, size) == -1)
317         goto path_fail;
318   }
319
320   /* We map this shared so that other processes see updates that we
321    * make.
322    *
323    * Note: We do use atomic addition to ensure that multiple
324    * processes don't scramble the cache size recorded in the
325    * index. But we don't use any locking to prevent multiple
326    * processes from updating the same entry simultaneously. The idea
327    * is that if either result lands entirely in the index, then
328    * that's equivalent to a well-ordered write followed by an
329    * eviction and a write. On the other hand, if the simultaneous
330    * writes result in a corrupt entry, that's not really any
331    * different than both entries being evicted, (since within the
332    * guarantees of the cryptographic hash, a corrupt entry is
333    * unlikely to ever match a real cache key).
334    */
335   cache->index_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE,
336                            MAP_SHARED, fd, 0);
337   if (cache->index_mmap == MAP_FAILED)
338      goto path_fail;
339   cache->index_mmap_size = size;
340
341   close(fd);
342
343   cache->size = (uint64_t *) cache->index_mmap;
344   cache->stored_keys = cache->index_mmap + sizeof(uint64_t);
345
346   max_size = 0;
347
348   max_size_str = getenv("MESA_GLSL_CACHE_MAX_SIZE");
349   if (max_size_str) {
350      char *end;
351      max_size = strtoul(max_size_str, &end, 10);
352      if (end == max_size_str) {
353         max_size = 0;
354      } else {
355         switch (*end) {
356         case 'K':
357         case 'k':
358            max_size *= 1024;
359            break;
360         case 'M':
361         case 'm':
362            max_size *= 1024*1024;
363            break;
364         case '\0':
365         case 'G':
366         case 'g':
367         default:
368            max_size *= 1024*1024*1024;
369            break;
370         }
371      }
372   }
373
374   /* Default to 1GB for maximum cache size. */
375   if (max_size == 0) {
376      max_size = 1024*1024*1024;
377   }
378
379   cache->max_size = max_size;
380
381   /* 1 thread was chosen because we don't really care about getting things
382    * to disk quickly just that it's not blocking other tasks.
383    *
384    * The queue will resize automatically when it's full, so adding new jobs
385    * doesn't stall.
386    */
387   util_queue_init(&cache->cache_queue, "disk$", 32, 1,
388                   UTIL_QUEUE_INIT_RESIZE_IF_FULL |
389                   UTIL_QUEUE_INIT_USE_MINIMUM_PRIORITY |
390                   UTIL_QUEUE_INIT_SET_FULL_THREAD_AFFINITY);
391
392   cache->path_init_failed = false;
393
394 path_fail:
395
396   cache->driver_keys_blob_size = cv_size;
397
398   /* Create driver id keys */
399   size_t id_size = strlen(driver_id) + 1;
400   size_t gpu_name_size = strlen(gpu_name) + 1;
401   cache->driver_keys_blob_size += id_size;
402   cache->driver_keys_blob_size += gpu_name_size;
403
404   /* We sometimes store entire structs that contains a pointers in the cache,
405    * use pointer size as a key to avoid hard to debug issues.
406    */
407   uint8_t ptr_size = sizeof(void *);
408   size_t ptr_size_size = sizeof(ptr_size);
409   cache->driver_keys_blob_size += ptr_size_size;
410
411   size_t driver_flags_size = sizeof(driver_flags);
412   cache->driver_keys_blob_size += driver_flags_size;
413
414   cache->driver_keys_blob =
415      ralloc_size(cache, cache->driver_keys_blob_size);
416   if (!cache->driver_keys_blob)
417      goto fail;
418
419   uint8_t *drv_key_blob = cache->driver_keys_blob;
420   DRV_KEY_CPY(drv_key_blob, &cache_version, cv_size)
421   DRV_KEY_CPY(drv_key_blob, driver_id, id_size)
422   DRV_KEY_CPY(drv_key_blob, gpu_name, gpu_name_size)
423   DRV_KEY_CPY(drv_key_blob, &ptr_size, ptr_size_size)
424   DRV_KEY_CPY(drv_key_blob, &driver_flags, driver_flags_size)
425
426   /* Seed our rand function */
427   s_rand_xorshift128plus(cache->seed_xorshift128plus, true);
428
429   ralloc_free(local);
430
431   return cache;
432
433 fail:
434   if (fd != -1)
435      close(fd);
436   if (cache)
437      ralloc_free(cache);
438   ralloc_free(local);
439
440   return NULL;
441}
442
443void
444disk_cache_destroy(struct disk_cache *cache)
445{
446   if (cache && !cache->path_init_failed) {
447      util_queue_destroy(&cache->cache_queue);
448      munmap(cache->index_mmap, cache->index_mmap_size);
449   }
450
451   ralloc_free(cache);
452}
453
454/* Return a filename within the cache's directory corresponding to 'key'. The
455 * returned filename is ralloced with 'cache' as the parent context.
456 *
457 * Returns NULL if out of memory.
458 */
459static char *
460get_cache_file(struct disk_cache *cache, const cache_key key)
461{
462   char buf[41];
463   char *filename;
464
465   if (cache->path_init_failed)
466      return NULL;
467
468   _mesa_sha1_format(buf, key);
469   if (asprintf(&filename, "%s/%c%c/%s", cache->path, buf[0],
470                buf[1], buf + 2) == -1)
471      return NULL;
472
473   return filename;
474}
475
476/* Create the directory that will be needed for the cache file for \key.
477 *
478 * Obviously, the implementation here must closely match
479 * _get_cache_file above.
480*/
481static void
482make_cache_file_directory(struct disk_cache *cache, const cache_key key)
483{
484   char *dir;
485   char buf[41];
486
487   _mesa_sha1_format(buf, key);
488   if (asprintf(&dir, "%s/%c%c", cache->path, buf[0], buf[1]) == -1)
489      return;
490
491   mkdir_if_needed(dir);
492   free(dir);
493}
494
495/* Given a directory path and predicate function, find the entry with
496 * the oldest access time in that directory for which the predicate
497 * returns true.
498 *
499 * Returns: A malloc'ed string for the path to the chosen file, (or
500 * NULL on any error). The caller should free the string when
501 * finished.
502 */
503static char *
504choose_lru_file_matching(const char *dir_path,
505                         bool (*predicate)(const char *dir_path,
506                                           const struct stat *,
507                                           const char *, const size_t))
508{
509   DIR *dir;
510   struct dirent *entry;
511   char *filename;
512   char *lru_name = NULL;
513   time_t lru_atime = 0;
514
515   dir = opendir(dir_path);
516   if (dir == NULL)
517      return NULL;
518
519   while (1) {
520      entry = readdir(dir);
521      if (entry == NULL)
522         break;
523
524      struct stat sb;
525      if (fstatat(dirfd(dir), entry->d_name, &sb, 0) == 0) {
526         if (!lru_atime || (sb.st_atime < lru_atime)) {
527            size_t len = strlen(entry->d_name);
528
529            if (!predicate(dir_path, &sb, entry->d_name, len))
530               continue;
531
532            char *tmp = realloc(lru_name, len + 1);
533            if (tmp) {
534               lru_name = tmp;
535               memcpy(lru_name, entry->d_name, len + 1);
536               lru_atime = sb.st_atime;
537            }
538         }
539      }
540   }
541
542   if (lru_name == NULL) {
543      closedir(dir);
544      return NULL;
545   }
546
547   if (asprintf(&filename, "%s/%s", dir_path, lru_name) < 0)
548      filename = NULL;
549
550   free(lru_name);
551   closedir(dir);
552
553   return filename;
554}
555
556/* Is entry a regular file, and not having a name with a trailing
557 * ".tmp"
558 */
559static bool
560is_regular_non_tmp_file(const char *path, const struct stat *sb,
561                        const char *d_name, const size_t len)
562{
563   if (!S_ISREG(sb->st_mode))
564      return false;
565
566   if (len >= 4 && strcmp(&d_name[len-4], ".tmp") == 0)
567      return false;
568
569   return true;
570}
571
572/* Returns the size of the deleted file, (or 0 on any error). */
573static size_t
574unlink_lru_file_from_directory(const char *path)
575{
576   struct stat sb;
577   char *filename;
578
579   filename = choose_lru_file_matching(path, is_regular_non_tmp_file);
580   if (filename == NULL)
581      return 0;
582
583   if (stat(filename, &sb) == -1) {
584      free (filename);
585      return 0;
586   }
587
588   unlink(filename);
589   free (filename);
590
591   return sb.st_blocks * 512;
592}
593
594/* Is entry a directory with a two-character name, (and not the
595 * special name of ".."). We also return false if the dir is empty.
596 */
597static bool
598is_two_character_sub_directory(const char *path, const struct stat *sb,
599                               const char *d_name, const size_t len)
600{
601   if (!S_ISDIR(sb->st_mode))
602      return false;
603
604   if (len != 2)
605      return false;
606
607   if (strcmp(d_name, "..") == 0)
608      return false;
609
610   char *subdir;
611   if (asprintf(&subdir, "%s/%s", path, d_name) == -1)
612      return false;
613   DIR *dir = opendir(subdir);
614   free(subdir);
615
616   if (dir == NULL)
617     return false;
618
619   unsigned subdir_entries = 0;
620   struct dirent *d;
621   while ((d = readdir(dir)) != NULL) {
622      if(++subdir_entries > 2)
623         break;
624   }
625   closedir(dir);
626
627   /* If dir only contains '.' and '..' it must be empty */
628   if (subdir_entries <= 2)
629      return false;
630
631   return true;
632}
633
634static void
635evict_lru_item(struct disk_cache *cache)
636{
637   char *dir_path;
638
639   /* With a reasonably-sized, full cache, (and with keys generated
640    * from a cryptographic hash), we can choose two random hex digits
641    * and reasonably expect the directory to exist with a file in it.
642    * Provides pseudo-LRU eviction to reduce checking all cache files.
643    */
644   uint64_t rand64 = rand_xorshift128plus(cache->seed_xorshift128plus);
645   if (asprintf(&dir_path, "%s/%02" PRIx64 , cache->path, rand64 & 0xff) < 0)
646      return;
647
648   size_t size = unlink_lru_file_from_directory(dir_path);
649
650   free(dir_path);
651
652   if (size) {
653      cache_size_adjust(cache->size, - (uint64_t)size);
654      return;
655   }
656
657   /* In the case where the random choice of directory didn't find
658    * something, we choose the least recently accessed from the
659    * existing directories.
660    *
661    * Really, the only reason this code exists is to allow the unit
662    * tests to work, (which use an artificially-small cache to be able
663    * to force a single cached item to be evicted).
664    */
665   dir_path = choose_lru_file_matching(cache->path,
666                                       is_two_character_sub_directory);
667   if (dir_path == NULL)
668      return;
669
670   size = unlink_lru_file_from_directory(dir_path);
671
672   free(dir_path);
673
674   if (size)
675      cache_size_adjust(cache->size, - (uint64_t)size);
676}
677
678void
679disk_cache_remove(struct disk_cache *cache, const cache_key key)
680{
681   struct stat sb;
682
683   char *filename = get_cache_file(cache, key);
684   if (filename == NULL) {
685      return;
686   }
687
688   if (stat(filename, &sb) == -1) {
689      free(filename);
690      return;
691   }
692
693   unlink(filename);
694   free(filename);
695
696   if (sb.st_blocks)
697      cache_size_adjust(cache->size, - (uint64_t)sb.st_blocks * 512);
698}
699
700static ssize_t
701read_all(int fd, void *buf, size_t count)
702{
703   char *in = buf;
704   ssize_t read_ret;
705   size_t done;
706
707   for (done = 0; done < count; done += read_ret) {
708      read_ret = read(fd, in + done, count - done);
709      if (read_ret == -1 || read_ret == 0)
710         return -1;
711   }
712   return done;
713}
714
715static ssize_t
716write_all(int fd, const void *buf, size_t count)
717{
718   const char *out = buf;
719   ssize_t written;
720   size_t done;
721
722   for (done = 0; done < count; done += written) {
723      written = write(fd, out + done, count - done);
724      if (written == -1)
725         return -1;
726   }
727   return done;
728}
729
730/* From the zlib docs:
731 *    "If the memory is available, buffers sizes on the order of 128K or 256K
732 *    bytes should be used."
733 */
734#define BUFSIZE 256 * 1024
735
736/**
737 * Compresses cache entry in memory and writes it to disk. Returns the size
738 * of the data written to disk.
739 */
740static size_t
741deflate_and_write_to_disk(const void *in_data, size_t in_data_size, int dest,
742                          const char *filename)
743{
744   unsigned char out[BUFSIZE];
745
746   /* allocate deflate state */
747   z_stream strm;
748   strm.zalloc = Z_NULL;
749   strm.zfree = Z_NULL;
750   strm.opaque = Z_NULL;
751   strm.next_in = (uint8_t *) in_data;
752   strm.avail_in = in_data_size;
753
754   int ret = deflateInit(&strm, Z_BEST_COMPRESSION);
755   if (ret != Z_OK)
756       return 0;
757
758   /* compress until end of in_data */
759   size_t compressed_size = 0;
760   int flush;
761   do {
762      int remaining = in_data_size - BUFSIZE;
763      flush = remaining > 0 ? Z_NO_FLUSH : Z_FINISH;
764      in_data_size -= BUFSIZE;
765
766      /* Run deflate() on input until the output buffer is not full (which
767       * means there is no more data to deflate).
768       */
769      do {
770         strm.avail_out = BUFSIZE;
771         strm.next_out = out;
772
773         ret = deflate(&strm, flush);    /* no bad return value */
774         assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
775
776         size_t have = BUFSIZE - strm.avail_out;
777         compressed_size += have;
778
779         ssize_t written = write_all(dest, out, have);
780         if (written == -1) {
781            (void)deflateEnd(&strm);
782            return 0;
783         }
784      } while (strm.avail_out == 0);
785
786      /* all input should be used */
787      assert(strm.avail_in == 0);
788
789   } while (flush != Z_FINISH);
790
791   /* stream should be complete */
792   assert(ret == Z_STREAM_END);
793
794   /* clean up and return */
795   (void)deflateEnd(&strm);
796   return compressed_size;
797}
798
799static struct disk_cache_put_job *
800create_put_job(struct disk_cache *cache, const cache_key key,
801               const void *data, size_t size,
802               struct cache_item_metadata *cache_item_metadata)
803{
804   struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *)
805      malloc(sizeof(struct disk_cache_put_job) + size);
806
807   if (dc_job) {
808      dc_job->cache = cache;
809      memcpy(dc_job->key, key, sizeof(cache_key));
810      dc_job->data = dc_job + 1;
811      memcpy(dc_job->data, data, size);
812      dc_job->size = size;
813
814      /* Copy the cache item metadata */
815      if (cache_item_metadata) {
816         dc_job->cache_item_metadata.type = cache_item_metadata->type;
817         if (cache_item_metadata->type == CACHE_ITEM_TYPE_GLSL) {
818            dc_job->cache_item_metadata.num_keys =
819               cache_item_metadata->num_keys;
820            dc_job->cache_item_metadata.keys = (cache_key *)
821               malloc(cache_item_metadata->num_keys * sizeof(cache_key));
822
823            if (!dc_job->cache_item_metadata.keys)
824               goto fail;
825
826            memcpy(dc_job->cache_item_metadata.keys,
827                   cache_item_metadata->keys,
828                   sizeof(cache_key) * cache_item_metadata->num_keys);
829         }
830      } else {
831         dc_job->cache_item_metadata.type = CACHE_ITEM_TYPE_UNKNOWN;
832         dc_job->cache_item_metadata.keys = NULL;
833      }
834   }
835
836   return dc_job;
837
838fail:
839   free(dc_job);
840
841   return NULL;
842}
843
844static void
845destroy_put_job(void *job, int thread_index)
846{
847   if (job) {
848      struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *) job;
849      free(dc_job->cache_item_metadata.keys);
850
851      free(job);
852   }
853}
854
855struct cache_entry_file_data {
856   uint32_t crc32;
857   uint32_t uncompressed_size;
858};
859
860static void
861cache_put(void *job, int thread_index)
862{
863   assert(job);
864
865   int fd = -1, fd_final = -1, err, ret;
866   unsigned i = 0;
867   char *filename = NULL, *filename_tmp = NULL;
868   struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *) job;
869
870   filename = get_cache_file(dc_job->cache, dc_job->key);
871   if (filename == NULL)
872      goto done;
873
874   /* If the cache is too large, evict something else first. */
875   while (*dc_job->cache->size + dc_job->size > dc_job->cache->max_size &&
876          i < 8) {
877      evict_lru_item(dc_job->cache);
878      i++;
879   }
880
881   /* Write to a temporary file to allow for an atomic rename to the
882    * final destination filename, (to prevent any readers from seeing
883    * a partially written file).
884    */
885   if (asprintf(&filename_tmp, "%s.tmp", filename) == -1)
886      goto done;
887
888   fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
889
890   /* Make the two-character subdirectory within the cache as needed. */
891   if (fd == -1) {
892      if (errno != ENOENT)
893         goto done;
894
895      make_cache_file_directory(dc_job->cache, dc_job->key);
896
897      fd = open(filename_tmp, O_WRONLY | O_CLOEXEC | O_CREAT, 0644);
898      if (fd == -1)
899         goto done;
900   }
901
902   /* With the temporary file open, we take an exclusive flock on
903    * it. If the flock fails, then another process still has the file
904    * open with the flock held. So just let that file be responsible
905    * for writing the file.
906    */
907   err = flock(fd, LOCK_EX | LOCK_NB);
908   if (err == -1)
909      goto done;
910
911   /* Now that we have the lock on the open temporary file, we can
912    * check to see if the destination file already exists. If so,
913    * another process won the race between when we saw that the file
914    * didn't exist and now. In this case, we don't do anything more,
915    * (to ensure the size accounting of the cache doesn't get off).
916    */
917   fd_final = open(filename, O_RDONLY | O_CLOEXEC);
918   if (fd_final != -1) {
919      unlink(filename_tmp);
920      goto done;
921   }
922
923   /* OK, we're now on the hook to write out a file that we know is
924    * not in the cache, and is also not being written out to the cache
925    * by some other process.
926    */
927
928   /* Write the driver_keys_blob, this can be used find information about the
929    * mesa version that produced the entry or deal with hash collisions,
930    * should that ever become a real problem.
931    */
932   ret = write_all(fd, dc_job->cache->driver_keys_blob,
933                   dc_job->cache->driver_keys_blob_size);
934   if (ret == -1) {
935      unlink(filename_tmp);
936      goto done;
937   }
938
939   /* Write the cache item metadata. This data can be used to deal with
940    * hash collisions, as well as providing useful information to 3rd party
941    * tools reading the cache files.
942    */
943   ret = write_all(fd, &dc_job->cache_item_metadata.type,
944                   sizeof(uint32_t));
945   if (ret == -1) {
946      unlink(filename_tmp);
947      goto done;
948   }
949
950   if (dc_job->cache_item_metadata.type == CACHE_ITEM_TYPE_GLSL) {
951      ret = write_all(fd, &dc_job->cache_item_metadata.num_keys,
952                      sizeof(uint32_t));
953      if (ret == -1) {
954         unlink(filename_tmp);
955         goto done;
956      }
957
958      ret = write_all(fd, dc_job->cache_item_metadata.keys[0],
959                      dc_job->cache_item_metadata.num_keys *
960                      sizeof(cache_key));
961      if (ret == -1) {
962         unlink(filename_tmp);
963         goto done;
964      }
965   }
966
967   /* Create CRC of the data. We will read this when restoring the cache and
968    * use it to check for corruption.
969    */
970   struct cache_entry_file_data cf_data;
971   cf_data.crc32 = util_hash_crc32(dc_job->data, dc_job->size);
972   cf_data.uncompressed_size = dc_job->size;
973
974   size_t cf_data_size = sizeof(cf_data);
975   ret = write_all(fd, &cf_data, cf_data_size);
976   if (ret == -1) {
977      unlink(filename_tmp);
978      goto done;
979   }
980
981   /* Now, finally, write out the contents to the temporary file, then
982    * rename them atomically to the destination filename, and also
983    * perform an atomic increment of the total cache size.
984    */
985   size_t file_size = deflate_and_write_to_disk(dc_job->data, dc_job->size,
986                                                fd, filename_tmp);
987   if (file_size == 0) {
988      unlink(filename_tmp);
989      goto done;
990   }
991   ret = rename(filename_tmp, filename);
992   if (ret == -1) {
993      unlink(filename_tmp);
994      goto done;
995   }
996
997   struct stat sb;
998   if (stat(filename, &sb) == -1) {
999      /* Something went wrong remove the file */
1000      unlink(filename);
1001      goto done;
1002   }
1003
1004   cache_size_adjust(dc_job->cache->size, sb.st_blocks * 512);
1005
1006 done:
1007   if (fd_final != -1)
1008      close(fd_final);
1009   /* This close finally releases the flock, (now that the final file
1010    * has been renamed into place and the size has been added).
1011    */
1012   if (fd != -1)
1013      close(fd);
1014   free(filename_tmp);
1015   free(filename);
1016}
1017
1018void
1019disk_cache_put(struct disk_cache *cache, const cache_key key,
1020               const void *data, size_t size,
1021               struct cache_item_metadata *cache_item_metadata)
1022{
1023   if (cache->blob_put_cb) {
1024      cache->blob_put_cb(key, CACHE_KEY_SIZE, data, size);
1025      return;
1026   }
1027
1028   if (cache->path_init_failed)
1029      return;
1030
1031   struct disk_cache_put_job *dc_job =
1032      create_put_job(cache, key, data, size, cache_item_metadata);
1033
1034   if (dc_job) {
1035      util_queue_fence_init(&dc_job->fence);
1036      util_queue_add_job(&cache->cache_queue, dc_job, &dc_job->fence,
1037                         cache_put, destroy_put_job);
1038   }
1039}
1040
1041/**
1042 * Decompresses cache entry, returns true if successful.
1043 */
1044static bool
1045inflate_cache_data(uint8_t *in_data, size_t in_data_size,
1046                   uint8_t *out_data, size_t out_data_size)
1047{
1048   z_stream strm;
1049
1050   /* allocate inflate state */
1051   strm.zalloc = Z_NULL;
1052   strm.zfree = Z_NULL;
1053   strm.opaque = Z_NULL;
1054   strm.next_in = in_data;
1055   strm.avail_in = in_data_size;
1056   strm.next_out = out_data;
1057   strm.avail_out = out_data_size;
1058
1059   int ret = inflateInit(&strm);
1060   if (ret != Z_OK)
1061      return false;
1062
1063   ret = inflate(&strm, Z_NO_FLUSH);
1064   assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
1065
1066   /* Unless there was an error we should have decompressed everything in one
1067    * go as we know the uncompressed file size.
1068    */
1069   if (ret != Z_STREAM_END) {
1070      (void)inflateEnd(&strm);
1071      return false;
1072   }
1073   assert(strm.avail_out == 0);
1074
1075   /* clean up and return */
1076   (void)inflateEnd(&strm);
1077   return true;
1078}
1079
1080void *
1081disk_cache_get(struct disk_cache *cache, const cache_key key, size_t *size)
1082{
1083   int fd = -1, ret;
1084   struct stat sb;
1085   char *filename = NULL;
1086   uint8_t *data = NULL;
1087   uint8_t *uncompressed_data = NULL;
1088   uint8_t *file_header = NULL;
1089
1090   if (size)
1091      *size = 0;
1092
1093   if (cache->blob_get_cb) {
1094      /* This is what Android EGL defines as the maxValueSize in egl_cache_t
1095       * class implementation.
1096       */
1097      const signed long max_blob_size = 64 * 1024;
1098      void *blob = malloc(max_blob_size);
1099      if (!blob)
1100         return NULL;
1101
1102      signed long bytes =
1103         cache->blob_get_cb(key, CACHE_KEY_SIZE, blob, max_blob_size);
1104
1105      if (!bytes) {
1106         free(blob);
1107         return NULL;
1108      }
1109
1110      if (size)
1111         *size = bytes;
1112      return blob;
1113   }
1114
1115   filename = get_cache_file(cache, key);
1116   if (filename == NULL)
1117      goto fail;
1118
1119   fd = open(filename, O_RDONLY | O_CLOEXEC);
1120   if (fd == -1)
1121      goto fail;
1122
1123   if (fstat(fd, &sb) == -1)
1124      goto fail;
1125
1126   data = malloc(sb.st_size);
1127   if (data == NULL)
1128      goto fail;
1129
1130   size_t ck_size = cache->driver_keys_blob_size;
1131   file_header = malloc(ck_size);
1132   if (!file_header)
1133      goto fail;
1134
1135   if (sb.st_size < ck_size)
1136      goto fail;
1137
1138   ret = read_all(fd, file_header, ck_size);
1139   if (ret == -1)
1140      goto fail;
1141
1142   /* Check for extremely unlikely hash collisions */
1143   if (memcmp(cache->driver_keys_blob, file_header, ck_size) != 0) {
1144      assert(!"Mesa cache keys mismatch!");
1145      goto fail;
1146   }
1147
1148   size_t cache_item_md_size = sizeof(uint32_t);
1149   uint32_t md_type;
1150   ret = read_all(fd, &md_type, cache_item_md_size);
1151   if (ret == -1)
1152      goto fail;
1153
1154   if (md_type == CACHE_ITEM_TYPE_GLSL) {
1155      uint32_t num_keys;
1156      cache_item_md_size += sizeof(uint32_t);
1157      ret = read_all(fd, &num_keys, sizeof(uint32_t));
1158      if (ret == -1)
1159         goto fail;
1160
1161      /* The cache item metadata is currently just used for distributing
1162       * precompiled shaders, they are not used by Mesa so just skip them for
1163       * now.
1164       * TODO: pass the metadata back to the caller and do some basic
1165       * validation.
1166       */
1167      cache_item_md_size += num_keys * sizeof(cache_key);
1168      ret = lseek(fd, num_keys * sizeof(cache_key), SEEK_CUR);
1169      if (ret == -1)
1170         goto fail;
1171   }
1172
1173   /* Load the CRC that was created when the file was written. */
1174   struct cache_entry_file_data cf_data;
1175   size_t cf_data_size = sizeof(cf_data);
1176   ret = read_all(fd, &cf_data, cf_data_size);
1177   if (ret == -1)
1178      goto fail;
1179
1180   /* Load the actual cache data. */
1181   size_t cache_data_size =
1182      sb.st_size - cf_data_size - ck_size - cache_item_md_size;
1183   ret = read_all(fd, data, cache_data_size);
1184   if (ret == -1)
1185      goto fail;
1186
1187   /* Uncompress the cache data */
1188   uncompressed_data = malloc(cf_data.uncompressed_size);
1189   if (!inflate_cache_data(data, cache_data_size, uncompressed_data,
1190                           cf_data.uncompressed_size))
1191      goto fail;
1192
1193   /* Check the data for corruption */
1194   if (cf_data.crc32 != util_hash_crc32(uncompressed_data,
1195                                        cf_data.uncompressed_size))
1196      goto fail;
1197
1198   free(data);
1199   free(filename);
1200   free(file_header);
1201   close(fd);
1202
1203   if (size)
1204      *size = cf_data.uncompressed_size;
1205
1206   return uncompressed_data;
1207
1208 fail:
1209   if (data)
1210      free(data);
1211   if (uncompressed_data)
1212      free(uncompressed_data);
1213   if (filename)
1214      free(filename);
1215   if (file_header)
1216      free(file_header);
1217   if (fd != -1)
1218      close(fd);
1219
1220   return NULL;
1221}
1222
1223void
1224disk_cache_put_key(struct disk_cache *cache, const cache_key key)
1225{
1226   const uint32_t *key_chunk = (const uint32_t *) key;
1227   int i = CPU_TO_LE32(*key_chunk) & CACHE_INDEX_KEY_MASK;
1228   unsigned char *entry;
1229
1230   if (cache->blob_put_cb) {
1231      cache->blob_put_cb(key, CACHE_KEY_SIZE, key_chunk, sizeof(uint32_t));
1232      return;
1233   }
1234
1235   if (cache->path_init_failed)
1236      return;
1237
1238   entry = &cache->stored_keys[i * CACHE_KEY_SIZE];
1239
1240   memcpy(entry, key, CACHE_KEY_SIZE);
1241}
1242
1243/* This function lets us test whether a given key was previously
1244 * stored in the cache with disk_cache_put_key(). The implement is
1245 * efficient by not using syscalls or hitting the disk. It's not
1246 * race-free, but the races are benign. If we race with someone else
1247 * calling disk_cache_put_key, then that's just an extra cache miss and an
1248 * extra recompile.
1249 */
1250bool
1251disk_cache_has_key(struct disk_cache *cache, const cache_key key)
1252{
1253   const uint32_t *key_chunk = (const uint32_t *) key;
1254   int i = CPU_TO_LE32(*key_chunk) & CACHE_INDEX_KEY_MASK;
1255   unsigned char *entry;
1256
1257   if (cache->blob_get_cb) {
1258      uint32_t blob;
1259      return cache->blob_get_cb(key, CACHE_KEY_SIZE, &blob, sizeof(uint32_t));
1260   }
1261
1262   if (cache->path_init_failed)
1263      return false;
1264
1265   entry = &cache->stored_keys[i * CACHE_KEY_SIZE];
1266
1267   return memcmp(entry, key, CACHE_KEY_SIZE) == 0;
1268}
1269
1270void
1271disk_cache_compute_key(struct disk_cache *cache, const void *data, size_t size,
1272                       cache_key key)
1273{
1274   struct mesa_sha1 ctx;
1275
1276   _mesa_sha1_init(&ctx);
1277   _mesa_sha1_update(&ctx, cache->driver_keys_blob,
1278                     cache->driver_keys_blob_size);
1279   _mesa_sha1_update(&ctx, data, size);
1280   _mesa_sha1_final(&ctx, key);
1281}
1282
1283void
1284disk_cache_set_callbacks(struct disk_cache *cache, disk_cache_put_cb put,
1285                         disk_cache_get_cb get)
1286{
1287   cache->blob_put_cb = put;
1288   cache->blob_get_cb = get;
1289}
1290
1291#endif /* ENABLE_SHADER_CACHE */
1292