]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/top/machine.c
This commit was generated by cvs2svn to compensate for changes in r174294,
[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_flag & P_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                 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
741                     pp->ki_ocomm[0]) {
742                         snprintf(cmdbuf, cmdlengthdelta, "{%s}", pp->ki_ocomm);
743                 } else {
744                         snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
745                 }
746         } else {
747                 if (pp->ki_flag & P_SYSTEM ||
748                     pp->ki_args == NULL ||
749                     (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL ||
750                     !(*args)) {
751                         if (ps.thread && pp->ki_flag & P_HADTHREADS &&
752                         pp->ki_ocomm[0]) {
753                                 snprintf(cmdbuf, cmdlengthdelta,
754                                     "{%s}", pp->ki_ocomm);
755                         } else {
756                                 snprintf(cmdbuf, cmdlengthdelta,
757                                     "[%s]", pp->ki_comm);
758                         }
759                 } else {
760                         char *src, *dst, *argbuf;
761                         char *cmd;
762                         size_t argbuflen;
763                         size_t len;
764
765                         argbuflen = cmdlengthdelta * 4;
766                         argbuf = (char *)malloc(argbuflen + 1);
767                         if (argbuf == NULL) {
768                                 warn("malloc(%d)", argbuflen + 1);
769                                 free(cmdbuf);
770                                 return NULL;
771                         }
772
773                         dst = argbuf;
774
775                         /* Extract cmd name from argv */
776                         cmd = strrchr(*args, '/');
777                         if (cmd == NULL)
778                                 cmd = *args;
779                         else
780                                 cmd++;
781
782                         for (; (src = *args++) != NULL; ) {
783                                 if (*src == '\0')
784                                         continue;
785                                 len = (argbuflen - (dst - argbuf) - 1) / 4;
786                                 strvisx(dst, src,
787                                     strlen(src) < len ? strlen(src) : len,
788                                     VIS_NL | VIS_CSTYLE);
789                                 while (*dst != '\0')
790                                         dst++;
791                                 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
792                                         *dst++ = ' '; /* add delimiting space */
793                         }
794                         if (dst != argbuf && dst[-1] == ' ')
795                                 dst--;
796                         *dst = '\0';
797
798                         if (strcmp(cmd, pp->ki_comm) != 0 )
799                                 snprintf(cmdbuf, cmdlengthdelta,
800                                     "%s (%s)",argbuf,  pp->ki_comm);
801                         else
802                                 strlcpy(cmdbuf, argbuf, cmdlengthdelta);
803
804                         free(argbuf);
805                 }
806         }
807
808         if (ps.jail == 0) 
809                 jid_buf[0] = '\0';
810         else
811                 snprintf(jid_buf, sizeof(jid_buf), " %*d",
812                     sizeof(jid_buf) - 3, pp->ki_jid);
813
814         if (displaymode == DISP_IO) {
815                 oldp = get_old_proc(pp);
816                 if (oldp != NULL) {
817                         ru.ru_inblock = RU(pp)->ru_inblock -
818                             RU(oldp)->ru_inblock;
819                         ru.ru_oublock = RU(pp)->ru_oublock -
820                             RU(oldp)->ru_oublock;
821                         ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
822                         ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
823                         ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
824                         rup = &ru;
825                 } else {
826                         rup = RU(pp);
827                 }
828                 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
829                 s_tot = total_inblock + total_oublock + total_majflt;
830
831                 sprintf(fmt, io_Proc_format,
832                     pp->ki_pid,
833                     jid_buf,
834                     namelength, namelength, (*get_userid)(pp->ki_ruid),
835                     rup->ru_nvcsw,
836                     rup->ru_nivcsw,
837                     rup->ru_inblock,
838                     rup->ru_oublock,
839                     rup->ru_majflt,
840                     p_tot,
841                     s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
842                     screen_width > cmdlengthdelta ?
843                     screen_width - cmdlengthdelta : 0,
844                     printable(cmdbuf));
845
846                 free(cmdbuf);
847
848                 return (fmt);
849         }
850
851         /* format this entry */
852         proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
853         if (ps.thread != 0)
854                 thr_buf[0] = '\0';
855         else
856                 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
857                     sizeof(thr_buf) - 2, pp->ki_numthreads);
858
859         sprintf(fmt, proc_fmt,
860             pp->ki_pid,
861             jid_buf,
862             namelength, namelength, (*get_userid)(pp->ki_ruid),
863             thr_buf,
864             pp->ki_pri.pri_level - PZERO,
865             format_nice(pp),
866             format_k2(PROCSIZE(pp)),
867             format_k2(pagetok(pp->ki_rssize)),
868             status,
869             smpmode ? pp->ki_lastcpu : 0,
870             format_time(cputime),
871             ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
872             screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
873             printable(cmdbuf));
874
875         free(cmdbuf);
876
877         /* return the result */
878         return (fmt);
879 }
880
881 static void
882 getsysctl(const char *name, void *ptr, size_t len)
883 {
884         size_t nlen = len;
885
886         if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
887                 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
888                     strerror(errno));
889                 quit(23);
890         }
891         if (nlen != len) {
892                 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
893                     name, (unsigned long)len, (unsigned long)nlen);
894                 quit(23);
895         }
896 }
897
898 static const char *
899 format_nice(const struct kinfo_proc *pp)
900 {
901         const char *fifo, *kthread;
902         int rtpri;
903         static char nicebuf[4 + 1];
904
905         fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
906         kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
907         switch (PRI_BASE(pp->ki_pri.pri_class)) {
908         case PRI_ITHD:
909                 return ("-");
910         case PRI_REALTIME:
911                 /*
912                  * XXX: the kernel doesn't tell us the original rtprio and
913                  * doesn't really know what it was, so to recover it we
914                  * must be more chummy with the implementation than the
915                  * implementation is with itself.  pri_user gives a
916                  * constant "base" priority, but is only initialized
917                  * properly for user threads.  pri_native gives what the
918                  * kernel calls the "base" priority, but it isn't constant
919                  * since it is changed by priority propagation.  pri_native
920                  * also isn't properly initialized for all threads, but it
921                  * is properly initialized for kernel realtime and idletime
922                  * threads.  Thus we use pri_user for the base priority of
923                  * user threads (it is always correct) and pri_native for
924                  * the base priority of kernel realtime and idletime threads
925                  * (there is nothing better, and it is usually correct).
926                  *
927                  * The field width and thus the buffer are too small for
928                  * values like "kr31F", but such values shouldn't occur,
929                  * and if they do then the tailing "F" is not displayed.
930                  */
931                 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
932                     pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
933                 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
934                     kthread, rtpri, fifo);
935                 break;
936         case PRI_TIMESHARE:
937                 if (pp->ki_flag & P_KTHREAD)
938                         return ("-");
939                 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
940                 break;
941         case PRI_IDLE:
942                 /* XXX: as above. */
943                 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
944                     pp->ki_pri.pri_user) - PRI_MIN_IDLE;
945                 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
946                     kthread, rtpri, fifo);
947                 break;
948         default:
949                 return ("?");
950         }
951         return (nicebuf);
952 }
953
954 /* comparison routines for qsort */
955
956 static int
957 compare_pid(const void *p1, const void *p2)
958 {
959         const struct kinfo_proc * const *pp1 = p1;
960         const struct kinfo_proc * const *pp2 = p2;
961
962         if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
963                 abort();
964
965         return ((*pp1)->ki_pid - (*pp2)->ki_pid);
966 }
967
968 /*
969  *  proc_compare - comparison function for "qsort"
970  *      Compares the resource consumption of two processes using five
971  *      distinct keys.  The keys (in descending order of importance) are:
972  *      percent cpu, cpu ticks, state, resident set size, total virtual
973  *      memory usage.  The process states are ordered as follows (from least
974  *      to most important):  WAIT, zombie, sleep, stop, start, run.  The
975  *      array declaration below maps a process state index into a number
976  *      that reflects this ordering.
977  */
978
979 static int sorted_state[] = {
980         0,      /* not used             */
981         3,      /* sleep                */
982         1,      /* ABANDONED (WAIT)     */
983         6,      /* run                  */
984         5,      /* start                */
985         2,      /* zombie               */
986         4       /* stop                 */
987 };
988
989
990 #define ORDERKEY_PCTCPU(a, b) do { \
991         long diff; \
992         if (ps.wcpu) \
993                 diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
994                     (b))) - \
995                     floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
996                     (a))); \
997         else \
998                 diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
999         if (diff != 0) \
1000                 return (diff > 0 ? 1 : -1); \
1001 } while (0)
1002
1003 #define ORDERKEY_CPTICKS(a, b) do { \
1004         int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1005         if (diff != 0) \
1006                 return (diff > 0 ? 1 : -1); \
1007 } while (0)
1008
1009 #define ORDERKEY_STATE(a, b) do { \
1010         int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1011         if (diff != 0) \
1012                 return (diff > 0 ? 1 : -1); \
1013 } while (0)
1014
1015 #define ORDERKEY_PRIO(a, b) do { \
1016         int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1017         if (diff != 0) \
1018                 return (diff > 0 ? 1 : -1); \
1019 } while (0)
1020
1021 #define ORDERKEY_THREADS(a, b) do { \
1022         int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1023         if (diff != 0) \
1024                 return (diff > 0 ? 1 : -1); \
1025 } while (0)
1026
1027 #define ORDERKEY_RSSIZE(a, b) do { \
1028         long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1029         if (diff != 0) \
1030                 return (diff > 0 ? 1 : -1); \
1031 } while (0)
1032
1033 #define ORDERKEY_MEM(a, b) do { \
1034         long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1035         if (diff != 0) \
1036                 return (diff > 0 ? 1 : -1); \
1037 } while (0)
1038
1039 #define ORDERKEY_JID(a, b) do { \
1040         int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1041         if (diff != 0) \
1042                 return (diff > 0 ? 1 : -1); \
1043 } while (0)
1044
1045 /* compare_cpu - the comparison function for sorting by cpu percentage */
1046
1047 int
1048 #ifdef ORDER
1049 compare_cpu(void *arg1, void *arg2)
1050 #else
1051 proc_compare(void *arg1, void *arg2)
1052 #endif
1053 {
1054         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1055         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1056
1057         ORDERKEY_PCTCPU(p1, p2);
1058         ORDERKEY_CPTICKS(p1, p2);
1059         ORDERKEY_STATE(p1, p2);
1060         ORDERKEY_PRIO(p1, p2);
1061         ORDERKEY_RSSIZE(p1, p2);
1062         ORDERKEY_MEM(p1, p2);
1063
1064         return (0);
1065 }
1066
1067 #ifdef ORDER
1068 /* "cpu" compare routines */
1069 int compare_size(), compare_res(), compare_time(), compare_prio(),
1070     compare_threads();
1071
1072 /*
1073  * "io" compare routines.  Context switches aren't i/o, but are displayed
1074  * on the "io" display.
1075  */
1076 int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1077     compare_vcsw(), compare_ivcsw();
1078
1079 int (*compares[])() = {
1080         compare_cpu,
1081         compare_size,
1082         compare_res,
1083         compare_time,
1084         compare_prio,
1085         compare_threads,
1086         compare_iototal,
1087         compare_ioread,
1088         compare_iowrite,
1089         compare_iofault,
1090         compare_vcsw,
1091         compare_ivcsw,
1092         compare_jid,
1093         NULL
1094 };
1095
1096 /* compare_size - the comparison function for sorting by total memory usage */
1097
1098 int
1099 compare_size(void *arg1, void *arg2)
1100 {
1101         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1102         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1103
1104         ORDERKEY_MEM(p1, p2);
1105         ORDERKEY_RSSIZE(p1, p2);
1106         ORDERKEY_PCTCPU(p1, p2);
1107         ORDERKEY_CPTICKS(p1, p2);
1108         ORDERKEY_STATE(p1, p2);
1109         ORDERKEY_PRIO(p1, p2);
1110
1111         return (0);
1112 }
1113
1114 /* compare_res - the comparison function for sorting by resident set size */
1115
1116 int
1117 compare_res(void *arg1, void *arg2)
1118 {
1119         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1120         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1121
1122         ORDERKEY_RSSIZE(p1, p2);
1123         ORDERKEY_MEM(p1, p2);
1124         ORDERKEY_PCTCPU(p1, p2);
1125         ORDERKEY_CPTICKS(p1, p2);
1126         ORDERKEY_STATE(p1, p2);
1127         ORDERKEY_PRIO(p1, p2);
1128
1129         return (0);
1130 }
1131
1132 /* compare_time - the comparison function for sorting by total cpu time */
1133
1134 int
1135 compare_time(void *arg1, void *arg2)
1136 {
1137         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1138         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1139
1140         ORDERKEY_CPTICKS(p1, p2);
1141         ORDERKEY_PCTCPU(p1, p2);
1142         ORDERKEY_STATE(p1, p2);
1143         ORDERKEY_PRIO(p1, p2);
1144         ORDERKEY_RSSIZE(p1, p2);
1145         ORDERKEY_MEM(p1, p2);
1146
1147         return (0);
1148 }
1149
1150 /* compare_prio - the comparison function for sorting by priority */
1151
1152 int
1153 compare_prio(void *arg1, void *arg2)
1154 {
1155         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1156         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1157
1158         ORDERKEY_PRIO(p1, p2);
1159         ORDERKEY_CPTICKS(p1, p2);
1160         ORDERKEY_PCTCPU(p1, p2);
1161         ORDERKEY_STATE(p1, p2);
1162         ORDERKEY_RSSIZE(p1, p2);
1163         ORDERKEY_MEM(p1, p2);
1164
1165         return (0);
1166 }
1167
1168 /* compare_threads - the comparison function for sorting by threads */
1169 int
1170 compare_threads(void *arg1, void *arg2)
1171 {
1172         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1173         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1174
1175         ORDERKEY_THREADS(p1, p2);
1176         ORDERKEY_PCTCPU(p1, p2);
1177         ORDERKEY_CPTICKS(p1, p2);
1178         ORDERKEY_STATE(p1, p2);
1179         ORDERKEY_PRIO(p1, p2);
1180         ORDERKEY_RSSIZE(p1, p2);
1181         ORDERKEY_MEM(p1, p2);
1182
1183         return (0);
1184 }
1185
1186 /* compare_jid - the comparison function for sorting by jid */
1187 static int
1188 compare_jid(const void *arg1, const void *arg2)
1189 {
1190         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1191         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1192
1193         ORDERKEY_JID(p1, p2);
1194         ORDERKEY_PCTCPU(p1, p2);
1195         ORDERKEY_CPTICKS(p1, p2);
1196         ORDERKEY_STATE(p1, p2);
1197         ORDERKEY_PRIO(p1, p2);
1198         ORDERKEY_RSSIZE(p1, p2);
1199         ORDERKEY_MEM(p1, p2);
1200
1201         return (0);
1202 }
1203 #endif /* ORDER */
1204
1205 /* assorted comparison functions for sorting by i/o */
1206
1207 int
1208 #ifdef ORDER
1209 compare_iototal(void *arg1, void *arg2)
1210 #else
1211 io_compare(void *arg1, void *arg2)
1212 #endif
1213 {
1214         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1215         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1216
1217         return (get_io_total(p2) - get_io_total(p1));
1218 }
1219
1220 #ifdef ORDER
1221 int
1222 compare_ioread(void *arg1, void *arg2)
1223 {
1224         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1225         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1226         long dummy, inp1, inp2;
1227
1228         (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1229         (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1230
1231         return (inp2 - inp1);
1232 }
1233
1234 int
1235 compare_iowrite(void *arg1, void *arg2)
1236 {
1237         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1238         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1239         long dummy, oup1, oup2;
1240
1241         (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1242         (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1243
1244         return (oup2 - oup1);
1245 }
1246
1247 int
1248 compare_iofault(void *arg1, void *arg2)
1249 {
1250         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1251         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1252         long dummy, flp1, flp2;
1253
1254         (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1255         (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1256
1257         return (flp2 - flp1);
1258 }
1259
1260 int
1261 compare_vcsw(void *arg1, void *arg2)
1262 {
1263         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1264         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1265         long dummy, flp1, flp2;
1266
1267         (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1268         (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1269
1270         return (flp2 - flp1);
1271 }
1272
1273 int
1274 compare_ivcsw(void *arg1, void *arg2)
1275 {
1276         struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1277         struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1278         long dummy, flp1, flp2;
1279
1280         (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1281         (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1282
1283         return (flp2 - flp1);
1284 }
1285 #endif /* ORDER */
1286
1287 /*
1288  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1289  *              the process does not exist.
1290  *              It is EXTREMLY IMPORTANT that this function work correctly.
1291  *              If top runs setuid root (as in SVR4), then this function
1292  *              is the only thing that stands in the way of a serious
1293  *              security problem.  It validates requests for the "kill"
1294  *              and "renice" commands.
1295  */
1296
1297 int
1298 proc_owner(int pid)
1299 {
1300         int cnt;
1301         struct kinfo_proc **prefp;
1302         struct kinfo_proc *pp;
1303
1304         prefp = pref;
1305         cnt = pref_len;
1306         while (--cnt >= 0) {
1307                 pp = *prefp++;
1308                 if (pp->ki_pid == (pid_t)pid)
1309                         return ((int)pp->ki_ruid);
1310         }
1311         return (-1);
1312 }
1313
1314 static int
1315 swapmode(int *retavail, int *retfree)
1316 {
1317         int n;
1318         int pagesize = getpagesize();
1319         struct kvm_swap swapary[1];
1320
1321         *retavail = 0;
1322         *retfree = 0;
1323
1324 #define CONVERT(v)      ((quad_t)(v) * pagesize / 1024)
1325
1326         n = kvm_getswapinfo(kd, swapary, 1, 0);
1327         if (n < 0 || swapary[0].ksw_total == 0)
1328                 return (0);
1329
1330         *retavail = CONVERT(swapary[0].ksw_total);
1331         *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1332
1333         n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1334         return (n);
1335 }