spi-topcliff-pch: supports a spi mode setup and bit order setup by IO control
[zen-stable.git] / tools / perf / util / util.c
blobfb25d132921882c3b432ece1bc07bd2700800bc2
1 #include "../perf.h"
2 #include "util.h"
3 #include <sys/mman.h>
5 /*
6 * XXX We need to find a better place for these things...
7 */
8 bool perf_host = true;
9 bool perf_guest = false;
11 void event_attr_init(struct perf_event_attr *attr)
13 if (!perf_host)
14 attr->exclude_host = 1;
15 if (!perf_guest)
16 attr->exclude_guest = 1;
19 int mkdir_p(char *path, mode_t mode)
21 struct stat st;
22 int err;
23 char *d = path;
25 if (*d != '/')
26 return -1;
28 if (stat(path, &st) == 0)
29 return 0;
31 while (*++d == '/');
33 while ((d = strchr(d, '/'))) {
34 *d = '\0';
35 err = stat(path, &st) && mkdir(path, mode);
36 *d++ = '/';
37 if (err)
38 return -1;
39 while (*d == '/')
40 ++d;
42 return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
45 static int slow_copyfile(const char *from, const char *to)
47 int err = 0;
48 char *line = NULL;
49 size_t n;
50 FILE *from_fp = fopen(from, "r"), *to_fp;
52 if (from_fp == NULL)
53 goto out;
55 to_fp = fopen(to, "w");
56 if (to_fp == NULL)
57 goto out_fclose_from;
59 while (getline(&line, &n, from_fp) > 0)
60 if (fputs(line, to_fp) == EOF)
61 goto out_fclose_to;
62 err = 0;
63 out_fclose_to:
64 fclose(to_fp);
65 free(line);
66 out_fclose_from:
67 fclose(from_fp);
68 out:
69 return err;
72 int copyfile(const char *from, const char *to)
74 int fromfd, tofd;
75 struct stat st;
76 void *addr;
77 int err = -1;
79 if (stat(from, &st))
80 goto out;
82 if (st.st_size == 0) /* /proc? do it slowly... */
83 return slow_copyfile(from, to);
85 fromfd = open(from, O_RDONLY);
86 if (fromfd < 0)
87 goto out;
89 tofd = creat(to, 0755);
90 if (tofd < 0)
91 goto out_close_from;
93 addr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fromfd, 0);
94 if (addr == MAP_FAILED)
95 goto out_close_to;
97 if (write(tofd, addr, st.st_size) == st.st_size)
98 err = 0;
100 munmap(addr, st.st_size);
101 out_close_to:
102 close(tofd);
103 if (err)
104 unlink(to);
105 out_close_from:
106 close(fromfd);
107 out:
108 return err;
111 unsigned long convert_unit(unsigned long value, char *unit)
113 *unit = ' ';
115 if (value > 1000) {
116 value /= 1000;
117 *unit = 'K';
120 if (value > 1000) {
121 value /= 1000;
122 *unit = 'M';
125 if (value > 1000) {
126 value /= 1000;
127 *unit = 'G';
130 return value;
133 int readn(int fd, void *buf, size_t n)
135 void *buf_start = buf;
137 while (n) {
138 int ret = read(fd, buf, n);
140 if (ret <= 0)
141 return ret;
143 n -= ret;
144 buf += ret;
147 return buf - buf_start;