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