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

1.101   ! guenther    1: /* $OpenBSD: machine.c,v 1.100 2019/10/08 20:51:03 kn 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:
1.81      deraadt    36: #include <sys/param.h> /* DEV_BSIZE MAXCOMLEN PZERO */
1.1       downsj     37: #include <sys/types.h>
1.81      deraadt    38: #include <sys/signal.h>
1.75      millert    39: #include <sys/mount.h>
                     40: #include <sys/proc.h>
1.79      miod       41: #include <sys/sched.h>
1.75      millert    42: #include <sys/swap.h>
                     43: #include <sys/sysctl.h>
                     44:
1.1       downsj     45: #include <stdio.h>
                     46: #include <stdlib.h>
1.3       downsj     47: #include <string.h>
1.1       downsj     48: #include <unistd.h>
                     49: #include <err.h>
1.51      millert    50: #include <errno.h>
1.1       downsj     51:
                     52: #include "top.h"
1.3       downsj     53: #include "display.h"
1.1       downsj     54: #include "machine.h"
                     55: #include "utils.h"
1.31      deraadt    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.86      edd        60: static int     cmd_matches(struct kinfo_proc *, char *);
                     61: static char    **get_proc_args(struct kinfo_proc *);
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.68      guenther   66:        struct kinfo_proc **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.64      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.64      deraadt    83:        "%5d %-8.8s %3d %4d %5s %5s %-9s %-7.7s %6s %5.2f%% %s"
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:
                     95: /* these are for calculating cpu state percentages */
1.95      cheloha    96: static struct cpustats *cp_time;
                     97: static struct cpustats *cp_old;
                     98: static struct cpustats *cp_diff;
1.1       downsj     99:
                    100: /* these are for detailing the process states */
1.45      markus    101: int process_states[8];
1.30      deraadt   102: char *procstatenames[] = {
                    103:        "", " starting, ", " running, ", " idle, ",
1.47      markus    104:        " stopped, ", " zombie, ", " dead, ", " on processor, ",
1.20      deraadt   105:        NULL
1.1       downsj    106: };
                    107:
                    108: /* these are for detailing the cpu states */
1.48      millert   109: int64_t *cpu_states;
1.30      deraadt   110: char *cpustatenames[] = {
1.90      mpi       111:        "user", "nice", "sys", "spin", "intr", "idle", NULL
1.1       downsj    112: };
                    113:
1.95      cheloha   114: /* this is for tracking which cpus are online */
                    115: int *cpu_online;
                    116:
1.1       downsj    117: /* these are for detailing the memory statistics */
1.69      tedu      118: int memory_stats[10];
1.30      deraadt   119: char *memorynames[] = {
1.69      tedu      120:        "Real: ", "K/", "K act/tot ", "Free: ", "K ",
                    121:        "Cache: ", "K ",
                    122:        "Swap: ", "K/", "K",
1.20      deraadt   123:        NULL
1.1       downsj    124: };
                    125:
1.11      kstailey  126: /* these are names given to allowed sorting orders -- first is default */
1.31      deraadt   127: char   *ordernames[] = {
1.65      tedu      128:        "cpu", "size", "res", "time", "pri", "pid", "command", NULL
1.31      deraadt   129: };
1.11      kstailey  130:
1.1       downsj    131: /* these are for keeping track of the proc array */
1.88      deraadt   132: static int     nproc;
                    133: static int     onproc = -1;
                    134: static int     pref_len;
1.68      guenther  135: static struct kinfo_proc *pbase;
                    136: static struct kinfo_proc **pref;
1.1       downsj    137:
                    138: /* these are for getting the memory statistics */
1.88      deraadt   139: static int     pageshift;      /* log base 2 of the pagesize */
1.1       downsj    140:
                    141: /* define pagetok in terms of pageshift */
                    142: #define pagetok(size) ((size) << pageshift)
                    143:
1.41      deraadt   144: int            ncpu;
1.95      cheloha   145: int            ncpuonline;
1.82      deraadt   146: int            fscale;
1.41      deraadt   147:
1.33      millert   148: unsigned int   maxslp;
1.26      art       149:
1.18      deraadt   150: int
1.82      deraadt   151: getfscale(void)
                    152: {
                    153:        int mib[] = { CTL_KERN, KERN_FSCALE };
                    154:        size_t size = sizeof(fscale);
                    155:
                    156:        if (sysctl(mib, sizeof(mib) / sizeof(mib[0]),
1.97      deraadt   157:            &fscale, &size, NULL, 0) == -1)
1.82      deraadt   158:                return (-1);
                    159:        return fscale;
                    160: }
                    161:
                    162: int
1.80      dlg       163: getncpu(void)
                    164: {
                    165:        int mib[] = { CTL_HW, HW_NCPU };
1.89      tedu      166:        int numcpu;
                    167:        size_t size = sizeof(numcpu);
1.80      dlg       168:
                    169:        if (sysctl(mib, sizeof(mib) / sizeof(mib[0]),
1.89      tedu      170:            &numcpu, &size, NULL, 0) == -1)
1.80      dlg       171:                return (-1);
                    172:
1.89      tedu      173:        return (numcpu);
1.80      dlg       174: }
                    175:
                    176: int
1.95      cheloha   177: getncpuonline(void)
                    178: {
                    179:        int mib[] = { CTL_HW, HW_NCPUONLINE };
                    180:        int numcpu;
                    181:        size_t size = sizeof(numcpu);
                    182:
                    183:        if (sysctl(mib, sizeof(mib) / sizeof(mib[0]),
                    184:            &numcpu, &size, NULL, 0) == -1)
                    185:                return (-1);
                    186:
                    187:        return (numcpu);
                    188: }
                    189:
                    190: int
1.29      pvalchev  191: machine_init(struct statics *statics)
1.1       downsj    192: {
1.95      cheloha   193:        int pagesize;
1.41      deraadt   194:
1.80      dlg       195:        ncpu = getncpu();
                    196:        if (ncpu == -1)
1.82      deraadt   197:                return (-1);
                    198:        if (getfscale() == -1)
1.41      deraadt   199:                return (-1);
1.62      deraadt   200:        cpu_states = calloc(ncpu, CPUSTATES * sizeof(int64_t));
1.48      millert   201:        if (cpu_states == NULL)
                    202:                err(1, NULL);
1.95      cheloha   203:        cp_time = calloc(ncpu, sizeof(*cp_time));
                    204:        cp_old  = calloc(ncpu, sizeof(*cp_old));
                    205:        cp_diff = calloc(ncpu, sizeof(*cp_diff));
1.48      millert   206:        if (cp_time == NULL || cp_old == NULL || cp_diff == NULL)
                    207:                err(1, NULL);
1.95      cheloha   208:        cpu_online = calloc(ncpu, sizeof(*cpu_online));
                    209:        if (cpu_online == NULL)
                    210:                err(1, NULL);
1.20      deraadt   211:
                    212:        pbase = NULL;
                    213:        pref = NULL;
                    214:        onproc = -1;
                    215:        nproc = 0;
                    216:
1.30      deraadt   217:        /*
                    218:         * get the page size with "getpagesize" and calculate pageshift from
                    219:         * it
                    220:         */
1.20      deraadt   221:        pagesize = getpagesize();
                    222:        pageshift = 0;
                    223:        while (pagesize > 1) {
                    224:                pageshift++;
                    225:                pagesize >>= 1;
                    226:        }
                    227:
                    228:        /* we only need the amount of log(2)1024 for our conversion */
                    229:        pageshift -= LOG1024;
                    230:
                    231:        /* fill in the statics information */
                    232:        statics->procstate_names = procstatenames;
                    233:        statics->cpustate_names = cpustatenames;
                    234:        statics->memory_names = memorynames;
                    235:        statics->order_names = ordernames;
                    236:        return (0);
1.1       downsj    237: }
                    238:
1.20      deraadt   239: char *
1.100     kn        240: format_header(char *second_field)
1.1       downsj    241: {
1.84      mpi       242:        char *field_name, *thread_field = "     TID";
1.20      deraadt   243:        char *ptr;
1.1       downsj    244:
1.100     kn        245:        field_name = second_field ? second_field : thread_field;
1.84      mpi       246:
1.20      deraadt   247:        ptr = header + UNAME_START;
1.84      mpi       248:        while (*field_name != '\0')
                    249:                *ptr++ = *field_name++;
1.20      deraadt   250:        return (header);
1.1       downsj    251: }
                    252:
                    253: void
1.31      deraadt   254: get_system_info(struct system_info *si)
1.1       downsj    255: {
1.95      cheloha   256:        static int cpustats_mib[] = {CTL_KERN, KERN_CPUSTATS, /*fillme*/0};
1.20      deraadt   257:        static int sysload_mib[] = {CTL_VM, VM_LOADAVG};
1.77      mpi       258:        static int uvmexp_mib[] = {CTL_VM, VM_UVMEXP};
1.69      tedu      259:        static int bcstats_mib[] = {CTL_VFS, VFS_GENERIC, VFS_BCACHESTAT};
1.1       downsj    260:        struct loadavg sysload;
1.77      mpi       261:        struct uvmexp uvmexp;
1.69      tedu      262:        struct bcachestats bcstats;
1.20      deraadt   263:        double *infoloadp;
1.30      deraadt   264:        size_t size;
1.35      deraadt   265:        int i;
1.48      millert   266:        int64_t *tmpstate;
1.30      deraadt   267:
1.95      cheloha   268:        size = sizeof(*cp_time);
                    269:        for (i = 0; i < ncpu; i++) {
                    270:                cpustats_mib[2] = i;
                    271:                tmpstate = cpu_states + (CPUSTATES * i);
1.97      deraadt   272:                if (sysctl(cpustats_mib, 3, &cp_time[i], &size, NULL, 0) == -1)
1.95      cheloha   273:                        warn("sysctl kern.cpustats failed");
                    274:                /* convert cpustats counts to percentages */
                    275:                (void) percentages(CPUSTATES, tmpstate, cp_time[i].cs_time,
                    276:                    cp_old[i].cs_time, cp_diff[i].cs_time);
                    277:                /* note whether the cpu is online */
                    278:                cpu_online[i] = (cp_time[i].cs_flags & CPUSTATS_ONLINE) != 0;
1.48      millert   279:        }
1.35      deraadt   280:
1.20      deraadt   281:        size = sizeof(sysload);
1.97      deraadt   282:        if (sysctl(sysload_mib, 2, &sysload, &size, NULL, 0) == -1)
1.20      deraadt   283:                warn("sysctl failed");
1.1       downsj    284:        infoloadp = si->load_avg;
                    285:        for (i = 0; i < 3; i++)
1.20      deraadt   286:                *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
1.1       downsj    287:
                    288:
                    289:        /* get total -- systemwide main memory usage structure */
1.77      mpi       290:        size = sizeof(uvmexp);
1.97      deraadt   291:        if (sysctl(uvmexp_mib, 2, &uvmexp, &size, NULL, 0) == -1) {
1.20      deraadt   292:                warn("sysctl failed");
1.77      mpi       293:                bzero(&uvmexp, sizeof(uvmexp));
1.1       downsj    294:        }
1.69      tedu      295:        size = sizeof(bcstats);
1.97      deraadt   296:        if (sysctl(bcstats_mib, 3, &bcstats, &size, NULL, 0) == -1) {
1.69      tedu      297:                warn("sysctl failed");
                    298:                bzero(&bcstats, sizeof(bcstats));
                    299:        }
1.1       downsj    300:        /* convert memory stats to Kbytes */
                    301:        memory_stats[0] = -1;
1.77      mpi       302:        memory_stats[1] = pagetok(uvmexp.active);
                    303:        memory_stats[2] = pagetok(uvmexp.npages - uvmexp.free);
1.1       downsj    304:        memory_stats[3] = -1;
1.77      mpi       305:        memory_stats[4] = pagetok(uvmexp.free);
1.1       downsj    306:        memory_stats[5] = -1;
1.69      tedu      307:        memory_stats[6] = pagetok(bcstats.numbufpages);
                    308:        memory_stats[7] = -1;
1.31      deraadt   309:
1.69      tedu      310:        if (!swapmode(&memory_stats[8], &memory_stats[9])) {
                    311:                memory_stats[8] = 0;
                    312:                memory_stats[9] = 0;
1.1       downsj    313:        }
                    314:
1.20      deraadt   315:        /* set arrays and strings */
                    316:        si->cpustates = cpu_states;
1.95      cheloha   317:        si->cpuonline = cpu_online;
1.20      deraadt   318:        si->memory = memory_stats;
                    319:        si->last_pid = -1;
1.1       downsj    320: }
                    321:
                    322: static struct handle handle;
                    323:
1.68      guenther  324: struct kinfo_proc *
1.29      pvalchev  325: getprocs(int op, int arg, int *cnt)
1.22      deraadt   326: {
1.37      millert   327:        size_t size;
1.68      guenther  328:        int mib[6] = {CTL_KERN, KERN_PROC, 0, 0, sizeof(struct kinfo_proc), 0};
1.26      art       329:        static int maxslp_mib[] = {CTL_VM, VM_MAXSLP};
1.68      guenther  330:        static struct kinfo_proc *procbase;
1.24      angelos   331:        int st;
1.22      deraadt   332:
1.31      deraadt   333:        mib[2] = op;
                    334:        mib[3] = arg;
                    335:
1.26      art       336:        size = sizeof(maxslp);
1.97      deraadt   337:        if (sysctl(maxslp_mib, 2, &maxslp, &size, NULL, 0) == -1) {
1.26      art       338:                warn("sysctl vm.maxslp failed");
                    339:                return (0);
                    340:        }
1.37      millert   341:     retry:
                    342:        free(procbase);
                    343:        st = sysctl(mib, 6, NULL, &size, NULL, 0);
1.22      deraadt   344:        if (st == -1) {
1.68      guenther  345:                /* _kvm_syserr(kd, kd->program, "kvm_getprocs"); */
1.22      deraadt   346:                return (0);
                    347:        }
1.37      millert   348:        size = 5 * size / 4;                    /* extra slop */
                    349:        if ((procbase = malloc(size)) == NULL)
1.22      deraadt   350:                return (0);
1.68      guenther  351:        mib[5] = (int)(size / sizeof(struct kinfo_proc));
1.37      millert   352:        st = sysctl(mib, 6, procbase, &size, NULL, 0);
1.22      deraadt   353:        if (st == -1) {
1.37      millert   354:                if (errno == ENOMEM)
                    355:                        goto retry;
1.68      guenther  356:                /* _kvm_syserr(kd, kd->program, "kvm_getprocs"); */
1.22      deraadt   357:                return (0);
                    358:        }
1.68      guenther  359:        *cnt = (int)(size / sizeof(struct kinfo_proc));
1.22      deraadt   360:        return (procbase);
                    361: }
                    362:
1.86      edd       363: static char **
                    364: get_proc_args(struct kinfo_proc *kp)
                    365: {
                    366:        static char     **s;
1.87      tedu      367:        static size_t   siz = 1023;
1.86      edd       368:        int             mib[4];
                    369:
1.87      tedu      370:        if (!s && !(s = malloc(siz)))
                    371:                err(1, NULL);
                    372:
                    373:        mib[0] = CTL_KERN;
                    374:        mib[1] = KERN_PROC_ARGS;
                    375:        mib[2] = kp->p_pid;
                    376:        mib[3] = KERN_PROC_ARGV;
                    377:        for (;;) {
                    378:                size_t space = siz;
                    379:                if (sysctl(mib, 4, s, &space, NULL, 0) == 0)
1.86      edd       380:                        break;
                    381:                if (errno != ENOMEM)
                    382:                        return NULL;
1.87      tedu      383:                siz *= 2;
                    384:                if ((s = realloc(s, siz)) == NULL)
                    385:                        err(1, NULL);
1.86      edd       386:        }
                    387:        return s;
                    388: }
                    389:
                    390: static int
                    391: cmd_matches(struct kinfo_proc *proc, char *term)
                    392: {
                    393:        extern int      show_args;
                    394:        char            **args = NULL;
                    395:
                    396:        if (!term) {
                    397:                /* No command filter set */
                    398:                return 1;
                    399:        } else {
                    400:                /* Filter set, process name needs to contain term */
                    401:                if (strstr(proc->p_comm, term))
                    402:                        return 1;
                    403:                /* If showing arguments, search those as well */
                    404:                if (show_args) {
                    405:                        args = get_proc_args(proc);
                    406:
                    407:                        if (args == NULL) {
                    408:                                /* Failed to get args, so can't search them */
                    409:                                return 0;
                    410:                        }
                    411:
                    412:                        while (*args != NULL) {
                    413:                                if (strstr(*args, term))
                    414:                                        return 1;
                    415:                                args++;
                    416:                        }
                    417:                }
                    418:        }
                    419:        return 0;
                    420: }
                    421:
1.99      kn        422: struct handle *
1.29      pvalchev  423: get_process_info(struct system_info *si, struct process_select *sel,
1.30      deraadt   424:     int (*compare) (const void *, const void *))
1.20      deraadt   425: {
1.56      otto      426:        int show_idle, show_system, show_threads, show_uid, show_pid, show_cmd;
1.73      brynet    427:        int hide_uid;
1.46      pat       428:        int total_procs, active_procs;
1.68      guenther  429:        struct kinfo_proc **prefp, *pp;
1.101   ! guenther  430:        int what = KERN_PROC_ALL;
1.20      deraadt   431:
1.101   ! guenther  432:        show_system = sel->system;
        !           433:        show_threads = sel->threads;
        !           434:
        !           435:        if (show_system)
        !           436:                what = KERN_PROC_KTHREAD;
        !           437:        if (show_threads)
1.71      pirofti   438:                what |= KERN_PROC_SHOW_THREADS;
                    439:
                    440:        if ((pbase = getprocs(what, 0, &nproc)) == NULL) {
1.22      deraadt   441:                /* warnx("%s", kvm_geterr(kd)); */
1.20      deraadt   442:                quit(23);
                    443:        }
                    444:        if (nproc > onproc)
1.85      deraadt   445:                pref = reallocarray(pref, (onproc = nproc),
                    446:                    sizeof(struct kinfo_proc *));
1.20      deraadt   447:        if (pref == NULL) {
                    448:                warnx("Out of memory.");
                    449:                quit(23);
                    450:        }
                    451:        /* get a pointer to the states summary array */
                    452:        si->procstates = process_states;
1.1       downsj    453:
1.20      deraadt   454:        /* set up flags which define what we are going to select */
                    455:        show_idle = sel->idle;
1.33      millert   456:        show_uid = sel->uid != (uid_t)-1;
1.73      brynet    457:        hide_uid = sel->huid != (uid_t)-1;
1.44      otto      458:        show_pid = sel->pid != (pid_t)-1;
1.56      otto      459:        show_cmd = sel->command != NULL;
1.20      deraadt   460:
                    461:        /* count up process states and get pointers to interesting procs */
                    462:        total_procs = 0;
                    463:        active_procs = 0;
                    464:        memset((char *) process_states, 0, sizeof(process_states));
                    465:        prefp = pref;
1.46      pat       466:        for (pp = pbase; pp < &pbase[nproc]; pp++) {
1.20      deraadt   467:                /*
1.101   ! guenther  468:                 * When showing threads, we want to ignore the structure
        !           469:                 * that represents the entire process, which has TID == -1
1.20      deraadt   470:                 */
1.70      pirofti   471:                if (show_threads && pp->p_tid == -1)
                    472:                        continue;
1.101   ! guenther  473:                /*
        !           474:                 * Place pointers to each valid proc structure in pref[].
        !           475:                 * Process slots that are actually in use have a non-zero
        !           476:                 * status field.
        !           477:                 */
        !           478:                if (pp->p_stat != 0) {
1.20      deraadt   479:                        total_procs++;
1.37      millert   480:                        process_states[(unsigned char) pp->p_stat]++;
1.78      guenther  481:                        if ((pp->p_psflags & PS_ZOMBIE) == 0 &&
1.37      millert   482:                            (show_idle || pp->p_pctcpu != 0 ||
                    483:                            pp->p_stat == SRUN) &&
1.73      brynet    484:                            (!hide_uid || pp->p_ruid != sel->huid) &&
1.44      otto      485:                            (!show_uid || pp->p_ruid == sel->uid) &&
1.56      otto      486:                            (!show_pid || pp->p_pid == sel->pid) &&
1.86      edd       487:                            (!show_cmd || cmd_matches(pp, sel->command))) {
1.20      deraadt   488:                                *prefp++ = pp;
                    489:                                active_procs++;
                    490:                        }
                    491:                }
                    492:        }
                    493:
                    494:        /* if requested, sort the "interesting" processes */
1.30      deraadt   495:        if (compare != NULL)
                    496:                qsort((char *) pref, active_procs,
1.68      guenther  497:                    sizeof(struct kinfo_proc *), compare);
1.20      deraadt   498:        /* remember active and total counts */
                    499:        si->p_total = total_procs;
                    500:        si->p_active = pref_len = active_procs;
                    501:
                    502:        /* pass back a handle */
                    503:        handle.next_proc = pref;
                    504:        handle.remaining = active_procs;
1.99      kn        505:        return &handle;
1.20      deraadt   506: }
                    507:
1.30      deraadt   508: char fmt[MAX_COLS];    /* static area where result is built */
1.20      deraadt   509:
1.58      otto      510: static char *
1.68      guenther  511: state_abbr(struct kinfo_proc *pp)
1.40      deraadt   512: {
                    513:        static char buf[10];
                    514:
1.42      deraadt   515:        if (ncpu > 1 && pp->p_cpuid != KI_NOCPU)
1.48      millert   516:                snprintf(buf, sizeof buf, "%s/%llu",
1.41      deraadt   517:                    state_abbrev[(unsigned char)pp->p_stat], pp->p_cpuid);
                    518:        else
                    519:                snprintf(buf, sizeof buf, "%s",
                    520:                    state_abbrev[(unsigned char)pp->p_stat]);
1.40      deraadt   521:        return buf;
                    522: }
                    523:
1.58      otto      524: static char *
1.68      guenther  525: format_comm(struct kinfo_proc *kp)
1.49      markus    526: {
1.86      edd       527:        static char     buf[MAX_COLS];
                    528:        char            **p, **s;
                    529:        extern int      show_args;
1.49      markus    530:
                    531:        if (!show_args)
                    532:                return (kp->p_comm);
                    533:
1.86      edd       534:        s = get_proc_args(kp);
                    535:        if (s == NULL)
                    536:                return kp->p_comm;
                    537:
1.49      markus    538:        buf[0] = '\0';
                    539:        for (p = s; *p != NULL; p++) {
                    540:                if (p != s)
                    541:                        strlcat(buf, " ", sizeof(buf));
                    542:                strlcat(buf, *p, sizeof(buf));
                    543:        }
                    544:        if (buf[0] == '\0')
                    545:                return (kp->p_comm);
                    546:        return (buf);
                    547: }
                    548:
                    549: char *
1.99      kn        550: format_next_process(struct handle *hndl, const char *(*get_userid)(uid_t, int),
1.100     kn        551:     pid_t *pid)
1.20      deraadt   552: {
1.76      tedu      553:        char *p_wait;
1.68      guenther  554:        struct kinfo_proc *pp;
1.20      deraadt   555:        int cputime;
                    556:        double pct;
1.84      mpi       557:        char buf[16];
1.20      deraadt   558:
                    559:        /* find and remember the next proc structure */
1.99      kn        560:        pp = *(hndl->next_proc++);
                    561:        hndl->remaining--;
1.20      deraadt   562:
1.66      lum       563:        cputime = pp->p_rtime_sec + ((pp->p_rtime_usec + 500000) / 1000000);
1.20      deraadt   564:
                    565:        /* calculate the base for cpu percentages */
1.83      millert   566:        pct = (double)pp->p_pctcpu / fscale;
1.20      deraadt   567:
1.76      tedu      568:        if (pp->p_wmesg[0])
                    569:                p_wait = pp->p_wmesg;
                    570:        else
1.20      deraadt   571:                p_wait = "-";
                    572:
1.100     kn        573:        if (get_userid == NULL)
1.84      mpi       574:                snprintf(buf, sizeof(buf), "%8d", pp->p_tid);
                    575:        else
1.92      millert   576:                snprintf(buf, sizeof(buf), "%s", (*get_userid)(pp->p_ruid, 0));
1.84      mpi       577:
1.20      deraadt   578:        /* format this entry */
1.84      mpi       579:        snprintf(fmt, sizeof(fmt), Proc_format, pp->p_pid, buf,
1.37      millert   580:            pp->p_priority - PZERO, pp->p_nice - NZERO,
1.1       downsj    581:            format_k(pagetok(PROCSIZE(pp))),
1.37      millert   582:            format_k(pagetok(pp->p_vm_rssize)),
                    583:            (pp->p_stat == SSLEEP && pp->p_slptime > maxslp) ?
1.40      deraadt   584:            "idle" : state_abbr(pp),
1.30      deraadt   585:            p_wait, format_time(cputime), 100.0 * pct,
1.49      markus    586:            printable(format_comm(pp)));
1.1       downsj    587:
1.61      otto      588:        *pid = pp->p_pid;
1.20      deraadt   589:        /* return the result */
                    590:        return (fmt);
1.1       downsj    591: }
                    592:
                    593: /* comparison routine for qsort */
1.11      kstailey  594: static unsigned char sorted_state[] =
                    595: {
1.20      deraadt   596:        0,                      /* not used              */
                    597:        4,                      /* start                 */
                    598:        5,                      /* run                   */
                    599:        2,                      /* sleep                 */
                    600:        3,                      /* stop                  */
                    601:        1                       /* zombie                */
1.11      kstailey  602: };
                    603:
1.96      kn        604: extern int rev_order;
                    605:
1.11      kstailey  606: /*
                    607:  *  proc_compares - comparison functions for "qsort"
                    608:  */
                    609:
                    610: /*
                    611:  * First, the possible comparison keys.  These are defined in such a way
                    612:  * that they can be merely listed in the source code to define the actual
                    613:  * desired ordering.
                    614:  */
                    615:
                    616: #define ORDERKEY_PCTCPU \
1.83      millert   617:        if ((result = (int)(p2->p_pctcpu - p1->p_pctcpu)) == 0)
1.11      kstailey  618: #define ORDERKEY_CPUTIME \
1.37      millert   619:        if ((result = p2->p_rtime_sec - p1->p_rtime_sec) == 0) \
                    620:                if ((result = p2->p_rtime_usec - p1->p_rtime_usec) == 0)
1.11      kstailey  621: #define ORDERKEY_STATE \
1.37      millert   622:        if ((result = sorted_state[(unsigned char)p2->p_stat] - \
                    623:            sorted_state[(unsigned char)p1->p_stat])  == 0)
1.11      kstailey  624: #define ORDERKEY_PRIO \
1.37      millert   625:        if ((result = p2->p_priority - p1->p_priority) == 0)
1.11      kstailey  626: #define ORDERKEY_RSSIZE \
1.37      millert   627:        if ((result = p2->p_vm_rssize - p1->p_vm_rssize) == 0)
1.11      kstailey  628: #define ORDERKEY_MEM \
                    629:        if ((result = PROCSIZE(p2) - PROCSIZE(p1)) == 0)
1.65      tedu      630: #define ORDERKEY_PID \
                    631:        if ((result = p1->p_pid - p2->p_pid) == 0)
                    632: #define ORDERKEY_CMD \
                    633:        if ((result = strcmp(p1->p_comm, p2->p_comm)) == 0)
1.11      kstailey  634:
1.96      kn        635: /* remove one level of indirection and set sort order */
                    636: #define SETORDER do { \
                    637:                if (rev_order) { \
1.98      kn        638:                        p1 = *(struct kinfo_proc **) v2; \
                    639:                        p2 = *(struct kinfo_proc **) v1; \
1.96      kn        640:                } else { \
1.98      kn        641:                        p1 = *(struct kinfo_proc **) v1; \
                    642:                        p2 = *(struct kinfo_proc **) v2; \
1.96      kn        643:                } \
                    644:        } while (0)
                    645:
1.11      kstailey  646: /* compare_cpu - the comparison function for sorting by cpu percentage */
1.36      deraadt   647: static int
1.29      pvalchev  648: compare_cpu(const void *v1, const void *v2)
1.11      kstailey  649: {
1.68      guenther  650:        struct kinfo_proc *p1, *p2;
1.20      deraadt   651:        int result;
                    652:
1.96      kn        653:        SETORDER;
1.20      deraadt   654:
                    655:        ORDERKEY_PCTCPU
1.30      deraadt   656:        ORDERKEY_CPUTIME
                    657:        ORDERKEY_STATE
                    658:        ORDERKEY_PRIO
                    659:        ORDERKEY_RSSIZE
                    660:        ORDERKEY_MEM
                    661:                ;
1.20      deraadt   662:        return (result);
1.11      kstailey  663: }
                    664:
                    665: /* compare_size - the comparison function for sorting by total memory usage */
1.36      deraadt   666: static int
1.29      pvalchev  667: compare_size(const void *v1, const void *v2)
1.11      kstailey  668: {
1.68      guenther  669:        struct kinfo_proc *p1, *p2;
1.20      deraadt   670:        int result;
                    671:
1.96      kn        672:        SETORDER;
1.20      deraadt   673:
                    674:        ORDERKEY_MEM
1.30      deraadt   675:        ORDERKEY_RSSIZE
                    676:        ORDERKEY_PCTCPU
                    677:        ORDERKEY_CPUTIME
                    678:        ORDERKEY_STATE
                    679:        ORDERKEY_PRIO
                    680:                ;
1.20      deraadt   681:        return (result);
1.11      kstailey  682: }
                    683:
                    684: /* compare_res - the comparison function for sorting by resident set size */
1.36      deraadt   685: static int
1.29      pvalchev  686: compare_res(const void *v1, const void *v2)
1.11      kstailey  687: {
1.68      guenther  688:        struct kinfo_proc *p1, *p2;
1.20      deraadt   689:        int result;
                    690:
1.96      kn        691:        SETORDER;
1.20      deraadt   692:
                    693:        ORDERKEY_RSSIZE
1.30      deraadt   694:        ORDERKEY_MEM
                    695:        ORDERKEY_PCTCPU
                    696:        ORDERKEY_CPUTIME
                    697:        ORDERKEY_STATE
                    698:        ORDERKEY_PRIO
                    699:                ;
1.20      deraadt   700:        return (result);
1.11      kstailey  701: }
                    702:
                    703: /* compare_time - the comparison function for sorting by CPU time */
1.36      deraadt   704: static int
1.29      pvalchev  705: compare_time(const void *v1, const void *v2)
1.11      kstailey  706: {
1.68      guenther  707:        struct kinfo_proc *p1, *p2;
1.20      deraadt   708:        int result;
                    709:
1.96      kn        710:        SETORDER;
1.20      deraadt   711:
                    712:        ORDERKEY_CPUTIME
1.30      deraadt   713:        ORDERKEY_PCTCPU
                    714:        ORDERKEY_STATE
                    715:        ORDERKEY_PRIO
                    716:        ORDERKEY_MEM
                    717:        ORDERKEY_RSSIZE
                    718:                ;
1.20      deraadt   719:        return (result);
1.11      kstailey  720: }
                    721:
                    722: /* compare_prio - the comparison function for sorting by CPU time */
1.36      deraadt   723: static int
1.29      pvalchev  724: compare_prio(const void *v1, const void *v2)
1.11      kstailey  725: {
1.68      guenther  726:        struct kinfo_proc *p1, *p2;
1.20      deraadt   727:        int result;
                    728:
1.96      kn        729:        SETORDER;
1.20      deraadt   730:
                    731:        ORDERKEY_PRIO
1.30      deraadt   732:        ORDERKEY_PCTCPU
                    733:        ORDERKEY_CPUTIME
                    734:        ORDERKEY_STATE
                    735:        ORDERKEY_RSSIZE
                    736:        ORDERKEY_MEM
                    737:                ;
1.20      deraadt   738:        return (result);
                    739: }
                    740:
1.65      tedu      741: static int
                    742: compare_pid(const void *v1, const void *v2)
                    743: {
1.68      guenther  744:        struct kinfo_proc *p1, *p2;
1.65      tedu      745:        int result;
                    746:
1.96      kn        747:        SETORDER;
1.65      tedu      748:
                    749:        ORDERKEY_PID
                    750:        ORDERKEY_PCTCPU
                    751:        ORDERKEY_CPUTIME
                    752:        ORDERKEY_STATE
                    753:        ORDERKEY_PRIO
                    754:        ORDERKEY_RSSIZE
                    755:        ORDERKEY_MEM
                    756:                ;
                    757:        return (result);
                    758: }
                    759:
                    760: static int
                    761: compare_cmd(const void *v1, const void *v2)
                    762: {
1.68      guenther  763:        struct kinfo_proc *p1, *p2;
1.65      tedu      764:        int result;
                    765:
1.96      kn        766:        SETORDER;
1.65      tedu      767:
                    768:        ORDERKEY_CMD
                    769:        ORDERKEY_PCTCPU
                    770:        ORDERKEY_CPUTIME
                    771:        ORDERKEY_STATE
                    772:        ORDERKEY_PRIO
                    773:        ORDERKEY_RSSIZE
                    774:        ORDERKEY_MEM
                    775:                ;
                    776:        return (result);
                    777: }
                    778:
                    779:
1.31      deraadt   780: int (*proc_compares[])(const void *, const void *) = {
1.20      deraadt   781:        compare_cpu,
                    782:        compare_size,
                    783:        compare_res,
                    784:        compare_time,
                    785:        compare_prio,
1.65      tedu      786:        compare_pid,
                    787:        compare_cmd,
1.20      deraadt   788:        NULL
1.11      kstailey  789: };
1.30      deraadt   790:
1.1       downsj    791: /*
                    792:  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
                    793:  *             the process does not exist.
1.43      otto      794:  *             It is EXTREMELY IMPORTANT that this function work correctly.
1.1       downsj    795:  *             If top runs setuid root (as in SVR4), then this function
                    796:  *             is the only thing that stands in the way of a serious
                    797:  *             security problem.  It validates requests for the "kill"
                    798:  *             and "renice" commands.
                    799:  */
1.33      millert   800: uid_t
1.29      pvalchev  801: proc_owner(pid_t pid)
1.20      deraadt   802: {
1.68      guenther  803:        struct kinfo_proc **prefp, *pp;
1.20      deraadt   804:        int cnt;
                    805:
                    806:        prefp = pref;
                    807:        cnt = pref_len;
                    808:        while (--cnt >= 0) {
                    809:                pp = *prefp++;
1.37      millert   810:                if (pp->p_pid == pid)
                    811:                        return ((uid_t)pp->p_ruid);
1.1       downsj    812:        }
1.34      jfb       813:        return (uid_t)(-1);
1.1       downsj    814: }
1.30      deraadt   815:
1.1       downsj    816: /*
1.17      todd      817:  * swapmode is rewritten by Tobias Weingartner <weingart@openbsd.org>
1.15      weingart  818:  * to be based on the new swapctl(2) system call.
1.1       downsj    819:  */
                    820: static int
1.29      pvalchev  821: swapmode(int *used, int *total)
1.1       downsj    822: {
1.15      weingart  823:        struct swapent *swdev;
1.30      deraadt   824:        int nswap, rnswap, i;
1.1       downsj    825:
1.15      weingart  826:        nswap = swapctl(SWAP_NSWAP, 0, 0);
1.20      deraadt   827:        if (nswap == 0)
1.15      weingart  828:                return 0;
                    829:
1.62      deraadt   830:        swdev = calloc(nswap, sizeof(*swdev));
1.20      deraadt   831:        if (swdev == NULL)
1.15      weingart  832:                return 0;
                    833:
                    834:        rnswap = swapctl(SWAP_STATS, swdev, nswap);
1.53      ray       835:        if (rnswap == -1) {
                    836:                free(swdev);
1.15      weingart  837:                return 0;
1.53      ray       838:        }
1.15      weingart  839:
                    840:        /* if rnswap != nswap, then what? */
                    841:
                    842:        /* Total things up */
                    843:        *total = *used = 0;
                    844:        for (i = 0; i < nswap; i++) {
                    845:                if (swdev[i].se_flags & SWF_ENABLE) {
1.20      deraadt   846:                        *used += (swdev[i].se_inuse / (1024 / DEV_BSIZE));
                    847:                        *total += (swdev[i].se_nblks / (1024 / DEV_BSIZE));
1.1       downsj    848:                }
                    849:        }
1.20      deraadt   850:        free(swdev);
1.1       downsj    851:        return 1;
                    852: }