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