[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.55

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