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

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