1 /*
2  * Copyright © 2013 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 
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <string.h>
30 #include <errno.h>
31 
32 #include "cpu-top.h"
33 
cpu_top_init(struct cpu_top * cpu)34 int cpu_top_init(struct cpu_top *cpu)
35 {
36 	memset(cpu, 0, sizeof(*cpu));
37 
38 	cpu->nr_cpu = sysconf(_SC_NPROCESSORS_ONLN);
39 
40 	return 0;
41 }
42 
cpu_top_update(struct cpu_top * cpu)43 int cpu_top_update(struct cpu_top *cpu)
44 {
45 	struct cpu_stat *s = &cpu->stat[cpu->count++&1];
46 	struct cpu_stat *d = &cpu->stat[cpu->count&1];
47 	uint64_t d_total, d_idle;
48 	char buf[4096], *b;
49 	int fd, len = -1;
50 
51 	fd = open("/proc/stat", 0);
52 	if (fd < 0)
53 		return errno;
54 
55 	len = read(fd, buf, sizeof(buf)-1);
56 	close(fd);
57 
58 	if (len < 0)
59 		return EIO;
60 	buf[len] = '\0';
61 
62 #ifdef __x86_64__
63 	sscanf(buf, "cpu %lu %lu %lu %lu",
64 	       &s->user, &s->nice, &s->sys, &s->idle);
65 #else
66 	sscanf(buf, "cpu %llu %llu %llu %llu",
67 	       &s->user, &s->nice, &s->sys, &s->idle);
68 #endif
69 
70 	b = strstr(buf, "procs_running");
71 	if (b)
72 		cpu->nr_running = atoi(b+sizeof("procs_running")) - 1;
73 
74 	s->total = s->user + s->nice + s->sys + s->idle;
75 	if (cpu->count == 1)
76 		return EAGAIN;
77 
78 	d_total = s->total - d->total;
79 	d_idle = s->idle - d->idle;
80 	cpu->busy = 100 - 100 * d_idle / d_total;
81 
82 	return 0;
83 }
84