]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/top/machine.c
This commit was generated by cvs2svn to compensate for changes in r168305,
[FreeBSD/FreeBSD.git] / usr.bin / top / machine.c
1 /*
2  * top - a top users display for Unix
3  *
4  * SYNOPSIS:  For FreeBSD-2.x and later
5  *
6  * DESCRIPTION:
7  * Originally written for BSD4.4 system by Christos Zoulas.
8  * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
9  * Order support hacked in from top-3.5beta6/machine/m_aix41.c
10  *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
11  *
12  * This is the machine-dependent module for FreeBSD 2.2
13  * Works for:
14  *      FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
15  *
16  * LIBS: -lkvm
17  *
18  * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
19  *          Steven Wallace  <swallace@freebsd.org>
20  *          Wolfram Schneider <wosch@FreeBSD.org>
21  *          Thomas Moestl <tmoestl@gmx.net>
22  *
23  * $FreeBSD$
24  */
25
26 #include <sys/param.h>
27 #include <sys/errno.h>
28 #include <sys/file.h>
29 #include <sys/proc.h>
30 #include <sys/resource.h>
31 #include <sys/rtprio.h>
32 #include <sys/signal.h>
33 #include <sys/sysctl.h>
34 #include <sys/time.h>
35 #include <sys/user.h>
36 #include <sys/vmmeter.h>
37
38 #include <kvm.h>
39 #include <math.h>
40 #include <nlist.h>
41 #include <paths.h>
42 #include <pwd.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <strings.h>
47 #include <unistd.h>
48
49 #include "top.h"
50 #include "machine.h"
51 #include "screen.h"
52 #include "utils.h"
53
54 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
55 #define SMPUNAMELEN     13
56 #define UPUNAMELEN      15
57
58 extern struct process_select ps;
59 extern char* printable(char *);
60 static int smpmode;
61 enum displaymodes displaymode;
62 static int namelength = 8;
63 static int cmdlengthdelta;
64
65 /* Prototypes for top internals */
66 void quit(int);
67
68 /* get_process_info passes back a handle.  This is what it looks like: */
69
70 struct handle {
71         struct kinfo_proc **next_proc;  /* points to next valid proc pointer */
72         int remaining;                  /* number of pointers remaining */
73 };
74
75 /* declarations for load_avg */
76 #include "loadavg.h"
77
78 /* define what weighted cpu is.  */
79 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
80                          ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
81
82 /* what we consider to be process size: */
83 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
84
85 #define RU(pp)  (&(pp)->ki_rusage)
86 #define RUTOT(pp) \
87         (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
88
89
90 /* definitions for indices in the nlist array */
91
92 /*
93  *  These definitions control the format of the per-process area
94  */
95
96 static char io_header[] =
97     "  PID %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
98
99 #define io_Proc_format \
100     "%5d %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
101
102 static char smp_header_thr[] =
103     "  PID %-*.*s  THR PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
104 static char smp_header[] =
105     "  PID %-*.*s "   "PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
106
107 #define smp_Proc_format \
108     "%5d %-*.*s %s%3d %4s%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
109
110 static char up_header_thr[] =
111     "  PID %-*.*s  THR PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
112 static char up_header[] =
113     "  PID %-*.*s "   "PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
114
115 #define up_Proc_format \
116     "%5d %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
117
118
119 /* process state names for the "STATE" column of the display */
120 /* the extra nulls in the string "run" are for adding a slash and
121    the processor number when needed */
122
123 char *state_abbrev[] = {
124         "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
125 };
126
127
128 static kvm_t *kd;
129
130 /* values that we stash away in _init and use in later routines */
131
132 static double logcpu;
133
134 /* these are retrieved from the kernel in _init */
135
136 static load_avg  ccpu;
137
138 /* these are used in the get_ functions */
139
140 static int lastpid;
141
142 /* these are for calculating cpu state percentages */
143
144 static long cp_time[CPUSTATES];
145 static long cp_old[CPUSTATES];
146 static long cp_diff[CPUSTATES];
147
148 /* these are for detailing the process states */
149
150 int process_states[8];
151 char *procstatenames[] = {
152         "", " starting, ", " running, ", " sleeping, ", " stopped, ",
153         " zombie, ", " waiting, ", " lock, ",
154         NULL
155 };
156
157 /* these are for detailing the cpu states */
158
159 int cpu_states[CPUSTATES];
160 char *cpustatenames[] = {
161         "user", "nice", "system", "interrupt", "idle", NULL
162 };
163
164 /* these are for detailing the memory statistics */
165
166 int memory_stats[7];
167 char *memorynames[] = {
168         "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
169         "K Free", NULL
170 };
171
172 int swap_stats[7];
173 char *swapnames[] = {
174         "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
175         NULL
176 };
177
178
179 /* these are for keeping track of the proc array */
180
181 static int nproc;
182 static int onproc = -1;
183 static int pref_len;
184 static struct kinfo_proc *pbase;
185 static struct kinfo_proc **pref;
186 static struct kinfo_proc *previous_procs;
187 static struct kinfo_proc **previous_pref;
188 static int previous_proc_count = 0;
189 static int previous_proc_count_max = 0;
190
191 /* total number of io operations */
192 static long total_inblock;
193 static long total_oublock;
194 static long total_majflt;
195
196 /* these are for getting the memory statistics */
197
198 static int pageshift;           /* log base 2 of the pagesize */
199
200 /* define pagetok in terms of pageshift */
201
202 #define pagetok(size) ((size) << pageshift)
203
204 /* useful externals */
205 long percentages();
206
207 #ifdef ORDER
208 /*
209  * Sorting orders.  The first element is the default.
210  */
211 char *ordernames[] = {
212         "cpu", "size", "res", "time", "pri", "threads",
213         "total", "read", "write", "fault", "vcsw", "ivcsw", NULL
214 };
215 #endif
216
217 static int compare_pid(const void *a, const void *b);
218 static const char *format_nice(const struct kinfo_proc *pp);
219 static void getsysctl(const char *name, void *ptr, size_t len);
220 static int swapmode(int *retavail, int *retfree);
221
222 int
223 machine_init(struct statics *statics)
224 {
225         int pagesize;
226         size_t modelen;
227         struct passwd *pw;
228
229         modelen = sizeof(smpmode);
230         if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
231             NULL, 0) != 0 &&
232             sysctlbyname("kern.smp.active", &smpmode, &modelen,
233             NULL, 0) != 0) ||
234             modelen != sizeof(smpmode))
235                 smpmode = 0;
236
237         while ((pw = getpwent()) != NULL) {
238                 if (strlen(pw->pw_name) > namelength)
239                         namelength = strlen(pw->pw_name);
240         }
241         if (smpmode && namelength > SMPUNAMELEN)
242                 namelength = SMPUNAMELEN;
243         else if (namelength > UPUNAMELEN)
244                 namelength = UPUNAMELEN;
245
246         kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
247         if (kd == NULL)
248                 return (-1);
249
250         GETSYSCTL("kern.ccpu", ccpu);
251
252         /* this is used in calculating WCPU -- calculate it ahead of time */
253         logcpu = log(loaddouble(ccpu));
254
255         pbase = NULL;
256         pref = NULL;
257         nproc = 0;
258         onproc = -1;
259
260         /* get the page size and calculate pageshift from it */
261         pagesize = getpagesize();
262         pageshift = 0;
263         while (pagesize > 1) {
264                 pageshift++;
265                 pagesize >>= 1;
266         }
267
268         /* we only need the amount of log(2)1024 for our conversion */
269         pageshift -= LOG1024;
270
271         /* fill in the statics information */
272         statics->procstate_names = procstatenames;
273         statics->cpustate_names = cpustatenames;
274         statics->memory_names = memorynames;
275         statics->swap_names = swapnames;
276 #ifdef ORDER
277         statics->order_names = ordernames;
278 #endif
279
280         /* all done! */
281         return (0);
282 }
283
284 char *
285 format_header(char *uname_field)
286 {
287         static char Header[128];
288         const char *prehead;
289
290         switch (displaymode) {
291         case DISP_CPU:
292                 /*
293                  * The logic of picking the right header format seems reverse
294                  * here because we only want to display a THR column when
295                  * "thread mode" is off (and threads are not listed as
296                  * separate lines).
297                  */
298                 prehead = smpmode ?
299                     (ps.thread ? smp_header : smp_header_thr) :
300                     (ps.thread ? up_header : up_header_thr);
301                 snprintf(Header, sizeof(Header), prehead,
302                     namelength, namelength, uname_field,
303                     ps.wcpu ? "WCPU" : "CPU");
304                 break;
305         case DISP_IO:
306                 prehead = io_header;
307                 snprintf(Header, sizeof(Header), prehead,
308                     namelength, namelength, uname_field);
309                 break;
310         }
311         cmdlengthdelta = strlen(Header) - 7;
312         return (Header);
313 }
314
315 static int swappgsin = -1;
316 static int swappgsout = -1;
317 extern struct timeval timeout;
318
319 void
320 get_system_info(struct system_info *si)
321 {
322         long total;
323         struct loadavg sysload;
324         int mib[2];
325         struct timeval boottime;
326         size_t bt_size;
327         int i;
328
329         /* get the cp_time array */
330         GETSYSCTL("kern.cp_time", cp_time);
331         GETSYSCTL("vm.loadavg", sysload);
332         GETSYSCTL("kern.lastpid", lastpid);
333
334         /* convert load averages to doubles */
335         for (i = 0; i < 3; i++)
336                 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
337
338         /* convert cp_time counts to percentages */
339         total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
340
341         /* sum memory & swap statistics */
342         {
343                 static unsigned int swap_delay = 0;
344                 static int swapavail = 0;
345                 static int swapfree = 0;
346                 static int bufspace = 0;
347                 static int nspgsin, nspgsout;
348
349                 GETSYSCTL("vfs.bufspace", bufspace);
350                 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
351                 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
352                 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
353                 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
354                 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
355                 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
356                 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
357                 /* convert memory stats to Kbytes */
358                 memory_stats[0] = pagetok(memory_stats[0]);
359                 memory_stats[1] = pagetok(memory_stats[1]);
360                 memory_stats[2] = pagetok(memory_stats[2]);
361                 memory_stats[3] = pagetok(memory_stats[3]);
362                 memory_stats[4] = bufspace / 1024;
363                 memory_stats[5] = pagetok(memory_stats[5]);
364                 memory_stats[6] = -1;
365
366                 /* first interval */
367                 if (swappgsin < 0) {
368                         swap_stats[4] = 0;
369                         swap_stats[5] = 0;
370                 }
371
372                 /* compute differences between old and new swap statistic */
373                 else {
374                         swap_stats[4] = pagetok(((nspgsin - swappgsin)));
375                         swap_stats[5] = pagetok(((nspgsout - swappgsout)));
376                 }
377
378                 swappgsin = nspgsin;
379                 swappgsout = nspgsout;
380
381                 /* call CPU heavy swapmode() only for changes */
382                 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
383                         swap_stats[3] = swapmode(&swapavail, &swapfree);
384                         swap_stats[0] = swapavail;
385                         swap_stats[1] = swapavail - swapfree;
386                         swap_stats[2] = swapfree;
387                 }
388                 swap_delay = 1;
389                 swap_stats[6] = -1;
390         }
391
392         /* set arrays and strings */
393         si->cpustates = cpu_states;
394         si->memory = memory_stats;
395         si->swap = swap_stats;
396
397
398         if (lastpid > 0) {
399                 si->last_pid = lastpid;
400         } else {
401                 si->last_pid = -1;
402         }
403
404         /*
405          * Print how long system has been up.
406          * (Found by looking getting "boottime" from the kernel)
407          */
408         mib[0] = CTL_KERN;
409         mib[1] = KERN_BOOTTIME;
410         bt_size = sizeof(boottime);
411         if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
412             boottime.tv_sec != 0) {
413                 si->boottime = boottime;
414         } else {
415                 si->boottime.tv_sec = -1;
416         }
417 }
418
419 #define NOPROC  ((void *)-1)
420
421 /*
422  * We need to compare data from the old process entry with the new
423  * process entry.
424  * To facilitate doing this quickly we stash a pointer in the kinfo_proc
425  * structure to cache the mapping.  We also use a negative cache pointer
426  * of NOPROC to avoid duplicate lookups.
427  * XXX: this could be done when the actual processes are fetched, we do
428  * it here out of laziness.
429  */
430 const struct kinfo_proc *
431 get_old_proc(struct kinfo_proc *pp)
432 {
433         struct kinfo_proc **oldpp, *oldp;
434
435         /*
436          * If this is the first fetch of the kinfo_procs then we don't have
437          * any previous entries.
438          */
439         if (previous_proc_count == 0)
440                 return (NULL);
441         /* negative cache? */
442         if (pp->ki_udata == NOPROC)
443                 return (NULL);
444         /* cached? */
445         if (pp->ki_udata != NULL)
446                 return (pp->ki_udata);
447         /*
448          * Not cached,
449          * 1) look up based on pid.
450          * 2) compare process start.
451          * If we fail here, then setup a negative cache entry, otherwise
452          * cache it.
453          */
454         oldpp = bsearch(&pp, previous_pref, previous_proc_count,
455             sizeof(*previous_pref), compare_pid);
456         if (oldpp == NULL) {
457                 pp->ki_udata = NOPROC;
458                 return (NULL);
459         }
460         oldp = *oldpp;
461         if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
462                 pp->ki_udata = NOPROC;
463                 return (NULL);
464         }
465         pp->ki_udata = oldp;
466         return (oldp);
467 }
468
469 /*
470  * Return the total amount of IO done in blocks in/out and faults.
471  * store the values individually in the pointers passed in.
472  */
473 long
474 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
475     long *vcsw, long *ivcsw)
476 {
477         const struct kinfo_proc *oldp;
478         static struct kinfo_proc dummy;
479         long ret;
480
481         oldp = get_old_proc(pp);
482         if (oldp == NULL) {
483                 bzero(&dummy, sizeof(dummy));
484                 oldp = &dummy;
485         }
486         *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
487         *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
488         *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
489         *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
490         *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
491         ret =
492             (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
493             (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
494             (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
495         return (ret);
496 }
497
498 /*
499  * Return the total number of block in/out and faults by a process.
500  */
501 long
502 get_io_total(struct kinfo_proc *pp)
503 {
504         long dummy;
505
506         return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
507 }
508
509 static struct handle handle;
510
511 caddr_t
512 get_process_info(struct system_info *si, struct process_select *sel,
513     int (*compare)(const void *, const void *))
514 {
515         int i;
516         int total_procs;
517         long p_io;
518         long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
519         int active_procs;
520         struct kinfo_proc **prefp;
521         struct kinfo_proc *pp;
522         struct kinfo_proc *prev_pp = NULL;
523
524         /* these are copied out of sel for speed */
525         int show_idle;
526         int show_self;
527         int show_system;
528         int show_uid;
529         int show_command;
530
531         /*
532          * Save the previous process info.
533          */
534         if (previous_proc_count_max < nproc) {
535                 free(previous_procs);
536                 previous_procs = malloc(nproc * sizeof(*previous_procs));
537                 free(previous_pref);
538                 previous_pref = malloc(nproc * sizeof(*previous_pref));
539                 if (previous_procs == NULL || previous_pref == NULL) {
540                         (void) fprintf(stderr, "top: Out of memory.\n");
541                         quit(23);
542                 }
543                 previous_proc_count_max = nproc;
544         }
545         if (nproc) {
546                 for (i = 0; i < nproc; i++)
547                         previous_pref[i] = &previous_procs[i];
548                 bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
549                 qsort(previous_pref, nproc, sizeof(*previous_pref),
550                     compare_pid);
551         }
552         previous_proc_count = nproc;
553
554         pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
555         if (nproc > onproc)
556                 pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
557         if (pref == NULL || pbase == NULL) {
558                 (void) fprintf(stderr, "top: Out of memory.\n");
559                 quit(23);
560         }
561         /* get a pointer to the states summary array */
562         si->procstates = process_states;
563
564         /* set up flags which define what we are going to select */
565         show_idle = sel->idle;
566         show_self = sel->self == -1;
567         show_system = sel->system;
568         show_uid = sel->uid != -1;
569         show_command = sel->command != NULL;
570
571         /* count up process states and get pointers to interesting procs */
572         total_procs = 0;
573         active_procs = 0;
574         total_inblock = 0;
575         total_oublock = 0;
576         total_majflt = 0;
577         memset((char *)process_states, 0, sizeof(process_states));
578         prefp = pref;
579         for (pp = pbase, i = 0; i < nproc; pp++, i++) {
580
581                 if (pp->ki_stat == 0)
582                         /* not in use */
583                         continue;
584
585                 if (!show_self && pp->ki_pid == sel->self)
586                         /* skip self */
587                         continue;
588
589                 if (!show_system && (pp->ki_flag & P_SYSTEM))
590                         /* skip system process */
591                         continue;
592
593                 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
594                     &p_vcsw, &p_ivcsw);
595                 total_inblock += p_inblock;
596                 total_oublock += p_oublock;
597                 total_majflt += p_majflt;
598                 total_procs++;
599                 process_states[pp->ki_stat]++;
600
601                 if (pp->ki_stat == SZOMB)
602                         /* skip zombies */
603                         continue;
604
605                 if (displaymode == DISP_CPU && !show_idle &&
606                     (pp->ki_pctcpu == 0 ||
607                      pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
608                         /* skip idle or non-running processes */
609                         continue;
610
611                 if (displaymode == DISP_IO && !show_idle && p_io == 0)
612                         /* skip processes that aren't doing I/O */
613                         continue;
614
615                 if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
616                         /* skip proc. that don't belong to the selected UID */
617                         continue;
618
619                 /*
620                  * When not showing threads, take the first thread
621                  * for output and add the fields that we can from
622                  * the rest of the process's threads rather than
623                  * using the system's mostly-broken KERN_PROC_PROC.
624                  */
625                 if (sel->thread || prev_pp == NULL ||
626                     prev_pp->ki_pid != pp->ki_pid) {
627                         *prefp++ = pp;
628                         active_procs++;
629                         prev_pp = pp;
630                 } else {
631                         prev_pp->ki_pctcpu += pp->ki_pctcpu;
632                 }
633         }
634
635         /* if requested, sort the "interesting" processes */
636         if (compare != NULL)
637                 qsort(pref, active_procs, sizeof(*pref), compare);
638
639         /* remember active and total counts */
640         si->p_total = total_procs;
641         si->p_active = pref_len = active_procs;
642
643         /* pass back a handle */
644         handle.next_proc = pref;
645         handle.remaining = active_procs;
646         return ((caddr_t)&handle);
647 }
648
649 static char fmt[128];   /* static area where result is built */
650
651 char *
652 format_next_process(caddr_t handle, char *(*get_userid)(int))
653 {
654         struct kinfo_proc *pp;
655         const struct kinfo_proc *oldp;
656         long cputime;
657         double pct;
658         struct handle *hp;
659         char status[16];
660         int state;
661         struct rusage ru, *rup;
662         long p_tot, s_tot;
663         char *proc_fmt, thr_buf[6];
664
665         /* find and remember the next proc structure */
666         hp = (struct handle *)handle;
667         pp = *(hp->next_proc++);
668         hp->remaining--;
669
670         /* get the process's command name */
671         if ((pp->ki_sflag & PS_INMEM) == 0) {
672                 /*
673                  * Print swapped processes as <pname>
674                  */
675                 size_t len;
676
677                 len = strlen(pp->ki_comm);
678                 if (len > sizeof(pp->ki_comm) - 3)
679                         len = sizeof(pp->ki_comm) - 3;
680                 memmove(pp->ki_comm + 1, pp->ki_comm, len);
681                 pp->ki_comm[0] = '<';
682                 pp->ki_comm[len + 1] = '>';
683                 pp->ki_comm[len + 2] = '\0';
684         }
685
686         /*
687          * Convert the process's runtime from microseconds to seconds.  This
688          * time includes the interrupt time although that is not wanted here.
689          * ps(1) is similarly sloppy.
690          */
691         cputime = (pp->ki_runtime + 500000) / 1000000;
692
693         /* calculate the base for cpu percentages */
694         pct = pctdouble(pp->ki_pctcpu);
695
696         /* generate "STATE" field */
697         switch (state = pp->ki_stat) {
698         case SRUN:
699                 if (smpmode && pp->ki_oncpu != 0xff)
700                         sprintf(status, "CPU%d", pp->ki_oncpu);
701                 else
702                         strcpy(status, "RUN");
703                 break;
704         case SLOCK:
705                 if (pp->ki_kiflag & KI_LOCKBLOCK) {
706                         sprintf(status, "*%.6s", pp->ki_lockname);
707                         break;
708                 }
709                 /* fall through */
710         case SSLEEP:
711                 if (pp->ki_wmesg != NULL) {
712                         sprintf(status, "%.6s", pp->ki_wmesg);
713                         break;
714                 }
715                 /* FALLTHROUGH */
716         default:
717
718                 if (state >= 0 &&
719                     state < sizeof(state_abbrev) / sizeof(*state_abbrev))
720                         sprintf(status, "%.6s", state_abbrev[state]);
721                 else
722                         sprintf(status, "?%5d", state);
723                 break;
724         }
725
726         if (displaymode == DISP_IO) {
727                 oldp = get_old_proc(pp);
728                 if (oldp != NULL) {
729                         ru.ru_inblock = RU(pp)->ru_inblock -
730                             RU(oldp)->ru_inblock;
731                         ru.ru_oublock = RU(pp)->ru_oublock -
732                             RU(oldp)->ru_oublock;
733                         ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
734                         ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
735                         ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
736                         rup = &ru;
737                 } else {
738                         rup = RU(pp);
739                 }
740                 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
741                 s_tot = total_inblock + total_oublock + total_majflt;
742
743                 sprintf(fmt, io_Proc_format,
744                     pp->ki_pid,
745                     namelength, namelength, (*get_userid)(pp->ki_ruid),
746                     rup->ru_nvcsw,
747                     rup->ru_nivcsw,
748                     rup->ru_inblock,
749                     rup->ru_oublock,
750                     rup->ru_majflt,
751                     p_tot,
752                     s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
753                     screen_width > cmdlengthdelta ?
754                     screen_width - cmdlengthdelta : 0,
755                     printable(pp->ki_comm));
756                 return (fmt);
757         }
758
759         /* format this entry */
760         proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
761         if (ps.thread != 0)
762                 thr_buf[0] = '\0';
763         else
764                 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
765                     sizeof(thr_buf) - 2, pp->ki_numthreads);
766
767         sprintf(fmt, proc_fmt,
768             pp->ki_pid,
769             namelength, namelength, (*get_userid)(pp->ki_ruid),
770             thr_buf,
771             pp->ki_pri.pri_level - PZERO,
772             format_nice(pp),
773             format_k2(PROCSIZE(pp)),
774             format_k2(pagetok(pp->ki_rssize)),
775             status,
776             smpmode ? pp->ki_lastcpu : 0,
777             format_time(cputime),
778             ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
779             screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
780             printable(pp->ki_comm));
781
782         /* return the result */
783         return (fmt);
784 }
785
786 static void
787 getsysctl(const char *name, void *ptr, size_t len)
788 {
789         size_t nlen = len;
790
791         if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
792                 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
793                     strerror(errno));
794                 quit(23);
795         }
796         if (nlen != len) {
797                 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
798                     name, (unsigned long)len, (unsigned long)nlen);
799                 quit(23);
800         }
801 }
802
803 static const char *
804 format_nice(const struct kinfo_proc *pp)
805 {
806         const char *fifo, *kthread;
807         int rtpri;
808         static char nicebuf[4 + 1];
809
810         fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
811         kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
812         switch (PRI_BASE(pp->ki_pri.pri_class)) {
813         case PRI_ITHD:
814                 return ("-");
815         case PRI_REALTIME:
816                 rtpri = pp->ki_pri.pri_level - PRI_MIN_REALTIME;
817                 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
818                     kthread, rtpri, fifo);
819                 break;
820         case PRI_TIMESHARE:
821                 if (pp->ki_flag & P_KTHREAD)
822                         return ("-");
823                 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
824                 break;
825         case PRI_IDLE:
826                 rtpri = pp->ki_pri.pri_level - PRI_MIN_IDLE;
827                 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
828                     kthread, rtpri, fifo);
829                 break;
830         default:
831                 return ("?");
832         }
833         return (nicebuf);
834 }
835
836 /* comparison routines for qsort */
837
838 static int
839 compare_pid(const void *p1, const void *p2)
840 {
841         const struct kinfo_proc * const *pp1 = p1;
842         const struct kinfo_proc * const *pp2 = p2;
843
844         if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
845                 abort();
846
847         return ((*pp1)->ki_pid - (*pp2)->ki_pid);
848 }
849
850 /*
851  *  proc_compare - comparison function for "qsort"
852  *      Compares the resource consumption of two processes using five
853  *      distinct keys.  The keys (in descending order of importance) are:
854  *      percent cpu, cpu ticks, state, resident set size, total virtual
855  *      memory usage.  The process states are ordered as follows (from least
856  *      to most important):  WAIT, zombie, sleep, stop, start, run.  The
857  *      array declaration below maps a process state index into a number
858  *      that reflects this ordering.
859  */
860
861 static int sorted_state[] = {
862         0,      /* not used             */
863         3,      /* sleep                */
864         1,      /* ABANDONED (WAIT)     */
865         6,      /* run                  */
866         5,      /* start                */
867         2,      /* zombie               */
868         4       /* stop                 */
869 };
870
871
872 #define ORDERKEY_PCTCPU(a, b) do { \
873         long diff; \
874         if (ps.wcpu) \
875                 diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
876                     (b))) - \
877                     floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
878                     (a))); \
879         else \
880                 diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
881         if (diff != 0) \
882                 return (diff > 0 ? 1 : -1); \
883 } while (0)
884
885 #define ORDERKEY_CPTICKS(a, b) do { \
886         int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
887         if (diff != 0) \
888                 return (diff > 0 ? 1 : -1); \
889 } while (0)
890
891 #define ORDERKEY_STATE(a, b) do { \
892         int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
893         if (diff != 0) \
894                 return (diff > 0 ? 1 : -1); \
895 } while (0)
896
897 #define ORDERKEY_PRIO(a, b) do { \
898         int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
899         if (diff != 0) \
900                 return (diff > 0 ? 1 : -1); \
901 } while (0)
902
903 #define ORDERKEY_THREADS(a, b) do { \
904         int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
905         if (diff != 0) \
906                 return (diff > 0 ? 1 : -1); \
907 } while (0)
908
909 #define ORDERKEY_RSSIZE(a, b) do { \
910         long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
911         if (diff != 0) \
912                 return (diff > 0 ? 1 : -1); \
913 } while (0)
914
915 #define ORDERKEY_MEM(a, b) do { \
916         long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
917         if (diff != 0) \
918                 return (diff > 0 ? 1 : -1); \
919 } while (0)
920
921 /* compare_cpu - the comparison function for sorting by cpu percentage */
922
923 int
924 #ifdef ORDER
925 compare_cpu(void *arg1, void *arg2)
926 #else
927 proc_compare(void *arg1, void *arg2)
928 #endif
929 {
930         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
931         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
932
933         ORDERKEY_PCTCPU(p1, p2);
934         ORDERKEY_CPTICKS(p1, p2);
935         ORDERKEY_STATE(p1, p2);
936         ORDERKEY_PRIO(p1, p2);
937         ORDERKEY_RSSIZE(p1, p2);
938         ORDERKEY_MEM(p1, p2);
939
940         return (0);
941 }
942
943 #ifdef ORDER
944 /* "cpu" compare routines */
945 int compare_size(), compare_res(), compare_time(), compare_prio(),
946     compare_threads();
947
948 /*
949  * "io" compare routines.  Context switches aren't i/o, but are displayed
950  * on the "io" display.
951  */
952 int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
953     compare_vcsw(), compare_ivcsw();
954
955 int (*compares[])() = {
956         compare_cpu,
957         compare_size,
958         compare_res,
959         compare_time,
960         compare_prio,
961         compare_threads,
962         compare_iototal,
963         compare_ioread,
964         compare_iowrite,
965         compare_iofault,
966         compare_vcsw,
967         compare_ivcsw,
968         NULL
969 };
970
971 /* compare_size - the comparison function for sorting by total memory usage */
972
973 int
974 compare_size(void *arg1, void *arg2)
975 {
976         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
977         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
978
979         ORDERKEY_MEM(p1, p2);
980         ORDERKEY_RSSIZE(p1, p2);
981         ORDERKEY_PCTCPU(p1, p2);
982         ORDERKEY_CPTICKS(p1, p2);
983         ORDERKEY_STATE(p1, p2);
984         ORDERKEY_PRIO(p1, p2);
985
986         return (0);
987 }
988
989 /* compare_res - the comparison function for sorting by resident set size */
990
991 int
992 compare_res(void *arg1, void *arg2)
993 {
994         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
995         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
996
997         ORDERKEY_RSSIZE(p1, p2);
998         ORDERKEY_MEM(p1, p2);
999         ORDERKEY_PCTCPU(p1, p2);
1000         ORDERKEY_CPTICKS(p1, p2);
1001         ORDERKEY_STATE(p1, p2);
1002         ORDERKEY_PRIO(p1, p2);
1003
1004         return (0);
1005 }
1006
1007 /* compare_time - the comparison function for sorting by total cpu time */
1008
1009 int
1010 compare_time(void *arg1, void *arg2)
1011 {
1012         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1013         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1014
1015         ORDERKEY_CPTICKS(p1, p2);
1016         ORDERKEY_PCTCPU(p1, p2);
1017         ORDERKEY_STATE(p1, p2);
1018         ORDERKEY_PRIO(p1, p2);
1019         ORDERKEY_RSSIZE(p1, p2);
1020         ORDERKEY_MEM(p1, p2);
1021
1022         return (0);
1023 }
1024
1025 /* compare_prio - the comparison function for sorting by priority */
1026
1027 int
1028 compare_prio(void *arg1, void *arg2)
1029 {
1030         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1031         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1032
1033         ORDERKEY_PRIO(p1, p2);
1034         ORDERKEY_CPTICKS(p1, p2);
1035         ORDERKEY_PCTCPU(p1, p2);
1036         ORDERKEY_STATE(p1, p2);
1037         ORDERKEY_RSSIZE(p1, p2);
1038         ORDERKEY_MEM(p1, p2);
1039
1040         return (0);
1041 }
1042
1043 /* compare_threads - the comparison function for sorting by threads */
1044 int
1045 compare_threads(void *arg1, void *arg2)
1046 {
1047         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1048         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1049
1050         ORDERKEY_THREADS(p1, p2);
1051         ORDERKEY_PCTCPU(p1, p2);
1052         ORDERKEY_CPTICKS(p1, p2);
1053         ORDERKEY_STATE(p1, p2);
1054         ORDERKEY_PRIO(p1, p2);
1055         ORDERKEY_RSSIZE(p1, p2);
1056         ORDERKEY_MEM(p1, p2);
1057
1058         return (0);
1059 }
1060 #endif /* ORDER */
1061
1062 /* assorted comparison functions for sorting by i/o */
1063
1064 int
1065 #ifdef ORDER
1066 compare_iototal(void *arg1, void *arg2)
1067 #else
1068 io_compare(void *arg1, void *arg2)
1069 #endif
1070 {
1071         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1072         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1073
1074         return (get_io_total(p2) - get_io_total(p1));
1075 }
1076
1077 #ifdef ORDER
1078 int
1079 compare_ioread(void *arg1, void *arg2)
1080 {
1081         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1082         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1083         long dummy, inp1, inp2;
1084
1085         (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1086         (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1087
1088         return (inp2 - inp1);
1089 }
1090
1091 int
1092 compare_iowrite(void *arg1, void *arg2)
1093 {
1094         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1095         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1096         long dummy, oup1, oup2;
1097
1098         (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1099         (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1100
1101         return (oup2 - oup1);
1102 }
1103
1104 int
1105 compare_iofault(void *arg1, void *arg2)
1106 {
1107         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1108         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1109         long dummy, flp1, flp2;
1110
1111         (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1112         (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1113
1114         return (flp2 - flp1);
1115 }
1116
1117 int
1118 compare_vcsw(void *arg1, void *arg2)
1119 {
1120         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1121         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1122         long dummy, flp1, flp2;
1123
1124         (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1125         (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1126
1127         return (flp2 - flp1);
1128 }
1129
1130 int
1131 compare_ivcsw(void *arg1, void *arg2)
1132 {
1133         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1134         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1135         long dummy, flp1, flp2;
1136
1137         (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1138         (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1139
1140         return (flp2 - flp1);
1141 }
1142 #endif /* ORDER */
1143
1144 /*
1145  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1146  *              the process does not exist.
1147  *              It is EXTREMLY IMPORTANT that this function work correctly.
1148  *              If top runs setuid root (as in SVR4), then this function
1149  *              is the only thing that stands in the way of a serious
1150  *              security problem.  It validates requests for the "kill"
1151  *              and "renice" commands.
1152  */
1153
1154 int
1155 proc_owner(int pid)
1156 {
1157         int cnt;
1158         struct kinfo_proc **prefp;
1159         struct kinfo_proc *pp;
1160
1161         prefp = pref;
1162         cnt = pref_len;
1163         while (--cnt >= 0) {
1164                 pp = *prefp++;
1165                 if (pp->ki_pid == (pid_t)pid)
1166                         return ((int)pp->ki_ruid);
1167         }
1168         return (-1);
1169 }
1170
1171 static int
1172 swapmode(int *retavail, int *retfree)
1173 {
1174         int n;
1175         int pagesize = getpagesize();
1176         struct kvm_swap swapary[1];
1177
1178         *retavail = 0;
1179         *retfree = 0;
1180
1181 #define CONVERT(v)      ((quad_t)(v) * pagesize / 1024)
1182
1183         n = kvm_getswapinfo(kd, swapary, 1, 0);
1184         if (n < 0 || swapary[0].ksw_total == 0)
1185                 return (0);
1186
1187         *retavail = CONVERT(swapary[0].ksw_total);
1188         *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1189
1190         n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1191         return (n);
1192 }