Пример #1
0
int
netstat_init()
{
	kstat_t *ksp;

	kc = kstat_open();

	if (kstat_chain_update(kc))
		(void) fprintf(stderr, "<<State Changed>>n");
	for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
		if (ksp->ks_type != KSTAT_TYPE_NAMED ||
		    strcmp(ksp->ks_class, "net") != 0 ||
		    kstat_read(kc, ksp, NULL) == -1 ||
		    kstat_data_lookup(ksp, "ipackets64") == NULL ||
		    kstat_data_lookup(ksp, "opackets64") == NULL)
			continue;
		strlcpy(nics[no_nics].interface, ksp->ks_name, INTERFACE_LEN);
		nics[no_nics++].ksp = ksp;
		if (no_nics >= MAX_NETS) {
			printf("Warning: Number of interfaces exceeded %d\n",
			    MAX_NETS);
			return (-1);
		}
	}

	return (0);
}
Пример #2
0
/*
 * Retrieve the vopstats.  If kspp (pointer to kstat_t pointer) is non-NULL,
 * then pass it back to the caller.
 *
 * Returns 0 on success, non-zero on failure.
 */
int
get_vopstats(kstat_ctl_t *kc, char *ksname, vopstats_t *vsp, kstat_t **kspp)
{
	kstat_t		*ksp;

	if (ksname == NULL || *ksname == 0)
		return (1);

	errno = 0;
	/* wait for a possibly up-to-date chain */
	while (kstat_chain_update(kc) == -1) {
		if (errno == EAGAIN) {
			errno = 0;
			(void) poll(NULL, 0, RETRY_DELAY);
			continue;
		}
		perror("kstat_chain_update");
		exit(1);
	}

	if ((ksp = kstat_lookup(kc, NULL, -1, ksname)) == NULL) {
		return (1);
	}

	if (kstat_read(kc, ksp, vsp) == -1) {
		return (1);
	}

	if (kspp)
		*kspp = ksp;

	return (0);
}
Пример #3
0
/*
 * Determine the count of pages scanned by the global page scanner, obtained
 * from the cpu_stat:*::scan kstats.  Return zero on success.
 */
static int
get_globally_scanned_pages(uint64_t *scannedp)
{
	kstat_t *ksp;
	uint64_t scanned = 0;

	if (kstat_chain_update(kctl) == -1) {
		warn(gettext("can't update kstat chain"));
		return (0);
	}

	for (ksp = kctl->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
		if (strcmp(ksp->ks_module, "cpu_stat") == 0) {
			if (kstat_read(kctl, ksp, NULL) != -1) {
				scanned += ((cpu_stat_t *)
				    ksp->ks_data)->cpu_vminfo.scan;
			} else {
				return (-1);
			}
		}
	}

	*scannedp = scanned;
	return (0);
}
Пример #4
0
void
netstat_snap(int snaptype)
{
	int		i, index;
	kstat_t		*ksp;
	kid_t		kstat_chain_id;

	if (kstat_chain_update(kc))
		state_changed = 1;
	if (snaptype == SNAP_BEGIN)
		index = 0;
	else
		index = 1;
	for (i = 0; i < no_nics; i++) {
		ksp = nics[i].ksp;
		kstat_chain_id = kstat_read(kc, ksp, nets[0]);
		nics[i].s[index].tx_pkts
		    = kstat_named_value(ksp, "opackets64");
		nics[i].s[index].rx_pkts
		    = kstat_named_value(ksp, "ipackets64");
		nics[i].s[index].tx_bytes = kstat_named_value(ksp, "obytes64");
		nics[i].s[index].rx_bytes = kstat_named_value(ksp, "rbytes64");
		nics[i].s[index].stamp = gethrtime();

	}
}
Пример #5
0
void
glibtop_get_cpu_s (glibtop *server, glibtop_cpu *buf)
{
    kstat_ctl_t * const kc = server->machine->kc;
    cpu_stat_t cpu_stat;
    processorid_t cpu;
    int ncpu, found;

    memset (buf, 0, sizeof (glibtop_cpu));

    buf->frequency = server->machine->ticks;
    buf->flags = _glibtop_sysdeps_cpu_freq;

    if(!kc)
	return;

    switch(kstat_chain_update(kc))
    {
	case -1: assert(0); /* Debugging purposes, shouldn't happen */
	case 0:  break;
	default: glibtop_get_kstats(server);
    }

    ncpu = MIN(GLIBTOP_NCPU, server->ncpu);

    for (cpu = 0, found = 0; cpu < GLIBTOP_NCPU && found != ncpu; cpu++)
    {
	kstat_t * const ksp = server->machine->cpu_stat_kstat [cpu];
	if (!ksp) continue;;

	++found;

	if(p_online(cpu, P_STATUS) == P_ONLINE)
	    buf->xcpu_flags |= (1L << cpu);
	else
	    continue;

	if (kstat_read (kc, ksp, &cpu_stat) == -1) {
	    glibtop_warn_io_r (server, "kstat_read (cpu_stat%d)", cpu);
	    continue;
	}

	buf->xcpu_idle [cpu] = cpu_stat.cpu_sysinfo.cpu [CPU_IDLE];
	buf->xcpu_user [cpu] = cpu_stat.cpu_sysinfo.cpu [CPU_USER];
	buf->xcpu_sys [cpu] = cpu_stat.cpu_sysinfo.cpu [CPU_KERNEL];
	buf->xcpu_total [cpu] = buf->xcpu_idle [cpu] + buf->xcpu_user [cpu] +
	    buf->xcpu_sys [cpu];

	buf->idle += cpu_stat.cpu_sysinfo.cpu [CPU_IDLE];
	buf->user += cpu_stat.cpu_sysinfo.cpu [CPU_USER];
	buf->sys  += cpu_stat.cpu_sysinfo.cpu [CPU_KERNEL];
    }

    if(!found)
	return;

    buf->total = buf->idle + buf->user + buf->sys;
    buf->flags = _glibtop_sysdeps_cpu_all;
}
Пример #6
0
struct snapshot *
acquire_snapshot(kstat_ctl_t *kc, int types, struct iodev_filter *iodev_filter)
{
	struct snapshot *ss = NULL;
	int err;

retry:
	err = 0;
	/* ensure any partial resources are freed on a retry */
	free_snapshot(ss);

	ss = safe_alloc(sizeof (struct snapshot));

	(void) memset(ss, 0, sizeof (struct snapshot));

	ss->s_types = types;

	/* wait for a possibly up-to-date chain */
	while (kstat_chain_update(kc) == -1) {
		if (errno == EAGAIN)
			(void) poll(NULL, 0, RETRY_DELAY);
		else
			fail(1, "kstat_chain_update failed");
	}

	if (!err && (types & SNAP_INTERRUPTS))
		err = acquire_intrs(ss, kc);

	if (!err && (types & (SNAP_CPUS | SNAP_SYSTEM | SNAP_PSETS)))
		err = acquire_cpus(ss, kc);

	if (!err && (types & SNAP_PSETS))
		err = acquire_psets(ss);

	if (!err && (types & (SNAP_IODEVS | SNAP_CONTROLLERS |
	    SNAP_IOPATHS_LI | SNAP_IOPATHS_LTI)))
		err = acquire_iodevs(ss, kc, iodev_filter);

	if (!err && (types & SNAP_SYSTEM))
		err = acquire_sys(ss, kc);

	switch (err) {
		case 0:
			break;
		case EAGAIN:
			(void) poll(NULL, 0, RETRY_DELAY);
		/* a kstat disappeared from under us */
		/*FALLTHRU*/
		case ENXIO:
		case ENOENT:
			goto retry;
		default:
			fail(1, "acquiring snapshot failed");
	}

	return (ss);
}
Пример #7
0
void 
ks_chain_update(kstat_ctl_t * kc)
{
	kid = kstat_chain_update(kc);
	if (kid < 0) {
		perror("kstat_chain_update");
		return;
	}
}
Пример #8
0
static void update_kstat()
{
	if (kstat == NULL) {
		kstat = kstat_open();
		if (kstat == NULL) {
			NORM_ERR("can't open kstat: %s", strerror(errno));
		}
	}

	if (kstat_chain_update(kstat) == -1) {
		perror("kstat_chain_update");
		return;
	}
}
Пример #9
0
static void update_kstat(void) {
  if (kc == NULL) {
    if ((kc = kstat_open()) == NULL)
      ERROR("Unable to open kstat control structure");
  } else {
    kid_t kid = kstat_chain_update(kc);
    if (kid > 0) {
      INFO("kstat chain has been updated");
      plugin_init_all();
    } else if (kid < 0)
      ERROR("kstat chain update failed");
    /* else: everything works as expected */
  }

  return;
} /* static void update_kstat (void) */
Пример #10
0
    /*
     * Initialise the list of CPUs on the system
     *   (including descriptions)
     */
void init_cpu_kstat( void ) {
    int               i = 0, n = 0, clock, state_begin;
    char              ctype[15], ftype[15], state[10];
    kstat_t          *ksp;
    kstat_named_t    *ks_data;
    netsnmp_cpu_info *cpu = netsnmp_cpu_get_byIdx( -1, 1 );
    strcpy(cpu->name, "Overall CPU statistics");

    if (kstat_fd == NULL)
        kstat_fd = kstat_open();
    kstat_chain_update( kstat_fd );

    DEBUGMSGTL(("cpu", "cpu_kstat init\n "));
    for (ksp = kstat_fd->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
        if (ksp->ks_flags & KSTAT_FLAG_INVALID)
            continue;
        if ((strcmp(ksp->ks_module, "cpu_info") == 0) &&
            (strcmp(ksp->ks_class,  "misc"    ) == 0)) {
            kstat_read(kstat_fd, ksp, NULL );
            n++;
            clock = 999999;
            memset(ctype, 0, sizeof(ctype));
            memset(ftype, 0, sizeof(ftype));
            memset(state, 0, sizeof(state));
            for (i=0, ks_data = ksp->ks_data; i < ksp->ks_ndata; i++, ks_data++) {
                if ( strcmp( ks_data->name, "state" ) == 0 ) {
                    strlcpy(state, ks_data->value.c, sizeof(state));
                } else if ( strcmp( ks_data->name, "state_begin" ) == 0 ) {
                    state_begin = ks_data->value.i32;
                } else if ( strcmp( ks_data->name, "cpu_type" ) == 0 ) {
                    strlcpy(ctype, ks_data->value.c, sizeof(ctype));
                } else if ( strcmp( ks_data->name, "fpu_type" ) == 0 ) {
                    strlcpy(ftype, ks_data->value.c, sizeof(ftype));
                } else if ( strcmp( ks_data->name, "clock_MHz" ) == 0 ) {
                    clock = ks_data->value.i32;
                }
            }
            i   = ksp->ks_instance;
            cpu = netsnmp_cpu_get_byIdx( i, 1 );
            sprintf( cpu->name,  "cpu%d", i );
            sprintf( cpu->descr, "CPU %d Sun %d MHz %s with %s FPU %s",
                                 i, clock, ctype, ftype, state  );
            cpu->status = _cpu_status(state); /* XXX - or in 'n_c_a_load' ? */
        }
    }
    cpu_num = i;
}
Пример #11
0
void
glibtop_get_loadavg_s (glibtop *server, glibtop_loadavg *buf)
{
#ifndef HAVE_GETLOADAVG
	kstat_ctl_t *kc;
	kstat_t *ksp;
	size_t i;
	static const char avestrings[][14] = { "avenrun_1min",
					       "avenrun_5min",
					       "avenrun_15min" };
#endif
	memset (buf, 0, sizeof (glibtop_loadavg));

#ifdef HAVE_GETLOADAVG
	if (getloadavg (buf->loadavg, 3) != 3)
		return;

#else
	if(!(kc = server->machine->kc))
	    return;

	switch(kstat_chain_update(kc))
	{
	    case -1: assert(0); /* Debugging, shouldn't happen */
	    case 0:  break;
	    default: glibtop_get_kstats(server);
	}

	if(!(ksp = server->machine->system))
	    return;

	if(kstat_read(kc, ksp, NULL) < 0)
	    return;

	for(i = 0; i < 3; ++i) /* Do we have a countof macro? */
	{
		kstat_named_t *kn;

		kn = (kstat_named_t *)kstat_data_lookup(ksp, avestrings[i]);
		if(kn)
		    buf->loadavg[i] = (double)kn->value.ul / FSCALE;
	}
#endif /* HAVE_GETLOADAVG */

	buf->flags = _glibtop_sysdeps_loadavg;
}
Пример #12
0
/*
 * Check to see if any DR operations have occured, and deal with the
 * consequences.
 *
 * Use the Kstat chain ID to check for DR operations. If the ID has
 * changed then some kstats on system have been modified, we check
 * all the data structures to see are they still valid. If they are
 * not we remove them.
 */
void
check_dr_ops()
{
	dev_node_t	*dev_node;
	kid_t		new_id;
	kstat_t		*ksp;
	int		match = 0;

	if ((new_id = kstat_chain_update(kc)) < 0) {
		(void) fprintf(stderr, gettext("%s: could not get "
			"kstat chain id\n"), pgmname);
		exit(1);
	}

	if (new_id == 0) {
		/* Kstat chain has not changed. */
		return;
	}

	/*
	 * Scan the chain of device nodes, making sure that their associated
	 * kstats are still present. If not we remove the appropiate node.
	 */
	dev_node = dev_list_head;

	while (dev_node != NULL) {
		for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) {
			if ((strcmp("bus", ksp->ks_class) == 0) &&
				(strcmp("counters", ksp->ks_name) == 0) &&
				(strcmp(dev_node->name, ksp->ks_module) == 0) &&
				(ksp->ks_instance == dev_node->dev_inst)) {
					match = 1;
					break;
			}
		}
		if (match == 0) {
			(void) fprintf(stderr, gettext("%s: device %s%d"
				" (pic %d) no longer valid.\n"), pgmname,
				    dev_node->name, dev_node->dev_inst,
				    dev_node->pic_num);

			remove_dev_node(dev_node);
		}
		dev_node = dev_node->next;
	}
}
gboolean
get_cpu_usage (gushort *cpu_count, gfloat *cpu_user, gfloat *cpu_system)
{
	kstat_t *ksp;
	kstat_named_t *knp;
	static gulong ticks_total = 0, ticks_total_old = 0;
	gulong ticks_user = 0, ticks_system = 0;

	if (!kc)
		init_stats ();

	_cpu_count = 0;
	kstat_chain_update (kc);

	ticks_total_old = ticks_total;
	ticks_total = 0;

	for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next)
	{
		if (!g_strcmp0 (ksp->ks_module, "cpu_info"))
		{
			_cpu_count += 1;
		}
		else if (!g_strcmp0 (ksp->ks_module, "cpu") && !g_strcmp0 (ksp->ks_name, "sys"))
		{
			kstat_read (kc, ksp, NULL);
			knp = kstat_data_lookup (ksp, "cpu_nsec_user");
			ticks_user += knp->value.ul / 100000;
			knp = kstat_data_lookup (ksp, "cpu_nsec_kernel");
			ticks_system += knp->value.ul / 100000;
			knp = kstat_data_lookup (ksp, "cpu_nsec_intr");
			ticks_system += knp->value.ul / 100000;
			knp = kstat_data_lookup (ksp, "cpu_nsec_idle");
			ticks_total += knp->value.ul / 100000;
			ticks_total += ticks_user + ticks_system;
		}
	}

	if (ticks_total > ticks_total_old)
		ticks_total_delta = ticks_total - ticks_total_old;

	get_cpu_percent (0, ticks_user, cpu_user, ticks_system, cpu_system);
	*cpu_count = _cpu_count;

        return TRUE;
}
Пример #14
0
int updateLoadAvg(void)
{

#ifdef HAVE_KSTAT
    kstat_ctl_t *kctl;
    kstat_t *ksp;
    kstat_named_t *kdata;

    /*
     *  get a kstat handle and update the user's kstat chain
     */
    if((kctl = kstat_open()) == NULL)
        return (0);
    while(kstat_chain_update(kctl) != 0)
        ;

    /*
     *  traverse the kstat chain to find the appropriate statistics
     */
    if((ksp = kstat_lookup(kctl, "unix", 0, "system_misc")) == NULL)
        return (0);
    if(kstat_read(kctl, ksp, NULL) == -1)
        return (0);

    /*
     *  lookup the data
     */
    kdata = (kstat_named_t *)kstat_data_lookup(ksp, "avenrun_1min");
    if(kdata != NULL)
        loadavg1 = LOAD(kdata->value.ui32);
    kdata = (kstat_named_t *)kstat_data_lookup(ksp, "avenrun_5min");
    if(kdata != NULL)
        loadavg5 = LOAD(kdata->value.ui32);
    kdata = (kstat_named_t *)kstat_data_lookup(ksp, "avenrun_15min");
    if(kdata != NULL)
        loadavg15 = LOAD(kdata->value.ui32);

    kstat_close(kctl);
#endif /* ! HAVE_KSTAT */

    return (0);
}
Пример #15
0
int updateMemory( void ) {
#ifdef HAVE_KSTAT
	kstat_ctl_t		*kctl;
	kstat_t			*ksp;
	kstat_named_t		*kdata;

	/*
	 *  get a kstat handle and update the user's kstat chain
	 */
	if( (kctl = kstat_open()) == NULL )
		return( 0 );
	while( kstat_chain_update( kctl ) != 0 )
		;

	totalmem = pagetok( sysconf( _SC_PHYS_PAGES ));

	/*
	 *  traverse the kstat chain to find the appropriate statistics
	 */
	if( (ksp = kstat_lookup( kctl, "unix", 0, "system_pages" )) == NULL ) {
		goto done;
	}

	if( kstat_read( kctl, ksp, NULL ) == -1 ) {
		goto done;
	}

	/*
	 *  lookup the data
	 */
	 kdata = (kstat_named_t *) kstat_data_lookup( ksp, "freemem" );
	 if( kdata != NULL )
		freemem = pagetok( kdata->value.ui32 );

done:
	kstat_close( kctl );
#endif /* ! HAVE_KSTAT */

	return( 0 );
}
Пример #16
0
kstat_ctl_t *
kstat_open(void)
{
	kstat_ctl_t *kc;
	int kd;

	kd = open("/dev/kstat", O_RDONLY);
	if (kd == -1)
		return (NULL);
	kstat_zalloc((void **)&kc, sizeof (kstat_ctl_t), 0);
	if (kc == NULL)
		return (NULL);

	kc->kc_kd = kd;
	kc->kc_chain = NULL;
	kc->kc_chain_id = 0;
	if (kstat_chain_update(kc) == -1) {
		int saved_err = errno;
		(void) kstat_close(kc);
		errno = saved_err;
		return (NULL);
	}
	return (kc);
}
static int
get_system_info (kstat_ctl_t *kc, sys_stat *sst)
{
  kstat_t *ksp;
  kstat_named_t *kn;
  kid_t kcid, nkcid;
  int totalswap, freeswap;
  int i, j;
  cpu_stat_t cpu_stat[MAX_CPU];
  static int pagesize = 0, maxmem = 0;
  static long cp_time[CPUSTATES];
  static long cp_old[CPUSTATES];
  static long cp_diff[CPUSTATES];
  static kstat_t *cpu_ks[MAX_CPU];
  static int ncpu = 0;
  static int freemem_check_time = 0;
  int changed = 0;

  kcid = kc->kc_chain_id;

kcid_changed:

  nkcid = kstat_chain_update (kc);
  if (nkcid)
    {
      kcid = nkcid;
      changed = 1;
    }
  CHECK_KCID (nkcid, 0);

  ksp = kstat_lookup (kc, "unix", -1, "system_misc");
  nkcid = kstat_read (kc, ksp, NULL);
  CHECK_KCID (nkcid, kcid);

  /*
   *  collect load average information
   */
  kn = kstat_data_lookup (ksp, "avenrun_1min");
  sst->load_avg[0] = kn->value.ui32;
  kn = kstat_data_lookup (ksp, "avenrun_5min");
  sst->load_avg[1] = kn->value.ui32;
  kn = kstat_data_lookup (ksp, "avenrun_15min");
  sst->load_avg[2] = kn->value.ui32;

  /*
   *  collect cpu information
   */
  if (changed == 1 || ncpu == 0)
    {
      ncpu = 0;
      for (ksp = kc->kc_chain; ksp && ncpu < MAX_CPU; ksp = ksp->ks_next)
        {
          if (strncmp (ksp->ks_name, "cpu_stat", 8) == 0)
            {
              nkcid = kstat_read (kc, ksp, NULL);
              CHECK_KCID (nkcid, kcid);
              cpu_ks[ncpu] = ksp;
              ncpu++;
            }
        }
    }

  for (i = 0; i < ncpu; i++)
    {
      nkcid = kstat_read (kc, cpu_ks[i], & (cpu_stat[i]));
      CHECK_KCID (nkcid, kcid);
    }

  for (j = 0; j < CPUSTATES; j++)
    {
      cp_time[j] = 0L;
    }

  for (i = 0; i < ncpu; i++)
    {
      for (j = 0; j < CPU_WAIT; j++)
        {
          cp_time[j] += (long) cpu_stat[i].cpu_sysinfo.cpu[j];
        }

      cp_time[CPUSTATE_IOWAIT] += (long) cpu_stat[i].cpu_sysinfo.wait[W_IO] +
                                  (long) cpu_stat[i].cpu_sysinfo.wait[W_PIO];
      cp_time[CPUSTATE_SWAP] = (long) cpu_stat[i].cpu_sysinfo.wait[W_SWAP];
    }

  percentages (CPUSTATES, sst->cpu_states, cp_time, cp_old, cp_diff);

  /*
   *  collect memory information
   */
  if (pagesize == 0)
    {
      pagesize = sysconf (_SC_PAGESIZE);
    }
  if (maxmem == 0)
    {
      maxmem = sysconf (_SC_PHYS_PAGES);
      sst->memory_stats[0] = PAGETOM (maxmem, pagesize);
    }

  if (time (NULL) - freemem_check_time > 30)
    {
      ksp = kstat_lookup (kc, "unix", 0, "system_pages");
      nkcid = kstat_read (kc, ksp, NULL);
      CHECK_KCID (nkcid, kcid);

      kn = kstat_data_lookup (ksp, "freemem");
      sst->memory_stats[2] = PAGETOM (kn->value.ui32, pagesize);

      if (sst->memory_stats[0] - sst->memory_stats[2] > 0)
        {
          sst->memory_stats[1] = sst->memory_stats[0] - sst->memory_stats[2];
        }
      freemem_check_time = time (NULL);
    }

#if 0
  kn = kstat_data_lookup (ksp, "availrmem");
#endif

  get_swapinfo (&totalswap, &freeswap);
  sst->memory_stats[3] = PAGETOM ((totalswap - freeswap), pagesize);
  sst->memory_stats[4] = PAGETOM (freeswap, pagesize);

  return 1;
}
    void
    Solaris_Network_Interface_Monitor::access_kstats (
      ACE_UINT64 &which_member)
    {
      this->kstats_ = kstat_open ();

      if (this->kstats_ == 0)
        {
          ACELIB_ERROR ((LM_ERROR,
                      ACE_TEXT ("opening kstats file failed\n")));
          return;
        }

      this->kstat_id_ = this->kstats_->kc_chain_id;
      int status = 0;

      while (true)
        {
          /// We have to sum the network interfaces manually.
          for (this->kstat_ = this->kstats_->kc_chain;
               this->kstat_ != 0;
               this->kstat_ = this->kstat_->ks_next)
            {
              if (ACE_OS::strcmp (this->kstat_->ks_class, "net") != 0)
                {
                  continue;
                }

              unsigned long ks_instance = this->kstat_->ks_instance;

              if (ACE_OS::strcmp (this->kstat_->ks_module, "lo") == 0)
                {
                  /// Interfaces 'lo' have only packet counters.
                  if (this->lookup_str_ == ACE_TEXT ("obytes")
                      || this->lookup_str_ == ACE_TEXT ("rbytes"))
                    {
                      continue;
                    }

                  status = this->check_ks_module (ks_instance,
                                                  MAX_LO_INTERFACES,
                                                  "MAX_LO_INTERFACES",
                                                  this->value_array_lo_,
                                                  which_member);

                  if (status == -1)
                    {
                      /// Unrecoverable error, diagnostic already output.
                      (void) kstat_close (this->kstats_);
                      return;
                    }
                  else if (status == 1)
                    {
                      /// The kstat_id changed underneath us, start over.
                      break;
                    }
                }
              else if (ACE_OS::strcmp (this->kstat_->ks_module, "hme") == 0
                       || ACE_OS::strcmp (this->kstat_->ks_module, "bge") == 0)
                {
                  status = this->check_ks_module (ks_instance,
                                                  MAX_HME_INTERFACES,
                                                  "MAX_HME_INTERFACES",
                                                  this->value_array_hme_,
                                                  which_member);

                  if (status == -1)
                    {
                      /// Unrecoverable error, diagnostic already output.
                      (void) kstat_close (this->kstats_);
                      return;
                    }
                  else if (status == 1)
                    {
                      /// The kstat_id changed underneath us, start over.
                      break;
                    }
                }
            }

          if (this->kstat_)
            {
              this->kstat_id_ = kstat_chain_update (this->kstats_);

              if (! this->kstat_id_ > 0)
                {
                  ACELIB_ERROR ((LM_ERROR, "kstat is is not > 0.\n"));
                  break;
                }
            }
          else
            {
              break;
            }
        }

      status = kstat_close (this->kstats_);

      if (status != 0)
        {
          ACELIB_ERROR ((LM_ERROR,
                      ACE_TEXT ("closing kstats file failed\n")));
        }
    }
Пример #19
0
int updateNetDev( void ) {

#ifdef HAVE_KSTAT
    kstat_ctl_t		*kctl;
    kstat_t			*ksp;
    kstat_named_t		*kdata;
    int			i;

    /*
     *  get a kstat handle and update the user's kstat chain
     */
    if( (kctl = kstat_open()) == NULL )
        return( 0 );
    while( kstat_chain_update( kctl ) != 0 )
        ;

    for( i = 0; i < NetDevCount; i++ ) {
        char	*name;
        char	*ptr;

        /*
         *  chop off the trailing interface no
         */
        name = strdup( IfInfo[i].Name );
        ptr = name + strlen( name ) - 1;
        while( (ptr > name) && isdigit( (int) *ptr ) ) {
            *ptr = '\0';
            ptr--;
        }

        /*
         *  traverse the kstat chain
         *  to find the appropriate statistics
         */
        if( (ksp = kstat_lookup( kctl,
                                 name, 0, IfInfo[i].Name )) == NULL ) {
            free( name );
            return( 0 );
        }
        if( kstat_read( kctl, ksp, NULL ) == -1 ) {
            free( name );
            return( 0 );
        }
        free( name );

        /*
         *  lookup & store the data
         */
        kdata = (kstat_named_t *) kstat_data_lookup( ksp, "ipackets" );
        if( kdata != NULL ) {
            IfInfo[i].OLDipackets = IfInfo[i].ipackets;
            IfInfo[i].ipackets = kdata->value.ul;
        }
        kdata = (kstat_named_t *) kstat_data_lookup( ksp, "opackets" );
        if( kdata != NULL ) {
            IfInfo[i].OLDopackets = IfInfo[i].opackets;
            IfInfo[i].opackets = kdata->value.ul;
        }
        kdata = (kstat_named_t *) kstat_data_lookup( ksp, "ierrors" );
        if( kdata != NULL ) {
            IfInfo[i].OLDierrors = IfInfo[i].ierrors;
            IfInfo[i].ierrors = kdata->value.ul;
        }
        kdata = (kstat_named_t *) kstat_data_lookup( ksp, "oerrors" );
        if( kdata != NULL ) {
            IfInfo[i].OLDoerrors = IfInfo[i].oerrors;
            IfInfo[i].oerrors = kdata->value.ul;
        }
        kdata = (kstat_named_t *) kstat_data_lookup( ksp, "collisions" );
        if( kdata != NULL ) {
            IfInfo[i].OLDcollisions = IfInfo[i].collisions;
            IfInfo[i].collisions = kdata->value.ul;
        }
        kdata = (kstat_named_t *) kstat_data_lookup( ksp, "multixmt" );
        if( kdata != NULL ) {
            IfInfo[i].OLDmultixmt = IfInfo[i].multixmt;
            IfInfo[i].multixmt = kdata->value.ul;
        }
        kdata = (kstat_named_t *) kstat_data_lookup( ksp, "multircv" );
        if( kdata != NULL ) {
            IfInfo[i].OLDmultircv = IfInfo[i].multircv;
            IfInfo[i].multircv = kdata->value.ul;
        }
        kdata = (kstat_named_t *) kstat_data_lookup( ksp, "brdcstxmt" );
        if( kdata != NULL ) {
            IfInfo[i].OLDbrdcstxmt = IfInfo[i].brdcstxmt;
            IfInfo[i].brdcstxmt = kdata->value.ul;
        }
        kdata = (kstat_named_t *) kstat_data_lookup( ksp, "brdcstrcv" );
        if( kdata != NULL ) {
            IfInfo[i].OLDbrdcstrcv = IfInfo[i].brdcstrcv;
            IfInfo[i].brdcstrcv = kdata->value.ul;
        }
    }

    kstat_close( kctl );
#endif /* ! HAVE_KSTAT */

    return( 0 );
}
Пример #20
0
TCN_IMPLEMENT_CALL(jint, OS, info)(TCN_STDARGS,
                                   jlongArray inf)
{
    jint rv;
    int  i;
    jsize ilen = (*e)->GetArrayLength(e, inf);
    jlong *pvals = (*e)->GetLongArrayElements(e, inf, NULL);

    UNREFERENCED(o);
    if (ilen < 16) {
        return APR_EINVAL;
    }
    for (i = 0; i < 16; i++)
        pvals[i] = 0;
#if defined(__linux__)
    {
        struct sysinfo info;
        if (sysinfo(&info))
            rv = apr_get_os_error();
        else {
            pvals[0] = (jlong)(info.totalram  * info.mem_unit);
            pvals[1] = (jlong)(info.freeram   * info.mem_unit);
            pvals[2] = (jlong)(info.totalswap * info.mem_unit);
            pvals[3] = (jlong)(info.freeswap  * info.mem_unit);
            pvals[4] = (jlong)(info.sharedram * info.mem_unit);
            pvals[5] = (jlong)(info.bufferram * info.mem_unit);
            pvals[6] = (jlong)(100 - (info.freeram * 100 / info.totalram));
            rv = APR_SUCCESS;
        }
    }
#elif defined(sun)
    {
        /* static variables with basic procfs info */
        static long creation = 0;              /* unix timestamp of process creation */
        static int psinf_fd = 0;               /* file descriptor for the psinfo procfs file */
        static int prusg_fd = 0;               /* file descriptor for the usage procfs file */
        static size_t rss = 0;                 /* maximum of resident set size from previous calls */
        /* static variables with basic kstat info */
        static kstat_ctl_t *kstat_ctl = NULL;  /* kstat control object, only initialized once */
        static kstat_t *kstat_cpu[MAX_CPUS];   /* array of kstat objects for per cpu statistics */
        static int cpu_count = 0;              /* number of cpu structures found in kstat */
        static kid_t kid = 0;                  /* kstat ID, for which the kstat_ctl holds the correct chain */
        /* non-static variables - general use */
        int res = 0;                           /* general result state */
        /* non-static variables - sysinfo/swapctl use */
        long ret_sysconf;                      /* value returned from sysconf call */
        long tck_dividend;                     /* factor used by transforming tick numbers to milliseconds */
        long tck_divisor;                      /* divisor used by transforming tick numbers to milliseconds */
        long sys_pagesize = sysconf(_SC_PAGESIZE); /* size of a system memory page in bytes */
        long sys_clk_tck = sysconf(_SC_CLK_TCK); /* number of system ticks per second */
        struct anoninfo info;                  /* structure for information about sizes in anonymous memory system */
        /* non-static variables - procfs use */
        psinfo_t psinf;                        /* psinfo structure from procfs */
        prusage_t prusg;                       /* usage structure from procfs */
        size_t new_rss = 0;                    /* resident set size read from procfs */
        time_t now;                            /* time needed for calculating process creation time */
        /* non-static variables - kstat use */
        kstat_t *kstat = NULL;                 /* kstat working pointer */
        cpu_sysinfo_t cpu;                     /* cpu sysinfo working pointer */
        kid_t new_kid = 0;                     /* kstat ID returned from chain update */
        int new_kstat = 0;                     /* flag indicating, if kstat structure has changed since last call */

        rv = APR_SUCCESS;

        if (sys_pagesize <= 0) {
            rv = apr_get_os_error();
        }
        else {
            ret_sysconf = sysconf(_SC_PHYS_PAGES);
            if (ret_sysconf >= 0) {
                pvals[0] = (jlong)((jlong)sys_pagesize * ret_sysconf);
            }
            else {
                rv = apr_get_os_error();
            }
            ret_sysconf = sysconf(_SC_AVPHYS_PAGES);
            if (ret_sysconf >= 0) {
                pvals[1] = (jlong)((jlong)sys_pagesize * ret_sysconf);
            }
            else {
                rv = apr_get_os_error();
            }
            res=swapctl(SC_AINFO, &info);
            if (res >= 0) {
                pvals[2] = (jlong)((jlong)sys_pagesize * info.ani_max);
                pvals[3] = (jlong)((jlong)sys_pagesize * info.ani_free);
                pvals[6] = (jlong)(100 - (jlong)info.ani_free * 100 / info.ani_max);
            }
            else {
                rv = apr_get_os_error();
            }
        }

        if (psinf_fd == 0) {
            psinf_fd = proc_open("psinfo");
        }
        res = proc_read(&psinf, PSINFO_T_SZ, psinf_fd);
        if (res >= 0) {
            new_rss = psinf.pr_rssize*1024;
            pvals[13] = (jlong)(new_rss);
            if (new_rss > rss) {
                rss = new_rss;
            }
            pvals[14] = (jlong)(rss);
        }
        else {
            psinf_fd = 0;
            rv = apr_get_os_error();
        }
        if (prusg_fd == 0) {
            prusg_fd = proc_open("usage");
        }
        res = proc_read(&prusg, PRUSAGE_T_SZ, prusg_fd);
        if (res >= 0) {
            if (creation <= 0) {
                time(&now);
                creation = (long)(now - (prusg.pr_tstamp.tv_sec -
                                         prusg.pr_create.tv_sec));
            }
            pvals[10] = (jlong)(creation);
            pvals[11] = (jlong)((jlong)prusg.pr_stime.tv_sec * 1000 +
                                (prusg.pr_stime.tv_nsec / 1000000));
            pvals[12] = (jlong)((jlong)prusg.pr_utime.tv_sec * 1000 +
                                (prusg.pr_utime.tv_nsec / 1000000));
            pvals[15] = (jlong)(prusg.pr_majf);
        }
        else {
            prusg_fd = 0;
            rv = apr_get_os_error();
        }

        if (sys_clk_tck <= 0) {
            rv = apr_get_os_error();
        }
        else {
            tck_dividend = 1000;
            tck_divisor = sys_clk_tck;
            for (i = 0; i < 3; i++) {
                if (tck_divisor % 2 == 0) {
                    tck_divisor = tck_divisor / 2;
                    tck_dividend = tck_dividend / 2;
                }
                if (tck_divisor % 5 == 0) {
                    tck_divisor = tck_divisor / 5;
                    tck_dividend = tck_dividend / 5;
                }
            }
            if (kstat_ctl == NULL) {
                kstat_ctl = kstat_open();
                kid = kstat_ctl->kc_chain_id;
                new_kstat = 1;
            } else {
                new_kid = kstat_chain_update(kstat_ctl);
                if (new_kid < 0) {
                    res=kstat_close(kstat_ctl);
                    kstat_ctl = kstat_open();
                    kid = kstat_ctl->kc_chain_id;
                    new_kstat = 1;
                } else if (new_kid > 0 && kid != new_kid) {
                    kid = new_kid;
                    new_kstat = 1;
                }
            }
            if (new_kstat) {
                cpu_count = 0;
                for (kstat = kstat_ctl->kc_chain; kstat; kstat = kstat->ks_next) {
                    if (strncmp(kstat->ks_name, "cpu_stat", 8) == 0) {
                        kstat_cpu[cpu_count++]=kstat;
                    }
                }
            }
            for (i = 0; i < cpu_count; i++) {
                new_kid = kstat_read(kstat_ctl, kstat_cpu[i], NULL);
                if (new_kid >= 0) {
                    cpu = ((cpu_stat_t *)kstat_cpu[i]->ks_data)->cpu_sysinfo;
                    if ( tck_divisor == 1 ) {
                        pvals[7] += (jlong)(((jlong)cpu.cpu[CPU_IDLE]) * tck_dividend);
                        pvals[7] += (jlong)(((jlong)cpu.cpu[CPU_WAIT]) * tck_dividend);
                        pvals[8] += (jlong)(((jlong)cpu.cpu[CPU_KERNEL]) * tck_dividend);
                        pvals[9] += (jlong)(((jlong)cpu.cpu[CPU_USER]) * tck_dividend);
                    } else {
                        pvals[7] += (jlong)(((jlong)cpu.cpu[CPU_IDLE]) * tck_dividend / tck_divisor);
                        pvals[7] += (jlong)(((jlong)cpu.cpu[CPU_WAIT]) * tck_dividend / tck_divisor);
                        pvals[8] += (jlong)(((jlong)cpu.cpu[CPU_KERNEL]) * tck_dividend / tck_divisor);
                        pvals[9] += (jlong)(((jlong)cpu.cpu[CPU_USER]) * tck_dividend / tck_divisor);
                    }
                }
            }
        }

        /*
         * The next two are not implemented yet for Solaris
         * inf[4]  - Amount of shared memory
         * inf[5]  - Memory used by buffers
         *
         */
    }

#elif defined(DARWIN)

    uint64_t mem_total;
    size_t len = sizeof(mem_total);

    vm_statistics_data_t vm_info;
    mach_msg_type_number_t info_count = HOST_VM_INFO_COUNT;

    sysctlbyname("hw.memsize", &mem_total, &len, NULL, 0);
    pvals[0] = (jlong)mem_total;

    host_statistics(mach_host_self (), HOST_VM_INFO, (host_info_t)&vm_info, &info_count);
    pvals[1] = (jlong)(((double)vm_info.free_count)*vm_page_size);
    pvals[6] = (jlong)(100 - (pvals[1] * 100 / mem_total));
    rv = APR_SUCCESS;

/* DARWIN */
#else
    rv = APR_ENOTIMPL;
#endif
   (*e)->ReleaseLongArrayElements(e, inf, pvals, 0);
    return rv;
}
Пример #21
0
void
glibtop_get_mem_s (glibtop *server, glibtop_mem *buf)
{
    kstat_ctl_t * const kc = server->machine->kc;
    kstat_t *ksp;
    kstat_named_t *kn;

#undef PAGESIZE
#define PAGESIZE (server->machine->pagesize)
#define PAGESHIFT (PAGESIZE + 10)

#ifdef _LP64
#define KN_VALUE kn->value.ui64
#elif !defined(KSTAT_DATA_UINT32)
#define KN_VALUE kn->value.ul
#else
#define KN_VALUE kn->value.ui32
#endif

    memset (buf, 0, sizeof (glibtop_mem));

    buf->total = (guint64) sysconf(_SC_PHYS_PAGES) << PAGESHIFT;
    buf->flags = (1 << GLIBTOP_MEM_TOTAL);

    if(!kc)
	return;

    switch(kstat_chain_update(kc))
    {
	case -1: assert(0);  /* Debugging purposes, shouldn't happen */
	case 0:  break;
	default: glibtop_get_kstats(server);
    }

    if((ksp = server->machine->syspages) && kstat_read(kc, ksp, NULL) >= 0)
    {
	kn = kstat_data_lookup(ksp, "pagesfree");
	if(kn)
	{
	    buf->free = (KN_VALUE << PAGESHIFT);
	    buf->used = buf->total - buf->free;
	    buf->flags |= (1 << GLIBTOP_MEM_FREE);
	    buf->flags |= (1 << GLIBTOP_MEM_USED);
	}

	kn = kstat_data_lookup(ksp, "pageslocked");
	if(kn)
	{
	    buf->locked = (KN_VALUE << PAGESIZE);
	    buf->flags |= (1 << GLIBTOP_MEM_LOCKED);
	}
    }

    /* Bunyip module provides data in multiples of system page size */

    if((ksp = server->machine->bunyip) && kstat_read(kc, ksp, NULL) >= 0)
    {
	kn = kstat_data_lookup(ksp, "pages_exec");
	if(kn)
	{
	    buf->shared = (KN_VALUE << PAGESHIFT);
	    buf->flags |= (1 << GLIBTOP_MEM_SHARED);
	}

	kn = kstat_data_lookup(ksp, "pages_vnode");
	if(kn)
	{
	    buf->buffer = (KN_VALUE << PAGESHIFT);
	    buf->flags |= (1 << GLIBTOP_MEM_BUFFER);
	}

	kn = kstat_data_lookup(ksp, "pages_anon");
	if(kn)
	{
	    buf->user = (KN_VALUE << PAGESHIFT);
	    buf->flags |= (1 << GLIBTOP_MEM_USER);
	}
	else
	    goto user_old_way;
    }
    else /* Bunyip is not available, let's compute buf->user the old way */
    {
    user_old_way:
	buf->user = buf->total - buf->free - buf->cached - buf->buffer;
	buf->flags |= (1 << GLIBTOP_MEM_USER);
    }
}
Пример #22
0
int kupdate(int avenrun[3])
{
   kstat_t *ks;
   kid_t nkcid;
   int i;
   int changed = 0;
   static int ncpu = 0;
   static kid_t kcid = 0;
   kstat_named_t *kn;

   /*
   * 0. kstat_open
   */
   if (!kc) {
      kc = kstat_open();
      if (!kc) {
         perror("kstat_open ");
         return -1;
      }
      changed = 1;
      kcid = kc->kc_chain_id;
   }


   /* keep doing it until no more changes */
   kcid_changed:

   /*
   * 1.  kstat_chain_update
   */
   nkcid = kstat_chain_update(kc);
   if (nkcid) {
      /* UPDKCID will abort if nkcid is -1, so no need to check */
      changed = 1;
      kcid = nkcid;
   }
   UPDKCID(nkcid,0);

   ks = kstat_lookup(kc, "unix", 0, "system_misc");
   if (kstat_read(kc, ks, 0) == -1) {
      perror("kstat_read");
      return -1;
   }

#if 0
   /* load average */
   kn = kstat_data_lookup(ks, "avenrun_1min");
   if (kn)
      avenrun[0] = kn->value.ui32;
   kn = kstat_data_lookup(ks, "avenrun_5min");
   if (kn)
      avenrun[1] = kn->value.ui32;
   kn = kstat_data_lookup(ks, "avenrun_15min");
   if (kn)
      avenrun[2] = kn->value.ui32;

   /* nproc */
   kn = kstat_data_lookup(ks, "nproc");
   if (kn) {
      nproc = kn->value.ui32;
#ifdef NO_NPROC
      if (nproc > maxprocs)
      reallocproc(2 * nproc);
#endif
   }
#endif

   if (changed) {
      int ncpus = 0;

      /*
      * 2. get data addresses
      */

      ncpu = 0;

      kn = kstat_data_lookup(ks, "ncpus");
      if (kn && kn->value.ui32 > ncpus) {
         ncpus = kn->value.ui32;
         cpu_ks = (kstat_t **)sge_realloc(cpu_ks, ncpus * sizeof(kstat_t *), 1);
         cpu_stat = (cpu_stat_t *)sge_realloc(cpu_stat, ncpus * sizeof(cpu_stat_t), 1);
      }

      for (ks = kc->kc_chain; ks; ks = ks->ks_next) {
         if (strncmp(ks->ks_name, "cpu_stat", 8) == 0) {
            nkcid = kstat_read(kc, ks, NULL);
            /* if kcid changed, pointer might be invalid */
            UPDKCID(nkcid, kcid);

            cpu_ks[ncpu] = ks;
            ncpu++;
            if (ncpu >= ncpus) {
               break;
            }
         }
      }
      /* note that ncpu could be less than ncpus, but that's okay */
      changed = 0;
   }


   /*
   * 3. get data
   */

   for (i = 0; i < ncpu; i++) {
      nkcid = kstat_read(kc, cpu_ks[i], &cpu_stat[i]);
      /* if kcid changed, pointer might be invalid */
      UPDKCID(nkcid, kcid);
   }

   /* return the number of cpus found */
   return(ncpu);
}
Пример #23
0
int updateMemory( void ) {

	long			swaptotal;
	long			swapfree;
	long			swapused;
#ifdef HAVE_KSTAT
	kstat_ctl_t		*kctl;
	kstat_t			*ksp;
	kstat_named_t		*kdata;
#endif /* HAVE_KSTAT */
	swaptotal = swapused = swapfree = 0L;

	/*
	 *  Retrieve overall swap information from anonymous memory structure -
	 *  which is the same way "swap -s" retrieves it's statistics.
	 *
	 *  swapctl(SC_LIST, void *arg) does not return what we are looking for.
	 */

	if (swapctl(SC_AINFO, &am_swap) == -1)
		return(0);

	swaptotal = am_swap.ani_max;
	swapused = am_swap.ani_resv;
	swapfree = swaptotal - swapused;

	totalswap = pagetok(swaptotal);
	freeswap = pagetok(swapfree);

#ifdef HAVE_KSTAT
	/*
	 *  get a kstat handle and update the user's kstat chain
	 */
	if( (kctl = kstat_open()) == NULL )
		return( 0 );
	while( kstat_chain_update( kctl ) != 0 )
		;

	totalmem = pagetok( sysconf( _SC_PHYS_PAGES ));

	/*
	 *  traverse the kstat chain to find the appropriate statistics
	 */
	if( (ksp = kstat_lookup( kctl, "unix", 0, "system_pages" )) == NULL )
		return( 0 );
	if( kstat_read( kctl, ksp, NULL ) == -1 )
		return( 0 );

	/*
	 *  lookup the data
	 */
	 kdata = (kstat_named_t *) kstat_data_lookup( ksp, "freemem" );
	 if( kdata != NULL )
	 	freemem = pagetok( kdata->value.ui32 );

	kstat_close( kctl );
#endif /* ! HAVE_KSTAT */

	Dirty = 0;

	return( 0 );
}
static void update_cpu_kstat_counters() {
    if(kstat_chain_update(kstat_ctrl) != 0) {
        free(cpu_loads);
        map_cpu_kstat_counters();
    }
}
Пример #25
0
    void
    CPU_Load_Monitor::access_kstats (unsigned long *which_idle)
    {
      this->kstats_ = kstat_open ();

      if (this->kstats_ == 0)
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("opening kstats file failed\n")));
          return;
        }

      this->kstat_id_ = this->kstats_->kc_chain_id;

      while (true)
        {
          this->kernel_ = 0UL;
          this->wait_ = 0UL;
          this->user_ = 0UL;
          (*which_idle) = 0UL;

          /// Unlike Linux's "/proc/stat", there is no entry for total CPU
          /// stats, so we have to sum them manually.
          for (this->kstat_ = this->kstats_->kc_chain;
               this->kstat_ != 0;
               this->kstat_ = this->kstat_->ks_next)
            {
              int result = ACE_OS::strncmp (this->kstat_->ks_name,
                                            "cpu_stat",
                                            ACE_OS::strlen ("cpu_stat"));

              if (result == 0)
                {
                  /// Because the kstat chain can change dynamically,
                  /// watch the chain ID and restart the walk if the ID
                  /// differs from what we saw during the walk. The restart
                  /// is done by breaking from the cycle with kstat_ not 0.

                  kid_t kstat_id = kstat_read (this->kstats_, this->kstat_, 0);

                  if (kstat_id != this->kstat_id_)
                    {
                      break;
                    }

                  cpu_stat_t &kstat_cpu =
                    *((cpu_stat_t *) this->kstat_->ks_data);

                  this->kernel_ += kstat_cpu.cpu_sysinfo.cpu[CPU_KERNEL];
                  this->wait_ += kstat_cpu.cpu_sysinfo.cpu[CPU_WAIT];
                  this->user_ += kstat_cpu.cpu_sysinfo.cpu[CPU_USER];
                  (*which_idle) += kstat_cpu.cpu_sysinfo.cpu[CPU_IDLE];
                }
            }

          if (this->kstat_ != 0)
            {
              /// The ID changed underneath us, so get the new one and
              /// start again.
              this->kstat_id_ = kstat_chain_update (this->kstats_);

              if (! this->kstat_id_ > 0)
                {
                  ACE_ERROR ((LM_ERROR,
                              ACE_TEXT ("kstat chain update ")
                              ACE_TEXT ("returned null id\n")));
                  return;
                }
            }
          else
            {
              /// Clean run, exit the WHILE loop.
              break;
            }
        }

      int status = kstat_close (this->kstats_);

      if (status != 0)
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("closing kstats file failed\n")));
        }
    }
Пример #26
0
static ERL_NIF_TERM
update_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
	ks_returner_t	*ret;
	kstat_raw_reader_t	save_raw = NULL;
	ks_handle_t	*handle;
	kid_t		id;
	ks_instance_t	*ksi, *ktmp;
	ks_nvpair_t	*nvpair, *ntmp;
	kstat_t		*kp;
	int		count = 0;

	ret = new_returner(env);

	if (argc < 1) {
		return EKSTAT_RETURN(enif_make_badarg(ret->env));
	}

	if (!enif_get_resource(env, argv[0], kstat_handle, (void **)(&handle))) {
		return EKSTAT_RETURN(enif_make_badarg(ret->env));
	}

	if ((id = kstat_chain_update(handle->ks_ctl)) == 0 && handle->ks_id != -1) {
		return EKSTAT_RETURN(EKSTAT_ERROR("kstat_chain_update stopped"));
	}

	if (id == -1) {
		return EKSTAT_RETURN(EKSTAT_ERROR("kid not valid"));
	}

	/* Free the instances list */
	ksi = list_head(&handle->instances_list);
	while (ksi != NULL) {
		nvpair = list_head(&ksi->ks_nvlist);
		while (nvpair != NULL) {
			ntmp = nvpair;
			nvpair = list_next(&ksi->ks_nvlist, nvpair);
			list_remove(&ksi->ks_nvlist, ntmp);
			if (ntmp->data_type == KSTAT_DATA_STRING)
				free(ntmp->value.str.addr.ptr);
			free(ntmp);
		}

		ktmp = ksi;
		ksi = list_next(&handle->instances_list, ksi);
		list_remove(&handle->instances_list, ktmp);
		list_destroy(&ktmp->ks_nvlist);
		free(ktmp);
	}

	for (kp = handle->ks_ctl->kc_chain; kp != NULL; kp = kp->ks_next) {
		/* Don't bother storing the kstat headers */
		if (strncmp(kp->ks_name, "kstat_", 6) == 0) {
			continue;
		}

		/* Don't bother storing raw stats we don't understand */
		if (kp->ks_type == KSTAT_TYPE_RAW) {
			save_raw = lookup_raw_kstat_fn(kp->ks_module, kp->ks_name);
			if (save_raw == NULL) {
				continue;
			}
		}

		/*
		 * Allocate a new instance and fill in the values
		 * we know so far.
		 */
		ksi = (ks_instance_t *)(malloc(sizeof (ks_instance_t)));
		if (ksi == NULL) {
			return EKSTAT_RETURN(EKSTAT_ERROR("ks_instance_t malloc"));
		}

		list_link_init(&ksi->ks_next);

		(void) strlcpy(ksi->ks_module, kp->ks_module, KSTAT_STRLEN);
		(void) strlcpy(ksi->ks_name, kp->ks_name, KSTAT_STRLEN);
		(void) strlcpy(ksi->ks_class, kp->ks_class, KSTAT_STRLEN);

		ksi->ks_instance = kp->ks_instance;
		ksi->ks_snaptime = kp->ks_snaptime;
		ksi->ks_type = kp->ks_type;

		list_create(&ksi->ks_nvlist, sizeof (ks_nvpair_t), offsetof(ks_nvpair_t, nv_next));

		SAVE_HRTIME_X(ret, ksi, "crtime", kp->ks_crtime);
		SAVE_HRTIME_X(ret, ksi, "snaptime", kp->ks_snaptime);

		/* Insert this instance into a sorted list */
		ktmp = list_head(&handle->instances_list);
		while (ktmp != NULL && compare_instances(ksi, ktmp) < 0) {
			ktmp = list_next(&handle->instances_list, ktmp);
		}

		list_insert_before(&handle->instances_list, ktmp, ksi);

		/* Read the actual statistics */
		id = kstat_read(handle->ks_ctl, kp, NULL);
		if (id == -1) {
			continue;
		}

		switch (kp->ks_type) {
		case KSTAT_TYPE_RAW:
			save_raw(ret, kp, ksi);
			break;
		case KSTAT_TYPE_NAMED:
			save_named(ret, kp, ksi);
			break;
		case KSTAT_TYPE_INTR:
			save_intr(ret, kp, ksi);
			break;
		case KSTAT_TYPE_IO:
			save_io(ret, kp, ksi);
			break;
		case KSTAT_TYPE_TIMER:
			save_timer(ret, kp, ksi);
			break;
		default:
			assert(B_FALSE); /* Invalid type */
			break;
		}

		count++;
	}

	return EKSTAT_RETURN(EKSTAT_OK(EKSTAT_INT(count)));
}
Пример #27
0
int updateSwap( int upd ) {
	long			swaptotal;
	long			swapfree;
	long			swapused;
#ifdef HAVE_KSTAT
	kstat_ctl_t		*kctl;
	kstat_t			*ksp;
	struct timeval 		sampling;
	vminfo_t		vmi;

	uint64_t _swap_resv = 0;
	uint64_t _swap_free = 0;
	uint64_t _swap_avail = 0;
	uint64_t _swap_alloc = 0;

#endif /* HAVE_KSTAT */
	swaptotal = swapused = swapfree = 0L;

#ifndef HAVE_KSTAT
	/*
	 *  Retrieve overall swap information from anonymous memory structure -
	 *  which is the same way "swap -s" retrieves it's statistics.
	 *
	 *  swapctl(SC_LIST, void *arg) does not return what we are looking for.
	 */

	if (swapctl(SC_AINFO, &am_swap) == -1)
		return(0);

	swaptotal = am_swap.ani_max;
	swapused = am_swap.ani_resv;
	swapfree = swaptotal - swapused;

	usedswap = pagetok(swapused);
	freeswap = pagetok(swapfree);

#else /* HAVE_KSTAT */
	/*
	 *  get a kstat handle and update the user's kstat chain
	 */
	if( (kctl = kstat_open()) == NULL )
		return( 0 );
	while( kstat_chain_update( kctl ) != 0 )
		;

	totalmem = pagetok( sysconf( _SC_PHYS_PAGES ));

	if( (ksp = kstat_lookup( kctl, "unix", -1, "vminfo" )) == NULL ) {
		goto done;
	}

	if( kstat_read( kctl, ksp, &vmi ) == -1 ) {
                goto done;
        }

	_swap_resv = vmi.swap_resv - swap_resv;
	if (_swap_resv)
		swap_resv = vmi.swap_resv;

	_swap_free = vmi.swap_free - swap_free;
	if (_swap_free)
		swap_free = vmi.swap_free;

	_swap_avail = vmi.swap_avail - swap_avail;
	if (_swap_avail)
		swap_avail = vmi.swap_avail;

	_swap_alloc = vmi.swap_alloc - swap_alloc;
	if (_swap_alloc)
		swap_alloc = vmi.swap_alloc;

	if (upd) {
		long timeInterval;

		gettimeofday(&sampling, 0);
		timeInterval = sampling.tv_sec - lastSampling.tv_sec +
		    ( sampling.tv_usec - lastSampling.tv_usec ) / 1000000.0;
		lastSampling = sampling;
		timeInterval = timeInterval > 0 ? timeInterval : 1;

		_swap_resv = _swap_resv / timeInterval;
		_swap_free = _swap_free / timeInterval;
		_swap_avail = _swap_avail / timeInterval;
		_swap_alloc = _swap_alloc / timeInterval;

		if (_swap_alloc)
			usedswap = pagetok((unsigned long)(_swap_alloc + _swap_free - _swap_avail));

		/*
		 * Assume minfree = totalmem / 8, i.e. it has not been tuned
		 */
		if (_swap_avail)
			freeswap = pagetok((unsigned long)(_swap_avail + totalmem / 8));
	}
done:
	kstat_close( kctl );
#endif /* ! HAVE_KSTAT */

	return( 0 );
}
Пример #28
0
int
main(int argc, char **argv)
{
ks_selector_t	*nselector;
ks_selector_t	*uselector;
kstat_ctl_t	*kc;
hrtime_t	start_n;
hrtime_t	period_n;
boolean_t	errflg = B_FALSE;
boolean_t	nselflg = B_FALSE;
boolean_t	uselflg = B_FALSE;
char		*q;
int		count = 1;
int		infinite_cycles = 0;
int		interval = 0;
int		n = 0;
int		c, m, tmp;

(void) setlocale(LC_ALL, "");
#if !defined(TEXT_DOMAIN)		/* Should be defined by cc -D */
#define	TEXT_DOMAIN "SYS_TEST"		/* Use this only if it wasn't */
#endif
(void) textdomain(TEXT_DOMAIN);

/*
 * Create the selector list and a dummy default selector to match
 * everything. While we process the cmdline options we will add
 * selectors to this list.
 */
list_create(&selector_list, sizeof (ks_selector_t),
		offsetof(ks_selector_t, ks_next));

nselector = new_selector();

/*
 * Parse named command line arguments.
 */
while ((c = getopt(argc, argv, "h?Cqjlpx:H:T:m:i:n:s:c:")) != EOF)
	switch (c) {
	case 'h':
	case '?':
		usage();
		exit(0);
		break;
	case 'C':
		g_pflg = g_cflg = B_TRUE;
		break;
	case 'q':
		g_qflg = B_TRUE;
		break;
	case 'j':
		g_jflg = B_TRUE;
		break;
	case 'l':
		g_pflg = g_lflg = B_TRUE;
		break;
	case 'H':
		g_host = B_TRUE;
		tachyon_host = (char *)ks_safe_strdup(optarg);
		break;
	case 'x':
		g_url = g_pflg = g_nflg = B_TRUE;
		// If we use nsq we need to init curl globaly.
    tm_curl_global_init();
		tachyon_url = (char *)ks_safe_strdup(optarg);
		break;
	case 'p':
		g_pflg = B_TRUE;
		break;
	case 'T':
		switch (*optarg) {
		case 'd':
			g_timestamp_fmt = DDATE;
			break;
		case 'u':
			g_timestamp_fmt = UDATE;
			break;
		default:
			errflg = B_TRUE;
		}
		break;
	case 'm':
		nselflg = B_TRUE;
		nselector->ks_module.pstr =
				(char *)ks_safe_strdup(optarg);
		break;
	case 'i':
		nselflg = B_TRUE;
		nselector->ks_instance.pstr =
				(char *)ks_safe_strdup(optarg);
		break;
	case 'n':
		nselflg = B_TRUE;
		nselector->ks_name.pstr =
				(char *)ks_safe_strdup(optarg);
		break;
	case 's':
		nselflg = B_TRUE;
		nselector->ks_statistic.pstr =
				(char *)ks_safe_strdup(optarg);
		break;
	case 'c':
		g_ks_class.pstr =
				(char *)ks_safe_strdup(optarg);
		break;
	default:
		errflg = B_TRUE;
		break;
	}

if (g_qflg && (g_jflg || g_pflg || g_nflg)) {
	(void) fprintf(stderr, gettext(
			"-q and -lpjn are mutually exclusive\n"));
	errflg = B_TRUE;
}
if (g_url ^ g_host) {
	(void) fprintf(stderr, gettext(
			"-H and -x must both be set.\n"));
	errflg = B_TRUE;
}

if (errflg) {
	usage();
	exit(2);
}

argc -= optind;
argv += optind;

/*
 * Consume the rest of the command line. Parsing the
 * unnamed command line arguments.
 */
while (argc--) {
	errno = 0;
	tmp = strtoul(*argv, &q, 10);
	if (tmp == ULONG_MAX && errno == ERANGE) {
		if (n == 0) {
			(void) fprintf(stderr, gettext(
					"Interval is too large\n"));
		} else if (n == 1) {
			(void) fprintf(stderr, gettext(
					"Count is too large\n"));
		}
		usage();
		exit(2);
	}

	if (errno != 0 || *q != '\0') {
		m = 0;
		uselector = new_selector();
		while ((q = (char *)strsep(argv, ":")) != NULL) {
			m++;
			if (m > 4) {
				free(uselector);
				usage();
				exit(2);
			}

			if (*q != '\0') {
				switch (m) {
				case 1:
					uselector->ks_module.pstr =
							(char *)ks_safe_strdup(q);
					break;
				case 2:
					uselector->ks_instance.pstr =
							(char *)ks_safe_strdup(q);
					break;
				case 3:
					uselector->ks_name.pstr =
							(char *)ks_safe_strdup(q);
					break;
				case 4:
					uselector->ks_statistic.pstr =
							(char *)ks_safe_strdup(q);
					break;
				default:
					assert(B_FALSE);
				}
			}
		}

		uselflg = B_TRUE;
		list_insert_tail(&selector_list, uselector);
	} else {
		if (tmp < 1) {
			if (n == 0) {
				(void) fprintf(stderr, gettext(
						"Interval must be an "
						"integer >= 1"));
			} else if (n == 1) {
				(void) fprintf(stderr, gettext(
						"Count must be an integer >= 1"));
			}
			usage();
			exit(2);
		} else {
			if (n == 0) {
				interval = tmp;
				count = -1;
			} else if (n == 1) {
				count = tmp;
			} else {
				usage();
				exit(2);
			}
		}
		n++;
	}
	argv++;
}

/*
 * Check if we founded a named selector on the cmdline.
 */
if (uselflg) {
	if (nselflg) {
		(void) fprintf(stderr, gettext(
				"[module[:instance[:name[:statistic]]]] and "
				"-m -i -n -s are mutually exclusive"));
		usage();
		exit(2);
	} else {
		free(nselector);
	}
} else {
	list_insert_tail(&selector_list, nselector);
}

assert(!list_is_empty(&selector_list));

list_create(&instances_list, sizeof (ks_instance_t),
		offsetof(ks_instance_t, ks_next));

while ((kc = kstat_open()) == NULL) {
	if (errno == EAGAIN) {
		(void) poll(NULL, 0, 200);
	} else {
		perror("kstat_open");
		exit(3);
	}
}

if (count > 1) {
	if (signal(SIGCONT, cont_handler) == SIG_ERR) {
		(void) fprintf(stderr, gettext(
				"signal failed"));
		exit(3);
	}
}

period_n = (hrtime_t)interval * NANOSEC;
start_n = gethrtime();


while (count == -1 || count-- > 0) {
	ks_instances_read(kc);
  kstat_time = time(NULL);
	ks_instances_print();

	if (interval && count) {
		ks_sleep_until(&start_n, period_n, infinite_cycles,
				&caught_cont);
		(void) kstat_chain_update(kc);
    if (! g_nflg)
  		(void) putchar('\n');
	}
}

(void) kstat_close(kc);

return (g_matched);
}
Пример #29
0
    /*
     * Load the latest CPU usage statistics
     */
int netsnmp_cpu_arch_load( netsnmp_cache *cache, void *magic ) {
    int               i=1;
    kstat_t          *ksp;
    cpu_stat_t        cs;
    netsnmp_cpu_info *cpu = netsnmp_cpu_get_byIdx( -1, 0 );
    netsnmp_cpu_info *cpu2;

        /* Clear overall stats, ready for summing individual CPUs */
    cpu->user_ticks = 0;
    cpu->idle_ticks = 0;
    cpu->kern_ticks = 0;
    cpu->wait_ticks = 0;
    cpu->sys2_ticks = 0;
    cpu->swapIn       = 0;
    cpu->swapOut      = 0;
    cpu->nInterrupts  = 0;
    cpu->nCtxSwitches = 0;

    kstat_chain_update( kstat_fd );
    DEBUGMSGTL(("cpu", "cpu_kstat load\n "));
    for (ksp = kstat_fd->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
        if (ksp->ks_flags & KSTAT_FLAG_INVALID)
            continue;
        if (strcmp(ksp->ks_module, "cpu_stat") == 0) {
            i    = ksp->ks_instance;
            cpu2 = netsnmp_cpu_get_byIdx( i, 0 );
            if ( !cpu2 )  
                break;   /* or continue ? */  /* Skip new CPUs */
            if ((ksp->ks_type != KSTAT_TYPE_RAW) ||
                (ksp->ks_data_size != sizeof(cs))||
                (kstat_read(kstat_fd, ksp, &cs) == -1)) {
                DEBUGMSGTL(("cpu", "cpu_kstat load failed (%d)\n ", i));
                break;   /* or continue ? */
            }

            cpu2->user_ticks = (unsigned long long)cs.cpu_sysinfo.cpu[CPU_USER];
            cpu2->idle_ticks = (unsigned long long)cs.cpu_sysinfo.cpu[CPU_IDLE];
            cpu2->kern_ticks = (unsigned long long)cs.cpu_sysinfo.cpu[CPU_KERNEL];
            cpu2->wait_ticks = (unsigned long long)cs.cpu_sysinfo.cpu[CPU_WAIT];
              /* or cs.cpu_sysinfo.wait[W_IO]+cs.cpu_sysinfo.wait[W_PIO] */
            cpu2->sys2_ticks = (unsigned long long)cpu2->kern_ticks+cpu2->wait_ticks;
                /* nice_ticks, intrpt_ticks, sirq_ticks unused */

                /* sum these for the overall stats */
            cpu->user_ticks += (unsigned long long)cs.cpu_sysinfo.cpu[CPU_USER];
            cpu->idle_ticks += (unsigned long long)cs.cpu_sysinfo.cpu[CPU_IDLE];
            cpu->kern_ticks += (unsigned long long)cs.cpu_sysinfo.cpu[CPU_KERNEL];
            cpu->wait_ticks += (unsigned long long)cs.cpu_sysinfo.cpu[CPU_WAIT];
              /* or cs.cpu_sysinfo.wait[W_IO]+cs.cpu_sysinfo.wait[W_PIO] */
            cpu->sys2_ticks += (unsigned long long)cpu2->kern_ticks+cpu2->wait_ticks;

                /*
                 * Interrupt/Context Switch statistics
                 *   XXX - Do these really belong here ?
                 */
            cpu->swapIn       += (unsigned long long)cs.cpu_vminfo.swapin;
            cpu->swapOut      += (unsigned long long)cs.cpu_vminfo.swapout;
            cpu->pageIn       += (unsigned long long)cs.cpu_sysinfo.bread;
            cpu->pageOut      += (unsigned long long)cs.cpu_sysinfo.bwrite;
            cpu->nInterrupts  += (unsigned long long)cs.cpu_sysinfo.intr;
            cpu->nCtxSwitches += (unsigned long long)cs.cpu_sysinfo.pswitch;
        }
    }
    return 0;
}
Пример #30
0
void KMemoryWidget::update() {

	kstat_ctl_t	*kctl;
	kstat_t		*ksp;
	kstat_named_t	*kdata;

	/*
	 *  get a kstat handle first and update the user's kstat chain
	 */
	if( (kctl = kstat_open()) == NULL )
		return;
	while( kstat_chain_update( kctl ) != 0 )
		;

	/*
	 *  traverse the kstat chain to find the appropriate kstat
	 */
	if( (ksp = kstat_lookup( kctl, "unix", 0, "system_pages" )) == NULL )
		return;

	if( kstat_read( kctl, ksp, NULL ) == -1 )
		return;

	/*
	 *  lookup the data
	 */
#if 0
	kdata = (kstat_named_t *) kstat_data_lookup( ksp, "physmem" );
	if( kdata != NULL ) {
		Memory_Info[TOTAL_MEM] = PAGETOK(kdata->value.ui32);
	}
#endif
	Memory_Info[TOTAL_MEM] = PAGETOK(sysconf(_SC_PHYS_PAGES));

	kdata = (kstat_named_t *) kstat_data_lookup( ksp, "freemem" );
	if( kdata != NULL )
		Memory_Info[FREE_MEM] = PAGETOK(kdata->value.ui32);
#ifdef __GNUC__
#warning "FIXME: Memory_Info[CACHED_MEM]"
#endif	
	Memory_Info[CACHED_MEM] = NO_MEMORY_INFO; // cached memory in ram
	  
	kstat_close( kctl );

	/*
	 *  Swap Info
	 */

	struct anoninfo		am_swap;
	long			swaptotal;
	long			swapfree;
	long			swapused;

	swaptotal = swapused = swapfree = 0L;

	/*
	 *  Retrieve overall swap information from anonymous memory structure -
	 *  which is the same way "swap -s" retrieves it's statistics.
	 *
	 *  swapctl(SC_LIST, void *arg) does not return what we are looking for.
	 */

	if (swapctl(SC_AINFO, &am_swap) == -1)
		return;

	swaptotal = am_swap.ani_max;
	swapused = am_swap.ani_resv;
	swapfree = swaptotal - swapused;

	Memory_Info[SWAP_MEM]     = PAGETOK(swaptotal);
	Memory_Info[FREESWAP_MEM] = PAGETOK(swapfree);
}