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