~aleteoryx/muditaos

ref: 2a53becd2524fc0dba7260632d3ec409eb3a61fd muditaos/module-os/board/linux/port.c -rw-r--r-- 24.7 KiB
2a53becd — Maciej Janicki [BH-1136] Fix bootloop after low power 4 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
/*
 *  Copyright (C) 2017 Michael Becker (michael.f.becker@gmail.com
 *  Modified from code from William Davy (william.davy@wittenstein.co.uk)
 *
 *  Modifications (not exhaustive):
 *  ---------------------------------------------
 *  + Updated to work with FreeRTOS v8.2.3
 *
 *  + Updated code that works with pthreads to 
 *    treat pthread_t data as opaque data structures,
 *    as specified in the POSIX standard. Likewise, 
 *    cannot initialize them to NULL, not portable.
 *
 *  + Since FreeRTOS is not multicore, we are forcing 
 *    all of the pthreads that simulate FreeRTOS tasks 
 *    to execute on a single core.
 *
 */
/*
    Copyright (C) 2009 William Davy - william.davy@wittenstein.co.uk
    Contributed to FreeRTOS.org V5.3.0.

    This file is part of the FreeRTOS.org distribution.

    FreeRTOS.org is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License (version 2) as published
    by the Free Software Foundation and modified by the FreeRTOS exception.

    FreeRTOS.org 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 FreeRTOS.org; if not, write to the Free Software Foundation, Inc., 59
    Temple Place, Suite 330, Boston, MA  02111-1307  USA.

    A special exception to the GPL is included to allow you to distribute a
    combined work that includes FreeRTOS.org without being obliged to provide
    the source code for any proprietary components.  See the licensing section
    of http://www.FreeRTOS.org for full details.


    ***************************************************************************
    *                                                                         *
    * Get the FreeRTOS eBook!  See http://www.FreeRTOS.org/Documentation      *
    *                                                                         *
    * This is a concise, step by step, 'hands on' guide that describes both   *
    * general multitasking concepts and FreeRTOS specifics. It presents and   *
    * explains numerous examples that are written using the FreeRTOS API.     *
    * Full source code for all the examples is provided in an accompanying    *
    * .zip file.                                                              *
    *                                                                         *
    ***************************************************************************

    1 tab == 4 spaces!

    Please ensure to read the configuration and relevant port sections of the
    online documentation.

    http://www.FreeRTOS.org - Documentation, latest information, license and
    contact details.

    http://www.SafeRTOS.com - A version that is certified for use in safety
    critical systems.

    http://www.OpenRTOS.com - Commercial support, development, porting,
    licensing and training services.
*/

/*-----------------------------------------------------------
 * Implementation of functions defined in portable.h for the Posix port.
 *----------------------------------------------------------*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <time.h>
#include <sys/times.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <assert.h>
#include <string.h>

/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "portmacro.h"
#include "macros.h"

/* Each task maintains its own interrupt status in the critical nesting variable. */
typedef struct ThreadState_t_
{
    pthread_t       Thread;
    int             Valid;    /* Treated as a boolean */
    xTaskHandle     hTask;
    portBASE_TYPE   uxCriticalNesting;
    pdTASK_CODE     pxCode;
    void            *pvParams;
    int             index;

} ThreadState_t;


#define MAX_NUMBER_OF_TASKS ( _POSIX_THREAD_THREADS_MAX )
static ThreadState_t pxThreads[MAX_NUMBER_OF_TASKS];

static pthread_once_t hSigSetupThread = PTHREAD_ONCE_INIT;

static pthread_mutex_t xSuspendResumeThreadMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t xSingleThreadMutex = PTHREAD_MUTEX_INITIALIZER;

static pthread_t hMainThread;
static pthread_t hEndSchedulerCallerThread;
int hEndSchedulerCallerThreadIndex;

static volatile portBASE_TYPE xSentinel = 0;
static volatile portBASE_TYPE xSchedulerEnd = pdFALSE;
static volatile portBASE_TYPE xInterruptsEnabled = pdTRUE;
static volatile portBASE_TYPE xServicingTick = pdFALSE;
static volatile portBASE_TYPE xPendYield = pdFALSE;
static volatile portLONG lIndexOfLastAddedTaskStack[_POSIX_THREAD_THREADS_MAX];
static volatile portLONG lLastAddedTaskStackIdx = 0;
static volatile portBASE_TYPE uxCriticalNesting;


/**
 *  pthread cleanup routine, always executed on pthread exit.
 */
static void DeleteThreadCleanupRoutine( void *Parameter )
{
    ThreadState_t *State = (ThreadState_t *)Parameter;

#if LINUX_PORT_DEBUG
    printf("[%d] DeleteThreadCleanupRoutine for index\n", State->index);
#endif

    State->Valid = 0;
    State->hTask = (xTaskHandle)NULL;
    if ( State->uxCriticalNesting > 0 )
    {
        State->uxCriticalNesting = 0;
        uxCriticalNesting = 0;
        vPortEnableInterrupts();
    }
}


/**
 *  Sends SIG_SUSPEND to target thread.
 */
static void SuspendThread( pthread_t Thread )
{
    pthread_mutex_lock( &xSuspendResumeThreadMutex );

    /* Set-up for the Suspend Signal handler? */
    xSentinel = 0;
    pthread_mutex_unlock( &xSuspendResumeThreadMutex );

    pthread_kill( Thread, SIG_SUSPEND );
    while ( ( xSentinel == 0 ) && ( pdTRUE != xServicingTick ) )
    {
        sched_yield();
    }
}

/**
 *  Signal handler for SIG_SUSPEND
 */
static void SuspendSignalHandler(int sig)
{
    sigset_t xSignals;
    int rc;

    /* Only interested in the resume signal. */
    sigemptyset( &xSignals );
    sigaddset( &xSignals, SIG_RESUME );
    xSentinel = 1;

    /* Unlock the Single thread mutex to allow the resumed task to continue. */
    rc = pthread_mutex_unlock(&xSingleThreadMutex);
    assert(rc == 0);

    /* Wait on the resume signal. */
    rc = sigwait(&xSignals, &sig);
    assert(rc == 0);
    
    /* Will resume here when the SIG_RESUME signal is received. */
    /* Need to set the interrupts based on the task's critical nesting. */
    if ( uxCriticalNesting == 0 )
    {
        vPortEnableInterrupts();
    }
    else
    {
        vPortDisableInterrupts();
    }
}


/**
 *  Signal handler for SIG_RESUME.
 */
static void ResumeSignalHandler(int sig)
{
    (void)sig;

    /* Yield the Scheduler to ensure that the yielding thread completes. */
    if (pthread_mutex_lock(&xSingleThreadMutex) == 0) {
        pthread_mutex_unlock(&xSingleThreadMutex);
    }
}


/**
 *  Sends SIG_RESUME to target thread.
 */
static void ResumeThread( pthread_t Thread )
{
    int rc;

    rc = pthread_mutex_lock(&xSuspendResumeThreadMutex);
    assert(rc == 0);
    
    if ( !pthread_equal(pthread_self(), Thread))
    {
        pthread_kill( Thread, SIG_RESUME );
    }

    pthread_mutex_unlock( &xSuspendResumeThreadMutex );
}


/**
 *  Utility function to lookup a pthread_t based on 
 *  a FreeRTOS Task Handle.
 */
static int LookupThread(xTaskHandle hTask, pthread_t *Thread)
{
    int i;
    
    for (i = 0; i < MAX_NUMBER_OF_TASKS; i++)
    {
        if (pxThreads[i].hTask == hTask)
        {
            *Thread = pxThreads[i].Thread;
            return 1;
        }
    }

    return 0;
}


static void prvSetTaskCriticalNesting( pthread_t Thread, portBASE_TYPE uxNesting )
{
    int i;

    for (i = 0; i < MAX_NUMBER_OF_TASKS; i++)
    {
        if ( pthread_equal(pxThreads[i].Thread, Thread) )
        {
            pxThreads[i].uxCriticalNesting = uxNesting;
            return;
        }
    }

    assert(!"Failed finding pthread for task mapping!");
}


static portBASE_TYPE prvGetTaskCriticalNesting( pthread_t Thread )
{
    unsigned portBASE_TYPE uxNesting = 0;
    int i;

    for (i = 0; i < MAX_NUMBER_OF_TASKS; i++)
    {
        if ( pthread_equal(pxThreads[i].Thread, Thread) )
        {
            uxNesting = pxThreads[i].uxCriticalNesting;
            return uxNesting;
        }
    }
    
    assert(!"Failed finding pthread for task mapping!");
    return 0;
}


/**
 *  Signal handler for SIG_TICK.
 */
static void TickSignalHandler( int sig )
{
    pthread_t ThreadToSuspend = 0;
    pthread_t ThreadToResume = 0;
    int success;

    (void)sig;

    if ((pdTRUE == xInterruptsEnabled) && (pdTRUE != xServicingTick))
    {
        if ( 0 == pthread_mutex_trylock( &xSingleThreadMutex ) )
        {
            xServicingTick = pdTRUE;

            /*
             *  Required call for newer FreeRTOS kernels
             */
            xTaskIncrementTick();

            success = LookupThread(xTaskGetCurrentTaskHandle(), &ThreadToSuspend);
            assert(success);

            /* Select Next Task. */
#if ( configUSE_PREEMPTION == 1 )
            vTaskSwitchContext();
#endif
            success = LookupThread(xTaskGetCurrentTaskHandle(), &ThreadToResume);
            if (success == 0) {
                LOG_FATAL("Emulator only bug." \
                          "Ignore and restart emulator or refer to commit linked with this log and fix it better :) ");
            }
            assert(success);

            /* The only thread that can process this tick is the running thread. */
            if ( !pthread_equal(ThreadToSuspend, ThreadToResume) )
            {
                /* Remember and switch the critical nesting. */
                prvSetTaskCriticalNesting( ThreadToSuspend, uxCriticalNesting );
                uxCriticalNesting = prvGetTaskCriticalNesting( ThreadToResume );
                /* Resume next task. */
                ResumeThread( ThreadToResume );
                /* Suspend the current task. */
                SuspendThread( ThreadToSuspend );
            }
            else
            {
                /* Release the lock as we are Resuming. */
                pthread_mutex_unlock( &xSingleThreadMutex );
            }
            xServicingTick = pdFALSE;
        }
        else
        {
            xPendYield = pdTRUE;
        }
    }
    else
    {
        xPendYield = pdTRUE;
    }
}


/**
 *  Only run once!
 */
static void prvSetupSignalsAndSchedulerPolicy( void )
{
    /* The following code would allow for configuring the scheduling of this task as a Real-time task.
     * The process would then need to be run with higher privileges for it to take affect.
    int iPolicy;
    int iResult;
    int iSchedulerPriority;
    iResult = pthread_getschedparam( pthread_self(), &iPolicy, &iSchedulerPriority );
    iResult = pthread_attr_setschedpolicy( &xThreadAttributes, SCHED_FIFO );
    iPolicy = SCHED_FIFO;
    iResult = pthread_setschedparam( pthread_self(), iPolicy, &iSchedulerPriority );        */

    int i;
    struct sigaction sigsuspendself, sigresume, sigtick;

    memset(pxThreads, 0, sizeof(pxThreads));

    for (i = 0; i < MAX_NUMBER_OF_TASKS; i++ )
    {
        pxThreads[i].index = i;
    }
    

    sigsuspendself.sa_flags = 0;
    sigsuspendself.sa_handler = SuspendSignalHandler;
    sigfillset( &sigsuspendself.sa_mask );

    sigresume.sa_flags = 0;
    sigresume.sa_handler = ResumeSignalHandler;
    sigfillset( &sigresume.sa_mask );

    sigtick.sa_flags = 0;
    sigtick.sa_handler = TickSignalHandler;
    sigfillset( &sigtick.sa_mask );

    if ( 0 != sigaction( SIG_SUSPEND, &sigsuspendself, NULL ) )
    {
        assert( !"Problem installing SIG_SUSPEND_SELF\n" );
    }
    if ( 0 != sigaction( SIG_RESUME, &sigresume, NULL ) )
    {
        assert( !"Problem installing SIG_RESUME\n" );
    }
    if ( 0 != sigaction( SIG_TICK, &sigtick, NULL ) )
    {
        assert( !"Problem installing SIG_TICK\n" );
    }

#if LINUX_PORT_DEBUG
    printf( "Running as PID: %d\n", getpid() );
#endif

    /*
     *  Also save the first thread as the main thread.
     */
    hMainThread = pthread_self();
}


/**
 *  Actual pthreads code, wrapper around FreeRTOS task.
 */
static void *ThreadStartWrapper( void * pvParams )
{
    ThreadState_t *State = (ThreadState_t *)pvParams;

    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    
    pthread_cleanup_push( DeleteThreadCleanupRoutine, State );

    pthread_mutex_lock(&xSingleThreadMutex); 
    SuspendThread( pthread_self() );

#if LINUX_PORT_DEBUG
    printf("[%d] Starting thread\n", State->index);
#endif

    State->pxCode( State->pvParams );

#if LINUX_PORT_DEBUG
    printf("[%d] Ending thread - SHOULD NEVER SEE THIS\n", State->index);
#endif

    /* make sure we execute DeleteThreadCleanupRoutine */
    pthread_cleanup_pop( 1 );

    return (void *)NULL;
}


/*
 * See header file for description.
 */
portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )
{
    int rc;
    int i;
    pthread_attr_t xThreadAttributes;
    cpu_set_t cpuset;
 
    pthread_once( &hSigSetupThread, prvSetupSignalsAndSchedulerPolicy );

    /* No need to join the threads. */
    pthread_attr_init( &xThreadAttributes );
    pthread_attr_setdetachstate( &xThreadAttributes, PTHREAD_CREATE_DETACHED );

    vPortEnterCritical();

    for (i = 0; i < MAX_NUMBER_OF_TASKS; i++ )
    {
        if (pxThreads[i].Valid == 0)
        {
            lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx] = i;
            break;
        }
    }
    /* No more free threads, please increase the maximum. */
    assert(i < MAX_NUMBER_OF_TASKS);


    /* Add the task parameters. */
    pxThreads[lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx]].pxCode = pxCode;
    pxThreads[lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx]].pvParams = pvParameters;

    /* Create the new pThread. */
    rc = pthread_mutex_lock(&xSingleThreadMutex);
    assert(rc == 0);

    xSentinel = 0;

    rc = pthread_create(&pxThreads[lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx]].Thread,
                        &xThreadAttributes, 
                        ThreadStartWrapper, 
                        (void *)&pxThreads[lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx]]
                        );
    assert(rc == 0);

    CPU_ZERO(&cpuset);
    CPU_SET(0, &cpuset);

    rc = pthread_setaffinity_np(pxThreads[lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx]].Thread,
                                sizeof(cpu_set_t), 
                                &cpuset);
	configASSERT( rc == 0 );
    pxThreads[lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx]].Valid = 1;

    lLastAddedTaskStackIdx++;

    /* Wait until the task suspends. */
    pthread_mutex_unlock( &xSingleThreadMutex );

    while ( xSentinel == 0 );
    vPortExitCritical();

    return pxTopOfStack;
}


/*
 * Setup the systick timer to generate the tick interrupts at the required
 * frequency.
 */
static void prvSetupTimerInterrupt( void )
{
    int rc;
    struct itimerval itimer, oitimer;
    suseconds_t MicroSeconds = (suseconds_t)(portTICK_RATE_MICROSECONDS % 1000000);
    time_t Seconds = portTICK_RATE_MICROSECONDS / 1000000;

    /* Initialise the structure with the current timer information. */
    rc = getitimer( TIMER_TYPE, &itimer);
    assert(rc == 0);

    /* Set the interval between timer events. */
    itimer.it_interval.tv_sec = Seconds;
    itimer.it_interval.tv_usec = MicroSeconds;

    /* Set the current count-down. */
    itimer.it_value.tv_sec = Seconds;
    itimer.it_value.tv_usec = MicroSeconds;

#if LINUX_PORT_DEBUG
    printf("Timer Setup:\n");
    printf("  Interval: %ld seconds, %ld useconds\n", 
            itimer.it_interval.tv_sec, itimer.it_interval.tv_usec);
    printf("  Current: %ld seconds, %ld useconds\n", 
            itimer.it_value.tv_sec, itimer.it_value.tv_usec);
#endif

    /* Set-up the timer interrupt. */
    rc = setitimer( TIMER_TYPE, &itimer, &oitimer );
    assert(rc == 0);
    
}


/*
 * See header file for description.
 */
portBASE_TYPE xPortStartScheduler( void )
{
    int iSignal;
    sigset_t xSignals;
    sigset_t xSignalToBlock;
    sigset_t xSignalsBlocked;
    pthread_t FirstThread = 0;
    int success;

#if LINUX_PORT_DEBUG
    printf("\n***** LINUX PORT CONFIGURED FOR DEBUG *****\n");
#endif    


    /* Establish the signals to block before they are needed. */
    sigfillset( &xSignalToBlock );

    /* Block until the end */
    pthread_sigmask( SIG_SETMASK, &xSignalToBlock, &xSignalsBlocked );

    /* Start the timer that generates the tick ISR.  Interrupts are disabled
    here already. */
    prvSetupTimerInterrupt();

    /* Start the first task. Will not return unless all threads are killed. */
    /* Initialise the critical nesting count ready for the first task. */
    uxCriticalNesting = 0;

    vPortEnableInterrupts();

    success = LookupThread( xTaskGetCurrentTaskHandle(), &FirstThread);
    assert(success);
    

    /* Start the first task. */
    ResumeThread(FirstThread);


    /* This is the end signal we are looking for. */
    sigemptyset( &xSignals );
    sigaddset( &xSignals, SIG_RESUME );

    while ( pdTRUE != xSchedulerEnd )
    {
        if ( 0 != sigwait( &xSignals, &iSignal ) )
        {
            printf( "Main thread spurious signal: %d\n", iSignal );
        }
    }

#if LINUX_PORT_DEBUG
    printf("Exiting scheduler.\n");
    printf("[%d] Canceling xTaskEndScheduler caller thread.\n", hEndSchedulerCallerThreadIndex);
#endif

    pthread_cancel(hEndSchedulerCallerThread);
    sleep(1);

    /* Cleanup the mutexes */
#if LINUX_PORT_DEBUG
    printf( "Freeing OS mutexes.\n" );
#endif

    pthread_mutex_destroy( &xSuspendResumeThreadMutex );
    pthread_mutex_destroy( &xSingleThreadMutex );

    sleep(1);

    memset(&xSuspendResumeThreadMutex,0,sizeof(xSuspendResumeThreadMutex));
    memset(&xSingleThreadMutex,0,sizeof(xSingleThreadMutex));

    hSigSetupThread = PTHREAD_ONCE_INIT;

    hMainThread =0;
    hEndSchedulerCallerThread=0;
    hEndSchedulerCallerThreadIndex=0;

    xSentinel = 0;
    xSchedulerEnd = pdFALSE;
    xInterruptsEnabled = pdTRUE;
    xServicingTick = pdFALSE;
    xPendYield = pdFALSE;
    lLastAddedTaskStackIdx = 0;
    uxCriticalNesting = 0;

    signal(SIG_SUSPEND, SIG_DFL);
    signal(SIG_RESUME, SIG_DFL);
    signal(SIG_TICK, SIG_DFL);

    /* Should not get here! */
    return 0;
}


void vPortEndScheduler( void )
{
    int i;
    int rc;
    struct sigaction sigtickdeinit;

    xInterruptsEnabled = pdFALSE;

    /* Signal the scheduler to exit its loop. */
    xSchedulerEnd = pdTRUE;

    /* Ignore next or pending SIG_TICK, it mustn't execute anymore. */
    sigtickdeinit.sa_flags = 0;
    sigtickdeinit.sa_handler = SIG_IGN;
    sigfillset(&sigtickdeinit.sa_mask);

    rc = sigaction(SIG_TICK, &sigtickdeinit, NULL);
    assert(rc == 0);

    rc = sigaction(SIG_RESUME, &sigtickdeinit, NULL);
    assert(rc == 0);

    rc = sigaction(SIG_SUSPEND, &sigtickdeinit, NULL);
    assert(rc == 0);
    

    for (i = 0; i < MAX_NUMBER_OF_TASKS; i++)
    {
        if ( pxThreads[i].Valid )
        {
            //pxThreads[i].Valid = 0;
                
            /* Don't kill yourself */
            if (pthread_equal(pxThreads[i].Thread, pthread_self())) 
            {
#if LINUX_PORT_DEBUG
                printf("[%d] Delaying canceling pthread\n", i);
#endif                
                hEndSchedulerCallerThread = pxThreads[i].Thread;
                hEndSchedulerCallerThreadIndex = pxThreads[i].index;
                continue;
            }
            else
            {
                /* Kill all of the threads, they are in the detached state. */
#if LINUX_PORT_DEBUG
                printf("[%d] canceling pthread\n", i);
#endif                
                pthread_cancel(pxThreads[i].Thread );
                sleep(1);
            }
        }
    }

    pthread_kill( hMainThread, SIG_RESUME );
}


void vPortYieldFromISR( void )
{
    /* Calling Yield from a Interrupt/Signal handler often doesn't work because the
     * xSingleThreadMutex is already owned by an original call to Yield. Therefore,
     * simply indicate that a yield is required soon.
     */
    xPendYield = pdTRUE;
}


void vPortEnterCritical( void )
{
    vPortDisableInterrupts();
    uxCriticalNesting++;
}


void vPortExitCritical( void )
{
    /* Check for unmatched exits. */
    if ( uxCriticalNesting > 0 )
    {
        uxCriticalNesting--;
    }

    /* If we have reached 0 then re-enable the interrupts. */
    if( uxCriticalNesting == 0 )
    {
        /* Have we missed ticks? This is the equivalent of pending an interrupt. */
        if ( pdTRUE == xPendYield )
        {
            xPendYield = pdFALSE;
            vPortYield();
        }
        vPortEnableInterrupts();
    }
}


void vPortYield( void )
{
    int rc;
    pthread_t ThreadToSuspend = 0;
    pthread_t ThreadToResume = 0;
    int success;

    rc = pthread_mutex_lock(&xSingleThreadMutex);
    assert(rc == 0);
   

    success = LookupThread(xTaskGetCurrentTaskHandle(), &ThreadToSuspend);
    assert(success);

    vTaskSwitchContext();

    success = LookupThread(xTaskGetCurrentTaskHandle(), &ThreadToResume);
    assert(success);
    

    if ( !pthread_equal(ThreadToSuspend, ThreadToResume) )
    {
        /* Remember and switch the critical nesting. */
        prvSetTaskCriticalNesting( ThreadToSuspend, uxCriticalNesting );
        uxCriticalNesting = prvGetTaskCriticalNesting( ThreadToResume );
        /* Switch tasks. */
        ResumeThread( ThreadToResume );
        SuspendThread( ThreadToSuspend );
    }
    else
    {
        /* Yielding to self */
        pthread_mutex_unlock( &xSingleThreadMutex );
    }
}


void vPortDisableInterrupts( void )
{
    xInterruptsEnabled = pdFALSE;
}


void vPortEnableInterrupts( void )
{
    xInterruptsEnabled = pdTRUE;
}


portBASE_TYPE xPortSetInterruptMask( void )
{
    portBASE_TYPE xReturn = xInterruptsEnabled;
    xInterruptsEnabled = pdFALSE;
    return xReturn;
}


void vPortClearInterruptMask( portBASE_TYPE xMask )
{
    xInterruptsEnabled = xMask;
}


/**
 *  Public API used in tasks.c
 */
void vPortForciblyEndThread( void *pxTaskToDelete )
{
    xTaskHandle hTaskToDelete = ( xTaskHandle )pxTaskToDelete;
    pthread_t ThreadToDelete = 0;
    pthread_t ThreadToResume = 0;
    int success;

    pthread_mutex_lock(&xSingleThreadMutex);

    success = LookupThread(hTaskToDelete, &ThreadToDelete);
    (void)success;

    LookupThread(xTaskGetCurrentTaskHandle(), &ThreadToResume);

    if ( pthread_equal(ThreadToResume, ThreadToDelete) )
    {
        /* This is a suicidal thread, need to select a different task to run. */
        vTaskSwitchContext();
        LookupThread(xTaskGetCurrentTaskHandle(), &ThreadToResume);
    }

    if ( !pthread_equal(pthread_self(), ThreadToDelete) )
    {
        /* Cancelling a thread that is not me. */
 
        /* Send a signal to wake the task so that it definitely cancels. */
        pthread_testcancel();
        pthread_cancel( ThreadToDelete );
 
        /* Pthread Clean-up function will note the cancellation. */
        pthread_mutex_unlock( &xSingleThreadMutex );
    }
    else
    {
        /* Resume the other thread. */
        ResumeThread( ThreadToResume );
        /* Pthread Clean-up function will note the cancellation. */
        /* Release the execution. */
        uxCriticalNesting = 0;
        vPortEnableInterrupts();
        pthread_mutex_unlock( &xSingleThreadMutex );
        /* Commit suicide */
        pthread_exit( (void *)1 );
    }
}


/**
 *  Used for traceTASK_CREATE in FreeRTOS.
 */
void vPortAddTaskHandle( void *pxTaskHandle )
{
    int i;
    vPortEnterCritical();
    lLastAddedTaskStackIdx--;
    pxThreads[lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx]].hTask = (xTaskHandle)pxTaskHandle;

    for (i = 0; i < MAX_NUMBER_OF_TASKS; i++)
    {
        if ( pthread_equal(pxThreads[i].Thread, pxThreads[lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx]].Thread))
        {
            if ( pxThreads[i].hTask != pxThreads[ lIndexOfLastAddedTaskStack[lLastAddedTaskStackIdx] ].hTask )
            {
                pxThreads[i].Valid = 0;
                pxThreads[i].hTask = NULL;
                pxThreads[i].uxCriticalNesting = 0;
            }
        }
    }
    vPortExitCritical();
}


void vPortFindTicksPerSecond( void )
{
    /* Needs to be reasonably high for accuracy. */
    unsigned long ulTicksPerSecond = sysconf(_SC_CLK_TCK);
    printf( "Timer Resolution for Run TimeStats is %ld ticks per second.\n", ulTicksPerSecond );
}


unsigned long ulPortGetTimerValue( void )
{
    struct tms xTimes;

    (void)times( &xTimes );
    /* Return the application code times.
     * The timer only increases when the application code is actually running
     * which means that the total execution times should add up to 100%.
     */
    return ( unsigned long ) xTimes.tms_utime;
}


BaseType_t xPortIsInsideInterrupt(void)
{
    return pdFALSE;
}