void mipi_chimei_video_wxga_init(struct msm_panel_info *pinfo)
{
	if (!pinfo)
		return;

	dprintf(INFO, "mipi-dsi chimei wxga (1366x768) driver ver 1.0.\n");

	/* Landscape */
	pinfo->xres = 1366;
	pinfo->yres = 768;
	pinfo->type =  MIPI_VIDEO_PANEL;
	pinfo->wait_cycle = 0;
	pinfo->bpp = 24; /* RGB888 = 24 bits-per-pixel */

	/* bitclk */
	pinfo->clk_rate = 473400000; /* 473.4 MHZ Calculated */

	/*
	 * this panel is operated by DE,
	 * vsycn and hsync are ignored
	 */

	pinfo->lcdc.h_front_porch = 96+2;/* thfp */
	pinfo->lcdc.h_back_porch = 88;	/* thb */
	pinfo->lcdc.h_pulse_width = 40;	/* thpw */

	pinfo->lcdc.v_front_porch = 15;	/* tvfp */
	pinfo->lcdc.v_back_porch = 23;	/* tvb */
	pinfo->lcdc.v_pulse_width = 20;	/* tvpw */

	pinfo->lcdc.border_clr = 0;		/* black */
	pinfo->lcdc.underflow_clr = 0xff;	/* blue */

	pinfo->lcdc.hsync_skew = 0;

	/* mipi - general */
	pinfo->mipi.vc = 0; /* virtual channel */
	pinfo->mipi.rgb_swap = DSI_RGB_SWAP_RGB;
	pinfo->mipi.tx_eot_append = true;
	pinfo->mipi.t_clk_post = 34;		/* Calculated */
	pinfo->mipi.t_clk_pre = 64;		/* Calculated */

	pinfo->mipi.dsi_phy_db = &dsi_video_mode_phy_db;

	/* Four lanes are recomended for 1366x768 at 60 frames per second */
	pinfo->mipi.frame_rate = 60; /* 60 frames per second */
	pinfo->mipi.data_lane0 = true;
	pinfo->mipi.data_lane1 = true;
	pinfo->mipi.data_lane2 = true;
	pinfo->mipi.data_lane3 = true;

	pinfo->mipi.mode = DSI_VIDEO_MODE;
	/*
	 * Note: The CMI panel input is RGB888,
	 * thus the DSI-to-LVDS bridge output is RGB888.
	 * This parameter selects the DSI-Core output to the bridge.
	 */
	pinfo->mipi.dst_format = DSI_VIDEO_DST_FORMAT_RGB888;

	/* mipi - video mode */
	pinfo->mipi.traffic_mode = DSI_NON_BURST_SYNCH_EVENT;
	pinfo->mipi.pulse_mode_hsa_he = false; /* sync mode */

	pinfo->mipi.hfp_power_stop = false;
	pinfo->mipi.hbp_power_stop = false;
	pinfo->mipi.hsa_power_stop = false;
	pinfo->mipi.eof_bllp_power_stop = false;
	pinfo->mipi.bllp_power_stop = false;

	/* mipi - command mode */
	pinfo->mipi.te_sel = 1; /* TE from vsycn gpio */
	pinfo->mipi.interleave_max = 1;
	/* The bridge supports only Generic Read/Write commands */
	pinfo->mipi.insert_dcs_cmd = false;
	pinfo->mipi.wr_mem_continue = 0;
	pinfo->mipi.wr_mem_start = 0;
	pinfo->mipi.stream = false; /* dma_p */
	pinfo->mipi.mdp_trigger = DSI_CMD_TRIGGER_NONE;
	pinfo->mipi.dma_trigger = DSI_CMD_TRIGGER_SW;
	/*
	 * toshiba d2l chip does not need max_pkt_szie dcs cmd
	 * client reply len is directly configure through
	 * RDPKTLN register (0x0404)
	 */
	pinfo->mipi.no_max_pkt_size = 1;
	pinfo->mipi.force_clk_lane_hs = 1;

	pinfo->mipi.num_of_lanes = 4;
	pinfo->mipi.panel_cmds = NULL; /* use in mipi_dsi_panel_initialize() */
	pinfo->mipi.num_of_panel_cmds = 0;


	/* Provide config/on/off callbacks */
	pinfo->on = mipi_chimei_video_wxga_on;
	pinfo->off = mipi_chimei_video_wxga_off;
	pinfo->config = mipi_chimei_video_wxga_config;
	pinfo->early_config = mipi_chimei_video_wxga_early_config;

	return;
}
static zio_t *
vdev_queue_io_to_issue(vdev_queue_t *vq, uint64_t pending_limit)
{
	zio_t *fio, *lio, *aio, *dio;
	avl_tree_t *tree;
	uint64_t size;

	ASSERT(MUTEX_HELD(&vq->vq_lock));

	if (avl_numnodes(&vq->vq_pending_tree) >= pending_limit ||
	    avl_numnodes(&vq->vq_deadline_tree) == 0)
		return (NULL);

	fio = lio = avl_first(&vq->vq_deadline_tree);

	tree = fio->io_vdev_tree;
	size = fio->io_size;

	while ((dio = AVL_PREV(tree, fio)) != NULL && IS_ADJACENT(dio, fio) &&
	    size + dio->io_size <= zfs_vdev_aggregation_limit) {
		dio->io_delegate_next = fio;
		fio = dio;
		size += dio->io_size;
	}

	while ((dio = AVL_NEXT(tree, lio)) != NULL && IS_ADJACENT(lio, dio) &&
	    size + dio->io_size <= zfs_vdev_aggregation_limit) {
		lio->io_delegate_next = dio;
		lio = dio;
		size += dio->io_size;
	}

	if (fio != lio) {
		char *buf = zio_buf_alloc(size);
		uint64_t offset = 0;
		int nagg = 0;

		ASSERT(size <= zfs_vdev_aggregation_limit);

		aio = zio_vdev_child_io(fio, NULL, fio->io_vd,
		    fio->io_offset, buf, size, fio->io_type,
		    ZIO_PRIORITY_NOW, ZIO_FLAG_DONT_QUEUE |
		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_PROPAGATE |
		    ZIO_FLAG_NOBOOKMARK,
		    vdev_queue_agg_io_done, NULL);

		aio->io_delegate_list = fio;

		for (dio = fio; dio != NULL; dio = dio->io_delegate_next) {
			ASSERT(dio->io_type == aio->io_type);
			ASSERT(dio->io_vdev_tree == tree);
			if (dio->io_type == ZIO_TYPE_WRITE)
				bcopy(dio->io_data, buf + offset, dio->io_size);
			offset += dio->io_size;
			vdev_queue_io_remove(vq, dio);
			zio_vdev_io_bypass(dio);
			nagg++;
		}

		ASSERT(offset == size);

		dprintf("%5s  T=%llu  off=%8llx  agg=%3d  "
		    "old=%5llx  new=%5llx\n",
		    zio_type_name[fio->io_type],
		    fio->io_deadline, fio->io_offset, nagg, fio->io_size, size);

		avl_add(&vq->vq_pending_tree, aio);

		return (aio);
	}

	ASSERT(fio->io_vdev_tree == tree);
	vdev_queue_io_remove(vq, fio);

	avl_add(&vq->vq_pending_tree, fio);

	return (fio);
}
BOOL write_to_emmc(u8* data, u32 length)
{
	u64 paritition_size = 0;
	u64 size_wrote = 0;
	int next_flip = 0;
	u32 index;
	u32 pre_chksum = 0;
	u32 post_chksum = 0;
	int r;

	if(sto_info.first_run)
	{
		r = get_partition_name(data, length, sto_info.partition_name);
		if(r < 0)
		{
			display_info("\nASSERT!! get_partition_name() Fail");
			return FALSE;
		}
		if(!strncmp(sto_info.partition_name, "boot", 8))
		{
			ctx.boot_info.is_boot_image = TRUE;
			ctx.boot_info.offset = 0;
		}
		index = partition_get_index(sto_info.partition_name);
		if(index == -1)
		{
			display_info("\nASSERT!! Brick phone??");
			return FALSE;
		}

		if(!is_support_flash(index))
		{
			display_info(sto_info.partition_name);
			display_info("\nASSERT!! Dont support system??");
			return FALSE;
		}

		paritition_size = partition_get_size(index);
		dprintf(DBG_LV, "[index:%d]-[partitionSize:%lld]-[downSize:%lld]\n", index, paritition_size, sto_info.to_write_data_len);

		if (ROUND_TO_PAGE(sto_info.to_write_data_len,511) > paritition_size)
		{
			display_info("\nsize too large, space small.");
			dprintf(DBG_LV, "size too large, space small.");
			return FALSE;
		}

		sto_info.image_base_addr = partition_get_offset(index);
		sto_info.unsparse_status.image_base_addr = sto_info.image_base_addr;
		sto_info.is_sparse_image = is_sparse_image(data, length);
		sto_info.first_run = 0;
	}

	//boot image do not need write to image at this function. it is in flash function.
	if(ctx.boot_info.is_boot_image)
	{
		dprintf(DBG_LV, "boot img: len: %d\n", length);
		dprintf(DBG_LV, "data: %08X\n", data);
		dprintf(DBG_LV, "ctx.boot_info.boot_image_address: %08X, ctx.boot_info.offset %u, \n", ctx.boot_info.boot_image_address , ctx.boot_info.offset);

		memcpy(ctx.boot_info.boot_image_address + ctx.boot_info.offset, data, length);
		ctx.boot_info.offset += length;
		return TRUE;
	}

	if(sto_info.is_sparse_image)
	{
		next_flip = cache_shift(ctx.flipIdxR);

		sto_info.unsparse_status.buf = data;
		sto_info.unsparse_status.size = length;
		mmc_write_sparse_data(&sto_info.unsparse_status);

		if(sto_info.unsparse_status.handle_status == S_DA_SDMMC_SPARSE_INCOMPLETE)
		{
			ctx.dual_cache[next_flip].padding_length = sto_info.unsparse_status.size;
			memcpy(ctx.dual_cache[next_flip].padding_buf +(CACHE_PADDING_SIZE-sto_info.unsparse_status.size)
				, sto_info.unsparse_status.buf
				, sto_info.unsparse_status.size);
		}
		else if (sto_info.unsparse_status.handle_status== S_DONE)
		{
			ctx.dual_cache[next_flip].padding_length = 0;
		}
		else
		{
			//some error
			dprintf(DBG_LV, "write_to_emmc() Failed. handle_status(%d)\n", sto_info.unsparse_status.handle_status);
			display_info("\nError in write sparse image in EMMC.");
			return FALSE;
		}
	}
	else
	{
		size_wrote = emmc_write(sto_info.image_base_addr+sto_info.bulk_image_offset , (void*)data, length);
		if (size_wrote  != length)
		{
			dprintf(DBG_LV, "write_to_emmc() Failed. act(%lld) != want(%lld)\n", size_wrote, length);
			display_info("\nError in write bulk in EMMC.");
			return FALSE;
		}
		if(sto_info.checksum_enabled)
		{
			pre_chksum = calc_checksum(data, (u32)length);
			if(length != emmc_read(sto_info.image_base_addr+sto_info.bulk_image_offset, data,  length))
			{
				dprintf(DBG_LV, "emmc_read() Failed.\n");
				display_info("\nError in Read bulk EMMC.");
				return FALSE;
			}

			post_chksum = calc_checksum(data, (u32)length);

			if(post_chksum != pre_chksum)
			{
				dprintf(DBG_LV, "write_to_emmc() Failed. checksum error\n");
				display_info("\nWrite bulk in EMMC. Checksum Error");
				return FALSE;
			}
		}

		sto_info.bulk_image_offset += size_wrote;
	}
	return TRUE;
}
Example #4
0
uint16_t scan_dir(char* path, char mkdb, uint32_t this_dir_tgt) {
	DIR dir;
	FILINFO fno;
	FRESULT res;
	uint8_t len;
	unsigned char* fn;
	static unsigned char depth = 0;
	static uint16_t crc;
	static uint32_t db_tgt;
	static uint32_t next_subdir_tgt;
	static uint32_t parent_tgt;
	static uint32_t dir_end = 0;
	static uint8_t was_empty = 0;
	uint32_t dir_tgt;
	uint16_t numentries;
	uint32_t dirsize;
	uint8_t pass = 0;

	dir_tgt = this_dir_tgt;
	if(depth==0) {
		crc = 0;
		db_tgt = SRAM_DB_ADDR+0x10;
		dir_tgt = SRAM_DIR_ADDR;
		next_subdir_tgt = SRAM_DIR_ADDR;
		this_dir_tgt = SRAM_DIR_ADDR;
		parent_tgt = 0;
		dprintf("root dir @%lx\n", dir_tgt);
	}	
	
	fno.lfn = file_lfn;
	numentries=0;
	for(pass = 0; pass < 2; pass++) {
		if(pass) {
			dirsize = 4*(numentries);
//			dir_tgt_next = dir_tgt + dirsize + 4; // number of entries + end marker
			next_subdir_tgt += dirsize + 4;
			if(parent_tgt) next_subdir_tgt += 4;
			if(next_subdir_tgt > dir_end) {
				dir_end = next_subdir_tgt;
			}
			dprintf("path=%s depth=%d ptr=%lx entries=%d parent=%lx next subdir @%lx\n", path, depth, db_tgt, numentries, parent_tgt, next_subdir_tgt /*dir_tgt_next*/);
//			_delay_ms(50);
			if(mkdb) {
				dprintf("d=%d Saving %lX to Address %lX  [end]\n", depth, 0L, next_subdir_tgt - 4);
//				_delay_ms(50);	
				sram_writelong(0L, next_subdir_tgt - 4);
			}
		}
		res = f_opendir(&dir, (unsigned char*)path);
		if (res == FR_OK) {
			if(pass && parent_tgt && mkdb) {
				// write backlink to parent dir
				// switch to next bank if record does not fit in current bank
				if((db_tgt&0xffff) > ((0x10000-(sizeof(next_subdir_tgt)+sizeof(len)+4))&0xffff)) {
					dprintf("switch! old=%lx ", db_tgt);
					db_tgt &= 0xffff0000;
					db_tgt += 0x00010000;
					dprintf("new=%lx\n", db_tgt);
				}
				sram_writelong((parent_tgt-SRAM_MENU_ADDR), db_tgt);
				sram_writebyte(0, db_tgt+sizeof(next_subdir_tgt));
				sram_writeblock("../\0", db_tgt+sizeof(next_subdir_tgt)+sizeof(len), 4);
				sram_writelong((db_tgt-SRAM_MENU_ADDR)|((uint32_t)0x80<<24), dir_tgt);
				db_tgt += sizeof(next_subdir_tgt)+sizeof(len)+4;
				dir_tgt += 4;
			}
			len = strlen((char*)path);
			for (;;) {
				toggle_busy_led();
				res = f_readdir(&dir, &fno);
				if (res != FR_OK || fno.fname[0] == 0) {
					if(pass) {
						if(!numentries) was_empty=1;
					}
					break;
				}
				fn = *fno.lfn ? fno.lfn : fno.fname;
	//			dprintf("%s\n", fn);
	//			_delay_ms(100);
				if (*fn == '.') continue;
				if (fno.fattrib & AM_DIR) {
					numentries++;
					if(pass) {
						path[len]='/';
						strncpy(path+len+1, (char*)fn, sizeof(fs_path)-len);
						depth++;
						if(mkdb) {
							uint16_t pathlen = strlen(path);
							// write element pointer to current dir structure
							dprintf("d=%d Saving %lX to Address %lX  [dir]\n", depth, db_tgt, dir_tgt);
//							_delay_ms(50);
							sram_writelong((db_tgt-SRAM_MENU_ADDR)|((uint32_t)0x80<<24), dir_tgt);
//							sram_writeblock((uint8_t*)&db_tgt, dir_tgt_save, sizeof(dir_tgt_save));

							// save element:
							//  - path name
							//  - pointer to sub dir structure
							if((db_tgt&0xffff) > ((0x10000-(sizeof(next_subdir_tgt) + sizeof(len) + pathlen + 2))&0xffff)) {
								dprintf("switch! old=%lx ", db_tgt);
								db_tgt &= 0xffff0000;
								db_tgt += 0x00010000;
								dprintf("new=%lx\n", db_tgt);
							}
							dprintf("    Saving dir descriptor to %lX, tgt=%lX, path=%s\n", db_tgt, next_subdir_tgt, path);
//							_delay_ms(100);
							sram_writelong((next_subdir_tgt-SRAM_MENU_ADDR), db_tgt);
							sram_writebyte(len+1, db_tgt+sizeof(next_subdir_tgt));
							sram_writeblock(path, db_tgt+sizeof(next_subdir_tgt)+sizeof(len), pathlen);
							sram_writeblock("/\0", db_tgt + sizeof(next_subdir_tgt) + sizeof(len) + pathlen, 2);
//							sram_writeblock((uint8_t*)&dir_tgt, db_tgt+256, sizeof(dir_tgt));
							db_tgt += sizeof(next_subdir_tgt) + sizeof(len) + pathlen + 2;
						}
						parent_tgt = this_dir_tgt;
						scan_dir(path, mkdb, next_subdir_tgt);
						dir_tgt += 4;
//						if(was_empty)dir_tgt_next += 4;
						was_empty = 0;
						depth--;
						path[len]=0;
					}
				} else {
					SNES_FTYPE type = determine_filetype((char*)fn);
					if(type != TYPE_UNKNOWN) {
						numentries++;
						if(pass) {
							if(mkdb) {
								snes_romprops_t romprops;
								path[len]='/';
								strncpy(path+len+1, (char*)fn, sizeof(fs_path)-len);
								uint16_t pathlen = strlen(path);
								switch(type) {
									case TYPE_SMC:
// XXX										file_open_by_filinfo(&fno);
// XXX										if(file_res){
// XXX											dprintf("ZOMG NOOOO %d\n", file_res);
// XXX											_delay_ms(30);
// XXX										}
// XXX										smc_id(&romprops);
// XXX										file_close();
		//								_delay_ms(30);
										// write element pointer to current dir structure
//										dprintf("d=%d Saving %lX to Address %lX  [file]\n", depth, db_tgt, dir_tgt);
//										_delay_ms(50);
										if((db_tgt&0xffff) > ((0x10000-(sizeof(romprops) + sizeof(len) + pathlen + 1))&0xffff)) {
											dprintf("switch! old=%lx ", db_tgt);
											db_tgt &= 0xffff0000;
											db_tgt += 0x00010000;
											dprintf("new=%lx\n", db_tgt);
										}
										sram_writelong((db_tgt-SRAM_MENU_ADDR), dir_tgt);
//										sram_writeblock((uint8_t*)&db_tgt, dir_tgt, sizeof(db_tgt));
										dir_tgt += 4;
										// save element:
										//  - SNES header information
										//  - file name
										sram_writeblock((uint8_t*)&romprops, db_tgt, sizeof(romprops));
										sram_writebyte(len+1, db_tgt + sizeof(romprops));
										sram_writeblock(path, db_tgt + sizeof(romprops) + sizeof(len), pathlen + 1);
										db_tgt += sizeof(romprops) + sizeof(len) + pathlen + 1;
										break;
									case TYPE_UNKNOWN:
									default:
										break;
								}
								path[len]=0;
		//						dprintf("%s ", path);
		//						_delay_ms(30);
							}
						} else {
							unsigned char* sfn = fno.fname;
							while(*sfn != 0) {
								crc += crc16_update(crc, sfn++, 1);
							}
						}
					}
	//					dprintf("%s/%s\n", path, fn);
	//					_delay_ms(50);
				}
			}
		} else uart_putc(0x30+res);
	}
//	dprintf("%x\n", crc);
//	_delay_ms(50);
	sram_writelong(db_tgt, SRAM_DB_ADDR+4);
	sram_writelong(dir_end, SRAM_DB_ADDR+8);
	return crc;
}
Example #5
0
VOID
ConfigInfoDebugDump( )

/*++

Routine Description:


Arguments:


Return Value:


--*/

{
   RtlEnterCriticalSection(&ConfigInfoLock);

   dprintf(TEXT("License Logging Service - Version: 0x%lX\n"), ConfigInfo.Version);
   dprintf(TEXT("   Started: %u-%u-%u @ %u:%u:%u\n"),
               (UINT) ConfigInfo.Started.wDay,
               (UINT) ConfigInfo.Started.wMonth,
               (UINT) ConfigInfo.Started.wYear,
               (UINT) ConfigInfo.Started.wHour,
               (UINT) ConfigInfo.Started.wMinute,
               (UINT) ConfigInfo.Started.wSecond );

   dprintf(TEXT("   Replication\n"));
   dprintf(TEXT("   +--------------+\n"));
   if (ConfigInfo.IsMaster)
      dprintf(TEXT("      Master Server\n"));
   else
      dprintf(TEXT("      NOT Master Server\n"));

   if (ConfigInfo.Replicate)
      dprintf(TEXT("      Replicates\n"));
   else
      dprintf(TEXT("      Does not Replicate\n"));

   if (ConfigInfo.IsReplicating)
      dprintf(TEXT("      Currently Replicating\n"));
   else
      dprintf(TEXT("      NOT Currently Replicating\n"));

   dprintf(TEXT("      Replicates To: %s\n"), ConfigInfo.ReplicateTo);
   dprintf(TEXT("      Enterprise Server: %s\n"), ConfigInfo.EnterpriseServer);

   if (ConfigInfo.ReplicationType == REPLICATE_DELTA)
      dprintf(TEXT("      Replicate Every: %lu Seconds\n"), ConfigInfo.ReplicationTime );
   else
      dprintf(TEXT("      Replicate @: %lu\n"), ConfigInfo.ReplicationTime );

   dprintf(TEXT("\n      Last Replicated: %u-%u-%u @ %u:%u:%u\n\n"),
               (UINT) ConfigInfo.LastReplicated.wDay,
               (UINT) ConfigInfo.LastReplicated.wMonth,
               (UINT) ConfigInfo.LastReplicated.wYear,
               (UINT) ConfigInfo.LastReplicated.wHour,
               (UINT) ConfigInfo.LastReplicated.wMinute,
               (UINT) ConfigInfo.LastReplicated.wSecond );

   dprintf(TEXT("      Number Servers Currently Replicating: %lu\n"), ConfigInfo.NumReplicating);

   dprintf(TEXT("      Current Backoff Time Delta: %lu\n"), ConfigInfo.BackoffTime);

   dprintf(TEXT("      Current Replication Speed: %lu\n"), ConfigInfo.ReplicationSpeed);

   RtlLeaveCriticalSection(&ConfigInfoLock);

} // ConfigInfoDebugDump
Example #6
0
/**
 * giop_recv_buffer_handle_fragmented:
 * @buf: pointer to recv buffer pointer
 * @cnx: current connection.
 * 
 *   This will append @buf to the right list of buffers
 * on the connection, forming a complete message, and
 * re-write *@buf to the first buffer in the chain.
 * 
 * Return value: TRUE on error else FALSE
 **/
static gboolean
giop_recv_buffer_handle_fragmented (GIOPRecvBuffer **ret_buf,
				    GIOPConnection  *cnx)
{
	GList *list;
	gboolean giop_1_1;
	gboolean error = FALSE;
	CORBA_long message_id;
	GIOPRecvBuffer *buf = *ret_buf;

	giop_1_1 = (buf->giop_version == GIOP_1_1);

	switch (buf->msg.header.message_type) {
	case GIOP_REPLY:
	case GIOP_LOCATEREPLY:
	case GIOP_REQUEST:
	case GIOP_LOCATEREQUEST:
		message_id = giop_recv_buffer_get_request_id (buf);
		break;
	case GIOP_FRAGMENT:
		if (!giop_1_1) {
			buf->cur = ALIGN_ADDRESS (buf->cur, 4);

			if ((buf->cur + 4) > buf->end) {
				dprintf (ERRORS, "incoming bogus fragment length");
				return TRUE;
			}
			if (giop_msg_conversion_needed (buf))
				message_id = GUINT32_SWAP_LE_BE (*((guint32 *)buf->cur));
			else
				message_id = *(guint32 *) buf->cur;
			buf->cur += 4;
		} else
			message_id = 0;
		break;
	default:
		dprintf (ERRORS, "Bogus fragment packet type %d",
			 buf->msg.header.message_type);
		return TRUE;
	}

	if (!(list = giop_connection_get_frag (cnx, message_id, giop_1_1))) {
		if (!MORE_FRAGMENTS_FOLLOW (buf))
			return TRUE;

		giop_connection_add_frag (cnx, buf);

	} else {
		GIOPRecvBuffer *head = list->data;

		*ret_buf = head;
		g_assert (head->msg.header.message_type != GIOP_FRAGMENT);

		/* track total length on head node */
		/* (end - cur) to account for fragment (msg id) header */
		head->msg.header.message_size += (buf->end - buf->cur);

		list = g_list_append (list, buf);

		if (!cnx->parent.is_auth &&
		    buf->msg.header.message_size > giop_initial_msg_size_limit) {
			dprintf (ERRORS, "Message exceeded initial size limit\n");
			error = TRUE;
			giop_connection_remove_frag (cnx, list);
		}
			
		if (!MORE_FRAGMENTS_FOLLOW (buf)) {
			g_assert (buf->msg.header.message_type == GIOP_FRAGMENT);

			/* concat all fragments - re-write & continue */
			error = concat_frags (list);

			giop_connection_remove_frag (cnx, list);
		}
	}

	return error;
}
int matlab_csv_serial_thread_main(int argc, char *argv[])
{

	if (argc < 2) {
		errx(1, "need a serial port name as argument");
	}

	const char *uart_name = argv[1];

	warnx("opening port %s", uart_name);

	int serial_fd = open(uart_name, O_RDWR | O_NOCTTY);

	unsigned speed = 921600;

	if (serial_fd < 0) {
		err(1, "failed to open port: %s", uart_name);
	}

	/* Try to set baud rate */
	struct termios uart_config;
	int termios_state;

	/* Back up the original uart configuration to restore it after exit */
	if ((termios_state = tcgetattr(serial_fd, &uart_config)) < 0) {
		warnx("ERR GET CONF %s: %d\n", uart_name, termios_state);
		close(serial_fd);
		return -1;
	}

	/* Clear ONLCR flag (which appends a CR for every LF) */
	uart_config.c_oflag &= ~ONLCR;

	/* USB serial is indicated by /dev/ttyACM0*/
	if (strcmp(uart_name, "/dev/ttyACM0") != OK && strcmp(uart_name, "/dev/ttyACM1") != OK) {

		/* Set baud rate */
		if (cfsetispeed(&uart_config, speed) < 0 || cfsetospeed(&uart_config, speed) < 0) {
			warnx("ERR SET BAUD %s: %d\n", uart_name, termios_state);
			close(serial_fd);
			return -1;
		}

	}

	if ((termios_state = tcsetattr(serial_fd, TCSANOW, &uart_config)) < 0) {
		warnx("ERR SET CONF %s\n", uart_name);
		close(serial_fd);
		return -1;
	}

	/* subscribe to vehicle status, attitude, sensors and flow*/
	struct accel_report accel0;
	struct accel_report accel1;
	struct gyro_report gyro0;
	struct gyro_report gyro1;

	/* subscribe to parameter changes */
	int accel0_sub = orb_subscribe_multi(ORB_ID(sensor_accel), 0);
	int accel1_sub = orb_subscribe_multi(ORB_ID(sensor_accel), 1);
	int gyro0_sub = orb_subscribe_multi(ORB_ID(sensor_gyro), 0);
	int gyro1_sub = orb_subscribe_multi(ORB_ID(sensor_gyro), 1);

	thread_running = true;

	while (!thread_should_exit) {

		/*This runs at the rate of the sensors */
		struct pollfd fds[] = {
			{ .fd = accel0_sub, .events = POLLIN }
		};

		/* wait for a sensor update, check for exit condition every 500 ms */
		int ret = poll(fds, sizeof(fds) / sizeof(fds[0]), 500);

		if (ret < 0) {
			/* poll error, ignore */

		} else if (ret == 0) {
			/* no return value, ignore */
			warnx("no sensor data");

		} else {

			/* accel0 update available? */
			if (fds[0].revents & POLLIN) {
				orb_copy(ORB_ID(sensor_accel), accel0_sub, &accel0);
				orb_copy(ORB_ID(sensor_accel), accel1_sub, &accel1);
				orb_copy(ORB_ID(sensor_gyro), gyro0_sub, &gyro0);
				orb_copy(ORB_ID(sensor_gyro), gyro1_sub, &gyro1);

				// write out on accel 0, but collect for all other sensors as they have updates
				dprintf(serial_fd, "%llu,%d,%d,%d,%d,%d,%d\n", accel0.timestamp, (int)accel0.x_raw, (int)accel0.y_raw,
					(int)accel0.z_raw,
					(int)accel1.x_raw, (int)accel1.y_raw, (int)accel1.z_raw);
			}

		}
	}
Example #8
0
void sendHTMLPage(int fd, char* status,char* headers, char* content) {
	dprintf(fd,"HTTP/1.1 %s \r\n%sContent-Type: text/html\r\nContent-Length: %zu\r\nConnection:close\r\n\r\n%s", status,headers, strlen(content),content);
}
Example #9
0
void sendSimpleHTMLPage(int fd, char* status, char* content) {
	dprintf(fd,"HTTP/1.1 %s \r\nContent-Length: %zu\r\nConnection:close\r\n\r\n%s", status, strlen(content),content);
}
Example #10
0
static int32
sis900_txInterrupt(struct sis_info *info)
{
	int16 releaseTxSem = 0;
	uint32 status;
	int16 limit;

	acquire_spinlock(&info->txSpinlock);

	HACK(spin(10000));

	for (limit = info->txSent; limit > 0; limit--) {
		status = info->txDescriptor[info->txInterruptIndex].status;

//dprintf("txIntr: %d: mem = %lx : hardware = %lx\n",info->txInterruptIndex,
//		physicalAddress(&info->txDescriptor[info->txInterruptIndex],sizeof(struct buffer_desc)),
//		read32(info->registers + SiS900_MAC_Tx_DESCR));

		/* Does the device generate extra interrupts? */
		if (status & SiS900_DESCR_OWN) {
			struct buffer_desc *descriptor = (void *)read32(info->registers + SiS900_MAC_Tx_DESCR);
			int16 that;
			for (that = 0;
				that < NUM_Tx_DESCR && (void *)physicalAddress(&info->txDescriptor[that],
					sizeof(struct buffer_desc)) != descriptor; that++) {
			}
			if (that == NUM_Tx_DESCR)
				that = 0;

//dprintf("tx busy %d: %lx (hardware status %d = %lx)!\n",info->txInterruptIndex,status,that,info->txDescriptor[that].status);
//			if (limit == info->txSent)
//			{
//dprintf("oh no!\n");
//				limit++;
//				continue;
//			}
			break;
		}

		if (status & (SiS900_DESCR_Tx_ABORT | SiS900_DESCR_Tx_UNDERRUN
				| SiS900_DESCR_Tx_OOW_COLLISION)) {
			dprintf("tx error: %lx\n", status);
		} else
			info->txDescriptor[info->txInterruptIndex].status = 0;

		releaseTxSem++;	/* this many buffers are free */
		info->txInterruptIndex = (info->txInterruptIndex + 1) & NUM_Tx_MASK;
		info->txSent--;

		if (info->txSent < 0 || info->txSent > NUM_Tx_DESCR)
			dprintf("ERROR interrupt: txSent = %d\n", info->txSent);
	}
	release_spinlock(&info->txSpinlock);

	if (releaseTxSem) {
		release_sem_etc(info->txSem, releaseTxSem, B_DO_NOT_RESCHEDULE);
		return B_INVOKE_SCHEDULER;
	}

	return B_HANDLED_INTERRUPT;
}
Example #11
0
status_t
sis900_initPHYs(struct sis_info *info)
{
	uint16 phy;

	// search for total of 32 possible MII PHY addresses
	for (phy = 0; phy < 32; phy++) {
		struct mii_phy *mii;
		uint16 status;
		int32 i;

		status = mdio_statusFromPHY(info, phy);
		if (status == 0xffff || status == 0x0000)
			// this MII is not accessable
			continue;

		mii = (struct mii_phy *)malloc(sizeof(struct mii_phy));
		if (mii == NULL)
			return B_NO_MEMORY;

		mii->address = phy;
		mii->id0 = mdio_readFromPHY(info, phy, MII_PHY_ID0);
		mii->id1 = mdio_readFromPHY(info, phy, MII_PHY_ID1);
		mii->types = MII_HOME;
		mii->next = info->firstPHY;
		info->firstPHY = mii;

		for (i = 0; gMIIChips[i].name; i++) {
			if (gMIIChips[i].id0 != mii->id0
				|| gMIIChips[i].id1 != (mii->id1 & 0xfff0))
				continue;

			dprintf("Found MII PHY: %s\n", gMIIChips[i].name);

			mii->types = gMIIChips[i].types;
			break;
		}
		if (gMIIChips[i].name == NULL)
			dprintf("Unknown MII PHY transceiver: id = (%x, %x).\n", mii->id0, mii->id1);
	}

	if (info->firstPHY == NULL) {
		dprintf("No MII PHY transceiver found!\n");
		return B_ENTRY_NOT_FOUND;
	}
	
	sis900_selectPHY(info);

	// if the internal PHY is selected, reset it
	if (info->currentPHY->id0 == PHY_ID0_SiS900_INTERNAL
		&& (info->currentPHY->id1 & 0xfff0) == PHY_ID1_SiS900_INTERNAL) {
		if (sis900_resetPHY(info) & MII_STATUS_LINK) {
			uint16 poll = MII_STATUS_LINK;
			while (poll) {
				poll ^= mdio_read(info, MII_STATUS) & poll;
			}
		}
	}

	// workaround for ICS1893 PHY
	if (info->currentPHY->id0 == PHY_ID0_ICS_1893
		&& (info->currentPHY->id1 & 0xfff0) == PHY_ID1_ICS_1893)
		mdio_write(info, 0x0018, 0xD200);

	// SiS 630E has some bugs on default value of PHY registers
	if (info->pciInfo->revision == SiS900_REVISION_SiS630E) {
		mdio_write(info, MII_AUTONEG_ADV, 0x05e1);
		mdio_write(info, MII_CONFIG1, 0x22);
		mdio_write(info, MII_CONFIG2, 0xff00);
		mdio_write(info, MII_MASK, 0xffc0);
	}

	info->link = mdio_status(info) & MII_STATUS_LINK;

	return B_OK;
}
Example #12
0
/* decompress gzip file "in_buf", return 0 if decompressed successful,
 * return -1 if decompressed failed.
 * in_buf - input gzip file
 * in_len - input the length file
 * out_buf - output the decompressed data
 * out_buf_len - the available length of out_buf
 * pos - position of the end of gzip file
 * out_len - the length of decompressed data
 */
int decompress(unsigned char *in_buf, unsigned int in_len,
		       unsigned char *out_buf,
		       unsigned int out_buf_len,
		       unsigned int *pos,
		       unsigned int *out_len) {
	struct z_stream_s *stream;
	int rc = -1;
	int i;

	if (in_len < GZIP_HEADER_LEN) {
		dprintf(INFO, "the input data is not a gzip package.\n");
		return rc;
	}
	if (out_buf_len < in_len) {
		dprintf(INFO, "the avaiable length of out_buf is not enough.\n");
		return rc;
	}

	stream = malloc(sizeof(*stream));
	if (stream == NULL) {
		dprintf(INFO, "allocating z_stream failed.\n");
		return rc;
	}

	stream->zalloc = zlib_alloc;
	stream->zfree = zlib_free;
	stream->next_out = out_buf;
	stream->avail_out = out_buf_len;

	/* skip over gzip header */
	stream->next_in = in_buf + GZIP_HEADER_LEN;
	stream->avail_in = out_buf_len - GZIP_HEADER_LEN;
	/* skip over asciz filename */
	if (in_buf[3] & 0x8) {
		for (i = 0; i < GZIP_FILENAME_LIMIT && *stream->next_in++; i++) {
			if (stream->avail_in == 0) {
				dprintf(INFO, "header error\n");
				goto gunzip_end;
			}
			--stream->avail_in;
		}
	}

	rc = inflateInit2(stream, -MAX_WBITS);
	if (rc != Z_OK) {
		dprintf(INFO, "inflateInit2 failed!\n");
		goto gunzip_end;
	}

	rc = inflate(stream, 0);
	/* Z_STREAM_END is "we unpacked it all" */
	if (rc == Z_STREAM_END) {
		rc = 0;
	} else if (rc != Z_OK) {
		dprintf(INFO, "uncompression error \n");
		rc = -1;
	}

	inflateEnd(stream);
	if (pos)
		/* alculation the length of the compressed package */
		*pos = stream->next_in - in_buf + 8;

	if (out_len)
		*out_len = stream->total_out;

gunzip_end:
	free(stream);
	return rc; /* returns 0 if decompressed successful */
}
Example #13
0
void kim_os_debug_print (kim_string in_string)
{
    dprintf (in_string);
}
Example #14
0
void Nes_Rewinder::enter_reverse()
{
	reversed_time = recorder::tell() - 1;
	
	reverse_pivot = reversed_time % frames_size;
	frame_count_t first_frame = reversed_time - reverse_pivot;
	if ( buffer_scrambled )
	{
		// buffer hasn't been filled with a clean second of frames since last seek
		
		dprintf( "Refilling reverse buffer, pivot: %d\n", (int) reverse_pivot );
		
		// fill beginning
		seek_clamped( first_frame );
		for ( int i = 0; i <= reverse_pivot; i++ )
			play_frame_( i );
		frames [0].fade_out = true;
		
		// fill end
		seek_clamped( first_frame - frames_size + reverse_pivot + 1 );
		for ( int i = reverse_pivot + 1; i < frames_size; i++ )
			play_frame_( i );
	}
	
	if ( reverse_pivot + 1 < frames_size )
		frames [reverse_pivot + 1].fade_out = true;
	
	reverse_unmirrored = 2; // unmirrored for first two passes, then alternating
	reverse_pivot = -reverse_pivot; // don't pivot yet
	
	seek_clamped( first_frame - frames_size );
	
	// Buffer is now filled. Current second is at beginning and previous at end,
	// and in this example reversed_time is 24 and reverse_pivot is 4:
	// 20 21 22 23 24 25 16 17 18 19
	
	// As fragment of current second is played backwards, it will be replaced with
	// beginning of previous second:
	
	//  <---------------
	// 20 21 22 23 24 25 16 17 18 19    frame 25
	// 20 21 22 23 24 10 16 17 18 19    frame 24
	// 20 21 22 23 11 10 16 17 18 19    frame 23
	// 20 21 22 12 11 10 16 17 18 19    frame 22
	// 20 21 13 12 11 10 16 17 18 19    frame 21
	// 20 14 13 12 11 10 16 17 18 19    frame 20
	// 15 14 13 12 11 10 16 17 18 19    frame 19
	// Then filling will keep replacing buffer contents in a converging fashion:
	//                    <---------
	// 15 14 13 12 11 10 16 17 18  0    frame 19
	// 15 14 13 12 11 10 16 17  1  0    frame 18
	// 15 14 13 12 11 10 16  2  1  0    frame 17
	// 15 14 13 12 11 10  3  2  1  0    frame 16
	//  -------------->
	//  4 14 13 12 11 10  3  2  1  0    frame 15
	//  4  5 13 12 11 10  3  2  1  0    frame 14
	//  4  5  6 12 11 10  3  2  1  0    frame 13
	//  4  5  6  7 11 10  3  2  1  0    frame 12
	//  4  5  6  7  8 10  3  2  1  0    frame 11
	//  4  5  6  7  8  9  3  2  1  0    frame 10
	//  <---------------
	// etc.
}
Example #15
0
static gboolean
handle_reply (GIOPRecvBuffer *buf)
{
	GList                 *l;
	gboolean               error;
	GIOPMessageQueueEntry *ent;
	CORBA_unsigned_long    request_id;

	request_id = giop_recv_buffer_get_request_id (buf);

	error = FALSE;

	LINK_MUTEX_LOCK (giop_queued_messages_lock);

	for (l = giop_queued_messages; l; l = l->next) {
		ent = l->data;

		if (ent->request_id == request_id &&
		    ent->msg_type == buf->msg.header.message_type)
			break;
	}

	ent = l ? l->data : NULL;

	if (!ent) {
		if (giop_recv_buffer_reply_status (buf) ==
		    CORBA_SYSTEM_EXCEPTION) {
			/*
			 * Unexpected - but sometimes a oneway
			 * method invocation on a de-activated
			 * object results in us getting a bogus
			 * system exception in reply.
			 */
 		} else {
#ifdef G_ENABLE_DEBUG
			if (giop_debug_hook_unexpected_reply)
				giop_debug_hook_unexpected_reply (buf);
			else
				dprintf (ERRORS, "We received an unexpected reply\n");
#endif /* G_ENABLE_DEBUG */
			error = TRUE;
		}

	} else if (ent->cnx != buf->connection) {
#ifdef G_ENABLE_DEBUG
		if (giop_debug_hook_spoofed_reply)
			giop_debug_hook_spoofed_reply (buf, ent);
#endif
		dprintf (ERRORS, "We received a bogus reply\n");

		error = TRUE;

	} else {
#ifdef DEBUG
		g_warning ("Pop XX:%p:%p - %d",
			   ent, ent->async_cb,
			   g_list_length (giop_queued_messages));
#endif
		giop_queued_messages = g_list_delete_link
			(giop_queued_messages, l);
	}

	LINK_MUTEX_UNLOCK (giop_queued_messages_lock);

	if (ent && !error) {
		gboolean async = FALSE;

		ent_lock (ent);
		ent->buffer = buf;

		if (giop_thread_io () && !ent->async_cb)
			giop_incoming_signal_T (ent->src_thread,
						GIOP_REPLY);

		else if (ent->async_cb)
			async = TRUE;

		ent_unlock (ent);

		if (async)
			giop_invoke_async (ent);

		buf = NULL;
	}
	
	giop_recv_buffer_unuse (buf);

	return error;
}
Example #16
0
    SEE ALSO
	utility.library/ToUpper(), locale.library/ConvToUpper().

    INTERNALS

    HISTORY

*****************************************************************************/
{
    AROS_LIBFUNC_INIT

    ULONG retval;
    
    REPLACEMENT_LOCK;

    DEBUG_CONVTOUPPER(dprintf("locToUpper: char 0x%lx\n",
			character));

    DEBUG_CONVTOUPPER(dprintf("locToUpper: locale 0x%lx\n",
			(struct Locale *)IntLB(LocaleBase)->lb_CurrentLocale));

    retval = ConvToUpper((struct Locale *)IntLB(LocaleBase)->lb_CurrentLocale, character);

    DEBUG_CONVTOUPPER(dprintf("locToUpperr: retval 0x%lx\n",
			retval));
    REPLACEMENT_UNLOCK;
    
    return retval;
    
    AROS_LIBFUNC_EXIT
    
} /* LocToUpper */
Example #17
0
/*
 * FIXME: we should definately handle things more asynchronously,
 * perhaps even at the expense of having to go to the GSource
 * twice in order to get fresh input (?)
 * or should we poll ourselves on the source to see what's up?
 *
 * The whole locking concept here looks broken to me,
 * especially since 'read' can flag the connection disconnected
 * giving a nice deadlock.
 */
gboolean
giop_connection_handle_input (LinkConnection *lcnx)
{
	GIOPRecvBuffer *buf;
	GIOPConnection *cnx = (GIOPConnection *) lcnx;

	do {
		int n;

		if (!cnx->incoming_msg)
			cnx->incoming_msg = giop_recv_buffer_use_buf (cnx);

		buf = cnx->incoming_msg;

		n = link_connection_read (
			lcnx, buf->cur, buf->left_to_read, FALSE);

		if (n == 0) /* We'll be back */
			return TRUE;

		if (n < 0 || !buf->left_to_read) /* HUP */
			goto msg_error;

/*		fprintf (stderr, "Read %d\n", n);
		giop_dump (stderr, buf->cur, n, 0); */

		buf->left_to_read -= n;
		buf->cur += n;

		if (buf->left_to_read == 0) {

#ifdef G_ENABLE_DEBUG
			if (giop_debug_hook_incoming_mangler)
				giop_debug_hook_incoming_mangler (buf);
#endif

			switch (buf->state) {

			case GIOP_MSG_READING_HEADER:
				if (giop_recv_msg_reading_body (buf, cnx->parent.is_auth)) {
					dprintf (ERRORS, "OOB incoming msg header data\n");
					goto msg_error;
				}
				buf->state = GIOP_MSG_READING_BODY;
				break;

			case GIOP_MSG_READING_BODY: {

				dprintf (GIOP, "Incoming IIOP body:\n");

				buf->cur = buf->message_body + 12;
				if ((buf->cur + buf->msg.header.message_size) > buf->end) {
					dprintf (ERRORS, "broken incoming length data\n");
					goto msg_error;
				}
				do_giop_dump (stderr, buf->cur, buf->msg.header.message_size, 12);

				buf->state = GIOP_MSG_READY;

				if (giop_recv_buffer_demarshal (buf)) {
					dprintf (ERRORS, "broken incoming header data\n");
					goto msg_error;
				}

				if (MORE_FRAGMENTS_FOLLOW (buf)) {
					if (giop_recv_buffer_handle_fragmented (&buf, cnx))
						goto msg_error;

					else {
						cnx->incoming_msg = NULL;
						goto frag_out;
					}

				} else if (buf->msg.header.message_type == GIOP_FRAGMENT) {
					if (giop_recv_buffer_handle_fragmented (&buf, cnx))
						goto msg_error;
					/* else last fragment */
				}
				break;
			}

			case GIOP_MSG_AWAITING_FRAGMENTS:
			case GIOP_MSG_READY:
				g_assert_not_reached ();
				break;
			}
		}

	} while (cnx->incoming_msg &&
		 buf->left_to_read > 0 &&
		 buf->state != GIOP_MSG_READY);

	cnx->incoming_msg = NULL;

	switch (buf->msg.header.message_type) {
	case GIOP_REPLY:
	case GIOP_LOCATEREPLY:
		dprintf (MESSAGES, "handling reply\n");
		if (handle_reply (buf)) /* dodgy inbound data, pull the cnx */
			link_connection_state_changed (lcnx, LINK_DISCONNECTED);
		break;

	case GIOP_REQUEST:
		dprintf (MESSAGES, "handling request\n");
		ORBit_handle_request (cnx->orb_data, buf);
		break;

	case GIOP_LOCATEREQUEST:
		dprintf (MESSAGES, "handling locate request\n");
		ORBit_handle_locate_request (cnx->orb_data, buf);
		break;

	case GIOP_CANCELREQUEST:
	case GIOP_MESSAGEERROR:
		dprintf (ERRORS, "dropping an unusual & unhandled input buffer 0x%x",
			 buf->msg.header.message_type);
		giop_recv_buffer_unuse (buf);
		break;

	case GIOP_CLOSECONNECTION:
		dprintf (MESSAGES, "received close connection\n");
		giop_recv_buffer_unuse (buf);
		link_connection_state_changed (lcnx, LINK_DISCONNECTED);
		break;

	case GIOP_FRAGMENT:
		dprintf (ERRORS, "Fragment got in the wrong channel\n");
	default:
		dprintf (ERRORS, "dropping an out of bound input buffer "
			 "on the floor 0x%x\n", buf->msg.header.message_type);
		goto msg_error;
		break;
	}

 frag_out:	
	return TRUE;

 msg_error:
	cnx->incoming_msg = NULL;

	buf->msg.header.message_type = GIOP_MESSAGEERROR;
	buf->msg.header.message_size = 0;

	giop_recv_buffer_unuse (buf);

	/* Zap it for badness.
	 * XXX We should probably handle oversized
	 * messages more graciously XXX */
	link_connection_state_changed (LINK_CONNECTION (cnx),
				       LINK_DISCONNECTED);

	return TRUE;
}
Example #18
0
static void
txg_sync_thread(void *arg)
{
	dsl_pool_t *dp = arg;
	spa_t *spa = dp->dp_spa;
	tx_state_t *tx = &dp->dp_tx;
	callb_cpr_t cpr;
	uint64_t start, delta;

	txg_thread_enter(tx, &cpr);

	start = delta = 0;
	for (;;) {
		uint64_t timeout = zfs_txg_timeout * hz;
		uint64_t timer;
		uint64_t txg;

		/*
		 * We sync when we're scanning, there's someone waiting
		 * on us, or the quiesce thread has handed off a txg to
		 * us, or we have reached our timeout.
		 */
		timer = (delta >= timeout ? 0 : timeout - delta);
		while (!dsl_scan_active(dp->dp_scan) &&
		    !tx->tx_exiting && timer > 0 &&
		    tx->tx_synced_txg >= tx->tx_sync_txg_waiting &&
		    tx->tx_quiesced_txg == 0 &&
		    dp->dp_dirty_total < zfs_dirty_data_sync) {
			dprintf("waiting; tx_synced=%llu waiting=%llu dp=%p\n",
			    tx->tx_synced_txg, tx->tx_sync_txg_waiting, dp);
			txg_thread_wait(tx, &cpr, &tx->tx_sync_more_cv, timer);
			delta = ddi_get_lbolt() - start;
			timer = (delta > timeout ? 0 : timeout - delta);
		}

		/*
		 * Wait until the quiesce thread hands off a txg to us,
		 * prompting it to do so if necessary.
		 */
		while (!tx->tx_exiting && tx->tx_quiesced_txg == 0) {
			if (tx->tx_quiesce_txg_waiting < tx->tx_open_txg+1)
				tx->tx_quiesce_txg_waiting = tx->tx_open_txg+1;
			cv_broadcast(&tx->tx_quiesce_more_cv);
			txg_thread_wait(tx, &cpr, &tx->tx_quiesce_done_cv, 0);
		}

		if (tx->tx_exiting)
			txg_thread_exit(tx, &cpr, &tx->tx_sync_thread);

		/*
		 * Consume the quiesced txg which has been handed off to
		 * us.  This may cause the quiescing thread to now be
		 * able to quiesce another txg, so we must signal it.
		 */
		txg = tx->tx_quiesced_txg;
		tx->tx_quiesced_txg = 0;
		tx->tx_syncing_txg = txg;
		DTRACE_PROBE2(txg__syncing, dsl_pool_t *, dp, uint64_t, txg);
		cv_broadcast(&tx->tx_quiesce_more_cv);

		dprintf("txg=%llu quiesce_txg=%llu sync_txg=%llu\n",
		    txg, tx->tx_quiesce_txg_waiting, tx->tx_sync_txg_waiting);
		mutex_exit(&tx->tx_sync_lock);

		start = ddi_get_lbolt();
		spa_sync(spa, txg);
		delta = ddi_get_lbolt() - start;

		mutex_enter(&tx->tx_sync_lock);
		tx->tx_synced_txg = txg;
		tx->tx_syncing_txg = 0;
		DTRACE_PROBE2(txg__synced, dsl_pool_t *, dp, uint64_t, txg);
		cv_broadcast(&tx->tx_sync_done_cv);

		/*
		 * Dispatch commit callbacks to worker threads.
		 */
		txg_dispatch_callbacks(dp, txg);
	}
}
Example #19
0
int main( int argc, char *argv[] )
{
	const char *filename=0;
	char *pool=0;
	int command=-1;
	int i;
	bool with_ack = false;
	bool allow_multiple = false;
	bool many_connections = false;

	myDistro->Init( argc, argv );
	config();

	bool use_tcp = param_boolean( "UPDATE_COLLECTOR_WITH_TCP", true );

	for( i=1; i<argc; i++ ) {
		if(!strcmp(argv[i],"-help")) {
			usage(argv[0]);
			exit(0);
		} else if(!strcmp(argv[i],"-pool")) {
			i++;
			if(!argv[i]) {
				fprintf(stderr,"-pool requires an argument.\n\n");
				usage(argv[0]);
				exit(1);
			}
			pool = argv[i];
		} else if(!strncmp(argv[i],"-tcp",strlen(argv[i]))) {
			use_tcp = true;
		} else if(!strncmp(argv[i],"-udp",strlen(argv[i]))) {
			use_tcp = false;
		} else if(!strncmp(argv[i],"-multiple",strlen(argv[i]))) {
				// We don't set allow_multiple=true by default, because
				// existing users (e.g. glideinWMS) have stray blank lines
				// in the input file.
			allow_multiple = true;
		} else if(!strcmp(argv[i],"-version")) {
			version();
			exit(0);
		} else if(!strcmp(argv[i],"-debug")) {
				// dprintf to console
			dprintf_set_tool_debug("TOOL", 0);
		} else if(argv[i][0]!='-' || !strcmp(argv[i],"-")) {
			if(command==-1) {
				command = getCollectorCommandNum(argv[i]);
				if(command==-1) {
					fprintf(stderr,"Unknown command name %s\n\n",argv[i]);
					usage(argv[0]);
					exit(1);
				}
			} else if(!filename) {
				filename = argv[i];
			} else {
				fprintf(stderr,"Extra argument: %s\n\n",argv[i]);
				usage(argv[0]);
				exit(1);
			}
		} else if(!strncmp(argv[i],"-many-connections", strlen(argv[i]))) { 
			many_connections = true;
		} else {
			fprintf(stderr,"Unknown argument: %s\n\n",argv[i]);
			usage(argv[0]);
			exit(1);
		}
	}

	FILE *file;
	ClassAdList ads;
	Daemon *collector;
	Sock *sock;

	switch( command ) {
	case UPDATE_STARTD_AD_WITH_ACK:
		with_ack = true;
		break;
	}

	if( with_ack ) {
		use_tcp =  true;
	}

	if(!filename || !strcmp(filename,"-")) {
		file = stdin;
		filename = "(stdin)";
	} else {
		file = safe_fopen_wrapper_follow(filename,"r");
	}
	if(!file) {
		fprintf(stderr,"couldn't open %s: %s\n",filename,strerror(errno));
		return 1;
	}

	while(!feof(file)) {
		int eof=0,error=0,empty=0;
		char const *delim = "\n";
		if( !allow_multiple ) {
			delim = "***";
		}
		ClassAd *ad = new ClassAd(file,const_cast<char *>(delim),eof,error,empty);
		if(error) {
			fprintf(stderr,"couldn't parse ClassAd in %s\n",filename);
			delete ad;
			return 1;
		}
		if( empty ) {
			delete ad;
			break;
		}
		if( !allow_multiple && ads.Length() > 0 ) {
			fprintf(stderr,"ERROR: failed to parse '%s' as a ClassAd attribute\n",delim);
			delete ad;
			return 1;
		}
		ads.Insert(ad);
	}

	if(ads.Length() == 0) {
		fprintf(stderr,"%s is empty\n",filename);
		return 1;
	}

	CollectorList * collectors;
	if ( pool ) {
		collector = new Daemon( DT_COLLECTOR, pool, 0 );
		collectors = new CollectorList();
		collectors->append (collector);
	} else {
		collectors = CollectorList::create();
	}

	bool had_error = false;

	collectors->rewind();
	while (collectors->next(collector)) {

		dprintf(D_FULLDEBUG,"locating collector %s...\n", collector->name());

		if(!collector->locate(Daemon::LOCATE_FOR_LOOKUP)) {
			fprintf(stderr,"couldn't locate collector: %s\n",collector->error());
			had_error = true;
			continue;
		}

		dprintf(D_FULLDEBUG,"collector is %s located at %s\n",
				collector->hostname(),collector->addr());

		sock = NULL;

		ClassAd *ad;
		int success_count = 0;
		int failure_count = 0;
		ads.Rewind();
		while( (ad=ads.Next()) ) {

				// If there's no "MyAddress", generate one..
			if( !ad->Lookup( ATTR_MY_ADDRESS ) ) {
				MyString tmp;
				tmp.formatstr( "<%s:0>", my_ip_string() );
				ad->Assign( ATTR_MY_ADDRESS, tmp.Value() );
			}

			if ( use_tcp ) {
				if( !sock ) {
					sock = collector->startCommand(command,Stream::reli_sock,20);
				}
				else {
						// Use existing connection.
					sock->encode();
					sock->put(command);
				}
			} else {
					// We must open a new UDP socket each time.
				delete sock;
				sock = collector->startCommand(command,Stream::safe_sock,20);
			}

			int result = 0;
			if ( sock ) {
				result += putClassAd( sock, *ad );
				result += sock->end_of_message();
			}
			if ( result != 2 ) {
				fprintf(stderr,"failed to send classad to %s\n",collector->addr());
				had_error = true;
				failure_count++;
				delete sock;
				sock = NULL;
				continue;
			}

			if( with_ack ) {
				sock->decode();
				int ok = 0;
				if( !sock->get(ok) || !sock->end_of_message() ) {
					fprintf(stderr,"failed to get ack from %s\n",collector->addr());
					had_error = true;
					failure_count++;
					delete sock;
					sock = NULL;
					continue;
				}

					// ack protocol does not allow for multiple updates,
					// so close the socket now
				delete sock;
				sock = NULL;
			}

			success_count++;
			if (many_connections) {
				sock = NULL;
			}
		}
		if( sock ) {
			CondorVersionInfo const *ver = sock->get_peer_version();
			if( !ver || ver->built_since_version(7,7,3) ) {
					// graceful hangup so the collector knows we are done
				sock->encode();
				int hangup_cmd = DC_NOP;
				sock->put(hangup_cmd);
				sock->end_of_message();
			}

			delete sock;
			sock = NULL;
		}

		printf("Sent %d of %d ad%s to %s.\n",
			   success_count,
			   success_count + failure_count,
			   success_count+failure_count == 1 ? "" : "s",
			   collector->name());
	}

	if (many_connections) {
		sleep(3600);
	}
	delete collectors;

	return (had_error)?1:0;
}
Example #20
0
sw_error_t
cmd_show_vlan(a_uint32_t *arg_val)
{
    if (ssdk_cfg.init_cfg.chip_type == CHIP_ISIS) {
	    sw_error_t rtn;
	    a_uint32_t rtn_size = 1 ,tmp_vid = FAL_NEXT_ENTRY_FIRST_ID, cnt = 0;
	    fal_vlan_t *vlan_entry = (fal_vlan_t *) (ioctl_buf + rtn_size);

	    while (1)
	    {
	        arg_val[0] = SW_API_VLAN_NEXT;
	        arg_val[1] = (a_uint32_t) ioctl_buf;
	        arg_val[2] = get_devid();
	        arg_val[3] = tmp_vid;
	        arg_val[4] = (a_uint32_t) vlan_entry;

	        rtn = cmd_exec_api(arg_val);
	        if ((SW_OK != rtn)  || (SW_OK != (sw_error_t) (*ioctl_buf)))
	        {
	            break;
	        }

	        tmp_vid = vlan_entry->vid;
	        cnt++;
	    }

	    if((rtn != SW_OK) && (rtn != SW_NO_MORE))
	        cmd_print_error(rtn);
	    else
	        dprintf("\ntotal %d entries\n", cnt);
    }else if (ssdk_cfg.init_cfg.chip_type == CHIP_ISISC) {
	    sw_error_t rtn;
	    a_uint32_t rtn_size = 1 ,tmp_vid = FAL_NEXT_ENTRY_FIRST_ID, cnt = 0;
	    fal_vlan_t *vlan_entry = (fal_vlan_t *) (ioctl_buf + rtn_size);

	    while (1)
	    {
	        arg_val[0] = SW_API_VLAN_NEXT;
	        arg_val[1] = (a_uint32_t) ioctl_buf;
	        arg_val[2] = get_devid();
	        arg_val[3] = tmp_vid;
	        arg_val[4] = (a_uint32_t) vlan_entry;

	        rtn = cmd_exec_api(arg_val);
	        if ((SW_OK != rtn)  || (SW_OK != (sw_error_t) (*ioctl_buf)))
	        {
	            break;
	        }

	        tmp_vid = vlan_entry->vid;
	        cnt++;
	    }

	    if((rtn != SW_OK) && (rtn != SW_NO_MORE))
	        cmd_print_error(rtn);
	    else
	        dprintf("\ntotal %d entries\n", cnt);
    } else {
	    sw_error_t rtn;
	    a_uint32_t rtn_size = 1 ,tmp_vid = 0, cnt = 0;
	    fal_vlan_t *vlan_entry = (fal_vlan_t *) (ioctl_buf + rtn_size);

	    while (1)
	    {
	        arg_val[0] = SW_API_VLAN_NEXT;
	        arg_val[1] = (a_uint32_t) ioctl_buf;
	        arg_val[2] = get_devid();
	        arg_val[3] = tmp_vid;
	        arg_val[4] = (a_uint32_t) vlan_entry;

	        rtn = cmd_exec_api(arg_val);
	        if ((SW_OK != rtn)  || (SW_OK != (sw_error_t) (*ioctl_buf)))
	        {
	            break;
	        }

	        tmp_vid = vlan_entry->vid;
	        cnt++;
	    }

	    if((rtn != SW_OK) && (rtn != SW_NO_MORE))
	        cmd_print_error(rtn);
	    else
	        dprintf("\ntotal %d entries\n", cnt);
	}

    return SW_OK;
}
Example #21
0
void cmd_reboot(const char *arg, void *data, unsigned sz)
{
  dprintf(INFO, "rebooting the device\n");
  fastboot_okay("");
  mtk_arch_reset(1); //bypass pwr key when reboot
}
Example #22
0
sw_error_t
cmd_show_fdb(a_uint32_t *arg_val)
{
    if (ssdk_cfg.init_cfg.chip_type == CHIP_ISIS) {
	    sw_error_t rtn;
	    a_uint32_t cnt = 0;
	    fal_fdb_op_t    *fdb_op    = (fal_fdb_op_t *)    (ioctl_buf + sizeof(sw_error_t) / 4);
	    fal_fdb_entry_t *fdb_entry = (fal_fdb_entry_t *) (ioctl_buf + sizeof(sw_error_t) / 4 + sizeof(fal_fdb_op_t) / 4);

	    aos_mem_zero(fdb_op,    sizeof (fal_fdb_op_t));
	    aos_mem_zero(fdb_entry, sizeof (fal_fdb_entry_t));
	    arg_val[0] = SW_API_FDB_EXTEND_FIRST;

	    while (1)
	    {
	        arg_val[1] = (a_uint32_t) ioctl_buf;
	        arg_val[2] = get_devid();
	        arg_val[3] = (a_uint32_t) fdb_op;
	        arg_val[4] = (a_uint32_t) fdb_entry;

	        rtn = cmd_exec_api(arg_val);
	        if ((SW_OK != rtn)  || (SW_OK != (sw_error_t) (*ioctl_buf)))
	        {
	            break;
	        }
	        arg_val[0] = SW_API_FDB_EXTEND_NEXT;
	        cnt++;
	    }

	    if((rtn != SW_OK) && (rtn != SW_NO_MORE))
	        cmd_print_error(rtn);
	    else
	        dprintf("\ntotal %d entries\n", cnt);
    }else if (ssdk_cfg.init_cfg.chip_type == CHIP_ISISC) {
	    sw_error_t rtn;
	    a_uint32_t cnt = 0;
	    fal_fdb_op_t    *fdb_op    = (fal_fdb_op_t *)    (ioctl_buf + sizeof(sw_error_t) / 4);
	    fal_fdb_entry_t *fdb_entry = (fal_fdb_entry_t *) (ioctl_buf + sizeof(sw_error_t) / 4 + sizeof(fal_fdb_op_t) / 4);

	    aos_mem_zero(fdb_op,    sizeof (fal_fdb_op_t));
	    aos_mem_zero(fdb_entry, sizeof (fal_fdb_entry_t));
	    arg_val[0] = SW_API_FDB_EXTEND_FIRST;

	    while (1)
	    {
	        arg_val[1] = (a_uint32_t) ioctl_buf;
	        arg_val[2] = get_devid();
	        arg_val[3] = (a_uint32_t) fdb_op;
	        arg_val[4] = (a_uint32_t) fdb_entry;

	        rtn = cmd_exec_api(arg_val);
	        if ((SW_OK != rtn)  || (SW_OK != (sw_error_t) (*ioctl_buf)))
	        {
	            break;
	        }
	        arg_val[0] = SW_API_FDB_EXTEND_NEXT;
	        cnt++;
	    }

	    if((rtn != SW_OK) && (rtn != SW_NO_MORE))
	        cmd_print_error(rtn);
	    else
	        dprintf("\ntotal %d entries\n", cnt);
    }else if (ssdk_cfg.init_cfg.chip_type == CHIP_SHIVA) {
	    sw_error_t rtn;
	    a_uint32_t cnt = 0;
	    fal_fdb_entry_t *fdb_entry = (fal_fdb_entry_t *) (ioctl_buf + 2);

	    memset(fdb_entry, 0, sizeof (fal_fdb_entry_t));
	    arg_val[0] = SW_API_FDB_ITERATE;
	    *(ioctl_buf + 1) = 0;

	    while (1)
	    {
	        arg_val[1] = (a_uint32_t) ioctl_buf;
	        arg_val[2] = get_devid();
	        arg_val[3] = (a_uint32_t) (ioctl_buf + 1);
	        arg_val[4] = (a_uint32_t) fdb_entry;

	        rtn = cmd_exec_api(arg_val);
	        if ((SW_OK != rtn)  || (SW_OK != (sw_error_t) (*ioctl_buf)))
	        {
	            break;
	        }
	        cnt++;
	    }

	    if((rtn != SW_OK) && (rtn != SW_NO_MORE))
	        cmd_print_error(rtn);
	    else
	        dprintf("\ntotal %d entries\n", cnt);
    }else {
	    sw_error_t rtn;
	    a_uint32_t rtn_size = 1, cnt = 0;
	    fal_fdb_entry_t *fdb_entry = (fal_fdb_entry_t *) (ioctl_buf + rtn_size);

	    memset(fdb_entry, 0, sizeof (fal_fdb_entry_t));
	    arg_val[0] = SW_API_FDB_FIRST;

	    while (1)
	    {
	        arg_val[1] = (a_uint32_t) ioctl_buf;
	        arg_val[2] = get_devid();
	        arg_val[3] = (a_uint32_t) fdb_entry;

	        rtn = cmd_exec_api(arg_val);
	        if ((SW_OK != rtn)  || (SW_OK != (sw_error_t) (*ioctl_buf)))
	        {
	            break;
	        }
	        arg_val[0] = SW_API_FDB_NEXT;
	        cnt++;
	    }

	    if((rtn != SW_OK) && (rtn != SW_NO_MORE))
	        cmd_print_error(rtn);
	    else
	        dprintf("\ntotal %d entries\n", cnt);
    }

    return SW_OK;
}
Example #23
0
DWORD _channel_packet_completion_routine(Remote *remote, Packet *packet, 
        LPVOID context, LPCSTR method, DWORD result)
{
    ChannelCompletionRoutine *comp = (ChannelCompletionRoutine *)context;
    DWORD channelId = packet_get_tlv_value_uint(packet, TLV_TYPE_CHANNEL_ID);
    Channel *channel = channel_find_by_id(channelId);
    DWORD res = ERROR_NOT_FOUND;

    dprintf( "[CHANNEL] _channel_packet_completion_routine. channel=0x%08X method=%s", channel, method );

    if (!channel && strcmp(method, "core_channel_open"))
        return ERROR_NOT_FOUND;

    if ((!strcmp(method, "core_channel_open")) &&
        (comp->routine.open))
        res = comp->routine.open(remote, channel, comp->context, result);
    else if ((!strcmp(method, "core_channel_read")) &&
             (comp->routine.read))
    {
        ULONG length = 0, realLength = 0;
        PUCHAR buffer = NULL;

        length = packet_get_tlv_value_uint(packet, TLV_TYPE_LENGTH);

        if ((length) && (buffer = (PUCHAR)malloc(length)))
        {
            memset(buffer, 0, length);

            channel_read_from_buffered(channel, buffer, length, &realLength);
        }

        res = comp->routine.read(remote, channel, comp->context, result,
                buffer, realLength);

        if (buffer)
            free(buffer);
    }
    else if ((!strcmp(method, "core_channel_write")) &&
             (comp->routine.write))
    {
        Tlv lengthTlv;
        ULONG length = 0;

        if ((packet_get_tlv(packet, TLV_TYPE_LENGTH, &lengthTlv)
                == ERROR_SUCCESS) &&
            (lengthTlv.header.length >= sizeof(DWORD)))
            length = ntohl(*(LPDWORD)lengthTlv.buffer);

        res = comp->routine.write(remote, channel, comp->context, result,
                length);
    }
    else if ((!strcmp(method, "core_channel_close")) &&
             (comp->routine.close)) {
        dprintf( "[CHANNEL] freeing up the completion context" );
        res = comp->routine.close(remote, channel, comp->context, result);
    }
    else if ((!strcmp(method, "core_channel_interact")) &&
             (comp->routine.interact))
        res = comp->routine.interact(remote, channel, comp->context, result);

    dprintf( "[CHANNEL] freeing up the completion context" );
    free(comp);

    return res;
}
Example #24
0
File: debug.c Project: M1cha/lk
static int cmd_bio(int argc, const cmd_args *argv)
{
	int rc = 0;

	if (argc < 2) {
notenoughargs:
		printf("not enough arguments:\n");
usage:
		printf("%s list\n", argv[0].str);
		printf("%s read <device> <address> <offset> <len>\n", argv[0].str);
		printf("%s write <device> <address> <offset> <len>\n", argv[0].str);
		printf("%s erase <device> <offset> <len>\n", argv[0].str);
		printf("%s ioctl <device> <request> <arg>\n", argv[0].str);
		printf("%s remove <device>\n", argv[0].str);
#if WITH_LIB_PARTITION
		printf("%s partscan <device> [offset]\n", argv[0].str);
#endif
#if WITH_LIB_CKSUM
		printf("%s crc32 <device> <offset> <len> [repeat]\n", argv[0].str);
#endif
		return -1;
	}

	if (!strcmp(argv[1].str, "list")) {
		bio_dump_devices();
	} else if (!strcmp(argv[1].str, "read")) {
		if (argc < 6) goto notenoughargs;

		addr_t address = argv[3].u;
		off_t offset = argv[4].u; // XXX use long
		size_t len = argv[5].u;

		bdev_t *dev = bio_open(argv[2].str);
		if (!dev) {
			printf("error opening block device\n");
			return -1;
		}

		lk_time_t t = current_time();
		ssize_t err = bio_read(dev, (void *)address, offset, len);
		t = current_time() - t;
		dprintf(INFO, "bio_read returns %d, took %u msecs (%d bytes/sec)\n", (int)err, (uint)t, (uint32_t)((uint64_t)err * 1000 / t));

		bio_close(dev);

		rc = err;
	} else if (!strcmp(argv[1].str, "write")) {
		if (argc < 6) goto notenoughargs;

		addr_t address = argv[3].u;
		off_t offset = argv[4].u; // XXX use long
		size_t len = argv[5].u;

		bdev_t *dev = bio_open(argv[2].str);
		if (!dev) {
			printf("error opening block device\n");
			return -1;
		}

		lk_time_t t = current_time();
		ssize_t err = bio_write(dev, (void *)address, offset, len);
		t = current_time() - t;
		dprintf(INFO, "bio_write returns %d, took %u msecs (%d bytes/sec)\n", (int)err, (uint)t, (uint32_t)((uint64_t)err * 1000 / t));

		bio_close(dev);

		rc = err;
	} else if (!strcmp(argv[1].str, "erase")) {
		if (argc < 5) goto notenoughargs;

		off_t offset = argv[3].u; // XXX use long
		size_t len = argv[4].u;

		bdev_t *dev = bio_open(argv[2].str);
		if (!dev) {
			printf("error opening block device\n");
			return -1;
		}

		lk_time_t t = current_time();
		ssize_t err = bio_erase(dev, offset, len);
		t = current_time() - t;
		dprintf(INFO, "bio_erase returns %d, took %u msecs (%d bytes/sec)\n", (int)err, (uint)t, (uint32_t)((uint64_t)err * 1000 / t));

		bio_close(dev);

		rc = err;
	} else if (!strcmp(argv[1].str, "ioctl")) {
		if (argc < 4) goto notenoughargs;

		int request = argv[3].u;
		int arg = (argc == 5) ? argv[4].u : 0;

		bdev_t *dev = bio_open(argv[2].str);
		if (!dev) {
			printf("error opening block device\n");
			return -1;
		}

		int err = bio_ioctl(dev, request, (void *)arg);
		dprintf(INFO, "bio_ioctl returns %d\n", err);

		bio_close(dev);

		rc = err;
	} else if (!strcmp(argv[1].str, "remove")) {
		if (argc < 3) goto notenoughargs;

		bdev_t *dev = bio_open(argv[2].str);
		if (!dev) {
			printf("error opening block device\n");
			return -1;
		}

		bio_unregister_device(dev);
		bio_close(dev);
#if WITH_LIB_PARTITION
	} else if (!strcmp(argv[1].str, "partscan")) {
		if (argc < 3) goto notenoughargs;

		off_t offset = 0;
		if (argc > 3)
			offset = argv[3].u;

		rc = partition_publish(argv[2].str, offset);
		dprintf(INFO, "partition_publish returns %d\n", rc);
#endif
#if WITH_LIB_CKSUM
	} else if (!strcmp(argv[1].str, "crc32")) {
		if (argc < 5) goto notenoughargs;

		off_t offset = argv[3].u; // XXX use long
		size_t len = argv[4].u;

		bdev_t *dev = bio_open(argv[2].str);
		if (!dev) {
			printf("error opening block device\n");
			return -1;
		}

		void *buf = malloc(dev->block_size);

		bool repeat = false;
		if (argc >= 6 && !strcmp(argv[5].str, "repeat")) {
			repeat = true;
		}

		do {
			ulong crc = 0;
			off_t pos = offset;
			while (pos < offset + len) {
				ssize_t err = bio_read(dev, buf, pos, MIN(len - (pos - offset), dev->block_size));

				if (err <= 0) {
					printf("error reading at offset 0x%llx\n", offset + pos);
					break;
				}

				crc = crc32(crc, buf, err);

				pos += err;
			}

			printf("crc 0x%08lx\n", crc);
		} while (repeat);

		bio_close(dev);
		free(buf);

#endif
	} else {
		printf("unrecognized subcommand\n");
		goto usage;
	}

	return rc;
}
Example #25
0
VOID
ConfigInfoUpdate( )

/*++

Routine Description:


Arguments:


Return Value:


--*/

{
   BOOL InDomain = FALSE;
   BOOL IsPDC = FALSE;
   USHORT cbTotalAvail, cbBuffer;
   LPBYTE pbBuffer;
   NET_API_STATUS uRet;
   PSERVER_INFO_101 pServer1;
   DWORD ReplicationType, ReplicationTime;
   TCHAR pDomain[MAX_COMPUTERNAME_LENGTH + 1];
   NT_PRODUCT_TYPE NtType;

#if DBG
   if (TraceFlags & TRACE_FUNCTION_TRACE)
      dprintf(TEXT("LLS TRACE: ConfigInfoUpdate\n"));
#endif
   //
   // Try to get a domain
   //
   lstrcpy(pDomain, TEXT(""));
   if ( !NTDomainGet(NULL, pDomain) ) {
      InDomain = TRUE;

      //
      // If we aren't a BDC/PDC then count us as a member
      //
      NtType = NtProductLanManNt;
      RtlGetNtProductType(&NtType);
      if (NtType != NtProductLanManNt)
         IsPDC = FALSE;
      else {
         //
         // Let's check if we are a PDC...
         //
         IsPDC = NTIsPDC(ConfigInfo.ComputerName);
      }

   } else {
      IsPDC = TRUE;
      InDomain = FALSE;
   }

   RtlEnterCriticalSection(&ConfigInfoLock);

   ConfigInfo.IsMaster = TRUE;
   ConfigInfo.Replicate = FALSE;

   //
   // If we are in a domain, and not the PDC then we replicate to the PDC
   //
   if (!IsPDC && InDomain) {
      //
      // Get the PDC of the domain
      //
      uRet = NetGetDCName(NULL, pDomain, &pbBuffer);
      if (uRet == 0) {
         lstrcpy(ConfigInfo.ReplicateTo, (LPWSTR) pbBuffer);
         NetApiBufferFree(pbBuffer);
         ConfigInfo.IsMaster = FALSE;
         ConfigInfo.Replicate = TRUE;
      } else {
         InDomain = FALSE;
         memset(ConfigInfo.ReplicateTo, 0, sizeof(ConfigInfo.ReplicateTo));
#if DBG
         dprintf(TEXT("LLS: (WARNING) NetGetDCName: 0x%lX\n"), uRet);
#endif
      }
   }

   //
   // Update values from Registry
   //
   ReplicationTime = ConfigInfo.ReplicationTime;
   ReplicationType = ConfigInfo.ReplicationType;
   ConfigInfoRegistryInit( &ConfigInfo.UseEnterprise, ConfigInfo.EnterpriseServer,
                           &ConfigInfo.ReplicationType, &ConfigInfo.ReplicationTime,
                           &ConfigInfo.LogLevel );

   //
   // Have all registy init'd values - now need to figure out who to
   // replicate to.
   //
   // If we are not in a domain or are a PDC then we can go to the
   // Enterprise Server.
   //
   if (IsPDC || !InDomain) {
      if (ConfigInfo.UseEnterprise) {
         ConfigInfo.IsMaster = FALSE;
         ConfigInfo.Replicate = TRUE;

         //
         // Make sure we have an enterprise server to go to
         //
         if ( ConfigInfo.EnterpriseServer[0] == TEXT('\0') ) {
            ConfigInfo.UseEnterprise = FALSE;
            ConfigInfo.IsMaster = TRUE;
            ConfigInfo.Replicate = FALSE;
         } else {
            //
            // Base ReplicateTo on enterprise server name
            //
            if (ConfigInfo.EnterpriseServer[0] != TEXT('\\'))
               lstrcpy(ConfigInfo.ReplicateTo, TEXT("\\\\"));
            else
               lstrcpy(ConfigInfo.ReplicateTo, TEXT(""));

            lstrcat(ConfigInfo.ReplicateTo, ConfigInfo.EnterpriseServer);
         }
      } else
         ConfigInfo.IsMaster = TRUE;
   } else
      ConfigInfo.UseEnterprise = FALSE;

   if (ConfigInfo.IsMaster == FALSE) {
      if ( (ConfigInfo.ReplicateTo == NULL) || (lstrlen(ConfigInfo.ReplicateTo) == 0) ||
           ( (*ConfigInfo.ReplicateTo == TEXT('\\')) && (lstrlen(ConfigInfo.ReplicateTo) < 3) )) {
         ConfigInfo.IsMaster = TRUE;
         ConfigInfo.Replicate = FALSE;
      }
   }

   //
   // Adjust replication time if it has changed
   //
   if ((ReplicationTime != ConfigInfo.ReplicationTime) || (ReplicationType != ConfigInfo.ReplicationType))
      ReplicationTimeSet();

   IsMaster = ConfigInfo.IsMaster;
   RtlLeaveCriticalSection(&ConfigInfoLock);

} // ConfigInfoUpdate
Example #26
0
int main (const int argc, const char** argv)
{
	GF_Err e;
	Bool run;

	/* location of the configuration file: 0 wait for config on a socket, 1 use the given file */
	u32 config_flag;	
	char config_file_name[MAX_BUF];

	int dest_port;
	unsigned short tcp_port = 0;
	/* Should be fine on WIFI network */
	unsigned short mtu_size = 1492;
	int debug = 0;
	TCP_Input *tcp_conf = NULL;
	GF_Thread *tcp_thread;
	GF_Err th_err_tcp;

	GF_Err th_err_rap;
	RAP_Input *rap_conf;
	GF_Thread *rap_thread;

	CONF_Data *conf;	
	GF_Config *gf_config_file;
	GF_Err res;
	
	GF_Socket *UDP_feedback_socket;
	u32 socketType_for_updates;
	
	PNC_CallbackData * data;
	GF_RTPChannel * chan;
	GF_RTPHeader hdr;
	u32 timer = -1;
	
	GF_Mutex *carrousel_mutex;	
	char sdp_fmt[5000];
	tcp_thread = NULL;
	
	/* init gpac lib */
	gf_sys_init();
	
	GF_SAFEALLOC(conf, CONF_Data);
		
	tcp_port = config_flag = 0;
	socketType_for_updates = GF_SOCK_TYPE_UDP;
	if (command_line_parsing(argc, argv, &tcp_port, config_file_name, (int *) &config_flag, &mtu_size, &debug, &socketType_for_updates)){
		print_usage();
		return -1;
	}
	setDebugMode( debug );
	gf_config_file = NULL;
	if (config_flag == 1)
	{
		char *cfg_path;
		char *cfg_fname;
		char *tmp;
		
		cfg_fname = config_file_name;
		cfg_path = config_file_name;
		tmp = strrchr(cfg_fname, GF_PATH_SEPARATOR);
		if (tmp) {
			cfg_fname = tmp+1;
			tmp[0] = 0;
		} else {
			cfg_path = ".";
		}
		gf_config_file = gf_cfg_new(cfg_path, cfg_fname);	
		if (!gf_config_file) {
			fprintf(stderr, "Cannot open config file %s\n", config_file_name);
			return -1;
		} else {
			dprintf(DEBUG_broadcaster, "Using config file %s.\n", config_file_name);
		}
		if (parse_config(gf_config_file, conf, debug)) return -1;
		tcp_port = atoi(conf->config_input_port);
	}
	else
	{
		GF_SAFEALLOC(tcp_conf, TCP_Input);
		tcp_conf->config_flag = &config_flag;
		tcp_conf->RAPtimer = &timer;
		tcp_conf->port = tcp_port;
		tcp_conf->config = conf;
		tcp_thread = gf_th_new("TCPInterface");

		/* Starting the thread which will write the received config in a temporary file */
		th_err_tcp = gf_th_run(tcp_thread, tcp_server, tcp_conf);
		
		fprintf(stdout, "Waiting for configuration on port %d...\n", tcp_conf->port);

		while(config_flag == 0) { 
			gf_sleep(1000); 
		}
		fprintf(stdout, "Configuration File received. Starting Streaming ...\n");
	}
	
	timer = atoi(conf->rap_timer);
	dest_port = atoi(conf->dest_port);
	res = PNC_InitRTP(&chan, (char *)conf->dest_ip, dest_port, mtu_size);
 	if (res != 0) {
		fprintf(stderr, "Cannot initialize RTP output (error: %d)\n", res); 
		exit(1);
	} 

	carrousel_mutex = gf_mx_new("Carrousel");
	data = PNC_Init_SceneGenerator(chan, &hdr, (char *) conf->scene_init_file,
								   socketType_for_updates, (u16) atoi(conf->modif_input_port), debug); 
	if (!data) {
		fprintf(stderr, "Cannot initialize Scene Generator\n"); 
		exit(1);
	}
	data->carrousel_mutex = carrousel_mutex;
	data->RAPsent = 1;
	
	UDP_feedback_socket = gf_sk_new(GF_SOCK_TYPE_UDP);
	e = gf_sk_bind(UDP_feedback_socket, NULL, (u16)atoi(conf->feedback_port), (char*)conf->feedback_ip, (u16)atoi(conf->feedback_port), 0);
	if (e) {
		fprintf(stderr, "Cannot bind socket for bitrate feedback information (%s)\n", gf_error_to_string(e));
	} else {
		e = gf_sk_set_block_mode(UDP_feedback_socket, 1);
		if (e) {
			fprintf(stderr, "Cannot set feedback socket block mode (%s)\n", gf_error_to_string(e));
		}
	}
	data->feedback_socket = UDP_feedback_socket;

	PNC_InitPacketiser(data, sdp_fmt, mtu_size); 
	PNC_SendInitScene(data);

	GF_SAFEALLOC(rap_conf, RAP_Input);
	rap_conf->RAPtimer = &timer;
	rap_conf->carrousel_mutex = carrousel_mutex;
	rap_conf->data = data;
	rap_thread = gf_th_new("RAPGenerator");
	th_err_rap = gf_th_run(rap_thread, RAP_send, rap_conf);

	sdp_generator(data, (char *)conf->dest_ip, sdp_fmt);
	
	run = 1;
	while (run)
	{
		GF_Err e = PNC_processBIFSGenerator(data); 
		if (e) {
			fprintf(stderr, "Cannot Process BIFS data (%s)\n", gf_error_to_string(e));
			break;
		}

		if (has_input()) {
			char c = get_a_char();
			switch (c) {
			case 'q':
				run = 0;
				break;
			}
		}
		gf_sleep(10);
	}

	/* waiting for termination of the RAP thread */
	rap_conf->status = 0;
	while (rap_conf->status != 2)
		gf_sleep(0);
	gf_free(rap_conf);
	gf_th_del(rap_thread);

	/* waiting for termination of the TCP listening thread */
	if (tcp_conf) {
		tcp_conf->status = 0;
		while (tcp_conf->status != 2)
			gf_sleep(0);
		gf_free(tcp_conf);
		gf_th_del(tcp_thread);
	}

	PNC_Close_SceneGenerator(data);
	
	gf_free(conf);
	
	if (gf_config_file)
		gf_cfg_del(gf_config_file);

	gf_mx_del(carrousel_mutex);
	gf_sys_close();
	return 0;
}
void cmd_flash_emmc_sparse_img(const char *arg, void *data, unsigned sz)
{
	unsigned int chunk;
	unsigned int chunk_data_sz;
	sparse_header_t *sparse_header;
	chunk_header_t *chunk_header;
	u32 total_blocks = 0;
	unsigned long long ptn = 0;
	unsigned long long size = 0;
	unsigned long long size_wrote = 0;
	int index = INVALID_PTN;
	char msg[256];
	dprintf(DBG_LV, "Enter cmd_flash_sparse_img()\n");
	dprintf(DBG_LV, "EMMC Offset[0x%x], Length[%d], data In[0x%x]\n", arg, sz, data);

	index = partition_get_index(arg);
	if(index == -1)
	{
		fastboot_fail_wrapper("partition table doesn't exist");
		return;
	}

	if(!is_support_flash(index)){
		sprintf(msg,"partition '%s' not support flash\n",arg);
		fastboot_fail_wrapper(msg);
		return;
	}

	ptn = partition_get_offset(index);

	size = partition_get_size(index);
	if (ROUND_TO_PAGE(sz,511) > size)
	{
		fastboot_fail_wrapper("size too large");
		return;
	}

	/* Read and skip over sparse image header */
	sparse_header = (sparse_header_t *) data;
	data += sparse_header->file_hdr_sz;
	if(sparse_header->file_hdr_sz > sizeof(sparse_header_t))
	{
		/* Skip the remaining bytes in a header that is longer than
		* we expected.
		*/
		data += (sparse_header->file_hdr_sz - sizeof(sparse_header_t));
	}

	dprintf (DBG_LV, "=== Sparse Image Header ===\n");
	dprintf (DBG_LV, "magic: 0x%x\n", sparse_header->magic);
	dprintf (DBG_LV, "major_version: 0x%x\n", sparse_header->major_version);
	dprintf (DBG_LV, "minor_version: 0x%x\n", sparse_header->minor_version);
	dprintf (DBG_LV, "file_hdr_sz: %d\n", sparse_header->file_hdr_sz);
	dprintf (DBG_LV, "chunk_hdr_sz: %d\n", sparse_header->chunk_hdr_sz);
	dprintf (DBG_LV, "blk_sz: %d\n", sparse_header->blk_sz);
	dprintf (DBG_LV, "total_blks: %d\n", sparse_header->total_blks);
	dprintf (DBG_LV, "total_chunks: %d\n", sparse_header->total_chunks);

	TIME_START;
	display_info("Writing Flash ... ");
	/* Start processing chunks */
	for (chunk=0; chunk<sparse_header->total_chunks; chunk++)
	{
		/* Read and skip over chunk header */
		chunk_header = (chunk_header_t *) data;
		data += sizeof(chunk_header_t);

		dprintf (INFO, "=== Chunk Header ===\n");
		dprintf (INFO, "chunk_type: 0x%x\n", chunk_header->chunk_type);
		dprintf (INFO, "chunk_data_sz: 0x%x\n", chunk_header->chunk_sz);
		dprintf (INFO, "total_size: 0x%x\n", chunk_header->total_sz);

		if(sparse_header->chunk_hdr_sz > sizeof(chunk_header_t))
		{
			/* Skip the remaining bytes in a header that is longer than
			* we expected.
			*/
			data += (sparse_header->chunk_hdr_sz - sizeof(chunk_header_t));
		}

		chunk_data_sz = sparse_header->blk_sz * chunk_header->chunk_sz;
		switch (chunk_header->chunk_type)
		{
		case CHUNK_TYPE_RAW:
			if(chunk_header->total_sz != (sparse_header->chunk_hdr_sz +
				chunk_data_sz))
			{
				fastboot_fail_wrapper("Bogus chunk size for chunk type Raw");
				return;
			}


			dprintf(INFO, "[Flash Base Address:0x%llx offset:0x%llx]-[size:%d]-[DRAM Address:0x%x]\n",
				ptn , ((uint64_t)total_blocks*sparse_header->blk_sz), chunk_data_sz, data);

			size_wrote = emmc_write(ptn + ((uint64_t)total_blocks*sparse_header->blk_sz),
				(unsigned int*)data, chunk_data_sz);

			dprintf(INFO, "[wrote:%lld]-[size:%d]\n", size_wrote ,chunk_data_sz);

			if(size_wrote != chunk_data_sz)
			{
				fastboot_fail_wrapper("flash write failure");
				return;
			}
			total_blocks += chunk_header->chunk_sz;
			data += chunk_data_sz;
			break;

		case CHUNK_TYPE_DONT_CARE:
			total_blocks += chunk_header->chunk_sz;
			break;

		case CHUNK_TYPE_CRC:
			if(chunk_header->total_sz != sparse_header->chunk_hdr_sz)
			{
				fastboot_fail_wrapper("Bogus chunk size for chunk type Dont Care");
				return;
			}
			total_blocks += chunk_header->chunk_sz;
			data += chunk_data_sz;
			break;

		default:
			fastboot_fail_wrapper("Unknown chunk type");
			return;
		}
	}

	dprintf(DBG_LV, "Wrote %d blocks, expected to write %d blocks\n",
		total_blocks, sparse_header->total_blks);

	if(total_blocks != sparse_header->total_blks)
	{
		fastboot_fail_wrapper("sparse image write failure");

	}
	else
	{
		fastboot_ok_wrapper("Write Flash OK", sz);
	}


	return;
}
Example #28
0
static void bs_rdwr_request(struct scsi_cmd *cmd)
{
	int ret, fd = cmd->dev->fd;
	uint32_t length;
	int result = SAM_STAT_GOOD;
	uint8_t key;
	uint16_t asc;
	char *tmpbuf;
	size_t blocksize;
	uint64_t offset = cmd->offset;
	uint32_t tl     = cmd->tl;
	int do_verify = 0;
	int i;
	char *ptr;
	const char *write_buf = NULL;
	ret = length = 0;
	key = asc = 0;

	switch (cmd->scb[0])
	{
	case ORWRITE_16:
		length = scsi_get_out_length(cmd);

		tmpbuf = malloc(length);
		if (!tmpbuf) {
			result = SAM_STAT_CHECK_CONDITION;
			key = HARDWARE_ERROR;
			asc = ASC_INTERNAL_TGT_FAILURE;
			break;
		}

		ret = pread64(fd, tmpbuf, length, offset);

		if (ret != length) {
			set_medium_error(&result, &key, &asc);
			free(tmpbuf);
			break;
		}

		ptr = scsi_get_out_buffer(cmd);
		for (i = 0; i < length; i++)
			ptr[i] |= tmpbuf[i];

		free(tmpbuf);

		write_buf = scsi_get_out_buffer(cmd);
		goto write;
	case COMPARE_AND_WRITE:
		/* Blocks are transferred twice, first the set that
		 * we compare to the existing data, and second the set
		 * to write if the compare was successful.
		 */
		length = scsi_get_out_length(cmd) / 2;
		if (length != cmd->tl) {
			result = SAM_STAT_CHECK_CONDITION;
			key = ILLEGAL_REQUEST;
			asc = ASC_INVALID_FIELD_IN_CDB;
			break;
		}

		tmpbuf = malloc(length);
		if (!tmpbuf) {
			result = SAM_STAT_CHECK_CONDITION;
			key = HARDWARE_ERROR;
			asc = ASC_INTERNAL_TGT_FAILURE;
			break;
		}

		ret = pread64(fd, tmpbuf, length, offset);

		if (ret != length) {
			set_medium_error(&result, &key, &asc);
			free(tmpbuf);
			break;
		}

		if (memcmp(scsi_get_out_buffer(cmd), tmpbuf, length)) {
			uint32_t pos = 0;
			char *spos = scsi_get_out_buffer(cmd);
			char *dpos = tmpbuf;

			/*
			 * Data differed, this is assumed to be 'rare'
			 * so use a much more expensive byte-by-byte
			 * comparasion to find out at which offset the
			 * data differs.
			 */
			for (pos = 0; pos < length && *spos++ == *dpos++;
			     pos++)
				;
			result = SAM_STAT_CHECK_CONDITION;
			key = MISCOMPARE;
			asc = ASC_MISCOMPARE_DURING_VERIFY_OPERATION;
			free(tmpbuf);
			break;
		}

		if (cmd->scb[1] & 0x10)
			posix_fadvise(fd, offset, length,
				      POSIX_FADV_NOREUSE);

		free(tmpbuf);

		write_buf = scsi_get_out_buffer(cmd) + length;
		goto write;
	case SYNCHRONIZE_CACHE:
	case SYNCHRONIZE_CACHE_16:
		/* TODO */
		length = (cmd->scb[0] == SYNCHRONIZE_CACHE) ? 0 : 0;

		if (cmd->scb[1] & 0x2) {
			result = SAM_STAT_CHECK_CONDITION;
			key = ILLEGAL_REQUEST;
			asc = ASC_INVALID_FIELD_IN_CDB;
		} else
			bs_sync_sync_range(cmd, length, &result, &key, &asc);
		break;
	case WRITE_VERIFY:
	case WRITE_VERIFY_12:
	case WRITE_VERIFY_16:
		do_verify = 1;
	case WRITE_6:
	case WRITE_10:
	case WRITE_12:
	case WRITE_16:
		length = scsi_get_out_length(cmd);
		write_buf = scsi_get_out_buffer(cmd);
write:
		ret = pwrite64(fd, write_buf, length,
			       offset);
		if (ret == length) {
			struct mode_pg *pg;

			/*
			 * it would be better not to access to pg
			 * directy.
			 */
			pg = find_mode_page(cmd->dev, 0x08, 0);
			if (pg == NULL) {
				result = SAM_STAT_CHECK_CONDITION;
				key = ILLEGAL_REQUEST;
				asc = ASC_INVALID_FIELD_IN_CDB;
				break;
			}
			if (((cmd->scb[0] != WRITE_6) && (cmd->scb[1] & 0x8)) ||
			    !(pg->mode_data[0] & 0x04))
				bs_sync_sync_range(cmd, length, &result, &key,
						   &asc);
		} else
			set_medium_error(&result, &key, &asc);

		if ((cmd->scb[0] != WRITE_6) && (cmd->scb[1] & 0x10))
			posix_fadvise(fd, offset, length,
				      POSIX_FADV_NOREUSE);
		if (do_verify)
			goto verify;
		break;
	case WRITE_SAME:
	case WRITE_SAME_16:
		/* WRITE_SAME used to punch hole in file */
		if (cmd->scb[1] & 0x08) {
			ret = unmap_file_region(fd, offset, tl);
			if (ret != 0) {
				eprintf("Failed to punch hole for WRITE_SAME"
					" command\n");
				result = SAM_STAT_CHECK_CONDITION;
				key = HARDWARE_ERROR;
				asc = ASC_INTERNAL_TGT_FAILURE;
				break;
			}
			break;
		}
		while (tl > 0) {
			blocksize = 1 << cmd->dev->blk_shift;
			tmpbuf = scsi_get_out_buffer(cmd);

			switch(cmd->scb[1] & 0x06) {
			case 0x02: /* PBDATA==0 LBDATA==1 */
				put_unaligned_be32(offset, tmpbuf);
				break;
			case 0x04: /* PBDATA==1 LBDATA==0 */
				/* physical sector format */
				put_unaligned_be64(offset, tmpbuf);
				break;
			}

			ret = pwrite64(fd, tmpbuf, blocksize, offset);
			if (ret != blocksize)
				set_medium_error(&result, &key, &asc);

			offset += blocksize;
			tl     -= blocksize;
		}
		break;
	case READ_6:
	case READ_10:
	case READ_12:
	case READ_16:
		length = scsi_get_in_length(cmd);
		ret = pread64(fd, scsi_get_in_buffer(cmd), length,
			      offset);

		if (ret != length)
			set_medium_error(&result, &key, &asc);

		if ((cmd->scb[0] != READ_6) && (cmd->scb[1] & 0x10))
			posix_fadvise(fd, offset, length,
				      POSIX_FADV_NOREUSE);

		break;
	case PRE_FETCH_10:
	case PRE_FETCH_16:
		ret = posix_fadvise(fd, offset, cmd->tl,
				POSIX_FADV_WILLNEED);

		if (ret != 0)
			set_medium_error(&result, &key, &asc);
		break;
	case VERIFY_10:
	case VERIFY_12:
	case VERIFY_16:
verify:
		length = scsi_get_out_length(cmd);

		tmpbuf = malloc(length);
		if (!tmpbuf) {
			result = SAM_STAT_CHECK_CONDITION;
			key = HARDWARE_ERROR;
			asc = ASC_INTERNAL_TGT_FAILURE;
			break;
		}

		ret = pread64(fd, tmpbuf, length, offset);

		if (ret != length)
			set_medium_error(&result, &key, &asc);
		else if (memcmp(scsi_get_out_buffer(cmd), tmpbuf, length)) {
			result = SAM_STAT_CHECK_CONDITION;
			key = MISCOMPARE;
			asc = ASC_MISCOMPARE_DURING_VERIFY_OPERATION;
		}

		if (cmd->scb[1] & 0x10)
			posix_fadvise(fd, offset, length,
				      POSIX_FADV_NOREUSE);

		free(tmpbuf);
		break;
	case UNMAP:
		if (!cmd->dev->attrs.thinprovisioning) {
			result = SAM_STAT_CHECK_CONDITION;
			key = ILLEGAL_REQUEST;
			asc = ASC_INVALID_FIELD_IN_CDB;
			break;
		}

		length = scsi_get_out_length(cmd);
		tmpbuf = scsi_get_out_buffer(cmd);

		if (length < 8)
			break;

		length -= 8;
		tmpbuf += 8;

		while (length >= 16) {
			offset = get_unaligned_be64(&tmpbuf[0]);
			offset = offset << cmd->dev->blk_shift;

			tl = get_unaligned_be32(&tmpbuf[8]);
			tl = tl << cmd->dev->blk_shift;

			if (offset + tl > cmd->dev->size) {
				eprintf("UNMAP beyond EOF\n");
				result = SAM_STAT_CHECK_CONDITION;
				key = ILLEGAL_REQUEST;
				asc = ASC_LBA_OUT_OF_RANGE;
				break;
			}

			if (tl > 0) {
				if (unmap_file_region(fd, offset, tl) != 0) {
					eprintf("Failed to punch hole for"
						" UNMAP at offset:%" PRIu64
						" length:%d\n",
						offset, tl);
					result = SAM_STAT_CHECK_CONDITION;
					key = HARDWARE_ERROR;
					asc = ASC_INTERNAL_TGT_FAILURE;
					break;
				}
			}

			length -= 16;
			tmpbuf += 16;
		}
		break;
	default:
		break;
	}

	dprintf("io done %p %x %d %u\n", cmd, cmd->scb[0], ret, length);

	scsi_set_result(cmd, result);

	if (result != SAM_STAT_GOOD) {
		eprintf("io error %p %x %d %d %" PRIu64 ", %m\n",
			cmd, cmd->scb[0], ret, length, offset);
		sense_data_build(cmd, key, asc);
	}
}
BOOL write_to_nand(u8* data, u32 length)
{
	u64 paritition_size = 0;
	int next_flip = 0;
	u32 index;
	BOOL partition_type;
	s8* p_type;
	//u32 pre_chksum = 0;
	//u32 post_chksum = 0;
	int r;

	if(sto_info.first_run)
	{
		r = get_partition_name(data, length, sto_info.partition_name);
		if(r < 0)
		{
			display_info("ASSERT!! get_partition_name() Fail");
			return FALSE;
		}

		index = partition_get_index(sto_info.partition_name);  //
		if(index == -1)
		{
			display_info("ASSERT!! Brick phone??");
			return FALSE;
		}

		if(!is_support_flash(index))
		{
			display_info("ASSERT!! Dont support system??");
			return FALSE;
		}
		//verify boot partition.
		if (!strcmp(sto_info.partition_name, "boot") || !strcmp(sto_info.partition_name, "recovery"))
		{
			if (memcmp((void *)data, BOOT_MAGIC, strlen(BOOT_MAGIC)))
			{
				display_info("image is not a boot image");
				return FALSE;
			}
		}

		paritition_size = partition_get_size(index);
		dprintf(DBG_LV, "[index:%d]-[partitionSize:%lld]-[downSize:%d]\n", index, paritition_size, sto_info.to_write_data_len);

		if (ROUND_TO_PAGE(sto_info.to_write_data_len,511) > paritition_size)
		{
			display_info("size too large, space small.");
			dprintf(DBG_LV, "size too large, space small.");
			return FALSE;
		}

		partition_get_type(index,&p_type);
		partition_type = (!strcmp(p_type,"yaffs2")) ? TRUE : FALSE;

		sto_info.image_base_addr = partition_get_offset(index);
		//NAND has no sparse image.
		//sto_info.unsparse_status.image_base_addr = sto_info.image_base_addr;
		//sto_info.is_sparse_image = is_sparse_image(data, length);
		sto_info.first_run = 0;
	}

	if (0 != nand_write_img((u32)(sto_info.image_base_addr+sto_info.bulk_image_offset), (void*)data, length,(u32)paritition_size, partition_type))
	{
		dprintf(DBG_LV, "nand_write_img() Failed.\n");
		display_info("Error in write bulk in NAND.");
		return FALSE;
	}
	if(sto_info.checksum_enabled)
	{
		//NAND do not support read() now.
	}

	sto_info.bulk_image_offset += length;

	return TRUE;
}
Example #30
0
static ATTRIBUTE_NO_SANITIZE_THREAD
void backtrace_sigaction(int signum, siginfo_t *info, void* ptr) {
	void *array[42];
	size_t size;
	void * caller_address;
	ucontext_t *uc = (ucontext_t *) ptr;
	int gdb_pid = -1;

	/* get all entries on the stack */
	size = backtrace(array, 42);

	/* Get the address at the time the signal was raised */
#if defined(REG_RIP)
	caller_address = (void *) uc->uc_mcontext.gregs[REG_RIP];
#elif defined(REG_EIP)
	caller_address = (void *) uc->uc_mcontext.gregs[REG_EIP];
#elif defined(__arm__)
	caller_address = (void *) uc->uc_mcontext.arm_pc;
#elif defined(__mips__)
	caller_address = (void *) uc->uc_mcontext.sc_pc;
#elif defined(REG_PC) && defined(__e2k__)
        caller_address = (void *) ((mcontext_t*) &uc->uc_mcontext)->mc_gregs[REG_PC];
#else /* TODO support more arch(s) */
#	warning Unsupported architecture.
	caller_address = info->si_addr;
#endif

	int should_die = 0;
	switch(info->si_signo) {
	case SIGXCPU:
	case SIGXFSZ:
		should_die = 1;
		break;
	case SIGABRT:
	case SIGALRM:
		if (info->si_pid == getpid())
			should_die = 1;
	case SIGBUS:
	case SIGFPE:
	case SIGILL:
	case SIGSEGV:
#ifndef SI_FROMKERNEL
#	define SI_FROMKERNEL(info) (info->si_code > 0)
#endif
		if (SI_FROMKERNEL(info))
			should_die = 1;
	}

	char time_buf[64];
	time_t t = ldap_time_unsteady();
	strftime(time_buf, sizeof(time_buf), "%F-%H%M%S", localtime(&t));

	char name_buf[PATH_MAX];
	int fd = -1;
#ifdef snprintf
#	undef snprintf
#endif
	if (snprintf(name_buf, sizeof(name_buf), "%s/slapd-backtrace.%s-%i.log%c",
				 backtrace_homedir ? backtrace_homedir : ".", time_buf, getpid(), 0) > 0)
		fd = open(name_buf, O_CREAT | O_EXCL | O_WRONLY | O_APPEND, 0644);

	if (fd < 0) {
		if (backtrace_homedir)
			fd = open(strrchr(name_buf, '/') + 1, O_CREAT | O_EXCL | O_WRONLY | O_APPEND, 0644);
		if (fd < 0)
			fd = STDERR_FILENO;
		dprintf(fd, "\n\n*** Unable create \"%s\": %s!", name_buf, STRERROR(errno));
	}

	dprintf(fd, "\n\n*** Signal %d (%s), address is %p from %p\n", signum, strsignal(signum),
			info->si_addr, (void *)caller_address);

	int n = readlink("/proc/self/exe", name_buf, sizeof(name_buf) - 1);
	if (n > 0) {
		name_buf[n] = 0;
		dprintf(fd, "    Executable file %s\n", name_buf);
	} else {
		dprintf(fd, "    Unable read executable name: %s\n", STRERROR(errno));
		strcpy(name_buf, "unknown");
	}

	void** actual = array;
	int frame = 0;
	for (n = 0; n < size; ++n)
		if (array[n] == caller_address) {
			frame = n;
			actual = array + frame;
			size -= frame;
			break;
		}

	dprintf(fd, "\n*** Backtrace by glibc:\n");
	backtrace_symbols_fd(actual, size, fd);

	int mem_map_fd = open("/proc/self/smaps", O_RDONLY, 0);
	if (mem_map_fd >= 0) {
		char buf[1024];
		dprintf(fd, "\n*** Memory usage map (by /proc/self/smaps):\n");
		while(1) {
			int n = read(mem_map_fd, &buf, sizeof(buf));
			if (n < 1)
				break;
			if (write(fd, &buf, n) != n)
				break;
		}
		close(mem_map_fd);
	}

	/* avoid ECHILD from waitpid() */
	signal(SIGCHLD, SIG_DFL);

	dprintf(fd, "\n*** Backtrace by addr2line:\n");
	for(n = 0; n < size; ++n) {
		int status = EXIT_FAILURE, child_pid = fork();
		if (! child_pid) {
			char addr_buf[64];
			close(STDIN_FILENO);
			dup2(fd, STDOUT_FILENO);
			close(fd);
			dprintf(STDOUT_FILENO, "(%d) %p: ", n, actual[n]);
			sprintf(addr_buf, "%p", actual[n]);
			execlp("addr2line", "addr2line", addr_buf, "-C", "-f", "-i",
#if __GLIBC_PREREQ(2,14)
				"-p", /* LY: not available on RHEL6, guest by glibc version */
#endif
				"-e", name_buf, NULL);
			exit(EXIT_FAILURE);
		} else if (child_pid < 0) {
			dprintf(fd, "\n*** Unable complete backtrace by addr2line, sorry (%s, %d).\n", "fork", errno);
			break;
		} else if (waitpid(child_pid, &status, 0) < 0 || status != W_EXITCODE(EXIT_SUCCESS, 0)) {
			dprintf(fd, "\n*** Unable complete backtrace by addr2line, sorry (%s, pid %d, errno %d, status 0x%x).\n",
				"waitpid", child_pid, errno, status);
			break;
		}
	}

	if (is_debugger_present()) {
		dprintf(fd, "*** debugger already present\n");
		goto ballout;
	}

	int retry_by_return = 0;
	if (should_die && SI_FROMKERNEL(info)) {
		/* LY: Expect kernel kill us again,
		 * therefore for switch to 'guilty' thread and we may just return,
		 * instead of sending SIGTRAP and later switch stack frame by GDB. */
		retry_by_return = 1;
	}

	if (is_valgrind_present()) {
		dprintf(fd, "*** valgrind present, skip backtrace by gdb\n");
		goto ballout;
	}

	int pipe_fd[2];
	if (pipe(pipe_fd)) {
		pipe_fd[0] = pipe_fd[1] = -1;
		goto ballout;
	}

	gdb_is_ready_for_backtrace = 0;
	pid_t tid = syscall(SYS_gettid);
	gdb_pid = fork();
	if (!gdb_pid) {
		char pid_buf[16];
		sprintf(pid_buf, "%d", getppid());

		dup2(pipe_fd[0], STDIN_FILENO);
		close(pipe_fd[1]);
		pipe_fd[0] = pipe_fd[1] =-1;
		dup2(fd, STDOUT_FILENO);
		dup2(fd, STDERR_FILENO);
		for(fd = getdtablesize(); fd > STDERR_FILENO; --fd)
			close(fd);
		setsid();
		setpgid(0, 0);

		dprintf(STDOUT_FILENO, "\n*** Backtrace by GDB "
#if GDB_SWITCH2GUILTY_THREAD
			"(pid %s, LWP %i, frame #%d):\n", pid_buf, tid, frame);
#else
			"(pid %s, LWP %i, please find frame manually):\n", pid_buf, tid);
#endif
		execlp("gdb", "gdb", "-q", "-se", name_buf, "-n", NULL);
		kill(getppid(), SIGKILL);
		dprintf(STDOUT_FILENO, "\n*** Sorry, GDB launch failed: %s\n", STRERROR(errno));
		fsync(STDOUT_FILENO);
		exit(EXIT_FAILURE);
	}