home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / UNIX / Utilities / top-0.5-MI / machine / m_netbsd10.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-02-24  |  22.6 KB  |  940 lines

  1. /*
  2.  * top - a top users display for Unix
  3.  *
  4.  * SYNOPSIS:  For a NetBSD-1.0 (4.4BSD) system
  5.  *          Note process resident sizes could be wrong, but ps shows
  6.  *          zero for them too..
  7.  *
  8.  * DESCRIPTION:
  9.  * Originally written for BSD4.4 system by Christos Zoulas.
  10.  * Based on the FreeBSD 2.0 version by Steven Wallace && Wolfram Schneider
  11.  * NetBSD-1.0 port by Arne Helme
  12.  * .
  13.  * This is the machine-dependent module for NetBSD-1.0
  14.  * Works for:
  15.  *    NetBSD-1.0
  16.  *
  17.  * LIBS: -lkvm
  18.  *
  19.  * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
  20.  *          Steven Wallace  <swallace@freebsd.org>
  21.  *          Wolfram Schneider <wosch@cs.tu-berlin.de>
  22.  *        Arne Helme <arne@acm.org>
  23.  *
  24.  * $Id: machine.c,v 1.5 1995/01/06 02:04:39 swallace Exp $
  25.  */
  26.  
  27.  
  28.  
  29. #define LASTPID      /**/  /* use last pid, compiler depended */
  30. /* #define LASTPID_FIXED /**/ 
  31. #define VM_REAL      /**/  /* use the same values as vmstat -s */
  32. #define USE_SWAP     /**/  /* use swap usage (pstat -s), 
  33.                               need to much cpu time */
  34. /* #define DEBUG 1      /**/
  35.  
  36. #include <sys/types.h>
  37. #include <sys/signal.h>
  38. #include <sys/param.h>
  39.  
  40. #include "os.h"
  41. #include <stdio.h>
  42. #include <nlist.h>
  43. #include <math.h>
  44. #include <kvm.h>
  45. #include <sys/errno.h>
  46. #include <sys/sysctl.h>
  47. #include <sys/dir.h>
  48. #include <sys/dkstat.h>
  49. #include <sys/file.h>
  50. #include <sys/time.h>
  51.  
  52. #ifdef USE_SWAP
  53. #include <stdlib.h>
  54. #include <sys/map.h>
  55. #include <sys/conf.h>
  56. #endif
  57.  
  58. static int check_nlist __P((struct nlist *));
  59. static int getkval __P((unsigned long, int *, int, char *));
  60. extern char* printable __P((char *));
  61.  
  62. #include "top.h"
  63. #include "machine.h"
  64.  
  65.  
  66. /* get_process_info passes back a handle.  This is what it looks like: */
  67.  
  68. struct handle
  69. {
  70.     struct kinfo_proc **next_proc;    /* points to next valid proc pointer */
  71.     int remaining;        /* number of pointers remaining */
  72. };
  73.  
  74. /* declarations for load_avg */
  75. #include "loadavg.h"
  76.  
  77. #define PP(pp, field) ((pp)->kp_proc . field)
  78. #define EP(pp, field) ((pp)->kp_eproc . field)
  79. #define VP(pp, field) ((pp)->kp_eproc.e_vm . field)
  80.  
  81. /* define what weighted cpu is.  */
  82. #define weighted_cpu(pct, pp) (PP((pp), p_swtime) == 0 ? 0.0 : \
  83.              ((pct) / (1.0 - exp(PP((pp), p_swtime) * logcpu))))
  84.  
  85. /* what we consider to be process size: */
  86. #define PROCSIZE(pp) (VP((pp), vm_tsize) + VP((pp), vm_dsize) + VP((pp), vm_ssize))
  87.  
  88. /* definitions for indices in the nlist array */
  89.  
  90.  
  91. static struct nlist nlst[] = {
  92. #define X_CCPU        0
  93.     { "_ccpu" },        /* 0 */
  94. #define X_CP_TIME    1
  95.     { "_cp_time" },        /* 1 */
  96. #define X_HZ        2
  97.     { "_hz" },                /* 2 */
  98. #define X_STATHZ    3
  99.     { "_stathz" },        /* 3 */
  100. #define X_AVENRUN    4
  101.     { "_averunnable" },        /* 4 */
  102.  
  103. #ifdef USE_SWAP
  104. #define VM_SWAPMAP    5
  105.     { "_swapmap" },    /* list of free swap areas */
  106. #define VM_NSWAPMAP    6
  107.     { "_nswapmap" },/* size of the swap map */
  108. #define VM_SWDEVT    7
  109.     { "_swdevt" },    /* list of swap devices and sizes */
  110. #define VM_NSWAP    8
  111.     { "_nswap" },    /* size of largest swap device */
  112. #define VM_NSWDEV    9
  113.     { "_nswdev" },    /* number of swap devices */
  114. #define VM_DMMAX    10
  115.     { "_dmmax" },    /* maximum size of a swap block */
  116. #define VM_NISWAP    11
  117.     { "_niswap" },
  118. #define VM_NISWDEV    12
  119.     { "_niswdev" },
  120. #endif /* USE_SWAP */
  121.  
  122. #ifdef VM_REAL
  123. #ifdef USE_SWAP
  124. #define X_CNT           13
  125. #else
  126. #define X_CNT           5
  127. #endif
  128.     { "_cnt" },                /* struct vmmeter cnt */
  129. #endif
  130.  
  131. #ifdef LASTPID
  132. #if (defined USE_SWAP && defined VM_REAL)
  133. #define X_LASTPID    14
  134. #elif (defined VM_REAL)
  135. #define X_LASTPID    6
  136. #else
  137. #define X_LASTPID       5
  138. #endif
  139. #ifdef LASTPID_FIXED
  140.     { "_nextpid" },        
  141. #else
  142.     { "_nextpid.178" },        /* lastpid, compiler depended 
  143.                  * should be changed 
  144.                  * in /sys/kern/kern_fork.c */
  145. #endif
  146. #endif
  147.  
  148.     { 0 }
  149. };
  150.  
  151. /*
  152.  *  These definitions control the format of the per-process area
  153.  */
  154.  
  155. static char header[] =
  156.   "  PID X        PRI NICE   SIZE   RES STATE   TIME   WCPU    CPU COMMAND";
  157. /* 0123456   -- field to fill in starts at header+6 */
  158. #define UNAME_START 6
  159.  
  160. #define Proc_format \
  161.     "%5d %-8.8s %3d %4d%7s %5s %-5s%7s %5.2f%% %5.2f%% %.14s"
  162.  
  163.  
  164. /* process state names for the "STATE" column of the display */
  165. /* the extra nulls in the string "run" are for adding a slash and
  166.    the processor number when needed */
  167.  
  168. char *state_abbrev[] =
  169. {
  170.     "", "start", "run\0\0\0", "sleep", "stop", "zomb", "WAIT"
  171. };
  172.  
  173.  
  174. static kvm_t *kd;
  175.  
  176. /* values that we stash away in _init and use in later routines */
  177.  
  178. static double logcpu;
  179.  
  180. /* these are retrieved from the kernel in _init */
  181.  
  182. static          long hz;
  183. static load_avg  ccpu;
  184.  
  185. /* these are offsets obtained via nlist and used in the get_ functions */
  186.  
  187. static unsigned long cp_time_offset;
  188. static unsigned long avenrun_offset;
  189. #ifdef LASTPID
  190. static unsigned long lastpid_offset;
  191. static long lastpid;
  192. #endif
  193. #ifdef VM_REAL
  194. static unsigned long cnt_offset;
  195. static long cnt;
  196. #endif
  197. /* these are for calculating cpu state percentages */
  198.  
  199. static long cp_time[CPUSTATES];
  200. static long cp_old[CPUSTATES];
  201. static long cp_diff[CPUSTATES];
  202.  
  203. /* these are for detailing the process states */
  204.  
  205. int process_states[7];
  206. char *procstatenames[] = {
  207.     "", " starting, ", " running, ", " sleeping, ", " stopped, ",
  208.     " zombie, ", " ABANDONED, ",
  209.     NULL
  210. };
  211.  
  212. /* these are for detailing the cpu states */
  213.  
  214. int cpu_states[CPUSTATES];
  215. char *cpustatenames[] = {
  216.     "user", "nice", "system", "interrupt", "idle", NULL
  217. };
  218.  
  219. /* these are for detailing the memory statistics */
  220.  
  221. int memory_stats[8];
  222. char *memorynames[] = {
  223. #ifndef VM_REAL
  224.     "Real: ", "K/", "K ", "Virt: ", "K/",
  225.     "K ", "Free: ", "K", NULL
  226. #else
  227. #if 0
  228.     "K Act ", "K Inact ", "K Wired ", "K Free ", "% Swap, ",
  229.     "K/", "K SWIO", 
  230. #else
  231.     "K Act ", "K Inact ", "K Wired ", "K Free ", "% Swap, ",
  232.     "Kin ", "Kout", 
  233. #endif
  234.     NULL
  235. #endif
  236. };
  237.  
  238. /* these are for keeping track of the proc array */
  239.  
  240. static int nproc;
  241. static int onproc = -1;
  242. static int pref_len;
  243. static struct kinfo_proc *pbase;
  244. static struct kinfo_proc **pref;
  245.  
  246. /* these are for getting the memory statistics */
  247.  
  248. static int pageshift;        /* log base 2 of the pagesize */
  249.  
  250. /* define pagetok in terms of pageshift */
  251.  
  252. #define pagetok(size) ((size) << pageshift)
  253.  
  254. /* useful externals */
  255. long percentages();
  256.  
  257. int
  258. machine_init(statics)
  259.  
  260. struct statics *statics;
  261.  
  262. {
  263.     register int i = 0;
  264.     register int pagesize;
  265.  
  266.     if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) == NULL)
  267.     return -1;
  268.  
  269.  
  270.     /* get the list of symbols we want to access in the kernel */
  271.     (void) kvm_nlist(kd, nlst);
  272.     if (nlst[0].n_type == 0)
  273.     {
  274.     fprintf(stderr, "top: nlist failed\n");
  275.     return(-1);
  276.     }
  277.  
  278.     /* make sure they were all found */
  279.     if (i > 0 && check_nlist(nlst) > 0)
  280.     {
  281.     return(-1);
  282.     }
  283.  
  284.     /* get the symbol values out of kmem */
  285.     (void) getkval(nlst[X_STATHZ].n_value, (int *)(&hz), sizeof(hz), "!");
  286.     if (!hz) {
  287.     (void) getkval(nlst[X_HZ].n_value, (int *)(&hz), sizeof(hz),
  288.                nlst[X_HZ].n_name);
  289.     }
  290.  
  291.  
  292. #if (defined DEBUG)
  293.     fprintf(stderr, "Hertz: %d\n", hz); 
  294. #endif
  295.  
  296.     (void) getkval(nlst[X_CCPU].n_value,   (int *)(&ccpu),    sizeof(ccpu),
  297.         nlst[X_CCPU].n_name);
  298.  
  299.     /* stash away certain offsets for later use */
  300.     cp_time_offset = nlst[X_CP_TIME].n_value;
  301.     avenrun_offset = nlst[X_AVENRUN].n_value;
  302. #ifdef LASTPID
  303.     lastpid_offset =  nlst[X_LASTPID].n_value;
  304. #endif
  305. #ifdef VM_REAL
  306.     cnt_offset = nlst[X_CNT].n_value;
  307. #endif
  308.  
  309.     /* this is used in calculating WCPU -- calculate it ahead of time */
  310.     logcpu = log(loaddouble(ccpu));
  311.  
  312.     pbase = NULL;
  313.     pref = NULL;
  314.     nproc = 0;
  315.     onproc = -1;
  316.     /* get the page size with "getpagesize" and calculate pageshift from it */
  317.     pagesize = getpagesize();
  318.     pageshift = 0;
  319.     while (pagesize > 1)
  320.     {
  321.     pageshift++;
  322.     pagesize >>= 1;
  323.     }
  324.  
  325.     /* we only need the amount of log(2)1024 for our conversion */
  326.     pageshift -= LOG1024;
  327.  
  328.     /* fill in the statics information */
  329.     statics->procstate_names = procstatenames;
  330.     statics->cpustate_names = cpustatenames;
  331.     statics->memory_names = memorynames;
  332.  
  333.     /* all done! */
  334.     return(0);
  335. }
  336.  
  337. char *format_header(uname_field)
  338.  
  339. register char *uname_field;
  340.  
  341. {
  342.     register char *ptr;
  343.  
  344.     ptr = header + UNAME_START;
  345.     while (*uname_field != '\0')
  346.     {
  347.     *ptr++ = *uname_field++;
  348.     }
  349.  
  350.     return(header);
  351. }
  352.  
  353. static int swappgsin = -1;
  354. static int swappgsout = -1;
  355. extern struct timeval timeout;
  356.  
  357. void
  358. get_system_info(si)
  359.  
  360. struct system_info *si;
  361.  
  362. {
  363.     long total;
  364.     load_avg avenrun[3];
  365.  
  366.     /* get the cp_time array */
  367.     (void) getkval(cp_time_offset, (int *)cp_time, sizeof(cp_time),
  368.            nlst[X_CP_TIME].n_name);
  369.     (void) getkval(avenrun_offset, (int *)avenrun, sizeof(avenrun),
  370.            nlst[X_AVENRUN].n_name);
  371.  
  372. #ifdef LASTPID
  373.     (void) getkval(lastpid_offset, (int *)(&lastpid), sizeof(lastpid),
  374.            "!");
  375. #endif
  376.  
  377.     /* convert load averages to doubles */
  378.     {
  379.     register int i;
  380.     register double *infoloadp;
  381.     load_avg *avenrunp;
  382.  
  383. #ifdef notyet
  384.     struct loadavg sysload;
  385.     int size;
  386.     getkerninfo(KINFO_LOADAVG, &sysload, &size, 0);
  387. #endif
  388.  
  389.     infoloadp = si->load_avg;
  390.     avenrunp = avenrun;
  391.     for (i = 0; i < 3; i++)
  392.     {
  393. #ifdef notyet
  394.         *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
  395. #endif
  396.         *infoloadp++ = loaddouble(*avenrunp++);
  397.     }
  398.     }
  399.  
  400.     /* convert cp_time counts to percentages */
  401.     total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
  402.  
  403.     /* sum memory statistics */
  404.     {
  405.  
  406. #ifndef VM_REAL
  407.     struct vmtotal total;
  408.     int size = sizeof(total);
  409.     static int mib[] = { CTL_VM, VM_METER };
  410.  
  411.     /* get total -- systemwide main memory usage structure */
  412.     if (sysctl(mib, 2, &total, &size, NULL, 0) < 0) {
  413.         (void) fprintf(stderr, "top: sysctl failed: %s\n", strerror(errno));
  414.         bzero(&total, sizeof(total));
  415.     }
  416.     /* convert memory stats to Kbytes */
  417.     memory_stats[0] = -1;
  418.     memory_stats[1] = pagetok(total.t_arm);
  419.     memory_stats[2] = pagetok(total.t_rm);
  420.     memory_stats[3] = -1;
  421.     memory_stats[4] = pagetok(total.t_avm);
  422.     memory_stats[5] = pagetok(total.t_vm);
  423.     memory_stats[6] = -1;
  424.     memory_stats[7] = pagetok(total.t_free);
  425.     }
  426. #else
  427.     struct vmmeter sum;
  428.     static unsigned int swap_delay = 0;
  429.  
  430.         (void) getkval(cnt_offset, (int *)(&sum), sizeof(sum),
  431.            "_cnt");
  432.  
  433.     /* convert memory stats to Kbytes */
  434.     memory_stats[0] = pagetok(sum.v_active_count);
  435.     memory_stats[1] = pagetok(sum.v_inactive_count);
  436.     memory_stats[2] = pagetok(sum.v_wire_count);
  437.     memory_stats[3] = pagetok(sum.v_free_count);
  438.  
  439.         if (swappgsin < 0) {
  440.         memory_stats[5] = 0;
  441.         memory_stats[6] = 0;
  442.     } else {
  443.         memory_stats[5] = pagetok(((sum.v_pswpin - swappgsin)));
  444.         memory_stats[6] = pagetok(((sum.v_pswpout - swappgsout)));
  445.     }
  446.         swappgsin = sum.v_pswpin;
  447.     swappgsout = sum.v_pswpout;
  448.  
  449. #ifdef USE_SWAP
  450.         if ((memory_stats[5] > 0 || memory_stats[6]) > 0 || swap_delay == 0) {
  451.         memory_stats[4] = swapmode();
  452.     }
  453.         /* swap_delay++; XXX Arne */
  454. #else
  455.         memory_stats[4] = 0;
  456. #endif
  457.  
  458.  
  459.     memory_stats[7] = -1;
  460.     }
  461. #endif
  462.     /* set arrays and strings */
  463.     si->cpustates = cpu_states;
  464.     si->memory = memory_stats;
  465. #ifdef LASTPID
  466.     if(lastpid > 0) {
  467.     si->last_pid = lastpid;
  468.     } else {
  469.     si->last_pid = -1;
  470.     }
  471. #else
  472.     si->last_pid = -1;
  473. #endif
  474.  
  475. }
  476.  
  477. static struct handle handle;
  478.  
  479. caddr_t get_process_info(si, sel, compare)
  480.  
  481. struct system_info *si;
  482. struct process_select *sel;
  483. int (*compare)();
  484.  
  485. {
  486.     register int i;
  487.     register int total_procs;
  488.     register int active_procs;
  489.     register struct kinfo_proc **prefp;
  490.     register struct kinfo_proc *pp;
  491.  
  492.     /* these are copied out of sel for speed */
  493.     int show_idle;
  494.     int show_system;
  495.     int show_uid;
  496.     int show_command;
  497.  
  498.     
  499.     pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
  500.     if (nproc > onproc)
  501.     pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
  502.         * (onproc = nproc));
  503.     if (pref == NULL || pbase == NULL) {
  504.     (void) fprintf(stderr, "top: Out of memory.\n");
  505.     quit(23);
  506.     }
  507.     /* get a pointer to the states summary array */
  508.     si->procstates = process_states;
  509.  
  510.     /* set up flags which define what we are going to select */
  511.     show_idle = sel->idle;
  512.     show_system = sel->system;
  513.     show_uid = sel->uid != -1;
  514.     show_command = sel->command != NULL;
  515.  
  516.     /* count up process states and get pointers to interesting procs */
  517.     total_procs = 0;
  518.     active_procs = 0;
  519.     memset((char *)process_states, 0, sizeof(process_states));
  520.     prefp = pref;
  521.     for (pp = pbase, i = 0; i < nproc; pp++, i++)
  522.     {
  523.     /*
  524.      *  Place pointers to each valid proc structure in pref[].
  525.      *  Process slots that are actually in use have a non-zero
  526.      *  status field.  Processes with P_SYSTEM set are system
  527.      *  processes---these get ignored unless show_sysprocs is set.
  528.      */
  529.     if (PP(pp, p_stat) != 0 &&
  530.         (show_system || ((PP(pp, p_flag) & P_SYSTEM) == 0)))
  531.     {
  532.         total_procs++;
  533.         process_states[(unsigned char) PP(pp, p_stat)]++;
  534.         if ((PP(pp, p_stat) != SZOMB) &&
  535.         (show_idle || (PP(pp, p_pctcpu) != 0) || 
  536.          (PP(pp, p_stat) == SRUN)) &&
  537.         (!show_uid || EP(pp, e_pcred.p_ruid) == (uid_t)sel->uid))
  538.         {
  539.         *prefp++ = pp;
  540.         active_procs++;
  541.         }
  542.     }
  543.     }
  544.  
  545.     /* if requested, sort the "interesting" processes */
  546.     if (compare != NULL)
  547.     {
  548.     qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
  549.     }
  550.  
  551.     /* remember active and total counts */
  552.     si->p_total = total_procs;
  553.     si->p_active = pref_len = active_procs;
  554.  
  555.     /* pass back a handle */
  556.     handle.next_proc = pref;
  557.     handle.remaining = active_procs;
  558.     return((caddr_t)&handle);
  559. }
  560.  
  561. char fmt[128];        /* static area where result is built */
  562.  
  563. char *format_next_process(handle, get_userid)
  564.  
  565. caddr_t handle;
  566. char *(*get_userid)();
  567.  
  568. {
  569.     register struct kinfo_proc *pp;
  570.     register long cputime;
  571.     register double pct;
  572.     struct handle *hp;
  573.  
  574.     /* find and remember the next proc structure */
  575.     hp = (struct handle *)handle;
  576.     pp = *(hp->next_proc++);
  577.     hp->remaining--;
  578.     
  579.  
  580.     /* get the process's user struct and set cputime */
  581.     if ((PP(pp, p_flag) & P_INMEM) == 0) {
  582.     /*
  583.      * Print swapped processes as <pname>
  584.      */
  585.     char *comm = PP(pp, p_comm);
  586. #define COMSIZ sizeof(PP(pp, p_comm))
  587.     char buf[COMSIZ];
  588.     (void) strncpy(buf, comm, COMSIZ);
  589.     comm[0] = '<';
  590.     (void) strncpy(&comm[1], buf, COMSIZ - 2);
  591.     comm[COMSIZ - 2] = '\0';
  592.     (void) strncat(comm, ">", COMSIZ - 1);
  593.     comm[COMSIZ - 1] = '\0';
  594.     }
  595.  
  596. #if 0
  597.     /* This does not produce the correct results */
  598.     cputime = PP(pp, p_uticks) + PP(pp, p_sticks) + PP(pp, p_iticks);
  599. #endif
  600.     cputime = PP(pp, p_rtime).tv_sec;    /* This does not count interrupts */
  601.  
  602.     /* calculate the base for cpu percentages */
  603.     pct = pctdouble(PP(pp, p_pctcpu));
  604.  
  605.     /* format this entry */
  606.     sprintf(fmt,
  607.         Proc_format,
  608.         PP(pp, p_pid),
  609.         (*get_userid)(EP(pp, e_pcred.p_ruid)),
  610.         PP(pp, p_priority) - PZERO,
  611.         PP(pp, p_nice) - NZERO,
  612.         format_k(pagetok(PROCSIZE(pp))),
  613.         format_k(pagetok(VP(pp, vm_rssize))),
  614.         state_abbrev[(unsigned char) PP(pp, p_stat)],
  615.         format_time(cputime),
  616.         10000.0 * weighted_cpu(pct, pp) / hz,
  617.         10000.0 * pct / hz,
  618.         printable(PP(pp, p_comm)));
  619.  
  620.     /* return the result */
  621.     return(fmt);
  622. }
  623.  
  624.  
  625. /*
  626.  * check_nlist(nlst) - checks the nlist to see if any symbols were not
  627.  *        found.  For every symbol that was not found, a one-line
  628.  *        message is printed to stderr.  The routine returns the
  629.  *        number of symbols NOT found.
  630.  */
  631.  
  632. static int check_nlist(nlst)
  633.  
  634. register struct nlist *nlst;
  635.  
  636. {
  637.     register int i;
  638.  
  639.     /* check to see if we got ALL the symbols we requested */
  640.     /* this will write one line to stderr for every symbol not found */
  641.  
  642.     i = 0;
  643.     while (nlst->n_name != NULL)
  644.     {
  645.     if (nlst->n_type == 0)
  646.     {
  647.         /* this one wasn't found */
  648.         (void) fprintf(stderr, "kernel: no symbol named `%s'\n",
  649.                nlst->n_name);
  650.         i = 1;
  651.     }
  652.     nlst++;
  653.     }
  654.  
  655.     return(i);
  656. }
  657.  
  658.  
  659. /*
  660.  *  getkval(offset, ptr, size, refstr) - get a value out of the kernel.
  661.  *    "offset" is the byte offset into the kernel for the desired value,
  662.  *      "ptr" points to a buffer into which the value is retrieved,
  663.  *      "size" is the size of the buffer (and the object to retrieve),
  664.  *      "refstr" is a reference string used when printing error meessages,
  665.  *        if "refstr" starts with a '!', then a failure on read will not
  666.  *          be fatal (this may seem like a silly way to do things, but I
  667.  *          really didn't want the overhead of another argument).
  668.  *      
  669.  */
  670.  
  671. static int getkval(offset, ptr, size, refstr)
  672.  
  673. unsigned long offset;
  674. int *ptr;
  675. int size;
  676. char *refstr;
  677.  
  678. {
  679.     if (kvm_read(kd, offset, (char *) ptr, size) != size)
  680.     {
  681.     if (*refstr == '!')
  682.     {
  683.         return(0);
  684.     }
  685.     else
  686.     {
  687.         fprintf(stderr, "top: kvm_read for %s: %s\n",
  688.         refstr, strerror(errno));
  689.         quit(23);
  690.     }
  691.     }
  692.     return(1);
  693. }
  694.     
  695. /* comparison routine for qsort */
  696.  
  697. /*
  698.  *  proc_compare - comparison function for "qsort"
  699.  *    Compares the resource consumption of two processes using five
  700.  *      distinct keys.  The keys (in descending order of importance) are:
  701.  *      percent cpu, cpu ticks, state, resident set size, total virtual
  702.  *      memory usage.  The process states are ordered as follows (from least
  703.  *      to most important):  WAIT, zombie, sleep, stop, start, run.  The
  704.  *      array declaration below maps a process state index into a number
  705.  *      that reflects this ordering.
  706.  */
  707.  
  708. static unsigned char sorted_state[] =
  709. {
  710.     0,    /* not used        */
  711.     3,    /* sleep        */
  712.     1,    /* ABANDONED (WAIT)    */
  713.     6,    /* run            */
  714.     5,    /* start        */
  715.     2,    /* zombie        */
  716.     4    /* stop            */
  717. };
  718.  
  719. int
  720. proc_compare(pp1, pp2)
  721.  
  722. struct proc **pp1;
  723. struct proc **pp2;
  724.  
  725. {
  726.     register struct kinfo_proc *p1;
  727.     register struct kinfo_proc *p2;
  728.     register int result;
  729.     register pctcpu lresult;
  730.  
  731.     /* remove one level of indirection */
  732.     p1 = *(struct kinfo_proc **) pp1;
  733.     p2 = *(struct kinfo_proc **) pp2;
  734.  
  735.     /* compare percent cpu (pctcpu) */
  736.     if ((lresult = PP(p2, p_pctcpu) - PP(p1, p_pctcpu)) == 0)
  737.     {
  738.     /* use cpticks to break the tie */
  739.     if ((result = PP(p2, p_cpticks) - PP(p1, p_cpticks)) == 0)
  740.     {
  741.         /* use process state to break the tie */
  742.         if ((result = sorted_state[(unsigned char) PP(p2, p_stat)] -
  743.               sorted_state[(unsigned char) PP(p1, p_stat)])  == 0)
  744.         {
  745.         /* use priority to break the tie */
  746.         if ((result = PP(p2, p_priority) - PP(p1, p_priority)) == 0)
  747.         {
  748.             /* use resident set size (rssize) to break the tie */
  749.             if ((result = VP(p2, vm_rssize) - VP(p1, vm_rssize)) == 0)
  750.             {
  751.             /* use total memory to break the tie */
  752.             result = PROCSIZE(p2) - PROCSIZE(p1);
  753.             }
  754.         }
  755.         }
  756.     }
  757.     }
  758.     else
  759.     {
  760.     result = lresult < 0 ? -1 : 1;
  761.     }
  762.  
  763.     return(result);
  764. }
  765.  
  766.  
  767. /*
  768.  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
  769.  *        the process does not exist.
  770.  *        It is EXTREMLY IMPORTANT that this function work correctly.
  771.  *        If top runs setuid root (as in SVR4), then this function
  772.  *        is the only thing that stands in the way of a serious
  773.  *        security problem.  It validates requests for the "kill"
  774.  *        and "renice" commands.
  775.  */
  776.  
  777. int proc_owner(pid)
  778.  
  779. int pid;
  780.  
  781. {
  782.     register int cnt;
  783.     register struct kinfo_proc **prefp;
  784.     register struct kinfo_proc *pp;
  785.  
  786.     prefp = pref;
  787.     cnt = pref_len;
  788.     while (--cnt >= 0)
  789.     {
  790.     pp = *prefp++;    
  791.     if (PP(pp, p_pid) == (pid_t)pid)
  792.     {
  793.         return((int)EP(pp, e_pcred.p_ruid));
  794.     }
  795.     }
  796.     return(-1);
  797. }
  798.  
  799.  
  800. #ifdef USE_SWAP
  801. /*
  802.  * swapmode is based on a program called swapinfo written
  803.  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
  804.  */
  805.  
  806. #define    SVAR(var) __STRING(var)    /* to force expansion */
  807. #define    KGET(idx, var)                            \
  808.     KGET1(idx, &var, sizeof(var), SVAR(var))
  809. #define    KGET1(idx, p, s, msg)                        \
  810.     KGET2(nlst[idx].n_value, p, s, msg)
  811. #define    KGET2(addr, p, s, msg)                        \
  812.     if (kvm_read(kd, (u_long)(addr), p, s) != s)            \
  813.         warnx("cannot read %s: %s", msg, kvm_geterr(kd))
  814. #define    KGETRET(addr, p, s, msg)                    \
  815.     if (kvm_read(kd, (u_long)(addr), p, s) != s) {            \
  816.         warnx("cannot read %s: %s", msg, kvm_geterr(kd));    \
  817.         return (0);                        \
  818.     }
  819.  
  820. int
  821. swapmode()
  822. {
  823.     char *header;
  824.     int hlen, nswap, nswdev, dmmax, nswapmap, niswap, niswdev;
  825.     int s, e, div, i, l, avail, nfree, npfree, used;
  826.     struct swdevt *sw;
  827.     long blocksize, *perdev;
  828.     struct map *swapmap, *kswapmap;
  829.     struct mapent *mp, *freemp;
  830.  
  831.     KGET(VM_NSWAP, nswap);
  832.     KGET(VM_NSWDEV, nswdev);
  833.     KGET(VM_DMMAX, dmmax);
  834.     KGET(VM_NSWAPMAP, nswapmap);
  835.     KGET(VM_SWAPMAP, kswapmap);    /* kernel `swapmap' is a pointer */
  836.     if ((sw = malloc(nswdev * sizeof(*sw))) == NULL ||
  837.         (perdev = malloc(nswdev * sizeof(*perdev))) == NULL ||
  838.         (freemp = mp = malloc(nswapmap * sizeof(*mp))) == NULL)
  839.         err(1, "malloc");
  840.     KGET1(VM_SWDEVT, sw, nswdev * sizeof(*sw), "swdevt");
  841.     KGET2((long)kswapmap, mp, nswapmap * sizeof(*mp), "swapmap");
  842.  
  843.     /* Supports sequential swap */
  844.     if (nlst[VM_NISWAP].n_value != 0) {
  845.         KGET(VM_NISWAP, niswap);
  846.         KGET(VM_NISWDEV, niswdev);
  847.     } else {
  848.         niswap = nswap;
  849.         niswdev = nswdev;
  850.     }
  851.  
  852.     /* First entry in map is `struct map'; rest are mapent's. */
  853.     swapmap = (struct map *)mp;
  854.     if (nswapmap != swapmap->m_limit - (struct mapent *)kswapmap)
  855.         errx(1, "panic: nswapmap goof");
  856.  
  857.     /* Count up swap space. */
  858.     nfree = 0;
  859.     memset(perdev, 0, nswdev * sizeof(*perdev));
  860.     for (mp++; mp->m_addr != 0; mp++) {
  861.         s = mp->m_addr;            /* start of swap region */
  862.         e = mp->m_addr + mp->m_size;    /* end of region */
  863.         nfree += mp->m_size;
  864.  
  865.         /*
  866.          * Swap space is split up among the configured disks.
  867.          *
  868.          * For interleaved swap devices, the first dmmax blocks
  869.          * of swap space some from the first disk, the next dmmax
  870.          * blocks from the next, and so on up to niswap blocks.
  871.          *
  872.          * Sequential swap devices follow the interleaved devices
  873.          * (i.e. blocks starting at niswap) in the order in which
  874.          * they appear in the swdev table.  The size of each device
  875.          * will be a multiple of dmmax.
  876.          *
  877.          * The list of free space joins adjacent free blocks,
  878.          * ignoring device boundries.  If we want to keep track
  879.          * of this information per device, we'll just have to
  880.          * extract it ourselves.  We know that dmmax-sized chunks
  881.          * cannot span device boundaries (interleaved or sequential)
  882.          * so we loop over such chunks assigning them to devices.
  883.          */
  884.         i = -1;
  885.         while (s < e) {        /* XXX this is inefficient */
  886.             int bound = roundup(s+1, dmmax);
  887.  
  888.             if (bound > e)
  889.                 bound = e;
  890.             if (bound <= niswap) {
  891.                 /* Interleaved swap chunk. */
  892.                 if (i == -1)
  893.                     i = (s / dmmax) % niswdev;
  894.                 perdev[i] += bound - s;
  895.                 if (++i >= niswdev)
  896.                     i = 0;
  897.             } else {
  898.                 /* Sequential swap chunk. */
  899.                 if (i < niswdev) {
  900.                     i = niswdev;
  901.                     l = niswap + sw[i].sw_nblks;
  902.                 }
  903.                 while (s >= l) {
  904.                     /* XXX don't die on bogus blocks */
  905.                     if (i == nswdev-1)
  906.                         break;
  907.                     l += sw[++i].sw_nblks;
  908.                 }
  909.                 perdev[i] += bound - s;
  910.             }
  911.             s = bound;
  912.         }
  913.     }
  914.  
  915.     header = getbsize(&hlen, &blocksize);
  916.     div = blocksize / 512;
  917.     avail = npfree = 0;
  918.     for (i = 0; i < nswdev; i++) {
  919.         int xsize, xfree;
  920.  
  921.         xsize = sw[i].sw_nblks;
  922.         xfree = perdev[i];
  923.         used = xsize - xfree;
  924.         npfree++;
  925.         avail += xsize;
  926.     }
  927.  
  928.     /* 
  929.      * If only one partition has been set up via swapon(8), we don't
  930.      * need to bother with totals.
  931.      */
  932.     used = avail - nfree;
  933.     free (sw); free (freemp); free (perdev);
  934.     return  (int)(((double)used / (double)avail * 100.0) + 0.5);
  935. }
  936.  
  937.  
  938. #endif
  939.  
  940.