Merge branch 'vendor/XZ'
[dragonfly.git] / usr.bin / top / m_dragonfly.c
1 /*
2  * top - a top users display for Unix
3  *
4  * SYNOPSIS:  For DragonFly 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 DragonFly 2.5.1
13  * Should work for:
14  *      DragonFly 2.x and above
15  *
16  * LIBS: -lkvm
17  *
18  * AUTHOR: Jan Lentfer <Jan.Lentfer@web.de>
19  * This module has been put together from different sources and is based on the
20  * work of many other people, e.g. Matthew Dillon, Simon Schubert, Jordan Gordeev.
21  *
22  * $FreeBSD: src/usr.bin/top/machine.c,v 1.29.2.2 2001/07/31 20:27:05 tmm Exp $
23  */
24
25 #include <sys/user.h>
26 #include <sys/types.h>
27 #include <sys/time.h>
28 #include <sys/signal.h>
29 #include <sys/param.h>
30
31 #include "os.h"
32 #include <err.h>
33 #include <kvm.h>
34 #include <stdio.h>
35 #include <unistd.h>
36 #include <math.h>
37 #include <pwd.h>
38 #include <sys/errno.h>
39 #include <sys/sysctl.h>
40 #include <sys/file.h>
41 #include <sys/vmmeter.h>
42 #include <sys/resource.h>
43 #include <sys/rtprio.h>
44
45 /* Swap */
46 #include <stdlib.h>
47 #include <sys/conf.h>
48
49 #include <osreldate.h>          /* for changes in kernel structures */
50
51 #include <sys/kinfo.h>
52 #include <kinfo.h>
53 #include "top.h"
54 #include "display.h"
55 #include "machine.h"
56 #include "screen.h"
57 #include "utils.h"
58
59 int swapmode(int *retavail, int *retfree);
60 static int smpmode;
61 static int namelength;
62 static int cmdlength;
63 static int show_fullcmd;
64
65 int n_cpus = 0;
66
67 /* get_process_info passes back a handle.  This is what it looks like: */
68
69 struct handle {
70         struct kinfo_proc **next_proc;  /* points to next valid proc pointer */
71         int remaining;          /* number of pointers remaining */
72 };
73
74 /* declarations for load_avg */
75 #include "loadavg.h"
76
77 #define PP(pp, field) ((pp)->kp_ ## field)
78 #define LP(pp, field) ((pp)->kp_lwp.kl_ ## field)
79 #define VP(pp, field) ((pp)->kp_vm_ ## field)
80
81 /* define what weighted cpu is.  */
82 #define weighted_cpu(pct, pp) (PP((pp), swtime) == 0 ? 0.0 : \
83                          ((pct) / (1.0 - exp(PP((pp), swtime) * logcpu))))
84
85 /* what we consider to be process size: */
86 #define PROCSIZE(pp) (VP((pp), map_size) / 1024)
87
88 /*
89  * These definitions control the format of the per-process area
90  */
91
92 static char smp_header[] =
93 "  PID %-*.*s NICE  SIZE   PRES   STATE CPU  TIME   CTIME    CPU COMMAND";
94
95 #define smp_Proc_format \
96         "%5d %-*.*s %3d%7s %6s %7.7s %2d %6s %7s %5.2f%% %.*s"
97
98 static char up_header[] =
99 "  PID %-*.*s NICE  SIZE   PRES   STATE    TIME   CTIME    CPU COMMAND";
100
101 #define up_Proc_format \
102         "%5d %-*.*s %3d%7s %6s %7.7s%.0d %7s %7s %5.2f%% %.*s"
103
104
105 /* process state names for the "STATE" column of the display */
106 /*
107  * the extra nulls in the string "run" are for adding a slash and the
108  * processor number when needed
109  */
110
111 const char *state_abbrev[] = {
112         "", "RUN\0\0\0", "STOP", "SLEEP",
113 };
114
115
116 static kvm_t *kd;
117
118 /* values that we stash away in _init and use in later routines */
119
120 static double logcpu;
121
122 static long lastpid;
123 static int ccpu;
124
125 /* these are for calculating cpu state percentages */
126
127 static struct kinfo_cputime *cp_time, *cp_old;
128
129 /* these are for detailing the process states */
130
131 int process_states[6];
132 char *procstatenames[] = {
133         " running, ", " idle, ", " active, ", " stopped, ", " zombie, ",
134         NULL
135 };
136
137 /* these are for detailing the cpu states */
138 #define CPU_STATES 5
139 int *cpu_states;
140 char *cpustatenames[CPU_STATES + 1] = {
141         "user", "nice", "system", "interrupt", "idle", NULL
142 };
143
144 /* these are for detailing the memory statistics */
145
146 long memory_stats[7];
147 char *memorynames[] = {
148         "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
149         NULL
150 };
151
152 long swap_stats[7];
153 char *swapnames[] = {
154         /* 0           1            2           3            4       5 */
155         "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
156         NULL
157 };
158
159
160 /* these are for keeping track of the proc array */
161
162 static int nproc;
163 static int onproc = -1;
164 static int pref_len;
165 static struct kinfo_proc *pbase;
166 static struct kinfo_proc **pref;
167
168 /* these are for getting the memory statistics */
169
170 static int pageshift;           /* log base 2 of the pagesize */
171
172 /* define pagetok in terms of pageshift */
173
174 #define pagetok(size) ((size) << pageshift)
175
176 /* sorting orders. first is default */
177 char *ordernames[] = {
178   "cpu", "size", "res", "time", "pri", "thr", "pid", "ctime",  "pres", NULL
179 };
180
181 /* compare routines */
182 int proc_compare (struct kinfo_proc **, struct kinfo_proc **);
183 int compare_size (struct kinfo_proc **, struct kinfo_proc **);
184 int compare_res (struct kinfo_proc **, struct kinfo_proc **);
185 int compare_time (struct kinfo_proc **, struct kinfo_proc **);
186 int compare_ctime (struct kinfo_proc **, struct kinfo_proc **);
187 int compare_prio(struct kinfo_proc **, struct kinfo_proc **);
188 int compare_thr (struct kinfo_proc **, struct kinfo_proc **);
189 int compare_pid (struct kinfo_proc **, struct kinfo_proc **);
190 int compare_pres(struct kinfo_proc **, struct kinfo_proc **);
191
192 int (*proc_compares[]) (struct kinfo_proc **,struct kinfo_proc **) = {
193         proc_compare,
194         compare_size,
195         compare_res,
196         compare_time,
197         compare_prio,
198         compare_thr,
199         compare_pid,
200         compare_ctime,
201         compare_pres,
202         NULL
203 };
204
205 static void
206 cputime_percentages(int out[CPU_STATES], struct kinfo_cputime *new,
207     struct kinfo_cputime *old)
208 {
209         struct kinfo_cputime diffs;
210         uint64_t total_change, half_total;
211
212         /* initialization */
213         total_change = 0;
214
215         diffs.cp_user = new->cp_user - old->cp_user;
216         diffs.cp_nice = new->cp_nice - old->cp_nice;
217         diffs.cp_sys = new->cp_sys - old->cp_sys;
218         diffs.cp_intr = new->cp_intr - old->cp_intr;
219         diffs.cp_idle = new->cp_idle - old->cp_idle;
220         total_change = diffs.cp_user + diffs.cp_nice + diffs.cp_sys +
221             diffs.cp_intr + diffs.cp_idle;
222         old->cp_user = new->cp_user;
223         old->cp_nice = new->cp_nice;
224         old->cp_sys = new->cp_sys;
225         old->cp_intr = new->cp_intr;
226         old->cp_idle = new->cp_idle;
227
228         /* avoid divide by zero potential */
229         if (total_change == 0)
230                 total_change = 1;
231
232         /* calculate percentages based on overall change, rounding up */
233         half_total = total_change >> 1;
234
235         out[0] = ((diffs.cp_user * 1000LL + half_total) / total_change);
236         out[1] = ((diffs.cp_nice * 1000LL + half_total) / total_change);
237         out[2] = ((diffs.cp_sys * 1000LL + half_total) / total_change);
238         out[3] = ((diffs.cp_intr * 1000LL + half_total) / total_change);
239         out[4] = ((diffs.cp_idle * 1000LL + half_total) / total_change);
240 }
241
242 int
243 machine_init(struct statics *statics)
244 {
245         int pagesize;
246         size_t modelen;
247         struct passwd *pw;
248         struct timeval boottime;
249
250         if (n_cpus < 1) {
251                 if (kinfo_get_cpus(&n_cpus))
252                         err(1, "kinfo_get_cpus failed");
253         }
254         /* get boot time */
255         modelen = sizeof(boottime);
256         if (sysctlbyname("kern.boottime", &boottime, &modelen, NULL, 0) == -1) {
257                 /* we have no boottime to report */
258                 boottime.tv_sec = -1;
259         }
260         modelen = sizeof(smpmode);
261         if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
262             sysctlbyname("smp.smp_active", &smpmode, &modelen, NULL, 0) < 0) ||
263             modelen != sizeof(smpmode))
264                 smpmode = 0;
265
266         while ((pw = getpwent()) != NULL) {
267                 if ((int)strlen(pw->pw_name) > namelength)
268                         namelength = strlen(pw->pw_name);
269         }
270         if (namelength < 8)
271                 namelength = 8;
272         if (smpmode && namelength > 13)
273                 namelength = 13;
274         else if (namelength > 15)
275                 namelength = 15;
276
277         if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL)) == NULL)
278                 return -1;
279
280         if (kinfo_get_sched_ccpu(&ccpu)) {
281                 fprintf(stderr, "top: kinfo_get_sched_ccpu failed\n");
282                 return (-1);
283         }
284         /* this is used in calculating WCPU -- calculate it ahead of time */
285         logcpu = log(loaddouble(ccpu));
286
287         pbase = NULL;
288         pref = NULL;
289         nproc = 0;
290         onproc = -1;
291         /*
292          * get the page size with "getpagesize" and calculate pageshift from
293          * it
294          */
295         pagesize = getpagesize();
296         pageshift = 0;
297         while (pagesize > 1) {
298                 pageshift++;
299                 pagesize >>= 1;
300         }
301
302         /* we only need the amount of log(2)1024 for our conversion */
303         pageshift -= LOG1024;
304
305         /* fill in the statics information */
306         statics->procstate_names = procstatenames;
307         statics->cpustate_names = cpustatenames;
308         statics->memory_names = memorynames;
309         statics->boottime = boottime.tv_sec;
310         statics->swap_names = swapnames;
311         statics->order_names = ordernames;
312         /* we need kvm descriptor in order to show full commands */
313         statics->flags.fullcmds = kd != NULL;
314
315         /* all done! */
316         return (0);
317 }
318
319 char *
320 format_header(char *uname_field)
321 {
322         static char Header[128];
323
324         snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
325             namelength, namelength, uname_field);
326
327         if (screen_width <= 79)
328                 cmdlength = 80;
329         else
330                 cmdlength = screen_width;
331
332         cmdlength = cmdlength - strlen(Header) + 6;
333
334         return Header;
335 }
336
337 static int swappgsin = -1;
338 static int swappgsout = -1;
339 extern struct timeval timeout;
340
341 void
342 get_system_info(struct system_info *si)
343 {
344         size_t len;
345         int cpu;
346
347         if (cpu_states == NULL) {
348                 cpu_states = malloc(sizeof(*cpu_states) * CPU_STATES * n_cpus);
349                 if (cpu_states == NULL)
350                         err(1, "malloc");
351                 bzero(cpu_states, sizeof(*cpu_states) * CPU_STATES * n_cpus);
352         }
353         if (cp_time == NULL) {
354                 cp_time = malloc(2 * n_cpus * sizeof(cp_time[0]));
355                 if (cp_time == NULL)
356                         err(1, "cp_time");
357                 cp_old = cp_time + n_cpus;
358                 len = n_cpus * sizeof(cp_old[0]);
359                 bzero(cp_time, len);
360                 if (sysctlbyname("kern.cputime", cp_old, &len, NULL, 0))
361                         err(1, "kern.cputime");
362         }
363         len = n_cpus * sizeof(cp_time[0]);
364         bzero(cp_time, len);
365         if (sysctlbyname("kern.cputime", cp_time, &len, NULL, 0))
366                 err(1, "kern.cputime");
367
368         getloadavg(si->load_avg, 3);
369
370         lastpid = 0;
371
372         /* convert cp_time counts to percentages */
373         for (cpu = 0; cpu < n_cpus; ++cpu) {
374                 cputime_percentages(cpu_states + cpu * CPU_STATES,
375                     &cp_time[cpu], &cp_old[cpu]);
376         }
377
378         /* sum memory & swap statistics */
379         {
380                 struct vmmeter vmm;
381                 struct vmstats vms;
382                 size_t vms_size = sizeof(vms);
383                 size_t vmm_size = sizeof(vmm);
384                 static unsigned int swap_delay = 0;
385                 static int swapavail = 0;
386                 static int swapfree = 0;
387                 static long bufspace = 0;
388
389                 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0))
390                         err(1, "sysctlbyname: vm.vmstats");
391
392                 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0))
393                         err(1, "sysctlbyname: vm.vmmeter");
394
395                 if (kinfo_get_vfs_bufspace(&bufspace))
396                         err(1, "kinfo_get_vfs_bufspace");
397
398                 /* convert memory stats to Kbytes */
399                 memory_stats[0] = pagetok(vms.v_active_count);
400                 memory_stats[1] = pagetok(vms.v_inactive_count);
401                 memory_stats[2] = pagetok(vms.v_wire_count);
402                 memory_stats[3] = pagetok(vms.v_cache_count);
403                 memory_stats[4] = bufspace / 1024;
404                 memory_stats[5] = pagetok(vms.v_free_count);
405                 memory_stats[6] = -1;
406
407                 /* first interval */
408                 if (swappgsin < 0) {
409                         swap_stats[4] = 0;
410                         swap_stats[5] = 0;
411                 }
412                 /* compute differences between old and new swap statistic */
413                 else {
414                         swap_stats[4] = pagetok(((vmm.v_swappgsin - swappgsin)));
415                         swap_stats[5] = pagetok(((vmm.v_swappgsout - swappgsout)));
416                 }
417
418                 swappgsin = vmm.v_swappgsin;
419                 swappgsout = vmm.v_swappgsout;
420
421                 /* call CPU heavy swapmode() only for changes */
422                 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
423                         swap_stats[3] = swapmode(&swapavail, &swapfree);
424                         swap_stats[0] = swapavail;
425                         swap_stats[1] = swapavail - swapfree;
426                         swap_stats[2] = swapfree;
427                 }
428                 swap_delay = 1;
429                 swap_stats[6] = -1;
430         }
431
432         /* set arrays and strings */
433         si->cpustates = cpu_states;
434         si->memory = memory_stats;
435         si->swap = swap_stats;
436
437
438         if (lastpid > 0) {
439                 si->last_pid = lastpid;
440         } else {
441                 si->last_pid = -1;
442         }
443 }
444
445
446 static struct handle handle;
447
448 caddr_t 
449 get_process_info(struct system_info *si, struct process_select *sel,
450     int compare_index)
451 {
452         int i;
453         int total_procs;
454         int active_procs;
455         struct kinfo_proc **prefp;
456         struct kinfo_proc *pp;
457
458         /* these are copied out of sel for speed */
459         int show_idle;
460         int show_system;
461         int show_uid;
462         int show_threads;
463
464         show_threads = sel->threads;
465
466
467         pbase = kvm_getprocs(kd,
468             KERN_PROC_ALL | (show_threads ? KERN_PROC_FLAG_LWP : 0), 0, &nproc);
469         if (nproc > onproc)
470                 pref = (struct kinfo_proc **)realloc(pref, sizeof(struct kinfo_proc *)
471                     * (onproc = nproc));
472         if (pref == NULL || pbase == NULL) {
473                 (void)fprintf(stderr, "top: Out of memory.\n");
474                 quit(23);
475         }
476         /* get a pointer to the states summary array */
477         si->procstates = process_states;
478
479         /* set up flags which define what we are going to select */
480         show_idle = sel->idle;
481         show_system = sel->system;
482         show_uid = sel->uid != -1;
483         show_fullcmd = sel->fullcmd;
484
485         /* count up process states and get pointers to interesting procs */
486         total_procs = 0;
487         active_procs = 0;
488         memset((char *)process_states, 0, sizeof(process_states));
489         prefp = pref;
490         for (pp = pbase, i = 0; i < nproc; pp++, i++) {
491                 /*
492                  * Place pointers to each valid proc structure in pref[].
493                  * Process slots that are actually in use have a non-zero
494                  * status field.  Processes with P_SYSTEM set are system
495                  * processes---these get ignored unless show_sysprocs is set.
496                  */
497                 if ((show_threads && (LP(pp, pid) == -1)) ||
498                     (show_system || ((PP(pp, flags) & P_SYSTEM) == 0))) {
499                         total_procs++;
500                         if (LP(pp, stat) == LSRUN)
501                                 process_states[0]++;
502                         process_states[PP(pp, stat)]++;
503                         if ((show_threads && (LP(pp, pid) == -1)) ||
504                             (show_idle || (LP(pp, pctcpu) != 0) ||
505                             (LP(pp, stat) == LSRUN)) &&
506                             (!show_uid || PP(pp, ruid) == (uid_t) sel->uid)) {
507                                 *prefp++ = pp;
508                                 active_procs++;
509                         }
510                 }
511         }
512
513         qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *),
514             (int (*)(const void *, const void *))proc_compares[compare_index]);
515
516         /* remember active and total counts */
517         si->p_total = total_procs;
518         si->p_active = pref_len = active_procs;
519
520         /* pass back a handle */
521         handle.next_proc = pref;
522         handle.remaining = active_procs;
523         return ((caddr_t) & handle);
524 }
525
526 char fmt[MAX_COLS];             /* static area where result is built */
527
528 char *
529 format_next_process(caddr_t xhandle, char *(*get_userid) (int))
530 {
531         struct kinfo_proc *pp;
532         long cputime;
533         long ccputime;
534         double pct;
535         struct handle *hp;
536         char status[16];
537         int state;
538         int xnice;
539         char **comm_full;
540         char *comm;
541         char cputime_fmt[10], ccputime_fmt[10];
542
543         /* find and remember the next proc structure */
544         hp = (struct handle *)xhandle;
545         pp = *(hp->next_proc++);
546         hp->remaining--;
547
548         /* get the process's command name */
549         if (show_fullcmd) {
550                 if ((comm_full = kvm_getargv(kd, pp, 0)) == NULL) {
551                         return (fmt);
552                 }
553         }
554         else {
555                 comm = PP(pp, comm);
556         }
557         
558         /*
559          * Convert the process's runtime from microseconds to seconds.  This
560          * time includes the interrupt time to be in compliance with ps output.
561         */
562         cputime = (LP(pp, uticks) + LP(pp, sticks) + LP(pp, iticks)) / 1000000;
563         ccputime = cputime + PP(pp, cru).ru_stime.tv_sec + PP(pp, cru).ru_utime.tv_sec;
564         format_time(cputime, cputime_fmt, sizeof(cputime_fmt));
565         format_time(ccputime, ccputime_fmt, sizeof(ccputime_fmt));
566
567         /* calculate the base for cpu percentages */
568         pct = pctdouble(LP(pp, pctcpu));
569
570         /* generate "STATE" field */
571         switch (state = LP(pp, stat)) {
572         case LSRUN:
573                 if (smpmode && LP(pp, tdflags) & TDF_RUNNING)
574                         sprintf(status, "CPU%d", LP(pp, cpuid));
575                 else
576                         strcpy(status, "RUN");
577                 break;
578         case LSSLEEP:
579                 if (LP(pp, wmesg) != NULL) {
580                         sprintf(status, "%.6s", LP(pp, wmesg));
581                         break;
582                 }
583                 /* fall through */
584         default:
585
586                 if (state >= 0 &&
587                     (unsigned)state < sizeof(state_abbrev) / sizeof(*state_abbrev))
588                         sprintf(status, "%.6s", state_abbrev[(unsigned char)state]);
589                 else
590                         sprintf(status, "?%5d", state);
591                 break;
592         }
593
594         if (PP(pp, stat) == SZOMB)
595                 strcpy(status, "ZOMB");
596
597         /*
598          * idle time 0 - 31 -> nice value +21 - +52 normal time      -> nice
599          * value -20 - +20 real time 0 - 31 -> nice value -52 - -21 thread
600          * 0 - 31 -> nice value -53 -
601          */
602         switch (LP(pp, rtprio.type)) {
603         case RTP_PRIO_REALTIME:
604                 xnice = PRIO_MIN - 1 - RTP_PRIO_MAX + LP(pp, rtprio.prio);
605                 break;
606         case RTP_PRIO_IDLE:
607                 xnice = PRIO_MAX + 1 + LP(pp, rtprio.prio);
608                 break;
609         case RTP_PRIO_THREAD:
610                 xnice = PRIO_MIN - 1 - RTP_PRIO_MAX - LP(pp, rtprio.prio);
611                 break;
612         default:
613                 xnice = PP(pp, nice);
614                 break;
615         }
616
617         /* format this entry */
618         snprintf(fmt, sizeof(fmt),
619             smpmode ? smp_Proc_format : up_Proc_format,
620             (int)PP(pp, pid),
621             namelength, namelength,
622             get_userid(PP(pp, ruid)),
623             (int)xnice,
624             format_k(PROCSIZE(pp)),
625             format_k(pagetok(VP(pp, prssize))),
626             status,
627             (int)(smpmode ? LP(pp, cpuid) : 0),
628             cputime_fmt,
629             ccputime_fmt,
630             100.0 * pct,
631             cmdlength,
632             show_fullcmd ? *comm_full : comm);
633
634         /* return the result */
635         return (fmt);
636 }
637
638 /* comparison routines for qsort */
639
640 /*
641  *  proc_compare - comparison function for "qsort"
642  *      Compares the resource consumption of two processes using five
643  *      distinct keys.  The keys (in descending order of importance) are:
644  *      percent cpu, cpu ticks, state, resident set size, total virtual
645  *      memory usage.  The process states are ordered as follows (from least
646  *      to most important):  WAIT, zombie, sleep, stop, start, run.  The
647  *      array declaration below maps a process state index into a number
648  *      that reflects this ordering.
649  */
650
651 static unsigned char sorted_state[] =
652 {
653         0,                      /* not used              */
654         3,                      /* sleep                 */
655         1,                      /* ABANDONED (WAIT)      */
656         6,                      /* run                   */
657         5,                      /* start                 */
658         2,                      /* zombie                */
659         4                       /* stop                  */
660 };
661
662
663 #define ORDERKEY_PCTCPU \
664   if (lresult = (long) LP(p2, pctcpu) - (long) LP(p1, pctcpu), \
665      (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
666
667 #define CPTICKS(p)      (LP(p, uticks) + LP(p, sticks) + LP(p, iticks))
668
669 #define ORDERKEY_CPTICKS \
670   if ((result = CPTICKS(p2) > CPTICKS(p1) ? 1 : \
671                 CPTICKS(p2) < CPTICKS(p1) ? -1 : 0) == 0)
672
673 #define CTIME(p)        (((LP(p, uticks) + LP(p, sticks) + LP(p, iticks))/1000000) + \
674   PP(p, cru).ru_stime.tv_sec + PP(p, cru).ru_utime.tv_sec)
675
676 #define ORDERKEY_CTIME \
677    if ((result = CTIME(p2) > CTIME(p1) ? 1 : \
678                 CTIME(p2) < CTIME(p1) ? -1 : 0) == 0)
679
680 #define ORDERKEY_STATE \
681   if ((result = sorted_state[(unsigned char) PP(p2, stat)] - \
682                 sorted_state[(unsigned char) PP(p1, stat)]) == 0)
683
684 #define ORDERKEY_PRIO \
685   if ((result = LP(p2, prio) - LP(p1, prio)) == 0)
686
687 #define ORDERKEY_KTHREADS \
688   if ((result = (LP(p1, pid) == 0) - (LP(p2, pid) == 0)) == 0)
689
690 #define ORDERKEY_KTHREADS_PRIO \
691   if ((result = LP(p2, tdprio) - LP(p1, tdprio)) == 0)
692
693 #define ORDERKEY_RSSIZE \
694   if ((result = VP(p2, rssize) - VP(p1, rssize)) == 0)
695
696 #define ORDERKEY_MEM \
697   if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
698
699 #define ORDERKEY_PID \
700   if ( (result = PP(p1, pid) - PP(p2, pid)) == 0)
701
702 #define ORDERKEY_PRSSIZE \
703   if((result = VP(p2, prssize) - VP(p1, prssize)) == 0)
704
705 /* compare_cpu - the comparison function for sorting by cpu percentage */
706
707 int
708 proc_compare(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
709 {
710         struct kinfo_proc *p1;
711         struct kinfo_proc *p2;
712         int result;
713         pctcpu lresult;
714
715         /* remove one level of indirection */
716         p1 = *(struct kinfo_proc **) pp1;
717         p2 = *(struct kinfo_proc **) pp2;
718
719         ORDERKEY_PCTCPU
720         ORDERKEY_CPTICKS
721         ORDERKEY_STATE
722         ORDERKEY_PRIO
723         ORDERKEY_RSSIZE
724         ORDERKEY_MEM
725         {} 
726         
727         return (result);
728 }
729
730 /* compare_size - the comparison function for sorting by total memory usage */
731
732 int
733 compare_size(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
734 {
735         struct kinfo_proc *p1;
736         struct kinfo_proc *p2;
737         int result;
738         pctcpu lresult;
739
740         /* remove one level of indirection */
741         p1 = *(struct kinfo_proc **) pp1;
742         p2 = *(struct kinfo_proc **) pp2;
743
744         ORDERKEY_MEM
745         ORDERKEY_RSSIZE
746         ORDERKEY_PCTCPU
747         ORDERKEY_CPTICKS
748         ORDERKEY_STATE
749         ORDERKEY_PRIO
750         {}
751
752         return (result);
753 }
754
755 /* compare_res - the comparison function for sorting by resident set size */
756
757 int
758 compare_res(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
759 {
760         struct kinfo_proc *p1;
761         struct kinfo_proc *p2;
762         int result;
763         pctcpu lresult;
764
765         /* remove one level of indirection */
766         p1 = *(struct kinfo_proc **) pp1;
767         p2 = *(struct kinfo_proc **) pp2;
768
769         ORDERKEY_RSSIZE
770         ORDERKEY_MEM
771         ORDERKEY_PCTCPU
772         ORDERKEY_CPTICKS
773         ORDERKEY_STATE
774         ORDERKEY_PRIO
775         {}
776
777         return (result);
778 }
779
780 /* compare_pres - the comparison function for sorting by proportional resident set size */
781
782 int
783 compare_pres(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
784 {
785         struct kinfo_proc *p1;
786         struct kinfo_proc *p2;
787         int result;
788         pctcpu lresult;
789
790         /* remove one level of indirection */
791         p1 = *(struct kinfo_proc **) pp1;
792         p2 = *(struct kinfo_proc **) pp2;
793
794         ORDERKEY_PRSSIZE
795         ORDERKEY_RSSIZE
796         ORDERKEY_MEM
797         ORDERKEY_PCTCPU
798         ORDERKEY_CPTICKS
799         ORDERKEY_STATE
800         ORDERKEY_PRIO
801         {}
802
803         return (result);
804 }
805
806 /* compare_time - the comparison function for sorting by total cpu time */
807
808 int
809 compare_time(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
810 {
811         struct kinfo_proc *p1;
812         struct kinfo_proc *p2;
813         int result;
814         pctcpu lresult;
815
816         /* remove one level of indirection */
817         p1 = *(struct kinfo_proc **) pp1;
818         p2 = *(struct kinfo_proc **) pp2;
819
820         ORDERKEY_CPTICKS
821         ORDERKEY_PCTCPU
822         ORDERKEY_KTHREADS
823         ORDERKEY_KTHREADS_PRIO
824         ORDERKEY_STATE
825         ORDERKEY_PRIO
826         ORDERKEY_RSSIZE
827         ORDERKEY_MEM
828         {}
829
830         return (result);
831 }
832
833 int
834 compare_ctime(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
835 {
836         struct kinfo_proc *p1;
837         struct kinfo_proc *p2;
838         int result;
839         pctcpu lresult;
840         
841         /* remove one level of indirection */
842         p1 = *(struct kinfo_proc **) pp1;
843         p2 = *(struct kinfo_proc **) pp2;
844         
845         ORDERKEY_CTIME
846         ORDERKEY_PCTCPU
847         ORDERKEY_KTHREADS
848         ORDERKEY_KTHREADS_PRIO
849         ORDERKEY_STATE
850         ORDERKEY_PRIO
851         ORDERKEY_RSSIZE
852         ORDERKEY_MEM
853         {}
854         
855         return (result);
856 }
857
858 /* compare_prio - the comparison function for sorting by cpu percentage */
859
860 int
861 compare_prio(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
862 {
863         struct kinfo_proc *p1;
864         struct kinfo_proc *p2;
865         int result;
866         pctcpu lresult;
867
868         /* remove one level of indirection */
869         p1 = *(struct kinfo_proc **) pp1;
870         p2 = *(struct kinfo_proc **) pp2;
871
872         ORDERKEY_KTHREADS
873         ORDERKEY_KTHREADS_PRIO
874         ORDERKEY_PRIO
875         ORDERKEY_CPTICKS
876         ORDERKEY_PCTCPU
877         ORDERKEY_STATE
878         ORDERKEY_RSSIZE
879         ORDERKEY_MEM
880         {}
881
882         return (result);
883 }
884
885 int
886 compare_thr(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
887 {
888         struct kinfo_proc *p1;
889         struct kinfo_proc *p2;
890         int result;
891         pctcpu lresult;
892
893         /* remove one level of indirection */
894         p1 = *(struct kinfo_proc **)pp1;
895         p2 = *(struct kinfo_proc **)pp2;
896
897         ORDERKEY_KTHREADS
898         ORDERKEY_KTHREADS_PRIO
899         ORDERKEY_CPTICKS
900         ORDERKEY_PCTCPU
901         ORDERKEY_STATE
902         ORDERKEY_RSSIZE
903         ORDERKEY_MEM
904         {}
905
906         return (result);
907 }
908
909 /* compare_pid - the comparison function for sorting by process id */
910
911 int
912 compare_pid(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
913 {
914         struct kinfo_proc *p1;
915         struct kinfo_proc *p2;
916         int result;
917
918         /* remove one level of indirection */
919         p1 = *(struct kinfo_proc **) pp1;
920         p2 = *(struct kinfo_proc **) pp2;
921         
922         ORDERKEY_PID
923         ;
924         
925         return(result);
926 }
927
928 /*
929  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
930  *              the process does not exist.
931  *              It is EXTREMLY IMPORTANT that this function work correctly.
932  *              If top runs setuid root (as in SVR4), then this function
933  *              is the only thing that stands in the way of a serious
934  *              security problem.  It validates requests for the "kill"
935  *              and "renice" commands.
936  */
937
938 int
939 proc_owner(int pid)
940 {
941         int xcnt;
942         struct kinfo_proc **prefp;
943         struct kinfo_proc *pp;
944
945         prefp = pref;
946         xcnt = pref_len;
947         while (--xcnt >= 0) {
948                 pp = *prefp++;
949                 if (PP(pp, pid) == (pid_t) pid) {
950                         return ((int)PP(pp, ruid));
951                 }
952         }
953         return (-1);
954 }
955
956
957 /*
958  * swapmode is based on a program called swapinfo written
959  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
960  */
961 int
962 swapmode(int *retavail, int *retfree)
963 {
964         int n;
965         int pagesize = getpagesize();
966         struct kvm_swap swapary[1];
967
968         *retavail = 0;
969         *retfree = 0;
970
971 #define CONVERT(v)      ((quad_t)(v) * pagesize / 1024)
972
973         n = kvm_getswapinfo(kd, swapary, 1, 0);
974         if (n < 0 || swapary[0].ksw_total == 0)
975                 return (0);
976
977         *retavail = CONVERT(swapary[0].ksw_total);
978         *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
979
980         n = (int)((double)swapary[0].ksw_used * 100.0 /
981             (double)swapary[0].ksw_total);
982         return (n);
983 }