mbed.org local branch of microbit-dal. The real version lives in git at https://github.com/lancaster-university/microbit-dal

Dependencies:   BLE_API nRF51822 mbed-dev-bin

Dependents:   microbit Microbit IoTChallenge1 microbit ... more

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers MicroBitFiber.h Source File

MicroBitFiber.h

00001 /*
00002 The MIT License (MIT)
00003 
00004 Copyright (c) 2016 British Broadcasting Corporation.
00005 This software is provided by Lancaster University by arrangement with the BBC.
00006 
00007 Permission is hereby granted, free of charge, to any person obtaining a
00008 copy of this software and associated documentation files (the "Software"),
00009 to deal in the Software without restriction, including without limitation
00010 the rights to use, copy, modify, merge, publish, distribute, sublicense,
00011 and/or sell copies of the Software, and to permit persons to whom the
00012 Software is furnished to do so, subject to the following conditions:
00013 
00014 The above copyright notice and this permission notice shall be included in
00015 all copies or substantial portions of the Software.
00016 
00017 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00018 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00019 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
00020 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00021 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
00022 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
00023 DEALINGS IN THE SOFTWARE.
00024 */
00025 
00026 /**
00027   * Functionality definitions for the MicroBit Fiber scheduler.
00028   *
00029   * This lightweight, non-preemptive scheduler provides a simple threading mechanism for two main purposes:
00030   *
00031   * 1) To provide a clean abstraction for application languages to use when building async behaviour (callbacks).
00032   * 2) To provide ISR decoupling for EventModel events generated in an ISR context.
00033   *
00034   * TODO: Consider a split mode scheduler, that monitors used stack size, and maintains a dedicated, persistent
00035   * stack for any long lived fibers with large stack
00036   */
00037 #ifndef MICROBIT_FIBER_H
00038 #define MICROBIT_FIBER_H
00039 
00040 #include "mbed.h"
00041 #include "MicroBitConfig.h"
00042 #include "MicroBitEvent.h"
00043 #include "EventModel.h"
00044 
00045 // Fiber Scheduler Flags
00046 #define MICROBIT_SCHEDULER_RUNNING          0x01
00047 
00048 // Fiber Flags
00049 #define MICROBIT_FIBER_FLAG_FOB             0x01
00050 #define MICROBIT_FIBER_FLAG_PARENT          0x02
00051 #define MICROBIT_FIBER_FLAG_CHILD           0x04
00052 #define MICROBIT_FIBER_FLAG_DO_NOT_PAGE     0x08
00053 
00054 /**
00055   *  Thread Context for an ARM Cortex M0 core.
00056   *
00057   * This is probably overkill, but the ARMCC compiler uses a lot register optimisation
00058   * in its calling conventions, so better safe than sorry!
00059   */
00060 struct Cortex_M0_TCB
00061 {
00062     uint32_t R0;
00063     uint32_t R1;
00064     uint32_t R2;
00065     uint32_t R3;
00066     uint32_t R4;
00067     uint32_t R5;
00068     uint32_t R6;
00069     uint32_t R7;
00070     uint32_t R8;
00071     uint32_t R9;
00072     uint32_t R10;
00073     uint32_t R11;
00074     uint32_t R12;
00075     uint32_t SP;
00076     uint32_t LR;
00077     uint32_t stack_base;
00078 };
00079 
00080 /**
00081   * Representation of a single Fiber
00082   */
00083 struct Fiber
00084 {
00085     Cortex_M0_TCB tcb;                  // Thread context when last scheduled out.
00086     uint32_t stack_bottom;              // The start address of this Fiber's stack. The stack is heap allocated, and full descending.
00087     uint32_t stack_top;                 // The end address of this Fiber's stack.
00088     uint32_t context;                   // Context specific information.
00089     uint32_t flags;                     // Information about this fiber.
00090     Fiber **queue;                      // The queue this fiber is stored on.
00091     Fiber *next, *prev;                 // Position of this Fiber on the run queue.
00092 };
00093 
00094 extern Fiber *currentFiber;
00095 
00096 
00097 /**
00098   * Initialises the Fiber scheduler.
00099   * Creates a Fiber context around the calling thread, and adds it to the run queue as the current thread.
00100   *
00101   * This function must be called once only from the main thread, and before any other Fiber operation.
00102   *
00103   * @param _messageBus An event model, used to direct the priorities of the scheduler.
00104   */
00105 void scheduler_init(EventModel &_messageBus);
00106 
00107 /**
00108   * Determines if the fiber scheduler is operational.
00109   *
00110   * @return 1 if the fber scheduler is running, 0 otherwise.
00111   */
00112 int fiber_scheduler_running();
00113 
00114 /**
00115   * Exit point for all fibers.
00116   *
00117   * Any fiber reaching the end of its entry function will return here  for recycling.
00118   */
00119 void release_fiber(void);
00120 void release_fiber(void *param);
00121 
00122 /**
00123  * Launches a fiber.
00124  *
00125  * @param ep the entry point for the fiber.
00126  *
00127  * @param cp the completion routine after ep has finished execution
00128  */
00129 void launch_new_fiber(void (*ep)(void), void (*cp)(void))
00130 #ifdef __GCC__
00131     __attribute__((naked))
00132 #endif
00133 ;
00134 
00135 /**
00136  * Launches a fiber with a parameter
00137  *
00138  * @param ep the entry point for the fiber.
00139  *
00140  * @param cp the completion routine after ep has finished execution
00141  *
00142  * @param pm the parameter to provide to ep and cp.
00143  */
00144 void launch_new_fiber_param(void (*ep)(void *), void (*cp)(void *), void *pm)
00145 #ifdef __GCC__
00146     __attribute__((naked))
00147 #endif
00148 ;
00149 
00150 /**
00151   * Creates a new Fiber, and launches it.
00152   *
00153   * @param entry_fn The function the new Fiber will begin execution in.
00154   *
00155   * @param completion_fn The function called when the thread completes execution of entry_fn.
00156   *                      Defaults to release_fiber.
00157   *
00158   * @return The new Fiber, or NULL if the operation could not be completed.
00159   */
00160 Fiber *create_fiber(void (*entry_fn)(void), void (*completion_fn)(void) = release_fiber);
00161 
00162 
00163 /**
00164   * Creates a new parameterised Fiber, and launches it.
00165   *
00166   * @param entry_fn The function the new Fiber will begin execution in.
00167   *
00168   * @param param an untyped parameter passed into the entry_fn and completion_fn.
00169   *
00170   * @param completion_fn The function called when the thread completes execution of entry_fn.
00171   *                      Defaults to release_fiber.
00172   *
00173   * @return The new Fiber, or NULL if the operation could not be completed.
00174   */
00175 Fiber *create_fiber(void (*entry_fn)(void *), void *param, void (*completion_fn)(void *) = release_fiber);
00176 
00177 
00178 /**
00179   * Calls the Fiber scheduler.
00180   * The calling Fiber will likely be blocked, and control given to another waiting fiber.
00181   * Call this function to yield control of the processor when you have nothing more to do.
00182   */
00183 void schedule();
00184 
00185 /**
00186   * Blocks the calling thread for the given period of time.
00187   * The calling thread will be immediateley descheduled, and placed onto a
00188   * wait queue until the requested amount of time has elapsed.
00189   *
00190   * @param t The period of time to sleep, in milliseconds.
00191   *
00192   * @note the fiber will not be be made runnable until after the elapsed time, but there
00193   * are no guarantees precisely when the fiber will next be scheduled.
00194   */
00195 void fiber_sleep(unsigned long t);
00196 
00197 /**
00198   * The timer callback, called from interrupt context once every SYSTEM_TICK_PERIOD_MS milliseconds.
00199   * This function checks to determine if any fibers blocked on the sleep queue need to be woken up
00200   * and made runnable.
00201   */
00202 void scheduler_tick();
00203 
00204 /**
00205   * Blocks the calling thread until the specified event is raised.
00206   * The calling thread will be immediateley descheduled, and placed onto a
00207   * wait queue until the requested event is received.
00208   *
00209   * @param id The ID field of the event to listen for (e.g. MICROBIT_ID_BUTTON_A)
00210   *
00211   * @param value The value of the event to listen for (e.g. MICROBIT_BUTTON_EVT_CLICK)
00212   *
00213   * @return MICROBIT_OK, or MICROBIT_NOT_SUPPORTED if the fiber scheduler is not running, or associated with an EventModel.
00214   *
00215   * @code
00216   * fiber_wait_for_event(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK);
00217   * @endcode
00218   *
00219   * @note the fiber will not be be made runnable until after the event is raised, but there
00220   * are no guarantees precisely when the fiber will next be scheduled.
00221   */
00222 int fiber_wait_for_event(uint16_t id, uint16_t value);
00223 
00224 /**
00225   * Configures the fiber context for the current fiber to block on an event ID
00226   * and value, but does not deschedule the fiber.
00227   *
00228   * @param id The ID field of the event to listen for (e.g. MICROBIT_ID_BUTTON_A)
00229   *
00230   * @param value The value of the event to listen for (e.g. MICROBIT_BUTTON_EVT_CLICK)
00231   *
00232   * @return MICROBIT_OK, or MICROBIT_NOT_SUPPORTED if the fiber scheduler is not running, or associated with an EventModel.
00233   *
00234   * @code
00235   * fiber_wake_on_event(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK);
00236   *
00237   * //perform some time critical operation.
00238   *
00239   * //deschedule the current fiber manually, waiting for the previously configured event.
00240   * schedule();
00241   * @endcode
00242   */
00243 int fiber_wake_on_event(uint16_t id, uint16_t value);
00244 
00245 /**
00246   * Executes the given function asynchronously if necessary.
00247   *
00248   * Fibers are often used to run event handlers, however many of these event handlers are very simple functions
00249   * that complete very quickly, bringing unecessary RAM overhead.
00250   *
00251   * This function takes a snapshot of the current processor context, then attempts to optimistically call the given function directly.
00252   * We only create an additional fiber if that function performs a block operation.
00253   *
00254   * @param entry_fn The function to execute.
00255   *
00256   * @return MICROBIT_OK, or MICROBIT_INVALID_PARAMETER.
00257   */
00258 int invoke(void (*entry_fn)(void));
00259 
00260 /**
00261   * Executes the given function asynchronously if necessary, and offers the ability to provide a parameter.
00262   *
00263   * Fibers are often used to run event handlers, however many of these event handlers are very simple functions
00264   * that complete very quickly, bringing unecessary RAM. overhead
00265   *
00266   * This function takes a snapshot of the current fiber context, then attempt to optimistically call the given function directly.
00267   * We only create an additional fiber if that function performs a block operation.
00268   *
00269   * @param entry_fn The function to execute.
00270   *
00271   * @param param an untyped parameter passed into the entry_fn and completion_fn.
00272   *
00273   * @return MICROBIT_OK, or MICROBIT_INVALID_PARAMETER.
00274   */
00275 int invoke(void (*entry_fn)(void *), void *param);
00276 
00277 /**
00278   * Resizes the stack allocation of the current fiber if necessary to hold the system stack.
00279   *
00280   * If the stack allocation is large enough to hold the current system stack, then this function does nothing.
00281   * Otherwise, the the current allocation of the fiber is freed, and a larger block is allocated.
00282   *
00283   * @param f The fiber context to verify.
00284   *
00285   * @return The stack depth of the given fiber.
00286   */
00287 inline void verify_stack_size(Fiber *f);
00288 
00289 /**
00290   * Event callback. Called from an instance of MicroBitMessageBus whenever an event is raised.
00291   *
00292   * This function checks to determine if any fibers blocked on the wait queue need to be woken up
00293   * and made runnable due to the event.
00294   *
00295   * @param evt the event that has just been raised on an instance of MicroBitMessageBus.
00296   */
00297 void scheduler_event(MicroBitEvent evt);
00298 
00299 /**
00300   * Determines if any fibers are waiting to be scheduled.
00301   *
00302   * @return The number of fibers currently on the run queue
00303   */
00304 int scheduler_runqueue_empty();
00305 
00306 /**
00307   * Utility function to add the currenty running fiber to the given queue.
00308   *
00309   * Perform a simple add at the head, to avoid complexity,
00310   *
00311   * Queues are normally very short, so maintaining a doubly linked, sorted list typically outweighs the cost of
00312   * brute force searching.
00313   *
00314   * @param f The fiber to add to the queue
00315   *
00316   * @param queue The run queue to add the fiber to.
00317   */
00318 void queue_fiber(Fiber *f, Fiber **queue);
00319 
00320 /**
00321   * Utility function to the given fiber from whichever queue it is currently stored on.
00322   *
00323   * @param f the fiber to remove.
00324   */
00325 void dequeue_fiber(Fiber *f);
00326 
00327 /**
00328   * Set of tasks to perform when idle.
00329   * Service any background tasks that are required, and attempt a power efficient sleep.
00330   */
00331 void idle();
00332 
00333 /**
00334   * The idle task, which is called when the runtime has no fibers that require execution.
00335   *
00336   * This function typically calls idle().
00337   */
00338 void idle_task();
00339 
00340 /**
00341   * Adds a component to the array of idle thread components, which are processed
00342   * when the run queue is empty.
00343   *
00344   * @param component The component to add to the array.
00345   * @return MICROBIT_OK on success or MICROBIT_NO_RESOURCES if the fiber components array is full.
00346   */
00347 int fiber_add_idle_component(MicroBitComponent *component);
00348 
00349 /**
00350   * remove a component from the array of idle thread components
00351   *
00352   * @param component the component to remove from the idle component array.
00353   * @return MICROBIT_OK on success. MICROBIT_INVALID_PARAMETER is returned if the given component has not been previously added.
00354   */
00355 int fiber_remove_idle_component(MicroBitComponent *component);
00356 
00357 /**
00358   * Determines if the processor is executing in interrupt context.
00359   *
00360   * @return true if any the processor is currently executing any interrupt service routine. False otherwise.
00361   */
00362 inline int inInterruptContext()
00363 {
00364     return (((int)__get_IPSR()) & 0x003F) > 0;
00365 }
00366 
00367 /**
00368   * Assembler Context switch routing.
00369   * Defined in CortexContextSwitch.s.
00370   */
00371 extern "C" void swap_context(Cortex_M0_TCB *from, Cortex_M0_TCB *to, uint32_t from_stack, uint32_t to_stack);
00372 extern "C" void save_context(Cortex_M0_TCB *tcb, uint32_t stack);
00373 extern "C" void save_register_context(Cortex_M0_TCB *tcb);
00374 extern "C" void restore_register_context(Cortex_M0_TCB *tcb);
00375 
00376 #endif