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

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