1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
2 * vim: ts=4 sw=4 noet ai cindent syntax=c
4 * Conky, a system monitor, based on torsmo
6 * Any original torsmo code is licensed under the BSD license
8 * All code written since the fork of torsmo is licensed under the GPL
10 * Please see COPYING for details
12 * Copyright (c) 2005 Adi Zaimi, Dan Piponi <dan@tanelorn.demon.co.uk>,
13 * Dave Clark <clarkd@skynet.ca>
14 * Copyright (c) 2005-2009 Brenden Matthews, Philip Kovacs, et. al.
16 * All rights reserved.
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 static unsigned long g_time = 0;
36 static unsigned long long previous_total = 0;
37 static struct process *first_process = 0;
39 /* a simple hash table to speed up find_process() */
40 struct proc_hash_entry {
41 struct proc_hash_entry *next;
44 static struct proc_hash_entry proc_hash_table[256];
46 static void hash_process(struct process *p)
48 struct proc_hash_entry *phe;
49 static char first_run = 1;
51 /* better make sure all next pointers are zero upon first access */
53 memset(proc_hash_table, 0, sizeof(struct proc_hash_entry) * 256);
57 /* get the bucket head */
58 phe = &proc_hash_table[p->pid % 256];
60 /* find the bucket's end */
65 phe->next = malloc(sizeof(struct proc_hash_entry));
66 memset(phe->next, 0, sizeof(struct proc_hash_entry));
70 static void unhash_process(struct process *p)
72 struct proc_hash_entry *phe, *tmp;
74 /* get the bucket head */
75 phe = &proc_hash_table[p->pid % 256];
77 /* find the entry pointing to p and drop it */
79 if (phe->next->proc == p) {
81 phe->next = phe->next->next;
89 static void __unhash_all_processes(struct proc_hash_entry *phe)
92 __unhash_all_processes(phe->next);
96 static void unhash_all_processes(void)
100 for (i = 0; i < 256; i++) {
101 __unhash_all_processes(&proc_hash_table[i]);
102 proc_hash_table[i].next = NULL;
106 struct process *get_first_process(void)
108 return first_process;
111 void free_all_processes(void)
113 struct process *next = NULL, *pr = first_process;
123 first_process = NULL;
125 /* drop the whole hash table */
126 unhash_all_processes();
129 struct process *get_process_by_name(const char *name)
131 struct process *p = first_process;
134 if (!strcmp(p->name, name))
141 static struct process *find_process(pid_t pid)
143 struct proc_hash_entry *phe;
145 phe = &proc_hash_table[pid % 256];
147 if (phe->next->proc->pid == pid)
148 return phe->next->proc;
154 /* Create a new process object and insert it into the process list */
155 static struct process *new_process(int p)
157 struct process *process;
158 process = (struct process *) malloc(sizeof(struct process));
160 // clean up memory first
161 memset(process, 0, sizeof(struct process));
163 /* Do stitching necessary for doubly linked list */
165 process->previous = 0;
166 process->next = first_process;
168 process->next->previous = process;
170 first_process = process;
173 process->time_stamp = 0;
174 process->previous_user_time = ULONG_MAX;
175 process->previous_kernel_time = ULONG_MAX;
177 process->previous_read_bytes = ULLONG_MAX;
178 process->previous_write_bytes = ULLONG_MAX;
180 process->counted = 1;
182 /* process_find_name(process); */
184 /* add the process to the hash table */
185 hash_process(process);
190 /******************************************
192 ******************************************/
194 /******************************************
195 * Extract information from /proc *
196 ******************************************/
198 /* These are the guts that extract information out of /proc.
199 * Anyone hoping to port wmtop should look here first. */
200 static int process_parse_stat(struct process *process)
202 char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN], procname[BUFFER_LEN];
204 unsigned long user_time = 0;
205 unsigned long kernel_time = 0;
210 char *lparen, *rparen;
212 snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid);
214 ps = open(filename, O_RDONLY);
216 /* The process must have finished in the last few jiffies! */
220 /* Mark process as up-to-date. */
221 process->time_stamp = g_time;
223 rc = read(ps, line, sizeof(line));
229 /* Extract cpu times from data in /proc filesystem */
230 lparen = strchr(line, '(');
231 rparen = strrchr(line, ')');
232 if(!lparen || !rparen || rparen < lparen)
233 return 1; // this should not happen
235 rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1);
236 strncpy(procname, lparen + 1, rc);
238 rc = sscanf(rparen + 1, "%*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu "
239 "%lu %*s %*s %*s %d %*s %*s %*s %u %u", &process->user_time,
240 &process->kernel_time, &nice_val, &process->vsize, &process->rss);
242 NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc);
245 /* remove any "kdeinit: " */
246 if (procname == strstr(procname, "kdeinit")) {
247 snprintf(filename, sizeof(filename), PROCFS_CMDLINE_TEMPLATE,
250 ps = open(filename, O_RDONLY);
252 /* The process must have finished in the last few jiffies! */
256 endl = read(ps, line, sizeof(line));
259 /* null terminate the input */
261 /* account for "kdeinit: " */
262 if ((char *) line == strstr(line, "kdeinit: ")) {
263 r = ((char *) line) + 9;
270 while (*r && *r != ' ') {
279 process->name = strndup(procname, text_buffer_size);
280 process->rss *= getpagesize();
282 process->total_cpu_time = process->user_time + process->kernel_time;
283 if (process->previous_user_time == ULONG_MAX) {
284 process->previous_user_time = process->user_time;
286 if (process->previous_kernel_time == ULONG_MAX) {
287 process->previous_kernel_time = process->kernel_time;
290 /* strangely, the values aren't monotonous */
291 if (process->previous_user_time > process->user_time)
292 process->previous_user_time = process->user_time;
294 if (process->previous_kernel_time > process->kernel_time)
295 process->previous_kernel_time = process->kernel_time;
297 /* store the difference of the user_time */
298 user_time = process->user_time - process->previous_user_time;
299 kernel_time = process->kernel_time - process->previous_kernel_time;
301 /* backup the process->user_time for next time around */
302 process->previous_user_time = process->user_time;
303 process->previous_kernel_time = process->kernel_time;
305 /* store only the difference of the user_time here... */
306 process->user_time = user_time;
307 process->kernel_time = kernel_time;
313 static int process_parse_io(struct process *process)
315 static const char *read_bytes_str="read_bytes:";
316 static const char *write_bytes_str="write_bytes:";
318 char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN];
322 unsigned long long read_bytes, write_bytes;
324 snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid);
326 ps = open(filename, O_RDONLY);
328 /* The process must have finished in the last few jiffies!
329 * Or, the kernel doesn't support I/O accounting.
334 rc = read(ps, line, sizeof(line));
340 pos = strstr(line, read_bytes_str);
342 /* these should not happen (unless the format of the file changes) */
345 pos += strlen(read_bytes_str);
346 process->read_bytes = strtoull(pos, &endpos, 10);
351 pos = strstr(line, write_bytes_str);
355 pos += strlen(write_bytes_str);
356 process->write_bytes = strtoull(pos, &endpos, 10);
361 if (process->previous_read_bytes == ULLONG_MAX) {
362 process->previous_read_bytes = process->read_bytes;
364 if (process->previous_write_bytes == ULLONG_MAX) {
365 process->previous_write_bytes = process->write_bytes;
368 /* store the difference of the byte counts */
369 read_bytes = process->read_bytes - process->previous_read_bytes;
370 write_bytes = process->write_bytes - process->previous_write_bytes;
372 /* backup the counts for next time around */
373 process->previous_read_bytes = process->read_bytes;
374 process->previous_write_bytes = process->write_bytes;
376 /* store only the difference here... */
377 process->read_bytes = read_bytes;
378 process->write_bytes = write_bytes;
384 /******************************************
385 * Get process structure for process pid *
386 ******************************************/
388 /* This function seems to hog all of the CPU time.
389 * I can't figure out why - it doesn't do much. */
390 static int calculate_stats(struct process *process)
394 /* compute each process cpu usage by reading /proc/<proc#>/stat */
395 rc = process_parse_stat(process);
397 /* rc = process_parse_statm(process); if (rc) return 1; */
400 rc = process_parse_io(process);
405 * Check name against the exclusion list
407 /* if (process->counted && exclusion_expression &&
408 * !regexec(exclusion_expression, process->name, 0, 0, 0))
409 * process->counted = 0; */
414 /******************************************
415 * Update process table *
416 ******************************************/
418 static int update_process_table(void)
421 struct dirent *entry;
423 if (!(dir = opendir("/proc"))) {
429 /* Get list of processes from /proc directory */
430 while ((entry = readdir(dir))) {
434 /* Problem reading list of processes */
439 if (sscanf(entry->d_name, "%d", &pid) > 0) {
442 p = find_process(pid);
444 p = new_process(pid);
447 /* compute each process cpu usage */
457 /******************************************
458 * Destroy and remove a process *
459 ******************************************/
461 static void delete_process(struct process *p)
463 #if defined(PARANOID)
464 assert(p->id == 0x0badfeed);
467 * Ensure that deleted processes aren't reused.
470 #endif /* defined(PARANOID) */
473 * Maintain doubly linked list.
476 p->next->previous = p->previous;
478 p->previous->next = p->next;
480 first_process = p->next;
485 /* remove the process from the hash table */
490 /******************************************
491 * Strip dead process entries *
492 ******************************************/
494 static void process_cleanup(void)
497 struct process *p = first_process;
500 struct process *current = p;
502 #if defined(PARANOID)
503 assert(p->id == 0x0badfeed);
504 #endif /* defined(PARANOID) */
507 /* Delete processes that have died */
508 if (current->time_stamp != g_time) {
509 delete_process(current);
514 /******************************************
515 * Calculate cpu total *
516 ******************************************/
517 #define TMPL_SHORTPROC "%*s %llu %llu %llu %llu"
518 #define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
520 static unsigned long long calc_cpu_total(void)
522 unsigned long long total = 0;
523 unsigned long long t = 0;
526 char line[BUFFER_LEN] = { 0 };
527 unsigned long long cpu = 0;
528 unsigned long long niceval = 0;
529 unsigned long long systemval = 0;
530 unsigned long long idle = 0;
531 unsigned long long iowait = 0;
532 unsigned long long irq = 0;
533 unsigned long long softirq = 0;
534 unsigned long long steal = 0;
535 const char *template =
536 KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC;
538 ps = open("/proc/stat", O_RDONLY);
539 rc = read(ps, line, sizeof(line));
545 sscanf(line, template, &cpu, &niceval, &systemval, &idle, &iowait, &irq,
547 total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal;
549 t = total - previous_total;
550 previous_total = total;
555 /******************************************
556 * Calculate each processes cpu *
557 ******************************************/
559 inline static void calc_cpu_each(unsigned long long total)
561 struct process *p = first_process;
564 p->amount = 100.0 * (cpu_separate ? info.cpu_count : 1) *
565 (p->user_time + p->kernel_time) / (float) total;
572 static void calc_io_each(void)
575 unsigned long long sum = 0;
577 for (p = first_process; p; p = p->next)
578 sum += p->read_bytes + p->write_bytes;
581 sum = 1; /* to avoid having NANs if no I/O occured */
582 for (p = first_process; p; p = p->next)
583 p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float) sum;
587 /******************************************
588 * Find the top processes *
589 ******************************************/
591 /* free a sp_process structure */
592 static void free_sp(struct sorted_process *sp)
597 /* create a new sp_process structure */
598 static struct sorted_process *malloc_sp(struct process *proc)
600 struct sorted_process *sp;
601 sp = malloc(sizeof(struct sorted_process));
602 memset(sp, 0, sizeof(struct sorted_process));
607 /* cpu comparison function for insert_sp_element */
608 static int compare_cpu(struct process *a, struct process *b)
610 if (a->amount < b->amount) {
612 } else if (a->amount > b->amount) {
619 /* mem comparison function for insert_sp_element */
620 static int compare_mem(struct process *a, struct process *b)
622 if (a->rss < b->rss) {
624 } else if (a->rss > b->rss) {
631 /* CPU time comparision function for insert_sp_element */
632 static int compare_time(struct process *a, struct process *b)
634 return b->total_cpu_time - a->total_cpu_time;
638 /* I/O comparision function for insert_sp_element */
639 static int compare_io(struct process *a, struct process *b)
641 if (a->io_perc < b->io_perc) {
643 } else if (a->io_perc > b->io_perc) {
651 /* insert this process into the list in a sorted fashion,
652 * or destroy it if it doesn't fit on the list */
653 static int insert_sp_element(struct sorted_process *sp_cur,
654 struct sorted_process **p_sp_head, struct sorted_process **p_sp_tail,
655 int max_elements, int compare_funct(struct process *, struct process *))
658 struct sorted_process *sp_readthru = NULL, *sp_destroy = NULL;
659 int did_insert = 0, x = 0;
661 if (*p_sp_head == NULL) {
666 for (sp_readthru = *p_sp_head, x = 0;
667 sp_readthru != NULL && x < max_elements;
668 sp_readthru = sp_readthru->less, x++) {
669 if (compare_funct(sp_readthru->proc, sp_cur->proc) > 0 && !did_insert) {
670 /* sp_cur is bigger than sp_readthru
671 * so insert it before sp_readthru */
672 sp_cur->less = sp_readthru;
673 if (sp_readthru == *p_sp_head) {
674 /* insert as the new head of the list */
677 /* insert inside the list */
678 sp_readthru->greater->less = sp_cur;
679 sp_cur->greater = sp_readthru->greater;
681 sp_readthru->greater = sp_cur;
682 /* element was inserted, so increase the counter */
686 if (x < max_elements && sp_readthru == NULL && !did_insert) {
687 /* sp_cur is the smallest element and list isn't full,
688 * so insert at the end */
689 (*p_sp_tail)->less = sp_cur;
690 sp_cur->greater = *p_sp_tail;
693 } else if (x >= max_elements) {
694 /* We inserted an element and now the list is too big by one.
695 * Destroy the smallest element */
696 sp_destroy = *p_sp_tail;
697 *p_sp_tail = sp_destroy->greater;
698 (*p_sp_tail)->less = NULL;
702 /* sp_cur wasn't added to the sorted list, so destroy it */
708 /* copy the procs in the sorted list to the array, and destroy the list */
709 static void sp_acopy(struct sorted_process *sp_head, struct process **ar, int max_size)
711 struct sorted_process *sp_cur, *sp_tmp;
715 for (x = 0; x < max_size && sp_cur != NULL; x++) {
716 ar[x] = sp_cur->proc;
718 sp_cur = sp_cur->less;
723 /* ****************************************************************** *
724 * Get a sorted list of the top cpu hogs and top mem hogs. *
725 * Results are stored in the cpu,mem arrays in decreasing order[0-9]. *
726 * ****************************************************************** */
728 void process_find_top(struct process **cpu, struct process **mem,
729 struct process **ptime
731 , struct process **io
735 struct sorted_process *spc_head = NULL, *spc_tail = NULL, *spc_cur = NULL;
736 struct sorted_process *spm_head = NULL, *spm_tail = NULL, *spm_cur = NULL;
737 struct sorted_process *spt_head = NULL, *spt_tail = NULL, *spt_cur = NULL;
739 struct sorted_process *spi_head = NULL, *spi_tail = NULL, *spi_cur = NULL;
741 struct process *cur_proc = NULL;
742 unsigned long long total = 0;
744 if (!top_cpu && !top_mem && !top_time
753 total = calc_cpu_total(); /* calculate the total of the processor */
754 update_process_table(); /* update the table with process list */
755 calc_cpu_each(total); /* and then the percentage for each task */
756 process_cleanup(); /* cleanup list from exited processes */
758 calc_io_each(); /* percentage of I/O for each task */
761 cur_proc = first_process;
763 while (cur_proc != NULL) {
765 spc_cur = malloc_sp(cur_proc);
766 insert_sp_element(spc_cur, &spc_head, &spc_tail, MAX_SP,
770 spm_cur = malloc_sp(cur_proc);
771 insert_sp_element(spm_cur, &spm_head, &spm_tail, MAX_SP,
775 spt_cur = malloc_sp(cur_proc);
776 insert_sp_element(spt_cur, &spt_head, &spt_tail, MAX_SP,
781 spi_cur = malloc_sp(cur_proc);
782 insert_sp_element(spi_cur, &spi_head, &spi_tail, MAX_SP,
786 cur_proc = cur_proc->next;
789 if (top_cpu) sp_acopy(spc_head, cpu, MAX_SP);
790 if (top_mem) sp_acopy(spm_head, mem, MAX_SP);
791 if (top_time) sp_acopy(spt_head, ptime, MAX_SP);
793 if (top_io) sp_acopy(spi_head, io, MAX_SP);
804 int parse_top_args(const char *s, const char *arg, struct text_object *obj)
811 NORM_ERR("top needs arguments");
815 if (obj->data.opaque) {
822 } else if (strcmp(&s[3], "_mem") == EQUAL) {
823 obj->type = OBJ_top_mem;
825 } else if (strcmp(&s[3], "_time") == EQUAL) {
826 obj->type = OBJ_top_time;
829 } else if (strcmp(&s[3], "_io") == EQUAL) {
830 obj->type = OBJ_top_io;
835 NORM_ERR("Must be top, top_mem, top_time or top_io");
837 NORM_ERR("Must be top, top_mem or top_time");
842 obj->data.opaque = td = malloc(sizeof(struct top_data));
843 memset(td, 0, sizeof(struct top_data));
844 td->s = strndup(arg, text_buffer_size);
846 if (sscanf(arg, "%63s %i", buf, &n) == 2) {
847 if (strcmp(buf, "name") == EQUAL) {
849 } else if (strcmp(buf, "cpu") == EQUAL) {
851 } else if (strcmp(buf, "pid") == EQUAL) {
853 } else if (strcmp(buf, "mem") == EQUAL) {
855 } else if (strcmp(buf, "time") == EQUAL) {
857 } else if (strcmp(buf, "mem_res") == EQUAL) {
858 td->type = TOP_MEM_RES;
859 } else if (strcmp(buf, "mem_vsize") == EQUAL) {
860 td->type = TOP_MEM_VSIZE;
862 } else if (strcmp(buf, "io_read") == EQUAL) {
863 td->type = TOP_READ_BYTES;
864 } else if (strcmp(buf, "io_write") == EQUAL) {
865 td->type = TOP_WRITE_BYTES;
866 } else if (strcmp(buf, "io_perc") == EQUAL) {
867 td->type = TOP_IO_PERC;
870 NORM_ERR("invalid type arg for top");
872 NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize, "
873 "io_read, io_write, io_perc");
875 NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize");
879 if (n < 1 || n > 10) {
880 NORM_ERR("invalid num arg for top. Must be between 1 and 10.");
886 NORM_ERR("invalid argument count for top");
892 static char *format_time(unsigned long timeval, const int width)
895 unsigned long nt; // narrow time, for speed on 32-bit
896 unsigned cc; // centiseconds
897 unsigned nn; // multi-purpose whatever
900 cc = nt % 100; // centiseconds past second
901 nt /= 100; // total seconds
902 nn = nt % 60; // seconds past the minute
903 nt /= 60; // total minutes
904 if (width >= snprintf(buf, sizeof buf, "%lu:%02u.%02u",
906 return strndup(buf, text_buffer_size);
908 if (width >= snprintf(buf, sizeof buf, "%lu:%02u", nt, nn)) {
909 return strndup(buf, text_buffer_size);
911 nn = nt % 60; // minutes past the hour
912 nt /= 60; // total hours
913 if (width >= snprintf(buf, sizeof buf, "%lu,%02u", nt, nn)) {
914 return strndup(buf, text_buffer_size);
916 nn = nt; // now also hours
917 if (width >= snprintf(buf, sizeof buf, "%uh", nn)) {
918 return strndup(buf, text_buffer_size);
920 nn /= 24; // now days
921 if (width >= snprintf(buf, sizeof buf, "%ud", nn)) {
922 return strndup(buf, text_buffer_size);
924 nn /= 7; // now weeks
925 if (width >= snprintf(buf, sizeof buf, "%uw", nn)) {
926 return strndup(buf, text_buffer_size);
928 // well shoot, this outta' fit...
929 return strndup("<inf>", text_buffer_size);
932 void print_top(struct text_object *obj, char *p, int top_name_width)
934 struct information *cur = &info;
935 struct top_data *td = obj->data.opaque;
936 struct process **needed = 0;
958 if (needed[td->num]) {
963 snprintf(p, top_name_width + 1, "%-*s", top_name_width,
964 needed[td->num]->name);
967 snprintf(p, 7, "%6.2f",
968 needed[td->num]->amount);
971 snprintf(p, 6, "%5i",
972 needed[td->num]->pid);
975 /* Calculate a percentage of residential mem from total mem available.
976 * Since rss is bytes and memmax kilobytes, dividing by 10 suffices here. */
977 snprintf(p, 7, "%6.2f",
978 (float) ((float)needed[td->num]->rss / cur->memmax) / 10);
981 timeval = format_time(
982 needed[td->num]->total_cpu_time, 9);
983 snprintf(p, 10, "%9s", timeval);
987 human_readable(needed[td->num]->rss,
991 human_readable(needed[td->num]->vsize,
996 human_readable(needed[td->num]->read_bytes / update_interval,
999 case TOP_WRITE_BYTES:
1000 human_readable(needed[td->num]->write_bytes / update_interval,
1004 snprintf(p, 7, "%6.2f",
1005 needed[td->num]->io_perc);
1012 void free_top(struct text_object *obj, int internal)
1014 struct top_data *td = obj->data.opaque;
1016 if (info.first_process && !internal) {
1017 free_all_processes();
1018 info.first_process = NULL;
1025 free(obj->data.opaque);
1026 obj->data.opaque = NULL;