top: drop problematic field totalmem
[monky] / src / top.c
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
3  *
4  * Conky, a system monitor, based on torsmo
5  *
6  * Any original torsmo code is licensed under the BSD license
7  *
8  * All code written since the fork of torsmo is licensed under the GPL
9  *
10  * Please see COPYING for details
11  *
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.
15  *      (see AUTHORS)
16  * All rights reserved.
17  *
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.
22  *
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/>.
29  *
30  */
31
32 #include "top.h"
33 #include "logging.h"
34
35 static unsigned long g_time = 0;
36 static unsigned long long previous_total = 0;
37 static struct process *first_process = 0;
38
39 /* a simple hash table to speed up find_process() */
40 struct proc_hash_entry {
41         struct proc_hash_entry *next;
42         struct process *proc;
43 };
44 static struct proc_hash_entry proc_hash_table[256];
45
46 static void hash_process(struct process *p)
47 {
48         struct proc_hash_entry *phe;
49         static char first_run = 1;
50
51         /* better make sure all next pointers are zero upon first access */
52         if (first_run) {
53                 memset(proc_hash_table, 0, sizeof(struct proc_hash_entry) * 256);
54                 first_run = 0;
55         }
56
57         /* get the bucket head */
58         phe = &proc_hash_table[p->pid % 256];
59
60         /* find the bucket's end */
61         while (phe->next)
62                 phe = phe->next;
63
64         /* append process */
65         phe->next = malloc(sizeof(struct proc_hash_entry));
66         memset(phe->next, 0, sizeof(struct proc_hash_entry));
67         phe->next->proc = p;
68 }
69
70 static void unhash_process(struct process *p)
71 {
72         struct proc_hash_entry *phe, *tmp;
73
74         /* get the bucket head */
75         phe = &proc_hash_table[p->pid % 256];
76
77         /* find the entry pointing to p and drop it */
78         while (phe->next) {
79                 if (phe->next->proc == p) {
80                         tmp = phe->next;
81                         phe->next = phe->next->next;
82                         free(tmp);
83                         return;
84                 }
85                 phe = phe->next;
86         }
87 }
88
89 static void __unhash_all_processes(struct proc_hash_entry *phe)
90 {
91         if (phe->next)
92                 __unhash_all_processes(phe->next);
93         free(phe->next);
94 }
95
96 static void unhash_all_processes(void)
97 {
98         int i;
99
100         for (i = 0; i < 256; i++) {
101                 __unhash_all_processes(&proc_hash_table[i]);
102                 proc_hash_table[i].next = NULL;
103         }
104 }
105
106 struct process *get_first_process(void)
107 {
108         return first_process;
109 }
110
111 void free_all_processes(void)
112 {
113         struct process *next = NULL, *pr = first_process;
114
115         while (pr) {
116                 next = pr->next;
117                 if (pr->name) {
118                         free(pr->name);
119                 }
120                 free(pr);
121                 pr = next;
122         }
123         first_process = NULL;
124
125         /* drop the whole hash table */
126         unhash_all_processes();
127 }
128
129 struct process *get_process_by_name(const char *name)
130 {
131         struct process *p = first_process;
132
133         while (p) {
134                 if (!strcmp(p->name, name))
135                         return p;
136                 p = p->next;
137         }
138         return 0;
139 }
140
141 static struct process *find_process(pid_t pid)
142 {
143         struct proc_hash_entry *phe;
144
145         phe = &proc_hash_table[pid % 256];
146         while (phe->next) {
147                 if (phe->next->proc->pid == pid)
148                         return phe->next->proc;
149                 phe = phe->next;
150         }
151         return 0;
152 }
153
154 /* Create a new process object and insert it into the process list */
155 static struct process *new_process(int p)
156 {
157         struct process *process;
158         process = (struct process *) malloc(sizeof(struct process));
159
160         // clean up memory first
161         memset(process, 0, sizeof(struct process));
162
163         /* Do stitching necessary for doubly linked list */
164         process->name = 0;
165         process->previous = 0;
166         process->next = first_process;
167         if (process->next) {
168                 process->next->previous = process;
169         }
170         first_process = process;
171
172         process->pid = p;
173         process->time_stamp = 0;
174         process->previous_user_time = ULONG_MAX;
175         process->previous_kernel_time = ULONG_MAX;
176 #ifdef IOSTATS
177         process->previous_read_bytes = ULLONG_MAX;
178         process->previous_write_bytes = ULLONG_MAX;
179 #endif /* IOSTATS */
180         process->counted = 1;
181
182         /* process_find_name(process); */
183
184         /* add the process to the hash table */
185         hash_process(process);
186
187         return process;
188 }
189
190 /******************************************
191  * Functions                                                      *
192  ******************************************/
193
194 /******************************************
195  * Extract information from /proc                 *
196  ******************************************/
197
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)
201 {
202         char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN], procname[BUFFER_LEN];
203         int ps;
204         unsigned long user_time = 0;
205         unsigned long kernel_time = 0;
206         int rc;
207         char *r, *q;
208         int endl;
209         int nice_val;
210         char *lparen, *rparen;
211
212         snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid);
213
214         ps = open(filename, O_RDONLY);
215         if (ps < 0) {
216                 /* The process must have finished in the last few jiffies! */
217                 return 1;
218         }
219
220         /* Mark process as up-to-date. */
221         process->time_stamp = g_time;
222
223         rc = read(ps, line, sizeof(line));
224         close(ps);
225         if (rc < 0) {
226                 return 1;
227         }
228
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
234
235         rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1);
236         strncpy(procname, lparen + 1, rc);
237         procname[rc] = '\0';
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);
241         if (rc < 5) {
242                 NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc);
243                 return 1;
244         }
245         /* remove any "kdeinit: " */
246         if (procname == strstr(procname, "kdeinit")) {
247                 snprintf(filename, sizeof(filename), PROCFS_CMDLINE_TEMPLATE,
248                                 process->pid);
249
250                 ps = open(filename, O_RDONLY);
251                 if (ps < 0) {
252                         /* The process must have finished in the last few jiffies! */
253                         return 1;
254                 }
255
256                 endl = read(ps, line, sizeof(line));
257                 close(ps);
258
259                 /* null terminate the input */
260                 line[endl] = 0;
261                 /* account for "kdeinit: " */
262                 if ((char *) line == strstr(line, "kdeinit: ")) {
263                         r = ((char *) line) + 9;
264                 } else {
265                         r = (char *) line;
266                 }
267
268                 q = procname;
269                 /* stop at space */
270                 while (*r && *r != ' ') {
271                         *q++ = *r++;
272                 }
273                 *q = 0;
274         }
275
276         if (process->name) {
277                 free(process->name);
278         }
279         process->name = strndup(procname, text_buffer_size);
280         process->rss *= getpagesize();
281
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;
285         }
286         if (process->previous_kernel_time == ULONG_MAX) {
287                 process->previous_kernel_time = process->kernel_time;
288         }
289
290         /* strangely, the values aren't monotonous */
291         if (process->previous_user_time > process->user_time)
292                 process->previous_user_time = process->user_time;
293
294         if (process->previous_kernel_time > process->kernel_time)
295                 process->previous_kernel_time = process->kernel_time;
296
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;
300
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;
304
305         /* store only the difference of the user_time here... */
306         process->user_time = user_time;
307         process->kernel_time = kernel_time;
308
309         return 0;
310 }
311
312 #ifdef IOSTATS
313 static int process_parse_io(struct process *process)
314 {
315         static const char *read_bytes_str="read_bytes:";
316         static const char *write_bytes_str="write_bytes:";
317
318         char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN];
319         int ps;
320         int rc;
321         char *pos, *endpos;
322         unsigned long long read_bytes, write_bytes;
323
324         snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid);
325
326         ps = open(filename, O_RDONLY);
327         if (ps < 0) {
328                 /* The process must have finished in the last few jiffies!
329                  * Or, the kernel doesn't support I/O accounting.
330                  */
331                 return 1;
332         }
333
334         rc = read(ps, line, sizeof(line));
335         close(ps);
336         if (rc < 0) {
337                 return 1;
338         }
339
340         pos = strstr(line, read_bytes_str);
341         if (pos == NULL) {
342                 /* these should not happen (unless the format of the file changes) */
343                 return 1;
344         }
345         pos += strlen(read_bytes_str);
346         process->read_bytes = strtoull(pos, &endpos, 10);
347         if (endpos == pos) {
348                 return 1;
349         }
350
351         pos = strstr(line, write_bytes_str);
352         if (pos == NULL) {
353                 return 1;
354         }
355         pos += strlen(write_bytes_str);
356         process->write_bytes = strtoull(pos, &endpos, 10);
357         if (endpos == pos) {
358                 return 1;
359         }
360
361         if (process->previous_read_bytes == ULLONG_MAX) {
362                 process->previous_read_bytes = process->read_bytes;
363         }
364         if (process->previous_write_bytes == ULLONG_MAX) {
365                 process->previous_write_bytes = process->write_bytes;
366         }
367
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;
371
372         /* backup the counts for next time around */
373         process->previous_read_bytes = process->read_bytes;
374         process->previous_write_bytes = process->write_bytes;
375
376         /* store only the difference here... */
377         process->read_bytes = read_bytes;
378         process->write_bytes = write_bytes;
379
380         return 0;
381 }
382 #endif /* IOSTATS */
383
384 /******************************************
385  * Get process structure for process pid  *
386  ******************************************/
387
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)
391 {
392         int rc;
393
394         /* compute each process cpu usage by reading /proc/<proc#>/stat */
395         rc = process_parse_stat(process);
396         if (rc) return 1;
397         /* rc = process_parse_statm(process); if (rc) return 1; */
398
399 #ifdef IOSTATS
400         rc = process_parse_io(process);
401         if (rc) return 1;
402 #endif /* IOSTATS */
403
404         /*
405          * Check name against the exclusion list
406          */
407         /* if (process->counted && exclusion_expression &&
408          * !regexec(exclusion_expression, process->name, 0, 0, 0))
409          * process->counted = 0; */
410
411         return 0;
412 }
413
414 /******************************************
415  * Update process table                                   *
416  ******************************************/
417
418 static int update_process_table(void)
419 {
420         DIR *dir;
421         struct dirent *entry;
422
423         if (!(dir = opendir("/proc"))) {
424                 return 1;
425         }
426
427         ++g_time;
428
429         /* Get list of processes from /proc directory */
430         while ((entry = readdir(dir))) {
431                 pid_t pid;
432
433                 if (!entry) {
434                         /* Problem reading list of processes */
435                         closedir(dir);
436                         return 1;
437                 }
438
439                 if (sscanf(entry->d_name, "%d", &pid) > 0) {
440                         struct process *p;
441
442                         p = find_process(pid);
443                         if (!p) {
444                                 p = new_process(pid);
445                         }
446
447                         /* compute each process cpu usage */
448                         calculate_stats(p);
449                 }
450         }
451
452         closedir(dir);
453
454         return 0;
455 }
456
457 /******************************************
458  * Destroy and remove a process           *
459  ******************************************/
460
461 static void delete_process(struct process *p)
462 {
463 #if defined(PARANOID)
464         assert(p->id == 0x0badfeed);
465
466         /*
467          * Ensure that deleted processes aren't reused.
468          */
469         p->id = 0x007babe;
470 #endif /* defined(PARANOID) */
471
472         /*
473          * Maintain doubly linked list.
474          */
475         if (p->next)
476                 p->next->previous = p->previous;
477         if (p->previous)
478                 p->previous->next = p->next;
479         else
480                 first_process = p->next;
481
482         if (p->name) {
483                 free(p->name);
484         }
485         /* remove the process from the hash table */
486         unhash_process(p);
487         free(p);
488 }
489
490 /******************************************
491  * Strip dead process entries                     *
492  ******************************************/
493
494 static void process_cleanup(void)
495 {
496
497         struct process *p = first_process;
498
499         while (p) {
500                 struct process *current = p;
501
502 #if defined(PARANOID)
503                 assert(p->id == 0x0badfeed);
504 #endif /* defined(PARANOID) */
505
506                 p = p->next;
507                 /* Delete processes that have died */
508                 if (current->time_stamp != g_time) {
509                         delete_process(current);
510                 }
511         }
512 }
513
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"
519
520 static unsigned long long calc_cpu_total(void)
521 {
522         unsigned long long total = 0;
523         unsigned long long t = 0;
524         int rc;
525         int ps;
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;
537
538         ps = open("/proc/stat", O_RDONLY);
539         rc = read(ps, line, sizeof(line));
540         close(ps);
541         if (rc < 0) {
542                 return 0;
543         }
544
545         sscanf(line, template, &cpu, &niceval, &systemval, &idle, &iowait, &irq,
546                         &softirq, &steal);
547         total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal;
548
549         t = total - previous_total;
550         previous_total = total;
551
552         return t;
553 }
554
555 /******************************************
556  * Calculate each processes cpu                   *
557  ******************************************/
558
559 inline static void calc_cpu_each(unsigned long long total)
560 {
561         struct process *p = first_process;
562
563         while (p) {
564                 p->amount = 100.0 * (cpu_separate ? info.cpu_count : 1) *
565                         (p->user_time + p->kernel_time) / (float) total;
566
567                 p = p->next;
568         }
569 }
570
571 #ifdef IOSTATS
572 static void calc_io_each(void)
573 {
574         struct process *p;
575         unsigned long long sum = 0;
576
577         for (p = first_process; p; p = p->next)
578                 sum += p->read_bytes + p->write_bytes;
579
580         if(sum == 0)
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;
584 }
585 #endif /* IOSTATS */
586
587 /******************************************
588  * Find the top processes                                 *
589  ******************************************/
590
591 /* free a sp_process structure */
592 static void free_sp(struct sorted_process *sp)
593 {
594         free(sp);
595 }
596
597 /* create a new sp_process structure */
598 static struct sorted_process *malloc_sp(struct process *proc)
599 {
600         struct sorted_process *sp;
601         sp = malloc(sizeof(struct sorted_process));
602         memset(sp, 0, sizeof(struct sorted_process));
603         sp->proc = proc;
604         return sp;
605 }
606
607 /* cpu comparison function for insert_sp_element */
608 static int compare_cpu(struct process *a, struct process *b)
609 {
610         if (a->amount < b->amount) {
611                 return 1;
612         } else if (a->amount > b->amount) {
613                 return -1;
614         } else {
615                 return 0;
616         }
617 }
618
619 /* mem comparison function for insert_sp_element */
620 static int compare_mem(struct process *a, struct process *b)
621 {
622         if (a->rss < b->rss) {
623                 return 1;
624         } else if (a->rss > b->rss) {
625                 return -1;
626         } else {
627                 return 0;
628         }
629 }
630
631 /* CPU time comparision function for insert_sp_element */
632 static int compare_time(struct process *a, struct process *b)
633 {
634         return b->total_cpu_time - a->total_cpu_time;
635 }
636
637 #ifdef IOSTATS
638 /* I/O comparision function for insert_sp_element */
639 static int compare_io(struct process *a, struct process *b)
640 {
641         if (a->io_perc < b->io_perc) {
642                 return 1;
643         } else if (a->io_perc > b->io_perc) {
644                 return -1;
645         } else {
646                 return 0;
647         }
648 }
649 #endif /* IOSTATS */
650
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 *))
656 {
657
658         struct sorted_process *sp_readthru = NULL, *sp_destroy = NULL;
659         int did_insert = 0, x = 0;
660
661         if (*p_sp_head == NULL) {
662                 *p_sp_head = sp_cur;
663                 *p_sp_tail = sp_cur;
664                 return 1;
665         }
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 */
675                                 *p_sp_head = sp_cur;
676                         } else {
677                                 /* insert inside the list */
678                                 sp_readthru->greater->less = sp_cur;
679                                 sp_cur->greater = sp_readthru->greater;
680                         }
681                         sp_readthru->greater = sp_cur;
682                         /* element was inserted, so increase the counter */
683                         did_insert = ++x;
684                 }
685         }
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;
691                 *p_sp_tail = sp_cur;
692                 did_insert = x;
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;
699                 free_sp(sp_destroy);
700         }
701         if (!did_insert) {
702                 /* sp_cur wasn't added to the sorted list, so destroy it */
703                 free_sp(sp_cur);
704         }
705         return did_insert;
706 }
707
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)
710 {
711         struct sorted_process *sp_cur, *sp_tmp;
712         int x;
713
714         sp_cur = sp_head;
715         for (x = 0; x < max_size && sp_cur != NULL; x++) {
716                 ar[x] = sp_cur->proc;
717                 sp_tmp = sp_cur;
718                 sp_cur = sp_cur->less;
719                 free_sp(sp_tmp);
720         }
721 }
722
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  * ****************************************************************** */
727
728 void process_find_top(struct process **cpu, struct process **mem,
729                 struct process **ptime
730 #ifdef IOSTATS
731                 , struct process **io
732 #endif /* IOSTATS */
733                 )
734 {
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;
738 #ifdef IOSTATS
739         struct sorted_process *spi_head = NULL, *spi_tail = NULL, *spi_cur = NULL;
740 #endif /* IOSTATS */
741         struct process *cur_proc = NULL;
742         unsigned long long total = 0;
743
744         if (!top_cpu && !top_mem && !top_time
745 #ifdef IOSTATS
746                         && !top_io
747 #endif /* IOSTATS */
748                         && !top_running
749            ) {
750                 return;
751         }
752
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 */
757 #ifdef IOSTATS
758         calc_io_each();                 /* percentage of I/O for each task */
759 #endif /* IOSTATS */
760
761         cur_proc = first_process;
762
763         while (cur_proc != NULL) {
764                 if (top_cpu) {
765                         spc_cur = malloc_sp(cur_proc);
766                         insert_sp_element(spc_cur, &spc_head, &spc_tail, MAX_SP,
767                                         &compare_cpu);
768                 }
769                 if (top_mem) {
770                         spm_cur = malloc_sp(cur_proc);
771                         insert_sp_element(spm_cur, &spm_head, &spm_tail, MAX_SP,
772                                         &compare_mem);
773                 }
774                 if (top_time) {
775                         spt_cur = malloc_sp(cur_proc);
776                         insert_sp_element(spt_cur, &spt_head, &spt_tail, MAX_SP,
777                                         &compare_time);
778                 }
779 #ifdef IOSTATS
780                 if (top_io) {
781                         spi_cur = malloc_sp(cur_proc);
782                         insert_sp_element(spi_cur, &spi_head, &spi_tail, MAX_SP,
783                                         &compare_io);
784                 }
785 #endif /* IOSTATS */
786                 cur_proc = cur_proc->next;
787         }
788
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);
792 #ifdef IOSTATS
793         if (top_io)             sp_acopy(spi_head, io,          MAX_SP);
794 #endif /* IOSTATS */
795 }
796
797 struct top_data {
798         int num;
799         int type;
800         int was_parsed;
801         char *s;
802 };
803
804 int parse_top_args(const char *s, const char *arg, struct text_object *obj)
805 {
806         struct top_data *td;
807         char buf[64];
808         int n;
809
810         if (!arg) {
811                 NORM_ERR("top needs arguments");
812                 return 0;
813         }
814
815         if (obj->data.opaque) {
816                 return 1;
817         }
818
819         if (s[3] == 0) {
820                 obj->type = OBJ_top;
821                 top_cpu = 1;
822         } else if (strcmp(&s[3], "_mem") == EQUAL) {
823                 obj->type = OBJ_top_mem;
824                 top_mem = 1;
825         } else if (strcmp(&s[3], "_time") == EQUAL) {
826                 obj->type = OBJ_top_time;
827                 top_time = 1;
828 #ifdef IOSTATS
829         } else if (strcmp(&s[3], "_io") == EQUAL) {
830                 obj->type = OBJ_top_io;
831                 top_io = 1;
832 #endif /* IOSTATS */
833         } else {
834 #ifdef IOSTATS
835                 NORM_ERR("Must be top, top_mem, top_time or top_io");
836 #else /* IOSTATS */
837                 NORM_ERR("Must be top, top_mem or top_time");
838 #endif /* IOSTATS */
839                 return 0;
840         }
841
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);
845
846         if (sscanf(arg, "%63s %i", buf, &n) == 2) {
847                 if (strcmp(buf, "name") == EQUAL) {
848                         td->type = TOP_NAME;
849                 } else if (strcmp(buf, "cpu") == EQUAL) {
850                         td->type = TOP_CPU;
851                 } else if (strcmp(buf, "pid") == EQUAL) {
852                         td->type = TOP_PID;
853                 } else if (strcmp(buf, "mem") == EQUAL) {
854                         td->type = TOP_MEM;
855                 } else if (strcmp(buf, "time") == EQUAL) {
856                         td->type = TOP_TIME;
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;
861 #ifdef IOSTATS
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;
868 #endif /* IOSTATS */
869                 } else {
870                         NORM_ERR("invalid type arg for top");
871 #ifdef IOSTATS
872                         NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize, "
873                                         "io_read, io_write, io_perc");
874 #else /* IOSTATS */
875                         NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize");
876 #endif /* IOSTATS */
877                         return 0;
878                 }
879                 if (n < 1 || n > 10) {
880                         NORM_ERR("invalid num arg for top. Must be between 1 and 10.");
881                         return 0;
882                 } else {
883                         td->num = n - 1;
884                 }
885         } else {
886                 NORM_ERR("invalid argument count for top");
887                 return 0;
888         }
889         return 1;
890 }
891
892 static char *format_time(unsigned long timeval, const int width)
893 {
894         char buf[10];
895         unsigned long nt;       // narrow time, for speed on 32-bit
896         unsigned cc;            // centiseconds
897         unsigned nn;            // multi-purpose whatever
898
899         nt = timeval;
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",
905                                 nt, nn, cc)) {
906                 return strndup(buf, text_buffer_size);
907         }
908         if (width >= snprintf(buf, sizeof buf, "%lu:%02u", nt, nn)) {
909                 return strndup(buf, text_buffer_size);
910         }
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);
915         }
916         nn = nt;                        // now also hours
917         if (width >= snprintf(buf, sizeof buf, "%uh", nn)) {
918                 return strndup(buf, text_buffer_size);
919         }
920         nn /= 24;                       // now days
921         if (width >= snprintf(buf, sizeof buf, "%ud", nn)) {
922                 return strndup(buf, text_buffer_size);
923         }
924         nn /= 7;                        // now weeks
925         if (width >= snprintf(buf, sizeof buf, "%uw", nn)) {
926                 return strndup(buf, text_buffer_size);
927         }
928         // well shoot, this outta' fit...
929         return strndup("<inf>", text_buffer_size);
930 }
931
932 void print_top(struct text_object *obj, char *p, int top_name_width)
933 {
934         struct information *cur = &info;
935         struct top_data *td = obj->data.opaque;
936         struct process **needed = 0;
937
938         if (!td)
939                 return;
940
941         switch (obj->type) {
942                 case OBJ_top:
943                         needed = cur->cpu;
944                         break;
945                 case OBJ_top_mem:
946                         needed = cur->memu;
947                         break;
948                 case OBJ_top_time:
949                         needed = cur->time;
950                         break;
951                 case OBJ_top_io:
952                         needed = cur->io;
953                         break;
954                 default:
955                         return;
956         }
957
958         if (needed[td->num]) {
959                 char *timeval;
960
961                 switch (td->type) {
962                         case TOP_NAME:
963                                 snprintf(p, top_name_width + 1, "%-*s", top_name_width,
964                                                 needed[td->num]->name);
965                                 break;
966                         case TOP_CPU:
967                                 snprintf(p, 7, "%6.2f",
968                                                 needed[td->num]->amount);
969                                 break;
970                         case TOP_PID:
971                                 snprintf(p, 6, "%5i",
972                                                 needed[td->num]->pid);
973                                 break;
974                         case TOP_MEM:
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);
979                                 break;
980                         case TOP_TIME:
981                                 timeval = format_time(
982                                                 needed[td->num]->total_cpu_time, 9);
983                                 snprintf(p, 10, "%9s", timeval);
984                                 free(timeval);
985                                 break;
986                         case TOP_MEM_RES:
987                                 human_readable(needed[td->num]->rss,
988                                                 p, 255);
989                                 break;
990                         case TOP_MEM_VSIZE:
991                                 human_readable(needed[td->num]->vsize,
992                                                 p, 255);
993                                 break;
994 #ifdef IOSTATS
995                         case TOP_READ_BYTES:
996                                 human_readable(needed[td->num]->read_bytes / update_interval,
997                                                 p, 255);
998                                 break;
999                         case TOP_WRITE_BYTES:
1000                                 human_readable(needed[td->num]->write_bytes / update_interval,
1001                                                 p, 255);
1002                                 break;
1003                         case TOP_IO_PERC:
1004                                 snprintf(p, 7, "%6.2f",
1005                                                 needed[td->num]->io_perc);
1006                                 break;
1007 #endif
1008                 }
1009         }
1010 }
1011
1012 void free_top(struct text_object *obj, int internal)
1013 {
1014         struct top_data *td = obj->data.opaque;
1015
1016         if (info.first_process && !internal) {
1017                 free_all_processes();
1018                 info.first_process = NULL;
1019         }
1020
1021         if (!td)
1022                 return;
1023         if (td->s)
1024                 free(td->s);
1025         free(obj->data.opaque);
1026         obj->data.opaque = NULL;
1027 }