コード例 #1
0
ファイル: msg.c プロジェクト: saschaefer/mdadm-deb-pkg
int receive_message(int fd, struct metadata_update *msg, int tmo)
{
	__u32 magic;
	__s32 len;
	int rv;

	rv = recv_buf(fd, &magic, 4, tmo);
	if (rv < 0 || magic != start_magic)
		return -1;
	rv = recv_buf(fd, &len, 4, tmo);
	if (rv < 0 || len > MSG_MAX_LEN)
		return -1;
	if (len > 0) {
		msg->buf = malloc(len);
		if (msg->buf == NULL)
			return -1;
		rv = recv_buf(fd, msg->buf, len, tmo);
		if (rv < 0) {
			free(msg->buf);
			return -1;
		}
	} else
		msg->buf = NULL;
	rv = recv_buf(fd, &magic, 4, tmo);
	if (rv < 0 || magic != end_magic) {
		free(msg->buf);
		return -1;
	}
	msg->len = len;
	return 0;
}
コード例 #2
0
ファイル: server.c プロジェクト: duansy2002/Linux-C
void child_main(int fd_client)
{
    int recv_len;
    recv_buf(fd_client,(char*)&recv_len,4);//length
    char filename[128]="";
    recv_buf(fd_client,filename,recv_len);
    printf("file :%s\n",filename);
    int fpsend = open(filename,O_RDONLY);
    if(fpsend == -1)
    {
        char nofile[128]="no file\n";
        int lenit = strlen(nofile);
        send(fd_client,(char*)&lenit,4,0);
        send_buf(fd_client,nofile,lenit);
        return;
    }
    char msg[1024];
    int sendlen;
    while(memset(msg,0,1023),sendlen = read(fpsend,msg,1024)!=0)
    {
        send(fd_client,(char *)&sendlen,4,0);
        send_buf(fd_client,msg,sendlen);
    }
    //send 0 to client?
}
コード例 #3
0
ファイル: mtcp.c プロジェクト: vjoel/mtcp
ssize_t mtcp_recv_message(mtcp_state *pmts, void *buf, size_t len)
{
    int         blocking;
    ssize_t     result;
    
    blocking = mtcp_get_block_state(pmts);
    if (blocking < 0) {
        return blocking;
    }
    
    // make sure we know how long the message is
    if (!pmts->msglen) {
        // try to recv the 32-bit length field
        result = recv_buf(pmts->sock, pmts->lenbuf, &pmts->lenbufpos, 4, blocking);
        if (result <= 0) {
            return result;
        }
        pmts->msglen = ntohl(*(uint32_t*)pmts->lenbuf);
    }
        
    if (pmts->msglen > len || pmts->msglen <= 0) {
        errno = EMSGSIZE;
        return -1;
    }
    
    // try to recv the message itself
    result = recv_buf(pmts->sock, buf, &pmts->bufpos, pmts->msglen, blocking);
    return result;
}
コード例 #4
0
ファイル: do_gets.c プロジェクト: jiangp/Linux-FTP
//do_gets
void do_gets(int fd_client, int role)
{
	if(role == 3){
		return ;
	}
	else{
		struct stat mystat;
		int send_len;
		char file_name[256] = "0";

		memset(&file_name, 0 , 256);
		recv_buf(fd_client, (char*)&send_len, 4);
		recv_buf(fd_client, file_name, send_len);

		file_name[strlen(file_name) - 1] = '\0';

		lstat(file_name, &mystat);
		if(S_ISDIR(mystat.st_mode)){
			send(fd_client, "dir", 8, 0);
			downDir(fd_client, file_name);		
		}
		else{
			downFile(fd_client, file_name);
		}

		printf("send complient!\n");
	}
}
コード例 #5
0
ファイル: ft2232h_23k256.c プロジェクト: JHJB/opendous
uint8_t SPI_SRAM_23K256_Init(struct ftdi_context *ftdi)
{
    char buf[16];

    // 23K256 Write Status to Disable HOLD

    // enable Chip Select signal
    buf[0] = SET_BITS_LOW;
    buf[1] = 0x00; // 0x00 = 0b00000000 ==> CS=Low
    buf[2] = 0x0B; // 0x0B = 0b00001011 ==> SK,DO,CS=Output

    // MPSSE command to clock data out on +ve edge, in on -ve edge
    buf[3] = 0x34;
    buf[4] = 0x01; // sending two bytes, command and data
    buf[5] = 0x00;
    buf[6] = 0x01; // Write Status byte to
    buf[7] = 0x01; // 0x01 ==> Byte Mode with Hold Pin Disabled

    // disable Chip Select signal
    buf[8] = SET_BITS_LOW;
    buf[9] = 0x08; // 0x08 = 0b00001000 ==> CS=High
    buf[10]= 0x0B; // 0x0B = 0b00001011 ==> SK,DO,CS=Output
    send_buf(ftdi, buf, 11);
    recv_buf(ftdi, buf, 1); // only one byte is read back

    sleep(0.1);

    // 23K256 Read STATUS

    // enable Chip Select signal
    buf[0] = SET_BITS_LOW;
    buf[1] = 0x00; // 0x08 = 0b00000000 ==> CS=Low
    buf[2] = 0x0B; // 0x0B = 0b00001011 ==> SK,DO,CS=Output

    // MPSSE command to clock data out on +ve edge, in on -ve edge
    buf[3] = 0x34;
    buf[4] = 0x01; // sending two bytes, command and data
    buf[5] = 0x00;
    buf[6] = 0x05; // read Status byte
    buf[7] = 0xFF; // force clocking in order to read byte by sending a byte

    // disable Chip Select signal
    buf[8] = SET_BITS_LOW;
    buf[9] = 0x08; // 0x08 = 0b00001000 ==> CS=High
    buf[10]= 0x0B; // 0x0B = 0b00001011 ==> SK,DO,CS=Output
    send_buf(ftdi, buf, 11);
    recv_buf(ftdi, buf, 3);

    if (DEBUG_LEVEL) {
        printf("Status Byte = 0x%02X\n\n", (uint8_t)buf[2]);
    }

    return (uint8_t)buf[2];
}
コード例 #6
0
ファイル: ft2232h_23k256.c プロジェクト: JHJB/opendous
void SPI_SRAM_23K256_Write_Byte(struct ftdi_context *ftdi, uint16_t address, uint8_t data)
{
    char buf[16];
    uint8_t bytesToTransfer = 4;

    // enable Chip Select signal
    buf[0] = SET_BITS_LOW;
    buf[1] = 0x00; // 0x00 = 0b00000000 ==> CS=Low
    buf[2] = 0x0B; // 0x0B = 0b00001011 ==> SK,DO,CS=Output

    // MPSSE command to clock data out on +ve edge, in on -ve edge
    buf[3] = 0x34;
    buf[4] = (bytesToTransfer - 1); // will be transferring 4 bytes so length=3
    buf[5] = 0x00;
    buf[6] = 0x02; // write
    buf[7] = (uint8_t)(address >> 8); // address high byte
    buf[8] = (uint8_t)(address); // address low byte
    buf[9] = data; // force clocking in order to read byte by sending a byte

    // disable Chip Select signal
    buf[10]= SET_BITS_LOW;
    buf[11]= 0x08; // 0x08 = 0b00001000 ==> CS=High
    buf[12]= 0x0B; // 0x0B = 0b00001011 ==> SK,DO,CS=Output
    send_buf(ftdi, buf, 13);
    recv_buf(ftdi, buf, bytesToTransfer); // same as number that will be transferred

    if (DEBUG_LEVEL) {
        printf("Byte written to address 0x%04X = 0x%02X\n\n", address, data);
    }
}
コード例 #7
0
ファイル: rcopy.c プロジェクト: dlee104/UDPConnection
STATE filename(char *fname, int32_t buf_size)
{
    uint8_t packet[MAX_LEN];
    uint8_t buf[MAX_LEN];
    uint8_t flag = 0;
    int32_t seq_num = 0;
    int32_t fname_len = strlen(fname) + 1;
    int32_t recv_check = 0;

    memcpy(buf, &buf_size, 4);
    memcpy(&buf[4], fname, fname_len);

    send_buf(buf, fname_len + 4, &server, FNAME, 0, packet);

    if (select_call(server.sk_num, 1, 0, NOT_NULL) == 1) {
        recv_check = recv_buf(packet, 1000, server.sk_num, &server, &flag, &seq_num);

        /* check for bit flip ... if so, send the file name again */
        if (recv_check == CRC_ERROR)
            return FILENAME;

        if (flag == FNAME_BAD)
        {
            printf("File %s already exists and is write-protected\n", fname);
            return DONE;
        }

        return FILE_OK;
    }
    return FILENAME;
}
コード例 #8
0
ファイル: rcopy.c プロジェクト: dlee104/UDPConnection
STATE wait_on_ack()
{
    static int32_t send_count = 0;
    uint32_t crc_check = 0;
    uint8_t buf[MAX_LEN];
    int32_t len = 1000;
    uint8_t flag = 0;
    int32_t seq_num = 0;

    send_count++;
    if (send_count > 5)
    {
        printf("Sent data 5 times, no ACK, client session terminated\n");
        return(DONE);
    }

    if (select_call(server.sk_num, 1, 0, NOT_NULL) != 1)
    {
        return (TIMEOUT_ON_ACK);
    }

    crc_check = recv_buf(buf, len, server.sk_num, &server, &flag, &seq_num);

    if (crc_check == CRC_ERROR)
        return WAIT_ON_ACK;

    if (flag != ACK)
    {
        printf("In wait_on_ack but its not an ACK flag (this should never happen) is: %d\n", flag);
        exit(-1);
    }
    /* ack is good so reset count and then go send some more data */
    send_count = 0;
    return SEND_DATA;
}
コード例 #9
0
ファイル: bitonicsort.hpp プロジェクト: eipi10ydz/mxx
void bitonic_split(_Iterator begin, _Iterator end, _Compare comp, const mxx::comm& comm, int partner, int dir) {
    typedef typename std::iterator_traits<_Iterator>::value_type T;
    size_t np = std::distance(begin, end);
    //std::cout << "[Rank " << comm.rank() << "]: split with partner= " << partner << ", dir=" << dir << std::endl;
    std::vector<T> recv_buf(np);
    std::vector<T> merge_buf(np);

    // send/recv
    mxx::datatype dt = mxx::get_datatype<T>();
    MPI_Sendrecv(&*begin, np, dt.type(), partner, 0,
                 &recv_buf[0], np, dt.type(), partner, 0, comm, MPI_STATUS_IGNORE);

    // merge in `dir` direction into merge buffer
    if ((dir == asc && partner > comm.rank()) || (dir == desc && partner < comm.rank())) {
        // forward merge and keep the `np` smaller elements
        _Iterator l = begin;
        typename std::vector<T>::iterator r = recv_buf.begin();
        typename std::vector<T>::iterator o = merge_buf.begin();

        for (size_t i = 0; i < np; ++i) {
            if (comp(*l, *r)) {
                *o = *l;
                ++o;
                ++l;
            } else {
                *o = *r;
                ++o;
                ++r;
            }
        }
    } else {
        // backward merge and keep the `np` larger elements
        _Iterator l = begin+np-1;
        typename std::vector<T>::iterator r = recv_buf.begin()+np-1;
        typename std::vector<T>::iterator o = merge_buf.begin()+np-1;

        for (size_t i = 0; i < np; ++i) {
            if (comp(*l, *r)) {
                *o = *r;
                --o;
                --r;
            } else {
                *o = *l;
                --o;
                --l;
            }
        }
    }
    // copy results into local buffer
    std::copy(merge_buf.begin(), merge_buf.end(), begin);
}
コード例 #10
0
ファイル: rcopy.c プロジェクト: jtdreisb/networks
STATE recv_eof(Window *window, int output_fd)
{
	uint8_t flag = 0;
	int32_t data_len = 0;
	uint8_t data_buf[MAX_PACKET_LEN];
	uint32_t seq_num = nextOpenSequenceNumber(window);

	send_ack(seq_num);
	// Drain the packet queue
	while (select_call(server.socket_num, 1, 0, NOT_NULL) == 1) {
		data_len = recv_buf(data_buf, MAX_PACKET_LEN, server.socket_num, &server, &flag, &seq_num);
		return STATE_EOF;
	}

	printf("File Transfer Complete\n");
	return STATE_DONE;
}
コード例 #11
0
ファイル: RDMACMSocket.cpp プロジェクト: nao23/ramp-with-rdma
void RDMACMSocket::setup_verbs_buf() {
        
    this->verbs_buf = Buffer::allocate(PACKET_SIZE * PACKET_WINDOW_SIZE * 2);

    this->verbs_mr = rdma_reg_msgs(this->client_id, this->verbs_buf.addr, this->verbs_buf.size);
    if (this->verbs_mr == NULL) {
	this->verbs_buf.free();
        rdma_destroy_ep(this->client_id);
	perror("rdma_reg_msgs");
	exit(1);
    }

    char* send_buf_begin = this->verbs_buf.addr + PACKET_SIZE * PACKET_WINDOW_SIZE;    
    for (int i = 0; i < PACKET_WINDOW_SIZE; ++i) {
	Buffer recv_buf(this->verbs_buf.addr + i * PACKET_SIZE, PACKET_SIZE);
	post_recv(recv_buf);
	Buffer send_buf(send_buf_begin + i * PACKET_SIZE, PACKET_SIZE);
       	send_bufs.push_back(send_buf);
    }
}
コード例 #12
0
ファイル: rcopy.c プロジェクト: jtdreisb/networks
STATE filename(char *fname, int32_t buf_size, int32_t window_size)
{
	uint8_t buf[MAX_PACKET_LEN];
	uint8_t flag = 0;
	uint32_t seq_num = 0;
	int32_t fname_len = strlen(fname) + 1;
	int32_t recv_check = 0;

	buf_size = htonl(buf_size);
	memcpy(buf, &buf_size, 4);
	window_size = htonl(window_size);
	memcpy(&buf[4], &window_size, 4);
	memcpy(&buf[8], fname, fname_len);

	send_buf(buf, fname_len + 8, &server, FLAG_FILENAME_REQ, 0);

	if (select_call(server.socket_num, 1, 0, NOT_NULL) == 1) {
		recv_check = recv_buf(buf, MAX_PACKET_LEN, server.socket_num, &server, &flag, &seq_num);

		if (recv_check == CRC_ERROR) {
			return STATE_FILENAME;
		}

		switch (flag) {
			case FLAG_FILENAME_RESP_OK:
				return STATE_FILE_OK;
				break;
			case FLAG_FILENAME_RESP_BAD:
				printf("File (%s) not found on server\n", fname);
				exit(1);
				break;
			default:
				break;
		}
	}

	return STATE_FILENAME;
}
void tweet_server(void *q)
{

    char *request, *reply, *format, *query;
    th_args_dt *args = (th_args_dt *)q;

    tweet_req_dt *tweet_req = (tweet_req_dt *)malloc(sizeof(tweet_req_dt));

    tweet_resp_dt *result;
    /*receive buffer*/
    pthread_mutex_lock(&args->th_mutex);
    request = recv_buf(args->sock);
    pthread_mutex_unlock(&args->th_mutex);
    printf("Request received: %s\n",request);

    char *dup = (char *)malloc(strlen(request));
    strcpy(dup,request);
    char *tmp;
    tmp = strtok(dup," ");
    tweet_req->command = tmp;
    tmp = strtok(NULL," ");
    tweet_req->handler = atoi(tmp);
    tmp = strtok(NULL,"\r\n\r\n");
    tweet_req->datalength = atoi(tmp);
    tmp = strtok(NULL,"\0");
    tmp = tmp+3*sizeof(char);
    tweet_req->data = tmp;
    //printf("Command:%sHandler:%dDatalength:%ldData:%s\n",tweet_req->command, tweet_req->handler, tweet_req->datalength, tweet_req->data);


    /*LOGIN and SIGNUP request handling*/
    if (tweet_req->handler <= 0) {//if the user is asking for login request
        char *tmp1, *username, *password;
        tmp1 = strtok(tweet_req->data," ");
        username = tmp1;
        tmp1 = strtok(NULL,"\0");
        password = tmp1;
        printf("Received username: %s & password: %s\n",username,password);

        if (strcmp(tweet_req->command,"LOGIN") == 0) {
            printf("Login Requested. Authenticating '%s'...\n",username);
            pthread_mutex_lock(&args->th_mutex);
            result = login(args->conn,username,password);
            pthread_mutex_unlock(&args->th_mutex);
            //printf("%s %d %ld %s\n", result->command,result->st_code, result->dlength,result->data);
        }
        else if (strcmp(tweet_req->command,"SIGNUP") == 0) {
            printf("Signup Requested. Creating user account for '%s'...\n",username);
            pthread_mutex_lock(&args->th_mutex);
            result = signup(args->conn,username,password);
            pthread_mutex_unlock(&args->th_mutex);
            //printf("%s %d %ld %s\n", result->command,result->st_code, result->dlength,result->data);
        }
    }
    /*other Request Handling*/
    else {
        if (strcmp(tweet_req->command,"LOGOUT") == 0) {
            printf("LOGOUT Requested. Closing session...");
            pthread_mutex_lock(&args->th_mutex);
            result = logout(args->conn,tweet_req->handler);
            pthread_mutex_unlock(&args->th_mutex);
            //printf("%s %d %ld %s\n", result->command,result->st_code, result->dlength,result->data);
        }
        else {
            if (strcmp(tweet_req->command,"FOLLOW") == 0) {
                printf("FOLLOW requested");
                format = "INSERT INTO follow_tb VALUES((SELECT user_id FROM session WHERE ssid= %d),(SELECT user_id FROM users WHERE user_name='%s'))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler,tweet_req->data);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"UNFOLLOW") == 0) {
                printf("UNFOLLOW requested");
                format = "DELETE FROM follow_tb WHERE follower= (SELECT user_id FROM session WHERE ssid=%d) AND following=(SELECT user_id FROM users WHERE user_name=('%s'))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler,tweet_req->data);
                //result = process_query(args->conn, tweet_req->command, query);
            }

            else if (strcmp(tweet_req->command,"FOLLOWERS") == 0) {
                printf("FOLLOWERS requested");
                format = "SELECT user_name FROM users LEFT JOIN follow_tb ON users.user_id=follow_tb.follower WHERE follow_tb.following=(SELECT user_id FROM session WHERE ssid=(%d))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"FOLLOWING") == 0) {
                printf("FOLLOWING requested");
                format = "SELECT user_name FROM users LEFT JOIN follow_tb ON users.user_id=follow_tb.following WHERE follow_tb.follower=(SELECT user_id FROM session WHERE ssid=(%d))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"TWEET") == 0) {
                printf("TWEET requested");
                format = "INSERT INTO tweets(tweet_text,user_id) VALUES ('%s',(SELECT user_id FROM session WHERE ssid=%d))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->data,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"UNTWEET") == 0) {
                printf("UNTWEET requested");
                format = "DELETE FROM tweets WHERE tweet_id=%d AND user_id=(SELECT user_id FROM session WHERE ssid=%d)";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,atoi(tweet_req->data),tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"ALLTWEETS") == 0) {
                printf("ALLTWEETS requested");
                format = "SELECT tweet_text,tweet_id FROM tweets LEFT JOIN follow_tb ON tweets.user_id = follow_tb.following \
WHERE follow_tb.follower= (SELECT user_id FROM session WHERE ssid=%d) \
UNION SELECT tweet_text,tweet_id FROM tweets WHERE user_id=(SELECT user_id FROM session WHERE ssid=%d)";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"MYTWEETS") == 0) {
                printf("MYTWEETS requested");
                format = "SELECT tweet_text,tweet_id FROM tweets WHERE user_id IN (SELECT user_id FROM session WHERE ssid=%d) ORDER BY time_created DESC";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }

            pthread_mutex_lock(&args->th_mutex);
            printf("Query:%s\n",query);
            result = process_query(args->conn, tweet_req->command, query);
            pthread_mutex_unlock(&args->th_mutex);
            free(query);
        }
コード例 #14
0
ファイル: rkflashtool.c プロジェクト: 33d/rkflashtool
int main(int argc, char **argv) {
    const struct t_pid *ppid = pidtab;
    int offset = 0, size = 0;
    char action;

    info("rkflashtool v%d.%d\n", RKFLASHTOOL_VERSION_MAJOR,
                                 RKFLASHTOOL_VERSION_MINOR);
    
    NEXT; if (!argc) usage();

    action = **argv; NEXT;

    switch(action) {
    case 'b':
    case 'l':
        if (argc) usage(); 
        break;
    case 'e':
    case 'r': 
    case 'w': 
    case 'm':
    case 'i':
        if (argc != 2) usage();
        offset = strtoul(argv[0], NULL, 0);
        size   = strtoul(argv[1], NULL, 0);
        break;
    case 'p':
        if (argc) usage();
        offset = 0;
        size   = 1024;
        break;
    default:
        usage();
    }

    /* Initialize libusb */
    
    if (libusb_init(&c)) fatal("cannot init libusb\n");

    libusb_set_debug(c, 3);
    
    /* Detect connected RockChip device */
    
    while ( !h && ppid->pid) {
        h = libusb_open_device_with_vid_pid(c, 0x2207, ppid->pid);
        if (h) {
            info("Detected %s...\n", ppid->name);
            break;
        }
        ppid++;
    } 
    if (!h) fatal("cannot open device\n");

    /* Connect to device */
    
    if (libusb_kernel_driver_active(h, 0) == 1) {
        info("kernel driver active\n");
        if (!libusb_detach_kernel_driver(h, 0))
            info("driver detached\n");
    }

    if (libusb_claim_interface(h, 0) < 0)  
        fatal("cannot claim interface\n");
    info("interface claimed\n");

    /* Initialize bootloader interface */

    send_cmd(RKFT_CMD_TESTUNITREADY, 0, 0);
    recv_res();
    usleep(20*1000);

    /* Check and execute command */

    switch(action) {
    case 'b':   /* Reboot device */
        info("rebooting device...\n");
        send_cmd(RKFT_CMD_RESETDEVICE, 0, 0);
        recv_res();
        break;
    case 'r':   /* Read FLASH */
        while (size > 0) {
            info("reading flash memory at offset 0x%08x\n", offset);

            send_cmd(RKFT_CMD_READLBA, offset, RKFT_OFF_INCR);
            recv_buf(RKFT_BLOCKSIZE);
            recv_res();

            if (write(1, buf, RKFT_BLOCKSIZE) <= 0)
                fatal("Write error! Disk full?\n");
            
            offset += RKFT_OFF_INCR;
            size   -= RKFT_OFF_INCR;
        }
        break;
    case 'w':   /* Write FLASH */
        while (size > 0) {
            info("writing flash memory at offset 0x%08x\n", offset);

            if (read(0, buf, RKFT_BLOCKSIZE) <= 0)
                fatal("premature end-of-file reached.\n");

            send_cmd(RKFT_CMD_WRITELBA, offset, RKFT_OFF_INCR);
            send_buf(RKFT_BLOCKSIZE);
            recv_res();

            offset += RKFT_OFF_INCR;
            size   -= RKFT_OFF_INCR;
        }
        break;
    case 'p':   /* Retreive parameters */
        {
            uint32_t *p = (uint32_t*)buf+1;

            info("reading parameters at offset 0x%08x\n", offset);

            send_cmd(RKFT_CMD_READLBA, offset, RKFT_OFF_INCR);
            recv_buf(RKFT_BLOCKSIZE);
            recv_res();
            size = *p;
            info("size:  0x%08x\n", size);

            if (write(1, &buf[8], size) <= 0)
                fatal("Write error! Disk full?\n");
        }
        break;
    case 'l':   /* Retreive flashinfo */
        {
            info("reading parameters at offset 0x%08x\n", offset);

            send_cmd(RKFT_CMD_READFLASHINFO, offset, RKFT_OFF_INCR);
            recv_buf(RKFT_FLASHINFO_SIZE);
            recv_res();

            if (write(1, buf, RKFT_FLASHINFO_SIZE) <= 0)
                fatal("Write error! Disk full?\n");
        }
        break;
    case 'm':   /* Read RAM */
        while (size > 0) {
            int sizeRead = size > RKFT_MEM_INCR ? RKFT_MEM_INCR : size;
            info("reading memory at offset 0x%08x size %x\n", offset, sizeRead);

            send_cmd(RKFT_CMD_READSDRAM, offset-0x60000000, sizeRead);
            recv_buf(sizeRead);
            recv_res();

            if (write(1, buf, sizeRead) <= 0)
                fatal("Write error! Disk full?\n");

            offset += sizeRead;
            size -= sizeRead;
        }
        break;
    case 'i':   /* Read IDB */
        while (size > 0) {
            int sizeRead = size > RKFT_IDB_INCR ? RKFT_IDB_INCR : size;
            info("reading IDB flash memory at offset 0x%08x\n", offset);
             
            send_cmd(RKFT_CMD_READSECTOR, offset, sizeRead);
            recv_buf(RKFT_IDB_BLOCKSIZE * sizeRead);
            recv_res();
             
            if (write(1, buf, RKFT_IDB_BLOCKSIZE * sizeRead) <= 0)
                fatal("Write error! Disk full?\n");

            offset += sizeRead;
            size -= sizeRead;
        }
        break;
    case 'e':   /* Erase flash */
        memset(buf, 0xff, RKFT_BLOCKSIZE);
        while (size > 0) {
                info("erasing flash memory at offset 0x%08x\n", offset);

                send_cmd(RKFT_CMD_WRITELBA, offset, RKFT_OFF_INCR);
                send_buf(RKFT_BLOCKSIZE);
                recv_res();

                offset += RKFT_OFF_INCR;
                size   -= RKFT_OFF_INCR;
        }
        break;
    default:
        break;
    }

    /* Disconnect and close all interfaces */

    libusb_release_interface(h, 0);
    libusb_close(h);
    libusb_exit(c);
    return 0;
}
コード例 #15
0
ファイル: rkflashtool.c プロジェクト: killerkink/rkflashtool
int main(int argc, char **argv) {
    libusb_context *c;
    libusb_device_handle *h;
    int offset = 0, size = 0;
    char action;

    NEXT; if (!argc) usage();

    action = **argv; NEXT;

    switch(action) {
    case 'b':
        if (argc) usage();
        break;
    case 'e': case 'r': case 'w':
        if (argc!=2) usage();
        offset = strtoul(argv[0], NULL, 0);
        size   = strtoul(argv[1], NULL, 0);
        break;
    case 'v': case 'V':
        printf("rkflashtool version %d.%d\n",
               RKFLASHTOOL_VER_MAJOR, RKFLASHTOOL_VER_MINOR);
        exit(0);
        break;
    default:
        usage();
    }

    if (libusb_init(&c)) fatal("cannot init libusb\n");

    libusb_set_debug(c, 3);

    if (!(h = libusb_open_device_with_vid_pid(c, 0x2207, 0x290a)))
        if (!(h = libusb_open_device_with_vid_pid(c, 0x2207, 0x281a)))
        if (!(h = libusb_open_device_with_vid_pid(c, 0x2207, 0x300a)))
        if (!(h = libusb_open_device_with_vid_pid(c, 0x2207, 0x310b)))
            fatal("cannot open device\n");

    if (libusb_kernel_driver_active(h, 0) == 1) {
        info("kernel driver active\n");
        if (!libusb_detach_kernel_driver(h, 0))
            info("driver detached\n");
    }

    if (libusb_claim_interface(h, 0)<0) fatal("cannot claim interface\n");
    info("interface claimed\n");

    send_cmd(h, 2, 0x80, 0x00060000, 0x00000000, 0x00);        /* INIT */
    recv_res(h, 1);
    usleep(20*1000);

    switch(action) {
    case 'b':
        info("rebooting device...\n");
        send_cmd(h, 2, 0x00, 0x0006ff00, 0x00000000, 0x00);
        recv_res(h, 1);
        break;
    case 'r':
        while (size>0) {
            if (offset % RKFT_DISPLAY == 0)
                info("reading flash memory at offset 0x%08x\r", offset);

            send_cmd(h, 2, 0x80, 0x000a1400, offset, RKFT_OFF_INCR);
            recv_buf(h, 1, RKFT_BLOCKSIZE);
            recv_res(h, 1);

            /* check for write() errors to catch disk-full, no-perms, etc. */
            if (write(1, buf, RKFT_BLOCKSIZE) < 0)
                fatal("error writing buffer to stdout: %s\n", strerror(errno));
            offset += RKFT_OFF_INCR;
            size   -= RKFT_OFF_INCR;
        }
        fprintf(stderr, "\n");
        break;
    case 'w':
        while (size>0) {
            if (offset % RKFT_DISPLAY == 0)
                info("writing flash memory at offset 0x%08x\r", offset);

            memset(buf, 0, RKFT_BLOCKSIZE);
            /* we ignore here read() errors and pad up to given size */
            if (read(0, buf, RKFT_BLOCKSIZE) < 0) {};

            send_cmd(h, 2, 0x80, 0x000a1500, offset, RKFT_OFF_INCR);
            send_buf(h, 2, RKFT_BLOCKSIZE);
            recv_res(h, 1);

            offset += RKFT_OFF_INCR;
            size   -= RKFT_OFF_INCR;
        }
        fprintf(stderr, "\n");
        break;
    case 'e':
        memset(buf, RKFT_FILLBYTE, RKFT_BLOCKSIZE);
        while (size>0) {
            if (offset % RKFT_DISPLAY == 0)
                info("erasing flash memory at offset 0x%08x\r", offset);

            send_cmd(h, 2, 0x80, 0x000a1500, offset, RKFT_OFF_INCR);
            send_buf(h, 2, RKFT_BLOCKSIZE);
            recv_res(h, 1);

            offset += RKFT_OFF_INCR;
            size   -= RKFT_OFF_INCR;
        }
        fprintf(stderr, "\n");
        break;
    default:
        break;
    }

    libusb_release_interface(h, 0);
    libusb_close(h);
    libusb_exit(c);
    return 0;
}
コード例 #16
0
ファイル: SAMRAI_MPI.C プロジェクト: 00liujj/SAMRAI
/*
 **************************************************************************
 * Specialized Allreduce for doubles.
 **************************************************************************
 */
int
SAMRAI_MPI::AllReduce(
   float* x,
   int count,
   Op op,
   int* ranks_of_extrema) const
{
#ifndef HAVE_MPI
   NULL_USE(x);
   NULL_USE(count);
   NULL_USE(op);
   NULL_USE(ranks_of_extrema);
#endif
   if ((op == MPI_MINLOC || op == MPI_MAXLOC) &&
       ranks_of_extrema == 0) {
      TBOX_ERROR("SAMRAI_MPI::AllReduce: If you specify reduce\n"
         << "operation MPI_MINLOC or MPI_MAXLOC, you must\n"
         << "provide space for the ranks in the 'ranks_of_extrema'\n"
         << "argument.");
   }
   if (!s_mpi_is_initialized) {
      TBOX_ERROR("SAMRAI_MPI::AllReduce is a no-op without run-time MPI!");
   }

   int rval = MPI_SUCCESS;
   /*
    * Get ranks of extrema if user operation specified it or user
    * specified min/max operation and provides space for rank.
    */
   bool get_ranks_of_extrema =
      op == MPI_MINLOC ? true :
      op == MPI_MAXLOC ? true :
      ranks_of_extrema != 0 && (op == MPI_MIN || op == MPI_MAX);

   if (!get_ranks_of_extrema) {
      std::vector<float> recv_buf(count);
      rval = Allreduce(x, &recv_buf[0], count, MPI_FLOAT, op);
      for (int c = 0; c < count; ++c) {
         x[c] = recv_buf[c];
      }
   } else {
      Op locop =
         op == MPI_MIN ? MPI_MINLOC :
         op == MPI_MAX ? MPI_MAXLOC :
         op;
      FloatIntStruct* send_buf = new FloatIntStruct[count];
      FloatIntStruct* recv_buf = new FloatIntStruct[count];
      for (int c = 0; c < count; ++c) {
         send_buf[c].f = x[c];
         send_buf[c].i = d_rank;
      }
      rval = Allreduce(send_buf, recv_buf, count, MPI_FLOAT_INT, locop);
      for (int c = 0; c < count; ++c) {
         x[c] = recv_buf[c].f;
         ranks_of_extrema[c] = recv_buf[c].i;
      }

      delete[] send_buf;
      delete[] recv_buf;
   }

   return rval;
}
コード例 #17
0
ファイル: loadbalancer.c プロジェクト: chintanvadgama/Twitter
void session(void *q)
{
    int sock = (int)q;
    char *request, *reply, *format;
    char *tmp1, *data1, *data2;
 //   th_args_dt *args = (th_args_dt *)q;
    pthread_t tid;
    pthread_attr_t tattr;
    tweet_req_dt *tweet_req = (tweet_req_dt *)malloc(sizeof(tweet_req_dt));

    tweet_resp_dt *result= (tweet_resp_dt *)malloc(sizeof(tweet_resp_dt));
    /*receive buffer*/

    request = recv_buf(sock);
    //printf("Request received: %s\n",request);
    
    char *tmp;
    tmp = strtok(request," ");
    tweet_req->command = tmp;

    if (strcmp(tweet_req->command,"CLIENT") == 0) {
        printf("CLIENT Requested the server address...\n");

        char ipaddr[15];
        int port;
        
        pthread_mutex_lock(&primary_server->th_mutex);
        if (primary_server->is_alive == 1) {
          strcpy(ipaddr,primary_server->ipaddr);
          port = primary_server->port;
        }
        else {

          pthread_mutex_lock(&secondary_server->th_mutex);
          strcpy(ipaddr,secondary_server->ipaddr);
          port = secondary_server->port;
          pthread_mutex_unlock(&secondary_server->th_mutex);

        }
        pthread_mutex_unlock(&primary_server->th_mutex);


        pthread_mutex_lock(&primary_server->th_mutex);
        if (primary_server->is_alive == 1) {
          result->st_code = 200;
        }
        else {

          pthread_mutex_lock(&secondary_server->th_mutex);
          result->st_code = 400;
          pthread_mutex_unlock(&secondary_server->th_mutex);

        }
        pthread_mutex_unlock(&primary_server->th_mutex);


        strcpy(result->command,tmp);
        result->dlength = (strlen(ipaddr) + 3);
        format = "%s %d %ld\r\n\r\n%s %d\0";
        reply = (char *)malloc(strlen(format)+strlen(result->command)+sizeof(result->st_code)+sizeof(result->dlength)+strlen(ipaddr)+sizeof(port));
        sprintf(reply,format,result->command,result->st_code, result->dlength,ipaddr,port);
        printf("\nData Sent:%s\n",reply);

        send_buf(sock,reply);
        free(reply);
        free(request);
        free(result);
        free(tweet_req);
        close(sock);
        pthread_exit(0);
    }
    else if (strcmp(tweet_req->command,"SERVER") == 0) {
        int count;

        tmp = strtok(NULL,"\0");
        int server_id = atoi(tmp);
        
        printf("Keep Alive message received from SERVER%d\n",server_id);
        time_t ltime;
        ltime=time(NULL); /* get current cal time */
        printf("Message Timestamp: %s\n",asctime(localtime(&ltime)));


        if (server_id == 1) {
          pthread_mutex_lock(&primary_server->th_mutex);
          primary_server->count++;
          count = primary_server->count;
          pthread_mutex_unlock(&primary_server->th_mutex);
        }
        else if(server_id == 2) {
          pthread_mutex_lock(&secondary_server->th_mutex);
          secondary_server->count++;
          count = secondary_server->count;
          pthread_mutex_unlock(&secondary_server->th_mutex);
        }
        /*
        if (server_id == 1) {
          pthread_mutex_lock(&primary_server->th_mutex);
          printf("TIMER START: Server:>%d< & Count:>%d< & Primary Count:>%d<\n",server_id,count,primary_server->count);
          pthread_mutex_unlock(&primary_server->th_mutex);
        }
        else {
          pthread_mutex_lock(&secondary_server->th_mutex);
          printf("TIMER START: Server:>%d< & Count:>%d< & Secondary Count:>%d<\n",server_id,count,secondary_server->count);
          pthread_mutex_unlock(&secondary_server->th_mutex);
        }*/

        sleep(70);

        
        if (server_id == 1) {
            pthread_mutex_lock(&primary_server->th_mutex);
            //printf("TIMER END: Server:>%d< & Primary Count:>%d<\n",server_id,primary_server->count);
            if (count <= primary_server->count) {
              primary_server->is_alive = 1;
              printf("Server%d is ALIVE!!!\n\n",server_id);
            }
            else {
              primary_server->is_alive = 0;
              printf("Server%d is DOWN!!!\n\n",server_id);
            }
            primary_server->count--;
            pthread_mutex_unlock(&primary_server->th_mutex);
        }
        else if (server_id == 2){
            pthread_mutex_lock(&secondary_server->th_mutex);
            //printf("TIMER END: Server:>%d< & Secondary Count:>%d<\n",server_id,secondary_server->count);
            if (count <= secondary_server->count) {
              secondary_server->is_alive = 1;
              printf("Server%d is ALIVE!!!\n\n",server_id);
            }
            else {
              secondary_server->is_alive = 0;
              printf("Server%d is DOWN!!!\n\n",server_id);
            }
            secondary_server->count--;
            pthread_mutex_unlock(&secondary_server->th_mutex);

        }


        /*pthread_mutex_unlock(&primary_server->th_mutex);

        pthread_attr_init(&tattr);
        pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_DETACHED);

        if (pthread_create(&tid,&tattr,(void*(*)(void *))timer,NULL) < 0) { 
          printf("Error: Failed to start the timer thread.\n");
          exit(0);
        }*/

        pthread_exit(0);
    }
}
コード例 #18
0
ファイル: ft2232h_23k256.c プロジェクト: JHJB/opendous
int main(int argc, char **argv)
{
    struct ftdi_context ftdic;
    char buf[16];
    int r,i;

    // Initialize FTDI Driver
    if (ftdi_init(&ftdic) < 0)
    {
        fprintf(stderr, "ftdi_init failed\n");
        return EXIT_FAILURE;
    }

    // Initialize Channel A on Device with corresponding VID, PID
    ftdi_set_interface(&ftdic, INTERFACE_A);
    r = ftdi_usb_open(&ftdic, DEVICE_VID, DEVICE_PID);
    if (r < 0 && r != -5)
    {
        fprintf(stderr, "unable to open ftdi device: %d (%s)\n", r, ftdi_get_error_string(&ftdic));
        exit(-1);
    }
    printf("FTDI Open Succeeded on Channel A: %d\n",r);

    printf("Enabling MPSSE Mode on Channel A\n\n");
    ftdi_set_bitmode(&ftdic, 0xFF, BITMODE_MPSSE);

    // Enable the Div-By-5 Clock Prescaler
    buf[0] =  EN_DIV_5;
    send_buf(&ftdic, buf, 1);
    recv_buf(&ftdic, buf, 1);

    // Configure the clock divisor for SPI
    buf[0] = TCK_DIVISOR;
    buf[1] = 0x00; // set to 0x0000 for 6MHz SPI Clock
    buf[2] = 0x00;
    send_buf(&ftdic, buf, 3);

    // Configure and check Pin State
    buf[0] = SET_BITS_LOW;
    buf[1] = 0x08; // 0x08 = 0b00001000 ==> CS=High, Start SK low
    buf[2] = 0x0B; // 0x0B = 0b00001011 ==> SK,DO,CS=Output
    send_buf(&ftdic, buf, 3);

    buf[0] = GET_BITS_LOW;
    send_buf(&ftdic, buf, 1);
    recv_buf(&ftdic, buf, 1);
    printf("Current State of IO Pins = 0x%02X\n\n", (uint8_t)buf[0]);



    SPI_SRAM_23K256_Init(&ftdic);

    SPI_SRAM_23K256_Read_Byte(&ftdic, 0x5555);

    SPI_SRAM_23K256_Write_Byte(&ftdic, 0x5555,  ((uint8_t)(&buf))  ); // a random value

    SPI_SRAM_23K256_Read_Byte(&ftdic, 0x5555);

    SPI_SRAM_23K256_Read_Byte(&ftdic, 0x5556);



    printf("\nDisabling and Exiting FTDI Communication\n");
    ftdi_disable_bitbang(&ftdic);
    ftdi_usb_close(&ftdic);
    ftdi_deinit(&ftdic);
}
コード例 #19
0
ファイル: rcopy.c プロジェクト: jtdreisb/networks
STATE recv_data(Window *window)
{
	uint32_t seq_num = 0;
	uint8_t flag = 0;
	int32_t data_len = 0;
	uint8_t data_buf[MAX_PACKET_LEN];

	uint32_t window_index;
	uint32_t buffer_offset;
	uint32_t next_seq_num;
	uint32_t max_seq_num;

	static uint32_t expected_seq_number = 0;

	if (select_call(server.socket_num, 10, 0, NOT_NULL) == 0) {
		fprintf(stderr, "Shutting down: No response from server for 10 seconds.\n");
		exit(1);
	}

	data_len = recv_buf(data_buf, MAX_PACKET_LEN, server.socket_num, &server, &flag, &seq_num);

	if (data_len == CRC_ERROR) {
		return STATE_RECV_DATA;
	}

	switch (flag) {
		case FLAG_DATA:
		case FLAG_DATA_RESENT:

			max_seq_num = maxSequenceNumber(window);
			next_seq_num = nextOpenSequenceNumber(window);

			// printf("PACKET: seq_num: %u max: %u next: %u exp: %u\n", seq_num, max_seq_num, next_seq_num, expected_seq_number);

			if (seq_num < next_seq_num) {
				if (seq_num < window->base_seq_num) {
					send_ack(window->base_seq_num-1);
				}
				else {
					if (windowIsFull(window)) {
						send_ack(max_seq_num);
					}
					else {
						send_srej(next_seq_num);
					}
				}
				break;
			}

			// See if the seq_num falls within this windows range
			if ((seq_num >= window->base_seq_num) && (seq_num < (window->base_seq_num + window->window_size))) {
				window_index = (seq_num-1) % window->window_size;
				// Save data if it isn't already in there
				if (window->registry[window_index] == 0) {

					buffer_offset = window_index * window->block_size;
					memcpy(&window->buffer[buffer_offset], data_buf, data_len);

					// Mark the window as received
					window->registry[window_index] = 1;

					max_seq_num = maxSequenceNumber(window);
					next_seq_num = nextOpenSequenceNumber(window);

					if (seq_num == max_seq_num) {
						window->buffer_size = buffer_offset + data_len;
					}
				}
			}


			if (seq_num > next_seq_num) {
				// the previous sequence number
				window_index = ((seq_num-1) % window->window_size);
				if (window->registry[window_index-1] == 0) {
					send_srej(window->base_seq_num+window_index-1);
				}
			}
			else {
				send_ack(next_seq_num-1);
			}

			expected_seq_number = next_seq_num;

			if (windowIsFull(window)) {
				// printf("Window Full\n");
				return STATE_WINDOW_FULL;
			}

			break;

		case FLAG_END_OF_FILE:
			// printf("GOT EOF: seq_num: %u\n", seq_num);// !!!
			return STATE_EOF;
			break;

		default:
			break;

	}

	return STATE_RECV_DATA;
}