Esempio n. 1
0
const struct sensors_input_cache_entry_t *sensors_input_cache_get(
							const char *name)
{
	int rc;
	int fd;
	DIR *dir;
	struct dirent * item;
	struct list_node *member;
	struct input_dev_list *temp;
	pthread_t id[MAX_EVENT_DRIVERS];
	unsigned int i = 0;
	unsigned int threads = 0;
	const struct sensors_input_cache_entry_t *found = NULL;

	pthread_mutex_lock(&util_mutex);
	if (!list_initialized) {
		node_init(&head);
		list_initialized = 1;
	}

	temp = lookup(name, NULL);
	if (temp) {
		found = &temp->entry;
		goto exit;
	}

	dir = opendir(INPUT_EVENT_DIR);
	if (!dir) {
		ALOGE("%s: error opening '%s'\n", __func__,
				INPUT_EVENT_DIR);
		goto exit;
	}

	while ((item = readdir(dir)) != NULL) {
		if (strncmp(item->d_name, INPUT_EVENT_BASENAME,
		    sizeof(INPUT_EVENT_BASENAME) - 1) != 0) {
			continue;
		}

		temp = (temp ? temp : malloc(sizeof(*temp)));
		if (temp == NULL) {
			ALOGE("%s: malloc error!\n", __func__);
			break;
		}

		/* skip already cached entries */
		snprintf(temp->entry.event_path, sizeof(temp->entry.event_path),
			 "%s%s", INPUT_EVENT_DIR, item->d_name);
		if (lookup(NULL, temp->entry.event_path))
			continue;

		/* make sure we have access */
		fd = open(temp->entry.event_path, O_RDONLY);
		if (fd < 0) {
			ALOGE("%s: cant open %s", __func__,
			     item->d_name);
			continue;
		}

		rc = ioctl(fd, EVIOCGNAME(sizeof(temp->entry.dev_name)),
				temp->entry.dev_name);

		/* close in parallell to optimize boot time */
		pthread_create(&id[threads++], NULL,
				close_input_dev_fd, (void*) fd);

		if (rc < 0) {
			ALOGE("%s: cant get name from  %s", __func__,
					item->d_name);
			continue;
		}

		temp->entry.nr = atoi(item->d_name +
				      sizeof(INPUT_EVENT_BASENAME) - 1);

		node_add(&head, &temp->node);
		if (!found && !strncmp(temp->entry.dev_name, name,
				       sizeof(temp->entry.dev_name) - 1))
			found = &temp->entry;
		temp = NULL;
	}

	closedir(dir);

	for(i = 0; i < threads; ++i)
		pthread_join(id[i], NULL);

exit:
	pthread_mutex_unlock(&util_mutex);
	return found;
}
static void unlock()
{
    pthread_mutex_unlock(&lock_loggable);
}
inline void interprocess_recursive_mutex::unlock()
{
   int res = 0;
   res = pthread_mutex_unlock(&m_mut);
   assert(res == 0);
}
Esempio n. 4
0
void slabs_rebalancer_resume(void) {
    pthread_mutex_unlock(&slabs_rebalance_lock);
}
Esempio n. 5
0
/* The main listening loop for the object. */
static alib_error listen_loop(ClientListener* listener)
{
	if(!listener)return(ALIB_BAD_ARG);

	int rval;
	int event_count;
	struct epoll_event* event_it;
	long data_in_count;
	void* data_in_buff = malloc(DEFAULT_INPUT_BUFF_SIZE);

	/* Ensure we were able to allocate the data in buffer. */
	if(!data_in_buff)
	{
		rval = ALIB_MEM_ERR;
		goto f_return;
	}

	/* While our socket is open, then we will keep running. */
	while(!(listener->flag_pole & THREAD_STOP))
	{
		/* If the array list is empty, then we simply wait until something is added
		 * to it or our thread is called to stop. */
		if(!ArrayList_get_count(listener->client_list))
		{
			/* Call the empty list callback. */
			if(listener->client_list_empty)
			{
				int rval = listener->client_list_empty(listener);
				if(rval & SCB_RVAL_STOP_SERVER)
					break;
			}

			pthread_mutex_lock(&listener->mutex);
			while(!ArrayList_get_count(listener->client_list) && !(listener->flag_pole & THREAD_STOP))
				pthread_cond_wait(&listener->t_cond, &listener->mutex);
			pthread_mutex_unlock(&listener->mutex);
			continue;
		}

		/* Wait for an event to come. */
		event_count = epoll_wait(listener->ep.efd, listener->ep.triggered_events, DEFAULT_BACKLOG_SIZE,
				1000);
		if(!event_count)continue;

		/* The the event_count is less than zero, then an error occurred. */
		if(event_count < 0)
		{
			if(listener->flag_pole & THREAD_STOP)
				rval = ALIB_OK;
			else
			{
				if(listener->ep.efd > -1)
					continue;
				rval = ALIB_CHECK_ERRNO;
			}

			goto f_return;
		}

		/* Iterate through the events. */
		if(pthread_mutex_lock(&listener->mutex))
		{
			rval = ALIB_MUTEX_ERR;
			goto f_return;
		}
		for(event_it = listener->ep.triggered_events; event_count > 0; ++event_it, --event_count)
		{
			/* Use compare_int_ptr as the first member in the socket package
			 * is an integer. */
			socket_package* client = (socket_package*)ArrayList_find_item_by_value_tsafe(
					listener->client_list, &event_it->data.fd, compare_int_ptr);
			if(!client)
			{
				close(listener->ep.triggered_events->data.fd);
				continue;
			}

			/* Error occurred on the socket. */
			if((event_it->events & (EPOLLERR | EPOLLHUP)) ||
					!(event_it->events & EPOLLIN))
			{
				ArrayList_remove_tsafe(listener->client_list, client);
				continue;
			}

			/* Call the client_data_ready callback. */
			if(listener->data_ready)
			{
				rval = listener->data_ready(listener, client, &data_in_buff,
						&data_in_count);
				if(rval & SCB_RVAL_CLOSE_CLIENT)
					ArrayList_remove_tsafe(listener->client_list, client);
				if(rval & SCB_RVAL_STOP_SERVER)
				{
					rval = ALIB_OK;
					flag_raise(&listener->flag_pole, THREAD_STOP);
					if(pthread_mutex_unlock(&listener->mutex))
						rval = ALIB_MUTEX_ERR;
					goto f_return;
				}

				if(rval & (SCB_RVAL_HANDLED | SCB_RVAL_CLOSE_CLIENT))
					continue;

			}
			else
			{
				data_in_count = recv(client->sock, data_in_buff,
						DEFAULT_INPUT_BUFF_SIZE, 0);
			}

			/* If the client's socket was closed, then we just remove it
			 * from the list. */
			if(data_in_count < 1)
				ArrayList_remove_tsafe(listener->client_list, client);
			/* Call the client data in callback. */
			else if(listener->data_in)
			{
				rval = listener->data_in(listener, client, data_in_buff,
						data_in_count);
				if(rval & SCB_RVAL_CLOSE_CLIENT)
					ArrayList_remove_tsafe(listener->client_list, client);
				if(rval & SCB_RVAL_STOP_SERVER)
				{
					rval = ALIB_OK;
					if(pthread_mutex_unlock(&listener->mutex))
						rval = ALIB_MUTEX_ERR;
					goto f_return;
				}
			}
		}
		if(pthread_mutex_unlock(&listener->mutex))
		{
			rval = ALIB_MUTEX_ERR;
			goto f_return;
		}
	}

	rval = ALIB_OK;

f_return:
	if(data_in_buff)
		free(data_in_buff);

	return(rval);
}
Esempio n. 6
0
void slabs_free(void *ptr, size_t size, unsigned int id) {
    pthread_mutex_lock(&slabs_lock);
    do_slabs_free(ptr, size, id);
    pthread_mutex_unlock(&slabs_lock);
}
Esempio n. 7
0
/* refcount == 0 is safe since nobody can incr while cache_lock is held.
 * refcount != 0 is impossible since flags/etc can be modified in other
 * threads. instead, note we found a busy one and bail. logic in do_item_get
 * will prevent busy items from continuing to be busy
 */
static int slab_rebalance_move(void) {
    slabclass_t *s_cls;
    int x;
    int was_busy = 0;
    int refcount = 0;
    enum move_status status = MOVE_PASS;

    pthread_mutex_lock(&cache_lock);
    pthread_mutex_lock(&slabs_lock);

    s_cls = &slabclass[slab_rebal.s_clsid];

    for (x = 0; x < slab_bulk_check; x++) {
        item *it = slab_rebal.slab_pos;
        status = MOVE_PASS;
        if (it->slabs_clsid != 255) {
            void *hold_lock = NULL;
            uint32_t hv = hash(ITEM_key(it), it->nkey, 0);
            if ((hold_lock = item_trylock(hv)) == NULL) {
                status = MOVE_LOCKED;
            } else {
                refcount = refcount_incr(&it->refcount);
                if (refcount == 1) { /* item is unlinked, unused */
                    if (it->it_flags & ITEM_SLABBED) {
                        /* remove from slab freelist */
                        if (s_cls->slots == it) {
                            s_cls->slots = it->next;
                        }
                        if (it->next) it->next->prev = it->prev;
                        if (it->prev) it->prev->next = it->next;
                        s_cls->sl_curr--;
                        status = MOVE_DONE;
                    } else {
                        status = MOVE_BUSY;
                    }
                } else if (refcount == 2) { /* item is linked but not busy */
                    if ((it->it_flags & ITEM_LINKED) != 0) {
                        do_item_unlink_nolock(it, hv);
                        status = MOVE_DONE;
                    } else {
                        /* refcount == 1 + !ITEM_LINKED means the item is being
                         * uploaded to, or was just unlinked but hasn't been freed
                         * yet. Let it bleed off on its own and try again later */
                        status = MOVE_BUSY;
                    }
                } else {
                    if (settings.verbose > 2) {
                        fprintf(stderr, "Slab reassign hit a busy item: refcount: %d (%d -> %d)\n",
                            it->refcount, slab_rebal.s_clsid, slab_rebal.d_clsid);
                    }
                    status = MOVE_BUSY;
                }
                item_trylock_unlock(hold_lock);
            }
        }

        switch (status) {
            case MOVE_DONE:
                it->refcount = 0;
                it->it_flags = 0;
                it->slabs_clsid = 255;
                break;
            case MOVE_BUSY:
                refcount_decr(&it->refcount);
            case MOVE_LOCKED:
                slab_rebal.busy_items++;
                was_busy++;
                break;
            case MOVE_PASS:
                break;
        }

        slab_rebal.slab_pos = (char *)slab_rebal.slab_pos + s_cls->size;
        if (slab_rebal.slab_pos >= slab_rebal.slab_end)
            break;
    }

    if (slab_rebal.slab_pos >= slab_rebal.slab_end) {
        /* Some items were busy, start again from the top */
        if (slab_rebal.busy_items) {
            slab_rebal.slab_pos = slab_rebal.slab_start;
            slab_rebal.busy_items = 0;
        } else {
            slab_rebal.done++;
        }
    }

    pthread_mutex_unlock(&slabs_lock);
    pthread_mutex_unlock(&cache_lock);

    return was_busy;
}
Esempio n. 8
0
static void *video_thread( void *arg )
{
    // Identify the arg
    consumer_sdl self = arg;

    // Obtain time of thread start
    struct timeval now;
    int64_t start = 0;
    int64_t elapsed = 0;
    struct timespec tm;
    mlt_frame next = NULL;
    mlt_properties properties = NULL;
    double speed = 0;

    // Get real time flag
    int real_time = mlt_properties_get_int( self->properties, "real_time" );

    // Get the current time
    gettimeofday( &now, NULL );

    // Determine start time
    start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;

    while ( self->running )
    {
        // Pop the next frame
        pthread_mutex_lock( &self->video_mutex );
        next = mlt_deque_pop_front( self->queue );
        while ( next == NULL && self->running )
        {
            pthread_cond_wait( &self->video_cond, &self->video_mutex );
            next = mlt_deque_pop_front( self->queue );
        }
        pthread_mutex_unlock( &self->video_mutex );

        if ( !self->running || next == NULL ) break;

        // Get the properties
        properties =  MLT_FRAME_PROPERTIES( next );

        // Get the speed of the frame
        speed = mlt_properties_get_double( properties, "_speed" );

        // Get the current time
        gettimeofday( &now, NULL );

        // Get the elapsed time
        elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start;

        // See if we have to delay the display of the current frame
        if ( mlt_properties_get_int( properties, "rendered" ) == 1 && self->running )
        {
            // Obtain the scheduled playout time
            int64_t scheduled = mlt_properties_get_int( properties, "playtime" );

            // Determine the difference between the elapsed time and the scheduled playout time
            int64_t difference = scheduled - elapsed;

            // Smooth playback a bit
            if ( real_time && ( difference > 20000 && speed == 1.0 ) )
            {
                tm.tv_sec = difference / 1000000;
                tm.tv_nsec = ( difference % 1000000 ) * 500;
                nanosleep( &tm, NULL );
            }

            // Show current frame if not too old
            if ( !real_time || ( difference > -10000 || speed != 1.0 || mlt_deque_count( self->queue ) < 2 ) )
                consumer_play_video( self, next );

            // If the queue is empty, recalculate start to allow build up again
            if ( real_time && ( mlt_deque_count( self->queue ) == 0 && speed == 1.0 ) )
            {
                gettimeofday( &now, NULL );
                start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000;
            }
        }

        // This frame can now be closed
        mlt_frame_close( next );
        next = NULL;
    }

    if ( next != NULL )
        mlt_frame_close( next );

    mlt_consumer_stopped( &self->parent );

    return NULL;
}
Esempio n. 9
0
static void *consumer_thread( void *arg )
{
    // Identify the arg
    consumer_sdl self = arg;

    // Get the consumer
    mlt_consumer consumer = &self->parent;

    // Get the properties
    mlt_properties consumer_props = MLT_CONSUMER_PROPERTIES( consumer );

    // Video thread
    pthread_t thread;

    // internal intialization
    int init_audio = 1;
    int init_video = 1;
    mlt_frame frame = NULL;
    mlt_properties properties = NULL;
    int duration = 0;
    int64_t playtime = 0;
    struct timespec tm = { 0, 100000 };
//	int last_position = -1;

    pthread_mutex_lock( &self->refresh_mutex );
    self->refresh_count = 0;
    pthread_mutex_unlock( &self->refresh_mutex );

    // Loop until told not to
    while( self->running )
    {
        // Get a frame from the attached producer
        frame = mlt_consumer_rt_frame( consumer );

        // Ensure that we have a frame
        if ( frame )
        {
            // Get the frame properties
            properties =  MLT_FRAME_PROPERTIES( frame );

            // Get the speed of the frame
            double speed = mlt_properties_get_double( properties, "_speed" );

            // Get refresh request for the current frame
            int refresh = mlt_properties_get_int( consumer_props, "refresh" );

            // Clear refresh
            mlt_events_block( consumer_props, consumer_props );
            mlt_properties_set_int( consumer_props, "refresh", 0 );
            mlt_events_unblock( consumer_props, consumer_props );

            // Play audio
            init_audio = consumer_play_audio( self, frame, init_audio, &duration );

            // Determine the start time now
            if ( self->playing && init_video )
            {
                // Create the video thread
                pthread_create( &thread, NULL, video_thread, self );

                // Video doesn't need to be initialised any more
                init_video = 0;
            }

            // Set playtime for this frame
            mlt_properties_set_int( properties, "playtime", playtime );

            while ( self->running && speed != 0 && mlt_deque_count( self->queue ) > 15 )
                nanosleep( &tm, NULL );

            // Push this frame to the back of the queue
            if ( self->running && speed )
            {
                pthread_mutex_lock( &self->video_mutex );
                if ( self->is_purge && speed == 1.0 )
                {
                    mlt_frame_close( frame );
                    self->is_purge = 0;
                }
                else
                {
                    mlt_deque_push_back( self->queue, frame );
                    pthread_cond_broadcast( &self->video_cond );
                }
                pthread_mutex_unlock( &self->video_mutex );

                // Calculate the next playtime
                playtime += ( duration * 1000 );
            }
            else if ( self->running )
            {
                pthread_mutex_lock( &self->refresh_mutex );
                if ( ( refresh == 0 && self->refresh_count <= 0 ) || self->refresh_count > 1 )
                {
                    consumer_play_video( self, frame );
                    pthread_cond_wait( &self->refresh_cond, &self->refresh_mutex );
                }
                mlt_frame_close( frame );
                self->refresh_count --;
                pthread_mutex_unlock( &self->refresh_mutex );
            }
            else
            {
                mlt_frame_close( frame );
                frame = NULL;
            }

            // Optimisation to reduce latency
            if ( frame && speed == 1.0 )
            {
                // TODO: disabled due to misbehavior on parallel-consumer
//				if ( last_position != -1 && last_position + 1 != mlt_frame_get_position( frame ) )
//					mlt_consumer_purge( consumer );
//				last_position = mlt_frame_get_position( frame );
            }
            else
            {
                mlt_consumer_purge( consumer );
//				last_position = -1;
            }
        }
    }

    // Kill the video thread
    if ( init_video == 0 )
    {
        pthread_mutex_lock( &self->video_mutex );
        pthread_cond_broadcast( &self->video_cond );
        pthread_mutex_unlock( &self->video_mutex );
        pthread_join( thread, NULL );
    }

    while( mlt_deque_count( self->queue ) )
        mlt_frame_close( mlt_deque_pop_back( self->queue ) );

    self->audio_avail = 0;

    return NULL;
}
Esempio n. 10
0
void CRITICAL_END() {
    pthread_mutex_unlock(&MULTITHREAD_MUT);
}
Esempio n. 11
0
static int consumer_play_audio( consumer_sdl self, mlt_frame frame, int init_audio, int *duration )
{
    // Get the properties of this consumer
    mlt_properties properties = self->properties;
    mlt_audio_format afmt = mlt_audio_s16;

    // Set the preferred params of the test card signal
    int channels = mlt_properties_get_int( properties, "channels" );
    int frequency = mlt_properties_get_int( properties, "frequency" );
    int scrub = mlt_properties_get_int( properties, "scrub_audio" );
    static int counter = 0;

    int samples = mlt_sample_calculator( mlt_properties_get_double( self->properties, "fps" ), frequency, counter++ );

    int16_t *pcm;
    int bytes;

    mlt_frame_get_audio( frame, (void**) &pcm, &afmt, &frequency, &channels, &samples );
    *duration = ( ( samples * 1000 ) / frequency );

    if ( mlt_properties_get_int( properties, "audio_off" ) )
    {
        self->playing = 1;
        init_audio = 1;
        return init_audio;
    }

    if ( init_audio == 1 )
    {
        SDL_AudioSpec request;
        SDL_AudioSpec got;

        int audio_buffer = mlt_properties_get_int( properties, "audio_buffer" );

        // specify audio format
        memset( &request, 0, sizeof( SDL_AudioSpec ) );
        self->playing = 0;
        request.freq = frequency;
        request.format = AUDIO_S16SYS;
        request.channels = channels;
        request.samples = audio_buffer;
        request.callback = sdl_fill_audio;
        request.userdata = (void *)self;
        if ( SDL_OpenAudio( &request, &got ) != 0 )
        {
            mlt_log_error( MLT_CONSUMER_SERVICE( self ), "SDL failed to open audio: %s\n", SDL_GetError() );
            init_audio = 2;
        }
        else if ( got.size != 0 )
        {
            SDL_PauseAudio( 0 );
            init_audio = 0;
        }
    }

    if ( init_audio == 0 )
    {
        mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
        bytes = ( samples * channels * 2 );
        pthread_mutex_lock( &self->audio_mutex );
        while ( self->running && bytes > ( sizeof( self->audio_buffer) - self->audio_avail ) )
            pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
        if ( self->running )
        {
            if ( scrub || mlt_properties_get_double( properties, "_speed" ) == 1 )
                memcpy( &self->audio_buffer[ self->audio_avail ], pcm, bytes );
            else
                memset( &self->audio_buffer[ self->audio_avail ], 0, bytes );
            self->audio_avail += bytes;
        }
        pthread_cond_broadcast( &self->audio_cond );
        pthread_mutex_unlock( &self->audio_mutex );
    }
    else
    {
        self->playing = 1;
    }

    return init_audio;
}
Esempio n. 12
0
int 
ldap_pvt_thread_mutex_unlock( ldap_pvt_thread_mutex_t *mutex )
{
	return ERRVAL( pthread_mutex_unlock( mutex ) );
}
Esempio n. 13
0
void* tty2_thread()
{
	while(1)
	{
		FILE* f;
		char fileName[30];
	
		int numlines = 0;
		int i; //Standard iterator.

		fprintf(tty2, "in: ");
		fscanf(tty2, "%s", fileName);
	
		f = fopen(fileName, "r");

		if(!f)
		{
			printf("Arquivo inválido!\n");
			exit(-1);
		}
	
		p2->tty = tty2;
		p2->ready = 0;
		
		pthread_mutex_lock(&allocatorMutex);
			if(allocate_block() == OUT_OF_MEMORY)
			{
				printf("SEM MEMÓRIA\n");
				continue;
			}
		pthread_mutex_unlock(&allocatorMutex);
			
		//Carregar programa na memória.
		while(!feof(f))
		{
			fscanf(f, "%d %d", &mem[numlines + p2->cs].inst, &mem[numlines + p2->cs].op);
			printf("inst= %d\t\top= %d\n", mem[numlines + p2->cs].inst, mem[numlines + p2->cs].op);
			numlines++;
		}
		
		p2->ready = 1;
		printf("Rodando!\n\n");
	
/*		while(1)
		{
			//MUTEX
			pthread_mutex_lock(&runningMutex);
				if(running == p2)
				{
					printf("PC: %d\t CS: %d\t DS: %d\t ACC: %d\n", running->pc, running->cs, running->ds, running->acc);
					if(run_line() == PROG_END) break;
					running->pc++;
				}
			pthread_mutex_unlock(&runningMutex);
			//MUTEX END
		}
		//Terminou execução
*/
		while(p2->ready == 1) {} //Fica parado enquanto o processo está em execução.
		
		pthread_mutex_lock(&allocatorMutex);
			if(p2->ready == 0)
			{
				if(free_memory_block(running->block) == UNALLOCATED_MEM)
				{
					printf("Memória já foi desalocada. Algo muito errado aconteceu.\n");
					continue;
				}
			}
		pthread_mutex_unlock(&allocatorMutex);
	}
}
Esempio n. 14
0
/** @brief Releases buffers under processing.
 * This function must be implemented in the derived classes, for the
 * specific processing
 */
OMX_ERRORTYPE videoenc_port_FlushProcessingBuffers(omx_base_PortType *openmaxStandPort)
{
	omx_videoenc_PortType *omx_videoenc_Port = (omx_videoenc_PortType *)openmaxStandPort;
	OMX_VCE_Buffers_List *pBuffersMng_List= &(omx_videoenc_Port->BuffersMng_List);
	omx_base_component_PrivateType *omx_base_component_Private;
	OMX_BUFFERHEADERTYPE *pBuffer;
	int errQue;

	DEBUG(DEB_LEV_FUNCTION_NAME, "In %s for port %p\n", __func__, openmaxStandPort);
	omx_base_component_Private = (omx_base_component_PrivateType *)openmaxStandPort->standCompContainer->pComponentPrivate;

	if(omx_videoenc_Port->ringbuffer == OMX_TRUE &&  omx_videoenc_Port->bufferpool)
	{
		clearBufferPool(omx_videoenc_Port->bufferpool);
	}

	if(openmaxStandPort->sPortParam.eDomain != OMX_PortDomainOther)
	{
		/* clock buffers not used in the clients buffer managment function */
		pthread_mutex_lock(&omx_base_component_Private->flush_mutex);
		openmaxStandPort->bIsPortFlushed = OMX_TRUE;

		/*Signal the buffer management thread of port flush,if it is waiting for buffers*/
		if(omx_base_component_Private->bMgmtSem->semval==0)
		{
			tsem_up(omx_base_component_Private->bMgmtSem);
		}

		if(omx_base_component_Private->state != OMX_StateExecuting )
		{
			/*Waiting at paused state*/
			tsem_signal(omx_base_component_Private->bStateSem);
		}
		DEBUG(DEB_LEV_FULL_SEQ, "In %s waiting for flush all condition port index =%d\n", __func__,
			(int)openmaxStandPort->sPortParam.nPortIndex);

		/* Wait until flush is completed */
		pthread_mutex_unlock(&omx_base_component_Private->flush_mutex);
		tsem_down(omx_base_component_Private->flush_all_condition);
	}
	DEBUG(DEB_LEV_FUNCTION_NAME, "In %s flushed all the buffers under processing\n", __func__);

	tsem_reset(omx_base_component_Private->bMgmtSem);

	/* Flush all the buffers not under processing */
	while (openmaxStandPort->pBufferSem->semval > 0)
	{
		DEBUG(DEB_LEV_FULL_SEQ, "In %s TFlag=%x Flusing Port=%d,Semval=%d Qelem=%d\n",
			__func__, (int)openmaxStandPort->nTunnelFlags, (int)openmaxStandPort->sPortParam.nPortIndex,
			(int)openmaxStandPort->pBufferSem->semval, (int)openmaxStandPort->pBufferQueue->nelem);

		tsem_down(openmaxStandPort->pBufferSem);
		pBuffer = dequeue(openmaxStandPort->pBufferQueue);

		//FlushProcessingBuffers_BuffersMng(pBuffersMng_List,pBuffer,omx_videoenc_Port->bIsStoreMediaData);

		if (PORT_IS_TUNNELED(openmaxStandPort) && !PORT_IS_BUFFER_SUPPLIER(openmaxStandPort))
		{
			DEBUG(DEB_LEV_FULL_SEQ, "In %s: Comp %s is returning io:%d buffer\n",
				__func__, omx_base_component_Private->name,(int)openmaxStandPort->sPortParam.nPortIndex);

			if (openmaxStandPort->sPortParam.eDir == OMX_DirInput)
			{
				((OMX_COMPONENTTYPE*)(openmaxStandPort->hTunneledComponent))->FillThisBuffer(openmaxStandPort->hTunneledComponent, pBuffer);
			}
			else
			{
				((OMX_COMPONENTTYPE*)(openmaxStandPort->hTunneledComponent))->EmptyThisBuffer(openmaxStandPort->hTunneledComponent, pBuffer);
			}
		}
		else if (PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(openmaxStandPort))
		{
			errQue = queue(openmaxStandPort->pBufferQueue, pBuffer);
			if (errQue)
			{
				/* /TODO the queue is full. This can be handled in a fine way with
				* some retrials, or other checking. For the moment this is a critical error
				* and simply causes the failure of this call
				*/
				return OMX_ErrorInsufficientResources;
			}
		}
		else
		{
			(*(openmaxStandPort->BufferProcessedCallback))(
				openmaxStandPort->standCompContainer,
				omx_base_component_Private->callbackData,
				pBuffer);
		}
	}

	/*Port is tunneled and supplier and didn't received all it's buffer then wait for the buffers*/
	if (PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(openmaxStandPort))
	{
		while(openmaxStandPort->pBufferQueue->nelem != (int)openmaxStandPort->nNumAssignedBuffers)
		{
			tsem_down(openmaxStandPort->pBufferSem);
			DEBUG(DEB_LEV_PARAMS, "In %s Got a buffer qelem=%d\n", __func__, openmaxStandPort->pBufferQueue->nelem);
		}
		tsem_reset(openmaxStandPort->pBufferSem);
	}

	pthread_mutex_lock(&omx_base_component_Private->flush_mutex);
	openmaxStandPort->bIsPortFlushed = OMX_FALSE;
	pthread_mutex_unlock(&omx_base_component_Private->flush_mutex);

	tsem_up(omx_base_component_Private->flush_condition);

	DEBUG(DEB_LEV_FULL_SEQ, "Out %s Port Index=%d bIsPortFlushed=%d Component %s\n", __func__,
		(int)openmaxStandPort->sPortParam.nPortIndex, (int)openmaxStandPort->bIsPortFlushed, omx_base_component_Private->name);

	DEBUG(DEB_LEV_PARAMS, "In %s TFlag=%x Qelem=%d BSem=%d bMgmtsem=%d component=%s\n", __func__,
		(int)openmaxStandPort->nTunnelFlags,
		(int)openmaxStandPort->pBufferQueue->nelem,
		(int)openmaxStandPort->pBufferSem->semval,
		(int)omx_base_component_Private->bMgmtSem->semval,
		omx_base_component_Private->name);

	DEBUG(DEB_LEV_FUNCTION_NAME, "Out %s Port %p Index=%d\n", __func__, openmaxStandPort, (int)openmaxStandPort->sPortParam.nPortIndex);
	return OMX_ErrorNone;
}
Esempio n. 15
0
void AsyncLogger::addMessageTokens(const std::string& line,const std::string& line2) {
	pthread_mutex_lock(&_mutex);
	msg_q->push_back(line);
	msg_q->push_back(line2);
	pthread_mutex_unlock(&_mutex);
}
Esempio n. 16
0
static void* __net_slice_worker(void* arg)
{
    net_slice_ctx_t* slice_ctx = (net_slice_ctx_t*)arg;
    int slice_num = slice_ctx->slice_num;
    int slice_id = slice_ctx->slice_id;
    int cpu_base = slice_ctx->cpu_base;

    assert(slice_ctx->fd > 0);

    if (cpu_base > 0) {
        cpu_base += (slice_id%4);
        spk_worker_set_affinity(cpu_base);
    }
    zlog_info(net_zc, "slice> spawned: id=%d, cpu=%d", slice_id, cpu_base);

    while (!slice_ctx->quit_req) {
        pthread_mutex_lock(&slice_ctx->lock);
        if(slice_ctx->wptr == slice_ctx->rptr) {
            struct timeval now;
            struct timespec outtime;
            gettimeofday(&now, NULL);
            outtime.tv_sec = now.tv_sec + 1;
            outtime.tv_nsec = now.tv_usec * 1000;
            pthread_cond_timedwait(&slice_ctx->not_empty, &slice_ctx->lock, &outtime);
        }
        if (slice_ctx->wptr == slice_ctx->rptr) {
            pthread_mutex_unlock(&slice_ctx->lock);
            continue;
        }

        assert(slice_ctx->data_chunk.flag == CHUNK_DATA_FLAG__REQ);

        size_t chunk_size = slice_ctx->data_chunk.size;
        size_t slice_sz = chunk_size / slice_num;
        ssize_t access = 0;

        // check chunk_size and slice_sz
        if ((chunk_size % slice_num) ||
                (slice_sz & (0x4000-1))) { // 16k alignment
            zlog_error(net_zc, "illegal chunk_sz: chunk_sz=%zu, slice_num=%d",
                       chunk_size, slice_num);
            access = SPKERR_PARAM;
            goto done;
        }

        if (slice_sz != slice_ctx->slice_sz) {
            zlog_warn(net_zc, "unexpected slice size : slice_sz=%zu, expect=%zu",slice_sz, slice_ctx->slice_sz);
            // this chunk may the last in file
        }

        if (slice_ctx->dir == SPK_DIR_WRITE) {
            // write
            if (slice_ctx->type == net_intf_tcp) {
                access = net_tcp_write(slice_ctx->fd,
                                       slice_ctx->data_chunk.buf + slice_id * slice_sz,slice_sz);
            } else if (slice_ctx->type == net_intf_udp) {
                access = net_udp_write(slice_ctx->fd,
                                       slice_ctx->data_chunk.buf + slice_id * slice_sz,slice_sz,((struct sockaddr*)&slice_ctx->svr_addr));

            }
        } else {
            // read
            if (slice_ctx->type == net_intf_tcp) {
                access = net_tcp_read(slice_ctx->fd,
                                      slice_ctx->data_chunk.buf + slice_id * slice_sz,slice_sz);
            } else if (slice_ctx->type == net_intf_udp) {
                access = net_udp_read(slice_ctx->fd,
                                      slice_ctx->data_chunk.buf + slice_id * slice_sz,slice_sz,((struct sockaddr*)&slice_ctx->svr_addr));

            }
        }

        if (access != slice_sz) {
            zlog_error(net_zc, "failed to access file: dir=%d, "
                       "sock_fd:%d slice_sz=%zu, offset=%ld, ret=%ld, errmsg=\'%s\'",
                       slice_ctx->dir, slice_ctx->fd,slice_sz,
                       slice_id * slice_sz, access, strerror(errno));
            access = SPKERR_EACCESS;
            goto done;
        }

done:
        if (access == slice_sz) {
            slice_ctx->data_chunk.flag = CHUNK_DATA_FLAG__DONE;
        } else {
            slice_ctx->data_chunk.flag = access;
        }
        slice_ctx->rptr++;
        pthread_cond_signal(&slice_ctx->not_full);
        pthread_mutex_unlock(&slice_ctx->lock);
    }
    zlog_info(net_zc, "slice> terminated: id=%d", slice_id);
    return(NULL);
}
/**
 * Starts or resumes processing Records
 */
void IpfixAggregator::start() {
	pthread_mutex_unlock(&mutex);
}
Esempio n. 18
0
void
pxgstrf_scheduler(const int pnum, const int n, const int *etree, 
		  int *cur_pan, int *bcol, pxgstrf_shared_t *pxgstrf_shared)
{
/*
 * -- SuperLU MT routine (version 1.0) --
 * Univ. of California Berkeley, Xerox Palo Alto Research Center,
 * and Lawrence Berkeley National Lab.
 * August 15, 1997
 *
 * Purpose
 * =======
 *
 * pxgstrf_scheduler() gets a panel for the processor to work on. 
 * It schedules a panel in decreasing order of priority:
 *   (1) the current panel's parent, if it can be done without pipelining
 *   (2) any other panel in the queue that can be done without pipelining
 *       ("CANGO" status)
 *   (3) any other panel in the queue that can be done with pipelining
 *       ("CANPIPE" status)
 *
 * Arguments
 * =========
 * pnum    (input) int
 *         Processor number.
 *
 * n       (input) int
 *         Column dimension of the matrix.
 *
 * etree   (input) int*
 *         Elimination tree of A'*A, size n.
 *         Note: etree is a vector of parent pointers for a forest whose
 *         vertices are the integers 0 to n-1; etree[root] = n.
 *
 * cur_pan (input/output) int*
 *         On entry, the current panel just finished by this processor;
 *         On exit, [0, n-1]: the new panel to work on;
 *                  EMPTY:    failed to get any work, will try later;
 *                  n:        all panels are taken; ready to terminate.
 *
 * taskq   (input/output) queue_t*
 *         Global work queue.
 *
 * fb_cols (input/output) int*
 *         The farthest busy descendant of each (leading column of the) panel.
 *
 * bcol    (output) int*
 *         The most distant busy descendant of cur_pan in the *linear*
 *         pipeline of busy descendants. If all proper descendants of
 *         cur_pan are done, bcol is returned equal to cur_pan.
 *
 * Defining terms
 * ==============
 *   o parent(panel) = etree(last column in the panel)
 *   o the kids of a panel = collective kids of all columns in the panel
 *     kids[REP] = SUM_{j in panel} ( kids[j] ) 
 *   o linear pipeline - what does it mean in the panel context?
 *       if ukids[REP] = 0, then the panel becomes a leaf (CANGO)
 *       if ukids[REP] = 1 && ukids[firstcol] = 1, then the panel can
 *                       be taken with pipelining (CANPIPE)
 *
 * NOTES
 * =====
 *   o When a "busy" panel finishes, if its parent has only one remaining
 *     undone child there is no check to see if the parent should change
 *     from "unready" to "canpipe". Thus a few potential pipelinings will
 *     be lost, but checking out this pipeline opportunity may be costly.
 *
 */

    register int dad, dad_ukids, jcol, w, j;
    int *fb_cols = pxgstrf_shared->fb_cols;
    queue_t *taskq = &pxgstrf_shared->taskq;
#ifdef PROFILE
    double t;
#endif

    jcol = *cur_pan;
    if ( jcol != EMPTY ) {
#ifdef DOMAINS
	if ( in_domain[jcol] == TREE_DOMAIN )
	    dad = etree[jcol];
	else
#endif
	    dad = DADPANEL (jcol);
    }

    /* w_top = sp_ienv(1)/2;
       if ( w_top == 0 ) w_top = 1;*/

#ifdef PROFILE
    TIC(t);
#endif;
#if ( MACH==SUN )
    mutex_lock( &pxgstrf_shared->lu_locks[SCHED_LOCK] );
#elif ( MACH==DEC || MACH==PTHREAD )
    pthread_mutex_lock( &pxgstrf_shared->lu_locks[SCHED_LOCK] );
#elif ( MACH==SGI || MACH==ORIGIN )
#pragma critical lock(pxgstrf_shared->lu_locks[SCHED_LOCK])
#elif ( MACH==CRAY_PVP )
#pragma _CRI guard SCHED_LOCK
#endif    

{   /* ---- START CRITICAL SECTION ---- */
    
    /* Update the status of the current panel and its parent, so that
     * the other processors waiting on it can proceed.
     * If all siblings are done, and dad is not busy, then take dad.
     */
    if ( jcol != EMPTY ) { /* jcol was just finished by this processor */    
	dad_ukids = --pxgstrf_shared->pan_status[dad].ukids;
	
#ifdef DEBUG
	printf("(%d) DONE %d in Scheduler(), dad %d, STATE %d, dad_ukids %d\n",
	       pnum, jcol, dad, STATE(dad), dad_ukids);
#endif	

	if ( dad_ukids == 0 && STATE( dad ) > BUSY ) { /* dad not started */
	    jcol = dad;
#ifdef DEBUG
	    printf("(%d) Scheduler[1] Got dad %d, STATE %d\n",
		   pnum, jcol, STATE(dad));
#endif
#ifdef PROFILE
	    ++panhows[DADPAN];
#endif	    
	} else {
	    /* Try to get a panel from the task Q. */
	    while ( 1 ) {
		/*>>if ( (j = Dequeue(taskq, &item)) == EMPTY ) {*/
		if ( taskq->count <= 0 ) {
		    jcol = EMPTY;
		    break;
		} else {
		    jcol = taskq->queue[taskq->head++];
		    --taskq->count;
		    if ( STATE( jcol ) >= CANGO ) { /* CANGO or CANPIPE */
#ifdef DEBUG
			printf("(%d) Dequeue[1] Got %d, STATE %d, Qcount %d\n",
			       pnum, jcol, STATE(jcol), j);
#endif
#ifdef PROFILE
			if ( STATE( jcol ) == CANGO ) ++panhows[NOPIPE];
			else ++panhows[PIPE];
#endif			
		        break;
		    }
		}
	    } /* while */
	}
    } else {
	/*
	 * jcol was EMPTY; Try to get a panel from the task Q.
	 */
    	while ( 1 ) {
    	    /*>>if ( (j = Dequeue(taskq, &item)) == EMPTY ) {*/
	    if ( taskq->count <= 0 ) {
		jcol = EMPTY;
		break;
	    } else {
		jcol = taskq->queue[taskq->head++];
		--taskq->count;
		if ( STATE( jcol ) >= CANGO ) { /* CANGO or CANPIPE */
#ifdef DEBUG
		    printf("(%d) Dequeue[2] Got %d, STATE %d, Qcount %d\n",
			   pnum, jcol, STATE(jcol), j);
#endif
#ifdef PROFILE
		    if ( STATE( jcol ) == CANGO ) ++panhows[NOPIPE];
		    else ++panhows[PIPE];
#endif			
		    break;
		}
	    }
	} /* while */
    }
    
    /*
     * Update the status of the new panel "jcol" and its parent "dad".
     */
    if ( jcol != EMPTY ) {
	    --pxgstrf_shared->tasks_remain;
#ifdef DOMAINS
	if ( in_domain[jcol] == TREE_DOMAIN ) {
	    /* Dequeue the first descendant of this domain */
	    *bcol = taskq->queue[taskq->head++];
	    --taskq->count;
	} else
#endif
	{
	    STATE( jcol ) = BUSY;
	    w = pxgstrf_shared->pan_status[jcol].size;

	    for (j = jcol; j < jcol+w; ++j) pxgstrf_shared->spin_locks[j] = 1;
	    dad = DADPANEL (jcol);
	    if ( dad < n && pxgstrf_shared->pan_status[dad].ukids == 1 ) {
		STATE( dad ) = CANPIPE;
		/*>> j = Enqueue(taskq, dad);*/
		taskq->queue[taskq->tail++] = dad;
		++taskq->count;
#ifdef DEBUG
		printf("(%d) Enqueue() %d's dad %d ->CANPIPE, Qcount %d\n",
		       pnum, jcol, dad, j);
#endif
	    }

#ifdef PROFILE
	    Gstat->procstat[pnum].panels++;
#endif
	
	    /* Find the farthest busy descendant of the new panel
	       and its parent.*/
	    *bcol = fb_cols[jcol];
#ifdef DEBUG
	    printf("(%d) Scheduler[2] fb_cols[%d]=%d, STATE %d\n",
		   pnum, jcol, *bcol, STATE( *bcol ));
#endif
	    while ( STATE( *bcol ) == DONE ) *bcol = DADPANEL (*bcol);
	    fb_cols[dad] = *bcol;
	
	} /* else regular_panel */

    } /* if jcol != empty */

    *cur_pan = jcol;

#ifdef DEBUG
    printf("(%d) Exit C.S. tasks_remain %d, cur_pan %d\n", 
	   pnum, pxgstrf_shared->tasks_remain, jcol);
#endif

} /* ---- END CRITICAL SECTION ---- */
    
#if ( MACH==SUN )
    /* Exit C.S. */
    mutex_unlock( &pxgstrf_shared->lu_locks[SCHED_LOCK] );
#elif ( MACH==DEC || MACH==PTHREAD )
    pthread_mutex_unlock( &pxgstrf_shared->lu_locks[SCHED_LOCK] );
#elif ( MACH==CRAY_PVP )
#pragma _CRI endguard SCHED_LOCK
#endif    

#ifdef PROFILE
    Gstat->procstat[pnum].cs_time += SuperLU_timer_() - t;
#endif

    return;
}
Esempio n. 19
0
void slabs_stats(ADD_STAT add_stats, void *c) {
    pthread_mutex_lock(&slabs_lock);
    do_slabs_stats(add_stats, c);
    pthread_mutex_unlock(&slabs_lock);
}
Esempio n. 20
0
static void *
rdd_read_write (void *arg)
{
    int i = 0, ret = 0;
    size_t bs = 0;
    off_t offset = 0;
    long rand = 0;
    long max_ops = 0;
    char *buf = NULL;

    buf = calloc (1, rdd_config.max_bs);
    if (!buf) {
        fprintf (stderr, "calloc failed (%s)\n", strerror (errno));
        ret = -1;
        goto out;
    }

    for (i = 0; i < rdd_config.iters; i++)
    {
        pthread_mutex_lock (&rdd_config.lock);
        {
            int bytes = 0;
            rand = random ();

            if (rdd_config.min_bs == rdd_config.max_bs) {
                bs = rdd_config.max_bs;
            } else {
                bs = rdd_config.min_bs +
                     (rand %
                      (rdd_config.max_bs -
                       rdd_config.min_bs));
            }

            offset = rand % rdd_config.in_file.st.st_size;
            max_ops = rand % rdd_config.max_ops_per_seq;
            if (!max_ops) {
                max_ops ++;
            }

            ret = lseek (rdd_config.in_file.fd, offset, SEEK_SET);
            if (ret != offset) {
                fprintf (stderr, "lseek failed (%s)\n",
                         strerror (errno));
                ret = -1;
                goto unlock;
            }

            ret = lseek (rdd_config.out_file.fd, offset, SEEK_SET);
            if (ret != offset) {
                fprintf (stderr, "lseek failed (%s)\n",
                         strerror (errno));
                ret = -1;
                goto unlock;
            }

            while (max_ops--)
            {
                bytes = read (rdd_config.in_file.fd, buf, bs);
                if (!bytes) {
                    break;
                }

                if (bytes == -1) {
                    fprintf (stderr, "read failed (%s)\n",
                             strerror (errno));
                    ret = -1;
                    goto unlock;
                }

                if (write (rdd_config.out_file.fd, buf, bytes)
                        != bytes) {
                    fprintf (stderr, "write failed (%s)\n",
                             strerror (errno));
                    ret = -1;
                    goto unlock;
                }
            }
        }
unlock:
        pthread_mutex_unlock (&rdd_config.lock);
        if (ret == -1) {
            goto out;
        }
        ret = 0;
    }
out:
    free (buf);
    pthread_barrier_wait (&rdd_config.barrier);

    return NULL;
}
Esempio n. 21
0
/* Return 1 means a decision was reached.
 * Move to its own thread (created/destroyed as needed) once automover is more
 * complex.
 */
static int slab_automove_decision(int *src, int *dst) {
    static uint64_t evicted_old[POWER_LARGEST];
    static unsigned int slab_zeroes[POWER_LARGEST];
    static unsigned int slab_winner = 0;
    static unsigned int slab_wins   = 0;
    uint64_t evicted_new[POWER_LARGEST];
    uint64_t evicted_diff = 0;
    uint64_t evicted_max  = 0;
    unsigned int highest_slab = 0;
    unsigned int total_pages[POWER_LARGEST];
    int i;
    int source = 0;
    int dest = 0;
    static rel_time_t next_run;

    /* Run less frequently than the slabmove tester. */
    if (current_time >= next_run) {
        next_run = current_time + 10;
    } else {
        return 0;
    }

    item_stats_evictions(evicted_new);
    pthread_mutex_lock(&cache_lock);
    for (i = POWER_SMALLEST; i < power_largest; i++) {
        total_pages[i] = slabclass[i].slabs;
    }
    pthread_mutex_unlock(&cache_lock);

    /* Find a candidate source; something with zero evicts 3+ times */
    for (i = POWER_SMALLEST; i < power_largest; i++) {
        evicted_diff = evicted_new[i] - evicted_old[i];
        if (evicted_diff == 0 && total_pages[i] > 2) {
            slab_zeroes[i]++;
            if (source == 0 && slab_zeroes[i] >= 3)
                source = i;
        } else {
            slab_zeroes[i] = 0;
            if (evicted_diff > evicted_max) {
                evicted_max = evicted_diff;
                highest_slab = i;
            }
        }
        evicted_old[i] = evicted_new[i];
    }

    /* Pick a valid destination */
    if (slab_winner != 0 && slab_winner == highest_slab) {
        slab_wins++;
        if (slab_wins >= 3)
            dest = slab_winner;
    } else {
        slab_wins = 1;
        slab_winner = highest_slab;
    }

    if (source && dest) {
        *src = source;
        *dst = dest;
        return 1;
    }
    return 0;
}
static ssize_t out_write(struct audio_stream_out *stream, const void* buffer,
                         size_t bytes)
{
    struct astream_out *out = (struct astream_out *)stream;
    int ret;
    size_t frames_total = bytes / sizeof(uint32_t); // always stereo 16 bit
    uint32_t *buf = (uint32_t *)buffer;
    size_t frames_written = 0;

    pthread_mutex_lock(&out->buf_lock);
    pthread_mutex_lock(&out->lock);
    if (!out->bt_enabled || out->suspended) {
        ALOGV("a2dp: bluetooth disabled bt_en %d, suspended %d",
             out->bt_enabled, out->suspended);
        ret = -1;
        goto err_bt_disabled;
    }

    if (out->standby) {
        acquire_wake_lock(PARTIAL_WAKE_LOCK, A2DP_WAKE_LOCK_NAME);
        out->standby = false;
        out->last_write_time = system_time();
        out->buf_rd_idx = 0;
        out->buf_wr_idx = 0;
        out->buf_frames_ready = 0;
    }

    ret = _out_init_locked(out, NULL);
    if (ret < 0) {
        goto err_init;
    }

    pthread_mutex_unlock(&out->lock);

    while (frames_written < frames_total) {
        size_t frames = _out_frames_available_locked(out);
        if (frames == 0) {
            int ret = pthread_cond_timeout_np(&out->buf_cond,
                                              &out->buf_lock,
                                              BUF_WRITE_AVAILABILITY_TIMEOUT_MS);
            if (ret != 0) {
                pthread_mutex_lock(&out->lock);
                goto err_write;
            }
            frames  = _out_frames_available_locked(out);
        }
        if (frames > frames_total - frames_written) {
            frames = frames_total - frames_written;
        }
        memcpy(out->buf + out->buf_wr_idx, buf + frames_written, frames * sizeof(uint32_t));
        frames_written += frames;
        _out_inc_wr_idx_locked(out, frames);
        pthread_mutex_lock(&out->lock);
        if (out->standby) {
            goto err_write;
        }
        pthread_mutex_unlock(&out->lock);
    }
    pthread_mutex_unlock(&out->buf_lock);

    return bytes;

/* out->lock must be locked and out->buf_lock unlocked when jumping here */
err_write:
err_init:
err_bt_disabled:
    pthread_mutex_unlock(&out->buf_lock);
    ALOGV("!!!! write error");
    out_standby_stream_locked(out);
    pthread_mutex_unlock(&out->lock);

    /* XXX: simulate audio output timing in case of error?!?! */
    usleep(out->buffer_duration_us);
    return ret;
}
ssize_t handle_with_cache(gfcontext_t* ctx, char *path, void* arg) {
        char* fldes;

        pthread_mutex_lock(&fldes_mutex);
        while (fldes_queue_size == 0) {
                pthread_cond_wait(&read_cond, &fldes_mutex);
        }
        fldes = (char*)steque_pop(&fldes_queue);
        fldes_queue_size--;
//		fprintf(stdout, "fldes is:%s.", fldes);
        pthread_mutex_unlock(&fldes_mutex);
        pthread_cond_broadcast(&write_cond);
		//pthread_cond_signal(&write_cond);



        shm_data* mem = create_shm_channel(fldes);

        mqd_t mq;

        do {
                mq = mq_open (MSGQID, O_RDWR);
        } while(mq == (mqd_t) -1 || mq == 0);

        msgq_data data;
        strcpy(data.path, path);
        strcpy(data.fldes, fldes);
        data.segment_size = segment_size;

 //       pthread_mutex_lock(&msgq_mutex);

        int msg_rsp = mq_send(mq, (const char *) &data, 1024, 1);
        if (msg_rsp < 0) {
                fprintf(stderr, "Error %d (%s) on server proxy mq_send.\n", errno, strerror(errno));
				fflush(stdout);
  //              exit(1);
        }
        mq_close(mq);
 //       pthread_mutex_unlock(&msgq_mutex);

        pthread_mutex_lock(&mem->file_len_mutex);
        while(mem->file_length == 0) {
			pthread_cond_wait(&mem->proxy_cond, &mem->file_len_mutex);
        }

        int file_len = mem->file_length;

        pthread_mutex_unlock(&mem->file_len_mutex);
        pthread_cond_broadcast(&mem->cache_cond);

 //       fprintf(stdout, "Received file length is: %d\n", file_len);
//        fflush(stdout);
        
        if(file_len < 0) {
 //               fprintf(stdout, "File not found in cache\n");
//				fflush(stdout);
                destroy_shm_seg(fldes, mem);
                return gfs_sendheader(ctx, GF_FILE_NOT_FOUND, 0);
        }else {

                gfs_sendheader(ctx, GF_OK, file_len);

             
                int bytes_transferred = 0;
                int write_len = 0;
                char *data_start = (void *)(mem + 1);
                while (bytes_transferred < file_len) {

                        pthread_mutex_lock(&mem->data_mutex);
                        while(mem->bytes_written == 0) {
                                pthread_cond_wait(&mem->proxy_cond, &mem->data_mutex);
                        }
                        int read_len = mem->bytes_written;
                        write_len = gfs_send(ctx, data_start, read_len);
                        if (write_len != read_len) {
                                fprintf(stderr, "handle_with_cache write error");
                                return EXIT_FAILURE;
                        }
                        mem->bytes_written = 0;

                        pthread_mutex_unlock(&mem->data_mutex);
                        pthread_cond_broadcast(&mem->cache_cond);
                        bytes_transferred += write_len;
                }


                destroy_shm_seg(fldes, mem);
                fflush(stdout);
                return bytes_transferred;
        }
}
static void *_out_buf_thread_func(void *context)
{
    struct astream_out *out = (struct astream_out *)context;

    pthread_mutex_lock(&out->buf_lock);

    while(!out->buf_thread_exit) {
        size_t frames;

        frames = _out_frames_ready_locked(out);
        while (frames && !out->buf_thread_exit) {
            int retries = MAX_WRITE_RETRIES;
            uint64_t now;
            uint32_t elapsed_us;

            while (frames > 0 && !out->buf_thread_exit) {
                int ret;
                uint32_t buffer_duration_us;
                /* PCM format is always 16bit stereo */
                size_t bytes = frames * sizeof(uint32_t);
                if (bytes > out->buffer_size) {
                    bytes = out->buffer_size;
                }

                pthread_mutex_lock(&out->lock);
                if (out->standby) {
                    /* abort and clear all pending frames if standby requested */
                    pthread_mutex_unlock(&out->lock);
                    frames = _out_frames_ready_locked(out);
                    _out_inc_rd_idx_locked(out, frames);
                    goto wait;
                }
                /* indicate to out_standby_stream_locked() that a2dp_write() is active */
                out->write_busy = true;
                pthread_mutex_unlock(&out->lock);
                pthread_mutex_unlock(&out->buf_lock);

                ret = a2dp_write(out->data, out->buf + out->buf_rd_idx, bytes);

                /* clear write_busy condition */
                pthread_mutex_lock(&out->buf_lock);
                pthread_mutex_lock(&out->lock);
                out->write_busy = false;
                pthread_cond_signal(&out->write_cond);
                pthread_mutex_unlock(&out->lock);

                if (ret < 0) {
                        ALOGE("%s: a2dp_write failed (%d)\n", __func__, ret);
                    /* skip pending frames in case of write error */
                    _out_inc_rd_idx_locked(out, frames);
                    break;
                } else if (ret == 0) {
                    if (retries-- == 0) {
                        /* skip pending frames in case of multiple time out */
                        _out_inc_rd_idx_locked(out, frames);
                        break;
                    }
                    continue;
                }
                ret /= sizeof(uint32_t);
                _out_inc_rd_idx_locked(out, ret);
                frames -= ret;

                /* XXX: PLEASE FIX ME!!!! */

                /* if A2DP sink runs abnormally fast, sleep a little so that
                 * audioflinger mixer thread does no spin and starve other threads. */
                /* NOTE: It is likely that the A2DP headset is being disconnected */
                now = system_time();
                elapsed_us = (now - out->last_write_time) / 1000UL;
                buffer_duration_us = ((ret * 1000) / out->sample_rate) * 1000;

                if (elapsed_us < (buffer_duration_us / 4)) {
                    ALOGV("A2DP sink runs too fast");
                    usleep(buffer_duration_us - elapsed_us);
                }
                out->last_write_time = now;

            }
            frames = _out_frames_ready_locked(out);
        }
wait:
        if (!out->buf_thread_exit) {
            pthread_cond_wait(&out->buf_cond, &out->buf_lock);
        }
    }
    pthread_mutex_unlock(&out->buf_lock);
    return NULL;
}
Esempio n. 25
0
int xlog(struct xlogger* logger, int level, const char *format, ...)
{
    struct xloghandler* l;
    int ret=0;
    int res;

    if (level<0 || LOG_DEBUG<level || level>logger->level) return ret;

    pthread_mutex_lock(&xlog_mutex);
    for (l=logger->handlers; l->enable>=0; l++)
    {
        va_list args;               // moved inside the loop because of x64
        va_start(args, format);     // was fine outside with i386
        if (l->level<0 || l->level<level) continue;
        if (l->filename)
        {
            if (l->file!=NULL)
            {
                if (l->max_bytes>0)
                {
                    struct stat stats;
                    res=fstat(fileno(l->file), &stats);
                    if (res==-1)
                    {
                        ret=1;
                        perror(l->filename);
                        continue;
                    }
                    if (stats.st_size >= l->max_bytes)
                    {
//                        printf("close %lld>%d\n", stats.st_size, l->max_bytes);
                        res=fclose(l->file);
                        if (res==-1)
                        {
                            ret=1;
                            perror(l->filename);
                            continue;
                        }
                        res=xlog_rollout(l->filename, l->backup_count);
                        if (res) ret=1;
                        l->file=NULL;
                    }
                }
            }

            if (l->file==NULL)
            {
                if (0!=strcmp(l->mode, "a") && l->backup_count>0)
                {
                    res=xlog_rollout(l->filename, l->backup_count);
                    if (res) ret=1;
                }
//                printf("open %s %s\n", l->filename, l->mode);
                l->file=fopen(l->filename, l->mode);
                if (l->file==NULL)
                {
                    ret=1;
                    perror(l->filename);
                    continue;
                }
                setlinebuf(l->file);
            }
        }
        if (format && l->time_fmt)
        {
            char timestr[1024];
            time_t t;
            struct tm *tmp;

            t=time(NULL);
            tmp=localtime(&t);

            strftime(timestr, sizeof(timestr), l->time_fmt, tmp);
            char *p=strstr(timestr, "%{LEVEL}");
            if (p)
            {
                memmove(p, p+5, strlen(p)-4); // include '\0'
                memcpy(p, level_long_str[level], 3);
            }

            res=fputs(timestr, l->file);
            if (res==EOF)
            {
                ret=1;
            }

        }
        if (format)
        {
            res=vfprintf(l->file, format, args);
            if (res<0) ret=1;
        }
        va_end(args);
    }
    pthread_mutex_unlock(&xlog_mutex);
    return ret;
}
static int adev_open_output_stream(struct audio_hw_device *dev,
                                   uint32_t devices, audio_format_t *format,
                                   uint32_t *channels, uint32_t *sample_rate,
                                   struct audio_stream_out **stream_out)
#endif
{
    struct adev_a2dp *adev = (struct adev_a2dp *)dev;
    struct astream_out *out;
    int ret;

    pthread_mutex_lock(&adev->lock);

    /* one output stream at a time */
    if (adev->output) {
        ALOGV("output exists");
        ret = -EBUSY;
        goto err_output_exists;
    }

    out = calloc(1, sizeof(struct astream_out));
    if (!out) {
        ret = -ENOMEM;
        goto err_alloc;
    }

    pthread_mutex_init(&out->lock, NULL);

    out->stream.common.get_sample_rate = out_get_sample_rate;
    out->stream.common.set_sample_rate = out_set_sample_rate;
    out->stream.common.get_buffer_size = out_get_buffer_size;
    out->stream.common.get_channels = out_get_channels;
    out->stream.common.get_format = out_get_format;
    out->stream.common.set_format = out_set_format;
    out->stream.common.standby = out_standby;
    out->stream.common.dump = out_dump;
    out->stream.common.set_parameters = out_set_parameters;
    out->stream.common.get_parameters = out_get_parameters;
    out->stream.common.set_device = out_set_device;
    out->stream.common.get_device = out_get_device;
    out->stream.common.add_audio_effect = out_add_audio_effect;
    out->stream.common.remove_audio_effect = out_remove_audio_effect;
    out->stream.get_latency = out_get_latency;
    out->stream.set_volume = out_set_volume;
    out->stream.write = out_write;
    out->stream.get_render_position = out_get_render_position;

    out->sample_rate = 48000;
    out->buffer_size = 512 * 8;
    out->channels = AUDIO_CHANNEL_OUT_STEREO;
    out->format = AUDIO_FORMAT_PCM_16_BIT;

    out->fd = -1;
    out->device = devices;
    out->bt_enabled = adev->bt_enabled;
    out->suspended = adev->suspended;

    /* for now, buffer_duration_us is precalculated and never changed.
     * if the sample rate or the format ever changes on the fly, we'd have
     * to recalculate this */
    out->buffer_duration_us = ((out->buffer_size * 1000 ) /
                               audio_stream_frame_size(&out->stream.common) /
                               out->sample_rate) * 1000;
#ifdef AUDIO_DEVICE_API_VERSION_1_0
    if (!_out_validate_parms(out, config->format,
                             config->channel_mask,
                             config->sample_rate))
#else
    if (!_out_validate_parms(out, format ? *format : 0,
                             channels ? *channels : 0,
                             sample_rate ? *sample_rate : 0))
#endif
    {
        ALOGV("invalid parameters");
        ret = -EINVAL;
        goto err_validate_parms;
    }

    int err = pthread_create(&out->buf_thread, (const pthread_attr_t *) NULL, _out_buf_thread_func, out);
    if (err != 0) {
        goto err_validate_parms;
    }

    /* PCM format is always 16bit, stereo */
    out->buf_size = (out->buffer_size * BUF_NUM_PERIODS) / sizeof(int32_t);
    out->buf = (uint32_t *)malloc(out->buf_size * sizeof(int32_t));
    if (!out->buf) {
        goto err_validate_parms;
    }

    /* XXX: check return code? */
    if (adev->bt_enabled)
        _out_init_locked(out, "00:00:00:00:00:00");

    adev->output = out;

#ifdef AUDIO_DEVICE_API_VERSION_1_0
    config->format = out->format;
    config->channel_mask = out->channels;
    config->sample_rate = out->sample_rate;
#else
    if (format)
        *format = out->format;
    if (channels)
        *channels = out->channels;
    if (sample_rate)
        *sample_rate = out->sample_rate;
#endif
    pthread_mutex_unlock(&adev->lock);

    *stream_out = &out->stream;

    return 0;

err_validate_parms:
    free(out);
err_alloc:
err_output_exists:
    pthread_mutex_unlock(&adev->lock);
    *stream_out = NULL;
    return ret;
}
Esempio n. 27
0
static gboolean play_start(InputPlayback *playback, const char *filename, VFSFile *file, int start_time, int stop_time, gboolean pause)
{
	int song = -1;
	unsigned char module[ASAPInfo_MAX_MODULE_LENGTH];
	int module_len;
	gboolean ok;
	const ASAPInfo *info;
	int channels;

#if _AUD_PLUGIN_VERSION >= 10
	char *real_filename = filename_split_subtune(filename, &song);
	if (real_filename != NULL)
		filename = real_filename;
#endif
	module_len = load_module(filename, file, module);
	ok = module_len > 0 && ASAP_Load(asap, filename, module, module_len);
#if _AUD_PLUGIN_VERSION >= 10
	g_free(real_filename);
#endif
	if (!ok)
		return FALSE;

	info = ASAP_GetInfo(asap);
	channels = ASAPInfo_GetChannels(info);
	if (song > 0)
		song--;
	else
		song = ASAPInfo_GetDefaultSong(info);
	if (stop_time < 0)
		stop_time = ASAPInfo_GetDuration(info, song);
	if (!ASAP_PlaySong(asap, song, stop_time))
		return FALSE;
	if (start_time > 0)
		ASAP_Seek(asap, start_time);

	if (!playback->output->open_audio(BITS_PER_SAMPLE == 8 ? FMT_U8 : FMT_S16_LE, ASAP_SAMPLE_RATE, channels))
		return FALSE;
	playback->set_params(playback,
#if _AUD_PLUGIN_VERSION < 18
		NULL, 0,
#endif
		0, ASAP_SAMPLE_RATE, channels);
	if (pause)
		playback->output->pause(TRUE);
	playing = TRUE;
	playback->set_pb_ready(playback);

	for (;;) {
		static unsigned char buffer[4096];
		int len;
		pthread_mutex_lock(&control_mutex);
		if (!playing) {
			pthread_mutex_unlock(&control_mutex);
			break;
		}
		len = ASAP_Generate(asap, buffer, sizeof(buffer), BITS_PER_SAMPLE == 8 ? ASAPSampleFormat_U8 : ASAPSampleFormat_S16_L_E);
		pthread_mutex_unlock(&control_mutex);
		if (len <= 0) {
#if _AUD_PLUGIN_VERSION < 18
			playback->eof = TRUE;
#endif
			break;
		}
#if _AUD_PLUGIN_VERSION >= 14
		playback->output->write_audio(buffer, len);
#else
		playback->pass_audio(playback, BITS_PER_SAMPLE == 8 ? FMT_U8 : FMT_S16_LE, channels, len, buffer, NULL);
#endif
	}

#if _AUD_PLUGIN_VERSION_MIN < 40
	while (playing && playback->output->buffer_playing())
		g_usleep(10000);
#endif
	pthread_mutex_lock(&control_mutex);
	playing = FALSE;
	pthread_mutex_unlock(&control_mutex);
#if _AUD_PLUGIN_VERSION_MIN < 40
	playback->output->close_audio();
#endif
	return TRUE;
}
Esempio n. 28
0
 Int unlock()
 {
     return pthread_mutex_unlock(&mutex);
 };
Esempio n. 29
0
static void my_cleanup(void *arg) {
  printf("my_cleanup\n");
  pthread_mutex_unlock((pthread_mutex_t*)arg);
}
Esempio n. 30
0
/*
 * runs a query from the query list or returns -1 in int *body_lentgh
 * should no query be waiting.
 */
char *query_list_run_query( sqlite3 *database, int *body_length, int *sock, int *monitorid) {

	sqlite3_stmt *stmt = NULL;
	int o, columns, colcount=0;
	const char *zErrmsg = NULL;
	char *z;
	char *FullAlloc;
	unsigned int FullLength = 0;

	if ( query_start == NULL) {
		*body_length = -1;
		return NULL;
	}
	struct query_entry *backup;
	backup = query_start;
	pthread_mutex_lock(&query_mutex);
	query_start = query_start->next;
	pthread_mutex_unlock(&query_mutex);
	/* we fetched the first item, run a SQL query on it */
	o = sqlite3_prepare(database,
		backup->data,
		strlen(backup->data),
		&stmt,
		&zErrmsg);
	/* internal query by a monitor ? */
	if (backup->monitorid != 0) *monitorid = backup->monitorid;
	DEBUG(1) syslog(LOG_DEBUG,"query_list_run_query: running %s, monitorid = %i",
		backup->data, backup->monitorid);
	columns = sqlite3_column_count( stmt );
	FullAlloc = (char *) malloc(sizeof(char));
	while(sqlite3_step(stmt) == SQLITE_ROW) {
		while (colcount < columns) {
			z=(char *) sqlite3_column_text(stmt, colcount);
			if (z == NULL) break;
			FullAlloc = (char *) realloc(FullAlloc, sizeof(char) *
				(FullLength + strlen(z) + strlen("0000") + 2));
			char lenstr[5];
			sprintf(lenstr,"%04i", (int) strlen(z));
			memcpy(FullAlloc+FullLength, lenstr, 4);
                        int x = 0;
                        while (x < strlen(z)) { // FIXME !
                                FullAlloc[FullLength+x+ 4] = z[x];
                                x++;
                        }
			FullLength=FullLength + strlen(z) + 4; // FIXME !
		colcount = colcount + 1;
		}			
	colcount = 0;
	}
	sqlite3_finalize( stmt );
	*sock = backup->sock;
	free(backup->data);
	free(backup);
	
	/* When the result was NULL, we return an identifier */
	if (FullLength == 0) {
		char *str = strdup("No Results.");
		char *strg = malloc(sizeof(char)*100);
		sprintf(strg, "%04i%s",(int) strlen(str),str);
		*body_length= 4+ strlen(str)+1;
		free(FullAlloc);
		return(strg);
	}

	*body_length = FullLength;
	
	return FullAlloc;
}