]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/top/machine.c
Compensate for header dethreading.
[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
27 #include <sys/time.h>
28 #include <sys/types.h>
29 #include <sys/signal.h>
30 #include <sys/param.h>
31 #include <sys/lock.h>
32
33 #include "os.h"
34 #include <stdio.h>
35 #include <nlist.h>
36 #include <math.h>
37 #include <kvm.h>
38 #include <pwd.h>
39 #include <sys/errno.h>
40 #include <sys/sysctl.h>
41 #include <sys/dkstat.h>
42 #include <sys/file.h>
43 #include <sys/time.h>
44 #include <sys/proc.h>
45 #include <sys/user.h>
46 #include <sys/vmmeter.h>
47 #include <sys/resource.h>
48 #include <sys/rtprio.h>
49
50 /* Swap */
51 #include <stdlib.h>
52 #include <sys/conf.h>
53
54 #include <unistd.h>
55 #include <osreldate.h> /* for changes in kernel structures */
56
57 #include "top.h"
58 #include "machine.h"
59 #include "screen.h"
60 #include "utils.h"
61
62 static void getsysctl __P((char *, void *, size_t));
63
64 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
65
66 extern char* printable __P((char *));
67 int swapmode __P((int *retavail, int *retfree));
68 static int smpmode;
69 static int namelength;
70 static int cmdlengthdelta;
71
72 /* Prototypes for top internals */
73 void quit __P((int));
74
75 /* get_process_info passes back a handle.  This is what it looks like: */
76
77 struct handle
78 {
79     struct kinfo_proc **next_proc;      /* points to next valid proc pointer */
80     int remaining;              /* number of pointers remaining */
81 };
82
83 /* declarations for load_avg */
84 #include "loadavg.h"
85
86 /* define what weighted cpu is.  */
87 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
88                          ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
89
90 /* what we consider to be process size: */
91 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
92
93 /* definitions for indices in the nlist array */
94
95 /*
96  *  These definitions control the format of the per-process area
97  */
98
99 static char smp_header[] =
100   "  PID %-*.*s PRI NICE   SIZE    RES STATE  C   TIME   WCPU    CPU COMMAND";
101
102 #define smp_Proc_format \
103         "%5d %-*.*s %3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
104
105 static char up_header[] =
106   "  PID %-*.*s PRI NICE   SIZE    RES STATE    TIME   WCPU    CPU COMMAND";
107
108 #define up_Proc_format \
109         "%5d %-*.*s %3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
110
111
112
113 /* process state names for the "STATE" column of the display */
114 /* the extra nulls in the string "run" are for adding a slash and
115    the processor number when needed */
116
117 char *state_abbrev[] =
118 {
119     "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "MUTEX"
120 };
121
122
123 static kvm_t *kd;
124
125 /* values that we stash away in _init and use in later routines */
126
127 static double logcpu;
128
129 /* these are retrieved from the kernel in _init */
130
131 static load_avg  ccpu;
132
133 /* these are used in the get_ functions */
134
135 static int lastpid;
136
137 /* these are for calculating cpu state percentages */
138
139 static long cp_time[CPUSTATES];
140 static long cp_old[CPUSTATES];
141 static long cp_diff[CPUSTATES];
142
143 /* these are for detailing the process states */
144
145 int process_states[8];
146 char *procstatenames[] = {
147     "", " starting, ", " running, ", " sleeping, ", " stopped, ",
148     " zombie, ", " waiting, ", " mutex, ",
149     NULL
150 };
151
152 /* these are for detailing the cpu states */
153
154 int cpu_states[CPUSTATES];
155 char *cpustatenames[] = {
156     "user", "nice", "system", "interrupt", "idle", NULL
157 };
158
159 /* these are for detailing the memory statistics */
160
161 int memory_stats[7];
162 char *memorynames[] = {
163     "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
164     NULL
165 };
166
167 int swap_stats[7];
168 char *swapnames[] = {
169 /*   0           1            2           3            4       5 */
170     "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
171     NULL
172 };
173
174
175 /* these are for keeping track of the proc array */
176
177 static int nproc;
178 static int onproc = -1;
179 static int pref_len;
180 static struct kinfo_proc *pbase;
181 static struct kinfo_proc **pref;
182
183 /* these are for getting the memory statistics */
184
185 static int pageshift;           /* log base 2 of the pagesize */
186
187 /* define pagetok in terms of pageshift */
188
189 #define pagetok(size) ((size) << pageshift)
190
191 /* useful externals */
192 long percentages();
193
194 #ifdef ORDER
195 /* sorting orders. first is default */
196 char *ordernames[] = {
197     "cpu", "size", "res", "time", "pri", NULL
198 };
199 #endif
200
201 int
202 machine_init(statics)
203
204 struct statics *statics;
205
206 {
207     register int pagesize;
208     size_t modelen;
209     struct passwd *pw;
210
211     modelen = sizeof(smpmode);
212     if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
213          sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
214         modelen != sizeof(smpmode))
215             smpmode = 0;
216
217     while ((pw = getpwent()) != NULL) {
218         if (strlen(pw->pw_name) > namelength)
219             namelength = strlen(pw->pw_name);
220     }
221     if (namelength < 8)
222         namelength = 8;
223     if (smpmode && namelength > 13)
224         namelength = 13;
225     else if (namelength > 15)
226         namelength = 15;
227
228     if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY, "kvm_open")) == NULL)
229         return -1;
230
231     GETSYSCTL("kern.ccpu", ccpu);
232
233     /* this is used in calculating WCPU -- calculate it ahead of time */
234     logcpu = log(loaddouble(ccpu));
235
236     pbase = NULL;
237     pref = NULL;
238     nproc = 0;
239     onproc = -1;
240     /* get the page size with "getpagesize" and calculate pageshift from it */
241     pagesize = getpagesize();
242     pageshift = 0;
243     while (pagesize > 1)
244     {
245         pageshift++;
246         pagesize >>= 1;
247     }
248
249     /* we only need the amount of log(2)1024 for our conversion */
250     pageshift -= LOG1024;
251
252     /* fill in the statics information */
253     statics->procstate_names = procstatenames;
254     statics->cpustate_names = cpustatenames;
255     statics->memory_names = memorynames;
256     statics->swap_names = swapnames;
257 #ifdef ORDER
258     statics->order_names = ordernames;
259 #endif
260
261     /* all done! */
262     return(0);
263 }
264
265 char *format_header(uname_field)
266
267 register char *uname_field;
268
269 {
270     static char Header[128];
271
272     snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
273              namelength, namelength, uname_field);
274
275     cmdlengthdelta = strlen(Header) - 7;
276
277     return Header;
278 }
279
280 static int swappgsin = -1;
281 static int swappgsout = -1;
282 extern struct timeval timeout;
283
284 void
285 get_system_info(si)
286
287 struct system_info *si;
288
289 {
290     long total;
291     struct loadavg sysload;
292     int mib[2];
293     struct timeval boottime;
294     size_t bt_size;
295
296     /* get the cp_time array */
297     GETSYSCTL("kern.cp_time", cp_time);
298     GETSYSCTL("vm.loadavg", sysload);
299     GETSYSCTL("kern.lastpid", lastpid);
300
301     /* convert load averages to doubles */
302     {
303         register int i;
304         register double *infoloadp;
305
306         infoloadp = si->load_avg;
307         for (i = 0; i < 3; i++)
308         {
309 #ifdef notyet
310             *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
311 #endif
312             *infoloadp++ = loaddouble(sysload.ldavg[i]);
313         }
314     }
315
316     /* convert cp_time counts to percentages */
317     total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
318
319     /* sum memory & swap statistics */
320     {
321         static unsigned int swap_delay = 0;
322         static int swapavail = 0;
323         static int swapfree = 0;
324         static int bufspace = 0;
325         static int nspgsin, nspgsout;
326
327         GETSYSCTL("vfs.bufspace", bufspace);
328         GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
329         GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
330         GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
331         GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
332         GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
333         GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
334         GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
335         /* convert memory stats to Kbytes */
336         memory_stats[0] = pagetok(memory_stats[0]);
337         memory_stats[1] = pagetok(memory_stats[1]);
338         memory_stats[2] = pagetok(memory_stats[2]);
339         memory_stats[3] = pagetok(memory_stats[3]);
340         memory_stats[4] = bufspace / 1024;
341         memory_stats[5] = pagetok(memory_stats[5]);
342         memory_stats[6] = -1;
343
344         /* first interval */
345         if (swappgsin < 0) {
346             swap_stats[4] = 0;
347             swap_stats[5] = 0;
348         } 
349
350         /* compute differences between old and new swap statistic */
351         else {
352             swap_stats[4] = pagetok(((nspgsin - swappgsin)));
353             swap_stats[5] = pagetok(((nspgsout - swappgsout)));
354         }
355
356         swappgsin = nspgsin;
357         swappgsout = nspgsout;
358
359         /* call CPU heavy swapmode() only for changes */
360         if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
361             swap_stats[3] = swapmode(&swapavail, &swapfree);
362             swap_stats[0] = swapavail;
363             swap_stats[1] = swapavail - swapfree;
364             swap_stats[2] = swapfree;
365         }
366         swap_delay = 1;
367         swap_stats[6] = -1;
368     }
369
370     /* set arrays and strings */
371     si->cpustates = cpu_states;
372     si->memory = memory_stats;
373     si->swap = swap_stats;
374
375
376     if(lastpid > 0) {
377         si->last_pid = lastpid;
378     } else {
379         si->last_pid = -1;
380     }
381
382     /*
383      * Print how long system has been up.
384      * (Found by looking getting "boottime" from the kernel)
385      */
386     mib[0] = CTL_KERN;
387     mib[1] = KERN_BOOTTIME;
388     bt_size = sizeof(boottime);
389     if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
390         boottime.tv_sec != 0) {
391         si->boottime = boottime;
392     } else {
393         si->boottime.tv_sec = -1;
394     }
395 }
396
397 static struct handle handle;
398
399 caddr_t get_process_info(si, sel, compare)
400
401 struct system_info *si;
402 struct process_select *sel;
403 int (*compare)();
404
405 {
406     register int i;
407     register int total_procs;
408     register int active_procs;
409     register struct kinfo_proc **prefp;
410     register struct kinfo_proc *pp;
411
412     /* these are copied out of sel for speed */
413     int show_idle;
414     int show_self;
415     int show_system;
416     int show_uid;
417     int show_command;
418
419     
420     pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
421     if (nproc > onproc)
422         pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
423                 * (onproc = nproc));
424     if (pref == NULL || pbase == NULL) {
425         (void) fprintf(stderr, "top: Out of memory.\n");
426         quit(23);
427     }
428     /* get a pointer to the states summary array */
429     si->procstates = process_states;
430
431     /* set up flags which define what we are going to select */
432     show_idle = sel->idle;
433     show_self = sel->self;
434     show_system = sel->system;
435     show_uid = sel->uid != -1;
436     show_command = sel->command != NULL;
437
438     /* count up process states and get pointers to interesting procs */
439     total_procs = 0;
440     active_procs = 0;
441     memset((char *)process_states, 0, sizeof(process_states));
442     prefp = pref;
443     for (pp = pbase, i = 0; i < nproc; pp++, i++)
444     {
445         /*
446          *  Place pointers to each valid proc structure in pref[].
447          *  Process slots that are actually in use have a non-zero
448          *  status field.  Processes with P_SYSTEM set are system
449          *  processes---these get ignored unless show_sysprocs is set.
450          */
451         if (pp->ki_stat != 0 &&
452             (show_self != pp->ki_pid) &&
453             (show_system || ((pp->ki_flag & P_SYSTEM) == 0)))
454         {
455             total_procs++;
456             process_states[(unsigned char) pp->ki_stat]++;
457             if ((pp->ki_stat != SZOMB) &&
458                 (show_idle || (pp->ki_pctcpu != 0) || 
459                  (pp->ki_stat == SRUN)) &&
460                 (!show_uid || pp->ki_ruid == (uid_t)sel->uid))
461             {
462                 *prefp++ = pp;
463                 active_procs++;
464             }
465         }
466     }
467
468     /* if requested, sort the "interesting" processes */
469     if (compare != NULL)
470     {
471         qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
472     }
473
474     /* remember active and total counts */
475     si->p_total = total_procs;
476     si->p_active = pref_len = active_procs;
477
478     /* pass back a handle */
479     handle.next_proc = pref;
480     handle.remaining = active_procs;
481     return((caddr_t)&handle);
482 }
483
484 char fmt[128];          /* static area where result is built */
485
486 char *format_next_process(handle, get_userid)
487
488 caddr_t handle;
489 char *(*get_userid)();
490
491 {
492     register struct kinfo_proc *pp;
493     register long cputime;
494     register double pct;
495     struct handle *hp;
496     char status[16];
497     int state;
498
499     /* find and remember the next proc structure */
500     hp = (struct handle *)handle;
501     pp = *(hp->next_proc++);
502     hp->remaining--;
503     
504     /* get the process's command name */
505     if ((pp->ki_sflag & PS_INMEM) == 0) {
506         /*
507          * Print swapped processes as <pname>
508          */
509         char *comm = pp->ki_comm;
510 #define COMSIZ sizeof(pp->ki_comm)
511         char buf[COMSIZ];
512         (void) strncpy(buf, comm, COMSIZ);
513         comm[0] = '<';
514         (void) strncpy(&comm[1], buf, COMSIZ - 2);
515         comm[COMSIZ - 2] = '\0';
516         (void) strncat(comm, ">", COMSIZ - 1);
517         comm[COMSIZ - 1] = '\0';
518     }
519
520     /*
521      * Convert the process's runtime from microseconds to seconds.  This
522      * time includes the interrupt time although that is not wanted here.
523      * ps(1) is similarly sloppy.
524      */
525     cputime = (pp->ki_runtime + 500000) / 1000000;
526
527     /* calculate the base for cpu percentages */
528     pct = pctdouble(pp->ki_pctcpu);
529
530     /* generate "STATE" field */
531     switch (state = pp->ki_stat) {
532         case SRUN:
533             if (smpmode && pp->ki_oncpu != 0xff)
534                 sprintf(status, "CPU%d", pp->ki_oncpu);
535             else
536                 strcpy(status, "RUN");
537             break;
538         case SMTX:
539             if (pp->ki_kiflag & KI_MTXBLOCK) {
540                 sprintf(status, "*%.6s", pp->ki_mtxname);
541                 break;
542             }
543             /* fall through */
544         case SSLEEP:
545             if (pp->ki_wmesg != NULL) {
546                 sprintf(status, "%.6s", pp->ki_wmesg);
547                 break;
548             }
549             /* fall through */
550         default:
551
552             if (state >= 0 &&
553                 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
554                     sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
555             else
556                     sprintf(status, "?%5d", state);
557             break;
558     }
559
560     /* format this entry */
561     sprintf(fmt,
562             smpmode ? smp_Proc_format : up_Proc_format,
563             pp->ki_pid,
564             namelength, namelength,
565             (*get_userid)(pp->ki_ruid),
566             pp->ki_pri.pri_level - PZERO,
567
568             /*
569              * normal time      -> nice value -20 - +20 
570              * real time 0 - 31 -> nice value -52 - -21
571              * idle time 0 - 31 -> nice value +21 - +52
572              */
573             (pp->ki_pri.pri_class ==  PRI_TIMESHARE ? 
574                 pp->ki_nice - NZERO : 
575                 (PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
576                     (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
577                     (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))), 
578             format_k2(PROCSIZE(pp)),
579             format_k2(pagetok(pp->ki_rssize)),
580             status,
581             smpmode ? pp->ki_lastcpu : 0,
582             format_time(cputime),
583             100.0 * weighted_cpu(pct, pp),
584             100.0 * pct,
585             screen_width > cmdlengthdelta ?
586                 screen_width - cmdlengthdelta :
587                 0,
588             printable(pp->ki_comm));
589
590     /* return the result */
591     return(fmt);
592 }
593
594 static void getsysctl (name, ptr, len)
595
596 char *name;
597 void *ptr;
598 size_t len;
599
600 {
601     size_t nlen = len;
602     if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
603             fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
604                 strerror(errno));
605             quit(23);
606     }
607     if (nlen != len) {
608             fprintf(stderr, "top: sysctl(%s...) expected %d, got %d\n", name, 
609                 len, nlen);
610             quit(23);
611     }
612 }
613
614 /* comparison routines for qsort */
615
616 /*
617  *  proc_compare - comparison function for "qsort"
618  *      Compares the resource consumption of two processes using five
619  *      distinct keys.  The keys (in descending order of importance) are:
620  *      percent cpu, cpu ticks, state, resident set size, total virtual
621  *      memory usage.  The process states are ordered as follows (from least
622  *      to most important):  WAIT, zombie, sleep, stop, start, run.  The
623  *      array declaration below maps a process state index into a number
624  *      that reflects this ordering.
625  */
626
627 static unsigned char sorted_state[] =
628 {
629     0,  /* not used             */
630     3,  /* sleep                */
631     1,  /* ABANDONED (WAIT)     */
632     6,  /* run                  */
633     5,  /* start                */
634     2,  /* zombie               */
635     4   /* stop                 */
636 };
637  
638
639 #define ORDERKEY_PCTCPU \
640   if (lresult = (long) p2->ki_pctcpu - (long) p1->ki_pctcpu, \
641      (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
642
643 #define ORDERKEY_CPTICKS \
644   if ((result = p2->ki_runtime > p1->ki_runtime ? 1 : \
645                 p2->ki_runtime < p1->ki_runtime ? -1 : 0) == 0)
646
647 #define ORDERKEY_STATE \
648   if ((result = sorted_state[(unsigned char) p2->ki_stat] - \
649                 sorted_state[(unsigned char) p1->ki_stat]) == 0)
650
651 #define ORDERKEY_PRIO \
652   if ((result = p2->ki_pri.pri_level - p1->ki_pri.pri_level) == 0)
653
654 #define ORDERKEY_RSSIZE \
655   if ((result = p2->ki_rssize - p1->ki_rssize) == 0) 
656
657 #define ORDERKEY_MEM \
658   if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
659
660 /* compare_cpu - the comparison function for sorting by cpu percentage */
661
662 int
663 #ifdef ORDER
664 compare_cpu(pp1, pp2)
665 #else
666 proc_compare(pp1, pp2)
667 #endif
668
669 struct proc **pp1;
670 struct proc **pp2;
671
672 {
673     register struct kinfo_proc *p1;
674     register struct kinfo_proc *p2;
675     register int result;
676     register pctcpu lresult;
677
678     /* remove one level of indirection */
679     p1 = *(struct kinfo_proc **) pp1;
680     p2 = *(struct kinfo_proc **) pp2;
681
682     ORDERKEY_PCTCPU
683     ORDERKEY_CPTICKS
684     ORDERKEY_STATE
685     ORDERKEY_PRIO
686     ORDERKEY_RSSIZE
687     ORDERKEY_MEM
688     ;
689
690     return(result);
691 }
692
693 #ifdef ORDER
694 /* compare routines */
695 int compare_size(), compare_res(), compare_time(), compare_prio();
696
697 int (*proc_compares[])() = {
698     compare_cpu,
699     compare_size,
700     compare_res,
701     compare_time,
702     compare_prio,
703     NULL
704 };
705
706 /* compare_size - the comparison function for sorting by total memory usage */
707
708 int
709 compare_size(pp1, pp2)
710
711 struct proc **pp1;
712 struct proc **pp2;
713
714 {
715     register struct kinfo_proc *p1;
716     register struct kinfo_proc *p2;
717     register int result;
718     register pctcpu lresult;
719
720     /* remove one level of indirection */
721     p1 = *(struct kinfo_proc **) pp1;
722     p2 = *(struct kinfo_proc **) pp2;
723
724     ORDERKEY_MEM
725     ORDERKEY_RSSIZE
726     ORDERKEY_PCTCPU
727     ORDERKEY_CPTICKS
728     ORDERKEY_STATE
729     ORDERKEY_PRIO
730     ;
731
732     return(result);
733 }
734
735 /* compare_res - the comparison function for sorting by resident set size */
736
737 int
738 compare_res(pp1, pp2)
739
740 struct proc **pp1;
741 struct proc **pp2;
742
743 {
744     register struct kinfo_proc *p1;
745     register struct kinfo_proc *p2;
746     register int result;
747     register pctcpu lresult;
748
749     /* remove one level of indirection */
750     p1 = *(struct kinfo_proc **) pp1;
751     p2 = *(struct kinfo_proc **) pp2;
752
753     ORDERKEY_RSSIZE
754     ORDERKEY_MEM
755     ORDERKEY_PCTCPU
756     ORDERKEY_CPTICKS
757     ORDERKEY_STATE
758     ORDERKEY_PRIO
759     ;
760
761     return(result);
762 }
763
764 /* compare_time - the comparison function for sorting by total cpu time */
765
766 int
767 compare_time(pp1, pp2)
768
769 struct proc **pp1;
770 struct proc **pp2;
771
772 {
773     register struct kinfo_proc *p1;
774     register struct kinfo_proc *p2;
775     register int result;
776     register pctcpu lresult;
777   
778     /* remove one level of indirection */
779     p1 = *(struct kinfo_proc **) pp1;
780     p2 = *(struct kinfo_proc **) pp2;
781
782     ORDERKEY_CPTICKS
783     ORDERKEY_PCTCPU
784     ORDERKEY_STATE
785     ORDERKEY_PRIO
786     ORDERKEY_RSSIZE
787     ORDERKEY_MEM
788     ;
789
790       return(result);
791   }
792   
793 /* compare_prio - the comparison function for sorting by cpu percentage */
794
795 int
796 compare_prio(pp1, pp2)
797
798 struct proc **pp1;
799 struct proc **pp2;
800
801 {
802     register struct kinfo_proc *p1;
803     register struct kinfo_proc *p2;
804     register int result;
805     register pctcpu lresult;
806
807     /* remove one level of indirection */
808     p1 = *(struct kinfo_proc **) pp1;
809     p2 = *(struct kinfo_proc **) pp2;
810
811     ORDERKEY_PRIO
812     ORDERKEY_CPTICKS
813     ORDERKEY_PCTCPU
814     ORDERKEY_STATE
815     ORDERKEY_RSSIZE
816     ORDERKEY_MEM
817     ;
818
819     return(result);
820 }
821 #endif
822
823 /*
824  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
825  *              the process does not exist.
826  *              It is EXTREMLY IMPORTANT that this function work correctly.
827  *              If top runs setuid root (as in SVR4), then this function
828  *              is the only thing that stands in the way of a serious
829  *              security problem.  It validates requests for the "kill"
830  *              and "renice" commands.
831  */
832
833 int proc_owner(pid)
834
835 int pid;
836
837 {
838     register int cnt;
839     register struct kinfo_proc **prefp;
840     register struct kinfo_proc *pp;
841
842     prefp = pref;
843     cnt = pref_len;
844     while (--cnt >= 0)
845     {
846         pp = *prefp++;  
847         if (pp->ki_pid == (pid_t)pid)
848         {
849             return((int)pp->ki_ruid);
850         }
851     }
852     return(-1);
853 }
854
855 int
856 swapmode(retavail, retfree)
857         int *retavail;
858         int *retfree;
859 {
860         int n;
861         int pagesize = getpagesize();
862         struct kvm_swap swapary[1];
863
864         *retavail = 0;
865         *retfree = 0;
866
867 #define CONVERT(v)      ((quad_t)(v) * pagesize / 1024)
868
869         n = kvm_getswapinfo(kd, swapary, 1, 0);
870         if (n < 0 || swapary[0].ksw_total == 0)
871                 return(0);
872
873         *retavail = CONVERT(swapary[0].ksw_total);
874         *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
875
876         n = (int)((double)swapary[0].ksw_used * 100.0 /
877             (double)swapary[0].ksw_total);
878         return(n);
879 }
880