mkfs: drop support for running on DOS
[minix.git] / usr.bin / top / top.c
blob7b3fd2262fc18022c1e589ce82db98b057d10c60
2 /* Author: Ben Gras <beng@few.vu.nl> 17 march 2006 */
3 /* Modified for ProcFS by Alen Stojanov and David van Moolenbroek */
5 #define _MINIX 1
6 #ifndef __NBSD_LIBC
7 #define _POSIX_SOURCE 1
8 #endif
10 #include <stdio.h>
11 #include <unistd.h>
12 #include <pwd.h>
13 #include <curses.h>
14 #include <timers.h>
15 #include <stdlib.h>
16 #include <limits.h>
17 #include <termcap.h>
18 #include <termios.h>
19 #include <time.h>
20 #include <string.h>
21 #include <signal.h>
22 #include <fcntl.h>
23 #include <errno.h>
24 #include <dirent.h>
25 #include <assert.h>
27 #include <sys/ioc_tty.h>
28 #include <sys/times.h>
29 #include <sys/types.h>
30 #include <sys/time.h>
31 #include <sys/select.h>
33 #include <minix/com.h>
34 #include <minix/config.h>
35 #include <minix/type.h>
36 #include <minix/endpoint.h>
37 #include <minix/const.h>
38 #include <minix/u64.h>
39 #include <paths.h>
40 #include <minix/procfs.h>
42 #define TIMECYCLEKEY 't'
43 #define ORDERKEY 'o'
45 #define ORDER_CPU 0
46 #define ORDER_MEMORY 1
47 #define ORDER_HIGHEST ORDER_MEMORY
48 int order = ORDER_CPU;
50 u32_t system_hz;
52 /* name of cpu cycle types, in the order they appear in /psinfo. */
53 char *cputimenames[] = { "user", "ipc", "kernelcall" };
55 #define CPUTIMENAMES (sizeof(cputimenames)/sizeof(cputimenames[0]))
57 #define CPUTIME(m, i) (m & (1L << (i)))
59 unsigned int nr_procs, nr_tasks;
60 int nr_total;
62 #define SLOT_NR(e) (_ENDPOINT_P(e) + nr_tasks)
64 #define TC_BUFFER 1024 /* Size of termcap(3) buffer */
65 #define TC_STRINGS 200 /* Enough room for cm,cl,so,se */
67 char *Tclr_all;
69 int blockedverbose = 0;
71 #define USED 0x1
72 #define IS_TASK 0x2
73 #define IS_SYSTEM 0x4
74 #define BLOCKED 0x8
76 struct proc {
77 int p_flags;
78 endpoint_t p_endpoint;
79 pid_t p_pid;
80 u64_t p_cpucycles[CPUTIMENAMES];
81 int p_priority;
82 endpoint_t p_blocked;
83 time_t p_user_time;
84 vir_bytes p_memory;
85 uid_t p_effuid;
86 int p_nice;
87 char p_name[PROC_NAME_LEN+1];
90 struct proc *proc = NULL, *prev_proc = NULL;
92 void parse_file(pid_t pid)
94 char path[PATH_MAX], name[256], type, state;
95 int version, endpt, effuid;
96 unsigned long cycles_hi, cycles_lo;
97 FILE *fp;
98 struct proc *p;
99 int slot;
100 int i;
102 sprintf(path, "%d/psinfo", pid);
104 if ((fp = fopen(path, "r")) == NULL)
105 return;
107 if (fscanf(fp, "%d", &version) != 1) {
108 fclose(fp);
109 return;
112 if (version != PSINFO_VERSION) {
113 fputs("procfs version mismatch!\n", stderr);
114 exit(1);
117 if (fscanf(fp, " %c %d", &type, &endpt) != 2) {
118 fclose(fp);
119 return;
122 slot = SLOT_NR(endpt);
124 if(slot < 0 || slot >= nr_total) {
125 fprintf(stderr, "top: unreasonable endpoint number %d\n", endpt);
126 fclose(fp);
127 return;
130 p = &proc[slot];
132 if (type == TYPE_TASK)
133 p->p_flags |= IS_TASK;
134 else if (type == TYPE_SYSTEM)
135 p->p_flags |= IS_SYSTEM;
137 p->p_endpoint = endpt;
138 p->p_pid = pid;
140 if (fscanf(fp, " %255s %c %d %d %lu %*u %lu %lu",
141 name, &state, &p->p_blocked, &p->p_priority,
142 &p->p_user_time, &cycles_hi, &cycles_lo) != 7) {
144 fclose(fp);
145 return;
148 strncpy(p->p_name, name, sizeof(p->p_name)-1);
149 p->p_name[sizeof(p->p_name)-1] = 0;
151 if (state != STATE_RUN)
152 p->p_flags |= BLOCKED;
153 p->p_cpucycles[0] = make64(cycles_lo, cycles_hi);
154 p->p_memory = 0L;
156 if (!(p->p_flags & IS_TASK)) {
157 int i;
158 if ((i=fscanf(fp, " %lu %*u %*u %*c %*d %*u %u %*u %d %*c %*d %*u",
159 &p->p_memory, &effuid, &p->p_nice)) != 3) {
161 fclose(fp);
162 return;
165 p->p_effuid = effuid;
166 } else p->p_effuid = 0;
168 for(i = 1; i < CPUTIMENAMES; i++) {
169 if(fscanf(fp, " %lu %lu",
170 &cycles_hi, &cycles_lo) == 2) {
171 p->p_cpucycles[i] = make64(cycles_lo, cycles_hi);
172 } else {
173 p->p_cpucycles[i] = 0;
177 if ((p->p_flags & IS_TASK)) {
178 if(fscanf(fp, " %lu", &p->p_memory) != 1) {
179 p->p_memory = 0;
183 p->p_flags |= USED;
185 fclose(fp);
188 void parse_dir(void)
190 DIR *p_dir;
191 struct dirent *p_ent;
192 pid_t pid;
193 char *end;
195 if ((p_dir = opendir(".")) == NULL) {
196 perror("opendir on " _PATH_PROC);
197 exit(1);
200 for (p_ent = readdir(p_dir); p_ent != NULL; p_ent = readdir(p_dir)) {
201 pid = strtol(p_ent->d_name, &end, 10);
203 if (!end[0] && pid != 0)
204 parse_file(pid);
207 closedir(p_dir);
210 void get_procs(void)
212 struct proc *p;
213 int i;
215 p = prev_proc;
216 prev_proc = proc;
217 proc = p;
219 if (proc == NULL) {
220 proc = malloc(nr_total * sizeof(proc[0]));
222 if (proc == NULL) {
223 fprintf(stderr, "Out of memory!\n");
224 exit(1);
228 for (i = 0; i < nr_total; i++)
229 proc[i].p_flags = 0;
231 parse_dir();
234 int print_memory(void)
236 FILE *fp;
237 unsigned int pagesize;
238 unsigned long total, free, largest, cached;
240 if ((fp = fopen("meminfo", "r")) == NULL)
241 return 0;
243 if (fscanf(fp, "%u %lu %lu %lu %lu", &pagesize, &total, &free,
244 &largest, &cached) != 5) {
245 fclose(fp);
246 return 0;
249 fclose(fp);
251 printf("main memory: %ldK total, %ldK free, %ldK contig free, "
252 "%ldK cached\n",
253 (pagesize * total)/1024, (pagesize * free)/1024,
254 (pagesize * largest)/1024, (pagesize * cached)/1024);
256 return 1;
259 int print_load(double *loads, int nloads)
261 int i;
262 printf("load averages: ");
263 for(i = 0; i < nloads; i++)
264 printf("%s %.2f", (i > 0) ? "," : "", loads[i]);
265 printf("\n");
266 return 1;
269 int print_proc_summary(struct proc *proc)
271 int p, alive, running, sleeping;
273 alive = running = sleeping = 0;
275 for(p = 0; p < nr_total; p++) {
276 if (proc[p].p_endpoint == IDLE)
277 continue;
278 if(!(proc[p].p_flags & USED))
279 continue;
280 alive++;
281 if(proc[p].p_flags & BLOCKED)
282 sleeping++;
283 else
284 running++;
286 printf("%d processes: %d running, %d sleeping\n",
287 alive, running, sleeping);
288 return 1;
291 struct tp {
292 struct proc *p;
293 u64_t ticks;
296 int cmp_procs(const void *v1, const void *v2)
298 struct tp *p1 = (struct tp *) v1, *p2 = (struct tp *) v2;
299 int p1blocked, p2blocked;
301 if(order == ORDER_MEMORY) {
302 if(p1->p->p_memory < p2->p->p_memory) return 1;
303 if(p1->p->p_memory > p2->p->p_memory) return -1;
304 return 0;
307 p1blocked = !!(p1->p->p_flags & BLOCKED);
308 p2blocked = !!(p2->p->p_flags & BLOCKED);
310 /* Primarily order by used number of cpu cycles.
312 * Exception: if in blockedverbose mode, a blocked
313 * process is always printed after an unblocked
314 * process, and used cpu cycles don't matter.
316 * In both cases, process slot number is a tie breaker.
319 if(blockedverbose && (p1blocked || p2blocked)) {
320 if(!p1blocked && p2blocked)
321 return -1;
322 if(!p2blocked && p1blocked)
323 return 1;
324 } else if(p1->ticks != p2->ticks) {
325 return (p2->ticks - p1->ticks);
328 /* Process slot number is a tie breaker. */
329 return (int) (p1->p - p2->p);
332 struct tp *lookup(endpoint_t who, struct tp *tptab, int np)
334 int t;
336 for(t = 0; t < np; t++)
337 if(who == tptab[t].p->p_endpoint)
338 return &tptab[t];
340 fprintf(stderr, "lookup: tp %d (0x%x) not found.\n", who, who);
341 abort();
343 return NULL;
346 double ktotal = 0;
348 void print_proc(struct tp *tp, u64_t total_ticks)
350 int euid = 0;
351 static struct passwd *who = NULL;
352 static int last_who = -1;
353 char *name = "";
354 int ticks;
355 struct proc *pr = tp->p;
357 printf("%5d ", pr->p_pid);
358 euid = pr->p_effuid;
359 name = pr->p_name;
361 if(last_who != euid || !who) {
362 who = getpwuid(euid);
363 last_who = euid;
366 if(who && who->pw_name) printf("%-8s ", who->pw_name);
367 else if(!(pr->p_flags & IS_TASK)) printf("%8d ", pr->p_effuid);
368 else printf(" ");
370 printf(" %2d ", pr->p_priority);
371 if(!(pr->p_flags & IS_TASK)) {
372 printf(" %3d ", pr->p_nice);
373 } else printf(" ");
374 printf("%6ldK", (pr->p_memory + 512) / 1024);
375 printf("%6s", (pr->p_flags & BLOCKED) ? "" : "RUN");
376 ticks = pr->p_user_time;
377 printf(" %3u:%02u ", (ticks/system_hz/60), (ticks/system_hz)%60);
379 printf("%6.2f%% %s", 100.0 * tp->ticks / total_ticks, name);
382 char *cputimemodename(int cputimemode)
384 static char name[100];
385 int i;
387 name[0] = '\0';
389 for(i = 0; i < CPUTIMENAMES; i++) {
390 if(CPUTIME(cputimemode, i)) {
391 assert(strlen(name) +
392 strlen(cputimenames[i]) < sizeof(name));
393 strcat(name, cputimenames[i]);
394 strcat(name, " ");
398 return name;
401 u64_t cputicks(struct proc *p1, struct proc *p2, int timemode)
403 int i;
404 u64_t t = 0;
405 for(i = 0; i < CPUTIMENAMES; i++) {
406 if(!CPUTIME(timemode, i))
407 continue;
408 if(p1->p_endpoint == p2->p_endpoint) {
409 t = t + p2->p_cpucycles[i] - p1->p_cpucycles[i];
410 } else {
411 t = t + p2->p_cpucycles[i];
415 return t;
418 char *ordername(int orderno)
420 switch(orderno) {
421 case ORDER_CPU: return "cpu";
422 case ORDER_MEMORY: return "memory";
424 return "invalid order";
427 void print_procs(int maxlines,
428 struct proc *proc1, struct proc *proc2, int cputimemode)
430 int p, nprocs;
431 u64_t idleticks = 0;
432 u64_t kernelticks = 0;
433 u64_t systemticks = 0;
434 u64_t userticks = 0;
435 u64_t total_ticks = 0;
436 int blockedseen = 0;
437 static struct tp *tick_procs = NULL;
439 if (tick_procs == NULL) {
440 tick_procs = malloc(nr_total * sizeof(tick_procs[0]));
442 if (tick_procs == NULL) {
443 fprintf(stderr, "Out of memory!\n");
444 exit(1);
448 for(p = nprocs = 0; p < nr_total; p++) {
449 u64_t uticks;
450 if(!(proc2[p].p_flags & USED))
451 continue;
452 tick_procs[nprocs].p = proc2 + p;
453 tick_procs[nprocs].ticks = cputicks(&proc1[p], &proc2[p], cputimemode);
454 uticks = cputicks(&proc1[p], &proc2[p], 1);
455 total_ticks = total_ticks + uticks;
456 if(p-NR_TASKS == IDLE) {
457 idleticks = uticks;
458 continue;
460 if(p-NR_TASKS == KERNEL) {
461 kernelticks = uticks;
463 if(!(proc2[p].p_flags & IS_TASK)) {
464 if(proc2[p].p_flags & IS_SYSTEM)
465 systemticks = systemticks + tick_procs[nprocs].ticks;
466 else
467 userticks = userticks + tick_procs[nprocs].ticks;
470 nprocs++;
473 if (total_ticks == 0)
474 return;
476 qsort(tick_procs, nprocs, sizeof(tick_procs[0]), cmp_procs);
478 printf("CPU states: %6.2f%% user, ", 100.0 * userticks / total_ticks);
479 printf("%6.2f%% system, ", 100.0 * systemticks / total_ticks);
480 printf("%6.2f%% kernel, ", 100.0 * kernelticks/ total_ticks);
481 printf("%6.2f%% idle", 100.0 * idleticks / total_ticks);
483 #define NEWLINE do { printf("\n"); if(--maxlines <= 0) { return; } } while(0)
484 NEWLINE;
486 printf("CPU time displayed ('%c' to cycle): %s; ",
487 TIMECYCLEKEY, cputimemodename(cputimemode));
488 printf(" sort order ('%c' to cycle): %s", ORDERKEY, ordername(order));
489 NEWLINE;
491 NEWLINE;
493 printf(" PID USERNAME PRI NICE SIZE STATE TIME CPU COMMAND");
494 NEWLINE;
495 for(p = 0; p < nprocs; p++) {
496 struct proc *pr;
497 int level = 0;
499 pr = tick_procs[p].p;
501 if((pr->p_flags & IS_TASK) && pr->p_pid != KERNEL) {
502 /* skip old kernel tasks as they don't run anymore */
503 continue;
506 /* If we're in blocked verbose mode, indicate start of
507 * blocked processes.
509 if(blockedverbose && (pr->p_flags & BLOCKED) && !blockedseen) {
510 NEWLINE;
511 printf("Blocked processes:");
512 NEWLINE;
513 blockedseen = 1;
516 print_proc(&tick_procs[p], total_ticks);
517 NEWLINE;
519 if(!blockedverbose)
520 continue;
522 /* Traverse dependency chain if blocked. */
523 while(pr->p_flags & BLOCKED) {
524 endpoint_t dep = NONE;
525 struct tp *tpdep;
526 level += 5;
528 if((dep = pr->p_blocked) == NONE) {
529 printf("not blocked on a process");
530 NEWLINE;
531 break;
534 if(dep == ANY)
535 break;
537 tpdep = lookup(dep, tick_procs, nprocs);
538 pr = tpdep->p;
539 printf("%*s> ", level, "");
540 print_proc(tpdep, total_ticks);
541 NEWLINE;
546 void showtop(int cputimemode, int r)
548 #define NLOADS 3
549 double loads[NLOADS];
550 int nloads, lines = 0;
551 struct winsize winsize;
553 if(ioctl(STDIN_FILENO, TIOCGWINSZ, &winsize) != 0) {
554 perror("TIOCGWINSZ");
555 fprintf(stderr, "TIOCGWINSZ failed\n");
556 exit(1);
559 get_procs();
560 if (prev_proc == NULL)
561 get_procs();
563 if((nloads = getloadavg(loads, NLOADS)) != NLOADS) {
564 fprintf(stderr, "getloadavg() failed - %d loads\n", nloads);
565 exit(1);
569 printf("%s", Tclr_all);
571 lines += print_load(loads, NLOADS);
572 lines += print_proc_summary(proc);
573 lines += print_memory();
575 if(winsize.ws_row > 0) r = winsize.ws_row;
577 print_procs(r - lines - 2, prev_proc, proc, cputimemode);
578 fflush(NULL);
581 void init(int *rows)
583 char *term;
584 static char buffer[TC_BUFFER], strings[TC_STRINGS];
585 char *s = strings, *v;
587 *rows = 0;
589 if(!(term = getenv("TERM"))) {
590 fprintf(stderr, "No TERM set\n");
591 exit(1);
594 if ( tgetent( buffer, term ) != 1 ) {
595 fprintf(stderr, "tgetent failed for term %s\n", term);
596 exit(1);
599 initscr();
600 cbreak();
602 if ( (Tclr_all = tgetstr( "cl", &s )) == NULL )
603 Tclr_all = "\f";
605 if((v = tgetstr ("li", &s)) != NULL)
606 sscanf(v, "%d", rows);
607 if(*rows < 1) *rows = 24;
610 void sigwinch(int sig) { }
612 void getkinfo(void)
614 FILE *fp;
616 if ((fp = fopen("kinfo", "r")) == NULL) {
617 fprintf(stderr, "opening " _PATH_PROC "kinfo failed\n");
618 exit(1);
621 if (fscanf(fp, "%u %u", &nr_procs, &nr_tasks) != 2) {
622 fprintf(stderr, "reading from " _PATH_PROC "kinfo failed\n");
623 exit(1);
626 fclose(fp);
628 nr_total = (int) (nr_procs + nr_tasks);
631 int main(int argc, char *argv[])
633 int r, c, s = 0;
634 int cputimemode = 1; /* bitmap. */
636 if (chdir(_PATH_PROC) != 0) {
637 perror("chdir to " _PATH_PROC);
638 return 1;
641 system_hz = (u32_t) sysconf(_SC_CLK_TCK);
643 getkinfo();
645 init(&r);
647 while((c=getopt(argc, argv, "s:B")) != EOF) {
648 switch(c) {
649 case 's':
650 s = atoi(optarg);
651 break;
652 case 'B':
653 blockedverbose = 1;
654 break;
655 default:
656 fprintf(stderr,
657 "Usage: %s [-s<secdelay>] [-B]\n",
658 argv[0]);
659 return 1;
663 if(s < 1)
664 s = 2;
666 /* Catch window size changes so display is updated properly
667 * right away.
669 signal(SIGWINCH, sigwinch);
671 while(1) {
672 fd_set fds;
673 int ns;
674 struct timeval tv;
675 showtop(cputimemode, r);
676 tv.tv_sec = s;
677 tv.tv_usec = 0;
679 FD_ZERO(&fds);
680 FD_SET(STDIN_FILENO, &fds);
682 if((ns=select(STDIN_FILENO+1, &fds, NULL, NULL, &tv)) < 0
683 && errno != EINTR) {
684 perror("select");
685 sleep(1);
688 if(ns > 0 && FD_ISSET(STDIN_FILENO, &fds)) {
689 char c;
690 if(read(STDIN_FILENO, &c, 1) == 1) {
691 switch(c) {
692 case 'q':
693 putchar('\r');
694 return 0;
695 break;
696 case 'o':
697 order++;
698 if(order > ORDER_HIGHEST)
699 order = 0;
700 break;
701 case TIMECYCLEKEY:
702 cputimemode++;
703 if(cputimemode >= (1L << CPUTIMENAMES))
704 cputimemode = 1;
705 break;
711 return 0;