[BACK]Return to machine.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / top

Annotation of src/usr.bin/top/machine.c, Revision 1.75

1.75    ! millert     1: /* $OpenBSD: machine.c,v 1.74 2012/07/09 22:41:45 deraadt Exp $         */
1.28      tholo       2:
                      3: /*-
                      4:  * Copyright (c) 1994 Thorsten Lockert <tholo@sigmasoft.com>
                      5:  * All rights reserved.
                      6:  *
                      7:  * Redistribution and use in source and binary forms, with or without
                      8:  * modification, are permitted provided that the following conditions
                      9:  * are met:
                     10:  * 1. Redistributions of source code must retain the above copyright
                     11:  *    notice, this list of conditions and the following disclaimer.
                     12:  * 2. Redistributions in binary form must reproduce the above copyright
                     13:  *    notice, this list of conditions and the following disclaimer in the
                     14:  *    documentation and/or other materials provided with the distribution.
                     15:  * 3. The name of the author may not be used to endorse or promote products
                     16:  *    derived from this software without specific prior written permission.
                     17:  *
                     18:  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
                     19:  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
                     20:  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
                     21:  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
                     22:  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
                     23:  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
                     24:  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
                     25:  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
                     26:  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
                     27:  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.1       downsj     28:  *
                     29:  * AUTHOR:  Thorsten Lockert <tholo@sigmasoft.com>
                     30:  *          Adapted from BSD4.4 by Christos Zoulas <christos@ee.cornell.edu>
                     31:  *          Patch for process wait display by Jarl F. Greipsland <jarle@idt.unit.no>
1.11      kstailey   32:  *         Patch for -DORDER by Kenneth Stailey <kstailey@disclosure.com>
1.15      weingart   33:  *         Patch for new swapctl(2) by Tobias Weingartner <weingart@openbsd.org>
1.1       downsj     34:  */
                     35:
                     36: #include <sys/types.h>
                     37: #include <sys/param.h>
1.75    ! millert    38: #include <sys/dkstat.h>
        !            39: #include <sys/mount.h>
        !            40: #include <sys/proc.h>
        !            41: #include <sys/swap.h>
        !            42: #include <sys/sysctl.h>
        !            43:
1.1       downsj     44: #include <stdio.h>
                     45: #include <stdlib.h>
1.3       downsj     46: #include <string.h>
1.1       downsj     47: #include <unistd.h>
                     48: #include <err.h>
1.51      millert    49: #include <errno.h>
1.1       downsj     50:
                     51: #include "top.h"
1.3       downsj     52: #include "display.h"
1.1       downsj     53: #include "machine.h"
                     54: #include "utils.h"
1.31      deraadt    55: #include "loadavg.h"
                     56:
1.38      deraadt    57: static int     swapmode(int *, int *);
1.68      guenther   58: static char    *state_abbr(struct kinfo_proc *);
                     59: static char    *format_comm(struct kinfo_proc *);
1.1       downsj     60:
                     61: /* get_process_info passes back a handle.  This is what it looks like: */
                     62:
1.20      deraadt    63: struct handle {
1.68      guenther   64:        struct kinfo_proc **next_proc;  /* points to next valid proc pointer */
1.38      deraadt    65:        int             remaining;      /* number of pointers remaining */
1.1       downsj     66: };
                     67:
                     68: /* what we consider to be process size: */
1.37      millert    69: #define PROCSIZE(pp) ((pp)->p_vm_tsize + (pp)->p_vm_dsize + (pp)->p_vm_ssize)
1.1       downsj     70:
                     71: /*
                     72:  *  These definitions control the format of the per-process area
                     73:  */
1.38      deraadt    74: static char header[] =
1.64      deraadt    75:        "  PID X        PRI NICE  SIZE   RES STATE     WAIT      TIME    CPU COMMAND";
1.31      deraadt    76:
1.1       downsj     77: /* 0123456   -- field to fill in starts at header+6 */
                     78: #define UNAME_START 6
                     79:
                     80: #define Proc_format \
1.64      deraadt    81:        "%5d %-8.8s %3d %4d %5s %5s %-9s %-7.7s %6s %5.2f%% %s"
1.1       downsj     82:
                     83: /* process state names for the "STATE" column of the display */
1.30      deraadt    84: /*
                     85:  * the extra nulls in the string "run" are for adding a slash and the
                     86:  * processor number when needed
                     87:  */
1.1       downsj     88:
1.30      deraadt    89: char   *state_abbrev[] = {
1.40      deraadt    90:        "", "start", "run", "sleep", "stop", "zomb", "dead", "onproc"
1.1       downsj     91: };
                     92:
                     93: /* these are for calculating cpu state percentages */
1.48      millert    94: static int64_t     **cp_time;
                     95: static int64_t     **cp_old;
                     96: static int64_t     **cp_diff;
1.1       downsj     97:
                     98: /* these are for detailing the process states */
1.45      markus     99: int process_states[8];
1.30      deraadt   100: char *procstatenames[] = {
                    101:        "", " starting, ", " running, ", " idle, ",
1.47      markus    102:        " stopped, ", " zombie, ", " dead, ", " on processor, ",
1.20      deraadt   103:        NULL
1.1       downsj    104: };
                    105:
                    106: /* these are for detailing the cpu states */
1.48      millert   107: int64_t *cpu_states;
1.30      deraadt   108: char *cpustatenames[] = {
1.20      deraadt   109:        "user", "nice", "system", "interrupt", "idle", NULL
1.1       downsj    110: };
                    111:
                    112: /* these are for detailing the memory statistics */
1.69      tedu      113: int memory_stats[10];
1.30      deraadt   114: char *memorynames[] = {
1.69      tedu      115:        "Real: ", "K/", "K act/tot ", "Free: ", "K ",
                    116:        "Cache: ", "K ",
                    117:        "Swap: ", "K/", "K",
1.20      deraadt   118:        NULL
1.1       downsj    119: };
                    120:
1.11      kstailey  121: /* these are names given to allowed sorting orders -- first is default */
1.31      deraadt   122: char   *ordernames[] = {
1.65      tedu      123:        "cpu", "size", "res", "time", "pri", "pid", "command", NULL
1.31      deraadt   124: };
1.11      kstailey  125:
1.1       downsj    126: /* these are for keeping track of the proc array */
1.30      deraadt   127: static int      nproc;
                    128: static int      onproc = -1;
                    129: static int      pref_len;
1.68      guenther  130: static struct kinfo_proc *pbase;
                    131: static struct kinfo_proc **pref;
1.1       downsj    132:
                    133: /* these are for getting the memory statistics */
1.30      deraadt   134: static int      pageshift;     /* log base 2 of the pagesize */
1.1       downsj    135:
                    136: /* define pagetok in terms of pageshift */
                    137: #define pagetok(size) ((size) << pageshift)
                    138:
1.41      deraadt   139: int            ncpu;
                    140:
1.33      millert   141: unsigned int   maxslp;
1.26      art       142:
1.18      deraadt   143: int
1.29      pvalchev  144: machine_init(struct statics *statics)
1.1       downsj    145: {
1.41      deraadt   146:        size_t size = sizeof(ncpu);
1.48      millert   147:        int mib[2], pagesize, cpu;
1.41      deraadt   148:
                    149:        mib[0] = CTL_HW;
                    150:        mib[1] = HW_NCPU;
                    151:        if (sysctl(mib, 2, &ncpu, &size, NULL, 0) == -1)
                    152:                return (-1);
1.62      deraadt   153:        cpu_states = calloc(ncpu, CPUSTATES * sizeof(int64_t));
1.48      millert   154:        if (cpu_states == NULL)
                    155:                err(1, NULL);
1.62      deraadt   156:        cp_time = calloc(ncpu, sizeof(int64_t *));
                    157:        cp_old  = calloc(ncpu, sizeof(int64_t *));
                    158:        cp_diff = calloc(ncpu, sizeof(int64_t *));
1.48      millert   159:        if (cp_time == NULL || cp_old == NULL || cp_diff == NULL)
                    160:                err(1, NULL);
                    161:        for (cpu = 0; cpu < ncpu; cpu++) {
1.52      otto      162:                cp_time[cpu] = calloc(CPUSTATES, sizeof(int64_t));
                    163:                cp_old[cpu] = calloc(CPUSTATES, sizeof(int64_t));
                    164:                cp_diff[cpu] = calloc(CPUSTATES, sizeof(int64_t));
1.48      millert   165:                if (cp_time[cpu] == NULL || cp_old[cpu] == NULL ||
                    166:                    cp_diff[cpu] == NULL)
                    167:                        err(1, NULL);
                    168:        }
1.20      deraadt   169:
                    170:        pbase = NULL;
                    171:        pref = NULL;
                    172:        onproc = -1;
                    173:        nproc = 0;
                    174:
1.30      deraadt   175:        /*
                    176:         * get the page size with "getpagesize" and calculate pageshift from
                    177:         * it
                    178:         */
1.20      deraadt   179:        pagesize = getpagesize();
                    180:        pageshift = 0;
                    181:        while (pagesize > 1) {
                    182:                pageshift++;
                    183:                pagesize >>= 1;
                    184:        }
                    185:
                    186:        /* we only need the amount of log(2)1024 for our conversion */
                    187:        pageshift -= LOG1024;
                    188:
                    189:        /* fill in the statics information */
                    190:        statics->procstate_names = procstatenames;
                    191:        statics->cpustate_names = cpustatenames;
                    192:        statics->memory_names = memorynames;
                    193:        statics->order_names = ordernames;
                    194:        return (0);
1.1       downsj    195: }
                    196:
1.20      deraadt   197: char *
1.29      pvalchev  198: format_header(char *uname_field)
1.1       downsj    199: {
1.20      deraadt   200:        char *ptr;
1.1       downsj    201:
1.20      deraadt   202:        ptr = header + UNAME_START;
1.30      deraadt   203:        while (*uname_field != '\0')
1.20      deraadt   204:                *ptr++ = *uname_field++;
                    205:        return (header);
1.1       downsj    206: }
                    207:
                    208: void
1.31      deraadt   209: get_system_info(struct system_info *si)
1.1       downsj    210: {
1.20      deraadt   211:        static int sysload_mib[] = {CTL_VM, VM_LOADAVG};
                    212:        static int vmtotal_mib[] = {CTL_VM, VM_METER};
1.69      tedu      213:        static int bcstats_mib[] = {CTL_VFS, VFS_GENERIC, VFS_BCACHESTAT};
1.1       downsj    214:        struct loadavg sysload;
1.20      deraadt   215:        struct vmtotal vmtotal;
1.69      tedu      216:        struct bcachestats bcstats;
1.20      deraadt   217:        double *infoloadp;
1.30      deraadt   218:        size_t size;
1.35      deraadt   219:        int i;
1.48      millert   220:        int64_t *tmpstate;
1.30      deraadt   221:
1.48      millert   222:        if (ncpu > 1) {
1.67      deraadt   223:                int cp_time_mib[] = {CTL_KERN, KERN_CPTIME2, /*fillme*/0};
                    224:
1.48      millert   225:                size = CPUSTATES * sizeof(int64_t);
                    226:                for (i = 0; i < ncpu; i++) {
1.67      deraadt   227:                        cp_time_mib[2] = i;
1.48      millert   228:                        tmpstate = cpu_states + (CPUSTATES * i);
                    229:                        if (sysctl(cp_time_mib, 3, cp_time[i], &size, NULL, 0) < 0)
                    230:                                warn("sysctl kern.cp_time2 failed");
                    231:                        /* convert cp_time2 counts to percentages */
                    232:                        (void) percentages(CPUSTATES, tmpstate, cp_time[i],
                    233:                            cp_old[i], cp_diff[i]);
                    234:                }
                    235:        } else {
                    236:                int cp_time_mib[] = {CTL_KERN, KERN_CPTIME};
                    237:                long cp_time_tmp[CPUSTATES];
                    238:
                    239:                size = sizeof(cp_time_tmp);
                    240:                if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, NULL, 0) < 0)
                    241:                        warn("sysctl kern.cp_time failed");
                    242:                for (i = 0; i < CPUSTATES; i++)
                    243:                        cp_time[0][i] = cp_time_tmp[i];
                    244:                /* convert cp_time counts to percentages */
                    245:                (void) percentages(CPUSTATES, cpu_states, cp_time[0],
                    246:                    cp_old[0], cp_diff[0]);
                    247:        }
1.35      deraadt   248:
1.20      deraadt   249:        size = sizeof(sysload);
1.35      deraadt   250:        if (sysctl(sysload_mib, 2, &sysload, &size, NULL, 0) < 0)
1.20      deraadt   251:                warn("sysctl failed");
1.1       downsj    252:        infoloadp = si->load_avg;
                    253:        for (i = 0; i < 3; i++)
1.20      deraadt   254:                *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
1.1       downsj    255:
                    256:
                    257:        /* get total -- systemwide main memory usage structure */
1.20      deraadt   258:        size = sizeof(vmtotal);
                    259:        if (sysctl(vmtotal_mib, 2, &vmtotal, &size, NULL, 0) < 0) {
                    260:                warn("sysctl failed");
                    261:                bzero(&vmtotal, sizeof(vmtotal));
1.1       downsj    262:        }
1.69      tedu      263:        size = sizeof(bcstats);
                    264:        if (sysctl(bcstats_mib, 3, &bcstats, &size, NULL, 0) < 0) {
                    265:                warn("sysctl failed");
                    266:                bzero(&bcstats, sizeof(bcstats));
                    267:        }
1.1       downsj    268:        /* convert memory stats to Kbytes */
                    269:        memory_stats[0] = -1;
1.20      deraadt   270:        memory_stats[1] = pagetok(vmtotal.t_arm);
                    271:        memory_stats[2] = pagetok(vmtotal.t_rm);
1.1       downsj    272:        memory_stats[3] = -1;
1.20      deraadt   273:        memory_stats[4] = pagetok(vmtotal.t_free);
1.1       downsj    274:        memory_stats[5] = -1;
1.69      tedu      275:        memory_stats[6] = pagetok(bcstats.numbufpages);
                    276:        memory_stats[7] = -1;
1.31      deraadt   277:
1.69      tedu      278:        if (!swapmode(&memory_stats[8], &memory_stats[9])) {
                    279:                memory_stats[8] = 0;
                    280:                memory_stats[9] = 0;
1.1       downsj    281:        }
                    282:
1.20      deraadt   283:        /* set arrays and strings */
                    284:        si->cpustates = cpu_states;
                    285:        si->memory = memory_stats;
                    286:        si->last_pid = -1;
1.1       downsj    287: }
                    288:
                    289: static struct handle handle;
                    290:
1.68      guenther  291: struct kinfo_proc *
1.29      pvalchev  292: getprocs(int op, int arg, int *cnt)
1.22      deraadt   293: {
1.37      millert   294:        size_t size;
1.68      guenther  295:        int mib[6] = {CTL_KERN, KERN_PROC, 0, 0, sizeof(struct kinfo_proc), 0};
1.26      art       296:        static int maxslp_mib[] = {CTL_VM, VM_MAXSLP};
1.68      guenther  297:        static struct kinfo_proc *procbase;
1.24      angelos   298:        int st;
1.22      deraadt   299:
1.31      deraadt   300:        mib[2] = op;
                    301:        mib[3] = arg;
                    302:
1.26      art       303:        size = sizeof(maxslp);
                    304:        if (sysctl(maxslp_mib, 2, &maxslp, &size, NULL, 0) < 0) {
                    305:                warn("sysctl vm.maxslp failed");
                    306:                return (0);
                    307:        }
1.37      millert   308:     retry:
                    309:        free(procbase);
                    310:        st = sysctl(mib, 6, NULL, &size, NULL, 0);
1.22      deraadt   311:        if (st == -1) {
1.68      guenther  312:                /* _kvm_syserr(kd, kd->program, "kvm_getprocs"); */
1.22      deraadt   313:                return (0);
                    314:        }
1.37      millert   315:        size = 5 * size / 4;                    /* extra slop */
                    316:        if ((procbase = malloc(size)) == NULL)
1.22      deraadt   317:                return (0);
1.68      guenther  318:        mib[5] = (int)(size / sizeof(struct kinfo_proc));
1.37      millert   319:        st = sysctl(mib, 6, procbase, &size, NULL, 0);
1.22      deraadt   320:        if (st == -1) {
1.37      millert   321:                if (errno == ENOMEM)
                    322:                        goto retry;
1.68      guenther  323:                /* _kvm_syserr(kd, kd->program, "kvm_getprocs"); */
1.22      deraadt   324:                return (0);
                    325:        }
1.68      guenther  326:        *cnt = (int)(size / sizeof(struct kinfo_proc));
1.22      deraadt   327:        return (procbase);
                    328: }
                    329:
1.30      deraadt   330: caddr_t
1.29      pvalchev  331: get_process_info(struct system_info *si, struct process_select *sel,
1.30      deraadt   332:     int (*compare) (const void *, const void *))
1.20      deraadt   333: {
1.56      otto      334:        int show_idle, show_system, show_threads, show_uid, show_pid, show_cmd;
1.73      brynet    335:        int hide_uid;
1.46      pat       336:        int total_procs, active_procs;
1.68      guenther  337:        struct kinfo_proc **prefp, *pp;
1.71      pirofti   338:        int what = KERN_PROC_KTHREAD;
1.20      deraadt   339:
1.71      pirofti   340:        if (sel->threads)
                    341:                what |= KERN_PROC_SHOW_THREADS;
                    342:
                    343:        if ((pbase = getprocs(what, 0, &nproc)) == NULL) {
1.22      deraadt   344:                /* warnx("%s", kvm_geterr(kd)); */
1.20      deraadt   345:                quit(23);
                    346:        }
                    347:        if (nproc > onproc)
1.68      guenther  348:                pref = (struct kinfo_proc **)realloc(pref,
                    349:                    sizeof(struct kinfo_proc *) * (onproc = nproc));
1.20      deraadt   350:        if (pref == NULL) {
                    351:                warnx("Out of memory.");
                    352:                quit(23);
                    353:        }
                    354:        /* get a pointer to the states summary array */
                    355:        si->procstates = process_states;
1.1       downsj    356:
1.20      deraadt   357:        /* set up flags which define what we are going to select */
                    358:        show_idle = sel->idle;
                    359:        show_system = sel->system;
1.50      tedu      360:        show_threads = sel->threads;
1.33      millert   361:        show_uid = sel->uid != (uid_t)-1;
1.73      brynet    362:        hide_uid = sel->huid != (uid_t)-1;
1.44      otto      363:        show_pid = sel->pid != (pid_t)-1;
1.56      otto      364:        show_cmd = sel->command != NULL;
1.20      deraadt   365:
                    366:        /* count up process states and get pointers to interesting procs */
                    367:        total_procs = 0;
                    368:        active_procs = 0;
                    369:        memset((char *) process_states, 0, sizeof(process_states));
                    370:        prefp = pref;
1.46      pat       371:        for (pp = pbase; pp < &pbase[nproc]; pp++) {
1.20      deraadt   372:                /*
                    373:                 *  Place pointers to each valid proc structure in pref[].
                    374:                 *  Process slots that are actually in use have a non-zero
1.59      otto      375:                 *  status field.  Processes with P_SYSTEM set are system
                    376:                 *  processes---these get ignored unless show_system is set.
1.20      deraadt   377:                 */
1.70      pirofti   378:                if (show_threads && pp->p_tid == -1)
                    379:                        continue;
1.37      millert   380:                if (pp->p_stat != 0 &&
1.50      tedu      381:                    (show_system || (pp->p_flag & P_SYSTEM) == 0) &&
                    382:                    (show_threads || (pp->p_flag & P_THREAD) == 0)) {
1.20      deraadt   383:                        total_procs++;
1.37      millert   384:                        process_states[(unsigned char) pp->p_stat]++;
                    385:                        if (pp->p_stat != SZOMB &&
                    386:                            (show_idle || pp->p_pctcpu != 0 ||
                    387:                            pp->p_stat == SRUN) &&
1.73      brynet    388:                            (!hide_uid || pp->p_ruid != sel->huid) &&
1.44      otto      389:                            (!show_uid || pp->p_ruid == sel->uid) &&
1.56      otto      390:                            (!show_pid || pp->p_pid == sel->pid) &&
                    391:                            (!show_cmd || strstr(pp->p_comm,
                    392:                                sel->command))) {
1.20      deraadt   393:                                *prefp++ = pp;
                    394:                                active_procs++;
                    395:                        }
                    396:                }
                    397:        }
                    398:
                    399:        /* if requested, sort the "interesting" processes */
1.30      deraadt   400:        if (compare != NULL)
                    401:                qsort((char *) pref, active_procs,
1.68      guenther  402:                    sizeof(struct kinfo_proc *), compare);
1.20      deraadt   403:        /* remember active and total counts */
                    404:        si->p_total = total_procs;
                    405:        si->p_active = pref_len = active_procs;
                    406:
                    407:        /* pass back a handle */
                    408:        handle.next_proc = pref;
                    409:        handle.remaining = active_procs;
                    410:        return ((caddr_t) & handle);
                    411: }
                    412:
1.30      deraadt   413: char fmt[MAX_COLS];    /* static area where result is built */
1.20      deraadt   414:
1.58      otto      415: static char *
1.68      guenther  416: state_abbr(struct kinfo_proc *pp)
1.40      deraadt   417: {
                    418:        static char buf[10];
                    419:
1.42      deraadt   420:        if (ncpu > 1 && pp->p_cpuid != KI_NOCPU)
1.48      millert   421:                snprintf(buf, sizeof buf, "%s/%llu",
1.41      deraadt   422:                    state_abbrev[(unsigned char)pp->p_stat], pp->p_cpuid);
                    423:        else
                    424:                snprintf(buf, sizeof buf, "%s",
                    425:                    state_abbrev[(unsigned char)pp->p_stat]);
1.40      deraadt   426:        return buf;
                    427: }
                    428:
1.58      otto      429: static char *
1.68      guenther  430: format_comm(struct kinfo_proc *kp)
1.49      markus    431: {
1.63      otto      432:        static char **s, buf[MAX_COLS];
1.49      markus    433:        size_t siz = 100;
                    434:        char **p;
                    435:        int mib[4];
                    436:        extern int show_args;
                    437:
                    438:        if (!show_args)
                    439:                return (kp->p_comm);
                    440:
                    441:        for (;; siz *= 2) {
                    442:                if ((s = realloc(s, siz)) == NULL)
                    443:                        err(1, NULL);
                    444:                mib[0] = CTL_KERN;
                    445:                mib[1] = KERN_PROC_ARGS;
                    446:                mib[2] = kp->p_pid;
                    447:                mib[3] = KERN_PROC_ARGV;
                    448:                if (sysctl(mib, 4, s, &siz, NULL, 0) == 0)
                    449:                        break;
                    450:                if (errno != ENOMEM)
                    451:                        return (kp->p_comm);
                    452:        }
                    453:        buf[0] = '\0';
                    454:        for (p = s; *p != NULL; p++) {
                    455:                if (p != s)
                    456:                        strlcat(buf, " ", sizeof(buf));
                    457:                strlcat(buf, *p, sizeof(buf));
                    458:        }
                    459:        if (buf[0] == '\0')
                    460:                return (kp->p_comm);
                    461:        return (buf);
                    462: }
                    463:
                    464: char *
1.61      otto      465: format_next_process(caddr_t handle, char *(*get_userid)(uid_t), pid_t *pid)
1.20      deraadt   466: {
1.30      deraadt   467:        char *p_wait, waddr[sizeof(void *) * 2 + 3];    /* Hexify void pointer */
1.68      guenther  468:        struct kinfo_proc *pp;
1.20      deraadt   469:        struct handle *hp;
                    470:        int cputime;
                    471:        double pct;
                    472:
                    473:        /* find and remember the next proc structure */
                    474:        hp = (struct handle *) handle;
                    475:        pp = *(hp->next_proc++);
                    476:        hp->remaining--;
                    477:
1.66      lum       478:        cputime = pp->p_rtime_sec + ((pp->p_rtime_usec + 500000) / 1000000);
1.20      deraadt   479:
                    480:        /* calculate the base for cpu percentages */
1.37      millert   481:        pct = pctdouble(pp->p_pctcpu);
1.20      deraadt   482:
1.37      millert   483:        if (pp->p_wchan) {
                    484:                if (pp->p_wmesg)
                    485:                        p_wait = pp->p_wmesg;
1.20      deraadt   486:                else {
1.37      millert   487:                        snprintf(waddr, sizeof(waddr), "%llx",
1.74      deraadt   488:                            (unsigned long long)pp->p_wchan);
1.20      deraadt   489:                        p_wait = waddr;
                    490:                }
1.30      deraadt   491:        } else
1.20      deraadt   492:                p_wait = "-";
                    493:
                    494:        /* format this entry */
1.30      deraadt   495:        snprintf(fmt, sizeof fmt, Proc_format,
1.37      millert   496:            pp->p_pid, (*get_userid)(pp->p_ruid),
                    497:            pp->p_priority - PZERO, pp->p_nice - NZERO,
1.1       downsj    498:            format_k(pagetok(PROCSIZE(pp))),
1.37      millert   499:            format_k(pagetok(pp->p_vm_rssize)),
                    500:            (pp->p_stat == SSLEEP && pp->p_slptime > maxslp) ?
1.40      deraadt   501:            "idle" : state_abbr(pp),
1.30      deraadt   502:            p_wait, format_time(cputime), 100.0 * pct,
1.49      markus    503:            printable(format_comm(pp)));
1.1       downsj    504:
1.61      otto      505:        *pid = pp->p_pid;
1.20      deraadt   506:        /* return the result */
                    507:        return (fmt);
1.1       downsj    508: }
                    509:
                    510: /* comparison routine for qsort */
1.11      kstailey  511: static unsigned char sorted_state[] =
                    512: {
1.20      deraadt   513:        0,                      /* not used              */
                    514:        4,                      /* start                 */
                    515:        5,                      /* run                   */
                    516:        2,                      /* sleep                 */
                    517:        3,                      /* stop                  */
                    518:        1                       /* zombie                */
1.11      kstailey  519: };
                    520:
                    521: /*
                    522:  *  proc_compares - comparison functions for "qsort"
                    523:  */
                    524:
                    525: /*
                    526:  * First, the possible comparison keys.  These are defined in such a way
                    527:  * that they can be merely listed in the source code to define the actual
                    528:  * desired ordering.
                    529:  */
                    530:
                    531: #define ORDERKEY_PCTCPU \
1.37      millert   532:        if (lresult = (pctcpu)p2->p_pctcpu - (pctcpu)p1->p_pctcpu, \
1.22      deraadt   533:            (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
1.11      kstailey  534: #define ORDERKEY_CPUTIME \
1.37      millert   535:        if ((result = p2->p_rtime_sec - p1->p_rtime_sec) == 0) \
                    536:                if ((result = p2->p_rtime_usec - p1->p_rtime_usec) == 0)
1.11      kstailey  537: #define ORDERKEY_STATE \
1.37      millert   538:        if ((result = sorted_state[(unsigned char)p2->p_stat] - \
                    539:            sorted_state[(unsigned char)p1->p_stat])  == 0)
1.11      kstailey  540: #define ORDERKEY_PRIO \
1.37      millert   541:        if ((result = p2->p_priority - p1->p_priority) == 0)
1.11      kstailey  542: #define ORDERKEY_RSSIZE \
1.37      millert   543:        if ((result = p2->p_vm_rssize - p1->p_vm_rssize) == 0)
1.11      kstailey  544: #define ORDERKEY_MEM \
                    545:        if ((result = PROCSIZE(p2) - PROCSIZE(p1)) == 0)
1.65      tedu      546: #define ORDERKEY_PID \
                    547:        if ((result = p1->p_pid - p2->p_pid) == 0)
                    548: #define ORDERKEY_CMD \
                    549:        if ((result = strcmp(p1->p_comm, p2->p_comm)) == 0)
1.11      kstailey  550:
                    551: /* compare_cpu - the comparison function for sorting by cpu percentage */
1.36      deraadt   552: static int
1.29      pvalchev  553: compare_cpu(const void *v1, const void *v2)
1.11      kstailey  554: {
1.20      deraadt   555:        struct proc **pp1 = (struct proc **) v1;
                    556:        struct proc **pp2 = (struct proc **) v2;
1.68      guenther  557:        struct kinfo_proc *p1, *p2;
1.30      deraadt   558:        pctcpu lresult;
1.20      deraadt   559:        int result;
                    560:
                    561:        /* remove one level of indirection */
1.68      guenther  562:        p1 = *(struct kinfo_proc **) pp1;
                    563:        p2 = *(struct kinfo_proc **) pp2;
1.20      deraadt   564:
                    565:        ORDERKEY_PCTCPU
1.30      deraadt   566:        ORDERKEY_CPUTIME
                    567:        ORDERKEY_STATE
                    568:        ORDERKEY_PRIO
                    569:        ORDERKEY_RSSIZE
                    570:        ORDERKEY_MEM
                    571:                ;
1.20      deraadt   572:        return (result);
1.11      kstailey  573: }
                    574:
                    575: /* compare_size - the comparison function for sorting by total memory usage */
1.36      deraadt   576: static int
1.29      pvalchev  577: compare_size(const void *v1, const void *v2)
1.11      kstailey  578: {
1.20      deraadt   579:        struct proc **pp1 = (struct proc **) v1;
                    580:        struct proc **pp2 = (struct proc **) v2;
1.68      guenther  581:        struct kinfo_proc *p1, *p2;
1.30      deraadt   582:        pctcpu lresult;
1.20      deraadt   583:        int result;
                    584:
                    585:        /* remove one level of indirection */
1.68      guenther  586:        p1 = *(struct kinfo_proc **) pp1;
                    587:        p2 = *(struct kinfo_proc **) pp2;
1.20      deraadt   588:
                    589:        ORDERKEY_MEM
1.30      deraadt   590:        ORDERKEY_RSSIZE
                    591:        ORDERKEY_PCTCPU
                    592:        ORDERKEY_CPUTIME
                    593:        ORDERKEY_STATE
                    594:        ORDERKEY_PRIO
                    595:                ;
1.20      deraadt   596:        return (result);
1.11      kstailey  597: }
                    598:
                    599: /* compare_res - the comparison function for sorting by resident set size */
1.36      deraadt   600: static int
1.29      pvalchev  601: compare_res(const void *v1, const void *v2)
1.11      kstailey  602: {
1.20      deraadt   603:        struct proc **pp1 = (struct proc **) v1;
                    604:        struct proc **pp2 = (struct proc **) v2;
1.68      guenther  605:        struct kinfo_proc *p1, *p2;
1.30      deraadt   606:        pctcpu lresult;
1.20      deraadt   607:        int result;
                    608:
                    609:        /* remove one level of indirection */
1.68      guenther  610:        p1 = *(struct kinfo_proc **) pp1;
                    611:        p2 = *(struct kinfo_proc **) pp2;
1.20      deraadt   612:
                    613:        ORDERKEY_RSSIZE
1.30      deraadt   614:        ORDERKEY_MEM
                    615:        ORDERKEY_PCTCPU
                    616:        ORDERKEY_CPUTIME
                    617:        ORDERKEY_STATE
                    618:        ORDERKEY_PRIO
                    619:                ;
1.20      deraadt   620:        return (result);
1.11      kstailey  621: }
                    622:
                    623: /* compare_time - the comparison function for sorting by CPU time */
1.36      deraadt   624: static int
1.29      pvalchev  625: compare_time(const void *v1, const void *v2)
1.11      kstailey  626: {
1.20      deraadt   627:        struct proc **pp1 = (struct proc **) v1;
                    628:        struct proc **pp2 = (struct proc **) v2;
1.68      guenther  629:        struct kinfo_proc *p1, *p2;
1.30      deraadt   630:        pctcpu lresult;
1.20      deraadt   631:        int result;
                    632:
                    633:        /* remove one level of indirection */
1.68      guenther  634:        p1 = *(struct kinfo_proc **) pp1;
                    635:        p2 = *(struct kinfo_proc **) pp2;
1.20      deraadt   636:
                    637:        ORDERKEY_CPUTIME
1.30      deraadt   638:        ORDERKEY_PCTCPU
                    639:        ORDERKEY_STATE
                    640:        ORDERKEY_PRIO
                    641:        ORDERKEY_MEM
                    642:        ORDERKEY_RSSIZE
                    643:                ;
1.20      deraadt   644:        return (result);
1.11      kstailey  645: }
                    646:
                    647: /* compare_prio - the comparison function for sorting by CPU time */
1.36      deraadt   648: static int
1.29      pvalchev  649: compare_prio(const void *v1, const void *v2)
1.11      kstailey  650: {
1.30      deraadt   651:        struct proc   **pp1 = (struct proc **) v1;
                    652:        struct proc   **pp2 = (struct proc **) v2;
1.68      guenther  653:        struct kinfo_proc *p1, *p2;
1.30      deraadt   654:        pctcpu lresult;
1.20      deraadt   655:        int result;
                    656:
                    657:        /* remove one level of indirection */
1.68      guenther  658:        p1 = *(struct kinfo_proc **) pp1;
                    659:        p2 = *(struct kinfo_proc **) pp2;
1.20      deraadt   660:
                    661:        ORDERKEY_PRIO
1.30      deraadt   662:        ORDERKEY_PCTCPU
                    663:        ORDERKEY_CPUTIME
                    664:        ORDERKEY_STATE
                    665:        ORDERKEY_RSSIZE
                    666:        ORDERKEY_MEM
                    667:                ;
1.20      deraadt   668:        return (result);
                    669: }
                    670:
1.65      tedu      671: static int
                    672: compare_pid(const void *v1, const void *v2)
                    673: {
                    674:        struct proc **pp1 = (struct proc **) v1;
                    675:        struct proc **pp2 = (struct proc **) v2;
1.68      guenther  676:        struct kinfo_proc *p1, *p2;
1.65      tedu      677:        pctcpu lresult;
                    678:        int result;
                    679:
                    680:        /* remove one level of indirection */
1.68      guenther  681:        p1 = *(struct kinfo_proc **) pp1;
                    682:        p2 = *(struct kinfo_proc **) pp2;
1.65      tedu      683:
                    684:        ORDERKEY_PID
                    685:        ORDERKEY_PCTCPU
                    686:        ORDERKEY_CPUTIME
                    687:        ORDERKEY_STATE
                    688:        ORDERKEY_PRIO
                    689:        ORDERKEY_RSSIZE
                    690:        ORDERKEY_MEM
                    691:                ;
                    692:        return (result);
                    693: }
                    694:
                    695: static int
                    696: compare_cmd(const void *v1, const void *v2)
                    697: {
                    698:        struct proc **pp1 = (struct proc **) v1;
                    699:        struct proc **pp2 = (struct proc **) v2;
1.68      guenther  700:        struct kinfo_proc *p1, *p2;
1.65      tedu      701:        pctcpu lresult;
                    702:        int result;
                    703:
                    704:        /* remove one level of indirection */
1.68      guenther  705:        p1 = *(struct kinfo_proc **) pp1;
                    706:        p2 = *(struct kinfo_proc **) pp2;
1.65      tedu      707:
                    708:        ORDERKEY_CMD
                    709:        ORDERKEY_PCTCPU
                    710:        ORDERKEY_CPUTIME
                    711:        ORDERKEY_STATE
                    712:        ORDERKEY_PRIO
                    713:        ORDERKEY_RSSIZE
                    714:        ORDERKEY_MEM
                    715:                ;
                    716:        return (result);
                    717: }
                    718:
                    719:
1.31      deraadt   720: int (*proc_compares[])(const void *, const void *) = {
1.20      deraadt   721:        compare_cpu,
                    722:        compare_size,
                    723:        compare_res,
                    724:        compare_time,
                    725:        compare_prio,
1.65      tedu      726:        compare_pid,
                    727:        compare_cmd,
1.20      deraadt   728:        NULL
1.11      kstailey  729: };
1.30      deraadt   730:
1.1       downsj    731: /*
                    732:  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
                    733:  *             the process does not exist.
1.43      otto      734:  *             It is EXTREMELY IMPORTANT that this function work correctly.
1.1       downsj    735:  *             If top runs setuid root (as in SVR4), then this function
                    736:  *             is the only thing that stands in the way of a serious
                    737:  *             security problem.  It validates requests for the "kill"
                    738:  *             and "renice" commands.
                    739:  */
1.33      millert   740: uid_t
1.29      pvalchev  741: proc_owner(pid_t pid)
1.20      deraadt   742: {
1.68      guenther  743:        struct kinfo_proc **prefp, *pp;
1.20      deraadt   744:        int cnt;
                    745:
                    746:        prefp = pref;
                    747:        cnt = pref_len;
                    748:        while (--cnt >= 0) {
                    749:                pp = *prefp++;
1.37      millert   750:                if (pp->p_pid == pid)
                    751:                        return ((uid_t)pp->p_ruid);
1.1       downsj    752:        }
1.34      jfb       753:        return (uid_t)(-1);
1.1       downsj    754: }
1.30      deraadt   755:
1.1       downsj    756: /*
1.17      todd      757:  * swapmode is rewritten by Tobias Weingartner <weingart@openbsd.org>
1.15      weingart  758:  * to be based on the new swapctl(2) system call.
1.1       downsj    759:  */
                    760: static int
1.29      pvalchev  761: swapmode(int *used, int *total)
1.1       downsj    762: {
1.15      weingart  763:        struct swapent *swdev;
1.30      deraadt   764:        int nswap, rnswap, i;
1.1       downsj    765:
1.15      weingart  766:        nswap = swapctl(SWAP_NSWAP, 0, 0);
1.20      deraadt   767:        if (nswap == 0)
1.15      weingart  768:                return 0;
                    769:
1.62      deraadt   770:        swdev = calloc(nswap, sizeof(*swdev));
1.20      deraadt   771:        if (swdev == NULL)
1.15      weingart  772:                return 0;
                    773:
                    774:        rnswap = swapctl(SWAP_STATS, swdev, nswap);
1.53      ray       775:        if (rnswap == -1) {
                    776:                free(swdev);
1.15      weingart  777:                return 0;
1.53      ray       778:        }
1.15      weingart  779:
                    780:        /* if rnswap != nswap, then what? */
                    781:
                    782:        /* Total things up */
                    783:        *total = *used = 0;
                    784:        for (i = 0; i < nswap; i++) {
                    785:                if (swdev[i].se_flags & SWF_ENABLE) {
1.20      deraadt   786:                        *used += (swdev[i].se_inuse / (1024 / DEV_BSIZE));
                    787:                        *total += (swdev[i].se_nblks / (1024 / DEV_BSIZE));
1.1       downsj    788:                }
                    789:        }
1.20      deraadt   790:        free(swdev);
1.1       downsj    791:        return 1;
                    792: }