Esempio n. 1
0
static int read_xattrs_from_system(char *filename, struct xattr_list **xattrs)
{
	ssize_t size, vsize;
	char *xattr_names, *p;
	int i;
	struct xattr_list *xattr_list = NULL;

#if 0
	while(1) {
		size = llistxattr(filename, NULL, 0);
		if(size <= 0) {
			if(size < 0 && errno != ENOTSUP)
				ERROR("llistxattr for %s failed in read_attrs,"
					" because %s\n", filename,
					strerror(errno));
			return 0;
		}

		xattr_names = malloc(size);
		if(xattr_names == NULL) {
			ERROR("Out of memory in read_attrs\n");
			return 0;
		}

		size = llistxattr(filename, xattr_names, size);
		if(size < 0) {
			free(xattr_names);
			if(errno == ERANGE)
				/* xattr list grew?  Try again */
				continue;
			else {
				ERROR("llistxattr for %s failed in read_attrs,"
					" because %s\n", filename,
					strerror(errno));
				return 0;
			}
		}

		break;
	}
#else
		ERROR("llistxattr not available");
#endif

	for(i = 0, p = xattr_names; p < xattr_names + size; i++) {
		struct xattr_list *x = realloc(xattr_list, (i + 1) *
						sizeof(struct xattr_list));
		if(x == NULL) {
			ERROR("Out of memory in read_attrs\n");
			goto failed;
		} else
			xattr_list = x;

		xattr_list[i].type = get_prefix(&xattr_list[i], p);
		p += strlen(p) + 1;
		if(xattr_list[i].type == -1) {
			ERROR("Unrecognised xattr prefix %s\n",
				xattr_list[i].full_name);
			free(xattr_list[i].full_name);
			i--;
			continue;
		}

#if 0
		while(1) {
			vsize = lgetxattr(filename, xattr_list[i].full_name,
								NULL, 0);
			if(vsize < 0) {
				ERROR("lgetxattr failed for %s in read_attrs,"
					" because %s\n", filename,
					strerror(errno));
				free(xattr_list[i].full_name);
				goto failed;
			}

			xattr_list[i].value = malloc(vsize);
			if(xattr_list[i].value == NULL) {
				ERROR("Out of memory in read_attrs\n");
				free(xattr_list[i].full_name);
				goto failed;
			}

			vsize = lgetxattr(filename, xattr_list[i].full_name,
						xattr_list[i].value, vsize);
			if(vsize < 0) {
				free(xattr_list[i].value);
				if(errno == ERANGE)
					/* xattr grew?  Try again */
					continue;
				else {
					ERROR("lgetxattr failed for %s in "
						"read_attrs, because %s\n",
						filename, strerror(errno));
					free(xattr_list[i].full_name);
					goto failed;
				}
			}
			
			break;
		}
#else
		ERROR("lgetxattr not supported");
#endif
		xattr_list[i].vsize = vsize;

		TRACE("read_xattrs_from_system: filename %s, xattr name %s,"
			" vsize %d\n", filename, xattr_list[i].full_name,
			xattr_list[i].vsize);
	}
	free(xattr_names);
	*xattrs = xattr_list;
	return i;

failed:
	while(--i >= 0) {
		free(xattr_list[i].full_name);
		free(xattr_list[i].value);
	}
	free(xattr_list);
	free(xattr_names);
	return 0;
}
/*
 * Function w83977af_open (iobase, irq)
 *
 *    Open driver instance
 *
 */
int w83977af_open(int i, unsigned int iobase, unsigned int irq, 
		  unsigned int dma)
{
	struct net_device *dev;
        struct w83977af_ir *self;
	int err;

	IRDA_DEBUG(0, "%s()\n", __FUNCTION__ );

	/* Lock the port that we need */
	if (!request_region(iobase, CHIP_IO_EXTENT, driver_name)) {
		IRDA_DEBUG(0, "%s(), can't get iobase of 0x%03x\n",
		      __FUNCTION__ , iobase);
		return -ENODEV;
	}

	if (w83977af_probe(iobase, irq, dma) == -1) {
		err = -1;
		goto err_out;
	}
	/*
	 *  Allocate new instance of the driver
	 */
	dev = alloc_irdadev(sizeof(struct w83977af_ir));
	if (dev == NULL) {
		printk( KERN_ERR "IrDA: Can't allocate memory for "
			"IrDA control block!\n");
		err = -ENOMEM;
		goto err_out;
	}

	self = dev->priv;
	spin_lock_init(&self->lock);
   

	/* Initialize IO */
	self->io.fir_base   = iobase;
        self->io.irq       = irq;
        self->io.fir_ext   = CHIP_IO_EXTENT;
        self->io.dma       = dma;
        self->io.fifo_size = 32;

	/* Initialize QoS for this device */
	irda_init_max_qos_capabilies(&self->qos);
	
	/* The only value we must override it the baudrate */

	/* FIXME: The HP HDLS-1100 does not support 1152000! */
	self->qos.baud_rate.bits = IR_9600|IR_19200|IR_38400|IR_57600|
		IR_115200|IR_576000|IR_1152000|(IR_4000000 << 8);

	/* The HP HDLS-1100 needs 1 ms according to the specs */
	self->qos.min_turn_time.bits = qos_mtt_bits;
	irda_qos_bits_to_value(&self->qos);
	
	/* Max DMA buffer size needed = (data_size + 6) * (window_size) + 6; */
	self->rx_buff.truesize = 14384; 
	self->tx_buff.truesize = 4000;
	
	/* Allocate memory if needed */
	self->rx_buff.head =
		dma_alloc_coherent(NULL, self->rx_buff.truesize,
				   &self->rx_buff_dma, GFP_KERNEL);
	if (self->rx_buff.head == NULL) {
		err = -ENOMEM;
		goto err_out1;
	}

	memset(self->rx_buff.head, 0, self->rx_buff.truesize);
	
	self->tx_buff.head =
		dma_alloc_coherent(NULL, self->tx_buff.truesize,
				   &self->tx_buff_dma, GFP_KERNEL);
	if (self->tx_buff.head == NULL) {
		err = -ENOMEM;
		goto err_out2;
	}
	memset(self->tx_buff.head, 0, self->tx_buff.truesize);

	self->rx_buff.in_frame = FALSE;
	self->rx_buff.state = OUTSIDE_FRAME;
	self->tx_buff.data = self->tx_buff.head;
	self->rx_buff.data = self->rx_buff.head;
	self->netdev = dev;

	/* Keep track of module usage */
	SET_MODULE_OWNER(dev);

	/* Override the network functions we need to use */
	dev->hard_start_xmit = w83977af_hard_xmit;
	dev->open            = w83977af_net_open;
	dev->stop            = w83977af_net_close;
	dev->do_ioctl        = w83977af_net_ioctl;
	dev->get_stats	     = w83977af_net_get_stats;

	err = register_netdev(dev);
	if (err) {
		ERROR("%s(), register_netdevice() failed!\n", __FUNCTION__);
		goto err_out3;
	}
	MESSAGE("IrDA: Registered device %s\n", dev->name);

	/* Need to store self somewhere */
	dev_self[i] = self;
	
	return 0;
err_out3:
	dma_free_coherent(NULL, self->tx_buff.truesize,
			  self->tx_buff.head, self->tx_buff_dma);
err_out2:	
	dma_free_coherent(NULL, self->rx_buff.truesize,
			  self->rx_buff.head, self->rx_buff_dma);
err_out1:
	free_netdev(dev);
err_out:
	release_region(iobase, CHIP_IO_EXTENT);
	return err;
}
Esempio n. 3
0
status_t
BTimeSource::HandleMessage(int32 message,
						   const void *rawdata,
						   size_t size)
{
	PRINT(4, "BTimeSource::HandleMessage %#" B_PRIx32 ", node %" B_PRId32 "\n",
		message, fNodeID);
	status_t rv;
	switch (message) {
		case TIMESOURCE_OP:
		{
			const time_source_op_info *data = static_cast<const time_source_op_info *>(rawdata);

			status_t result;
			result = TimeSourceOp(*data, NULL);
			if (result != B_OK) {
				ERROR("BTimeSource::HandleMessage: TimeSourceOp failed\n");
			}

			switch (data->op) {
				case B_TIMESOURCE_START:
					DirectStart(data->real_time);
					break;
				case B_TIMESOURCE_STOP:
					DirectStop(data->real_time, false);
					break;
				case B_TIMESOURCE_STOP_IMMEDIATELY:
					DirectStop(data->real_time, true);
					break;
				case B_TIMESOURCE_SEEK:
					DirectSeek(data->performance_time, data->real_time);
					break;
			}
			return B_OK;
		}

		case TIMESOURCE_ADD_SLAVE_NODE:
		{
			const timesource_add_slave_node_command *data = static_cast<const timesource_add_slave_node_command *>(rawdata);
			DirectAddMe(data->node);
			return B_OK;
		}

		case TIMESOURCE_REMOVE_SLAVE_NODE:
		{
			const timesource_remove_slave_node_command *data = static_cast<const timesource_remove_slave_node_command *>(rawdata);
			DirectRemoveMe(data->node);
			return B_OK;
		}

		case TIMESOURCE_GET_START_LATENCY:
		{
			const timesource_get_start_latency_request *request = static_cast<const timesource_get_start_latency_request *>(rawdata);
			timesource_get_start_latency_reply reply;
			rv = GetStartLatency(&reply.start_latency);
			request->SendReply(rv, &reply, sizeof(reply));
			return B_OK;
		}
	}
	return B_ERROR;
}
Esempio n. 4
0
static int mysql_read (user_data_t *ud)
{
	mysql_database_t *db;
	MYSQL     *con;
	MYSQL_RES *res;
	MYSQL_ROW  row;
	char      *query;

	derive_t qcache_hits          = 0;
	derive_t qcache_inserts       = 0;
	derive_t qcache_not_cached    = 0;
	derive_t qcache_lowmem_prunes = 0;
	gauge_t qcache_queries_in_cache = NAN;

	gauge_t threads_running   = NAN;
	gauge_t threads_connected = NAN;
	gauge_t threads_cached    = NAN;
	derive_t threads_created = 0;

	unsigned long long traffic_incoming = 0ULL;
	unsigned long long traffic_outgoing = 0ULL;
    unsigned long mysql_version = 0ULL;

	if ((ud == NULL) || (ud->data == NULL))
	{
		ERROR ("mysql plugin: mysql_database_read: Invalid user data.");
		return (-1);
	}

	db = (mysql_database_t *) ud->data;

	/* An error message will have been printed in this case */
	if ((con = getconnection (db)) == NULL)
		return (-1);

  mysql_version = mysql_get_server_version(con);

	query = "SHOW STATUS";
	if (mysql_version >= 50002)
		query = "SHOW GLOBAL STATUS";

	res = exec_query (con, query);
	if (res == NULL)
		return (-1);

	while ((row = mysql_fetch_row (res)))
	{
		char *key;
		unsigned long long val;

		key = row[0];
		val = atoll (row[1]);

		if (strncmp (key, "Com_", 
			          strlen ("Com_")) == 0)
		{
			if (val == 0ULL)
				continue;

			/* Ignore `prepared statements' */
			if (strncmp (key, "Com_stmt_", strlen ("Com_stmt_")) != 0)
				counter_submit ("mysql_commands", 
						key + strlen ("Com_"), 
						val, db);
		}
		else if (strncmp (key, "Handler_", 
				        strlen ("Handler_")) == 0)
		{
			if (val == 0ULL)
				continue;

			counter_submit ("mysql_handler", 
					key + strlen ("Handler_"), 
					val, db);
		}
		else if (strncmp (key, "Qcache_",
       				        strlen ("Qcache_")) == 0)
		{
			if (strcmp (key, "Qcache_hits") == 0)
				qcache_hits = (derive_t) val;
			else if (strcmp (key, "Qcache_inserts") == 0)
				qcache_inserts = (derive_t) val;
			else if (strcmp (key, "Qcache_not_cached") == 0)
				qcache_not_cached = (derive_t) val;
			else if (strcmp (key, "Qcache_lowmem_prunes") == 0)
				qcache_lowmem_prunes = (derive_t) val;
			else if (strcmp (key, "Qcache_queries_in_cache") == 0)
				qcache_queries_in_cache = (gauge_t) val;
		}
		else if (strncmp (key, "Bytes_", 
				        strlen ("Bytes_")) == 0)
		{
			if (strcmp (key, "Bytes_received") == 0)
				traffic_incoming += val;
			else if (strcmp (key, "Bytes_sent") == 0)
				traffic_outgoing += val;
		}
		else if (strncmp (key, "Threads_", 
       				        strlen ("Threads_")) == 0)
		{
			if (strcmp (key, "Threads_running") == 0)
				threads_running = (gauge_t) val;
			else if (strcmp (key, "Threads_connected") == 0)
				threads_connected = (gauge_t) val;
			else if (strcmp (key, "Threads_cached") == 0)
				threads_cached = (gauge_t) val;
			else if (strcmp (key, "Threads_created") == 0)
				threads_created = (derive_t) val;
		}
		else if (strncmp (key, "Table_locks_",
					strlen ("Table_locks_")) == 0)
		{
			counter_submit ("mysql_locks",
					key + strlen ("Table_locks_"),
					val, db);
		}
		else if (db->innodb_stats && strncmp (key, "Innodb_", strlen ("Innodb_")) == 0)
		{
			/* buffer pool */
			if (strcmp (key, "Innodb_buffer_pool_pages_data") == 0)
				gauge_submit ("mysql_bpool_pages", "data", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_pages_dirty") == 0)
				gauge_submit ("mysql_bpool_pages", "dirty", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_pages_flushed") == 0)
				counter_submit ("mysql_bpool_pages", "flushed", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_pages_free") == 0)
				gauge_submit ("mysql_bpool_pages", "free", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_pages_misc") == 0)
				gauge_submit ("mysql_bpool_pages", "misc", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_pages_total") == 0)
				gauge_submit ("mysql_bpool_pages", "total", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_read_ahead_rnd") == 0)
				counter_submit ("mysql_bpool_counters", "read_ahead_rnd", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_read_ahead") == 0)
				counter_submit ("mysql_bpool_counters", "read_ahead", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_read_ahead_evicted") == 0)
				counter_submit ("mysql_bpool_counters", "read_ahead_evicted", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_read_requests") == 0)
				counter_submit ("mysql_bpool_counters", "read_requests", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_reads") == 0)
				counter_submit ("mysql_bpool_counters", "reads", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_write_requests") == 0)
				counter_submit ("mysql_bpool_counters", "write_requests", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_bytes_data") == 0)
				gauge_submit ("mysql_bpool_bytes", "data", val, db);
			else if (strcmp (key, "Innodb_buffer_pool_bytes_dirty") == 0)
				gauge_submit ("mysql_bpool_bytes", "dirty", val, db);

			/* data */
			if (strcmp (key, "Innodb_data_fsyncs") == 0)
				counter_submit ("mysql_innodb_data", "fsyncs", val, db);
			else if (strcmp (key, "Innodb_data_read") == 0)
				counter_submit ("mysql_innodb_data", "read", val, db);
			else if (strcmp (key, "Innodb_data_reads") == 0)
				counter_submit ("mysql_innodb_data", "reads", val, db);
			else if (strcmp (key, "Innodb_data_writes") == 0)
				counter_submit ("mysql_innodb_data", "writes", val, db);
			else if (strcmp (key, "Innodb_data_written") == 0)
				counter_submit ("mysql_innodb_data", "written", val, db);

			/* double write */
			else if (strcmp (key, "Innodb_dblwr_writes") == 0)
				counter_submit ("mysql_innodb_dblwr", "writes", val, db);
			else if (strcmp (key, "Innodb_dblwr_pages_written") == 0)
				counter_submit ("mysql_innodb_dblwr", "written", val, db);

			/* log */
			else if (strcmp (key, "Innodb_log_waits") == 0)
				counter_submit ("mysql_innodb_log", "waits", val, db);
			else if (strcmp (key, "Innodb_log_write_requests") == 0)
				counter_submit ("mysql_innodb_log", "write_requests", val, db);
			else if (strcmp (key, "Innodb_log_writes") == 0)
				counter_submit ("mysql_innodb_log", "writes", val, db);
			else if (strcmp (key, "Innodb_os_log_fsyncs") == 0)
				counter_submit ("mysql_innodb_log", "fsyncs", val, db);
			else if (strcmp (key, "Innodb_os_log_written") == 0)
				counter_submit ("mysql_innodb_log", "written", val, db);

			/* pages */
			else if (strcmp (key, "Innodb_pages_created") == 0)
				counter_submit ("mysql_innodb_pages", "created", val, db);
			else if (strcmp (key, "Innodb_pages_read") == 0)
				counter_submit ("mysql_innodb_pages", "read", val, db);
			else if (strcmp (key, "Innodb_pages_written") == 0)
				counter_submit ("mysql_innodb_pages", "written", val, db);

			/* row lock */
			else if (strcmp (key, "Innodb_row_lock_time") == 0)
				counter_submit ("mysql_innodb_row_lock", "time", val, db);
			else if (strcmp (key, "Innodb_row_lock_waits") == 0)
				counter_submit ("mysql_innodb_row_lock", "waits", val, db);

			/* rows */
			else if (strcmp (key, "Innodb_rows_deleted") == 0)
				counter_submit ("mysql_innodb_rows", "deleted", val, db);
			else if (strcmp (key, "Innodb_rows_inserted") == 0)
				counter_submit ("mysql_innodb_rows", "inserted", val, db);
			else if (strcmp (key, "Innodb_rows_read") == 0)
				counter_submit ("mysql_innodb_rows", "read", val, db);
			else if (strcmp (key, "Innodb_rows_updated") == 0)
				counter_submit ("mysql_innodb_rows", "updated", val, db);
		}
		else if (strncmp (key, "Select_", strlen ("Select_")) == 0)
		{
			counter_submit ("mysql_select", key + strlen ("Select_"),
					val, db);
		}
		else if (strncmp (key, "Sort_", strlen ("Sort_")) == 0)
		{
			counter_submit ("mysql_sort", key + strlen ("Sort_"),
					val, db);
		}
	}
	mysql_free_result (res); res = NULL;

	if ((qcache_hits != 0)
			|| (qcache_inserts != 0)
			|| (qcache_not_cached != 0)
			|| (qcache_lowmem_prunes != 0))
	{
		derive_submit ("cache_result", "qcache-hits",
				qcache_hits, db);
		derive_submit ("cache_result", "qcache-inserts",
				qcache_inserts, db);
		derive_submit ("cache_result", "qcache-not_cached",
				qcache_not_cached, db);
		derive_submit ("cache_result", "qcache-prunes",
				qcache_lowmem_prunes, db);

		gauge_submit ("cache_size", "qcache",
				qcache_queries_in_cache, db);
	}

	if (threads_created != 0)
	{
		gauge_submit ("threads", "running",
				threads_running, db);
		gauge_submit ("threads", "connected",
				threads_connected, db);
		gauge_submit ("threads", "cached",
				threads_cached, db);

		derive_submit ("total_threads", "created",
				threads_created, db);
	}

	traffic_submit  (traffic_incoming, traffic_outgoing, db);

	if (mysql_version >= 50600 && db->innodb_stats)
        mysql_read_innodb_stats (db, con);

	if (db->master_stats)
		mysql_read_master_stats (db, con);

	if ((db->slave_stats) || (db->slave_notif))
		mysql_read_slave_stats (db, con);

	return (0);
} /* int mysql_read */
Esempio n. 5
0
/*
 * Look-up block in cache, and increment usage count.  If not in cache, read
 * and decompress it from disk.
 */
struct squashfs_cache_entry *squashfs_cache_get(struct super_block *sb,
	struct squashfs_cache *cache, u64 block, int length)
{
	int i, n;
	struct squashfs_cache_entry *entry;

	spin_lock(&cache->lock);

	while (1) {
		for (i = cache->curr_blk, n = 0; n < cache->entries; n++) {
			if (cache->entry[i].block == block) {
				cache->curr_blk = i;
				break;
			}
			i = (i + 1) % cache->entries;
		}

		if (n == cache->entries) {
			/*
			 * Block not in cache, if all cache entries are used
			 * go to sleep waiting for one to become available.
			 */
			if (cache->unused == 0) {
				cache->num_waiters++;
				spin_unlock(&cache->lock);
				wait_event(cache->wait_queue, cache->unused);
				spin_lock(&cache->lock);
				cache->num_waiters--;
				continue;
			}

			/*
			 * At least one unused cache entry.  A simple
			 * round-robin strategy is used to choose the entry to
			 * be evicted from the cache.
			 */
			i = cache->next_blk;
			for (n = 0; n < cache->entries; n++) {
				if (cache->entry[i].refcount == 0)
					break;
				i = (i + 1) % cache->entries;
			}

			cache->next_blk = (i + 1) % cache->entries;
			entry = &cache->entry[i];

			/*
			 * Initialise chosen cache entry, and fill it in from
			 * disk.
			 */
			cache->unused--;
			entry->block = block;
			entry->refcount = 1;
			entry->pending = 1;
			entry->num_waiters = 0;
			entry->error = 0;
			spin_unlock(&cache->lock);

			entry->length = squashfs_read_data(sb, block, length,
				&entry->next_index, entry->actor);

			spin_lock(&cache->lock);

			if (entry->length < 0)
				entry->error = entry->length;

			entry->pending = 0;

			/*
			 * While filling this entry one or more other processes
			 * have looked it up in the cache, and have slept
			 * waiting for it to become available.
			 */
			if (entry->num_waiters) {
				spin_unlock(&cache->lock);
				wake_up_all(&entry->wait_queue);
			} else
				spin_unlock(&cache->lock);

			goto out;
		}

		/*
		 * Block already in cache.  Increment refcount so it doesn't
		 * get reused until we're finished with it, if it was
		 * previously unused there's one less cache entry available
		 * for reuse.
		 */
		entry = &cache->entry[i];
		if (entry->refcount == 0)
			cache->unused--;
		entry->refcount++;

		/*
		 * If the entry is currently being filled in by another process
		 * go to sleep waiting for it to become available.
		 */
		if (entry->pending) {
			entry->num_waiters++;
			spin_unlock(&cache->lock);
			wait_event(entry->wait_queue, !entry->pending);
		} else
			spin_unlock(&cache->lock);

		goto out;
	}

out:
	TRACE("Got %s %d, start block %lld, refcount %d, error %d\n",
		cache->name, i, entry->block, entry->refcount, entry->error);

	if (entry->error)
		ERROR("Unable to read %s cache entry [%llx]\n", cache->name,
							block);
	return entry;
}
Esempio n. 6
0
float
fs_identify_partition(int fd, partition_data *partition, void **_cookie)
{
	NTFS_BOOT_SECTOR boot;
	identify_cookie *cookie;
	ntfs_volume *ntVolume;
	uint8 *buf = (uint8*)&boot;
	char devpath[256];

	// read in the boot sector
	TRACE("fs_identify_partition: read in the boot sector\n");
	if (read_pos(fd, 0, (void*)&boot, 512) != 512) {
		ERROR("fs_identify_partition: couldn't read boot sector\n");
		return -1;
	}

	// check boot signature
	if ((buf[0x1fe] != 0x55 || buf[0x1ff] != 0xaa) && buf[0x15] == 0xf8) {
		ERROR("fs_identify_partition: boot signature doesn't match\n");
		return -1;
	}

	// check boot signature NTFS
	if (memcmp(buf + 3, "NTFS    ", 8) != 0) {
		ERROR("fs_identify_partition: boot signature NTFS doesn't match\n");
		return -1;
	}

	// get path for device
	if (!ioctl(fd, B_GET_PATH_FOR_DEVICE, devpath)) {
		ERROR("fs_identify_partition: couldn't get path for device\n");
		return -1;
	}

	// try mount
	ntVolume = utils_mount_volume(devpath, MS_RDONLY, true);
	if (!ntVolume) {
		ERROR("fs_identify_partition: mount failed\n");
		return -1;
	}

	// allocate identify_cookie
	cookie = (identify_cookie *)malloc(sizeof(identify_cookie));
	if (!cookie) {
		ERROR("fs_identify_partition: cookie allocation failed\n");
		return -1;
	}

	memcpy(&cookie->boot, &boot, 512);

	strcpy(cookie->label, "NTFS Volume");

	if (ntVolume->vol_name && ntVolume->vol_name[0] != '\0')
		strcpy(cookie->label, ntVolume->vol_name);

	ntfs_umount(ntVolume, true);

	*_cookie = cookie;

	return 0.8f;
}
Esempio n. 7
0
/* Configuration handling functions {{{
 *
 * <Plugin mysql>
 *   <Database "plugin_instance1">
 *     Host "localhost"
 *     Port 22000
 *     ...
 *   </Database>
 * </Plugin>
 */
static int mysql_config_database (oconfig_item_t *ci) /* {{{ */
{
	mysql_database_t *db;
	int status = 0;
	int i;

	if ((ci->values_num != 1)
	    || (ci->values[0].type != OCONFIG_TYPE_STRING))
	{
		WARNING ("mysql plugin: The `Database' block "
			 "needs exactly one string argument.");
		return (-1);
	}

	db = (mysql_database_t *) malloc (sizeof (*db));
	if (db == NULL)
	{
		ERROR ("mysql plugin: malloc failed.");
		return (-1);
	}
	memset (db, 0, sizeof (*db));

	/* initialize all the pointers */
	db->alias    = NULL;
	db->host     = NULL;
	db->user     = NULL;
	db->pass     = NULL;
	db->database = NULL;
	db->socket   = NULL;
	db->con      = NULL;
	db->timeout  = 0;

	/* trigger a notification, if it's not running */
	db->slave_io_running  = 1;
	db->slave_sql_running = 1;

	status = cf_util_get_string (ci, &db->instance);
	if (status != 0)
	{
		sfree (db);
		return (status);
	}
	assert (db->instance != NULL);

	/* Fill the `mysql_database_t' structure.. */
	for (i = 0; i < ci->children_num; i++)
	{
		oconfig_item_t *child = ci->children + i;

		if (strcasecmp ("Alias", child->key) == 0)
			status = cf_util_get_string (child, &db->alias);
		else if (strcasecmp ("Host", child->key) == 0)
			status = cf_util_get_string (child, &db->host);
		else if (strcasecmp ("User", child->key) == 0)
			status = cf_util_get_string (child, &db->user);
		else if (strcasecmp ("Password", child->key) == 0)
			status = cf_util_get_string (child, &db->pass);
		else if (strcasecmp ("Port", child->key) == 0)
		{
			status = cf_util_get_port_number (child);
			if (status > 0)
			{
				db->port = status;
				status = 0;
			}
		}
		else if (strcasecmp ("Socket", child->key) == 0)
			status = cf_util_get_string (child, &db->socket);
		else if (strcasecmp ("Database", child->key) == 0)
			status = cf_util_get_string (child, &db->database);
		else if (strcasecmp ("ConnectTimeout", child->key) == 0)
			status = cf_util_get_int (child, &db->timeout);
		else if (strcasecmp ("MasterStats", child->key) == 0)
			status = cf_util_get_boolean (child, &db->master_stats);
		else if (strcasecmp ("SlaveStats", child->key) == 0)
			status = cf_util_get_boolean (child, &db->slave_stats);
		else if (strcasecmp ("SlaveNotifications", child->key) == 0)
			status = cf_util_get_boolean (child, &db->slave_notif);
		else if (strcasecmp ("InnodbStats", child->key) == 0)
			status = cf_util_get_boolean (child, &db->innodb_stats);
		else
		{
			WARNING ("mysql plugin: Option `%s' not allowed here.", child->key);
			status = -1;
		}

		if (status != 0)
			break;
	}

	/* If all went well, register this database for reading */
	if (status == 0)
	{
		user_data_t ud;
		char cb_name[DATA_MAX_NAME_LEN];

		DEBUG ("mysql plugin: Registering new read callback: %s",
				(db->database != NULL) ? db->database : "<default>");

		memset (&ud, 0, sizeof (ud));
		ud.data = (void *) db;
		ud.free_func = mysql_database_free;

		if (db->instance != NULL)
			ssnprintf (cb_name, sizeof (cb_name), "mysql-%s",
					db->instance);
		else
			sstrncpy (cb_name, "mysql", sizeof (cb_name));

		plugin_register_complex_read (/* group = */ NULL, cb_name,
					      mysql_read,
					      /* interval = */ 0, &ud);
	}
	else
	{
		mysql_database_free (db);
		return (-1);
	}

	return (0);
} /* }}} int mysql_config_database */
Esempio n. 8
0
static void csnmp_host_open_session (host_definition_t *host)
{
  struct snmp_session sess;
  int error;

  if (host->sess_handle != NULL)
    csnmp_host_close_session (host);

  snmp_sess_init (&sess);
  sess.peername = host->address;
  switch (host->version)
  {
    case 1:
      sess.version = SNMP_VERSION_1;
      break;
    case 3:
      sess.version = SNMP_VERSION_3;
      break;
    default:
      sess.version = SNMP_VERSION_2c;
      break;
  }

  if (host->version == 3)
  {
    sess.securityName = host->username;
    sess.securityNameLen = strlen (host->username);
    sess.securityLevel = host->security_level;

    if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV || sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV)
    {
      sess.securityAuthProto = host->auth_protocol;
      sess.securityAuthProtoLen = host->auth_protocol_len;
      sess.securityAuthKeyLen = USM_AUTH_KU_LEN;
      error = generate_Ku (sess.securityAuthProto,
	    sess.securityAuthProtoLen,
	    (u_char *) host->auth_passphrase,
	    strlen(host->auth_passphrase),
	    sess.securityAuthKey,
	    &sess.securityAuthKeyLen);
      if (error != SNMPERR_SUCCESS) {
	ERROR ("snmp plugin: host %s: Error generating Ku from auth_passphrase. (Error %d)", host->name, error);
      }
    }

    if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV)
    {
      sess.securityPrivProto = host->priv_protocol;
      sess.securityPrivProtoLen = host->priv_protocol_len;
      sess.securityPrivKeyLen = USM_PRIV_KU_LEN;
      error = generate_Ku (sess.securityAuthProto,
	    sess.securityAuthProtoLen,
	    (u_char *) host->priv_passphrase,
	    strlen(host->priv_passphrase),
	    sess.securityPrivKey,
	    &sess.securityPrivKeyLen);
      if (error != SNMPERR_SUCCESS) {
	ERROR ("snmp plugin: host %s: Error generating Ku from priv_passphrase. (Error %d)", host->name, error);
      }
    }

    if (host->context != NULL)
    {
      sess.contextName = host->context;
      sess.contextNameLen = strlen (host->context);
    }
  }
  else /* SNMPv1/2 "authenticates" with community string */
  {
    sess.community = (u_char *) host->community;
    sess.community_len = strlen (host->community);
  }

  /* snmp_sess_open will copy the `struct snmp_session *'. */
  host->sess_handle = snmp_sess_open (&sess);

  if (host->sess_handle == NULL)
  {
    char *errstr = NULL;

    snmp_error (&sess, NULL, NULL, &errstr);

    ERROR ("snmp plugin: host %s: snmp_sess_open failed: %s",
        host->name, (errstr == NULL) ? "Unknown problem" : errstr);
    sfree (errstr);
  }
} /* void csnmp_host_open_session */
Esempio n. 9
0
/* TODO: Check if negative values wrap around. Problem: negative temperatures. */
static value_t csnmp_value_list_to_value (struct variable_list *vl, int type,
    double scale, double shift,
    const char *host_name, const char *data_name)
{
  value_t ret;
  uint64_t tmp_unsigned = 0;
  int64_t tmp_signed = 0;
  _Bool defined = 1;
  /* Set to true when the original SNMP type appears to have been signed. */
  _Bool prefer_signed = 0;

  if ((vl->type == ASN_INTEGER)
      || (vl->type == ASN_UINTEGER)
      || (vl->type == ASN_COUNTER)
#ifdef ASN_TIMETICKS
      || (vl->type == ASN_TIMETICKS)
#endif
      || (vl->type == ASN_GAUGE))
  {
    tmp_unsigned = (uint32_t) *vl->val.integer;
    tmp_signed = (int32_t) *vl->val.integer;

    if ((vl->type == ASN_INTEGER)
        || (vl->type == ASN_GAUGE))
      prefer_signed = 1;

    DEBUG ("snmp plugin: Parsed int32 value is %"PRIu64".", tmp_unsigned);
  }
  else if (vl->type == ASN_COUNTER64)
  {
    tmp_unsigned = (uint32_t) vl->val.counter64->high;
    tmp_unsigned = tmp_unsigned << 32;
    tmp_unsigned += (uint32_t) vl->val.counter64->low;
    tmp_signed = (int64_t) tmp_unsigned;
    DEBUG ("snmp plugin: Parsed int64 value is %"PRIu64".", tmp_unsigned);
  }
  else if (vl->type == ASN_OCTET_STR)
  {
    /* We'll handle this later.. */
  }
  else
  {
    char oid_buffer[1024];

    memset (oid_buffer, 0, sizeof (oid_buffer));
    snprint_objid (oid_buffer, sizeof (oid_buffer) - 1,
        vl->name, vl->name_length);

#ifdef ASN_NULL
    if (vl->type == ASN_NULL)
      INFO ("snmp plugin: OID \"%s\" is undefined (type ASN_NULL)",
          oid_buffer);
    else
#endif
      WARNING ("snmp plugin: I don't know the ASN type #%i "
               "(OID: \"%s\", data block \"%s\", host block \"%s\")",
          (int) vl->type, oid_buffer,
          (data_name != NULL) ? data_name : "UNKNOWN",
          (host_name != NULL) ? host_name : "UNKNOWN");

    defined = 0;
  }

  if (vl->type == ASN_OCTET_STR)
  {
    int status = -1;

    if (vl->val.string != NULL)
    {
      char string[64];
      size_t string_length;

      string_length = sizeof (string) - 1;
      if (vl->val_len < string_length)
        string_length = vl->val_len;

      /* The strings we get from the Net-SNMP library may not be null
       * terminated. That is why we're using `memcpy' here and not `strcpy'.
       * `string_length' is set to `vl->val_len' which holds the length of the
       * string.  -octo */
      memcpy (string, vl->val.string, string_length);
      string[string_length] = 0;

      status = parse_value (string, &ret, type);
      if (status != 0)
      {
        ERROR ("snmp plugin: csnmp_value_list_to_value: Parsing string as %s failed: %s",
            DS_TYPE_TO_STRING (type), string);
      }
    }

    if (status != 0)
    {
      switch (type)
      {
        case DS_TYPE_COUNTER:
        case DS_TYPE_DERIVE:
        case DS_TYPE_ABSOLUTE:
          memset (&ret, 0, sizeof (ret));
          break;

        case DS_TYPE_GAUGE:
          ret.gauge = NAN;
          break;

        default:
          ERROR ("snmp plugin: csnmp_value_list_to_value: Unknown "
              "data source type: %i.", type);
          ret.gauge = NAN;
      }
    }
  } /* if (vl->type == ASN_OCTET_STR) */
  else if (type == DS_TYPE_COUNTER)
  {
    ret.counter = tmp_unsigned;
  }
  else if (type == DS_TYPE_GAUGE)
  {
    if (!defined)
      ret.gauge = NAN;
    else if (prefer_signed)
      ret.gauge = (scale * tmp_signed) + shift;
    else
      ret.gauge = (scale * tmp_unsigned) + shift;
  }
  else if (type == DS_TYPE_DERIVE)
  {
    if (prefer_signed)
      ret.derive = (derive_t) tmp_signed;
    else
      ret.derive = (derive_t) tmp_unsigned;
  }
  else if (type == DS_TYPE_ABSOLUTE)
  {
    ret.absolute = (absolute_t) tmp_unsigned;
  }
  else
  {
    ERROR ("snmp plugin: csnmp_value_list_to_value: Unknown data source "
        "type: %i.", type);
    ret.gauge = NAN;
  }

  return (ret);
} /* value_t csnmp_value_list_to_value */
Esempio n. 10
0
static int csnmp_read_value (host_definition_t *host, data_definition_t *data)
{
  struct snmp_pdu *req;
  struct snmp_pdu *res;
  struct variable_list *vb;

  const data_set_t *ds;
  value_list_t vl = VALUE_LIST_INIT;

  int status;
  int i;

  DEBUG ("snmp plugin: csnmp_read_value (host = %s, data = %s)",
      host->name, data->name);

  if (host->sess_handle == NULL)
  {
    DEBUG ("snmp plugin: csnmp_read_table: host->sess_handle == NULL");
    return (-1);
  }

  ds = plugin_get_ds (data->type);
  if (!ds)
  {
    ERROR ("snmp plugin: DataSet `%s' not defined.", data->type);
    return (-1);
  }

  if (ds->ds_num != data->values_len)
  {
    ERROR ("snmp plugin: DataSet `%s' requires %i values, but config talks about %i",
        data->type, ds->ds_num, data->values_len);
    return (-1);
  }

  vl.values_len = ds->ds_num;
  vl.values = (value_t *) malloc (sizeof (value_t) * vl.values_len);
  if (vl.values == NULL)
    return (-1);
  for (i = 0; i < vl.values_len; i++)
  {
    if (ds->ds[i].type == DS_TYPE_COUNTER)
      vl.values[i].counter = 0;
    else
      vl.values[i].gauge = NAN;
  }

  sstrncpy (vl.host, host->name, sizeof (vl.host));
  sstrncpy (vl.plugin, "snmp", sizeof (vl.plugin));
  sstrncpy (vl.type, data->type, sizeof (vl.type));
  sstrncpy (vl.type_instance, data->instance.string, sizeof (vl.type_instance));

  vl.interval = host->interval;

  req = snmp_pdu_create (SNMP_MSG_GET);
  if (req == NULL)
  {
    ERROR ("snmp plugin: snmp_pdu_create failed.");
    sfree (vl.values);
    return (-1);
  }

  for (i = 0; i < data->values_len; i++)
    snmp_add_null_var (req, data->values[i].oid, data->values[i].oid_len);

  res = NULL;
  status = snmp_sess_synch_response (host->sess_handle, req, &res);

  if ((status != STAT_SUCCESS) || (res == NULL))
  {
    char *errstr = NULL;

    snmp_sess_error (host->sess_handle, NULL, NULL, &errstr);
    ERROR ("snmp plugin: host %s: snmp_sess_synch_response failed: %s",
        host->name, (errstr == NULL) ? "Unknown problem" : errstr);

    if (res != NULL)
      snmp_free_pdu (res);
    res = NULL;

    sfree (errstr);
    csnmp_host_close_session (host);

    return (-1);
  }


  for (vb = res->variables; vb != NULL; vb = vb->next_variable)
  {
#if COLLECT_DEBUG
    char buffer[1024];
    snprint_variable (buffer, sizeof (buffer),
        vb->name, vb->name_length, vb);
    DEBUG ("snmp plugin: Got this variable: %s", buffer);
#endif /* COLLECT_DEBUG */

    for (i = 0; i < data->values_len; i++)
      if (snmp_oid_compare (data->values[i].oid, data->values[i].oid_len,
            vb->name, vb->name_length) == 0)
        vl.values[i] = csnmp_value_list_to_value (vb, ds->ds[i].type,
            data->scale, data->shift, host->name, data->name);
  } /* for (res->variables) */

  if (res != NULL)
    snmp_free_pdu (res);
  res = NULL;

  DEBUG ("snmp plugin: -> plugin_dispatch_values (&vl);");
  plugin_dispatch_values (&vl);
  sfree (vl.values);

  return (0);
} /* int csnmp_read_value */
Esempio n. 11
0
static int csnmp_config_add_host (oconfig_item_t *ci)
{
  host_definition_t *hd;
  int status = 0;
  int i;

  /* Registration stuff. */
  char cb_name[DATA_MAX_NAME_LEN];
  user_data_t cb_data;
  struct timespec cb_interval;

  hd = (host_definition_t *) malloc (sizeof (host_definition_t));
  if (hd == NULL)
    return (-1);
  memset (hd, '\0', sizeof (host_definition_t));
  hd->version = 2;
  C_COMPLAIN_INIT (&hd->complaint);

  status = cf_util_get_string(ci, &hd->name);
  if (status != 0)
    return status;

  hd->sess_handle = NULL;
  hd->interval = 0;

  for (i = 0; i < ci->children_num; i++)
  {
    oconfig_item_t *option = ci->children + i;
    status = 0;

    if (strcasecmp ("Address", option->key) == 0)
      status = cf_util_get_string(option, &hd->address);
    else if (strcasecmp ("Community", option->key) == 0)
      status = cf_util_get_string(option, &hd->community);
    else if (strcasecmp ("Version", option->key) == 0)
      status = csnmp_config_add_host_version (hd, option);
    else if (strcasecmp ("Collect", option->key) == 0)
      csnmp_config_add_host_collect (hd, option);
    else if (strcasecmp ("Interval", option->key) == 0)
      cf_util_get_cdtime (option, &hd->interval);
    else if (strcasecmp ("Username", option->key) == 0)
      status = cf_util_get_string(option, &hd->username);
    else if (strcasecmp ("AuthProtocol", option->key) == 0)
      status = csnmp_config_add_host_auth_protocol (hd, option);
    else if (strcasecmp ("PrivacyProtocol", option->key) == 0)
      status = csnmp_config_add_host_priv_protocol (hd, option);
    else if (strcasecmp ("AuthPassphrase", option->key) == 0)
      status = cf_util_get_string(option, &hd->auth_passphrase);
    else if (strcasecmp ("PrivacyPassphrase", option->key) == 0)
      status = cf_util_get_string(option, &hd->priv_passphrase);
    else if (strcasecmp ("SecurityLevel", option->key) == 0)
      status = csnmp_config_add_host_security_level (hd, option);
    else if (strcasecmp ("Context", option->key) == 0)
      status = cf_util_get_string(option, &hd->context);
    else
    {
      WARNING ("snmp plugin: csnmp_config_add_host: Option `%s' not allowed here.", option->key);
      status = -1;
    }

    if (status != 0)
      break;
  } /* for (ci->children) */

  while (status == 0)
  {
    if (hd->address == NULL)
    {
      WARNING ("snmp plugin: `Address' not given for host `%s'", hd->name);
      status = -1;
      break;
    }
    if (hd->community == NULL && hd->version < 3)
    {
      WARNING ("snmp plugin: `Community' not given for host `%s'", hd->name);
      status = -1;
      break;
    }
    if (hd->version == 3)
    {
      if (hd->username == NULL)
      {
        WARNING ("snmp plugin: `Username' not given for host `%s'", hd->name);
        status = -1;
        break;
      }
      if (hd->security_level == 0)
      {
        WARNING ("snmp plugin: `SecurityLevel' not given for host `%s'", hd->name);
        status = -1;
        break;
      }
      if (hd->security_level == SNMP_SEC_LEVEL_AUTHNOPRIV || hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV)
      {
	if (hd->auth_protocol == NULL)
	{
	  WARNING ("snmp plugin: `AuthProtocol' not given for host `%s'", hd->name);
	  status = -1;
	  break;
	}
	if (hd->auth_passphrase == NULL)
	{
	  WARNING ("snmp plugin: `AuthPassphrase' not given for host `%s'", hd->name);
	  status = -1;
	  break;
	}
      }
      if (hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV)
      {
	if (hd->priv_protocol == NULL)
	{
	  WARNING ("snmp plugin: `PrivacyProtocol' not given for host `%s'", hd->name);
	  status = -1;
	  break;
	}
	if (hd->priv_passphrase == NULL)
	{
	  WARNING ("snmp plugin: `PrivacyPassphrase' not given for host `%s'", hd->name);
	  status = -1;
	  break;
	}
      }
    }

    break;
  } /* while (status == 0) */

  if (status != 0)
  {
    csnmp_host_definition_destroy (hd);
    return (-1);
  }

  DEBUG ("snmp plugin: hd = { name = %s, address = %s, community = %s, version = %i }",
      hd->name, hd->address, hd->community, hd->version);

  ssnprintf (cb_name, sizeof (cb_name), "snmp-%s", hd->name);

  memset (&cb_data, 0, sizeof (cb_data));
  cb_data.data = hd;
  cb_data.free_func = csnmp_host_definition_destroy;

  CDTIME_T_TO_TIMESPEC (hd->interval, &cb_interval);

  status = plugin_register_complex_read (/* group = */ NULL, cb_name,
      csnmp_read_host, /* interval = */ &cb_interval,
      /* user_data = */ &cb_data);
  if (status != 0)
  {
    ERROR ("snmp plugin: Registering complex read function failed.");
    csnmp_host_definition_destroy (hd);
    return (-1);
  }

  return (0);
} /* int csnmp_config_add_host */
Esempio n. 12
0
static int csnmp_read_table (host_definition_t *host, data_definition_t *data)
{
  struct snmp_pdu *req;
  struct snmp_pdu *res;
  struct variable_list *vb;

  const data_set_t *ds;

  uint32_t oid_list_len = (uint32_t) (data->values_len + 1);
  /* Holds the last OID returned by the device. We use this in the GETNEXT
   * request to proceed. */
  oid_t oid_list[oid_list_len];
  /* Set to false when an OID has left its subtree so we don't re-request it
   * again. */
  _Bool oid_list_todo[oid_list_len];

  int status;
  int i;
  uint32_t j;

  /* `value_list_head' and `value_list_tail' implement a linked list for each
   * value. `instance_list_head' and `instance_list_tail' implement a linked list of
   * instance names. This is used to jump gaps in the table. */
  csnmp_list_instances_t *instance_list_head;
  csnmp_list_instances_t *instance_list_tail;
  csnmp_table_values_t **value_list_head;
  csnmp_table_values_t **value_list_tail;

  DEBUG ("snmp plugin: csnmp_read_table (host = %s, data = %s)",
      host->name, data->name);

  if (host->sess_handle == NULL)
  {
    DEBUG ("snmp plugin: csnmp_read_table: host->sess_handle == NULL");
    return (-1);
  }

  ds = plugin_get_ds (data->type);
  if (!ds)
  {
    ERROR ("snmp plugin: DataSet `%s' not defined.", data->type);
    return (-1);
  }

  if (ds->ds_num != data->values_len)
  {
    ERROR ("snmp plugin: DataSet `%s' requires %i values, but config talks about %i",
        data->type, ds->ds_num, data->values_len);
    return (-1);
  }

  /* We need a copy of all the OIDs, because GETNEXT will destroy them. */
  memcpy (oid_list, data->values, data->values_len * sizeof (oid_t));
  if (data->instance.oid.oid_len > 0)
    memcpy (oid_list + data->values_len, &data->instance.oid, sizeof (oid_t));
  else /* no InstanceFrom option specified. */
    oid_list_len--;

  for (j = 0; j < oid_list_len; j++)
    oid_list_todo[j] = 1;

  /* We're going to construct n linked lists, one for each "value".
   * value_list_head will contain pointers to the heads of these linked lists,
   * value_list_tail will contain pointers to the tail of the lists. */
  value_list_head = calloc (data->values_len, sizeof (*value_list_head));
  value_list_tail = calloc (data->values_len, sizeof (*value_list_tail));
  if ((value_list_head == NULL) || (value_list_tail == NULL))
  {
    ERROR ("snmp plugin: csnmp_read_table: calloc failed.");
    sfree (value_list_head);
    sfree (value_list_tail);
    return (-1);
  }

  instance_list_head = NULL;
  instance_list_tail = NULL;

  status = 0;
  while (status == 0)
  {
    int oid_list_todo_num;

    req = snmp_pdu_create (SNMP_MSG_GETNEXT);
    if (req == NULL)
    {
      ERROR ("snmp plugin: snmp_pdu_create failed.");
      status = -1;
      break;
    }

    oid_list_todo_num = 0;
    for (j = 0; j < oid_list_len; j++)
    {
      /* Do not rerequest already finished OIDs */
      if (!oid_list_todo[j])
        continue;
      oid_list_todo_num++;
      snmp_add_null_var (req, oid_list[j].oid, oid_list[j].oid_len);
    }

    if (oid_list_todo_num == 0)
    {
      /* The request is still empty - so we are finished */
      DEBUG ("snmp plugin: all variables have left their subtree");
      status = 0;
      break;
    }

    res = NULL;
    status = snmp_sess_synch_response (host->sess_handle, req, &res);
    if ((status != STAT_SUCCESS) || (res == NULL))
    {
      char *errstr = NULL;

      snmp_sess_error (host->sess_handle, NULL, NULL, &errstr);

      c_complain (LOG_ERR, &host->complaint,
          "snmp plugin: host %s: snmp_sess_synch_response failed: %s",
          host->name, (errstr == NULL) ? "Unknown problem" : errstr);

      if (res != NULL)
        snmp_free_pdu (res);
      res = NULL;

      sfree (errstr);
      csnmp_host_close_session (host);

      status = -1;
      break;
    }

    status = 0;
    assert (res != NULL);
    c_release (LOG_INFO, &host->complaint,
        "snmp plugin: host %s: snmp_sess_synch_response successful.",
        host->name);

    vb = res->variables;
    if (vb == NULL)
    {
      status = -1;
      break;
    }

    for (vb = res->variables, i = 0; (vb != NULL); vb = vb->next_variable, i++)
    {
      /* Calculate value index from todo list */
      while (!oid_list_todo[i] && (i < oid_list_len))
        i++;

      /* An instance is configured and the res variable we process is the
       * instance value (last index) */
      if ((data->instance.oid.oid_len > 0) && (i == data->values_len))
      {
        if ((vb->type == SNMP_ENDOFMIBVIEW)
            || (snmp_oid_ncompare (data->instance.oid.oid,
                data->instance.oid.oid_len,
                vb->name, vb->name_length,
                data->instance.oid.oid_len) != 0))
        {
          DEBUG ("snmp plugin: host = %s; data = %s; Instance left its subtree.",
              host->name, data->name);
          oid_list_todo[i] = 0;
          continue;
        }

        /* Allocate a new `csnmp_list_instances_t', insert the instance name and
         * add it to the list */
        if (csnmp_instance_list_add (&instance_list_head, &instance_list_tail,
              res, host, data) != 0)
        {
          ERROR ("snmp plugin: csnmp_instance_list_add failed.");
          status = -1;
          break;
        }
      }
      else /* The variable we are processing is a normal value */
      {
        csnmp_table_values_t *vt;
        oid_t vb_name;
        oid_t suffix;
        int ret;

        csnmp_oid_init (&vb_name, vb->name, vb->name_length);

        /* Calculate the current suffix. This is later used to check that the
         * suffix is increasing. This also checks if we left the subtree */
        ret = csnmp_oid_suffix (&suffix, &vb_name, data->values + i);
        if (ret != 0)
        {
          DEBUG ("snmp plugin: host = %s; data = %s; i = %i; "
              "Value probably left its subtree.",
              host->name, data->name, i);
          oid_list_todo[i] = 0;
          continue;
        }

        /* Make sure the OIDs returned by the agent are increasing. Otherwise our
         * table matching algorithm will get confused. */
        if ((value_list_tail[i] != NULL)
            && (csnmp_oid_compare (&suffix, &value_list_tail[i]->suffix) <= 0))
        {
          DEBUG ("snmp plugin: host = %s; data = %s; i = %i; "
              "Suffix is not increasing.",
              host->name, data->name, i);
          oid_list_todo[i] = 0;
          continue;
        }

        vt = malloc (sizeof (*vt));
        if (vt == NULL)
        {
          ERROR ("snmp plugin: malloc failed.");
          status = -1;
          break;
        }
        memset (vt, 0, sizeof (*vt));

        vt->value = csnmp_value_list_to_value (vb, ds->ds[i].type,
            data->scale, data->shift, host->name, data->name);
        memcpy (&vt->suffix, &suffix, sizeof (vt->suffix));
        vt->next = NULL;

        if (value_list_tail[i] == NULL)
          value_list_head[i] = vt;
        else
          value_list_tail[i]->next = vt;
        value_list_tail[i] = vt;
      }

      /* Copy OID to oid_list[i] */
      memcpy (oid_list[i].oid, vb->name, sizeof (oid) * vb->name_length);
      oid_list[i].oid_len = vb->name_length;

    } /* for (vb = res->variables ...) */

    if (res != NULL)
      snmp_free_pdu (res);
    res = NULL;
  } /* while (status == 0) */

  if (res != NULL)
    snmp_free_pdu (res);
  res = NULL;

  if (status == 0)
    csnmp_dispatch_table (host, data, instance_list_head, value_list_head);

  /* Free all allocated variables here */
  while (instance_list_head != NULL)
  {
    csnmp_list_instances_t *next = instance_list_head->next;
    sfree (instance_list_head);
    instance_list_head = next;
  }

  for (i = 0; i < data->values_len; i++)
  {
    while (value_list_head[i] != NULL)
    {
      csnmp_table_values_t *next = value_list_head[i]->next;
      sfree (value_list_head[i]);
      value_list_head[i] = next;
    }
  }

  sfree (value_list_head);
  sfree (value_list_tail);

  return (0);
} /* int csnmp_read_table */
Esempio n. 13
0
static int csnmp_dispatch_table (host_definition_t *host, data_definition_t *data,
    csnmp_list_instances_t *instance_list,
    csnmp_table_values_t **value_table)
{
  const data_set_t *ds;
  value_list_t vl = VALUE_LIST_INIT;

  csnmp_list_instances_t *instance_list_ptr;
  csnmp_table_values_t **value_table_ptr;

  int i;
  _Bool have_more;
  oid_t current_suffix;

  ds = plugin_get_ds (data->type);
  if (!ds)
  {
    ERROR ("snmp plugin: DataSet `%s' not defined.", data->type);
    return (-1);
  }
  assert (ds->ds_num == data->values_len);

  instance_list_ptr = instance_list;

  value_table_ptr = malloc (sizeof (*value_table_ptr) * data->values_len);
  if (value_table_ptr == NULL)
    return (-1);
  for (i = 0; i < data->values_len; i++)
    value_table_ptr[i] = value_table[i];

  vl.values_len = ds->ds_num;
  vl.values = malloc (sizeof (*vl.values) * vl.values_len);
  if (vl.values == NULL)
  {
    ERROR ("snmp plugin: malloc failed.");
    sfree (value_table_ptr);
    return (-1);
  }

  sstrncpy (vl.host, host->name, sizeof (vl.host));
  sstrncpy (vl.plugin, "snmp", sizeof (vl.plugin));

  vl.interval = host->interval;

  have_more = 1;
  memset (&current_suffix, 0, sizeof (current_suffix));
  while (have_more)
  {
    _Bool suffix_skipped = 0;

    /* Determine next suffix to handle. */
    if (instance_list != NULL)
    {
      if (instance_list_ptr == NULL)
      {
        have_more = 0;
        continue;
      }

      memcpy (&current_suffix, &instance_list_ptr->suffix, sizeof (current_suffix));
    }
    else /* no instance configured */
    {
      csnmp_table_values_t *ptr = value_table_ptr[0];
      if (ptr == NULL)
      {
        have_more = 0;
        continue;
      }

      memcpy (&current_suffix, &ptr->suffix, sizeof (current_suffix));
    }

    /* Update all the value_table_ptr to point at the entry with the same
     * trailing partial OID */
    for (i = 0; i < data->values_len; i++)
    {
      while ((value_table_ptr[i] != NULL)
          && (csnmp_oid_compare (&value_table_ptr[i]->suffix, &current_suffix) < 0))
        value_table_ptr[i] = value_table_ptr[i]->next;

      if (value_table_ptr[i] == NULL)
      {
        have_more = 0;
        break;
      }
      else if (csnmp_oid_compare (&value_table_ptr[i]->suffix, &current_suffix) > 0)
      {
        /* This suffix is missing in the subtree. Indicate this with the
         * "suffix_skipped" flag and try the next instance / suffix. */
        suffix_skipped = 1;
        break;
      }
    } /* for (i = 0; i < columns; i++) */

    if (!have_more)
      break;

    /* Matching the values failed. Start from the beginning again. */
    if (suffix_skipped)
    {
      if (instance_list != NULL)
        instance_list_ptr = instance_list_ptr->next;
      else
        value_table_ptr[0] = value_table_ptr[0]->next;

      continue;
    }

    /* if we reach this line, all value_table_ptr[i] are non-NULL and are set
     * to the same subid. instance_list_ptr is either NULL or points to the
     * same subid, too. */
#if COLLECT_DEBUG
    for (i = 1; i < data->values_len; i++)
    {
      assert (value_table_ptr[i] != NULL);
      assert (csnmp_oid_compare (&value_table_ptr[i-1]->suffix,
            &value_table_ptr[i]->suffix) == 0);
    }
    assert ((instance_list_ptr == NULL)
        || (csnmp_oid_compare (&instance_list_ptr->suffix,
            &value_table_ptr[0]->suffix) == 0));
#endif

    sstrncpy (vl.type, data->type, sizeof (vl.type));

    {
      char temp[DATA_MAX_NAME_LEN];

      if (instance_list_ptr == NULL)
        csnmp_oid_to_string (temp, sizeof (temp), &current_suffix);
      else
        sstrncpy (temp, instance_list_ptr->instance, sizeof (temp));

      if (data->instance_prefix == NULL)
        sstrncpy (vl.type_instance, temp, sizeof (vl.type_instance));
      else
        ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s%s",
            data->instance_prefix, temp);
    }

    for (i = 0; i < data->values_len; i++)
      vl.values[i] = value_table_ptr[i]->value;

    /* If we get here `vl.type_instance' and all `vl.values' have been set */
    plugin_dispatch_values (&vl);

    if (instance_list != NULL)
      instance_list_ptr = instance_list_ptr->next;
    else
      value_table_ptr[0] = value_table_ptr[0]->next;
  } /* while (have_more) */

  sfree (vl.values);
  sfree (value_table_ptr);

  return (0);
} /* int csnmp_dispatch_table */
Esempio n. 14
0
static int csnmp_instance_list_add (csnmp_list_instances_t **head,
    csnmp_list_instances_t **tail,
    const struct snmp_pdu *res,
    const host_definition_t *hd, const data_definition_t *dd)
{
  csnmp_list_instances_t *il;
  struct variable_list *vb;
  oid_t vb_name;
  int status;
  uint32_t i;
  uint32_t is_matched;

  /* Set vb on the last variable */
  for (vb = res->variables;
      (vb != NULL) && (vb->next_variable != NULL);
      vb = vb->next_variable)
    /* do nothing */;
  if (vb == NULL)
    return (-1);

  csnmp_oid_init (&vb_name, vb->name, vb->name_length);

  il = malloc (sizeof (*il));
  if (il == NULL)
  {
    ERROR ("snmp plugin: malloc failed.");
    return (-1);
  }
  memset (il, 0, sizeof (*il));
  il->next = NULL;

  status = csnmp_oid_suffix (&il->suffix, &vb_name, &dd->instance.oid);
  if (status != 0)
  {
    sfree (il);
    return (status);
  }

  /* Get instance name */
  if ((vb->type == ASN_OCTET_STR) || (vb->type == ASN_BIT_STR))
  {
    char *ptr;

    csnmp_strvbcopy (il->instance, vb, sizeof (il->instance));
    is_matched = 0;
    for (i = 0; i < dd->ignores_len; i++)
    {
      status = fnmatch(dd->ignores[i], il->instance, 0);
      if (status == 0)
      {
        if (dd->invert_match == 0)
        {
          sfree(il);
          return 0;
        }
	else
	{
          is_matched = 1;
	  break;
	}
      }
    }
    if (dd->invert_match != 0 && is_matched == 0)
    {
      sfree(il);
      return 0;
    }
    for (ptr = il->instance; *ptr != '\0'; ptr++)
    {
      if ((*ptr > 0) && (*ptr < 32))
        *ptr = ' ';
      else if (*ptr == '/')
        *ptr = '_';
    }
    DEBUG ("snmp plugin: il->instance = `%s';", il->instance);
  }
  else
  {
    value_t val = csnmp_value_list_to_value (vb, DS_TYPE_COUNTER,
        /* scale = */ 1.0, /* shift = */ 0.0, hd->name, dd->name);
    ssnprintf (il->instance, sizeof (il->instance),
        "%llu", val.counter);
  }

  /* TODO: Debugging output */

  if (*head == NULL)
    *head = il;
  else
    (*tail)->next = il;
  *tail = il;

  return (0);
} /* int csnmp_instance_list_add */
static int parse_flags(char *flags, struct flag_list *fl,
                       struct fs_mgr_flag_values *flag_vals,
                       char *fs_options, int fs_options_len)
{
    int f = 0;
    int i;
    char *p;
    char *savep;

    /* initialize flag values.  If we find a relevant flag, we'll
     * update the value */
    if (flag_vals) {
        memset(flag_vals, 0, sizeof(*flag_vals));
        flag_vals->partnum = -1;
        flag_vals->swap_prio = -1; /* negative means it wasn't specified. */
    }

    /* initialize fs_options to the null string */
    if (fs_options && (fs_options_len > 0)) {
        fs_options[0] = '\0';
    }

    p = strtok_r(flags, ",", &savep);
    while (p) {
        /* Look for the flag "p" in the flag list "fl"
         * If not found, the loop exits with fl[i].name being null.
         */
        for (i = 0; fl[i].name; i++) {
            if (!strncmp(p, fl[i].name, strlen(fl[i].name))) {
                f |= fl[i].flag;
                if ((fl[i].flag == MF_CRYPT) && flag_vals) {
                    /* The encryptable flag is followed by an = and the
                     * location of the keys.  Get it and return it.
                     */
                    flag_vals->key_loc = strdup(strchr(p, '=') + 1);
                } else if ((fl[i].flag == MF_VERIFY) && flag_vals) {
                    /* If the verify flag is followed by an = and the
                     * location for the verity state,  get it and return it.
                     */
                    char *start = strchr(p, '=');
                    if (start) {
                        flag_vals->verity_loc = strdup(start + 1);
                    }
                } else if ((fl[i].flag == MF_FORCECRYPT) && flag_vals) {
                    /* The forceencrypt flag is followed by an = and the
                     * location of the keys.  Get it and return it.
                     */
                    flag_vals->key_loc = strdup(strchr(p, '=') + 1);
                } else if ((fl[i].flag == MF_LENGTH) && flag_vals) {
                    /* The length flag is followed by an = and the
                     * size of the partition.  Get it and return it.
                     */
                    flag_vals->part_length = strtoll(strchr(p, '=') + 1, NULL, 0);
                } else if ((fl[i].flag == MF_VOLDMANAGED) && flag_vals) {
                    /* The voldmanaged flag is followed by an = and the
                     * label, a colon and the partition number or the
                     * word "auto", e.g.
                     *   voldmanaged=sdcard:3
                     * Get and return them.
                     */
                    char *label_start;
                    char *label_end;
                    char *part_start;

                    label_start = strchr(p, '=') + 1;
                    label_end = strchr(p, ':');
                    if (label_end) {
                        flag_vals->label = strndup(label_start,
                                                   (int) (label_end - label_start));
                        part_start = strchr(p, ':') + 1;
                        if (!strcmp(part_start, "auto")) {
                            flag_vals->partnum = -1;
                        } else {
                            flag_vals->partnum = strtol(part_start, NULL, 0);
                        }
                    } else {
                        ERROR("Warning: voldmanaged= flag malformed\n");
                    }
                } else if ((fl[i].flag == MF_SWAPPRIO) && flag_vals) {
                    flag_vals->swap_prio = strtoll(strchr(p, '=') + 1, NULL, 0);
                } else if ((fl[i].flag == MF_ZRAMSIZE) && flag_vals) {
                    flag_vals->zram_size = strtoll(strchr(p, '=') + 1, NULL, 0);
                }
                break;
            }
        }

        if (!fl[i].name) {
            if (fs_options) {
                /* It's not a known flag, so it must be a filesystem specific
                 * option.  Add it to fs_options if it was passed in.
                 */
                strlcat(fs_options, p, fs_options_len);
                strlcat(fs_options, ",", fs_options_len);
            } else {
                /* fs_options was not passed in, so if the flag is unknown
                 * it's an error.
                 */
                ERROR("Warning: unknown flag %s\n", p);
            }
        }
        p = strtok_r(NULL, ",", &savep);
    }

    if (fs_options && fs_options[0]) {
        /* remove the last trailing comma from the list of options */
        fs_options[strlen(fs_options) - 1] = '\0';
    }

    return f;
}
Esempio n. 16
0
static int memory_read (void)
{
#if HAVE_HOST_STATISTICS
    kern_return_t status;
    vm_statistics_data_t   vm_data;
    mach_msg_type_number_t vm_data_len;

    gauge_t wired;
    gauge_t active;
    gauge_t inactive;
    gauge_t free;

    if (!port_host || !pagesize)
        return (-1);

    vm_data_len = sizeof (vm_data) / sizeof (natural_t);
    if ((status = host_statistics (port_host, HOST_VM_INFO,
                                   (host_info_t) &vm_data,
                                   &vm_data_len)) != KERN_SUCCESS)
    {
        ERROR ("memory-plugin: host_statistics failed and returned the value %i", (int) status);
        return (-1);
    }

    /*
     * From <http://docs.info.apple.com/article.html?artnum=107918>:
     *
     * Wired memory
     *   This information can't be cached to disk, so it must stay in RAM.
     *   The amount depends on what applications you are using.
     *
     * Active memory
     *   This information is currently in RAM and actively being used.
     *
     * Inactive memory
     *   This information is no longer being used and has been cached to
     *   disk, but it will remain in RAM until another application needs
     *   the space. Leaving this information in RAM is to your advantage if
     *   you (or a client of your computer) come back to it later.
     *
     * Free memory
     *   This memory is not being used.
     */

    wired    = (gauge_t) (((uint64_t) vm_data.wire_count)     * ((uint64_t) pagesize));
    active   = (gauge_t) (((uint64_t) vm_data.active_count)   * ((uint64_t) pagesize));
    inactive = (gauge_t) (((uint64_t) vm_data.inactive_count) * ((uint64_t) pagesize));
    free     = (gauge_t) (((uint64_t) vm_data.free_count)     * ((uint64_t) pagesize));

    memory_submit ("wired",    wired);
    memory_submit ("active",   active);
    memory_submit ("inactive", inactive);
    memory_submit ("free",     free);
    /* #endif HAVE_HOST_STATISTICS */

#elif HAVE_SYSCTLBYNAME
    /*
     * vm.stats.vm.v_page_size: 4096
     * vm.stats.vm.v_page_count: 246178
     * vm.stats.vm.v_free_count: 28760
     * vm.stats.vm.v_wire_count: 37526
     * vm.stats.vm.v_active_count: 55239
     * vm.stats.vm.v_inactive_count: 113730
     * vm.stats.vm.v_cache_count: 10809
     */
    char *sysctl_keys[8] =
    {
        "vm.stats.vm.v_page_size",
        "vm.stats.vm.v_page_count",
        "vm.stats.vm.v_free_count",
        "vm.stats.vm.v_wire_count",
        "vm.stats.vm.v_active_count",
        "vm.stats.vm.v_inactive_count",
        "vm.stats.vm.v_cache_count",
        NULL
    };
    double sysctl_vals[8];

    int    i;

    for (i = 0; sysctl_keys[i] != NULL; i++)
    {
        int value;
        size_t value_len = sizeof (value);

        if (sysctlbyname (sysctl_keys[i], (void *) &value, &value_len,
                          NULL, 0) == 0)
        {
            sysctl_vals[i] = value;
            DEBUG ("memory plugin: %26s: %g", sysctl_keys[i], sysctl_vals[i]);
        }
        else
        {
            sysctl_vals[i] = NAN;
        }
    } /* for (sysctl_keys) */

    /* multiply all all page counts with the pagesize */
    for (i = 1; sysctl_keys[i] != NULL; i++)
        if (!isnan (sysctl_vals[i]))
            sysctl_vals[i] *= sysctl_vals[0];

    memory_submit ("free",     sysctl_vals[2]);
    memory_submit ("wired",    sysctl_vals[3]);
    memory_submit ("active",   sysctl_vals[4]);
    memory_submit ("inactive", sysctl_vals[5]);
    memory_submit ("cache",    sysctl_vals[6]);
    /* #endif HAVE_SYSCTLBYNAME */

#elif KERNEL_LINUX
    FILE *fh;
    char buffer[1024];

    char *fields[8];
    int numfields;

    long long mem_used = 0;
    long long mem_buffered = 0;
    long long mem_cached = 0;
    long long mem_free = 0;

    if ((fh = fopen ("/proc/meminfo", "r")) == NULL)
    {
        char errbuf[1024];
        WARNING ("memory: fopen: %s",
                 sstrerror (errno, errbuf, sizeof (errbuf)));
        return (-1);
    }

    while (fgets (buffer, 1024, fh) != NULL)
    {
        long long *val = NULL;

        if (strncasecmp (buffer, "MemTotal:", 9) == 0)
            val = &mem_used;
        else if (strncasecmp (buffer, "MemFree:", 8) == 0)
            val = &mem_free;
        else if (strncasecmp (buffer, "Buffers:", 8) == 0)
            val = &mem_buffered;
        else if (strncasecmp (buffer, "Cached:", 7) == 0)
            val = &mem_cached;
        else
            continue;

        numfields = strsplit (buffer, fields, 8);

        if (numfields < 2)
            continue;

        *val = atoll (fields[1]) * 1024LL;
    }

    if (fclose (fh))
    {
        char errbuf[1024];
        WARNING ("memory: fclose: %s",
                 sstrerror (errno, errbuf, sizeof (errbuf)));
    }

    if (mem_used >= (mem_free + mem_buffered + mem_cached))
    {
        mem_used -= mem_free + mem_buffered + mem_cached;
        memory_submit ("used",     mem_used);
        memory_submit ("buffered", mem_buffered);
        memory_submit ("cached",   mem_cached);
        memory_submit ("free",     mem_free);
    }
    /* #endif KERNEL_LINUX */

#elif HAVE_LIBKSTAT
    /* Most of the additions here were taken as-is from the k9toolkit from
     * Brendan Gregg and are subject to change I guess */
    long long mem_used;
    long long mem_free;
    long long mem_lock;
    long long mem_kern;
    long long mem_unus;

    long long pp_kernel;
    long long physmem;
    long long availrmem;

    if (ksp == NULL)
        return (-1);

    mem_used = get_kstat_value (ksp, "pagestotal");
    mem_free = get_kstat_value (ksp, "pagesfree");
    mem_lock = get_kstat_value (ksp, "pageslocked");
    mem_kern = 0;
    mem_unus = 0;

    pp_kernel = get_kstat_value (ksp, "pp_kernel");
    physmem = get_kstat_value (ksp, "physmem");
    availrmem = get_kstat_value (ksp, "availrmem");

    if ((mem_used < 0LL) || (mem_free < 0LL) || (mem_lock < 0LL))
    {
        WARNING ("memory plugin: one of used, free or locked is negative.");
        return (-1);
    }

    mem_unus = physmem - mem_used;

    if (mem_used < (mem_free + mem_lock))
    {
        /* source: http://wesunsolve.net/bugid/id/4909199
         * this seems to happen when swap space is small, e.g. 2G on a 32G system
         * we will make some assumptions here
         * educated solaris internals help welcome here */
        DEBUG ("memory plugin: pages total is smaller than \"free\" "
               "+ \"locked\". This is probably due to small "
               "swap space");
        mem_free = availrmem;
        mem_used = 0;
    }
    else
    {
        mem_used -= mem_free + mem_lock;
    }

    /* mem_kern is accounted for in mem_lock */
    if ( pp_kernel < mem_lock )
    {
        mem_kern = pp_kernel;
        mem_lock -= pp_kernel;
    }
    else
    {
        mem_kern = mem_lock;
        mem_lock = 0;
    }

    mem_used *= pagesize; /* If this overflows you have some serious */
    mem_free *= pagesize; /* memory.. Why not call me up and give me */
    mem_lock *= pagesize; /* some? ;) */
    mem_kern *= pagesize; /* it's 2011 RAM is cheap */
    mem_unus *= pagesize;

    memory_submit ("used",   mem_used);
    memory_submit ("free",   mem_free);
    memory_submit ("locked", mem_lock);
    memory_submit ("kernel", mem_kern);
    memory_submit ("unusable", mem_unus);
    /* #endif HAVE_LIBKSTAT */

#elif HAVE_SYSCTL
    int mib[] = {CTL_VM, VM_METER};
    struct vmtotal vmtotal;
    size_t size;

    memset (&vmtotal, 0, sizeof (vmtotal));
    size = sizeof (vmtotal);

    if (sysctl (mib, 2, &vmtotal, &size, NULL, 0) < 0) {
        char errbuf[1024];
        WARNING ("memory plugin: sysctl failed: %s",
                 sstrerror (errno, errbuf, sizeof (errbuf)));
        return (-1);
    }

    assert (pagesize > 0);
    memory_submit ("active",   vmtotal.t_arm * pagesize);
    memory_submit ("inactive", (vmtotal.t_rm - vmtotal.t_arm) * pagesize);
    memory_submit ("free",     vmtotal.t_free * pagesize);
    /* #endif HAVE_SYSCTL */

#elif HAVE_LIBSTATGRAB
    sg_mem_stats *ios;

    if ((ios = sg_get_mem_stats ()) != NULL)
    {
        memory_submit ("used",   ios->used);
        memory_submit ("cached", ios->cache);
        memory_submit ("free",   ios->free);
    }
    /* #endif HAVE_LIBSTATGRAB */

#elif HAVE_PERFSTAT
    if (perfstat_memory_total(NULL, &pmemory, sizeof(perfstat_memory_total_t), 1) < 0)
    {
        char errbuf[1024];
        WARNING ("memory plugin: perfstat_memory_total failed: %s",
                 sstrerror (errno, errbuf, sizeof (errbuf)));
        return (-1);
    }
    memory_submit ("used",   pmemory.real_inuse * pagesize);
    memory_submit ("free",   pmemory.real_free * pagesize);
    memory_submit ("cached", pmemory.numperm * pagesize);
    memory_submit ("system", pmemory.real_system * pagesize);
    memory_submit ("user",   pmemory.real_process * pagesize);
#endif /* HAVE_PERFSTAT */

    return (0);
}
Esempio n. 17
0
cholmod_sparse *CHOLMOD(vertcat)
(
    /* ---- input ---- */
    cholmod_sparse *A,	/* left matrix to concatenate */
    cholmod_sparse *B,	/* right matrix to concatenate */
    int values,		/* if TRUE compute the numerical values of C */
    /* --------------- */
    cholmod_common *Common
)
{
    double *Ax, *Bx, *Cx ;
    Int *Ap, *Ai, *Anz, *Bp, *Bi, *Bnz, *Cp, *Ci ;
    cholmod_sparse *C, *A2, *B2 ;
    Int apacked, bpacked, anrow, bnrow, ncol, nrow, anz, bnz, nz, j, p, pend,
	pdest ;

    /* ---------------------------------------------------------------------- */
    /* check inputs */
    /* ---------------------------------------------------------------------- */

    RETURN_IF_NULL_COMMON (NULL) ;
    RETURN_IF_NULL (A, NULL) ;
    RETURN_IF_NULL (B, NULL) ;
    values = values &&
	(A->xtype != CHOLMOD_PATTERN) && (B->xtype != CHOLMOD_PATTERN) ;
    RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN,
	    values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ;
    RETURN_IF_XTYPE_INVALID (B, CHOLMOD_PATTERN,
	    values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ;
    if (A->ncol != B->ncol)
    {
	/* A and B must have the same number of columns */
	ERROR (CHOLMOD_INVALID, "A and B must have same # of columns") ;
	return (NULL) ;
    }
    /* A and B must have the same numerical type if values is TRUE (both must
     * be CHOLMOD_REAL, this is implicitly checked above) */
    Common->status = CHOLMOD_OK ;

    /* ---------------------------------------------------------------------- */
    /* allocate workspace */
    /* ---------------------------------------------------------------------- */

    anrow = A->nrow ;
    bnrow = B->nrow ;
    ncol = A->ncol ;
    CHOLMOD(allocate_work) (0, MAX3 (anrow, bnrow, ncol), 0, Common) ;
    if (Common->status < CHOLMOD_OK)
    {
	/* out of memory */
	return (NULL) ;
    }

    /* ---------------------------------------------------------------------- */
    /* get inputs */
    /* ---------------------------------------------------------------------- */

    /* convert A to unsymmetric, if necessary */
    A2 = NULL ;
    if (A->stype != 0)
    {
	/* workspace: Iwork (max (A->nrow,A->ncol)) */
	A2 = CHOLMOD(copy) (A, 0, values, Common) ;
	if (Common->status < CHOLMOD_OK)
	{
	    /* out of memory */
	    return (NULL) ;
	}
	A = A2 ;
    }

    /* convert B to unsymmetric, if necessary */
    B2 = NULL ;
    if (B->stype != 0)
    {
	/* workspace: Iwork (max (B->nrow,B->ncol)) */
	B2 = CHOLMOD(copy) (B, 0, values, Common) ;
	if (Common->status < CHOLMOD_OK)
	{
	    /* out of memory */
	    CHOLMOD(free_sparse) (&A2, Common) ;
	    return (NULL) ;
	}
	B = B2 ;
    }

    Ap  = A->p ;
    Anz = A->nz ;
    Ai  = A->i ;
    Ax  = A->x ;
    apacked = A->packed ;

    Bp  = B->p ;
    Bnz = B->nz ;
    Bi  = B->i ;
    Bx  = B->x ;
    bpacked = B->packed ;

    /* ---------------------------------------------------------------------- */
    /* allocate C */
    /* ---------------------------------------------------------------------- */

    anz = CHOLMOD(nnz) (A, Common) ;
    bnz = CHOLMOD(nnz) (B, Common) ;
    nrow = anrow + bnrow ;
    nz = anz + bnz ;

    C = CHOLMOD(allocate_sparse) (nrow, ncol, nz, A->sorted && B->sorted, TRUE,
	    0, values ? A->xtype : CHOLMOD_PATTERN, Common) ;
    if (Common->status < CHOLMOD_OK)
    {
	/* out of memory */
	CHOLMOD(free_sparse) (&A2, Common) ;
	CHOLMOD(free_sparse) (&B2, Common) ;
	return (NULL) ;
    }
    Cp = C->p ;
    Ci = C->i ;
    Cx = C->x ;

    /* ---------------------------------------------------------------------- */
    /* C = [A ; B] */
    /* ---------------------------------------------------------------------- */

    pdest = 0 ;
    for (j = 0 ; j < ncol ; j++)
    {
	/* attach A(:,j) as the first part of C(:,j) */
	p = Ap [j] ;
	pend = (apacked) ? (Ap [j+1]) : (p + Anz [j]) ;
	Cp [j] = pdest ;
	for ( ; p < pend ; p++)
	{
	    Ci [pdest] = Ai [p] ;
	    if (values)
	    {
		Cx [pdest] = Ax [p] ;
	    }
	    pdest++ ;
	}

	/* attach B(:,j) as the second part of C(:,j) */
	p = Bp [j] ;
	pend = (bpacked) ? (Bp [j+1]) : (p + Bnz [j]) ;
	for ( ; p < pend ; p++)
	{
	    Ci [pdest] = Bi [p] + anrow ;
	    if (values)
	    {
		Cx [pdest] = Bx [p] ;
	    }
	    pdest++ ;
	}
    }
    Cp [ncol] = pdest ;
    ASSERT (pdest == nz) ;

    /* ---------------------------------------------------------------------- */
    /* free the unsymmetric copies of A and B, and return C */
    /* ---------------------------------------------------------------------- */

    CHOLMOD(free_sparse) (&A2, Common) ;
    CHOLMOD(free_sparse) (&B2, Common) ;
    return (C) ;
}
Esempio n. 18
0
/**
 *  Get process config values from the database.
 *
 *  The nature of this function requires that NULL column values in the
 *  process_config table will match any argument value. A SQL reqular
 *  expression can be used for the key argument.
 *
 *  The memory used by the output array is dynamically allocated.
 *  It is the responsibility of the calling process to free this memory
 *  when it is no longer needed (see dsdb_free_process_config_values()).
 *
 *  Error messages from this function are sent to the message
 *  handler (see msngr_init_log() and msngr_init_mail()).
 *
 *  Null results from the database are not reported as errors.
 *  It is the responsibility of the calling process to report
 *  these as errors if necessary.
 *
 *  @param  dsdb      - pointer to the open database connection
 *  @param  site      - site name
 *  @param  facility  - facility name
 *  @param  proc_type - process type
 *  @param  proc_name - process name
 *  @param  key       - config key
 *  @param  proc_conf - output: pointer to the NULL terminated array
 *                              of ProcConf structure pointers
 *
 *  @return
 *    -  1 if successful
 *    -  0 if the database returned a NULL result
 *    - -1 if an error occurred
 *
 *  @see  dsdb_free_process_config_values()
 */
int dsdb_get_process_config_values(
    DSDB         *dsdb,
    const char   *site,
    const char   *facility,
    const char   *proc_type,
    const char   *proc_name,
    const char   *key,
    ProcConf   ***proc_conf)
{
    DBStatus  status;
    DBResult *dbres;
    int       row;

    *proc_conf = (ProcConf **)NULL;
    
    status = dsdbog_get_process_config_values(
        dsdb->dbconn, proc_type, proc_name, site, facility, key, &dbres);

    if (status == DB_NO_ERROR) {

        *proc_conf = (ProcConf **)calloc(dbres->nrows + 1, sizeof(ProcConf *));
        if (!*proc_conf) {

            ERROR( DSDB_LIB_NAME,
                "Could not get process config values\n"
                " -> memory allocation error\n");

            dbres->free(dbres);
            return(-1);
        }

        for (row = 0; row < dbres->nrows; row++) {

            (*proc_conf)[row] = _dsdb_create_proc_conf(
                ProcConfType(dbres,row),
                ProcConfName(dbres,row),
                ProcConfSite(dbres,row),
                ProcConfFac(dbres,row),
                ProcConfKey(dbres,row),
                ProcConfValue(dbres,row));

            if (!(*proc_conf)[row]) {

                ERROR( DSDB_LIB_NAME,
                    "Could not get process config values\n"
                    " -> memory allocation error\n");

                dsdb_free_process_config_values(*proc_conf);
                *proc_conf = (ProcConf **)NULL;

                dbres->free(dbres);
                return(-1);
            }
        }

        (*proc_conf)[dbres->nrows] = (ProcConf *)NULL;

        dbres->free(dbres);
        return(1);
    }
    else if (status == DB_NULL_RESULT) {
        return(0);
    }

    return(-1);
}
Esempio n. 19
0
status_t
fs_mount(fs_volume *_vol, const char *device, ulong flags, const char *args,
	ino_t *_rootID)
{
	nspace *ns;
	vnode *newNode = NULL;
	char lockname[32];
	void *handle;
	unsigned long mountFlags = 0;
	status_t result = B_NO_ERROR;

	TRACE("fs_mount - ENTER\n");

	ns = ntfs_malloc(sizeof(nspace));
	if (!ns) {
		result = ENOMEM;
		goto exit;
	}

	*ns = (nspace) {
		.state = NF_FreeClustersOutdate | NF_FreeMFTOutdate,
		.show_sys_files = false,
		.ro = false,
		.flags = 0
	};

	strcpy(ns->devicePath,device);

	sprintf(lockname, "ntfs_lock %lx", ns->id);
	recursive_lock_init_etc(&(ns->vlock), lockname, MUTEX_FLAG_CLONE_NAME);

	handle = load_driver_settings("ntfs");
	ns->show_sys_files = ! (strcasecmp(get_driver_parameter(handle,
		"hide_sys_files", "true", "true"), "true") == 0);
	ns->ro = strcasecmp(get_driver_parameter(handle, "read_only", "false",
		"false"), "false") != 0;
	ns->noatime = strcasecmp(get_driver_parameter(handle, "no_atime", "true",
		"true"), "true") == 0;
	unload_driver_settings(handle);

	if (ns->ro || (flags & B_MOUNT_READ_ONLY) != 0) {
		mountFlags |= MS_RDONLY;
		ns->flags |= B_FS_IS_READONLY;
	}

	// TODO: this does not take read-only volumes into account!
	ns->ntvol = utils_mount_volume(device, mountFlags, true);
	if (ns->ntvol != NULL)
		result = B_NO_ERROR;
	else
		result = errno;

	if (result == B_NO_ERROR) {
		*_rootID = FILE_root;
		ns->id = _vol->id;
		_vol->private_volume = (void *)ns;
		_vol->ops = &gNTFSVolumeOps;

		newNode = (vnode*)ntfs_calloc(sizeof(vnode));
		if (newNode == NULL)
			result = ENOMEM;
		else {
			newNode->vnid = *_rootID;
			newNode->parent_vnid = -1;

			result = publish_vnode(_vol, *_rootID, (void*)newNode,
				&gNTFSVnodeOps, S_IFDIR, 0);
			if (result != B_NO_ERROR) {
				free(ns);
				result = EINVAL;
				goto exit;
			} else {
				result = B_NO_ERROR;
				ntfs_mark_free_space_outdated(ns);
				ntfs_calc_free_space(ns);
			}
		}
	} else
		free(ns);

exit:
	ERROR("fs_mount - EXIT, result code is %s\n", strerror(result));

	return result;
}


status_t
fs_unmount(fs_volume *_vol)
{
	nspace *ns = (nspace*)_vol->private_volume;
	status_t result = B_NO_ERROR;

	TRACE("fs_unmount - ENTER\n");

	ntfs_umount(ns->ntvol, true);

	recursive_lock_destroy(&(ns->vlock));

	free(ns);

	TRACE("fs_unmount - EXIT, result is %s\n", strerror(result));

	return result;
}
Esempio n. 20
0
SLEvaluatorConcrete<RT>::SLEvaluatorConcrete(SLProgram *SLP, M2_arrayint cPos,  M2_arrayint vPos, 
					     const MutableMat< SMat<RT> >* consts /* DMat<RT>& DMat_consts */)
  : mRing(consts->getMat().ring())
{
  ERROR("not implemented");
}    
Esempio n. 21
0
static int mysql_read_slave_stats (mysql_database_t *db, MYSQL *con)
{
	MYSQL_RES *res;
	MYSQL_ROW  row;

	char *query;
	int   field_num;

	/* WTF? libmysqlclient does not seem to provide any means to
	 * translate a column name to a column index ... :-/ */
	const int READ_MASTER_LOG_POS_IDX   = 6;
	const int SLAVE_IO_RUNNING_IDX      = 10;
	const int SLAVE_SQL_RUNNING_IDX     = 11;
	const int EXEC_MASTER_LOG_POS_IDX   = 21;
	const int SECONDS_BEHIND_MASTER_IDX = 32;

	query = "SHOW SLAVE STATUS";

	res = exec_query (con, query);
	if (res == NULL)
		return (-1);

	row = mysql_fetch_row (res);
	if (row == NULL)
	{
		ERROR ("mysql plugin: Failed to get slave statistics: "
				"`%s' did not return any rows.", query);
		mysql_free_result (res);
		return (-1);
	}

	field_num = mysql_num_fields (res);
	if (field_num < 33)
	{
		ERROR ("mysql plugin: Failed to get slave statistics: "
				"`%s' returned less than 33 columns.", query);
		mysql_free_result (res);
		return (-1);
	}

	if (db->slave_stats)
	{
		unsigned long long counter;
		double gauge;

		counter = atoll (row[READ_MASTER_LOG_POS_IDX]);
		counter_submit ("mysql_log_position", "slave-read", counter, db);

		counter = atoll (row[EXEC_MASTER_LOG_POS_IDX]);
		counter_submit ("mysql_log_position", "slave-exec", counter, db);

		if (row[SECONDS_BEHIND_MASTER_IDX] != NULL)
		{
			gauge = atof (row[SECONDS_BEHIND_MASTER_IDX]);
			gauge_submit ("time_offset", NULL, gauge, db);
		}
	}

	if (db->slave_notif)
	{
		notification_t n = { 0, cdtime (), "", "",
			"mysql", "", "time_offset", "", NULL };

		char *io, *sql;

		io  = row[SLAVE_IO_RUNNING_IDX];
		sql = row[SLAVE_SQL_RUNNING_IDX];

		set_host (db, n.host, sizeof (n.host));

		/* Assured by "mysql_config_database" */
		assert (db->instance != NULL);
		sstrncpy (n.plugin_instance, db->instance, sizeof (n.plugin_instance));

		if (((io == NULL) || (strcasecmp (io, "yes") != 0))
				&& (db->slave_io_running))
		{
			n.severity = NOTIF_WARNING;
			ssnprintf (n.message, sizeof (n.message),
					"slave I/O thread not started or not connected to master");
			plugin_dispatch_notification (&n);
			db->slave_io_running = 0;
		}
		else if (((io != NULL) && (strcasecmp (io, "yes") == 0))
				&& (! db->slave_io_running))
		{
			n.severity = NOTIF_OKAY;
			ssnprintf (n.message, sizeof (n.message),
					"slave I/O thread started and connected to master");
			plugin_dispatch_notification (&n);
			db->slave_io_running = 1;
		}

		if (((sql == NULL) || (strcasecmp (sql, "yes") != 0))
				&& (db->slave_sql_running))
		{
			n.severity = NOTIF_WARNING;
			ssnprintf (n.message, sizeof (n.message),
					"slave SQL thread not started");
			plugin_dispatch_notification (&n);
			db->slave_sql_running = 0;
		}
		else if (((sql != NULL) && (strcasecmp (sql, "yes") == 0))
				&& (! db->slave_sql_running))
		{
			n.severity = NOTIF_OKAY;
			ssnprintf (n.message, sizeof (n.message),
					"slave SQL thread started");
			plugin_dispatch_notification (&n);
			db->slave_sql_running = 1;
		}
	}

	row = mysql_fetch_row (res);
	if (row != NULL)
		WARNING ("mysql plugin: `%s' returned more than one row - "
				"ignoring further results.", query);

	mysql_free_result (res);

	return (0);
} /* mysql_read_slave_stats */
Esempio n. 22
0
bool HomotopyConcrete< RT, FixedPrecisionHomotopyAlgorithm > :: track(
     const MutableMatrix* inputs, 
     MutableMatrix* outputs, 
     MutableMatrix* output_extras,  
     gmp_RR init_dt, 
     gmp_RR min_dt,
     gmp_RR epsilon, // o.CorrectorTolerance,
     int max_corr_steps, 
     gmp_RR infinity_threshold,
     bool checkPrecision )
{
  std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
  size_t solveLinearTime = 0, solveLinearCount = 0, evaluateTime = 0;
 
  // std::cout << "inside HomotopyConcrete<RT,FixedPrecisionHomotopyAlgorithm>::track" << std::endl;
  // double the_smallest_number = 1e-13;
  const Ring* matRing = inputs->get_ring();
  if (outputs->get_ring()!= matRing) { 
    ERROR("outputs and inputs are in different rings");
    return false;
  }
  auto inp = dynamic_cast<const MutableMat< DMat<RT> >*>(inputs);
  auto out = dynamic_cast<MutableMat< DMat<RT> >*>(outputs);
  auto out_extras = dynamic_cast<MutableMat< DMat<M2::ARingZZGMP> >*>(output_extras);
  if (inp == nullptr) { 
    ERROR("inputs: expected a dense mutable matrix");
    return false;
  }
  if (out == nullptr) { 
    ERROR("outputs: expected a dense mutable matrix");
    return false;
  }
  if (out_extras == nullptr) { 
    ERROR("output_extras: expected a dense mutable matrix");
    return false;
  }

  auto& in = inp->getMat();
  auto& ou = out->getMat();
  auto& oe = out_extras->getMat();
  size_t n_sols = in.numColumns();  
  size_t n = in.numRows()-1; // number of x vars

  if (ou.numColumns() != n_sols or ou.numRows() != n+2) { 
    ERROR("output: wrong shape");
    return false;
  }
  if (oe.numColumns() != n_sols or oe.numRows() != 2) { 
    ERROR("output_extras: wrong shape");
    return false;
  }
  
  const RT& C = in.ring();  
  typename RT::RealRingType R = C.real_ring();  

  typedef typename RT::ElementType ElementType;
  typedef typename RT::RealRingType::ElementType RealElementType;
  typedef MatElementaryOps< DMat< RT > > MatOps;
 
  RealElementType t_step;
  RealElementType min_step2;
  RealElementType epsilon2;
  RealElementType infinity_threshold2;
  R.init(t_step);
  R.init(min_step2);
  R.init(epsilon2);
  R.init(infinity_threshold2);
  R.set_from_BigReal(t_step,init_dt); // initial step
  R.set_from_BigReal(min_step2,min_dt);
  R.mult(min_step2, min_step2, min_step2); //min_step^2
  R.set_from_BigReal(epsilon2,epsilon); 
  int tolerance_bits = int(log2(fabs(R.coerceToDouble(epsilon2))));
  R.mult(epsilon2, epsilon2, epsilon2); //epsilon^2
  R.set_from_BigReal(infinity_threshold2,infinity_threshold); 
  R.mult(infinity_threshold2, infinity_threshold2, infinity_threshold2);
  int num_successes_before_increase = 3;

  RealElementType t0,dt,one_minus_t0,dx_norm2,x_norm2,abs2dc;
  R.init(t0);
  R.init(dt);
  R.init(one_minus_t0);
  R.init(dx_norm2);
  R.init(x_norm2);
  R.init(abs2dc);
  
  // constants
  RealElementType one,two,four,six,one_half,one_sixth;
  RealElementType& dt_factor = one_half; 
  R.init(one);
  R.set_from_long(one,1);    
  R.init(two);
  R.set_from_long(two,2);    
  R.init(four);
  R.set_from_long(four,4);
  R.init(six);
  R.set_from_long(six,6);    
  R.init(one_half);
  R.divide(one_half,one,two);
  R.init(one_sixth);
  R.divide(one_sixth,one,six);

  ElementType c_init,c_end,dc,one_half_dc;
  C.init(c_init);
  C.init(c_end);
  C.init(dc);
  C.init(one_half_dc);

  // think: x_0..x_(n-1), c
  // c = the homotopy continuation parameter "t" upstair, varies on a (staight line) segment of complex plane (from c_init to c_end)  
  // t = a real running in the interval [0,1] 

  DMat<RT> x0c0(C,n+1,1); 
  DMat<RT> x1c1(C,n+1,1);
  DMat<RT> xc(C,n+1,1);
  DMat<RT> HxH(C,n,n+1);
  DMat<RT>& Hxt = HxH; // the matrix has the same shape: reuse memory  
  DMat<RT> LHSmat(C,n,n);
  auto LHS = submatrix(LHSmat); 
  DMat<RT> RHSmat(C,n,1);
  auto RHS = submatrix(RHSmat); 
  DMat<RT> dx(C,n,1);
  DMat<RT> dx1(C,n,1);
  DMat<RT> dx2(C,n,1);
  DMat<RT> dx3(C,n,1);
  DMat<RT> dx4(C,n,1);
  DMat<RT> Jinv_times_random(C,n,1);

  ElementType& c0 = x0c0.entry(n,0);
  ElementType& c1 = x1c1.entry(n,0);  
  ElementType& c = xc.entry(n,0);
  RealElementType& tol2 = epsilon2; // current tolerance squared
  bool linearSolve_success;
  for(size_t s=0; s<n_sols; s++) {
    SolutionStatus status = PROCESSING;
    // set initial solution and initial value of the continuation parameter
    //for(size_t i=0; i<=n; i++)   
    //  C.set(x0c0.entry(i,0), in.entry(i,s));
    submatrix(x0c0) = submatrix(const_cast<DMat<RT>&>(in), 0,s, n+1,1); 
    C.set(c_init,c0);
    C.set(c_end,ou.entry(n,s));

    R.set_zero(t0);
    bool t0equals1 = false;

    // t_step is actually the initial (absolute) length of step on the interval [c_init,c_end]
    // dt is an increment for t on the interval [0,1]
    R.set(dt,t_step);
    C.subtract(dc,c_end,c_init); 
    C.abs(abs2dc,dc); // don't wnat to create new temporary elts: reusing dc and abs2dc
    R.divide(dt,dt,abs2dc);

    int predictor_successes = 0;
    int count = 0; // number of steps
    // track the real segment (1-t)*c0 + t*c1, a\in [0,1]
    while (status == PROCESSING and not t0equals1) {
      if (M2_numericalAlgebraicGeometryTrace>3) {
        buffer o; 
        R.elem_text_out(o,t0,true,false,false);
        std::cout << "t0 = " << o.str();
        o.reset();
        C.elem_text_out(o,c0,true,false,false);
        std::cout << ", c0 = " << o.str() << std::endl;
      }
      R.subtract(one_minus_t0,one,t0);
      if (R.compare_elems(dt,one_minus_t0)>0) {
        R.set(dt,one_minus_t0);
        t0equals1 = true;
        C.subtract(dc,c_end,c0);
        C.set(c1,c_end);
      } else {
        C.subtract(dc,c_end,c0);
        C.mult(dc,dc,dt);
        C.divide(dc,dc,one_minus_t0);
        C.add(c1,c0,dc);
      }
      
      // PREDICTOR in: x0c0,dt
      //           out: dx
      /*  top-level code for Runge-Kutta-4 
          dx1 := solveHxTimesDXequalsMinusHt(x0,t0);
          dx2 := solveHxTimesDXequalsMinusHt(x0+(1/2)*dx1*dt,t0+(1/2)*dt);
          dx3 := solveHxTimesDXequalsMinusHt(x0+(1/2)*dx2*dt,t0+(1/2)*dt);
          dx4 := solveHxTimesDXequalsMinusHt(x0+dx3*dt,t0+dt);
          (1/6)*dt*(dx1+2*dx2+2*dx3+dx4)      
      */                    

      C.mult(one_half_dc, dc, one_half);

      // dx1
      submatrix(xc) = submatrix(x0c0);
      TIME(evaluateTime,
           mHxt.evaluate(xc,Hxt)
           )

      LHS = submatrix(Hxt, 0,0, n,n);
      RHS = submatrix(Hxt, 0,n, n,1);
      MatrixOps::negateInPlace(RHSmat);

      TIME(solveLinearTime,
           linearSolve_success = MatrixOps::solveLinear(LHSmat,RHSmat,dx1)
           );
      solveLinearCount++;

      // dx2
      if (linearSolve_success) { 
        submatrix(dx1) *= one_half_dc; // "dx1" := (1/2)*dx1*dt
        submatrix(xc, 0,0, n,1) += submatrix(dx1); 
        C.add(c,c,one_half_dc); 
       
        TIME(evaluateTime,
             mHxt.evaluate(xc,Hxt)
             )

        LHS = submatrix(Hxt, 0,0, n,n);
        RHS = submatrix(Hxt, 0,n, n,1);
        MatrixOps::negateInPlace(RHSmat);

        TIME(solveLinearTime,
             linearSolve_success = MatrixOps::solveLinear(LHSmat,RHSmat,dx2);
             )
        solveLinearCount++;
      }

      // dx3
      if (linearSolve_success) { 
        submatrix(dx2) *= one_half_dc; // "dx2" := (1/2)*dx2*dt
        submatrix(xc, 0,0, n,1) = submatrix(x0c0,  0,0, n,1);
        submatrix(xc, 0,0, n,1) += submatrix(dx2);
        // C.add(c,c,one_half_dc); // c should not change here??? or copy c two lines above??? 
       
        TIME(evaluateTime,
             mHxt.evaluate(xc,Hxt)
             );

        LHS = submatrix(Hxt, 0,0, n,n);
        RHS = submatrix(Hxt, 0,n, n,1);
        MatrixOps::negateInPlace(RHSmat);

        TIME(solveLinearTime,
             linearSolve_success = MatrixOps::solveLinear(LHSmat,RHSmat,dx3);
             );
        solveLinearCount++;
      }

      // dx4
      if (linearSolve_success) { 
        submatrix(dx3) *= dc; // "dx3" := dx3*dt
        submatrix(xc) = submatrix(x0c0); // sets c=c0 as well (not needed for dx2???,dx3)
        submatrix(xc, 0,0, n,1) += submatrix(dx3); 
        C.add(c,c,dc);

        TIME(evaluateTime,
             mHxt.evaluate(xc,Hxt)
             );

        LHS = submatrix(Hxt, 0,0, n,n);
        RHS = submatrix(Hxt, 0,n, n,1);
        MatrixOps::negateInPlace(RHSmat);

        TIME(solveLinearTime,
             linearSolve_success = MatrixOps::solveLinear(LHSmat,RHSmat,dx4);
             );
        solveLinearCount++;
      }
Esempio n. 23
0
/*
 * Initialise cache allocating the specified number of entries, each of
 * size block_size.  To avoid vmalloc fragmentation issues each entry
 * is allocated as a sequence of kmalloced PAGE_CACHE_SIZE buffers.
 */
struct squashfs_cache *squashfs_cache_init(char *name, int entries,
	int block_size)
{
	int i, j;
	struct squashfs_cache *cache = kzalloc(sizeof(*cache), GFP_KERNEL);

	if (cache == NULL) {
		ERROR("Failed to allocate %s cache\n", name);
		return NULL;
	}

	cache->entry = kcalloc(entries, sizeof(*(cache->entry)), GFP_KERNEL);
	if (cache->entry == NULL) {
		ERROR("Failed to allocate %s cache\n", name);
		goto cleanup;
	}

	cache->curr_blk = 0;
	cache->next_blk = 0;
	cache->unused = entries;
	cache->entries = entries;
	cache->block_size = block_size;
	cache->pages = block_size >> PAGE_CACHE_SHIFT;
	cache->pages = cache->pages ? cache->pages : 1;
	cache->name = name;
	cache->num_waiters = 0;
	spin_lock_init(&cache->lock);
	init_waitqueue_head(&cache->wait_queue);

	for (i = 0; i < entries; i++) {
		struct squashfs_cache_entry *entry = &cache->entry[i];

		init_waitqueue_head(&cache->entry[i].wait_queue);
		entry->cache = cache;
		entry->block = SQUASHFS_INVALID_BLK;
		entry->data = kcalloc(cache->pages, sizeof(void *), GFP_KERNEL);
		if (entry->data == NULL) {
			ERROR("Failed to allocate %s cache entry\n", name);
			goto cleanup;
		}

		for (j = 0; j < cache->pages; j++) {
			entry->data[j] = kmalloc(PAGE_CACHE_SIZE, GFP_KERNEL);
			if (entry->data[j] == NULL) {
				ERROR("Failed to allocate %s buffer\n", name);
				goto cleanup;
			}
		}

		entry->actor = squashfs_page_actor_init(entry->data,
						cache->pages, 0);
		if (entry->actor == NULL) {
			ERROR("Failed to allocate %s cache entry\n", name);
			goto cleanup;
		}
	}

	return cache;

cleanup:
	squashfs_cache_delete(cache);
	return NULL;
}
Esempio n. 24
0
/*
 *	Instantiate the module.
 */
static int mod_instantiate(CONF_SECTION *conf, void *instance)
{
	rlm_cache_t *inst = instance;
	CONF_SECTION *update;

	inst->cs = conf;

	inst->xlat_name = cf_section_name2(conf);
	if (!inst->xlat_name) inst->xlat_name = cf_section_name1(conf);

	/*
	 *	Register the cache xlat function
	 */
	xlat_register(inst->xlat_name, cache_xlat, NULL, inst);

	/*
	 *	Sanity check for crazy people.
	 */
	if (strncmp(inst->driver_name, "rlm_cache_", 8) != 0) {
		ERROR("rlm_cache (%s): \"%s\" is NOT an Cache driver!", inst->xlat_name, inst->driver_name);
		return -1;
	}

	/*
	 *	Load the appropriate driver for our database
	 */
	inst->handle = lt_dlopenext(inst->driver_name);
	if (!inst->handle) {
		ERROR("rlm_cache (%s): Could not link driver %s: %s", inst->xlat_name, inst->driver_name, dlerror());
		ERROR("rlm_cache (%s): Make sure it (and all its dependent libraries!) are in the search path"
		      "of your system's ld", inst->xlat_name);
		return -1;
	}

	inst->module = (cache_module_t *) dlsym(inst->handle, inst->driver_name);
	if (!inst->module) {
		ERROR("rlm_cache (%s): Could not link symbol %s: %s", inst->xlat_name, inst->driver_name, dlerror());
		return -1;
	}

	INFO("rlm_cache (%s): Driver %s (module %s) loaded and linked", inst->xlat_name,
	     inst->driver_name, inst->module->name);

	/*
	 *	Non optional fields and callbacks
	 */
	rad_assert(inst->module->name);
	rad_assert(inst->module->find);
	rad_assert(inst->module->insert);
	rad_assert(inst->module->expire);

	if (inst->module->mod_instantiate) {
		CONF_SECTION *cs;
		char const *name;

		name = strrchr(inst->driver_name, '_');
		if (!name) {
			name = inst->driver_name;
		} else {
			name++;
		}

		cs = cf_section_sub_find(conf, name);
		if (!cs) {
			cs = cf_section_alloc(conf, name, NULL);
			if (!cs) return -1;
		}

		/*
		 *	It's up to the driver to register a destructor (using talloc)
		 *
		 *	Should write its instance data in inst->driver,
		 *	and parent it off of inst.
		 */
		if (inst->module->mod_instantiate(cs, inst) < 0) return -1;
	}

	rad_assert(inst->key && *inst->key);

	if (inst->ttl == 0) {
		cf_log_err_cs(conf, "Must set 'ttl' to non-zero");
		return -1;
	}

	if (inst->epoch != 0) {
		cf_log_err_cs(conf, "Must not set 'epoch' in the configuration files");
		return -1;
	}

	update = cf_section_sub_find(inst->cs, "update");
	if (!update) {
		cf_log_err_cs(conf, "Must have an 'update' section in order to cache anything.");
		return -1;
	}

	/*
	 *	Make sure the users don't screw up too badly.
	 */
	if (map_afrom_cs(&inst->maps, update,
			 PAIR_LIST_REQUEST, PAIR_LIST_REQUEST, cache_verify, NULL, MAX_ATTRMAP) < 0) {
		return -1;
	}

	if (!inst->maps) {
		cf_log_err_cs(inst->cs, "Cache config must contain an update section, and "
			      "that section must not be empty");

		return -1;
	}
	return 0;
}
Esempio n. 25
0
void
delete_archive_members (void)
{
  enum read_header logical_status = HEADER_STILL_UNREAD;
  enum read_header previous_status = HEADER_STILL_UNREAD;

  /* FIXME: Should clean the routine before cleaning these variables :-( */
  struct name *name;
  off_t blocks_to_skip = 0;
  off_t blocks_to_keep = 0;
  int kept_blocks_in_record;

  name_gather ();
  open_archive (ACCESS_UPDATE);
  acting_as_filter = strcmp (archive_name_array[0], "-") == 0;

  do
    {
      enum read_header status = read_header (true);

      switch (status)
	{
	case HEADER_STILL_UNREAD:
	  abort ();

	case HEADER_SUCCESS:
	  if ((name = name_scan (current_stat_info.file_name)) == NULL)
	    {
	      skip_member ();
	      break;
	    }
	  name->found_count++;
	  if (!ISFOUND(name))
	    {
	      skip_member ();
	      break;
	    }

	  /* Fall through.  */
	case HEADER_SUCCESS_EXTENDED:
	  logical_status = status;
	  break;

	case HEADER_ZERO_BLOCK:
	  if (ignore_zeros_option)
	    {
	      set_next_block_after (current_header);
	      break;
	    }
	  /* Fall through.  */
	case HEADER_END_OF_FILE:
	  logical_status = HEADER_END_OF_FILE;
	  break;

	case HEADER_FAILURE:
	  set_next_block_after (current_header);
	  switch (previous_status)
	    {
	    case HEADER_STILL_UNREAD:
	      WARN ((0, 0, _("This does not look like a tar archive")));
	      /* Fall through.  */

	    case HEADER_SUCCESS:
	    case HEADER_SUCCESS_EXTENDED:
	    case HEADER_ZERO_BLOCK:
	      ERROR ((0, 0, _("Skipping to next header")));
	      /* Fall through.  */

	    case HEADER_FAILURE:
	      break;

	    case HEADER_END_OF_FILE:
	      abort ();
	    }
	  break;
	}

      previous_status = status;
    }
  while (logical_status == HEADER_STILL_UNREAD);

  records_skipped = records_read - 1;
  new_record = xmalloc (record_size);

  if (logical_status == HEADER_SUCCESS
      || logical_status == HEADER_SUCCESS_EXTENDED)
    {
      write_archive_to_stdout = false;

      /* Save away blocks before this one in this record.  */

      new_blocks = current_block - record_start;
      if (new_blocks)
	memcpy (new_record, record_start, new_blocks * BLOCKSIZE);

      if (logical_status == HEADER_SUCCESS)
	{
	  /* FIXME: Pheew!  This is crufty code!  */
	  logical_status = HEADER_STILL_UNREAD;
	  goto flush_file;
	}

      /* FIXME: Solaris 2.4 Sun cc (the ANSI one, not the old K&R) says:
	 "delete.c", line 223: warning: loop not entered at top
	 Reported by Bruno Haible.  */
      while (1)
	{
	  enum read_header status;

	  /* Fill in a record.  */

	  if (current_block == record_end)
	    flush_archive ();
	  status = read_header (false);

	  xheader_decode (&current_stat_info);

	  if (status == HEADER_ZERO_BLOCK && ignore_zeros_option)
	    {
	      set_next_block_after (current_header);
	      continue;
	    }
	  if (status == HEADER_END_OF_FILE || status == HEADER_ZERO_BLOCK)
	    {
	      logical_status = HEADER_END_OF_FILE;
	      break;
	    }

	  if (status == HEADER_FAILURE)
	    {
	      ERROR ((0, 0, _("Deleting non-header from archive")));
	      set_next_block_after (current_header);
	      continue;
	    }

	  /* Found another header.  */

	  if ((name = name_scan (current_stat_info.file_name)) != NULL)
	    {
	      name->found_count++;
	      if (ISFOUND(name))
		{
		flush_file:
		  set_next_block_after (current_header);
		  blocks_to_skip = (current_stat_info.stat.st_size
				    + BLOCKSIZE - 1) / BLOCKSIZE;
		  
		  while (record_end - current_block <= blocks_to_skip)
		    {
		      blocks_to_skip -= (record_end - current_block);
		      flush_archive ();
		    }
		  current_block += blocks_to_skip;
		  blocks_to_skip = 0;
		  continue;
		}
	    }
	  /* Copy header.  */

	  if (current_stat_info.xhdr.size)
	    {
	      write_recent_bytes (current_stat_info.xhdr.buffer,
				  current_stat_info.xhdr.size);
	    }
	  else
	    {
	      write_recent_blocks (recent_long_name, recent_long_name_blocks);
	      write_recent_blocks (recent_long_link, recent_long_link_blocks);
	    }
	  new_record[new_blocks] = *current_header;
	  new_blocks++;
	  blocks_to_keep
	    = (current_stat_info.stat.st_size + BLOCKSIZE - 1) / BLOCKSIZE;
	  set_next_block_after (current_header);
	  if (new_blocks == blocking_factor)
	    write_record (1);

	  /* Copy data.  */

	  kept_blocks_in_record = record_end - current_block;
	  if (kept_blocks_in_record > blocks_to_keep)
	    kept_blocks_in_record = blocks_to_keep;

	  while (blocks_to_keep)
	    {
	      int count;

	      if (current_block == record_end)
		{
		  flush_read ();
		  current_block = record_start;
		  kept_blocks_in_record = blocking_factor;
		  if (kept_blocks_in_record > blocks_to_keep)
		    kept_blocks_in_record = blocks_to_keep;
		}
	      count = kept_blocks_in_record;
	      if (blocking_factor - new_blocks < count)
		count = blocking_factor - new_blocks;

	      if (! count)
		abort ();

	      memcpy (new_record + new_blocks, current_block, count * BLOCKSIZE);
	      new_blocks += count;
	      current_block += count;
	      blocks_to_keep -= count;
	      kept_blocks_in_record -= count;

	      if (new_blocks == blocking_factor)
		write_record (1);
	    }
	}

      if (logical_status == HEADER_END_OF_FILE)
	{
	  /* Write the end of tape.  FIXME: we can't use write_eot here,
	     as it gets confused when the input is at end of file.  */

	  int total_zero_blocks = 0;

	  do
	    {
	      int zero_blocks = blocking_factor - new_blocks;
	      memset (new_record + new_blocks, 0, BLOCKSIZE * zero_blocks);
	      total_zero_blocks += zero_blocks;
	      write_record (total_zero_blocks < 2);
	    }
	  while (total_zero_blocks < 2);
	}

      if (! acting_as_filter && ! _isrmt (archive))
	{
	  if (sys_truncate (archive))
	    truncate_warn (archive_name_array[0]);
	}
    }
  free (new_record);

  close_archive ();
  names_notfound ();
}
Esempio n. 26
0
int agentMain(
    rsComm_t *rsComm ) {
    if ( !rsComm ) {
        return SYS_INTERNAL_NULL_INPUT_ERR;

    }

    int status = 0;

    // =-=-=-=-=-=-=-
    // capture server properties
    irods::server_properties& props = irods::server_properties::getInstance();
    irods::error result = props.capture_if_needed();
    if ( !result.ok() ) {
        irods::log( PASSMSG( "failed to read server configuration", result ) );
    }

    // =-=-=-=-=-=-=-
    // compiler backwards compatibility hack
    // see header file for more details
    irods::dynamic_cast_hack();

    while ( result.ok() && status >= 0 ) {

        // set default to the native auth scheme here.
        if ( rsComm->auth_scheme == NULL ) {
            rsComm->auth_scheme = strdup( "native" );
        }
        // construct an auth object based on the scheme specified in the comm
        irods::auth_object_ptr auth_obj;
        irods::error ret = irods::auth_factory( rsComm->auth_scheme, &rsComm->rError, auth_obj );
        if ( ( result = ASSERT_PASS( ret, "Failed to factory an auth object for scheme: \"%s\".", rsComm->auth_scheme ) ).ok() ) {

            irods::plugin_ptr ptr;
            ret = auth_obj->resolve( irods::AUTH_INTERFACE, ptr );
            if ( ( result = ASSERT_PASS( ret, "Failed to resolve the auth plugin for scheme: \"%s\".",
                                         rsComm->auth_scheme ) ).ok() ) {

                irods::auth_ptr auth_plugin = boost::dynamic_pointer_cast< irods::auth >( ptr );

                // Call agent start
                char* foo = "";
                ret = auth_plugin->call < const char* > ( rsComm, irods::AUTH_AGENT_START, auth_obj, foo );
                result = ASSERT_PASS( ret, "Failed during auth plugin agent start for scheme: \"%s\".", rsComm->auth_scheme );
            }

            // =-=-=-=-=-=-=-
            // add the user info to the server properties for
            // reach by the operation wrapper for access by the
            // dynamic policy enforcement points
            set_rule_engine_globals( rsComm, props );
        }

        if ( result.ok() ) {
            if ( rsComm->ssl_do_accept ) {
                status = sslAccept( rsComm );
                if ( status < 0 ) {
                    rodsLog( LOG_ERROR, "sslAccept failed in agentMain with status %d", status );
                }
                rsComm->ssl_do_accept = 0;
            }
            if ( rsComm->ssl_do_shutdown ) {
                status = sslShutdown( rsComm );
                if ( status < 0 ) {
                    rodsLog( LOG_ERROR, "sslShutdown failed in agentMain with status %d", status );
                }
                rsComm->ssl_do_shutdown = 0;
            }

            status = readAndProcClientMsg( rsComm, READ_HEADER_TIMEOUT );
            if ( status < 0 ) {
                if ( status == DISCONN_STATUS ) {
                    status = 0;
                    break;
                }
            }
        }
    }

    if ( !result.ok() ) {
        irods::log( result );
        status = result.code();
        return status;
    }

    // =-=-=-=-=-=-=-
    // determine if we even need to connect, break the
    // infinite reconnect loop.
    if ( !resc_mgr.need_maintenance_operations() ) {
        return status;
    }

    // =-=-=-=-=-=-=-
    // find the icat host
    rodsServerHost_t *rodsServerHost = 0;
    status = getRcatHost( MASTER_RCAT, 0, &rodsServerHost );
    if ( status < 0 ) {
        irods::log( ERROR( status, "getRcatHost failed." ) );
        return status;
    }

    // =-=-=-=-=-=-=-
    // connect to the icat host
    status = svrToSvrConnect( rsComm, rodsServerHost );
    if ( status < 0 ) {
        irods::log( ERROR( status, "svrToSvrConnect failed." ) );
        return status;
    }

    // =-=-=-=-=-=-=-
    // call post disconnect maintenance operations before exit
    status = resc_mgr.call_maintenance_operations( rodsServerHost->conn );

    return status;
}
Esempio n. 27
0
static struct dentry *squashfs_lookup(struct inode *dir, struct dentry *dentry,
				 struct nameidata *nd)
{
	const unsigned char *name = dentry->d_name.name;
	int len = dentry->d_name.len;
	struct inode *inode = NULL;
	struct squashfs_sb_info *msblk = dir->i_sb->s_fs_info;
	struct squashfs_dir_header dirh;
	struct squashfs_dir_entry *dire;
	u64 block = squashfs_i(dir)->start + msblk->directory_table;
	int offset = squashfs_i(dir)->offset;
	int err, length = 0, dir_count, size;

	TRACE("Entered squashfs_lookup [%llx:%x]\n", block, offset);

	dire = kmalloc(sizeof(*dire) + SQUASHFS_NAME_LEN + 1, GFP_KERNEL);
	if (dire == NULL) {
		ERROR("Failed to allocate squashfs_dir_entry\n");
		return ERR_PTR(-ENOMEM);
	}

	if (len > SQUASHFS_NAME_LEN) {
		err = -ENAMETOOLONG;
		goto failed;
	}

	length = get_dir_index_using_name(dir->i_sb, &block, &offset,
				squashfs_i(dir)->dir_idx_start,
				squashfs_i(dir)->dir_idx_offset,
				squashfs_i(dir)->dir_idx_cnt, name, len);

	while (length < i_size_read(dir)) {
		/*
		 * Read directory header.
		 */
		err = squashfs_read_metadata(dir->i_sb, &dirh, &block,
				&offset, sizeof(dirh));
		if (err < 0)
			goto read_failure;

		length += sizeof(dirh);

		dir_count = le32_to_cpu(dirh.count) + 1;

		/* dir_count should never be larger than 256 */
		if (dir_count > 256)
			goto data_error;

		while (dir_count--) {
			/*
			 * Read directory entry.
			 */
			err = squashfs_read_metadata(dir->i_sb, dire, &block,
					&offset, sizeof(*dire));
			if (err < 0)
				goto read_failure;

			size = le16_to_cpu(dire->size) + 1;

			/* size should never be larger than SQUASHFS_NAME_LEN */
			if (size > SQUASHFS_NAME_LEN)
				goto data_error;

			err = squashfs_read_metadata(dir->i_sb, dire->name,
					&block, &offset, size);
			if (err < 0)
				goto read_failure;

			length += sizeof(*dire) + size;

			if (name[0] < dire->name[0])
				goto exit_lookup;

			if (len == size && !strncmp(name, dire->name, len)) {
				unsigned int blk, off, ino_num;
				long long ino;
				blk = le32_to_cpu(dirh.start_block);
				off = le16_to_cpu(dire->offset);
				ino_num = le32_to_cpu(dirh.inode_number) +
					(short) le16_to_cpu(dire->inode_number);
				ino = SQUASHFS_MKINODE(blk, off);

				TRACE("calling squashfs_iget for directory "
					"entry %s, inode  %x:%x, %d\n", name,
					blk, off, ino_num);

				inode = squashfs_iget(dir->i_sb, ino, ino_num);
				goto exit_lookup;
			}
		}
	}

exit_lookup:
	kfree(dire);
	return d_splice_alias(inode, dentry);

data_error:
	err = -EIO;

read_failure:
	ERROR("Unable to read directory block [%llx:%x]\n",
		squashfs_i(dir)->start + msblk->directory_table,
		squashfs_i(dir)->offset);
failed:
	kfree(dire);
	return ERR_PTR(err);
}
struct fstab *fs_mgr_read_fstab(const char *fstab_path)
{
    FILE *fstab_file;
    int cnt, entries;
    ssize_t len;
    size_t alloc_len = 0;
    char *line = NULL;
    const char *delim = " \t";
    char *save_ptr, *p;
    struct fstab *fstab = NULL;
    struct fs_mgr_flag_values flag_vals;
#define FS_OPTIONS_LEN 1024
    char tmp_fs_options[FS_OPTIONS_LEN];

    fstab_file = fopen(fstab_path, "r");
    if (!fstab_file) {
        ERROR("Cannot open file %s\n", fstab_path);
        return 0;
    }

    entries = 0;
    while ((len = getline(&line, &alloc_len, fstab_file)) != -1) {
        /* if the last character is a newline, shorten the string by 1 byte */
        if (line[len - 1] == '\n') {
            line[len - 1] = '\0';
        }
        /* Skip any leading whitespace */
        p = line;
        while (isspace(*p)) {
            p++;
        }
        /* ignore comments or empty lines */
        if (*p == '#' || *p == '\0')
            continue;
        entries++;
    }

    if (!entries) {
        ERROR("No entries found in fstab\n");
        goto err;
    }

    /* Allocate and init the fstab structure */
    fstab = calloc(1, sizeof(struct fstab));
    fstab->num_entries = entries;
    fstab->fstab_filename = strdup(fstab_path);
    fstab->recs = calloc(fstab->num_entries, sizeof(struct fstab_rec));

    fseek(fstab_file, 0, SEEK_SET);

    cnt = 0;
    while ((len = getline(&line, &alloc_len, fstab_file)) != -1) {
        /* if the last character is a newline, shorten the string by 1 byte */
        if (line[len - 1] == '\n') {
            line[len - 1] = '\0';
        }

        /* Skip any leading whitespace */
        p = line;
        while (isspace(*p)) {
            p++;
        }
        /* ignore comments or empty lines */
        if (*p == '#' || *p == '\0')
            continue;

        /* If a non-comment entry is greater than the size we allocated, give an
         * error and quit.  This can happen in the unlikely case the file changes
         * between the two reads.
         */
        if (cnt >= entries) {
            ERROR("Tried to process more entries than counted\n");
            break;
        }

        if (!(p = strtok_r(line, delim, &save_ptr))) {
            ERROR("Error parsing mount source\n");
            goto err;
        }
        fstab->recs[cnt].blk_device = strdup(p);

        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
            ERROR("Error parsing mount_point\n");
            goto err;
        }
        fstab->recs[cnt].mount_point = strdup(p);

        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
            ERROR("Error parsing fs_type\n");
            goto err;
        }
        fstab->recs[cnt].fs_type = strdup(p);

        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
            ERROR("Error parsing mount_flags\n");
            goto err;
        }
        tmp_fs_options[0] = '\0';
        fstab->recs[cnt].flags = parse_flags(p, mount_flags, NULL,
                                       tmp_fs_options, FS_OPTIONS_LEN);

        /* fs_options are optional */
        if (tmp_fs_options[0]) {
            fstab->recs[cnt].fs_options = strdup(tmp_fs_options);
        } else {
            fstab->recs[cnt].fs_options = NULL;
        }

        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
            ERROR("Error parsing fs_mgr_options\n");
            goto err;
        }
        fstab->recs[cnt].fs_mgr_flags = parse_flags(p, fs_mgr_flags,
                                                    &flag_vals, NULL, 0);
        fstab->recs[cnt].key_loc = flag_vals.key_loc;
        fstab->recs[cnt].verity_loc = flag_vals.verity_loc;
        fstab->recs[cnt].length = flag_vals.part_length;
        fstab->recs[cnt].label = flag_vals.label;
        fstab->recs[cnt].partnum = flag_vals.partnum;
        fstab->recs[cnt].swap_prio = flag_vals.swap_prio;
        fstab->recs[cnt].zram_size = flag_vals.zram_size;

        /* If an A/B partition, modify block device to be the real block device */
        if (fstab->recs[cnt].fs_mgr_flags & MF_SLOTSELECT) {
            char propbuf[PROPERTY_VALUE_MAX];
            char *tmp;

            /* use the kernel parameter if set */
            property_get("ro.boot.slot_suffix", propbuf, "");

            if (asprintf(&tmp, "%s%s", fstab->recs[cnt].blk_device, propbuf) > 0) {
                free(fstab->recs[cnt].blk_device);
                fstab->recs[cnt].blk_device = tmp;
            } else {
                ERROR("Error updating block device name\n");
                goto err;
            }
        }
        cnt++;
    }
    fclose(fstab_file);
    free(line);
    return fstab;

err:
    fclose(fstab_file);
    free(line);
    if (fstab)
        fs_mgr_free_fstab(fstab);
    return NULL;
}
Esempio n. 29
0
/*
 * Find and validate the coff header
 *
 */
static int check_nt_hdr(IMAGE_NT_HEADERS *nt_hdr)
{
	int i;
	WORD attr;
	PIMAGE_OPTIONAL_HEADER opt_hdr;

	/* Validate the "PE\0\0" signature */
	if (nt_hdr->Signature != IMAGE_NT_SIGNATURE) {
		ERROR("is this driver file? bad signature %08x",
		      nt_hdr->Signature);
		return -EINVAL;
	}

	opt_hdr = &nt_hdr->OptionalHeader;
	/* Make sure Image is PE32 or PE32+ */
#ifdef CONFIG_X86_64
	if (opt_hdr->Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
		ERROR("kernel is 64-bit, but Windows driver is not 64-bit;"
		      "bad magic: %04X", opt_hdr->Magic);
		return -EINVAL;
	}
#else
	if (opt_hdr->Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
		ERROR("kernel is 32-bit, but Windows driver is not 32-bit;"
		      "bad magic: %04X", opt_hdr->Magic);
		return -EINVAL;
	}
#endif

	/* Validate the image for the current architecture. */
#ifdef CONFIG_X86_64
	if (nt_hdr->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) {
		ERROR("kernel is 64-bit, but Windows driver is not 64-bit;"
		      " (PE signature is %04X)", nt_hdr->FileHeader.Machine);
		return -EINVAL;
	}
#else
	if (nt_hdr->FileHeader.Machine != IMAGE_FILE_MACHINE_I386) {
		ERROR("kernel is 32-bit, but Windows driver is not 32-bit;"
		      " (PE signature is %04X)", nt_hdr->FileHeader.Machine);
		return -EINVAL;
	}
#endif

	/* Must have attributes */
#ifdef CONFIG_X86_64
	attr = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_LARGE_ADDRESS_AWARE;
#else
	attr = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_32BIT_MACHINE;
#endif
	if ((nt_hdr->FileHeader.Characteristics & attr) != attr)
		return -EINVAL;

	/* Must be relocatable */
	attr = IMAGE_FILE_RELOCS_STRIPPED;
	if ((nt_hdr->FileHeader.Characteristics & attr))
		return -EINVAL;

	/* Make sure we have at least one section */
	if (nt_hdr->FileHeader.NumberOfSections == 0)
		return -EINVAL;

	if (opt_hdr->SectionAlignment < opt_hdr->FileAlignment) {
		ERROR("alignment mismatch: secion: 0x%x, file: 0x%x",
		      opt_hdr->SectionAlignment, opt_hdr->FileAlignment);
		return -EINVAL;
	}

	DBGLINKER("number of datadictionary entries %d",
		  opt_hdr->NumberOfRvaAndSizes);
	for (i = 0; i < opt_hdr->NumberOfRvaAndSizes; i++) {
		DBGLINKER("datadirectory %s RVA:%X Size:%d",
			  (i<=IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR)?
			  image_directory_name[i] : "unknown",
			  opt_hdr->DataDirectory[i].VirtualAddress,
			  opt_hdr->DataDirectory[i].Size);
	}

	if ((nt_hdr->FileHeader.Characteristics & IMAGE_FILE_DLL))
		return IMAGE_FILE_DLL;
	if ((nt_hdr->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE))
		return IMAGE_FILE_EXECUTABLE_IMAGE;
	return -EINVAL;
}
Esempio n. 30
0
void glPopAttrib() {
    ERROR_IN_BLOCK();
    glstack_t *cur = tack_pop(&state.stack.attrib);
    if (cur == NULL) {
        ERROR(GL_STACK_UNDERFLOW);
    }

    if (cur->mask & GL_COLOR_BUFFER_BIT) {
#ifndef USE_ES2
        enable_disable(GL_ALPHA_TEST, cur->alpha_test);
        glAlphaFunc(cur->alpha_test_func, cur->alpha_test_ref);
#endif

        enable_disable(GL_BLEND, cur->blend);
        glBlendFunc(cur->blend_src_func, cur->blend_dst_func);

        enable_disable(GL_DITHER, cur->dither);
#ifndef USE_ES2
        enable_disable(GL_COLOR_LOGIC_OP, cur->color_logic_op);
        glLogicOp(cur->logic_op);
#endif

        GLfloat *c;
        glClearColor(v4(cur->clear_color));
        glColorMask(v4(cur->color_mask));
    }

    if (cur->mask & GL_CURRENT_BIT) {
        glColor4f(v4(cur->color));
#ifndef USE_ES2
        glNormal3f(v3(cur->normal));
#endif
        for (int i = 0; i < MAX_TEX; i++) {
            glMultiTexCoord2f(GL_TEXTURE0 + i, v2(cur->tex[i]));
        }
    }

    if (cur->mask & GL_DEPTH_BUFFER_BIT) {
        enable_disable(GL_DEPTH_TEST, cur->depth_test);
        glDepthFunc(cur->depth_func);
        glClearDepth(cur->clear_depth);
        glDepthMask(cur->depth_mask);
    }

    if (cur->mask & GL_ENABLE_BIT) {
        int i;
        GLint max_clip_planes;
        glGetIntegerv(GL_MAX_CLIP_PLANES, &max_clip_planes);
        for (i = 0; i < max_clip_planes; i++) {
            enable_disable(GL_CLIP_PLANE0 + i, *(cur->clip_planes_enabled + i));
        }

        GLint max_lights;
        glGetIntegerv(GL_MAX_LIGHTS, &max_lights);
        for (i = 0; i < max_lights; i++) {
            enable_disable(GL_LIGHT0 + i, *(cur->lights_enabled + i));
        }

        enable_disable(GL_ALPHA_TEST, cur->alpha_test);
        enable_disable(GL_BLEND, cur->blend);
        enable_disable(GL_CULL_FACE, cur->cull_face);
        enable_disable(GL_DEPTH_TEST, cur->depth_test);
        enable_disable(GL_DITHER, cur->dither);
        enable_disable(GL_FOG, cur->fog);
        enable_disable(GL_LIGHTING, cur->lighting);
        enable_disable(GL_LINE_SMOOTH, cur->line_smooth);
        enable_disable(GL_LINE_STIPPLE, cur->line_stipple);
        enable_disable(GL_COLOR_LOGIC_OP, cur->color_logic_op);
        enable_disable(GL_MULTISAMPLE, cur->multisample);
        enable_disable(GL_NORMALIZE, cur->normalize);
        enable_disable(GL_POINT_SMOOTH, cur->point_smooth);
        enable_disable(GL_POLYGON_OFFSET_FILL, cur->polygon_offset_fill);
        enable_disable(GL_SAMPLE_ALPHA_TO_COVERAGE, cur->sample_alpha_to_coverage);
        enable_disable(GL_SAMPLE_ALPHA_TO_ONE, cur->sample_alpha_to_one);
        enable_disable(GL_SAMPLE_COVERAGE, cur->sample_coverage);
        enable_disable(GL_SCISSOR_TEST, cur->scissor_test);
        enable_disable(GL_STENCIL_TEST, cur->stencil_test);
        enable_disable(GL_TEXTURE_2D, cur->texture_2d);
    }

#ifndef USE_ES2
    if (cur->mask & GL_FOG_BIT) {
        enable_disable(GL_FOG, cur->fog);
        glFogfv(GL_FOG_COLOR, cur->fog_color);
        glFogf(GL_FOG_DENSITY, cur->fog_density);
        glFogf(GL_FOG_START, cur->fog_start);
        glFogf(GL_FOG_END, cur->fog_end);
        glFogf(GL_FOG_MODE, cur->fog_mode);
    }
#endif

    if (cur->mask & GL_HINT_BIT) {
        enable_disable(GL_PERSPECTIVE_CORRECTION_HINT, cur->perspective_hint);
        enable_disable(GL_POINT_SMOOTH_HINT, cur->point_smooth_hint);
        enable_disable(GL_LINE_SMOOTH_HINT, cur->line_smooth_hint);
        enable_disable(GL_FOG_HINT, cur->fog_hint);
        enable_disable(GL_GENERATE_MIPMAP_HINT, cur->mipmap_hint);
    }

    if (cur->mask & GL_LINE_BIT) {
        enable_disable(GL_LINE_SMOOTH, cur->line_smooth);
        // TODO: stipple stuff here
        glLineWidth(cur->line_width);
    }

    if (cur->mask & GL_MULTISAMPLE_BIT) {
        enable_disable(GL_MULTISAMPLE, cur->multisample);
        enable_disable(GL_SAMPLE_ALPHA_TO_COVERAGE, cur->sample_alpha_to_coverage);
        enable_disable(GL_SAMPLE_ALPHA_TO_ONE, cur->sample_alpha_to_one);
        enable_disable(GL_SAMPLE_COVERAGE, cur->sample_coverage);
    }

#ifndef USE_ES2
    if (cur->mask & GL_POINT_BIT) {
        enable_disable(GL_POINT_SMOOTH, cur->point_smooth);
        glPointSize(cur->point_size);
    }
#endif

    if (cur->mask & GL_SCISSOR_BIT) {
        enable_disable(GL_SCISSOR_TEST, cur->scissor_test);
        glScissor(v4(cur->scissor_box));
    }

    if (cur->mask & GL_TEXTURE_BIT) {
        glBindTexture(GL_TEXTURE_2D, cur->texture);
    }

    free(cur->clip_planes_enabled);
    free(cur->clip_planes);
    free(cur->lights_enabled);
    free(cur->lights);
    free(cur);
}