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