Example #1
0
/***********************************************************************
 * Benchmark RX Rate
 **********************************************************************/
void benchmark_rx_rate(
        uhd::usrp::multi_usrp::sptr usrp,
        const std::string &rx_cpu,
        uhd::rx_streamer::sptr rx_stream,
        bool random_nsamps,
        const boost::posix_time::ptime &start_time,
        std::atomic<bool>& burst_timer_elapsed
) {
    uhd::set_thread_priority_safe();

    //print pre-test summary
    std::cout << boost::format(
        "[%s] Testing receive rate %f Msps on %u channels"
    ) % NOW() % (usrp->get_rx_rate()/1e6) % rx_stream->get_num_channels() << std::endl;

    //setup variables and allocate buffer
    uhd::rx_metadata_t md;
    const size_t max_samps_per_packet = rx_stream->get_max_num_samps();
    std::vector<char> buff(max_samps_per_packet*uhd::convert::get_bytes_per_item(rx_cpu));
    std::vector<void *> buffs;
    for (size_t ch = 0; ch < rx_stream->get_num_channels(); ch++)
        buffs.push_back(&buff.front()); //same buffer for each channel
    bool had_an_overflow = false;
    uhd::time_spec_t last_time;
    const double rate = usrp->get_rx_rate();

    uhd::stream_cmd_t cmd(uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS);
    cmd.time_spec = usrp->get_time_now() + uhd::time_spec_t(INIT_DELAY);
    cmd.stream_now = (buffs.size() == 1);
    rx_stream->issue_stream_cmd(cmd);

    const float burst_pkt_time =
        std::max<float>(0.100f, (2 * max_samps_per_packet/rate));
    float recv_timeout = burst_pkt_time + INIT_DELAY;

    bool stop_called = false;
    while (true) {
        //if (burst_timer_elapsed.load(boost::memory_order_relaxed) and not stop_called) {
        if (burst_timer_elapsed and not stop_called) {
            rx_stream->issue_stream_cmd(uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS);
            stop_called = true;
        }
        if (random_nsamps) {
            cmd.num_samps = rand() % max_samps_per_packet;
            rx_stream->issue_stream_cmd(cmd);
        }
        try {
            num_rx_samps += rx_stream->recv(buffs, max_samps_per_packet, md, recv_timeout)*rx_stream->get_num_channels();
            recv_timeout = burst_pkt_time;
        }
        catch (uhd::io_error &e) {
            std::cerr << "[" << NOW() << "] Caught an IO exception. " << std::endl;
            std::cerr << e.what() << std::endl;
            return;
        }

        //handle the error codes
        switch(md.error_code){
        case uhd::rx_metadata_t::ERROR_CODE_NONE:
            if (had_an_overflow) {
                had_an_overflow = false;
                const long dropped_samps =
                    (md.time_spec - last_time).to_ticks(rate);
                if (dropped_samps < 0) {
                    std::cerr
                        << "[" << NOW() << "] Timestamp after overrun recovery "
                           "ahead of error timestamp! Unable to calculate "
                           "number of dropped samples."
                           "(Delta: " << dropped_samps << " ticks)\n";
                }
                num_dropped_samps += std::max<long>(1, dropped_samps);
            }
            if ((burst_timer_elapsed or stop_called) and md.end_of_burst) {
                return;
            }
            break;

        // ERROR_CODE_OVERFLOW can indicate overflow or sequence error
        case uhd::rx_metadata_t::ERROR_CODE_OVERFLOW:
            last_time = md.time_spec;
            had_an_overflow = true;
            // check out_of_sequence flag to see if it was a sequence error or overflow
            if (!md.out_of_sequence) {
                num_overruns++;
            } else {
                num_seqrx_errors++;
                std::cerr << "[" << NOW() << "] Detected Rx sequence error." << std::endl;
            }
            break;

        case uhd::rx_metadata_t::ERROR_CODE_LATE_COMMAND:
            std::cerr << "[" << NOW() << "] Receiver error: " << md.strerror() << ", restart streaming..."<< std::endl;
            num_late_commands++;
            // Radio core will be in the idle state. Issue stream command to restart streaming.
            cmd.time_spec = usrp->get_time_now() + uhd::time_spec_t(0.05);
            cmd.stream_now = (buffs.size() == 1);
            rx_stream->issue_stream_cmd(cmd);
            break;

        case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:
            if (burst_timer_elapsed) {
                return;
            }
            std::cerr << "[" << NOW() << "] Receiver error: " << md.strerror() << ", continuing..." << std::endl;
            num_timeouts_rx++;
            break;

            // Otherwise, it's an error
        default:
            std::cerr << "[" << NOW() << "] Receiver error: " << md.strerror() << std::endl;
            std::cerr << "[" << NOW() << "] Unexpected error on recv, continuing..." << std::endl;
            break;
        }
    }
}
Example #2
0
static void nmi_timer_fn(void *unused)
{
    this_cpu(nmi_timer_ticks)++;
    set_timer(&this_cpu(nmi_timer), NOW() + MILLISECS(1000));
}
Example #3
0
int GzippedFileReader::_ReadSync(void* pBuffer, PX_off_t offset, uint bytesToRead) {
	if (!OkIndex())
		return -1;

	// Without all the caching, chunking and states, this would be enough:
	// return extract(m_src, m_pIndex, offset, (unsigned char*)pBuffer, bytesToRead);

	// Split request to GZFILE_READ_CHUNK_SIZE chunks at GZFILE_READ_CHUNK_SIZE boundaries
	uint maxInChunk = GZFILE_READ_CHUNK_SIZE - offset % GZFILE_READ_CHUNK_SIZE;
	if (bytesToRead > maxInChunk) {
		int first = _ReadSync(pBuffer, offset, maxInChunk);
		if (first != (int)maxInChunk)
			return first; // EOF or failure

		int rest = _ReadSync((char*)pBuffer + maxInChunk, offset + maxInChunk, bytesToRead - maxInChunk);
		if (rest < 0)
			return rest;

		return first + rest;
	}

	// From here onwards it's guarenteed that the request is inside a single GZFILE_READ_CHUNK_SIZE boundaries

	int res = m_cache.Read(pBuffer, offset, bytesToRead);
	if (res >= 0)
		return res;

	// Not available from cache. Decompress from optimal starting
	// point in GZFILE_READ_CHUNK_SIZE chunks and cache each chunk.
	PTT s = NOW();
	PX_off_t extractOffset = GetOptimalExtractionStart(offset); // guaranteed in GZFILE_READ_CHUNK_SIZE boundaries
	int size = offset + maxInChunk - extractOffset;
	unsigned char* extracted = (unsigned char*)malloc(size);

	int span = m_pIndex->span;
	int spanix = extractOffset / span;
	AsyncPrefetchCancel();
	res = extract(m_src, m_pIndex, extractOffset, extracted, size, &(m_zstates[spanix].state));
	if (res < 0) {
		free(extracted);
		return res;
	}
	AsyncPrefetchChunk(getInOffset(&(m_zstates[spanix].state)));

	int copied = ChunksCache::CopyAvailable(extracted, extractOffset, res, pBuffer, offset, bytesToRead);

	if (m_zstates[spanix].state.isValid && (extractOffset + res) / span != offset / span) {
		// The state no longer matches this span.
		// move the state to the appropriate span because it will be faster than using the index
		int targetix = (extractOffset + res) / span;
		m_zstates[targetix].Kill();
		m_zstates[targetix] = m_zstates[spanix]; // We have elements for the entire file, and another one.
		m_zstates[spanix].state.isValid = 0; // Not killing because we need the state.
	}

	if (size <= GZFILE_READ_CHUNK_SIZE)
		m_cache.Take(extracted, extractOffset, res, size);
	else { // split into cacheable chunks
		for (int i = 0; i < size; i += GZFILE_READ_CHUNK_SIZE) {
			int available = CLAMP(res - i, 0, GZFILE_READ_CHUNK_SIZE);
			void* chunk = available ? malloc(available) : 0;
			if (available)
				memcpy(chunk, extracted + i, available);
			m_cache.Take(chunk, extractOffset + i, available, std::min(size - i, GZFILE_READ_CHUNK_SIZE));
		}
		free(extracted);
	}

	int duration = NOW() - s;
	if (duration > 10)
		Console.WriteLn(Color_Gray, L"gunzip: chunk #%5d-%2d : %1.2f MB - %d ms",
		                (int)(offset / 4 / 1024 / 1024),
		                (int)(offset % (4 * 1024 * 1024) / GZFILE_READ_CHUNK_SIZE),
		                (float)size / 1024 / 1024,
		                duration);

	return copied;
}
void CMeracCastle::SetNextWarTime(int nextWarTime)
{
	time_t curtime;
	time(&curtime);

	// 공성 시작 시간이 현재 시간이후이면 그대로 적용
	if (GetState() == WCSF_NORMAL && nextWarTime != 0)
	{
		if (nextWarTime > curtime)
		{
			m_nextWarTime = nextWarTime;
			return ;
		}
		else
		{
			GAMELOG << init("WAR CASTLE : WARN SET TIME")
					<< "CUR TIME : " << (int)curtime << delim
					<< "NEXT TIME : " << nextWarTime
					<< end;
		}
	}

	// 공성 시간을 기본 값으로 설정
	// 현재 요일을 구함
	struct tm curtm = NOW();

	// 다음 토요일을 구함
	int next = 6 - curtm.tm_wday;
	if (next <= 0)
		next += 7;

	// 다음 토요일 20시에 해당하는 time_t 값을 구함
	struct tm nexttm = curtm;
#ifdef LC_TLD
	nexttm.tm_hour = 19;
#else
	nexttm.tm_hour = 20;
#endif
	nexttm.tm_min = 0;
	nexttm.tm_sec = 0;
	nexttm.tm_mday += next;
	nexttm.tm_isdst = -1;
	time_t nexttime = mktime(&nexttm);

	// 현재 시간보다 작으면 다음주로
	if (nexttime < curtime)
	{
		nexttm.tm_mday += 7;
		nexttime = mktime(&nexttm);
	}

	m_nextWarTime = nexttime;

	if (nextWarTime != 0)
	{
		GAMELOG << init("WAR CASTLE : SET NEXT TIME FOR LOAD")
				<< "IN : " << nextWarTime << delim
				<< "SET : " << m_nextWarTime
				<< end;
	}
}
Example #5
0
/* Bring up a remote CPU */
int __cpu_up(unsigned int cpu)
{
    int rc;
    s_time_t deadline;

    printk("Bringing up CPU%d\n", cpu);

    rc = init_secondary_pagetables(cpu);
    if ( rc < 0 )
        return rc;

    console_start_sync(); /* Secondary may use early_printk */

    /* Tell the remote CPU which stack to boot on. */
    init_data.stack = idle_vcpu[cpu]->arch.stack;

    /* Tell the remote CPU what its logical CPU ID is. */
    init_data.cpuid = cpu;

    /* Open the gate for this CPU */
    smp_up_cpu = cpu_logical_map(cpu);
    clean_dcache(smp_up_cpu);

    rc = arch_cpu_up(cpu);

    console_end_sync();

    if ( rc < 0 )
    {
        printk("Failed to bring up CPU%d\n", cpu);
        return rc;
    }

    deadline = NOW() + MILLISECS(1000);

    while ( !cpu_online(cpu) && NOW() < deadline )
    {
        cpu_relax();
        process_pending_softirqs();
    }

    /*
     * Nuke start of day info before checking one last time if the CPU
     * actually came online. If it is not online it may still be
     * trying to come up and may show up later unexpectedly.
     *
     * This doesn't completely avoid the possibility of the supposedly
     * failed CPU trying to progress with another CPUs stack settings
     * etc, but better than nothing, hopefully.
     */
    init_data.stack = NULL;
    init_data.cpuid = ~0;
    smp_up_cpu = MPIDR_INVALID;
    clean_dcache(smp_up_cpu);

    if ( !cpu_online(cpu) )
    {
        printk("CPU%d never came online\n", cpu);
        return -EIO;
    }

    return 0;
}
Example #6
0
/* Just poll without blocking */
static int select_poll(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds)
{
    int i, n = 0;
#ifdef HAVE_LWIP
    int sock_n = 0, sock_nfds = 0;
    fd_set sock_readfds, sock_writefds, sock_exceptfds;
    struct timeval timeout = { .tv_sec = 0, .tv_usec = 0};
#endif

#ifdef LIBC_VERBOSE
    static int nb;
    static int nbread[NOFILE], nbwrite[NOFILE], nbexcept[NOFILE];
    static s_time_t lastshown;

    nb++;
#endif

#ifdef HAVE_LWIP
    /* first poll network */
    FD_ZERO(&sock_readfds);
    FD_ZERO(&sock_writefds);
    FD_ZERO(&sock_exceptfds);
    for (i = 0; i < nfds; i++) {
	if (files[i].type == FTYPE_SOCKET) {
	    if (FD_ISSET(i, readfds)) {
		FD_SET(files[i].socket.fd, &sock_readfds);
		sock_nfds = i+1;
	    }
	    if (FD_ISSET(i, writefds)) {
		FD_SET(files[i].socket.fd, &sock_writefds);
		sock_nfds = i+1;
	    }
	    if (FD_ISSET(i, exceptfds)) {
		FD_SET(files[i].socket.fd, &sock_exceptfds);
		sock_nfds = i+1;
	    }
	}
    }
    if (sock_nfds > 0) {
        DEBUG("lwip_select(");
        dump_set(nfds, &sock_readfds, &sock_writefds, &sock_exceptfds, &timeout);
        DEBUG("); -> ");
        sock_n = lwip_select(sock_nfds, &sock_readfds, &sock_writefds, &sock_exceptfds, &timeout);
        dump_set(nfds, &sock_readfds, &sock_writefds, &sock_exceptfds, &timeout);
        DEBUG("\n");
    }
#endif

    /* Then see others as well. */
    for (i = 0; i < nfds; i++) {
	switch(files[i].type) {
	default:
	    if (FD_ISSET(i, readfds) || FD_ISSET(i, writefds) || FD_ISSET(i, exceptfds))
		printk("bogus fd %d in select\n", i);
	    /* Fallthrough.  */
	case FTYPE_CONSOLE:
	    if (FD_ISSET(i, readfds)) {
                if (xencons_ring_avail(files[i].cons.dev))
		    n++;
		else
		    FD_CLR(i, readfds);
            }
	    if (FD_ISSET(i, writefds))
                n++;
	    FD_CLR(i, exceptfds);
	    break;
#ifdef CONFIG_XENBUS
	case FTYPE_XENBUS:
	    if (FD_ISSET(i, readfds)) {
                if (files[i].xenbus.events)
		    n++;
		else
		    FD_CLR(i, readfds);
	    }
	    FD_CLR(i, writefds);
	    FD_CLR(i, exceptfds);
	    break;
#endif
	case FTYPE_EVTCHN:
	case FTYPE_TAP:
	case FTYPE_BLK:
	case FTYPE_KBD:
	case FTYPE_FB:
	    if (FD_ISSET(i, readfds)) {
		if (files[i].read)
		    n++;
		else
		    FD_CLR(i, readfds);
	    }
	    FD_CLR(i, writefds);
	    FD_CLR(i, exceptfds);
	    break;
#ifdef HAVE_LWIP
	case FTYPE_SOCKET:
	    if (FD_ISSET(i, readfds)) {
	        /* Optimize no-network-packet case.  */
		if (sock_n && FD_ISSET(files[i].socket.fd, &sock_readfds))
		    n++;
		else
		    FD_CLR(i, readfds);
	    }
            if (FD_ISSET(i, writefds)) {
		if (sock_n && FD_ISSET(files[i].socket.fd, &sock_writefds))
		    n++;
		else
		    FD_CLR(i, writefds);
            }
            if (FD_ISSET(i, exceptfds)) {
		if (sock_n && FD_ISSET(files[i].socket.fd, &sock_exceptfds))
		    n++;
		else
		    FD_CLR(i, exceptfds);
            }
	    break;
#endif
	}
#ifdef LIBC_VERBOSE
	if (FD_ISSET(i, readfds))
	    nbread[i]++;
	if (FD_ISSET(i, writefds))
	    nbwrite[i]++;
	if (FD_ISSET(i, exceptfds))
	    nbexcept[i]++;
#endif
    }
#ifdef LIBC_VERBOSE
    if (NOW() > lastshown + 1000000000ull) {
	lastshown = NOW();
	printk("%lu MB free, ", num_free_pages() / ((1 << 20) / PAGE_SIZE));
	printk("%d(%d): ", nb, sock_n);
	for (i = 0; i < nfds; i++) {
	    if (nbread[i] || nbwrite[i] || nbexcept[i])
		printk(" %d(%c):", i, file_types[files[i].type]);
	    if (nbread[i])
	    	printk(" %dR", nbread[i]);
	    if (nbwrite[i])
		printk(" %dW", nbwrite[i]);
	    if (nbexcept[i])
		printk(" %dE", nbexcept[i]);
	}
	printk("\n");
	memset(nbread, 0, sizeof(nbread));
	memset(nbwrite, 0, sizeof(nbwrite));
	memset(nbexcept, 0, sizeof(nbexcept));
	nb = 0;
    }
#endif
    return n;
}

/* The strategy is to
 * - announce that we will maybe sleep
 * - poll a bit ; if successful, return
 * - if timeout, return
 * - really sleep (except if somebody woke us in the meanwhile) */
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
	struct timeval *timeout)
{
    int n, ret;
    fd_set myread, mywrite, myexcept;
    struct thread *thread = get_current();
    s_time_t start = NOW(), stop;
#ifdef CONFIG_NETFRONT
    DEFINE_WAIT(netfront_w);
#endif
    DEFINE_WAIT(event_w);
#ifdef CONFIG_BLKFRONT
    DEFINE_WAIT(blkfront_w);
#endif
#ifdef CONFIG_XENBUS
    DEFINE_WAIT(xenbus_watch_w);
#endif
#ifdef CONFIG_KBDFRONT
    DEFINE_WAIT(kbdfront_w);
#endif
    DEFINE_WAIT(console_w);

    assert(thread == main_thread);

    DEBUG("select(%d, ", nfds);
    dump_set(nfds, readfds, writefds, exceptfds, timeout);
    DEBUG(");\n");

    if (timeout)
	stop = start + SECONDS(timeout->tv_sec) + timeout->tv_usec * 1000;
    else
	/* just make gcc happy */
	stop = start;

    /* Tell people we're going to sleep before looking at what they are
     * saying, hence letting them wake us if events happen between here and
     * schedule() */
#ifdef CONFIG_NETFRONT
    add_waiter(netfront_w, netfront_queue);
#endif
    add_waiter(event_w, event_queue);
#ifdef CONFIG_BLKFRONT
    add_waiter(blkfront_w, blkfront_queue);
#endif
#ifdef CONFIG_XENBUS
    add_waiter(xenbus_watch_w, xenbus_watch_queue);
#endif
#ifdef CONFIG_KBDFRONT
    add_waiter(kbdfront_w, kbdfront_queue);
#endif
    add_waiter(console_w, console_queue);

    if (readfds)
        myread = *readfds;
    else
        FD_ZERO(&myread);
    if (writefds)
        mywrite = *writefds;
    else
        FD_ZERO(&mywrite);
    if (exceptfds)
        myexcept = *exceptfds;
    else
        FD_ZERO(&myexcept);

    DEBUG("polling ");
    dump_set(nfds, &myread, &mywrite, &myexcept, timeout);
    DEBUG("\n");
    n = select_poll(nfds, &myread, &mywrite, &myexcept);

    if (n) {
	dump_set(nfds, readfds, writefds, exceptfds, timeout);
	if (readfds)
	    *readfds = myread;
	if (writefds)
	    *writefds = mywrite;
	if (exceptfds)
	    *exceptfds = myexcept;
	DEBUG(" -> ");
	dump_set(nfds, readfds, writefds, exceptfds, timeout);
	DEBUG("\n");
	wake(thread);
	ret = n;
	goto out;
    }
    if (timeout && NOW() >= stop) {
	if (readfds)
	    FD_ZERO(readfds);
	if (writefds)
	    FD_ZERO(writefds);
	if (exceptfds)
	    FD_ZERO(exceptfds);
	timeout->tv_sec = 0;
	timeout->tv_usec = 0;
	wake(thread);
	ret = 0;
	goto out;
    }

    if (timeout)
	thread->wakeup_time = stop;
    schedule();

    if (readfds)
        myread = *readfds;
    else
        FD_ZERO(&myread);
    if (writefds)
        mywrite = *writefds;
    else
        FD_ZERO(&mywrite);
    if (exceptfds)
        myexcept = *exceptfds;
    else
        FD_ZERO(&myexcept);

    n = select_poll(nfds, &myread, &mywrite, &myexcept);

    if (n) {
	if (readfds)
	    *readfds = myread;
	if (writefds)
	    *writefds = mywrite;
	if (exceptfds)
	    *exceptfds = myexcept;
	ret = n;
	goto out;
    }
    errno = EINTR;
    ret = -1;

out:
#ifdef CONFIG_NETFRONT
    remove_waiter(netfront_w, netfront_queue);
#endif
    remove_waiter(event_w, event_queue);
#ifdef CONFIG_BLKFRONT
    remove_waiter(blkfront_w, blkfront_queue);
#endif
#ifdef CONFIG_XENBUS
    remove_waiter(xenbus_watch_w, xenbus_watch_queue);
#endif
#ifdef CONFIG_KBDFRONT
    remove_waiter(kbdfront_w, kbdfront_queue);
#endif
    remove_waiter(console_w, console_queue);
    return ret;
}
Example #7
0
File: domain.c Project: bjzhang/xen
struct vcpu *alloc_vcpu(
    struct domain *d, unsigned int vcpu_id, unsigned int cpu_id)
{
    struct vcpu *v;

    BUG_ON((!is_idle_domain(d) || vcpu_id) && d->vcpu[vcpu_id]);

    if ( (v = alloc_vcpu_struct()) == NULL )
        return NULL;

    v->domain = d;
    v->vcpu_id = vcpu_id;

    spin_lock_init(&v->virq_lock);

    tasklet_init(&v->continue_hypercall_tasklet, NULL, 0);

    if ( !zalloc_cpumask_var(&v->cpu_affinity) ||
         !zalloc_cpumask_var(&v->cpu_affinity_tmp) ||
         !zalloc_cpumask_var(&v->vcpu_dirty_cpumask) )
        goto fail_free;

    if ( is_idle_domain(d) )
    {
        v->runstate.state = RUNSTATE_running;
    }
    else
    {
        v->runstate.state = RUNSTATE_offline;        
        v->runstate.state_entry_time = NOW();
        set_bit(_VPF_down, &v->pause_flags);
        v->vcpu_info = ((vcpu_id < XEN_LEGACY_MAX_VCPUS)
                        ? (vcpu_info_t *)&shared_info(d, vcpu_info[vcpu_id])
                        : &dummy_vcpu_info);
        init_waitqueue_vcpu(v);
    }

    if ( sched_init_vcpu(v, cpu_id) != 0 )
        goto fail_wq;

    if ( vcpu_initialise(v) != 0 )
    {
        sched_destroy_vcpu(v);
 fail_wq:
        destroy_waitqueue_vcpu(v);
 fail_free:
        free_cpumask_var(v->cpu_affinity);
        free_cpumask_var(v->cpu_affinity_tmp);
        free_cpumask_var(v->vcpu_dirty_cpumask);
        free_vcpu_struct(v);
        return NULL;
    }

    d->vcpu[vcpu_id] = v;
    if ( vcpu_id != 0 )
    {
        int prev_id = v->vcpu_id - 1;
        while ( (prev_id >= 0) && (d->vcpu[prev_id] == NULL) )
            prev_id--;
        BUG_ON(prev_id < 0);
        v->next_in_list = d->vcpu[prev_id]->next_in_list;
        d->vcpu[prev_id]->next_in_list = v;
    }

    /* Must be called after making new vcpu visible to for_each_vcpu(). */
    vcpu_check_shutdown(v);

    domain_update_node_affinity(d);

    return v;
}
Example #8
0
qint64 ZDateTime::now_t(){
    return UNIXTIME(NOW());
}
Example #9
0
qint64 ZDateTime::secondsTo(QDateTime target){
    ptime then(EPOCH_DATE(),seconds(target.toTime_t()));
    time_duration rv = (then - NOW());
    return rv.total_seconds();
}
Example #10
0
/* Read a block from the fs, returning a pointer to a struct blockbuf. The
   block is locked as appropriate. YOU MUST CALL brelse() once you are
   finished with the block, otherwise it will sit around for ages. */
struct buffer_head *bread(ext2fs_st *st, uint32_t block, bool_t rw)
{
    struct buffer_head *buf;

    TRC(printf("bread %d\n", block));
    MU_LOCK(&st->cache.mu);

    buf = bfind(st, block);

    if (buf) {

	LINK_REMOVE(buf);
	MU_LOCK(&buf->mu);	/* Lock the buffer */
	LINK_ADD_TO_HEAD(&st->cache.bufs, buf);	/* Pull to front */
	MU_RELEASE(&st->cache.mu); /* Don't need the cache lacked any more */

	if (rw) {
	    /* We're going for exclusive access. Anything else just
	       isn't good enough. */
	retry:
	    if (buf->state == buf_unlocked) {
		buf->state = buf_locked_readwrite;
		TRC(printf("ext2fs: cached block %d now locked readwrite\n",
			   block));
		/* ASSERT b_count==0 */
		MU_RELEASE(&buf->mu);
		return buf;
	    }
	    
	    TRC(printf("Correct block cached, but already inuse -> retry\n"));
	    
	    /* We can't get it now; wait for a signal and try again */
	    WAIT(&buf->mu, &buf->cv);
	    goto retry;
	} else {
	    buf->state = buf_locked_readonly;
	}
	buf->b_count++;

	buf->lastused = NOW();
	buf->refd++;

	MU_RELEASE(&buf->mu);
	return buf;

    } else {
	/* Wait on the LRU buffer */
	while (! (buf = balloc(st))) {
	    TRC(printf("waiting...\n"));
	    WAIT(&st->cache.mu, &st->cache.freebufs);
	    TRC(printf("retry...\n"));
	}
	LINK_REMOVE(buf);

	if (buf->state) {
	    TRC(printf("E %d %d %d %d\n", 
		   buf->b_blocknr, buf->refd,
		   (buf->lastused - buf->firstused) / MILLISECS(1),
		   (NOW() - buf->lastused) / MILLISECS(1)));
	}

	MU_RELEASE(&st->cache.mu);
	/* At this point the block is either unlocked or empty. We can fetch
	   a new block into it. */
	TRC(printf("reading %d\n", block));
	memset(buf->b_data, 0xaa, st->fsc.block_size);
	if (!logical_read(st, block, 1, buf->b_data, st->fsc.block_size)) {
	    printf("ext2fs: getblock: read of block %d failed\n",
		   block);
	    /* XXX what now? */
	}
	buf->firstused = buf->lastused  = NOW();
	buf->refd      = 1;
	buf->b_size    = st->fsc.block_size;
	buf->b_blocknr = block;
	buf->b_count++;
	if (rw) {
	    buf->state = buf_locked_readwrite;
	} else {
	    buf->state = buf_locked_readonly;
	    /* ASSERT refcount==1 */
	}
	MU_LOCK(&st->cache.mu);
	LINK_ADD_TO_HEAD(&st->cache.bufs, buf);	/* Pull to front */
	MU_RELEASE(&st->cache.mu);
    }

    return buf;
}
Example #11
0
QDateTime ZDateTime::now(){
    return QDateTime::fromTime_t(UNIXTIME(NOW()));
}
Example #12
0
 void handle(){
   xprintf("sendTimed at %lld\n", NOW());
   long seconds = NOW() / SECONDS;
   counter2.publish(seconds);
 }
Example #13
0
u32_t sys_now(void)
{
    return ((u32_t) NOW());
}
Example #14
0
File: io.c Project: berkus/nemesis
/* ---------------------------------- Server side IO implementation ---- */
PUBLIC void IOThread(disk_t *disk)
{
    stream_t *stream;
    QoSEntry_clp qosentry = disk->qosentry;
    Time_T pre,post;
    IO_clp io;
    IO_Rec recs[2]; 
    uint32_t nrecs;
    word_t value;
    uint32_t offset;
    Time_ns cost;
    uint32_t  notify;
    USD_Extent ext;

    FileIO_Request copyreq;
    FileIO_Request *req;

    while (True) {
	TRC(printf(__FUNCTION__": about to Rendezvous...\n"));
	io = IOEntry$Rendezvous((IOEntry_clp)qosentry, FOREVER);

	/* 
	** Account the time we're about to spend processing this packet
	** to the QosEntry: for now, we just are sych. and so can 
	** actually count the amount of time. XXX no overhead accounted.
	*/
	pre = NOW();

	TRC(printf(__FUNCTION__": back from Rdzvs, io at %p\n", io));

	/* Find out whose IO it is */
	stream = (stream_t *)IO_HANDLE(io);
	offset = stream->usd->partition->p_offset;

	TRC(printf("(It's stream %d)\n",stream->sid));

	/* XXX SMH: nasty hardwired request/buffer IO_Rec pair */
	if (IO$GetPkt(io, 2, recs, 0, &nrecs, &value)) {
	    
	    FTRC("got packet.\n");

	    req = (FileIO_Request *)recs[0].base;
	
	    copyreq = *req;

	    IOTRC(printf("req=%p\n",req));

	    IOTRC(printf("%qx:(%qd,%d)\n", stream->sid, 
			 copyreq.blockno, copyreq.nblocks));
	
	    /* Translate the addresses in the request */
	    if(!USDCallback$Translate(stream->usd->callbacks,
				      stream->sid,
				      stream->cid,
				      &copyreq,
				      &ext,
				      &notify))
	    {
		TRC(printf("denied %qx:(%qd,%x)\n", stream->sid,
			   copyreq.blockno, copyreq.nblocks));
		req->rc = FileIO_RC_DENIED;
		goto denied;
	    }

	    /* Actually do the transaction */
	    switch(copyreq.op) {
	    case FileIO_Op_Read:
		FTRC("trying to read.\n");
		MU_LOCK(&disk->mu);
		if (BlockDev$Read((BlockDev_clp)disk->device, 
			      ext.base + offset, 
			      ext.len, 
				  recs[1].base)) {
		  req->rc = FileIO_RC_OK;
		  FTRC("done.\n");
		}
		else {
		  req->rc = FileIO_RC_FAILURE;
		  FTRC("failure trying to read.\n");
		}
		MU_RELEASE(&disk->mu);
		break; 
		
	    case FileIO_Op_Write:
		FTRC("trying to write.\n");
		MU_LOCK(&disk->mu);
		if (BlockDev$Write((BlockDev_clp)disk->device, 
			       ext.base + offset, 
			       ext.len, 
				   recs[1].base)) {
		  req->rc = FileIO_RC_OK;
		  FTRC("done.\n");
		}
		else {
		  req->rc = FileIO_RC_FAILURE;
		  FTRC("failure trying to write.\n");
		}
		MU_RELEASE(&disk->mu);
		break;

	    case FileIO_Op_Sync:
		FTRC("trying to sync.\n");
		printf(__FUNCTION__": FileIO_Op_Sync unimplemented.\n");
		FTRC("done.\n");
		break;

	    default:
		printf(__FUNCTION__": bad FileIO_Op %x\n", copyreq.op);
		ntsc_dbgstop();
	    }

	    USDCallback$Notify(stream->usd->callbacks,
			       stream->sid,
			       stream->cid,
			       &copyreq,
			       &ext,
			       notify,
			       recs[1].base);
	denied:
	    post = NOW();
	    cost = post - pre;
	    QoSEntry$Charge(qosentry, io, cost);
	
	    /* Return the IO_Rec vector */
	    TRC(printf("USD$IOThread: returning IOs.\n"));
	    IO$PutPkt(io, nrecs, &recs[0], cost, 0);
	}    
    } /* while true */

    printf("USD$IOThread: BAD NEWS. Exiting (?)\n");
}
Example #15
0
/**
 * This function is called by the adjust_global scheduler hook to put
 * in place a new ARINC653 schedule.
 *
 * @param ops       Pointer to this instance of the scheduler structure
 *
 * @return          <ul>
 *                  <li> 0 = success
 *                  <li> !0 = error
 *                  </ul>
 */
static int
arinc653_sched_set(
    const struct scheduler *ops,
    struct xen_sysctl_arinc653_schedule *schedule)
{
    a653sched_priv_t *sched_priv = SCHED_PRIV(ops);
    s_time_t total_runtime = 0;
    unsigned int i;
    unsigned long flags;
    int rc = -EINVAL;

    spin_lock_irqsave(&sched_priv->lock, flags);

    /* Check for valid major frame and number of schedule entries. */
    if ( (schedule->major_frame <= 0)
         || (schedule->num_sched_entries < 1)
         || (schedule->num_sched_entries > ARINC653_MAX_DOMAINS_PER_SCHEDULE) )
        goto fail;

    for ( i = 0; i < schedule->num_sched_entries; i++ )
    {
        /* Check for a valid VCPU ID and run time. */
        if ( (schedule->sched_entries[i].vcpu_id >= MAX_VIRT_CPUS)
             || (schedule->sched_entries[i].runtime <= 0) )
            goto fail;

        /* Add this entry's run time to total run time. */
        total_runtime += schedule->sched_entries[i].runtime;
    }

    /*
     * Error if the major frame is not large enough to run all entries as
     * indicated by comparing the total run time to the major frame length.
     */
    if ( total_runtime > schedule->major_frame )
        goto fail;

    /* Copy the new schedule into place. */
    sched_priv->num_schedule_entries = schedule->num_sched_entries;
    sched_priv->major_frame = schedule->major_frame;
    for ( i = 0; i < schedule->num_sched_entries; i++ )
    {
        memcpy(sched_priv->schedule[i].dom_handle,
               schedule->sched_entries[i].dom_handle,
               sizeof(sched_priv->schedule[i].dom_handle));
        sched_priv->schedule[i].vcpu_id =
            schedule->sched_entries[i].vcpu_id;
        sched_priv->schedule[i].runtime =
            schedule->sched_entries[i].runtime;
    }
    update_schedule_vcpus(ops);

    /*
     * The newly-installed schedule takes effect immediately. We do not even
     * wait for the current major frame to expire.
     *
     * Signal a new major frame to begin. The next major frame is set up by
     * the do_schedule callback function when it is next invoked.
     */
    sched_priv->next_major_frame = NOW();

    rc = 0;

 fail:
    spin_unlock_irqrestore(&sched_priv->lock, flags);
    return rc;
}
Example #16
0
static int udp_send(struct socket *sock, const char *message, int len,
		    int flags, const struct sockaddr *dest_addr, int dest_len)
{
    struct udp_data *udp_data= (struct udp_data *)sock->data;
    IO_Rec txrecs[3];
    struct sockaddr_in *laddr= (struct sockaddr_in *)&(sock->laddr);
    struct sockaddr_in *raddr= (struct sockaddr_in *)&(sock->raddr);
    int i;
    uint32_t nrecs;
    pktcx_t *pktcx;

    TRC(eprintf("udp_send: entered\n"));

    MU_LOCK(&sock->lock);

    if(sock->state != SS_CONNECTED) /* stack needs building */
    {
	if (dest_addr)
	{
	    *raddr = *(struct sockaddr_in *)dest_addr;
	}
	else
	{
	    MU_RELEASE(&sock->lock);
	    return -1; /* ENOTCONN or summit */
	}

	TRC(eprintf("udp_send: building stack\n"));
	build_stack(udp_data, laddr, NULL);
	sock->state = SS_CONNECTED;

	/* now target it */
	TRC(eprintf("udp_send: retargeting to %I:%d\n",
		    raddr->sin_addr, raddr->sin_port));
	if(!retarget(udp_data, laddr, raddr)) {
	    TRC(eprintf("...retarget failed\n"));
	    /* ARP failed */
	    MU_RELEASE(&sock->lock);
	    return -1; /* EHOSTDOWN or sim */
	}
    }
    else
    {
	struct sockaddr_in *daddr = (struct sockaddr_in *)dest_addr;

	TRC(eprintf("udp_send: stack already built\n"));
	if (daddr->sin_addr.s_addr == raddr->sin_addr.s_addr
	    && daddr->sin_port == raddr->sin_port)
	{
	    TRC(eprintf("... and targeted correctly\n"));
	}
	else
	{
	    TRC(eprintf("... but incorrectly targeted; retargeting\n"));
	    /* retarget stack for this destination */
	    if(!retarget(udp_data, laddr, daddr)) {
		/* ARP failed */
		MU_RELEASE(&sock->lock);
		return -1; /* EHOSTDOWN or sim */
	    }
	    *raddr = *daddr;
	    TRC(eprintf("udp_send: retargeted stack\n"));
	}
    }

    /* done with global state, now need the acquire the receive resource
     * lock */
    MU_RELEASE(&sock->lock);
    MU_LOCK(&sock->txlock);

    /* organise mem for headers */
    txrecs[0].len  = udp_data->head;
    txrecs[0].base = udp_data->txbuf;

    /* 
    ** XXX SMH: for the moment, we must copy the data to be transmitted
    ** onto a heap which is readable by the driver domain. This is not, 
    ** however, the most efficient way one can imagine doing transmit.
    ** Some alternatives that should be investigated are:
       a) make the driver enter kernel mode s.t. it can read the data.
          This is essentially what used to happen before coz drivers
	  ran in kernel mode the entire time. 
       b) map the clients data readable to the driver domain on the fly.
          This would require some way of getting hold of the stretch
	  containing the message buffer, and might be a very bad idea
	  indeed coz lots of other stuff would be mapped too.
       c) force clients to give us data which is readable by the driver
          pdom. This is trickier than it sounds since in general clients
	  won't know the pdom of the driver for the interface upon which
	  their message will eventually be transmitted. Though we could
	  arrange for all network drivers to be in the same pdom (!?!).
    ** Even apart from those considerations, this temporary solution should
    ** be modified s.t. the mallocing is done out of band, or not at all
    ** [i.e. perhaps have a stretch, not a heap, and then can just memcpy
    **  to the start of this. requires some locking though ;-]
    */
    txrecs[1].len  = len;
    if(!(txrecs[1].base = Heap$Malloc(udp_data->txheap, len))) {
	eprintf("udp_send: failed to malloc txrec buf!\n"); 
	MU_RELEASE(&sock->txlock); 
	return -1;   /* error */
    }
    memcpy((char *)txrecs[1].base, message, len);

    if(!(pktcx = Heap$Calloc(udp_data->txheap, sizeof(pktcx_t), 1))) {
	eprintf("udp_send: failed to malloc packet context!\n"); 
	Heap$Free(udp_data->txheap, txrecs[1].base);
	MU_RELEASE(&sock->txlock); 
	return -1;   /* error */
    }

    pktcx->ri_nrecs = 2;
    for(i=0; i<2; i++)
	pktcx->ri_recs[i] = txrecs[i];

    TRC(eprintf("udp_send: About to IO$PutPkt...\n"));


    if (!IO$PutPkt(udp_data->txio, 2, txrecs, (word_t)pktcx, FOREVER))
    {
	txrecs[1].len = -1;  /* error */
	goto out;
    }

    /* pick up the tx buffer from the driver */
    do {
	IO$GetPkt(udp_data->txio, 2, txrecs, NOW() + SECONDS(10),
		  &nrecs, (word_t*)&pktcx);
	if (nrecs == 0) {
	    printf("udp_send: timeout recovering tx buffers\n");
	} else {
	    if (nrecs != 2)
	    {
		printf("udp_send: didn't recover enough tx buffers (%d!=3)\n",
		       nrecs);
	    }
	}
    } while(nrecs != 2);
    if (!pktcx)
	printf("udp_send: didn't get packet context back?\n");
    if (pktcx && pktcx->error)
	printf("udp_send: error %d sending\n", pktcx->error);

out:
    Heap$Free(udp_data->txheap, txrecs[1].base);
    Heap$Free(udp_data->txheap, pktcx);

    MU_RELEASE(&sock->txlock);

    return txrecs[1].len;
}
Example #17
0
static uint64_t get_stime_tick(void) { return (uint64_t)NOW(); }
Example #18
0
static int udp_select(struct socket *sock, int nfds,
		      fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
		      struct timeval *timeout)
{
    IO_Rec rec;
    uint32_t nrecs;
    word_t value;
    Time_ns t;
    struct udp_data *udp_data= (struct udp_data *)sock->data;

    MU_LOCK(&sock->lock);

    /* XXX really want to keep a domain-wide cache of connections */
    if(sock->state != SS_CONNECTED) /* stack needs building */
    {
	struct sockaddr_in *laddr = (struct sockaddr_in *)&(sock->laddr);

	/* remote address isn't used for anything in recv */
	build_stack(udp_data, laddr, NULL);
	sock->state = SS_CONNECTED;
    }
    MU_RELEASE(&sock->lock);
    MU_LOCK(&sock->rxlock);

    if (timeout)
    {
	t = NOW() + 
	    timeout->tv_sec * SECONDS(1) + 
	    timeout->tv_usec * MICROSECS(1);
    }
    else
    {
	t = FOREVER;
    }

    value = 0;
    IO$GetPkt(udp_data->rxio, 0, &rec, t, &nrecs, &value);
    if (value)
    {
	eprintf("udp_select: got a packet cx?!?\n");
	ntsc_dbgstop();
    }

#ifdef PARANOID
    if (NOW() > t + SECONDS(2))
	printf("udp_select: warning: took >2 secs to return from select?\n");
#endif

    MU_RELEASE(&sock->rxlock);

    if (nrecs)
    {
//	eprintf("sel ok\n");
	return 1;  /* there's data available */
    }
    else
    {
//	eprintf("sel t/o\n");
	return 0;  /* no data, but not an error - we timed out */
    }
}
Example #19
0
File: rtc.c Project: Fantu/Xen
/* handle alarm timer */
static void alarm_timer_update(RTCState *s)
{
    uint64_t next_update_time, next_alarm_sec;
    uint64_t expire_time;
    int32_t alarm_sec, alarm_min, alarm_hour, cur_hour, cur_min, cur_sec;
    int32_t hour, min;
    struct domain *d = vrtc_domain(s);

    ASSERT(spin_is_locked(&s->lock));

    stop_timer(&s->alarm_timer);

    if (!(s->hw.cmos_data[RTC_REG_C] & RTC_AF) &&
            !(s->hw.cmos_data[RTC_REG_B] & RTC_SET))
    {
        s->current_tm = gmtime(get_localtime(d));
        rtc_copy_date(s);

        alarm_sec = from_bcd(s, s->hw.cmos_data[RTC_SECONDS_ALARM]);
        alarm_min = from_bcd(s, s->hw.cmos_data[RTC_MINUTES_ALARM]);
        alarm_hour = convert_hour(s, s->hw.cmos_data[RTC_HOURS_ALARM]);

        cur_sec = from_bcd(s, s->hw.cmos_data[RTC_SECONDS]);
        cur_min = from_bcd(s, s->hw.cmos_data[RTC_MINUTES]);
        cur_hour = convert_hour(s, s->hw.cmos_data[RTC_HOURS]);

        next_update_time = USEC_PER_SEC - (get_localtime_us(d) % USEC_PER_SEC);
        next_update_time = next_update_time * NS_PER_USEC + NOW();

        if ((s->hw.cmos_data[RTC_HOURS_ALARM] & 0xc0) == 0xc0)
        {
            if ((s->hw.cmos_data[RTC_MINUTES_ALARM] & 0xc0) == 0xc0)
            {
                if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                    next_alarm_sec = 1;
                else if (cur_sec < alarm_sec)
                    next_alarm_sec = alarm_sec - cur_sec;
                else
                    next_alarm_sec = alarm_sec + SEC_PER_MIN - cur_sec;
            }
            else
            {
                if (cur_min < alarm_min)
                {
                    min = alarm_min - cur_min;
                    next_alarm_sec = min * SEC_PER_MIN - cur_sec;
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec += 0;
                    else
                        next_alarm_sec += alarm_sec;
                }
                else if (cur_min == alarm_min)
                {
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec = 1;
                    else if (cur_sec < alarm_sec)
                        next_alarm_sec = alarm_sec - cur_sec;
                    else
                    {
                        min = alarm_min + MIN_PER_HOUR - cur_min;
                        next_alarm_sec =
                            alarm_sec + min * SEC_PER_MIN - cur_sec;
                    }
                }
                else
                {
                    min = alarm_min + MIN_PER_HOUR - cur_min;
                    next_alarm_sec = min * SEC_PER_MIN - cur_sec;
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec += 0;
                    else
                        next_alarm_sec += alarm_sec;
                }
            }
        }
        else
        {
            if (cur_hour < alarm_hour)
            {
                hour = alarm_hour - cur_hour;
                next_alarm_sec = hour * SEC_PER_HOUR -
                    cur_min * SEC_PER_MIN - cur_sec;
                if ((s->hw.cmos_data[RTC_MINUTES_ALARM] & 0xc0) == 0xc0)
                {
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec += 0;
                    else
                        next_alarm_sec += alarm_sec;
                }
                else
                {
                    next_alarm_sec += alarm_min * SEC_PER_MIN;
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec += 0;
                    else
                        next_alarm_sec += alarm_sec;
                }
            }
            else if (cur_hour == alarm_hour)
            {
                if ((s->hw.cmos_data[RTC_MINUTES_ALARM] & 0xc0) == 0xc0)
                {
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec = 1;
                    else if (cur_sec < alarm_sec)
                        next_alarm_sec = alarm_sec - cur_sec;
                    else
                        next_alarm_sec = alarm_sec + SEC_PER_MIN - cur_sec;
                }
                else if (cur_min < alarm_min)
                {
                    min = alarm_min - cur_min;
                    next_alarm_sec = min * SEC_PER_MIN - cur_sec;
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec += 0;
                    else
                        next_alarm_sec += alarm_sec;
                }
                else if (cur_min == alarm_min)
                {
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec = 1;
                    else if (cur_sec < alarm_sec)
                        next_alarm_sec = alarm_sec - cur_sec;
                    else
                    {
                        hour = alarm_hour + HOUR_PER_DAY - cur_hour;
                        next_alarm_sec = hour * SEC_PER_HOUR -
                            cur_min * SEC_PER_MIN - cur_sec;
                        next_alarm_sec += alarm_min * SEC_PER_MIN + alarm_sec;
                    }
                }
                else
                {
                    hour = alarm_hour + HOUR_PER_DAY - cur_hour;
                    next_alarm_sec = hour * SEC_PER_HOUR -
                        cur_min * SEC_PER_MIN - cur_sec;
                    next_alarm_sec += alarm_min * SEC_PER_MIN;
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec += 0;
                    else
                        next_alarm_sec += alarm_sec;
                }
            }
            else
            {
                hour = alarm_hour + HOUR_PER_DAY - cur_hour;
                next_alarm_sec = hour * SEC_PER_HOUR -
                    cur_min * SEC_PER_MIN - cur_sec;
                if ((s->hw.cmos_data[RTC_MINUTES_ALARM] & 0xc0) == 0xc0)
                {
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec += 0;
                    else
                        next_alarm_sec += alarm_sec;
                }
                else
                {
                    next_alarm_sec += alarm_min * SEC_PER_MIN;
                    if ((s->hw.cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0)
                        next_alarm_sec += 0;
                    else
                        next_alarm_sec += alarm_sec;
                }
            }
        }
        expire_time = (next_alarm_sec - 1) * NS_PER_SEC + next_update_time;
        /* release lock before set timer */
        spin_unlock(&s->lock);
        set_timer(&s->alarm_timer, expire_time);
        /* fetch lock again */
        spin_lock(&s->lock);
    }
}
Example #20
0
void hwTriggerWatchdog() {
    timeOfLastTriggerWatchdog = NOW();
}
Example #21
0
int domain_vtimer_init(struct domain *d)
{
    d->arch.phys_timer_base.offset = NOW();
    d->arch.virt_timer_base.offset = READ_SYSREG64(CNTPCT_EL0);
    return 0;
}
EventBase::EventBase(MMTIME t, uint8_t p)
    : m_p(new Private)
{
    m_p->timestamp = (t == 0) ? NOW() : t;
    m_p->priority = p;
}
Example #23
0
void mysql_search_logg(MYSQL *demo_db, struct QueryDataForamt *QueryData, 
	struct SiderHederFormat *FinalSiderHeder, int totlaAds, 
	struct queryNodeHederFormat *queryNodeHeder, int nrOfServers, struct SiderFormat *Sider, 
	int nrOfPiServers) {
	/********************************************************************************************/
	//mysql logging
	/********************************************************************************************/

#ifndef MYSQL_VERSION_ID

	#error "MYSQL_VERSION_ID fra mysql_version.h er ikke definert"

#elif MYSQL_VERSION_ID==50045


	MYSQL_STMT *logstmt, *pilogstmt;
	char query [2048];
	MYSQL_BIND bind[12];
	unsigned long len[12];
	memset(bind, 0, sizeof(bind));
	logstmt = mysql_stmt_init(demo_db);
	pilogstmt = mysql_stmt_init(demo_db);

	if ((logstmt==NULL) || (pilogstmt==NULL)) {
		fprintf(stderr, "out of memory. Cant Create logstmt or pilogstmt");
	}

	sprintf(query,"INSERT DELAYED INTO search_logg (tid,query,search_bruker,treff,search_tid,ip_adresse,betaler_keywords_treff,HTTP_ACCEPT_LANGUAGE,HTTP_USER_AGENT,HTTP_REFERER,GeoIPLang,side) VALUES(NOW(),?,?,?,?,?,?,?,?,?,?,?)");

	if (mysql_stmt_prepare(logstmt, query, strlen(query)) != 0) {
		fprintf(stderr, " mysql_stmt_prepare(), INSERT INTO search_logg failed\n");
		fprintf(stderr, " Error: \"%s\"\n", mysql_stmt_error(logstmt));			
		return;
	}

	bind[0].buffer_type = MYSQL_TYPE_STRING; // query
	bind[0].buffer = QueryData->query;	// Ax: Max lengde i databasen er 30 tegn. Lage en nice-write?
	len[0] = strlen(QueryData->query);
	bind[0].length = &len[0];

	bind[1].buffer_type = MYSQL_TYPE_STRING; // user
	bind[1].buffer = QueryData->search_user;
	len[1] = strlen(QueryData->search_user);
	bind[1].length = &len[1];

	if (FinalSiderHeder==NULL) {

		bind[2].buffer_type = MYSQL_TYPE_NULL; // treff
		bind[2].buffer = NULL;

		bind[3].buffer_type = MYSQL_TYPE_NULL; // sÃketid
		bind[3].buffer = NULL;
	}
	else {
		bind[2].buffer_type = MYSQL_TYPE_LONG; // treff
		bind[2].buffer = &FinalSiderHeder->TotaltTreff;

		bind[3].buffer_type = MYSQL_TYPE_DOUBLE; // sÃketid
		bind[3].buffer = &FinalSiderHeder->total_usecs;
	}
	bind[4].buffer_type = MYSQL_TYPE_STRING; // ip
	bind[4].buffer = QueryData->userip;
	len[4] = strlen(QueryData->userip);
	bind[4].length = &len[4];

	bind[5].buffer_type = MYSQL_TYPE_LONG; // betaler
	bind[5].buffer = &totlaAds;
		
	bind[6].buffer_type = MYSQL_TYPE_STRING; // http lang
	bind[6].buffer = QueryData->HTTP_ACCEPT_LANGUAGE;
	len[6] = strlen(QueryData->HTTP_ACCEPT_LANGUAGE);
	bind[6].length = &len[6];

	bind[7].buffer_type = MYSQL_TYPE_STRING; // http user agent
	bind[7].buffer = QueryData->HTTP_USER_AGENT;
	len[7] = strlen(QueryData->HTTP_USER_AGENT);
	bind[7].length = &len[7];

	bind[8].buffer_type = MYSQL_TYPE_STRING; // http referer
	bind[8].buffer = QueryData->HTTP_REFERER;
	len[8] = strlen(QueryData->HTTP_REFERER);
	bind[8].length = &len[8];

	bind[9].buffer_type = MYSQL_TYPE_STRING; // geoip
	bind[9].buffer = QueryData->GeoIPcontry;
	len[9] = strlen(QueryData->GeoIPcontry);
	bind[9].length = &len[9];

	bind[10].buffer_type = MYSQL_TYPE_LONG; // side
	bind[10].buffer = &QueryData->start;


	mysql_stmt_bind_param(logstmt, bind);

	mysql_stmt_execute(logstmt);
	mysql_stmt_close(logstmt);


	/************************************************************************************************
	Logging av Paid Inclusion til sql db.
	************************************************************************************************/
	#ifndef BLACK_BOX
		if (Sider != NULL) {
			sprintf(query,"insert into pi_search_logg (tid,query,treff,search_tid,ip_adresse,spot,piDocID ) \
				select NOW(),?,?,?,?,?,id from pi_sider where WWWDocID=? ");


			if (mysql_stmt_prepare(pilogstmt, query, strlen(query)) != 0) {
				fprintf(stderr, " mysql_stmt_prepare(), INSERT into pi_search_logg failed\n");
				fprintf(stderr, " %s\n", mysql_stmt_error(pilogstmt));
				return;
			}

			i = QueryData->MaxsHits * (QueryData->start -1);
			x = i;

			while ((x<(QueryData->MaxsHits * QueryData->start)) && (x<FinalSiderHeder->showabal) && (i < (queryNodeHeder->MaxsHits * (nrOfServers + nrOfPiServers)))) {

				if (!Sider[i].deletet) {
					dprintf("pi analyse. Subname \"%s\", pi \"%i\"\n",Sider[i].subname.subname, (int)Sider[i].subname.config.isPaidInclusion);

					if (Sider[i].subname.config.isPaidInclusion) {
						unsigned int spot;

						spot = x + 1;		

						memset(bind, 0, sizeof(bind));
						memset(len, 0, sizeof(len)); // må vi ha denne?

						bind[0].buffer_type = MYSQL_TYPE_STRING; // query
						bind[0].buffer = QueryData->query;
						len[0] = strlen(QueryData->query);
						bind[0].length = &len[0];
						
						bind[1].buffer_type = MYSQL_TYPE_LONG; // treff
						bind[1].buffer = &FinalSiderHeder->TotaltTreff;
						
						bind[2].buffer_type = MYSQL_TYPE_DOUBLE; // sÃketid
						bind[2].buffer = &FinalSiderHeder->total_usecs;
						
						bind[3].buffer_type = MYSQL_TYPE_STRING; // ip
						bind[3].buffer = QueryData->userip;
						len[3] = strlen(QueryData->userip);
						bind[3].length = &len[3];

						bind[4].buffer_type = MYSQL_TYPE_LONG ; // spot 
						bind[4].buffer = &spot;
						bind[4].is_unsigned = 1; 
		
						bind[5].buffer_type = MYSQL_TYPE_LONG; // piDocID
						bind[5].buffer = &Sider[i].iindex.DocID;
						bind[5].is_unsigned = 1; 


						if (mysql_stmt_bind_param(pilogstmt, bind) != 0) {
							fprintf(stderr, " mysql_stmt_bind_param() failed\n");
							fprintf(stderr, " %s\n", mysql_stmt_error(pilogstmt));
						}

						if (mysql_stmt_execute(pilogstmt) != 0) {
							fprintf(stderr, " mysql_stmt_execute(), 1 failed\n");
							fprintf(stderr, " %s\n", mysql_stmt_error(pilogstmt));
						}

						/* Get the total number of affected rows */
						affected_rows= mysql_stmt_affected_rows(pilogstmt);

						if (affected_rows != 1) /* validate affected rows */
						{
							fprintf(stderr, " invalid affected rows by MySQL\n");
							fprintf(stderr, " total affected rows(insert 1): %lu\n", (unsigned long) affected_rows);
							break;
						}
					}
					else {
						//dprintf("is NOT pi! :(\n");
					}
				}
				//teller bare normale sider (hva med Paid Inclusion ?)
				// Denne skal vel vaere innenfor !deletet?
				if (Sider[i].type == siderType_normal) {
					++x;
				}

				++i;
			}

			mysql_stmt_close(pilogstmt);
		}
Example #24
0
static void bep034_dump_record( bep034_hostrecord * hostrecord ) {
  int i;
  printf( "Hostname: %s\n Expiry in s: %ld\n", hostrecord->hostname, (long)(hostrecord->expiry - NOW()) );
  for( i=0; i<hostrecord->entries; ++i ) {
    printf( " Tracker at: %s Port %d\n", ( ( hostrecord->trackers[i] ) >> 16 == PROTO_UDP ) ? "UDP " : "HTTP", hostrecord->trackers[i] & 0xffff );
  }
  putchar( 10 );
}
Example #25
0
int Grab::getGrabNum(const string& user_id, string& num, int32_t is_pre)
{
	extern string IP;
	int res;
	string query_sql;
	//DuokooMysql mysql;
    DuokooMysql mysql("grab_mysql");
	if(!mysql.startTransaction()){
		return -5;
	}
	//get num from mysql
	//comment by zhengxie 2013.10.22
	/*query_sql="SELECT num FROM `MCP`.`mcp_content_grab_num` WHERE `is_occupy` = 0 AND `grab_id` = " + toString(_id) + " limit 0, 1";*/
	//UB_LOG_DEBUG("query_sql:[%s]", query_sql.c_str());
	//res=mysql.query(query_sql);
	//if(res<0){
		//UB_LOG_FATAL( "query sql[%s] failed, [%s], [%s:%d]", query_sql.c_str(), mysql.getErrDes().c_str(), __FILE__, __LINE__ );
		//mysql.rollback();
		//return -5;
	//}else if(res==0){
		//UB_LOG_FATAL( "query sql[%s] have no record, [%s:%d]", query_sql.c_str(), __FILE__, __LINE__ );
		//mysql.rollback();
		//return -3;
	//}
	/*num=mysql.getResult(0,0);*/

	/* 2013.10.22 add by zhengxie get num from mysql => get num from redis start */
	redisContext *c;
    uint32_t send_amount(0);
    c=redisConnPool::getInstance()->getConnection();
    if(c==NULL)
	{
        UB_LOG_FATAL( "get redis connection failed, [%s:%d]", __FILE__, __LINE__ );
        return -5;
    }
    redisReply *reply;
	/* 2013.12.03 add by zhengxie add lock */

	string thread_id = DuokooTools::toString(CommonInterface::get_thread_id());
	string random = DuokooTools::toString(getRandomNum(10000000));

	string key = "grab_and_user_id:" + DuokooTools::toString(_id) + "," + user_id;
	string value = IP + "," + thread_id + "," + random;

	redisCommand(c, "SETNX %s %s", key.c_str(), value.c_str());

	LOGD( "[zx]get_value key:%s ", key.c_str() );
    reply = (redisReply*)redisCommand( c, "GET %s", key.c_str() );

    redisConnPool::getInstance()->releaseConnection(c);
    if(reply!=NULL)
	{
        if(reply->type!=REDIS_REPLY_ERROR)
		{
            if(reply->type!=REDIS_REPLY_NIL)
			{
                string temp_value = reply->str;
				freeReplyObject(reply);
				reply = NULL;
				if(strcmp(temp_value.c_str(), value.c_str()))
				{
					LOGA( "[zx] shit, bad user[%s] ", user_id.c_str() );
					return -3;//同一个用户重复抢号
				}
            }
			else
			{
				freeReplyObject(reply);
				reply = NULL;
				return -3;
            }
		}
	}
	else
	{
		LOGA( "[zx] key not set[%s] ", key.c_str() );
		return -5;
	}

	/* 2013.12.03 add by zhengxie add lock */

	c=redisConnPool::getInstance()->getConnection();
    if(c==NULL)
	{
        UB_LOG_FATAL( "get redis connection failed, [%s:%d]", __FILE__, __LINE__ );
        return -5;
    }

	redisCommand(c, "EXPIRE %s %ld", key.c_str(), 10*24*60*60);
    //LOGD( "[zx]SPOP grab_id:%d ", _id );
    reply = (redisReply*)redisCommand( c, "SPOP grab_id:%d", _id );
    redisConnPool::getInstance()->releaseConnection(c);
    if(reply!=NULL)
	{
        if(reply->type!=REDIS_REPLY_ERROR)
		{
            if(reply->type!=REDIS_REPLY_NIL)
			{
                LOGA( "grab_id:[%d], user_id:[%s], grab_num:[%s]", _id, user_id.c_str(), reply->str );
                num=reply->str;
				freeReplyObject(reply);
				reply = NULL;
            }
			else
			{
				LOGD( "[zx] has no grab_nums grab_id[%d] ", _id );
				freeReplyObject(reply);
				reply = NULL;
				return -3;
            }
		}
	}
	else
	{
		LOGD( "[zx] not exist grab_id[%d] ", _id );
		return -5;
	}

	/* 2013.10.22 add by zhengxie get num from mysql => get num from redis end */
	//update num
	query_sql="UPDATE `MCP`.`mcp_content_grab_num` SET `is_occupy` = "+ toString(is_pre) +" WHERE num = '" + num + "' ";
	UB_LOG_DEBUG("query_sql:[%s]", query_sql.c_str());
	res=mysql.query(query_sql);
	if(res<0){
		UB_LOG_FATAL( "query sql[%s] failed, [%s], [%s:%d]", query_sql.c_str(), mysql.getErrDes().c_str(), __FILE__, __LINE__ );
		mysql.rollback();
		return -5;
	}
	//insert user_num
	query_sql="INSERT INTO `MCP`.`mcp_content_user_grab`( `id`, `grab_id`, `user_id`, `grab_time`, `use_time`, `num` )"
		"VALUES( NULL, '"+toString(_id)+"', '"+user_id+"', '"+NOW()+"', '0', '"+num+"' ) ";
	UB_LOG_DEBUG("query_sql:[%s]", query_sql.c_str());
	res=mysql.query(query_sql);
	if(res<0){
		UB_LOG_FATAL( "query sql[%s] failed, [%s], [%s:%d]", query_sql.c_str(), mysql.getErrDes().c_str(), __FILE__, __LINE__ );
		mysql.rollback();
		return -5;
	}
	return mysql.commit()?0:-5;
}
Example #26
0
/* This function expects the bep034_lock to be held by caller,
   releases it while working and returns with the lock held
*/
static bep034_status bep034_fill_hostrecord( const char * hostname, bep034_hostrecord ** hostrecord, uintptr_t dns_handle ) {
  uint8_t answer[NS_PACKETSZ];
  bep034_hostrecord * hr = 0;
  int answer_len, num_msgs, max_entries, i;
  ns_msg msg;
  ns_rr rr;

  /* Reset hostrecord pointer */
  * hostrecord = 0;

  /* If we find a record in cache, return it */
  hr = bep034_find_hostrecord( hostname, &i /* dummy */ );
  if( hr ) {
    *hostrecord = hr;
    return BEP_034_INPROGRESS;
  }

  /* Return mutex, we'll be blocking now and do not
     hold any resources in need of guarding  */
  bep034_dounlock();

  /* Query resolver for TXT records for the trackers domain */
#ifdef __MACH__
  {
    struct sockaddr tmp;
    uint32_t tmplen;
    answer_len = dns_search( (dns_handle_t)dns_handle, hostname, ns_c_in, ns_t_txt, answer, sizeof(answer), &tmp, &tmplen );
  }
#else
  (void)dns_handle;
  answer_len = res_search(hostname, ns_c_in, ns_t_txt, answer, sizeof(answer));
#endif
  if( answer_len < 0 ) {
    /* Here we enter race condition land */
    switch( h_errno ) {
    case NO_RECOVERY: case HOST_NOT_FOUND: return BEP_034_NXDOMAIN;
    case NO_DATA: return BEP_034_NORECORD;
    case NETDB_INTERNAL: case TRY_AGAIN: default: return BEP_034_TIMEOUT;
    }
  }

  ns_initparse (answer, answer_len, &msg);
  num_msgs = ns_msg_count (msg, ns_s_an);
  for( i=0; i<num_msgs; ++i) {
    ns_parserr (&msg, ns_s_an, i, &rr);
    if (ns_rr_class(rr) == ns_c_in && ns_rr_type(rr) == ns_t_txt ) {
      uint32_t record_ttl = ns_rr_ttl(rr);
      uint16_t record_len = ns_rr_rdlen(rr);
      const uint8_t *record_ptr = ns_rr_rdata(rr);
      const char * string_ptr, * string_end;

      /* First octet is length of (first) string in the txt record.
         Since BEP034 does not say anything about multiple strings,
         we ignore all but the first string in each TXT record. */
      uint8_t string_len = *record_ptr;

      /* If we would read beyond buffer end, ignore record */
      if( record_ptr + 1 + string_len > answer + answer_len )
        continue;

      /* Sanitize string length against record length */
      if( string_len + 1 > record_len )
        string_len = record_len - 1;

      /* Test if we are interested in the record */
      if( string_len < 10 /* strlen( "BITTORRENT" ) */ )
        continue;

      /* Although the BEP is not very specific, we interpret the wording
         "This should always be the first word in the record" as a requirment
         to not start the record with a space */
      if( memcmp( record_ptr + 1, "BITTORRENT", 10 ) )
        continue;

      /* We found a BITTORRENT TXT record. Now start parsing:
         Given entries of the form "UDP:\d+\s" i.e. 6 bytes,
         in a record of length N we have an upper bound of
         ( N - 11 ) / 6 records.
      */
      max_entries = 1 + ( string_len - 11 ) / 6;

      /* Allocate memory for host record */
      hr = (bep034_hostrecord*)
        malloc( sizeof(bep034_hostrecord) + sizeof( uint32_t ) * max_entries );
      if( !hr )
        return BEP_034_TIMEOUT;

      /* Init host record */
      hr->hostname = strdup( hostname );
      hr->entries = 0;
      hr->expiry = NOW() + record_ttl;

      /* Look for "\s(TCP|UDP):\d+" */
      string_ptr = record_ptr + 1;
      string_end = string_ptr + string_len;
      string_ptr += 10 /* strlen( "BITTORRENT" ) */;

      while( string_ptr + 6 < string_end ) { /* We need at least 6 bytes for a word */
        int found;
        uint32_t port = 0;

        ++string_ptr;
        if( string_ptr[-1] != ' ' || string_ptr[2] != 'P' || string_ptr[3] != ':' )
          continue;
        if( string_ptr[0] == 'T' && string_ptr[1] == 'C' )
          found = 0;
        else if( string_ptr[0] == 'U' && string_ptr[1] == 'D' )
          found = 1;
        else
          continue;

        /* Now we're sure, we've found UDP: or TCP: and assume, from string_ptr + 4 there's
           a port number*/
        string_ptr += 4;
        while( string_ptr < string_end && (*string_ptr >= '0' && *string_ptr <= '9' ) )
          port = port * 10 + *(string_ptr++) - '0';

        /* If no digit was found, word is invalid */
        if( string_ptr[-1] == ':' ) continue;

        /* If number did not terminate on end of string or with a space, word is invalid */
        if( string_ptr != string_end && *string_ptr != ' ' ) continue;

        /* If we have an invalid port number, word is invalid */
        if( port > 65335 ) continue;

        /* Valid word found, add it to tracker list */
        hr->trackers[ hr->entries++ ] = port | ( found ? 0x10000 : 0 );
      }

      /* Ensure exclusive access to the host record list, lock will be held
         on return so that the caller can work with hr */
      bep034_dolock();

      /* Hand over record to cache, from now the cache has to release memory */
      if( bep034_save_record( &hr ) )
        return BEP_034_TIMEOUT;

      /* Dump what we found */
      bep034_dump_record( hr );

      /* Once the first line in the first record has been parsed, return host record */
      *hostrecord = hr;
      return BEP_034_INPROGRESS;
    }
  }
}
Example #27
0
static void BEGIN()
{
    total_bytes = 0;
    start_time = NOW();
}
Example #28
0
File: disk.cpp Project: Ypalav/cbm
void diskt(char *cmd, bool is_random, int block_size, int n_thread)
{
  boost::thread worker[n_thread];
  unsigned long size = 0;
  double dur = 0.0;
  long test_size = 1024*1024*1024;

  if(is_random)
  {
    if(strcmp(cmd, "read")==0)
    {
      for(int i=0;i<n_thread;++i)
      {
        std::stringstream file_out;
        file_out << "/tmp/" << test_size << "B." << i << ".tst";

        if(cbm::make_ran_file(test_size, file_out.str()) < 0)
          return;
        
        worker[i] = boost::thread(disk_read_ran_worker, file_out.str(), test_size, block_size);
      }
    }
    else if(strcmp(cmd, "write")==0)
    {
      for(int i=0;i<n_thread;++i)
      {
        std::stringstream file_out;
        file_out << "/tmp/" << test_size << "B." << i << ".tst";

        if(cbm::make_ran_file(test_size, file_out.str()) < 0)
          return;

        worker[i] = boost::thread(disk_write_ran_worker, file_out.str(), test_size, block_size);
      }
    }
  }
  else
  {
    if(strcmp(cmd, "read")==0)
    {
      for(int i=0;i<n_thread;++i)
      {
        std::stringstream file_out;
        file_out << "/tmp/" << test_size << "B." << i << ".tst";

        if(cbm::make_ran_file(test_size, file_out.str()) < 0)
          return;
        
        worker[i] = boost::thread(disk_read_seq_worker, file_out.str(), block_size);
      }
    }
    else if(strcmp(cmd, "write")==0)
    {
      for(int i=0;i<n_thread;++i)
      {
        std::stringstream file_out;
        file_out << "/tmp/" << test_size << "B." << i << ".tst";

        if(cbm::make_ran_file(test_size, file_out.str()) < 0)
          return;

        worker[i] = boost::thread(disk_write_seq_worker, file_out.str(), block_size);
      }
    }
  }

  auto start = NOW();
  for(int j=0;j<n_thread;++j)
    worker[j].join();
  auto end = NOW();
  dur = DURATION(end, start);

  size = (unsigned long)(block_size) * n_thread;
  cbm::print_results(cmd, is_random, block_size, n_thread, size, dur);
}
Example #29
0
/* Handle the recv of otherwise unhandled packets */
void default_packet_rec(struct default_rec_st *rec_info)
{
    card_st     *cdst;
    char	*rxbuf;
    word_t	value;
    IO_Rec	rxrecs[2];
    int		header_size = 128;
    int		mtu = 1514;	/* XXX hardwired constants */
    int		i;
    intf_st	*intfp; 
    iphost_st	*host_st;
    bool_t	ok = False;    
    Net_IPHostAddr ipaddr;
    Net_IPHostAddr *ipaddrp;
    char	buf[32];
    uint32_t	rec_recs;       /* nr of recs the received in call */

    TRC(printf("packet recv running\n"));

    cdst    = rec_info->mycard;
    host_st = rec_info->myhost;
    intfp   = rec_info->intf;


    sprintf(buf, "svc>net>%s>ipaddr", intfp->name);
    ipaddrp = NAME_FIND(buf, Net_IPHostAddrP);
    ipaddr = *ipaddrp;

    intfp->def_txfilt = LMPFMod$NewTXDef(cdst->pfmod, cdst->mac, ipaddr.a);

    getDxIOs(cdst->netif, intfp->def_txfilt, "DEF",
		     /* RETURNS: */
		     &intfp->def_rxhdl, &intfp->def_txhdl,
		     &intfp->io_rx,      &intfp->io_tx,
		     &intfp->def_rxoff, &intfp->def_txoff,
		     &intfp->def_heap);

    /* sanity check what we got  */
    if (intfp->def_rxoff == NULL || intfp->def_rxhdl==0)
        printf("flowman: error: bad recv handle or offer\n");
    if (intfp->io_tx == NULL)
        printf("flowman: default handler: tx bind failed\n");    
    if (intfp->io_rx == NULL)
        printf("flowman: default handler: rx bind failed\n");
    if (intfp->def_heap == NULL)
        printf("flowman: default handler: def_heap == NULL\n");

    ok = Netif$SetTxFilter(cdst->netif, intfp->def_txhdl, intfp->def_txfilt);
    if (!ok)
        printf("flowman: cannot set tx filter\n");

    /* install default filter */
    ok = LMPFCtl$SetDefault(cdst->rx_pfctl, intfp->def_rxhdl);
    if (!ok)
        printf("flowman: cannot set rx default filter\n");

    /* set xxstat to 0 */
    memset(&host_st->ipstat,  0, sizeof(ipstat_st));
    memset(&host_st->tcpstat, 0, sizeof(tcpstat_st));
    memset(&host_st->udpstat, 0, sizeof(udpstat_st));

     /* Thiemo: should be something with time of day, so that it grows
      * after crashing */
    host_st->ip_id = NOW() & 0xffff;

    mtu = ALIGN4(mtu);

#define PIPEDEPTH 16
    rxbuf = Heap$Malloc(intfp->def_heap, PIPEDEPTH * (mtu + header_size));
    
    for(i=0; i<PIPEDEPTH; i++)
    {
        /* chop up memory */
        rxrecs[0].base = rxbuf + i*(mtu+header_size);
        rxrecs[0].len  = header_size;
        rxrecs[1].base = rxbuf + i*(mtu+header_size) + header_size;
        rxrecs[1].len  = mtu;

        /* send recs */
//	TRC(printf("prime : %p+%d %p+%d \n",
//		   rxrecs[0].base, rxrecs[0].len,
//		   rxrecs[1].base, rxrecs[1].len));

	/* Actually, want to skip the first 2 bytes of header, so Ethernet
	 * frames land mis-aligned, but IP layer and up is correctly
	 * aligned */
	((char *)rxrecs[0].base) += 2;
	rxrecs[0].len -= 2;
        if (!IO$PutPkt(intfp->io_rx, 2, rxrecs, 0, 0))
	    printf("flowman: default prime %d failed\n", i);

//        TRC(printf("prime %d sent\n", i));
    }

    while (1)
    {
        /* loop and get incoming packets */
	DTRC(printf("flowman: default: waiting for packet..\n"));
        
        IO$GetPkt(intfp->io_rx, 2, rxrecs, FOREVER, &rec_recs, &value);
	((char *)rxrecs[0].base) -= 2;
	rxrecs[0].len  += 2;

        DTRC(printf("flowman: got packet on default channel, "
		    "nr of IO_Recs %d, rec[0].len=%d\n",
		    rec_recs, rxrecs[0].len));

        ether_input(rxrecs, rec_recs, cdst->mac, host_st);

        /* send down an empty packet after adapting to orig. size */
	/* XXX check base */
        rxrecs[0].len = header_size;
        rxrecs[1].len = mtu-header_size;

	/* again, send down the version which is advanced slightly */
	((char *)rxrecs[0].base) += 2;
	rxrecs[0].len -= 2;
	IO$PutPkt(intfp->io_rx, 2, rxrecs, 0, 0);
    }
}
Example #30
0
/***********************************************************************
 * Main code + dispatcher
 **********************************************************************/
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;
    std::string rx_subdev, tx_subdev;
    double duration;
    double rx_rate, tx_rate;
    std::string rx_otw, tx_otw;
    std::string rx_cpu, tx_cpu;
    std::string mode, ref, pps;
    std::string channel_list, rx_channel_list, tx_channel_list;
    bool random_nsamps = false;
    std::atomic<bool> burst_timer_elapsed(false);
    size_t overrun_threshold, underrun_threshold, drop_threshold, seq_threshold;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args")
        ("duration", po::value<double>(&duration)->default_value(10.0), "duration for the test in seconds")
        ("rx_subdev", po::value<std::string>(&rx_subdev), "specify the device subdev for RX")
        ("tx_subdev", po::value<std::string>(&tx_subdev), "specify the device subdev for TX")
        ("rx_rate", po::value<double>(&rx_rate), "specify to perform a RX rate test (sps)")
        ("tx_rate", po::value<double>(&tx_rate), "specify to perform a TX rate test (sps)")
        ("rx_otw", po::value<std::string>(&rx_otw)->default_value("sc16"), "specify the over-the-wire sample mode for RX")
        ("tx_otw", po::value<std::string>(&tx_otw)->default_value("sc16"), "specify the over-the-wire sample mode for TX")
        ("rx_cpu", po::value<std::string>(&rx_cpu)->default_value("fc32"), "specify the host/cpu sample mode for RX")
        ("tx_cpu", po::value<std::string>(&tx_cpu)->default_value("fc32"), "specify the host/cpu sample mode for TX")
        ("ref", po::value<std::string>(&ref), "clock reference (internal, external, mimo, gpsdo)")
        ("pps", po::value<std::string>(&pps), "PPS source (internal, external, mimo, gpsdo)")
        ("mode", po::value<std::string>(&mode), "DEPRECATED - use \"ref\" and \"pps\" instead (none, mimo)")
        ("random", "Run with random values of samples in send() and recv() to stress-test the I/O.")
        ("channels", po::value<std::string>(&channel_list)->default_value("0"), "which channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
        ("rx_channels", po::value<std::string>(&rx_channel_list), "which RX channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
        ("tx_channels", po::value<std::string>(&tx_channel_list), "which TX channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
        ("overrun-threshold", po::value<size_t>(&overrun_threshold),
         "Number of overruns (O) which will declare the benchmark a failure.")
        ("underrun-threshold", po::value<size_t>(&underrun_threshold),
         "Number of underruns (U) which will declare the benchmark a failure.")
        ("drop-threshold", po::value<size_t>(&drop_threshold),
         "Number of dropped packets (D) which will declare the benchmark a failure.")
        ("seq-threshold", po::value<size_t>(&seq_threshold),
         "Number of dropped packets (D) which will declare the benchmark a failure.")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help") or (vm.count("rx_rate") + vm.count("tx_rate")) == 0){
        std::cout << boost::format("UHD Benchmark Rate %s") % desc << std::endl;
        std::cout <<
        "    Specify --rx_rate for a receive-only test.\n"
        "    Specify --tx_rate for a transmit-only test.\n"
        "    Specify both options for a full-duplex test.\n"
        << std::endl;
        return ~0;
    }

    // Random number of samples?
    if (vm.count("random")) {
        std::cout << "Using random number of samples in send() and recv() calls." << std::endl;
        random_nsamps = true;
    }

    if (vm.count("mode")) {
        if (vm.count("pps") or vm.count("ref")) {
            std::cout << "ERROR: The \"mode\" parameter cannot be used with the \"ref\" and \"pps\" parameters.\n" << std::endl;
            return -1;
        } else if (mode == "mimo") {
            ref = pps = "mimo";
            std::cout << "The use of the \"mode\" parameter is deprecated.  Please use \"ref\" and \"pps\" parameters instead\n" << std::endl;
        }
    }

    //create a usrp device
    std::cout << std::endl;
    uhd::device_addrs_t device_addrs = uhd::device::find(args, uhd::device::USRP);
    if (not device_addrs.empty() and device_addrs.at(0).get("type", "") == "usrp1"){
        std::cerr << "*** Warning! ***" << std::endl;
        std::cerr << "Benchmark results will be inaccurate on USRP1 due to insufficient features.\n" << std::endl;
    }
    boost::posix_time::ptime start_time(boost::posix_time::microsec_clock::local_time());
    std::cout << boost::format("[%s] Creating the usrp device with: %s...") % NOW() % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);

    //always select the subdevice first, the channel mapping affects the other settings
    if (vm.count("rx_subdev")) {
        usrp->set_rx_subdev_spec(rx_subdev);
    }
    if (vm.count("tx_subdev")) {
        usrp->set_tx_subdev_spec(tx_subdev);
    }

    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;
    int num_mboards = usrp->get_num_mboards();

    boost::thread_group thread_group;

    if(vm.count("ref"))
    {
        if (ref == "mimo")
        {
            if (num_mboards != 2) {
                std::cerr << "ERROR: ref = \"mimo\" implies 2 motherboards; your system has " << num_mboards << " boards" << std::endl;
                return -1;
            }
            usrp->set_clock_source("mimo",1);
        } else {
            usrp->set_clock_source(ref);
        }

        if(ref != "internal") {
            std::cout << "Now confirming lock on clock signals..." << std::endl;
            bool is_locked = false;
            auto end_time =
                boost::get_system_time() +
                boost::posix_time::milliseconds(CLOCK_TIMEOUT);
            for (int i = 0; i < num_mboards; i++) {
                if (ref == "mimo" and i == 0) continue;
                while((is_locked = usrp->get_mboard_sensor("ref_locked",i).to_bool()) == false and
                            boost::get_system_time() < end_time )
                {
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));
                }
                if (is_locked == false) {
                    std::cerr << "ERROR: Unable to confirm clock signal locked on board:" << i <<  std::endl;
                    return -1;
                }
                is_locked = false;
            }
        }
    }

    if(vm.count("pps"))
    {
       if(pps == "mimo")
       {
           if (num_mboards != 2) {
               std::cerr << "ERROR: ref = \"mimo\" implies 2 motherboards; your system has " << num_mboards << " boards" << std::endl;
               return -1;
           }
           //make mboard 1 a slave over the MIMO Cable
           usrp->set_time_source("mimo", 1);
       } else {
           usrp->set_time_source(pps);
       }
    }

    //check that the device has sufficient RX and TX channels available
    std::vector<std::string> channel_strings;
    std::vector<size_t> rx_channel_nums;
    if (vm.count("rx_rate")) {
        if (!vm.count("rx_channels")) {
            rx_channel_list = channel_list;
        }

        boost::split(channel_strings, rx_channel_list, boost::is_any_of("\"',"));
        for (size_t ch = 0; ch < channel_strings.size(); ch++) {
            size_t chan = std::stoul(channel_strings[ch]);
            if (chan >= usrp->get_rx_num_channels()) {
                throw std::runtime_error("Invalid channel(s) specified.");
            } else {
                rx_channel_nums.push_back(std::stoul(channel_strings[ch]));
            }
        }
    }

    std::vector<size_t> tx_channel_nums;
    if (vm.count("tx_rate")) {
        if (!vm.count("tx_channels")) {
            tx_channel_list = channel_list;
        }

        boost::split(channel_strings, tx_channel_list, boost::is_any_of("\"',"));
        for (size_t ch = 0; ch < channel_strings.size(); ch++) {
            size_t chan = std::stoul(channel_strings[ch]);
            if (chan >= usrp->get_tx_num_channels()) {
                throw std::runtime_error("Invalid channel(s) specified.");
            } else {
                tx_channel_nums.push_back(std::stoul(channel_strings[ch]));
            }
        }
    }

    std::cout << boost::format("[%s] Setting device timestamp to 0...") % NOW() << std::endl;
    if (pps == "mimo" or ref == "mimo") {
        // only set the master's time, the slave's is automatically sync'd
        usrp->set_time_now(uhd::time_spec_t(0.0), 0);
        // ensure that the setter has completed
        usrp->get_time_now();
        // wait for the time to sync
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    } else if (rx_channel_nums.size() > 1 or tx_channel_nums.size() > 1) {
        usrp->set_time_unknown_pps(uhd::time_spec_t(0.0));
    } else {
        usrp->set_time_now(0.0);
    }

    //spawn the receive test thread
    if (vm.count("rx_rate")){
        usrp->set_rx_rate(rx_rate);
        //create a receive streamer
        uhd::stream_args_t stream_args(rx_cpu, rx_otw);
        stream_args.channels = rx_channel_nums;
        uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);
        auto rx_thread = thread_group.create_thread([=, &burst_timer_elapsed](){
            benchmark_rx_rate(
                usrp,
                rx_cpu,
                rx_stream,
                random_nsamps,
                start_time,
                burst_timer_elapsed
            );
        });
        uhd::set_thread_name(rx_thread, "bmark_rx_stream");
    }

    //spawn the transmit test thread
    if (vm.count("tx_rate")){
        usrp->set_tx_rate(tx_rate);
        //create a transmit streamer
        uhd::stream_args_t stream_args(tx_cpu, tx_otw);
        stream_args.channels = tx_channel_nums;
        uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);
        auto tx_thread = thread_group.create_thread([=, &burst_timer_elapsed](){
            benchmark_tx_rate(
                usrp,
                tx_cpu,
                tx_stream,
                burst_timer_elapsed,
                start_time,
                random_nsamps
            );
        });
        uhd::set_thread_name(tx_thread, "bmark_tx_stream");
        auto tx_async_thread = thread_group.create_thread([=, &burst_timer_elapsed](){
            benchmark_tx_rate_async_helper(
                tx_stream,
                start_time,
                burst_timer_elapsed
            );
        });
        uhd::set_thread_name(tx_async_thread, "bmark_tx_helper");
    }

    //sleep for the required duration
    const bool wait_for_multichan =
        (rx_channel_nums.size() <= 1 and tx_channel_nums.size() <= 1);
    const int64_t secs =
        int64_t(duration + (wait_for_multichan ? 0 : INIT_DELAY * 1000));
    const int64_t usecs = int64_t((duration - secs)*1e6);
    std::this_thread::sleep_for(
        std::chrono::seconds(secs) +
        std::chrono::microseconds(usecs)
    );

    //interrupt and join the threads
    burst_timer_elapsed = true;
    thread_group.join_all();

    std::cout << "[" << NOW() << "] Benchmark complete." << std::endl << std::endl;

    //print summary
    const std::string threshold_err(" ERROR: Exceeds threshold!");
    const bool overrun_threshold_err =
        vm.count("overrun-threshold") and
        num_overruns > overrun_threshold;
    const bool underrun_threshold_err =
        vm.count("underrun-threshold") and
        num_underruns > underrun_threshold;
    const bool drop_threshold_err =
        vm.count("drop-threshold") and
        num_seqrx_errors > drop_threshold;
    const bool seq_threshold_err =
        vm.count("seq-threshold") and
        num_seq_errors > seq_threshold;
    std::cout << std::endl
        << boost::format(
                "Benchmark rate summary:\n"
                "  Num received samples:     %u\n"
                "  Num dropped samples:      %u\n"
                "  Num overruns detected:    %u\n"
                "  Num transmitted samples:  %u\n"
                "  Num sequence errors (Tx): %u\n"
                "  Num sequence errors (Rx): %u\n"
                "  Num underruns detected:   %u\n"
                "  Num late commands:        %u\n"
                "  Num timeouts (Tx):        %u\n"
                "  Num timeouts (Rx):        %u\n"
            ) % num_rx_samps
              % num_dropped_samps
              % num_overruns
              % num_tx_samps
              % num_seq_errors
              % num_seqrx_errors
              % num_underruns
              % num_late_commands
              % num_timeouts_tx
              % num_timeouts_rx
        << std::endl;
    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    if (overrun_threshold_err
            || underrun_threshold_err
            || drop_threshold_err
            || seq_threshold_err) {
        std::cout << "The following error thresholds were exceeded:\n";
        if (overrun_threshold_err) {
            std::cout
                << boost::format("  * Overruns (%d/%d)")
                   % num_overruns
                   % overrun_threshold
                << std::endl;
        }
        if (underrun_threshold_err) {
            std::cout
                << boost::format("  * Underruns (%d/%d)")
                   % num_underruns
                   % underrun_threshold
                << std::endl;
        }
        if (drop_threshold_err) {
            std::cout
                << boost::format("  * Dropped packets (RX) (%d/%d)")
                   % num_seqrx_errors
                   % drop_threshold
                << std::endl;
        }
        if (seq_threshold_err) {
            std::cout
                << boost::format("  * Dropped packets (TX) (%d/%d)")
                   % num_seq_errors
                   % seq_threshold
                << std::endl;
        }
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}