• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* vmstat.c - Report virtual memory statistics.
2  *
3  * Copyright 2012 Elie De Brauwer <eliedebrauwer@gmail.com>
4  *
5  * TODO: I have no idea how "system" category is calculated.
6  * whatever we're doing isn't matching what other implementations are doing.
7 
8 USE_VMSTAT(NEWTOY(vmstat, ">2n", TOYFLAG_BIN))
9 
10 config VMSTAT
11   bool "vmstat"
12   default y
13   help
14     usage: vmstat [-n] [DELAY [COUNT]]
15 
16     Print virtual memory statistics, repeating each DELAY seconds, COUNT times.
17     (With no DELAY, prints one line. With no COUNT, repeats until killed.)
18 
19     Show processes running and blocked, kilobytes swapped, free, buffered, and
20     cached, kilobytes swapped in and out per second, file disk blocks input and
21     output per second, interrupts and context switches per second, percent
22     of CPU time spent running user code, system code, idle, and awaiting I/O.
23     First line is since system started, later lines are since last line.
24 
25     -n	Display the header only once
26 */
27 
28 #define FOR_vmstat
29 #include "toys.h"
30 
31 struct vmstat_proc {
32   // From /proc/stat (jiffies)
33   uint64_t user, nice, sys, idle, wait, irq, sirq, intr, ctxt, running, blocked;
34   // From /proc/meminfo (units are kb)
35   uint64_t memfree, buffers, cached, swapfree, swaptotal;
36   // From /proc/vmstat (units are kb)
37   uint64_t io_in, io_out;
38   // From /proc/vmstat (units are pages)
39   uint64_t swap_in, swap_out;
40 };
41 
42 // All the elements of vmstat_proc are the same size, so we can populate it as
43 // a big array, then read the elements back out by name
get_vmstat_proc(struct vmstat_proc * vmstat_proc)44 static void get_vmstat_proc(struct vmstat_proc *vmstat_proc)
45 {
46   char *vmstuff[] = { "/proc/stat", "cpu ", 0, 0, 0, 0, 0, 0,
47     "intr ", "ctxt ", "procs_running ", "procs_blocked ", "/proc/meminfo",
48     "MemFree: ", "Buffers: ", "Cached: ", "SwapFree: ", "SwapTotal: ",
49     "/proc/vmstat", "pgpgin ", "pgpgout ", "pswpin ", "pswpout " };
50   uint64_t *new = (uint64_t *)vmstat_proc;
51   char *p = p, *name = name, *file = NULL;
52   int i, j;
53 
54   // We use vmstuff to fill out vmstat_proc as an array of uint64_t:
55   //   Strings starting with / are the file to find next entries in
56   //   Any other string is a key to search for, with decimal value right after
57   //   0 means parse another value on same line as last key
58 
59   for (i = 0; i<ARRAY_LEN(vmstuff); i++) {
60     if (!vmstuff[i]) p++;
61     else if (*vmstuff[i] == '/') {
62       // /proc/stat for a 48-core machine doesn't fit in toybuf.
63       free(file);
64       file = xreadfile(name = vmstuff[i], 0, 0);
65 
66       continue;
67     } else p = strafter(file, vmstuff[i]);
68     if (!p || 1!=sscanf(p, "%"PRIu64"%n", new++, &j))
69       error_exit("Bad %sin %s: %s", vmstuff[i], name, p ? p : "");
70     p += j;
71   }
72   free(file);
73 }
74 
vmstat_main(void)75 void vmstat_main(void)
76 {
77   struct vmstat_proc top[2];
78   int i, loop_delay = 0, loop_max = 0;
79   unsigned loop, rows = 25, page_kb = sysconf(_SC_PAGESIZE)/1024;
80   char *headers="r\0b\0swpd\0free\0buff\0cache\0si\0so\0bi\0bo\0in\0cs\0us\0"
81                 "sy\0id\0wa", lengths[] = {2,2,6,6,6,6,4,4,5,5,4,4,2,2,2,2};
82 
83   memset(top, 0, sizeof(top));
84   if (toys.optc) loop_delay = atolx_range(toys.optargs[0], 0, INT_MAX);
85   if (toys.optc > 1) loop_max = atolx_range(toys.optargs[1], 1, INT_MAX);
86 
87   for (loop = 0; !loop_max || loop < loop_max; loop++) {
88     unsigned idx = loop&1, offset = 0, expected = 0;
89     uint64_t units, total_hz, *ptr = (uint64_t *)(top+idx),
90              *oldptr = (uint64_t *)(top+!idx);
91 
92     if (loop && loop_delay) sleep(loop_delay);
93 
94     // Print headers
95     if (rows>3 && !(loop % (rows-3))) {
96       char *header = headers;
97 
98       if (!(toys.optflags&FLAG_n) && isatty(1)) terminal_size(0, &rows);
99       else rows = 0;
100 
101       printf("procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----\n");
102       for (i=0; i<sizeof(lengths); i++) {
103         printf(" %*s"+!i, lengths[i], header);
104         header += strlen(header)+1;
105       }
106       xputc('\n');
107     }
108 
109     // Read data and combine some fields we display as aggregates
110     get_vmstat_proc(top+idx);
111     top[idx].running--; // Don't include ourselves
112     top[idx].user += top[idx].nice;
113     top[idx].sys += top[idx].irq + top[idx].sirq;
114     top[idx].swaptotal -= top[idx].swapfree;
115 
116     // Collect unit adjustments (outside the inner loop to save time)
117 
118     if (!loop) {
119       char *s = toybuf;
120 
121       xreadfile("/proc/uptime", toybuf, sizeof(toybuf));
122       while (*(s++) > ' ');
123       sscanf(s, "%"PRIu64, &units);
124     } else units = loop_delay;
125 
126     // add up user, sys, idle, and wait time used since last time
127     // (Already appended nice to user)
128     total_hz = 0;
129     for (i=0; i<4; i++) total_hz += ptr[i+!!i] - oldptr[i+!!i];
130 
131     // Output values in order[]: running, blocked, swaptotal, memfree, buffers,
132     // cache, swap_in, swap_out, io_in, io_out, sirq, ctxt, user, sys, idle,wait
133 
134     for (i=0; i<sizeof(lengths); i++) {
135       char order[] = {9, 10, 15, 11, 12, 13, 18, 19, 16, 17, 6, 8, 0, 2, 3, 4};
136       uint64_t out = ptr[order[i]];
137       int len;
138 
139       // Adjust rate and units
140       if (i>5) out -= oldptr[order[i]];
141       if (order[i]<7) out = ((out*100) + (total_hz/2)) / total_hz;
142       else if (order[i]>17) out = ((out * page_kb)+(units-1))/units;
143       else if (order[i]>15) out = ((out)+(units-1))/units;
144       else if (order[i]<9) out = (out+(units-1)) / units;
145 
146       // If a field was too big to fit in its slot, try to compensate later
147       expected += lengths[i] + !!i;
148       len = expected - offset - !!i;
149       if (len < 0) len = 0;
150       offset += printf(" %*"PRIu64+!i, len, out);
151     }
152     xputc('\n');
153 
154     if (!loop_delay) break;
155   }
156 }
157