+
+#if CONFIG_KERN_PREEMPT
+/* Global preemption nesting counter */
+cpu_atomic_t preempt_count;
+
+/*
+ * The time sharing interval: when a process is scheduled on a CPU it gets an
+ * amount of CONFIG_KERN_QUANTUM clock ticks. When these ticks expires and
+ * preemption is enabled a new process is selected to run.
+ */
+int _proc_quantum;
+
+/**
+ * Check if we need to schedule another task
+ */
+bool proc_needPreempt(void)
+{
+ if (UNLIKELY(current_process == NULL))
+ return false;
+ if (!proc_preemptAllowed())
+ return false;
+ if (LIST_EMPTY(&proc_ready_list))
+ return false;
+ return preempt_quantum() ? prio_next() > prio_curr() :
+ prio_next() >= prio_curr();
+}
+
+/**
+ * Preempt the current task.
+ */
+void proc_preempt(void)
+{
+ IRQ_ASSERT_DISABLED();
+ ASSERT(current_process);
+
+ /* Perform the kernel preemption */
+ LOG_INFO("preempting %p:%s\n", current_process, proc_currentName());
+ /* We are inside a IRQ context, so ATOMIC is not needed here */
+ SCHED_ENQUEUE(current_process);
+ preempt_reset_quantum();
+ proc_schedule();
+}
+#endif /* CONFIG_KERN_PREEMPT */
+
+/* Immediately switch to a particular process */
+static void proc_switchTo(Process *proc)
+{
+ Process *old_process = current_process;
+
+ SCHED_ENQUEUE(current_process);
+ preempt_reset_quantum();
+ current_process = proc;
+ proc_context_switch(current_process, old_process);
+}
+
+/**
+ * Give the control of the CPU to another process.
+ *
+ * \note Assume the current process has been already added to a wait queue.
+ *
+ * \warning This should be considered an internal kernel function, even if it
+ * is allowed, usage from application code is strongly discouraged.
+ */
+void proc_switch(void)
+{
+ ASSERT(proc_preemptAllowed());
+ ATOMIC(
+ preempt_reset_quantum();
+ proc_schedule();
+ );
+}
+
+/**
+ * Immediately wakeup a process, dispatching it to the CPU.
+ */
+void proc_wakeup(Process *proc)
+{
+ ASSERT(proc_preemptAllowed());
+ ASSERT(current_process);
+ IRQ_ASSERT_DISABLED();
+
+ if (prio_proc(proc) >= prio_curr())
+ proc_switchTo(proc);
+ else
+ SCHED_ENQUEUE_HEAD(proc);
+}
+
+/**
+ * Voluntarily release the CPU.
+ */
+void proc_yield(void)
+{
+ Process *proc;
+
+ /*
+ * Voluntary preemption while preemption is disabled is considered
+ * illegal, as not very useful in practice.
+ *
+ * ASSERT if it happens.
+ */
+ ASSERT(proc_preemptAllowed());
+ IRQ_ASSERT_ENABLED();
+
+ IRQ_DISABLE;
+ proc = (struct Process *)list_remHead(&proc_ready_list);
+ if (proc)
+ proc_switchTo(proc);
+ IRQ_ENABLE;
+}