示例#1
0
static void discover_task ()
{
    uint8_t periods_in_idle = discover_period_s / DISCOVER_TASK_PERIOD_S;
    nrk_time_t now, elapsed;
    int8_t rc;

    while (1) {
        switch (discover_state) {
            case DISCOVER_IDLE:
                if (auto_discover) {
                    if (periods_in_idle < periods_in_idle)
                        break;

                    set_state(DISCOVER_SCHEDULED);
                }
                break;

            case DISCOVER_SCHEDULED:
#if ENABLE_LED
                pulse_led(led_discover);
#endif
                set_state(DISCOVER_PENDING);
                nrk_event_signal(discover_signal);
                break;

            case DISCOVER_IN_PROGRESS:
                nrk_time_get(&now);
                nrk_time_sub(&elapsed, now, last_activity);
                if (time_cmp(&elapsed, &discover_time_out) < 0) {
                    LOG("silent for ");
                    LOGP("%lu ms\r\n", TIME_TO_MS(elapsed));
                    break;
                }

                LOG("finished, distrib routes: seq ");
                LOGP("%d\r\n", outstanding_seq);

                print_graph(&network);

                rc = calc_routes(&network, &routes);
                if (rc == NRK_OK) {
                    print_routes(&routes);
                    rc = broadcast_routes(&routes, outstanding_seq);
                    if (rc != NRK_OK)
                        LOG("WARN: failed to bcast routes\r\n");
                } else {
                    LOG("WARN: failed to calc routes\r\n");
                }
                set_state(DISCOVER_COMPLETED);
                nrk_event_signal(discover_signal);
                break;

            case DISCOVER_PENDING:
            case DISCOVER_COMPLETED:
                /* the router failed to do its part in one task period */
                set_state(DISCOVER_IDLE);
                break;

            default:
                ABORT("unexpected state\r\n");
        }
        periods_in_state++;
        nrk_wait_until_next_period();
    }
    ABORT("discover task exited\r\n");
}
int pa__init(pa_module*m) {

    struct userdata *u;
    pa_modargs *ma;
    pa_sink_new_data data;
    int backend_state;
    int ret;
    char strbuf[100];

    pa_assert(m);

    if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
        pa_log("Failed to parse module arguments.");
        goto fail;
    }

    ss = m->core->default_sample_spec;
    map = m->core->default_channel_map;

    /* user arguments override these */
    if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_DEFAULT) < 0) {
        pa_log("Invalid sample format specification or channel map");
        return 1;
    }

    /* Xen Basic init */
    xsh = xs_domain_open();
    if (xsh==NULL) {
        pa_log("xs_domain_open failed");
        goto fail;
    }
    set_state(XenbusStateUnknown);

    xch = xc_interface_open(NULL, NULL, 0);
    if (xch==0) {
        pa_log("xc_interface_open failed");
        goto fail;
    }

    xce = xc_evtchn_open(NULL, 0);
    if (xce==0) {
        pa_log("xc_evtchn_open failed");
        goto fail;
    }

    /* use only dom0 as the backend for now */
    xen_evtchn_port = xc_evtchn_bind_unbound_port(xce, 0);
    if (xen_evtchn_port == 0) {
        pa_log("xc_evtchn_bind_unbound_port failed");
    }

    /* get grant reference & map locally */
    if (alloc_gref(&gref, (void**)&ioring)) {
       pa_log("alloc_gref failed");
    };
    device_id = 0; /* hardcoded for now */

    if (register_backend_state_watch()) {
        pa_log("Xen sink: register xenstore watch failed");
    };

    publish_param_int("event-channel", xen_evtchn_port);
    publish_param_int("ring-ref", gref.gref_ids[0]);

    /* let's ask for something absurd and deal with rejection */
    ss.rate = 192000;

    publish_spec(&ss);

    ret=0;
    while (!ret) {
        backend_state = wait_for_backend_state_change();
        if (backend_state == STATE_UNDEFINED) {
            pa_log("Xen Backend is taking long to respond, still waiting...");
            continue;
        } else if (backend_state == -1) {
            pa_log("Error while waiting for backend: %s", strerror(errno));
            break;
            goto fail;
        }
        ret = state_callbacks[backend_state]();
    }
    if (ret!=NEGOTIATION_OK) {
        pa_log("Negotiation with Xen backend failed!");
        return 1;
    }

    pa_sample_spec_snprint(strbuf, 100, &ss);
    pa_log_debug("Negotiation ended, the result was: %s", strbuf);

    /* End of Phase 2, begin playback cycle */

    u = pa_xnew0(struct userdata, 1);
    u->core = m->core;
    u->module = m;
    m->userdata = u;
    pa_memchunk_reset(&u->memchunk);
    u->rtpoll = pa_rtpoll_new();
    pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
    u->write_type = 0;

    /* init ring buffer */
    ioring->prod_indx = ioring->cons_indx = 0;
    ioring->usable_buffer_space = BUFSIZE - BUFSIZE % pa_frame_size(&ss);

    pa_sink_new_data_init(&data);
    data.driver = __FILE__;
    data.module = m;
    pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, "xensink");
    pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Xen PV audio sink");
    pa_sink_new_data_set_sample_spec(&data, &ss);
    pa_sink_new_data_set_channel_map(&data, &map);

    if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
        pa_log("Invalid properties");
        pa_sink_new_data_done(&data);
        goto fail;
    }

    u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
    pa_sink_new_data_done(&data);

    if (!u->sink) {
        pa_log("Failed to create sink.");
        goto fail;
    }

    u->sink->parent.process_msg = sink_process_msg;
    u->sink->userdata = u;

    pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
    pa_sink_set_rtpoll(u->sink, u->rtpoll);
    pa_sink_set_max_request(u->sink, ioring->usable_buffer_space);
    pa_sink_set_fixed_latency(u->sink, pa_bytes_to_usec(ioring->usable_buffer_space, &u->sink->sample_spec));

    u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);

    if (!(u->thread = pa_thread_new("xenpv-sink", thread_func, u))) {
        pa_log("Failed to create thread.");
        goto fail;
    }

    pa_sink_put(u->sink);

    pa_modargs_free(ma);

    return 0;

fail:
    if (ma)
        pa_modargs_free(ma);

    pa__done(m);

    return -1;
}
示例#3
0
文件: driver.c 项目: ferhatelmas/adb
/*
* MAIN
*
* assumes the existance of getopt() to clean up the command 
* line handling
*/
int
main (int ac, char **av)
{
	DSS_HUGE i;
	
	table = (1 << CUST) |
		(1 << SUPP) |
		(1 << NATION) |
		(1 << REGION) |
		(1 << PART_PSUPP) |
		(1 << ORDER_LINE);
	force = 0;
    insert_segments=0;
    delete_segments=0;
    insert_orders_segment=0;
    insert_lineitem_segment=0;
    delete_segment=0;
	verbose = 0;
	set_seeds = 0;
	scale = 1;
	flt_scale = 1.0;
	updates = 0;
	step = -1;
        partition = -1;
	tdefs[ORDER].base *=
		ORDERS_PER_CUST;			/* have to do this after init */
	tdefs[LINE].base *=
		ORDERS_PER_CUST;			/* have to do this after init */
	tdefs[ORDER_LINE].base *=
		ORDERS_PER_CUST;			/* have to do this after init */
	children = 1;
	d_path = NULL;
	
#ifdef NO_SUPPORT
	signal (SIGINT, exit);
#endif /* NO_SUPPORT */
	process_options (ac, av);
	validate_options();
#if (defined(WIN32)&&!defined(_POSIX_))
	for (i = 0; i < ac; i++)
	{
		spawn_args[i] = malloc (((int)strlen (av[i]) + 1) * sizeof (char));
		MALLOC_CHECK (spawn_args[i]);
		strcpy (spawn_args[i], av[i]);
	}
	spawn_args[ac] = NULL;
#endif
	
	if (verbose >= 0)
		{
		fprintf (stderr,
			"%s Population Generator (Version %d.%d.%d)\n",
			NAME, VERSION, RELEASE, PATCH);
		fprintf (stderr, "Copyright %s %s\n", TPC, C_DATES);
		}
	
	load_dists ();
#ifdef RNG_TEST
	for (i=0; i <= MAX_STREAM; i++)
		Seed[i].nCalls = 0;
#endif
	/* have to do this after init */
	tdefs[NATION].base = nations.count;
	tdefs[REGION].base = regions.count;
	
	/* 
	* updates are never parallelized 
	*/
	if (updates)
		{
		/* 
		 * set RNG to start generating rows beyond SF=scale
		 */
		set_state (ORDER, scale, 100, 101, &i); 
		rowcnt = (int)(tdefs[ORDER_LINE].base / 10000 * scale * UPD_PCT);
		if (step > 0)
			{
			/* 
			 * adjust RNG for any prior update generation
			 */
	      for (i=1; i < step; i++)
         {
			sd_order(0, rowcnt);
			sd_line(0, rowcnt);
         }
			upd_num = step - 1;
			}
		else
			upd_num = 0;

		while (upd_num < updates)
			{
			if (verbose > 0)
				fprintf (stderr,
				"Generating update pair #%d for %s",
				upd_num + 1, tdefs[ORDER_LINE].comment);
			insert_orders_segment=0;
			insert_lineitem_segment=0;
			delete_segment=0;
			minrow = upd_num * rowcnt + 1;
			gen_tbl (ORDER_LINE, minrow, rowcnt, upd_num + 1);
			if (verbose > 0)
				fprintf (stderr, "done.\n");
			pr_drange (ORDER_LINE, minrow, rowcnt, upd_num + 1);
			upd_num++;
			}

		exit (0);
		}
	
	/**
	** actual data generation section starts here
	**/

	/*
	* traverse the tables, invoking the appropriate data generation routine for any to be built
	*/
	for (i = PART; i <= REGION; i++)
		if (table & (1 << i))
		{
			if (children > 1 && i < NATION)
			{
				partial ((int)i, step);
			}
			else
			{
				minrow = 1;
				if (i < NATION)
					rowcnt = tdefs[i].base * scale;
				else
					rowcnt = tdefs[i].base;
				if (verbose > 0)
					fprintf (stderr, "Generating data for %s", tdefs[i].comment);
				gen_tbl ((int)i, minrow, rowcnt, upd_num);
				if (verbose > 0)
					fprintf (stderr, "done.\n");
			}
		}
			
		return (0);
}
/* negotiation callbacks */
static int state_unknown_cb() {
    pa_log_debug("Xen audio sink: Backend state was XenbusStateUnknown\n");
    set_state(XenbusStateInitialising);

    return 0;
}
static int state_initialised_cb() {
    pa_log_debug("Xen audio sink: Backend state was XenbusStateInitialised\n");
    /*Remind the backend we are ready*/
    set_state(XenbusStateInitialised);
    return 0;
}
示例#6
0
文件: kcs_bmc.c 项目: guribe94/linux
static void kcs_bmc_handle_data(struct kcs_bmc *kcs_bmc)
{
	u8 data;

	switch (kcs_bmc->phase) {
	case KCS_PHASE_WRITE_START:
		kcs_bmc->phase = KCS_PHASE_WRITE_DATA;
		/* fall through */

	case KCS_PHASE_WRITE_DATA:
		if (kcs_bmc->data_in_idx < KCS_MSG_BUFSIZ) {
			set_state(kcs_bmc, WRITE_STATE);
			write_data(kcs_bmc, KCS_ZERO_DATA);
			kcs_bmc->data_in[kcs_bmc->data_in_idx++] =
						read_data(kcs_bmc);
		} else {
			kcs_force_abort(kcs_bmc);
			kcs_bmc->error = KCS_LENGTH_ERROR;
		}
		break;

	case KCS_PHASE_WRITE_END_CMD:
		if (kcs_bmc->data_in_idx < KCS_MSG_BUFSIZ) {
			set_state(kcs_bmc, READ_STATE);
			kcs_bmc->data_in[kcs_bmc->data_in_idx++] =
						read_data(kcs_bmc);
			kcs_bmc->phase = KCS_PHASE_WRITE_DONE;
			kcs_bmc->data_in_avail = true;
			wake_up_interruptible(&kcs_bmc->queue);
		} else {
			kcs_force_abort(kcs_bmc);
			kcs_bmc->error = KCS_LENGTH_ERROR;
		}
		break;

	case KCS_PHASE_READ:
		if (kcs_bmc->data_out_idx == kcs_bmc->data_out_len)
			set_state(kcs_bmc, IDLE_STATE);

		data = read_data(kcs_bmc);
		if (data != KCS_CMD_READ_BYTE) {
			set_state(kcs_bmc, ERROR_STATE);
			write_data(kcs_bmc, KCS_ZERO_DATA);
			break;
		}

		if (kcs_bmc->data_out_idx == kcs_bmc->data_out_len) {
			write_data(kcs_bmc, KCS_ZERO_DATA);
			kcs_bmc->phase = KCS_PHASE_IDLE;
			break;
		}

		write_data(kcs_bmc,
			kcs_bmc->data_out[kcs_bmc->data_out_idx++]);
		break;

	case KCS_PHASE_ABORT_ERROR1:
		set_state(kcs_bmc, READ_STATE);
		read_data(kcs_bmc);
		write_data(kcs_bmc, kcs_bmc->error);
		kcs_bmc->phase = KCS_PHASE_ABORT_ERROR2;
		break;

	case KCS_PHASE_ABORT_ERROR2:
		set_state(kcs_bmc, IDLE_STATE);
		read_data(kcs_bmc);
		write_data(kcs_bmc, KCS_ZERO_DATA);
		kcs_bmc->phase = KCS_PHASE_IDLE;
		break;

	default:
		kcs_force_abort(kcs_bmc);
		break;
	}
}
示例#7
0
文件: main.c 项目: wulfskin/mod-rob
void controller_run(void) {
	//Declare variables
	//Store sensors readings
	uint8_t ir_frontleft, ir_frontright, ir_backleft, ir_backright, dis_front;
	
	//Speeds to be managed by the control logic, without taking into account speed adaption
	int speed_left = 0, speed_right = 0;
	
	//Speeds applied to the motors after adaptive speed calculation
	uint16_t speed_l, speed_r;
	
	//Speed offset, to make sure initially heading slightly to the right and finally slightly to the left
	int offset = 10;
	
	//Directions of the wheels
	char direction_left = 0, direction_right = 0;
	
	//main loop
	while(1) {
		//Read sensor values
		dis_front = sensor_read(SENSOR_FRONT, SENSOR_DISTANCE);
		ir_frontleft = (sensor_read(SENSOR_FRONTLEFT, SENSOR_IR));
		ir_frontright = (sensor_read(SENSOR_FRONTRIGHT, SENSOR_IR));
		ir_backleft = sensor_read(SENSOR_BACKLEFT, SENSOR_IR);
		ir_backright = sensor_read(SENSOR_BACKRIGHT, SENSOR_IR);
		
		// Remove noise
		if (ir_frontleft < NOISE_LEVEL)
		ir_frontleft = 0;
		if (ir_frontright < NOISE_LEVEL)
		ir_frontright = 0;
		if (ir_backleft < NOISE_LEVEL)
		ir_backleft = 0;
		if (ir_backright < NOISE_LEVEL)
		ir_backright = 0;
		
		switch (get_state())
		{
			case STATE_BRAITENBERG:
			{
				// State 0: Avoid obstacles
				LED_OFF(LED_PLAY);
				LED_OFF(LED_AUX);
				
				if (ir_frontright < DISTANCE_TO_TURN) { //no obstacle close
					direction_left = MOTOR_CCW;		// Going forward
					speed_left = 255;				//At full speed
				}
				else {		//close to an obstacle
					direction_left = MOTOR_CW;		//Going backwards
					speed_left = ir_frontright;		//speed proportional to obstacle distance (proximity)
				}
				// Going forward
				if (ir_frontleft < DISTANCE_TO_TURN) { //same as above for the other wheel
					direction_right = MOTOR_CW;
					speed_right = 255;
				}
				else {
					direction_right = MOTOR_CCW;
					speed_right = ir_frontleft;
				}
				
				if (offset > 0)		//apply speed offset to left/right wheel (before/after wall mode)
				speed_right -= offset;
				else
				speed_left -= offset;
				
				if (WALL_MODE) //If wall follow mode is activated
				{
					if(ir_backleft > 80) //If close to wall
					{
						set_state(STATE_FOLLOW);	//Go to wall-follow state
					}
				}
				break;
			}
			
			case STATE_FOLLOW:		// State: Follow the left wall
			{
				LED_ON(LED_AUX);
				if (ir_frontleft < 20)	
				{					//too far
					speed_left = 255-40;	//Head towards the wall
					speed_right = 255;
				}
				else
				{					//too close
					speed_left = 255;	//head away from the wall
					speed_right = 255-40;
				}
				// Go forward
				direction_left = MOTOR_CCW;
				direction_right = MOTOR_CW;
				if (ir_frontleft == 0)	{	//If arrived to the end of the wall
					set_state(STATE_BRAITENBERG);		//Return to Obstacle avoidance state
					offset = -offset;		//Invert speed offset (always head slightly to the left)
				}		
				break;
			}
			default:
			{
				// default state: stop
				speed_left = 0;
				speed_right = 0;
				break;
			}
		}//close switch statement
		
		//Calculate front distance, providing min distance to be able to stop/turn on time
		uint8_t dist = 0;
		if (DISTANCE_TO_BRAKE > dis_front)
			dist = DISTANCE_TO_BRAKE - dis_front;
		else
			dist = 0;
		//unless already turning
		if (direction_left == MOTOR_CW && direction_right == MOTOR_CCW)
			dist = 255;
		
		//Adjust speed according to distance
		uint8_t speed = (uint8_t)(MAX_SPEED_IN_PERCENTAGE * (uint32_t)dist / DISTANCE_TO_BRAKE);
		if (speed < MIN_SPEED_IN_PERCENTAGE)
		speed = MIN_SPEED_IN_PERCENTAGE;
		
		//Calculate motors speed
		speed_l = (uint16_t) ((speed_left<<2) * (uint32_t)speed / 100ul);
		speed_r = (uint16_t) ((speed_right<<2) * (uint32_t)speed / 100ul);
		
		//Apply motors speed and direction
		motor_set_speed_dir(MOTOR_LEFT, speed_l, direction_left);
		motor_set_speed_dir(MOTOR_RIGHT, speed_r, direction_right);

	}//close main loop
}//close main function
示例#8
0
bool densoecu::listen_denso02_bootloader()
{
	unsigned char rsp;
	unsigned int datalen = 1;
	int checksum = 0;

	dc->set_default_timeout(3000);
	if (!dc->read_serial_bytes(&rsp,&datalen))
		return false;

	checksum += rsp;
	int addr,len;

	switch(rsp)
	{
	case denso02_bootloader_cmd_start:
		l->print(log_densoecu,"denso02_bootloader_cmd_start\n");
		datalen = 1;
		if (!dc->read_serial_bytes(&rsp,&datalen))
			return false;
		checksum += rsp;
		// verify checksum
		datalen = 1;
		if (!dc->read_serial_bytes(&rsp,&datalen))
			return false;
		if (rsp != 0x100-(checksum & 0xFF))
		{
			l->print(log_densoecu,"bad checksum.\n");
			return false;
		}
		rxbuf[0] = 0x00;
		if (state == bootloader_auth)
		{
			if (!dc->write_denso02_cmd(denso02_bootloader_cmd_start,rxbuf,1))
				return false;
			set_state(bootloader);
		}
		break;
	case denso02_bootloader_cmd_write_kernel_ram:
		// read address and length
		datalen = 5;
		if (!dc->read_serial_bytes(rxbuf,&datalen))
		{
			l->print(log_densoecu,"denso write kernel area timeout!");
			return false;
		}
		checksum += dc->checksum(rxbuf,datalen);
		addr = byte_to_int24(rxbuf);
		len = byte_to_int16(rxbuf+3);
		l->print(log_densoecu,"denso write kernel area addr:%06X len:%02X\n",addr,len);
		if (addr < locrambase || addr+len > locrambase + 0x1800)
		{
			l->print(log_densoecu,"bad address range.\n");
			rsp = denso02_bootloader_rsp_bad_address;
			if (!dc->write_raw(&rsp,1))
				return false;
		}
		/*
		// todo: verify kernel length, return 0x22 if overrun
		if (len > datalen - 5)
		{
			if (!dc->write_raw(densocomm::denso02_bootloader_rsp_data_overrun,1))
				return false;
		}
		*/
		// now read data block
		datalen = len;
		if (!dc->read_serial_bytes(rxbuf,&datalen))
			return false;
		checksum += dc->checksum(rxbuf,datalen);
		// verify checksum
		datalen = 1;
		if (!dc->read_serial_bytes(&rsp,&datalen))
			return false;
		if (rsp != 0x100-(checksum & 0xFF))
		{
			l->print(log_densoecu,"bad checksum.\n");
			// todo: send 0x03
			rsp = denso02_bootloader_rsp_bad_checksum;
			if (!dc->write_raw(&rsp,1))
				return false;
			return false;
		}

		transform_kernel_block02(rxbuf,len,0,false);
		memcpy(rom+addr,rxbuf,len);
		// verify valid kernel
		if (byte_to_int16(rom+locrambase+2) != denso_magic_number)
		{
			// invalid_kernel magic number
			l->print(log_densoecu,"invalid magic number.\n");
			rsp = denso02_bootloader_rsp_bad_magic_number;
			if (!dc->write_raw(&rsp,1))
				return false;
		}
		l->print(log_densoecu,"valid kernel loaded.\n");

		delay(100);
		set_state(oecukernel);
		break;
	default:
		l->print(log_densoecu,"unk [%02X]\n",rsp);
	}
	return true;
}
示例#9
0
void densoecu::set_model(ecumodel _model)
{
	model = _model;
	set_state(normal);
}
示例#10
0
/**
 * @brief The main routine which accepts a SQL query and returns a list of type
 * 			TblColList which will contain list of all table and column names
 * 			referenced in the given query.
 * @param queryStr The query which is to be looked into.
 * @return A list of results.
 */
struct TblColList* ProcessQuery(std::string queryStr) {
	std::string current_token, previous_token, next_token;
	unsigned int index = 0;
	std::list<std::string> table_name_list; //store list of tables in current state
	// a SELECT/UNION will reset it.
	token_state_t current_state = NONE, previous_state = NONE;
	std::string table_name, col_name;

	std::list<lookup_table_for_name_alias_t> lookup_table_list;
	lookup_table_for_name_alias_t lookup_element;

	/*
	 * we will use stack where we will save the table_name_list the moment
	 * we encounter a opening round bracket. We dont need to save pRes as
	 * this stores relationship already established between column name and tables.
	 * This is in a way immutable once we the values have been stored. values
	 * such as current_token, next_token and index are all either changing and thus
	 * have state for that iteration only or their linear growth is valid even
	 * in a subquery (for index).
	 *
	 */
	struct query_state_t query_state;
	std::stack<struct query_state_t> query_state_stack;

	struct TblColList *pRes = new TblColList;

	while (index < queryStr.length()) {
		col_name = "";
		current_token = "";
		current_token = get_next_valid_token(&queryStr, &index);

		//have we reached end of stream
		if (current_token == "") {
			//no matter what we must end processing. How could we get an empty token ?
			return pRes;
		}

		if (current_token == "(") {
			/*
			 * when a opening '(' is encountered in the stream, it will not
			 * necessarily mean beginning of a sub-query. It can involve expressions
			 * like:
			 * ..from coupon c where c.id=5 and (c.roll>9)
			 * If we do a state save the moment we encounter "(" then alias c cant be
			 * looked up therefore we will do a state save only when we encounter
			 * SELECT after '(' .
			 *
			 * Also when we encounter a '(' NOT followed by a select then we will
			 * do the state save but we will not reset the state. So we will push
			 * current state the moment we find '(' but we will reset the state only
			 * when the next token is SELECT.
			 *
			 * Another option could have been that we save state only when '(' is
			 * followed by SELECT. But when we encounter the closing bracket ')'
			 * what do we pop off the stack ?
			 * (Well it could be simple pop if u can otherwise ignore. It would only
			 * mean that the opening ( for this closing ) did not mark a subquery.)
			 * Not a good option since for mal-formed query if there are misplaced
			 * closing brackets then wrong state will get popped off at wrong time .
			 * (optimal but does not work)
			 */

			next_token = "";
			next_token = get_next_valid_token(&queryStr, &index);

			//create an empty query_state variable
			query_state.current_state = NONE;
			query_state.previous_state = NONE;
			query_state.table_name_list.clear();
			query_state.select_triggered_query_state_change = false;

			//save the state
			query_state.current_state = current_state;
			query_state.previous_state = previous_state;
			query_state.table_name_list = table_name_list;

			//state save only when SELECT is the next token
			if (convert_to_uppercase(next_token) == "SELECT") {
				query_state.select_triggered_query_state_change = true;
				query_state_stack.push(query_state);

				//also  reset the state
				table_name_list.clear();
				current_state = NONE;
				previous_state = NONE;
			}
			//also push back this token
			pushback_token_to_stream(&next_token, &index);
			continue;
		}
		if (current_token == ")") {
			//now time to pop back what we stored in stack
			if (query_state_stack.empty()) {
				continue;
			}

			if (query_state_stack.top().select_triggered_query_state_change
					== true) {
				/*
				 * if the state saved at stack was triggered by SELECT then only
				 * do a state save and pop
				 * pop and save state into current variables
				 */
				table_name_list = (query_state_stack.top().table_name_list);
				current_state = (query_state_stack.top()).current_state;
				previous_state = (query_state_stack.top()).previous_state;

				//pop the top
				query_state_stack.pop();

			}
			continue;
		}
		// see if this token triggers a state change
		if (set_state(current_token, &current_state, &previous_state) == true) {
			continue;
		}

		/*
		 * if a state reset needed because keyword SELECT/UNION has been
		 * encountered in the input stream, then perform a state reset. After
		 * resetting table_name_list toggle state_reset_needed flag.
		 */
		if (state_reset_needed) {
			table_name_list.clear();
			toggle_state_reset();
		}
		/*
		 * when being in a state, if a reserved token is encountered and
		 * if code at that position can not handle it then it must do
		 *  a pushback followed a continue. We will handle reserved keywords
		 *  or unhandled tokens here.
		 *  Right now we are not handling most of the reserved tokens or operators
		 *  in this block. so continue
		 */
		if (is_token_reserved(current_token)
				or is_token_operator(current_token)) {
			// deal with token
			continue;
		}

		if (current_token == "," or current_token == ";") {
			continue;
		}

		//process state SELECT
		if (current_state == SELECT) {

		}
		// process state FROM
		if (current_state == FROM) {
			/*
			 * we can look for columns in FROM state
			 * 1. .. select name,roll from table_t1,table_t2
			 * 		// table_names separated by comma
			 * 2. .. select name,roll from table1 where roll>9
			 * 		// table names followed by reserved keywords
			 * 3. .. select a,b,c from table1 as t1,table2 as t2
			 * 		// table_name with alias_name separated by 'AS'
			 * 4. .. select t1.name,t2.roll from table1 t1,table2 t2
			 * 		// table_name with alias separated by space
			 */
			lookup_element.alias_name = "";
			lookup_element.table_name = "";

			if (!is_valid_tblcol_name(current_token)) {
				pushback_token_to_stream(&current_token, &index);
				continue;
			}

			next_token = "";
			next_token = get_next_valid_token(&queryStr, &index);
			/*
			 * Next token can be 'AS' or an alias name. For all other values
			 * of next_tokens, it must be pushed back to stream
			 */
			if ((is_valid_tblcol_name(next_token) == false)) {
				/*
				 * first and second case
				 * token_reserved will be when we have single table only.
				 * should AND,OR,NOT be part of reserved_tokens or operators ?
				 */
				table_name_list.push_back(current_token);

				lookup_element.table_name = current_token;
				lookup_table_list.push_back(lookup_element);

				//next_token may be reserved see if it triggers state change
				pushback_token_to_stream(&next_token, &index);
				continue;

			} else if (next_token == "AS" or next_token == "as") {
				// third case , then do one more lookahead
				table_name_list.push_back(current_token);

				//get next token
				next_token = get_next_valid_token(&queryStr, &index);
				if (!is_valid_tblcol_name(next_token)) {
					//this is bad
					std::cerr
							<< "Expected a valid <column_name> after AS before : "
							<< next_token << std::endl;
					return pRes;
				}
				//save the table_name and col_names
				lookup_element.table_name = current_token;
				lookup_element.alias_name = next_token;
				lookup_table_list.push_back(lookup_element);
				continue;
			} else {
				//fourth case
				table_name_list.push_back(current_token);
				lookup_element.table_name = current_token;
				lookup_element.alias_name = next_token;
				lookup_table_list.push_back(lookup_element);
			}

		} else if (current_state == WHERE) {
			/*
			 * what about queries where col name is referenced in a non-composite
			 * relationship ? for e.g 'select rollno from class where rollno >9'.
			 * since we are processing only queries where cols and tables will
			 * be referenced not selected, then we might not handle this case.
			 */
			// reject tokens that we might not need
			// for now we will reject any reserved keyword or operator
			if (!is_valid_tblcol_name(current_token)) {
				pushback_token_to_stream(&current_token, &index);
				continue;
			}

			next_token = "";
			next_token = get_next_valid_token(&queryStr, &index);
			if (next_token == ".") {
				//case where composite col name and table name will be found
				next_token = get_next_valid_token(&queryStr, &index);
				if (!is_valid_tblcol_name(next_token)) {
					//thats bad
					std::cerr << "Expected valid token after '.' near " << index
							<< std::endl;
					return pRes;
				}
				/*
				 * checks could be put here to ensure that next_token is a valid token
				 * as a matter of all places where we are doing lookahead, this
				 * should be checked.
				 */

				//current_token could be alias so lets get its table name
				table_name = find_table_name_of_alias_tblname(lookup_table_list,
						current_token);
				if (!is_valid_tblcol_name(table_name)) {
					//its an error -- will not happen since we will get back alias name
					// in cases where we dont find a suitable table_name for alias_name
				} else {
					store_table_name_uniquely(pRes->mTblNameList, table_name);
					std::string tmp = table_name + "." + next_token;
					store_table_col_name_uniquely(pRes->mTblColNameList, tmp);
				}
			} else {
				/*
				 *  =========== NON_STANDARD BEHAVIOUR ===========
				 * case where we have non-composite and possibly single col.
				 * When in WHERE clause more than one columns are referenced then
				 * they will always use '.' to denote table_name or table_name_alias
				 * with col_name . For.eg. select * from table1,table2 where table1.id >5 and table2.id <5;
				 * And when there are no colms with '.' separating the col and table_name
				 * then it means we have single table only.
				 *
				 * Therefore, this token is the col_name beglonging
				 * to this case.
				 *
				 * Resolving the ambiguity: IDB-4122
				 * ----------------------
				 *
				 * For single table case: all cols will be considered as referenced. However for
				 * multi-table non-composite columns , we will list them without any relationship.
				 */
				if (table_name_list.size() == 1) {
					/*
					 * case where we have single table name but may have
					 * mutliple cols.
					 */
					table_name = table_name_list.front();
					store_table_name_uniquely(pRes->mTblNameList, table_name);
					std::string tmp = table_name + "." + current_token;
					store_table_col_name_uniquely(pRes->mTblColNameList, tmp);
				} else {
					/*
					 * case where we have more than one tables --
					 * ambiguity IDB-4122
					 */
					for (std::list<std::string>::iterator it =
							table_name_list.begin();
							it != table_name_list.end(); it++) {
						store_table_name_uniquely(pRes->mTblNameList, *it);
					}

					std::string tmp = current_token;
					store_table_col_name_uniquely(pRes->mTblColNameList, tmp);
				}
			}
		}
	}
	return pRes;
}
/*
 * ******************************************* 
 *  Function: handle_transport_layer_packet  
 *
 *  Description: 
 *
 *  handle a transport layer 
 *  packet. Core transport layer handling 
 *  function , all the other funcitons 
 *  were written to support this big guy 
 *  
 *  Parameters: 
 *     buffer - packet buffer 
 *     src_id  - Source id 
 *     dest_id - Destination id 
 *
 * ******************************************* 
 */
void handle_transport_layer_packet( void * buffer , int src_id , int dest_id )
{

      
        int packet_type; 
        int requested_mtu; 
        int seq_no; 
        int connect_id; 
        void *realloc_buffer;
        int win_size ;	
	void *packet_data;
        int cid_seq_no; 	
        int current_sender_id; 
	int current_cid_state; 
	int sender_id ;
        char *realloc_buf_ptr; 	
	int max_connections_permitted = get_state(&__max_connections);
	packet_type = get_packet_type(buffer);

	switch(packet_type)
	{
		case CONTROL_CONNECT:
			requested_mtu = get_requested_mtu(buffer);
		        connect_id  =allocate_sender(max_connections_permitted);
			sender_id  = get_sender_id(buffer);
		        if ( connect_id  <  max_connections_permitted)
			{
                             
		              init_state(&__session_tab.cid_info[connect_id].curr_state);
		              set_state(&__session_tab.cid_info[connect_id].curr_state ,STATE_CONNECTED);
		              __session_tab.cid_info[connect_id].sequence_number = 0;  
		              __session_tab.cid_info[connect_id].buf_len = 0;  	
			        
                              send_connect_ack(src_id  , requested_mtu , connect_id,sender_id); 

			}
		        else
		        {
                              fprintf(stderr ,"%s", "\n Connection not possilbe  all slots full \n"); 
                              
		        }	
                        break;
		case CONTROL_ACK:
                        seq_no = get_sequence_number(buffer);
                        current_sender_id = get_sender_id(buffer);
			connect_id  = get_cid(buffer); 
			sender_buffer[current_sender_id].seq_no = seq_no; 
		        sender_buffer[current_sender_id].response_code = CONTROL_ACK; 
			sender_buffer[current_sender_id].connection_id = connect_id; 
                        break;
		case CONTROL_DATA:
		   {	
                       
			fprintf(stderr,"DATA packet received  ... ");    
		        connect_id  = get_cid(buffer);
		        seq_no = get_sequence_number(buffer);
			sender_id = get_sender_id(buffer);
                        cid_seq_no = __session_tab.cid_info[connect_id].sequence_number;
                        current_cid_state = get_state(&__session_tab.cid_info[connect_id].curr_state); 			
			fprintf(stderr,"\n seq no = %d cid seq no = %d window size = %d  CID = %d" , seq_no , cid_seq_no , get_window_size(buffer) , connect_id);
		        /* are we getting the next sequnce number  & we are connected */
			if( (  seq_no == cid_seq_no + 1 ) )
			{
                              win_size = get_window_size(buffer); 
		              realloc_buffer = malloc(win_size + __session_tab.cid_info[connect_id].buf_len);
		              if ( __session_tab.cid_info[connect_id].buf_len >  0  && ( current_cid_state != STATE_CLOSE)) 
			      {
			              memcpy(realloc_buffer,__session_tab.cid_info[connect_id].data_buf,__session_tab.cid_info[connect_id].buf_len);
				      realloc_buf_ptr = (char *) realloc_buffer + __session_tab.cid_info[connect_id].buf_len ;
				      packet_data    = (char *) buffer + TRASPORT_LAYER_SIZE ;  
				      memcpy(realloc_buf_ptr,packet_data , win_size);
				      __session_tab.cid_info[connect_id].buf_len += win_size; 
				      free( __session_tab.cid_info[connect_id].data_buf); 
				      __session_tab.cid_info[connect_id].data_buf = realloc_buffer;
                                      __session_tab.cid_info[connect_id].sequence_number++;
				      send_ack_request(src_id,seq_no,sender_id) ;   
		              }	     
			      else
			      {

				      packet_data    = (char *) buffer + TRASPORT_LAYER_SIZE ;  
				      memcpy(realloc_buffer,packet_data , win_size); 
				      __session_tab.cid_info[connect_id].buf_len += win_size; 
				      __session_tab.cid_info[connect_id].data_buf = realloc_buffer;
                                      __session_tab.cid_info[connect_id].sequence_number++;
				      send_ack_request(src_id,seq_no,sender_id) ;  

			      } 
                             
			}
		        else  if (  seq_no == cid_seq_no   )
			{
			        send_ack_request(src_id,seq_no,sender_id) ;   

			
			}
			else
			{
                            fprintf(stderr , "%s" , "\n Packet out of sequence number / duplicate  discarded \n ");  

			}	
                      }     
		      break; 

		case CONTROL_FIN:
		      fprintf(stderr ,"\n fin received  "); 
                      connect_id  = get_cid(buffer);
		      sender_id   = get_sender_id(buffer);
		      current_cid_state = get_state(&__session_tab.cid_info[connect_id].curr_state); 			
                      if ( current_cid_state  == STATE_CONNECTED )
		      {  
                              nfd_buffer_receved(__session_tab.cid_info[connect_id].data_buf,__session_tab.cid_info[connect_id].buf_len);
		              free(__session_tab.cid_info[connect_id].data_buf);
		              __session_tab.cid_info[connect_id].buf_len = 0 ; 
 		      }
		      else
		      {

                               set_state(&__session_tab.cid_info[connect_id].curr_state,STATE_FIN); 	
		      }
		      send_ack_request(src_id,0,sender_id); 
		      break;

		case  CONTROL_CLOSE:
                      connect_id  = get_cid(buffer);
		      set_state(&__session_tab.cid_info[connect_id].curr_state,STATE_CLOSE);
                      deallocate_connection(connect_id);
		      fprintf(stderr , "\nRecevied close packet "); 
		      break;

		case CONTROL_CONNECT_ACK:
	               seq_no = get_sequence_number(buffer);
                       current_sender_id = get_sender_id(buffer);
		       connect_id  = get_cid(buffer); 
		       sender_buffer[current_sender_id].response_code = CONTROL_CONNECT_ACK;
		       sender_buffer[current_sender_id].mtu_possible = get_window_size(buffer);  
		       sender_buffer[current_sender_id].connection_id = connect_id; 
	               fprintf(stderr , "\n Recieved control connect ack  sender id %d  mtu_possible  %d " ,current_sender_id, sender_buffer[current_sender_id].mtu_possible );  
 	       
 	               break; 

                default:
		       /* None of the known control types */
		       /* dropping packet */
		      fprintf(stderr,"\n Not one of the known packet types, Type = %d " , packet_type ); 
		      break; 

	}

}
示例#12
0
int process_alps_status(

  char           *nd_name,
  dynamic_string *status_info)

  {
  char           *str;
  char           *ccu_p = NULL;
  char           *current_node_id = NULL;
  char            node_index_buf[MAXLINE];
  int             node_index = 0;
  struct pbsnode *parent;
  struct pbsnode *current = NULL;
  int             rc;
  pbs_attribute   temp;
  hash_table_t   *rsv_ht;
  char            log_buf[LOCAL_LOG_BUF_SIZE];

  memset(&temp, 0, sizeof(temp));

  if ((rc = decode_arst(&temp, NULL, NULL, NULL, 0)) != PBSE_NONE)
    {
    log_record(PBSEVENT_DEBUG, PBS_EVENTCLASS_NODE, __func__, "cannot initialize attribute");
    return(rc);
    }

  /* if we can't find the parent node, ignore the update */
  if ((parent = find_nodebyname(nd_name)) == NULL)
    return(PBSE_NONE);

  /* keep track of reservations so that they're only processed once per update */
  rsv_ht = create_hash(INITIAL_RESERVATION_HOLDER_SIZE);

  /* loop over each string */
  for (str = status_info->str; str != NULL && *str != '\0'; str += strlen(str) + 1)
    {
    if (!strncmp(str, "node=", strlen("node=")))
      {
      if (str != status_info->str)
        {
        snprintf(node_index_buf, sizeof(node_index_buf), "node_index=%d", node_index++);
        decode_arst(&temp, NULL, NULL, node_index_buf, 0);
        
        if (current != NULL)
          save_node_status(current, &temp);
        }

      if ((current = determine_node_from_str(str, parent, current)) == NULL)
        break;
      else
        continue;
      }

    if (current == NULL)
      continue;

    /* process the gpu status information separately */
    if (!strcmp(CRAY_GPU_STATUS_START, str))
      {
      process_gpu_status(current, &str);
      
      continue;
      }
    else if (!strncmp(reservation_id, str, strlen(reservation_id)))
      {
      char *just_rsv_id = str + strlen(reservation_id);

      if (get_value_hash(rsv_ht, just_rsv_id) == -1)
        {
        add_hash(rsv_ht, 1, strdup(just_rsv_id));

        /* sub-functions will attempt to lock a job, so we must unlock the
         * reporter node */
        unlock_node(parent, __func__, NULL, LOGLEVEL);

        process_reservation_id(current, str);

        current_node_id = strdup(current->nd_name);
        unlock_node(current, __func__, NULL, LOGLEVEL);

        /* re-lock the parent */
        if ((parent = find_nodebyname(nd_name)) == NULL)
          {
          /* reporter node disappeared - this shouldn't be possible */
          log_err(PBSE_UNKNODE, __func__, "Alps reporter node disappeared while recording a reservation");
          free_arst(&temp);
          free_all_keys(rsv_ht);
          free_hash(rsv_ht);
          free(current_node_id);
          return(PBSE_NONE);
          }

        if ((current = find_node_in_allnodes(&parent->alps_subnodes, current_node_id)) == NULL)
          {
          /* current node disappeared, this shouldn't be possible either */
          unlock_node(parent, __func__, NULL, LOGLEVEL);
          snprintf(log_buf, sizeof(log_buf), "Current node '%s' disappeared while recording a reservation",
            current_node_id);
          log_err(PBSE_UNKNODE, __func__, log_buf);
          free_arst(&temp);
          free_all_keys(rsv_ht);
          free_hash(rsv_ht);
          free(current_node_id);
          return(PBSE_NONE);
          }

        free(current_node_id);
        current_node_id = NULL;
        }
      }
    /* save this as is to the status strings */
    else if ((rc = decode_arst(&temp, NULL, NULL, str, 0)) != PBSE_NONE)
      {
      free_arst(&temp);
      free_all_keys(rsv_ht);
      free_hash(rsv_ht);
      return(rc);
      }

    /* perform any special processing */
    if (!strncmp(str, ccu_eq, ac_ccu_eq_len))
      {
      /* save compute unit count in case we need it */
      /* note: this string (ccu_eq (CCU=)) needs to be found before cprocs_eq (CPROCS=) */
      /*  for the node */
      ccu_p = str;
      }
    else if (!strncmp(str, cproc_eq, ac_cproc_eq_len))
      {
      int ncpus;
      long svr_nppcu_value = 0;

      /*
       * Get the server nppcu value which determines how Hyper-Threaded
       * cores are reported. When server nppcu value is:
       *
       *  0 - Let ALPS choose whether or not to use Hyper-Threaded cores 
       *      (report all cores)
       *  1 - Do not use Hyper-Threaded cores
       *      (report only physical core (compute unit count)
       *  2 - Use Hyper-Threaded cores
       *      (report all cores)
       */
      get_svr_attr_l(SRV_ATR_nppcu, &svr_nppcu_value);

      if (svr_nppcu_value == NPPCU_NO_USE_HT && ccu_p != NULL)
        {
        /* no HT (nppcu==1), so use compute unit count */
        ncpus = atoi(ccu_p + ac_ccu_eq_len);

        /* use CPROC value if we are using APBASIL protocol < 1.3 */
        if (ncpus == 0)
          ncpus = atoi(str + ac_cproc_eq_len);

        /* reset the pointer */
        ccu_p = NULL;
        }
      else
        {
        /* let ALPS choose (nppcu==0) or use HT (nppcu==2), use actual processor count */
        ncpus = atoi(str + ac_cproc_eq_len);
        }

      set_ncpus(current, parent, ncpus);
      }
    else if (!strncmp(str, state, strlen(state)))
      {
      set_state(current, str);
      }

    } /* END processing the status update */

  if (current != NULL)
    {
    snprintf(node_index_buf, sizeof(node_index_buf), "node_index=%d", node_index++);
    decode_arst(&temp, NULL, NULL, node_index_buf, 0);
    save_node_status(current, &temp);
    unlock_node(current, __func__, NULL, LOGLEVEL);
    }

  unlock_node(parent, __func__, NULL, LOGLEVEL);

  free_all_keys(rsv_ht);
  free_hash(rsv_ht);

  return(PBSE_NONE);
  } /* END process_alps_status() */
示例#13
0
文件: nltest.c 项目: openSUSE/lldpad
int main(int argc, char *argv[])
{
	struct tc_config tc[8];
	int i, err = 0;
	int newstate = -1;
	int read_only = 0;
	__u8 state;
	__u8 pfc[8] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
	__u8 bwg[8] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
	__u8 mac[ETH_ALEN], san_mac[ETH_ALEN];
	__u8 cap[DCB_CAP_ATTR_MAX+1];
	__u8 numtcs;
	bcn_cfg bcn_set_data, bcn_data;
#ifdef DCB_APP_DRV_IF_SUPPORTED
	appgroup_attribs app_data = {DCB_APP_IDTYPE_ETHTYPE, 0x8906, 0x08};
#endif /* DCB_APP_DRV_IF_SUPPORTED */
	int ifindex;
	int optind = 1;
	char *ifname;

	printf("Calling RTNETLINK interface.\n");
	if (argc < 2) {
		fprintf(stderr, "usage: %s [-v] <ifname> [on|off|ro]\n",
			argv[0]);
		exit(1);
	}

	if (argc > 2) {
		if (!strcmp(argv[1], "-v")) {
			hexdump = 1;
			optind++;
		}
		if (argc > optind + 1) {
			if (!strcmp(argv[optind + 1], "on"))
				newstate = 1;
			if (!strcmp(argv[optind + 1], "off"))
				newstate = 0;
			if (!strcmp(argv[optind + 1], "ro"))
				read_only = 1;
		}
	}
	ifname = argv[optind];
	ifindex = if_nametoindex(ifname);
	if (ifindex == 0) {
		printf("no ifindex for %s\n", ifname);
		exit(1);
	}

	if ((nl_sd = init_socket()) < 0) {
		fprintf(stderr, "error creating netlink socket\n");
		return nl_sd;
	}

#ifdef DO_GETLINK_QUERY
	printf("DOING A GETLINK COMMAND\n");
	nlh = start_msg(RTM_GETLINK, ifindex);
	if (nlh == NULL)
		exit(1);
	if (send_msg(nlh))
		exit(1);
	free(nlh);
	nlh = get_msg();
#endif

	printf("GETTING DCB STATE\n");
	err = get_state(ifname, &state);
	if (err) {
		fprintf(stderr, "Error getting DCB state\n");
		goto err_main;
	}
	printf("DCB State = %d\n", state);

	if (newstate >= 0) {
		printf("\nSETTING DCB STATE TO: %d\n", newstate);
		err = set_state(ifname, newstate);
		if (err)
			goto err_main;

		err = get_state(ifname, &state);
		if (err) {
			fprintf(stderr, "Error getting DCB state\n");
			goto err_main;
		}
		printf("New DCB State = %d\n", state);
	}

	printf("\nGETTING PFC CONFIGURATION\n");
	for (i=0; i<8; i++)
		pfc[i] = 0x0f;
	get_pfc_cfg(ifname, pfc);
	printf("PFC config:\n");
	for (i=0; i<8; i++)
		printf("%x ", pfc[i]);
	printf("\n");

	get_pfc_state(ifname, &state);
	if (err) {
		fprintf(stderr, "Error getting PFC status\n");
		goto err_main;
	}
	printf("PFC State = %d\n", state);

	printf("\nGETTING PG TX CONFIGURATION\n");
	get_pg(ifname, tc, bwg, DCB_CMD_PGTX_GCFG);
	for (i = 0; i < 8; i++) {
		printf("%d: pr=%d\tbwgid=%d\tbw%%=%d\tu2t=%d\tlk%%=%d\n", i,
			tc[i].prio_type,
			tc[i].bwg_id,
			tc[i].bwg_percent,
			tc[i].up_to_tc_bitmap,
			bwg[i]);

		tc[i].prio_type = 3;
		tc[i].bwg_id = i;
		tc[i].bwg_percent = 100;
		tc[i].up_to_tc_bitmap = i;
		bwg[i] = 12 + (i & 1);
	}

	printf("\nGETTING PG RX CONFIGURATION\n");
	memset(bwg, 0, sizeof(bwg));
	memset(&tc[0], 0, sizeof(tc));
	get_pg(ifname, tc, bwg, DCB_CMD_PGRX_GCFG);
	for (i = 0; i < 8; i++) {
		printf("%d: pr=%d\tbwgid=%d\tbw%%=%d\tu2t=%d\tlk%%=%d\n", i,
			tc[i].prio_type,
			tc[i].bwg_id,
			tc[i].bwg_percent,
			tc[i].up_to_tc_bitmap,
			bwg[i]);
	}

	printf("\nGETTING PERMANENT MAC: ");
	get_perm_hwaddr(ifname, mac, san_mac);
	for (i = 0; i < 5; i++)
		printf("%02x:", mac[i]);
	printf("%02x\n", mac[i]);

	printf("\nGETTING SAN MAC: ");
	for (i = 0; i < 5; i++)
		printf("%02x:", san_mac[i]);
	printf("%02x\n", san_mac[i]);

	printf("\nGETTING DCB CAPABILITIES\n");
	get_cap(ifname, &cap[0]);

	printf("\nGET NUMBER OF PG TCS\n");
	if (!get_numtcs(ifname, DCB_NUMTCS_ATTR_PG, &numtcs))
		printf("num = %d\n", numtcs);
	else	printf("not found\n");

	printf("\nGET NUMBER OF PFC TCS\n");
	if (!get_numtcs(ifname, DCB_NUMTCS_ATTR_PFC, &numtcs))
		printf("num = %d\n", numtcs);
	else	printf("not found\n");

	if (!read_only) {
		printf("\nTEST SET NUMBER OF PG TCS\n");
		if (!set_numtcs(ifname, DCB_NUMTCS_ATTR_PG, numtcs))
			printf("set passed\n");
		else	printf("error\n");

		printf("\nTEST SET NUMBER OF PFC TCS\n");
		if (!set_numtcs(ifname, DCB_NUMTCS_ATTR_PFC, numtcs))
			printf("set passed\n");
		else	printf("error\n\n");

/*	printf("set_pfc_cfg = %d\n", set_pfc_cfg(ifname, pfc)); */
/*	printf("set_rx_pg = %d\n", set_pg(ifname, tc, bwg, DCB_CMD_PGRX_SCFG));*/
/*	printf("set_hw_all = %d\n", set_hw_all(ifname)); */

		err = set_hw_bcn(ifname, &bcn_set_data, 1);
		printf("set_bcn_cfg result is %d.\n", err);

		/*set_hw_all(ifname);*/
	}

	printf("\nGETTING BCN:\n");
	if (!get_bcn(ifname, &bcn_data)) {
		for (i = 0; i < 8; i++) {
			printf("BCN RP %d: %d\n", i,
			       bcn_data.up_settings[i].rp_admin);
		}
		printf("\nBCN RP ALPHA: %f\n", bcn_data.rp_alpha);
		printf("BCN RP BETA : %f\n", bcn_data.rp_beta);
		printf("BCN RP GD   : %f\n", bcn_data.rp_gd);
		printf("BCN RP GI   : %f\n", bcn_data.rp_gi);
		printf("BCN RP TMAX : %d\n", bcn_data.rp_tmax);
		printf("BCN RP RI   : %d\n", bcn_data.rp_ri);
		printf("BCN RP TD   : %d\n", bcn_data.rp_td);
		printf("BCN RP RMIN : %d\n", bcn_data.rp_rmin);
		printf("BCN RP W    : %d\n", bcn_data.rp_w);
		printf("BCN RP RD   : %d\n", bcn_data.rp_rd);
		printf("BCN RP RU   : %d\n", bcn_data.rp_ru);
		printf("BCN RP WRTT : %d\n", bcn_data.rp_wrtt);
	} else	printf("not found\n");

#ifdef DCB_APP_DRV_IF_SUPPORTED
	if (!read_only) {
		printf("\nSETTING APP:\n");
		if (set_hw_app0(ifname, &app_data)) {
			printf("Fail to set app data.\n");
			goto err_main;
		}
	}

	printf("\nGETTING APP:\n");
	if (!get_app_cfg(ifname, &app_data)) {
		printf("APP ID TYPE: ");
		if (app_data.dcb_app_idtype)
			printf(" \t DCB_APP_IDTYPE_ETHTYPE.\n");
		else
			printf(" \t DCB_APP_IDTYPE_PORTNUM.\n");

		printf(" APP ID: 0x%0x.\n", app_data.dcb_app_id);
		printf(" APP PRIORITY: 0x%0x.\n", app_data.dcb_app_priority);
	}
	else {
		printf("GETTING APP FAILED!.\n");
	}
#endif /* DCB_APP_DRV_IF_SUPPORTED */

	if (!read_only) {
		struct ieee_ets ets = {
			.willing = 0, .ets_cap = 0x1, .cbs = 0,
			.tc_tx_bw = {25, 25, 25, 25, 0, 0, 0, 0},
			.tc_rx_bw = {0, 0, 0, 0, 25, 25, 25, 25},
			.tc_tsa = {1, 2, 3, 4, 1, 2, 3, 4},
			.prio_tc = {1, 2, 3, 4, 1, 2, 3, 4}
		};
		struct ieee_pfc pfc = {
			.pfc_cap = 0xf1, .pfc_en = 0, .mbc = 0, .delay = 0x32
		};
		struct dcb_app app = {
			.selector = 0, .priority = 4, .protocol = 0x8906
		};

		printf("\nSETTING ETS:\n");
		set_ieee(ifname, &ets, &pfc, &app);
	}

	get_ieee(ifname);

err_main:
	close(nl_sd);
	return err;
}
示例#14
0
void RedChannel::run()
{
    for (;;) {
        Lock lock(_action_lock);
        if (_action == WAIT_ACTION) {
            _action_cond.wait(lock);
        }
        int action = _action;
        _action = WAIT_ACTION;
        lock.unlock();
        switch (action) {
        case CONNECT_ACTION:
            try {
                get_client().get_sync_info(get_type(), get_id(), _sync_info);
                on_connecting();
                set_state(CONNECTING_STATE);
                ConnectionOptions con_options(_client.get_connection_options(get_type()),
                                              _client.get_port(),
                                              _client.get_sport(),
                                              _client.get_protocol(),
                                              _client.get_host_auth_options(),
                                              _client.get_connection_ciphers());
                RedChannelBase::connect(con_options, _client.get_connection_id(),
                                        _client.get_host().c_str(),
                                        _client.get_password().c_str());
                /* If automatic protocol, remember the first connect protocol type */
                if (_client.get_protocol() == 0) {
                    if (get_peer_major() == 1) {
                        _client.set_protocol(1);
                    } else {
                        /* Major is 2 or unstable high value, use 2 */
                        _client.set_protocol(2);
                    }
                }
                /* Initialize when we know the remote major version */
                if (_client.get_peer_major() == 1) {
                    _marshallers = spice_message_marshallers_get1();
                } else {
                    _marshallers = spice_message_marshallers_get();
                }
                on_connect();
                set_state(CONNECTED_STATE);
                _loop.add_socket(*this);
                _socket_in_loop = true;
                on_event();
                _loop.run();
            } catch (RedPeer::DisconnectedException&) {
                _error = SPICEC_ERROR_CODE_SUCCESS;
            } catch (Exception& e) {
                LOG_WARN("%s", e.what());
                _error = e.get_error_code();
            } catch (std::exception& e) {
                LOG_WARN("%s", e.what());
                _error = SPICEC_ERROR_CODE_ERROR;
            }
            if (_socket_in_loop) {
                _socket_in_loop = false;
                _loop.remove_socket(*this);
            }
            if (_outgoing_message) {
                _outgoing_message->release();
                _outgoing_message = NULL;
            }
            _incomming_header_pos = 0;
            if (_incomming_message) {
                _incomming_message->unref();
                _incomming_message = NULL;
            }
        case DISCONNECT_ACTION:
            close();
            on_disconnect();
            set_state(DISCONNECTED_STATE);
            _client.on_channel_disconnected(*this);
            continue;
        case QUIT_ACTION:
            set_state(TERMINATED_STATE);
            return;
        }
    }
}
示例#15
0
// abort a result that's not currently running
//
void RESULT::abort_inactive(int status) {
    if (state() >= RESULT_COMPUTE_ERROR) return;
    set_state(RESULT_ABORTED, "RESULT::abort_inactive");
    exit_status = status;
}
示例#16
0
bool densoecu::listen_denso()
{
	unsigned char rsp;
	int datalen = szrxbuf;

	if (model == wrx2002 && state == normal)
	{
		// look for 200ms pulse DSR/DTE (for Denso init sequence)

		if (!dc->is_LE_high())
		{
			for (int d = 0; d < 300; d+=10)
			{
				if (dc->is_LE_high())
					break;
				delay(10);
			}

			if (dc->is_LE_high())
			{
				l->print(log_densoecu,"LE low pulse\n");
				// correctly signalled
				set_state(bootloader_auth);
				return true;
			}
		}
	}

	if (model == wrx2002 && state == normal)
		dc->set_default_timeout(100);

	if (!dc->read_denso_rsp_varlen(&rsp,rxbuf,&datalen))
	{
		dc->set_default_timeout(3000);
		return false;
	}
	dc->set_default_timeout(3000);

	int addr;
	dump(rsp,rxbuf,datalen);

	switch(rsp)
	{
	case denso_write_ram:
		addr = byte_to_int24(rxbuf);
		l->print(log_densoecu,"denso write ram addr:%06X len:%02X\n",addr,datalen-3);
		if (addr < locrambase || addr+datalen-3 > szram+locrambase)
			respond_denso_fail();
		else
		{
			memcpy(&rom[addr-locrambase],&rxbuf[3],datalen-3);
			if (!listenmode)
				dc->write_denso_rsp(denso_rsp_write_ram,&rxbuf[3],datalen-3);
		}
		break;
	case denso_rsp_write_ram:
		addr = byte_to_int24(rxbuf);
		l->print(log_densoecu,"denso response write ram addr:%06X len:%02X\n",addr,datalen);
		break;
	case denso_reset_trouble_codes:
		l->print(log_densoecu,"denso reset trouble codesh\n");
		respond_denso_ok();
		break;
	case denso_rsp_reset_trouble_codes:
		l->print(log_densoecu,"denso response reset trouble codesh\n");
		break;
	case denso_read_param:
		l->print(log_densoecu,"denso read param %02x\n",rxbuf[0]);
		if (!listenmode)
		{
			// fake params for now
			//case param_boost:
			rxbuf[0] = 77;
			dc->write_denso_rsp(denso_rsp_read_param,rxbuf,1);
		}
		break;
	case denso_rsp_read_param:
		l->print(log_densoecu,"denso response read param %02X : %02X\n",rxbuf[0],rxbuf[1]);
		break;
	case denso_0x81:
		l->print(log_densoecu,"denso command 0x81\n");
		if (!listenmode)
		{
			rxbuf[0] = 0xEF;
			rxbuf[1] = 0x8F;
			dc->write_denso_rsp(denso_rsp_0x81,rxbuf,2);
		}
		break;
	case denso_rsp_0x81:
		l->print(log_densoecu,"denso response 0xC1 %02X %02X\n",rxbuf[0],rxbuf[1]);
		break;
	case denso_0x83:
		l->print(log_densoecu,"denso command 0x83 %02X\n",rxbuf[0]);
		if (!listenmode)
		{
			rxbuf[0] = 0x00;
			rxbuf[1] = 0x00;
			rxbuf[2] = 0xFF;
			rxbuf[3] = 0x00;
			rxbuf[4] = 0xFF;
			rxbuf[5] = 0x00;
			dc->write_denso_rsp(denso_rsp_0x83,rxbuf,6);
		}
		break;
	case denso_0x30:
		respond_denso_ok();
		break;
	case denso_0x10:
		l->print(log_densoecu,"denso reflash state\n");
		if (state == bootloader_auth)
		{
			respond_denso_ok();
			// now we should change into reflash state, 
			set_state(bootloader);
		}
		else
			respond_denso_fail();
		break;
	case denso_cmd_challenge:
		switch(rxbuf[0])
		{
		case 1: // get challenge number
			l->print(log_densoecu,"denso get challenge\n");
			if (!listenmode)
			{
				rxbuf[1] = rand() % 256;
				rxbuf[2] = rand() % 256;
				rxbuf[3] = rand() % 256;
				rxbuf[4] = rand() % 256;
				memcpy(lastchallenge,rxbuf+1,4);
				crazy_transform(lastchallenge);
				dc->write_denso_rsp(denso_rsp_challenge,rxbuf,5);
			}
			break;
		case 2: // responding to challenge
			l->print(log_densoecu,"denso respond to challenge %02X %02X %02X %02X\n",rxbuf[1],rxbuf[2],rxbuf[3],rxbuf[4]);
			if (!listenmode)
			{// test validity
				if (memcmp(lastchallenge,rxbuf+1,4) == 0)
				{
					l->print(log_densoecu,"denso challenge is correct\n");
					rxbuf[1] = 0x34;
					dc->write_denso_rsp(denso_rsp_challenge,rxbuf,2);
					set_state(bootloader_auth);
				}
				else
				{
					l->print(log_densoecu,"denso challenge is incorrect\n");
					l->print(log_densoecu,"correct response is %02X %02X %02X %02X\n",lastchallenge[0],lastchallenge[1],lastchallenge[2],lastchallenge[3]);
					respond_denso_fail();
				}
			}
			break;
		}
	case denso_rsp_challenge:
		l->print(log_densoecu,"denso response challenge\n");
		break;
	}
	lastrsp = rsp;
	return true;
}
示例#17
0
void
MrIceBlock::activate()
{
  WalkingBadguy::activate();
  set_state(ICESTATE_NORMAL);
}
示例#18
0
bool densoecu::listen_denso_bootloader()
{
	unsigned char rsp;
	int datalen = szrxbuf;

	if (!dc->read_denso_rsp_varlen(&rsp,rxbuf,&datalen))
	{
		dc->set_default_timeout(3000);
		return false;
	}
	dc->set_default_timeout(3000);

	int addr;
	dump(rsp,rxbuf,datalen);

	switch(rsp)
	{
	case denso_bootloader_cmd_write_kernel_ram:
		addr = byte_to_int24(rxbuf);
		l->print(log_densoecu,"denso write flash addr:%06X len:%02X\n",addr,datalen-3);
		if (!listenmode)
		{
		if (addr < validate_addr 
			|| addr+datalen-3 > validate_addr+validate_len 
			|| addr+datalen-3 > szram+locrambase)
				respond_denso_fail();
			else
			{
				transform_kernel_block04(rxbuf+3,datalen-3,false);
				memcpy(rom+addr,rxbuf+3,datalen-3);
				dc->write_denso_rsp(denso_bootloader_rsp_write_kernel_ram,NULL,0);
			}
		}
		break;
	case denso_bootloader_rsp_write_kernel_ram:
		addr = byte_to_int24(rxbuf);
		l->print(log_densoecu,"denso response write flash addr:%06X len:%02X\n",addr,datalen);
		break;
	case denso_bootloader_cmd_enter_kernel:
		l->print(log_densoecu,"denso enter kernel\n");
		// todo: verify flash mode

		// verify correct parameters
		if (datalen != 2 || byte_to_int16(rxbuf) != denso_bootloader_rsp_ok)
		{
			l->print(log_densoecu,"enter kernel: invalid parameters.\n");
			// this actually uses bad checksum error code
			int16_to_byte(rxbuf,denso_bootloader_rsp_error_bad_checksum);
			dc->write_denso_rsp_echocheck(denso_bootloader_rsp_error,rxbuf,2);
		}
		// verify valid kernel
		else if (bootloader_calculate_odd_checksum(rom+validate_addr,validate_len) != denso_odd_checksum)
		{
			// invalid_kernel magic number
			l->print(log_densoecu,"invalid checksum.\n");
			int16_to_byte(rxbuf,denso_bootloader_rsp_error_bad_checksum);
			dc->write_denso_rsp_echocheck(denso_bootloader_rsp_error,rxbuf,2);
		}
		else
		{

			l->print(log_densoecu,"valid kernel loaded.\n");
			int16_to_byte(rxbuf,denso_bootloader_rsp_ok);
			dc->write_denso_rsp_echocheck(denso_bootloader_rsp_enter_kernel,rxbuf,2);
			// now we should change into kernel state, 
			set_state(oecukernel);
		}
		break;	
	case denso_bootloader_rsp_enter_kernel:
		if (datalen == 2)
			l->print(log_densoecu,"denso response enter kernel: [%02X} [%02X]\n",rxbuf[0],rxbuf[1]);
		break;
	case denso_bootloader_validate_kram_addr:
		validate_addr = byte_to_int24(rxbuf);
		validate_len = byte_to_int16(&rxbuf[5]);
		l->print(log_densoecu,"denso validate flash addr:%06X len:%04X\n",validate_addr,validate_len);
		if (lastrsp != denso_0x10 && !listenmode)
		{
			rxbuf[0] = 0x84;
			dc->write_denso_rsp(denso_bootloader_rsp_validate_kram_addr,rxbuf,1);
		}
		break;
	case denso_bootloader_rsp_validate_kram_addr:
		l->print(log_densoecu,"denso response blank flash %02X\n",rxbuf[0]);
		break;
	}
	lastrsp = rsp;
	return true;
}
示例#19
0
/*
 * MAIN
 *
 * assumes the existance of getopt() to clean up the command 
 * line handling
 */
int
    main (int ac, char **av)
{
    DSS_HUGE i;
	
    o_table = 0;
    o_force = 0;
    insert_segments=0;
    delete_segments=0;
    insert_orders_segment=0;
    insert_lineitem_segment=0;
    delete_segment=0;
    o_verbose = 0;
    o_columnar = 0;
    o_set_seeds = 0;
    o_header = 0;
    o_direct = 0;
    o_scale = 1;
    flt_scale = 1.0;
    o_updates = 0;
    o_refresh = UPD_PCT;
    tdefs[ORDER].base *=
	ORDERS_PER_CUST;			/* have to do this after init */
    tdefs[LINE].base *=
	ORDERS_PER_CUST;			/* have to do this after init */
    tdefs[ORDER_LINE].base *=
	ORDERS_PER_CUST;			/* have to do this after init */
    o_fnames = 0;
    o_db_name = NULL;
    o_schema_name = NULL;
    o_gen_sql = 0;
    o_gen_rng = 0;
    o_d_path = NULL;

    o_step = 1;
    o_stepmax = 1;

	
#ifdef NO_SUPPORT
    signal (SIGINT, exit);
#endif /* NO_SUPPORT */

    process_options (ac, av);
    if (o_table == 0) {
	usage();
	fprintf(stderr, "Error: please specify -T option\n");
	exit(1);
    }
    if (o_stepmax <= 0) {
	usage();
	fprintf(stderr, "Error: invalid -N option\n");
	exit(1);
    }
    if (! (0 < o_step && o_step <= o_stepmax)) {
	usage();
	fprintf(stderr, "Error: invalid -n option\n");
	exit(1);
    }
    if (o_verbose >= 0) {
	fprintf (stderr,
		 "%s Population Generator (Version %d.%d.%d build %d)\n",
		 NAME, VERSION, RELEASE, PATCH, BUILD);
	fprintf (stderr, "Copyright %s %s\n", TPC, C_DATES);
    }
	
    load_dists ();
    /* have to do this after init */
    tdefs[NATION].base = nations.count;
    tdefs[REGION].base = regions.count;
	
    /* 
     * updates are never parallelized 
     */
    if (o_updates) {
	/* 
	 * set RNG to start generating rows beyond SF=scale
	 */
	set_state (ORDER, o_scale, o_stepmax, o_stepmax + 1, &i); 
	rowcnt = (int)(tdefs[ORDER_LINE].base / 10000 * o_scale * o_refresh);
	if (o_step > 0) {
	    /* 
	     * adjust RNG for any prior update generation
	     */
	    for (i=1; i < o_step; i++) {
		sd_order(0, rowcnt);
		sd_line(0, rowcnt);
	    }
	    upd_num = o_step - 1;
	}
	else
	    upd_num = 0;

	while (upd_num < o_updates) {
	    if (o_verbose > 0)
		fprintf (stderr,
			 "Generating update pair #%ld for %s [pid: %d]",
			 upd_num + 1, tdefs[ORDER_LINE].comment, (int)DSS_PROC);
	    insert_orders_segment=0;
	    insert_lineitem_segment=0;
	    delete_segment=0;
	    minrow = upd_num * rowcnt + 1;
	    gen_tbl (ORDER_LINE, minrow, rowcnt, upd_num + 1);
	    if (o_verbose > 0)
		fprintf (stderr, "done.\n");
	    pr_drange (ORDER_LINE, minrow, rowcnt, upd_num + 1);
	    upd_num++;
	}

	exit (0);
    }
	
    /**
     ** actual data generation section starts here
     **/
    /*
     * open database connection or set all the file names, as appropriate
     */
    if (o_fnames)
	for (i = PART; i <= REGION; i++) {
	    if (o_table & (1 << i))
		if (set_files ((int)i, -1)) {
		    fprintf (stderr, "Load aborted!\n");
		    exit (1);
		}
	}
		
    /*
     * traverse the tables, invoking the appropriate data generation routine for any to be built
     */
    for (i = PART; i <= REGION; i++) {
	if (0 == (o_table & (1 << i)))
	    continue;
		
	minrow = 1;
	if (i < NATION)
	    rowcnt = tdefs[i].base * o_scale;
	else
	    rowcnt = tdefs[i].base;
	if (o_verbose > 0)
	    fprintf (stderr, "%s data for %s [pid: %ld, step: %d]",
		     (o_validate)?"Validating":"Generating", tdefs[i].comment, (long)DSS_PROC, o_step);

	if (i < NATION) {
	    partial(i, o_step);
	}
	else {
	    gen_tbl ((int)i, minrow, rowcnt, upd_num);
	}

	if (o_verbose > 0)
	    fprintf (stderr, "done.\n");
		
	if (o_validate)
	    printf("Validation checksum for %s at %ld GB: %0x\n", 
		   tdefs[i].name, o_scale, (unsigned int) tdefs[i].vtotal);
    }
	
    return (0);
}
示例#20
0
static int bluetooth_start(struct bluetooth_data *data)
{
	char c = 'w';
	char buf[BT_SUGGESTED_BUFFER_SIZE];
	struct bt_start_stream_req *start_req = (void*) buf;
	struct bt_start_stream_rsp *start_rsp = (void*) buf;
	struct bt_new_stream_ind *streamfd_ind = (void*) buf;
	int opt_name, err, bytes;

	DBG("bluetooth_start");
	data->state = A2DP_STATE_STARTING;
	/* send start */
	memset(start_req, 0, BT_SUGGESTED_BUFFER_SIZE);
	start_req->h.type = BT_REQUEST;
	start_req->h.name = BT_START_STREAM;
	start_req->h.length = sizeof(*start_req);


	err = audioservice_send(data, &start_req->h);
	if (err < 0)
		goto error;

	start_rsp->h.length = sizeof(*start_rsp);
	err = audioservice_expect(data, &start_rsp->h, BT_START_STREAM);
	if (err < 0)
		goto error;

	streamfd_ind->h.length = sizeof(*streamfd_ind);
	err = audioservice_expect(data, &streamfd_ind->h, BT_NEW_STREAM);
	if (err < 0)
		goto error;

	data->stream.fd = bt_audio_service_get_data_fd(data->server.fd);
	if (data->stream.fd < 0) {
		ERR("bt_audio_service_get_data_fd failed, errno: %d", errno);
		err = -errno;
		goto error;
	}
	l2cap_set_flushable(data->stream.fd, 1);
	data->stream.events = POLLOUT;

	/* set our socket buffer to the size of PACKET_BUFFER_COUNT packets */
	bytes = data->link_mtu * PACKET_BUFFER_COUNT;
	setsockopt(data->stream.fd, SOL_SOCKET, SO_SNDBUF, &bytes,
			sizeof(bytes));

	data->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload) + data->sizeof_scms_t;
	data->frame_count = 0;
	data->samples = 0;
	data->nsamples = 0;
	data->seq_num = 0;
	data->frame_count = 0;
	data->next_write = 0;

	set_state(data, A2DP_STATE_STARTED);
	return 0;

error:
	/* close bluetooth connection to force reinit and reconfiguration */
	if (data->state == A2DP_STATE_STARTING) {
		bluetooth_close(data);
		/* notify client that thread is ready for next command */
		pthread_cond_signal(&data->client_wait);
        }
	return err;
}
void AIFilePicker::multiplex_impl(state_type run_state)
{
	mPluginManager->update();										// Give the plugin some CPU for it's messages.
	LLPluginClassBasic* plugin = mPluginManager->getPlugin();
	if (!plugin || plugin->isPluginExited())
	{
		// This happens when there was a problem with the plugin (ie, it crashed).
		abort();
		return;
	}
	switch (run_state)
	{
		case AIFilePicker_initialize_plugin:
		{
			if (!plugin->isPluginRunning())
			{
				yield();
				break;												// Still initializing.
			}

			// Send initialization message.
			LLPluginMessage initialization_message(LLPLUGIN_MESSAGE_CLASS_BASIC, "initialization");
			static char const* key_str[] = {
				"all_files", "sound_files", "animation_files", "image_files", "save_file_verb",
				"targa_image_files", "bitmap_image_files", "avi_movie_file", "xaf_animation_file",
				"xml_file", "raw_file", "compressed_image_files", "load_file_verb", "load_files",
				"choose_the_directory"
			};
			LLSD dictionary;
			for (int key = 0; key < sizeof(key_str) / sizeof(key_str[0]); ++key)
			{
				dictionary[key_str[key]] = LLTrans::getString(key_str[key]);
			}
			initialization_message.setValueLLSD("dictionary", dictionary);
#if LL_WINDOWS || (LL_GTK && LL_X11)
			std::ostringstream window_id_str;
#if LL_WINDOWS
			unsigned long window_id = (unsigned long)gViewerWindow->getPlatformWindow();
#else
			unsigned long window_id = LLWindowSDL::get_SDL_XWindowID();
#endif
			if (window_id != 0)
			{
				window_id_str << std::hex << "0x" << window_id;
				initialization_message.setValue("window_id", window_id_str.str());
			}
			else
			{
				LL_WARNS("Plugin") << "Couldn't get xwid to use for transient." << LL_ENDL;
			}
#endif // LL_WINDOWS || (LL_GTK && LL_X11)
			plugin->sendMessage(initialization_message);

			// Send open message.
			LLPluginMessage open_message(LLPLUGIN_MESSAGE_CLASS_BASIC, "open");
			open_message.setValue("type", (mOpenType == save) ? "save" : (mOpenType == load) ? "load" : "load_multiple");
			open_message.setValue("filter", mFilter);
			if (mOpenType == save) open_message.setValue("default", mFilename);
			open_message.setValue("folder", mFolder);
			open_message.setValue("gorgon", "block");		// Don't expect HeartBeat messages after an "open".
			plugin->sendMessage(open_message);

			set_state(AIFilePicker_plugin_running);
			break;
		}
		case AIFilePicker_plugin_running:
		{
			// Users are slow, no need to look for new messages from the plugin all too often.
			yield_ms(250);
			break;
		}
		case AIFilePicker_canceled:
		{
			mCanceled = true;
			finish();
			break;
		}
		case AIFilePicker_done:
		{
			// Store folder of first filename as context.
			AIFilePicker::store_folder(mContext, getFolder());
			finish();
			break;
		}
	}
}
示例#22
0
void multimenu_button::set_active(const bool active)
{
	if(get_active() != active) {
		set_state(active ? ENABLED : DISABLED);
	}
}
示例#23
0
static int state_initialising_cb() {
    pa_log_debug("Xen audio sink: Backend state was XenbusStateInitialising\n");
    set_state(XenbusStateInitialised);
    return 0;
}
示例#24
0
文件: window.c 项目: nfnty/bspwm
void manage_window(xcb_window_t win, rule_consequence_t *csq, int fd)
{
	monitor_t *m = mon;
	desktop_t *d = mon->desk;
	node_t *f = mon->desk->focus;

	parse_rule_consequence(fd, csq);

	if (!csq->manage) {
		free(csq->layer);
		free(csq->state);
		window_show(win);
		return;
	}

	if (csq->node_desc[0] != '\0') {
		coordinates_t ref = {m, d, f};
		coordinates_t trg = {NULL, NULL, NULL};
		if (node_from_desc(csq->node_desc, &ref, &trg) == SELECTOR_OK) {
			m = trg.monitor;
			d = trg.desktop;
			f = trg.node;
		}
	} else if (csq->desktop_desc[0] != '\0') {
		coordinates_t ref = {m, d, NULL};
		coordinates_t trg = {NULL, NULL, NULL};
		if (desktop_from_desc(csq->desktop_desc, &ref, &trg) == SELECTOR_OK) {
			m = trg.monitor;
			d = trg.desktop;
			f = trg.desktop->focus;
		}
	} else if (csq->monitor_desc[0] != '\0') {
		coordinates_t ref = {m, NULL, NULL};
		coordinates_t trg = {NULL, NULL, NULL};
		if (monitor_from_desc(csq->monitor_desc, &ref, &trg) == SELECTOR_OK) {
			m = trg.monitor;
			d = trg.monitor->desk;
			f = trg.monitor->desk->focus;
		}
	}

	if (csq->sticky) {
		m = mon;
		d = mon->desk;
		f = mon->desk->focus;
	}

	if (csq->split_dir[0] != '\0' && f != NULL) {
		direction_t dir;
		if (parse_direction(csq->split_dir, &dir)) {
			presel_dir(m, d, f, dir);
		}
	}

	if (csq->split_ratio != 0 && f != NULL) {
		presel_ratio(m, d, f, csq->split_ratio);
	}

	node_t *n = make_node(win);
	client_t *c = make_client();
	c->border_width = csq->border ? d->border_width : 0;
	n->client = c;
	initialize_client(n);
	initialize_floating_rectangle(n);

	if (c->floating_rectangle.x == 0 && c->floating_rectangle.y == 0) {
		csq->center = true;
	}

	monitor_t *mm = monitor_from_client(c);
	embrace_client(mm, c);
	adapt_geometry(&mm->rectangle, &m->rectangle, n);

	if (csq->center) {
		window_center(m, c);
	}

	snprintf(c->class_name, sizeof(c->class_name), "%s", csq->class_name);
	snprintf(c->instance_name, sizeof(c->instance_name), "%s", csq->instance_name);

	f = insert_node(m, d, n, f);
	clients_count++;

	put_status(SBSC_MASK_NODE_MANAGE, "node_manage 0x%08X 0x%08X 0x%08X 0x%08X\n", m->id, d->id, win, f!=NULL?f->id:0);

	if (f != NULL && f->client != NULL && csq->state != NULL && *(csq->state) == STATE_FLOATING) {
		c->layer = f->client->layer;
	}

	if (csq->layer != NULL) {
		c->layer = *(csq->layer);
	}

	if (csq->state != NULL) {
		set_state(m, d, n, *(csq->state));
	}

	set_hidden(m, d, n, csq->hidden);
	set_sticky(m, d, n, csq->sticky);
	set_private(m, d, n, csq->private);
	set_locked(m, d, n, csq->locked);

	arrange(m, d);

	uint32_t values[] = {CLIENT_EVENT_MASK | (focus_follows_pointer ? XCB_EVENT_MASK_ENTER_WINDOW : 0)};
	xcb_change_window_attributes(dpy, win, XCB_CW_EVENT_MASK, values);

	if (d == m->desk) {
		show_node(d, n);
	} else {
		hide_node(d, n);
	}

	if (!csq->hidden && csq->focus) {
		if (d == mon->desk || csq->follow) {
			focus_node(m, d, n);
		} else {
			activate_node(m, d, n);
		}
	} else {
		stack(d, n, false);
	}

	ewmh_set_wm_desktop(n, d);
	ewmh_update_client_list(false);
	free(csq->layer);
	free(csq->state);
}
示例#25
0
static int state_connected_cb() {
    /* The backend accepted our parameters, sweet! */
    set_state(XenbusStateConnected);
    pa_log_debug("Xen audio sink: Backend state was XenbusStateConnected\n");
    return NEGOTIATION_OK;
}
示例#26
0
文件: dialog.c 项目: natib/belle-sip
/*
 * return 0 if message should be delivered to the next listener, otherwise, its a retransmision, just keep it
 * */
int belle_sip_dialog_update(belle_sip_dialog_t *obj, belle_sip_transaction_t* transaction, int as_uas){
	int is_retransmition=FALSE;
	int delete_dialog=FALSE;
	belle_sip_request_t *req=belle_sip_transaction_get_request(transaction);
	belle_sip_response_t *resp=belle_sip_transaction_get_response(transaction);
	int code=-1;

	belle_sip_message("Dialog [%p]: now updated by transaction [%p].",obj, transaction);
	
	belle_sip_object_ref(transaction);
	if (obj->last_transaction) belle_sip_object_unref(obj->last_transaction);
	obj->last_transaction=transaction;
	
	if (!as_uas){
		belle_sip_header_privacy_t *privacy_header=belle_sip_message_get_header_by_type(req,belle_sip_header_privacy_t);
		SET_OBJECT_PROPERTY(obj,privacy,privacy_header);
	}
	
	if (!resp)
		return 0;


	/*first update local/remote cseq*/
	if (as_uas) {
		belle_sip_header_cseq_t* cseq=belle_sip_message_get_header_by_type(BELLE_SIP_MESSAGE(req),belle_sip_header_cseq_t);
		obj->remote_cseq=belle_sip_header_cseq_get_seq_number(cseq);
	}

	code=belle_sip_response_get_status_code(resp);
	switch (obj->state){
		case BELLE_SIP_DIALOG_NULL:
			/*alway establish a dialog*/
			if (code>100 && code<300 && (strcmp(belle_sip_request_get_method(req),"INVITE")==0 || strcmp(belle_sip_request_get_method(req),"SUBSCRIBE")==0)) {
				belle_sip_dialog_establish(obj,req,resp);
				if (code<200){
					set_state(obj,BELLE_SIP_DIALOG_EARLY);
					break;
				}/* no break  for code >200 because need to call belle_sip_dialog_establish_full*/
			}/* no break*/
		case BELLE_SIP_DIALOG_EARLY:
			/*don't terminate dialog for UPDATE*/
			if (code>=300 && (strcmp(belle_sip_request_get_method(req),"INVITE")==0 || strcmp(belle_sip_request_get_method(req),"SUBSCRIBE")==0)) {
				/*12.3 Termination of a Dialog
			   	   Independent of the method, if a request outside of a dialog generates
			   	   a non-2xx final response, any early dialogs created through
			   	   provisional responses to that request are terminated.  The mechanism
			   	   for terminating confirmed dialogs is method specific.*/
					belle_sip_dialog_delete(obj);
					break;
			}
			if (code>=200 && code<300 && (strcmp(belle_sip_request_get_method(req),"INVITE")==0 || strcmp(belle_sip_request_get_method(req),"SUBSCRIBE")==0))
				belle_sip_dialog_establish_full(obj,req,resp);
			break;
		case BELLE_SIP_DIALOG_CONFIRMED:
			code=belle_sip_response_get_status_code(resp);
			if (strcmp(belle_sip_request_get_method(req),"INVITE")==0){
				if (code>=200 && code<300){
					/*refresh the remote_target*/
					belle_sip_header_contact_t *ct;
					if (as_uas){
						ct=belle_sip_message_get_header_by_type(req,belle_sip_header_contact_t);

					}else{
						set_last_out_invite(obj,req);
						ct=belle_sip_message_get_header_by_type(resp,belle_sip_header_contact_t);
					}
					if (ct){
						belle_sip_object_unref(obj->remote_target);
						obj->remote_target=(belle_sip_header_address_t*)belle_sip_object_ref(ct);
					}
					/*handle possible retransmission of 200Ok */
					if (!as_uas && (is_retransmition=(belle_sip_dialog_handle_200Ok(obj,resp)==0))) {
						return is_retransmition;
					} else {
						obj->needs_ack=TRUE; /*REINVITE case, ack needed by both uas and uac*/
					}
				}else if (code>=300){
					/*final response, ack will be automatically sent by transaction layer*/
					obj->needs_ack=FALSE;
				}
			} else if (strcmp(belle_sip_request_get_method(req),"BYE")==0 && (/*(*/code>=200 /*&& code<300) || code==481 || code==408*/)){
				/*15.1.1 UAC Behavior

				   A BYE request is constructed as would any other request within a
				   dialog, as described in Section 12.

				   Once the BYE is constructed, the UAC core creates a new non-INVITE
				   client transaction, and passes it the BYE request.  The UAC MUST
				   consider the session terminated (and therefore stop sending or
				   listening for media) as soon as the BYE request is passed to the
				   client transaction.  If the response for the BYE is a 481
				   (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no
				   response at all is received for the BYE (that is, a timeout is
				   returned by the client transaction), the UAC MUST consider the
				   session and the dialog terminated. */
				/*what should we do with other reponse >300 ?? */
				obj->needs_ack=FALSE; /*no longuer need ACK*/
				if (obj->terminate_on_bye) delete_dialog=TRUE;
			}
		break;
		case BELLE_SIP_DIALOG_TERMINATED:
			/*ignore*/
		break;
	}
	if (delete_dialog) belle_sip_dialog_delete(obj);
	else {
		belle_sip_dialog_process_queue(obj);
	}
	return 0;
}
 /*virtual*/ void initialize_impl(void) { set_state(UpdateItem_idle); }
示例#28
0
// parse a <result> element from state file
//
int RESULT::parse_state(XML_PARSER& xp) {
    FILE_REF file_ref;

    clear();
    while (!xp.get_tag()) {
        if (xp.match_tag("/result")) {
            // set state to something reasonable in case of bad state file
            //
            if (got_server_ack || ready_to_report) {
                switch (state()) {
                case RESULT_NEW:
                case RESULT_FILES_DOWNLOADING:
                case RESULT_FILES_DOWNLOADED:
                case RESULT_FILES_UPLOADING:
                    set_state(RESULT_FILES_UPLOADED, "RESULT::parse_state");
                    break;
                }
            }
            return 0;
        }
        if (xp.parse_str("name", name, sizeof(name))) continue;
        if (xp.parse_str("wu_name", wu_name, sizeof(wu_name))) continue;
        if (xp.parse_double("received_time", received_time)) continue;
        if (xp.parse_double("report_deadline", report_deadline)) {
            continue;
        }
        if (xp.match_tag("file_ref")) {
            file_ref.parse(xp);
#ifndef SIM
            output_files.push_back(file_ref);
#endif
            continue;
        }
        if (xp.parse_double("final_cpu_time", final_cpu_time)) continue;
        if (xp.parse_double("final_elapsed_time", final_elapsed_time)) continue;
        if (xp.parse_double("final_peak_working_set_size", final_peak_working_set_size)) continue;
        if (xp.parse_double("final_peak_swap_size", final_peak_swap_size)) continue;
        if (xp.parse_double("final_peak_disk_usage", final_peak_disk_usage)) continue;
        if (xp.parse_double("final_bytes_sent", final_bytes_sent)) continue;
        if (xp.parse_double("final_bytes_received", final_bytes_received)) continue;
        if (xp.parse_int("exit_status", exit_status)) continue;
        if (xp.parse_bool("got_server_ack", got_server_ack)) continue;
        if (xp.parse_bool("ready_to_report", ready_to_report)) continue;
        if (xp.parse_double("completed_time", completed_time)) continue;
        if (xp.parse_bool("suspended_via_gui", suspended_via_gui)) continue;
        if (xp.parse_bool("report_immediately", report_immediately)) continue;
        if (xp.parse_int("state", _state)) continue;
        if (xp.parse_string("stderr_out", stderr_out)) continue;
        if (xp.parse_double("fpops_per_cpu_sec", fpops_per_cpu_sec)) continue;
        if (xp.parse_double("fpops_cumulative", fpops_cumulative)) continue;
        if (xp.parse_double("intops_per_cpu_sec", intops_per_cpu_sec)) continue;
        if (xp.parse_double("intops_cumulative", intops_cumulative)) continue;
        if (xp.parse_str("platform", platform, sizeof(platform))) continue;
        if (xp.parse_str("plan_class", plan_class, sizeof(plan_class))) continue;
        if (xp.parse_int("version_num", version_num)) continue;
        if (log_flags.unparsed_xml) {
            msg_printf(0, MSG_INFO,
                "[unparsed_xml] RESULT::parse(): unrecognized: %s\n",
                xp.parsed_tag
            );
        }
        xp.skip_unexpected();
    }
    return ERR_XML_PARSE;
}
示例#29
0
	/** Inherited from tcontrol. */
	void set_active(const bool active)
		{ if(get_active() != active) set_state(active ? ENABLED : DISABLED); }
示例#30
0
void reset_discover_state()
{
    discovered_seq = 0;
    set_state(DISCOVER_IDLE);
}