A simple RTOS for microcontrollers based upon concepts of FreeRTOS

This file is part of SimpleRTOS2

by Isaac Marino Bavaresco

This is file "SimpleRTOS\PortPIC32-C.c"

/*============================================================================*/
/*
SimpleRTOS - Very simple RTOS for Microcontrollers - PIC32 port
v2.00 (2014-01-21)
isaacbavaresco@yahoo.com.br
*/
/*============================================================================*/
/*
 Copyright (c) 2007-2014, Isaac Marino Bavaresco
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
     * Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
     * Neither the name of the author nor the
       names of its contributors may be used to endorse or promote products
       derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*============================================================================*/
#if         defined __XC32__  || defined __C32_VERSION__
/*============================================================================*/
#include "PortPIC32.h"
#include "SimpleRTOSInternals.h"
/*============================================================================*/
extern void __attribute__((weak)) TickHook( void );
/*============================================================================*/
void __attribute__(( vector( _TIMER_1_VECTOR ), interrupt( IPL1SOFT ), nomips16 ))T1Interrupt(void);
/*============================================================================*/
void Switch( void )
    {
    /*INTClearFlag( INT_T1 );*/     /* clear the interrupt flag */
    IFS0bits.T1IF   = 0;

    SystemTick++;

    CheckDelayList();

    /* The current task ran for at least one full time slice... */
    if( AlreadySwitched == 0 && CurrentTask->Priority == HighestReadyPriority )
        /* ... it doesn't deserve an additional time slice. */
        ReadyTasks[HighestReadyPriority]
            = ReadyTasks[HighestReadyPriority]->Next;

    CurrentTask         = ReadyTasks[HighestReadyPriority];

    /*
    The upcoming task will run from the very beginning of its time slice,
    at the end of this slice it will be switched off.
    */
    AlreadySwitched     = 0;

    if( TickHook != NULL )
        TickHook();
    }
/*============================================================================*/

#if         defined __PIC32MZ__ && __PIC32_FEATURE_SET1 == 'F'
context_t   *FPUOwner   = NULL;
#endif  /*  defined __PIC32MZ__ && __PIC32_FEATURE_SET1 == 'F' */

/*============================================================================*/
void ContextInit( context_t *Context, unsigned char *Stack, unsigned long StackSize, void *Parameter, void (*TaskFunc)( void* ), unsigned int Priority, void *FPUContext )
    {
    memset( Context, 0x00, sizeof( context_t ));

    Context->r4         = (unsigned long)Parameter;
    /*Context->r28      = $gp;*/
    asm volatile( "sw   $gp,%0" :: "m"( Context->r28 ));
    Context->r29        = (unsigned long)Stack + StackSize - sizeof( unsigned long );
    Context->r30        = (unsigned long)Stack + StackSize - sizeof( unsigned long );
    Context->r31        = (unsigned long)TaskFinish;
    Context->CP0_EPC    = (unsigned long)TaskFunc;

#if         defined __PIC32MZ__ && __PIC32_FEATURE_SET1 == 'F'
    Context->FPUContext = FPUContext;
#endif  /*  defined __PIC32MZ__ && __PIC32_FEATURE_SET1 == 'F' */

#if         defined __PIC32MZ__
    #if         __PIC32_FEATURE_SET1 == 'F'
    Context->CP0_STATUS = 0x05000003;
    #else   /*  __PIC32_FEATURE_SET1 == 'F' */
    Context->CP0_STATUS = 0x01000003;
    #endif  /*  __PIC32_FEATURE_SET1 == 'F' */
#elif       defined __PIC32MX__
    Context->CP0_STATUS = 0x00000003;
#endif  /*  defined __PIC32MZ__ */
    Context->CP0_CAUSE  = _CP0_GET_CAUSE();

    Context->Priority               = Priority;
    Context->TDelay                 = 0;
    Context->PreviousDelayedTask    = 0;
    Context->NextDelayedTask        = 0;
    Context->DelayList              = 0;

#ifdef      USE_SLICE_LENGTH
    Context->SliceLength            = 0;
#endif  /*  USE_SLICE_LENGTH */

    Context->Previous               = 0;
    Context->Next                   = 0;
    Context->List                   = 0;
    }
/*============================================================================*/
void InitRTOS( context_t *ctxts, unsigned int Number )
    {
    unsigned int i;

    /* No contexts to be initialized... The RTOS is useless.*/
    if( ctxts == NULL || Number == 0 )
        {
        FreeContexts    = NULL;
        return;
        }

    CurrentTask     = ctxts;

    for( i = 0; i < MaxPriorities; i++ )
        ReadyTasks[i]   = NULL;

    /*------------------------------------------------------------------------*/
    /* Initialize all contexts and link them to the free contexts list.*/
    FreeContexts    = ctxts;
    for( i = 0; i < Number - 1; i++, ctxts++ )
        {
        ctxts->Next = ctxts + 1;
        ctxts->List = &FreeContexts;
        }
    ctxts->Next     = NULL;
    ctxts->List     = &FreeContexts;

    /*------------------------------------------------------------------------*/
    }
/*============================================================================*/
void __attribute__((nomips16,noreturn)) StartRTOS( tickcount_t TickPeriod )
    {
    int PS;

    if( TickPeriod <= 65536 )
        {
        PS           = 0;
        }
    else if( TickPeriod <= 65536 * 8 )
        {
        TickPeriod >>= 3;
        PS           = 1;
        }
    else if( TickPeriod <= 65536 * 64 )
        {
        TickPeriod >>= 6;
        PS           = 2;
        }
    else
        {
        TickPeriod >>= 8;
        PS           = 3;
        }

    /* set up the core timer interrupt with a prioirty of 2 and zero sub-priority */
    /*INTSetVectorPriority( INT_TIMER_1_VECTOR, configKERNEL_INTERRUPT_PRIORITY );*/
    IPC1bits.T1IP   = KERNEL_INTERRUPT_PRIORITY;
    /*INTSetVectorSubPriority( INT_TIMER_1_VECTOR, INT_SUB_PRIORITY_LEVEL_0 );*/
    IPC1bits.T1IS   = 0;
    /*INTClearFlag( INT_T1 );*/
    IFS0bits.T1IF   = 0;
    /*INTEnable( INT_T1, INT_ENABLED );*/
    IEC0bits.T1IE   = 1;

    /* configure for multi-vectored mode*/
    /*INTConfigureSystem( INT_SYSTEM_CONFIG_MULT_VECTOR );*/
    INTCONbits.MVEC = 1;

    SystemTick  = 0;
    CurrentTask = ReadyTasks[HighestReadyPriority];

    /*OpenTimer1( T1_ON | PS, TickPeriod );*/   /* load with the period */
    PR1             = TickPeriod;
    TMR1            = 0;
    T1CONbits.TCKPS = PS;
    T1CONbits.TON   = 1;

    /* enable interrupts*/
    /*INTEnableInterrupts();*/
    _CP0_BIC_STATUS( 0x07 << 10 );
#if         defined __PIC32MZ__
    _CP0_BIS_STATUS( 0x01 << 24 );
#endif  /*  defined __PIC32MZ__ */

    asm volatile(
        ".extern    RestoreContext  \n"
        ".set       noreorder       \n"
        ".set       noat            \n"

        "addiu      $sp,$sp,-8      \n"
        "sw         $ra,4($sp)      \n"

        "j          RestoreContext  \n"
        "nop                        \n"
        );

    while( 1 )
        {}
    }
/*============================================================================*/
#endif  /*  defined __XC32__  || defined __C32_VERSION__ */
/*============================================================================*/

/*============================================================================*/
#if     defined __PIC32MZ__ && __PIC32_FEATURE_SET1 == 'F'
/*============================================================================*/

void    SaveFP      ( unsigned long * );
void    RestoreFP   ( unsigned long * );

/*============================================================================*/
void    RestoreContext( void );
/*============================================================================*/

void _general_exception_handler ( void )
    {
    unsigned int    _excep_code;
    /* Mask off Mask of the ExcCode Field from the Cause Register
    Refer to the MIPs Software User's manual */

    _excep_code = ( _CP0_GET_CAUSE() & 0x0000007C ) >> 2;

    if( _excep_code != 11 )
        {
        asm volatile( "nop" );
        while( 1 )
            __asm__ volatile (" sdbbp 0");
        }

    /* The current task is trying to do FP operation but it doesn't have an
     area to save the FPU context...
    */
    if( CurrentTask->FPUContext == NULL )
        {
        /* ... we are going to kill it. */
        RemoveTaskFromAllLists( CurrentTask );

        /* Link the task's context to the free contexts list*/
        CurrentTask->Next   = FreeContexts;
        FreeContexts        = CurrentTask;
        /* Mark the context as belonging to the free contexts list.*/
        CurrentTask->List   = &FreeContexts;

        CurrentTask         = ReadyTasks[HighestReadyPriority];
        RestoreContext();
        }

    _CP0_SET_STATUS( _CP0_GET_STATUS() | 0x20000000 );

    if( FPUOwner != CurrentTask )
        {
        if( FPUOwner != NULL )
            {
            SaveFP( FPUOwner->FPUContext );
            FPUOwner    = NULL;
            }

        RestoreFP( CurrentTask->FPUContext );
        FPUOwner        = CurrentTask;
        }
    }

/*============================================================================*/
#endif  /*  defined __PIC32MZ__ && __PIC32_FEATURE_SET1 == 'F' */
/*============================================================================*/