13ae893696f10cdb211e551d6092c263a981daf8
[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  * $DragonFly: src/usr.bin/top/machine.c,v 1.26 2008/10/16 01:52:33 swildner Exp $
24  */
25
26 #include <sys/time.h>
27 #include <sys/types.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/time.h>
42 #include <sys/user.h>
43 #include <sys/vmmeter.h>
44 #include <sys/resource.h>
45 #include <sys/rtprio.h>
46
47 /* Swap */
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <sys/conf.h>
51
52 #include <osreldate.h>          /* for changes in kernel structures */
53
54 #include <sys/kinfo.h>
55 #include <kinfo.h>
56 #include "top.h"
57 #include "display.h"
58 #include "machine.h"
59 #include "screen.h"
60 #include "utils.h"
61
62 int swapmode(int *retavail, int *retfree);
63 static int smpmode;
64 static int namelength;
65 static int cmdlength;
66 static int show_fullcmd;
67
68 int n_cpus = 0;
69
70 /*
71  * needs to be a global symbol, so wrapper can be modified accordingly.
72  */
73 static int show_threads = 0;
74
75 /* get_process_info passes back a handle.  This is what it looks like: */
76
77 struct handle {
78         struct kinfo_proc **next_proc;  /* points to next valid proc pointer */
79         int remaining;          /* number of pointers remaining */
80 };
81
82 /* declarations for load_avg */
83 #include "loadavg.h"
84
85 #define PP(pp, field) ((pp)->kp_ ## field)
86 #define LP(pp, field) ((pp)->kp_lwp.kl_ ## field)
87 #define VP(pp, field) ((pp)->kp_vm_ ## field)
88
89 /* define what weighted cpu is.  */
90 #define weighted_cpu(pct, pp) (PP((pp), swtime) == 0 ? 0.0 : \
91                          ((pct) / (1.0 - exp(PP((pp), swtime) * logcpu))))
92
93 /* what we consider to be process size: */
94 #define PROCSIZE(pp) (VP((pp), map_size) / 1024)
95
96 /*
97  * These definitions control the format of the per-process area
98  */
99
100 static char smp_header[] =
101 "  PID %-*.*s PRI NICE  SIZE    RES STATE  C   TIME   WCPU    CPU COMMAND";
102
103 #define smp_Proc_format \
104         "%5d %-*.*s %3d %3d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
105
106 static char up_header[] =
107 "  PID %-*.*s PRI NICE  SIZE    RES STATE    TIME   WCPU    CPU COMMAND";
108
109 #define up_Proc_format \
110         "%5d %-*.*s %3d %3d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
111
112
113
114 /* process state names for the "STATE" column of the display */
115 /*
116  * the extra nulls in the string "run" are for adding a slash and the
117  * processor number when needed
118  */
119
120 const char *state_abbrev[] = {
121         "", "RUN\0\0\0", "STOP", "SLEEP",
122 };
123
124
125 static kvm_t *kd;
126
127 /* values that we stash away in _init and use in later routines */
128
129 static double logcpu;
130
131 static long lastpid;
132 static int ccpu;
133
134 /* these are for calculating cpu state percentages */
135
136 static struct kinfo_cputime *cp_time, *cp_old;
137
138 /* these are for detailing the process states */
139
140 int process_states[6];
141 char *procstatenames[] = {
142         "", " starting, ", " running, ", " sleeping, ", " stopped, ",
143         " zombie, ",
144         NULL
145 };
146
147 /* these are for detailing the cpu states */
148 #define CPU_STATES 5
149 int *cpu_states;
150 char *cpustatenames[CPU_STATES + 1] = {
151         "user", "nice", "system", "interrupt", "idle", NULL
152 };
153
154 /* these are for detailing the memory statistics */
155
156 long memory_stats[7];
157 char *memorynames[] = {
158         "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
159         NULL
160 };
161
162 long swap_stats[7];
163 char *swapnames[] = {
164         /* 0           1            2           3            4       5 */
165         "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
166         NULL
167 };
168
169
170 /* these are for keeping track of the proc array */
171
172 static int nproc;
173 static int onproc = -1;
174 static int pref_len;
175 static struct kinfo_proc *pbase;
176 static struct kinfo_proc **pref;
177
178 /* these are for getting the memory statistics */
179
180 static int pageshift;           /* log base 2 of the pagesize */
181
182 /* define pagetok in terms of pageshift */
183
184 #define pagetok(size) ((size) << pageshift)
185
186 /* sorting orders. first is default */
187 char *ordernames[] = {
188         "cpu", "size", "res", "time", "pri", "thr", NULL
189 };
190
191 /* compare routines */
192 int proc_compare(const void *, const void *), compare_size(const void *, const void *),
193     compare_res(const void *, const void *), compare_time(const void *, const void *),
194     compare_prio(const void *, const void *), compare_thr(const void *, const void *);
195
196 int (*proc_compares[]) () = {
197         proc_compare,
198         compare_size,
199         compare_res,
200         compare_time,
201         compare_prio,
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-1;
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
359                 len = n_cpus * sizeof(cp_old[0]);
360                 bzero(cp_time, len);
361                 if (sysctlbyname("kern.cputime", cp_old, &len, NULL, 0))
362                         err(1, "kern.cputime");
363         }
364         len = n_cpus * sizeof(cp_time[0]);
365         bzero(cp_time, len);
366         if (sysctlbyname("kern.cputime", cp_time, &len, NULL, 0))
367                 err(1, "kern.cputime");
368
369         getloadavg(si->load_avg, 3);
370
371         lastpid = 0;
372
373         /* convert cp_time counts to percentages */
374         for (cpu = 0; cpu < n_cpus; ++cpu) {
375                 cputime_percentages(cpu_states + cpu * CPU_STATES,
376                     &cp_time[cpu], &cp_old[cpu]);
377         }
378
379         /* sum memory & swap statistics */
380         {
381                 struct vmmeter vmm;
382                 struct vmstats vms;
383                 size_t vms_size = sizeof(vms);
384                 size_t vmm_size = sizeof(vmm);
385                 static unsigned int swap_delay = 0;
386                 static int swapavail = 0;
387                 static int swapfree = 0;
388                 static int bufspace = 0;
389
390                 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0))
391                         err(1, "sysctlbyname: vm.vmstats");
392
393                 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0))
394                         err(1, "sysctlbyname: vm.vmmeter");
395
396                 if (kinfo_get_vfs_bufspace(&bufspace))
397                         err(1, "kinfo_get_vfs_bufspace");
398
399                 /* convert memory stats to Kbytes */
400                 memory_stats[0] = pagetok(vms.v_active_count);
401                 memory_stats[1] = pagetok(vms.v_inactive_count);
402                 memory_stats[2] = pagetok(vms.v_wire_count);
403                 memory_stats[3] = pagetok(vms.v_cache_count);
404                 memory_stats[4] = bufspace / 1024;
405                 memory_stats[5] = pagetok(vms.v_free_count);
406                 memory_stats[6] = -1;
407
408                 /* first interval */
409                 if (swappgsin < 0) {
410                         swap_stats[4] = 0;
411                         swap_stats[5] = 0;
412                 }
413                 /* compute differences between old and new swap statistic */
414                 else {
415                         swap_stats[4] = pagetok(((vmm.v_swappgsin - swappgsin)));
416                         swap_stats[5] = pagetok(((vmm.v_swappgsout - swappgsout)));
417                 }
418
419                 swappgsin = vmm.v_swappgsin;
420                 swappgsout = vmm.v_swappgsout;
421
422                 /* call CPU heavy swapmode() only for changes */
423                 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
424                         swap_stats[3] = swapmode(&swapavail, &swapfree);
425                         swap_stats[0] = swapavail;
426                         swap_stats[1] = swapavail - swapfree;
427                         swap_stats[2] = swapfree;
428                 }
429                 swap_delay = 1;
430                 swap_stats[6] = -1;
431         }
432
433         /* set arrays and strings */
434         si->cpustates = cpu_states;
435         si->memory = memory_stats;
436         si->swap = swap_stats;
437
438
439         if (lastpid > 0) {
440                 si->last_pid = lastpid;
441         } else {
442                 si->last_pid = -1;
443         }
444 }
445
446
447 static struct handle handle;
448
449 caddr_t 
450 get_process_info(struct system_info *si, struct process_select *sel,
451     int compare_index)
452 {
453         int i;
454         int total_procs;
455         int active_procs;
456         struct kinfo_proc **prefp;
457         struct kinfo_proc *pp;
458
459         /* these are copied out of sel for speed */
460         int show_idle;
461         int show_system;
462         int show_uid;
463
464
465         pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
466         if (nproc > onproc)
467                 pref = (struct kinfo_proc **)realloc(pref, sizeof(struct kinfo_proc *)
468                     * (onproc = nproc));
469         if (pref == NULL || pbase == NULL) {
470                 (void)fprintf(stderr, "top: Out of memory.\n");
471                 quit(23);
472         }
473         /* get a pointer to the states summary array */
474         si->procstates = process_states;
475
476         /* set up flags which define what we are going to select */
477         show_idle = sel->idle;
478         show_system = sel->system;
479         show_uid = sel->uid != -1;
480         show_fullcmd = sel->fullcmd;
481
482         /* count up process states and get pointers to interesting procs */
483         total_procs = 0;
484         active_procs = 0;
485         memset((char *)process_states, 0, sizeof(process_states));
486         prefp = pref;
487         for (pp = pbase, i = 0; i < nproc; pp++, i++) {
488                 /*
489                  * Place pointers to each valid proc structure in pref[].
490                  * Process slots that are actually in use have a non-zero
491                  * status field.  Processes with P_SYSTEM set are system
492                  * processes---these get ignored unless show_sysprocs is set.
493                  */
494                 if ((show_threads && (LP(pp, pid) == -1)) ||
495                     (show_system || ((PP(pp, flags) & P_SYSTEM) == 0))) {
496                         total_procs++;
497                         process_states[(unsigned char)PP(pp, stat)]++;
498                         if ((show_threads && (LP(pp, pid) == -1)) ||
499                             (show_idle || (LP(pp, pctcpu) != 0) ||
500                             (LP(pp, stat) == LSRUN)) &&
501                             (!show_uid || PP(pp, ruid) == (uid_t) sel->uid)) {
502                                 *prefp++ = pp;
503                                 active_procs++;
504                         }
505                 }
506         }
507
508         qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *),
509             proc_compares[compare_index]);
510
511         /* remember active and total counts */
512         si->p_total = total_procs;
513         si->p_active = pref_len = active_procs;
514
515         /* pass back a handle */
516         handle.next_proc = pref;
517         handle.remaining = active_procs;
518         return ((caddr_t) & handle);
519 }
520
521 char fmt[128];                  /* static area where result is built */
522
523 char *
524 format_next_process(caddr_t xhandle, char *(*get_userid) (int))
525 {
526         struct kinfo_proc *pp;
527         long cputime;
528         double pct;
529         struct handle *hp;
530         char status[16];
531         int state;
532         int xnice;
533         char **comm_full;
534         char *comm;
535
536         /* find and remember the next proc structure */
537         hp = (struct handle *)xhandle;
538         pp = *(hp->next_proc++);
539         hp->remaining--;
540
541         /* get the process's command name */
542         if (show_fullcmd) {
543                 if ((comm_full = kvm_getargv(kd, pp, 0)) == NULL) {
544                         return (fmt);
545                 }
546         }
547         else {
548                 comm = PP(pp, comm);
549         }
550         
551         /*
552          * Convert the process's runtime from microseconds to seconds.  This
553          * time includes the interrupt time although that is not wanted here.
554          * ps(1) is similarly sloppy.
555          */
556         cputime = (LP(pp, uticks) + LP(pp, sticks)) / 1000000;
557
558         /* calculate the base for cpu percentages */
559         pct = pctdouble(LP(pp, pctcpu));
560
561         /* generate "STATE" field */
562         switch (state = LP(pp, stat)) {
563         case LSRUN:
564                 if (smpmode && LP(pp, tdflags) & TDF_RUNNING)
565                         sprintf(status, "CPU%d", LP(pp, cpuid));
566                 else
567                         strcpy(status, "RUN");
568                 break;
569         case LSSLEEP:
570                 if (LP(pp, wmesg) != NULL) {
571                         sprintf(status, "%.6s", LP(pp, wmesg));
572                         break;
573                 }
574                 /* fall through */
575         default:
576
577                 if (state >= 0 &&
578                     (unsigned)state < sizeof(state_abbrev) / sizeof(*state_abbrev))
579                         sprintf(status, "%.6s", state_abbrev[(unsigned char)state]);
580                 else
581                         sprintf(status, "?%5d", state);
582                 break;
583         }
584
585         if (PP(pp, stat) == SZOMB)
586                 strcpy(status, "ZOMB");
587
588         /*
589          * idle time 0 - 31 -> nice value +21 - +52 normal time      -> nice
590          * value -20 - +20 real time 0 - 31 -> nice value -52 - -21 thread
591          * 0 - 31 -> nice value -53 -
592          */
593         switch (LP(pp, rtprio.type)) {
594         case RTP_PRIO_REALTIME:
595                 xnice = PRIO_MIN - 1 - RTP_PRIO_MAX + LP(pp, rtprio.prio);
596                 break;
597         case RTP_PRIO_IDLE:
598                 xnice = PRIO_MAX + 1 + LP(pp, rtprio.prio);
599                 break;
600         case RTP_PRIO_THREAD:
601                 xnice = PRIO_MIN - 1 - RTP_PRIO_MAX - LP(pp, rtprio.prio);
602                 break;
603         default:
604                 xnice = PP(pp, nice);
605                 break;
606         }
607
608         /* format this entry */
609         snprintf(fmt, sizeof(fmt),
610             smpmode ? smp_Proc_format : up_Proc_format,
611             (int)PP(pp, pid),
612             namelength, namelength,
613             get_userid(PP(pp, ruid)),
614             (int)((show_threads && (LP(pp, pid) == -1)) ?
615             LP(pp, tdprio) : LP(pp, prio)),
616             (int)xnice,
617             format_k(PROCSIZE(pp)),
618             format_k(pagetok(VP(pp, rssize))),
619             status,
620             (int)(smpmode ? LP(pp, cpuid) : 0),
621             format_time(cputime),
622             100.0 * weighted_cpu(pct, pp),
623             100.0 * pct,
624             cmdlength,
625             show_fullcmd ? *comm_full : comm);
626
627         /* return the result */
628         return (fmt);
629 }
630
631 /* comparison routines for qsort */
632
633 /*
634  *  proc_compare - comparison function for "qsort"
635  *      Compares the resource consumption of two processes using five
636  *      distinct keys.  The keys (in descending order of importance) are:
637  *      percent cpu, cpu ticks, state, resident set size, total virtual
638  *      memory usage.  The process states are ordered as follows (from least
639  *      to most important):  WAIT, zombie, sleep, stop, start, run.  The
640  *      array declaration below maps a process state index into a number
641  *      that reflects this ordering.
642  */
643
644 static unsigned char sorted_state[] =
645 {
646         0,                      /* not used              */
647         3,                      /* sleep                 */
648         1,                      /* ABANDONED (WAIT)      */
649         6,                      /* run                   */
650         5,                      /* start                 */
651         2,                      /* zombie                */
652         4                       /* stop                  */
653 };
654
655
656 #define ORDERKEY_PCTCPU \
657   if (lresult = (long) LP(p2, pctcpu) - (long) LP(p1, pctcpu), \
658      (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
659
660 #define CPTICKS(p)      (LP(p, uticks) + LP(p, sticks))
661
662 #define ORDERKEY_CPTICKS \
663   if ((result = CPTICKS(p2) > CPTICKS(p1) ? 1 : \
664                 CPTICKS(p2) < CPTICKS(p1) ? -1 : 0) == 0)
665
666 #define ORDERKEY_STATE \
667   if ((result = sorted_state[(unsigned char) PP(p2, stat)] - \
668                 sorted_state[(unsigned char) PP(p1, stat)]) == 0)
669
670 #define ORDERKEY_PRIO \
671   if ((result = LP(p2, prio) - LP(p1, prio)) == 0)
672
673 #define ORDERKEY_KTHREADS \
674   if ((result = (LP(p1, pid) == 0) - (LP(p2, pid) == 0)) == 0)
675
676 #define ORDERKEY_KTHREADS_PRIO \
677   if ((result = LP(p2, tdprio) - LP(p1, tdprio)) == 0)
678
679 #define ORDERKEY_RSSIZE \
680   if ((result = VP(p2, rssize) - VP(p1, rssize)) == 0)
681
682 #define ORDERKEY_MEM \
683   if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
684
685 /* compare_cpu - the comparison function for sorting by cpu percentage */
686
687 int
688 proc_compare(const void *arg1, const void *arg2)
689 {
690         const struct proc *const *pp1 = arg1;
691         const struct proc *const *pp2 = arg2;
692         const struct kinfo_proc *p1;
693         const struct kinfo_proc *p2;
694         int result;
695         pctcpu lresult;
696
697         /* remove one level of indirection */
698         p1 = *(const struct kinfo_proc *const *)pp1;
699         p2 = *(const struct kinfo_proc *const *)pp2;
700
701         ORDERKEY_PCTCPU
702         ORDERKEY_CPTICKS
703         ORDERKEY_STATE
704         ORDERKEY_PRIO
705         ORDERKEY_RSSIZE
706         ORDERKEY_MEM
707         {} 
708         
709         return (result);
710 }
711
712 /* compare_size - the comparison function for sorting by total memory usage */
713
714 int
715 compare_size(const void *arg1, const void *arg2)
716 {
717         struct proc *const *pp1 = arg1;
718         struct proc *const *pp2 = arg2;
719         struct kinfo_proc *p1;
720         struct kinfo_proc *p2;
721         int result;
722         pctcpu lresult;
723
724         /* remove one level of indirection */
725         p1 = *(struct kinfo_proc *const *)pp1;
726         p2 = *(struct kinfo_proc *const *)pp2;
727
728         ORDERKEY_MEM
729         ORDERKEY_RSSIZE
730         ORDERKEY_PCTCPU
731         ORDERKEY_CPTICKS
732         ORDERKEY_STATE
733         ORDERKEY_PRIO
734         {}
735
736         return (result);
737 }
738
739 /* compare_res - the comparison function for sorting by resident set size */
740
741 int
742 compare_res(const void *arg1, const void *arg2)
743 {
744         struct proc *const *pp1 = arg1;
745         struct proc *const *pp2 = arg2;
746         struct kinfo_proc *p1;
747         struct kinfo_proc *p2;
748         int result;
749         pctcpu lresult;
750
751         /* remove one level of indirection */
752         p1 = *(struct kinfo_proc *const *)pp1;
753         p2 = *(struct kinfo_proc *const *)pp2;
754
755         ORDERKEY_RSSIZE
756         ORDERKEY_MEM
757         ORDERKEY_PCTCPU
758         ORDERKEY_CPTICKS
759         ORDERKEY_STATE
760         ORDERKEY_PRIO
761         {}
762
763         return (result);
764 }
765
766 /* compare_time - the comparison function for sorting by total cpu time */
767
768 int
769 compare_time(const void *arg1, const void *arg2)
770 {
771         struct proc *const *pp1 = arg1;
772         struct proc *const *pp2 = arg2;
773         const struct kinfo_proc *p1;
774         const struct kinfo_proc *p2;
775         int result;
776         pctcpu lresult;
777
778         /* remove one level of indirection */
779         p1 = *(struct kinfo_proc *const *)pp1;
780         p2 = *(struct kinfo_proc *const *)pp2;
781
782         ORDERKEY_CPTICKS
783         ORDERKEY_PCTCPU
784         ORDERKEY_KTHREADS
785         ORDERKEY_KTHREADS_PRIO
786         ORDERKEY_STATE
787         ORDERKEY_PRIO
788         ORDERKEY_RSSIZE
789         ORDERKEY_MEM
790         {}
791
792         return (result);
793 }
794
795 /* compare_prio - the comparison function for sorting by cpu percentage */
796
797 int
798 compare_prio(const void *arg1, const void *arg2)
799 {
800         struct proc *const *pp1 = arg1;
801         struct proc *const *pp2 = arg2;
802         const struct kinfo_proc *p1;
803         const struct kinfo_proc *p2;
804         int result;
805         pctcpu lresult;
806
807         /* remove one level of indirection */
808         p1 = *(struct kinfo_proc *const *)pp1;
809         p2 = *(struct kinfo_proc *const *)pp2;
810
811         ORDERKEY_KTHREADS
812         ORDERKEY_KTHREADS_PRIO
813         ORDERKEY_PRIO
814         ORDERKEY_CPTICKS
815         ORDERKEY_PCTCPU
816         ORDERKEY_STATE
817         ORDERKEY_RSSIZE
818         ORDERKEY_MEM
819         {}
820
821         return (result);
822 }
823
824 int
825 compare_thr(const void *arg1, const void *arg2)
826 {
827         struct proc *const *pp1 = arg1;
828         struct proc *const *pp2 = arg2;
829         const struct kinfo_proc *p1;
830         const struct kinfo_proc *p2;
831         int result;
832         pctcpu lresult;
833
834         /* remove one level of indirection */
835         p1 = *(struct kinfo_proc *const *)pp1;
836         p2 = *(struct kinfo_proc *const *)pp2;
837
838         ORDERKEY_KTHREADS
839         ORDERKEY_KTHREADS_PRIO
840         ORDERKEY_CPTICKS
841         ORDERKEY_PCTCPU
842         ORDERKEY_STATE
843         ORDERKEY_RSSIZE
844         ORDERKEY_MEM
845         {}
846
847         return (result);
848 }
849
850 /*
851  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
852  *              the process does not exist.
853  *              It is EXTREMLY IMPORTANT that this function work correctly.
854  *              If top runs setuid root (as in SVR4), then this function
855  *              is the only thing that stands in the way of a serious
856  *              security problem.  It validates requests for the "kill"
857  *              and "renice" commands.
858  */
859
860 int
861 proc_owner(int pid)
862 {
863         int xcnt;
864         struct kinfo_proc **prefp;
865         struct kinfo_proc *pp;
866
867         prefp = pref;
868         xcnt = pref_len;
869         while (--xcnt >= 0) {
870                 pp = *prefp++;
871                 if (PP(pp, pid) == (pid_t) pid) {
872                         return ((int)PP(pp, ruid));
873                 }
874         }
875         return (-1);
876 }
877
878
879 /*
880  * swapmode is based on a program called swapinfo written
881  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
882  */
883 int
884 swapmode(int *retavail, int *retfree)
885 {
886         int n;
887         int pagesize = getpagesize();
888         struct kvm_swap swapary[1];
889
890         *retavail = 0;
891         *retfree = 0;
892
893 #define CONVERT(v)      ((quad_t)(v) * pagesize / 1024)
894
895         n = kvm_getswapinfo(kd, swapary, 1, 0);
896         if (n < 0 || swapary[0].ksw_total == 0)
897                 return (0);
898
899         *retavail = CONVERT(swapary[0].ksw_total);
900         *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
901
902         n = (int)((double)swapary[0].ksw_used * 100.0 /
903             (double)swapary[0].ksw_total);
904         return (n);
905 }