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