-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathosapi.c
2496 lines (2132 loc) · 75.2 KB
/
osapi.c
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2018, United States government as represented by the
* administrator of the National Aeronautics Space Administration.
* All rights reserved. This software was created at NASA Glenn
* Research Center pursuant to government contracts.
*
* This is governed by the NASA Open Source Agreement and may be used,
* distributed and modified only according to the terms of that agreement.
*/
/**
* \file osapi.c
* \author joseph.p.hickey@nasa.gov
*
* Purpose: This file contains some of the OS APIs abstraction layer
* implementation for POSIX, specifically for Linux with the 2.6 kernel ( > 2.6.18 )
* with the glibc library. uClibc or other embedded C libraries are not yet tested.
*
* This implementation works with the "shared" OSAL to complete the functionality.
* This contains only the POSIX-specific parts.
*/
/****************************************************************************************
INCLUDE FILES
***************************************************************************************/
#include "os-posix.h"
#include "bsp-impl.h"
#include <sched.h>
#include <posix-macos-time.h>
#include <posix-macos-semaphore2-debug.h>
#include <posix-macos-stubs.h>
#include <posix-macos-pthread.h>
/*
* Defines
*/
#ifndef PTHREAD_STACK_MIN
#define PTHREAD_STACK_MIN (8*1024)
#endif
/*
* Added SEM_VALUE_MAX Define
*/
#ifndef SEM_VALUE_MAX
#define SEM_VALUE_MAX (UINT32_MAX/2)
#endif
/*
* By default use the stdout stream for the console (OS_printf)
*/
#define OSAL_CONSOLE_FILENO STDOUT_FILENO
/*
* By default the console output is always asynchronous
* (equivalent to "OS_UTILITY_TASK_ON" being set)
*
* This option was removed from osconfig.h and now is
* assumed to always be on.
*/
#define OS_CONSOLE_ASYNC true
#define OS_CONSOLE_TASK_PRIORITY OS_UTILITYTASK_PRIORITY
/*
* Global data for the API
*/
/*
* Tables for the properties of objects
*/
/*tasks */
typedef struct
{
pthread_t id;
} OS_impl_task_internal_record_t;
/* queues */
typedef struct
{
mqd_t id;
} OS_impl_queue_internal_record_t;
/* Counting & Binary Semaphores */
typedef struct
{
pthread_mutex_t id;
pthread_cond_t cv;
volatile sig_atomic_t flush_request;
volatile sig_atomic_t current_value;
}OS_impl_binsem_internal_record_t;
typedef struct
{
sem_t id;
}OS_impl_countsem_internal_record_t;
/* Mutexes */
typedef struct
{
pthread_mutex_t id;
}OS_impl_mut_sem_internal_record_t;
/* Console device */
typedef struct
{
bool is_async;
sem_t data_sem;
int out_fd;
}OS_impl_console_internal_record_t;
/* Tables where the OS object information is stored */
OS_impl_task_internal_record_t OS_impl_task_table [OS_MAX_TASKS];
OS_impl_queue_internal_record_t OS_impl_queue_table [OS_MAX_QUEUES];
OS_impl_binsem_internal_record_t OS_impl_bin_sem_table [OS_MAX_BIN_SEMAPHORES];
OS_impl_countsem_internal_record_t OS_impl_count_sem_table [OS_MAX_COUNT_SEMAPHORES];
OS_impl_mut_sem_internal_record_t OS_impl_mut_sem_table [OS_MAX_MUTEXES];
OS_impl_console_internal_record_t OS_impl_console_table [OS_MAX_CONSOLES];
typedef struct
{
pthread_mutex_t mutex;
sigset_t sigmask;
} POSIX_GlobalLock_t;
static POSIX_GlobalLock_t OS_global_task_table_mut;
static POSIX_GlobalLock_t OS_queue_table_mut;
static POSIX_GlobalLock_t OS_bin_sem_table_mut;
static POSIX_GlobalLock_t OS_mut_sem_table_mut;
static POSIX_GlobalLock_t OS_count_sem_table_mut;
static POSIX_GlobalLock_t OS_stream_table_mut;
static POSIX_GlobalLock_t OS_dir_table_mut;
static POSIX_GlobalLock_t OS_timebase_table_mut;
static POSIX_GlobalLock_t OS_module_table_mut;
static POSIX_GlobalLock_t OS_filesys_table_mut;
static POSIX_GlobalLock_t OS_console_mut;
static POSIX_GlobalLock_t * const MUTEX_TABLE[] =
{
[OS_OBJECT_TYPE_UNDEFINED] = NULL,
[OS_OBJECT_TYPE_OS_TASK] = &OS_global_task_table_mut,
[OS_OBJECT_TYPE_OS_QUEUE] = &OS_queue_table_mut,
[OS_OBJECT_TYPE_OS_COUNTSEM] = &OS_count_sem_table_mut,
[OS_OBJECT_TYPE_OS_BINSEM] = &OS_bin_sem_table_mut,
[OS_OBJECT_TYPE_OS_MUTEX] = &OS_mut_sem_table_mut,
[OS_OBJECT_TYPE_OS_STREAM] = &OS_stream_table_mut,
[OS_OBJECT_TYPE_OS_DIR] = &OS_dir_table_mut,
[OS_OBJECT_TYPE_OS_TIMEBASE] = &OS_timebase_table_mut,
[OS_OBJECT_TYPE_OS_MODULE] = &OS_module_table_mut,
[OS_OBJECT_TYPE_OS_FILESYS] = &OS_filesys_table_mut,
[OS_OBJECT_TYPE_OS_CONSOLE] = &OS_console_mut,
};
POSIX_GlobalVars_t POSIX_GlobalVars = { 0 };
enum
{
MUTEX_TABLE_SIZE = (sizeof(MUTEX_TABLE) / sizeof(MUTEX_TABLE[0]))
};
const OS_ErrorTable_Entry_t OS_IMPL_ERROR_NAME_TABLE[] = { { 0, NULL } };
/*
* Local Function Prototypes
*/
static void OS_CompAbsDelayTime( uint32 msecs , struct timespec * tm);
static int OS_PriorityRemap(uint32 InputPri);
/*----------------------------------------------------------------
*
* Function: OS_NoopSigHandler
*
* Purpose: Local helper routine, not part of OSAL API.
* A POSIX signal handler that does nothing
*
*-----------------------------------------------------------------*/
static void OS_NoopSigHandler (int signal)
{
} /* end OS_NoopSigHandler */
/*----------------------------------------------------------------
*
* Function: OS_Lock_Global_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
int32 OS_Lock_Global_Impl(uint32 idtype)
{
POSIX_GlobalLock_t *mut;
sigset_t previous;
if (idtype < MUTEX_TABLE_SIZE)
{
mut = MUTEX_TABLE[idtype];
}
else
{
mut = NULL;
}
if (mut == NULL)
{
return OS_ERROR;
}
if (pthread_sigmask(SIG_SETMASK, &POSIX_GlobalVars.MaximumSigMask, &previous) != 0)
{
return OS_ERROR;
}
if (pthread_mutex_lock(&mut->mutex) != 0)
{
return OS_ERROR;
}
/* Only set values inside the GlobalLock _after_ it is locked */
mut->sigmask = previous;
return OS_SUCCESS;
} /* end OS_Lock_Global_Impl */
/*----------------------------------------------------------------
*
* Function: OS_Unlock_Global_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
int32 OS_Unlock_Global_Impl(uint32 idtype)
{
POSIX_GlobalLock_t *mut;
sigset_t previous;
if (idtype < MUTEX_TABLE_SIZE)
{
mut = MUTEX_TABLE[idtype];
}
else
{
mut = NULL;
}
if (mut == NULL)
{
return OS_ERROR;
}
/* Only get values inside the GlobalLock _before_ it is unlocked */
previous = mut->sigmask;
if (pthread_mutex_unlock(&mut->mutex) != 0)
{
return OS_ERROR;
}
pthread_sigmask(SIG_SETMASK, &previous, NULL);
return OS_SUCCESS;
} /* end OS_Unlock_Global_Impl */
/*---------------------------------------------------------------------------------------
Name: OS_API_Init
Purpose: Initialize the tables that the OS API uses to keep track of information
about objects
returns: OS_SUCCESS or OS_ERROR
---------------------------------------------------------------------------------------*/
int32 OS_API_Impl_Init(uint32 idtype)
{
int ret;
int32 return_code = OS_SUCCESS;
pthread_mutexattr_t mutex_attr;
do
{
/* Initialize the table mutex for the given idtype */
if (idtype < MUTEX_TABLE_SIZE && MUTEX_TABLE[idtype] != NULL)
{
/*
** initialize the pthread mutex attribute structure with default values
*/
ret = pthread_mutexattr_init(&mutex_attr);
if ( ret != 0 )
{
OS_DEBUG("Error: pthread_mutexattr_init failed: %s\n",strerror(ret));
return_code = OS_ERROR;
break;
}
/*
** Allow the mutex to use priority inheritance
*/
ret = pthread_mutexattr_setprotocol(&mutex_attr,PTHREAD_PRIO_INHERIT) ;
if ( ret != 0 )
{
OS_DEBUG("Error: pthread_mutexattr_setprotocol failed: %s\n",strerror(ret));
return_code = OS_ERROR;
break;
}
/*
** Set the mutex type to RECURSIVE so a thread can do nested locks
** TBD - not sure if this is really desired, but keep it for now.
*/
ret = pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE);
if ( ret != 0 )
{
OS_DEBUG("Error: pthread_mutexattr_settype failed: %s\n",strerror(ret));
return_code = OS_ERROR;
break;
}
ret = pthread_mutex_init(&MUTEX_TABLE[idtype]->mutex, &mutex_attr);
if ( ret != 0 )
{
OS_DEBUG("Error: pthread_mutex_init failed: %s\n",strerror(ret));
return_code = OS_ERROR;
break;
}
}
switch(idtype)
{
case OS_OBJECT_TYPE_OS_TASK:
return_code = OS_Posix_TaskAPI_Impl_Init();
break;
case OS_OBJECT_TYPE_OS_QUEUE:
return_code = OS_Posix_QueueAPI_Impl_Init();
break;
case OS_OBJECT_TYPE_OS_BINSEM:
return_code = OS_Posix_BinSemAPI_Impl_Init();
break;
case OS_OBJECT_TYPE_OS_COUNTSEM:
return_code = OS_Posix_CountSemAPI_Impl_Init();
break;
case OS_OBJECT_TYPE_OS_MUTEX:
return_code = OS_Posix_MutexAPI_Impl_Init();
break;
case OS_OBJECT_TYPE_OS_MODULE:
return_code = OS_Posix_ModuleAPI_Impl_Init();
break;
case OS_OBJECT_TYPE_OS_TIMEBASE:
return_code = OS_Posix_TimeBaseAPI_Impl_Init();
break;
case OS_OBJECT_TYPE_OS_STREAM:
return_code = OS_Posix_StreamAPI_Impl_Init();
break;
case OS_OBJECT_TYPE_OS_DIR:
return_code = OS_Posix_DirAPI_Impl_Init();
break;
case OS_OBJECT_TYPE_OS_FILESYS:
return_code = OS_Posix_FileSysAPI_Impl_Init();
break;
default:
break;
}
}
while (0);
return(return_code);
} /* end OS_API_Impl_Init */
/*----------------------------------------------------------------
*
* Function: OS_IdleLoop_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
void OS_IdleLoop_Impl()
{
/*
* Unblock signals and wait for something to occur
*
* Note - "NormalSigMask" was calculated during task init to be the original signal mask
* of the process PLUS all "RT" signals. The RT signals are used by timers, so we want
* to keep them masked here (this is different than the original POSIX impl). The
* timebase objects have a dedicated thread that will be doing "sigwait" on those.
*/
sigsuspend(&POSIX_GlobalVars.NormalSigMask);
} /* end OS_IdleLoop_Impl */
/*----------------------------------------------------------------
*
* Function: OS_ApplicationShutdown_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
void OS_ApplicationShutdown_Impl()
{
/*
* Raise a signal that is unblocked in OS_IdleLoop(),
* which should break it out of the sigsuspend() call.
*/
kill(getpid(), SIGHUP);
} /* end OS_ApplicationShutdown_Impl */
/*---------------------------------------------------------------------------------------
Name: OS_PthreadEntry
Purpose: A Simple pthread-compatible entry point that calls the real task function
returns: NULL
NOTES: This wrapper function is only used locally by OS_TaskCreate below
---------------------------------------------------------------------------------------*/
static void *OS_PthreadTaskEntry(void *arg)
{
OS_U32ValueWrapper_t local_arg;
local_arg.opaque_arg = arg;
OS_TaskEntryPoint(local_arg.value); /* Never returns */
return NULL;
}
/*---------------------------------------------------------------------------------------
Name: OS_Posix_GetSchedulerParams
Purpose: Helper function to get the details of the given OS scheduling policy.
Determines if the policy is usable by OSAL - namely, that it provides
enough priority levels to be useful.
returns: true if policy is suitable for use by OSAL
NOTES: Only used locally by task API initialization
---------------------------------------------------------------------------------------*/
static bool OS_Posix_GetSchedulerParams(int sched_policy, POSIX_PriorityLimits_t *PriLim)
{
int ret;
/*
* Set up the local Min/Max priority levels (varies by OS and scheduler policy)
*
* Per POSIX:
* - The sched_get_priority_min/max() returns a number >= 0 on success.
* (-1 indicates an error)
* - Numerically higher values are scheduled before numerically lower values
* - A compliant OS will have a spread of at least 32 between min and max
*/
ret = sched_get_priority_max(sched_policy);
if (ret < 0)
{
OS_DEBUG("Policy %d: Unable to obtain maximum scheduling priority: %s\n", sched_policy, strerror(errno));
return false;
}
PriLim->PriorityMax = ret;
ret = sched_get_priority_min(sched_policy);
if (ret < 0)
{
OS_DEBUG("Policy %d: Unable to obtain minimum scheduling priority: %s\n", sched_policy, strerror(errno));
return false;
}
PriLim->PriorityMin = ret;
/*
* For OSAL, the absolute minimum spread between min and max must be 4.
*
* Although POSIX stipulates 32, we don't necessarily need that many, but we
* also want to confirm that there is an acceptable spread.
*
* - Highest is reserved for the root task
* - Next highest is reserved for OSAL priority=0 task(s)
* - Lowest is reserved for OSAL priority=255 tasks(s)
* - Need at least 1 for everything else.
*/
if ((PriLim->PriorityMax - PriLim->PriorityMin) < 4)
{
OS_DEBUG("Policy %d: Insufficient spread between priority min-max: %d-%d\n",
sched_policy, (int)PriLim->PriorityMin, (int)PriLim->PriorityMax);
return false;
}
/* If we get here, then the sched_policy is potentially valid */
OS_DEBUG("Policy %d: available, min-max: %d-%d\n", sched_policy,
(int)PriLim->PriorityMin, (int)PriLim->PriorityMax);
return true;
} /* end OS_Posix_GetSchedulerParams */
/*
*********************************************************************************
* TASK API
*********************************************************************************
*/
/*---------------------------------------------------------------------------------------
Name: OS_Posix_TaskAPI_Impl_Init
Purpose: Initialize the Posix Task data structures
----------------------------------------------------------------------------------------*/
int32 OS_Posix_TaskAPI_Impl_Init(void)
{
int ret;
int sig;
struct sched_param sched_param;
int sched_policy;
POSIX_PriorityLimits_t sched_fifo_limits;
bool sched_fifo_valid;
POSIX_PriorityLimits_t sched_rr_limits;
bool sched_rr_valid;
/* Initialize Local Tables */
memset(OS_impl_task_table, 0, sizeof(OS_impl_task_table));
/* Clear the "limits" structs otherwise the compiler may warn
* about possibly being used uninitialized (false warning)
*/
memset(&sched_fifo_limits, 0, sizeof(sched_fifo_limits));
memset(&sched_rr_limits, 0, sizeof(sched_rr_limits));
/*
* Create the key used to store OSAL task IDs
*/
ret = pthread_key_create(&POSIX_GlobalVars.ThreadKey, NULL );
if ( ret != 0 )
{
OS_DEBUG("Error creating thread key: %s (%d)\n",strerror(ret),ret);
return OS_ERROR;
}
/*
** Disable Signals to parent thread and therefore all
** child threads create will block all signals
** Note: Timers will not work in the application unless
** threads are spawned in OS_Application_Startup.
*/
sigfillset(&POSIX_GlobalVars.MaximumSigMask);
/*
* Keep these signals unblocked so the process can be interrupted
*/
sigdelset(&POSIX_GlobalVars.MaximumSigMask, SIGINT); /* CTRL+C */
sigdelset(&POSIX_GlobalVars.MaximumSigMask, SIGABRT); /* Abort */
/*
* One should not typically block ANY of the synchronous error
* signals, i.e. SIGSEGV, SIGFPE, SIGILL, SIGBUS
*
* The kernel generates these signals in response to hardware events
* and they get routed to the _specific thread_ that was executing when
* the problem occurred.
*
* While it is technically possible to block these signals, the result is
* undefined, and it makes debugging _REALLY_ hard. If the kernel ever does
* send one it means there really is a major problem, best to listen to it,
* and not ignore it.
*/
sigdelset(&POSIX_GlobalVars.MaximumSigMask, SIGSEGV); /* Segfault */
sigdelset(&POSIX_GlobalVars.MaximumSigMask, SIGILL); /* Illegal instruction */
sigdelset(&POSIX_GlobalVars.MaximumSigMask, SIGBUS); /* Bus Error */
sigdelset(&POSIX_GlobalVars.MaximumSigMask, SIGFPE); /* Floating Point Exception */
/*
* Set the mask and store the original (default) mask in the POSIX_GlobalVars.NormalSigMask
*/
sigprocmask(SIG_SETMASK, &POSIX_GlobalVars.MaximumSigMask, &POSIX_GlobalVars.NormalSigMask);
/*
* Add all "RT" signals into the POSIX_GlobalVars.NormalSigMask
* This will be used for the signal mask of the main thread
* (This way it will end up as the default/original signal mask plus all RT sigs)
*/
for (sig = SIGRTMIN; sig <= SIGRTMAX; ++sig)
{
sigaddset(&POSIX_GlobalVars.NormalSigMask, sig);
}
/*
* SIGHUP is used to wake up the main thread when necessary,
* so make sure it is NOT in the set.
*/
sigdelset(&POSIX_GlobalVars.NormalSigMask, SIGHUP);
/*
** Install noop as the signal handler for SIGUP.
*/
signal(SIGHUP, OS_NoopSigHandler);
/*
** Raise the priority of the current (main) thread so that subsequent
** application initialization will complete. This had previously been
** done by the BSP and but it is moved here.
**
** This will only work if the user owning this process has permission
** to create real time threads. Otherwise, the default priority will
** be retained. Typically this is only the root user, but finer grained
** permission controls are out there. So if it works, great, but if
** a permission denied error is generated, that is OK too - this allows
** easily debugging code as a normal user.
*/
ret = pthread_getschedparam(pthread_self(), &sched_policy, &sched_param);
if (ret == 0)
{
POSIX_GlobalVars.SelectedRtScheduler = sched_policy; /* Fallback/default */
do
{
sched_fifo_valid = OS_Posix_GetSchedulerParams(SCHED_FIFO, &sched_fifo_limits);
sched_rr_valid = OS_Posix_GetSchedulerParams(SCHED_RR, &sched_rr_limits);
/*
* If both policies are valid, choose the best. In general, FIFO is preferred
* since it is simpler.
*
* But, RR is preferred if mapping several OSAL priority levels into the
* same local priority level. For instance, if 2 OSAL tasks are created at priorities
* "2" and "1", both may get mapped to local priority 98, and if using FIFO then the
* task at priority "2" could run indefinitely, never letting priority "1" execute.
*
* This violates the original intent, which would be to have priority "1" preempt
* priority "2" tasks. RR is less bad since it at least guarantees both tasks some
* CPU time,
*/
if (sched_fifo_valid && sched_rr_valid)
{
/*
* If the spread from min->max is greater than what OSAL actually needs,
* then FIFO is the preferred scheduler. Must take into account one extra level
* for the root task.
*/
if ((sched_fifo_limits.PriorityMax - sched_fifo_limits.PriorityMin) > OS_MAX_TASK_PRIORITY)
{
sched_policy = SCHED_FIFO;
POSIX_GlobalVars.PriLimits = sched_fifo_limits;
}
else
{
sched_policy = SCHED_RR;
POSIX_GlobalVars.PriLimits = sched_rr_limits;
}
}
else if (sched_fifo_valid)
{
/* only FIFO is available */
sched_policy = SCHED_FIFO;
POSIX_GlobalVars.PriLimits = sched_fifo_limits;
}
else if (sched_rr_valid)
{
/* only RR is available */
sched_policy = SCHED_RR;
POSIX_GlobalVars.PriLimits = sched_rr_limits;
}
else
{
/* Nothing is valid, use default */
break;
}
/*
* This OSAL POSIX implementation will reserve the absolute highest priority
* for the root thread, which ultimately will just pend in sigsuspend() so
* it will not actually DO anything, except if sent a signal. This way,
* that thread will still be able to preempt a high-priority user thread that
* has gone awry (i.e. using 100% cpu in FIFO mode).
*/
sched_param.sched_priority = POSIX_GlobalVars.PriLimits.PriorityMax;
--POSIX_GlobalVars.PriLimits.PriorityMax;
OS_DEBUG("Selected policy %d for RT tasks, root task = %d\n", sched_policy, (int)sched_param.sched_priority);
/*
* If the spread from min->max is greater than what OSAL actually needs,
* then truncate it at the number of OSAL priorities. This will end up mapping 1:1.
* and leaving the highest priority numbers unused.
*/
if ((POSIX_GlobalVars.PriLimits.PriorityMax - POSIX_GlobalVars.PriLimits.PriorityMin) > OS_MAX_TASK_PRIORITY)
{
POSIX_GlobalVars.PriLimits.PriorityMax = POSIX_GlobalVars.PriLimits.PriorityMin + OS_MAX_TASK_PRIORITY;
}
#ifndef OSAL_DEBUG_DISABLE_TASK_PRIORITIES
ret = pthread_setschedparam(pthread_self(), sched_policy, &sched_param);
if (ret != 0)
{
OS_DEBUG("Could not setschedparam in main thread: %s (%d)\n",strerror(ret),ret);
break;
}
/*
* Set the boolean to indicate that "setschedparam" worked --
* This means that it is also expected to work for future calls.
*/
POSIX_GlobalVars.SelectedRtScheduler = sched_policy;
POSIX_GlobalVars.EnableTaskPriorities = true;
#endif
}
while (0);
}
else
{
OS_DEBUG("Could not getschedparam in main thread: %s (%d)\n",strerror(ret),ret);
}
#if !defined(OSAL_DEBUG_PERMISSIVE_MODE) && !defined(OSAL_DEBUG_DISABLE_TASK_PRIORITIES)
/*
* In strict (non-permissive) mode, if the task priority setting did not work, fail with an error.
* This would be used on a real target where it needs to be ensured that priorities are active
* and the "silent fallback" of debug mode operation is not desired.
*/
if (!POSIX_GlobalVars.EnableTaskPriorities)
{
return OS_ERROR;
}
#endif
return OS_SUCCESS;
} /* end OS_Posix_TaskAPI_Impl_Init */
/*----------------------------------------------------------------
*
* Function: OS_Posix_InternalTaskCreate_Impl
*
* Purpose: Local helper routine, not part of OSAL API.
*
*-----------------------------------------------------------------*/
int32 OS_Posix_InternalTaskCreate_Impl(pthread_t *pthr, uint32 priority, size_t stacksz, PthreadFuncPtr_t entry, void *entry_arg)
{
int return_code = 0;
pthread_attr_t custom_attr;
struct sched_param priority_holder;
/*
** Initialize the pthread_attr structure.
** The structure is used to set the stack and priority
*/
memset(&custom_attr, 0, sizeof(custom_attr));
return_code = pthread_attr_init(&custom_attr);
if(return_code != 0)
{
OS_DEBUG("pthread_attr_init error in OS_TaskCreate: %s\n",strerror(return_code));
return(OS_ERROR);
}
/*
** Test to see if the original main task scheduling priority worked.
** If so, then also set the attributes for this task. Otherwise attributes
** are left at default.
*/
if (POSIX_GlobalVars.EnableTaskPriorities)
{
/*
** Set the scheduling inherit attribute to EXPLICIT
*/
return_code = pthread_attr_setinheritsched(&custom_attr, PTHREAD_EXPLICIT_SCHED);
if ( return_code != 0 )
{
OS_DEBUG("pthread_attr_setinheritsched error in OS_TaskCreate, errno = %s\n",strerror(return_code));
return(OS_ERROR);
}
/*
** Set the Stack Size
*/
if (stacksz > 0)
{
if (stacksz < PTHREAD_STACK_MIN)
{
stacksz = PTHREAD_STACK_MIN;
}
return_code = pthread_attr_setstacksize(&custom_attr, stacksz);
if (return_code != 0)
{
OS_DEBUG("pthread_attr_setstacksize error in OS_TaskCreate: %s\n",strerror(return_code));
return(OS_ERROR);
}
}
/*
** Set the scheduling policy
** The best policy is determined during initialization
*/
return_code = pthread_attr_setschedpolicy(&custom_attr, POSIX_GlobalVars.SelectedRtScheduler);
if (return_code != 0)
{
OS_DEBUG("pthread_attr_setschedpolity error in OS_TaskCreate: %s\n",strerror(return_code));
return(OS_ERROR);
}
/*
** Set priority
*/
return_code = pthread_attr_getschedparam(&custom_attr, &priority_holder);
if (return_code != 0)
{
OS_DEBUG("pthread_attr_getschedparam error in OS_TaskCreate: %s\n",strerror(return_code));
return(OS_ERROR);
}
priority_holder.sched_priority = OS_PriorityRemap(priority);
return_code = pthread_attr_setschedparam(&custom_attr,&priority_holder);
if(return_code != 0)
{
OS_DEBUG("pthread_attr_setschedparam error in OS_TaskCreate: %s\n",strerror(return_code));
return(OS_ERROR);
}
} /* End if user is root */
/*
** Create thread
*/
return_code = pthread_create(pthr, &custom_attr, entry, entry_arg);
if (return_code != 0)
{
OS_DEBUG("pthread_create error in OS_TaskCreate: %s\n",strerror(return_code));
return(OS_ERROR);
}
/*
** Free the resources that are no longer needed
** Since the task is now running - pthread_create() was successful -
** Do not treat anything bad that happens after this point as fatal.
** The task is running, after all - better to leave well enough alone.
*/
return_code = pthread_detach(*pthr);
if (return_code != 0)
{
OS_DEBUG("pthread_detach error in OS_TaskCreate: %s\n",strerror(return_code));
}
return_code = pthread_attr_destroy(&custom_attr);
if (return_code != 0)
{
OS_DEBUG("pthread_attr_destroy error in OS_TaskCreate: %s\n",strerror(return_code));
}
return OS_SUCCESS;
} /* end OS_Posix_InternalTaskCreate_Impl */
/*----------------------------------------------------------------
*
* Function: OS_TaskCreate_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
int32 OS_TaskCreate_Impl (uint32 task_id, uint32 flags)
{
OS_U32ValueWrapper_t arg;
int32 return_code;
arg.opaque_arg = NULL;
arg.value = OS_global_task_table[task_id].active_id;
return_code = OS_Posix_InternalTaskCreate_Impl(
&OS_impl_task_table[task_id].id,
OS_task_table[task_id].priority,
OS_task_table[task_id].stack_size,
OS_PthreadTaskEntry,
arg.opaque_arg);
return return_code;
} /* end OS_TaskCreate_Impl */
/*----------------------------------------------------------------
*
* Function: OS_TaskMatch_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
int32 OS_TaskMatch_Impl(uint32 task_id)
{
if (pthread_equal(pthread_self(), OS_impl_task_table[task_id].id) == 0)
{
return OS_ERROR;
}
return OS_SUCCESS;
} /* end OS_TaskMatch_Impl */
/*----------------------------------------------------------------
*
* Function: OS_TaskDelete_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
int32 OS_TaskDelete_Impl (uint32 task_id)
{
/*
** Try to delete the task
** If this fails, not much recourse - the only potential cause of failure
** to cancel here is that the thread ID is invalid because it already exited itself,
** and if that is true there is nothing wrong - everything is OK to continue normally.
*/
pthread_cancel(OS_impl_task_table[task_id].id);
return OS_SUCCESS;
} /* end OS_TaskDelete_Impl */
/*----------------------------------------------------------------
*
* Function: OS_TaskExit_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
void OS_TaskExit_Impl()
{
pthread_exit(NULL);
} /* end OS_TaskExit_Impl */
/*----------------------------------------------------------------
*
* Function: OS_TaskDelay_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
int32 OS_TaskDelay_Impl(uint32 millisecond)
{
struct timespec sleep_end;
int status;
clock_gettime(CLOCK_MONOTONIC, &sleep_end);
sleep_end.tv_sec += millisecond / 1000;
sleep_end.tv_nsec += 1000000 * (millisecond % 1000);
if (sleep_end.tv_nsec >= 1000000000)
{
sleep_end.tv_nsec -= 1000000000;
++sleep_end.tv_sec;
}
do
{
status = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &sleep_end, NULL);
}
while (status == EINTR);
if (status != 0)
{
return OS_ERROR;
}
else
{
return OS_SUCCESS;
}
} /* end OS_TaskDelay_Impl */
/*----------------------------------------------------------------
*
* Function: OS_TaskSetPriority_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
int32 OS_TaskSetPriority_Impl (uint32 task_id, uint32 new_priority)
{
int os_priority;
int ret;
if (POSIX_GlobalVars.EnableTaskPriorities)
{
/* Change OSAL priority into a priority that will work for this OS */