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