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