Beispiel #1
0
	void simple_scheduler::thread_proc(int id) {
		try {
			schedule_queue_type::value_type instance;
			while (!stop_requested_) {
				instance = queue_.pop();
				if (!instance) {
					boost::unique_lock<boost::mutex> lock(idle_thread_mutex_);
					idle_thread_cond_.wait(lock);
					continue;
				}

				try {
					boost::posix_time::time_duration off = now() - (*instance).time;
					if (off.total_seconds() > error_threshold_) {
						log_error("Ran scheduled item " + strEx::s::xtos(instance->schedule_id) + " " + strEx::s::xtos(off.total_seconds()) + " seconds to late from thread " + strEx::s::xtos(id));
					}
					boost::thread::sleep((*instance).time);
				} catch (boost::thread_interrupted  &e) {
					if (!queue_.push(*instance))
						log_error("ERROR");
					if (stop_requested_) {
						log_error("Terminating thread: " + strEx::s::xtos(id));
						return;
					}
					continue;
				} catch (...) {
					if (!queue_.push(*instance))
						log_error("ERROR");
					continue;
				}

				boost::posix_time::ptime now_time = now();
				boost::optional<schedules::schedule_object> item = get_task((*instance).schedule_id);
				if (item) {
					try {
						if (handler_)
							handler_->handle_schedule(*item);
						reschedule(*item,now_time);
					} catch (...) {
						log_error("UNKNOWN ERROR RUNING TASK: ");
						reschedule(*item);
					}
				} else {
					log_error("Task not found: " + strEx::s::xtos(instance->schedule_id));
				}
			}
		} catch (const std::exception &e) {
			log_error("Exception in scheduler thread (thread will be killed): " + utf8::utf8_from_native(e.what()));
		} catch (...) {
			log_error("Exception in scheduler thread (thread will be killed)");
		}

	}
Beispiel #2
0
void Courier::setForwardRescheduleSignal(QObject &ob, bool fwd)
{
	if(fwd) {
		if(!connect(&ob,SIGNAL(reschedule(quint64)),this,SIGNAL(reschedule(quint64)),OC_CONTYPE)) {
			qWarning()<<"ERROR: Could not connect "<<ob.objectName();
		}
	} else {
		if(!disconnect(&ob,SIGNAL(reschedule(quint64)),this,SIGNAL(reschedule(quint64)))) {
			qWarning()<<"ERROR: Could not disconnect "<<ob.objectName();
		}
	}
}
Beispiel #3
0
char *resolve_name(int serviceid)
{
	struct directory_resolvename res_cmd;
	struct directory_response dir_res;
	char *service_name = "";
	int id_proc;

	res_cmd.command = DIRECTORY_RESOLVENAME;
	res_cmd.serviceid = serviceid;
 	res_cmd.ret_port = dirlib_port;
	res_cmd.thr_id = get_current_thread();
	// we will send an smo with size 1 first
	// servicename will not fit and directory will return
	// an error spacifying dir name size.
	res_cmd.name_smo = share_mem(DIRECTORY_TASK, service_name, 1, WRITE_PERM); 
	
	send_msg(DIRECTORY_TASK, DIRECTORY_PORT, &res_cmd);
  
	while (get_msg_count(dirlib_port) == 0) { reschedule(); }

	get_msg(dirlib_port, &dir_res, &id_proc);

	claim_mem(res_cmd.name_smo);	

	if(dir_res.ret == DIRECTORYERR_SMO_TOOSMALL)
	{
		// now malloc for servicename
		service_name = (char *)malloc(dir_res.ret_value + 1);

		res_cmd.name_smo = share_mem(DIRECTORY_TASK, service_name, len(service_name) + 1, WRITE_PERM); 

		send_msg(DIRECTORY_TASK, DIRECTORY_PORT, &res_cmd);
  
		while (get_msg_count(dirlib_port) == 0) { reschedule(); }

		get_msg(dirlib_port, &dir_res, &id_proc);

		claim_mem(res_cmd.name_smo);	

		if(dir_res.ret != DIRECTORYERR_OK) 
		{
			free(service_name);
			return NULL; // fail
		}

		return service_name;
	}
	else
	{
		return NULL; // fail
	}
}
Beispiel #4
0
/*
 * Change task priority.
 */
EXPORT void change_task_priority( TCB *tcb, INT priority )
{
	INT	oldpri;

	if ( tcb->state == TS_READY ) {
		/*
		 * When deleting a task from the ready queue,
		 * a value in the 'priority' field in TCB is needed.
		 * Therefore you need to delete the task from the
		 * ready queue before changing 'tcb->priority.'
		 */
		ready_queue_delete(&ready_queue, tcb);
		tcb->priority = (UB)priority;
		ready_queue_insert(&ready_queue, tcb);
		reschedule();
	} else {
		oldpri = tcb->priority;
		tcb->priority = (UB)priority;

		/* If the hook routine at the task priority change is defined,
		   execute it */
		if ( (tcb->state & TS_WAIT) != 0 && tcb->wspec->chg_pri_hook) {
			(*tcb->wspec->chg_pri_hook)(tcb, oldpri);
		}
	}
}
Beispiel #5
0
                        virtual void operator() ()
                        {
                                m_dht.restore();
                                m_dht.maintain();

                                reschedule();
                        }
Beispiel #6
0
                        virtual void operator() ()
                        {
                                m_dht.refresh();
                                m_dht.sweep_rdp();

                                reschedule();
                        }
Beispiel #7
0
void
ser_base_async (struct serial *scb,
		int async_p)
{
  if (async_p)
    {
      /* Force a re-schedule.  */
      scb->async_state = NOTHING_SCHEDULED;
      if (serial_debug_p (scb))
	fprintf_unfiltered (gdb_stdlog, "[fd%d->asynchronous]\n",
			    scb->fd);
      reschedule (scb);
    }
  else
    {
      if (serial_debug_p (scb))
	fprintf_unfiltered (gdb_stdlog, "[fd%d->synchronous]\n",
			    scb->fd);
      /* De-schedule whatever tasks are currently scheduled.  */
      switch (scb->async_state)
	{
	case FD_SCHEDULED:
	  delete_file_handler (scb->fd);
	  break;
	case NOTHING_SCHEDULED:
	  break;
	default: /* TIMER SCHEDULED */
	  delete_timer (scb->async_state);
	  break;
	}
    }
}
Beispiel #8
0
/* block_thread() & preempt_thread() */
void block_thread(void)
{
    cthread->state = THREAD_BLOCKED;
    memcpy((void *) &cthread->ctx, (void *) __ctx, sizeof(struct sys_context)); /* save threads context */
    reschedule();
    return;
}
Beispiel #9
0
    void Monotonic::Manager::start(Monotonic *timer)
    {
      if(timer == nullptr)
      {
        throw;
      }

      bool added = false;

      for(auto i = timers.begin(); i != timers.end(); ++i)
      {
        Monotonic *current = *i;

        if(current->time + current->offset > timer->time + timer->offset)
        {
          timers.insert(i, timer);
          added = true;
          break;
        }
      }

      if(!added)
      {
        timers.push_back(timer);
      }

      Watcher::start();
      reschedule();
    }
// Warning: this function is called in the context of an unknown thread.
// As a result, it must be thread-safe relative to other operations on
// the alarm list.
static void timer_callback(void *ptr) {
  alarm_t *alarm = (alarm_t *)ptr;
  assert(alarm != NULL);

  pthread_mutex_lock(&monitor);

  bool alarm_valid = list_remove(alarms, alarm);
  alarm_callback_t callback = alarm->callback;
  void *data = alarm->data;

  alarm->deadline = 0;
  alarm->callback = NULL;
  alarm->data = NULL;

  reschedule();

  // The alarm was cancelled before we got to it. Release the monitor
  // lock and exit right away since there's nothing left to do.
  if (!alarm_valid) {
    pthread_mutex_unlock(&monitor);
    return;
  }

  // Downgrade lock.
  pthread_mutex_lock(&alarm->callback_lock);
  pthread_mutex_unlock(&monitor);

  callback(data);

  pthread_mutex_unlock(&alarm->callback_lock);
}
Beispiel #11
0
static void
fd_event (int error, void *context)
{
  struct serial *scb = context;
  if (error != 0)
    {
      scb->bufcnt = SERIAL_ERROR;
    }
  else if (scb->bufcnt == 0)
    {
      /* Prime the input FIFO.  The readchar() function is used to
         pull characters out of the buffer.  See also
         generic_readchar(). */
      int nr;
      nr = scb->ops->read_prim (scb, BUFSIZ);
      if (nr == 0)
	{
	  scb->bufcnt = SERIAL_EOF;
	}
      else if (nr > 0)
	{
	  scb->bufcnt = nr;
	  scb->bufp = scb->buf;
	}
      else
	{
	  scb->bufcnt = SERIAL_ERROR;
	}
    }
  scb->async_handler (scb, scb->async_context);
  reschedule (scb);
}
void DefaultFileSource::Impl::startRealRequest(DefaultFileRequest& request) {
    assert(!request.realRequest);

    // Cancel the timer if we have one.
    if (request.timerRequest) {
        request.timerRequest->stop();
    }

    auto callback = [this, &request](std::shared_ptr<const Response> response) {
        request.realRequest = nullptr;

        if (cache) {
            // Store response in database. Make sure we only refresh the expires column if the data
            // didn't change.
            FileCache::Hint hint = FileCache::Hint::Full;
            if (request.getResponse() && response->data == request.getResponse()->data) {
                hint = FileCache::Hint::Refresh;
            }
            cache->put(request.resource, response, hint);
        }

        request.setResponse(response);
        request.notify();
        reschedule(request);
    };

    if (algo::starts_with(request.resource.url, "asset://")) {
        request.realRequest =
            assetContext->createRequest(request.resource, callback, loop, assetRoot);
    } else {
        request.realRequest =
            httpContext->createRequest(request.resource, callback, loop, request.getResponse());
    }
}
Beispiel #13
0
int timer_wait(unsigned int ticks)
{
	uint64_t eticks = per_core(timer_ticks) + ticks;

	task_t* curr_task = per_core(current_task);

	if (curr_task->status == TASK_IDLE)
	{
		/*
		 * This will continuously loop until the given time has
		 * been reached
		 */
		while (per_core(timer_ticks) < eticks) {
			check_workqueues();

			// recheck break condition
			if (per_core(timer_ticks) >= eticks)
				break;

			PAUSE;
		}
	} else if (per_core(timer_ticks) < eticks) {
		check_workqueues();

		if (per_core(timer_ticks) < eticks) {
			set_timer(eticks);
			reschedule();
		}
	}

	return 0;
}
Beispiel #14
0
void
dumpme(int flag)
{
	int		f;
	double		x;
	struct event	*e;
	int		i;

	f = flag;
	Ship.quadx = ranf(NQUADS);
	Ship.quady = ranf(NQUADS);
	Ship.sectx = ranf(NSECTS);
	Ship.secty = ranf(NSECTS);
	x = 1.5 * franf();
	Move.time += x;
	if (f) {
		printf("%s falls into a black hole.\n", Ship.shipname);
	} else {
		printf("Computer applies full reverse power to avoid hitting "
		       "the\n");
		printf("   negative energy barrier.  A space warp was "
		       "entered.\n");
	}
	/* bump repair dates forward */
	for (i = 0; i < MAXEVENTS; i++) {
		e = &Event[i];
		if (e->evcode != E_FIXDV)
			continue;
		reschedule(e, (e->date - Now.date) + x);
	}
	events(1);
	printf("You are now in quadrant %d,%d.  It is stardate %.2f\n",
		Ship.quadx, Ship.quady, Now.date);
	Move.time = 0;
}
Beispiel #15
0
    void Monotonic::Manager::stop(Monotonic *timer)
    {
      for(auto i = timers.begin(); i != timers.end();)
      {
        Monotonic *current = *i;

        if(current == timer)
        {
          i = timers.erase(i);
        }
        else
        {
          ++i;
        }
      }

      if(!timers.empty())
      {
        reschedule();
      }
      else
      {
        Watcher::disable();
      }
    }
Beispiel #16
0
void wake_thread(unsigned int id)
{
    if(threads[id-1] != NULL)
        threads[id-1]->state = THREAD_READY;
    reschedule();
    return;
}
Beispiel #17
0
    void Real::Manager::stop(Real *timer)
    {
      for(std::list<Real *>::iterator i = timers.begin(); i != timers.end();)
      {
        Real *current = *i;

        if(current == timer)
        {
          i = timers.erase(i);
        }
        else
        {
          ++i;
        }
      }

      if(!timers.empty())
      {
        reschedule();
      }
      else
      {
        Watcher::disable();
      }
    }
Beispiel #18
0
void __attribute__((noreturn)) kernel_main(unsigned int _memory_size)
{
    struct vm_translation_map *init_map;
    struct process *init_proc;

    vm_page_init(_memory_size);
    init_map = vm_translation_map_init();
    boot_init_heap((char*) KERNEL_HEAP_BASE + PAGE_STRUCTURES_SIZE(_memory_size));
    vm_address_space_init(init_map);
    bootstrap_vm_cache();
    bool_init_kernel_process();
    boot_init_thread();

    // Start other threads
    REGISTERS[REG_THREAD_RESUME] = 0xffffffff;

    spawn_kernel_thread("Grim Reaper", grim_reaper, 0);

    init_proc = exec_program("program.elf");

    // Idle task
    for (;;)
    {
        if (list_is_empty(&init_proc->thread_list))
        {
            kprintf("init process has exited, shutting down\n");
            REGISTERS[REG_THREAD_HALT] = 0xffffffff;
        }

        reschedule();
    }
}
Beispiel #19
0
void NORETURN do_exit(int arg)
{
	task_t* curr_task = per_core(current_task);
	const uint32_t core_id = CORE_ID;

	LOG_INFO("Terminate task: %u, return value %d\n", curr_task->id, arg);

	uint8_t flags = irq_nested_disable();

	// decrease the number of active tasks
	spinlock_irqsave_lock(&readyqueues[core_id].lock);
	readyqueues[core_id].nr_tasks--;
	spinlock_irqsave_unlock(&readyqueues[core_id].lock);

	// release the thread local storage
	destroy_tls();

	curr_task->status = TASK_FINISHED;

	reschedule();

	irq_nested_enable(flags);

	LOG_ERROR("Kernel panic: scheduler found no valid task\n");
	while(1) {
		HALT;
	}
}
Beispiel #20
0
/** @brief A procedure to be called by
 * procedures which are called by exiting tasks. */
static void NORETURN do_exit(int arg)
{
  int task_id;
  
  task_t* curr_task = current_task;

  kprintf("Terminate task: %u, return value %d\n", curr_task->id, arg);

  page_map_drop();

  for (task_id = 0; task_id = MAX_TASKS; task_id++) {
    task_t* task = &task_table[task_id];
    if (task->status == TASK_IDLE && task->wait_id == curr_task->id) {
      task->wait_id = -1;
      task->status = TASK_READY;
    }
  }
  // decrease the number of active tasks
  spinlock_irqsave_lock(&readyqueues.lock);
  readyqueues.nr_tasks--;
  spinlock_irqsave_unlock(&readyqueues.lock);

  curr_task->status = TASK_FINISHED;
  reschedule();

  kprintf("Kernel panic: scheduler found no valid task\n");
  while(1) {
    HALT;
  }
}
// Runs in exclusion with alarm_cancel and timer_callback.
void alarm_set(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data) {
  assert(alarms != NULL);
  assert(alarm != NULL);
  assert(cb != NULL);

  pthread_mutex_lock(&monitor);

  // If the alarm is currently set and it's at the start of the list,
  // we'll need to re-schedule since we've adjusted the earliest deadline.
  bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
  if (alarm->callback)
    list_remove(alarms, alarm);

  alarm->deadline = now() + deadline;
  alarm->callback = cb;
  alarm->data = data;

  // Add it into the timer list sorted by deadline (earliest deadline first).
  if (list_is_empty(alarms))
    list_prepend(alarms, alarm);
  else
    for (list_node_t *node = list_begin(alarms); node != list_end(alarms); node = list_next(node)) {
      list_node_t *next = list_next(node);
      if (next == list_end(alarms) || ((alarm_t *)list_node(next))->deadline >= alarm->deadline) {
        list_insert_after(alarms, node, alarm);
        break;
      }
    }

  // If the new alarm has the earliest deadline, we need to re-evaluate our schedule.
  if (needs_reschedule || (!list_is_empty(alarms) && list_front(alarms) == alarm))
    reschedule();

  pthread_mutex_unlock(&monitor);
}
Beispiel #22
0
        void free(void* p, std::size_t count = 1)
        {
            if (NULL == p || !threads::threadmanager_is(running))
                return;

            // if this is called from outside a HPX thread we need to
            // re-schedule the request
            typedef boost::is_same<boost::shared_mutex, SharedMutex>
                reschedule_pred;
            if (reschedule(p, count, reschedule_pred()))
                return;

            shared_lock_type guard(mtx_);

            // Find the heap which allocated this pointer.
            for (iterator it = heap_list_.begin(); it != heap_list_.end(); ++it)
            {
                if ((*it)->did_alloc(p))
                {
                    (*it)->free(p, count);
                    free_count_ += count;
                    return;
                }
            }

            HPX_THROW_EXCEPTION(bad_parameter,
                name() + "::free",
                boost::str(boost::format(
                    "pointer %1% was not allocated by this %2%")
                    % p % name()));
        }
Beispiel #23
0
/*
 * Rotate the ready queue including the highest priority task.
 */
EXPORT void rotate_ready_queue_run( void )
{
	if ( schedtsk != NULL ) {
		ready_queue_rotate(&ready_queue,
				ready_queue_top_priority(&ready_queue));
		reschedule();
	}
}
Beispiel #24
0
void MprTimer::reschedule(int msec)
{
	if (msec < 10) {				// Sanity check
		msec = 10;
	}
	period = msec;
	reschedule();
}
Beispiel #25
0
static void battery_exit(void)
{
	trace("");

	reschedule( 0 );		// make sure we kill the timer :)
	flush_workqueue( g_Workqueue );
	destroy_workqueue( g_Workqueue );
}
Beispiel #26
0
dock()
{
	register int		i, j;
	int			ok;
	register struct event	*e;

	if (Ship.cond == DOCKED)
		return (printf("Chekov: But captain, we are already docked\n"));
	/* check for ok to dock, i.e., adjacent to a starbase */
	ok = 0;
	for (i = Ship.sectx - 1; i <= Ship.sectx + 1 && !ok; i++)
	{
		if (i < 0 || i >= NSECTS)
			continue;
		for (j = Ship.secty - 1; j <= Ship.secty + 1; j++)
		{
			if (j  < 0 || j >= NSECTS)
				continue;
			if (Sect[i][j] == BASE)
			{
				ok++;
				break;
			}
		}
	}
	if (!ok)
		return (printf("Chekov: But captain, we are not adjacent to a starbase.\n"));

	/* restore resources */
	Ship.energy = Param.energy;
	Ship.torped = Param.torped;
	Ship.shield = Param.shield;
	Ship.crew = Param.crew;
	Game.captives += Param.brigfree - Ship.brigfree;
	Ship.brigfree = Param.brigfree;

	/* reset ship's defenses */
	Ship.shldup = 0;
	Ship.cloaked = 0;
	Ship.cond = DOCKED;
	Ship.reserves = Param.reserves;

	/* recalibrate space inertial navigation system */
	Ship.sinsbad = 0;

	/* output any saved radio messages */
	dumpssradio();

	/* reschedule any device repairs */
	for (i = 0; i < MAXEVENTS; i++)
	{
		e = &Event[i];
		if (e->evcode != E_FIXDV)
			continue;
		reschedule(e, (e->date - Now.date) * Param.dockfac);
	}
	return;
}
Beispiel #27
0
/* This is where most of the magic happens. This function gets called
 * every millisecond to handle scheduling decisions.
 */
static void scheduler_cb(void) {
  U32 time = nx_systick_get_ms();
  bool need_reschedule = FALSE;

  /* Security mechanism: in case the system crashes, as long as the
   * scheduler is still running, the brick can be powered off.
   */
  if (nx_avr_get_button() == BUTTON_CANCEL)
    nx_core_halt();

  /* If the scheduler state is locked, nothing can be done. */
  if (sched_lock > 0)
    return;

  sched_lock = 1;

  /* Process pending commands, if any */
  if (task_command != CMD_NONE) {
    switch (task_command) {
    case CMD_YIELD:
      need_reschedule = TRUE;
      break;
    case CMD_DIE:
      destroy_running_task();
      need_reschedule = TRUE;
      break;
    default:
      break;
    }
    task_command = CMD_NONE;
    nx_systick_unmask_scheduler();
  } else {
    /* Check if the task quantum for the running task has expired. */
    if (time - sched_state.last_context_switch >= TASK_EXECUTION_QUANTUM)
      need_reschedule = TRUE;
  }

  /* Wake up tasks that have scheduled alarms. */
  while (!mv_list_is_empty(sched_state.alarms_pending) &&
         sched_state.alarms_pending->wakeup_time <= time) {
    struct mv_alarm_entry *a = sched_state.alarms_pending;
    mv_list_remove(sched_state.alarms_pending, sched_state.alarms_pending);
    mv__scheduler_task_unblock(a->task);
    nx_free(a);
  }

  /* Task switching time? */
  if (need_reschedule) {
    if (sched_state.task_current != NULL)
      sched_state.task_current->stack_current = mv__task_get_stack();
    reschedule();
    mv__task_set_stack(sched_state.task_current->stack_current);
    sched_state.last_context_switch = nx_systick_get_ms();
  }

  sched_lock = 0;
}
Beispiel #28
0
	int simple_scheduler::add_task(schedules::schedule_object item) {
		{
			boost::mutex::scoped_lock l(mutex_);
			item.id = ++schedule_id_;
			targets_[item.id] = item;
		}
		reschedule(item);
		return item.id;
	}
Beispiel #29
0
static void
push_event (void *context)
{
  struct serial *scb = context;
  scb->async_state = NOTHING_SCHEDULED; /* Timers are one-off */
  scb->async_handler (scb, scb->async_context);
  /* re-schedule */
  reschedule (scb);
}
Beispiel #30
0
void main (uint32_t mboot_magic, uint32_t mboot_info)
    {
    multiboot_memmap_t *first_free;
    uint64_t *new_stack;

    asm volatile ("cli");

    cpu_early_init();

    x64_gdt_init();

    x64_idt_init();

    vga_console_init();

    printk("\n================================\n");
    printk("||==Welcome to CELLOS 64 bit==||");
    printk("\n================================\n");

    /* Read mboot header */

    first_free = mboot_init(mboot_info, mboot_magic);

    if (first_free == NULL)
        {
        panic("No free memory for use! STOP~!\n");
        }

    mb_parse_kernel_image();
    
    paging_init(first_free->base_addr,
                    first_free->base_addr + first_free->length);

    /* Init page allocator */

    page_alloc_init(mem_get_low_addr(),mem_get_high_addr());

    /* Initialize the memory pool */
    init_memory_pool(CONFIG_KHEAP_SIZE,
                    (void *)page_alloc_contig(CONFIG_KHEAP_SIZE/PAGE_SIZE));

    detect_cpu();

    acpi_init();

    smp_init();

    paging_late_init();

    sched_core_init();

    sched_init();

    reschedule();
    
    /* No reached */ 
    }