repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
moslevin/Mark3C
stage/src/threadport.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file threadport.h \brief ATMega328p Multithreading support. */ #ifndef __THREADPORT_H_ #define __THREADPORT_H_ #include "kerneltypes.h" #include "thread.h" #include <avr/io.h> #include <avr/interrupt.h> #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- //! ASM Macro - simplify the use of ASM directive in C #define ASM(x) asm volatile(x); //! Status register define - map to 0x003F #define SR_ 0x3F //! Stack pointer define #define SPH_ 0x3E #define SPL_ 0x3D //--------------------------------------------------------------------------- //! Macro to find the top of a stack given its size and top address #define TOP_OF_STACK(x, y) (K_UCHAR*) ( ((K_USHORT)x) + (y-1) ) //! Push a value y to the stack pointer x and decrement the stack pointer #define PUSH_TO_STACK(x, y) *x = y; x--; //--------------------------------------------------------------------------- //! Save the context of the Thread_t #define Thread_SaveContext() \ ASM("push r0"); \ ASM("in r0, __SREG__"); \ ASM("cli"); \ ASM("push r0"); \ ASM("push r1"); \ ASM("clr r1"); \ ASM("push r2"); \ ASM("push r3"); \ ASM("push r4"); \ ASM("push r5"); \ ASM("push r6"); \ ASM("push r7"); \ ASM("push r8"); \ ASM("push r9"); \ ASM("push r10"); \ ASM("push r11"); \ ASM("push r12"); \ ASM("push r13"); \ ASM("push r14"); \ ASM("push r15"); \ ASM("push r16"); \ ASM("push r17"); \ ASM("push r18"); \ ASM("push r19"); \ ASM("push r20"); \ ASM("push r21"); \ ASM("push r22"); \ ASM("push r23"); \ ASM("push r24"); \ ASM("push r25"); \ ASM("push r26"); \ ASM("push r27"); \ ASM("push r28"); \ ASM("push r29"); \ ASM("push r30"); \ ASM("push r31"); \ ASM("lds r26, g_pstCurrent"); \ ASM("lds r27, g_pstCurrent + 1"); \ ASM("adiw r26, 4"); \ ASM("in r0, 0x3D"); \ ASM("st x+, r0"); \ ASM("in r0, 0x3E"); \ ASM("st x+, r0"); //--------------------------------------------------------------------------- //! Restore the context of the Thread_t #define Thread_RestoreContext() \ ASM("lds r26, g_pstCurrent"); \ ASM("lds r27, g_pstCurrent + 1");\ ASM("adiw r26, 4"); \ ASM("ld r28, x+"); \ ASM("out 0x3D, r28"); \ ASM("ld r29, x+"); \ ASM("out 0x3E, r29"); \ ASM("pop r31"); \ ASM("pop r30"); \ ASM("pop r29"); \ ASM("pop r28"); \ ASM("pop r27"); \ ASM("pop r26"); \ ASM("pop r25"); \ ASM("pop r24"); \ ASM("pop r23"); \ ASM("pop r22"); \ ASM("pop r21"); \ ASM("pop r20"); \ ASM("pop r19"); \ ASM("pop r18"); \ ASM("pop r17"); \ ASM("pop r16"); \ ASM("pop r15"); \ ASM("pop r14"); \ ASM("pop r13"); \ ASM("pop r12"); \ ASM("pop r11"); \ ASM("pop r10"); \ ASM("pop r9"); \ ASM("pop r8"); \ ASM("pop r7"); \ ASM("pop r6"); \ ASM("pop r5"); \ ASM("pop r4"); \ ASM("pop r3"); \ ASM("pop r2"); \ ASM("pop r1"); \ ASM("pop r0"); \ ASM("out __SREG__, r0"); \ ASM("pop r0"); //------------------------------------------------------------------------ //! These macros *must* be used in pairs ! //------------------------------------------------------------------------ //! Enter critical section (copy status register, disable interrupts) #define CS_ENTER() \ { \ volatile K_UCHAR x; \ x = _SFR_IO8(SR_); \ ASM("cli"); //------------------------------------------------------------------------ //! Exit critical section (restore status register) #define CS_EXIT() \ _SFR_IO8(SR_) = x;\ } //------------------------------------------------------------------------ //! Initiate a contex switch without using the SWI #define ENABLE_INTS() ASM("sei"); #define DISABLE_INTS() ASM("cli"); //------------------------------------------------------------------------ /*! Class defining the architecture specific functions required by the kernel. This is limited (at this point) to a function to start the scheduler, and a function to initialize the default stack-frame for a thread. */ //--------------------------------------------------------------------------- /*! \brief ThreadPort_StartThreads Function to start the scheduler, initial threads, etc. */ void ThreadPort_StartThreads(void); //--------------------------------------------------------------------------- /*! \brief ThreadPort_InitStack Initialize the thread's stack. \param pstThread_ Pointer to the thread to initialize */ void ThreadPort_InitStack(Thread_t *pstThread_); #ifdef __cplusplus } #endif #endif //__ThreadPORT_H_
moslevin/Mark3C
tests/unit/ut_sanity/ut_sanity.c
#include "kerneltypes.h" #include "mark3cfg.h" #include "kernel.h" #include "thread.h" #include "driver.h" #include "drvUART.h" #include "profile.h" #include "kernelprofile.h" #include "ksemaphore.h" #include "mutex.h" #include "message.h" #include "timerlist.h" #include "../unit_test.h" #include "../ut_platform.h" #include "kernelaware.h" //--------------------------------------------------------------------------- #include <avr/io.h> #include <avr/interrupt.h> #include <avr/sleep.h> //--------------------------------------------------------------------------- static volatile K_UCHAR ucTestVal; //--------------------------------------------------------------------------- static Mutex_t stMutex; //--------------------------------------------------------------------------- #define TEST_STACK1_SIZE (240) #define TEST_STACK2_SIZE (240) #define TEST_STACK3_SIZE (240) static MessageQueue_t stMsgQ1; static MessageQueue_t stMsgQ2; static Thread_t stTestThread2; static Thread_t stTestThread3; static Thread_t stTestThread1; static K_WORD aucTestStack1[TEST_STACK1_SIZE]; static K_WORD aucTestStack2[TEST_STACK2_SIZE]; static K_WORD aucTestStack3[TEST_STACK3_SIZE]; //--------------------------------------------------------------------------- void TestSemThread(Semaphore_t *pstSe) { Semaphore_Pend( pstSe ); if (ucTestVal != 0x12) { ucTestVal = 0xFF; } else { ucTestVal = 0x21; } Semaphore_Pend( pstSe ); if (ucTestVal != 0x32) { ucTestVal = 0xFF; } else { ucTestVal = 0x23; } Semaphore_Pend( pstSe ); if (ucTestVal != 0x45) { ucTestVal = 0xFF; } else { ucTestVal = 0x54; } Semaphore_Pend( pstSe ); } //--------------------------------------------------------------------------- // Binary semaphore test: // Create a worker thread at a higher priority, which pends on a semaphore // that we hold. The main thread and the new thread alternate pending/posting // the semaphore, while modifying/verifying a global variable. //--------------------------------------------------------------------------- //void UT_SemaphoreTest(void) TEST(ut_sanity_sem) { Semaphore_t stSemaphore; Semaphore_Init( &stSemaphore, 0, 1); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 1, (ThreadEntry_t)TestSemThread, (void*)&stSemaphore); Thread_Start( &stTestThread1 ); ucTestVal = 0x12; Semaphore_Post( &stSemaphore ); EXPECT_EQUALS(ucTestVal, 0x21); ucTestVal = 0x32; Semaphore_Post( &stSemaphore ); EXPECT_EQUALS(ucTestVal, 0x23); ucTestVal = 0x45; Semaphore_Post( &stSemaphore ); EXPECT_EQUALS(ucTestVal, 0x54); Thread_Stop( &stTestThread1 ); Thread_Exit( &stTestThread1 ); Semaphore_Init( &stSemaphore, 0, 1 ); } TEST_END //--------------------------------------------------------------------------- void TimedSemaphoreThread_Short( Semaphore_t *pstSe ) { Thread_Sleep(10); Semaphore_Post( pstSe ); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- void TimedSemaphoreThread_Long( Semaphore_t *pstSe ) { Thread_Sleep(20); Semaphore_Post( pstSe ); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- //void UT_TimedSemaphoreTest(void) TEST(ut_sanity_timed_sem) { Semaphore_t stSem; Thread_SetPriority( Scheduler_GetCurrentThread(), 3); Semaphore_Init( &stSem, 0,1); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TimedSemaphoreThread_Short, (void*)&stSem ); Thread_Start( &stTestThread1 ); // Test 1 - block on a semaphore, wait on thread that will post before expiry EXPECT_TRUE( Semaphore_TimedPend( &stSem, 15 ) ); // Test 2 - block on a semaphore, wait on thread that will post after expiry Semaphore_Init( &stSem, 0, 1 ); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TimedSemaphoreThread_Long, (void*)&stSem ); Thread_Start( &stTestThread1 ); EXPECT_FALSE( Semaphore_TimedPend( &stSem, 15 ) ); Thread_SetPriority( Scheduler_GetCurrentThread(), 1); } TEST_END //--------------------------------------------------------------------------- void TestSleepThread(void *pvArg_) { while(1) { ucTestVal = 0xAA; } } //--------------------------------------------------------------------------- // Sleep Test // Verify that thread sleeping works as expected. Check that the lower // priority thread is able to execute, setting the global variable to a // target value. //--------------------------------------------------------------------------- //void UT_SleepTest(void) TEST(ut_sanity_sleep) { Thread_SetPriority( Scheduler_GetCurrentThread(), 3 ); ucTestVal = 0x00; // Create a lower-priority thread that sets the test value to a known // cookie. Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TestSleepThread, NULL); Thread_Start( &stTestThread1 ); // Sleep, when we wake up check the test value Thread_Sleep(5); EXPECT_EQUALS(ucTestVal, 0xAA); Thread_Exit( &stTestThread1 ); Thread_SetPriority( Scheduler_GetCurrentThread(), 1 ); } TEST_END //--------------------------------------------------------------------------- void TestMutexThread(Mutex_t *pstMutex_) { Mutex_Claim( pstMutex_ ); if (ucTestVal != 0xDC) { ucTestVal = 0xAA; } else { ucTestVal = 0xAC; } Mutex_Release( pstMutex_ ); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- void TestTimedMutexThreadShort(Mutex_t *pstMutex_) { Mutex_Claim( pstMutex_ ); Thread_Sleep( 10 ); Mutex_Release( pstMutex_ ); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- void TestTimedMutexThreadLong(Mutex_t *pstMutex_) { Mutex_Claim( pstMutex_ ); Thread_Sleep( 20 ); Mutex_Release( pstMutex_ ); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- // Mutex test // Create a mutex and stst| staim it. While the mutex is owned, create a new // thread at a higher priority, which tries to stst| staim the mutex itself. // Use a global variable to verify that the threads do not proceed outside // of the control. //--------------------------------------------------------------------------- //void UT_MutexTest(void) TEST(ut_sanity_mutex) { Mutex_Init( &stMutex ); ucTestVal = 0x10; Mutex_Claim( &stMutex ); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TestMutexThread, (void*)&stMutex ); Thread_Start( &stTestThread1 ); ucTestVal = 0xDC; Mutex_Release( &stMutex ); EXPECT_EQUALS(ucTestVal, 0xAC); Mutex_Init( &stMutex ); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TestTimedMutexThreadShort, (void*)&stMutex ); Thread_Start( &stTestThread1 ); EXPECT_TRUE( Mutex_TimedClaim( &stMutex, 15 ) ); Mutex_Init( &stMutex ); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TestTimedMutexThreadLong, (void*)&stMutex ); Thread_Start( &stTestThread1 ); EXPECT_FALSE( Mutex_TimedClaim( &stMutex, 15 ) ); } TEST_END //--------------------------------------------------------------------------- void TimedMessageThread(MessageQueue_t *pstMsgQ_) { Message_t *pstMsg = GlobalMessagePool_Pop(); Message_SetData( pstMsg, NULL ); Message_SetCode( pstMsg, 0 ); Thread_Sleep(10); MessageQueue_Send( pstMsgQ_, pstMsg ); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- //void UT_TimedMessageTest(void) TEST(ut_sanity_timed_msg) { Message_t *pstMsg; Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TimedMessageThread, (void*)&stMsgQ1); Thread_Start( &stTestThread1 ); pstMsg = MessageQueue_TimedReceive( &stMsgQ1, 15 ); if (!pstMsg) { EXPECT_TRUE(0); } else { EXPECT_TRUE(1); GlobalMessagePool_Push(pstMsg); } pstMsg = MessageQueue_TimedReceive( &stMsgQ1, 10 ); if (pstMsg) { EXPECT_TRUE(0); GlobalMessagePool_Push(pstMsg); } else { EXPECT_TRUE(1); } } TEST_END //--------------------------------------------------------------------------- void TestMessageTest(void *pvArg) { Message_t *pstMesg; bool bPass = true; pstMesg = MessageQueue_Receive( &stMsgQ2 ); if (Message_GetCode( pstMesg ) != 0x11) { bPass = false; } GlobalMessagePool_Push(pstMesg); pstMesg = GlobalMessagePool_Pop(); Message_SetCode( pstMesg, 0x22 ); MessageQueue_Send( &stMsgQ1, pstMesg ); pstMesg = MessageQueue_Receive( &stMsgQ2 ); if(Message_GetCode( pstMesg ) != 0xAA) { bPass = false; } GlobalMessagePool_Push(pstMesg); pstMesg = MessageQueue_Receive( &stMsgQ2 ); if(Message_GetCode( pstMesg ) != 0xBB) { bPass = false; } GlobalMessagePool_Push(pstMesg); pstMesg = MessageQueue_Receive( &stMsgQ2 ); if(Message_GetCode( pstMesg ) != 0xCC) { bPass = false; } GlobalMessagePool_Push(pstMesg); pstMesg = GlobalMessagePool_Pop(); if (bPass) { Message_SetCode( pstMesg, 0xDD ); } else { Message_SetCode( pstMesg, 0xFF ); } MessageQueue_Send( &stMsgQ1, pstMesg ); pstMesg = GlobalMessagePool_Pop(); if (bPass) { Message_SetCode( pstMesg, 0xEE ); } else { Message_SetCode( pstMesg, 0x00 ); } MessageQueue_Send( &stMsgQ1, pstMesg ); pstMesg = GlobalMessagePool_Pop(); if (bPass) { Message_SetCode( pstMesg, 0xFF); } else { Message_SetCode( pstMesg, 0x11); } MessageQueue_Send( &stMsgQ1, pstMesg ); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- // Message test // Create a second thread that we communicate with by passing messages. // Ensure that messages being passed between threads are received as expected // in the correct FIFO order, and have the correct IDs. //--------------------------------------------------------------------------- //void UT_MessageTest(void) TEST(ut_sanity_msg) { MessageQueue_Init( &stMsgQ1 ); MessageQueue_Init( &stMsgQ2 ); Message_t *pstMsg; pstMsg = GlobalMessagePool_Pop(); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TestMessageTest, NULL); Thread_Start( &stTestThread1 ); Thread_Yield(); Message_SetCode( pstMsg, 0x11 ); Message_SetData( pstMsg, NULL ); MessageQueue_Send( &stMsgQ2, pstMsg ); pstMsg = MessageQueue_Receive( &stMsgQ1 ); EXPECT_EQUALS(Message_GetCode( pstMsg ), 0x22); GlobalMessagePool_Push(pstMsg); pstMsg = GlobalMessagePool_Pop(); Message_SetCode( pstMsg, 0xAA); MessageQueue_Send( &stMsgQ2, pstMsg ); pstMsg = GlobalMessagePool_Pop(); Message_SetCode( pstMsg, 0xBB); MessageQueue_Send( &stMsgQ2, pstMsg ); pstMsg = GlobalMessagePool_Pop(); Message_SetCode( pstMsg, 0xCC); MessageQueue_Send( &stMsgQ2, pstMsg ); pstMsg = MessageQueue_Receive( &stMsgQ1 ); EXPECT_EQUALS(Message_GetCode( pstMsg ), 0xDD); GlobalMessagePool_Push(pstMsg); pstMsg = MessageQueue_Receive( &stMsgQ1 ); EXPECT_EQUALS(Message_GetCode( pstMsg ), 0xEE); GlobalMessagePool_Push(pstMsg); pstMsg = MessageQueue_Receive( &stMsgQ1 ); EXPECT_EQUALS(Message_GetCode( pstMsg ), 0xFF); GlobalMessagePool_Push(pstMsg); } TEST_END //--------------------------------------------------------------------------- void TestRRThread(volatile K_ULONG *pulCounter_) { while (1) { (*pulCounter_)++; } } //--------------------------------------------------------------------------- // Round-Robin Thread // Create 3 threads in the same priority group (lower than our thread), and // set their quantums to different values. Verify that the ratios of their // "work cycles" are stst| stose to equivalent. //--------------------------------------------------------------------------- //void UT_RoundRobinTest(void) TEST(ut_sanity_rr) { volatile K_ULONG ulCounter1 = 0; volatile K_ULONG ulCounter2 = 0; volatile K_ULONG ulCounter3 = 0; K_ULONG ulDelta; Thread_SetPriority( Scheduler_GetCurrentThread(), 3); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TestRRThread, (void*)&ulCounter1 ); Thread_Init( &stTestThread2, aucTestStack2, TEST_STACK2_SIZE, 2, (ThreadEntry_t)TestRRThread, (void*)&ulCounter2 ); Thread_Init( &stTestThread3, aucTestStack3, TEST_STACK3_SIZE, 2, (ThreadEntry_t)TestRRThread, (void*)&ulCounter3 ); Thread_Start( &stTestThread1 ); Thread_Start( &stTestThread2 ); Thread_Start( &stTestThread3 ); // Sleep for a while to let the other threads execute Thread_Sleep(120); // Must be modal to the worker thread quantums if (ulCounter1 > ulCounter2) { ulDelta = ulCounter1 - ulCounter2; } else { ulDelta = ulCounter2 - ulCounter1; } // Give or take... EXPECT_FALSE(ulDelta > ulCounter1/2); if (ulCounter1 > ulCounter3) { ulDelta = ulCounter1 - ulCounter3; } else { ulDelta = ulCounter3 - ulCounter1; } // Give or take... EXPECT_FALSE(ulDelta > ulCounter1/2); Thread_Exit( &stTestThread1 ); Thread_Exit( &stTestThread2 ); Thread_Exit( &stTestThread3 ); Thread_SetPriority( Scheduler_GetCurrentThread(), 1 ); } TEST_END //--------------------------------------------------------------------------- //void UT_QuantumTest(void) TEST(ut_sanity_quantum) { volatile K_ULONG ulCounter1 = 0; volatile K_ULONG ulCounter2 = 0; volatile K_ULONG ulCounter3 = 0; K_ULONG ulDelta; Thread_SetPriority( Scheduler_GetCurrentThread(), 3); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)TestRRThread, (void*)&ulCounter1 ); Thread_Init( &stTestThread2, aucTestStack2, TEST_STACK2_SIZE, 2, (ThreadEntry_t)TestRRThread, (void*)&ulCounter2 ); Thread_Init( &stTestThread3, aucTestStack3, TEST_STACK3_SIZE, 2, (ThreadEntry_t)TestRRThread, (void*)&ulCounter3 ); Thread_SetQuantum( &stTestThread1, 10 ); Thread_SetQuantum( &stTestThread2, 20); Thread_SetQuantum( &stTestThread3, 30); Thread_Start( &stTestThread1 ); Thread_Start( &stTestThread2 ); Thread_Start( &stTestThread3 ); // Sleep for a while to let the other threads execute Thread_Sleep(180); // Must be modal to the worker thread quantums // Kill the worker threads ulCounter2 /= 2; ulCounter3 /= 3; if (ulCounter1 > ulCounter2) { ulDelta = ulCounter1 - ulCounter2; } else { ulDelta = ulCounter2 - ulCounter1; } // Give or take... EXPECT_FALSE(ulDelta > ulCounter1/2); if (ulCounter1 > ulCounter3) { ulDelta = ulCounter1 - ulCounter3; } else { ulDelta = ulCounter3 - ulCounter1; } // Give or take... EXPECT_FALSE(ulDelta > ulCounter1/2); Thread_Exit( &stTestThread1 ); Thread_Exit( &stTestThread2 ); Thread_Exit( &stTestThread3 ); Thread_SetPriority( Scheduler_GetCurrentThread(), 1 ); } TEST_END void TimerTestCallback(Thread_t *pstOwner_, void *pvData_) { ucTestVal++; } //void UT_TimerTest(void) TEST(ut_sanity_timer) { Timer_t stTimer; ucTestVal = 0; Timer_Init( &stTimer ); Timer_Start( &stTimer, 1, 2, TimerTestCallback, NULL ); Thread_Sleep(3); EXPECT_EQUALS(ucTestVal, 1); ucTestVal = 0; Timer_Stop( &stTimer ); Timer_Start( &stTimer, 1, 1, TimerTestCallback, NULL); Thread_Sleep(10); EXPECT_GTE(ucTestVal, 9); Timer_Stop( &stTimer ); } TEST_END //=========================================================================== // Test Whitelist Goes Here //=========================================================================== TEST_CASE_START TEST_CASE(ut_sanity_sem), TEST_CASE(ut_sanity_timed_sem), TEST_CASE(ut_sanity_sleep), TEST_CASE(ut_sanity_mutex), TEST_CASE(ut_sanity_msg), TEST_CASE(ut_sanity_timed_msg), TEST_CASE(ut_sanity_rr), TEST_CASE(ut_sanity_quantum), TEST_CASE(ut_sanity_timer), TEST_CASE_END
moslevin/Mark3C
tests/unit/ut_semaphore/ut_semaphore.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ //--------------------------------------------------------------------------- #include "kerneltypes.h" #include "kernel.h" #include "../ut_platform.h" #include "ksemaphore.h" #include "thread.h" #include "memutil.h" #include "driver.h" #include "kernelaware.h" //=========================================================================== // Local Defines //=========================================================================== //=========================================================================== // Define Test Cases Here //=========================================================================== TEST(ut_semaphore_count) { // Test - verify that we can only increment a counting Semaphore_t to the // maximum count. // Verify that a counting Semaphore_t with an initial count of zero and a // maximum count of 10 can only be posted 10 times before saturaiton and // failure. Semaphore_t stTestSem; Semaphore_Init( &stTestSem, 0, 10 ); int i; for (i = 0; i < 10; i++) { EXPECT_TRUE(Semaphore_Post(&stTestSem)); } EXPECT_FALSE(Semaphore_Post(&stTestSem)); } TEST_END //=========================================================================== static Thread_t stThread; #define SEM_STACK_SIZE (256) static K_WORD aucStack[SEM_STACK_SIZE]; static Semaphore_t stSem1; static Semaphore_t stSem2; static volatile K_UCHAR ucCounter = 0; //=========================================================================== void PostPendFunction(void *para) { Semaphore_t *pstSem = (Semaphore_t*)para; while(1) { Semaphore_Pend( pstSem ); ucCounter++; } } //=========================================================================== TEST(ut_semaphore_post_pend) { // Test - Make sure that pending on a Semaphore_t causes a higher-priority // waiting thread to block, and that posting that Semaphore_t from a running // lower-priority thread awakens the higher-priority thread Semaphore_Init( &stSem1, 0, 1); Thread_Init( &stThread, aucStack, SEM_STACK_SIZE, 7, PostPendFunction, (void*)&stSem1); Thread_Start( &stThread ); KernelAware_ProfileInit("seminit"); int i; for (i = 0; i < 10; i++) { KernelAware_ProfileStart(); Semaphore_Post( &stSem1 ); KernelAware_ProfileStop(); } KernelAware_ProfileReport(); // Verify all 10 posts have been acknowledged by the high-priority thread EXPECT_EQUALS(ucCounter, 10); // After the test is over, kill the test thread. Thread_Exit( &stThread ); // Test - same as above, but with a counting Semaphore_t instead of a // binary Semaphore_t. Also using a default value. Semaphore_Init( &stSem2, 10, 10); // Restart the test thread. ucCounter = 0; Thread_Init( &stThread, aucStack, SEM_STACK_SIZE, 7, PostPendFunction, (void*)&stSem2); Thread_Start( &stThread ); // We'll kill the thread as soon as it blocks. Thread_Exit( &stThread ); // Semaphore_t should have pended 10 times before returning. EXPECT_EQUALS(ucCounter, 10); } TEST_END //=========================================================================== void TimeSemFunction(void *para) { Semaphore_t *pstSem = (Semaphore_t*)para; Thread_Sleep(20); Semaphore_Post( pstSem ); Thread_Exit( Scheduler_GetCurrentThread() ); } //=========================================================================== TEST(ut_semaphore_timed) { Semaphore_t stTestSem; Semaphore_t stTestSem2; Semaphore_Init( &stTestSem, 0,1); Thread_Init( &stThread, aucStack, SEM_STACK_SIZE, 7, TimeSemFunction, (void*)&stTestSem); Thread_Start( &stThread ); EXPECT_FALSE( Semaphore_TimedPend( &stTestSem, 10 ) ); Thread_Sleep(20); // Pretty nuanced - we can only re-init the Semaphore_t under the knowledge // that there's nothing blocking on it already... don't do this in // production Semaphore_Init( &stTestSem2, 0,1); Thread_Init( &stThread, aucStack, SEM_STACK_SIZE, 7, TimeSemFunction, (void*)&stTestSem2); Thread_Start( &stThread ); EXPECT_TRUE( Semaphore_TimedPend( &stTestSem2, 30) ); } TEST_END //=========================================================================== // Test Whitelist Goes Here //=========================================================================== TEST_CASE_START TEST_CASE(ut_semaphore_count), TEST_CASE(ut_semaphore_post_pend), TEST_CASE(ut_semaphore_timed), TEST_CASE_END
moslevin/Mark3C
kernel/cpu/cm0/stm32f0/gcc/public/threadport.h
<reponame>moslevin/Mark3C /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file threadport.h \brief Cortex M-0 Multithreading support. */ #ifndef __THREADPORT_H_ #define __THREADPORT_H_ #include "kerneltypes.h" #include "thread.h" #include <stm32f0xx.h> //--------------------------------------------------------------------------- //! ASM Macro - simplify the use of ASM directive in C #define ASM asm volatile //--------------------------------------------------------------------------- //! Macro to find the top of a stack given its size and top address #define TOP_OF_STACK(x, y) (K_WORD*) ( ((K_ULONG)x) + (y - sizeof(K_WORD)) ) //! Push a value y to the stack pointer x and decrement the stack pointer #define PUSH_TO_STACK(x, y) *x = y; x--; //------------------------------------------------------------------------ //! These macros *must* be used in matched-pairs ! //! Nesting *is* supported ! extern volatile K_ULONG g_ulCriticalCount; //------------------------------------------------------------------------ #ifndef xDMB #define xDMB() ASM(" dmb \n"); #endif #ifndef xdisable_irq #define xdisable_irq() ASM(" cpsid i \n"); #endif #ifndef xenable_irq #define xenable_irq() ASM(" cpsie i \n"); #endif #define ENABLE_INTS() { xDMB(); xenable_irq(); } #define DISABLE_INTS() { xdisable_irq(); xDMB(); } //------------------------------------------------------------------------ //! Enter critical section (copy current PRIMASK register value, disable interrupts) #define CS_ENTER() \ { \ DISABLE_INTS(); \ g_ulCriticalCount++;\ } //------------------------------------------------------------------------ //! Exit critical section (restore previous PRIMASK status register value) #define CS_EXIT() \ { \ g_ulCriticalCount--; \ if( 0 == g_ulCriticalCount ) { \ ENABLE_INTS(); \ } \ } /*! \fn void StartThreads() Function to start the scheduler, initial threads, etc. */ void ThreadPort_StartThreads(); /*! \fn void InitStack(Thread *pstThread_) Initialize the thread's stack. \param pstThread_ Pointer to the thread to initialize */ void ThreadPort_InitStack(Thread_t *pstThread_); #endif //__ThreadPORT_H_
moslevin/Mark3C
kernel/threadlist.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file threadlist.cpp \brief Thread_t linked-list definitions */ #include "kerneltypes.h" #include "ll.h" #include "threadlist.h" #include "thread.h" #include "kerneldebug.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ THREADLIST_CPP //!< File ID used in kernel trace calls //--------------------------------------------------------------------------- void ThreadList_Init( ThreadList_t *pstList_ ) { CircularLinkList_Init( (CircularLinkList_t*)pstList_ ); pstList_->ucPriority = 0; pstList_->pucFlag = NULL; } //--------------------------------------------------------------------------- void ThreadList_SetPriority( ThreadList_t *pstList_, K_UCHAR ucPriority_ ) { pstList_->ucPriority = ucPriority_; } //--------------------------------------------------------------------------- void ThreadList_SetFlagPointer( ThreadList_t *pstList_, K_UCHAR *pucFlag_) { pstList_->pucFlag = pucFlag_; } //--------------------------------------------------------------------------- void ThreadList_Add( ThreadList_t *pstList_, Thread_t *node_ ) { CircularLinkList_t *pstCLL = (CircularLinkList_t*)pstList_; CircularLinkList_Add( pstCLL, (LinkListNode_t*)node_); CircularLinkList_PivotForward( pstCLL ); // We've specified a bitmap for this threadlist if (pstList_->pucFlag) { // Set the flag for this priority level *pstList_->pucFlag |= (1 << pstList_->ucPriority); } } //--------------------------------------------------------------------------- void ThreadList_AddEx( ThreadList_t *pstList_, Thread_t *node_, K_UCHAR *pucFlag_, K_UCHAR ucPriority_) { // Set the threadlist's priority level, flag pointer, and then add the // thread to the threadlist ThreadList_SetPriority( pstList_, ucPriority_ ); ThreadList_SetFlagPointer( pstList_, pucFlag_ ); ThreadList_Add( pstList_, node_); } //--------------------------------------------------------------------------- void ThreadList_Remove( ThreadList_t *pstList_, Thread_t *node_) { // Remove the thread from the list CircularLinkList_t *pstCLL = (CircularLinkList_t*)pstList_; CircularLinkList_Remove( pstCLL, (LinkListNode_t*)node_); // If the list is empty... if (!pstCLL->pstHead) { // Clear the bit in the bitmap at this priority level if (pstList_->pucFlag) { *pstList_->pucFlag &= ~(1 << pstList_->ucPriority); } } } //--------------------------------------------------------------------------- Thread_t *ThreadList_HighestWaiter( ThreadList_t *pstList_ ) { Thread_t *pstTemp = (Thread_t*)LinkList_GetHead( (LinkList_t*)pstList_ ); Thread_t *pstChosen = pstTemp; K_UCHAR ucMaxPri = 0; // Go through the list, return the highest-priority thread in this list. while(1) { // Compare against current max-priority thread if (Thread_GetPriority( pstTemp ) >= ucMaxPri) { ucMaxPri = Thread_GetPriority( pstTemp ); pstChosen = pstTemp; } // Break out if this is the last thread in the list if (pstTemp == (Thread_t*)LinkList_GetTail( (LinkList_t*)pstList_ ) ) { break; } pstTemp = (Thread_t*)LinkListNode_GetNext( (LinkListNode_t*)pstTemp ); } return pstChosen; }
moslevin/Mark3C
examples/avr/lab5_mutexes/main.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ #include "mark3.h" /*=========================================================================== Lab Example 5: Using Mutexes. Lessons covered in this example include: -You can use mutexes to lock accesses to a shared resource Takeaway: ===========================================================================*/ //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP1_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp1Thread; static K_WORD awApp1Stack[APP1_STACK_SIZE]; static void App1Main(void *unused_); //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP2_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp2Thread; static K_WORD awApp2Stack[APP2_STACK_SIZE]; static void App2Main(void *unused_); //--------------------------------------------------------------------------- // This is the mutex that we'll use to synchronize two threads in this // demo application. static Mutex_t stMyMutex; // This counter variable is the "shared resource" in the example, protected // by the mutex. Only one thread should be given access to the counter at // any time. static volatile K_ULONG ulCounter = 0; //--------------------------------------------------------------------------- int main(void) { // See the annotations in previous labs for details on init. Kernel_Init(); Thread_Init( &stApp1Thread, awApp1Stack, APP1_STACK_SIZE, 1, App1Main, 0); Thread_Init( &stApp2Thread, awApp2Stack, APP2_STACK_SIZE, 1, App2Main, 0); Thread_Start( &stApp1Thread ); Thread_Start( &stApp2Thread ); // Initialize the mutex used in this example. Mutex_Init( &stMyMutex ); Kernel_Start(); return 0; } //--------------------------------------------------------------------------- void App1Main(void *unused_) { while(1) { // Claim the mutex. This will prevent any other thread from claiming // this lock simulatenously. As a result, the other thread has to // wait until we're done before it can do its work. You will notice // that the Start/Done prints for the thread will come as a pair (i.e. // you won't see "Thread2: Start" then "Thread1: Start"). Mutex_Claim( &stMyMutex ); // Start our work (incrementing a counter). Notice that the Start and // Done prints wind up as a pair when simuated with flAVR. KernelAware_Print("Thread1: Start\n"); ulCounter++; while (ulCounter <= 10000) { ulCounter++; } ulCounter = 0; KernelAware_Print("Thread1: Done\n"); // Release the lock, allowing the other thread to do its thing. Mutex_Release( &stMyMutex ); } } //--------------------------------------------------------------------------- void App2Main(void *unused_) { while(1) { // Claim the mutex. This will prevent any other thread from claiming // this lock simulatenously. As a result, the other thread has to // wait until we're done before it can do its work. You will notice // that the Start/Done prints for the thread will come as a pair (i.e. // you won't see "Thread2: Start" then "Thread1: Start"). Mutex_Claim( &stMyMutex ); // Start our work (incrementing a counter). Notice that the Start and // Done prints wind up as a pair when simuated with flAVR. KernelAware_Print("Thread2: Start\n"); ulCounter++; while (ulCounter <= 10000) { ulCounter++; } ulCounter = 0; KernelAware_Print("Thread2: Done\n"); // Release the lock, allowing the other thread to do its thing. Mutex_Release( &stMyMutex ); } }
moslevin/Mark3C
kernel/public/ksemaphore.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file ksemaphore.h \brief Semaphore_t Blocking Object object declarations */ #ifndef __KSEMAPHORE_H__ #define __KSEMAPHORE_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "blocking.h" #include "threadlist.h" #if KERNEL_USE_SEMAPHORE #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- /*! Counting Semaphore_t, based on BlockingObject base object. */ typedef struct { // Inherit from BlockingObject -- must go first!! ThreadList_t clBlockList; K_USHORT usValue; //!< Current count held by the Semaphore_t K_USHORT usMaxValue; //!< Maximum count that can be held by this Semaphore_t } Semaphore_t; //--------------------------------------------------------------------------- /*! \fn void Init(K_USHORT usInitVal_, K_USHORT usMaxVal_) Initialize a Semaphore_t before use. Must be called before post/pend operations. \param usInitVal_ Initial value held by the Semaphore_t \param usMaxVal_ Maximum value for the Semaphore_t */ void Semaphore_Init( Semaphore_t *pstSe, K_USHORT usInitVal_, K_USHORT usMaxVal_); //--------------------------------------------------------------------------- /*! \fn void Post(); Increment the Semaphore_t count. \return true if the Semaphore_t was posted, false if the count is already maxed out. */ K_BOOL Semaphore_Post( Semaphore_t *pstSe ); //--------------------------------------------------------------------------- /*! \fn void Pend(); Decrement the Semaphore_t count. If the count is zero, the thread will block until the Semaphore_t is pended. */ void Semaphore_Pend( Semaphore_t *pstSe ); //--------------------------------------------------------------------------- /*! \fn K_USHORT GetCount() Return the current Semaphore_t counter. This can be used by a thread to bypass blocking on a Semaphore_t - allowing it to do other things until a non-zero count is returned, instead of blocking until the Semaphore_t is posted. \return The current Semaphore_t counter value. */ K_USHORT Semaphore_GetCount( Semaphore_t *pstSe ); #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- /*! \fn K_BOOL Pend( K_ULONG ulWaitTimeMS_ ); Decrement the Semaphore_t count. If the count is zero, the thread will block until the Semaphore_t is pended. If the specified interval expires before the thread is unblocked, then the status is returned back to the user. \return true - Semaphore_t was acquired before the timeout false - timeout occurred before the Semaphore_t was claimed. */ K_BOOL Semaphore_TimedPend( Semaphore_t *pstSe, K_ULONG ulWaitTimeMS_); #endif #ifdef __cplusplus } #endif #endif //KERNEL_USE_SEMAPHORE #endif
moslevin/Mark3C
kernel/writebuf16.c
<filename>kernel/writebuf16.c /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file writebuf16.cpp \brief 16 bit circular buffer implementation with callbacks. */ #include "kerneltypes.h" #include "writebuf16.h" #include "kerneldebug.h" #include "threadport.h" #if KERNEL_USE_DEBUG && !KERNEL_AWARE_SIMULATION //--------------------------------------------------------------------------- void WriteBuffer16_SetBuffers( WriteBuffer16_t *pstBuffer_, K_USHORT *pusData_, K_USHORT usSize_ ) { pstBuffer_->pusData = pusData_; pstBuffer_->usSize = usSize_; pstBuffer_->usHead = 0; pstBuffer_->usTail = 0; } //--------------------------------------------------------------------------- void WriteBuffer16_SetCallback( WriteBuffer16_t *pstBuffer_, WriteBufferCallback pfCallback_ ) { pstBuffer_->pfCallback = pfCallback_; } //--------------------------------------------------------------------------- void WriteBuffer16_WriteData( WriteBuffer16_t *pstBuffer_, K_USHORT *pusBuf_, K_USHORT usLen_ ) { K_USHORT *apusBuf[1]; K_USHORT ausLen[1]; apusBuf[0] = pusBuf_; ausLen[0] = usLen_; WriteBuffer16_WriteVector( pstBuffer_, apusBuf, ausLen, 1 ); } //--------------------------------------------------------------------------- void WriteBuffer16_WriteVector( WriteBuffer16_t *pstBuffer_, K_USHORT **ppusBuf_, K_USHORT *pusLen_, K_UCHAR ucCount_ ) { K_USHORT usTempHead; K_UCHAR i; K_UCHAR j; K_USHORT usTotalLen = 0; K_BOOL bCallback = false; K_BOOL bRollover = false; // Update the head pointer synchronously, using a small // critical section in order to provide thread safety without // compromising on responsiveness by adding lots of extra // interrupt latency. CS_ENTER(); usTempHead = pstBuffer_->usHead; { for (i = 0; i < ucCount_; i++) { usTotalLen += pusLen_[i]; } pstBuffer_->usHead = (usTempHead + usTotalLen) % pstBuffer_->usSize; } CS_EXIT(); // Call the callback if we cross the 50% mark or rollover if (pstBuffer_->usHead < usTempHead) { if (pstBuffer_->pfCallback) { bCallback = true; bRollover = true; } } else if ((usTempHead < (pstBuffer_->usSize >> 1)) && (pstBuffer_->usHead >= (pstBuffer_->usSize >> 1))) { // Only trigger the callback if it's non-null if (pstBuffer_->pfCallback) { bCallback = true; } } // Are we going to roll-over? for (j = 0; j < ucCount_; j++) { K_USHORT usSegmentLength = pusLen_[j]; if (usSegmentLength + usTempHead >= pstBuffer_->usSize) { // We need to two-part this... First part: before the rollover K_USHORT usTempLen; K_USHORT *pusTmp = &pstBuffer_->pusData[ usTempHead ]; K_USHORT *pusSrc = ppusBuf_[j]; usTempLen = pstBuffer_->usSize - usTempHead; for (i = 0; i < usTempLen; i++) { *pusTmp++ = *pusSrc++; } // Second part: after the rollover usTempLen = usSegmentLength - usTempLen; pusTmp = pstBuffer_->pusData; for (i = 0; i < usTempLen; i++) { *pusTmp++ = *pusSrc++; } } else { // No rollover - do the copy all at once. K_USHORT *pusSrc = ppusBuf_[j]; K_USHORT *pusTmp = &pstBuffer_->pusData[ usTempHead ]; for (K_USHORT i = 0; i < usSegmentLength; i++) { *pusTmp++ = *pusSrc++; } } } // Call the callback if necessary if (bCallback) { if (bRollover) { // Rollover - process the back-half of the buffer pstBuffer_->pfCallback( &pstBuffer_->pusData[ pstBuffer_->usSize >> 1], pstBuffer_->usSize >> 1 ); } else { // 50% point - process the front-half of the buffer pstBuffer_->pfCallback( pstBuffer_->pusData, pstBuffer_->usSize >> 1); } } } #endif
moslevin/Mark3C
kernel/cpu/avr/atmega328p/gcc/kerneltimer.c
<filename>kernel/cpu/avr/atmega328p/gcc/kerneltimer.c /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kerneltimer.cpp \brief Kernel Timer_t Implementation for ATMega328p */ #include "kerneltypes.h" #include "kerneltimer.h" #include "mark3cfg.h" #include <avr/io.h> #include <avr/interrupt.h> #define TCCR1B_INIT ((1 << WGM12) | (1 << CS12)) #define TIMER_IMSK (1 << OCIE1A) #define TIMER_IFR (1 << OCF1A) //--------------------------------------------------------------------------- void KernelTimer_Config(void) { TCCR1B = TCCR1B_INIT; } //--------------------------------------------------------------------------- void KernelTimer_Start(void) { #if !KERNEL_TIMERS_TICKLESS TCCR1B = ((1 << WGM12) | (1 << CS11) | (1 << CS10)); OCR1A = ((SYSTEM_FREQ / 1000) / 64); #else TCCR1B |= (1 << CS12); #endif TCNT1 = 0; TIFR1 &= ~TIMER_IFR; TIMSK1 |= TIMER_IMSK; } //--------------------------------------------------------------------------- void KernelTimer_Stop(void) { #if KERNEL_TIMERS_TICKLESS TIFR1 &= ~TIMER_IFR; TIMSK1 &= ~TIMER_IMSK; TCCR1B &= ~(1 << CS12); // Disable count... TCNT1 = 0; OCR1A = 0; #endif } //--------------------------------------------------------------------------- K_USHORT KernelTimer_Read(void) { #if KERNEL_TIMERS_TICKLESS volatile K_USHORT usRead1; volatile K_USHORT usRead2; do { usRead1 = TCNT1; usRead2 = TCNT1; } while (usRead1 != usRead2); return usRead1; #else return 0; #endif } //--------------------------------------------------------------------------- K_ULONG KernelTimer_SubtractExpiry(K_ULONG ulInterval_) { #if KERNEL_TIMERS_TICKLESS OCR1A -= (K_USHORT)ulInterval_; return (K_ULONG)OCR1A; #else return 0; #endif } //--------------------------------------------------------------------------- K_ULONG KernelTimer_TimeToExpiry(void) { #if KERNEL_TIMERS_TICKLESS K_USHORT usRead = KernelTimer_Read(); K_USHORT usOCR1A = OCR1A; if (usRead >= usOCR1A) { return 0; } else { return (K_ULONG)(usOCR1A - usRead); } #else return 0; #endif } //--------------------------------------------------------------------------- K_ULONG KernelTimer_GetOvertime(void) { return KernelTimer_Read(); } //--------------------------------------------------------------------------- K_ULONG KernelTimer_SetExpiry(K_ULONG ulInterval_) { #if KERNEL_TIMERS_TICKLESS K_USHORT usSetInterval; if (ulInterval_ > 65535) { usSetInterval = 65535; } else { usSetInterval = (K_USHORT)ulInterval_ ; } OCR1A = usSetInterval; return (K_ULONG)usSetInterval; #else return 0; #endif } //--------------------------------------------------------------------------- void KernelTimer_ClearExpiry(void) { #if KERNEL_TIMERS_TICKLESS OCR1A = 65535; // Clear the compare value #endif } //--------------------------------------------------------------------------- K_UCHAR KernelTimer_DI(void) { #if KERNEL_TIMERS_TICKLESS K_BOOL bEnabled = ((TIMSK1 & (TIMER_IMSK)) != 0); TIFR1 &= ~TIMER_IFR; // Clear interrupt flags TIMSK1 &= ~TIMER_IMSK; // Disable interrupt return bEnabled; #else return 0; #endif } //--------------------------------------------------------------------------- void KernelTimer_EI(void) { KernelTimer_RI(0); } //--------------------------------------------------------------------------- void KernelTimer_RI(K_BOOL bEnable_) { #if KERNEL_TIMERS_TICKLESS if (bEnable_) { TIMSK1 |= (1 << OCIE1A); // Enable interrupt } else { TIMSK1 &= ~(1 << OCIE1A); } #endif }
moslevin/Mark3C
kernel/public/profile.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file profile.h \brief High-precision profiling timers Enables the profiling and instrumentation of performance-critical code. Multiple timers can be used simultaneously to enable system-wide performance metrics to be computed in a lightweight manner. Usage: \code ProfileTimer_t stMyTimer; int i; clMyTimer.Init(); // Profile the same block of code ten times for (i = 0; i < 10; i++) { clMyTimer.Start(); ... //Block of code to profile ... clMyTimer.Stop(); } // Get the average execution time of all iterations ulAverageTimer = stMyTimer.GetAverage(); // Get the execution time from the last iteration ulLastTimer = stMyTimer.GetCurrent(); \endcode */ #ifndef __PROFILE_H__ #define __PROFILE_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #if KERNEL_USE_PROFILER #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- typedef struct { K_ULONG ulCumulative; //!< Cumulative tick-count for this timer K_ULONG ulCurrentIteration; //!< Tick-count for the current iteration K_USHORT usInitial; //!< Initial count K_ULONG ulInitialEpoch; //!< Initial Epoch K_USHORT usIterations; //!< Number of iterations executed for this profiling timer K_UCHAR bActive; //!< Wheter or not the timer is active or stopped } ProfileTimer_t; //--------------------------------------------------------------------------- /*! \fn void Init( void ) Initialize the profiling timer prior to use. Can also be used to reset a timer that's been used previously. */ void ProfileTimer_Init( ProfileTimer_t *pstTimer_ ); //--------------------------------------------------------------------------- /*! \fn void Start( void ) Start a profiling session, if the timer is not already active. Has no effect if the timer is already active. */ void ProfileTimer_Start( ProfileTimer_t *pstTimer_ ); //--------------------------------------------------------------------------- /*! \fn void Stop( void ) Stop the current profiling session, adding to the cumulative time for this timer, and the total iteration count. */ void ProfileTimer_Stop( ProfileTimer_t *pstTimer_ ); //--------------------------------------------------------------------------- /*! \fn K_ULONG GetAverage( void ) Get the average time associated with this operation. \return Average tick count normalized over all iterations */ K_ULONG ProfileTimer_GetAverage( ProfileTimer_t *pstTimer_ ); //--------------------------------------------------------------------------- /*! \fn K_ULONG GetCurrent( void ) Return the current tick count held by the profiler. Valid for both active and stopped timers. \return The currently held tick count. */ K_ULONG ProfileTimer_GetCurrent( ProfileTimer_t *pstTimer_ ); //--------------------------------------------------------------------------- /*! Figure out how many ticks have elapsed in this iteration \param usCount_ Current timer count \param ulEpoch_ Current timer epoch \return Current tick count */ K_ULONG ProfileTimer_ComputeCurrentTicks( ProfileTimer_t *pstTimer_, K_USHORT usCount_, K_ULONG ulEpoch_ ); #ifdef __cplusplus } #endif #endif // KERNEL_USE_PROFILE #endif
moslevin/Mark3C
kernel/public/debugtokens.h
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file debugtokens.h \brief Hex codes/translation tables used for efficient string tokenization. We use this for efficiently encoding strings used for kernel traces, debug prints, etc. The upside - this is really fast and efficient for encoding strings and data. Downside? The tools need to parse this header file in order to convert the enumerated data into actual strings, decoding them. */ #ifndef __DEBUG_TOKENS_H__ #define __DEBUG_TOKENS_H__ //--------------------------------------------------------------------------- /*! Source file names start at 0x0000 */ #define BLOCKING_C 0x0001 /* SUBSTITUTE="blocking.c" */ #define DRIVER_C 0x0002 /* SUBSTITUTE="driver.c" */ #define KERNEL_C 0x0003 /* SUBSTITUTE="kernel.c" */ #define LL_C 0x0004 /* SUBSTITUTE="ll.c" */ #define MESSAGE_C 0x0005 /* SUBSTITUTE="message.c" */ #define MUTEX_C 0x0006 /* SUBSTITUTE="Mutex_t.c" */ #define PROFILE_C 0x0007 /* SUBSTITUTE="profile.c" */ #define QUANTUM_C 0x0008 /* SUBSTITUTE="quantum.c" */ #define SCHEDULER_C 0x0009 /* SUBSTITUTE="scheduler.c" */ #define SEMAPHORE_C 0x000A /* SUBSTITUTE="Semaphore_t.c" */ #define THREAD_C 0x000B /* SUBSTITUTE="thread.c" */ #define THREADLIST_C 0x000C /* SUBSTITUTE="threadlist.c" */ #define TIMERLIST_C 0x000D /* SUBSTITUTE="timerlist.c" */ #define KERNELSWI_C 0x000E /* SUBSTITUTE="kernelswi.c" */ #define KERNELTIMER_C 0x000F /* SUBSTITUTE="kerneltimer.c" */ #define KPROFILE_C 0x0010 /* SUBSTITUTE="kernelprofile.c" */ #define THREADPORT_C 0x0011 /* SUBSTITUTE="threadport.c" */ #define TIMER_C 0x0012 /* SUBSTITUTE="timer.c" */ //--------------------------------------------------------------------------- /*! Header file names start at 0x1000 */ #define BLOCKING_H 0x1000 /* SUBSTITUTE="blocking.h" */ #define DRIVER_H 0x1001 /* SUBSTITUTE="driver.h" */ #define KERNEL_H 0x1002 /* SUBSTITUTE="kernel.h" */ #define KERNELTYPES_H 0x1003 /* SUBSTITUTE="kerneltypes.h" */ #define LL_H 0x1004 /* SUBSTITUTE="ll.h" */ #define MANUAL_H 0x1005 /* SUBSTITUTE="manual.h" */ #define MARK3CFG_H 0x1006 /* SUBSTITUTE="mark3cfg.h" */ #define MESSAGE_H 0x1007 /* SUBSTITUTE="message.h" */ #define MUTEX_H 0x1008 /* SUBSTITUTE="mutex.h" */ #define PROFILE_H 0x1009 /* SUBSTITUTE="profile.h" */ #define PROFILING_RESULTS_H 0x100A /* SUBSTITUTE="profiling_results.h" */ #define QUANTUM_H 0x100B /* SUBSTITUTE="quantum.h" */ #define SCHEDULER_H 0x100C /* SUBSTITUTE="scheduler.h" */ #define SEMAPHORE_H 0x100D /* SUBSTITUTE="ksemaphore.h" */ #define THREAD_H 0x100E /* SUBSTITUTE="thread.h" */ #define THREADLIST_H 0x100F /* SUBSTITUTE="threadlist.h" */ #define TIMERLIST_H 0x1010 /* SUBSTITUTE="timerlist.h" */ #define KERNELSWI_H 0x1011 /* SUBSTITUTE="kernelswi.h */ #define KERNELTIMER_H 0x1012 /* SUBSTITUTE="kerneltimer.h */ #define KPROFILE_H 0x1013 /* SUBSTITUTE="kernelprofile.h" */ #define THREADPORT_H 0x1014 /* SUBSTITUTE="threadport.h" */ //--------------------------------------------------------------------------- /*! Indexed strings start at 0x2000 */ #define STR_PANIC 0x2000 /* SUBSTITUTE="!Panic!" */ #define STR_MARK3_INIT 0x2001 /* SUBSTITUTE="Initializing Kernel Objects" */ #define STR_KERNEL_ENTER 0x2002 /* SUBSTITUTE="Starting Kernel" */ #define STR_THREAD_START 0x2003 /* SUBSTITUTE="Switching to First Thread_t" */ #define STR_START_ERROR 0x2004 /* SUBSTITUTE="Error starting kernel - function should never return" */ #define STR_THREAD_CREATE 0x2005 /* SUBSTITUTE="Creating Thread_t" */ #define STR_STACK_SIZE_1 0x2006 /* SUBSTITUTE=" Stack Size: %1" */ #define STR_PRIORITY_1 0x2007 /* SUBSTITUTE=" Priority: %1" */ #define STR_THREAD_ID_1 0x2008 /* SUBSTITUTE=" Thread_t ID: %1" */ #define STR_ENTRYPOINT_1 0x2009 /* SUBSTITUTE=" EntryPoint: %1" */ #define STR_CONTEXT_SWITCH_1 0x200A /* SUBSTITUTE="Context Switch To Thread_t: %1" */ #define STR_IDLING 0x200B /* SUBSTITUTE="Idling CPU" */ #define STR_WAKEUP 0x200C /* SUBSTITUTE="Waking up" */ #define STR_SEMAPHORE_PEND_1 0x200D /* SUBSTITUTE="Semaphore_t Pend: %1" */ #define STR_SEMAPHORE_POST_1 0x200E /* SUBSTITUTE="Semaphore_t Post: %1" */ #define STR_MUTEX_CLAIM_1 0x200F /* SUBSTITUTE="Mutex_t Claim: %1" */ #define STR_MUTEX_RELEASE_1 0x2010 /* SUBSTITUTE="Mutex_t Release: %1" */ #define STR_THREAD_BLOCK_1 0x2011 /* SUBSTITUTE="Thread_t %1 Blocked" */ #define STR_THREAD_UNBLOCK_1 0x2012-2015 /* SUBSTITUTE="Thread_t %1 Unblocked" */ #define STR_ASSERT_FAILED 0x2013 /* SUBSTITUTE="Assertion Failed" */ #define STR_SCHEDULE_1 0x2014 /* SUBSTITUTE="Scheduler chose %1" */ #define STR_THREAD_START_1 0x2015 /* SUBSTITUTE="Thread_t Start: %1" */ #define STR_THREAD_EXIT_1 0x2016 /* SUBSTITUTE="Thread_t Exit: %1" */ //--------------------------------------------------------------------------- #define STR_UNDEFINED 0xFFFF /* SUBSTITUTE="UNDEFINED" */ #endif
moslevin/Mark3C
kernel/ll.c
<reponame>moslevin/Mark3C /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file ll.cpp \brief Core Linked-List implementation, from which all kernel objects are derived */ #include "kerneltypes.h" #include "ll.h" #include "kerneldebug.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ LL_C //!< File ID used in kernel trace calls //--------------------------------------------------------------------------- void DoubleLinkList_Add( DoubleLinkList_t *pstList_, LinkListNode_t *node_) { KERNEL_ASSERT( node_ ); // Add a node to the end of the linked list. if (!pstList_->pstHead) { // If the list is empty, initilize the nodes pstList_->pstHead = node_; pstList_->pstTail = node_; pstList_->pstHead->prev = NULL; pstList_->pstTail->next = NULL; return; } // Move the tail node, and assign it to the new node just passed in pstList_->pstTail->next = node_; node_->prev = pstList_->pstTail; node_->next = NULL; pstList_->pstTail = node_; } //--------------------------------------------------------------------------- void DoubleLinkList_Remove( DoubleLinkList_t *pstList_, LinkListNode_t *node_) { KERNEL_ASSERT( node_ ); if (node_->prev) { #if SAFE_UNLINK if (node_->prev->next != node_) { Kernel_Panic(PANIC_LIST_UNLINK_FAILED); } #endif node_->prev->next = node_->next; } if (node_->next) { #if SAFE_UNLINK if (node_->next->prev != node_) { Kernel_Panic(PANIC_LIST_UNLINK_FAILED); } #endif node_->next->prev = node_->prev; } if (node_ == pstList_->pstHead) { pstList_->pstHead = node_->next; } if (node_ == pstList_->pstTail) { pstList_->pstTail = node_->prev; } LinkListNode_Clear( node_ ); } //--------------------------------------------------------------------------- void CircularLinkList_Add( CircularLinkList_t *pstList_, LinkListNode_t *node_) { KERNEL_ASSERT( node_ ); // Add a node to the end of the linked list. if (!pstList_->pstHead) { // If the list is empty, initilize the nodes pstList_->pstHead = node_; pstList_->pstTail = node_; pstList_->pstHead->prev = pstList_->pstHead; pstList_->pstHead->next = pstList_->pstHead; return; } // Move the tail node, and assign it to the new node just passed in pstList_->pstTail->next = node_; node_->prev = pstList_->pstTail; node_->next = pstList_->pstHead; pstList_->pstTail = node_; pstList_->pstHead->prev = node_; } //--------------------------------------------------------------------------- void CircularLinkList_Remove( CircularLinkList_t *pstList_, LinkListNode_t *node_) { KERNEL_ASSERT( node_ ); // Check to see if this is the head of the list... if ((node_ == pstList_->pstHead) && (pstList_->pstHead == pstList_->pstTail)) { // Clear the head and tail pointers - nothing else left. pstList_->pstHead = NULL; pstList_->pstTail = NULL; return; } #if SAFE_UNLINK // Verify that all nodes are properly connected if ((node_->prev->next != node_) || (node_->next->prev != node_)) { Kernel_Panic(PANIC_LIST_UNLINK_FAILED); } #endif // This is a circularly linked list - no need to check for connection, // just remove the node. node_->next->prev = node_->prev; node_->prev->next = node_->next; if (node_ == pstList_->pstHead) { pstList_->pstHead = pstList_->pstHead->next; } if (node_ == pstList_->pstTail) { pstList_->pstTail = pstList_->pstTail->prev; } LinkListNode_Clear( node_ ); } //--------------------------------------------------------------------------- void CircularLinkList_PivotForward( CircularLinkList_t *pstList_ ) { if (pstList_->pstHead) { pstList_->pstHead = pstList_->pstHead->next; pstList_->pstTail = pstList_->pstTail->next; } } //--------------------------------------------------------------------------- void CircularLinkList_PivotBackward( CircularLinkList_t *pstList_ ) { if (pstList_->pstHead) { pstList_->pstHead = pstList_->pstHead->prev; pstList_->pstTail = pstList_->pstTail->prev; } }
moslevin/Mark3C
tests/unit/ut_platform.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ //--------------------------------------------------------------------------- #include "mark3.h" #include "drvUART.h" #include "unit_test.h" #include "ut_platform.h" #include "memutil.h" #if defined(AVR) #include <avr/io.h> #include <avr/sleep.h> #endif //--------------------------------------------------------------------------- // Global objects static Thread_t AppThread; //!< Main "application" thread static K_WORD aucAppStack[STACK_SIZE_APP]; //--------------------------------------------------------------------------- #if !KERNEL_USE_IDLE_FUNC static Thread_t IdleThread; //!< Idle thread - runs when app can't static K_UCHAR aucIdleStack[STACK_SIZE_IDLE]; #endif //--------------------------------------------------------------------------- static K_UCHAR aucTxBuffer[UART_SIZE_TX]; static K_UCHAR aucRxBuffer[UART_SIZE_RX]; //--------------------------------------------------------------------------- static void AppEntry(void); static void IdleEntry(void); //--------------------------------------------------------------------------- void MyUnitTest_PrintTestResult( UnitTest_t *pstTest_ ) { K_CHAR acTemp[6]; int iLen; PrintString("Test "); PrintString(UnitTest_GetName( pstTest_ )); PrintString(": "); iLen = MemUtil_StringLength(UnitTest_GetName( pstTest_ )); if (iLen >= 32) { iLen = 32; } uint8_t i; for (i = 0; i < 32 - iLen; i++) { PrintString("."); } if (UnitTest_GetPassed(pstTest_) == UnitTest_GetTotal(pstTest_)) { PrintString("(PASS)["); } else { PrintString("(FAIL)["); } MemUtil_DecimalToString16(UnitTest_GetPassed(pstTest_), (K_CHAR*)acTemp); PrintString((const K_CHAR*)acTemp); PrintString("/"); MemUtil_DecimalToString16(UnitTest_GetTotal(pstTest_), (K_CHAR*)acTemp); PrintString((const K_CHAR*)acTemp); PrintString("]\n"); } typedef void (*FuncPtr)(void); //--------------------------------------------------------------------------- void run_tests() { MyTestCase *pstTestCase; pstTestCase = astTestCases; while (pstTestCase->pstTestCase) { pstTestCase->pfTestFunc(); pstTestCase++; } PrintString("--DONE--\n"); Thread_Sleep(100); FuncPtr pfReset = 0; pfReset(); } //--------------------------------------------------------------------------- void init_tests() { MyTestCase *pstTestCase; pstTestCase = astTestCases; while (pstTestCase->pstTestCase) { UnitTest_SetName( pstTestCase->pstTestCase, pstTestCase->szName ); pstTestCase++; } } //--------------------------------------------------------------------------- void PrintString(const K_CHAR *szStr_) { K_CHAR *szTemp = (K_CHAR*)szStr_; while (*szTemp) { while( 1 != Driver_Write( (Driver_t*)&stUART, 1, (K_UCHAR*)szTemp ) ) { /* Do nothing */ } szTemp++; } } //--------------------------------------------------------------------------- void AppEntry(void) { { ATMegaUART_Init( &stUART ); Driver_Control( (Driver_t*)&stUART, CMD_SET_BUFFERS, UART_SIZE_RX, aucRxBuffer, UART_SIZE_TX, aucTxBuffer ); Driver_Open( (Driver_t*)&stUART ); init_tests(); } while(1) { run_tests(); } } //--------------------------------------------------------------------------- void IdleEntry(void) { #if !KERNEL_USE_IDLE_FUNC while(1) { #endif #if defined(AVR) // LPM code; set_sleep_mode(SLEEP_MODE_IDLE); cli(); sleep_enable(); sei(); sleep_cpu(); sleep_disable(); sei(); #endif #if !KERNEL_USE_IDLE_FUNC } #endif } //--------------------------------------------------------------------------- int main(void) { Kernel_Init(); //!< MUST be before other kernel ops Thread_Init( &AppThread, aucAppStack, //!< Pointer to the stack STACK_SIZE_APP, //!< Size of the stack 1, //!< Thread priority (ThreadEntry_t)AppEntry, //!< Entry function (void*)&AppThread );//!< Entry function argument Thread_Start( &AppThread ); //!< Schedule the threads #if KERNEL_USE_IDLE_FUNC Kernel_SetIdleFunc(IdleEntry); #else Thread_Init( &IdleThread, aucIdleStack, //!< Pointer to the stack STACK_SIZE_IDLE, //!< Size of the stack 0, //!< Thread priority (ThreadEntry_t)IdleEntry, //!< Entry function NULL ); //!< Entry function argument Thread_Start( &IdleThread ); #endif Kernel_Start(); //!< Start the kernel! return 0; }
moslevin/Mark3C
kernel/cpu/cm0/stm32f0/gcc/public/kernelswi.h
<filename>kernel/cpu/cm0/stm32f0/gcc/public/kernelswi.h /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernelswi.h \brief Kernel Software interrupt declarations */ #include "kerneltypes.h" #ifndef __KERNELSWI_H_ #define __KERNELSWI_H_ //--------------------------------------------------------------------------- /*! Class providing the software-interrupt required for context-switching in the kernel. */ /*! \fn void Config(void) Configure the software interrupt - must be called before any other software interrupt functions are called. */ void KernelSWI_Config(void); /*! \fn void Start(void) Enable ("Start") the software interrupt functionality */ void KernelSWI_Start(void); /*! \fn void Stop(void) Disable the software interrupt functionality */ void KernelSWI_Stop(void); /*! \fn void Clear(void) Clear the software interrupt */ void KernelSWI_Clear(void); /*! Call the software interrupt \fn void Trigger(void) */ void KernelSWI_Trigger(void); /*! \fn K_UCHAR DI(); Disable the SWI flag itself \return previous status of the SWI, prior to the DI call */ K_UCHAR KernelSWI_DI(); /*! \fn void RI(K_BOOL bEnable_) Restore the state of the SWI to the value specified \param bEnable_ true - enable the SWI, false - disable SWI */ void KernelSWI_RI(K_BOOL bEnable_); #endif // __KERNELSIW_H_
moslevin/Mark3C
tests/unit/unit_test.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file unit_test.cpp \brief Unit test object definition */ #include "kerneltypes.h" #include "unit_test.h" //--------------------------------------------------------------------------- void UnitTest_Init( UnitTest_t *pstTest_ ) { pstTest_->bIsActive = false; pstTest_->usIterations = 0; pstTest_->usPassed = 0; pstTest_->bComplete = false; } //--------------------------------------------------------------------------- void UnitTest_Pass( UnitTest_t *pstTest_ ) { if (pstTest_->bComplete) { return; } if (pstTest_->bIsActive) { pstTest_->bIsActive = false; pstTest_->usIterations++; pstTest_->usPassed++; pstTest_->bStatus = true; } } //--------------------------------------------------------------------------- void UnitTest_Fail( UnitTest_t *pstTest_ ) { if (pstTest_->bComplete) { return; } if (pstTest_->bIsActive) { pstTest_->bIsActive = false; pstTest_->usIterations++; pstTest_->bStatus = false; } } //--------------------------------------------------------------------------- void UnitTest_ExpectTrue( UnitTest_t *pstTest_, bool bExpression_ ) { bExpression_ ? UnitTest_Pass(pstTest_) : UnitTest_Fail(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectFalse( UnitTest_t *pstTest_, bool bExpression_ ) { !bExpression_ ? UnitTest_Pass(pstTest_) : UnitTest_Fail(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ == lExpression_) ? UnitTest_Pass(pstTest_) : UnitTest_Fail(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectFailTrue( UnitTest_t *pstTest_, bool bExpression_ ) { bExpression_ ? UnitTest_Fail(pstTest_) : UnitTest_Pass(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectFailFalse( UnitTest_t *pstTest_, bool bExpression_ ) { !bExpression_ ? UnitTest_Fail(pstTest_) : UnitTest_Pass(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectFailEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ == lExpression_) ? UnitTest_Fail(pstTest_) : UnitTest_Pass(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectGreaterThan( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ > lExpression_) ? UnitTest_Pass(pstTest_) : UnitTest_Fail(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectLessThan( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ < lExpression_) ? UnitTest_Pass(pstTest_) : UnitTest_Fail(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectGreaterThanEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ >= lExpression_) ? UnitTest_Pass(pstTest_) : UnitTest_Fail(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectLessThanEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ <= lExpression_) ? UnitTest_Pass(pstTest_) : UnitTest_Fail(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectFailGreaterThan( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ > lExpression_) ? UnitTest_Fail(pstTest_) : UnitTest_Pass(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectFailLessThan( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ < lExpression_) ? UnitTest_Fail(pstTest_) : UnitTest_Pass(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectFailGreaterThanEquals(UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ >= lExpression_) ? UnitTest_Fail(pstTest_) : UnitTest_Pass(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_ExpectFailLessThanEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ) { (lVal_ <= lExpression_) ? UnitTest_Fail(pstTest_) : UnitTest_Pass(pstTest_); } //--------------------------------------------------------------------------- void UnitTest_SetName( UnitTest_t *pstTest_, const K_CHAR *szName_ ) { pstTest_->szName = szName_; } //--------------------------------------------------------------------------- void UnitTest_Start( UnitTest_t *pstTest_ ) { pstTest_->bIsActive = 1; } //--------------------------------------------------------------------------- void UnitTest_Complete( UnitTest_t *pstTest_ ) { pstTest_->bComplete = 1; } //--------------------------------------------------------------------------- const K_CHAR *UnitTest_GetName( UnitTest_t *pstTest_ ) { return pstTest_->szName; } //--------------------------------------------------------------------------- bool UnitTest_GetResult(UnitTest_t *pstTest_) { return pstTest_->bStatus; } //--------------------------------------------------------------------------- K_USHORT UnitTest_GetPassed(UnitTest_t *pstTest_) { return pstTest_->usPassed; } //--------------------------------------------------------------------------- K_USHORT UnitTest_GetFailed(UnitTest_t *pstTest_) { return pstTest_->usIterations - pstTest_->usPassed; } //--------------------------------------------------------------------------- K_USHORT UnitTest_GetTotal(UnitTest_t *pstTest_) { return pstTest_->usIterations; }
moslevin/Mark3C
examples/avr/lab4_semaphore/main.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ #include "mark3.h" /*=========================================================================== Lab Example 4: Using binary semaphores In this example, we implement two threads, synchronized using a semaphore to model the classic producer-consumer pattern. One thread does work, and then posts the semaphore indicating that the other thread can consume that work. The blocking thread just waits idly until there is data for it to consume. Lessons covered in this example include: -Use of a binary semaphore to implement the producer-consumer pattern -Synchronization of threads (within a single priority, or otherwise) using a semaphore Takeaway: Semaphores can be used to control which threads execute at which time. This allows threads to work cooperatively to achieve a goal in the system. ===========================================================================*/ //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP1_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp1Thread_t; static K_WORD awApp1Stack[APP1_STACK_SIZE]; static void App1Main(void *unused_); //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP2_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp2Thread_t; static K_WORD awApp2Stack[APP2_STACK_SIZE]; static void App2Main(void *unused_); //--------------------------------------------------------------------------- // This is the semaphore that we'll use to synchronize two threads in this // demo application static Semaphore_t stMySem; //--------------------------------------------------------------------------- int main(void) { // See the annotations in previous labs for details on init. Kernel_Init(); // In this example we create two threads to illustrate the use of a // binary semaphore as a synchronization method between two threads. // Thread_t 1 is a "consumer" thread -- It waits, blocked on the semaphore // until thread 2 is done doing some work. Once the semaphore is posted, // the thread is unblocked, and does some work. // Thread_t 2 is thus the "producer" thread -- It does work, and once that // work is done, the semaphore is posted to indicate that the other thread // can use the producer's work product. Thread_Init( &stApp1Thread_t, awApp1Stack, APP1_STACK_SIZE, 1, App1Main, 0); Thread_Init( &stApp2Thread_t, awApp2Stack, APP2_STACK_SIZE, 1, App2Main, 0); Thread_Start( &stApp1Thread_t ); Thread_Start( &stApp2Thread_t ); // Initialize a binary semaphore (maximum value of one, initial value of // zero). Semaphore_Init( &stMySem, 0,1); Kernel_Start(); return 0; } //--------------------------------------------------------------------------- void App1Main(void *unused_) { while(1) { // Wait until the semaphore is posted from the other thread KernelAware_Print("Wait\n"); Semaphore_Pend( &stMySem ); // Producer thread has finished doing its work -- do something to // consume its output. Once again - a contrived example, but we // can imagine that printing out the message is "consuming" the output // from the other thread. KernelAware_Print("Triggered!\n"); } } //--------------------------------------------------------------------------- void App2Main(void *unused_) { volatile K_ULONG ulCounter = 0; while(1) { // Do some work. Once the work is complete, post the semaphore. This // will cause the other thread to wake up and then take some action. // It's a bit contrived, but imagine that the results of this process // are necessary to drive the work done by that other thread. ulCounter++; if (ulCounter == 1000) { ulCounter = 0; KernelAware_Print("Posted\n"); Semaphore_Post(&stMySem); } } }
moslevin/Mark3C
kernel/thread.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file thread.cpp \brief Platform-Independent thread object Definition */ #define INLINE #include "kerneltypes.h" #include "mark3cfg.h" #include "thread.h" #include "scheduler.h" #include "kernelswi.h" #include "timerlist.h" #include "ksemaphore.h" #include "quantum.h" #include "kernel.h" #include "kerneldebug.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ THREAD_C //!< File ID used in kernel trace calls //--------------------------------------------------------------------------- void Thread_Init( Thread_t *pstThread_, K_WORD *pwStack_, K_USHORT usStackSize_, K_UCHAR ucPriority_, ThreadEntry_t pfEntryPoint_, void *pvArg_ ) { static K_UCHAR ucThreadID = 0; KERNEL_ASSERT( pwStack_ ); KERNEL_ASSERT( pfEntryPoint_ ); LinkListNode_Clear( (LinkListNode_t*)pstThread_ ); pstThread_->ucThreadID = ucThreadID++; KERNEL_TRACE_1( STR_STACK_SIZE_1, usStackSize_ ); KERNEL_TRACE_1( STR_PRIORITY_1, (K_UCHAR)ucPriority_ ); KERNEL_TRACE_1( STR_THREAD_ID_1, (K_USHORT)pstThread_->ucThreadID ); KERNEL_TRACE_1( STR_ENTRYPOINT_1, (K_USHORT)pfEntryPoint_ ); // Initialize the thread parameters to their initial values. pstThread_->pwStack = pwStack_; pstThread_->pwStackTop = TOP_OF_STACK(pwStack_, usStackSize_); pstThread_->usStackSize = usStackSize_; #if KERNEL_USE_QUANTUM pstThread_->usQuantum = THREAD_QUANTUM_DEFAULT; #endif pstThread_->ucPriority = ucPriority_ ; pstThread_->ucCurPriority = pstThread_->ucPriority; pstThread_->pfEntryPoint = pfEntryPoint_; pstThread_->pvArg = pvArg_; pstThread_->eState = THREAD_STATE_STOP; #if KERNEL_USE_THREADNAME pstThread_->szName = NULL; #endif #if KERNEL_USE_TIMERS Timer_Init( &(pstThread_->stTimer) ); #endif // Call CPU-specific stack initialization ThreadPort_InitStack( pstThread_ ); // Add to the global "stop" list. CS_ENTER(); pstThread_->pstOwner = Scheduler_GetThreadList(pstThread_->ucPriority); pstThread_->pstCurrent = Scheduler_GetStopList(); ThreadList_Add( pstThread_->pstCurrent, pstThread_ ); CS_EXIT(); } //--------------------------------------------------------------------------- void Thread_Start( Thread_t *pstThread_ ) { // Remove the thread from the scheduler's "stopped" list, and add it // to the scheduler's ready list at the proper priority. KERNEL_TRACE_1( STR_THREAD_START_1, (K_USHORT)pstThread_->ucThreadID ); CS_ENTER(); ThreadList_Remove( Scheduler_GetStopList(), pstThread_ ); Scheduler_Add(pstThread_); pstThread_->pstOwner = Scheduler_GetThreadList(pstThread_->ucPriority); pstThread_->pstCurrent = pstThread_->pstOwner; pstThread_->eState = THREAD_STATE_READY; #if KERNEL_USE_QUANTUM if ( Thread_GetCurPriority( pstThread_ ) >= Thread_GetCurPriority( Scheduler_GetCurrentThread() ) ) { // Deal with the thread Quantum Quantum_RemoveThread(); Quantum_AddThread(pstThread_); } #endif if (Kernel_IsStarted()) { if ( Thread_GetCurPriority( pstThread_ ) >= Thread_GetCurPriority( Scheduler_GetCurrentThread() ) ) { Thread_Yield(); } } CS_EXIT(); } //--------------------------------------------------------------------------- void Thread_Stop( Thread_t *pstThread_ ) { K_BOOL bReschedule = 0; CS_ENTER(); // If a thread is attempting to stop itself, ensure we call the scheduler if (pstThread_ == Scheduler_GetCurrentThread()) { bReschedule = true; } // Add this thread to the stop-list (removing it from active scheduling) // Remove the thread from scheduling if (pstThread_->eState == THREAD_STATE_READY) { Scheduler_Remove(pstThread_); } else if (pstThread_->eState == THREAD_STATE_BLOCKED) { ThreadList_Remove( pstThread_->pstCurrent, pstThread_ ); } pstThread_->pstOwner = Scheduler_GetStopList(); pstThread_->pstCurrent = pstThread_->pstOwner; ThreadList_Add( pstThread_->pstOwner, pstThread_ ); pstThread_->eState = THREAD_STATE_STOP; #if KERNEL_USE_TIMERS // Just to be safe - attempt to remove the thread's timer // from the timer-scheduler (does no harm if it isn't // in the timer-list) TimerScheduler_Remove(&pstThread_->stTimer); #endif CS_EXIT(); if (bReschedule) { Thread_Yield(); } } #if KERNEL_USE_DYNAMIC_THREADS //--------------------------------------------------------------------------- void Thread_Exit( Thread_t *pstThread_ ) { K_BOOL bReschedule = 0; KERNEL_TRACE_1( STR_THREAD_EXIT_1, pstThread_->ucThreadID ); CS_ENTER(); // If this thread is the actively-running thread, make sure we run the // scheduler again. if (pstThread_ == Scheduler_GetCurrentThread()) { bReschedule = 1; } // Remove the thread from scheduling if (pstThread_->eState == THREAD_STATE_READY) { Scheduler_Remove(pstThread_); } else if (pstThread_->eState == THREAD_STATE_BLOCKED) { ThreadList_Remove( pstThread_->pstCurrent, pstThread_ ); } pstThread_->pstCurrent = 0; pstThread_->pstOwner = 0; pstThread_->eState = THREAD_STATE_EXIT; // We've removed the thread from scheduling, but interrupts might // trigger checks against this thread's currently priority before // we get around to scheduling new threads. As a result, set the // priority to idle to ensure that we always wind up scheduling // new threads. pstThread_->ucCurPriority = 0; pstThread_->ucPriority = 0; #if KERNEL_USE_TIMERS // Just to be safe - attempt to remove the thread's timer // from the timer-scheduler (does no harm if it isn't // in the timer-list) TimerScheduler_Remove(&pstThread_->stTimer); #endif CS_EXIT(); if (bReschedule) { // Choose a new "next" thread if we must Thread_Yield(); } } #endif #if KERNEL_USE_SLEEP //--------------------------------------------------------------------------- //! This callback is used to wake up a thread once the interval has expired static void ThreadSleepCallback( Thread_t *pstOwner_, void *pvData_ ) { Semaphore_t *pstSemaphore = (Semaphore_t*)(pvData_); // Post the Semaphore_t, which will wake the sleeping thread. Semaphore_Post( pstSemaphore ); } //--------------------------------------------------------------------------- void Thread_Sleep( K_ULONG ulTimeMs_) { Semaphore_t stSemaphore; Timer_t *pstTimer = Thread_GetTimer( g_pstCurrent ); // Create a Semaphore_t that this thread will block on Semaphore_Init( &stSemaphore, 0, 1 ); // Create a one-shot timer that will call a callback that posts the // Semaphore_t, waking our thread. Timer_Init( pstTimer ); Timer_SetIntervalMSeconds( pstTimer, ulTimeMs_ ); Timer_SetCallback( pstTimer, ThreadSleepCallback ); Timer_SetData( pstTimer, (void*)&stSemaphore ); Timer_SetFlags( pstTimer, TIMERLIST_FLAG_ONE_SHOT ); // Add the new timer to the timer scheduler, and block the thread TimerScheduler_Add(pstTimer); Semaphore_Pend( &stSemaphore ); } //--------------------------------------------------------------------------- void Thread_USleep( K_ULONG ulTimeUs_) { Semaphore_t stSemaphore; Timer_t *pstTimer = Thread_GetTimer( g_pstCurrent ); // Create a Semaphore_t that this thread will block on Semaphore_Init( &stSemaphore, 0, 1 ); // Create a one-shot timer that will call a callback that posts the // Semaphore_t, waking our thread. Timer_Init( pstTimer ); Timer_SetIntervalUSeconds( pstTimer, ulTimeUs_ ); Timer_SetCallback( pstTimer, ThreadSleepCallback ); Timer_SetData( pstTimer, (void*)&stSemaphore ); Timer_SetFlags( pstTimer, TIMERLIST_FLAG_ONE_SHOT ); // Add the new timer to the timer scheduler, and block the thread TimerScheduler_Add(pstTimer); Semaphore_Pend( &stSemaphore ); } #endif // KERNEL_USE_SLEEP //--------------------------------------------------------------------------- K_USHORT Thread_GetStackSlack( Thread_t *pstThread_ ) { K_USHORT usCount = 0; CS_ENTER(); //!! ToDo: Take into account stacks that grow up for (usCount = 0; usCount < pstThread_->usStackSize; usCount++) { if (pstThread_->pwStack[usCount] != 0xFF) { break; } } CS_EXIT(); return usCount; } //--------------------------------------------------------------------------- void Thread_Yield( void ) { CS_ENTER(); // Run the scheduler if (Scheduler_IsEnabled()) { Scheduler_Schedule(); // Only switch contexts if the new task is different than the old task if (Scheduler_GetCurrentThread() != Scheduler_GetNextThread()) { #if KERNEL_USE_QUANTUM // new thread scheduled. Stop current quantum timer (if it exists), // and restart it for the new thread (if required). Quantum_RemoveThread(); Quantum_AddThread((Thread_t*)g_pstNext); #endif Thread_ContextSwitchSWI(); } } else { Scheduler_QueueScheduler(); } CS_EXIT(); } //--------------------------------------------------------------------------- void Thread_SetPriorityBase( Thread_t *pstThread_, K_UCHAR ucPriority_ ) { ThreadList_Remove( Thread_GetCurrent( pstThread_ ), pstThread_ ); Thread_SetCurrent( pstThread_, Scheduler_GetThreadList(pstThread_->ucPriority) ); ThreadList_Add( Thread_GetCurrent( pstThread_ ), pstThread_ ); } //--------------------------------------------------------------------------- void Thread_SetPriority( Thread_t *pstThread_, K_UCHAR ucPriority_ ) { K_BOOL bSchedule = 0; CS_ENTER(); // If this is the currently running thread, it's a good idea to reschedule // Or, if the new priority is a higher priority than the current thread's. if ((g_pstCurrent == pstThread_) || (ucPriority_ > Thread_GetPriority( g_pstCurrent )) ) { bSchedule = 1; } Scheduler_Remove(pstThread_); CS_EXIT(); pstThread_->ucCurPriority = ucPriority_; pstThread_->ucPriority = ucPriority_; CS_ENTER(); Scheduler_Add(pstThread_); CS_EXIT(); if (bSchedule) { if (Scheduler_IsEnabled()) { CS_ENTER(); Scheduler_Schedule(); #if KERNEL_USE_QUANTUM // new thread scheduled. Stop current quantum timer (if it exists), // and restart it for the new thread (if required). Quantum_RemoveThread(); Quantum_AddThread((Thread_t*)g_pstNext); #endif CS_EXIT(); Thread_ContextSwitchSWI(); } else { Scheduler_QueueScheduler(); } } } //--------------------------------------------------------------------------- void Thread_InheritPriority( Thread_t *pstThread_, K_UCHAR ucPriority_ ) { Thread_SetOwner(pstThread_, Scheduler_GetThreadList(ucPriority_)); pstThread_->ucCurPriority = ucPriority_; } //--------------------------------------------------------------------------- void Thread_ContextSwitchSWI( void ) { // Call the context switch interrupt if the scheduler is enabled. if (Scheduler_IsEnabled() == 1) { KERNEL_TRACE_1( STR_CONTEXT_SWITCH_1, (K_USHORT)Thread_GetID( (Thread_t*)g_pstNext ) ); KernelSWI_Trigger(); } } #if KERNEL_USE_IDLE_FUNC //--------------------------------------------------------------------------- void Thread_InitIdle( Thread_t *pstThread_ ) { LinkListNode_Clear( (LinkListNode_t*)pstThread_ ); pstThread_->ucPriority = 0; pstThread_->ucCurPriority = 0; pstThread_->pfEntryPoint = 0; pstThread_->pvArg = 0; pstThread_->ucThreadID = 255; pstThread_->eState = THREAD_STATE_READY; #if KERNEL_USE_THREADNAME pstThread_->szName = "IDLE"; #endif } #endif
moslevin/Mark3C
drivers/cpu/avr/atmega328p/gcc/uart/public/drvUART.h
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file ATMegaUART.h \brief Atmega328p serial port driver */ #ifndef __ATMEGAUART_H_ #define __ATMEGAUART_H_ #include "kerneltypes.h" #include "driver.h" //--------------------------------------------------------------------------- // UART defines - user-configurable for different targets //--------------------------------------------------------------------------- #define UART_SRA (UCSR0A) #define UART_SRB (UCSR0B) #define UART_SRC (UCSR0C) #define UART_BAUDH (UBRR0H) #define UART_BAUDL (UBRR0L) #define UART_RXEN (RXEN0) #define UART_TXEN (TXEN0) #define UART_TXCIE (TXCIE0) #define UART_RXCIE (RXCIE0) #define UART_UDR (UDR0) #define UART_UDRE (UDRE0) #define UART_RXC (RXC0) #define UART_DEFAULT_BAUD ((K_ULONG)57600) #define UART_RX_ISR (USART_RX_vect) #define UART_TX_ISR (USART_TX_vect) //--------------------------------------------------------------------------- typedef enum { CMD_SET_BAUDRATE = 0x80, CMD_SET_BUFFERS, CMD_SET_RX_ESCAPE, CMD_SET_RX_CALLBACK, CMD_SET_RX_ECHO, CMD_SET_RX_ENABLE, CMD_SET_RX_DISABLE } CMD_UART; //--------------------------------------------------------------------------- struct ATMegaUART_; //--------------------------------------------------------------------------- typedef void (*UART_Rx_Callback_t)( struct ATMegaUART_ *pstUART ); //--------------------------------------------------------------------------- /*! Implements a UART driver on the ATMega328p */ struct ATMegaUART_ { //Inherit from Driver_t -- must be first. Driver_t stDriver; K_UCHAR ucTxSize; //!< Size of the TX Buffer K_UCHAR ucTxHead; //!< Head index K_UCHAR ucTxTail; //!< Tail index K_UCHAR ucRxSize; //!< Size of the RX Buffer K_UCHAR ucRxHead; //!< Head index K_UCHAR ucRxTail; //!< Tail index K_UCHAR bRxOverflow; //!< Receive buffer overflow K_UCHAR bEcho; //!< Whether or not to echo RX characters to TX K_UCHAR *pucRxBuffer; //!< Receive buffer pointer K_UCHAR *pucTxBuffer; //!< Transmit buffer pointer K_ULONG ulBaudRate; //!< Baud rate K_UCHAR ucRxEscape; //!< Escape character UART_Rx_Callback_t pfCallback; //!< Callback function on matched escape character }; typedef struct ATMegaUART_ ATMegaUART_t; //--------------------------------------------------------------------------- extern ATMegaUART_t stUART; //--------------------------------------------------------------------------- void ATMegaUART_Init( ATMegaUART_t *pstUART_ ); //--------------------------------------------------------------------------- K_UCHAR ATMegaUART_Open( ATMegaUART_t *pstUART_ ); //--------------------------------------------------------------------------- K_UCHAR ATMegaUART_Close( ATMegaUART_t *pstUART_ ); //--------------------------------------------------------------------------- K_USHORT ATMegaUART_Read( ATMegaUART_t *pstUART_, K_USHORT usBytes_, K_UCHAR *pucData_ ); //--------------------------------------------------------------------------- K_USHORT ATMegaUART_Write( ATMegaUART_t *pstUART_, K_USHORT usBytes_, K_UCHAR *pucData_ ); //--------------------------------------------------------------------------- K_USHORT ATMegaUART_Control( ATMegaUART_t *pstUART_, K_USHORT usEvent_, K_USHORT usSizeIn_, void *pvIn_, K_USHORT usSizeOut_, void *pvOut_ ); //--------------------------------------------------------------------------- /*! \fn K_UCHAR *GetRxBuffer(void) Return a pointer to the receive buffer for this UART. \return pointer to the driver's RX buffer */ K_UCHAR *ATMegaUART_GetRxBuffer( ATMegaUART_t *pstUART_ ); //--------------------------------------------------------------------------- /*! \fn K_UCHAR *GetTxBuffer(void) Return a pointer to the transmit buffer for this UART. \return pointer to the driver's TX buffer */ K_UCHAR *ATMegaUART_GetTxBuffer( ATMegaUART_t *pstUART_ ); //--------------------------------------------------------------------------- #endif
moslevin/Mark3C
kernel/scheduler.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file scheduler.cpp \brief Strict-Priority + Round-Robin thread scheduler implementation */ #include "kerneltypes.h" #include "ll.h" #include "scheduler.h" #include "thread.h" #include "threadport.h" #include "kernel.h" #include "kerneldebug.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ SCHEDULER_C //!< File ID used in kernel trace calls //--------------------------------------------------------------------------- volatile Thread_t *g_pstNext; //!< Pointer to the currently-chosen next-running thread Thread_t *g_pstCurrent; //!< Pointer to the currently-running thread K_BOOL bEnabled; //! Scheduler's state - enabled or disabled //--------------------------------------------------------------------------- static ThreadList_t stStopList; //! ThreadList_t for all stopped threads static ThreadList_t aclPriorities[NUM_PRIORITIES]; //! ThreadLists for all threads at all priorities static K_BOOL bQueuedSchedule; //! Variable representing whether or not there's a queued scheduler operation static K_UCHAR ucPriFlag; //! Bitmap flag for each //--------------------------------------------------------------------------- /*! * This implements a 4-bit "Count-leading-zeros" operation using a RAM-based * lookup table. It is used to efficiently perform a CLZ operation under the * assumption that a native CLZ instruction is unavailable. This table is * further optimized to provide a 0xFF result in the event that the index value * is itself zero, allowing us to quickly identify whether or not subsequent * 4-bit LUT operations are required to complete the scheduling process. */ static const K_UCHAR aucCLZ[16] ={255,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3}; //--------------------------------------------------------------------------- void Scheduler_Init() { ucPriFlag = 0; uint8_t i; for (i = 0; i < NUM_PRIORITIES; i++) { ThreadList_Init( &aclPriorities[i] ); ThreadList_SetPriority( &aclPriorities[i], i ); ThreadList_SetFlagPointer( &aclPriorities[i], &ucPriFlag ); } bQueuedSchedule = false; } //--------------------------------------------------------------------------- void Scheduler_Schedule() { K_UCHAR ucPri = 0; // Figure out what priority level has ready tasks (8 priorities max) // To do this, we apply our current active-thread bitmap (ucPriFlag) // and perform a CLZ on the upper four bits. If no tasks are found // in the higher priority bits, search the lower priority bits. This // also assumes that we always have the idle thread ready-to-run in // priority level zero. ucPri = aucCLZ[ucPriFlag >> 4 ]; if (ucPri == 0xFF) { ucPri = aucCLZ[ucPriFlag & 0x0F]; } else { ucPri += 4; } #if KERNEL_USE_IDLE_FUNC if (ucPri == 0xFF) { // There aren't any active threads at all - set g_pstNext to IDLE g_pstNext = Kernel_GetIdleThread(); } else #endif { // Get the thread node at this priority. g_pstNext = (Thread_t*)( LinkList_GetHead( (LinkList_t*)&aclPriorities[ucPri] ) ); } KERNEL_TRACE_1( STR_SCHEDULE_1, (K_USHORT)Thread_GetID( (Thread_t*)g_pstNext) ); } //--------------------------------------------------------------------------- void Scheduler_Add(Thread_t *pstThread_) { ThreadList_Add( &aclPriorities[ Thread_GetPriority(pstThread_) ], pstThread_ ); } //--------------------------------------------------------------------------- void Scheduler_Remove(Thread_t *pstThread_) { ThreadList_Remove( &aclPriorities[ Thread_GetPriority(pstThread_) ], pstThread_ ); } //--------------------------------------------------------------------------- K_BOOL Scheduler_SetScheduler(K_BOOL bEnable_) { K_BOOL bRet ; CS_ENTER(); bRet = bEnabled; bEnabled = bEnable_; // If there was a queued scheduler evevent, dequeue and trigger an // immediate Yield if (bEnabled && bQueuedSchedule) { bQueuedSchedule = false; Thread_Yield(); } CS_EXIT(); return bRet; } //--------------------------------------------------------------------------- void Scheduler_QueueScheduler() { bQueuedSchedule = true; } //--------------------------------------------------------------------------- ThreadList_t *Scheduler_GetThreadList( K_UCHAR ucPriority_ ) { return &aclPriorities[ucPriority_]; } //--------------------------------------------------------------------------- ThreadList_t *Scheduler_GetStopList() { return &stStopList; }
moslevin/Mark3C
kernel/public/timerlist.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file timerlist.h \brief Timer_t list declarations These classes implements a linked list of timer objects attached to the global kernel timer scheduler. */ #ifndef __TIMERLIST_H__ #define __TIMERLIST_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "timer.h" #if KERNEL_USE_TIMERS #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- /*! \fn void TimerList_Init() Initialize the TimerList object. Must be called before using the object. */ void TimerList_Init( void ); //--------------------------------------------------------------------------- /*! \fn void TimerList_Add(Timer_t *pstListNode_) Add a timer to the TimerList. \param pstListNode_ Pointer to the Timer_t to Add */ void TimerList_Add( Timer_t *pstListNode_ ); //--------------------------------------------------------------------------- /*! \fn void TimerList_Remove(Timer_t *pstListNode_) Remove a timer from the TimerList, cancelling its expiry. \param pstListNode_ Pointer to the Timer_t to remove */ void TimerList_Remove( Timer_t *pstListNode_ ); //--------------------------------------------------------------------------- /*! \fn void TimerList_Process() Process all timers in the timerlist as a result of the timer expiring. This will select a new timer epoch based on the next timer to expire. */ void TimerList_Process( void ); #ifdef __cplusplus } #endif #endif // KERNEL_USE_TIMERS #endif
moslevin/Mark3C
drivers/cpu/avr/atmega328p/gcc/uart/drvUART.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file drvUART.cpp \brief Atmega328p serial port driver */ #include "kerneltypes.h" #include "drvUART.h" #include "driver.h" #include "thread.h" #include "threadport.h" #include "kerneltimer.h" #include <avr/io.h> #include <avr/interrupt.h> //--------------------------------------------------------------------------- static ATMegaUART_t *pstActive; // Pointer to the active object //--------------------------------------------------------------------------- static DriverVTable_t stUART_VT = { (OpenFunc_t)ATMegaUART_Open, (CloseFunc_t)ATMegaUART_Close, (ReadFunc_t)ATMegaUART_Read, (WriteFunc_t)ATMegaUART_Write, (ControlFunc_t)ATMegaUART_Control }; //--------------------------------------------------------------------------- ATMegaUART_t stUART = { { .pstVTable = &stUART_VT, .szName = "/dev/tty" } }; //--------------------------------------------------------------------------- static void ATMegaUART_StartTx( ATMegaUART_t *pstUART_ ); static void ATMegaUART_TxISR( ATMegaUART_t *pstUART_ ); //--------------------------------------------------------------------------- static void ATMegaUART_SetBaud( ATMegaUART_t *pstUART_ ) { K_USHORT usBaudTemp; K_USHORT usPortTemp; // Calculate the baud rate from the value in the driver. usBaudTemp = (K_USHORT)(((SYSTEM_FREQ/16)/pstUART_->ulBaudRate) - 1); // Save the current port config registers usPortTemp = UART_SRB; // Clear the registers (disable rx/tx/interrupts) UART_SRB = 0; UART_SRA = 0; // Set the baud rate high/low values. UART_BAUDH = (K_UCHAR)(usBaudTemp >> 8); UART_BAUDL = (K_UCHAR)(usBaudTemp & 0x00FF); // Restore the Rx/Tx flags to their previous state UART_SRB = usPortTemp; } //--------------------------------------------------------------------------- void ATMegaUART_Init( ATMegaUART_t *pstUART_ ) { // Set up the FIFOs pstUART_->ucTxHead = 0; pstUART_->ucTxTail = 0; pstUART_->ucRxHead = 0; pstUART_->ucRxTail = 0; pstUART_->bEcho = 0; pstUART_->ucRxEscape = '\n'; pstUART_->pfCallback = NULL; pstUART_->bRxOverflow = 0; pstUART_->ulBaudRate = UART_DEFAULT_BAUD; // Clear flags UART_SRA = 0; UART_SRB = 0; ATMegaUART_SetBaud( pstUART_ ); // Set frame format: 8 N 1 UART_SRC = 0x06; } //--------------------------------------------------------------------------- K_UCHAR ATMegaUART_Open( ATMegaUART_t *pstUART_ ) { // Enable Rx/Tx + Interrupts UART_SRB |= (1 << UART_RXEN) | ( 1 << UART_TXEN); UART_SRB |= (1 << UART_RXCIE) | (1 << UART_TXCIE); pstActive = pstUART_; return 0; } //--------------------------------------------------------------------------- K_UCHAR ATMegaUART_Close( ATMegaUART_t *pstUART_ ) { // Disable Rx/Tx + Interrupts UART_SRB &= ~((1 << UART_RXEN) | ( 1 << UART_TXEN)); UART_SRB &= ~((1 << UART_TXCIE) | (1 << UART_RXCIE)); return 0; } //--------------------------------------------------------------------------- K_USHORT ATMegaUART_Control( ATMegaUART_t *pstUART_, K_USHORT usCmdId_, K_USHORT usSizeIn_, void *pvIn_, K_USHORT usSizeOut_, void *pvOut_ ) { switch ((CMD_UART)usCmdId_) { case CMD_SET_BAUDRATE: { K_ULONG ulBaudRate = *((K_ULONG*)pvIn_); pstUART_->ulBaudRate = ulBaudRate; ATMegaUART_SetBaud( pstUART_ ); } break; case CMD_SET_BUFFERS: { pstUART_->pucRxBuffer = (K_UCHAR*)pvIn_; pstUART_->pucTxBuffer = (K_UCHAR*)pvOut_; pstUART_->ucRxSize = usSizeIn_; pstUART_->ucTxSize = usSizeOut_; } break; case CMD_SET_RX_ESCAPE: { pstUART_->ucRxEscape = *((K_UCHAR*)pvIn_); } break; case CMD_SET_RX_CALLBACK: { pstUART_->pfCallback = (UART_Rx_Callback_t)pvIn_; } break; case CMD_SET_RX_ECHO: { pstUART_->bEcho = *((K_UCHAR*)pvIn_); } break; case CMD_SET_RX_ENABLE: { UART_SRB |= (1 << UART_RXEN); } break; case CMD_SET_RX_DISABLE: { UART_SRB &= ~(1 << UART_RXEN); } break; default: break; } return 0; } //--------------------------------------------------------------------------- K_USHORT ATMegaUART_Read( ATMegaUART_t *pstUART_, K_USHORT usSizeIn_, K_UCHAR *pvData_ ) { // Read a string of characters of length N. Return the number of bytes // actually read. If less than the 1 length, this indicates that // the buffer is full and that the app needs to wait. K_USHORT i = 0; K_USHORT usRead = 0; K_BOOL bExit = 0; K_UCHAR *pucData = (K_UCHAR*)pvData_; for (i = 0; i < usSizeIn_; i++) { // If Tail != Head, there's data in the buffer. CS_ENTER(); if (pstUART_->ucRxTail != pstUART_->ucRxHead) { // We have room to add the byte, so add it. pucData[i] = pstUART_->pucRxBuffer[pstUART_->ucRxTail]; // Update the buffer head pointer. pstUART_->ucRxTail++; if (pstUART_->ucRxTail >= pstUART_->ucRxSize) { pstUART_->ucRxTail = 0; } usRead++; } else { // Can't do anything else - the buffer is empty bExit = 1; } CS_EXIT(); // If we have to bail because the buffer is empty, do it now. if (bExit == 1) { break; } } return usRead; } //--------------------------------------------------------------------------- K_USHORT ATMegaUART_Write( ATMegaUART_t *pstUART_, K_USHORT usSizeOut_, K_UCHAR *pvData_) { // Write a string of characters of length N. Return the number of bytes // actually written. If less than the 1 length, this indicates that // the buffer is full and that the app needs to wait. K_USHORT i = 0; K_USHORT usWritten = 0; K_UCHAR ucNext; K_BOOL bActivate = 0; K_BOOL bExit = 0; K_UCHAR *pucData = (K_UCHAR*)pvData_; // If the head = tail, we need to start sending data out the data ourselves. if (pstUART_->ucTxHead == pstUART_->ucTxTail) { bActivate = 1; } for (i = 0; i < usSizeOut_; i++) { CS_ENTER(); // Check that head != tail (we have room) ucNext = (pstUART_->ucTxHead + 1); if (ucNext >= pstUART_->ucTxSize) { ucNext = 0; } if (ucNext != pstUART_->ucTxTail) { // We have room to add the byte, so add it. pstUART_->pucTxBuffer[pstUART_->ucTxHead] = pucData[i]; // Update the buffer head pointer. pstUART_->ucTxHead = ucNext; usWritten++; } else { // Can't do anything - buffer is full bExit = 1; } CS_EXIT(); // bail if the buffer is full if (bExit == 1) { break; } } // Activate the transmission if we're currently idle if (bActivate == 1) { // We know we're idle if we get here. CS_ENTER(); if (UART_SRA & (1 << UDRE0)) { ATMegaUART_StartTx(pstUART_); } CS_EXIT(); } return usWritten; } //--------------------------------------------------------------------------- void ATMegaUART_StartTx( ATMegaUART_t *pstUART_ ) { // Send the tail byte out. K_UCHAR ucNext; CS_ENTER(); // Send the byte at the tail index UART_UDR = pstUART_->pucTxBuffer[pstUART_->ucTxTail]; // Update the tail index ucNext = (pstUART_->ucTxTail + 1); if (ucNext >= pstUART_->ucTxSize) { ucNext = 0; } pstUART_->ucTxTail = ucNext; CS_EXIT(); } //--------------------------------------------------------------------------- void ATMegaUART_RxISR( ATMegaUART_t *pstUART_ ) { K_UCHAR ucTemp; K_UCHAR ucNext; // Read the byte from the data buffer register ucTemp = UART_UDR; // Check that head != tail (we have room) ucNext = (pstUART_->ucRxHead + 1); if (ucNext >= pstUART_->ucRxSize) { ucNext = 0; } // Always add the byte to the buffer (but flag an error if it's full...) pstUART_->pucRxBuffer[pstUART_->ucRxHead] = ucTemp; // Update the buffer head pointer. pstUART_->ucRxHead = ucNext; // If the buffer's full, discard the oldest byte in the buffer and flag an error if (ucNext == pstUART_->ucRxTail) { // Update the buffer tail pointer pstUART_->ucRxTail = (pstUART_->ucRxTail + 1); if (pstUART_->ucRxTail >= pstUART_->ucRxSize) { pstUART_->ucRxTail = 0; } // Flag an error - the buffer is full pstUART_->bRxOverflow = 1; } // If local-echo is enabled, TX the K_CHAR if (pstUART_->bEcho) { ATMegaUART_Write(pstUART_, 1, &ucTemp); } // If we've hit the RX callback character, run the callback // This is used for calling line-end functions, etc.. if (ucTemp == pstUART_->ucRxEscape) { if (pstUART_->pfCallback) { pstUART_->pfCallback( pstUART_ ); } } } //--------------------------------------------------------------------------- ISR(UART_RX_ISR) { ATMegaUART_RxISR( pstActive ); } //--------------------------------------------------------------------------- void ATMegaUART_TxISR( ATMegaUART_t *pstUART_ ) { // If the head != tail, there's something to send. if (pstUART_->ucTxHead != pstUART_->ucTxTail) { ATMegaUART_StartTx( pstUART_ ); } } //--------------------------------------------------------------------------- ISR(UART_TX_ISR) { ATMegaUART_TxISR( pstActive ); }
moslevin/Mark3C
kernel/public/message.h
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file message.h \brief Inter-thread communication via message-passing Embedded systems guru <NAME> once said that without a robust form of interprocess communications (IPC), an RTOS is just a toy. Mark3 implements a form of IPC to provide safe and flexible messaging between threads. Using kernel-managed IPC offers significant benefits over other forms of data sharing (i.e. Global variables) in that it avoids synchronization issues and race conditions common to the practice. Using IPC also enforces a more disciplined coding style that keeps threads decoupled from one another and minimizes global data, preventing careless and hard-to-debug errors. \section MBCreate Using Messages, Queues, and the Global Message_t Pool \code // Declare a message queue shared between two threads MessageQueue_t my_queue; int main() { ... // Initialize the message queue my_queue.init(); ... } void Thread1() { // Example TX thread - sends a message every 10ms while(1) { // Grab a message from the global message pool Message_t *tx_message = GlobalMessagePool_Pop(); // Set the message data/parameters tx_message->SetCode( 1234 ); tx_message->SetData( NULL ); // Send the message on the queue. my_queue.Send( tx_message ); Thread_t_Sleep(10); } } void Thread2() { while() { // Blocking receive - wait until we have messages to process Message_t *rx_message = my_queue.Recv(); // Do something with the message data... // Return back into the pool when done GlobalMessagePool_Push(rx_message); } } \endcode */ #ifndef __MESSAGE_H__ #define __MESSAGE_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #include "ksemaphore.h" #if KERNEL_USE_MESSAGE #if KERNEL_USE_TIMEOUTS #include "timerlist.h" #endif #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- /*! Class to provide message-based IPC services in the kernel. */ typedef struct { // Inherit from LinkListNode_t -- must be first. LinkListNode_t stNode; //! Pointer to the message data void *pvData; //! Message_t code, providing context for the message K_USHORT usCode; } Message_t; //--------------------------------------------------------------------------- /*! \fn void Init(); Initialize the data and code in the message. */ void Message_Init( Message_t* pstMsg_ ); //--------------------------------------------------------------------------- /*! \fn void SetData( void *pvData_ ) Set the data pointer for the message before transmission. \param pvData_ Pointer to the data object to send in the message */ void Message_SetData( Message_t* pstMsg_, void *pvData_ ); //--------------------------------------------------------------------------- /*! \fn void *GetData() Get the data pointer stored in the message upon receipt \return Pointer to the data set in the message object */ void *Message_GetData( Message_t* pstMsg_ ); //--------------------------------------------------------------------------- /*! \fn SetCode( K_USHORT usCode_ ) Set the code in the message before transmission \param usCode_ Data code to set in the object */ void Message_SetCode( Message_t* pstMsg_, K_USHORT usCode_ ); //--------------------------------------------------------------------------- /*! \fn K_USHORT GetCode() Return the code set in the message upon receipt \return User code set in the object */ K_USHORT Message_GetCode( Message_t* pstMsg_ ); //--------------------------------------------------------------------------- /*! \fn void Init() Initialize the message queue prior to use */ void GlobalMessagePool_Init( void ); //--------------------------------------------------------------------------- /*! \fn void Push( Message_t *pstMessage_ ) Return a previously-claimed message object back to the global queue. Used once the message has been processed by a receiver. \param pstMessage_ Pointer to the Message_t object to return back to the global queue */ void GlobalMessagePool_Push( Message_t *pstMessage_ ); //--------------------------------------------------------------------------- /*! \fn Message_t *Pop() Pop a message from the global queue, returning it to the user to be populated before sending by a transmitter. \return Pointer to a Message_t object */ Message_t *GlobalMessagePool_Pop( void ); //--------------------------------------------------------------------------- /*! List of messages, used as the channel for sending and receiving messages between threads. */ typedef struct { //! Counting Semaphore_t used to manage thread blocking Semaphore_t stSemaphore; //! List object used to store messages DoubleLinkList_t stLinkList; } MessageQueue_t; //--------------------------------------------------------------------------- /*! \fn void Init() Initialize the message queue prior to use. */ void MessageQueue_Init( MessageQueue_t *pstMsgQ_ ); //--------------------------------------------------------------------------- /*! \fn Message_t *Receive() Receive a message from the message queue. If the message queue is empty, the thread will block until a message is available. \return Pointer to a message object at the head of the queue */ Message_t *MessageQueue_Receive( MessageQueue_t *pstMsgQ_ ); #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- /*! \fn Message_t *Receive( K_ULONG ulWaitTimeMS_ ) Receive a message from the message queue. If the message queue is empty, the thread will block until a message is available for the duration specified. If no message arrives within that duration, the call will return with NULL. \param ulWaitTimeMS_ The amount of time in ms to wait for a message before timing out and unblocking the waiting thread. \return Pointer to a message object at the head of the queue or NULL on timeout. */ Message_t *MessageQueue_TimedReceive( MessageQueue_t *pstMsgQ_, K_ULONG ulTimeWaitMS_ ); #endif //--------------------------------------------------------------------------- /*! \fn void Send( Message_t *pstSrc_ ) Send a message object into this message queue. Will un-block the first waiting thread blocked on this queue if that occurs. \param pstSrc_ Pointer to the message object to add to the queue */ void MessageQueue_Send( MessageQueue_t *pstMsgQ_, Message_t *pstSrc_ ); //--------------------------------------------------------------------------- /*! \fn K_USHORT MessageQueue_GetCount() Return the number of messages pending in the "receive" queue. \return Count of pending messages in the queue. */ K_USHORT MessageQueue_GetCount( MessageQueue_t *pstMsgQ_ ); #ifdef __cplusplus } #endif #endif //KERNEL_USE_MESSAGE #endif
moslevin/Mark3C
kernel/cpu/cm0/stm32f0/gcc/kerneltimer.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kerneltimer.cpp \brief Kernel Timer Implementation for ARM Cortex-M0 */ #include "kerneltypes.h" #include "kerneltimer.h" #include "threadport.h" //--------------------------------------------------------------------------- void KernelTimer_Config(void) { } //--------------------------------------------------------------------------- void KernelTimer_Start(void) { SysTick_Config(SYSTEM_FREQ / 1000); // 1KHz fixed clock... NVIC_EnableIRQ(SysTick_IRQn); } //--------------------------------------------------------------------------- void KernelTimer_Stop(void) { SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; } //--------------------------------------------------------------------------- K_USHORT KernelTimer_Read(void) { // Not implemented in this port return 0; } //--------------------------------------------------------------------------- K_ULONG KernelTimer_SubtractExpiry(K_ULONG ulInterval_) { return 0; } //--------------------------------------------------------------------------- K_ULONG KernelTimer_TimeToExpiry(void) { return 0; } //--------------------------------------------------------------------------- K_ULONG KernelTimer_GetOvertime(void) { return 0; } //--------------------------------------------------------------------------- K_ULONG KernelTimer_SetExpiry(K_ULONG ulInterval_) { return 0; } //--------------------------------------------------------------------------- void KernelTimer_ClearExpiry(void) { } //------------------------------------------------------------------------- K_UCHAR KernelTimer_DI(void) { return 0; } //--------------------------------------------------------------------------- void KernelTimer_EI(void) { KernelTimer_RI(0); } //--------------------------------------------------------------------------- void KernelTimer_RI(K_BOOL bEnable_) { } //---------------------------------------------------------------------------
moslevin/Mark3C
examples/avr/lab1_kernel_setup/main.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ #include "mark3.h" #include "drvUART.h" /*=========================================================================== Lab Example 1: Initializing the Mark3 RTOS kernel with two threads. The following example code presents a working example of how to initialize the Mark3 RTOS kernel, configure two application threads, and execute the configured tasks. This example also uses the flAVR kernel-aware module to print out messages when run through the flAVR AVR Simulator. This is a turnkey-ready example of how to use the Mark3 RTOS at its simplest level, and should be well understood before moving on to other examples. Lessons covered in this example include: - Usage of the Kernel object - configuring and starting the kernel - Usage of the Thread_t object - initializing and starting static threads. - Demonstrate the relationship between Thread_t objects, stacks, and entry functions. - Usage of Thread_t_Sleep() to block execution of a thread for a period of time - When using an idle thread, the idle thread MUST not block. Exercise: - Add another application thread that prints a message, flashes an LED, etc. using the code below as an example. Takeaway: At the end of this example, the reader should be able to use the Mark3 Kernel and Thread_t APIs to initialize and start the kernel with any number of static threads. ===========================================================================*/ //--------------------------------------------------------------------------- // This block declares the thread data for the main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stAppThread; static K_WORD awAppStack[APP_STACK_SIZE]; static void AppMain(void *unused_); //--------------------------------------------------------------------------- // This block declares the thread data for the idle thread. It defines a // thread object, stack (in word-array form), and the entry-point function // used by the idle thread. #define IDLE_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stIdleThread; static K_WORD awIdleStack[IDLE_STACK_SIZE]; static void IdleMain(void *unused_); K_UCHAR aucRX[32]; K_UCHAR aucTX[32]; //--------------------------------------------------------------------------- int main(void) { // Before any Mark3 RTOS APIs can be called, the user must call Kernel_Init(). // Note that if you have any hardware-specific init code, it can be called // before Kernel_Init, so long as it does not enable interrupts, or // rely on hardware peripherals (timer, software interrupt, etc.) used by the // kernel. Kernel_Init(); // Once the kernel initialization has been complete, the user can add their // application thread(s) and idle thread. Threads added before the kerel // is started are refered to as the "static threads" in the system, as they // are the default working-set of threads that make up the application on // kernel startup. // Initialize the application thread to use a specified word-array as its stack. // The thread will run at priority level "1", and start execution the // "AppMain" function when it's started. Thread_Init( &stAppThread, awAppStack, APP_STACK_SIZE, 1, AppMain, 0); // Initialize the idle thread to use a specific word-array as its stack. // The thread will run at priority level "0", which is reserved for the idle // priority thread. IdleMain will be run when the thread is started. Thread_Init( &stIdleThread, awIdleStack, IDLE_STACK_SIZE, 0, IdleMain, 0); // Once the static threads have been added, the user must then ensure that the // threads are ready to execute. By default, creating a thread is created // in a STOPPED state. All threads must manually be started using the // Start() API before they will be scheduled by the system. Here, we are // starting the application and idle threads before starting the kernel - and // that's OK. When the kernel is started, it will choose which thread to run // first from the pool of ready threads. Thread_Start( &stAppThread ); Thread_Start( &stIdleThread ); // All threads have been initialized and made ready. The kernel will now // select the first thread to run, enable the hardware required to run the // kernel (Timers, software interrupts, etc.), and then do whatever is // necessary to maneuver control of thread execution to the kernel. At this // point, execution will transition to the highest-priority ready thread. // This function will not return. ATMegaUART_Init( &stUART ); Kernel_Start(); // As Kernel_Start() results in the operating system being executed, control // will not be relinquished back to main(). The "return 0" is simply to // avoid warnings. return 0; } //--------------------------------------------------------------------------- void AppMain(void *unused_) { // This function is run from within the application thread. Here, we // simply print a friendly greeting and allow the thread to sleep for a // while before repeating the message. Note that while the thread is // sleeping, CPU execution will transition to the Idle thread. Driver_Control( (Driver_t*)&stUART, CMD_SET_BUFFERS, 32, aucRX, 32, aucTX); K_ULONG ulBaud = 57600; Driver_Control( (Driver_t*)&stUART, CMD_SET_BAUDRATE, 0, (void*)&ulBaud, 0, 0 ); Driver_Open( (Driver_t*)&stUART ); while(1) { Driver_Write( (Driver_t*)&stUART, 12, (K_UCHAR*)"Hello World\n" ); Thread_Sleep(1000); } } //--------------------------------------------------------------------------- void IdleMain(void *unused_) { while(1) { // Low priority task + power management routines go here. // The actions taken in this context must *not* cause the thread // to block, as the kernel requires that at least one thread is // schedulable at all times when not using an idle thread. // Note that if you have no special power-management code or idle // tasks, an empty while(1){} loop is sufficient to guarantee that // condition. } }
moslevin/Mark3C
tests/unit/ut_thread/ut_thread.c
<reponame>moslevin/Mark3C /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ //--------------------------------------------------------------------------- #include "kerneltypes.h" #include "kernel.h" #include "../ut_platform.h" #include "thread.h" #include "ksemaphore.h" #include "kernelprofile.h" #include "profile.h" #include "kerneltimer.h" #include "driver.h" #include "memutil.h" //=========================================================================== // Local Defines //=========================================================================== #define TEST_STACK_SIZE (224) static K_WORD aucStack1[TEST_STACK_SIZE]; static K_WORD aucStack2[TEST_STACK_SIZE]; static K_WORD aucStack3[TEST_STACK_SIZE]; static Thread_t stThread1; static Thread_t stThread2; static Thread_t stThread3; static Semaphore_t stSem1; static Semaphore_t stSem2; static volatile K_ULONG ulRR1; static volatile K_ULONG ulRR2; static volatile K_ULONG ulRR3; //=========================================================================== static void Thread_tEntryPoint1(void *unused_) { while(1) { Semaphore_Pend( &stSem2 ); Semaphore_Post( &stSem1 ); } unused_ = unused_; } //=========================================================================== // Define Test Cases Here //=========================================================================== TEST(ut_thread_create) { // Test point - Create a Thread_t, verify that the Thread_t actually starts. Semaphore_Init( &stSem1, 0, 1); Semaphore_Init( &stSem2, 0, 1); // Initialize our Thread_t Thread_Init( &stThread1, aucStack1, TEST_STACK_SIZE, 7, Thread_tEntryPoint1, NULL); // Start the Thread_t (Thread_ts are created in the stopped state) Thread_Start( &stThread1 ); // Poke the Thread_t using a Semaphore_t, verify it's working Semaphore_Post( &stSem2 ); Semaphore_TimedPend( &stSem1, 10 ); // Ensure that the Semaphore_t was posted before we got to the 10ms timeout EXPECT_FALSE( Thread_GetExpired( Scheduler_GetCurrentThread() ) ); } TEST_END //=========================================================================== TEST(ut_thread_stop) { // Test point - stop and restart a Thread_t Thread_Stop( &stThread1 ); Thread_Sleep(10); Thread_Start( &stThread1 ); // Poke the Thread_t using a Semaphore_t, verify it's still responding Semaphore_Post( &stSem2 ); Semaphore_TimedPend( &stSem1, 10 ); EXPECT_FALSE( Thread_GetExpired( Scheduler_GetCurrentThread() ) ); } TEST_END //=========================================================================== TEST(ut_thread_exit) { // Test point - force a Thread_t exit; ensure it doesn't respond once // it's un-scheduled. Thread_Exit( &stThread1 ); Semaphore_Post( &stSem2 ); Semaphore_TimedPend( &stSem1, 100 ); EXPECT_TRUE( Thread_GetExpired( Scheduler_GetCurrentThread() ) ); } TEST_END //=========================================================================== static ProfileTimer_t stProfiler1; static void Thread_tSleepEntryPoint(void *unused_) { unused_ = unused_; // Thread_t will sleep for various intervals, synchronized // to Semaphore_t-based IPC. Semaphore_Pend( &stSem1 ); Thread_Sleep(5); Semaphore_Post( &stSem2 ); Semaphore_Pend( &stSem1 ); Thread_Sleep(50); Semaphore_Post( &stSem2 ); Semaphore_Pend( &stSem1 ); Thread_Sleep(500); Semaphore_Post( &stSem2 ); // Exit this Thread_t. Thread_Exit( Scheduler_GetCurrentThread() ); } //=========================================================================== TEST(ut_thread_sleep) { Profiler_Init(); Profiler_Start(); // Start another Thread_t, which sleeps for a various length of time Semaphore_Init( &stSem1, 0, 1); Semaphore_Init( &stSem2, 0, 1); // Initialize our Thread_t Thread_Init( &stThread1, aucStack1, TEST_STACK_SIZE, 7, Thread_tSleepEntryPoint, NULL); // Start the Thread_t (Thread_ts are created in the stopped state) Thread_Start( &stThread1 ); ProfileTimer_Init( &stProfiler1 ); ProfileTimer_Start( &stProfiler1 ); Semaphore_Post( &stSem1 ); Semaphore_Pend( &stSem2 ); ProfileTimer_Stop( &stProfiler1 ); EXPECT_GTE( (ProfileTimer_GetCurrent( &stProfiler1 ) * CLOCK_DIVIDE), (SYSTEM_FREQ / 200)); EXPECT_LTE( (ProfileTimer_GetCurrent( &stProfiler1 ) * CLOCK_DIVIDE), (SYSTEM_FREQ / 200) + (SYSTEM_FREQ / 200) ); ProfileTimer_Init( &stProfiler1 ); ProfileTimer_Start( &stProfiler1 ); Semaphore_Post( &stSem1 ); Semaphore_Pend( &stSem2 ); ProfileTimer_Stop( &stProfiler1 ); EXPECT_GTE( (ProfileTimer_GetCurrent( &stProfiler1 ) * CLOCK_DIVIDE), SYSTEM_FREQ / 20 ); EXPECT_LTE( (ProfileTimer_GetCurrent( &stProfiler1 ) * CLOCK_DIVIDE), (SYSTEM_FREQ / 20) + (SYSTEM_FREQ / 200)); ProfileTimer_Init( &stProfiler1 ); ProfileTimer_Start( &stProfiler1 ); Semaphore_Post( &stSem1 ); Semaphore_Pend( &stSem2 ); ProfileTimer_Stop( &stProfiler1 ); EXPECT_GTE( (ProfileTimer_GetCurrent( &stProfiler1 ) * CLOCK_DIVIDE), SYSTEM_FREQ / 2 ); EXPECT_LTE( (ProfileTimer_GetCurrent( &stProfiler1 ) * CLOCK_DIVIDE), (SYSTEM_FREQ / 2) + (SYSTEM_FREQ / 200) ); Profiler_Stop(); } TEST_END //=========================================================================== void RR_EntryPoint(void *value_) { volatile K_ULONG *pulValue = (K_ULONG*)value_; while(1) { (*pulValue)++; } } //=========================================================================== TEST(ut_roundrobin) { K_ULONG ulAvg; K_ULONG ulMax; K_ULONG ulMin; K_ULONG ulRange; // Create three Thread_ts that only increment counters, and keep them at // the same priority in order to test the roundrobin functionality of // the scheduler Thread_Init( &stThread1, aucStack1, TEST_STACK_SIZE, 1, RR_EntryPoint, (void*)&ulRR1); Thread_Init( &stThread2, aucStack2, TEST_STACK_SIZE, 1, RR_EntryPoint, (void*)&ulRR2); Thread_Init( &stThread3, aucStack3, TEST_STACK_SIZE, 1, RR_EntryPoint, (void*)&ulRR3); ulRR1 = 0; ulRR2 = 0; ulRR3 = 0; // Adjust Thread_t priority before starting test Thread_ts to ensure // they all start at the same time (when we hit the 1 second sleep) Thread_SetPriority( Scheduler_GetCurrentThread(), 2); Thread_Start( &stThread1 ); Thread_Start( &stThread2 ); Thread_Start( &stThread3 ); Thread_Sleep(5000); // When the sleep ends, this will preempt the Thread_t in progress, // allowing us to stop them, and drop priority. Thread_Stop( &stThread1 ); Thread_Stop( &stThread2 ); Thread_Stop( &stThread3 ); Thread_SetPriority( Scheduler_GetCurrentThread(), 1); // Compare the three counters - they should be nearly identical if (ulRR1 > ulRR2) { ulMax = ulRR1; } else { ulMax = ulRR2; } if (ulMax < ulRR3) { ulMax = ulRR3; } if (ulRR1 < ulRR2) { ulMin = ulRR1; } else { ulMin = ulRR2; } if (ulMin > ulRR3) { ulMin = ulRR3; } ulRange = ulMax - ulMin; ulAvg = (ulRR1 + ulRR2 + ulRR3) / 3; // Max-Min delta should not exceed 1% of average for this simple test EXPECT_LT( ulRange, ulAvg / 100); // Make sure none of the component values are 0 EXPECT_FAIL_EQUALS( ulRR1, 0 ); EXPECT_FAIL_EQUALS( ulRR2, 0 ); EXPECT_FAIL_EQUALS( ulRR3, 0 ); } TEST_END //=========================================================================== TEST(ut_quanta) { K_ULONG ulAvg; K_ULONG ulMax; K_ULONG ulMin; K_ULONG ulRange; // Create three Thread_ts that only increment counters - similar to the // previous test. However, modify the Thread_t quanta such that each Thread_t // will get a different proportion of the CPU cycles. Thread_Init( &stThread1, aucStack1, TEST_STACK_SIZE, 1, RR_EntryPoint, (void*)&ulRR1); Thread_Init( &stThread2, aucStack2, TEST_STACK_SIZE, 1, RR_EntryPoint, (void*)&ulRR2); Thread_Init( &stThread3, aucStack3, TEST_STACK_SIZE, 1, RR_EntryPoint, (void*)&ulRR3); ulRR1 = 0; ulRR2 = 0; ulRR3 = 0; // Adjust Thread_t priority before starting test Thread_ts to ensure // they all start at the same time (when we hit the 1 second sleep) Thread_SetPriority( Scheduler_GetCurrentThread(), 2); // Set a different execution quanta for each Thread_t Thread_SetQuantum( &stThread1, 3); Thread_SetQuantum( &stThread2, 6); Thread_SetQuantum( &stThread3, 9); Thread_Start( &stThread1 ); Thread_Start( &stThread2 ); Thread_Start( &stThread3 ); Thread_Sleep(1800); // When the sleep ends, this will preempt the Thread_t in progress, // allowing us to stop them, and drop priority. Thread_Stop( &stThread1 ); Thread_Stop( &stThread2 ); Thread_Stop( &stThread3 ); Thread_SetPriority( Scheduler_GetCurrentThread(), 1); // Test point - make sure that Q3 > Q2 > Q1 EXPECT_GT( ulRR2, ulRR1 ); EXPECT_GT( ulRR3, ulRR2 ); // scale the counters relative to the largest value, and compare. ulRR1 *= 3; ulRR2 *= 3; ulRR2 = (ulRR2 + 1) / 2; // After scaling, they should be nearly identical (well, stose at least) if (ulRR1 > ulRR2) { ulMax = ulRR1; } else { ulMax = ulRR2; } if (ulMax < ulRR3) { ulMax = ulRR3; } if (ulRR1 < ulRR2) { ulMin = ulRR1; } else { ulMin = ulRR2; } if (ulMin > ulRR3) { ulMin = ulRR3; } ulRange = ulMax - ulMin; ulAvg = (ulRR1 + ulRR2 + ulRR3) / 3; #if KERNEL_TIMERS_TICKLESS // Max-Min delta should not exceed 5% of average for this test EXPECT_LT( ulRange, ulAvg / 20); #else // Max-Min delta should not exceed 20% of average for this test -- tick-based timers // are coarse, and prone to Thread_t preference due to phase. EXPECT_LT( ulRange, ulAvg / 5); #endif // Make sure none of the component values are 0 EXPECT_FAIL_EQUALS( ulRR1, 0 ); EXPECT_FAIL_EQUALS( ulRR2, 0 ); EXPECT_FAIL_EQUALS( ulRR3, 0 ); } TEST_END //=========================================================================== // Test Whitelist Goes Here //=========================================================================== TEST_CASE_START TEST_CASE(ut_thread_create), TEST_CASE(ut_thread_stop), TEST_CASE(ut_thread_exit), TEST_CASE(ut_thread_sleep), TEST_CASE(ut_roundrobin), TEST_CASE(ut_quanta), TEST_CASE_END
moslevin/Mark3C
kernel/public/kernel.h
<reponame>moslevin/Mark3C /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernel.h \brief Kernel initialization and startup object The Kernel namespace provides functions related to initializing and starting up the kernel. The Kernel_Init() function must be called before any of the other functions in the kernel can be used. Once the initial kernel configuration has been completed (i.e. first threads have been added to the scheduler), the Kernel_Start() function can then be called, which will transition code execution from the "main()" context to the threads in the scheduler. */ #ifndef __KERNEL_H__ #define __KERNEL_H__ #include "mark3cfg.h" #include "kerneltypes.h" #include "paniccodes.h" #include "thread.h" #ifdef __cplusplus extern "C" { #endif #if KERNEL_USE_IDLE_FUNC typedef void (*idle_func_t)(void); #endif //--------------------------------------------------------------------------- /*! Class that encapsulates all of the kernel startup functions. */ /*! Kernel Initialization Function, call before any other OS function \fn Init() Initializes all global resources used by the operating system. This must be called before any other kernel function is invoked. */ void Kernel_Init( void ); /*! Start the kernel; function never returns \fn Start() Start the operating system kernel - the current execution context is cancelled, all kernel services are started, and the processor resumes execution at the entrypoint for the highest-priority thread. You must have at least one thread added to the kernel before calling this function, otherwise the behavior is undefined. */ void Kernel_Start( void ); /*! \brief IsStarted \return Whether or not the kernel has started - true = running, false = not started */ K_BOOL Kernel_IsStarted( void ); /*! * \brief SetPanic Set a function to be called when a kernel panic occurs, * giving the user to determine the behavior when a catastrophic * failure is observed. * * \param pfPanic_ Panic function pointer */ void Kernel_SetPanic( panic_func_t pfPanic_ ); /*! * \brief IsPanic Returns whether or not the kernel is in a panic state * \return Whether or not the kernel is in a panic state */ K_BOOL Kernel_IsPanic( void ); /*! * \brief Panic Cause the kernel to enter its panic state * \param usCause_ Reason for the kernel panic */ void Kernel_Panic(K_USHORT usCause_); #if KERNEL_USE_IDLE_FUNC /*! * \brief SetIdleFunc Set the function to be called when no active threads * are available to be scheduled by the scheduler. * \param pfIdle_ Pointer to the idle function */ void Kernel_SetIdleFunc( idle_func_t pfIdle_ ); /*! * \brief IdleFunc Call the low-priority idle function when no active * threads are available to be scheduled. */ void Kernel_IdleFunc( void ); /*! * \brief GetIdleThread Return a pointer to the Kernel's idle thread * object to the user. Note that the Thread_t object involved is * to be used for comparisons only -- the thread itself is "virtual", * and doesn't represent a unique execution context with its own stack. * \return Pointer to the Kernel's idle thread object */ Thread_t *Kernel_GetIdleThread( void ); #endif #ifdef __cplusplus } #endif #endif
moslevin/Mark3C
kernel/blocking.c
<filename>kernel/blocking.c<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file blocking.cpp \brief Implementation of base object for blocking objects */ #include "kerneltypes.h" #include "mark3cfg.h" #include "kerneldebug.h" #include "blocking.h" #include "thread.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ BLOCKING_C //!< File ID used in kernel trace calls #if KERNEL_USE_SEMAPHORE || KERNEL_USE_MUTEX //--------------------------------------------------------------------------- void BlockingObject_Block( ThreadList_t *pstList_, Thread_t *pstThread_ ) { KERNEL_ASSERT( pstThread_ ); KERNEL_TRACE_1( STR_THREAD_BLOCK_1, (K_USHORT)Thread_GetID( pstThread_ ) ); // Remove the thread from its current thread list (the "owner" list) // ... And add the thread to this object's block list Scheduler_Remove( pstThread_ ); ThreadList_Add( pstList_, pstThread_ ); // Set the "current" list location to the blocklist for this thread Thread_SetCurrent( pstThread_, pstList_ ); Thread_SetState( pstThread_, THREAD_STATE_BLOCKED ); } //--------------------------------------------------------------------------- void BlockingObject_UnBlock( Thread_t *pstThread_ ) { KERNEL_ASSERT( pstThread_ ); KERNEL_TRACE_1( STR_THREAD_UNBLOCK_1, (K_USHORT)Thread_GetID( pstThread_ ) ); // Remove the thread from its current thread list (the "owner" list) ThreadList_Remove( Thread_GetCurrent( pstThread_ ), pstThread_ ); // Put the thread back in its active owner's list. This is usually // the ready-queue at the thread's original priority. Scheduler_Add( pstThread_ ); // Tag the thread's current list location to its owner Thread_SetCurrent( pstThread_, Thread_GetOwner( pstThread_ ) ); Thread_SetState( pstThread_, THREAD_STATE_READY ); } #endif
moslevin/Mark3C
kernel/cpu/cm0/stm32f0/gcc/threadport.c
<filename>kernel/cpu/cm0/stm32f0/gcc/threadport.c /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file threadport.cpp \brief ARM Cortex-M0 Multithreading */ #include "kerneltypes.h" #include "mark3cfg.h" #include "thread.h" #include "threadport.h" #include "kernelswi.h" #include "kerneltimer.h" #include "timerlist.h" #include "quantum.h" //--------------------------------------------------------------------------- static void ThreadPort_StartFirstThread( void ) __attribute__ (( naked )); void SVC_Handler( void ) __attribute__ (( naked )); void PendSV_Handler( void ) __attribute__ (( naked )); void SysTick_Handler( void ); //--------------------------------------------------------------------------- volatile K_ULONG g_ulCriticalCount; //--------------------------------------------------------------------------- /* 1) Setting up the Thread_t stacks Stack consists of 2 separate frames mashed together. a) Exception Stack Frame Contains the 8 registers the CPU pushes/pops to/from the stack on execution of an exception: [ XPSR ] [ PC ] [ LR ] [ R12 ] [ R3 ] [ R2 ] [ R1 ] [ R0 ] XPSR - Needs to be set to 0x01000000; the "T" bit (thumb) must be set for any Thread_t executing on an ARMv6-m processor PC - Should be set with the initial entry point for the Thread_t LR - The base link register. We can leave this as 0, and set to 0xD on first context switch to tell the CPU to resume execution using the stack pointer held in the PSP as the regular stack. This is done by the CPU automagically- this format is part of the architecture, and there's nothing we can do to change or modify it. b) "Other" Register Context [ R11 ] ... [ R4 ] These are the other GP registers that need to be backed up/restored on a context switch, but aren't by default on a CM0 exception. If there were any additional hardware registers to back up, then we'd also have to include them in this part of the context. These all need to be manually pushed to the stack on stack creation, and puhsed/pop as part of a normal context switch. */ void ThreadPort_InitStack(Thread_t *pclThread_) { K_ULONG *pulStack; K_ULONG *pulTemp; K_ULONG ulAddr; K_USHORT i; // Get the entrypoint for the Thread_t ulAddr = (K_ULONG)(pclThread_->pfEntryPoint); // Get the top-of-stack pointer for the Thread_t pulStack = (K_ULONG*)pclThread_->pwStackTop; // Initialize the stack to all FF's to aid in stack depth checking pulTemp = (K_ULONG*)pclThread_->pwStack; for (i = 0; i < pclThread_->usStackSize / sizeof(K_ULONG); i++) { pulTemp[i] = 0xFFFFFFFF; } PUSH_TO_STACK(pulStack, 0); // We need one word of padding, apparently... //-- Simulated Exception Stack Frame -- PUSH_TO_STACK(pulStack, 0x01000000); // XSPR PUSH_TO_STACK(pulStack, ulAddr); // PC PUSH_TO_STACK(pulStack, 0); // LR PUSH_TO_STACK(pulStack, 0x12); PUSH_TO_STACK(pulStack, 0x3); PUSH_TO_STACK(pulStack, 0x2); PUSH_TO_STACK(pulStack, 0x1); PUSH_TO_STACK(pulStack, (K_ULONG)pclThread_->pvArg); // R0 = argument //-- Simulated Manually-Stacked Registers -- PUSH_TO_STACK(pulStack, 0x11); PUSH_TO_STACK(pulStack, 0x10); PUSH_TO_STACK(pulStack, 0x09); PUSH_TO_STACK(pulStack, 0x08); PUSH_TO_STACK(pulStack, 0x07); PUSH_TO_STACK(pulStack, 0x06); PUSH_TO_STACK(pulStack, 0x05); PUSH_TO_STACK(pulStack, 0x04); pulStack++; pclThread_->pwStackTop = pulStack; } //--------------------------------------------------------------------------- void Thread_Switch(void) { g_pstCurrent = (Thread_t*)g_pstNext; } //--------------------------------------------------------------------------- void ThreadPort_StartThreads() { KernelSWI_Config(); // configure the task switch SWI KernelTimer_Config(); // configure the kernel timer Scheduler_SetScheduler(1); // enable the scheduler Scheduler_Schedule(); // run the scheduler - determine the first Thread_t to run Thread_Switch(); // Set the next scheduled Thread_t to the current Thread_t KernelTimer_Start(); // enable the kernel timer KernelSWI_Start(); // enable the task switch SWI ThreadPort_StartFirstThread(); // Jump to the first Thread_t (does not return) } //--------------------------------------------------------------------------- /* The same general process applies to starting the kernel as per usual We can either: 1) Simulate a return from an exception manually to start the first Thread_t, or.. 2) Use a software exception to trigger the first "Context Restore /Return from Interrupt" that we have otherwised used to this point. For 1), we basically have to restore the whole stack manually, not relying on the CPU to do any of this for us. That's certainly doable, but not all Cortex parts support this (due to other members of the family supporting priveleged modes). So, we will opt for the second option. So, to implement a software interrupt to restore our first Thread_t, we will use the SVC instruction to generate that exception. At the end of Thread_t initialization, we have to do 2 things: -Enable exceptions/interrupts -Call SVC Optionally, we can reset the MSP stack pointer to the top-of-stack. Note, the default stack pointer location is stored at address 0x00000000 on all ARM Cortex M0 parts (While Mark3 avoids assembler code as much as possible, there are some places where it cannot be avoided. However, we can at least inline it in most circumstances.) */ void ThreadPort_StartFirstThread( void ) { ASM ( " mov r0, #0 \n" " ldr r1, [r0] \n" " msr msp, r1 \n" " cpsie i \n" " svc 0 \n" ); } //--------------------------------------------------------------------------- /* The SVC Call This handler has the job of taking the first Thread_t object's stack, and restoring the default state data in a way that ensures that the Thread_t starts executing when returning from the call. We also keep in mind that there's an 8-byte offset from the beginning of the Thread_t object to the location of the Thread_t stack pointer. This offset is a result of the Thread_t object inheriting from the linked-list node class, which has 8-bytes of data. This is stored first in the object, before the first element of the class, which is the "stack top" pointer. get_thread_stack: ; Get the stack pointer for the current Thread_t ldr r0, g_pstCurrent ldr r1, [r0] add r1, #8 ldr r2, [r1] ; r2 contains the current stack-top load_manually_placed_context_r11_r8: ; Handle the bottom 32-bytes of the stack frame ; Start with r11-r8, because only r0-r7 can be used ; with ldmia on CM0. add r2, #16 ldmia r2!, {r4-r7} mov r11, r7 mov r10, r6 mov r9, r5 mov r8, r4 set_psp: ; Since r2 is coincidentally back to where the stack pointer should be, ; Set the program stack pointer such that returning from the exception handler msr psp, r2 load_manually_placed_context_r7_r4: ; Get back to the bottom of the manually stacked registers and pop. sub r2, #32 ldmia r2!, {r4-r7} ; Register r4-r11 are restored. ** Note - Since we don't care about these registers on init, we could take a shortcut if we wanted to ** shortcut_init: add r2, #32 msr psp, r2 set_lr: ; Set up the link register such that on return, the code operates in Thread_t mode using the PSP ; To do this, we or 0x0D to the value stored in the lr by the exception hardware EXC_RETURN. ; Alternately, we could just force lr to be 0xFFFFFFFD (we know that's what we want from the hardware, anyway) mov r0, #0x0D mov r1, lr orr r0, r1 exit_exception: ; Return from the exception handler. The CPU will automagically unstack R0-R3, R12, PC, LR, and xPSR ; for us. If all goes well, our Thread_t will start execution at the entrypoint, with the user-specified ; argument. bx r0 This code is identical to what we need to restore the context, so we'll just make it a macro and be done with it. */ void SVC_Handler(void) { ASM( // Get the pointer to the first Thread_t's stack " mov r3, %[CURRENT_THREAD]\n " " add r3, #8 \n " " ldr r2, [r3] \n " // Stack pointer is in r2, start loading registers from the "manually-stacked" set // Start with r11-r8, since these can't be accessed directly. " add r2, #16 \n " " ldmia r2!, {r4-r7} \n " " mov r11, r7 \n " " mov r10, r6 \n " " mov r9, r5 \n " " mov r8, r4 \n " // After subbing R2 #16 manually, and #16 through ldmia, our PSP is where it // needs to be when we return from the exception handler " msr psp, r2 \n " // Pop manually-stacked R4-R7 " sub r2, #32 \n " " ldmia r2!, {r4-r7} \n " // Also modify the control register to force use of Thread_t mode as well // For CM3 forward-compatibility, also set user mode. " mrs r0, control \n" " mov r1, #0x03 \n" " orr r0, r1 \n" " msr control, r0 \n" // Return into Thread_t mode, using PSP as the Thread_t's stack pointer // To do this, or 0x0D into the current lr. " mov r0, #0x0D \n " " mov r1, lr \n " " orr r0, r1 \n " " bx r0 \n " : : [CURRENT_THREAD] "r" (g_pstCurrent) ); } //--------------------------------------------------------------------------- /* Context Switching: On ARM Cortex parts, there's dedicated hardware that's used primarily to support RTOS (or RTOS-like) funcationlity. This functionality includes the SysTick timer, and the PendSV Exception. SysTick is used for the kernel timer (I need to learn how to use it to see whether or not I can do tickless timers), while the PendSV exception is used for triggering context switches. In reality, it's a "special SVC" call that's designed to be lower-overhead, in that it isn't mux'd with a bunch of other system or application functionality. Alright, so how do we go about actually implementing a context switch here? There are a lot of different parts involved, but it essentially comes down to 3 steps: 1) Save Context 2) Swap "current" and "next" Thread_t pointers 3) Restore Context 1) Saving the context. Alright, so when we enter the exception handler, We should expect that the exception stack frame is stored to our PSP. This takes care of everything but r4-r11. Similar to the "restore context" code, we'll have to break up the register storage into multiple chunks. ; Get address of current Thread_t stack ldr r0, g_pstCurrentThread ldr r1, [r0] add r1, #8 ; Grab the psp and adjust it by 32 based on the extra registers we're going ; to be manually stacking. mrs r2, psp sub r2, #32 ; While we're here, store the new top-of-stack value str r2, [r1] ; And, while r2 is at the bottom of the stack frame, stack r7-r4 stmia r2!, {r4-r7} ; Stack r11-r8 mov r7, r11 mov r6, r10 mov r5, r9 mov r4, r8 stmia r2!, {r4-r7} ; Done! Thread_t's top-of-stack value is stored, all registers are stacked. We're good to go! 2) Swap threads This is the easy part - we just call a function to swap in the Thread_t "current" Thread_t from the "next" Thread_t. 3) Restore Context This is more or less identical to what we did when restoring the first context. Small optimization - we don't bother explicitly setting the */ void PendSV_Handler(void) { ASM( // Thread_SaveContext() " ldr r1, CURR_ \n" " ldr r1, [r1] \n " " mov r3, r1 \n " " add r3, #8 \n " // Grab the psp and adjust it by 32 based on the extra registers we're going // to be manually stacking. " mrs r2, psp \n " " sub r2, #32 \n " // While we're here, store the new top-of-stack value " str r2, [r3] \n " // And, while r2 is at the bottom of the stack frame, stack r7-r4 " stmia r2!, {r4-r7} \n " // Stack r11-r8 " mov r7, r11 \n " " mov r6, r10 \n " " mov r5, r9 \n " " mov r4, r8 \n " " stmia r2!, {r4-r7} \n " // Equivalent of Thread_Swap() " ldr r1, CURR_ \n" " ldr r0, NEXT_ \n" " ldr r0, [r0] \n" " str r0, [r1] \n" // Get the pointer to the next Thread_t's stack " add r0, #8 \n " " ldr r2, [r0] \n " // Stack pointer is in r2, start loading registers from the "manually-stacked" set // Start with r11-r8, since these can't be accessed directly. " add r2, #16 \n " " ldmia r2!, {r4-r7} \n " " mov r11, r7 \n " " mov r10, r6 \n " " mov r9, r5 \n " " mov r8, r4 \n " // After subbing R2 #16 manually, and #16 through ldmia, our PSP is where it // needs to be when we return from the exception handler " msr psp, r2 \n " // Pop manually-stacked R4-R7 " sub r2, #32 \n " " ldmia r2!, {r4-r7} \n " // lr contains the proper EXC_RETURN value, we're done with exceptions. " bx lr \n " " nop \n " // Must be 4-byte aligned. Also - GNU assembler, I hate you for making me resort to this. " NEXT_: .word g_pstNext \n" " CURR_: .word g_pstCurrent \n" ); } //--------------------------------------------------------------------------- void SysTick_Handler(void) { #if KERNEL_USE_TIMERS TimerScheduler_Process(); #endif #if KERNEL_USE_QUANTUM Quantum_UpdateTimer(); #endif // Clear the systick interrupt pending bit. SCB->ICSR |= SCB_ICSR_PENDSTCLR_Msk; }
moslevin/Mark3C
kernel/public/mark3.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file mark3.h \brief Single include file given to users of the Mark3 Kernel API */ #ifndef __MARK3_H__ #define __MARK3_H__ #include "mark3cfg.h" #include "kerneltypes.h" #include "ll.h" #include "kernel.h" #include "scheduler.h" #include "threadport.h" #include "thread.h" #include "kerneltimer.h" #include "timer.h" #include "kernelswi.h" #include "kernelprofile.h" #include "timerlist.h" #include "ksemaphore.h" #include "mutex.h" #include "eventflag.h" #include "message.h" #include "notify.h" #include "atomic.h" #include "driver.h" #include "kernelaware.h" #include "profile.h" #endif
moslevin/Mark3C
kernel/public/threadlist.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file threadlist.h \brief Thread_t linked-list declarations */ #ifndef __THREADLIST_H__ #define __THREADLIST_H__ #include "kerneltypes.h" #include "ll.h" #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- /*! \brief ThreadList_Init Default constructor - zero-initializes data before use. \param pstList_ ThreadList object to manipulate */ void ThreadList_Init( ThreadList_t *pstList_ ); //--------------------------------------------------------------------------- /*! \brief ThreadList_SetPriority Set the priority of this threadlist (if used for a scheduler). \param pstList_ ThreadList object to manipulate \param ucPriority_ Priority level of the thread list */ void ThreadList_SetPriority( ThreadList_t *pstList_, K_UCHAR ucPriority_ ); //--------------------------------------------------------------------------- /*! \brief ThreadList_SetFlagPointer Set the pointer to a bitmap to use for this threadlist. Once again, only needed when the threadlist is being used for scheduling purposes. \param pstList_ ThreadList object to manipulate \param pucFlag_ Pointer to the bitmap flag */ void ThreadList_SetFlagPointer( ThreadList_t *pstList_, K_UCHAR *pucFlag_ ); //--------------------------------------------------------------------------- /*! \brief ThreadList_Add Add a thread to the threadlist. \param pstList_ ThreadList object to manipulate \param node_ Pointer to the thread (link list node) to add to the list */ void ThreadList_Add( ThreadList_t *pstList_, Thread_t *node_ ); //--------------------------------------------------------------------------- /*! \brief ThreadList_AddEX \fn void Add(LinkListNode_t *node_, K_UCHAR *pucFlag_, K_UCHAR ucPriority_) Add a thread to the threadlist, specifying the flag and priority at the same time. \param pstList_ ThreadList object to manipulate \param node_ Pointer to the thread to add (link list node) \param pucFlag_ Pointer to the bitmap flag to set (if used in a scheduler context), or NULL for non-scheduler. \param ucPriority_ Priority of the threadlist */ void ThreadList_AddEX( ThreadList_t *pstList_, Thread_t *node_, K_UCHAR *pucFlag_, K_UCHAR ucPriority_); //--------------------------------------------------------------------------- /*! \brief ThreadList_Remove Remove the specified thread from the threadlist \param pstList_ ThreadList object to manipulate \param node_ Pointer to the thread to remove */ void ThreadList_Remove( ThreadList_t *pstList_, Thread_t *node_); //--------------------------------------------------------------------------- /*! \brief ThreadList_HighestWaiter Return a pointer to the highest-priority thread in the thread-list. \param pstList_ ThreadList object to manipulate \return Pointer to the highest-priority thread */ Thread_t *ThreadList_HighestWaiter( ThreadList_t *pstList_ ); #ifdef __cplusplus } #endif #endif
moslevin/Mark3C
kernel/public/timer.h
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file timer.h \brief Timer_t object declarations */ #ifndef __TIMER_H__ #define __TIMER_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #if KERNEL_USE_TIMERS #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- #define TIMERLIST_FLAG_ONE_SHOT (0x01) //!< Timer_t is one-shot #define TIMERLIST_FLAG_ACTIVE (0x02) //!< Timer_t is currently active #define TIMERLIST_FLAG_CALLBACK (0x04) //!< Timer_t is pending a callback #define TIMERLIST_FLAG_EXPIRED (0x08) //!< Timer_t is actually expired. //--------------------------------------------------------------------------- #if KERNEL_TIMERS_TICKLESS //--------------------------------------------------------------------------- #define MAX_TIMER_TICKS (0x7FFFFFFF) //!< Maximum value to set //--------------------------------------------------------------------------- /* Ugly macros to support a wide resolution of delays. Given a 16-bit timer @ 16MHz & 256 cycle prescaler, this gives us... Max time, SECONDS_TO_TICKS: 68719s Max time, MSECONDS_TO_TICKS: 6871.9s Max time, USECONDS_TO_TICKS: 6.8719s ...With a 16us tick resolution. Depending on the system frequency and timer resolution, you may want to customize these values to suit your system more appropriately. */ //--------------------------------------------------------------------------- #define SECONDS_TO_TICKS(x) ((((K_ULONG)x) * TIMER_FREQ)) #define MSECONDS_TO_TICKS(x) ((((((K_ULONG)x) * (TIMER_FREQ/100)) + 5) / 10)) #define USECONDS_TO_TICKS(x) ((((((K_ULONG)x) * TIMER_FREQ) + 50000) / 1000000)) //--------------------------------------------------------------------------- #define MIN_TICKS (3) //!< The minimum tick value to set //--------------------------------------------------------------------------- #else //--------------------------------------------------------------------------- // Tick-based timers, assuming 1khz tick rate #define MAX_TIMER_TICKS (0x7FFFFFFF) //!< Maximum value to set //--------------------------------------------------------------------------- // add time because we don't know how far in an epoch we are when a call is made. #define SECONDS_TO_TICKS(x) (((K_ULONG)(x) * 1000) + 1) #define MSECONDS_TO_TICKS(x) ((K_ULONG)(x + 1)) #define USECONDS_TO_TICKS(x) (((K_ULONG)(x + 999)) / 1000) //--------------------------------------------------------------------------- #define MIN_TICKS (1) //!< The minimum tick value to set //--------------------------------------------------------------------------- #endif // KERNEL_TIMERS_TICKLESS //--------------------------------------------------------------------------- /*! Timer_t - an event-driven execution context based on a specified time interval. This inherits from a LinkListNode_t for ease of management by a global TimerList object. */ //--------------------------------------------------------------------------- /*! * \brief Timer_Init Re-initialize the Timer_t to default values. * \param pstTimer_ Pointer to the timer object to manipulate */ void Timer_Init( Timer_t *pstTimer_ ); //--------------------------------------------------------------------------- /*! \brief Timer_Start Start a timer using default ownership, using repeats as an option, and millisecond resolution. \param pstTimer_ Pointer to the timer object to manipulate \param bRepeat_ 0 - timer is one-shot. 1 - timer is repeating. \param ulIntervalMs_ - Interval of the timer in miliseconds \param pfCallback_ - Function to call on timer expiry \param pvData_ - Data to pass into the callback function */ void Timer_Start( Timer_t *pstTimer_, K_BOOL bRepeat_, K_ULONG ulIntervalMs_, TimerCallback_t pfCallback_, void *pvData_ ); //--------------------------------------------------------------------------- /*! \brief Timer_StartEx Start a timer using default ownership, using repeats as an option, and millisecond resolution. \param pstTimer_ Pointer to the timer object to manipulate \param bRepeat_ 0 - timer is one-shot. 1 - timer is repeating. \param ulIntervalMs_ - Interval of the timer in miliseconds \param ulToleranceMs - Allow the timer expiry to be delayed by an additional maximum time, in order to have as many timers expire at the same time as possible. \param pfCallback_ - Function to call on timer expiry \param pvData_ - Data to pass into the callback function */ void Timer_StartEx( Timer_t *pstTimer_, K_BOOL bRepeat_, K_ULONG ulIntervalMs_, K_ULONG ulToleranceMs_, TimerCallback_t pfCallback_, void *pvData_ ); //--------------------------------------------------------------------------- /*! Stop a timer already in progress. Has no effect on timers that have already been stopped. */ /*! * \brief Timer_Stop * * Stop a timer already in progress. Has no effect on timers that have * already been stopped. * * \param pstTimer_ Pointer to the timer object to manipulate */ void Timer_Stop( Timer_t *pstTimer_ ); //--------------------------------------------------------------------------- /*! \fn void Timer_SetFlags (K_UCHAR ucFlags_) Set the timer's flags based on the bits in the ucFlags_ argument \param pstTimer_ Pointer to the timer object to manipulate \param ucFlags_ Flags to assign to the timer object. TIMERLIST_FLAG_ONE_SHOT for a one-shot timer, 0 for a continuous timer. */ void Timer_SetFlags ( Timer_t *pstTimer_, K_UCHAR ucFlags_); //--------------------------------------------------------------------------- /*! \fn void Timer_SetCallback( TimerCallback_t pfCallback_) Define the callback function to be executed on expiry of the timer \param pstTimer_ Pointer to the timer object to manipulate \param pfCallback_ Pointer to the callback function to call */ void Timer_SetCallback( Timer_t *pstTimer_, TimerCallback_t pfCallback_); //--------------------------------------------------------------------------- /*! \fn void Timer_SetData( void *pvData_ ) Define a pointer to be sent to the timer callbcak on timer expiry \param pvData_ Pointer to data to pass as argument into the callback */ void Timer_SetData( Timer_t *pstTimer_, void *pvData_ ); //--------------------------------------------------------------------------- /*! \fn void Timer_SetOwner( Thread_t *pstOwner_) Set the owner-thread of this timer object (all timers must be owned by a thread). \param pstOwner_ Owner thread of this timer object */ void Timer_SetOwner( Timer_t *pstTimer_, Thread_t *pstOwner_); //--------------------------------------------------------------------------- /*! \fn void Timer_SetIntervalTicks(K_ULONG ulTicks_) Set the timer expiry in system-ticks (platform specific!) \param pstTimer_ Pointer to the timer object to manipulate \param ulTicks_ Time in ticks */ void Timer_SetIntervalTicks( Timer_t *pstTimer_, K_ULONG ulTicks_); //--------------------------------------------------------------------------- /*! \fn void Timer_SetIntervalSeconds(K_ULONG ulSeconds_); Set the timer expiry interval in seconds (platform agnostic) \param ulSeconds_ Time in seconds */ void Timer_SetIntervalSeconds( Timer_t *pstTimer_, K_ULONG ulSeconds_); //--------------------------------------------------------------------------- /*! * \brief Timer_GetInterval Return the timer object's programmed interval * \param pstTimer_ Pointer to the timer object to manipulate * \return The timer object's programmed interval, in ticks. */ K_ULONG Timer_GetInterval( Timer_t *pstTimer_ ); //--------------------------------------------------------------------------- /*! \fn void Timer_SetIntervalMSeconds(K_ULONG ulMSeconds_) Set the timer expiry interval in milliseconds (platform agnostic) \param pstTimer_ Pointer to the timer object to manipulate \param ulMSeconds_ Time in milliseconds */ void Timer_SetIntervalMSeconds( Timer_t *pstTimer_, K_ULONG ulMSeconds_); //--------------------------------------------------------------------------- /*! \fn void Timer_SetIntervalUSeconds(K_ULONG ulUSeconds_) Set the timer expiry interval in microseconds (platform agnostic) \param pstTimer_ Pointer to the timer object to manipulate \param ulUSeconds_ Time in microseconds */ void Timer_SetIntervalUSeconds( Timer_t *pstTimer_, K_ULONG ulUSeconds_); //--------------------------------------------------------------------------- /*! \fn void Timer_SetTolerance(K_ULONG ulTicks_) Set the timer's maximum tolerance in order to synchronize timer processing with other timers in the system. \param pstTimer_ Pointer to the timer object to manipulate \param ulTicks_ Maximum tolerance in ticks */ void Timer_SetTolerance( Timer_t *pstTimer_, K_ULONG ulTicks_); #ifdef __cplusplus } #endif #endif // KERNEL_USE_TIMERS #endif
moslevin/Mark3C
kernel/cpu/avr/atmega328p/gcc/kernelprofile.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernelprofile.cpp \brief ATMega328p Profiling timer implementation */ #include "kerneltypes.h" #include "mark3cfg.h" #include "profile.h" #include "kernelprofile.h" #include "threadport.h" #include <avr/io.h> #include <avr/interrupt.h> #if KERNEL_USE_PROFILER K_ULONG ulEpoch; //--------------------------------------------------------------------------- void Profiler_Init( void ) { TCCR0A = 0; TCCR0B = 0; TIFR0 = 0; TIMSK0 = 0; ulEpoch = 0; } //--------------------------------------------------------------------------- void Profiler_Start( void ) { TIFR0 = 0; TCNT0 = 0; TCCR0B |= (1 << CS01); TIMSK0 |= (1 << TOIE0); } //--------------------------------------------------------------------------- void Profiler_Stop( void ) { TIFR0 = 0; TCCR0B &= ~(1 << CS01); TIMSK0 &= ~(1 << TOIE0); } //--------------------------------------------------------------------------- K_USHORT Profiler_Read( void ) { K_USHORT usRet; CS_ENTER(); TCCR0B &= ~(1 << CS01); usRet = TCNT0; TCCR0B |= (1 << CS01); CS_EXIT(); return usRet; } //--------------------------------------------------------------------------- void Profiler_Process( void ) { CS_ENTER(); ulEpoch++; CS_EXIT(); } //--------------------------------------------------------------------------- K_ULONG Profiler_GetEpoch( void ) { return ulEpoch; } //--------------------------------------------------------------------------- ISR(TIMER0_OVF_vect) { Profiler_Process(); } #endif
moslevin/Mark3C
kernel/public/eventflag.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file eventflag.h \brief Event Flag Blocking Object/IPC-Object definition. */ #ifndef __EVENTFLAG_H__ #define __EVENTFLAG_H__ #include "mark3cfg.h" #include "kernel.h" #include "kerneltypes.h" #include "blocking.h" #include "thread.h" #if KERNEL_USE_EVENTFLAG #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- /*! * \brief The EventFlag_t object is a blocking object, similar to a Semaphore_t or * Mutex_t, commonly used for synchronizing thread execution based on events * occurring within the system. * * Each EventFlag_t object contains a 16-bit bitmask, which is used to trigger * events on associated threads. Threads wishing to block, waiting for * a specific event to occur can wait on any pattern within this 16-bit bitmask * to be set. Here, we provide the ability for a thread to block, waiting * for ANY bits in a specified mask to be set, or for ALL bits within a * specific mask to be set. Depending on how the object is configured, the * bits that triggered the wakeup can be automatically cleared once a match * has occurred. * */ typedef struct { // Inherit from BlockingObject -- must go first ThreadList_t stList; K_USHORT usSetMask; //!< Event flags currently set in this object } EventFlag_t; /*! \brief Init Initializes the EventFlag_t object prior to use. */ void EventFlag_Init( EventFlag_t *pstFlag_ ); /*! * \brief Wait - Block a thread on the specific flags in this event flag group * \param usMask_ - 16-bit bitmask to block on * \param eMode_ - EVENT_FLAG_ANY: Thread_t will block on any of the bits in the mask * - EVENT_FLAG_ALL: Thread_t will block on all of the bits in the mask * \return Bitmask condition that caused the thread to unblock, or 0 on error or timeout */ K_USHORT EventFlag_Wait( EventFlag_t *pstFlag_, K_USHORT usMask_, EventFlagOperation_t eMode_); #if KERNEL_USE_TIMEOUTS /*! * \brief Wait - Block a thread on the specific flags in this event flag group * \param usMask_ - 16-bit bitmask to block on * \param eMode_ - EVENT_FLAG_ANY: Thread_t will block on any of the bits in the mask * - EVENT_FLAG_ALL: Thread_t will block on all of the bits in the mask * \param ulTimeMS_ - Time to block (in ms) * \return Bitmask condition that caused the thread to unblock, or 0 on error or timeout */ K_USHORT EventFlag_TimedWait( EventFlag_t *pstFlag_, K_USHORT usMask_, EventFlagOperation_t eMode_, K_ULONG ulTimeMS_); #endif /*! * \brief Set - Set additional flags in this object (logical OR). This API can potentially * result in threads blocked on Wait() to be unblocked. * \param usMask_ - Bitmask of flags to set. */ void EventFlag_Set( EventFlag_t *pstFlag_, K_USHORT usMask_); /*! * \brief ClearFlags - Clear a specific set of flags within this object, specific by bitmask * \param usMask_ - Bitmask of flags to clear */ void EventFlag_Clear( EventFlag_t *pstFlag_, K_USHORT usMask_); /*! * \brief GetMask Returns the state of the 16-bit bitmask within this object * \return The state of the 16-bit bitmask */ K_USHORT EventFlag_GetMask( EventFlag_t *pstFlag_ ); #ifdef __cplusplus } #endif #endif //KERNEL_USE_EVENTFLAG #endif //__EVENTFLAG_H__
moslevin/Mark3C
kernel/driver.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file driver.cpp \brief Device driver/hardware abstraction layer */ #include "kerneltypes.h" #include "mark3cfg.h" #include "kerneldebug.h" #include "driver.h" #include "ll.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ DRIVER_C //!< File ID used in kernel trace calls //--------------------------------------------------------------------------- #if KERNEL_USE_DRIVER static DoubleLinkList_t stDriverList; /*! This object implements the "default" driver (/dev/null) */ //--------------------------------------------------------------------------- static DriverVTable_t stDevNullVT = { 0, 0, 0, 0, 0 }; //--------------------------------------------------------------------------- static Driver_t stDevNull = { .pstVTable = &stDevNullVT, .szName = "/dev/null" }; //--------------------------------------------------------------------------- /*! * \brief DrvCmp * * String comparison function used to compare input driver name against a * known driver name in the existing driver list. * * \param szStr1_ user-specified driver name * \param szStr2_ name of a driver, provided from the driver table * \return 1 on match, 0 on no-match */ static K_UCHAR DrvCmp( const K_CHAR *szStr1_, const K_CHAR *szStr2_ ) { K_CHAR *szTmp1 = (K_CHAR*) szStr1_; K_CHAR *szTmp2 = (K_CHAR*) szStr2_; while (*szTmp1 && *szTmp2) { if (*szTmp1++ != *szTmp2++) { return 0; } } // Both terminate at the same length if (!(*szTmp1) && !(*szTmp2)) { return 1; } return 0; } //--------------------------------------------------------------------------- void DriverList_Init( void ) { // Ensure we always have at least one entry - a default in case no match // is found (/dev/null) DoubleLinkList_Init( (DoubleLinkList_t*)&stDriverList ); DoubleLinkList_Add( (DoubleLinkList_t*)&stDriverList, (LinkListNode_t*)&stDevNull); } //--------------------------------------------------------------------------- void DriverList_Add( Driver_t *pstDriver_ ) { DoubleLinkList_Add( (DoubleLinkList_t*)&stDriverList, (LinkListNode_t*)pstDriver_ ); } //--------------------------------------------------------------------------- Driver_t *DriverList_FindByPath( const K_CHAR *pcPath ) { KERNEL_ASSERT( pcPath ); Driver_t *pstTemp; pstTemp = (Driver_t*)(LinkList_GetHead( (LinkList_t*)&stDriverList ) ); // Iterate through the list of drivers until we find a match, or we // exhaust our list of installed drivers while (pstTemp) { if( DrvCmp( pcPath, Driver_GetPath( pstTemp ) ) ) { return pstTemp; } pstTemp = (Driver_t*)(LinkListNode_GetNext( (LinkListNode_t*)pstTemp ) ); } // No matching driver found - return a pointer to our /dev/null driver return &stDevNull; } //--------------------------------------------------------------------------- void Driver_SetName( Driver_t *pstDriver_, const K_CHAR *pcName_ ) { pstDriver_->szName = pcName_; } //--------------------------------------------------------------------------- const K_CHAR *Driver_GetPath( Driver_t *pstDriver_ ) { return pstDriver_->szName; } //--------------------------------------------------------------------------- K_UCHAR Driver_Open( Driver_t *pstDriver_ ) { if ( pstDriver_->pstVTable->pfOpen ) { return pstDriver_->pstVTable->pfOpen( pstDriver_ ); } return 0; } //--------------------------------------------------------------------------- K_UCHAR Driver_Close( Driver_t *pstDriver_ ) { if ( pstDriver_->pstVTable->pfClose ) { return pstDriver_->pstVTable->pfClose( pstDriver_ ); } return 0; } //--------------------------------------------------------------------------- K_USHORT Driver_Read( Driver_t *pstDriver_, K_USHORT usSize_, K_UCHAR *pucData_ ) { if ( pstDriver_->pstVTable->pfRead ) { return pstDriver_->pstVTable->pfRead( pstDriver_, usSize_, pucData_ ); } return usSize_; } //--------------------------------------------------------------------------- K_USHORT Driver_Write( Driver_t *pstDriver_, K_USHORT usSize_, K_UCHAR *pucData_ ) { if ( pstDriver_->pstVTable->pfWrite ) { return pstDriver_->pstVTable->pfWrite( pstDriver_, usSize_, pucData_ ); } return usSize_; } //--------------------------------------------------------------------------- K_USHORT Driver_Control( Driver_t *pstDriver_, K_USHORT usEvent_, K_USHORT usInSize_, K_UCHAR *pucIn_, K_USHORT usOutSize_, K_UCHAR *pucOut_) { if ( pstDriver_->pstVTable->pfControl ) { return pstDriver_->pstVTable->pfControl( pstDriver_, usEvent_, usInSize_, pucIn_, usOutSize_, pucOut_); } return 0; } #endif
moslevin/Mark3C
kernel/public/kerneltypes.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kerneltypes.h \brief Basic data type primatives used throughout the OS */ #ifndef __KERNELTYPES_H__ #define __KERNELTYPES_H__ #include <stdint.h> #include <stdbool.h> #include "ll.h" #include "mark3cfg.h" #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- #if defined(bool) #define K_BOOL bool //!< Basic boolean data type (true = 1, false = 0) #else #define K_BOOL uint8_t //!< Basic boolean data type (true = 1, false = 0) #endif #define K_CHAR char //!< The 8-bit signed integer type used by Mark3 #define K_UCHAR uint8_t //!< The 8-bit unsigned integer type used by Mark3 #define K_USHORT uint16_t //!< The 16-bit unsigned integer type used by Mark3 #define K_SHORT int16_t //!< The 16-bit signed integer type used by Mark3 #define K_ULONG uint32_t //!< The 32-bit unsigned integer type used by Mark3 #define K_LONG int32_t //!< The 32-bit signed integer type used by Mark3 #if !defined(K_ADDR) #define K_ADDR uint16_t //!< Primative datatype representing address-size #endif #if !defined(K_WORD) #define K_WORD uint8_t //!< Primative datatype representing a data word #endif //--------------------------------------------------------------------------- // Forward declarations struct _Thread; struct _ThreadList; struct _Timer; //--------------------------------------------------------------------------- /*! * Function pointer type used to implement kernel-panic handlers. */ typedef void (*panic_func_t)( K_USHORT usPanicCode_ ); //--------------------------------------------------------------------------- /*! * This enumeration describes the different operations supported by the * event flag blocking object. */ typedef enum { EVENT_FLAG_ALL, //!< Block until all bits in the specified bitmask are set EVENT_FLAG_ANY, //!< Block until any bits in the specified bitmask are set EVENT_FLAG_ALL_CLEAR, //!< Block until all bits in the specified bitmask are cleared EVENT_FLAG_ANY_CLEAR, //!< Block until any bits in the specified bitmask are cleared //--- EVENT_FLAG_MODES, //!< Count of event-flag modes. Not used by user EVENT_FLAG_PENDING_UNBLOCK //!< Special code. Not used by user } EventFlagOperation_t; //--------------------------------------------------------------------------- /*! This object is used for building thread-management facilities, such as schedulers, and blocking objects. */ struct _ThreadList { // Inherit from CircularLinkList_t -- must be first!! CircularLinkList_t stList; //! Priority of the threadlist K_UCHAR ucPriority; //! Pointer to the bitmap/flag to set when used for scheduling. K_UCHAR *pucFlag; }; //--------------------------------------------------------------------------- /*! * This type defines the callback function type for timer events. Since these * are called from an interrupt context, they do not operate from within a * thread or object context directly -- as a result, the context must be * manually passed into the calls. * * pstOwner_ is a pointer to the thread that owns the timer * pvData_ is a pointer to some data or object that needs to know about the * timer's expiry from within the timer interrupt context. */ typedef void (*TimerCallback_t)( struct _Thread *pstOwner_, void *pvData_ ); //--------------------------------------------------------------------------- struct _Timer { // Inherit from LinkListNode_t -- must be first! LinkListNode_t stNode; //! Flags for the timer, defining if the timer is one-shot or repeated K_UCHAR ucFlags; //! Pointer to the callback function TimerCallback_t pfCallback; //! Interval of the timer in timer ticks K_ULONG ulInterval; //! Time remaining on the timer K_ULONG ulTimeLeft; //! Maximum tolerance (used for timer harmonization) K_ULONG ulTimerTolerance; //! Pointer to the owner thread struct _Thread *pstOwner; //! Pointer to the callback data void *pvData; }; //--------------------------------------------------------------------------- /*! Function pointer type used for thread entrypoint functions */ typedef void (*ThreadEntry_t)(void *pvArg_); //--------------------------------------------------------------------------- /*! Enumeration representing the different states a thread can exist in */ typedef enum { THREAD_STATE_EXIT = 0, THREAD_STATE_READY, THREAD_STATE_BLOCKED, THREAD_STATE_STOP, //-- THREAD_STATES } ThreadState_t; //--------------------------------------------------------------------------- /*! Object providing fundamental multitasking support in the kernel. */ struct _Thread { //! Linked-list metadata. Must be first! LinkListNode_t stLinkList; //! Pointer to the top of the thread's stack K_WORD *pwStackTop; //! Pointer to the thread's stack K_WORD *pwStack; //! Thread_t ID K_UCHAR ucThreadID; //! Default priority of the thread K_UCHAR ucPriority; //! Current priority of the thread (priority inheritence) K_UCHAR ucCurPriority; //! Enum indicating the thread's current state ThreadState_t eState; #if KERNEL_USE_THREADNAME //! Thread_t name const K_CHAR *szName; #endif //! Size of the stack (in bytes) K_USHORT usStackSize; //! Pointer to the thread-list where the thread currently resides struct _ThreadList *pstCurrent; //! Pointer to the thread-list where the thread resides when active struct _ThreadList *pstOwner; //! The entry-point function called when the thread starts ThreadEntry_t pfEntryPoint; //! Pointer to the argument passed into the thread's entrypoint void *pvArg; #if KERNEL_USE_QUANTUM //! Thread_t quantum (in milliseconds) K_USHORT usQuantum; #endif #if KERNEL_USE_EVENTFLAG //! Event-flag mask K_USHORT usFlagMask; //! Event-flag mode EventFlagOperation_t eFlagMode; #endif #if KERNEL_USE_TIMEOUTS || KERNEL_USE_SLEEP //! Timer_t used for blocking-object timeouts struct _Timer stTimer; #endif #if KERNEL_USE_TIMEOUTS //! Indicate whether or not a blocking-object timeout has occurred K_BOOL bExpired; #endif }; typedef struct _Thread Thread_t; typedef struct _Timer Timer_t; typedef struct _ThreadList ThreadList_t; #ifdef __cplusplus } #endif #endif
moslevin/Mark3C
kernel/public/writebuf16.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file writebuf16.h \brief Thread_t-safe circular buffer implementation with 16-bit elements */ #ifndef __WRITEBUF16_H__ #define __WRITEBUF16_H__ #include "kerneltypes.h" #include "mark3cfg.h" #if KERNEL_USE_DEBUG && !KERNEL_AWARE_SIMULATION #ifdef __cplusplus extern "C" { #endif struct _WriteBuffer16; //--------------------------------------------------------------------------- /*! Function pointer type used to define a callback handler for when the circular buffer reaches 50% capacity, */ typedef void (*WriteBufferCallback)( K_USHORT *pusData_, K_USHORT usSize_ ); //--------------------------------------------------------------------------- /*! * \brief The _WriteBuffer16 struct * * This object is used to provide a general-purpose, fully thread-safe circular * buffer implementation which can be used for creating tracebuffers, data * logging queues, transaction queues, etc. We use it for implementing * a debug print journal. */ struct _WriteBuffer16 { K_USHORT *pusData; //!< Pointer to the circular buffer data volatile K_USHORT usSize; //!< Size of the buffer volatile K_USHORT usHead; //!< Current head element (where data is written) volatile K_USHORT usTail; //!< Current tail element (where data is read) WriteBufferCallback pfCallback; //!< Buffer callback function }; typedef struct _WriteBuffer16 WriteBuffer16_t; //--------------------------------------------------------------------------- /*! \fn void WriteBuffer16_SetBuffers( K_USHORT *pusData_, K_USHORT usSize_ ) Assign the data to be used as storage for this circular buffer \param pstBuffer_ Pointer to the WriteBuffer16 context \param pusData_ Pointer to the array of data to be managed as a circular buffer by this object. \param usSize_ Size of the buffer in 16-bit elements */ void WriteBuffer16_SetBuffers( WriteBuffer16_t *pstBuffer_, K_USHORT *pusData_, K_USHORT usSize_ ); //--------------------------------------------------------------------------- /*! \fn void WriteBuffer16_SetCallback( WriteBufferCallback pfCallback_ ) Set the callback function to be called when the buffer hits 50% of its capacity, and again when the buffer rolls over completely. \param pstBuffer_ Pointer to the WriteBuffer16 context \param pfCallback_ Function pointer to call whenever the buffer has reached 50% capacity, or has rolled over completely. */ void WriteBuffer16_SetCallback( WriteBuffer16_t *pstBuffer_, WriteBufferCallback pfCallback_ ); //--------------------------------------------------------------------------- /*! \fn void WriteBuffer16_WriteData( K_USHORT *pusBuf_, K_USHORT usLen_ ) Write an array of values to the circular buffer \param pstBuffer_ Pointer to the WriteBuffer16 context \param pusBuf_ Source data array to write to the circular buffer \param usLen_ Length of the source data array in 16-bit elements */ void WriteBuffer16_WriteData( WriteBuffer16_t *pstBuffer_, K_USHORT *pusBuf_, K_USHORT usLen_ ); //--------------------------------------------------------------------------- /*! \fn void WriteBuffer16_WriteVector( K_USHORT **ppusBuf_, K_USHORT *pusLen_, K_UCHAR ucCount_) Write a multi-part vector to the circular buffer \param pstBuffer_ Pointer to the WriteBuffer16 context \param ppusBuf_ Pointer to the array of source data pointers \param pusLen_ Array of buffer lengths \param ucCount_ Number of source-data arrays to write to the buffer */ void WriteBuffer16_WriteVector( WriteBuffer16_t *pstBuffer_, K_USHORT **ppusBuf_, K_USHORT *pusLen_, K_UCHAR ucCount_); #ifdef __cplusplus } #endif #endif #endif
moslevin/Mark3C
kernel/timerscheduler.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file timerscheduler.cpp \brief Timer_t scheduler definition */ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #include "timer.h" #include "timerlist.h" #include "timerscheduler.h" //--------------------------------------------------------------------------- void TimerScheduler_Init( void ) { TimerList_Init( ); } //--------------------------------------------------------------------------- void TimerScheduler_Add( Timer_t *pstListNode_ ) { TimerList_Add( pstListNode_ ); } //--------------------------------------------------------------------------- void TimerScheduler_Remove( Timer_t *pstListNode_ ) { TimerList_Remove( pstListNode_ ); } //--------------------------------------------------------------------------- void TimerScheduler_Process( void ) { TimerList_Process( ); }
moslevin/Mark3C
tests/unit/ut_mailbox/ut_mailbox.c
<reponame>moslevin/Mark3C /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ //--------------------------------------------------------------------------- #include "kerneltypes.h" #include "kernel.h" #include "../ut_platform.h" #include "mark3.h" #include "memutil.h" #include "mailbox.h" //=========================================================================== // Local Defines //=========================================================================== static Thread_t stMBoxThread; static K_WORD akMBoxStack[160]; static MailBox_t stMBox; static K_UCHAR aucMBoxBuffer[128]; static volatile K_UCHAR aucTxBuf[17] = "abcdefghijklmnop"; //allocate a byte of slack for null-termination static volatile K_UCHAR aucRxBuf[16]; static volatile bool exit_flag; //=========================================================================== // Define Test Cases Here //=========================================================================== void mbox_test(void *unused_) { while(1) { MailBox_Receive( &stMBox, (void*)aucRxBuf); } } TEST(mailbox_blocking_receive) { MailBox_Init( &stMBox, (void*)aucMBoxBuffer, 128, 16); Thread_Init( &stMBoxThread, akMBoxStack, 160, 7, mbox_test, 0); Thread_Start( &stMBoxThread ) ; int i, j; for (i = 0; i < 100; i++) { EXPECT_TRUE(MailBox_Send( &stMBox, (void*)aucTxBuf)); EXPECT_TRUE( MemUtil_CompareMemory((void*)aucRxBuf, (void*)aucTxBuf, 16) ); for (j = 0; j < 16; j++) { aucTxBuf[j]++; } } Thread_Exit( &stMBoxThread ); } TEST_END volatile K_USHORT usTimeouts = 0; void mbox_timed_test(void *param) { usTimeouts = 0; exit_flag = false; while(!exit_flag) { if (!MailBox_TimedReceive( &stMBox, (void*)aucRxBuf, 10)) { // KernelAware_Trace(0,0, usTimeouts); usTimeouts++; } else { // KernelAware_Trace(0,0, 1337); usTimeouts = usTimeouts; } } Thread_Exit( &stMBoxThread ); } TEST(mailbox_blocking_timed) { usTimeouts = 0; MailBox_Init( &stMBox, (void*)aucMBoxBuffer, 128, 16); Thread_Init( &stMBoxThread, akMBoxStack, 160, 7, mbox_timed_test, (void*)&usTimeouts); Thread_Start( &stMBoxThread ); int i,j; for (j = 0; j < 16; j++) { aucTxBuf[j] = 'x'; } Thread_Sleep(109); EXPECT_EQUALS(usTimeouts, 10); // KernelAware_Trace(0,0, usTimeouts); for (i = 0; i < 10; i++) { EXPECT_TRUE(MailBox_Send( &stMBox, (void*)aucTxBuf)); EXPECT_TRUE( MemUtil_CompareMemory((void*)aucRxBuf, (void*)aucTxBuf, 16) ); for (j = 0; j < 16; j++) { aucTxBuf[j]++; } Thread_Sleep(5); } exit_flag = true; Thread_Sleep(100); } TEST_END TEST(mailbox_send_recv) { MailBox_Init( &stMBox, (void*)aucMBoxBuffer, 128, 16); int i,j; for (i = 0; i < 8; i++) { EXPECT_TRUE(MailBox_Send( &stMBox, (void*)aucTxBuf)); for (j = 0; j < 16; j++) { aucTxBuf[j]++; } } EXPECT_FALSE(MailBox_Send( &stMBox, (void*)aucTxBuf)); for (i = 0; i < 8; i++) { MailBox_Receive( &stMBox, (void*)aucRxBuf); for (j = 0; j < 16; j++) { aucTxBuf[j]--; } EXPECT_TRUE( MemUtil_CompareMemory((void*)aucRxBuf, (void*)aucTxBuf, 16) ); } EXPECT_FALSE(MailBox_TimedReceive( &stMBox, (void*)aucRxBuf, 10)); } TEST_END void mbox_recv_test(void *unused) { exit_flag = false; while(!exit_flag) { MailBox_TimedReceive( &stMBox, (void*)aucRxBuf, 10); } Thread_Exit( &stMBoxThread ); } TEST(mailbox_send_blocking) { usTimeouts = 0; MailBox_Init( &stMBox, (void*)aucMBoxBuffer, 128, 16); Thread_Init( &stMBoxThread, akMBoxStack, 160, 7, mbox_recv_test, (void*)&usTimeouts); int i, j; for (j = 0; j < 16; j++) { aucTxBuf[j] = 'x'; } for (i = 0; i < 8; i++) { MailBox_Send( &stMBox, (void*)aucTxBuf); } for (i = 0; i < 10; i++) { EXPECT_FALSE(MailBox_TimedSend( &stMBox, (void*)aucTxBuf, 20)); } Thread_Start( &stMBoxThread ) ; for (i = 0; i < 10; i++) { EXPECT_TRUE(MailBox_TimedSend( &stMBox, (void*)aucTxBuf, 20)); } exit_flag = true; Thread_Sleep(100); } TEST_END //=========================================================================== // Test Whitelist Goes Here //=========================================================================== TEST_CASE_START TEST_CASE(mailbox_send_recv), TEST_CASE(mailbox_blocking_receive), TEST_CASE(mailbox_blocking_timed), TEST_CASE(mailbox_send_blocking), TEST_CASE_END
moslevin/Mark3C
examples/avr/lab8_messages/main.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ #include "mark3.h" /*=========================================================================== Lab Example 8: Using messages for IPC. In this example, we present a typical asynchronous producer/consumer pattern using Mark3's message-driven IPC. Lessons covered in this example include: - Use of Message and MessageQueue objects to send data between threads - Use of GlobalMessagePool to allocate and free message objects Takeaway: Unlike cases presented in previous examples that relied on semaphores or event flags, messages carry substantial context, specified in its "code" and "data" members. This mechanism can be used to pass data between threads extremely efficiently, with a simple and flexible API. Any number of threads can write to/block on a single message queue, which give this method of IPC even more flexibility. ===========================================================================*/ //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP1_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp1Thread; static K_WORD awApp1Stack[APP1_STACK_SIZE]; static void App1Main(void *unused_); //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP2_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp2Thread; static K_WORD awApp2Stack[APP2_STACK_SIZE]; static void App2Main(void *unused_); //--------------------------------------------------------------------------- static MessageQueue_t stMsgQ; //--------------------------------------------------------------------------- int main(void) { // See the annotations in previous labs for details on init. Kernel_Init(); Thread_Init( &stApp1Thread, awApp1Stack, APP1_STACK_SIZE, 1, App1Main, 0); Thread_Init( &stApp2Thread, awApp2Stack, APP2_STACK_SIZE, 1, App2Main, 0); Thread_Start( &stApp1Thread ); Thread_Start( &stApp2Thread ); MessageQueue_Init( &stMsgQ ); Kernel_Start(); return 0; } //--------------------------------------------------------------------------- void App1Main(void *unused_) { K_USHORT usData = 0; while(1) { // This thread grabs a message from the global message pool, sets a // code-value and the message data pointer, then sends the message to // a message queue object. Another thread (Thread2) is blocked, waiting // for a message to arrive in the queue. // Get the message object Message_t *pstMsg = GlobalMessagePool_Pop(); // Set the message object's data (contrived in this example) Message_SetCode( pstMsg, 0x1337); usData++; Message_SetData( pstMsg, &usData); // Send the message to the shared message queue MessageQueue_Send( &stMsgQ, pstMsg); // Wait before sending another message. Thread_Sleep(20); } } //--------------------------------------------------------------------------- void App2Main(void *unused_) { while(1) { // This thread waits until it receives a message on the shared global // message queue. When it gets the message, it prints out information // about the message's code and data, before returning the messaage object // back to the global message pool. In a more practical application, // the user would typically use the code to tell the receiving thread // what kind of message was sent, and what type of data to expect in the // data field. // Wait for a message to arrive on the specified queue. Note that once // this thread receives the message, it is "owned" by the thread, and // must be returned back to its source message pool when it is no longer // needed. Message_t *pstMsg = MessageQueue_Receive( &stMsgQ ); // We received a message, now print out its information KernelAware_Print("Received Message\n"); KernelAware_Trace1(0, __LINE__, Message_GetCode( pstMsg ), *((K_USHORT*)Message_GetData( pstMsg ))); // Done with the message, return it back to the global message queue. GlobalMessagePool_Push(pstMsg); } }
moslevin/Mark3C
kernel/public/timerscheduler.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file timerscheduler.h \brief Timer_t scheduler declarations */ #ifndef __TIMERSCHEDULER_H__ #define __TIMERSCHEDULER_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #include "timer.h" #include "timerlist.h" #if KERNEL_USE_TIMERS #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- /*! \fn void TimerScheduler_Init() Initialize the timer scheduler. Must be called before any timer, or timer-derived functions are used. */ void TimerScheduler_Init( void ); //--------------------------------------------------------------------------- /*! \fn void TimerScheduler_Add(Timer_t *pstListNode_) Add a timer to the timer scheduler. Adding a timer implicitly starts the timer as well. \param pstListNode_ Pointer to the timer list node to add */ void TimerScheduler_Add( Timer_t *pstListNode_ ); //--------------------------------------------------------------------------- /*! \fn void TimerScheduler_Remove(Timer_t *pstListNode_) Remove a timer from the timer scheduler. May implicitly stop the timer if this is the only active timer scheduled. \param pstListNode_ Pointer to the timer list node to remove */ void TimerScheduler_Remove( Timer_t *pstListNode_ ); //--------------------------------------------------------------------------- /*! \fn void TimerScheduler_Process() This function must be called on timer expiry (from the timer's ISR context). This will result in all timers being updated based on the epoch that just elapsed. The next timer epoch is set based on the next Timer_t object to expire. */ void TimerScheduler_Process( void ); #ifdef __cplusplus } #endif #endif //KERNEL_USE_TIMERS #endif //__TIMERSCHEDULER_H__
moslevin/Mark3C
tests/unit/ut_platform.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ #ifndef __UT_PLATFORM_H__ #define __UT_PLATFORM_H__ #include "mark3.h" #include "kerneltypes.h" #include "kernel.h" #include "unit_test.h" //--------------------------------------------------------------------------- #if KERNEL_USE_IDLE_FUNC #define STACK_SIZE_APP (300) //!< Size of the main app's stack #else #define STACK_SIZE_APP (192) #endif #define STACK_SIZE_IDLE (192) //!< Size of the idle thread stack //--------------------------------------------------------------------------- #define UART_SIZE_RX (12) //!< UART RX Buffer size #define UART_SIZE_TX (12) //!< UART TX Buffer size //--------------------------------------------------------------------------- typedef void (*TestFunc)(void); //--------------------------------------------------------------------------- typedef struct { const K_CHAR *szName; UnitTest_t *pstTestCase; TestFunc pfTestFunc; } MyTestCase; //--------------------------------------------------------------------------- #define TEST(x) \ static UnitTest_t TestObj_##x; \ static void TestFunc_##x(void) \ { \ UnitTest_t *pstCurrent = &TestObj_##x; #define TEST_END \ UnitTest_Complete( pstCurrent ); \ MyUnitTest_PrintTestResult( pstCurrent ); \ } //--------------------------------------------------------------------------- #define EXPECT_TRUE(x) UnitTest_Start( pstCurrent); UnitTest_ExpectTrue(pstCurrent, x) #define EXPECT_FALSE(x) UnitTest_Start( pstCurrent); UnitTest_ExpectFalse(pstCurrent, x) #define EXPECT_EQUALS(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectEquals(pstCurrent, (K_LONG)(x), (K_LONG)(y)) #define EXPECT_GT(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectGreaterThan(pstCurrent, (K_LONG)(x), (K_LONG)(y)) #define EXPECT_LT(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectLessThan(pstCurrent, (K_LONG)(x), (K_LONG)(y)) #define EXPECT_GTE(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectGreaterThanEquals(pstCurrent, (K_LONG)(x), (K_LONG)(y)) #define EXPECT_LTE(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectLessThanEquals(pstCurrent, (K_LONG)(x), (K_LONG)(y)) //--------------------------------------------------------------------------- #define EXPECT_FAIL_TRUE(x) UnitTest_Start( pstCurrent); UnitTest_ExpectFailTrue(pstCurrent, x) #define EXPECT_FAIL_FALSE(x) UnitTest_Start( pstCurrent); UnitTest_ExpectFailFalse(pstCurrent, x) #define EXPECT_FAIL_EQUALS(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectFailEquals(pstCurrent, (K_LONG)(x), (K_LONG)(y)) #define EXPECT_FAIL_GT(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectFailGreaterThan(pstCurrent, (K_LONG)(x), (K_LONG)(y)) #define EXPECT_FAIL_LT(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectFailLessThan(pstCurrent, (K_LONG)(x), (K_LONG)(y)) #define EXPECT_FAIL_GTE(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectFailGreaterThanEquals(pstCurrent, (K_LONG)(x), (K_LONG)(y)) #define EXPECT_FAIL_LTE(x,y) UnitTest_Start( pstCurrent); UnitTest_ExpectFailLessThanEquals(pstCurrent, (K_LONG)(x), (K_LONG)(y)) //--------------------------------------------------------------------------- #define TEST_NAME_EVALUATE(name) #name #define TEST_NAME_STRINGIZE(name) TEST_NAME_EVALUATE(name) //--------------------------------------------------------------------------- #define TEST_CASE_START MyTestCase astTestCases[] = { #define TEST_CASE(x) { TEST_NAME_STRINGIZE(x), &TestObj_##x, TestFunc_##x } #define TEST_CASE_END { 0, 0, 0 } }; //--------------------------------------------------------------------------- extern MyTestCase astTestCases[]; extern void run_tests(); //--------------------------------------------------------------------------- void PrintString(const K_CHAR *szStr_); //--------------------------------------------------------------------------- void MyUnitTest_PrintTestResult( UnitTest_t *pstTest_ ); #endif //__UT_PLATFORM_H__
moslevin/Mark3C
kernel/public/ll.h
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file ll.h \brief Core linked-list declarations, used by all kernel list types At the heart of RTOS data structures are linked lists. Having a robust and efficient set of linked-list types that we can use as a foundation for building the rest of our kernel types allows us to keep our RTOS code efficient and logically-separated. So what data types rely on these linked-list classes? -Threads -ThreadLists -The Scheduler -Timers, -The Timer_t Scheduler -Blocking objects (Semaphores, Mutexes, etc...) Pretty much everything in the kernel uses these linked lists. By having objects inherit from the base linked-list node type, we're able to leverage the double and circular linked-list classes to manager virtually every object type in the system without duplicating code. These functions are very efficient as well, allowing for very deterministic behavior in our code. */ #ifndef __LL_H__ #define __LL_H__ #include "kerneltypes.h" #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- #ifndef NULL #define NULL (0) #endif //--------------------------------------------------------------------------- /*! Basic linked-list node data structure. This data is managed by the linked-list object types, and can be used transparently between them. */ typedef struct _LinkListNode { struct _LinkListNode *next; //!< Pointer to the next node in the list struct _LinkListNode *prev; //!< Pointer to the previous node in the list } LinkListNode_t; //--------------------------------------------------------------------------- /*! \fn void ClearNode() Initialize the linked list node, clearing its next and previous node. */ #define LinkListNode_Clear( pstNode_ ) \ do { \ ((LinkListNode_t *)pstNode_)->next = NULL; \ ((LinkListNode_t *)pstNode_)->prev = NULL; \ } while (0); //--------------------------------------------------------------------------- /*! \fn LinkListNode_t *GetNext(); Returns a pointer to the next node in the list. \return a pointer to the next node in the list. */ #define LinkListNode_GetNext( pstNode_ ) ( ((LinkListNode_t *)pstNode_)->next ) //--------------------------------------------------------------------------- /*! \fn LinkListNode_t *GetPrev(); Returns a pointer to the previous node in the list. \return a pointer to the previous node in the list. */ #define LinkListNode_GetPrev( pstNode_ ) ( ((LinkListNode_t *)pstNode_)->prev ) //--------------------------------------------------------------------------- #define LinkList_Init( pstList_ ) \ { \ ((LinkList_t*)(pstList_))->pstHead = NULL; \ ((LinkList_t*)(pstList_))->pstTail = NULL; \ } #define DoubleLinkList_Init( pstList_ ) (LinkList_Init( ((LinkList_t*)(pstList_) ) )) #define CircularLinkList_Init( pstList_ ) (LinkList_Init( ((LinkList_t*)(pstList_) ) )) //--------------------------------------------------------------------------- /*! \fn LinkListNode_t *GetHead() Get the head node in the linked list \return Pointer to the head node in the list */ #define LinkList_GetHead( pstList_ ) ( ((LinkList_t*)(pstList_))->pstHead ) //--------------------------------------------------------------------------- /*! \fn LinkListNode_t *GetTail() Get the tail node of the linked list \return Pointer to the tail node in the list */ #define LinkList_GetTail( pstList_ ) ( ((LinkList_t*)(pstList_))->pstTail ) //--------------------------------------------------------------------------- /*! Abstract-data-type from which all other linked-lists are derived */ typedef struct _LinkList { LinkListNode_t *pstHead; //!< Pointer to the head node in the list LinkListNode_t *pstTail; //!< Pointer to the tail node in the list } LinkList_t; //--------------------------------------------------------------------------- /*! Doubly-linked-list data type, inherited from the base LinkList_t type. */ typedef struct _DoubleLinkList { LinkListNode_t *pstHead; //!< Pointer to the head node in the list LinkListNode_t *pstTail; //!< Pointer to the tail node in the list } DoubleLinkList_t; //--------------------------------------------------------------------------- /*! \fn void Add(LinkListNode_t *node_) Add the linked list node to this linked list \param node_ Pointer to the node to add */ void DoubleLinkList_Add( DoubleLinkList_t *pstList_, LinkListNode_t *node_ ); //--------------------------------------------------------------------------- /*! \fn void Remove(LinkListNode_t *node_) Add the linked list node to this linked list \param node_ Pointer to the node to remove */ void DoubleLinkList_Remove( DoubleLinkList_t *pstList_, LinkListNode_t *node_ ); //--------------------------------------------------------------------------- /*! Circular-linked-list data type, inherited from the base LinkList_t type. */ typedef struct _CircularLinkList { LinkListNode_t *pstHead; //!< Pointer to the head node in the list LinkListNode_t *pstTail; //!< Pointer to the tail node in the list } CircularLinkList_t; //--------------------------------------------------------------------------- /*! \fn void Add(LinkListNode_t *node_) Add the linked list node to this linked list \param node_ Pointer to the node to add */ void CircularLinkList_Add( CircularLinkList_t *pstList_, LinkListNode_t *node_); //--------------------------------------------------------------------------- /*! \fn void Remove(LinkListNode_t *node_) Add the linked list node to this linked list \param node_ Pointer to the node to remove */ void CircularLinkList_Remove( CircularLinkList_t *pstList_, LinkListNode_t *node_); //--------------------------------------------------------------------------- /*! \fn void PivotForward() Pivot the head of the circularly linked list forward ( Head = Head->next, Tail = Tail->next ) */ void CircularLinkList_PivotForward( CircularLinkList_t *pstList_ ); //--------------------------------------------------------------------------- /*! \fn void PivotBackward() Pivot the head of the circularly linked list backward ( Head = Head->prev, Tail = Tail->prev ) */ void CircularLinkList_PivotBackward( CircularLinkList_t *pstList_ ); #ifdef __cplusplus } #endif #endif
moslevin/Mark3C
kernel/public/kerneldebug.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kerneldebug.h \brief Macros and functions used for assertions, kernel traces, etc. */ #ifndef __KERNEL_DEBUG_H__ #define __KERNEL_DEBUG_H__ #include "debugtokens.h" #include "mark3cfg.h" #include "tracebuffer.h" #include "kernelaware.h" #include "paniccodes.h" #include "kernel.h" //--------------------------------------------------------------------------- #if (KERNEL_USE_DEBUG && !KERNEL_AWARE_SIMULATION) //--------------------------------------------------------------------------- #define __FILE_ID__ STR_UNDEFINED //!< File ID used in kernel trace calls //--------------------------------------------------------------------------- #define KERNEL_TRACE( x ) \ { \ K_USHORT ausMsg__[5]; \ ausMsg__[0] = 0xACDC; \ ausMsg__[1] = __FILE_ID__; \ ausMsg__[2] = __LINE__; \ ausMsg__[3] = TraceBuffer_Increment() ; \ ausMsg__[4] = (K_USHORT)(x) ; \ TraceBuffer_Write(ausMsg__, 5); \ }; //--------------------------------------------------------------------------- #define KERNEL_TRACE_1( x, arg1 ) \ { \ K_USHORT ausMsg__[6]; \ ausMsg__[0] = 0xACDC; \ ausMsg__[1] = __FILE_ID__; \ ausMsg__[2] = __LINE__; \ ausMsg__[3] = TraceBuffer_Increment(); \ ausMsg__[4] = (K_USHORT)(x); \ ausMsg__[5] = arg1; \ TraceBuffer_Write(ausMsg__, 6); \ } //--------------------------------------------------------------------------- #define KERNEL_TRACE_2( x, arg1, arg2 ) \ { \ K_USHORT ausMsg__[7]; \ ausMsg__[0] = 0xACDC; \ ausMsg__[1] = __FILE_ID__; \ ausMsg__[2] = __LINE__; \ ausMsg__[3] = TraceBuffer_Increment(); \ ausMsg__[4] = (K_USHORT)(x); \ ausMsg__[5] = arg1; \ ausMsg__[6] = arg2; \ TraceBuffer_Write(ausMsg__, 7); \ } //--------------------------------------------------------------------------- #define KERNEL_ASSERT( x ) \ { \ if( ( x ) == false ) \ { \ K_USHORT ausMsg__[5]; \ ausMsg__[0] = 0xACDC; \ ausMsg__[1] = __FILE_ID__; \ ausMsg__[2] = __LINE__; \ ausMsg__[3] = TraceBuffer_Increment(); \ ausMsg__[4] = STR_ASSERT_FAILED; \ TraceBuffer_Write(ausMsg__, 5); \ Kernel_Panic(PANIC_ASSERT_FAILED); \ } \ } #elif (KERNEL_USE_DEBUG && KERNEL_AWARE_SIMULATION) //--------------------------------------------------------------------------- #define __FILE_ID__ STR_UNDEFINED //--------------------------------------------------------------------------- #define KERNEL_TRACE( x ) \ { \ KernelAware_Trace( __FILE_ID__, __LINE__, x ); \ }; //--------------------------------------------------------------------------- #define KERNEL_TRACE_1( x, arg1 ) \ { \ KernelAware_Trace1( __FILE_ID__, __LINE__, x, arg1 ); \ } //--------------------------------------------------------------------------- #define KERNEL_TRACE_2( x, arg1, arg2 ) \ { \ KernelAware_Trace2( __FILE_ID__, __LINE__, x, arg1, arg2 ); \ } //--------------------------------------------------------------------------- #define KERNEL_ASSERT( x ) \ { \ if( ( x ) == false ) \ { \ KernelAware_Trace( __FILE_ID__, __LINE__, STR_ASSERT_FAILED ); \ Kernel_Panic( PANIC_ASSERT_FAILED ); \ } \ } #else //--------------------------------------------------------------------------- // Note -- when kernel-debugging is disabled, we still have to define the // macros to ensure that the expressions compile (albeit, by elimination // during pre-processing). //--------------------------------------------------------------------------- #define __FILE_ID__ 0 //!< Null ID //--------------------------------------------------------------------------- #define KERNEL_TRACE( x ) //!< Null Kernel Trace Macro //--------------------------------------------------------------------------- #define KERNEL_TRACE_1( x, arg1 ) //!< Null Kernel Trace Macro //--------------------------------------------------------------------------- #define KERNEL_TRACE_2( x, arg1, arg2 ) //!< Null Kernel Trace Macro //--------------------------------------------------------------------------- #define KERNEL_ASSERT( x ) //!< Null Kernel Assert Macro #endif // KERNEL_USE_DEBUG #endif
moslevin/Mark3C
kernel/public/blocking.h
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file blocking.h \brief Blocking object base object declarations A Blocking object in Mark3 is essentially a thread list. Any blocking object implementation (being a Semaphore_t, Mutex_t, event flag, etc.) can be built on top of this object, utilizing the provided functions to manipulate thread location within the Kernel. Blocking a thread results in that thread becoming de-scheduled, placed in the blocking object's own private list of threads which are waiting on the object. Unblocking a thread results in the reverse: The thread is moved back to its original location from the blocking list. The only difference between a blocking object based on this object is the logic used to determine what consitutes a Block or Unblock condition. For instance, a Semaphore_t Pend operation may result in a call to the Block() method with the currently-executing thread in order to make that thread wait for a Semaphore_t Post. That operation would then invoke the UnBlock() method, removing the blocking thread from the Semaphore_t's list, and back into the the appropriate thread inside the scheduler. Care must be taken when implementing blocking objects to ensure that critical sections are used judiciously, otherwise asynchronous events like timers and interrupts could result in non-deterministic and often catastrophic behavior. */ #ifndef __BLOCKING_H__ #define __BLOCKING_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #include "threadlist.h" #include "thread.h" #if KERNEL_USE_MUTEX || KERNEL_USE_SEMAPHORE || KERNEL_USE_EVENTFLAG #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- /*! Class implementing thread-blocking primatives. Used for implementing things like semaphores, mutexes, message queues, or anything else that could cause a thread to suspend execution on some external stimulus. */ //--------------------------------------------------------------------------- /*! \fn void BlockingObject_Block(Thread_t *pstThread_); \param pstList_ Pointer to the threadlist associated with the blocking object, that will receive the thread as a result of the operation. \param pstThread_ Pointer to the thread object that will be blocked. Blocks a thread on this object. This is the fundamental operation performed by any sort of blocking operation in the operating system. All semaphores/mutexes/sleeping/messaging/etc ends up going through the blocking code at some point as part of the code that manages a transition from an "active" or "waiting" thread to a "blocked" thread. The steps involved in blocking a thread (which are performed in the function itself) are as follows; 1) Remove the specified thread from the current owner's list (which is likely one of the scheduler's thread lists) 2) Add the thread to this object's thread list 3) Setting the thread's "current thread-list" point to reference this object's threadlist. */ void BlockingObject_Block( ThreadList_t *pstList_, Thread_t *pstThread_ ); //--------------------------------------------------------------------------- /*! \fn void BlockingObject_UnBlock(Thread_t *pstThread_) \param pstThread_ Pointer to the thread to unblock. Unblock a thread that is already blocked on this object, returning it to the "ready" state by performing the following steps: 1) Removing the thread from this object's threadlist 2) Restoring the thread to its "original" owner's list */ void BlockingObject_UnBlock( Thread_t *pstThread_); #ifdef __cplusplus } #endif #endif #endif
moslevin/Mark3C
examples/avr/lab9_dynamic_threads/main.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ #include "mark3.h" /*=========================================================================== Lab Example 9: Dynamic Threading Lessons covered in this example include: - Creating, pausing, and destorying dynamically-created threads at runtime Takeaway: In addition to being able to specify a static set of threads during system initialization, Mark3 gives the user the ability to create and manipulate threads at runtime. These threads can act as "temporary workers" that can be activated when needed, without impacting the responsiveness of the rest of the application. ===========================================================================*/ //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP1_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp1Thread; static K_WORD awApp1Stack[APP1_STACK_SIZE]; static void App1Main(void *unused_); //--------------------------------------------------------------------------- // This block declares the thread stack data for a thread that we'll create // dynamically. #define APP2_STACK_SIZE (320/sizeof(K_WORD)) static K_WORD awApp2Stack[APP2_STACK_SIZE]; //--------------------------------------------------------------------------- int main(void) { // See the annotations in previous labs for details on init. Kernel_Init(); Thread_Init( &stApp1Thread, awApp1Stack, APP1_STACK_SIZE, 1, App1Main, 0); Thread_Start( &stApp1Thread ); Kernel_Start(); return 0; } //--------------------------------------------------------------------------- static void WorkerMain1(void *arg_) { Semaphore_t *pstSem = (Semaphore_t*)arg_; K_ULONG ulCount = 0; // Do some work. Post a semaphore to notify the other thread that the // work has been completed. while (ulCount < 10000) { ulCount++; } KernelAware_Print( "Worker1 -- Done Work\n"); Semaphore_Post( pstSem ); // Work is completed, just spin now. Let another thread destory us. while(1) { } } //--------------------------------------------------------------------------- static void WorkerMain2(void *arg_) { K_ULONG ulCount = 0; while (ulCount < 10000) { ulCount++; } KernelAware_Print( "Worker2 -- Done Work\n"); // A dynamic thread can self-terminate as well: Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- void App1Main(void *unused_) { Thread_t stMyThread; Semaphore_t stMySem; Semaphore_Init( &stMySem, 0,1); while (1) { // Example 1 - create a worker thread at our current priority in order to // parallelize some work. Thread_Init( &stMyThread, awApp2Stack, APP2_STACK_SIZE, 1, WorkerMain1, (void*)&stMySem ); Thread_Start( &stMyThread ); // Do some work of our own in parallel, while the other thread works on its project. K_ULONG ulCount = 0; while (ulCount < 10000) { ulCount++; } KernelAware_Print( "Thread -- Done Work\n" ); // Wait for the other thread to finish its job. Semaphore_Pend( &stMySem ); // Once the thread has signalled us, we can safely call "Exit" on the thread to // remove it from scheduling and recycle it later. Thread_Exit( &stMyThread ); // Spin the thread up again to do something else in parallel. This time, the thread // will run completely asynchronously to this thread. Thread_Init( &stMyThread, awApp2Stack, APP2_STACK_SIZE, 1, WorkerMain2, 0 ); Thread_Start( &stMyThread ); ulCount = 0; while (ulCount < 10000) { ulCount++; } KernelAware_Print( "Thread -- Done Work\n" ); // Check that we're sure the worker thread has terminated before we try running the // test loop again. while (Thread_GetState( &stMyThread ) != THREAD_STATE_EXIT) { } KernelAware_Print (" Test Done\n"); Thread_Sleep(100); } }
moslevin/Mark3C
tests/unit/unit_test.h
<reponame>moslevin/Mark3C<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file unit_test.h \brief Unit test object declarations */ #ifndef __UNIT_TEST_H__ #define __UNIT_TEST_H__ #include "kerneltypes.h" typedef struct { const K_CHAR *szName; //!< Name of the tests performed bool bIsActive; //!< Whether or not the test is active K_UCHAR bComplete; //!< Whether or not the test is complete bool bStatus; //!< Status of the last-run test K_USHORT usIterations; //!< Number of iterations executed K_USHORT usPassed; //!< Number of iterations that have passed } UnitTest_t; //--------------------------------------------------------------------------- void UnitTest_Init( UnitTest_t *pstTest_ ); //--------------------------------------------------------------------------- /*! \fn void SetName( const K_CHAR *szName_ ) Set the name of the test object \param szName_ Name of the tests associated with this object */ void UnitTest_SetName( UnitTest_t *pstTest_, const K_CHAR *szName_ ); //--------------------------------------------------------------------------- /*! \fn void Start() Start a new test iteration. */ void UnitTest_Start( UnitTest_t *pstTest_ ); //--------------------------------------------------------------------------- /*! \fn void Pass() Stop the current iteration (if started), and register that the test was successful. */ void UnitTest_Pass( UnitTest_t *pstTest_ ); //--------------------------------------------------------------------------- /*! \fn void Fail(); Stop the current iterations (if started), and register that the current test failed. */ void UnitTest_Fail( UnitTest_t *pstTest_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectTrue( UnitTest_t *pstTest_, bool bExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectFalse( UnitTest_t *pstTest_, bool bExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectFailTrue( UnitTest_t *pstTest_, bool bExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectFailFalse( UnitTest_t *pstTest_, bool bExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectFailEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectGreaterThan( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectLessThan( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectGreaterThanEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectLessThanEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectFailGreaterThan( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectFailLessThan( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectFailGreaterThanEquals(UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- void UnitTest_ExpectFailLessThanEquals( UnitTest_t *pstTest_, K_LONG lVal_, K_LONG lExpression_ ); //--------------------------------------------------------------------------- /*! \fn void Complete() Complete the test. Once a test has been completed, no new iterations can be started (i.e Start()/Pass()/Fail() will have no effect). */ void UnitTest_Complete( UnitTest_t *pstTest_ ); //--------------------------------------------------------------------------- /*! \fn const K_CHAR *GetName() Get the name of the tests associated with this object \return Name of the test */ const K_CHAR *UnitTest_GetName(UnitTest_t *pstTest_); //--------------------------------------------------------------------------- /*! \fn bool GetResult() Return the result of the last test \return Status of the last run test (false = fail, true = pass) */ bool UnitTest_GetResult(UnitTest_t *pstTest_); //--------------------------------------------------------------------------- /*! \fn K_USHORT GetPassed() Return the total number of test points/iterations passed \return Count of all successful test points/iterations */ K_USHORT UnitTest_GetPassed(UnitTest_t *pstTest_); //--------------------------------------------------------------------------- /*! \fn K_USHORT GetFailed() Return the number of failed test points/iterations \return Failed test point/iteration count */ K_USHORT UnitTest_GetFailed(UnitTest_t *pstTest_); //--------------------------------------------------------------------------- /*! \fn K_USHORT GetTotal() Return the total number of iterations/test-points executed \return Total number of ierations/test-points executed */ K_USHORT UnitTest_GetTotal(UnitTest_t *pstTest_); #endif
moslevin/Mark3C
tests/unit/ut_message/ut_message.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ //--------------------------------------------------------------------------- #include "kerneltypes.h" #include "kernel.h" #include "../ut_platform.h" #include "message.h" #include "thread.h" static Thread_t stMsgThread; #define MSG_STACK_SIZE (192) static K_WORD aucMsgStack[MSG_STACK_SIZE]; static MessageQueue_t stMsgQ; static volatile K_UCHAR ucPassCount = 0; //=========================================================================== // Local Defines //=========================================================================== void MsgConsumer(void *unused_) { Message_t *pstMsg; K_UCHAR i; for (i = 0; i < 20; i++) { pstMsg = MessageQueue_Receive( &stMsgQ ); ucPassCount = 0; if (pstMsg) { ucPassCount++; } else { ucPassCount = 0; continue; } switch(i) { case 0: if (0 == Message_GetCode( pstMsg )) { ucPassCount++; } if (0 == Message_GetData( pstMsg )) { ucPassCount++; } break; case 1: if (1337 == (Message_GetCode( pstMsg )) ) { ucPassCount++; } if (7331 == (K_USHORT)(Message_GetData( pstMsg ))) { ucPassCount++; } case 2: if (0xA0A0== (Message_GetCode( pstMsg )) ) { ucPassCount++; } if (0xC0C0 == (K_USHORT)(Message_GetData( pstMsg ))) { ucPassCount++; } break; default: break; } GlobalMessagePool_Push(pstMsg); } } //=========================================================================== // Define Test Cases Here //=========================================================================== TEST(ut_message_tx_rx) { // Test - verify that we can use a message queue object to send data // from one thread to another, and that the receiver can block on the // message queue. This test also relies on priority scheduling working // as expected. Message_t *pstMsg; Thread_Init( &stMsgThread, aucMsgStack, MSG_STACK_SIZE, 7, MsgConsumer, 0); MessageQueue_Init( &stMsgQ ); Thread_Start( &stMsgThread ); // Get a message from the pool pstMsg = GlobalMessagePool_Pop(); EXPECT_FAIL_FALSE( pstMsg ); // Send the message to the consumer thread Message_SetData( pstMsg, NULL ); Message_SetCode( pstMsg, 0 ); MessageQueue_Send( &stMsgQ, pstMsg ); EXPECT_EQUALS(ucPassCount, 3); pstMsg = GlobalMessagePool_Pop(); EXPECT_FAIL_FALSE( pstMsg ); // Send the message to the consumer thread Message_SetCode( pstMsg, 1337); Message_SetData( pstMsg, (void*)7331); MessageQueue_Send( &stMsgQ, pstMsg); EXPECT_EQUALS(ucPassCount, 3); pstMsg = GlobalMessagePool_Pop(); EXPECT_FAIL_FALSE( pstMsg ); // Send the message to the consumer thread Message_SetCode( pstMsg, 0xA0A0 ); Message_SetData( pstMsg, (void*)0xC0C0 ); MessageQueue_Send( &stMsgQ, pstMsg ); EXPECT_EQUALS(ucPassCount, 3); Thread_Exit( &stMsgThread ); } TEST_END //=========================================================================== TEST(ut_message_exhaust) { // Test - exhaust the global message pool and ensure that we eventually // get "NULL" returned when the pool is depleted, and not some other // unexpected condition/system failure. int i; for ( i = 0; i < GLOBAL_MESSAGE_POOL_SIZE; i++) { EXPECT_FAIL_FALSE( GlobalMessagePool_Pop() ); } EXPECT_FALSE( GlobalMessagePool_Pop()); // Test is over - re-init the pool.. GlobalMessagePool_Init(); } TEST_END static volatile K_BOOL bTimedOut = false; //=========================================================================== void MsgTimed(void *unused) { Message_t *pstRet; ucPassCount = 0; pstRet = MessageQueue_TimedReceive( &stMsgQ, 10); if (0 == pstRet) { ucPassCount++; } else { GlobalMessagePool_Push(pstRet); } pstRet = MessageQueue_TimedReceive( &stMsgQ, 1000); if (0 != pstRet) { ucPassCount++; } else { GlobalMessagePool_Push(pstRet); } while(1) { pstRet = MessageQueue_Receive( &stMsgQ ); GlobalMessagePool_Push(pstRet); } } //=========================================================================== TEST(ut_message_timed_rx) { Message_t *pstMsg; pstMsg = GlobalMessagePool_Pop(); EXPECT_FAIL_FALSE( pstMsg ); // Send the message to the consumer thread Message_SetData( pstMsg, NULL ); Message_SetCode( pstMsg, 0); // Test - Verify that the timed blocking in the message queues works Thread_Init( &stMsgThread, aucMsgStack, MSG_STACK_SIZE, 7, MsgTimed, 0); Thread_Start( &stMsgThread ); // Just let the timeout expire Thread_Sleep(11); EXPECT_EQUALS( ucPassCount, 1 ); // other thread has a timeout set... Don't leave them waiting! MessageQueue_Send( &stMsgQ, pstMsg ); EXPECT_EQUALS( ucPassCount, 2 ); MessageQueue_Send( &stMsgQ, pstMsg ); Thread_Exit( &stMsgThread ); } TEST_END //=========================================================================== // Test Whitelist Goes Here //=========================================================================== TEST_CASE_START TEST_CASE(ut_message_tx_rx), TEST_CASE(ut_message_exhaust), TEST_CASE(ut_message_timed_rx), TEST_CASE_END
moslevin/Mark3C
kernel/cpu/avr/atmega328p/gcc/kernelswi.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernelswi.cpp \brief Kernel Software interrupt implementation for ATMega328p */ #include "kerneltypes.h" #include "kernelswi.h" #include <avr/io.h> #include <avr/interrupt.h> //--------------------------------------------------------------------------- void KernelSWI_Config(void) { PORTD &= ~0x04; // Clear INT0 DDRD |= 0x04; // Set PortD, bit 2 (INT0) As Output EICRA |= (1 << ISC00) | (1 << ISC01); // Rising edge on INT0 } //--------------------------------------------------------------------------- void KernelSWI_Start(void) { EIFR &= ~(1 << INTF0); // Clear any pending interrupts on INT0 EIMSK |= (1 << INT0); // Enable INT0 interrupt (as K_LONG as I-bit is set) } //--------------------------------------------------------------------------- void KernelSWI_Stop(void) { EIMSK &= ~(1 << INT0); // Disable INT0 interrupts } //--------------------------------------------------------------------------- K_UCHAR KernelSWI_DI() { K_BOOL bEnabled = ((EIMSK & (1 << INT0)) != 0); EIMSK &= ~(1 << INT0); return bEnabled; } //--------------------------------------------------------------------------- void KernelSWI_RI(K_BOOL bEnable_) { if (bEnable_) { EIMSK |= (1 << INT0); } else { EIMSK &= ~(1 << INT0); } } //--------------------------------------------------------------------------- void KernelSWI_Clear(void) { EIFR &= ~(1 << INTF0); // Clear the interrupt flag for INT0 } //--------------------------------------------------------------------------- void KernelSWI_Trigger(void) { //if(Thread_IsSchedulerEnabled()) { PORTD &= ~0x04; PORTD |= 0x04; } }
moslevin/Mark3C
bootloader/bootloader.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file bootloader.c \brief atmega328p Bootloader \page BOOTLOAD1 The Mark3 Bootloader The Mark3 bootloader module implements a custom FunkenSlip-encoded bootloader, which fits in a 1KB bootloader block. FunkenSlip encoding is used by Mark2 to provide a robust, common, and standards-based communications protocol for host-to-target interaction. Why use FunkenSlip encoding? -It's packet-driven. As a result, the host utility and the target device can work together, producing fast, bullet-proof loads. -FunkenSlip encoding is similar to many popular programming formats, and as a result it's easy to use as a generic abstraction for intel hex, S-records, etc. -Each packet is terminated with a special end-of-packet character, which makes it especially easy to parse and decode. -Each packet contains framing information (channel ID, message size, and CRC16) which makes data easy to validate. -Only devices supporting the Flash-write channel will respond to requests to write the flash. -It's lightweight - we can fit our whole bootloader in under 1KB of code. Bootloader implementation: On bootup, we disable interrupts and configure the serial port in busy- read/write mode. We then wait a few seconds to see whether or not a client utility is going to try and flash the device. If we receive the proper framing messages, we will enter bootloader mode; at which point we will wait for packets until we recieve an EOF message from the host flashing utility. If no attempt to communicate with the bootloader is made in the first few seconds, the bootloader will exit, attempting to jump to the main application. In the event that there is no main application, the device will jump right back to the bootloader. Once in bootloader mode, we wait on FunkenSlip encoded packets. These can be used to either SEEK to a new address in flash, WRITE a packet of data to the current flash location, or commit remaining data and reboot to the newly-flashed application on EOF. In the event of an error, an error is returned to the host application via the UART, and corrective action can be attempted. However, in most cases, it's probably easiest to reboot the device and attempt to re-flash. In this implementation, the device always enters the bootloader - there is no special bit that must be held before the bootloader will be invoked. While this adds delay, the convenience of always being able to access the bootloader is certainly a benefit during development. */ /*-------------------------------------------------------------------------*/ #include <avr/io.h> #include <avr/interrupt.h> #include <avr/boot.h> #include <avr/wdt.h> /*-------------------------------------------------------------------------*/ /*! generic types/defines used throughout the bootloader */ /*-------------------------------------------------------------------------*/ #define K_UCHAR unsigned char #define K_USHORT unsigned short #define K_ULONG unsigned long #define K_BOOL unsigned char #define K_TRUE 1 #define K_FALSE 0 /*-------------------------------------------------------------------------*/ /*! Serial port register configuration. This is used to abstract-out the registers from device-to-device. */ /*-------------------------------------------------------------------------*/ #define UDR UDR0 #define UCSRA UCSR0A #define UCSRB UCSR0B #define UCSRC UCSR0C #define RXC RXC0 #define RXEN RXEN0 #define TXEN TXEN0 #define UDRE UDRE0 #define BAUD_H UBRR0H #define BAUD_L UBRR0L /*-------------------------------------------------------------------------*/ /*! Define the baud rate that the bootloader will operate at */ /*-------------------------------------------------------------------------*/ #define BAUD_RATE ((K_ULONG)57600) /*-------------------------------------------------------------------------*/ /*! Define the frequency that the system is running at. This MUST match the actual running frequency, otherwise the serial port won't run at the correct baud rate. */ /*-------------------------------------------------------------------------*/ #define SYSTEM_FREQ ((K_ULONG)16000000) /*-------------------------------------------------------------------------*/ /*! Buffer definitions - we have two buffers in our bootloader. -The serial buffer This is where packets transmitted to the device are staged until the contents can be verified. Verification in this case involves correct SLIP decoding, channel matching (Funkenslip framing), sub-msg matching and 16-bit payload checkusm matching. -The page buffer Once the individual packets have been validated as being correct - the data is copied into the page buffer. Once the page-buffer is full (the size varies between parts), the page buffer is committed to FLASH. */ #define PAGE_SIZE (128) /*!< 64 words on mega328p.*/ #define RX_BUF_SIZE (64) /*!< Maximum single funkenslip packet size */ /*-------------------------------------------------------------------------*/ /*! Protocol configuration The FunkenSlip protocol defines 256 channels on which messages can be addressed. Only devices which implement certain channels will respond to messages on those channels without a NACK. This section defines the channel ID used by our bootloader, as well as the sub-commands (data-byte 0) used to implement the specific operations required by the bootloader. Speaking of which, we can get away with three simple commands: -SEEK- Set the write pointer to a specific address, generally set on startup. If a partially-written page exists, assume the seek will take us out of the page currently being written. Write the contents of the partial page to flash, and then set the write pointer to the given address -WRITE- Write a packet of data to the current write address, committing to flash whenever a page boundary is crossed. -EOF- No more data to be transmitted. Commit partial-pages to flash, and boot into the newly-flashed application. */ #define PROGRAM_CHANNEL (127) /*!< FunkenSlip channel to program on*/ #define PROGRAM_CMD_SEEK (0) /*!< Seek to address*/ #define PROGRAM_CMD_WRITE (1) /*!< Write current buffer*/ #define PROGRAM_CMD_EOF (2) /*!< End of file - stop programming */ /*-------------------------------------------------------------------------*/ static K_ULONG ulPageAddr; /*!< Page address pointer*/ static K_UCHAR ucPageIdx; /*!< Index in the data page*/ static K_UCHAR aucPageBuf[PAGE_SIZE]; /*!< Data buffer written to FLASH*/ static K_UCHAR aucSerialBuf[RX_BUF_SIZE]; /*!< Buffer filled with FunkenSlip packets*/ /*-------------------------------------------------------------------------*/ typedef void (*main_func_t)(void); /*!< Function pointer type used to jump to app*/ /*-------------------------------------------------------------------------*/ /*! Forward declarations */ /*-------------------------------------------------------------------------*/ static void BL_Exit(void); static void Serial_Init(void); static K_UCHAR Serial_Read(void); static void Serial_Write(K_UCHAR ucByte_); static K_BOOL Slip_FillPacket(void); static K_UCHAR Slip_DecodePacket(void); static K_BOOL Serial_ValidatePacket(K_USHORT *pusLen_); static void Flash_WritePage(void); /*-------------------------------------------------------------------------*/ /*! Exit out of the bootloader, jumping to the main application. Writes a message to the UART "Booting App", before performing the reboot. \fn static void BL_Exit(void) */ static void BL_Exit(void) { /* Set a function pointer to the start of the user-app. */ main_func_t app_start = (void*)0; /* Write our farewell message to the UART */ Serial_Write('B'); Serial_Write('o'); Serial_Write('o'); Serial_Write('t'); Serial_Write('i'); Serial_Write('n'); Serial_Write('g'); Serial_Write(' '); Serial_Write('A'); Serial_Write('p'); Serial_Write('p'); Serial_Write('\n'); /* Reboot! */ app_start(); } /*-------------------------------------------------------------------------*/ /*! Initialize the serial port to the default baud rate specified in the port configuration. The bootloader uses a polling/busy-waiting RX and TX mechanism (no ISRs), so only basic RX and TX operations are supported. \fn static void Serial_Init(void) */ static void Serial_Init(void) { K_USHORT usBaudTemp = 0; /* Clear port config*/ UCSRA = 0; UCSRB = 0; /* Set baud rate*/ usBaudTemp = (K_USHORT)(((SYSTEM_FREQ/16)/BAUD_RATE) - 1); BAUD_H = (K_UCHAR)(usBaudTemp >> 8); BAUD_L = (K_UCHAR)(usBaudTemp & 0x00FF); /* Set 8N1 format on the port */ UCSRC = 0x06; /* Enable RX & TX, but no interrupts. */ UCSRB = (1 << RXEN) | (1 << TXEN); } /*-------------------------------------------------------------------------*/ /*! Read a byte of data from the serial port, returning it to the user. \fn static K_UCHAR Serial_Read(void) \return A single byte of data read from the serial port */ static K_UCHAR Serial_Read(void) { while (!(UCSRA & (1 << RXC0))){}; return UDR; } /*-------------------------------------------------------------------------*/ /*! Poll until we recieve the SLIP end-of-packet character (192). If a specified internal (ad-hoc) timeout occurs before receiving a valid framing character, bail. \fn static K_BOOL Serial_RxPoll(void) \return K_TRUE if a SLIP end-of-packet character recieved within the predefined tiemout interval, K_FALSE if a timeout occurred. */ static K_BOOL Serial_RxPoll(void) { volatile K_ULONG ulTimeout = 2000000UL; while (ulTimeout--) { if (UCSRA & (1 << RXC0)) { if (UDR == 192) { return K_TRUE; } } } return K_FALSE; } /*-------------------------------------------------------------------------*/ /*! Push a byte of data out of the serial port. Waits until the port is free before attempting to write the character. \fn static void Serial_Write(K_UCHAR ucByte_) */ static void Serial_Write(K_UCHAR ucByte_) { while (!(UCSRA & (1 << UDRE))){}; UDR = ucByte_; } /*-------------------------------------------------------------------------*/ /*! Busy-wait until a full packet of data is received. \fn static K_BOOL Slip_FillPacket(void) \return K_TRUE if a packet was successfully read, K_FALSE if the packet failed as a result of overflowing the buffer/garbage data on the port. */ static K_BOOL Slip_FillPacket(void) { K_UCHAR i = 0; K_UCHAR ucData; while (i < RX_BUF_SIZE) { ucData = Serial_Read(); aucSerialBuf[i] = ucData; if (ucData == 192) { return K_TRUE; } i++; } return K_FALSE; } /*-------------------------------------------------------------------------*/ /*! Perform in-place decoding on SLIP data in the serial buffer. \fn static K_UCHAR Slip_DecodePacket(void) \return Number of characters read */ static K_UCHAR Slip_DecodePacket(void) { K_UCHAR i = 0; K_UCHAR *pucSrc = aucSerialBuf; K_UCHAR *pucDst = aucSerialBuf; /* Perform slip decoding in-place in the serial buffer packet*/ while ((*pucSrc != 192) && i < RX_BUF_SIZE) { if (*pucSrc == 219) { if (*(pucSrc+1) == 220) { *pucDst = 192; } else if (*(pucSrc+1) == 221) { *pucDst = 219; } pucSrc++; } else { *pucDst = *pucSrc; } i++; pucSrc++; pucDst++; } *pucDst = 192; return i; } /*-------------------------------------------------------------------------*/ /*! Attempt to validate a packet of serial data which has already been SLIP decoded. This function validates the contents of the payload as being FunkenSlip encoded data - We search for a correct channel, correct CRC's, and correct message length before allowing a packet to be valid. \fn static K_BOOL Serial_ValidatePacket(K_USHORT *pusLen_) \param K_USHORT *pusLen_ Length of packet data returned to the user \return K_TRUE if packet is valid, K_FALSE if any of the checks fail */ static K_BOOL Serial_ValidatePacket(K_USHORT *pusLen_) { K_UCHAR ucChannel; K_USHORT usCRC_Calc = 0; K_USHORT usCRC_Read = 0; K_USHORT usLen; K_UCHAR *pucData; ucChannel = aucSerialBuf[0]; /* Ensure the channel is correct */ if (ucChannel != PROGRAM_CHANNEL) { return K_FALSE; } usCRC_Calc += aucSerialBuf[0]; /* Read the length out */ usLen = ((K_USHORT)aucSerialBuf[1]) << 8; usCRC_Calc += aucSerialBuf[1]; usLen += (K_USHORT)aucSerialBuf[2]; usCRC_Calc += aucSerialBuf[2]; /* Length returned to the user is -1 because of the sub-command byte,*/ /* which is part of the actual FunkenSlip data payload.*/ *pusLen_ = usLen - 1; /* Continue reading through the packet to compute the CRC */ pucData = &aucSerialBuf[3]; while (usLen--) { usCRC_Calc += *pucData; pucData++; } /* The CRC is stored at the end of the packet */ usCRC_Read = ((K_USHORT)*pucData) << 8; pucData++; usCRC_Read += ((K_USHORT)*pucData); /* Make sure the read CRC matches the generated CRC*/ if (usCRC_Read != usCRC_Calc) { *pusLen_ = 0; return K_FALSE; } return K_TRUE; } /*-------------------------------------------------------------------------*/ /*! Shamelessly lifted from the AVR libc docs. This uses the functions and macros defined in boot.h in order to safely commit our page buffer to flash. \fn static void Flash_WritePage(void) */ static void Flash_WritePage(void) { K_USHORT i; K_UCHAR *pucData = aucPageBuf; eeprom_busy_wait(); boot_page_erase(ulPageAddr); boot_spm_busy_wait(); /* Wait until the memory is erased. */ for (i=0; i<PAGE_SIZE; i+=2) { /* Set up little-endian word. */ K_USHORT w = *pucData++; w += ((K_USHORT)(*pucData++)) << 8; boot_page_fill (ulPageAddr + i, w); } boot_page_write (ulPageAddr); /* Store buffer in flash page. */ boot_spm_busy_wait(); /* Wait until the memory is written. */ /* Reenable RWW-section again. We need this if we want to jump back */ /* to the application after bootloading. */ boot_rww_enable (); } /*-------------------------------------------------------------------------*/ /*! Copy data in from the serial buffer to the page buffer. Whenever a page buffer is full, commit the page to flash, and start the next. \fn static K_BOOL Flash_WriteBuffer(K_USHORT usLen_) \return K_TRUE on success, K_FALSE on failure */ static K_BOOL Flash_WriteBuffer(K_USHORT usLen_) { K_UCHAR ucIdx = 4; /* Size of the header... */ /* Write from the serial buffer to the flash staging buffer */ while (usLen_--) { aucPageBuf[ucPageIdx] = aucSerialBuf[ucIdx++]; ucPageIdx++; if (ucPageIdx == PAGE_SIZE) { /* Write the page of data to flash... */ Flash_WritePage(); /* Update indexes/pages. */ ucPageIdx = 0; ulPageAddr += PAGE_SIZE; } } return K_TRUE; } /*-------------------------------------------------------------------------*/ /*! Commit a partial-page of data to flash. This completes the page buffer with 0xFF bytes, before running Flash_WritePage() to seal the deal. \fn static void Flash_WritePartialPage(void) */ static void Flash_WritePartialPage(void) { if (ucPageIdx != 0) { while (ucPageIdx < PAGE_SIZE) { aucPageBuf[ucPageIdx] = 0xFF; ucPageIdx++; } Flash_WritePage(); } } /*-------------------------------------------------------------------------*/ int main(void) { /* Ensure interrupts are disabled when running the bootloader... */ cli(); /* Clear the watchdog timer... */ { volatile K_UCHAR ucTemp = MCUSR; MCUSR = 0; WDTCSR |= (1 << WDCE) | (1 << WDE); WDTCSR = 0; ucTemp = ucTemp; } /* Start off by initializing the serial port */ Serial_Init(); /* Send a banner message, indicating we're in the Mark3 Boot Loader */ Serial_Write('M'); Serial_Write('a'); Serial_Write('r'); Serial_Write('k'); Serial_Write('3'); Serial_Write('B'); Serial_Write('L'); Serial_Write('\n'); #if 1 /* Check to see if we're getting our start character to begin using the BL */ if (!Serial_RxPoll()) { /* Timed out - exit the bootloader */ BL_Exit(); } /* Acknowledge the request to start programming. */ Serial_Write(69); #endif /* Main programming loop. Program until we can't program no more! */ while (1) { K_USHORT usLen; /* Wait until we receive a packet of data. */ Slip_FillPacket(); /* Decode the serial buffer */ if (!Slip_DecodePacket()) { Serial_Write('D'); continue; } /* Make sure the packet is VALID before trying to operate on it. */ if (!Serial_ValidatePacket(&usLen)) { Serial_Write('V'); continue; } /* Figure out what action to take based on the command field... */ if (aucSerialBuf[3] == PROGRAM_CMD_SEEK) { /* Seek to new address... */ K_USHORT usNewAddr = ((K_USHORT)aucSerialBuf[4]) << 8; usNewAddr += aucSerialBuf[5]; Flash_WritePartialPage(); ulPageAddr = (K_ULONG)usNewAddr; ucPageIdx = 0; } else if (aucSerialBuf[3] == PROGRAM_CMD_WRITE) { /* Write contents of buffer to staging buffer, then flash.*/ Flash_WriteBuffer(usLen); } else if (aucSerialBuf[3] == PROGRAM_CMD_EOF) { /* End of file. Commit current page to flash (if non-empty) and boot to */ /* application, if possible. */ Flash_WritePartialPage(); BL_Exit(); } else { /* error, invalid command */ Serial_Write('I'); continue; } /* If we get here, the packet was valid. */ Serial_Write(69); } /* Return to app on exit. */ BL_Exit(); }
moslevin/Mark3C
tests/unit/ut_logic/ut_logic.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ //--------------------------------------------------------------------------- #include "kerneltypes.h" #include "kernel.h" #include "../ut_platform.h" //=========================================================================== // Local Defines //=========================================================================== //=========================================================================== // Define Test Cases Here //=========================================================================== TEST(ut_logic) { // Test the built-in unit-test logic to ensure our base assumptions are // correct. // 1 == true, ensure that this test passes EXPECT_TRUE(1); // 0 == false, ensure that this test passes EXPECT_FALSE(0); // 1 != false, ensure that this test fails EXPECT_FAIL_FALSE(1); // 0 != true, ensure that this test fails EXPECT_FAIL_TRUE(0); // Ensure that various 8-32 bit values meet equality conditions EXPECT_EQUALS(0, 0); // signed 8-bit values EXPECT_EQUALS(-128, -128); EXPECT_EQUALS(127, 127); // unsigned 8-bit values EXPECT_EQUALS(255, 255); // signed 16-bit values EXPECT_EQUALS(32767, 32767); EXPECT_EQUALS(-32768, -32768); // unsigned 16-bit values EXPECT_EQUALS(65535, 65535); // unsigned 32-bit values EXPECT_EQUALS(-214783648, -214783648); EXPECT_EQUALS(214783647, 214783647); // signed 32-bit values EXPECT_EQUALS(4294967295, 4294967295); // Ensure that various 8-32 bit values meet equality conditions EXPECT_FAIL_EQUALS(0, -1); // signed 8-bit values EXPECT_FAIL_EQUALS(-128, -1); EXPECT_FAIL_EQUALS(127, -1); // unsigned 8-bit values EXPECT_FAIL_EQUALS(255, 0); // signed 16-bit values EXPECT_FAIL_EQUALS(32767, -1); EXPECT_FAIL_EQUALS(-32768, -1); // unsigned 16-bit values EXPECT_FAIL_EQUALS(65535, 0); // unsigned 32-bit values EXPECT_FAIL_EQUALS(-214783648, -1); EXPECT_FAIL_EQUALS(214783647, 1); // signed 32-bit values EXPECT_FAIL_EQUALS(4294967295, 0); } TEST_END //=========================================================================== // Test Whitelist Goes Here //=========================================================================== TEST_CASE_START TEST_CASE(ut_logic), TEST_CASE_END
moslevin/Mark3C
kernel/timer.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file timer.cpp \brief Timer_t implementations */ #include "kerneltypes.h" #include "mark3cfg.h" #include "timer.h" #include "timerlist.h" #include "timerscheduler.h" #include "kerneltimer.h" #include "threadport.h" #include "kerneldebug.h" #include "quantum.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ TIMER_C //!< File ID used in kernel trace calls #if KERNEL_USE_TIMERS //--------------------------------------------------------------------------- void Timer_Init( Timer_t *pstTimer_ ) { LinkListNode_Clear( (LinkListNode_t*)pstTimer_ ); pstTimer_->ulInterval = 0; pstTimer_->ulTimerTolerance = 0; pstTimer_->ulTimeLeft = 0; pstTimer_->ucFlags = 0; } //--------------------------------------------------------------------------- void Timer_Start( Timer_t *pstTimer_, K_BOOL bRepeat_, K_ULONG ulIntervalMs_, TimerCallback_t pfCallback_, void *pvData_ ) { Timer_SetIntervalMSeconds( pstTimer_, ulIntervalMs_ ); pstTimer_->ulTimerTolerance = 0; pstTimer_->pfCallback = pfCallback_; pstTimer_->pvData = pvData_; if (!bRepeat_) { pstTimer_->ucFlags = TIMERLIST_FLAG_ONE_SHOT; } else { pstTimer_->ucFlags = 0; } pstTimer_->pstOwner = Scheduler_GetCurrentThread(); TimerScheduler_Add( pstTimer_ ); } //--------------------------------------------------------------------------- void Timer_StartEx( Timer_t *pstTimer_, K_BOOL bRepeat_, K_ULONG ulIntervalMs_, K_ULONG ulToleranceMs_, TimerCallback_t pfCallback_, void *pvData_ ) { pstTimer_->ulTimerTolerance = MSECONDS_TO_TICKS( ulToleranceMs_ ); Timer_Start( pstTimer_, bRepeat_, ulIntervalMs_, pfCallback_, pvData_ ); } //--------------------------------------------------------------------------- void Timer_Stop( Timer_t *pstTimer_ ) { TimerScheduler_Remove( pstTimer_ ); } //--------------------------------------------------------------------------- void Timer_SetFlags ( Timer_t *pstTimer_, K_UCHAR ucFlags_) { pstTimer_->ucFlags = ucFlags_; } //--------------------------------------------------------------------------- void Timer_SetCallback( Timer_t *pstTimer_, TimerCallback_t pfCallback_) { pstTimer_->pfCallback = pfCallback_; } //--------------------------------------------------------------------------- void Timer_SetData( Timer_t *pstTimer_, void *pvData_ ) { pstTimer_->pvData = pvData_; } //--------------------------------------------------------------------------- void Timer_SetOwner( Timer_t *pstTimer_, Thread_t *pstOwner_) { pstTimer_->pstOwner = pstOwner_; } //--------------------------------------------------------------------------- void Timer_SetIntervalTicks( Timer_t *pstTimer_, K_ULONG ulTicks_ ) { pstTimer_->ulInterval = ulTicks_; } //--------------------------------------------------------------------------- //!! The next three cost us 330 bytes of flash on AVR... //--------------------------------------------------------------------------- void Timer_SetIntervalSeconds( Timer_t *pstTimer_, K_ULONG ulSeconds_) { pstTimer_->ulInterval = SECONDS_TO_TICKS(ulSeconds_); } //--------------------------------------------------------------------------- void Timer_SetIntervalMSeconds( Timer_t *pstTimer_, K_ULONG ulMSeconds_) { pstTimer_->ulInterval = MSECONDS_TO_TICKS(ulMSeconds_); } //--------------------------------------------------------------------------- void Timer_SetIntervalUSeconds( Timer_t *pstTimer_, K_ULONG ulUSeconds_) { pstTimer_->ulInterval = USECONDS_TO_TICKS(ulUSeconds_); } //--------------------------------------------------------------------------- void Timer_SetTolerance( Timer_t *pstTimer_, K_ULONG ulTicks_) { pstTimer_->ulTimerTolerance = ulTicks_; } //--------------------------------------------------------------------------- K_ULONG Timer_GetInterval( Timer_t *pstTimer_ ) { return pstTimer_->ulInterval; } #endif
moslevin/Mark3C
kernel/public/mark3cfg.h
<reponame>moslevin/Mark3C<filename>kernel/public/mark3cfg.h /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file mark3cfg.h \brief Mark3 Kernel Configuration This file is used to configure the kernel for your specific application in order to provide the optimal set of features for a given use case. Since you only pay the price (code space/RAM) for the features you use, you can usually find a sweet spot between features and resource usage by picking and choosing features a-la-carte. This config file is written in an "interactive" way, in order to minimize confusion about what each option provides, and to make dependencies obvious. */ #ifndef __MARK3CFG_H__ #define __MARK3CFG_H__ /*! The following options is related to all kernel time-tracking. -timers provide a way for events to be periodically triggered in a lightweight manner. These can be periodic, or one-shot. -Thread_t Quantum (used for round-robin scheduling) is dependent on this module, as is Thread_t Sleep functionality. */ #define KERNEL_USE_TIMERS (1) #define KERNEL_USE_SLEEP (1) /*! If you've opted to use the kernel timers module, you have an option as to which timer implementation to use: Tick-based or Tick-less. Tick-based timers provide a "traditional" RTOS timer implementation based on a fixed-frequency timer interrupt. While this provides very accurate, reliable timing, it also means that the CPU is being interrupted far more often than may be necessary (as not all timer ticks result in "real work" being done). Tick-less timers still rely on a hardware timer interrupt, but uses a dynamic expiry interval to ensure that the interrupt is only called when the next timer expires. This increases the complexity of the timer interrupt handler, but reduces the number and frequency. Note that the CPU port (kerneltimer.cpp) must be implemented for the particular timer variant desired. */ #if KERNEL_USE_TIMERS #define KERNEL_TIMERS_TICKLESS (0) #endif /*! By default, if you opt to enable kernel timers, you also get timeout- enabled versions of the blocking object APIs along with it. This support comes at a small cost to code size, but a slightly larger cost to realtime performance - as checking for the use of timers in the underlying internal code costs some cycles. As a result, the option is given to the user here to manually disable these timeout-based APIs if desired by the user for performance and code-size reasons. */ #if KERNEL_USE_TIMERS #define KERNEL_USE_TIMEOUTS (1) #else #define KERNEL_USE_TIMEOUTS (0) #endif /*! Do you want to enable time quanta? This is useful when you want to have tasks in the same priority group share time in a controlled way. This allows equal tasks to use unequal amounts of the CPU, which is a great way to set up CPU budgets per thread in a round-robin scheduling system. If enabled, you can specify a number of ticks that serves as the default time period (quantum). Unless otherwise specified, every thread in a priority will get the default quantum. */ #if KERNEL_USE_TIMERS #define KERNEL_USE_QUANTUM (1) #else #define KERNEL_USE_QUANTUM (0) #endif /*! This value defines the default thread quantum when KERNEL_USE_QUANTUM is enabled. The thread quantum value is in milliseconds */ #define THREAD_QUANTUM_DEFAULT (4) /*! Do you want the ability to use counting/binary semaphores for thread synchronization? Enabling this features provides fully-blocking semaphores and enables all API functions declared in semaphore.h. If you have to pick one blocking mechanism, this is the one to choose. */ #define KERNEL_USE_SEMAPHORE (1) /*! Do you want the ability to use mutual exclusion semaphores (Mutex_t) for resource/block protection? Enabling this feature provides mutexes, with priority inheritence, as declared in mutex.h. */ #define KERNEL_USE_MUTEX (1) /*! Provides additional event-flag based blocking. This relies on an additional per-thread flag-mask to be allocated, which adds 2 bytes to the size of each thread object. */ #define KERNEL_USE_EVENTFLAG (1) /*! Enable inter-thread messaging using message queues. This is the preferred mechanism for IPC for serious multi-threaded communications; generally anywhere a Semaphore_t or event-flag is insufficient. */ #if KERNEL_USE_SEMAPHORE #define KERNEL_USE_MESSAGE (1) #else #define KERNEL_USE_MESSAGE (0) #endif /*! If Messages are enabled, define the size of the default kernel message pool. Messages can be manually added to the message pool, but this mechansims is more convenient and automatic. All message queues share their message objects from this global pool to maximize efficiency and simplify data management. */ #if KERNEL_USE_MESSAGE #define GLOBAL_MESSAGE_POOL_SIZE (8) #endif #define KERNEL_USE_MAILBOX (1) #define KERNEL_USE_NOTIFY (1) /*! Do you want to be able to set threads to sleep for a specified time? This enables the Thread_t_Sleep() API. */ #if KERNEL_USE_TIMERS && KERNEL_USE_SEMAPHORE #define KERNEL_USE_SLEEP (1) #else #define KERNEL_USE_SLEEP (0) #endif /*! Enabling device drivers provides a posix-like filesystem interface for peripheral device drivers. */ #define KERNEL_USE_DRIVER (1) /*! Provide Thread_t method to allow the user to set a name for each thread in the system. Adds a const K_CHAR* pointer to the size of the thread object. */ #define KERNEL_USE_THREADNAME (0) /*! Provide extra Thread_t methods to allow the application to create (and more importantly destroy) threads at runtime. Useful for designs implementing worker threads, or threads that can be restarted after encountering error conditions. */ #define KERNEL_USE_DYNAMIC_THREADS (1) /*! Provides extra classes for profiling the performance of code. Useful for debugging and development, but uses an additional hardware timer. */ #define KERNEL_USE_PROFILER (1) /*! Provides extra logic for kernel debugging, and instruments the kernel with extra asserts, and kernel trace functionality. */ #define KERNEL_USE_DEBUG (0) /*! Provides support for atomic operations, including addition, subtraction, set, and test-and-set. Add/Sub/Set contain 8, 16, and 32-bit variants. */ #define KERNEL_USE_ATOMIC (0) /*! "Safe unlinking" performs extra checks on data to make sure that there are no consistencies when performing operations on linked lists. This goes beyond pointer checks, adding a layer of structural and metadata validation to help detect system corruption early. */ #define SAFE_UNLINK (0) /*! Include support for kernel-aware simulation. Enabling this feature adds advanced profiling, trace, and environment-aware debugging and diagnostic functionality when Mark3-based applications are run on the flavr AVR simulator. */ #define KERNEL_AWARE_SIMULATION (1) /*! Enabling this feature removes the necessity for the user to dedicate a complete thread for idle functionality. This saves a full thread stack, but also requires a bit extra static data. This also adds a slight overhead to the context switch and scheduler, as a special case has to be taken into account. */ #define KERNEL_USE_IDLE_FUNC (1) #endif
moslevin/Mark3C
examples/avr/lab6_timers/main.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ #include "mark3.h" /*=========================================================================== Lab Example 6: Using Periodic and One-shot timers. Lessons covered in this example include: Takeaway: ===========================================================================*/ //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP1_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp1Thread; static K_WORD awApp1Stack[APP1_STACK_SIZE]; static void App1Main(void *unused_); //--------------------------------------------------------------------------- static void PeriodicCallback(Thread_t *owner, void *pvData_); static void OneShotCallback(Thread_t *owner, void *pvData_); //--------------------------------------------------------------------------- int main(void) { // See the annotations in previous labs for details on init. Kernel_Init(); Thread_Init( &stApp1Thread, awApp1Stack, APP1_STACK_SIZE, 1, App1Main, 0); Thread_Start( &stApp1Thread ); Kernel_Start(); return 0; } //--------------------------------------------------------------------------- void PeriodicCallback(Thread_t *owner, void *pvData_) { // Timer callback function used to post a semaphore. Posting the semaphore // will wake up a thread that's pending on that semaphore. Semaphore_t *pstSem = (Semaphore_t*)pvData_; Semaphore_Post( pstSem ); } //--------------------------------------------------------------------------- void OneShotCallback(Thread_t *owner, void *pvData_) { KernelAware_Print("One-shot timer expired.\n"); } //--------------------------------------------------------------------------- void App1Main(void *unused_) { Timer_t stMyTimer; // Periodic timer object Timer_t stOneShot; // One-shot timer object Semaphore_t stMySem; // Semaphore used to wake this thread // Initialize a binary semaphore (maximum value of one, initial value of // zero). Semaphore_Init( &stMySem, 0, 1 ); // Start a timer that triggers every 500ms that will call PeriodicCallback. // This timer simulates an external stimulus or event that would require // an action to be taken by this thread, but would be serviced by an // interrupt or other high-priority context. // PeriodicCallback will post the semaphore which wakes the thread // up to perform an action. Here that action consists of a trivial message // print. Timer_Start( &stMyTimer, true, 50, PeriodicCallback, (void*)&stMySem); // Set up a one-shot timer to print a message after 2.5 seconds, asynchronously // from the execution of this thread. Timer_Start( &stOneShot, false, 250, OneShotCallback, 0); while(1) { // Wait until the semaphore is posted from the timer expiry Semaphore_Pend( &stMySem ); // Take some action after the timer posts the semaphore to wake this // thread. KernelAware_Print("Thread Triggered.\n"); } }
moslevin/Mark3C
kernel/public/notify.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file notify.h \brief Lightweight thread notification - blocking object */ #ifndef __NOTIFY_H__ #define __NOTIFY_H__ #include "mark3cfg.h" #include "blocking.h" typedef struct { ThreadList_t stBlockList; } Notify_t; /*! * \brief Init * * Initialze the Notification object prior to use. */ void Notify_Init( Notify_t *pstNotify_ ); /*! * \brief Signal * * Signal the notification object. This will cause the * highest priority thread currently blocking on the object * to wake. If no threads are currently blocked on the * object, the call has no effect. * */ void Notify_Signal( Notify_t *pstNotify_ ); /*! * \brief Wait * * Block the current thread, waiting for a signal on the * object. * * \param pbFlag_ Flag set to false on block, and true * upon wakeup. */ void Notify_Wait( Notify_t *pstNotify_, bool *pbFlag_ ); #if KERNEL_USE_TIMEOUTS /*! * \brief Wait * Block the current thread, waiting for a signal on the * object. * * \param ulWaitTimeMS_ Time to wait for the notification * event. * \param pbFlag_ Flag set to false on block, and * true upon wakeup. * \return true on notification, false on timeout */ bool Notify_TimedWait( Notify_t *pstNotify_, K_ULONG ulWaitTimeMS_, bool *pbFlag_ ); #endif /*! * \brief WakeMe * * Wake the specified thread from its current blocking queue. * Note that this is only public in order to be accessible * from a timer callack. * * \param pclChosenOne_ Thread to wake up */ void Notify_WakeMe( Notify_t *pstNotify_, Thread_t *pclChosenOne_ ); #endif
moslevin/Mark3C
kernel/kernel.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernel.cpp \brief Kernel initialization and startup code */ #include "kerneltypes.h" #include "mark3cfg.h" #include "kernel.h" #include "scheduler.h" #include "thread.h" #include "threadport.h" #include "timerlist.h" #include "message.h" #include "driver.h" #include "profile.h" #include "kernelprofile.h" #include "tracebuffer.h" #include "kerneldebug.h" #include "kernelaware.h" #include "debugtokens.h" K_BOOL bIsStarted; K_BOOL bIsPanic; panic_func_t pfPanic; #if KERNEL_USE_IDLE_FUNC idle_func_t pfIdle; FakeThread_t stIdle; #endif //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ KERNEL_C //!< File ID used in kernel trace calls //--------------------------------------------------------------------------- void Kernel_Init(void) { bIsStarted = false; bIsPanic = false; pfPanic = 0; #if KERNEL_AWARE_SIMULATION g_ucKACommand = KA_COMMAND_IDLE; g_bIsKernelAware = g_bIsKernelAware; #endif #if KERNEL_USE_DEBUG & !KERNEL_AWARE_SIMULATION TraceBuffer_Init(); #endif #if KERNEL_USE_IDLE_FUNC Thread_InitIdle( (Thread_t*)&stIdle ); pfIdle = 0; #endif KERNEL_TRACE( STR_MARK3_INIT ); // Initialize the global kernel data - scheduler, timer-scheduler, and // the global message pool. Scheduler_Init(); #if KERNEL_USE_DRIVER DriverList_Init(); #endif #if KERNEL_USE_TIMERS TimerScheduler_Init(); #endif #if KERNEL_USE_MESSAGE GlobalMessagePool_Init(); #endif #if KERNEL_USE_PROFILER Profiler_Init(); #endif } //--------------------------------------------------------------------------- void Kernel_Start(void) { KERNEL_TRACE( STR_THREAD_START ); bIsStarted = true; ThreadPort_StartThreads(); KERNEL_TRACE( STR_START_ERROR ); } //--------------------------------------------------------------------------- void Kernel_Panic(K_USHORT usCause_) { bIsPanic = true; if (pfPanic) { pfPanic(usCause_); } else { #if KERNEL_AWARE_SIMULATION KernelAware_ExitSimulator(); #endif while(1); } } //--------------------------------------------------------------------------- K_BOOL Kernel_IsStarted( void ) { return bIsStarted; } //--------------------------------------------------------------------------- void Kernel_SetPanic( panic_func_t pfPanic_ ) { pfPanic = pfPanic_; } //--------------------------------------------------------------------------- K_BOOL Kernel_IsPanic( void ) { return bIsPanic; } #if KERNEL_USE_IDLE_FUNC //--------------------------------------------------------------------------- void Kernel_SetIdleFunc( idle_func_t pfIdle_ ) { pfIdle = pfIdle_; } //--------------------------------------------------------------------------- void Kernel_IdleFunc( void ) { if (pfIdle != 0 ) { pfIdle(); } } //--------------------------------------------------------------------------- Thread_t *Kernel_GetIdleThread( void ) { return (Thread_t*)&stIdle; } #endif
moslevin/Mark3C
kernel/mutex.c
<filename>kernel/mutex.c<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file Mutex_t.cpp \brief Mutual-exclusion object */ #include "kerneltypes.h" #include "mark3cfg.h" #include "blocking.h" #include "mutex.h" #include "kerneldebug.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ MUTEX_C //!< File ID used in kernel trace calls #if KERNEL_USE_MUTEX /*! \fn K_UCHAR WakeNext(); Wake the next thread waiting on the Mutex_t. */ static K_UCHAR Mutex_WakeNext( Mutex_t *pstMutex_ ); #if KERNEL_USE_TIMEOUTS /*! * \brief Claii * * Abstracts out timed/non-timed Mutex_t claim operations. * * \param ulWaitTimeMS_ Time in MS to wait, 0 for infinite * \return true on successful claim, false otherwise */ static K_BOOL Mutex_Claii( Mutex_t *pstMutex_, K_ULONG ulWaitTimeMS_ ); /*! \fn void WakeMe( Thread_t *pstOwner_ ) Wake a thread blocked on the Mutex_t. This is an internal function used for implementing timed mutexes relying on timer callbacks. Since these do not have access to the private data of the Mutex_t and its base classes, we have to wrap this as a public method - do not use this for any other purposes. \param pstOwner_ Thread_t to unblock from this object. */ static void Mutex_WakeMe( Mutex_t *pstMutex_, Thread_t *pstOwner_ ); #else /*! * \brief Claii * * Abstraction for Mutex_t claim operations. * */ static void Mutex_Claii( Mutex_t *pstMutex_ ); #endif #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- /*! * \brief TimedMutex_Calback * * This function is called from the timer-expired context to trigger a timeout * on this Mutex_t. This results in the waking of the thread that generated * the Mutex_t claim call that was not completed in time. * * \param pstOwner_ Pointer to the thread to wake * \param pvData_ Pointer to the Mutex_t object that the thread is blocked on */ void TimedMutex_Calback(Thread_t *pstOwner_, void *pvData_) { Mutex_t *pstMutex = (Mutex_t*)(pvData_); // Indicate that the Semaphore_t has expired on the thread Thread_SetExpired( pstOwner_, true ); // Wake up the thread that was blocked on this Semaphore_t. Mutex_WakeMe( pstMutex, pstOwner_ ); if ( Thread_GetCurPriority( pstOwner_ ) >= Thread_GetCurPriority( Scheduler_GetCurrentThread() ) ) { Thread_Yield(); } } //--------------------------------------------------------------------------- void Mutex_WakeMe( Mutex_t *pstMutex_, Thread_t *pstOwner_ ) { // Remove from the Semaphore_t waitlist and back to its ready list. BlockingObject_UnBlock(pstOwner_); } #endif //--------------------------------------------------------------------------- K_UCHAR Mutex_WakeNext( Mutex_t *pstMutex_ ) { Thread_t *pstChosenOne = NULL; // Get the highest priority waiter thread pstChosenOne = ThreadList_HighestWaiter( (ThreadList_t*)pstMutex_ ); // Unblock the thread BlockingObject_UnBlock(pstChosenOne); // The chosen one now owns the Mutex_t pstMutex_->pstOwner = pstChosenOne; // Signal a context switch if it's a greater than or equal to the current priority if ( Thread_GetCurPriority(pstChosenOne) >= Thread_GetCurPriority( Scheduler_GetCurrentThread() ) ) { return 1; } return 0; } //--------------------------------------------------------------------------- void Mutex_Init( Mutex_t *pstMutex_ ) { ThreadList_Init( (ThreadList_t*)pstMutex_ ); // Reset the data in the Mutex_t pstMutex_->bReady = 1; // The Mutex_t is free. pstMutex_->ucMaxPri = 0; // Set the maximum priority inheritence state pstMutex_->pstOwner = NULL; // Clear the Mutex_t owner pstMutex_->ucRecurse = 0; // Reset recurse count } //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS K_BOOL Mutex_Claii( Mutex_t *pstMutex_, K_ULONG ulWaitTimeMS_) #else void Mutex_Claii( Mutex_t *pstMutex_ ) #endif { KERNEL_TRACE_1( STR_MUTEX_CLAIM_1, (K_USHORT)Thread_GetID( g_pstCurrent ) ); #if KERNEL_USE_TIMEOUTS Timer_t stTimer; K_BOOL bUseTimer = false; #endif // Disable the scheduler while claiming the Mutex_t - we're dealing with all // sorts of private thread data, can't have a thread switch while messing // with internal data structures. Scheduler_SetScheduler( false ); // Check to see if the Mutex_t is claimed or not if (pstMutex_->bReady != 0) { // Mutex_t isn't claimed, claim it. pstMutex_->bReady = 0; pstMutex_->ucRecurse = 0; pstMutex_->ucMaxPri = Thread_GetPriority( g_pstCurrent ); pstMutex_->pstOwner = g_pstCurrent; Scheduler_SetScheduler( true ); #if KERNEL_USE_TIMEOUTS return true; #else return; #endif } // If the Mutex_t is already claimed, check to see if this is the owner thread, // since we allow the Mutex_t to be claimed recursively. if (g_pstCurrent == pstMutex_->pstOwner) { // Ensure that we haven't exceeded the maximum recursive-lock count KERNEL_ASSERT( (pstMutex_->ucRecurse < 255) ); pstMutex_->ucRecurse++; // Increment the lock count and bail Scheduler_SetScheduler( true ); #if KERNEL_USE_TIMEOUTS return true; #else return; #endif } // The Mutex_t is claimed already - we have to block now. Move the // current thread to the list of threads waiting on the Mutex_t. #if KERNEL_USE_TIMEOUTS if (ulWaitTimeMS_) { Thread_SetExpired( g_pstCurrent, false ); Timer_Init( &stTimer ); Timer_Start( &stTimer, false, ulWaitTimeMS_, (TimerCallback_t)TimedMutex_Calback, (void*)pstMutex_); bUseTimer = true; } #endif BlockingObject_Block( (ThreadList_t*)pstMutex_, g_pstCurrent ); // Check if priority inheritence is necessary. We do this in order // to ensure that we don't end up with priority inversions in case // multiple threads are waiting on the same resource. if(pstMutex_->ucMaxPri <= Thread_GetPriority( g_pstCurrent ) ) { pstMutex_->ucMaxPri = Thread_GetPriority( g_pstCurrent ); Thread_t *pstTemp = (Thread_t*)(LinkList_GetHead( (LinkList_t*)pstMutex_ )); while(pstTemp) { Thread_InheritPriority( pstTemp, pstMutex_->ucMaxPri ); if(pstTemp == (Thread_t*)(LinkList_GetTail( (LinkList_t*)pstMutex_ )) ) { break; } pstTemp = (Thread_t*)LinkListNode_GetNext( (LinkListNode_t*)pstTemp ); } Thread_InheritPriority( pstMutex_->pstOwner, pstMutex_->ucMaxPri ); } // Done with thread data -reenable the scheduler Scheduler_SetScheduler( true ); // Switch threads if this thread acquired the Mutex_t Thread_Yield(); #if KERNEL_USE_TIMEOUTS if (bUseTimer) { Timer_Stop( &stTimer ); return ( Thread_GetExpired( g_pstCurrent ) == 0); } return true; #endif } //--------------------------------------------------------------------------- void Mutex_Claim( Mutex_t *pstMutex_ ) { #if KERNEL_USE_TIMEOUTS Mutex_Claii( pstMutex_ , 0 ); #else Mutex_Claii( pstMutex_ ); #endif } //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS K_BOOL Mutex_TimedClaim( Mutex_t *pstMutex_, K_ULONG ulWaitTimeMS_ ) { return Mutex_Claii( pstMutex_ , ulWaitTimeMS_ ); } #endif //--------------------------------------------------------------------------- void Mutex_Release( Mutex_t *pstMutex_ ) { KERNEL_TRACE_1( STR_MUTEX_RELEASE_1, (K_USHORT)Thread_GetID( g_pstCurrent ) ); K_BOOL bSchedule = 0; // Disable the scheduler while we deal with internal data structures. Scheduler_SetScheduler( false ); // This thread had better be the one that owns the Mutex_t currently... KERNEL_ASSERT( (g_pstCurrent == pstMutex_->pstOwner) ); // If the owner had claimed the lock multiple times, decrease the lock // count and return immediately. if (pstMutex_->ucRecurse) { pstMutex_->ucRecurse--; Scheduler_SetScheduler( true ); return; } // Restore the thread's original priority if (Thread_GetCurPriority( g_pstCurrent ) != Thread_GetPriority( g_pstCurrent )) { Thread_SetPriority( g_pstCurrent, Thread_GetPriority(g_pstCurrent) ); // In this case, we want to reschedule bSchedule = 1; } // No threads are waiting on this Mutex_t? if ( LinkList_GetHead( (LinkList_t*)pstMutex_ ) == NULL) { // Re-initialize the Mutex_t to its default values pstMutex_->bReady = 1; pstMutex_->ucMaxPri = 0; pstMutex_->pstOwner = NULL; } else { // Wake the highest priority Thread_t pending on the Mutex_t if( Mutex_WakeNext( pstMutex_ ) ) { // Switch threads if it's higher or equal priority than the current thread bSchedule = 1; } } // Must enable the scheduler again in order to switch threads. Scheduler_SetScheduler( true ); if(bSchedule) { // Switch threads if a higher-priority thread was woken Thread_Yield(); } } #endif //KERNEL_USE_MUTEX
moslevin/Mark3C
kernel/public/driver.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file driver.h \brief Driver abstraction framework \section DrvIntro Intro This is the basis of the driver framework. In the context of Mark3, drivers don't necessarily have to be based on physical hardware peripherals. They can be used to represent algorithms (such as random number generators), files, or protocol stacks. Unlike FunkOS, where driver IO is protected automatically by a Mutex_t, we do not use this kind of protection - we leave it up to the driver implementor to do what's right in its own context. This also frees up the driver to implement all sorts of other neat stuff, like sending messages to threads associated with the driver. Drivers are implemented as character devices, with the standard array of posix-style accessor methods for reading, writing, and general driver control. A global driver list is provided as a convenient and minimal "filesystem" structure, in which devices can be accessed by name. \section DrvDesign Driver Design A device driver needs to be able to perform the following operations: -Initialize a peripheral -Start/stop a peripheral -Handle I/O control operations -Perform various read/write operations At the end of the day, that's pretty much all a device driver has to do, and all of the functionality that needs to be presented to the developer. We abstract all device drivers using a base-object which implements the following methods: -Start/Open -Stop/Close -Control -Read -Write A basic driver framework and API can thus be implemented in five function calls - that's it! You could even reduce that further by handling the initialize, start, and stop operations inside the "control" operation. \section DrvAPI Driver API In C++, we can implement this as a object to abstract these event handlers, with virtual void functions in the base object overridden by the inherited objects. To add and remove device drivers from the global table, we use the following methods: \code void DriverList_Add( Driver *pstDriver_ ); void DriverList_Remove( Driver *pstDriver_ ); \endcode DriverList_Add()/Remove() takes a single arguments � the pointer to he object to operate on. Once a driver has been added to the table, drivers are opened by NAME using DriverList_FindByName("/dev/name"). This function returns a pointer to the specified driver if successful, or to a built in /dev/null device if the path name is invalid. After a driver is open, that pointer is used for all other driver access functions. This abstraction is incredibly useful � any peripheral or service can be accessed through a consistent set of APIs, that make it easy to substitute implementations from one platform to another. Portability is ensured, the overhead is negligible, and it emphasizes the reuse of both driver and application code as separate entities. Consider a system with drivers for I2C, SPI, and UART peripherals - under our driver framework, an application can initialize these peripherals and write a greeting to each using the same simple API functions for all drivers: \code pstI2C = DriverList_FindByName("/dev/i2c"); pstUART = DriverList_FindByName("/dev/tty0"); pstSPI = DriverList_FindByName("/dev/spi"); pstI2C->Write(12,"Hello World!"); pstUART->Write(12, "Hello World!"); pstSPI->Write(12, "Hello World!"); \endcode */ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #ifndef __DRIVER_H__ #define __DRIVER_H__ #if KERNEL_USE_DRIVER #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- typedef K_UCHAR (*OpenFunc_t)(void *pvCtx_); typedef K_UCHAR (*CloseFunc_t)(void *pvCtx_); typedef K_USHORT (*ReadFunc_t)(void *pvCtx_, K_USHORT usSize_, K_UCHAR *pucData_ ); typedef K_USHORT (*WriteFunc_t)(void *pvCtx_, K_USHORT usSize_, K_UCHAR *pucData_ ); typedef K_USHORT (*ControlFunc_t)(void *pvCtx, K_USHORT usEvent_, K_USHORT usInSize_, K_UCHAR *pucIn_, K_USHORT usOutSize_, K_UCHAR *pucOut_); //--------------------------------------------------------------------------- typedef struct { OpenFunc_t pfOpen; CloseFunc_t pfClose; ReadFunc_t pfRead; WriteFunc_t pfWrite; ControlFunc_t pfControl; } DriverVTable_t; //--------------------------------------------------------------------------- typedef struct { // Inherit from LinkListNode -- must go first LinkListNode_t stNode; DriverVTable_t *pstVTable; const K_CHAR *szName; } Driver_t; //--------------------------------------------------------------------------- /*! Base device-driver object used in hardware abstraction. All other device drivers inherit from this object */ /*! \fn void Init() Initialize a driver, must be called prior to use */ void Driver_Init( Driver_t *pstDriver_ ); //--------------------------------------------------------------------------- /*! \fn K_UCHAR Open() Open a device driver prior to use. \return Driver-specific return code, 0 = OK, non-0 = error */ K_UCHAR Driver_Open( Driver_t *pstDriver_ ); //--------------------------------------------------------------------------- /*! \fn K_UCHAR Close() Close a previously-opened device driver. \return Driver-specific return code, 0 = OK, non-0 = error */ K_UCHAR Driver_Close( Driver_t *pstDriver_ ); //--------------------------------------------------------------------------- /*! \fn K_USHORT Read( K_USHORT usBytes_, K_UCHAR *pucData_) Read a specified number of bytes from the device into a specific buffer. Depending on the driver-specific implementation, this may be a number less than the requested number of bytes read, indicating that there there was less input than desired, or that as a result of buffering, the data may not be available. \param usBytes_ Number of bytes to read (<= size of the buffer) \param pucData_ Pointer to a data buffer receiving the read data \return Number of bytes actually read */ K_USHORT Driver_Read( Driver_t *pstDriver_, K_USHORT usSize_, K_UCHAR *pucData_ ); //--------------------------------------------------------------------------- /*! \fn K_USHORT Write( K_USHORT usBytes_, K_UCHAR *pucData_) Write a payload of data of a given length to the device. Depending on the implementation of the driver, the amount of data written to the device may be less than the requested number of bytes. A result less than the requested size may indicate that the device buffer is full, indicating that the user must retry the write at a later point with the remaining data. \param usBytes_ Number of bytes to write (<= size of the buffer) \param pucData_ Pointer to a data buffer containing the data to write \return Number of bytes actually written */ K_USHORT Driver_Write( Driver_t *pstDriver_, K_USHORT usSize_, K_UCHAR *pucData_ ); //--------------------------------------------------------------------------- /*! \fn K_USHORT Control( K_USHORT usEvent_, void *pvDataIn_, K_USHORT usSizeIn_, void *pvDataOut_, K_USHORT usSizeOut_ ) This is the main entry-point for device-specific io and control operations. This is used for implementing all "side-channel" communications with a device, and any device-specific IO operations that do not conform to the typical POSIX read/write paradigm. Use of this funciton is analagous to the non-POSIX (yet still common) devctl() or ioctl(). \param usEvent_ Code defining the io event (driver-specific) \param pvDataIn_ Pointer to the intput data \param usSizeIn_ Size of the input data (in bytes) \param pvDataOut_ Pointer to the output data \param usSizeOut_ Size of the output data (in bytes) \return Driver-specific return code, 0 = OK, non-0 = error */ K_USHORT Driver_Control( Driver_t *pstDriver_, K_USHORT usEvent_, K_USHORT usInSize_, K_UCHAR *pucIn_, K_USHORT usOutSize_, K_UCHAR *pucOut_); //--------------------------------------------------------------------------- /*! \fn void SetName( const K_CHAR *pcName_ ) Set the path for the driver. Name must be set prior to access (since driver access is name-based). \param pcName_ String constant containing the device path */ void Driver_SetName( Driver_t *pstDriver_, const K_CHAR *pcName_ ); //--------------------------------------------------------------------------- /*! \fn const K_CHAR *GetPath() Returns a string containing the device path. \return pcName_ Return the string constant representing the device path */ const K_CHAR *Driver_GetPath( Driver_t *pstDriver_ ); //--------------------------------------------------------------------------- /*! List of Driver objects used to keep track of all device drivers in the system. By default, the list contains a single entity, "/dev/null". */ void DriverList_Init( void ); //--------------------------------------------------------------------------- Driver_t *DriverList_FindByPath( const K_CHAR *pcPath ); //--------------------------------------------------------------------------- void DriverList_Add( Driver_t *pstDriver_ ); #ifdef __cplusplus } #endif #endif //KERNEL_USE_DRIVER #endif
moslevin/Mark3C
kernel/tracebuffer.c
<reponame>moslevin/Mark3C /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file tracebuffer.cpp \brief Kernel trace buffer object definition */ #include "kerneltypes.h" #include "tracebuffer.h" #include "mark3cfg.h" #include "writebuf16.h" #include "kerneldebug.h" #if KERNEL_USE_DEBUG && !KERNEL_AWARE_SIMULATION //--------------------------------------------------------------------------- static WriteBuffer16_t stBuffer; //!< Object used to implement the tracebuffer static volatile K_USHORT usIndex; //!< Current print index static K_USHORT ausBuffer[ (TRACE_BUFFER_SIZE / sizeof( K_USHORT )) ]; //!< Data buffer //--------------------------------------------------------------------------- void TraceBuffer_Init() { WriteBuffer16_SetBuffers( &stBuffer, ausBuffer, TRACE_BUFFER_SIZE/sizeof(K_USHORT)); usIndex = 0; } //--------------------------------------------------------------------------- K_USHORT TraceBuffer_Increment() { return usIndex++; } //--------------------------------------------------------------------------- void TraceBuffer_Write( K_USHORT *pusData_, K_USHORT usSize_ ) { // Pipe the data directly to the circular buffer WriteBuffer16_WriteData( &stBuffer, pusData_, usSize_ ); } //--------------------------------------------------------------------------- void TraceBuffer_SetCallback( WriteBufferCallback pfCallback_ ) { WriteBuffer16_SetCallback( &stBuffer, pfCallback_ ); } #endif
moslevin/Mark3C
tests/unit/ut_mutex/ut_mutex.c
<filename>tests/unit/ut_mutex/ut_mutex.c /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ //--------------------------------------------------------------------------- #include "kerneltypes.h" #include "kernel.h" #include "../ut_platform.h" #include "thread.h" #include "mutex.h" //=========================================================================== // Local Defines //=========================================================================== #define MUTEX_STACK_SIZE (256) static K_WORD aucTestStack[MUTEX_STACK_SIZE]; static Thread_t stMutexThread; static K_WORD aucTestStack2[MUTEX_STACK_SIZE]; static Thread_t stTestThread2; static volatile K_UCHAR ucToken; //=========================================================================== // Define Test Cases Here //=========================================================================== void TypicalMutexTest(void *mutex_) { Mutex_t *pstMutex = (Mutex_t*)mutex_; Mutex_Claim( pstMutex ); ucToken = 0x69; Mutex_Release( pstMutex ); // Exit the thread when we're done this operation. Thread_Exit( Scheduler_GetCurrentThread() ); } TEST(ut_typical_mutex) { // Test - Typical mutex usage, ensure that two threads can synchronize // access to a single resource Mutex_t stMutex; Mutex_Init( &stMutex ); // Create a higher-priority thread that will immediately pre-empt us. // Verify that while we have the mutex held, that the high-priority thread // is blocked waiting for us to relinquish access. Thread_Init( &stMutexThread, aucTestStack, MUTEX_STACK_SIZE, 7, TypicalMutexTest, (void*)&stMutex); Mutex_Claim( &stMutex ); ucToken = 0x96; Thread_Start( &stMutexThread ); // Spend some time sleeping, just to drive the point home... Thread_Sleep(100); // Test Point - Verify that the token value hasn't changed (which would // indicate the high-priority thread held the mutex...) EXPECT_EQUALS( ucToken, 0x96 ); // Relese the mutex, see what happens. Mutex_Release( &stMutex ); // Test Point - Verify that after releasing the mutex, the higher-priority // thread immediately resumes, claiming the mutex, and adjusting the // token value to its value. Check the new token value here. EXPECT_EQUALS( ucToken, 0x69 ); } TEST_END //=========================================================================== void TimedMutexTest(void *mutex_) { Mutex_t *pstMutex = (Mutex_t*)mutex_; Mutex_Claim( pstMutex ); Thread_Sleep(20); Mutex_Release( pstMutex ); Thread_Exit( Scheduler_GetCurrentThread() ); } //=========================================================================== TEST(ut_timed_mutex) { // Test - Enusre that when a thread fails to obtain a resource in a // timeout scenario, that the timeout is reported correctly Mutex_t stMutex; Mutex_Init( &stMutex ); Thread_Init( &stMutexThread, aucTestStack, MUTEX_STACK_SIZE, 7, TimedMutexTest, (void*)&stMutex); Thread_Start( &stMutexThread ); EXPECT_FALSE( Mutex_TimedClaim( &stMutex, 10 ) ); Thread_Sleep(20); Thread_Init( &stMutexThread, aucTestStack, MUTEX_STACK_SIZE, 7, TimedMutexTest, (void*)&stMutex); Thread_Start( &stMutexThread ); EXPECT_TRUE( Mutex_TimedClaim( &stMutex, 30 ) ); } TEST_END //=========================================================================== void LowPriThread(void *mutex_) { Mutex_t *pstMutex = (Mutex_t*)mutex_; Mutex_Claim( pstMutex ); Thread_Sleep( 100 ); Mutex_Release( pstMutex ); while(1) { Thread_Sleep(1000); } } //=========================================================================== void HighPriThread(void *mutex_) { Mutex_t *pstMutex = (Mutex_t*)mutex_; Mutex_Claim( pstMutex ); Thread_Sleep(100); Mutex_Release( pstMutex ); while(1) { Thread_Sleep(1000); } } //=========================================================================== TEST(ut_priority_mutex) { // Test - Priority inheritence protocol. Ensure that the priority // inversion problem is correctly avoided by our semaphore implementation // In the low/med/high scenario, we play the "med" priority thread Mutex_t stMutex; Mutex_Init( &stMutex ); Thread_SetPriority( Scheduler_GetCurrentThread(), 3 ); Thread_Init( &stMutexThread, aucTestStack, MUTEX_STACK_SIZE, 2, LowPriThread, (void*)&stMutex); Thread_Init( &stTestThread2, aucTestStack2, MUTEX_STACK_SIZE, 4, HighPriThread, (void*)&stMutex); // Start the low-priority thread and give it the mutex Thread_Start( &stMutexThread ); Thread_Sleep(20); // Start the high-priority thread, which will block, waiting for the // low-priority action to complete... Thread_Start( &stTestThread2 ); Thread_Sleep(20); // Test point - Low-priority thread boost: // Check the priorities of the threads. The low-priority thread // should now have the same priority as the high-priority thread EXPECT_EQUALS(Thread_GetCurPriority( &stMutexThread ), 4 ); EXPECT_EQUALS(Thread_GetCurPriority( &stTestThread2 ), 4 ); Thread_Sleep(2000); // Test point - Low-priority thread drop: // After the threads have relinquished their mutexes, ensure that // they are placed back at their correct priorities EXPECT_EQUALS( Thread_GetCurPriority( &stMutexThread ), 2 ); EXPECT_EQUALS( Thread_GetCurPriority( &stTestThread2 ), 4 ); Thread_Exit( &stMutexThread ); Thread_Exit( &stTestThread2 ); } TEST_END //=========================================================================== // Test Whitelist Goes Here //=========================================================================== TEST_CASE_START TEST_CASE(ut_typical_mutex), TEST_CASE(ut_timed_mutex), TEST_CASE(ut_priority_mutex), TEST_CASE_END
moslevin/Mark3C
kernel/public/quantum.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file quantum.h \brief Thread_t Quantum declarations for Round-Robin Scheduling */ #ifndef __KQUANTUM_H__ #define __KQUANTUM_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "thread.h" #include "timer.h" #include "timerlist.h" #include "timerscheduler.h" #if KERNEL_USE_QUANTUM #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- /*! Static-object used to implement Thread_t quantum functionality, which is a key part of round-robin scheduling. */ //--------------------------------------------------------------------------- /*! \fn void UpdateTimer() This function is called to update the thread quantum timer whenever something in the scheduler has changed. This can result in the timer being re-loaded or started. The timer is never stopped, but if may be ignored on expiry. */ void Quantum_UpdateTimer( void ); //--------------------------------------------------------------------------- /*! \fn void AddThread( Thread_t *pstThread_ ) Add the thread to the quantum timer. Only one thread can own the quantum, since only one thread can be running on a core at a time. */ void Quantum_AddThread( Thread_t *pstThread_ ); //--------------------------------------------------------------------------- /*! \fn void RemoveThread() Remove the thread from the quantum timer. This will cancel the timer. */ void Quantum_RemoveThread( void ); //--------------------------------------------------------------------------- /*! * \brief SetInTimer * * Set a flag to indicate that the CPU is currently running within the * timer-callback routine. This prevents the Quantum timer from being * updated in the middle of a callback cycle, potentially resulting in * the kernel timer becoming disabled. */ void Quantum_SetInTimer( void ); //--------------------------------------------------------------------------- /*! * \brief ClearInTimer * * Clear the flag once the timer callback function has been completed. */ void Quantum_ClearInTimer( void ); //--------------------------------------------------------------------------- /*! \fn void SetTimer( Thread_t *pstThread_ ) Set up the quantum timer in the timer scheduler. This creates a one-shot timer, which calls a static callback in quantum.cpp that on expiry will pivot the head of the threadlist for the thread's priority. This is the mechanism that provides round-robin scheduling in the system. \param pstThread_ Pointer to the thread to set the Quantum timer on */ void Quantum_SetTimer( Thread_t *pstThread_ ); #ifdef __cplusplus } #endif #endif //KERNEL_USE_QUANTUM #endif
moslevin/Mark3C
kernel/kernelaware.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernelaware.cpp \brief Kernel aware simulation support */ #include "kerneltypes.h" #include "mark3cfg.h" #include "kernelaware.h" #include "threadport.h" #if KERNEL_AWARE_SIMULATION //--------------------------------------------------------------------------- /*! This structure is used to communicate between the kernel and a kernel- aware host. Its data contents is interpreted differently depending on the command executed (by means of setting the g_ucKACommand variable, as is done in the command handlers in this module). As a result, any changes to this struct by way of modifying or adding data must be mirrored in the kernel-aware simulator. */ typedef union { volatile K_USHORT ausBuffer[5]; //!< Raw binary contents of the struct /*! * \brief The Profiler struct contains data related to the code-execution * profiling functionality provided by a kernel-aware host simluator. */ struct { volatile const K_CHAR *szName; //!< Name of the profiling data to report } Profiler; /*! * \brief The Trace struct contains data related to the display and output * of kernel-trace strings on a kernel-aware host. */ struct { volatile K_USHORT usFile; //!< File index volatile K_USHORT usLine; //!< Line number volatile K_USHORT usCode; //!< Print code volatile K_USHORT usArg1; //!< (optional) argument code volatile K_USHORT usArg2; //!< (optional) argument code } Trace; /*! * \brief The Print struct contains data related to the display of arbitrary * null-terminated ASCII strings on the kernel-aware host. */ struct { volatile const K_CHAR *szString; //!< Pointer ot a string (in RAM) to print } Print; } KernelAwareData_t; //--------------------------------------------------------------------------- volatile K_BOOL g_bIsKernelAware = false; //!< Will be set to true by a kernel-aware host. volatile K_UCHAR g_ucKACommand; //!< Kernel-aware simulator command to execute KernelAwareData_t g_stKAData; //!< Data structure used to communicate with host. //--------------------------------------------------------------------------- /*! * \brief Trace_i * * Private function by which the object's Trace() methods are reflected, which * allows us to realize a modest code saving. * * \param usFile_ 16-bit code representing the file * \param usLine_ 16-bit code representing the line in the file * \param usCode_ 16-bit data code, which indicates the line's format * \param usArg1_ 16-bit argument to the format string. * \param usArg2_ 16-bit argument to the format string. * \param eCmd_ Code indicating the number of arguments to emit. */ static void KernelAware_Trace_i( K_USHORT usFile_, K_USHORT usLine_, K_USHORT usCode_, K_USHORT usArg1_, K_USHORT usArg2_, KernelAwareCommand_t eCmd_); //--------------------------------------------------------------------------- void KernelAware_ProfileInit(const K_CHAR *szStr_) { CS_ENTER(); g_stKAData.Profiler.szName = szStr_; g_ucKACommand = KA_COMMAND_PROFILE_INIT; CS_EXIT(); } //--------------------------------------------------------------------------- void KernelAware_ProfileStart(void) { g_ucKACommand = KA_COMMAND_PROFILE_START; } //--------------------------------------------------------------------------- void KernelAware_ProfileStop(void) { g_ucKACommand = KA_COMMAND_PROFILE_STOP; } //--------------------------------------------------------------------------- void KernelAware_ProfileReport(void) { g_ucKACommand = KA_COMMAND_PROFILE_REPORT; } //--------------------------------------------------------------------------- void KernelAware_ExitSimulator(void) { g_ucKACommand = KA_COMMAND_EXIT_SIMULATOR; } //--------------------------------------------------------------------------- void KernelAware_Trace( K_USHORT usFile_, K_USHORT usLine_, K_USHORT usCode_ ) { KernelAware_Trace_i( usFile_, usLine_, usCode_, 0, 0, KA_COMMAND_TRACE_0 ); } //--------------------------------------------------------------------------- void KernelAware_Trace1( K_USHORT usFile_, K_USHORT usLine_, K_USHORT usCode_, K_USHORT usArg1_) { KernelAware_Trace_i( usFile_, usLine_, usCode_, usArg1_, 0 ,KA_COMMAND_TRACE_1 ); } //--------------------------------------------------------------------------- void KernelAware_Trace2( K_USHORT usFile_, K_USHORT usLine_, K_USHORT usCode_, K_USHORT usArg1_, K_USHORT usArg2_) { KernelAware_Trace_i( usFile_, usLine_, usCode_, usArg1_, usArg2_, KA_COMMAND_TRACE_2 ); } //--------------------------------------------------------------------------- void KernelAware_Trace_i( K_USHORT usFile_, K_USHORT usLine_, K_USHORT usCode_, K_USHORT usArg1_, K_USHORT usArg2_, KernelAwareCommand_t eCmd_ ) { CS_ENTER(); g_stKAData.Trace.usFile = usFile_; g_stKAData.Trace.usLine = usLine_; g_stKAData.Trace.usCode = usCode_; g_stKAData.Trace.usArg1 = usArg1_; g_stKAData.Trace.usArg2 = usArg2_; g_ucKACommand = eCmd_; CS_EXIT(); } //--------------------------------------------------------------------------- void KernelAware_Print(const K_CHAR *szStr_) { CS_ENTER(); g_stKAData.Print.szString = szStr_; g_ucKACommand = KA_COMMAND_PRINT; CS_EXIT(); } //--------------------------------------------------------------------------- K_BOOL KernelAware_IsSimulatorAware(void) { return g_bIsKernelAware; } #endif
moslevin/Mark3C
kernel/cpu/cm0/stm32f0/gcc/kernelswi.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernelswi.cpp \brief Kernel Software interrupt implementation for ARM Cortex-M0 */ #include "kerneltypes.h" #include "kernelswi.h" #include "threadport.h" //--------------------------------------------------------------------------- void KernelSWI_Config(void) { NVIC_SetPriority(SVC_IRQn, (1<<__NVIC_PRIO_BITS) - 1); NVIC_SetPriority(PendSV_IRQn, (1<<__NVIC_PRIO_BITS) - 1); } //--------------------------------------------------------------------------- void KernelSWI_Start(void) { // Nothing to do... } //--------------------------------------------------------------------------- void KernelSWI_Stop(void) { // Nothing to do... } //--------------------------------------------------------------------------- K_UCHAR KernelSWI_DI() { // Not implemented return 0; } //--------------------------------------------------------------------------- void KernelSWI_RI(K_BOOL bEnable_) { // Not implemented } //--------------------------------------------------------------------------- void KernelSWI_Clear(void) { // There's no convenient CMSIS function call for PendSV set/clear, // But we do at least have some structs/macros. // Note that set/clear each have their own bits in the same register. // Setting the "set" or "clear" bit results in the desired operation. SCB->ICSR |= SCB_ICSR_PENDSVCLR_Msk; } //--------------------------------------------------------------------------- void KernelSWI_Trigger(void) { SCB->ICSR |= SCB_ICSR_PENDSVSET_Msk; }
moslevin/Mark3C
kernel/public/scheduler.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file scheduler.h \brief Thread_t scheduler function declarations This scheduler implements a very flexible type of scheduling, which has become the defacto industry standard when it comes to real-time operating systems. This scheduling mechanism is referred to as priority round- robin. From the name, there are two concepts involved here: 1) Priority scheduling: Threads are each assigned a priority, and the thread with the highest priority which is ready to run gets to execute. 2) Round-robin scheduling: Where there are multiple ready threads at the highest-priority level, each thread in that group gets to share time, ensuring that progress is made. The scheduler uses an array of ThreadList_t objects to provide the necessary housekeeping required to keep track of threads at the various priorities. As s result, the scheduler contains one ThreadList_t per priority, with an additional list to manage the storage of threads which are in the "stopped" state (either have been stopped, or have not been started yet). */ #ifndef __SCHEDULER_H__ #define __SCHEDULER_H__ #include "kerneltypes.h" #include "thread.h" #include "threadport.h" #ifdef __cplusplus extern "C" { #endif #define NUM_PRIORITIES (8) //!< Defines the maximum number of thread priorities supported in the scheduler //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- extern volatile Thread_t *g_pstNext; extern Thread_t *g_pstCurrent; extern K_BOOL bEnabled; //! Scheduler's state - enabled or disabled //--------------------------------------------------------------------------- /*! \brief Scheduler_Init Intiailize the scheduler, must be called before use. */ void Scheduler_Init( void ); //--------------------------------------------------------------------------- /*! \brief Scheduler_Schedule Run the scheduler, determines the next thread to run based on the current state of the threads. Note that the next-thread chosen from this function is only valid while in a critical section. */ void Scheduler_Schedule( void ); //--------------------------------------------------------------------------- /*! \brief Scheduler_Add Add a thread to the scheduler at its current priority level. \param pstThread_ Pointer to the thread to add to the scheduler */ void Scheduler_Add(Thread_t *pstThread_); //--------------------------------------------------------------------------- /*! \brief Scheduler_Remove Remove a thread from the scheduler at its current priority level. \param pstThread_ Pointer to the thread to be removed from the scheduler */ void Scheduler_Remove(Thread_t *pstThread_); //--------------------------------------------------------------------------- /*! \brief Scheduler_SetScheduler Set the active state of the scheduler. When the scheduler is disabled, the *next thread* is never set; the currently running thread will run forever until the scheduler is enabled again. Care must be taken to ensure that we don't end up trying to block while the scheduler is disabled, otherwise the system ends up in an unusable state. \param bEnable_ true to enable, false to disable the scheduler */ K_BOOL Scheduler_SetScheduler(K_BOOL bEnable_); //--------------------------------------------------------------------------- /*! \brief Scheduler_GetThreadList Return the pointer to the active list of threads that are at the given priority level in the scheduler. \param ucPriority_ Priority level of \return Pointer to the ThreadList_t for the given priority level */ ThreadList_t *Scheduler_GetThreadList( K_UCHAR ucPriority_ ); //--------------------------------------------------------------------------- /*! \brief Scheduler_GetCurrentThread Return the pointer to the currently-running thread. \return Pointer to the currently-running thread */ #define Scheduler_GetCurrentThread() ( g_pstCurrent ) //--------------------------------------------------------------------------- /*! \brief Scheduler_GetNextThread Return the pointer to the thread that should run next, according to the last run of the scheduler. \return Pointer to the next-running thread */ #define Scheduler_GetNextThread() ( g_pstNext ) //--------------------------------------------------------------------------- /*! \brief Scheduler_IsEnabled Return the current state of the scheduler - whether or not scheudling is enabled or disabled. \return true - scheduler enabled, false - disabled */ #define Scheduler_IsEnabled() ( bEnabled ) //--------------------------------------------------------------------------- /*! * \brief Scheduler_QueueScheduler * * Tell the kernel to perform a scheduling operation as soon as the * scheduler is re-enabled. */ void Scheduler_QueueScheduler(); //--------------------------------------------------------------------------- /*! \brief Scheduler_GetStopList Return the pointer to the list of threads that are in the scheduler's stopped state. \return Pointer to the ThreadList_t containing the stopped threads */ ThreadList_t *Scheduler_GetStopList(); #ifdef __cplusplus } #endif #endif
moslevin/Mark3C
kernel/public/kernelaware.h
<reponame>moslevin/Mark3C<filename>kernel/public/kernelaware.h /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernelaware.h \brief Kernel aware simulation support */ #ifndef __KERNEL_AWARE_H__ #define __KERNEL_AWARE_H__ #include "mark3cfg.h" #include "kerneltypes.h" #if KERNEL_AWARE_SIMULATION #ifdef __cplusplus extern "C" { #endif extern volatile K_BOOL g_bIsKernelAware; //!< Will be set to true by a kernel-aware host. extern volatile K_UCHAR g_ucKACommand; //!< Kernel-aware simulator command to execute //--------------------------------------------------------------------------- /*! This enumeration contains a list of supported commands that can be executed to invoke a response from a kernel aware host. */ typedef enum { KA_COMMAND_IDLE = 0, //!< Null command, does nothing. KA_COMMAND_PROFILE_INIT, //!< Initialize a new profiling session KA_COMMAND_PROFILE_START, //!< Begin a profiling sample KA_COMMAND_PROFILE_STOP, //!< End a profiling sample KA_COMMAND_PROFILE_REPORT, //!< Report current profiling session KA_COMMAND_EXIT_SIMULATOR, //!< Terminate the host simulator KA_COMMAND_TRACE_0, //!< 0-argument kernel trace KA_COMMAND_TRACE_1, //!< 1-argument kernel trace KA_COMMAND_TRACE_2, //!< 2-argument kernel trace KA_COMMAND_PRINT //!< Print an arbitrary string of data } KernelAwareCommand_t; //--------------------------------------------------------------------------- /*! * \brief The KernelAware object * * This object contains functions that are used to trigger kernel-aware * functionality within a supported simulation environment (i.e. flAVR). * * These static methods operate on a singleton set of global variables, * which are monitored for changes from within the simulator. The simulator * hooks into these variables by looking for the correctly-named symbols in * an elf-formatted binary being run and registering callbacks that are called * whenever the variables are changed. On each change of the command variable, * the kernel-aware data is analyzed and interpreted appropriately. * * If these methods are run in an unsupported simulator or on actual hardware * the commands generally have no effect (except for the exit-on-reset command, * which will result in a jump-to-0 reset). */ //--------------------------------------------------------------------------- /*! * \brief ProfileInit * * Initializes the kernel-aware profiler. This function instructs the * kernel-aware simulator to reset its accounting variables, and prepare to * start counting profiling data tagged to the given string. How this is * handled is the responsibility of the simulator. * * \param szStr_ String to use as a tag for the profilng session. */ void KernelAware_ProfileInit( const K_CHAR *szStr_ ); //--------------------------------------------------------------------------- /*! * \brief ProfileStart * * Instruct the kernel-aware simulator to begin counting cycles towards the * current profiling counter. * */ void KernelAware_ProfileStart( void ); //--------------------------------------------------------------------------- /*! * \brief ProfileStop * * Instruct the kernel-aware simulator to end counting cycles relative to the * current profiling counter's iteration. */ void KernelAware_ProfileStop( void ); //--------------------------------------------------------------------------- /*! * \brief ProfileReport * * Instruct the kernel-aware simulator to print a report for its current * profiling data. * */ void KernelAware_ProfileReport( void ); //--------------------------------------------------------------------------- /*! * \brief ExitSimulator * * Instruct the kernel-aware simulator to terminate (destroying the virtual * CPU). * */ void KernelAware_ExitSimulator( void ); //--------------------------------------------------------------------------- /*! * \brief Print * * Instruct the kernel-aware simulator to print a char string * * \param szStr_ */ void KernelAware_Print( const K_CHAR *szStr_ ); //--------------------------------------------------------------------------- /*! * \brief Trace * * Insert a kernel trace statement into the kernel-aware simulator's debug * data stream. * * \param usFile_ 16-bit code representing the file * \param usLine_ 16-bit code representing the line in the file * \param usCode_ 16-bit data code, which indicates the line's format. */ void KernelAware_Trace( K_USHORT usFile_, K_USHORT usLine_, K_USHORT usCode_ ); //--------------------------------------------------------------------------- /*! * \brief Trace * * Insert a kernel trace statement into the kernel-aware simulator's debug * data stream. * * \param usFile_ 16-bit code representing the file * \param usLine_ 16-bit code representing the line in the file * \param usCode_ 16-bit data code, which indicates the line's format * \param usArg1_ 16-bit argument to the format string. */ void KernelAware_Trace1( K_USHORT usFile_, K_USHORT usLine_, K_USHORT usCode_, K_USHORT usArg1_); //--------------------------------------------------------------------------- /*! * \brief Trace * * Insert a kernel trace statement into the kernel-aware simulator's debug * data stream. * * \param usFile_ 16-bit code representing the file * \param usLine_ 16-bit code representing the line in the file * \param usCode_ 16-bit data code, which indicates the line's format * \param usArg1_ 16-bit argument to the format string. * \param usArg2_ 16-bit argument to the format string. */ void KernelAware_Trace2( K_USHORT usFile_, K_USHORT usLine_, K_USHORT usCode_, K_USHORT usArg1_, K_USHORT usArg2_); //--------------------------------------------------------------------------- /*! * \brief IsSimulatorAware * * Use this function to determine whether or not the code is running on a * simulator that is aware of the kernel. * * \return true - the application is being run in a kernel-aware simulator. * false - otherwise. */ K_BOOL KernelAware_IsSimulatorAware(void); #ifdef __cplusplus } #endif #endif #endif
moslevin/Mark3C
kernel/cpu/avr/atmega328p/gcc/threadport.c
<filename>kernel/cpu/avr/atmega328p/gcc/threadport.c<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file threadport.cpp \brief ATMega328p Multithreading */ #include "kerneltypes.h" #include "mark3cfg.h" #include "thread.h" #include "threadport.h" #include "kernelswi.h" #include "kerneltimer.h" #include "timerlist.h" #include "quantum.h" #include "kernel.h" #include "kernelaware.h" #include <avr/io.h> #include <avr/interrupt.h> //--------------------------------------------------------------------------- void ThreadPort_InitStack(Thread_t *pstThread_) { // Initialize the stack for a Thread_t K_USHORT usAddr; K_UCHAR *pucStack; K_USHORT i; // Get the address of the thread's entry function usAddr = (K_USHORT)(pstThread_->pfEntryPoint); // Start by finding the bottom of the stack pucStack = (K_UCHAR*)pstThread_->pwStackTop; // clear the stack, and initialize it to a known-default value (easier // to debug when things go sour with stack corruption or overflow) for (i = 0; i < pstThread_->usStackSize; i++) { pstThread_->pwStack[i] = 0xFF; } // Our context starts with the entry function PUSH_TO_STACK(pucStack, (K_UCHAR)(usAddr & 0x00FF)); PUSH_TO_STACK(pucStack, (K_UCHAR)((usAddr >> 8) & 0x00FF)); // R0 PUSH_TO_STACK(pucStack, 0x00); // R0 // Push status register and R1 (which is used as a constant zero) PUSH_TO_STACK(pucStack, 0x80); // SR PUSH_TO_STACK(pucStack, 0x00); // R1 // Push other registers for (i = 2; i <= 23; i++) //R2-R23 { PUSH_TO_STACK(pucStack, i); } // Assume that the argument is the only stack variable PUSH_TO_STACK(pucStack, (K_UCHAR)(((K_USHORT)(pstThread_->pvArg)) & 0x00FF)); //R24 PUSH_TO_STACK(pucStack, (K_UCHAR)((((K_USHORT)(pstThread_->pvArg))>>8) & 0x00FF)); //R25 // Push the rest of the registers in the context for (i = 26; i <=31; i++) { PUSH_TO_STACK(pucStack, i); } // Set the top o' the stack. pstThread_->pwStackTop = (K_UCHAR*)pucStack; // That's it! the thread is ready to run now. } //--------------------------------------------------------------------------- static void Thread_Switch(void) { #if KERNEL_USE_IDLE_FUNC // If there's no next-thread-to-run... if (g_pstNext == Kernel_GetIdleThread()) { g_pstCurrent = Kernel_GetIdleThread(); // Disable the SWI, and re-enable interrupts -- enter nested interrupt // mode. KernelSWI_DI(); K_UCHAR ucSR = _SFR_IO8(SR_); // So long as there's no "next-to-run" thread, keep executing the Idle // function to conclusion... while (g_pstNext == Kernel_GetIdleThread()) { // Ensure that we run this block in an interrupt enabled context (but // with the rest of the checks being performed in an interrupt disabled // context). ASM( "sei" ); Kernel_IdleFunc(); ASM( "cli" ); } // Progress has been achieved -- an interrupt-triggered event has caused // the scheduler to run, and choose a new thread. Since we've already // saved the context of the thread we've hijacked to run idle, we can // proceed to disable the nested interrupt context and switch to the // new thread. _SFR_IO8(SR_) = ucSR; KernelSWI_RI( true ); } #endif g_pstCurrent = (Thread_t*)g_pstNext; } //--------------------------------------------------------------------------- void ThreadPort_StartThreads() { KernelSWI_Config(); // configure the task switch SWI KernelTimer_Config(); // configure the kernel timer Scheduler_SetScheduler(1); // enable the scheduler Scheduler_Schedule(); // run the scheduler - determine the first thread to run Thread_Switch(); // Set the next scheduled thread to the current thread KernelTimer_Start(); // enable the kernel timer KernelSWI_Start(); // enable the task switch SWI // Restore the context... Thread_RestoreContext(); // restore the context of the first running thread ASM("reti"); // return from interrupt - will return to the first scheduled thread } //--------------------------------------------------------------------------- /*! SWI using INT0 - used to trigger a context switch \fn ISR(INT0_vect) __attribute__ ( ( signal, naked ) ); */ //--------------------------------------------------------------------------- ISR(INT0_vect) __attribute__ ( ( signal, naked ) ); ISR(INT0_vect) { Thread_SaveContext(); // Push the context (registers) of the current task Thread_Switch(); // Switch to the next task Thread_RestoreContext(); // Pop the context (registers) of the next task ASM("reti"); // Return to the next task } //--------------------------------------------------------------------------- /*! Timer_t interrupt ISR - causes a tick, which may cause a context switch \fn ISR(TIMER1_COMPA_vect) ; */ //--------------------------------------------------------------------------- ISR(TIMER1_COMPA_vect) { #if KERNEL_USE_TIMERS TimerScheduler_Process(); #endif #if KERNEL_USE_QUANTUM Quantum_UpdateTimer(); #endif }
moslevin/Mark3C
kernel/cpu/cm0/stm32f0/gcc/kernelprofile.c
<reponame>moslevin/Mark3C /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernelprofile.cpp \brief Profiling timer implementation */ #include "kerneltypes.h" #include "mark3cfg.h" #include "profile.h" #include "kernelprofile.h" #include "threadport.h" #if KERNEL_USE_PROFILER K_ULONG m_ulEpoch; //--------------------------------------------------------------------------- void Profiler_Init() { } //--------------------------------------------------------------------------- void Profiler_Start() { } //--------------------------------------------------------------------------- void Profiler_Stop() { } //--------------------------------------------------------------------------- K_USHORT Profiler_Read() { return 0; } //--------------------------------------------------------------------------- void Profiler_Process() { } //--------------------------------------------------------------------------- K_ULONG Profiler_GetEpoch() { return m_ulEpoch; } #endif
moslevin/Mark3C
stage/src/kerneltimer.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kerneltimer.h \brief Kernel Timer_t Class declaration */ #include "kerneltypes.h" #ifndef __KERNELTIMER_H_ #define __KERNELTIMER_H_ #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- #define SYSTEM_FREQ ((K_ULONG)16000000) #define TIMER_FREQ ((K_ULONG)(SYSTEM_FREQ / 256)) // Timer_t ticks per second... //--------------------------------------------------------------------------- /*! \fn void Config(void) Initializes the kernel timer before use */ void KernelTimer_Config(void); //--------------------------------------------------------------------------- /*! \fn void Start(void) Starts the kernel time (must be configured first) */ void KernelTimer_Start(void); //--------------------------------------------------------------------------- /*! \fn void Stop(void) Shut down the kernel timer, used when no timers are scheduled */ void KernelTimer_Stop(void); //--------------------------------------------------------------------------- /*! \fn K_UCHAR DI(void) Disable the kernel timer's expiry interrupt */ K_UCHAR KernelTimer_DI(void); //--------------------------------------------------------------------------- /*! \fn void RI(K_BOOL bEnable_) Retstore the state of the kernel timer's expiry interrupt. \param bEnable_ 1 enable, 0 disable */ void KernelTimer_RI(K_BOOL bEnable_); //--------------------------------------------------------------------------- /*! \fn void EI(void) Enable the kernel timer's expiry interrupt */ void KernelTimer_EI(void); //--------------------------------------------------------------------------- /*! \fn K_ULONG SubtractExpiry(K_ULONG ulInterval_) Subtract the specified number of ticks from the timer's expiry count register. Returns the new expiry value stored in the register. \param ulInterval_ Time (in HW-specific) ticks to subtract \return Value in ticks stored in the timer's expiry register */ K_ULONG KernelTimer_SubtractExpiry(K_ULONG ulInterval_); //--------------------------------------------------------------------------- /*! \fn K_ULONG TimeToExpiry(void) Returns the number of ticks remaining before the next timer expiry. \return Time before next expiry in platform-specific ticks */ K_ULONG KernelTimer_TimeToExpiry(void); //--------------------------------------------------------------------------- /*! \fn K_ULONG SetExpiry(K_ULONG ulInterval_) Resets the kernel timer's expiry interval to the specified value \param ulInterval_ Desired interval in ticks to set the timer for \return Actual number of ticks set (may be less than desired) */ K_ULONG KernelTimer_SetExpiry(K_ULONG ulInterval_); //--------------------------------------------------------------------------- /*! \fn K_ULONG GetOvertime(void) Return the number of ticks that have elapsed since the last expiry. \return Number of ticks that have elapsed after last timer expiration */ K_ULONG KernelTimer_GetOvertime(void); //--------------------------------------------------------------------------- /*! \fn void ClearExpiry(void) Clear the hardware timer expiry register */ void KernelTimer_ClearExpiry(void); //--------------------------------------------------------------------------- /*! \fn K_USHORT Read(void) Safely read the current value in the timer register \return Value held in the timer register */ K_USHORT KernelTimer_Read(void); #ifdef __cplusplus } #endif #endif //__KERNELTIMER_H_
moslevin/Mark3C
kernel/eventflag.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file EventFlag_t.cpp \brief Event Flag Blocking Object/IPC-Object implementation. */ #include "mark3cfg.h" #include "blocking.h" #include "kernel.h" #include "thread.h" #include "eventflag.h" #include "kernelaware.h" #if KERNEL_USE_EVENTFLAG #if KERNEL_USE_TIMEOUTS #include "timerlist.h" #if KERNEL_USE_TIMEOUTS /*! * \brief WakeMe * * Wake the given thread, currently blocking on this object * * \param pstOwner_ Pointer to the owner thread to unblock. */ static void EventFlag_WakeMe( EventFlag_t *pstFlag_, Thread_t *pstOwner_); /*! * \brief Wait_i * * Interal abstraction used to manage both timed and untimed wait operations * * \param usMask_ - 16-bit bitmask to block on * \param eMode_ - EVENT_FLAG_ANY: Thread_t will block on any of the bits in the mask * - EVENT_FLAG_ALL: Thread_t will block on all of the bits in the mask * \param ulTimeMS_ - Time to block (in ms) * * \return Bitmask condition that caused the thread to unblock, or 0 on error or timeout */ static K_USHORT EventFlag_Wait_i( EventFlag_t *pstFlag_, K_USHORT usMask_, EventFlagOperation_t eMode_, K_ULONG ulTimeMS_); #else /*! * \brief Wait_i * Interal abstraction used to manage wait operations * * \param usMask_ - 16-bit bitmask to block on * \param eMode_ - EVENT_FLAG_ANY: Thread_t will block on any of the bits in the mask * - EVENT_FLAG_ALL: Thread_t will block on all of the bits in the mask * * \return Bitmask condition that caused the thread to unblock. */ static K_USHORT EventFlag_Wait_i( EventFlag_t *pstFlag_, K_USHORT usMask_, EventFlagOperation_t eMode_); #endif /*! \brief Init Initializes the EventFlag_t object prior to use. */ void EventFlag_Init( EventFlag_t *pstFlag_ ) { pstFlag_->usSetMask = 0; ThreadList_Init( (ThreadList_t*)pstFlag_ ); } //--------------------------------------------------------------------------- /*! * \brief TimedEventFlag_Callback * * This funciton is called whenever a timed event flag wait operation fails * in the time provided. This function wakes the thread for which the timeout * was requested on the blocking call, sets the thread's expiry flags, and * reschedules if necessary. * * \param pstOwner_ Thread_t to wake * \param pvData_ Pointer to the event-flag object */ void TimedEventFlag_Callback(Thread_t *pstOwner_, void *pvData_) { EventFlag_t *pstEventFlag = (EventFlag_t*)(pvData_); EventFlag_WakeMe( pstEventFlag, pstOwner_ ); Thread_SetExpired( pstOwner_, true ); Thread_SetEventFlagMask( pstOwner_, 0 ); if (Thread_GetCurPriority( pstOwner_ ) >= Thread_GetCurPriority( Scheduler_GetCurrentThread() )) { Thread_Yield(); } } //--------------------------------------------------------------------------- void EventFlag_WakeMe( EventFlag_t *pstFlag_, Thread_t *pstChosenOne_) { BlockingObject_UnBlock( pstChosenOne_ ); } #endif //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS K_USHORT EventFlag_Wait_i( EventFlag_t *pstFlag_, K_USHORT usMask_, EventFlagOperation_t eMode_, K_ULONG ulTimeMS_) #else K_USHORT EventFlag_Wait_i( EventFlag_t *pstFlag_, K_USHORT usMask_, EventFlagOperation_t eMode_) #endif { K_BOOL bThreadYield = false; K_BOOL bMatch = false; #if KERNEL_USE_TIMEOUTS Timer_t stEventTimer; K_BOOL bUseTimer = false; #endif // Ensure we're operating in a critical section while we determine // whether or not we need to block the current thread on this object. CS_ENTER(); // Check to see whether or not the current mask matches any of the // desired bits. Thread_SetEventFlagMask( g_pstCurrent, usMask_ ); if ((eMode_ == EVENT_FLAG_ALL) || (eMode_ == EVENT_FLAG_ALL_CLEAR)) { // Check to see if the flags in their current state match all of // the set flags in the event flag group, with this mask. if ((pstFlag_->usSetMask & usMask_) == usMask_) { bMatch = true; Thread_SetEventFlagMask( g_pstCurrent, usMask_ ); } } else if ((eMode_ == EVENT_FLAG_ANY) || (eMode_ == EVENT_FLAG_ANY_CLEAR)) { // Check to see if the existing flags match any of the set flags in // the event flag group with this mask if (pstFlag_->usSetMask & usMask_) { bMatch = true; Thread_SetEventFlagMask( g_pstCurrent, pstFlag_->usSetMask & usMask_); } } // We're unable to match this pattern as-is, so we must block. if (!bMatch) { // Reset the current thread's event flag mask & mode Thread_SetEventFlagMask( g_pstCurrent, usMask_ ); Thread_SetEventFlagMode( g_pstCurrent, eMode_ ); #if KERNEL_USE_TIMEOUTS if (ulTimeMS_) { Thread_SetExpired( g_pstCurrent, false ); Timer_Init( &stEventTimer ); Timer_Start( &stEventTimer, false, ulTimeMS_, TimedEventFlag_Callback, (void*)pstFlag_); bUseTimer = true; } #endif // Add the thread to the object's block-list. BlockingObject_Block( (ThreadList_t*)pstFlag_, g_pstCurrent); // Trigger that bThreadYield = true; } // If bThreadYield is set, it means that we've blocked the current thread, // and must therefore rerun the scheduler to determine what thread to // switch to. if (bThreadYield) { // Switch threads immediately Thread_Yield(); } // Exit the critical section and return back to normal execution CS_EXIT(); //!! If the Yield operation causes a new thread to be chosen, there will //!! Be a context switch at the above CS_EXIT(). The original calling //!! thread will not return back until a matching SetFlags call is made //!! or a timeout occurs. #if KERNEL_USE_TIMEOUTS if (bUseTimer && bThreadYield) { Timer_Stop( &stEventTimer ); } #endif return Thread_GetEventFlagMask( g_pstCurrent ); } //--------------------------------------------------------------------------- K_USHORT EventFlag_Wait( EventFlag_t *pstFlag_, K_USHORT usMask_, EventFlagOperation_t eMode_) { #if KERNEL_USE_TIMEOUTS return EventFlag_Wait_i( pstFlag_, usMask_, eMode_, 0); #else return EventFlag_Wait_i( pstFlag_, usMask_, eMode_); #endif } #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- K_USHORT EventFlag_TimedWait( EventFlag_t *pstFlag_, K_USHORT usMask_, EventFlagOperation_t eMode_, K_ULONG ulTimeMS_) { return EventFlag_Wait_i( pstFlag_, usMask_, eMode_, ulTimeMS_); } #endif //--------------------------------------------------------------------------- void EventFlag_Set( EventFlag_t *pstFlag_, K_USHORT usMask_) { Thread_t *pstPrev; Thread_t *pstCurrent; K_BOOL bReschedule = false; K_USHORT usNewMask; CS_ENTER(); // Walk through the whole block list, checking to see whether or not // the current flag set now matches any/all of the masks and modes of // the threads involved. pstFlag_->usSetMask |= usMask_; usNewMask = pstFlag_->usSetMask; // Start at the head of the list, and iterate through until we hit the // "head" element in the list again. Ensure that we handle the case where // we remove the first or last elements in the list, or if there's only // one element in the list. pstCurrent = (Thread_t*)(LinkList_GetHead( (LinkList_t*)pstFlag_ )); // Do nothing when there are no objects blocking. if (pstCurrent) { // First loop - process every thread in the block-list and check to // see whether or not the current flags match the event-flag conditions // on the thread. do { pstPrev = pstCurrent; pstCurrent = (Thread_t*)(LinkListNode_GetNext( (LinkListNode_t*)pstCurrent ) ); // Read the thread's event mask/mode K_USHORT usThreadMask = Thread_GetEventFlagMask( pstPrev ); EventFlagOperation_t eThreadMode = Thread_GetEventFlagMode( pstPrev ); // For the "any" mode - unblock the blocked threads if one or more bits // in the thread's bitmask match the object's bitmask if ((EVENT_FLAG_ANY == eThreadMode) || (EVENT_FLAG_ANY_CLEAR == eThreadMode)) { if (usThreadMask & pstFlag_->usSetMask) { Thread_SetEventFlagMode( pstPrev, EVENT_FLAG_PENDING_UNBLOCK ); Thread_SetEventFlagMask( pstPrev, pstFlag_->usSetMask & usThreadMask ); bReschedule = true; // If the "clear" variant is set, then clear the bits in the mask // that caused the thread to unblock. if (EVENT_FLAG_ANY_CLEAR == eThreadMode) { usNewMask &=~ (usThreadMask & usMask_); } } } // For the "all" mode, every set bit in the thread's requested bitmask must // match the object's flag mask. else if ((EVENT_FLAG_ALL == eThreadMode) || (EVENT_FLAG_ALL_CLEAR == eThreadMode)) { if ((usThreadMask & pstFlag_->usSetMask) == usThreadMask) { Thread_SetEventFlagMode( pstPrev, EVENT_FLAG_PENDING_UNBLOCK ); Thread_SetEventFlagMask( pstPrev, usThreadMask); bReschedule = true; // If the "clear" variant is set, then clear the bits in the mask // that caused the thread to unblock. if (EVENT_FLAG_ALL_CLEAR == eThreadMode) { usNewMask &=~ (usThreadMask & usMask_); } } } } // To keep looping, ensure that there's something in the list, and // that the next item isn't the head of the list. while (pstPrev != (Thread_t*)LinkList_GetTail( (LinkList_t*)pstFlag_ ) ); // Second loop - go through and unblock all of the threads that // were tagged for unblocking. pstCurrent = (Thread_t*)(LinkList_GetHead( (LinkList_t*)pstFlag_ )); K_BOOL bIsTail = false; do { pstPrev = pstCurrent; pstCurrent = (Thread_t*)(LinkListNode_GetNext( (LinkListNode_t*)pstCurrent )); // Check to see if this is the condition to terminate the loop if (pstPrev == (Thread_t*)(LinkList_GetTail( (LinkList_t*)pstFlag_ ))) { bIsTail = true; } // If the first pass indicated that this thread should be // unblocked, then unblock the thread if (Thread_GetEventFlagMode( pstPrev ) == EVENT_FLAG_PENDING_UNBLOCK) { BlockingObject_UnBlock( pstPrev ); } } while (!bIsTail); } // If we awoke any threads, re-run the scheduler if (bReschedule) { Thread_Yield(); } // Update the bitmask based on any "clear" operations performed along // the way pstFlag_->usSetMask = usNewMask; // Restore interrupts - will potentially cause a context switch if a // thread is unblocked. CS_EXIT(); } //--------------------------------------------------------------------------- void EventFlag_Clear( EventFlag_t *pstFlag_, K_USHORT usMask_) { // Just clear the bitfields in the local object. CS_ENTER(); pstFlag_->usSetMask &= ~usMask_; CS_EXIT(); } //--------------------------------------------------------------------------- K_USHORT EventFlag_GetMask( EventFlag_t *pstFlag_ ) { // Return the presently held event flag values in this object. Ensure // we get this within a critical section to guarantee atomicity. K_USHORT usReturn; CS_ENTER(); usReturn = pstFlag_->usSetMask; CS_EXIT(); return usReturn; } #endif // KERNEL_USE_EVENTFLAG
moslevin/Mark3C
kernel/atomic.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file atomic.cpp \brief Basic Atomic Operations */ #include "kerneltypes.h" #include "mark3cfg.h" #include "atomic.h" #include "threadport.h" #if KERNEL_USE_ATOMIC //--------------------------------------------------------------------------- K_UCHAR Atomic_Set8( K_UCHAR *pucSource_, K_UCHAR ucVal_ ) { K_UCHAR ucRet; CS_ENTER(); ucRet = *pucSource_; *pucSource_ = ucVal_; CS_EXIT(); return ucRet; } //--------------------------------------------------------------------------- K_USHORT Atomic_Set16( K_USHORT *pusSource_, K_USHORT usVal_ ) { K_USHORT usRet; CS_ENTER(); usRet = *pusSource_; *pusSource_ = usVal_; CS_EXIT(); return usRet; } //--------------------------------------------------------------------------- K_ULONG Atomic_Set32( K_ULONG *pulSource_, K_ULONG ulVal_ ) { K_ULONG ulRet; CS_ENTER(); ulRet = *pulSource_; *pulSource_ = ulVal_; CS_EXIT(); return ulRet; } //--------------------------------------------------------------------------- K_UCHAR Atomic_Add8( K_UCHAR *pucSource_, K_UCHAR ucVal_ ) { K_UCHAR ucRet; CS_ENTER(); ucRet = *pucSource_; *pucSource_ += ucVal_; CS_EXIT(); return ucRet; } //--------------------------------------------------------------------------- K_USHORT Atomic_Add16( K_USHORT *pusSource_, K_USHORT usVal_ ) { K_USHORT usRet; CS_ENTER(); usRet = *pusSource_; *pusSource_ += usVal_; CS_EXIT(); return usRet; } //--------------------------------------------------------------------------- K_ULONG Atomic_Add32( K_ULONG *pulSource_, K_ULONG ulVal_ ) { K_ULONG ulRet; CS_ENTER(); ulRet = *pulSource_; *pulSource_ += ulVal_; CS_EXIT(); return ulRet; } //--------------------------------------------------------------------------- K_UCHAR Atomic_Sub8( K_UCHAR *pucSource_, K_UCHAR ucVal_ ) { K_UCHAR ucRet; CS_ENTER(); ucRet = *pucSource_; *pucSource_ -= ucVal_; CS_EXIT(); return ucRet; } //--------------------------------------------------------------------------- K_USHORT Atomic_Sub16( K_USHORT *pusSource_, K_USHORT usVal_ ) { K_USHORT usRet; CS_ENTER(); usRet = *pusSource_; *pusSource_ -= usVal_; CS_EXIT(); return usRet; } //--------------------------------------------------------------------------- K_ULONG Atomic_Sub32( K_ULONG *pulSource_, K_ULONG ulVal_ ) { K_ULONG ulRet; CS_ENTER(); ulRet = *pulSource_; *pulSource_ -= ulVal_; CS_EXIT(); return ulRet; } //--------------------------------------------------------------------------- K_BOOL Atomic_TestAndSet( K_BOOL *pbLock_ ) { K_UCHAR ucRet; CS_ENTER(); ucRet = *pbLock_; if (!ucRet) { *pbLock_ = 1; } CS_EXIT(); return ucRet; } #endif // KERNEL_USE_ATOMIC
moslevin/Mark3C
tests/unit/ut_timers/ut_timers.c
<filename>tests/unit/ut_timers/ut_timers.c /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ //--------------------------------------------------------------------------- #include "kerneltypes.h" #include "kernel.h" #include "../ut_platform.h" #include "timerlist.h" #include "thread.h" #include "kernelprofile.h" #include "profile.h" #include "kernel.h" #include "ksemaphore.h" #include "kerneltimer.h" #include "driver.h" #include "memutil.h" //=========================================================================== // Local Defines //=========================================================================== static Timer_t stTimer1; static Timer_t stTimer2; static Timer_t stTimer3; static Semaphore_t stTimerSem; static ProfileTimer_t stProfileTimer; static ProfileTimer_t stProfileTimer2; static ProfileTimer_t stProfileTimer3; static K_ULONG ulTimeVal; static K_ULONG ulTempTime; static volatile K_ULONG ulCallbackCount = 0; static void TimerCallback( Thread_t *pstOwner_, void *pvVal_ ) { Semaphore_Post( &stTimerSem ); ulCallbackCount++; } //=========================================================================== // Define Test Cases Here //=========================================================================== TEST(ut_timer_tolerance) { Profiler_Start(); Semaphore_Init( &stTimerSem, 0, 1); // Test point - 1ms Timer_t should take at least 1ms ProfileTimer_Init( &stProfileTimer ); ProfileTimer_Start( &stProfileTimer ); Timer_Start( &stTimer1, false, 1, TimerCallback, 0 ); Semaphore_Pend( &stTimerSem ); ProfileTimer_Stop( &stProfileTimer ); ulTimeVal = ProfileTimer_GetCurrent( &stProfileTimer ) * CLOCK_DIVIDE; ulTempTime = SYSTEM_FREQ / 1000; EXPECT_GT(ulTimeVal, ulTempTime); // Test point - 1ms Timer_t should be no more than 3ms ulTempTime *= 3; EXPECT_LT(ulTimeVal, ulTempTime); // Test point - 10ms Timer_t should take at least 10ms ProfileTimer_Init( &stProfileTimer ); ProfileTimer_Start( &stProfileTimer ); Timer_Start( &stTimer1, false, 10, TimerCallback, 0 ); Semaphore_Pend( &stTimerSem ); ProfileTimer_Stop( &stProfileTimer ); ulTimeVal = ProfileTimer_GetCurrent( &stProfileTimer ) * CLOCK_DIVIDE; ulTempTime = SYSTEM_FREQ / 100; EXPECT_GT(ulTimeVal, ulTempTime); // Test point - 10ms Timer_t should be no more than 12ms ulTempTime += 2* (SYSTEM_FREQ / 1000); EXPECT_LT(ulTimeVal, ulTempTime); // Test point - 100ms Timer_t should take at least 100ms ProfileTimer_Init( &stProfileTimer ); ProfileTimer_Start( &stProfileTimer ); Timer_Start( &stTimer1, false, 100, TimerCallback, 0 ); Semaphore_Pend( &stTimerSem ); ProfileTimer_Stop( &stProfileTimer ); ulTimeVal = ProfileTimer_GetCurrent( &stProfileTimer ) * CLOCK_DIVIDE; ulTempTime = SYSTEM_FREQ / 10; EXPECT_GT(ulTimeVal, ulTempTime); // Test point - 100ms Timer_t should be no more than 102ms ulTempTime += 2 * (SYSTEM_FREQ / 1000); EXPECT_LT(ulTimeVal, ulTempTime); // Test point - 1000ms Timer_t should take at least 100ms ProfileTimer_Init( &stProfileTimer ); ProfileTimer_Start( &stProfileTimer ); Timer_Start( &stTimer1, false, 1000, TimerCallback, 0 ); Semaphore_Pend( &stTimerSem ); ProfileTimer_Stop( &stProfileTimer ); ulTimeVal = ProfileTimer_GetCurrent( &stProfileTimer ) * CLOCK_DIVIDE; ulTempTime = SYSTEM_FREQ; EXPECT_GT(ulTimeVal, ulTempTime); // Test point - 1000ms Timer_t should be no more than 1002ms ulTempTime += 2* (SYSTEM_FREQ / 1000); EXPECT_LT(ulTimeVal, ulTempTime); Profiler_Stop(); } TEST_END TEST(ut_timer_longrun) { // Profiling Timer_t is not really designed for long profiling // operations (1.2 seconds is about as high as we get, since it's // so high resolution). So, use sleeps and multiple iterations // w/averaging in order to verify. K_ULONG ulSleepCount = 0; Profiler_Start(); Semaphore_Init( &stTimerSem, 0, 1); // Test point - long running Timer_t accuracy; 10-second Timer_t // expires after 10 seconds. ProfileTimer_Init( &stProfileTimer ); Timer_Start( &stTimer1, false, 10000, TimerCallback, 0 ); ulCallbackCount = 0; while (!ulCallbackCount) { ProfileTimer_Start( &stProfileTimer ); Thread_Sleep(100); ProfileTimer_Stop( &stProfileTimer ); ulSleepCount++; } ProfileTimer_Stop( &stProfileTimer ); ulTimeVal = ProfileTimer_GetAverage( &stProfileTimer ) * CLOCK_DIVIDE * ulSleepCount; ulTempTime = SYSTEM_FREQ * 10; EXPECT_GT(ulTimeVal, ulTempTime); // Test point - 100ms accuracy over 10 seconds ulTempTime += SYSTEM_FREQ / 10; EXPECT_LT(ulTimeVal, ulTempTime); Profiler_Stop(); } TEST_END TEST(ut_timer_repeat) { // Profiling Timer_t is not really designed for long profiling // operations (1.2 seconds is about as high as we get, since it's // so high resolution). So, use sleeps and multiple iterations // w/averaging in order to verify. K_ULONG ulSleepCount = 0; Profiler_Start(); Semaphore_Init( &stTimerSem, 0, 1); // Repeated Timer_t case - run a 10ms Timer_t 100 times and measure // accuracy. Average iteration must be > 10ms ulCallbackCount = 0; ProfileTimer_Init( &stProfileTimer ); ProfileTimer_Start( &stProfileTimer ); Timer_Start( &stTimer1, true, 10, TimerCallback, 0 ); while (ulCallbackCount < 100) { Semaphore_Pend( &stTimerSem ); } ProfileTimer_Stop( &stProfileTimer ); Timer_Stop( &stTimer1 ); ulTimeVal = ProfileTimer_GetCurrent( &stProfileTimer ) * CLOCK_DIVIDE; ulTempTime = SYSTEM_FREQ; EXPECT_GT(ulTimeVal, ulTempTime); #if KERNEL_TIMERS_TICKLESS // Test point - 50ms (5%) maximum tolerance for callback overhead, etc. ulTempTime += SYSTEM_FREQ / 20; EXPECT_LT(ulTimeVal, ulTempTime); #else // Test point - 100ms (10%) maximum tolerance for callback overhead, etc. ulTempTime += SYSTEM_FREQ / 10; EXPECT_LT(ulTimeVal, ulTempTime); #endif #if 0 // Debug code to print out the profiling times Driver *pstDriver = DriverList_FindByPath("/dev/tty"); K_CHAR acData[13]; MemUtil_DecimalToString(ulTimeVal, acData); pstDriver->Write( MemUtil_StringLength(acData), (K_UCHAR*)acData); pstDriver->Write(1, (K_UCHAR*)(" ")); MemUtil_DecimalToString(ulTempTime, acData); pstDriver->Write( MemUtil_StringLength(acData), (K_UCHAR*)acData); #endif Profiler_Stop(); } TEST_END TEST(ut_timer_multi) { Profiler_Start(); Semaphore_Init( &stTimerSem, 0, 3); // Test using multiple timers simultaneously, verify that // each of them expire at the expected times within a specific // tolerance ProfileTimer_Init( &stProfileTimer ); ProfileTimer_Init( &stProfileTimer2 ); ProfileTimer_Init( &stProfileTimer3 ); ProfileTimer_Start( &stProfileTimer ); Timer_Start( &stTimer1, false, 100, TimerCallback, 0 ); ProfileTimer_Start( &stProfileTimer2 ); Timer_Start( &stTimer2, false, 200, TimerCallback, 0 ); ProfileTimer_Start( &stProfileTimer3 ); Timer_Start( &stTimer3, false, 50, TimerCallback, 0 ); // Each Timer_t expiry will post the Semaphore_t. Semaphore_Pend( &stTimerSem ); ProfileTimer_Stop( &stProfileTimer3 ); Semaphore_Pend( &stTimerSem ); ProfileTimer_Stop( &stProfileTimer ); Semaphore_Pend( &stTimerSem ); ProfileTimer_Stop( &stProfileTimer2 ); // Test Point - Timer_t 1 expired @ 100ms, with a 1 ms tolerance ulTimeVal = ProfileTimer_GetCurrent( &stProfileTimer ) * CLOCK_DIVIDE; ulTempTime = SYSTEM_FREQ / 10; EXPECT_GT(ulTimeVal, ulTempTime); ulTempTime += SYSTEM_FREQ / 1000; EXPECT_LT(ulTimeVal, ulTempTime); // Test Point - Timer_t 2 expired @ 200ms, with a 1 ms tolerance ulTimeVal = ProfileTimer_GetCurrent( &stProfileTimer2 ) * CLOCK_DIVIDE; ulTempTime = SYSTEM_FREQ / 5; EXPECT_GT(ulTimeVal, ulTempTime); ulTempTime += SYSTEM_FREQ / 1000; EXPECT_LT(ulTimeVal, ulTempTime); // Test Point - Timer_t 3 expired @ 50ms, with a 1 ms tolerance ulTimeVal = ProfileTimer_GetCurrent( &stProfileTimer3 ) * CLOCK_DIVIDE; ulTempTime = SYSTEM_FREQ / 20; EXPECT_GT(ulTimeVal, ulTempTime); ulTempTime += SYSTEM_FREQ / 1000; EXPECT_LT(ulTimeVal, ulTempTime); Profiler_Stop(); } TEST_END //=========================================================================== // Test Whitelist Goes Here //=========================================================================== TEST_CASE_START TEST_CASE(ut_timer_tolerance), TEST_CASE(ut_timer_longrun), TEST_CASE(ut_timer_repeat), TEST_CASE(ut_timer_multi), TEST_CASE_END
moslevin/Mark3C
kernel/notify.c
<filename>kernel/notify.c<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file notify.c \brief Lightweight thread notification - blocking object */ #include "mark3cfg.h" #include "notify.h" #if KERNEL_USE_NOTIFY //--------------------------------------------------------------------------- void TimedNotify_Callback( Thread_t *pstOwner_, void *pvData_ ) { Notify_t *pstNotify = (Notify_t*)(pvData_); // Indicate that the semaphore has expired on the thread Thread_SetExpired( pstOwner_, true ); // Wake up the thread that was blocked on this semaphore. Notify_WakeMe( pstNotify, pstOwner_ ); if ( Thread_GetCurPriority( pstOwner_ ) >= Thread_GetCurPriority( Scheduler_GetCurrentThread() ) ) { Thread_Yield(); } } //--------------------------------------------------------------------------- void Notify_Init( Notify_t *pstNotify_ ) { ThreadList_Init( (ThreadList_t*)pstNotify_ ); } //--------------------------------------------------------------------------- void Notify_Signal( Notify_t *pstNotify_ ) { bool bReschedule = false; CS_ENTER(); Thread_t *pstCurrent = (Thread_t*)LinkList_GetHead((LinkListNode_t*)pstNotify_); while (pstCurrent != NULL) { BlockingObject_UnBlock( pstCurrent ); if ( !bReschedule && ( Thread_GetCurPriority( pstCurrent ) >= Thread_GetCurPriority( Scheduler_GetCurrentThread() ) ) ) { bReschedule = true; } pstCurrent = (Thread_t*)LinkList_GetHead(pstNotify_); } CS_EXIT(); if (bReschedule) { Thread_Yield(); } } //--------------------------------------------------------------------------- void Notify_Wait( Notify_t *pstNotify_, bool *pbFlag_ ) { CS_ENTER(); BlockingObject_Block( (ThreadList_t*)pstNotify_, Scheduler_GetCurrentThread() ); if (pbFlag_) { *pbFlag_ = false; } CS_EXIT(); Thread_Yield(); if (pbFlag_) { *pbFlag_ = true; } } //--------------------------------------------------------------------------- #if KERNEL_USER_TIMEOUTS bool Notify_Wait( Notify_t *pstNotify_, K_ULONG ulWaitTimeMS_, bool *pbFlag_ ) { bool bUseTimer = false; Timer_t stNotifyTimer; CS_ENTER(); if (ulWaitTimeMS_) { bUseTimer = true; Thread_SetExpired( Scheduler_GetCurrentThread(), false ); Timer_Init( &stNotifyTimer ); Timer_Start( &stNotifyTimer, 0, ulWaitTimeMS_, TimedNotify_Callback, (void*)pstNotify_); } Block(g_pstCurrent); if (pbFlag_) { *pbFlag_ = false; } CS_EXIT(); Thread_Yield(); if (pbFlag_) { *pbFlag_ = true; } if (bUseTimer) { Timer_Stop( &stNotifyTimer ); return ( Thread_GetExpired( Scheduler_GetCurrentThread() ) == false ); } return true; } #endif //--------------------------------------------------------------------------- void Notify_WakeMe( Notify_t *pstNotify_, Thread_t *pclChosenOne_ ) { BlockingObject_UnBlock( pclChosenOne_ ); } #endif
moslevin/Mark3C
kernel/public/paniccodes.h
<reponame>moslevin/Mark3C /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file paniccodes.h \brief Defines the reason codes thrown when a kernel panic occurs */ #ifndef __PANIC_CODES_H #define __PANIC_CODES_H #define PANIC_ASSERT_FAILED (1) #define PANIC_LIST_UNLINK_FAILED (2) #define PANIC_STACK_SLACK_VIOLATED (3) #endif // __PANIC_CODES_H
moslevin/Mark3C
kernel/profile.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file profile.cpp \brief Code profiling utilities */ #include "kerneltypes.h" #include "mark3cfg.h" #include "profile.h" #include "kernelprofile.h" #include "threadport.h" #include "kerneldebug.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ PROFILE_C //!< File ID used in kernel trace calls #if KERNEL_USE_PROFILER //--------------------------------------------------------------------------- void ProfileTimer_Init( ProfileTimer_t *pstTimer_ ) { pstTimer_->ulCumulative = 0; pstTimer_->ulCurrentIteration = 0; pstTimer_->usIterations = 0; pstTimer_->bActive = 0; } //--------------------------------------------------------------------------- void ProfileTimer_Start( ProfileTimer_t *pstTimer_ ) { if (!pstTimer_->bActive) { CS_ENTER(); pstTimer_->ulCurrentIteration = 0; pstTimer_->ulInitialEpoch = Profiler_GetEpoch(); pstTimer_->usInitial = Profiler_Read(); CS_EXIT(); pstTimer_->bActive = 1; } } //--------------------------------------------------------------------------- void ProfileTimer_Stop( ProfileTimer_t *pstTimer_ ) { if (pstTimer_->bActive) { K_USHORT usFinal; K_ULONG ulEpoch; CS_ENTER(); usFinal = Profiler_Read(); ulEpoch = Profiler_GetEpoch(); // Compute total for current iteration... pstTimer_->ulCurrentIteration = ProfileTimer_ComputeCurrentTicks( pstTimer_, usFinal, ulEpoch); pstTimer_->ulCumulative += pstTimer_->ulCurrentIteration; pstTimer_->usIterations++; CS_EXIT(); pstTimer_->bActive = 0; } } //--------------------------------------------------------------------------- K_ULONG ProfileTimer_GetAverage( ProfileTimer_t *pstTimer_ ) { if (pstTimer_->usIterations) { return pstTimer_->ulCumulative / (K_ULONG)pstTimer_->usIterations; } return 0; } //--------------------------------------------------------------------------- K_ULONG ProfileTimer_GetCurrent( ProfileTimer_t *pstTimer_ ) { if (pstTimer_->bActive) { K_USHORT usCurrent; K_ULONG ulEpoch; CS_ENTER(); usCurrent = Profiler_Read(); ulEpoch = Profiler_GetEpoch(); CS_EXIT(); return ProfileTimer_ComputeCurrentTicks( pstTimer_, usCurrent, ulEpoch); } return pstTimer_->ulCurrentIteration; } //--------------------------------------------------------------------------- K_ULONG ProfileTimer_ComputeCurrentTicks( ProfileTimer_t *pstTimer_, K_USHORT usCurrent_, K_ULONG ulEpoch_) { K_ULONG ulTotal; K_ULONG ulOverflows; ulOverflows = ulEpoch_ - pstTimer_->ulInitialEpoch; // More than one overflow... if (ulOverflows > 1) { ulTotal = ((K_ULONG)(ulOverflows-1) * TICKS_PER_OVERFLOW) + (K_ULONG)(TICKS_PER_OVERFLOW - pstTimer_->usInitial) + (K_ULONG)usCurrent_; } // Only one overflow, or one overflow that has yet to be processed else if (ulOverflows || (usCurrent_ < pstTimer_->usInitial)) { ulTotal = (K_ULONG)(TICKS_PER_OVERFLOW - pstTimer_->usInitial) + (K_ULONG)usCurrent_; } // No overflows, none pending. else { ulTotal = (K_ULONG)(usCurrent_ - pstTimer_->usInitial); } return ulTotal; } #endif
moslevin/Mark3C
examples/avr/lab7_events/main.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ #include "mark3.h" /*=========================================================================== Lab Example 7: Using Event Flags Lessons covered in this example include: -Using the EventFlag Class to synchronize thread execution -Explore the behavior of the EVENT_FLAG_ANY and EVENT_FLAG_ALL, and the event-mask bitfield. Takeaway: Like Semaphores and Mutexes, EventFlag objects can be used to synchronize the execution of threads in a system. The EventFlag object allows for many threads to share the same object, blocking on different event combinations. This provides an efficient, robust way for threads to process asynchronous system events that occur with a unified interface. ===========================================================================*/ //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP1_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp1Thread; static K_WORD awApp1Stack[APP1_STACK_SIZE]; static void App1Main(void *unused_); //--------------------------------------------------------------------------- // This block declares the thread data for one main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP2_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stApp2Thread; static K_WORD awApp2Stack[APP2_STACK_SIZE]; static void App2Main(void *unused_); //--------------------------------------------------------------------------- // static EventFlag_t stFlags; //--------------------------------------------------------------------------- int main(void) { // See the annotations in previous labs for details on init. Kernel_Init(); Thread_Init( &stApp1Thread, awApp1Stack, APP1_STACK_SIZE, 1, App1Main, 0); Thread_Init( &stApp2Thread, awApp2Stack, APP2_STACK_SIZE, 1, App2Main, 0); Thread_Start( &stApp1Thread ); Thread_Start( &stApp2Thread ); EventFlag_Init( &stFlags ); Kernel_Start(); return 0; } //--------------------------------------------------------------------------- void App1Main(void *unused_) { while(1) { K_USHORT usFlags; // Block this thread until any of the event flags have been set by // some outside force (here, we use Thread 2). As an exercise to the // user, try playing around with the event mask to see the effect it // has on which events get processed. Different threads can block on // different bitmasks - this allows events with different real-time // priorities to be handled in different threads, while still using // the same event-flag object. // Also note that EVENT_FLAG_ANY indicates that the thread will be // unblocked whenever any of the flags in the mask are selected. If // you wanted to trigger an action that only takes place once multiple // bits are set, you could block the thread waiting for a specific // event bitmask with EVENT_FLAG_ALL specified. usFlags = EventFlag_Wait( &stFlags, 0xFFFF, EVENT_FLAG_ANY); // Print a message indicaating which bit was set this time. switch (usFlags) { case 0x0001: KernelAware_Print("Event1\n"); break; case 0x0002: KernelAware_Print("Event2\n"); break; case 0x0004: KernelAware_Print("Event3\n"); break; case 0x0008: KernelAware_Print("Event4\n"); break; case 0x0010: KernelAware_Print("Event5\n"); break; case 0x0020: KernelAware_Print("Event6\n"); break; case 0x0040: KernelAware_Print("Event7\n"); break; case 0x0080: KernelAware_Print("Event8\n"); break; case 0x0100: KernelAware_Print("Event9\n"); break; case 0x0200: KernelAware_Print("Event10\n"); break; case 0x0400: KernelAware_Print("Event11\n"); break; case 0x0800: KernelAware_Print("Event12\n"); break; case 0x1000: KernelAware_Print("Event13\n"); break; case 0x2000: KernelAware_Print("Event14\n"); break; case 0x4000: KernelAware_Print("Event15\n"); break; case 0x8000: KernelAware_Print("Event16\n"); break; default: break; } // Clear the event-flag that we just printed a message about. This // will allow us to acknowledge further events in that bit in the future. EventFlag_Clear( &stFlags, usFlags ); } } //--------------------------------------------------------------------------- void App2Main(void *unused_) { K_USHORT usFlag = 1; while(1) { Thread_Sleep(100); // Event flags essentially map events to bits in a bitmap. Here we // set one bit each 100ms. In this loop, we cycle through bits 0-15 // repeatedly. Note that this will wake the other thread, which is // blocked, waiting for *any* of the flags in the bitmap to be set. EventFlag_Set( &stFlags, usFlag); // Bitshift the flag value to the left. This will be the flag we set // the next time this thread runs through its loop. if (usFlag != 0x8000) { usFlag <<= 1; } else { usFlag = 1; } } }
Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M
.pio/libdeps/mega2560/SlowSoftI2CMaster/SlowSoftI2CMaster.h
/* Arduino Slow Software I2C Master */ #ifndef SLOW_SOFT_I2C_MASTER_H #define SLOW_SOFT_I2C_MASTER_H #include <Arduino.h> #include <inttypes.h> #include "Stream.h" #define I2C_READ 1 #define I2C_WRITE 0 #define DELAY 4 // usec delay #define BUFFER_LENGTH 32 class SlowSoftI2CMaster { public: SlowSoftI2CMaster(uint8_t sda, uint8_t scl); bool i2c_init(void); bool i2c_start(uint8_t addr); bool i2c_rep_start(uint8_t addr); void i2c_stop(void); bool i2c_write(uint8_t value); uint8_t i2c_read(bool last); bool error; private: uint8_t _sda; uint8_t _scl; }; #endif
Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M
.pio/libdeps/esp32/SoftwareSerialM/HAL_platform.h
/** * FYSETC * * Copyright (c) 2019 SoftwareSerialM [https://github.com/FYSETC/SoftwareSerialM] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once #define HAL_PLATFORM_AVR 0 #define HAL_PLATFORM_DUE 1 #define HAL_PLATFORM_TEENSY31_32 2 #define HAL_PLATFORM_TEENSY35_36 3 #define HAL_PLATFORM_LPC1768 4 #define HAL_PLATFORM_STM32F1 5 #define HAL_PLATFORM_STM32_F4_F7 6 #define HAL_PLATFORM_STM32 7 #define HAL_PLATFORM_ESP32 8 #define HAL_PLATFORM_LINUX 9 #define HAL_PLATFORM_SAMD51 10 #ifndef HAL_SS_PLATFORM #ifdef __AVR__ #define HAL_SS_PLATFORM HAL_PLATFORM_AVR #elif defined(ARDUINO_ARCH_SAM) #define HAL_SS_PLATFORM HAL_PLATFORM_DUE #elif defined(__MK20DX256__) #define HAL_SS_PLATFORM HAL_PLATFORM_TEENSY31_32 #elif defined(__MK64FX512__) || defined(__MK66FX1M0__) #define HAL_SS_PLATFORM HAL_PLATFORM_TEENSY35_36 #elif defined(TARGET_LPC1768) #define HAL_SS_PLATFORM HAL_PLATFORM_LPC1768 #elif defined(__STM32F1__) || defined(TARGET_STM32F1) #define HAL_SS_PLATFORM HAL_PLATFORM_STM32F1 #elif defined(STM32GENERIC) && (defined(STM32F4) || defined(STM32F7)) #define HAL_SS_PLATFORM HAL_PLATFORM_STM32_F4_F7 #elif defined(ARDUINO_ARCH_STM32) #define HAL_SS_PLATFORM HAL_PLATFORM_STM32 #elif defined(ARDUINO_ARCH_ESP32) #define HAL_SS_PLATFORM HAL_PLATFORM_ESP32 #elif defined(__PLAT_LINUX__) #define HAL_SS_PLATFORM HAL_PLATFORM_LINUX #elif defined(__SAMD51__) #define HAL_SS_PLATFORM HAL_PLATFORM_SAMD51 #else #error "Unsupported Platform!" #endif #endif
Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M
.pio/libdeps/LPC1768/SailfishLCD/SailfishLCD.h
<reponame>Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M<filename>.pio/libdeps/LPC1768/SailfishLCD/SailfishLCD.h<gh_stars>1-10 /* * SailfishLCD.h * * Created on: Jan 5, 2019 * Author: mikes */ #pragma once #ifndef SAILFISHLCD_H_ #define SAILFISHLCD_H_ #include <Arduino.h> /* StandardLiquidCrystalSerial * * This is an implementation of communciation routines for the * Makerbot OEM display hardware. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ // commands #define LCD_CLEARDISPLAY 0x01 #define LCD_RETURNHOME 0x02 #define LCD_ENTRYMODESET 0x04 #define LCD_DISPLAYCONTROL 0x08 #define LCD_CURSORSHIFT 0x10 #define LCD_FUNCTIONSET 0x20 #define LCD_SETCGRAMADDR 0x40 #define LCD_SETDDRAMADDR 0x80 // flags for display entry mode #define LCD_ENTRYRIGHT 0x00 #define LCD_ENTRYLEFT 0x02 #define LCD_ENTRYSHIFTINCREMENT 0x01 #define LCD_ENTRYSHIFTDECREMENT 0x00 // flags for display on/off control #define LCD_DISPLAYON 0x04 #define LCD_DISPLAYOFF 0x00 #define LCD_CURSORON 0x02 #define LCD_CURSOROFF 0x00 #define LCD_BLINKON 0x01 #define LCD_BLINKOFF 0x00 #define LCD_BACKLIGHT 0x08 // flags for display/cursor shift #define LCD_DISPLAYMOVE 0x08 #define LCD_CURSORMOVE 0x00 #define LCD_MOVERIGHT 0x04 #define LCD_MOVELEFT 0x00 // flags for function set #define LCD_8BITMODE 0x10 #define LCD_4BITMODE 0x00 #define LCD_2LINE 0x08 #define LCD_1LINE 0x00 #define LCD_5x10DOTS 0x04 #define LCD_5x8DOTS 0x00 // Custom chars // Unlike the Gen 4 LCD, this module -- ACM2004 series -- this // LCD display module only provides 8 custom characters and // n % 8 == n #define LCD_CUSTOM_CHAR_DOWN 0 #define LCD_CUSTOM_CHAR_EXTRUDER_NORMAL 2 #define LCD_CUSTOM_CHAR_EXTRUDER_HEATING 3 #define LCD_CUSTOM_CHAR_PLATFORM_NORMAL 4 #define LCD_CUSTOM_CHAR_PLATFORM_HEATING 5 #define LCD_CUSTOM_CHAR_FOLDER 6 // Must not be 0 #define LCD_CUSTOM_CHAR_RETURN 7 // Must not be 0 #define LCD_CUSTOM_CHAR_DEGREE 0xdf // MAY ALSO BE 0xdf #define LCD_CUSTOM_CHAR_UP 0x5e // ^ #define LCD_CUSTOM_CHAR_RIGHT 0x7e // right pointing arrow (0x7f is left pointing) class LiquidCrystalSerial : public Print{ public: LiquidCrystalSerial(int strobe, int data, int CLK); void init(int strobe, int data, int CLK); void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS); void clear(); void home(); void homeCursor(); // faster version of home() void clearHomeCursor(); // clear() and homeCursor() combined void noDisplay(); void display(); void noBlink(); void blink(); void noCursor(); void cursor(); void scrollDisplayLeft(); void scrollDisplayRight(); void leftToRight(); void rightToLeft(); void autoscroll(); void noAutoscroll(); void createChar(uint8_t, uint8_t[]); void setCursor(uint8_t, uint8_t); void setRow(uint8_t); void setCursorExt(int8_t col, int8_t row); virtual size_t write(uint8_t); using Print::write; /** Added by MakerBot Industries to support storing strings in flash **/ void writeInt(uint16_t value, uint8_t digits); void moveWriteInt(uint8_t col, uint8_t row, uint16_t value, uint8_t digits); void writeInt32(uint32_t value, uint8_t digits); void writeFloat(float value, uint8_t decimalPlaces, uint8_t rightJustifyToCol); void writeString(char message[]); /** Display the given line until a newline or null is encountered. * Returns a pointer to the first character not displayed. */ char *writeLine(char *message); void writeFromPgmspace(const unsigned char message[]); void moveWriteFromPgmspace(uint8_t col, uint8_t row, const unsigned char message[]); void command(uint8_t); private: void send(uint8_t, bool); void writeSerial(uint8_t); void write4bits(uint8_t value, bool dataMode); void pulseEnable(uint8_t value); uint8_t _strobe_pin; // LOW: command. HIGH: character. uint8_t _data_pin; // LOW: write to LCD. HIGH: read from LCD. uint8_t _clk_pin; // activated by a HIGH pulse. uint8_t _displayfunction; uint8_t _displaycontrol; uint8_t _displaymode; uint8_t _initialized; uint8_t _xcursor; uint8_t _ycursor; uint8_t _numlines, _numCols; }; #endif /* SAILFISHLCD_H_ */
Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M
.pio/libdeps/esp32/Adafruit_MAX31865/Adafruit_MAX31865.h
<filename>.pio/libdeps/esp32/Adafruit_MAX31865/Adafruit_MAX31865.h<gh_stars>1-10 /*************************************************** This is a library for the Adafruit PT100/P1000 RTD Sensor w/MAX31865 Designed specifically to work with the Adafruit RTD Sensor ----> https://www.adafruit.com/products/3328 This sensor uses SPI to communicate, 4 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by <NAME>/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution ****************************************************/ #ifndef ADAFRUIT_MAX31865_H #define ADAFRUIT_MAX31865_H #define MAX31856_CONFIG_REG 0x00 #define MAX31856_CONFIG_BIAS 0x80 #define MAX31856_CONFIG_MODEAUTO 0x40 #define MAX31856_CONFIG_MODEOFF 0x00 #define MAX31856_CONFIG_1SHOT 0x20 #define MAX31856_CONFIG_3WIRE 0x10 #define MAX31856_CONFIG_24WIRE 0x00 #define MAX31856_CONFIG_FAULTSTAT 0x02 #define MAX31856_CONFIG_FILT50HZ 0x01 #define MAX31856_CONFIG_FILT60HZ 0x00 #define MAX31856_RTDMSB_REG 0x01 #define MAX31856_RTDLSB_REG 0x02 #define MAX31856_HFAULTMSB_REG 0x03 #define MAX31856_HFAULTLSB_REG 0x04 #define MAX31856_LFAULTMSB_REG 0x05 #define MAX31856_LFAULTLSB_REG 0x06 #define MAX31856_FAULTSTAT_REG 0x07 #define MAX31865_FAULT_HIGHTHRESH 0x80 #define MAX31865_FAULT_LOWTHRESH 0x40 #define MAX31865_FAULT_REFINLOW 0x20 #define MAX31865_FAULT_REFINHIGH 0x10 #define MAX31865_FAULT_RTDINLOW 0x08 #define MAX31865_FAULT_OVUV 0x04 #define RTD_A 3.9083e-3 #define RTD_B -5.775e-7 #if (ARDUINO >= 100) #include "Arduino.h" #else #include "WProgram.h" #endif typedef enum max31865_numwires { MAX31865_2WIRE = 0, MAX31865_3WIRE = 1, MAX31865_4WIRE = 0 } max31865_numwires_t; /*! Interface class for the MAX31865 RTD Sensor reader */ class Adafruit_MAX31865 { public: Adafruit_MAX31865(int8_t spi_cs, int8_t spi_mosi, int8_t spi_miso, int8_t spi_clk); Adafruit_MAX31865(int8_t spi_cs); bool begin(max31865_numwires_t x = MAX31865_2WIRE); uint8_t readFault(void); void clearFault(void); uint16_t readRTD(); void setWires(max31865_numwires_t wires); void autoConvert(bool b); void enableBias(bool b); float temperature(float RTDnominal, float refResistor); private: int8_t _sclk, _miso, _mosi, _cs; void readRegisterN(uint8_t addr, uint8_t buffer[], uint8_t n); uint8_t readRegister8(uint8_t addr); uint16_t readRegister16(uint8_t addr); void writeRegister8(uint8_t addr, uint8_t reg); uint8_t spixfer(uint8_t addr); }; #endif
Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M
.pio/libdeps/esp32/SoftwareSerialM/HAL_softserial_SAMD51.h
/** * FYSETC * * Copyright (c) 2019 SoftwareSerialM [https://github.com/FYSETC/SoftwareSerialM] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * HAL for Adafruit Grand Central and compatible (SAMD51) */ #pragma once #include <Arduino.h> #ifndef SS_TIMER #define SS_TIMER 4 #endif #define OVERSAMPLE 3 #define INTERRUPT_PRIORITY 0 #define gpio_set(IO,V) do { \ if (V) digitalPinToPort(IO)->OUTSET.reg = digitalPinToBitMask(IO); \ else digitalPinToPort(IO)->OUTCLR.reg = digitalPinToBitMask(IO); \ }while(0) #define gpio_get(IO) ((digitalPinToPort(IO)->IN.reg & digitalPinToBitMask(IO)) ? HIGH : LOW) #define __SS_TIMERIRQ(t) TC##t##_IRQn #define _SS_TIMERIRQ(t) __SS_TIMERIRQ(t) #define SS_TIMERIRQ _SS_TIMERIRQ(SS_TIMER) #define __SS_TC_DEV(t) TC##t #define _SS_TC_DEV(t) __SS_TC_DEV(t) #define SS_TC_DEV _SS_TC_DEV(SS_TIMER) #define _SS_TC_HANDLER(t) void TC##t##_Handler() #define SS_TC_HANDLER(t) _SS_TC_HANDLER(t) #define Disable_Irq(i) do { \ NVIC_DisableIRQ(i); \ __DSB(); \ __ISB(); \ }while(0) #define cli() Disable_Irq(SS_TIMERIRQ) // Disable timer interrupt #define sei() NVIC_EnableIRQ(SS_TIMERIRQ) // Enable timer interrupt #define HAL_softserial_timer_isr_prologue() do{ SS_TC_DEV->COUNT16.INTFLAG.reg = TC_INTFLAG_OVF; } while(0) #define HAL_softserial_timer_isr_epilogue() #define HAL_SOFTSERIAL_TIMER_ISR() SS_TC_HANDLER(SS_TIMER)
Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M
.pio/libdeps/mega2560/SailfishRGB_LED/SailfishRGB_LED.h
/* * SailfishRGB_LED.h * * Created on: Jan 7, 2019 * Author: mikes */ #pragma once #ifndef SAILFISHRGB_LED_H_ #define SAILFISHRGB_LED_H_ #include <Arduino.h> #define ENABLE_I2C_PULLUPS #define SET_COLOR(r,g,b,c) RGB_LED::setColor((r),(g),(b),(c)) // LED control registers #define LED_REG_PSC0 0b00000001 #define LED_REG_PWM0 0b00000010 #define LED_REG_PSC1 0b00000011 #define LED_REG_PWM1 0b00000100 #define LED_REG_SELECT 0b00000101 // LED output types #define LED_BLINK_PWM0 0b10101010 #define LED_BLINK_PWM1 0b11111111 #define LED_ON 0b01010101 #define LED_OFF 0b00000000 // RBG IDs #define LED_RED 0b00110000 #define LED_GREEN 0b00000011 #define LED_BLUE 0b00001100 // Channel IDs #define LED_CHANNEL1 0 #define LED_CHANNEL2 1 enum LEDColors { LED_DEFAULT_WHITE = 0, LED_DEFAULT_RED, LED_DEFAULT_ORANGE, LED_DEFAULT_PINK, LED_DEFAULT_GREEN, LED_DEFAULT_BLUE, LED_DEFAULT_PURPLE, LED_DEFAULT_OFF, LED_DEFAULT_CUSTOM }; //#include "Types.hh" extern bool LEDEnabled; void RGBinit(); void RGBclear(); void RGBerrorSequence(); void RGBsetColor(uint8_t red, uint8_t green, uint8_t blue, bool clearOld = true); void RGBsetDefaultColor(uint8_t c = 0xff); void RGBsetCustomColor(uint8_t red, uint8_t green, uint8_t blue); #endif /* SAILFISHRGB_LED_H_ */
Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M
.pio/libdeps/esp32/Arduino-L6470/src/L6470.h
//////////////////////////////////////////////////////////////////// // // // ORIGINAL CODE 12 Dec 2011 <NAME>, SparkFun Electronics // // // // LIBRARY Created by <NAME> (@ameyer) of bildr 18 Aug 2012 // // Released as MIT license // // // // Changes: // // <NAME> (@thinkyhead) - Cleanup 06 Mar 2018 // // <NAME> (@bob-the-kuhn) - Chain / SPI 06 Jan 2019 // // <NAME> (@thinkyhead) - L64XXHelper 01 Mar 2019 // // // //////////////////////////////////////////////////////////////////// #pragma once #ifndef _L6470_H_ #define _L6470_H_ /** * This library is aimed at the L6470 but it also can be used * for other L647x devices, L648x devices and the powerSTEP01. * * Page numbers are for the L6470 data sheet. */ #include <Arduino.h> #define L6470_LIBRARY_VERSION 0x000800 //#define SCK 10 // Wire this to the CSN pin //#define MOSI 11 // Wire this to the SDI pin //#define MISO 12 // Wire this to the SDO pin //#define SS_PIN 16 // Wire this to the CK pin #define PIN_RESET 6 // Wire this to the STBY line #define PIN_BUSYN 4 // Wire this to the BSYN line #define STAT1 14 // Hooked to an LED on the test jig #define STAT2 15 // Hooked to an LED on the test jig #define SWITCH 8 // Hooked to the switch input and a pB on the jig // Constant definitions for L6470 overcurrent thresholds. Write these values to // register dSPIN_OCD_TH to set the level at which an overcurrent even occurs. #define OCD_TH_375mA 0x00 #define OCD_TH_750mA 0x01 #define OCD_TH_1125mA 0x02 #define OCD_TH_1500mA 0x03 #define OCD_TH_1875mA 0x04 #define OCD_TH_2250mA 0x05 #define OCD_TH_2625mA 0x06 #define OCD_TH_3000mA 0x07 #define OCD_TH_3375mA 0x08 #define OCD_TH_3750mA 0x09 #define OCD_TH_4125mA 0x0A #define OCD_TH_4500mA 0x0B #define OCD_TH_4875mA 0x0C #define OCD_TH_5250mA 0x0D #define OCD_TH_5625mA 0x0E #define OCD_TH_6000mA 0x0F // L6470_STEP_MODE option values. // First comes the "microsteps per step" options... #define STEP_MODE_STEP_SEL 0x07 // Mask for these bits only. #define STEP_SEL_1 0x00 #define STEP_SEL_1_2 0x01 #define STEP_SEL_1_4 0x02 #define STEP_SEL_1_8 0x03 #define STEP_SEL_1_16 0x04 #define STEP_SEL_1_32 0x05 #define STEP_SEL_1_64 0x06 #define STEP_SEL_1_128 0x07 // ...next, define the SYNC_EN bit. When set, the BUSYN pin will instead // output a clock related to the full-step frequency as defined by the // SYNC_SEL bits below. #define STEP_MODE_SYNC_EN 0x80 // Mask for this bit #define SYNC_EN 0x80 #define BUSY_EN 0x00 // ...last, define the SYNC_SEL modes. The clock output is defined by // the full-step frequency and the value in these bits- see the datasheet // for a matrix describing that relationship (page 46). #define STEP_MODE_SYNC_SEL 0x70 #define SYNC_SEL_1_2 0x00 #define SYNC_SEL_1 0x10 #define SYNC_SEL_2 0x20 #define SYNC_SEL_4 0x30 #define SYNC_SEL_8 0x40 #define SYNC_SEL_16 0x50 #define SYNC_SEL_32 0x60 #define SYNC_SEL_64 0x70 // Bit names for the L6470_ALARM_EN register. // Each of these bits defines one potential alarm condition. // When one of these conditions occurs and the respective bit in L6470_ALARM_EN is set, // the FLAG pin will go low. The register must be queried to determine which event // caused the alarm. #define ALARM_EN_OVERCURRENT 0x01 #define ALARM_EN_THERMAL_SHUTDOWN 0x02 #define ALARM_EN_THERMAL_WARNING 0x04 #define ALARM_EN_UNDER_VOLTAGE 0x08 #define ALARM_EN_STALL_DET_A 0x10 #define ALARM_EN_STALL_DET_B 0x20 #define ALARM_EN_SW_TURN_ON 0x40 #define ALARM_EN_WRONG_NPERF_CMD 0x80 // L64XX_CONFIG register renames. // Oscillator options. // The dSPIN needs to know what the clock frequency is because it uses that for some // calculations during operation. #define CONFIG_OSC_SEL 0x000F // Mask for this bit field. #define CONFIG_INT_16MHZ 0x0000 // Internal 16MHz, no output #define CONFIG_INT_16MHZ_OSCOUT_2MHZ 0x0008 // Default; internal 16MHz, 2MHz output #define CONFIG_INT_16MHZ_OSCOUT_4MHZ 0x0009 // Internal 16MHz, 4MHz output #define CONFIG_INT_16MHZ_OSCOUT_8MHZ 0x000A // Internal 16MHz, 8MHz output #define CONFIG_INT_16MHZ_OSCOUT_16MHZ 0x000B // Internal 16MHz, 16MHz output #define CONFIG_EXT_8MHZ_XTAL_DRIVE 0x0004 // External 8MHz crystal #define CONFIG_EXT_16MHZ_XTAL_DRIVE 0x0005 // External 16MHz crystal #define CONFIG_EXT_24MHZ_XTAL_DRIVE 0x0006 // External 24MHz crystal #define CONFIG_EXT_32MHZ_XTAL_DRIVE 0x0007 // External 32MHz crystal #define CONFIG_EXT_8MHZ_OSCOUT_INVERT 0x000C // External 8MHz crystal, output inverted #define CONFIG_EXT_16MHZ_OSCOUT_INVERT 0x000D // External 16MHz crystal, output inverted #define CONFIG_EXT_24MHZ_OSCOUT_INVERT 0x000E // External 24MHz crystal, output inverted #define CONFIG_EXT_32MHZ_OSCOUT_INVERT 0x000F // External 32MHz crystal, output inverted #define CONFIG_EN_TQREG 0x0020 // L6474 only - enable setting output slew rate // Configure the functionality of the external switch input #define CONFIG_SW_MODE 0x0010 // Mask for this bit. #define CONFIG_SW_HARD_STOP 0x0000 // Default; hard stop motor on switch. #define CONFIG_SW_USER 0x0010 // Tie to the GoUntil and ReleaseSW // commands to provide jog function. // See page 25 of datasheet. // Configure the motor voltage compensation mode (see page 34 of datasheet) #define CONFIG_EN_VSCOMP 0x0020 // Mask for this bit. #define CONFIG_VS_COMP_DISABLE 0x0000 // Disable motor voltage compensation. #define CONFIG_VS_COMP_ENABLE 0x0020 // Enable motor voltage compensation. // Configure overcurrent detection event handling #define CONFIG_OC_SD 0x0080 // Mask for this bit. #define CONFIG_OC_SD_DISABLE 0x0000 // Bridges do NOT shutdown on OC detect #define CONFIG_OC_SD_ENABLE 0x0080 // Bridges shutdown on OC detect // Configure the slew rate of the power bridge output // L6470 & L6474 #define CONFIG_POW_SR 0x0300 // Mask for this bit field. #define CONFIG_POW_SR_BIT 8 // starting bit of this field #define CONFIG_SR_320V_us 0x0000 // 320V/us #define CONFIG_SR_75V_us 0x0100 // 75V/us #define CONFIG_SR_110V_us 0x0200 // 110V/us #define CONFIG_SR_260V_us 0x0300 // 260V/us // L6480 & powerSTEP01 #define CONFIG1_SR 0x00FF // Mask for this bit field. #define CONFIG1_SR_220V_us 0x006C #define CONFIG1_SR_400V_us 0x0087 #define CONFIG1_SR_520V_us 0x00A6 #define CONFIG1_SR_980V_us 0x00E2 #define CONFIG2_SR_220V_us 0x10 #define CONFIG2_SR_400V_us 0x10 #define CONFIG2_SR_520V_us 0x10 #define CONFIG2_SR_980V_us 0x30 // L6480 & powerSTEP01 VCC setting #define PWR_VCC_7_5V 0 #define PWR_VCC_15V 0x0100 // Integer divisors for PWM sinewave generation // See page 32 of the datasheet for more information on this. #define CONFIG_F_PWM_DEC 0x1C00 // mask for this bit field #define CONFIG_PWM_MUL_0_625 (0x00<<10) #define CONFIG_PWM_MUL_0_75 (0x01<<10) #define CONFIG_PWM_MUL_0_875 (0x02<<10) #define CONFIG_PWM_MUL_1 (0x03<<10) #define CONFIG_PWM_MUL_1_25 (0x04<<10) #define CONFIG_PWM_MUL_1_5 (0x05<<10) #define CONFIG_PWM_MUL_1_75 (0x06<<10) #define CONFIG_PWM_MUL_2 (0x07<<10) // Multiplier for the PWM sinewave frequency #define CONFIG_F_PWM_INT 0xE000 // mask for this bit field. #define CONFIG_PWM_DIV_1 (0x00<<13) #define CONFIG_PWM_DIV_2 (0x01<<13) #define CONFIG_PWM_DIV_3 (0x02<<13) #define CONFIG_PWM_DIV_4 (0x03<<13) #define CONFIG_PWM_DIV_5 (0x04<<13) #define CONFIG_PWM_DIV_6 (0x05<<13) #define CONFIG_PWM_DIV_7 (0x06<<13) // status register layouts #define L6470_STATUS_LAYOUT 0x0000 #define L6474_STATUS_LAYOUT 0x0001 #define L6480_STATUS_LAYOUT 0x0002 // Status register bit renames- read-only bits conferring information about the // device to the user. #define STATUS_HIZ 0x0001 // high when bridges are in HiZ mode #define STATUS_BUSY 0x0002 // mirrors BUSY pin #define STATUS_SW_F 0x0004 // low when switch open, high when closed #define STATUS_SW_EVN 0x0008 // active high, set on switch falling edge, // cleared by reading L64XX_STATUS #define STATUS_DIR 0x0010 // Indicates current motor direction. // High is dSPIN_FWD, Low is dSPIN_REV. // Status register motor status field #define STATUS_MOT_STATUS 0x0060 // field mask #define STATUS_MOT_STATUS_STOPPED (0x0000<<13) // Motor stopped #define STATUS_MOT_STATUS_ACCELERATION (0x0001<<13) // Motor accelerating #define STATUS_MOT_STATUS_DECELERATION (0x0002<<13) // Motor decelerating #define STATUS_MOT_STATUS_CONST_SPD (0x0003<<13) // Motor at constant speed // Register address redefines. // See the Param_Handler() function for more info about these. #define L6470_ABS_POS 0x01 #define L6470_EL_POS 0x02 #define L6470_MARK 0x03 #define L6470_SPEED 0x04 #define L6470_ACC 0x05 #define L6470_DEC 0x06 #define L6470_MAX_SPEED 0x07 #define L6470_MIN_SPEED 0x08 #define L6470_FS_SPD 0x15 #define L6470_KVAL_HOLD 0x09 #define L6470_KVAL_RUN 0x0A #define L6470_KVAL_ACC 0x0B #define L6470_KVAL_DEC 0x0C #define L6470_INT_SPD 0x0D #define L6470_ST_SLP 0x0E #define L6470_FN_SLP_ACC 0x0F #define L6470_FN_SLP_DEC 0x10 #define L6470_K_THERM 0x11 #define L6470_ADC_OUT 0x12 #define L6470_OCD_TH 0x13 #define L6470_STALL_TH 0x14 #define L6470_STEP_MODE 0x16 #define L6470_ALARM_EN 0x17 #define L6470_GATECFG1 0x18 // L6480 & powerSTEP01 only #define L6470_GATECFG2 0x19 // L6480 & powerSTEP01 only #define L6474_TVAL 0x09 // L6474 only #define PWR_TVAL_HOLD 0X09 // powerSTEP01 current mode register names #define PWR_TVAL_RUN 0X0A #define PWR_TVAL_ACC 0X0B #define PWR_TVAL_DEC 0X0C #define PWR_T_FAST 0X0E #define PWR_TON_MIN 0X0F #define PWR_TOFF_MIN 0X10 // dSPIN commands #define dSPIN_NOP 0x00 #define dSPIN_SET_PARAM 0x00 #define dSPIN_GET_PARAM 0x20 #define dSPIN_RUN 0x50 #define dSPIN_STEP_CLOCK 0x58 #define dSPIN_MOVE 0x40 #define dSPIN_GOTO 0x60 #define dSPIN_GOTO_DIR 0x68 #define dSPIN_GO_UNTIL 0x82 #define dSPIN_RELEASE_SW 0x92 #define dSPIN_GO_HOME 0x70 #define dSPIN_GO_MARK 0x78 #define dSPIN_RESET_POS 0xD8 #define dSPIN_RESET_DEVICE 0xC0 #define dSPIN_SOFT_STOP 0xB0 #define dSPIN_HARD_STOP 0xB8 #define dSPIN_L6474_ENABLE dSPIN_HARD_STOP #define dSPIN_SOFT_HIZ 0xA0 #define dSPIN_HARD_HIZ 0xA8 #define dSPIN_GET_STATUS 0xD0 // dSPIN direction options #define dSPIN_FWD 0x01 #define dSPIN_REV 0x00 // dSPIN action options #define dSPIN_ACTION_RESET 0x00 #define dSPIN_ACTION_COPY 0x01 typedef int16_t _pin_t; typedef void (*spi_init_handler_t)(); typedef uint8_t (*transfer_handler_t)(uint8_t data, const int16_t ss_pin); typedef uint8_t (*chain_transfer_handler_t)(uint8_t data, const int16_t ss_pin, const uint8_t chain_position); uint8_t chain_transfer_dummy(uint8_t data, const int16_t ss_pin, const uint8_t chain_position); uint8_t transfer_dummy(uint8_t data, const int16_t ss_pin); void spi_init_dummy(); class L64XXHelper { //protected: public: friend class L64XX; friend class L6470; friend class L6480; friend class powerSTEP01; static inline void spi_init() { } static inline uint8_t transfer(uint8_t data, const _pin_t ss_pin) { return 0; } static inline uint8_t transfer(uint8_t data, const _pin_t ss_pin, const uint8_t chain_position) { return 0; } static inline uint8_t transfer_single(uint8_t data, const _pin_t ss_pin) { return 0; } static inline uint8_t transfer_chain(uint8_t data, const _pin_t ss_pin, const uint8_t chain_position) { return 0; } }; extern L64XXHelper nullHelper; class L64XX { public: _pin_t pin_SS = -1, pin_SCK = -1, pin_MOSI = -1, pin_MISO = -1, pin_RESET = -1, pin_BUSYN = -1; static uint8_t chain[21]; // [0] - number of drivers in chain // [1]... axis index for first device in the chain (closest to MOSI) uint8_t axis_index; uint8_t position = 0; // 0 - not part of a chain // This object must be supplied by the client static L64XXHelper *helper; static inline void set_helper(L64XXHelper *_helper) { helper = _helper; } ////////////////////////////////////////////////////////////////////////////////////////////////// // These methods must be supplied by the client chain_transfer_handler_t chain_transfer = chain_transfer_dummy; transfer_handler_t transfer = transfer_dummy; spi_init_handler_t spi_init = spi_init_dummy; inline void set_spi_init_handler(spi_init_handler_t _spi_init) { spi_init = _spi_init; } inline void set_transfer_handler(transfer_handler_t _transfer) { transfer = _transfer; } inline void set_chain_transfer_handler(chain_transfer_handler_t _chain_transfer) { chain_transfer = _chain_transfer; } void set_handlers(spi_init_handler_t _spi_init, transfer_handler_t _transfer, chain_transfer_handler_t _chain_transfer) { set_spi_init_handler(_spi_init); set_transfer_handler(_transfer); set_chain_transfer_handler(_chain_transfer); } //////////////////////////////////////////////////////////////////////////////////////////////////////////// void init(); inline void init(const _pin_t ss_pin) { pin_SS = ss_pin; } inline void init(const _pin_t ss_pin, L64XXHelper *_helper) { pin_SS = ss_pin; set_helper(_helper); } void set_pins(const _pin_t SCK, const _pin_t MOSI, const _pin_t MISO, const _pin_t RESET, const _pin_t BUSYN); void set_chain_info(const uint8_t axis_index, const uint8_t position); void setMicroSteps(int16_t microSteps); void setMaxSpeed(const int16_t speed); void setMinSpeed(const int16_t speed); void setAcc(const float acceleration); void setDec(const float deceleration); void setOverCurrent(float ma_current); void setTVALCurrent(float ma_current); void setThresholdSpeed(const float threshold); void setStallCurrent(float ma_current); uint32_t ParamHandler(const uint8_t param, const uint32_t value); void SetLowSpeedOpt(uint8_t enable); void run(const uint8_t dir, const float spd); void Step_Clock(const uint8_t dir); void goHome(); void setAsHome(); void goMark(); void move(const long n_step); void goTo(long pos); void goTo_DIR(const uint8_t dir, long pos); void goUntil(const uint8_t act, const uint8_t dir, uint32_t spd); uint8_t isBusy(); void releaseSW(const uint8_t act, const uint8_t dir); float getSpeed(); long getPos(); void setMark(); void setMark(long value); void resetPos(); void resetDev(); void softStop(); void hardStop(); void softFree(); void free(); int16_t getStatus(); void SetParam(const uint8_t param, const uint32_t value); uint32_t GetParam(const uint8_t param); // // L6470 placeholders - will be set by sub-classes // // current warning definitions uint8_t OCD_TH_MAX; // max value of OCD_TH bit field uint8_t STALL_TH_MAX; // max value of STALL_TH bit field float OCD_CURRENT_CONSTANT_INV; // mA per count float OCD_CURRENT_CONSTANT; // counts per mA float STALL_CURRENT_CONSTANT_INV; // mA per count float STALL_CURRENT_CONSTANT ; // counts per mA uint8_t L64XX_CONFIG; // CONFIG register address uint8_t L64XX_STATUS; // STATUS register address uint8_t L6470_status_layout; // status bit locations uint16_t STATUS_NOTPERF_CMD; // Last command not performed. uint16_t STATUS_WRONG_CMD; // Last command not valid. uint16_t STATUS_CMD_ERR; // Command error uint16_t STATUS_UVLO; // Undervoltage lockout is active uint16_t STATUS_TH_WRN; // Thermal warning uint16_t STATUS_TH_SD; // Thermal shutdown uint16_t STATUS_OCD; // Overcurrent detected uint16_t STATUS_STEP_LOSS_A; // Stall detected on A bridge uint16_t STATUS_STEP_LOSS_B; // Stall detected on B bridge uint16_t STATUS_SCK_MOD; // Step clock mode is active uint16_t UVLO_ADC; // ADC undervoltage event private: long convert(uint32_t val); uint32_t AccCalc(const float stepsPerSecPerSec); uint32_t DecCalc(const float stepsPerSecPerSec); uint32_t MaxSpdCalc(const float stepsPerSec); uint32_t MinSpdCalc(const float stepsPerSec); uint32_t FSCalc(const float stepsPerSec); uint32_t IntSpdCalc(const float stepsPerSec); uint32_t SpdCalc(const float stepsPerSec); uint32_t Param(uint32_t value, const uint8_t bit_len); uint8_t Xfer(uint8_t data); uint8_t Xfer(uint8_t data, _pin_t ss_pin, uint8_t position); }; class L6470 : public L64XX { public: L6470(const _pin_t ss_pin) { init(ss_pin); L6470::OCD_TH_MAX = 15; L6470::STALL_TH_MAX = 127; L6470::OCD_CURRENT_CONSTANT_INV = 375.0f; // mA per count L6470::OCD_CURRENT_CONSTANT = 1.0f / L6470::OCD_CURRENT_CONSTANT_INV; // counts per mA L6470::STALL_CURRENT_CONSTANT_INV = 31.25; // mA per count L6470::STALL_CURRENT_CONSTANT = 1.0f / L6470::STALL_CURRENT_CONSTANT_INV; // counts per mA L6470::L64XX_CONFIG = 0x18; L6470::L64XX_STATUS = 0x19; L6470::L6470_status_layout = L6470_STATUS_LAYOUT; L6470::STATUS_NOTPERF_CMD = 0x0080; // Last command not performed. L6470::STATUS_WRONG_CMD = 0x0100; // Last command not valid. L6470::STATUS_CMD_ERR = 0x0180; // Command error L6470::STATUS_UVLO = 0x0200; // Undervoltage lockout is active L6470::STATUS_TH_WRN = 0x0400; // Thermal warning L6470::STATUS_TH_SD = 0x0800; // Thermal shutdown L6470::STATUS_OCD = 0x1000; // Overcurrent detected L6470::STATUS_STEP_LOSS_A = 0x2000; // Stall detected on A bridge L6470::STATUS_STEP_LOSS_B = 0x4000; // Stall detected on B bridge L6470::STATUS_SCK_MOD = 0x0001; // Step clock mode is active L6470::UVLO_ADC = 0x0400; // ADC undervoltage event } L6470(const _pin_t ss_pin, L64XXHelper *_helper) { init(ss_pin, _helper); L6470::OCD_TH_MAX = 15; L6470::STALL_TH_MAX = 127; L6470::OCD_CURRENT_CONSTANT_INV = 375.0f; // mA per count L6470::OCD_CURRENT_CONSTANT = 1.0f / L6470::OCD_CURRENT_CONSTANT_INV; // counts per mA L6470::STALL_CURRENT_CONSTANT_INV = 31.25; // mA per count L6470::STALL_CURRENT_CONSTANT = 1.0f / L6470::STALL_CURRENT_CONSTANT_INV; // counts per mA L6470::L64XX_CONFIG = 0x18; L6470::L64XX_STATUS = 0x19; L6470::L6470_status_layout = L6470_STATUS_LAYOUT; L6470::STATUS_NOTPERF_CMD = 0x0080; // Last command not performed. L6470::STATUS_WRONG_CMD = 0x0100; // Last command not valid. L6470::STATUS_CMD_ERR = 0x0180; // Command error L6470::STATUS_UVLO = 0x0200; // Undervoltage lockout is active L6470::STATUS_TH_WRN = 0x0400; // Thermal warning L6470::STATUS_TH_SD = 0x0800; // Thermal shutdown L6470::STATUS_OCD = 0x1000; // Overcurrent detected L6470::STATUS_STEP_LOSS_A = 0x2000; // Stall detected on A bridge L6470::STATUS_STEP_LOSS_B = 0x4000; // Stall detected on B bridge L6470::STATUS_SCK_MOD = 0x0001; // Step clock mode is active L6470::UVLO_ADC = 0x0400; // ADC undervoltage event } }; class L6474 : public L64XX { public: L6474(const _pin_t ss_pin) { init(ss_pin); L6474::OCD_TH_MAX = 15; L6474::STALL_TH_MAX = 127; // STALL function not implemented on L6474 L6474::OCD_CURRENT_CONSTANT_INV = 375.0f; // mA per count L6474::OCD_CURRENT_CONSTANT = 1.0f / L6474::OCD_CURRENT_CONSTANT_INV; // counts per mA L6474::STALL_CURRENT_CONSTANT_INV = 31.25; // mA per count L6474::STALL_CURRENT_CONSTANT = 1.0f / L6474::STALL_CURRENT_CONSTANT_INV; // counts per mA L6474::L64XX_CONFIG = 0x18; L6474::L64XX_STATUS = 0x19; L6474::L6470_status_layout = L6474_STATUS_LAYOUT; L6474::STATUS_NOTPERF_CMD = 0x0080; // Last command not performed. L6474::STATUS_WRONG_CMD = 0x0100; // Last command not valid L6474::STATUS_CMD_ERR = 0x0000; // Command error - not implemented on L6474 L6474::STATUS_UVLO = 0x0200; // Undervoltage lockout is active L6474::STATUS_TH_WRN = 0x0400; // Thermal warning L6474::STATUS_TH_SD = 0x0800; // Thermal shutdown L6474::STATUS_OCD = 0x1000; // Overcurrent detected L6474::STATUS_STEP_LOSS_A = 0x0000; // Stall detected on A bridge - not implemented on L6474 L6474::STATUS_STEP_LOSS_B = 0x0000; // Stall detected on B bridge - not implemented on L6474 L6474::STATUS_SCK_MOD = 0x0000; // Step clock mode is active - not implemented on L6474 L6474::UVLO_ADC = 0x0000; // ADC undervoltage event - not implemented on L6474 } L6474(const _pin_t ss_pin, L64XXHelper *_helper) { init(ss_pin, _helper); L6474::OCD_TH_MAX = 15; L6474::STALL_TH_MAX = 127; L6474::OCD_CURRENT_CONSTANT_INV = 375.0f; // mA per count L6474::OCD_CURRENT_CONSTANT = 1.0f / L6474::OCD_CURRENT_CONSTANT_INV; // counts per mA L6474::STALL_CURRENT_CONSTANT_INV = 31.25; // mA per count L6474::STALL_CURRENT_CONSTANT = 1.0f / L6474::STALL_CURRENT_CONSTANT_INV; // counts per mA L6474::L64XX_CONFIG = 0x18; L6474::L64XX_STATUS = 0x19; L6474::L6470_status_layout = L6474_STATUS_LAYOUT; L6474::STATUS_NOTPERF_CMD = 0x0080; // Last command not performed. L6474::STATUS_WRONG_CMD = 0x0100; // Last command not valid L6474::STATUS_CMD_ERR = 0x0000; // Command error - not implemented on L6474 L6474::STATUS_UVLO = 0x0200; // Undervoltage lockout is active L6474::STATUS_TH_WRN = 0x0400; // Thermal warning L6474::STATUS_TH_SD = 0x0800; // Thermal shutdown L6474::STATUS_OCD = 0x1000; // Overcurrent detected L6474::STATUS_STEP_LOSS_A = 0x0000; // Stall detected on A bridge - not implemented on L6474 L6474::STATUS_STEP_LOSS_B = 0x0000; // Stall detected on B bridge - not implemented on L6474 L6474::STATUS_SCK_MOD = 0x0000; // Step clock mode is active - not implemented on L6474 L6474::UVLO_ADC = 0x0000; // ADC undervoltage event - not implemented on L6474 } }; class L6480_Base : public L64XX { public: }; class L6480 : public L6480_Base { public: L6480(const _pin_t ss_pin) { init(ss_pin); L6480::OCD_TH_MAX = 31; L6480::STALL_TH_MAX = 31; L6480::OCD_CURRENT_CONSTANT_INV = 375.0f; // mA per count L6480::OCD_CURRENT_CONSTANT = 1.0f / L6480::OCD_CURRENT_CONSTANT_INV; // counts per mA L6480::STALL_CURRENT_CONSTANT_INV = 31.25; // mA per count L6480::STALL_CURRENT_CONSTANT = 1.0f / L6480::STALL_CURRENT_CONSTANT_INV; // counts per mA L6480::L6470_status_layout = L6480_STATUS_LAYOUT; L6480::L64XX_CONFIG = 0x1A; L6480::L64XX_STATUS = 0x1B; L6480::L6470_status_layout = L6480_STATUS_LAYOUT; L6480::STATUS_WRONG_CMD = 0x0080; // Last command not valid. L6480::STATUS_CMD_ERR = 0x0080; // Command error L6480::STATUS_UVLO = 0x0200; // Undervoltage lockout is active L6480::UVLO_ADC = 0x0400; // ADC undervoltage event L6480::STATUS_TH_WRN = 0x0800; // Thermal warning L6480::STATUS_TH_SD = 0x1000; // Thermal shutdown L6480::STATUS_OCD = 0x2000; // Overcurrent detected L6480::STATUS_STEP_LOSS_A = 0x4000; // Stall detected on A bridge L6480::STATUS_STEP_LOSS_B = 0x8000; // Stall detected on B bridge L6480::STATUS_SCK_MOD = 0x0100; // Step clock mode is active } L6480(const _pin_t ss_pin, L64XXHelper *_helper) { init(ss_pin, _helper); L6480::OCD_TH_MAX = 31; L6480::STALL_TH_MAX = 31; L6480::OCD_CURRENT_CONSTANT_INV = 375.0f; // mA per count L6480::OCD_CURRENT_CONSTANT = 1.0f / L6480::OCD_CURRENT_CONSTANT_INV; // counts per mA L6480::STALL_CURRENT_CONSTANT_INV = 31.25; // mA per count L6480::STALL_CURRENT_CONSTANT = 1.0f / L6480::STALL_CURRENT_CONSTANT_INV; // counts per mA L6480::L6470_status_layout = L6480_STATUS_LAYOUT; L6480::L64XX_CONFIG = 0x1A; L6480::L64XX_STATUS = 0x1B; L6480::L6470_status_layout = L6480_STATUS_LAYOUT; L6480::STATUS_WRONG_CMD = 0x0080; // Last command not valid. L6480::STATUS_CMD_ERR = 0x0080; // Command error L6480::STATUS_UVLO = 0x0200; // Undervoltage lockout is active L6480::UVLO_ADC = 0x0400; // ADC undervoltage event L6480::STATUS_TH_WRN = 0x0800; // Thermal warning L6480::STATUS_TH_SD = 0x1000; // Thermal shutdown L6480::STATUS_OCD = 0x2000; // Overcurrent detected L6480::STATUS_STEP_LOSS_A = 0x4000; // Stall detected on A bridge L6480::STATUS_STEP_LOSS_B = 0x8000; // Stall detected on B bridge L6480::STATUS_SCK_MOD = 0x0100; // Step clock mode is active } }; class powerSTEP01 : public L6480_Base { public: powerSTEP01(const _pin_t ss_pin) { init(ss_pin); powerSTEP01::OCD_TH_MAX = 31; powerSTEP01::STALL_TH_MAX = 31; powerSTEP01::OCD_CURRENT_CONSTANT = 0.001; // counts per mA (empirically derived for powerSTEP01) powerSTEP01::OCD_CURRENT_CONSTANT_INV = 1000; // mA per count (empirically derived for powerSTEP01) powerSTEP01::STALL_CURRENT_CONSTANT = 0.005; // counts per mA (empirically derived for powerSTEP01) powerSTEP01::STALL_CURRENT_CONSTANT_INV = 200; // mA per count (empirically derived for powerSTEP01) powerSTEP01::L64XX_CONFIG = 0x1A; powerSTEP01::L64XX_STATUS = 0x1B; powerSTEP01::L6470_status_layout = L6480_STATUS_LAYOUT; powerSTEP01::STATUS_WRONG_CMD = 0x0080; // Last command not valid. powerSTEP01::STATUS_CMD_ERR = 0x0080; // Command error powerSTEP01::STATUS_UVLO = 0x0200; // Undervoltage lockout is active powerSTEP01::UVLO_ADC = 0x0400; // ADC undervoltage event powerSTEP01::STATUS_TH_WRN = 0x0800; // Thermal warning powerSTEP01::STATUS_TH_SD = 0x1000; // Thermal shutdown powerSTEP01::STATUS_OCD = 0x2000; // Overcurrent detected powerSTEP01::STATUS_STEP_LOSS_A = 0x4000; // Stall detected on A bridge powerSTEP01::STATUS_STEP_LOSS_B = 0x8000; // Stall detected on B bridge powerSTEP01::STATUS_SCK_MOD = 0x0100; // Step clock mode is active } powerSTEP01(const _pin_t ss_pin, L64XXHelper *_helper) { init(ss_pin, _helper); powerSTEP01::OCD_TH_MAX = 31; powerSTEP01::STALL_TH_MAX = 31; powerSTEP01::OCD_CURRENT_CONSTANT = 0.001; // counts per mA (empirically derived for powerSTEP01) powerSTEP01::OCD_CURRENT_CONSTANT_INV = 1000; // mA per count (empirically derived for powerSTEP01) powerSTEP01::STALL_CURRENT_CONSTANT = 0.005; // counts per mA (empirically derived for powerSTEP01) powerSTEP01::STALL_CURRENT_CONSTANT_INV = 200; // mA per count (empirically derived for powerSTEP01) powerSTEP01::L64XX_CONFIG = 0x1A; powerSTEP01::L64XX_STATUS = 0x1B; powerSTEP01::L6470_status_layout = L6480_STATUS_LAYOUT; powerSTEP01::STATUS_WRONG_CMD = 0x0080; // Last command not valid. powerSTEP01::STATUS_CMD_ERR = 0x0080; // Command error powerSTEP01::STATUS_UVLO = 0x0200; // Undervoltage lockout is active powerSTEP01::UVLO_ADC = 0x0400; // ADC undervoltage event powerSTEP01::STATUS_TH_WRN = 0x0800; // Thermal warning powerSTEP01::STATUS_TH_SD = 0x1000; // Thermal shutdown powerSTEP01::STATUS_OCD = 0x2000; // Overcurrent detected powerSTEP01::STATUS_STEP_LOSS_A = 0x4000; // Stall detected on A bridge powerSTEP01::STATUS_STEP_LOSS_B = 0x8000; // Stall detected on B bridge powerSTEP01::STATUS_SCK_MOD = 0x0100; // Step clock mode is active } }; #endif // _L6470_H_
Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M
.pio/libdeps/esp32/SoftwareSerialM/HAL_softserial_LPC1768.h
<gh_stars>1-10 #pragma once #define OVERSAMPLE 3 #define INTERRUPT_PRIORITY 0 #include <pinmapping.h> #include <time.h> #include "lpc17xx_rit.h" #include "lpc17xx_clkpwr.h" #include "debug_frmwrk.h"
Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M
.pio/libdeps/esp32/SoftwareSerialM/HAL_softserial_STM32F1.h
<reponame>Sundancer78/Marlin-2.0.5.3_SKR_13_Geeetech_A10M /** * FYSETC * * Copyright (c) 2019 SoftwareSerialM [https://github.com/FYSETC/SoftwareSerialM] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * HAL for stm32duino.com based on Libmaple and compatible (STM32F1) */ #pragma once #include <HardwareTimer.h> #define OVERSAMPLE 3 #define INTERRUPT_PRIORITY 0 #define gpio_set(IO,V) (PIN_MAP[IO].gpio_device->regs->BSRR = (1U << PIN_MAP[IO].gpio_bit) << ((V) ? 0 : 16)) #define gpio_get(IO) (PIN_MAP[IO].gpio_device->regs->IDR & (1U << PIN_MAP[IO].gpio_bit) ? HIGH : LOW) #define cli() noInterrupts() // Disable interrupts #define sei() interrupts() // Enable interrupts #define HAL_softserial_timer_isr_prologue() #define HAL_softserial_timer_isr_epilogue() #define HAL_SOFTSERIAL_TIMER_ISR() extern "C" void SoftSerial_Handler() extern "C" void SoftSerial_Handler(void);
iplinux/linebreak
filter_dup.c
#include <stdio.h> #include <string.h> int main() { char s[80]; char beg[16]; char end[16]; char prop[16]; char lastbeg[16]; char lastend[16]; char lastprop[16]; lastprop[0] = 0; for (;;) { if (fgets(s, sizeof s, stdin) == NULL) break; if (strstr(s, "LBP_") == NULL || strstr(s, "LBP_Undef") != NULL) { if (lastprop[0]) { printf("\t{ %s %s %s },\n", lastbeg, lastend, lastprop); lastprop[0] = 0; } printf("%s", s); continue; } sscanf(s, "\t{ %s %s %s }", beg, end, prop); /*printf("==>\t{ \"%s\" \"%s\" \"%s\" },\n", beg, end, prop);*/ if (lastprop[0] && strcmp(lastprop, prop) != 0) { printf("\t{ %s %s %s },\n", lastbeg, lastend, lastprop); lastprop[0] = 0; } if (lastprop[0] == 0) { strcpy(lastbeg, beg); strcpy(lastprop, prop); } strcpy(lastend, end); } if (lastprop[0]) { printf("\t{ %s %s %s },\n", lastbeg, lastend, prop); } return 0; }
isklikas/PadlockAnimationView
PadlockAnimationView/ViewController.h
<reponame>isklikas/PadlockAnimationView<filename>PadlockAnimationView/ViewController.h // // ViewController.h // PadlockAnimationView // // Created by Yannis on 11/3/20. // Copyright © 2020 isklikas. All rights reserved. // #import <UIKit/UIKit.h> #import "LockView.h" @interface ViewController : UIViewController @property LockView *lockView; @property UISlider *slider; @property UILabel *sliderLabel; @property CGFloat currentProgress; @end
isklikas/PadlockAnimationView
PadlockAnimationView/LockView.h
// // LockView.h // PadlockAnimationView // // Created by Yannis on 11/3/20. // Copyright © 2020 isklikas. All rights reserved. // #import <UIKit/UIKit.h> #import "LockViewAnimator.h" @class LockViewAnimator; NS_ASSUME_NONNULL_BEGIN @interface LockView : UIView @property (nonatomic) CGFloat progress; // 0.0 being locked, 1.0 being unlocked @property CAShapeLayer *shackleLayer; @property CAShapeLayer *bodyLayer; @property UIBezierPath *shacklePath; @property LockViewAnimator *animator; @end NS_ASSUME_NONNULL_END
isklikas/PadlockAnimationView
PadlockAnimationView/LockViewAnimator.h
<filename>PadlockAnimationView/LockViewAnimator.h<gh_stars>1-10 // // LockViewAnimator.h // PadlockAnimationView // // Created by Yannis on 11/3/20. // Copyright © 2020 isklikas. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface LockViewAnimator : NSObject @property (weak, nonatomic) id lockView; @property CGFloat threshold; @property CGFloat progress; @end NS_ASSUME_NONNULL_END
MuthukumarPhoton/JailBreakDetect
JailBreakDetect/JailBreakDetect.h
#import <Foundation/Foundation.h> @interface JailBreakDetect : NSObject + (BOOL)isCompromised; @end
RomanKazantsev/image-processing-filters
inc/pixelformats.h
<filename>inc/pixelformats.h /* Copyright (c) 2011-2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #pragma pack(push, 1) struct ColorBytePixel { unsigned char b, g, r, a; inline ColorBytePixel() : b(0), g(0), r(0), a(0) {} inline ColorBytePixel(unsigned char b, unsigned char g, unsigned char r, unsigned char a = 0) : b(b), g(g), r(r), a(a) {} }; struct ColorFloatPixel { public: float b, g, r, a; inline ColorFloatPixel() : b(0.0f), g(0.0f), r(0.0f), a(0.0f) {} inline ColorFloatPixel(float b, float g, float r, float a = 0.0f) : b(b), g(g), r(r), a(a) {} inline ColorFloatPixel& operator += (const ColorFloatPixel &other) { b += other.b; g += other.g; r += other.r; a += other.a; return *this; } inline ColorFloatPixel operator + (const ColorFloatPixel &other) const { return ColorFloatPixel(b + other.b, g + other.g, r + other.r, a + other.a); } inline ColorFloatPixel operator * (float q) const { return ColorFloatPixel(b * q, g * q, r * q, a * q); } }; inline ColorFloatPixel operator * (float q, const ColorFloatPixel &p) { return ColorFloatPixel(p.b * q, p.g * q, p.r * q, p.a * q); } #pragma pack(pop)
RomanKazantsev/image-processing-filters
inc/mirror.h
/* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "imageio.h" using namespace std; int Mirror(char *inputfilename, char *outputfilename, int mode) { if (mode != 1 && mode != 2) { return 0; } ColorFloatImage image = ImageIO::FileToColorFloatImage(inputfilename); ColorFloatImage res(image.Width(), image.Height()); if (mode == 1) { // horizontal for (int j = 0; j < res.Height(); j++) { for (int i = 0; i < res.Width(); i++) { res(i, j).b = image(res.Width() - 1 - i, j).b; res(i, j).g = image(res.Width() - 1 - i, j).g; res(i, j).r = image(res.Width() - 1 - i, j).r; res(i, j).a = image(res.Width() - 1 - i, j).a; } } } else if (mode = 2) { // vertical for (int j = 0; j < res.Height(); j++) { for (int i = 0; i < res.Width(); i++) { res(i, j).b = image(i, res.Height() - 1 - j).b; res(i, j).g = image(i, res.Height() - 1 - j).g; res(i, j).r = image(i, res.Height() - 1 - j).r; res(i, j).a = image(i, res.Height() - 1 - j).a; } } } ImageIO::ImageToFile(res, outputfilename); return 0; }
RomanKazantsev/image-processing-filters
inc/gabor.h
<reponame>RomanKazantsev/image-processing-filters /* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #define _USE_MATH_DEFINES #include <vector> #include <float.h> #include "imageio.h" using namespace std; int ExtrapolateImage(ColorFloatImage const &image, ColorFloatImage &ext_image, int rad_x, int rad_y) { for (int j = 0; j < image.Height(); j++) { for (int i = 0; i < image.Width(); i++) { ext_image(i + rad_x, j + rad_y) = image(i, j); } } for (int j = 0; j < image.Height(); j++) { for (int i = 0; i < rad_x; i++) { ext_image(i, j + rad_y) = image(rad_x - i - 1, j); ext_image(image.Width() + rad_x + i, j + rad_y) = image(image.Width() - i - 1, j); } } for (int j = 0; j < rad_y; j++) { for (int i = 0; i < image.Width(); i++) { ext_image(i + rad_x, j) = image(i, rad_y - j - 1); ext_image(i + rad_x, image.Height() + rad_y + j) = image(i, image.Height() - j - 1); } } for (int j = 0; j < rad_y; j++) { for (int i = 0; i < rad_x; i++) { ext_image(i, j) = image(rad_x - i, rad_y - j); ext_image(i, ext_image.Height() - 1 - j) = image(rad_x - 1 - i, image.Height() - 1 - rad_y + j); // ? ext_image(ext_image.Width() - 1 - i, j) = image(image.Width() - 1 - rad_x + i, rad_y - 1 - j); // ? ext_image(image.Width() + rad_x + i, image.Height() + rad_y + j) = image(image.Width() - 1 - i, image.Height() - 1 - j); } } return 0; } int CreateGaborKernel(float sigma, float gamma, float theta, float lambda, float psi, std::vector<float> &kernel, int &rad_x, int &rad_y) { float sigma_x = sigma; float sigma_y = sigma_x / gamma; rad_x = std::ceil(3.0f * sigma_x); rad_y = std::ceil(3.0f * sigma_y); kernel.clear(); float sigma_x2 = 2.0f * sigma * sigma; for (int ky = -rad_y; ky <= rad_y; ky++) { for (int kx = -rad_x; kx <= rad_x; kx++) { float x_theta = kx * std::cosf(theta) + ky * std::sinf(theta); float y_theta = -kx * std::sinf(theta) + ky * std::cosf(theta); float gb = std::expf(-(x_theta * x_theta + gamma * gamma * y_theta * y_theta) / sigma_x2) * std::cosf(2.0f * M_PI * x_theta / lambda + psi); kernel.push_back(gb); } } return 0; } int ApplyGaborFilter(ColorFloatImage const &input_image, GrayscaleFloatImage &output_image, float sigma, float gamma, float theta, float lambda, float psi) { int rad_x = 0; int rad_y = 0; int width = output_image.Width(); int height = output_image.Height(); // convert angels to radians theta = theta / 180.0f * float(M_PI); psi = psi / 180.0f * float(M_PI); // compute gabor kernel std::vector<float> kernel; CreateGaborKernel(sigma, gamma, theta, lambda, psi, kernel, rad_x, rad_y); // prepare extrapolated image ColorFloatImage tmp_image(input_image.Width() + 2 * rad_x, input_image.Height() + 2 * rad_y); ExtrapolateImage(input_image, tmp_image, rad_x, rad_y); // process image with gabor filter for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { float sum = 0.0f; for (int k = 0; k < kernel.size(); k++) { int jj = k / (2 * rad_x + 1); int ii = k % (2 * rad_x + 1); float p = ToGray(tmp_image(i + ii, j + jj)); sum += kernel[k] * p; } output_image(i, j) = sum; } } return 0; }
RomanKazantsev/image-processing-filters
inc/imageio.h
/* Copyright (c) 2011-2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) #include <Windows.h> #include <GdiPlus.h> #endif #include "imageformats.h" class ImageIO { public: static GrayscaleFloatImage FileToGrayscaleFloatImage(const char* filename); static GrayscaleByteImage FileToGrayscaleByteImage(const char* filename); static ColorFloatImage FileToColorFloatImage(const char* filename); static ColorByteImage FileToColorByteImage(const char* filename); static void ImageToFile(const GrayscaleFloatImage &image, const char *filename); static void ImageToFile(const GrayscaleByteImage &image, const char *filename); static void ImageToFile(const ColorFloatImage &image, const char *filename); static void ImageToFile(const ColorByteImage &image, const char *filename); #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) private: static GrayscaleFloatImage BitmapToGrayscaleFloatImage(Gdiplus::Bitmap &B); static GrayscaleByteImage BitmapToGrayscaleByteImage(Gdiplus::Bitmap &B); static ColorFloatImage BitmapToColorFloatImage(Gdiplus::Bitmap &B); static ColorByteImage BitmapToColorByteImage(Gdiplus::Bitmap &B); static std::unique_ptr<Gdiplus::Bitmap> ImageToBitmap(const GrayscaleFloatImage &image); static std::unique_ptr<Gdiplus::Bitmap> ImageToBitmap(const GrayscaleByteImage &image); static std::unique_ptr<Gdiplus::Bitmap> ImageToBitmap(const ColorFloatImage &image); static std::unique_ptr<Gdiplus::Bitmap> ImageToBitmap(const ColorByteImage &image); #endif };
RomanKazantsev/image-processing-filters
inc/median.h
<gh_stars>1-10 /* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <vector> #include <algorithm> #include "imageio.h" using namespace std; int ExtrapolateImage(ColorFloatImage const &image, ColorFloatImage &ext_image, int rad) { for (int j = 0; j < image.Height(); j++) { for (int i = 0; i < image.Width(); i++) { ext_image(i + rad, j + rad) = image(i, j); } } for (int j = 0; j < image.Height(); j++) { for (int i = 0; i < rad; i++) { ext_image(i, j + rad) = image(rad - i - 1, j); ext_image(image.Width() + rad + i, j + rad) = image(image.Width() - i - 1, j); } } for (int j = 0; j < rad; j++) { for (int i = 0; i < image.Width(); i++) { ext_image(i + rad, j) = image(i, rad - j - 1); ext_image(i + rad, image.Height() + rad + j) = image(i, image.Height() - j - 1); } } for (int j = 0; j < rad; j++) { for (int i = 0; i < rad; i++) { ext_image(i, j) = image(rad - i, rad - j); ext_image(i, ext_image.Height() - 1 - j) = image(rad - 1 - i, image.Height() - 1 - rad + j); // ? ext_image(ext_image.Width() - 1 - i, j) = image(image.Width() - 1 - rad + i, rad - 1 - j); // ? ext_image(image.Width() + rad + i, image.Height() + rad + j) = image(image.Width() - 1 - i, image.Height() - 1 - j); } } return 0; } int Median(char *inputfilename, char *outputfilename, int rad) { ColorFloatImage image = ImageIO::FileToColorFloatImage(inputfilename); ColorFloatImage res(image.Width(), image.Height()); // prepare extrapolated image ColorFloatImage tmp_image(image.Width() + 2 * rad, image.Height() + 2 * rad); ExtrapolateImage(image, tmp_image, rad); std::vector<float> window_r; std::vector<float> window_g; std::vector<float> window_b; window_r.reserve((2 * rad + 1) * (2 * rad + 1)); window_g.reserve((2 * rad + 1) * (2 * rad + 1)); window_b.reserve((2 * rad + 1) * (2 * rad + 1)); // process image with median filter for (int j = 0; j < res.Height(); j++) { for (int i = 0; i < res.Width(); i++) { window_b.clear(); window_g.clear(); window_r.clear(); for (int k1 = -rad; k1 <= rad; k1++) { for (int k2 = -rad; k2 <= rad; k2++) { window_b.push_back(tmp_image(i + k1 + rad, j + k2 + rad).b); window_g.push_back(tmp_image(i + k1 + rad, j + k2 + rad).g); window_r.push_back(tmp_image(i + k1 + rad, j + k2 + rad).r); } } std::sort(window_b.begin(), window_b.end()); std::sort(window_g.begin(), window_g.end()); std::sort(window_r.begin(), window_r.end()); res(i, j).b = window_b[2 * rad * (rad + 1)]; res(i, j).g = window_g[2 * rad * (rad + 1)]; res(i, j).r = window_r[2 * rad * (rad + 1)]; } } ImageIO::ImageToFile(res, outputfilename); return 0; }
RomanKazantsev/image-processing-filters
inc/imageformats.h
/* Copyright (c) 2011-2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <memory> #include <assert.h> #include "pixelformats.h" template<typename PixelType> class ImageBase { private: std::unique_ptr<PixelType[]> rawdata; int width, height; public: inline ImageBase(int Width, int Height) { assert(Width > 0 && Height > 0); this->width = Width; this->height = Height; this->rawdata.reset(new PixelType[Width * Height]); } // --- The code is needed for C++11 compatibility (for VS2013) --- ImageBase(const ImageBase&) = default; ImageBase(ImageBase&&) = default; ImageBase& operator = (const ImageBase&) = default; ImageBase& operator = (ImageBase&&) = default; // --- End of code region --- inline PixelType operator() (int x, int y) const { assert(x >= 0 && x < width && y >= 0 && y < height); return rawdata[y * width + x]; } inline PixelType& operator() (int x, int y) { assert(x >= 0 && x < width && y >= 0 && y < height); return rawdata[y * width + x]; } inline int Width() const { return width; } inline int Height() const { return height; } inline ImageBase<PixelType> Copy() const { ImageBase<PixelType> res(width, height); if (rawdata) memcpy(res.rawdata.get(), rawdata.get(), width * height * sizeof(PixelType)); return res; } }; typedef ImageBase<unsigned char> GrayscaleByteImage; typedef ImageBase<ColorBytePixel> ColorByteImage; typedef ImageBase<float> GrayscaleFloatImage; typedef ImageBase<ColorFloatPixel> ColorFloatImage;
RomanKazantsev/image-processing-filters
inc/ssim.h
/* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "imageio.h" int ComputeSsim(GrayscaleFloatImage const &input_image1, GrayscaleFloatImage const &input_image2, unsigned int block_x, unsigned block_y, unsigned int x, unsigned int y, float &ssim) { float L = 255.0f; float K1 = 0.01f; float K2 = 0.03f; float C1 = K1 * L * K1 * L; float C2 = K2 * L * K2 * L; float mean1 = 0.0f; float mean2 = 0.0f; unsigned int num_pixels = block_x * block_y; // compute means for both blocks for (unsigned int j = 0; j < block_y; j++) { for (unsigned int i = 0; i < block_x; i++) { mean1 += input_image1(x + i, y + j); mean2 += input_image2(x + i, y + j); } } mean1 = mean1 / num_pixels; mean2 = mean2 / num_pixels; // compute standard derivatiance for both block and covariance float var1 = 0.0f; float var2 = 0.0f; float covar = 0.0f; for (unsigned int j = 0; j < block_y; j++) { for (unsigned int i = 0; i < block_x; i++) { var1 += (input_image1(x + i, y + j) - mean1) * (input_image1(x + i, y + j) - mean1); var2 += (input_image2(x + i, y + j) - mean2) * (input_image2(x + i, y + j) - mean2); covar += (input_image1(x + i, y + j) - mean1) * (input_image2(x + i, y + j) - mean2); } } var1 = var1 / (num_pixels - 1); var2 = var2 / (num_pixels - 1); covar = covar / (num_pixels - 1); // compute ssim for given block ssim = (2 * mean1 * mean2 + C1) * (2 * covar + C2) / ((mean1 * mean1 + mean2 * mean2 + C1) * (var1 + var2 + C2)); return 0; } int ComputeMssim(GrayscaleFloatImage const &input_image1, GrayscaleFloatImage const &input_image2, float &mssim) { int block_x = 8; int block_y = 8; mssim = 0.0f; int widht = input_image1.Width(); int height = input_image1.Height(); int num_blocks_x = input_image1.Width() - block_x + 1; int num_blocks_y = input_image1.Height() - block_y + 1; for (int j = 0; j < num_blocks_y; j++) { for (int i = 0; i < num_blocks_x; i++) { float ssim = 0.0f; ComputeSsim(input_image1, input_image2, block_x, block_y, i, j, ssim); mssim += ssim; } } mssim = mssim / (num_blocks_x * num_blocks_y); return 0; }
RomanKazantsev/image-processing-filters
inc/gradient.h
<reponame>RomanKazantsev/image-processing-filters<gh_stars>1-10 /* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #define _USE_MATH_DEFINES #include <vector> #include <math.h> #include "imageio.h" using namespace std; static int ComputeGaussianDerivativeKernel(float sigma, int radius, std::vector<float> &kernelx, std::vector<float> &kernely) { int k = 2 * radius + 1; kernelx.clear(); kernelx.reserve(k * k); kernely.clear(); kernely.reserve(k * k); float coeff1 = 1 / (2.0f * sigma * sigma); float coeff2 = coeff1 / float(M_PI); for (int j = -radius; j <= radius; j++) { for (int i = -radius; i <= radius; i++) { float value = coeff2 * exp(-(i * i + j * j) * coeff1); kernelx.push_back(value * (-i / (sigma * sigma))); kernely.push_back(value * (-j / (sigma * sigma))); } } return 0; } int Gradient(char *inputfilename, char *outputfilename, float sigma) { ColorFloatImage input_image = ImageIO::FileToColorFloatImage(inputfilename); GrayscaleFloatImage output_image(input_image.Width(), input_image.Height()); int radius = int(3 * sigma) > 0 ? int(3 * sigma) : 1; std::vector<float> kernelx, kernely; ComputeGaussianDerivativeKernel(sigma, radius, kernelx, kernely); // prepare extrapolated image ColorFloatImage tmp_image(input_image.Width() + 2 * radius, input_image.Height() + 2 * radius); ExtrapolateImage(input_image, tmp_image, radius); // process image with gaussian filter for (int j = 0; j < output_image.Height(); j++) { for (int i = 0; i < output_image.Width(); i++) { float sumx = 0, sumy = 0; for (int k = 0; k < kernelx.size(); k++) { int ii = k % (2 * radius + 1); int jj = k / (2 * radius + 1); float p = ToGray(tmp_image(i + ii, j + jj)); sumx += kernelx[k] * p; sumy += kernely[k] * p; } output_image(i, j) = sqrt(sumx * sumx + sumy * sumy); } } ImageIO::ImageToFile(output_image, outputfilename); return 0; } int Gradient(ColorFloatImage const &input_image, GrayscaleFloatImage &output_image, float &max_grad, std::vector<float> &angles, float sigma) { max_grad = -1.0f; int radius = int(3 * sigma) > 0 ? int(3 * sigma) : 1; std::vector<float> kernelx, kernely; ComputeGaussianDerivativeKernel(sigma, radius, kernelx, kernely); // prepare extrapolated image ColorFloatImage tmp_image(input_image.Width() + 2 * radius, input_image.Height() + 2 * radius); ExtrapolateImage(input_image, tmp_image, radius); // process image with gaussian filter for (int j = 0; j < output_image.Height(); j++) { for (int i = 0; i < output_image.Width(); i++) { float sumx = 0.0f, sumy = 0.0f; for (int k = 0; k < kernelx.size(); k++) { int ii = k % (2 * radius + 1); int jj = k / (2 * radius + 1); float p = ToGray(tmp_image(i + ii, j + jj)); sumx += kernelx[k] * p; sumy += kernely[k] * p; } float G1 = sumx; float G2 = sumy; float G = std::sqrtf(G1 * G1 + G2 * G2); if (G > max_grad) max_grad = G; output_image(i, j) = G; float division = G2 / G1; float angle = std::atanf(G2 / G1); // in radians in a range [-pi/2l pi/2] if (angle < 0) angle = float(M_PI) + angle; // in radians in a range [0; pi] angles.push_back(angle); } } return 0; }
RomanKazantsev/image-processing-filters
inc/gauss.h
/* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #define _USE_MATH_DEFINES #include <math.h> #include <vector> #include "imageio.h" using namespace std; static int ComputeGaussianKernel(float sigma, int radius, std::vector<float> &kernel) { int k = 2 * radius + 1; kernel.clear(); kernel.reserve(k * k); float coeff1 = 1 / (2.0f * sigma * sigma); float coeff2 = coeff1 / float(M_PI); for (int i = -radius; i <= radius; i++) { for (int j = -radius; j <= radius; j++) { float value = coeff2 * exp(-(i * i + j * j) * coeff1); kernel.push_back(value); } } return 0; } static int ApplyGammaCorrection(ColorFloatImage const &intput, ColorFloatImage &output, float gamma) { float max = 255.0f; for (int j = 0; j < output.Height(); j++) { for (int i = 0; i < output.Width(); i++) { output(i, j).b = pow(intput(i, j).b / max, gamma) * max; output(i, j).g = pow(intput(i, j).g / max, gamma) * max; output(i, j).r = pow(intput(i, j).r / max, gamma) * max; } } return 0; } int GaussGamma(ColorFloatImage const &image, ColorFloatImage &res, float sigma, float gamma) { int radius = int(3 * sigma) > 0 ? int(3 * sigma) : 1; std::vector<float> kernel; ComputeGaussianKernel(sigma, radius, kernel); float max = 255; // apply gamma correction before process with gaussian ApplyGammaCorrection(image, res, gamma); // prepare extrapolated image ColorFloatImage tmp_image(image.Width() + 2 * radius, image.Height() + 2 * radius); ExtrapolateImage(res, tmp_image, radius); // process image with gaussian filter for (int j = 0; j < res.Height(); j++) { for (int i = 0; i < res.Width(); i++) { float sum_b = 0; float sum_g = 0; float sum_r = 0; for (int k = 0; k < kernel.size(); k++) { int ii = k % (2 * radius + 1); int jj = k / (2 * radius + 1); sum_b += kernel[k] * tmp_image(i + ii, j + jj).b; sum_g += kernel[k] * tmp_image(i + ii, j + jj).g; sum_r += kernel[k] * tmp_image(i + ii, j + jj).r; } res(i, j).b = sum_b; res(i, j).g = sum_g; res(i, j).r = sum_r; } } ApplyGammaCorrection(res, res, 1 / gamma); return 0; }
RomanKazantsev/image-processing-filters
inc/bilateral.h
/* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #define _USE_MATH_DEFINES #include <vector> #include <math.h> #include "imageio.h" static int ComputeKernelRadius(float sigma_d, float sigma_r) { int rad = int(std::max<float>(std::ceil(sigma_d), std::ceil(3 * sigma_r))); return rad; } static int CreateGaussianKernel(float sigma_d, int rad, std::vector<float> &kernel) { kernel.clear(); float coeff = 1.0f / (2.0f * sigma_d * sigma_d * float(M_PI)); for (int l = -rad; l <= rad; l++) { for (int k = -rad; k <= rad; k++) { float fd = std::expf(-(k * k + l * l) / (2 * sigma_d * sigma_d)) * coeff; kernel.push_back(fd); } } return 0; } static int CreateBilateralKernel(float sigma_d, float sigma_r, ColorFloatImage const &tmp_image, std::vector<float> const &gaussian_kernel, int i, int j, std::vector<float> &kernel) { int rad = ComputeKernelRadius(sigma_d, sigma_r); ColorFloatPixel p_base = tmp_image(i, j); float sum = 0.0f; float coeff = 1.0f / (2.0f * sigma_r * sigma_r * float(M_PI)); for (int l = -rad; l <= rad; l++) { for (int k = -rad; k <= rad; k++) { float fd = 0.0f; float fr = 0.0f; ColorFloatPixel p_curr = tmp_image(i + k, j + l); fd = gaussian_kernel[(l + rad) * (2 * rad + 1) + (k + rad)]; fr = std::expf(-((p_curr.r - p_base.r) * (p_curr.r - p_base.r) + (p_curr.g - p_base.g) * (p_curr.g - p_base.g) + (p_curr.b - p_base.b) * (p_curr.b - p_base.b)) / (2 * sigma_r * sigma_r)) * coeff; kernel.push_back(fd * fr); sum += (fd * fr); } } // normalize coefficients of the kernel for (int k = 0; k < kernel.size(); k++) { kernel[k] /= sum; } return 0; } int ApplyBilateralFilter(ColorFloatImage const &input_image, ColorFloatImage &output_image, float sigma_d, float sigma_r) { int rad = ComputeKernelRadius(sigma_d, sigma_r); // Compute gaussian kernel std::vector<float> gaussian_kernel; CreateGaussianKernel(sigma_d, rad, gaussian_kernel); // prepare extrapolated image ColorFloatImage tmp_image(input_image.Width() + 2 * rad, input_image.Height() + 2 * rad); ExtrapolateImage(input_image, tmp_image, rad); // process image with bilateral filter for (int j = 0; j < output_image.Height(); j++) { for (int i = 0; i < output_image.Width(); i++) { // compute gabor kernel std::vector<float> kernel; kernel.clear(); CreateBilateralKernel(sigma_d, sigma_r, tmp_image, gaussian_kernel, i + rad, j + rad, kernel); float sum_r = 0.0f; float sum_g = 0.0f; float sum_b = 0.0f; for (int k = 0; k < kernel.size(); k++) { int jj = k / (2 * rad + 1); int ii = k % (2 * rad + 1); sum_r += kernel[k] * tmp_image(i + ii, j + jj).r; sum_g += kernel[k] * tmp_image(i + ii, j + jj).g; sum_b += kernel[k] * tmp_image(i + ii, j + jj).b; } output_image(i, j).r = sum_r; output_image(i, j).g = sum_g; output_image(i, j).b = sum_b; } } return 0; }
RomanKazantsev/image-processing-filters
inc/canny.h
<reponame>RomanKazantsev/image-processing-filters /* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #define _USE_MATH_DEFINES #include <queue> #include <utility> #include "imageio.h" #include "gradient.h" int RunCannyEdgeDetector(ColorFloatImage const &input_image, GrayscaleFloatImage &output_image, float sigma, float thr_high, float thr_low) { int width = output_image.Width(); int height = output_image.Height(); GrayscaleFloatImage G(input_image.Width(), input_image.Height()); //GrayscaleFloatImage &G = output_image; std::vector<float> angles; float max_grad = 0.0f; // apply derivation of gaussian filter Gradient(input_image, G, max_grad, angles, sigma); //return 0; float upper_grad = thr_high * max_grad; float bottom_grad = thr_low * max_grad; // apply non-maximum suppression to get rid of spurious response to edge detection for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { output_image(i, j) = 0.0f; float angle = angles[j * width + i]; float curr_G = G(i, j); float prev_G = -1.0f; float next_G = -1.0f; if (angle == 0.0f) { if (i < (width - 1)) next_G = G(i + 1, j); if (i > 0) prev_G = G(i - 1, j); } else if (angle == float(M_PI) / 2.0f) { if (j < (height - 1)) next_G = G(i, j + 1); if (j > 0) prev_G = G(i, j - 1); } else if (angle > 0.0f && angle <= float(M_PI) / 4.0f) { float l = std::tanf(angle); if (i < (width - 1) && j < (height - 1)) next_G = (1.0f - l) * G(i + 1, j) + l * G(i + 1, j + 1); if (i > 0 && j > 0) prev_G = (1.0f - l) * G(i - 1, j) + l * G(i - 1, j - 1); } else if (angle > float(M_PI) / 4.0f && angle < float(M_PI) / 2.0f) { angle = float(M_PI) / 2.0f - angle; float l = std::tanf(angle); if (i < (width - 1) && j < (height - 1)) next_G = (1.0f - l) * G(i, j + 1) + l * G(i + 1, j + 1); if (i > 0 && j > 0) prev_G = (1.0f - l) * G(i, j - 1) + l * G(i - 1, j - 1); } else if (angle > float(M_PI) / 2.0f && angle <= 3.0f * float(M_PI) / 4.0f) { angle = angle - float(M_PI) / 2.0f; float l = std::tanf(angle); if (i > 0 && j < (height - 1)) next_G = (1.0f - l) * G(i, j + 1) + l * G(i - 1, j + 1); if (i < (width - 1) && j > 0) prev_G = (1.0f - l) * G(i, j - 1) + l * G(i + 1, j - 1); } else if (angle > 3.0f * float(M_PI) / 4.0f && angle <= float(M_PI)) { angle = float(M_PI) - angle; float l = std::tanf(angle); if (i > 0 && j < (height - 1)) next_G = (1.0f - l) * G(i - 1, j) + l * G(i - 1, j + 1); if (i < (width - 1) && j > 0) prev_G = (1.0f - l) * G(i + 1, j) + l * G(i + 1, j - 1); } // mark strong edges if (curr_G > prev_G && curr_G > next_G && curr_G > upper_grad) output_image(i, j) = 254.0f; // mark weak edges if (curr_G > prev_G && curr_G > next_G && curr_G > bottom_grad && curr_G <= upper_grad) output_image(i, j) = 1.0f; } } // walkthrough with threshold hysteresis for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { // find next strong edge if (output_image(i, j) == 254.0f) { std::queue<std::pair<int, int>> edge_queue; edge_queue.push(std::pair<int, int>(i, j)); while (!edge_queue.empty()) { std::pair<int, int> curr_edge = edge_queue.front(); edge_queue.pop(); int xx = curr_edge.first; int yy = curr_edge.second; // skip pixel if it has already been visited or non-edge with below low threshold gradient magnitude if (output_image(xx, yy) == 0.0f || output_image(xx, yy) == 255.0f) continue; // mark edge pixels as visited if (output_image(xx, yy) == 1.0f || output_image(xx, yy) == 254.0f) output_image(xx, yy) = 255.0f; // add new edges to check if (xx > 0) { edge_queue.push(std::pair<int, int>(xx - 1, yy)); if (yy > 0) edge_queue.push(std::pair<int, int>(xx - 1, yy - 1)); if (yy < (height - 1)) edge_queue.push(std::pair<int, int>(xx - 1, yy + 1)); } if (xx < (width - 1)) { edge_queue.push(std::pair<int, int>(xx + 1, yy)); if (yy > 0) edge_queue.push(std::pair<int, int>(xx + 1, yy - 1)); if (yy < (height - 1)) edge_queue.push(std::pair<int, int>(xx + 1, yy + 1)); } if (yy > 0) edge_queue.push(std::pair<int, int>(xx, yy - 1)); if (yy < (height - 1)) edge_queue.push(std::pair<int, int>(xx, yy + 1)); } } } } // remove all weak egdes not visited from strong edges for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { if (output_image(i, j) == 1.0f) output_image(i, j) = 0.0f; } } return 0; }
RomanKazantsev/image-processing-filters
inc/mse_psnr.h
/* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "imageio.h" int ComputeMse(GrayscaleFloatImage const &input_image1, GrayscaleFloatImage const &input_image2, float &mse) { int width = input_image1.Width(); int height = input_image1.Height(); int num_pixels = width * height; mse = 0.0f; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { mse += (input_image1(i, j) - input_image2(i, j)) * (input_image1(i, j) - input_image2(i, j)) / num_pixels; } } return 0; } int ComputePsnr(GrayscaleFloatImage const &input_image1, GrayscaleFloatImage const &input_image2, float &psnr) { psnr = 0.0f; float mse = 0.0f; float s = 255.0f; ComputeMse(input_image1, input_image2, mse); psnr = 10 * std::log10f(s * s / mse); return 0; }