top(1): Fix building with -fno-common.
[dragonfly.git] / usr.bin / top / m_dragonfly.c
CommitLineData
984263bc
MD
1/*
2 * top - a top users display for Unix
3 *
7af1b2bc 4 * SYNOPSIS: For DragonFly 2.x and later
984263bc
MD
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 *
7af1b2bc
JL
12 * This is the machine-dependent module for DragonFly 2.5.1
13 * Should work for:
14 * DragonFly 2.x and above
984263bc
MD
15 *
16 * LIBS: -lkvm
17 *
7af1b2bc
JL
18 * AUTHOR: Jan Lentfer <Jan.Lentfer@web.de>
19 * This module has been put together from different sources and is based on the
20 * work of many other people, e.g. Matthew Dillon, Simon Schubert, Jordan Gordeev.
984263bc
MD
21 *
22 * $FreeBSD: src/usr.bin/top/machine.c,v 1.29.2.2 2001/07/31 20:27:05 tmm Exp $
23 */
24
e0ecab34 25#include <sys/user.h>
984263bc 26#include <sys/types.h>
e0ecab34 27#include <sys/time.h>
984263bc
MD
28#include <sys/signal.h>
29#include <sys/param.h>
30
31#include "os.h"
f5d21610 32#include <err.h>
2c3b1d1b 33#include <fcntl.h>
f5d21610 34#include <kvm.h>
984263bc 35#include <stdio.h>
b552171b 36#include <unistd.h>
984263bc 37#include <math.h>
984263bc
MD
38#include <pwd.h>
39#include <sys/errno.h>
40#include <sys/sysctl.h>
984263bc
MD
41#include <sys/vmmeter.h>
42#include <sys/resource.h>
43#include <sys/rtprio.h>
44
45/* Swap */
46#include <stdlib.h>
b5121966 47#include <string.h>
984263bc
MD
48#include <sys/conf.h>
49
961f1f09 50#include <osreldate.h> /* for changes in kernel structures */
984263bc 51
f5d21610 52#include <sys/kinfo.h>
9169bd75 53#include <kinfo.h>
984263bc 54#include "top.h"
bec9f4e2 55#include "display.h"
984263bc 56#include "machine.h"
bec9f4e2 57#include "screen.h"
b552171b 58#include "utils.h"
984263bc 59
1d1731fa 60int swapmode(int *retavail, int *retfree);
984263bc
MD
61static int namelength;
62static int cmdlength;
efde5811 63static int show_fullcmd;
984263bc 64
8ea225a8 65int n_cpus, enable_ncpus;
7af1b2bc 66
984263bc
MD
67/* get_process_info passes back a handle. This is what it looks like: */
68
961f1f09
JL
69struct handle {
70 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
71 int remaining; /* number of pointers remaining */
0ca59c34 72 int show_threads;
984263bc
MD
73};
74
75/* declarations for load_avg */
76#include "loadavg.h"
77
5dfd06ac
SS
78#define PP(pp, field) ((pp)->kp_ ## field)
79#define LP(pp, field) ((pp)->kp_lwp.kl_ ## field)
80#define VP(pp, field) ((pp)->kp_vm_ ## field)
984263bc 81
984263bc 82/* what we consider to be process size: */
5dfd06ac 83#define PROCSIZE(pp) (VP((pp), map_size) / 1024)
984263bc 84
984263bc 85/*
961f1f09 86 * These definitions control the format of the per-process area
984263bc
MD
87 */
88
89static char smp_header[] =
c61c17ed 90" PID %-*.*s NICE SIZE RES STATE C TIME CTIME CPU COMMAND";
984263bc
MD
91
92#define smp_Proc_format \
c61c17ed 93 "%6d %-*.*s %3d%7s %6s %8.8s %3d %6s %7s %5.2f%% %.*s"
984263bc 94
984263bc 95/* process state names for the "STATE" column of the display */
961f1f09
JL
96/*
97 * the extra nulls in the string "run" are for adding a slash and the
98 * processor number when needed
99 */
984263bc 100
961f1f09
JL
101const char *state_abbrev[] = {
102 "", "RUN\0\0\0", "STOP", "SLEEP",
984263bc
MD
103};
104
105
106static kvm_t *kd;
107
108/* values that we stash away in _init and use in later routines */
109
984263bc 110static long lastpid;
984263bc
MD
111
112/* these are for calculating cpu state percentages */
113
edb881dd 114static struct kinfo_cputime *cp_time, *cp_old;
984263bc
MD
115
116/* these are for detailing the process states */
117
d6eee517
MD
118#define MAXPSTATES 6
119
120int process_states[MAXPSTATES];
121
7af1b2bc 122char *procstatenames[] = {
bc40e61d 123 " running, ", " idle, ", " active, ", " stopped, ", " zombie, ",
961f1f09 124 NULL
984263bc
MD
125};
126
127/* these are for detailing the cpu states */
f5d21610 128#define CPU_STATES 5
edb881dd 129int *cpu_states;
edc735ac 130int* cpu_averages;
7af1b2bc 131char *cpustatenames[CPU_STATES + 1] = {
961f1f09 132 "user", "nice", "system", "interrupt", "idle", NULL
984263bc
MD
133};
134
135/* these are for detailing the memory statistics */
136
7af1b2bc
JL
137long memory_stats[7];
138char *memorynames[] = {
961f1f09
JL
139 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
140 NULL
984263bc
MD
141};
142
7af1b2bc
JL
143long swap_stats[7];
144char *swapnames[] = {
961f1f09
JL
145 /* 0 1 2 3 4 5 */
146 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
147 NULL
984263bc
MD
148};
149
150
151/* these are for keeping track of the proc array */
152
153static int nproc;
154static int onproc = -1;
155static int pref_len;
156static struct kinfo_proc *pbase;
157static struct kinfo_proc **pref;
158
b5121966
SZ
159static uint64_t prev_pbase_time; /* unit: us */
160static struct kinfo_proc *prev_pbase;
76ccf3d0
SZ
161static int prev_pbase_alloc;
162static int prev_nproc;
b5121966
SZ
163static int fscale;
164
984263bc
MD
165/* these are for getting the memory statistics */
166
167static int pageshift; /* log base 2 of the pagesize */
168
169/* define pagetok in terms of pageshift */
170
171#define pagetok(size) ((size) << pageshift)
172
984263bc 173/* sorting orders. first is default */
7af1b2bc 174char *ordernames[] = {
50a55c46 175 "cpu", "size", "res", "time", "pri", "thr", "pid", "ctime", "pres", NULL
984263bc 176};
7af1b2bc
JL
177
178/* compare routines */
8b72b421
JL
179int proc_compare (struct kinfo_proc **, struct kinfo_proc **);
180int compare_size (struct kinfo_proc **, struct kinfo_proc **);
181int compare_res (struct kinfo_proc **, struct kinfo_proc **);
182int compare_time (struct kinfo_proc **, struct kinfo_proc **);
bcd4a7c1 183int compare_ctime (struct kinfo_proc **, struct kinfo_proc **);
8b72b421
JL
184int compare_prio(struct kinfo_proc **, struct kinfo_proc **);
185int compare_thr (struct kinfo_proc **, struct kinfo_proc **);
186int compare_pid (struct kinfo_proc **, struct kinfo_proc **);
50a55c46 187int compare_pres(struct kinfo_proc **, struct kinfo_proc **);
8b72b421
JL
188
189int (*proc_compares[]) (struct kinfo_proc **,struct kinfo_proc **) = {
7af1b2bc
JL
190 proc_compare,
191 compare_size,
192 compare_res,
193 compare_time,
194 compare_prio,
8b72b421
JL
195 compare_thr,
196 compare_pid,
bcd4a7c1 197 compare_ctime,
50a55c46 198 compare_pres,
7af1b2bc
JL
199 NULL
200};
984263bc 201
f5d21610
JS
202static void
203cputime_percentages(int out[CPU_STATES], struct kinfo_cputime *new,
961f1f09 204 struct kinfo_cputime *old)
f5d21610 205{
961f1f09 206 struct kinfo_cputime diffs;
f5d21610
JS
207 uint64_t total_change, half_total;
208
961f1f09 209 /* initialization */
f5d21610
JS
210 total_change = 0;
211
961f1f09 212 diffs.cp_user = new->cp_user - old->cp_user;
f5d21610
JS
213 diffs.cp_nice = new->cp_nice - old->cp_nice;
214 diffs.cp_sys = new->cp_sys - old->cp_sys;
961f1f09
JL
215 diffs.cp_intr = new->cp_intr - old->cp_intr;
216 diffs.cp_idle = new->cp_idle - old->cp_idle;
f5d21610 217 total_change = diffs.cp_user + diffs.cp_nice + diffs.cp_sys +
961f1f09
JL
218 diffs.cp_intr + diffs.cp_idle;
219 old->cp_user = new->cp_user;
220 old->cp_nice = new->cp_nice;
221 old->cp_sys = new->cp_sys;
222 old->cp_intr = new->cp_intr;
f5d21610
JS
223 old->cp_idle = new->cp_idle;
224
961f1f09 225 /* avoid divide by zero potential */
f5d21610
JS
226 if (total_change == 0)
227 total_change = 1;
228
229 /* calculate percentages based on overall change, rounding up */
961f1f09 230 half_total = total_change >> 1;
f5d21610
JS
231
232 out[0] = ((diffs.cp_user * 1000LL + half_total) / total_change);
961f1f09 233 out[1] = ((diffs.cp_nice * 1000LL + half_total) / total_change);
f5d21610 234 out[2] = ((diffs.cp_sys * 1000LL + half_total) / total_change);
961f1f09 235 out[3] = ((diffs.cp_intr * 1000LL + half_total) / total_change);
f5d21610
JS
236 out[4] = ((diffs.cp_idle * 1000LL + half_total) / total_change);
237}
238
984263bc 239int
1d1731fa 240machine_init(struct statics *statics)
984263bc 241{
961f1f09 242 int pagesize;
b5121966 243 size_t modelen, prmlen;
961f1f09 244 struct passwd *pw;
7af1b2bc 245 struct timeval boottime;
984263bc 246
961f1f09
JL
247 if (n_cpus < 1) {
248 if (kinfo_get_cpus(&n_cpus))
249 err(1, "kinfo_get_cpus failed");
250 }
7af1b2bc
JL
251 /* get boot time */
252 modelen = sizeof(boottime);
253 if (sysctlbyname("kern.boottime", &boottime, &modelen, NULL, 0) == -1) {
7af1b2bc
JL
254 /* we have no boottime to report */
255 boottime.tv_sec = -1;
256 }
961f1f09 257
b5121966
SZ
258 prmlen = sizeof(fscale);
259 if (sysctlbyname("kern.fscale", &fscale, &prmlen, NULL, 0) == -1)
76ccf3d0 260 err(1, "sysctl kern.fscale failed");
b5121966 261
961f1f09
JL
262 while ((pw = getpwent()) != NULL) {
263 if ((int)strlen(pw->pw_name) > namelength)
264 namelength = strlen(pw->pw_name);
265 }
266 if (namelength < 8)
267 namelength = 8;
975fc636 268 if (namelength > 13)
961f1f09 269 namelength = 13;
961f1f09 270
efde5811 271 if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL)) == NULL)
961f1f09
JL
272 return -1;
273
961f1f09
JL
274 pbase = NULL;
275 pref = NULL;
276 nproc = 0;
277 onproc = -1;
b5121966 278 prev_pbase = NULL;
76ccf3d0
SZ
279 prev_pbase_alloc = 0;
280 prev_pbase_time = 0;
281 prev_nproc = 0;
961f1f09
JL
282 /*
283 * get the page size with "getpagesize" and calculate pageshift from
284 * it
285 */
286 pagesize = getpagesize();
287 pageshift = 0;
288 while (pagesize > 1) {
289 pageshift++;
290 pagesize >>= 1;
291 }
292
293 /* we only need the amount of log(2)1024 for our conversion */
294 pageshift -= LOG1024;
295
296 /* fill in the statics information */
297 statics->procstate_names = procstatenames;
298 statics->cpustate_names = cpustatenames;
299 statics->memory_names = memorynames;
300 statics->boottime = boottime.tv_sec;
301 statics->swap_names = swapnames;
302 statics->order_names = ordernames;
efde5811
JL
303 /* we need kvm descriptor in order to show full commands */
304 statics->flags.fullcmds = kd != NULL;
cb68a542 305 statics->flags.threads = 1;
961f1f09
JL
306
307 /* all done! */
308 return (0);
984263bc
MD
309}
310
b552171b 311char *
7af1b2bc 312format_header(char *uname_field)
984263bc 313{
961f1f09 314 static char Header[128];
984263bc 315
975fc636 316 snprintf(Header, sizeof(Header), smp_header,
961f1f09 317 namelength, namelength, uname_field);
984263bc 318
961f1f09
JL
319 if (screen_width <= 79)
320 cmdlength = 80;
321 else
8b72b421 322 cmdlength = screen_width;
95578ad0 323
961f1f09 324 cmdlength = cmdlength - strlen(Header) + 6;
984263bc 325
961f1f09 326 return Header;
984263bc
MD
327}
328
329static int swappgsin = -1;
330static int swappgsout = -1;
331extern struct timeval timeout;
332
333void
1d1731fa 334get_system_info(struct system_info *si)
984263bc 335{
961f1f09
JL
336 size_t len;
337 int cpu;
338
339 if (cpu_states == NULL) {
340 cpu_states = malloc(sizeof(*cpu_states) * CPU_STATES * n_cpus);
341 if (cpu_states == NULL)
342 err(1, "malloc");
343 bzero(cpu_states, sizeof(*cpu_states) * CPU_STATES * n_cpus);
984263bc 344 }
961f1f09
JL
345 if (cp_time == NULL) {
346 cp_time = malloc(2 * n_cpus * sizeof(cp_time[0]));
347 if (cp_time == NULL)
348 err(1, "cp_time");
349 cp_old = cp_time + n_cpus;
961f1f09
JL
350 len = n_cpus * sizeof(cp_old[0]);
351 bzero(cp_time, len);
352 if (sysctlbyname("kern.cputime", cp_old, &len, NULL, 0))
353 err(1, "kern.cputime");
354 }
355 len = n_cpus * sizeof(cp_time[0]);
356 bzero(cp_time, len);
357 if (sysctlbyname("kern.cputime", cp_time, &len, NULL, 0))
358 err(1, "kern.cputime");
359
360 getloadavg(si->load_avg, 3);
361
362 lastpid = 0;
984263bc 363
961f1f09 364 /* convert cp_time counts to percentages */
edc735ac 365 int combine_cpus = (enable_ncpus == 0 && n_cpus > 1);
961f1f09
JL
366 for (cpu = 0; cpu < n_cpus; ++cpu) {
367 cputime_percentages(cpu_states + cpu * CPU_STATES,
368 &cp_time[cpu], &cp_old[cpu]);
369 }
edc735ac
JA
370 if (combine_cpus) {
371 if (cpu_averages == NULL) {
372 cpu_averages = malloc(sizeof(*cpu_averages) * CPU_STATES);
373 if (cpu_averages == NULL)
374 err(1, "cpu_averages");
375 }
376 bzero(cpu_averages, sizeof(*cpu_averages) * CPU_STATES);
377 for (cpu = 0; cpu < n_cpus; ++cpu) {
378 int j = 0;
379 cpu_averages[0] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
380 cpu_averages[1] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
381 cpu_averages[2] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
382 cpu_averages[3] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
383 cpu_averages[4] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
384 }
385 for (int i = 0; i < CPU_STATES; ++i)
386 cpu_averages[i] /= n_cpus;
387 }
984263bc 388
961f1f09
JL
389 /* sum memory & swap statistics */
390 {
391 struct vmmeter vmm;
392 struct vmstats vms;
393 size_t vms_size = sizeof(vms);
394 size_t vmm_size = sizeof(vmm);
395 static unsigned int swap_delay = 0;
396 static int swapavail = 0;
397 static int swapfree = 0;
3583bbb4 398 static long bufspace = 0;
961f1f09
JL
399
400 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0))
401 err(1, "sysctlbyname: vm.vmstats");
402
403 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0))
404 err(1, "sysctlbyname: vm.vmmeter");
405
406 if (kinfo_get_vfs_bufspace(&bufspace))
407 err(1, "kinfo_get_vfs_bufspace");
408
409 /* convert memory stats to Kbytes */
410 memory_stats[0] = pagetok(vms.v_active_count);
411 memory_stats[1] = pagetok(vms.v_inactive_count);
412 memory_stats[2] = pagetok(vms.v_wire_count);
413 memory_stats[3] = pagetok(vms.v_cache_count);
414 memory_stats[4] = bufspace / 1024;
415 memory_stats[5] = pagetok(vms.v_free_count);
416 memory_stats[6] = -1;
417
418 /* first interval */
419 if (swappgsin < 0) {
420 swap_stats[4] = 0;
421 swap_stats[5] = 0;
422 }
423 /* compute differences between old and new swap statistic */
424 else {
425 swap_stats[4] = pagetok(((vmm.v_swappgsin - swappgsin)));
426 swap_stats[5] = pagetok(((vmm.v_swappgsout - swappgsout)));
427 }
428
429 swappgsin = vmm.v_swappgsin;
430 swappgsout = vmm.v_swappgsout;
431
432 /* call CPU heavy swapmode() only for changes */
433 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
434 swap_stats[3] = swapmode(&swapavail, &swapfree);
435 swap_stats[0] = swapavail;
436 swap_stats[1] = swapavail - swapfree;
437 swap_stats[2] = swapfree;
438 }
439 swap_delay = 1;
440 swap_stats[6] = -1;
984263bc 441 }
984263bc 442
961f1f09 443 /* set arrays and strings */
edc735ac
JA
444 si->cpustates = combine_cpus == 1 ?
445 cpu_averages : cpu_states;
961f1f09
JL
446 si->memory = memory_stats;
447 si->swap = swap_stats;
984263bc
MD
448
449
961f1f09
JL
450 if (lastpid > 0) {
451 si->last_pid = lastpid;
452 } else {
453 si->last_pid = -1;
454 }
984263bc
MD
455}
456
7af1b2bc 457
984263bc
MD
458static struct handle handle;
459
b5121966 460static void
76ccf3d0 461fixup_pctcpu(struct kinfo_proc *fixit, uint64_t d)
b5121966
SZ
462{
463 struct kinfo_proc *pp;
76ccf3d0 464 uint64_t ticks;
685dc2e1 465 int i;
b5121966 466
76ccf3d0 467 if (prev_nproc == 0 || d == 0)
b5121966
SZ
468 return;
469
76ccf3d0
SZ
470 if (LP(fixit, pid) == -1) {
471 /* Skip kernel "idle" threads */
472 if (PP(fixit, stat) == SIDL)
473 return;
474 for (pp = prev_pbase, i = 0; i < prev_nproc; pp++, i++) {
475 if (LP(pp, pid) == -1 &&
476 PP(pp, ktaddr) == PP(fixit, ktaddr))
477 break;
478 }
479 } else {
480 for (pp = prev_pbase, i = 0; i < prev_nproc; pp++, i++) {
481 if (LP(pp, pid) == LP(fixit, pid) &&
482 LP(pp, tid) == LP(fixit, tid)) {
483 if (PP(pp, paddr) != PP(fixit, paddr)) {
484 /* pid/tid are reused */
485 pp = NULL;
486 }
487 break;
488 }
b5121966
SZ
489 }
490 }
76ccf3d0
SZ
491 if (i == prev_nproc || pp == NULL)
492 return;
493
494 ticks = LP(fixit, iticks) - LP(pp, iticks);
495 ticks += LP(fixit, sticks) - LP(pp, sticks);
496 ticks += LP(fixit, uticks) - LP(pp, uticks);
5deae5c6
MD
497 if (ticks > d * 1000)
498 ticks = d * 1000;
76ccf3d0 499 LP(fixit, pctcpu) = (ticks * (uint64_t)fscale) / d;
b5121966
SZ
500}
501
961f1f09
JL
502caddr_t
503get_process_info(struct system_info *si, struct process_select *sel,
7af1b2bc 504 int compare_index)
984263bc 505{
76ccf3d0
SZ
506 struct timespec tv;
507 uint64_t t, d = 0;
508
961f1f09
JL
509 int i;
510 int total_procs;
511 int active_procs;
512 struct kinfo_proc **prefp;
513 struct kinfo_proc *pp;
514
515 /* these are copied out of sel for speed */
516 int show_idle;
517 int show_system;
518 int show_uid;
b0b07bbb 519 int show_threads;
ea03a758 520 char *match_command;
b0b07bbb
AH
521
522 show_threads = sel->threads;
961f1f09 523
b0b07bbb
AH
524 pbase = kvm_getprocs(kd,
525 KERN_PROC_ALL | (show_threads ? KERN_PROC_FLAG_LWP : 0), 0, &nproc);
961f1f09
JL
526 if (nproc > onproc)
527 pref = (struct kinfo_proc **)realloc(pref, sizeof(struct kinfo_proc *)
528 * (onproc = nproc));
529 if (pref == NULL || pbase == NULL) {
530 (void)fprintf(stderr, "top: Out of memory.\n");
531 quit(23);
532 }
76ccf3d0
SZ
533
534 clock_gettime(CLOCK_MONOTONIC_PRECISE, &tv);
535 t = (tv.tv_sec * 1000000ULL) + (tv.tv_nsec / 1000ULL);
536 if (prev_pbase_time > 0 && t > prev_pbase_time)
537 d = t - prev_pbase_time;
538
961f1f09
JL
539 /* get a pointer to the states summary array */
540 si->procstates = process_states;
541
542 /* set up flags which define what we are going to select */
543 show_idle = sel->idle;
544 show_system = sel->system;
545 show_uid = sel->uid != -1;
efde5811 546 show_fullcmd = sel->fullcmd;
ea03a758 547 match_command = sel->command;
961f1f09
JL
548
549 /* count up process states and get pointers to interesting procs */
550 total_procs = 0;
551 active_procs = 0;
552 memset((char *)process_states, 0, sizeof(process_states));
553 prefp = pref;
554 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
555 /*
556 * Place pointers to each valid proc structure in pref[].
557 * Process slots that are actually in use have a non-zero
558 * status field. Processes with P_SYSTEM set are system
559 * processes---these get ignored unless show_sysprocs is set.
560 */
bfb09e3b 561 if ((show_system && (LP(pp, pid) == -1)) ||
961f1f09 562 (show_system || ((PP(pp, flags) & P_SYSTEM) == 0))) {
0ce28ef3
JG
563 int lpstate = LP(pp, stat);
564 int pstate = PP(pp, stat);
d6eee517 565
961f1f09 566 total_procs++;
0ce28ef3 567 if (lpstate == LSRUN)
bc40e61d 568 process_states[0]++;
0ce28ef3 569 if (pstate >= 0 && pstate < MAXPSTATES - 1)
d6eee517 570 process_states[pstate]++;
76ccf3d0
SZ
571
572 if (match_command != NULL &&
573 strstr(PP(pp, comm), match_command) == NULL) {
574 /* Command does not match */
575 continue;
961f1f09 576 }
984263bc 577
76ccf3d0
SZ
578 if (show_uid && PP(pp, ruid) != (uid_t)sel->uid) {
579 /* UID does not match */
580 continue;
581 }
b5121966 582
76ccf3d0
SZ
583 if (!show_system && LP(pp, pid) == -1) {
584 /* Don't show system processes */
585 continue;
586 }
b5121966 587
76ccf3d0
SZ
588 /* Fix up pctcpu before show_idle test */
589 fixup_pctcpu(pp, d);
b5121966 590
76ccf3d0
SZ
591 if (!show_idle && LP(pp, pctcpu) == 0 &&
592 lpstate != LSRUN) {
593 /* Don't show idle processes */
594 continue;
b5121966 595 }
76ccf3d0
SZ
596
597 *prefp++ = pp;
598 active_procs++;
b5121966 599 }
76ccf3d0 600 }
b5121966 601
76ccf3d0
SZ
602 /*
603 * Save kinfo_procs for later pctcpu fixup.
604 */
605 if (prev_pbase_alloc < nproc) {
606 prev_pbase_alloc = nproc;
607 prev_pbase = realloc(prev_pbase,
608 prev_pbase_alloc * sizeof(struct kinfo_proc));
609 if (prev_pbase == NULL) {
610 fprintf(stderr, "top: Out of memory.\n");
611 quit(23);
b5121966 612 }
b5121966 613 }
76ccf3d0
SZ
614 prev_nproc = nproc;
615 prev_pbase_time = t;
616 memcpy(prev_pbase, pbase, nproc * sizeof(struct kinfo_proc));
b5121966 617
7af1b2bc 618 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *),
8b72b421 619 (int (*)(const void *, const void *))proc_compares[compare_index]);
984263bc 620
961f1f09
JL
621 /* remember active and total counts */
622 si->p_total = total_procs;
623 si->p_active = pref_len = active_procs;
984263bc 624
961f1f09
JL
625 /* pass back a handle */
626 handle.next_proc = pref;
627 handle.remaining = active_procs;
0ca59c34 628 handle.show_threads = show_threads;
961f1f09 629 return ((caddr_t) & handle);
984263bc
MD
630}
631
cef6b642 632char fmt[MAX_COLS]; /* static area where result is built */
984263bc 633
b552171b 634char *
961f1f09 635format_next_process(caddr_t xhandle, char *(*get_userid) (int))
984263bc 636{
961f1f09
JL
637 struct kinfo_proc *pp;
638 long cputime;
bcd4a7c1 639 long ccputime;
961f1f09
JL
640 double pct;
641 struct handle *hp;
642 char status[16];
961f1f09
JL
643 int state;
644 int xnice;
efde5811 645 char *comm;
bcd4a7c1 646 char cputime_fmt[10], ccputime_fmt[10];
961f1f09
JL
647
648 /* find and remember the next proc structure */
649 hp = (struct handle *)xhandle;
650 pp = *(hp->next_proc++);
651 hp->remaining--;
652
961f1f09 653 /* get the process's command name */
efde5811 654 if (show_fullcmd) {
cb68a542 655 char **comm_full = kvm_getargv(kd, pp, 0);
5e83d98b 656 if (comm_full != NULL)
cb68a542
AN
657 comm = *comm_full;
658 else
826597b5 659 comm = PP(pp, comm);
efde5811
JL
660 }
661 else {
662 comm = PP(pp, comm);
961f1f09 663 }
cb68a542
AN
664
665 /* the actual field to display */
666 char cmdfield[MAX_COLS];
667
668 if (PP(pp, flags) & P_SYSTEM) {
669 /* system process */
670 snprintf(cmdfield, sizeof cmdfield, "[%s]", comm);
0ca59c34 671 } else if (hp->show_threads && PP(pp, nthreads) > 1) {
cb68a542 672 /* display it as a thread */
0ca59c34
SZ
673 if (strcmp(PP(pp, comm), LP(pp, comm)) == 0) {
674 snprintf(cmdfield, sizeof cmdfield, "%s{%d}", comm,
675 LP(pp, tid));
676 } else {
677 /* show thread name in addition to tid */
678 snprintf(cmdfield, sizeof cmdfield, "%s{%d/%s}", comm,
679 LP(pp, tid), LP(pp, comm));
680 }
cb68a542
AN
681 } else {
682 snprintf(cmdfield, sizeof cmdfield, "%s", comm);
683 }
efde5811 684
961f1f09
JL
685 /*
686 * Convert the process's runtime from microseconds to seconds. This
bcd4a7c1 687 * time includes the interrupt time to be in compliance with ps output.
213c68be 688 */
bcd4a7c1
JL
689 cputime = (LP(pp, uticks) + LP(pp, sticks) + LP(pp, iticks)) / 1000000;
690 ccputime = cputime + PP(pp, cru).ru_stime.tv_sec + PP(pp, cru).ru_utime.tv_sec;
691 format_time(cputime, cputime_fmt, sizeof(cputime_fmt));
692 format_time(ccputime, ccputime_fmt, sizeof(ccputime_fmt));
961f1f09
JL
693
694 /* calculate the base for cpu percentages */
695 pct = pctdouble(LP(pp, pctcpu));
696
697 /* generate "STATE" field */
698 switch (state = LP(pp, stat)) {
164b8401 699 case LSRUN:
975fc636 700 if (LP(pp, tdflags) & TDF_RUNNING)
961f1f09
JL
701 sprintf(status, "CPU%d", LP(pp, cpuid));
702 else
703 strcpy(status, "RUN");
704 break;
164b8401 705 case LSSLEEP:
961f1f09 706 if (LP(pp, wmesg) != NULL) {
8ddceaf5 707 sprintf(status, "%.8s", LP(pp, wmesg)); /* WMESGLEN */
961f1f09
JL
708 break;
709 }
710 /* fall through */
711 default:
712
e62ef63c 713 if (state >= 0 && (unsigned)state < NELEM(state_abbrev))
961f1f09
JL
714 sprintf(status, "%.6s", state_abbrev[(unsigned char)state]);
715 else
716 sprintf(status, "?%5d", state);
717 break;
718 }
719
720 if (PP(pp, stat) == SZOMB)
721 strcpy(status, "ZOMB");
722
723 /*
724 * idle time 0 - 31 -> nice value +21 - +52 normal time -> nice
725 * value -20 - +20 real time 0 - 31 -> nice value -52 - -21 thread
726 * 0 - 31 -> nice value -53 -
727 */
728 switch (LP(pp, rtprio.type)) {
729 case RTP_PRIO_REALTIME:
730 xnice = PRIO_MIN - 1 - RTP_PRIO_MAX + LP(pp, rtprio.prio);
731 break;
732 case RTP_PRIO_IDLE:
733 xnice = PRIO_MAX + 1 + LP(pp, rtprio.prio);
734 break;
735 case RTP_PRIO_THREAD:
736 xnice = PRIO_MIN - 1 - RTP_PRIO_MAX - LP(pp, rtprio.prio);
984263bc 737 break;
984263bc 738 default:
961f1f09
JL
739 xnice = PP(pp, nice);
740 break;
741 }
984263bc 742
961f1f09
JL
743 /* format this entry */
744 snprintf(fmt, sizeof(fmt),
975fc636 745 smp_Proc_format,
b552171b 746 (int)PP(pp, pid),
984263bc 747 namelength, namelength,
b552171b 748 get_userid(PP(pp, ruid)),
b552171b 749 (int)xnice,
7af1b2bc 750 format_k(PROCSIZE(pp)),
30277d08 751 format_k(pagetok(VP(pp, rssize))),
984263bc 752 status,
975fc636 753 LP(pp, cpuid),
bcd4a7c1
JL
754 cputime_fmt,
755 ccputime_fmt,
984263bc
MD
756 100.0 * pct,
757 cmdlength,
cb68a542 758 cmdfield);
984263bc 759
961f1f09
JL
760 /* return the result */
761 return (fmt);
984263bc
MD
762}
763
984263bc
MD
764/* comparison routines for qsort */
765
766/*
767 * proc_compare - comparison function for "qsort"
768 * Compares the resource consumption of two processes using five
769 * distinct keys. The keys (in descending order of importance) are:
770 * percent cpu, cpu ticks, state, resident set size, total virtual
771 * memory usage. The process states are ordered as follows (from least
772 * to most important): WAIT, zombie, sleep, stop, start, run. The
773 * array declaration below maps a process state index into a number
774 * that reflects this ordering.
775 */
776
777static unsigned char sorted_state[] =
778{
961f1f09
JL
779 0, /* not used */
780 3, /* sleep */
781 1, /* ABANDONED (WAIT) */
782 6, /* run */
783 5, /* start */
784 2, /* zombie */
785 4 /* stop */
984263bc 786};
961f1f09 787
984263bc
MD
788
789#define ORDERKEY_PCTCPU \
5dfd06ac 790 if (lresult = (long) LP(p2, pctcpu) - (long) LP(p1, pctcpu), \
984263bc
MD
791 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
792
bcd4a7c1 793#define CPTICKS(p) (LP(p, uticks) + LP(p, sticks) + LP(p, iticks))
6ac7b760 794
984263bc 795#define ORDERKEY_CPTICKS \
6ac7b760
MD
796 if ((result = CPTICKS(p2) > CPTICKS(p1) ? 1 : \
797 CPTICKS(p2) < CPTICKS(p1) ? -1 : 0) == 0)
984263bc 798
bcd4a7c1
JL
799#define CTIME(p) (((LP(p, uticks) + LP(p, sticks) + LP(p, iticks))/1000000) + \
800 PP(p, cru).ru_stime.tv_sec + PP(p, cru).ru_utime.tv_sec)
801
802#define ORDERKEY_CTIME \
803 if ((result = CTIME(p2) > CTIME(p1) ? 1 : \
804 CTIME(p2) < CTIME(p1) ? -1 : 0) == 0)
805
984263bc 806#define ORDERKEY_STATE \
5dfd06ac
SS
807 if ((result = sorted_state[(unsigned char) PP(p2, stat)] - \
808 sorted_state[(unsigned char) PP(p1, stat)]) == 0)
984263bc
MD
809
810#define ORDERKEY_PRIO \
5dfd06ac 811 if ((result = LP(p2, prio) - LP(p1, prio)) == 0)
984263bc 812
95578ad0 813#define ORDERKEY_KTHREADS \
5dfd06ac 814 if ((result = (LP(p1, pid) == 0) - (LP(p2, pid) == 0)) == 0)
95578ad0
HP
815
816#define ORDERKEY_KTHREADS_PRIO \
5dfd06ac 817 if ((result = LP(p2, tdprio) - LP(p1, tdprio)) == 0)
95578ad0 818
984263bc 819#define ORDERKEY_RSSIZE \
961f1f09 820 if ((result = VP(p2, rssize) - VP(p1, rssize)) == 0)
984263bc
MD
821
822#define ORDERKEY_MEM \
823 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
824
8b72b421
JL
825#define ORDERKEY_PID \
826 if ( (result = PP(p1, pid) - PP(p2, pid)) == 0)
827
50a55c46
MD
828#define ORDERKEY_PRSSIZE \
829 if((result = VP(p2, prssize) - VP(p1, prssize)) == 0)
830
bfbef474
SZ
831static __inline int
832orderkey_kernidle(const struct kinfo_proc *p1, const struct kinfo_proc *p2)
833{
834 int p1_kidle = 0, p2_kidle = 0;
835
836 if (LP(p1, pid) == -1 && PP(p1, stat) == SIDL)
837 p1_kidle = 1;
838 if (LP(p2, pid) == -1 && PP(p2, stat) == SIDL)
839 p2_kidle = 1;
840
841 if (!p2_kidle && p1_kidle)
842 return 1;
843 if (p2_kidle && !p1_kidle)
844 return -1;
845 return 0;
846}
847
848#define ORDERKEY_KIDLE if ((result = orderkey_kernidle(p1, p2)) == 0)
849
984263bc
MD
850/* compare_cpu - the comparison function for sorting by cpu percentage */
851
852int
8b72b421 853proc_compare(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
984263bc 854{
8b72b421
JL
855 struct kinfo_proc *p1;
856 struct kinfo_proc *p2;
961f1f09
JL
857 int result;
858 pctcpu lresult;
859
860 /* remove one level of indirection */
8b72b421
JL
861 p1 = *(struct kinfo_proc **) pp1;
862 p2 = *(struct kinfo_proc **) pp2;
961f1f09 863
bfbef474 864 ORDERKEY_KIDLE
961f1f09
JL
865 ORDERKEY_PCTCPU
866 ORDERKEY_CPTICKS
867 ORDERKEY_STATE
868 ORDERKEY_PRIO
869 ORDERKEY_RSSIZE
870 ORDERKEY_MEM
871 {}
872
873 return (result);
984263bc
MD
874}
875
984263bc
MD
876/* compare_size - the comparison function for sorting by total memory usage */
877
878int
8b72b421 879compare_size(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
984263bc 880{
961f1f09
JL
881 struct kinfo_proc *p1;
882 struct kinfo_proc *p2;
883 int result;
884 pctcpu lresult;
885
886 /* remove one level of indirection */
8b72b421
JL
887 p1 = *(struct kinfo_proc **) pp1;
888 p2 = *(struct kinfo_proc **) pp2;
961f1f09
JL
889
890 ORDERKEY_MEM
891 ORDERKEY_RSSIZE
bfbef474 892 ORDERKEY_KIDLE
961f1f09
JL
893 ORDERKEY_PCTCPU
894 ORDERKEY_CPTICKS
895 ORDERKEY_STATE
896 ORDERKEY_PRIO
897 {}
898
899 return (result);
984263bc
MD
900}
901
902/* compare_res - the comparison function for sorting by resident set size */
903
904int
8b72b421 905compare_res(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
984263bc 906{
961f1f09
JL
907 struct kinfo_proc *p1;
908 struct kinfo_proc *p2;
909 int result;
910 pctcpu lresult;
911
912 /* remove one level of indirection */
8b72b421
JL
913 p1 = *(struct kinfo_proc **) pp1;
914 p2 = *(struct kinfo_proc **) pp2;
961f1f09
JL
915
916 ORDERKEY_RSSIZE
917 ORDERKEY_MEM
bfbef474 918 ORDERKEY_KIDLE
961f1f09
JL
919 ORDERKEY_PCTCPU
920 ORDERKEY_CPTICKS
921 ORDERKEY_STATE
922 ORDERKEY_PRIO
923 {}
924
925 return (result);
984263bc
MD
926}
927
50a55c46
MD
928/* compare_pres - the comparison function for sorting by proportional resident set size */
929
930int
931compare_pres(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
932{
933 struct kinfo_proc *p1;
934 struct kinfo_proc *p2;
935 int result;
936 pctcpu lresult;
937
938 /* remove one level of indirection */
939 p1 = *(struct kinfo_proc **) pp1;
940 p2 = *(struct kinfo_proc **) pp2;
941
942 ORDERKEY_PRSSIZE
943 ORDERKEY_RSSIZE
944 ORDERKEY_MEM
bfbef474 945 ORDERKEY_KIDLE
50a55c46
MD
946 ORDERKEY_PCTCPU
947 ORDERKEY_CPTICKS
948 ORDERKEY_STATE
949 ORDERKEY_PRIO
950 {}
951
952 return (result);
953}
954
984263bc
MD
955/* compare_time - the comparison function for sorting by total cpu time */
956
957int
8b72b421 958compare_time(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
984263bc 959{
8b72b421
JL
960 struct kinfo_proc *p1;
961 struct kinfo_proc *p2;
961f1f09
JL
962 int result;
963 pctcpu lresult;
964
965 /* remove one level of indirection */
8b72b421
JL
966 p1 = *(struct kinfo_proc **) pp1;
967 p2 = *(struct kinfo_proc **) pp2;
961f1f09 968
bfbef474 969 ORDERKEY_KIDLE
961f1f09
JL
970 ORDERKEY_CPTICKS
971 ORDERKEY_PCTCPU
972 ORDERKEY_KTHREADS
973 ORDERKEY_KTHREADS_PRIO
974 ORDERKEY_STATE
975 ORDERKEY_PRIO
976 ORDERKEY_RSSIZE
977 ORDERKEY_MEM
978 {}
979
980 return (result);
981}
982
bcd4a7c1
JL
983int
984compare_ctime(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
985{
986 struct kinfo_proc *p1;
987 struct kinfo_proc *p2;
988 int result;
989 pctcpu lresult;
990
991 /* remove one level of indirection */
992 p1 = *(struct kinfo_proc **) pp1;
993 p2 = *(struct kinfo_proc **) pp2;
bfbef474
SZ
994
995 ORDERKEY_KIDLE
bcd4a7c1
JL
996 ORDERKEY_CTIME
997 ORDERKEY_PCTCPU
998 ORDERKEY_KTHREADS
999 ORDERKEY_KTHREADS_PRIO
1000 ORDERKEY_STATE
1001 ORDERKEY_PRIO
1002 ORDERKEY_RSSIZE
1003 ORDERKEY_MEM
1004 {}
1005
1006 return (result);
1007}
1008
984263bc
MD
1009/* compare_prio - the comparison function for sorting by cpu percentage */
1010
1011int
8b72b421 1012compare_prio(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
984263bc 1013{
8b72b421
JL
1014 struct kinfo_proc *p1;
1015 struct kinfo_proc *p2;
961f1f09
JL
1016 int result;
1017 pctcpu lresult;
1018
1019 /* remove one level of indirection */
8b72b421
JL
1020 p1 = *(struct kinfo_proc **) pp1;
1021 p2 = *(struct kinfo_proc **) pp2;
961f1f09
JL
1022
1023 ORDERKEY_KTHREADS
1024 ORDERKEY_KTHREADS_PRIO
1025 ORDERKEY_PRIO
bfbef474 1026 ORDERKEY_KIDLE
961f1f09
JL
1027 ORDERKEY_CPTICKS
1028 ORDERKEY_PCTCPU
1029 ORDERKEY_STATE
1030 ORDERKEY_RSSIZE
1031 ORDERKEY_MEM
1032 {}
1033
1034 return (result);
984263bc 1035}
95578ad0
HP
1036
1037int
8b72b421 1038compare_thr(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
95578ad0 1039{
8b72b421
JL
1040 struct kinfo_proc *p1;
1041 struct kinfo_proc *p2;
961f1f09
JL
1042 int result;
1043 pctcpu lresult;
1044
1045 /* remove one level of indirection */
8b72b421
JL
1046 p1 = *(struct kinfo_proc **)pp1;
1047 p2 = *(struct kinfo_proc **)pp2;
961f1f09
JL
1048
1049 ORDERKEY_KTHREADS
1050 ORDERKEY_KTHREADS_PRIO
bfbef474 1051 ORDERKEY_KIDLE
961f1f09
JL
1052 ORDERKEY_CPTICKS
1053 ORDERKEY_PCTCPU
1054 ORDERKEY_STATE
1055 ORDERKEY_RSSIZE
1056 ORDERKEY_MEM
1057 {}
1058
1059 return (result);
95578ad0
HP
1060}
1061
8b72b421
JL
1062/* compare_pid - the comparison function for sorting by process id */
1063
1064int
1065compare_pid(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
1066{
1067 struct kinfo_proc *p1;
1068 struct kinfo_proc *p2;
1069 int result;
1070
1071 /* remove one level of indirection */
1072 p1 = *(struct kinfo_proc **) pp1;
1073 p2 = *(struct kinfo_proc **) pp2;
1074
1075 ORDERKEY_PID
1076 ;
1077
1078 return(result);
1079}
1080
984263bc
MD
1081/*
1082 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1083 * the process does not exist.
1084 * It is EXTREMLY IMPORTANT that this function work correctly.
1085 * If top runs setuid root (as in SVR4), then this function
1086 * is the only thing that stands in the way of a serious
1087 * security problem. It validates requests for the "kill"
1088 * and "renice" commands.
1089 */
1090
b552171b
MD
1091int
1092proc_owner(int pid)
984263bc 1093{
961f1f09
JL
1094 int xcnt;
1095 struct kinfo_proc **prefp;
1096 struct kinfo_proc *pp;
1097
1098 prefp = pref;
1099 xcnt = pref_len;
1100 while (--xcnt >= 0) {
1101 pp = *prefp++;
1102 if (PP(pp, pid) == (pid_t) pid) {
1103 return ((int)PP(pp, ruid));
1104 }
984263bc 1105 }
961f1f09 1106 return (-1);
984263bc
MD
1107}
1108
1109
1110/*
1111 * swapmode is based on a program called swapinfo written
1112 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
1113 */
984263bc 1114int
1d1731fa 1115swapmode(int *retavail, int *retfree)
984263bc
MD
1116{
1117 int n;
1118 int pagesize = getpagesize();
1119 struct kvm_swap swapary[1];
1120
1121 *retavail = 0;
1122 *retfree = 0;
1123
1124#define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1125
1126 n = kvm_getswapinfo(kd, swapary, 1, 0);
1127 if (n < 0 || swapary[0].ksw_total == 0)
961f1f09 1128 return (0);
984263bc
MD
1129
1130 *retavail = CONVERT(swapary[0].ksw_total);
1131 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1132
1133 n = (int)((double)swapary[0].ksw_used * 100.0 /
1134 (double)swapary[0].ksw_total);
961f1f09 1135 return (n);
984263bc 1136}