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-2010 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 (p->name && !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];
205 unsigned long user_time = 0;
206 unsigned long kernel_time = 0;
211 char *lparen, *rparen;
213 snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid);
215 ps = open(filename, O_RDONLY);
217 /* The process must have finished in the last few jiffies! */
221 /* Mark process as up-to-date. */
222 process->time_stamp = g_time;
224 rc = read(ps, line, sizeof(line));
230 /* Extract cpu times from data in /proc filesystem */
231 lparen = strchr(line, '(');
232 rparen = strrchr(line, ')');
233 if(!lparen || !rparen || rparen < lparen)
234 return 1; // this should not happen
236 rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1);
237 strncpy(procname, lparen + 1, rc);
239 rc = sscanf(rparen + 1, "%3s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu "
240 "%lu %*s %*s %*s %d %*s %*s %*s %u %u", state, &process->user_time,
241 &process->kernel_time, &nice_val, &process->vsize, &process->rss);
243 NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc);
250 /* remove any "kdeinit: " */
251 if (procname == strstr(procname, "kdeinit")) {
252 snprintf(filename, sizeof(filename), PROCFS_CMDLINE_TEMPLATE,
255 ps = open(filename, O_RDONLY);
257 /* The process must have finished in the last few jiffies! */
261 endl = read(ps, line, sizeof(line));
264 /* null terminate the input */
266 /* account for "kdeinit: " */
267 if ((char *) line == strstr(line, "kdeinit: ")) {
268 r = ((char *) line) + 9;
275 while (*r && *r != ' ') {
284 process->name = strndup(procname, text_buffer_size);
285 process->rss *= getpagesize();
287 process->total_cpu_time = process->user_time + process->kernel_time;
288 if (process->previous_user_time == ULONG_MAX) {
289 process->previous_user_time = process->user_time;
291 if (process->previous_kernel_time == ULONG_MAX) {
292 process->previous_kernel_time = process->kernel_time;
295 /* strangely, the values aren't monotonous */
296 if (process->previous_user_time > process->user_time)
297 process->previous_user_time = process->user_time;
299 if (process->previous_kernel_time > process->kernel_time)
300 process->previous_kernel_time = process->kernel_time;
302 /* store the difference of the user_time */
303 user_time = process->user_time - process->previous_user_time;
304 kernel_time = process->kernel_time - process->previous_kernel_time;
306 /* backup the process->user_time for next time around */
307 process->previous_user_time = process->user_time;
308 process->previous_kernel_time = process->kernel_time;
310 /* store only the difference of the user_time here... */
311 process->user_time = user_time;
312 process->kernel_time = kernel_time;
318 static int process_parse_io(struct process *process)
320 static const char *read_bytes_str="read_bytes:";
321 static const char *write_bytes_str="write_bytes:";
323 char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN];
327 unsigned long long read_bytes, write_bytes;
329 snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid);
331 ps = open(filename, O_RDONLY);
333 /* The process must have finished in the last few jiffies!
334 * Or, the kernel doesn't support I/O accounting.
339 rc = read(ps, line, sizeof(line));
345 pos = strstr(line, read_bytes_str);
347 /* these should not happen (unless the format of the file changes) */
350 pos += strlen(read_bytes_str);
351 process->read_bytes = strtoull(pos, &endpos, 10);
356 pos = strstr(line, write_bytes_str);
360 pos += strlen(write_bytes_str);
361 process->write_bytes = strtoull(pos, &endpos, 10);
366 if (process->previous_read_bytes == ULLONG_MAX) {
367 process->previous_read_bytes = process->read_bytes;
369 if (process->previous_write_bytes == ULLONG_MAX) {
370 process->previous_write_bytes = process->write_bytes;
373 /* store the difference of the byte counts */
374 read_bytes = process->read_bytes - process->previous_read_bytes;
375 write_bytes = process->write_bytes - process->previous_write_bytes;
377 /* backup the counts for next time around */
378 process->previous_read_bytes = process->read_bytes;
379 process->previous_write_bytes = process->write_bytes;
381 /* store only the difference here... */
382 process->read_bytes = read_bytes;
383 process->write_bytes = write_bytes;
389 /******************************************
390 * Get process structure for process pid *
391 ******************************************/
393 /* This function seems to hog all of the CPU time.
394 * I can't figure out why - it doesn't do much. */
395 static int calculate_stats(struct process *process)
399 /* compute each process cpu usage by reading /proc/<proc#>/stat */
400 rc = process_parse_stat(process);
402 /* rc = process_parse_statm(process); if (rc) return 1; */
405 rc = process_parse_io(process);
410 * Check name against the exclusion list
412 /* if (process->counted && exclusion_expression &&
413 * !regexec(exclusion_expression, process->name, 0, 0, 0))
414 * process->counted = 0; */
419 /******************************************
420 * Update process table *
421 ******************************************/
423 static int update_process_table(void)
426 struct dirent *entry;
428 if (!(dir = opendir("/proc"))) {
435 /* Get list of processes from /proc directory */
436 while ((entry = readdir(dir))) {
440 /* Problem reading list of processes */
445 if (sscanf(entry->d_name, "%d", &pid) > 0) {
448 p = find_process(pid);
450 p = new_process(pid);
453 /* compute each process cpu usage */
463 /******************************************
464 * Destroy and remove a process *
465 ******************************************/
467 static void delete_process(struct process *p)
469 #if defined(PARANOID)
470 assert(p->id == 0x0badfeed);
473 * Ensure that deleted processes aren't reused.
476 #endif /* defined(PARANOID) */
479 * Maintain doubly linked list.
482 p->next->previous = p->previous;
484 p->previous->next = p->next;
486 first_process = p->next;
491 /* remove the process from the hash table */
496 /******************************************
497 * Strip dead process entries *
498 ******************************************/
500 static void process_cleanup(void)
503 struct process *p = first_process;
506 struct process *current = p;
508 #if defined(PARANOID)
509 assert(p->id == 0x0badfeed);
510 #endif /* defined(PARANOID) */
513 /* Delete processes that have died */
514 if (current->time_stamp != g_time) {
515 delete_process(current);
520 /******************************************
521 * Calculate cpu total *
522 ******************************************/
523 #define TMPL_SHORTPROC "%*s %llu %llu %llu %llu"
524 #define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
526 static unsigned long long calc_cpu_total(void)
528 unsigned long long total = 0;
529 unsigned long long t = 0;
532 char line[BUFFER_LEN] = { 0 };
533 unsigned long long cpu = 0;
534 unsigned long long niceval = 0;
535 unsigned long long systemval = 0;
536 unsigned long long idle = 0;
537 unsigned long long iowait = 0;
538 unsigned long long irq = 0;
539 unsigned long long softirq = 0;
540 unsigned long long steal = 0;
541 const char *template =
542 KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC;
544 ps = open("/proc/stat", O_RDONLY);
545 rc = read(ps, line, sizeof(line));
551 sscanf(line, template, &cpu, &niceval, &systemval, &idle, &iowait, &irq,
553 total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal;
555 t = total - previous_total;
556 previous_total = total;
561 /******************************************
562 * Calculate each processes cpu *
563 ******************************************/
565 inline static void calc_cpu_each(unsigned long long total)
567 struct process *p = first_process;
570 p->amount = 100.0 * (cpu_separate ? info.cpu_count : 1) *
571 (p->user_time + p->kernel_time) / (float) total;
578 static void calc_io_each(void)
581 unsigned long long sum = 0;
583 for (p = first_process; p; p = p->next)
584 sum += p->read_bytes + p->write_bytes;
587 sum = 1; /* to avoid having NANs if no I/O occured */
588 for (p = first_process; p; p = p->next)
589 p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float) sum;
593 /******************************************
594 * Find the top processes *
595 ******************************************/
597 /* free a sp_process structure */
598 static void free_sp(struct sorted_process *sp)
603 /* create a new sp_process structure */
604 static struct sorted_process *malloc_sp(struct process *proc)
606 struct sorted_process *sp;
607 sp = malloc(sizeof(struct sorted_process));
608 memset(sp, 0, sizeof(struct sorted_process));
613 /* cpu comparison function for insert_sp_element */
614 static int compare_cpu(struct process *a, struct process *b)
616 if (a->amount < b->amount) {
618 } else if (a->amount > b->amount) {
625 /* mem comparison function for insert_sp_element */
626 static int compare_mem(struct process *a, struct process *b)
628 if (a->rss < b->rss) {
630 } else if (a->rss > b->rss) {
637 /* CPU time comparision function for insert_sp_element */
638 static int compare_time(struct process *a, struct process *b)
640 return b->total_cpu_time - a->total_cpu_time;
644 /* I/O comparision function for insert_sp_element */
645 static int compare_io(struct process *a, struct process *b)
647 if (a->io_perc < b->io_perc) {
649 } else if (a->io_perc > b->io_perc) {
657 /* insert this process into the list in a sorted fashion,
658 * or destroy it if it doesn't fit on the list */
659 static int insert_sp_element(struct sorted_process *sp_cur,
660 struct sorted_process **p_sp_head, struct sorted_process **p_sp_tail,
661 int max_elements, int compare_funct(struct process *, struct process *))
664 struct sorted_process *sp_readthru = NULL, *sp_destroy = NULL;
665 int did_insert = 0, x = 0;
667 if (*p_sp_head == NULL) {
672 for (sp_readthru = *p_sp_head, x = 0;
673 sp_readthru != NULL && x < max_elements;
674 sp_readthru = sp_readthru->less, x++) {
675 if (compare_funct(sp_readthru->proc, sp_cur->proc) > 0 && !did_insert) {
676 /* sp_cur is bigger than sp_readthru
677 * so insert it before sp_readthru */
678 sp_cur->less = sp_readthru;
679 if (sp_readthru == *p_sp_head) {
680 /* insert as the new head of the list */
683 /* insert inside the list */
684 sp_readthru->greater->less = sp_cur;
685 sp_cur->greater = sp_readthru->greater;
687 sp_readthru->greater = sp_cur;
688 /* element was inserted, so increase the counter */
692 if (x < max_elements && sp_readthru == NULL && !did_insert) {
693 /* sp_cur is the smallest element and list isn't full,
694 * so insert at the end */
695 (*p_sp_tail)->less = sp_cur;
696 sp_cur->greater = *p_sp_tail;
699 } else if (x >= max_elements) {
700 /* We inserted an element and now the list is too big by one.
701 * Destroy the smallest element */
702 sp_destroy = *p_sp_tail;
703 *p_sp_tail = sp_destroy->greater;
704 (*p_sp_tail)->less = NULL;
708 /* sp_cur wasn't added to the sorted list, so destroy it */
714 /* copy the procs in the sorted list to the array, and destroy the list */
715 static void sp_acopy(struct sorted_process *sp_head, struct process **ar, int max_size)
717 struct sorted_process *sp_cur, *sp_tmp;
721 for (x = 0; x < max_size && sp_cur != NULL; x++) {
722 ar[x] = sp_cur->proc;
724 sp_cur = sp_cur->less;
729 /* ****************************************************************** *
730 * Get a sorted list of the top cpu hogs and top mem hogs. *
731 * Results are stored in the cpu,mem arrays in decreasing order[0-9]. *
732 * ****************************************************************** */
734 void process_find_top(struct process **cpu, struct process **mem,
735 struct process **ptime
737 , struct process **io
741 struct sorted_process *spc_head = NULL, *spc_tail = NULL, *spc_cur = NULL;
742 struct sorted_process *spm_head = NULL, *spm_tail = NULL, *spm_cur = NULL;
743 struct sorted_process *spt_head = NULL, *spt_tail = NULL, *spt_cur = NULL;
745 struct sorted_process *spi_head = NULL, *spi_tail = NULL, *spi_cur = NULL;
747 struct process *cur_proc = NULL;
748 unsigned long long total = 0;
750 if (!top_cpu && !top_mem && !top_time
759 total = calc_cpu_total(); /* calculate the total of the processor */
760 update_process_table(); /* update the table with process list */
761 calc_cpu_each(total); /* and then the percentage for each task */
762 process_cleanup(); /* cleanup list from exited processes */
764 calc_io_each(); /* percentage of I/O for each task */
767 cur_proc = first_process;
769 while (cur_proc != NULL) {
771 spc_cur = malloc_sp(cur_proc);
772 insert_sp_element(spc_cur, &spc_head, &spc_tail, MAX_SP,
776 spm_cur = malloc_sp(cur_proc);
777 insert_sp_element(spm_cur, &spm_head, &spm_tail, MAX_SP,
781 spt_cur = malloc_sp(cur_proc);
782 insert_sp_element(spt_cur, &spt_head, &spt_tail, MAX_SP,
787 spi_cur = malloc_sp(cur_proc);
788 insert_sp_element(spi_cur, &spi_head, &spi_tail, MAX_SP,
792 cur_proc = cur_proc->next;
795 if (top_cpu) sp_acopy(spc_head, cpu, MAX_SP);
796 if (top_mem) sp_acopy(spm_head, mem, MAX_SP);
797 if (top_time) sp_acopy(spt_head, ptime, MAX_SP);
799 if (top_io) sp_acopy(spi_head, io, MAX_SP);
810 int parse_top_args(const char *s, const char *arg, struct text_object *obj)
817 NORM_ERR("top needs arguments");
821 if (obj->data.opaque) {
828 } else if (strcmp(&s[3], "_mem") == EQUAL) {
829 obj->type = OBJ_top_mem;
831 } else if (strcmp(&s[3], "_time") == EQUAL) {
832 obj->type = OBJ_top_time;
835 } else if (strcmp(&s[3], "_io") == EQUAL) {
836 obj->type = OBJ_top_io;
841 NORM_ERR("Must be top, top_mem, top_time or top_io");
843 NORM_ERR("Must be top, top_mem or top_time");
848 obj->data.opaque = td = malloc(sizeof(struct top_data));
849 memset(td, 0, sizeof(struct top_data));
850 td->s = strndup(arg, text_buffer_size);
852 if (sscanf(arg, "%63s %i", buf, &n) == 2) {
853 if (strcmp(buf, "name") == EQUAL) {
855 } else if (strcmp(buf, "cpu") == EQUAL) {
857 } else if (strcmp(buf, "pid") == EQUAL) {
859 } else if (strcmp(buf, "mem") == EQUAL) {
861 } else if (strcmp(buf, "time") == EQUAL) {
863 } else if (strcmp(buf, "mem_res") == EQUAL) {
864 td->type = TOP_MEM_RES;
865 } else if (strcmp(buf, "mem_vsize") == EQUAL) {
866 td->type = TOP_MEM_VSIZE;
868 } else if (strcmp(buf, "io_read") == EQUAL) {
869 td->type = TOP_READ_BYTES;
870 } else if (strcmp(buf, "io_write") == EQUAL) {
871 td->type = TOP_WRITE_BYTES;
872 } else if (strcmp(buf, "io_perc") == EQUAL) {
873 td->type = TOP_IO_PERC;
876 NORM_ERR("invalid type arg for top");
878 NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize, "
879 "io_read, io_write, io_perc");
881 NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize");
883 free_and_zero(td->s);
884 free_and_zero(obj->data.opaque);
887 if (n < 1 || n > 10) {
888 NORM_ERR("invalid num arg for top. Must be between 1 and 10.");
889 free_and_zero(td->s);
890 free_and_zero(obj->data.opaque);
896 NORM_ERR("invalid argument count for top");
897 free_and_zero(td->s);
898 free_and_zero(obj->data.opaque);
904 static char *format_time(unsigned long timeval, const int width)
907 unsigned long nt; // narrow time, for speed on 32-bit
908 unsigned cc; // centiseconds
909 unsigned nn; // multi-purpose whatever
912 cc = nt % 100; // centiseconds past second
913 nt /= 100; // total seconds
914 nn = nt % 60; // seconds past the minute
915 nt /= 60; // total minutes
916 if (width >= snprintf(buf, sizeof buf, "%lu:%02u.%02u",
918 return strndup(buf, text_buffer_size);
920 if (width >= snprintf(buf, sizeof buf, "%lu:%02u", nt, nn)) {
921 return strndup(buf, text_buffer_size);
923 nn = nt % 60; // minutes past the hour
924 nt /= 60; // total hours
925 if (width >= snprintf(buf, sizeof buf, "%lu,%02u", nt, nn)) {
926 return strndup(buf, text_buffer_size);
928 nn = nt; // now also hours
929 if (width >= snprintf(buf, sizeof buf, "%uh", nn)) {
930 return strndup(buf, text_buffer_size);
932 nn /= 24; // now days
933 if (width >= snprintf(buf, sizeof buf, "%ud", nn)) {
934 return strndup(buf, text_buffer_size);
936 nn /= 7; // now weeks
937 if (width >= snprintf(buf, sizeof buf, "%uw", nn)) {
938 return strndup(buf, text_buffer_size);
940 // well shoot, this outta' fit...
941 return strndup("<inf>", text_buffer_size);
944 static unsigned int top_name_width = 15;
946 /* return zero on success, non-zero otherwise */
947 int set_top_name_width(const char *s)
951 return !(sscanf(s, "%u", &top_name_width) == 1);
954 void print_top(struct text_object *obj, char *p, int p_max_size)
956 struct information *cur = &info;
957 struct top_data *td = obj->data.opaque;
958 struct process **needed = 0;
984 if (needed[td->num]) {
989 width = MIN(p_max_size, (int)top_name_width + 1);
990 snprintf(p, width + 1, "%-*s", width,
991 needed[td->num]->name);
994 width = MIN(p_max_size, 7);
995 snprintf(p, width, "%6.2f",
996 needed[td->num]->amount);
999 width = MIN(p_max_size, 6);
1000 snprintf(p, width, "%5i",
1001 needed[td->num]->pid);
1004 /* Calculate a percentage of residential mem from total mem available.
1005 * Since rss is bytes and memmax kilobytes, dividing by 10 suffices here. */
1006 width = MIN(p_max_size, 7);
1007 snprintf(p, width, "%6.2f",
1008 (float) ((float)needed[td->num]->rss / cur->memmax) / 10);
1011 width = MIN(p_max_size, 10);
1012 timeval = format_time(
1013 needed[td->num]->total_cpu_time, 9);
1014 snprintf(p, width, "%9s", timeval);
1018 human_readable(needed[td->num]->rss,
1022 human_readable(needed[td->num]->vsize,
1026 case TOP_READ_BYTES:
1027 human_readable(needed[td->num]->read_bytes / update_interval,
1030 case TOP_WRITE_BYTES:
1031 human_readable(needed[td->num]->write_bytes / update_interval,
1035 width = MIN(p_max_size, 7);
1036 snprintf(p, width, "%6.2f",
1037 needed[td->num]->io_perc);
1044 void free_top(struct text_object *obj, int internal)
1046 struct top_data *td = obj->data.opaque;
1048 if (info.first_process && !internal) {
1049 free_all_processes();
1050 info.first_process = NULL;
1057 free(obj->data.opaque);
1058 obj->data.opaque = NULL;