aboutsummaryrefslogtreecommitdiffstats
path: root/tools/perf/util/fncache.c
blob: 6225cbc523101313c3faa7f645d2d670abbad597 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// SPDX-License-Identifier: GPL-2.0-only
/* Manage a cache of file names' existence */
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <linux/list.h>
#include "fncache.h"

struct fncache {
	struct hlist_node nd;
	bool res;
	char name[];
};

#define FNHSIZE 61

static struct hlist_head fncache_hash[FNHSIZE];

unsigned shash(const unsigned char *s)
{
	unsigned h = 0;
	while (*s)
		h = 65599 * h + *s++;
	return h ^ (h >> 16);
}

static bool lookup_fncache(const char *name, bool *res)
{
	int h = shash((const unsigned char *)name) % FNHSIZE;
	struct fncache *n;

	hlist_for_each_entry(n, &fncache_hash[h], nd) {
		if (!strcmp(n->name, name)) {
			*res = n->res;
			return true;
		}
	}
	return false;
}

static void update_fncache(const char *name, bool res)
{
	struct fncache *n = malloc(sizeof(struct fncache) + strlen(name) + 1);
	int h = shash((const unsigned char *)name) % FNHSIZE;

	if (!n)
		return;
	strcpy(n->name, name);
	n->res = res;
	hlist_add_head(&n->nd, &fncache_hash[h]);
}

/* No LRU, only use when bounded in some other way. */
bool file_available(const char *name)
{
	bool res;

	if (lookup_fncache(name, &res))
		return res;
	res = access(name, R_OK) == 0;
	update_fncache(name, res);
	return res;
}