home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / UNIX / Utilities / top-0.5-MI / machine / m_ultrix4.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-09-13  |  19.1 KB  |  813 lines

  1. /*
  2.  * top - a top users display for Unix
  3.  *
  4.  * SYNOPSIS:  any DEC running ULTRIX V4.2 or later
  5.  *
  6.  * DESCRIPTION:
  7.  * This is the machine-dependent module for ULTRIX V4.x
  8.  * It should work on any DEC (mips or VAX) running V4.0 or later.
  9.  *
  10.  * LIBS: 
  11.  *
  12.  * AUTHOR:  David S. Comay <dsc@seismo.css.gov>
  13.  * patches: Alex A. Sergejew <aas@swin.oz.au>
  14.  */
  15.  
  16. #include <sys/types.h>
  17. #include <sys/signal.h>
  18. #include <sys/param.h>
  19.  
  20. #include <stdio.h>
  21. #include <nlist.h>
  22. #include <math.h>
  23. #include <sys/dir.h>
  24. #include <sys/user.h>
  25. #include <sys/proc.h>
  26. #include <sys/dk.h>
  27. #include <sys/vm.h>
  28. #include <sys/file.h>
  29. #include <sys/time.h>
  30. #include <machine/pte.h>
  31. #ifdef _SIZE_T_
  32. #include <sys/cpudata.h>
  33. #endif
  34.  
  35. /* #define DOSWAP */
  36.  
  37. #include "top.h"
  38. #include "machine.h"
  39.  
  40. extern int errno, sys_nerr;
  41. extern char *sys_errlist[];
  42. #define strerror(e) (((e) >= 0 && (e) < sys_nerr) ? sys_errlist[(e)] : "Unknown error")
  43.  
  44. #define VMUNIX    "/vmunix"
  45. #define KMEM    "/dev/kmem"
  46. #define MEM    "/dev/mem"
  47. #ifdef DOSWAP
  48. #define SWAP    "/dev/drum"
  49. #endif
  50.  
  51. /* get_process_info passes back a handle.  This is what it looks like: */
  52.  
  53. struct handle
  54. {
  55.     struct proc **next_proc;    /* points to next valid proc pointer */
  56.     int remaining;        /* number of pointers remaining */
  57. };
  58.  
  59. /* declarations for load_avg */
  60. #include "loadavg.h"
  61.  
  62. /* define what weighted cpu is.  */
  63. #define weighted_cpu(pct, pp) ((pp)->p_time == 0 ? 0.0 : \
  64.              ((pct) / (1.0 - exp((pp)->p_time * logcpu))))
  65.  
  66. /* what we consider to be process size: */
  67. #define PROCSIZE(pp) ((pp)->p_tsize + (pp)->p_dsize + (pp)->p_ssize)
  68.  
  69. /* definitions for indices in the nlist array */
  70. #define X_AVENRUN    0
  71. #define X_CCPU        1
  72. #define X_NPROC        2
  73. #define X_PROC        3
  74. #define X_TOTAL        4
  75. #define X_CPUDATA    5
  76. #define X_MPID        6
  77. #define X_HZ        7
  78. #define X_LOWCPU    8
  79. #define X_HIGHCPU    9
  80.  
  81. static struct nlist nlst[] = {
  82.     { "_avenrun" },        /* 0 */
  83.     { "_ccpu" },        /* 1 */
  84.     { "_nproc" },        /* 2 */
  85.     { "_proc" },        /* 3 */
  86.     { "_total" },        /* 4 */
  87.     { "_cpudata" },        /* 5 */
  88.     { "_mpid" },        /* 6 */
  89.     { "_hz" },            /* 7 */
  90.     { "_lowcpu" },        /* 8 */
  91.     { "_highcpu" },        /* 9 */
  92.     { 0 }
  93. };
  94.  
  95. /*
  96.  *  These definitions control the format of the per-process area
  97.  */
  98.  
  99. static char header[] =
  100.   "  PID X        PRI NICE   SIZE   RES STATE   TIME   WCPU    CPU COMMAND";
  101. /* 0123456   -- field to fill in starts at header+6 */
  102. #define UNAME_START 6
  103.  
  104. #define Proc_format \
  105.     "%5d %-8.8s %3d %4d%6dK %4dK %-5s%4d:%02d %5.2f%% %5.2f%% %.16s"
  106.  
  107.  
  108. /* process state names for the "STATE" column of the display */
  109. /* the extra nulls in the string "run" are for adding a slash and
  110.    the processor number when needed */
  111.  
  112. char *state_abbrev[] =
  113. {
  114.     "", "sleep", "WAIT", "run\0\0\0", "start", "zomb", "stop"
  115. };
  116.  
  117.  
  118. static int kmem, mem;
  119. #ifdef DOSWAP
  120. static int swap;
  121. #endif
  122.  
  123. /* values that we stash away in _init and use in later routines */
  124.  
  125. static double logcpu;
  126.  
  127. /* these are retrieved from the kernel in _init */
  128.  
  129. static unsigned long proc;
  130. static          int  nproc;
  131. static          long hz;
  132. static load_avg  ccpu;
  133. static          int  lowcpu = 0;
  134. static          int  highcpu = 0;
  135.  
  136. /* these are offsets obtained via nlist and used in the get_ functions */
  137.  
  138. static unsigned long avenrun_offset;
  139. static unsigned long mpid_offset;
  140. static unsigned long total_offset;
  141. static unsigned long cpudata_offset;
  142.  
  143. /* these are for calculating cpu state percentages */
  144.  
  145. static long cp_time[CPUSTATES];
  146. static long cp_old[CPUSTATES];
  147. static long cp_diff[CPUSTATES];
  148. static struct cpudata *cpudata[MAXCPU];
  149.  
  150. /* these are for detailing the process states */
  151.  
  152. int process_states[7];
  153. char *procstatenames[] = {
  154.     "", " sleeping, ", " ABANDONED, ", " running, ", " starting, ",
  155.     " zombie, ", " stopped, ",
  156.     NULL
  157. };
  158.  
  159. /* these are for detailing the cpu states */
  160.  
  161. int cpu_states[4];
  162. char *cpustatenames[] = {
  163.     "user", "nice", "system", "idle", NULL
  164. };
  165.  
  166. /* these are for detailing the memory statistics */
  167.  
  168. int memory_stats[8];
  169. char *memorynames[] = {
  170.     "Real: ", "K/", "K act/tot  ", "Virtual: ", "K/",
  171.     "K act/tot  ", "Free: ", "K", NULL
  172. };
  173.  
  174. /* these are for keeping track of the proc array */
  175.  
  176. static int bytes;
  177. static int pref_len;
  178. static struct proc *pbase;
  179. static struct proc **pref;
  180.  
  181. /* these are for getting the memory statistics */
  182.  
  183. static int pageshift;        /* log base 2 of the pagesize */
  184.  
  185. /* define pagetok in terms of pageshift */
  186.  
  187. #define pagetok(size) ((size) << pageshift)
  188.  
  189. /* useful externals */
  190. extern int errno;
  191. extern char *sys_errlist[];
  192.  
  193. long lseek();
  194. long percentages();
  195.  
  196. machine_init(statics)
  197.  
  198. struct statics *statics;
  199.  
  200. {
  201.     register int i = 0;
  202.     register int pagesize;
  203.  
  204.     if ((kmem = open(KMEM, O_RDONLY)) == -1) {
  205.     perror(KMEM);
  206.     return(-1);
  207.     }
  208.     if ((mem = open(MEM, O_RDONLY)) == -1) {
  209.     perror(MEM);
  210.     return(-1);
  211.     }
  212.  
  213. #ifdef DOSWAP
  214.     if ((swap = open(SWAP, O_RDONLY)) == -1) {
  215.     perror(SWAP);
  216.     return(-1);
  217.     }
  218. #endif
  219.  
  220.     /* get the list of symbols we want to access in the kernel */
  221.     (void) nlist(VMUNIX, nlst);
  222.     if (nlst[0].n_type == 0)
  223.     {
  224.     fprintf(stderr, "top: nlist failed\n");
  225.     return(-1);
  226.     }
  227.  
  228.     /* make sure they were all found */
  229.     if (i > 0 && check_nlist(nlst) > 0)
  230.     {
  231.     return(-1);
  232.     }
  233.  
  234.     /* get the symbol values out of kmem */
  235.     (void) getkval(nlst[X_PROC].n_value,   (int *)(&proc),    sizeof(proc),
  236.         nlst[X_PROC].n_name);
  237.     (void) getkval(nlst[X_NPROC].n_value,  &nproc,        sizeof(nproc),
  238.         nlst[X_NPROC].n_name);
  239.     (void) getkval(nlst[X_HZ].n_value,     (int *)(&hz),    sizeof(hz),
  240.         nlst[X_HZ].n_name);
  241.     (void) getkval(nlst[X_CCPU].n_value,   (int *)(&ccpu),    sizeof(ccpu),
  242.         nlst[X_CCPU].n_name);
  243.     (void) getkval(nlst[X_LOWCPU].n_value,   (int *)(&lowcpu),    sizeof(lowcpu),
  244.         nlst[X_LOWCPU].n_name);
  245.     (void) getkval(nlst[X_HIGHCPU].n_value,   (int *)(&highcpu),    sizeof(highcpu),
  246.         nlst[X_HIGHCPU].n_name);
  247.  
  248.     /* stash away certain offsets for later use */
  249.     mpid_offset = nlst[X_MPID].n_value;
  250.     avenrun_offset = nlst[X_AVENRUN].n_value;
  251.     total_offset = nlst[X_TOTAL].n_value;
  252.     cpudata_offset = nlst[X_CPUDATA].n_value;
  253.  
  254.     /* this is used in calculating WCPU -- calculate it ahead of time */
  255.     logcpu = log(loaddouble(ccpu));
  256.  
  257.     /* allocate space for proc structure array and array of pointers */
  258.     bytes = nproc * sizeof(struct proc);
  259.     pbase = (struct proc *)malloc(bytes);
  260.     pref  = (struct proc **)malloc(nproc * sizeof(struct proc *));
  261.  
  262.     /* Just in case ... */
  263.     if (pbase == (struct proc *)NULL || pref == (struct proc **)NULL)
  264.     {
  265.     fprintf(stderr, "top: can't allocate sufficient memory\n");
  266.     return(-1);
  267.     }
  268.  
  269.     /* get the page size with "getpagesize" and calculate pageshift from it */
  270.     pagesize = getpagesize();
  271.     pageshift = 0;
  272.     while (pagesize > 1)
  273.     {
  274.     pageshift++;
  275.     pagesize >>= 1;
  276.     }
  277.  
  278.     /* we only need the amount of log(2)1024 for our conversion */
  279.     pageshift -= LOG1024;
  280.  
  281.     /* fill in the statics information */
  282.     statics->procstate_names = procstatenames;
  283.     statics->cpustate_names = cpustatenames;
  284.     statics->memory_names = memorynames;
  285.  
  286.     /* all done! */
  287.     return(0);
  288. }
  289.  
  290. char *format_header(uname_field)
  291.  
  292. register char *uname_field;
  293.  
  294. {
  295.     register char *ptr;
  296.  
  297.     ptr = header + UNAME_START;
  298.     while (*uname_field != '\0')
  299.     {
  300.     *ptr++ = *uname_field++;
  301.     }
  302.  
  303.     return(header);
  304. }
  305.  
  306. get_system_info(si)
  307.  
  308. struct system_info *si;
  309.  
  310. {
  311.     load_avg avenrun[3];
  312.     long total;
  313.     register int i;
  314.     register int ncpu;
  315.     register struct cpudata cpu;
  316.  
  317.     for (i = 0; i < CPUSTATES; ++i)
  318.     {
  319.         cp_time[i] = 0;
  320.     }
  321.     (void) getkval(cpudata_offset, cpudata, sizeof(cpudata), "_cpudata");
  322.     for (ncpu = lowcpu; ncpu <= highcpu; ++ncpu)
  323.     {
  324.     if (cpudata[ncpu] != NULL) {
  325.         (void) getkval(cpudata[ncpu], &cpu, sizeof(cpu), "???");
  326.         if (cpu.cpu_state & CPU_RUN)
  327.         {
  328.             for (i = 0; i < CPUSTATES; ++i)
  329.             {
  330.             cp_time[i] += cpu.cpu_cptime[i];
  331.             }
  332.         }
  333.     }
  334.     }
  335.  
  336.     /* get load average array */
  337.     (void) getkval(avenrun_offset, (int *)avenrun, sizeof(avenrun),
  338.            "_avenrun");
  339.  
  340.     /* get mpid -- process id of last process */
  341.     (void) getkval(mpid_offset, &(si->last_pid), sizeof(si->last_pid),
  342.            "_mpid");
  343.  
  344.     /* convert load averages to doubles */
  345.     {
  346.     register int i;
  347.     register double *infoloadp;
  348.     register load_avg *sysloadp;
  349.  
  350.     infoloadp = si->load_avg;
  351.     sysloadp = avenrun;
  352.     for (i = 0; i < 3; i++)
  353.     {
  354.         *infoloadp++ = loaddouble(*sysloadp++);
  355.     }
  356.     }
  357.  
  358.     /* convert cp_time counts to percentages */
  359.     total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
  360.  
  361.     /* sum memory statistics */
  362.     {
  363.     struct vmtotal total;
  364.  
  365.     /* get total -- systemwide main memory usage structure */
  366.     (void) getkval(total_offset, (int *)(&total), sizeof(total),
  367.                "_total");
  368.     /* convert memory stats to Kbytes */
  369.     memory_stats[0] = -1;
  370.     memory_stats[1] = pagetok(total.t_arm);
  371.     memory_stats[2] = pagetok(total.t_rm);
  372.     memory_stats[3] = -1;
  373.     memory_stats[4] = pagetok(total.t_avm);
  374.     memory_stats[5] = pagetok(total.t_vm);
  375.     memory_stats[6] = -1;
  376.     memory_stats[7] = pagetok(total.t_free);
  377.     }
  378.  
  379.     /* set arrays and strings */
  380.     si->cpustates = cpu_states;
  381.     si->memory = memory_stats;
  382. }
  383.  
  384. static struct handle handle;
  385.  
  386. caddr_t get_process_info(si, sel, compare)
  387.  
  388. struct system_info *si;
  389. struct process_select *sel;
  390. int (*compare)();
  391.  
  392. {
  393.     register int i;
  394.     register int total_procs;
  395.     register int active_procs;
  396.     register struct proc **prefp;
  397.     register struct proc *pp;
  398.  
  399.     /* these are copied out of sel for speed */
  400.     int show_idle;
  401.     int show_system;
  402.     int show_uid;
  403.     int show_command;
  404.  
  405.     /* read all the proc structures in one fell swoop */
  406.     (void) getkval(proc, (int *)pbase, bytes, "proc array");
  407.  
  408.     /* get a pointer to the states summary array */
  409.     si->procstates = process_states;
  410.  
  411.     /* set up flags which define what we are going to select */
  412.     show_idle = sel->idle;
  413.     show_system = sel->system;
  414.     show_uid = sel->uid != -1;
  415.     show_command = sel->command != NULL;
  416.  
  417.     /* count up process states and get pointers to interesting procs */
  418.     total_procs = 0;
  419.     active_procs = 0;
  420.     memset((char *)process_states, 0, sizeof(process_states));
  421.     prefp = pref;
  422.     for (pp = pbase, i = 0; i < nproc; pp++, i++)
  423.     {
  424.     /*
  425.      *  Place pointers to each valid proc structure in pref[].
  426.      *  Process slots that are actually in use have a non-zero
  427.      *  status field.  Processes with SSYS set are system
  428.      *  processes---these get ignored unless show_sysprocs is set.
  429.      */
  430.     if (pp->p_stat != 0 && pp->p_stat != SIDL &&
  431.         (show_system || ((pp->p_type & SSYS) == 0)))
  432.     {
  433.         total_procs++;
  434.         process_states[pp->p_stat]++;
  435.         if ((pp->p_stat != SZOMB) &&
  436.         (pp->p_stat != SIDL) &&
  437. #ifdef vax
  438.         (show_idle || (pp->p_pctcpu != 0.0) || (pp->p_stat == SRUN)) &&
  439.         (!show_uid || pp->p_uid == (uid_t)sel->uid))
  440. #else
  441.           (show_idle || (pp->p_pctcpu != 0) || (pp->p_stat == SRUN)) &&
  442.           (!show_uid || pp->p_uid == (uid_t)sel->uid))
  443. #endif
  444.         {
  445.         *prefp++ = pp;
  446.         active_procs++;
  447.         }
  448.     }
  449.     }
  450.  
  451.     /* if requested, sort the "interesting" processes */
  452.     if (compare != NULL)
  453.     {
  454.     qsort((char *)pref, active_procs, sizeof(struct proc *), compare);
  455.     }
  456.  
  457.     /* remember active and total counts */
  458.     si->p_total = total_procs;
  459.     si->p_active = pref_len = active_procs;
  460.  
  461.     /* pass back a handle */
  462.     handle.next_proc = pref;
  463.     handle.remaining = active_procs;
  464.     return((caddr_t)&handle);
  465. }
  466.  
  467. char fmt[MAX_COLS];        /* static area where result is built */
  468.  
  469. char *format_next_process(handle, get_userid)
  470.  
  471. caddr_t handle;
  472. char *(*get_userid)();
  473.  
  474. {
  475.     register struct proc *pp;
  476.     register long cputime;
  477.     register double pct;
  478.     int where;
  479.     struct user u;
  480.     struct handle *hp;
  481.  
  482.     /* find and remember the next proc structure */
  483.     hp = (struct handle *)handle;
  484.     pp = *(hp->next_proc++);
  485.     hp->remaining--;
  486.     
  487.  
  488.     /* get the process's user struct and set cputime */
  489.     where = getu(pp, &u);
  490.     if (where == -1)
  491.     {
  492.     (void) strcpy(u.u_comm, "<swapped>");
  493.     cputime = 0;
  494.     }
  495.     else
  496.     {
  497.  
  498.       
  499.     /* set u_comm for system processes */
  500.     if (u.u_comm[0] == '\0')
  501.     {
  502.         if (pp->p_pid == 0)
  503.         {
  504.         (void) strcpy(u.u_comm, "Swapper");
  505.         }
  506.         else if (pp->p_pid == 2)
  507.         {
  508.         (void) strcpy(u.u_comm, "Pager");
  509.         }
  510.     }
  511.     if (where == 1) {
  512.         /*
  513.          * Print swapped processes as <pname>
  514.          */
  515.         char buf[sizeof(u.u_comm)];
  516.         (void) strncpy(buf, u.u_comm, sizeof(u.u_comm));
  517.         u.u_comm[0] = '<';
  518.         (void) strncpy(&u.u_comm[1], buf, sizeof(u.u_comm) - 2);
  519.         u.u_comm[sizeof(u.u_comm) - 2] = '\0';
  520.         (void) strncat(u.u_comm, ">", sizeof(u.u_comm) - 1);
  521.         u.u_comm[sizeof(u.u_comm) - 1] = '\0';
  522.     }
  523.  
  524.     cputime = u.u_ru.ru_utime.tv_sec + u.u_ru.ru_stime.tv_sec;
  525.     }
  526.  
  527.     /* calculate the base for cpu percentages */
  528.     pct = pctdouble(pp->p_pctcpu);
  529.  
  530.     /* format this entry */
  531.     sprintf(fmt,
  532.         Proc_format,
  533.         pp->p_pid,
  534.         (*get_userid)(pp->p_uid),
  535.         pp->p_pri - PZERO,
  536.         pp->p_nice - NZERO,
  537.         pagetok(PROCSIZE(pp)),
  538.         pagetok(pp->p_rssize),
  539.         state_abbrev[pp->p_stat],
  540.         cputime / 60l,
  541.         cputime % 60l,
  542.         100.0 * weighted_cpu(pct, pp),
  543.         100.0 * pct,
  544.         printable(u.u_comm));
  545.  
  546.     /* return the result */
  547.     return(fmt);
  548. }
  549.  
  550. /*
  551.  *  getu(p, u) - get the user structure for the process whose proc structure
  552.  *    is pointed to by p.  The user structure is put in the buffer pointed
  553.  *    to by u.  Return 0 if successful, -1 on failure (such as the process
  554.  *    being swapped out).
  555.  */
  556.  
  557. #ifdef ibm032
  558. static struct alignuser {
  559.     char userfill[UPAGES*NBPG-sizeof (struct user)];
  560.     struct user user;
  561. } au;
  562. # define USERSIZE sizeof(struct alignuser)
  563. # define GETUSER(b)    (&au)
  564. # define SETUSER(b)    *(b) = au.user
  565. #else
  566. # define USERSIZE sizeof(struct user)
  567. # define GETUSER(b)    (b)
  568. # define SETUSER(b)    /* Nothing */
  569. #endif
  570.  
  571. getu(p, u)
  572.  
  573. register struct proc *p;
  574. struct user *u;
  575.  
  576. {
  577.     struct pte uptes[UPAGES];
  578.     register caddr_t upage;
  579.     register struct pte *pte;
  580.     register nbytes, n;
  581.  
  582.     /*
  583.      *  Check if the process is currently loaded or swapped out.  The way we
  584.      *  get the u area is totally different for the two cases.  For this
  585.      *  application, we just don't bother if the process is swapped out.
  586.      */
  587.     if ((p->p_sched & SLOAD) == 0) {
  588. #ifdef DOSWAP
  589.     if (lseek(swap, (long)dtob(p->p_swaddr), 0) == -1) {
  590.         perror("lseek(swap)");
  591.         return(-1);
  592.     }
  593.     if (read(swap, (char *) GETUSER(u), USERSIZE) != USERSIZE)  {
  594.         perror("read(swap)");
  595.         return(-1);
  596.     }
  597.     SETUSER(u);
  598.     return (1);
  599. #else
  600.     return(-1);
  601. #endif
  602.     }
  603.  
  604.     /*
  605.      *  Process is currently in memory, we hope!
  606.      */
  607.     if (!getkval((unsigned long)p->p_addr, (int *)uptes, sizeof(uptes),
  608.                 "!p->p_addr"))
  609.     {
  610. #ifdef DEBUG
  611.     perror("getkval(uptes)");
  612. #endif
  613.     /* we can't seem to get to it, so pretend it's swapped out */
  614.     return(-1);
  615.     } 
  616.     upage = (caddr_t) GETUSER(u);
  617.     pte = uptes;
  618.     for (nbytes = USERSIZE; nbytes > 0; nbytes -= NBPG) {
  619.         (void) lseek(mem, (long)(pte++->pg_pfnum * NBPG), 0);
  620. #ifdef DEBUG
  621.     perror("lseek(mem)");
  622. #endif
  623.     n = MIN(nbytes, NBPG);
  624.     if (read(mem, upage, n) != n) {
  625. #ifdef DEBUG
  626.     perror("read(mem)");
  627. #endif
  628.         /* we can't seem to get to it, so pretend it's swapped out */
  629.         return(-1);
  630.     }
  631.     upage += n;
  632.     }
  633.     SETUSER(u);
  634.     return(0);
  635. }
  636.  
  637. /*
  638.  * check_nlist(nlst) - checks the nlist to see if any symbols were not
  639.  *        found.  For every symbol that was not found, a one-line
  640.  *        message is printed to stderr.  The routine returns the
  641.  *        number of symbols NOT found.
  642.  */
  643.  
  644. int check_nlist(nlst)
  645.  
  646. register struct nlist *nlst;
  647.  
  648. {
  649.     register int i;
  650.  
  651.     /* check to see if we got ALL the symbols we requested */
  652.     /* this will write one line to stderr for every symbol not found */
  653.  
  654.     i = 0;
  655.     while (nlst->n_name != NULL)
  656.     {
  657.     if (nlst->n_type == 0)
  658.     {
  659.         /* this one wasn't found */
  660.         fprintf(stderr, "kernel: no symbol named `%s'\n", nlst->n_name);
  661.         i = 1;
  662.     }
  663.     nlst++;
  664.     }
  665.  
  666.     return(i);
  667. }
  668.  
  669.  
  670. /*
  671.  *  getkval(offset, ptr, size, refstr) - get a value out of the kernel.
  672.  *    "offset" is the byte offset into the kernel for the desired value,
  673.  *      "ptr" points to a buffer into which the value is retrieved,
  674.  *      "size" is the size of the buffer (and the object to retrieve),
  675.  *      "refstr" is a reference string used when printing error meessages,
  676.  *        if "refstr" starts with a '!', then a failure on read will not
  677.  *          be fatal (this may seem like a silly way to do things, but I
  678.  *          really didn't want the overhead of another argument).
  679.  *      
  680.  */
  681.  
  682. getkval(offset, ptr, size, refstr)
  683.  
  684. unsigned long offset;
  685. int *ptr;
  686. int size;
  687. char *refstr;
  688.  
  689. {
  690.     if (lseek(kmem, (long)offset, L_SET) == -1) {
  691.         if (*refstr == '!')
  692.             refstr++;
  693.         (void) fprintf(stderr, "%s: lseek to %s: %s\n", KMEM, 
  694.                refstr, strerror(errno));
  695.         quit(23);
  696.     }
  697.     if (read(kmem, (char *) ptr, size) == -1) {
  698.         if (*refstr == '!') 
  699.             return(0);
  700.         else {
  701.             (void) fprintf(stderr, "%s: reading %s: %s\n", KMEM, 
  702.                refstr, strerror(errno));
  703.             quit(23);
  704.         }
  705.     }
  706.     return(1);
  707. }
  708.     
  709. /* comparison routine for qsort */
  710.  
  711. /*
  712.  *  proc_compare - comparison function for "qsort"
  713.  *    Compares the resource consumption of two processes using five
  714.  *      distinct keys.  The keys (in descending order of importance) are:
  715.  *      percent cpu, cpu ticks, state, resident set size, total virtual
  716.  *      memory usage.  The process states are ordered as follows (from least
  717.  *      to most important):  WAIT, zombie, sleep, stop, start, run.  The
  718.  *      array declaration below maps a process state index into a number
  719.  *      that reflects this ordering.
  720.  */
  721.  
  722. static unsigned char sorted_state[] =
  723. {
  724.     0,    /* not used        */
  725.     3,    /* sleep        */
  726.     1,    /* ABANDONED (WAIT)    */
  727.     6,    /* run            */
  728.     5,    /* start        */
  729.     2,    /* zombie        */
  730.     4    /* stop            */
  731. };
  732.  
  733. proc_compare(pp1, pp2)
  734.  
  735. struct proc **pp1;
  736. struct proc **pp2;
  737.  
  738. {
  739.     register struct proc *p1;
  740.     register struct proc *p2;
  741.     register int result;
  742.     register pctcpu lresult;
  743.  
  744.     /* remove one level of indirection */
  745.     p1 = *pp1;
  746.     p2 = *pp2;
  747.  
  748.     /* compare percent cpu (pctcpu) */
  749. #ifdef vax
  750.     if ((lresult = p2->p_pctcpu - p1->p_pctcpu) == 0.0)
  751. #else
  752.     if ((lresult = p2->p_pctcpu - p1->p_pctcpu) == 0)
  753. #endif
  754.     {
  755.     /* use cpticks to break the tie */
  756.     if ((result = p2->p_cpticks - p1->p_cpticks) == 0)
  757.     {
  758.         /* use process state to break the tie */
  759.         if ((result = sorted_state[p2->p_stat] -
  760.               sorted_state[p1->p_stat])  == 0)
  761.         {
  762.         /* use priority to break the tie */
  763.         if ((result = p2->p_pri - p1->p_pri) == 0)
  764.         {
  765.             /* use resident set size (rssize) to break the tie */
  766.             if ((result = p2->p_rssize - p1->p_rssize) == 0)
  767.             {
  768.             /* use total memory to break the tie */
  769.             result = PROCSIZE(p2) - PROCSIZE(p1);
  770.             }
  771.         }
  772.         }
  773.     }
  774.     }
  775.     else
  776.     {
  777.     result = lresult < 0 ? -1 : 1;
  778.     }
  779.  
  780.     return(result);
  781. }
  782.  
  783. /*
  784.  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
  785.  *        the process does not exist.
  786.  *        It is EXTREMLY IMPORTANT that this function work correctly.
  787.  *        If top runs setuid root (as in SVR4), then this function
  788.  *        is the only thing that stands in the way of a serious
  789.  *        security problem.  It validates requests for the "kill"
  790.  *        and "renice" commands.
  791.  */
  792.  
  793. int proc_owner(pid)
  794.  
  795. int pid;
  796.  
  797. {
  798.     register int cnt;
  799.     register struct proc **prefp;
  800.     register struct proc *pp;
  801.  
  802.     prefp = pref;
  803.     cnt = pref_len;
  804.     while (--cnt >= 0)
  805.     {
  806.     if ((pp = *prefp++)->p_pid == (pid_t)pid)
  807.     {
  808.         return((int)pp->p_uid);
  809.     }
  810.     }
  811.     return(-1);
  812. }
  813.