make intense use of const keyword
[monky] / src / top.c
1 /* Conky, a system monitor, based on torsmo
2  *
3  * Any original torsmo code is licensed under the BSD license
4  *
5  * All code written since the fork of torsmo is licensed under the GPL
6  *
7  * Please see COPYING for details
8  *
9  * Copyright (c) 2005 Adi Zaimi, Dan Piponi <dan@tanelorn.demon.co.uk>,
10  *                                        Dave Clark <clarkd@skynet.ca>
11  * Copyright (c) 2005-2007 Brenden Matthews, Philip Kovacs, et. al.
12  *      (see AUTHORS)
13  * All rights reserved.
14  *
15  * This program is free software: you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation, either version 3 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  *
27  * $Id$ */
28
29 #include "top.h"
30
31 static unsigned long g_time = 0;
32 static unsigned long long previous_total = 0;
33 static struct process *first_process = 0;
34
35 struct process *get_first_process(void)
36 {
37         return first_process;
38 }
39
40 void free_all_processes(void)
41 {
42         struct process *next = NULL, *pr = first_process;
43
44         while (pr) {
45                 next = pr->next;
46                 if (pr->name) {
47                         free(pr->name);
48                 }
49                 free(pr);
50                 pr = next;
51         }
52         first_process = NULL;
53 }
54
55 static struct process *find_process(pid_t pid)
56 {
57         struct process *p = first_process;
58
59         while (p) {
60                 if (p->pid == pid) {
61                         return p;
62                 }
63                 p = p->next;
64         }
65         return 0;
66 }
67
68 /* Create a new process object and insert it into the process list */
69 static struct process *new_process(int p)
70 {
71         struct process *process;
72         process = (struct process *) malloc(sizeof(struct process));
73
74         // clean up memory first
75         memset(process, 0, sizeof(struct process));
76
77         /* Do stitching necessary for doubly linked list */
78         process->name = 0;
79         process->previous = 0;
80         process->next = first_process;
81         if (process->next) {
82                 process->next->previous = process;
83         }
84         first_process = process;
85
86         process->pid = p;
87         process->time_stamp = 0;
88         process->previous_user_time = ULONG_MAX;
89         process->previous_kernel_time = ULONG_MAX;
90         process->counted = 1;
91
92         /* process_find_name(process); */
93
94         return process;
95 }
96
97 /******************************************
98  * Functions                                                      *
99  ******************************************/
100
101 /******************************************
102  * Extract information from /proc                 *
103  ******************************************/
104
105 /* These are the guts that extract information out of /proc.
106  * Anyone hoping to port wmtop should look here first. */
107 static int process_parse_stat(struct process *process)
108 {
109         struct information *cur;
110
111         cur = &info;
112         char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN], procname[BUFFER_LEN];
113         int ps;
114         unsigned long user_time = 0;
115         unsigned long kernel_time = 0;
116         int rc;
117         char *r, *q;
118         char deparenthesised_name[BUFFER_LEN];
119         int endl;
120         int nice_val;
121
122         snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid);
123
124         ps = open(filename, O_RDONLY);
125         if (ps < 0) {
126                 /* The process must have finished in the last few jiffies! */
127                 return 1;
128         }
129
130         /* Mark process as up-to-date. */
131         process->time_stamp = g_time;
132
133         rc = read(ps, line, sizeof(line));
134         close(ps);
135         if (rc < 0) {
136                 return 1;
137         }
138
139         /* Extract cpu times from data in /proc filesystem */
140         rc = sscanf(line, "%*s %s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu "
141                 "%lu %*s %*s %*s %d %*s %*s %*s %u %u", procname, &process->user_time,
142                 &process->kernel_time, &nice_val, &process->vsize, &process->rss);
143         if (rc < 5) {
144                 return 1;
145         }
146         /* Remove parentheses from the process name stored in /proc/ under Linux */
147         r = procname + 1;
148         /* remove any "kdeinit: " */
149         if (r == strstr(r, "kdeinit")) {
150                 snprintf(filename, sizeof(filename), PROCFS_CMDLINE_TEMPLATE,
151                         process->pid);
152
153                 ps = open(filename, O_RDONLY);
154                 if (ps < 0) {
155                         /* The process must have finished in the last few jiffies! */
156                         return 1;
157                 }
158
159                 endl = read(ps, line, sizeof(line));
160                 close(ps);
161
162                 /* null terminate the input */
163                 line[endl] = 0;
164                 /* account for "kdeinit: " */
165                 if ((char *) line == strstr(line, "kdeinit: ")) {
166                         r = ((char *) line) + 9;
167                 } else {
168                         r = (char *) line;
169                 }
170
171                 q = deparenthesised_name;
172                 /* stop at space */
173                 while (*r && *r != ' ') {
174                         *q++ = *r++;
175                 }
176                 *q = 0;
177         } else {
178                 q = deparenthesised_name;
179                 while (*r && *r != ')') {
180                         *q++ = *r++;
181                 }
182                 *q = 0;
183         }
184
185         if (process->name) {
186                 free(process->name);
187         }
188         process->name = strdup(deparenthesised_name);
189         process->rss *= getpagesize();
190
191         if (!cur->memmax) {
192                 update_total_processes();
193         }
194
195         process->total_cpu_time = process->user_time + process->kernel_time;
196         process->totalmem = (float) (((float) process->rss / cur->memmax) / 10);
197         if (process->previous_user_time == ULONG_MAX) {
198                 process->previous_user_time = process->user_time;
199         }
200         if (process->previous_kernel_time == ULONG_MAX) {
201                 process->previous_kernel_time = process->kernel_time;
202         }
203
204         /* store the difference of the user_time */
205         user_time = process->user_time - process->previous_user_time;
206         kernel_time = process->kernel_time - process->previous_kernel_time;
207
208         /* backup the process->user_time for next time around */
209         process->previous_user_time = process->user_time;
210         process->previous_kernel_time = process->kernel_time;
211
212         /* store only the difference of the user_time here... */
213         process->user_time = user_time;
214         process->kernel_time = kernel_time;
215
216         return 0;
217 }
218
219 /******************************************
220  * Get process structure for process pid  *
221  ******************************************/
222
223 /* This function seems to hog all of the CPU time.
224  * I can't figure out why - it doesn't do much. */
225 static int calculate_cpu(struct process *process)
226 {
227         int rc;
228
229         /* compute each process cpu usage by reading /proc/<proc#>/stat */
230         rc = process_parse_stat(process);
231         if (rc)
232                 return 1;
233         /* rc = process_parse_statm(process); if (rc) return 1; */
234
235         /*
236          * Check name against the exclusion list
237          */
238         /* if (process->counted && exclusion_expression &&
239          * !regexec(exclusion_expression, process->name, 0, 0, 0))
240          * process->counted = 0; */
241
242         return 0;
243 }
244
245 /******************************************
246  * Update process table                                   *
247  ******************************************/
248
249 static int update_process_table(void)
250 {
251         DIR *dir;
252         struct dirent *entry;
253
254         if (!(dir = opendir("/proc"))) {
255                 return 1;
256         }
257
258         ++g_time;
259
260         /* Get list of processes from /proc directory */
261         while ((entry = readdir(dir))) {
262                 pid_t pid;
263
264                 if (!entry) {
265                         /* Problem reading list of processes */
266                         closedir(dir);
267                         return 1;
268                 }
269
270                 if (sscanf(entry->d_name, "%d", &pid) > 0) {
271                         struct process *p;
272
273                         p = find_process(pid);
274                         if (!p) {
275                                 p = new_process(pid);
276                         }
277
278                         /* compute each process cpu usage */
279                         calculate_cpu(p);
280                 }
281         }
282
283         closedir(dir);
284
285         return 0;
286 }
287
288 /******************************************
289  * Destroy and remove a process           *
290  ******************************************/
291
292 static void delete_process(struct process *p)
293 {
294 #if defined(PARANOID)
295         assert(p->id == 0x0badfeed);
296
297         /*
298          * Ensure that deleted processes aren't reused.
299          */
300         p->id = 0x007babe;
301 #endif /* defined(PARANOID) */
302
303         /*
304          * Maintain doubly linked list.
305          */
306         if (p->next)
307                 p->next->previous = p->previous;
308         if (p->previous)
309                 p->previous->next = p->next;
310         else
311                 first_process = p->next;
312
313         if (p->name) {
314                 free(p->name);
315         }
316         free(p);
317 }
318
319 /******************************************
320  * Strip dead process entries                     *
321  ******************************************/
322
323 static void process_cleanup(void)
324 {
325
326         struct process *p = first_process;
327
328         while (p) {
329                 struct process *current = p;
330
331 #if defined(PARANOID)
332                 assert(p->id == 0x0badfeed);
333 #endif /* defined(PARANOID) */
334
335                 p = p->next;
336                 /* Delete processes that have died */
337                 if (current->time_stamp != g_time) {
338                         delete_process(current);
339                 }
340         }
341 }
342
343 /******************************************
344  * Calculate cpu total                                    *
345  ******************************************/
346 #define TMPL_SHORTPROC "%*s %llu %llu %llu %llu"
347 #define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
348
349 static unsigned long long calc_cpu_total(void)
350 {
351         unsigned long long total = 0;
352         unsigned long long t = 0;
353         int rc;
354         int ps;
355         char line[BUFFER_LEN] = { 0 };
356         unsigned long long cpu = 0;
357         unsigned long long nice = 0;
358         unsigned long long system = 0;
359         unsigned long long idle = 0;
360         unsigned long long iowait = 0;
361         unsigned long long irq = 0;
362         unsigned long long softirq = 0;
363         unsigned long long steal = 0;
364         const char *template =
365                 KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC;
366
367         ps = open("/proc/stat", O_RDONLY);
368         rc = read(ps, line, sizeof(line));
369         close(ps);
370         if (rc < 0) {
371                 return 0;
372         }
373
374         sscanf(line, template, &cpu, &nice, &system, &idle, &iowait, &irq,
375                 &softirq, &steal);
376         total = cpu + nice + system + idle + iowait + irq + softirq + steal;
377
378         t = total - previous_total;
379         previous_total = total;
380
381         return t;
382 }
383
384 /******************************************
385  * Calculate each processes cpu                   *
386  ******************************************/
387
388 inline static void calc_cpu_each(unsigned long long total)
389 {
390         struct process *p = first_process;
391
392         while (p) {
393                 p->amount = 100.0 * (cpu_separate ? info.cpu_count : 1) *
394                         (p->user_time + p->kernel_time) / (float) total;
395
396                 p = p->next;
397         }
398 }
399
400 /******************************************
401  * Find the top processes                                 *
402  ******************************************/
403
404 /* free a sp_process structure */
405 void free_sp(struct sorted_process *sp)
406 {
407         free(sp);
408 }
409
410 /* create a new sp_process structure */
411 struct sorted_process *malloc_sp(struct process *proc)
412 {
413         struct sorted_process *sp;
414         sp = malloc(sizeof(struct sorted_process));
415         sp->greater = NULL;
416         sp->less = NULL;
417         sp->proc = proc;
418         return sp;
419 }
420
421 /* cpu comparison function for insert_sp_element */
422 int compare_cpu(struct process *a, struct process *b)
423 {
424         if (a->amount < b->amount) {
425                 return 1;
426         } else if (a->amount > b->amount) {
427                 return -1;
428         } else {
429                 return 0;
430         }
431 }
432
433 /* mem comparison function for insert_sp_element */
434 int compare_mem(struct process *a, struct process *b)
435 {
436         if (a->totalmem < b->totalmem) {
437                 return 1;
438         } else if (a->totalmem > b->totalmem) {
439                 return -1;
440         } else {
441                 return 0;
442         }
443 }
444
445 /* insert this process into the list in a sorted fashion,
446  * or destroy it if it doesn't fit on the list */
447 int insert_sp_element(struct sorted_process *sp_cur,
448                 struct sorted_process **p_sp_head, struct sorted_process **p_sp_tail,
449                 int max_elements, int compare_funct(struct process *, struct process *))
450 {
451
452         struct sorted_process *sp_readthru = NULL, *sp_destroy = NULL;
453         int did_insert = 0, x = 0;
454
455         if (*p_sp_head == NULL) {
456                 *p_sp_head = sp_cur;
457                 *p_sp_tail = sp_cur;
458                 return 1;
459         }
460         for (sp_readthru = *p_sp_head, x = 0;
461                         sp_readthru != NULL && x < max_elements;
462                         sp_readthru = sp_readthru->less, x++) {
463                 if (compare_funct(sp_readthru->proc, sp_cur->proc) > 0 && !did_insert) {
464                         /* sp_cur is bigger than sp_readthru
465                          * so insert it before sp_readthru */
466                         sp_cur->less = sp_readthru;
467                         if (sp_readthru == *p_sp_head) {
468                                 /* insert as the new head of the list */
469                                 *p_sp_head = sp_cur;
470                         } else {
471                                 /* insert inside the list */
472                                 sp_readthru->greater->less = sp_cur;
473                                 sp_cur->greater = sp_readthru->greater;
474                         }
475                         sp_readthru->greater = sp_cur;
476                         /* element was inserted, so increase the counter */
477                         did_insert = ++x;
478                 }
479         }
480         if (x < max_elements && sp_readthru == NULL && !did_insert) {
481                 /* sp_cur is the smallest element and list isn't full,
482                  * so insert at the end */
483                 (*p_sp_tail)->less = sp_cur;
484                 sp_cur->greater = *p_sp_tail;
485                 *p_sp_tail = sp_cur;
486                 did_insert = x;
487         } else if (x >= max_elements) {
488                 /* We inserted an element and now the list is too big by one.
489                  * Destroy the smallest element */
490                 sp_destroy = *p_sp_tail;
491                 *p_sp_tail = sp_destroy->greater;
492                 (*p_sp_tail)->less = NULL;
493                 free_sp(sp_destroy);
494         }
495         if (!did_insert) {
496                 /* sp_cur wasn't added to the sorted list, so destroy it */
497                 free_sp(sp_cur);
498         }
499         return did_insert;
500 }
501
502 /* copy the procs in the sorted list to the array, and destroy the list */
503 void sp_acopy(struct sorted_process *sp_head, struct process **ar, int max_size)
504 {
505         struct sorted_process *sp_cur, *sp_tmp;
506         int x;
507
508         sp_cur = sp_head;
509         for (x = 0; x < max_size && sp_cur != NULL; x++) {
510                 ar[x] = sp_cur->proc;
511                 sp_tmp = sp_cur;
512                 sp_cur = sp_cur->less;
513                 free_sp(sp_tmp);
514         }
515 }
516
517 /* ****************************************************************** *
518  * Get a sorted list of the top cpu hogs and top mem hogs.                        *
519  * Results are stored in the cpu,mem arrays in decreasing order[0-9]. *
520  * ****************************************************************** */
521
522 inline void process_find_top(struct process **cpu, struct process **mem)
523 {
524         struct sorted_process *spc_head = NULL, *spc_tail = NULL, *spc_cur = NULL;
525         struct sorted_process *spm_head = NULL, *spm_tail = NULL, *spm_cur = NULL;
526         struct process *cur_proc = NULL;
527         unsigned long long total = 0;
528
529         if (!top_cpu && !top_mem) {
530                 return;
531         }
532
533         total = calc_cpu_total();       /* calculate the total of the processor */
534         update_process_table();         /* update the table with process list */
535         calc_cpu_each(total);           /* and then the percentage for each task */
536         process_cleanup();                      /* cleanup list from exited processes */
537
538         cur_proc = first_process;
539
540         while (cur_proc != NULL) {
541                 if (top_cpu) {
542                         spc_cur = malloc_sp(cur_proc);
543                         insert_sp_element(spc_cur, &spc_head, &spc_tail, MAX_SP,
544                                 &compare_cpu);
545                 }
546                 if (top_mem) {
547                         spm_cur = malloc_sp(cur_proc);
548                         insert_sp_element(spm_cur, &spm_head, &spm_tail, MAX_SP,
549                                 &compare_mem);
550                 }
551                 cur_proc = cur_proc->next;
552         }
553         sp_acopy(spc_head, cpu, MAX_SP);
554         sp_acopy(spm_head, mem, MAX_SP);
555 }