summaryrefslogtreecommitdiff
path: root/tool/mbed/mbed-sdk/libraries/rtos/rtx/TARGET_CORTEX_A/rt_CMSIS.c
blob: 8b7b1fad4e8ebbad1656aee4f209e91b63dc760f (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
/*----------------------------------------------------------------------------
 *      RL-ARM - RTX
 *----------------------------------------------------------------------------
 *      Name:    rt_CMSIS.c
 *      Purpose: CMSIS RTOS API
 *      Rev.:    V4.60
 *----------------------------------------------------------------------------
 *
 * Copyright (c) 1999-2009 KEIL, 2009-2012 ARM Germany GmbH
 * 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.
 *  - Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  - Neither the name of ARM  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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDERS AND CONTRIBUTORS 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.
 *---------------------------------------------------------------------------*/

#define __CMSIS_GENERIC

#if defined (__CORTEX_M4) || defined (__CORTEX_M4F)
  #include "core_cm4.h"
#elif defined (__CORTEX_M3)
  #include "core_cm3.h"
#elif defined (__CORTEX_M0)
  #include "core_cm0.h"
#elif defined (__CORTEX_A9)
  #include "core_ca9.h"
#else
  #error "Missing __CORTEX_xx definition"
#endif

#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_Task.h"
#include "rt_Event.h"
#include "rt_List.h"
#include "rt_Time.h"
#include "rt_Mutex.h"
#include "rt_Semaphore.h"
#include "rt_Mailbox.h"
#include "rt_MemBox.h"
#include "rt_Memory.h"
#include "rt_HAL_CM.h"

#define os_thread_cb OS_TCB

#include "cmsis_os.h"

#if (osFeature_Signals != 16)
#error Invalid "osFeature_Signals" value!
#endif
#if (osFeature_Semaphore > 65535)
#error Invalid "osFeature_Semaphore" value!
#endif
#if (osFeature_Wait != 0)
#error osWait not supported!
#endif


// ==== Enumeration, structures, defines ====

// Service Calls defines

#if defined (__CC_ARM)          /* ARM Compiler */

#define __NO_RETURN __declspec(noreturn)

#define osEvent_type       osEvent
#define osEvent_ret_status ret
#define osEvent_ret_value  ret
#define osEvent_ret_msg    ret
#define osEvent_ret_mail   ret

#define osCallback_type    osCallback
#define osCallback_ret     ret

#define SVC_0_1(f,t,...)                                                       \
__svc_indirect(0) t  _##f (t(*)());                                            \
                  t     f (void);                                              \
__attribute__((always_inline))                                                 \
static __inline   t __##f (void) {                                             \
  return _##f(f);                                                              \
}

#define SVC_1_1(f,t,t1,...)                                                    \
__svc_indirect(0) t  _##f (t(*)(t1),t1);                                       \
                  t     f (t1 a1);                                             \
__attribute__((always_inline))                                                 \
static __inline   t __##f (t1 a1) {                                            \
  return _##f(f,a1);                                                           \
}

#define SVC_2_1(f,t,t1,t2,...)                                                 \
__svc_indirect(0) t  _##f (t(*)(t1,t2),t1,t2);                                 \
                  t     f (t1 a1, t2 a2);                                      \
__attribute__((always_inline))                                                 \
static __inline   t __##f (t1 a1, t2 a2) {                                     \
  return _##f(f,a1,a2);                                                        \
}

#define SVC_3_1(f,t,t1,t2,t3,...)                                              \
__svc_indirect(0) t  _##f (t(*)(t1,t2,t3),t1,t2,t3);                           \
                  t     f (t1 a1, t2 a2, t3 a3);                               \
__attribute__((always_inline))                                                 \
static __inline   t __##f (t1 a1, t2 a2, t3 a3) {                              \
  return _##f(f,a1,a2,a3);                                                     \
}

#define SVC_4_1(f,t,t1,t2,t3,t4,...)                                           \
__svc_indirect(0) t  _##f (t(*)(t1,t2,t3,t4),t1,t2,t3,t4);                     \
                  t     f (t1 a1, t2 a2, t3 a3, t4 a4);                        \
__attribute__((always_inline))                                                 \
static __inline   t __##f (t1 a1, t2 a2, t3 a3, t4 a4) {                       \
  return _##f(f,a1,a2,a3,a4);                                                  \
}

#define SVC_1_2 SVC_1_1
#define SVC_1_3 SVC_1_1
#define SVC_2_3 SVC_2_1

#elif defined (__GNUC__)        /* GNU Compiler */

#define __NO_RETURN __attribute__((noreturn))

typedef uint32_t __attribute__((vector_size(8)))  ret64;
typedef uint32_t __attribute__((vector_size(16))) ret128;

#define RET_pointer    __r0
#define RET_int32_t    __r0
#define RET_uint32_t   __r0
#define RET_osStatus   __r0
#define RET_osPriority __r0
#define RET_osEvent    {(osStatus)__r0, {(uint32_t)__r1}, {(void *)__r2}}
#define RET_osCallback {(void *)__r0, (void *)__r1}

#if defined (__ARM_PCS_VFP)

#define osEvent_type        void
#define osEvent_ret_status {  __asm ("MOV r0, %0;"      \
                                     : /* no outputs */ \
                                     : "r"(ret.status)  \
                                     : "r0"             \
                                     );                 \
                           }
#define osEvent_ret_value  {  __asm ("MOV r1, %0;"         \
                                     "MOV r0, %1;"         \
                                     :   /* no outputs */  \
                                     :   "r"(ret.value.v), \
                                         "r"(ret.status)   \
                                     : "r0", "r1"          \
                                     );                    \
                           }
#define osEvent_ret_msg    {  __asm ("MOV r2, %0;"                \
                                     "MOV r1, %1;"                \
                                     "MOV r0, %2;"                \
                                     : /* no outputs */           \
                                     :   "r"(ret.def.message_id), \
                                         "r"(ret.value.v),        \
                                         "r"(ret.status)          \
                                     : "r0", "r1" , "r2"          \
                                     );                           \
                           }

#define osEvent_ret_mail   {  __asm ("MOV r2, %0;"             \
                                     "MOV r1, %1;"             \
                                     "MOV r0, %2;"             \
                                     : /* no outputs */        \
                                     :   "r"(ret.def.mail_id), \
                                         "r"(ret.value.v),     \
                                         "r"(ret.status)       \
                                     : "r0", "r1" , "r2"       \
                                     );                        \
                           }

#define osCallback_type     void
#define osCallback_ret     {  __asm ("MOV r1, %0;"      \
                                     "MOV r0, %1;"      \
                                     : /* no outputs */ \
                                     : "r"(ret.arg),    \
                                       "r"(ret.fp)      \
                                     : "r0", "r1"       \
                                     );                 \
                           }

#else /* defined (__ARM_PCS_VFP) */

#define osEvent_type        ret128
#define osEvent_ret_status (ret128){ret.status}
#define osEvent_ret_value  (ret128){ret.status, ret.value.v}
#define osEvent_ret_msg    (ret128){ret.status, ret.value.v, (uint32_t)ret.def.message_id}
#define osEvent_ret_mail   (ret128){ret.status, ret.value.v, (uint32_t)ret.def.mail_id}

#define osCallback_type     ret64
#define osCallback_ret     (ret64) {(uint32_t)ret.fp, (uint32_t)ret.arg}

#endif /* defined (__ARM_PCS_VFP) */

#define SVC_ArgN(n) \
  register int __r##n __asm("r"#n);

#define SVC_ArgR(n,t,a) \
  register t   __r##n __asm("r"#n) = a;

#define SVC_Arg0()                                                             \
  SVC_ArgN(0)                                                                  \
  SVC_ArgN(1)                                                                  \
  SVC_ArgN(2)                                                                  \
  SVC_ArgN(3)

#define SVC_Arg1(t1)                                                           \
  SVC_ArgR(0,t1,a1)                                                            \
  SVC_ArgN(1)                                                                  \
  SVC_ArgN(2)                                                                  \
  SVC_ArgN(3)

#define SVC_Arg2(t1,t2)                                                        \
  SVC_ArgR(0,t1,a1)                                                            \
  SVC_ArgR(1,t2,a2)                                                            \
  SVC_ArgN(2)                                                                  \
  SVC_ArgN(3)

#define SVC_Arg3(t1,t2,t3)                                                     \
  SVC_ArgR(0,t1,a1)                                                            \
  SVC_ArgR(1,t2,a2)                                                            \
  SVC_ArgR(2,t3,a3)                                                            \
  SVC_ArgN(3)

#define SVC_Arg4(t1,t2,t3,t4)                                                  \
  SVC_ArgR(0,t1,a1)                                                            \
  SVC_ArgR(1,t2,a2)                                                            \
  SVC_ArgR(2,t3,a3)                                                            \
  SVC_ArgR(3,t4,a4)

#if (defined (__CORTEX_M0))
#define SVC_Call(f)                                                            \
  __asm volatile                                                                 \
  (                                                                            \
    "ldr r7,="#f"\n\t"                                                         \
    "mov r12,r7\n\t"                                                           \
    "svc 0"                                                                    \
    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)         \
    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)         \
    : "r7", "r12", "lr", "cc"                                                  \
  );
#else
#define SVC_Call(f)                                                            \
  __asm volatile                                                                 \
  (                                                                            \
    "ldr r12,="#f"\n\t"                                                        \
    "svc 0"                                                                    \
    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)         \
    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)         \
    : "r12", "lr", "cc"                                                        \
  );
#endif

#define SVC_0_1(f,t,rv)                                                        \
__attribute__((always_inline))                                                 \
static inline  t __##f (void) {                                                \
  SVC_Arg0();                                                                  \
  SVC_Call(f);                                                                 \
  return (t) rv;                                                               \
}

#define SVC_1_1(f,t,t1,rv)                                                     \
__attribute__((always_inline))                                                 \
static inline  t __##f (t1 a1) {                                               \
  SVC_Arg1(t1);                                                                \
  SVC_Call(f);                                                                 \
  return (t) rv;                                                               \
}

#define SVC_2_1(f,t,t1,t2,rv)                                                  \
__attribute__((always_inline))                                                 \
static inline  t __##f (t1 a1, t2 a2) {                                        \
  SVC_Arg2(t1,t2);                                                             \
  SVC_Call(f);                                                                 \
  return (t) rv;                                                               \
}

#define SVC_3_1(f,t,t1,t2,t3,rv)                                               \
__attribute__((always_inline))                                                 \
static inline  t __##f (t1 a1, t2 a2, t3 a3) {                                 \
  SVC_Arg3(t1,t2,t3);                                                          \
  SVC_Call(f);                                                                 \
  return (t) rv;                                                               \
}

#define SVC_4_1(f,t,t1,t2,t3,t4,rv)                                            \
__attribute__((always_inline))                                                 \
static inline  t __##f (t1 a1, t2 a2, t3 a3, t4 a4) {                          \
  SVC_Arg4(t1,t2,t3,t4);                                                       \
  SVC_Call(f);                                                                 \
  return (t) rv;                                                               \
}

#define SVC_1_2 SVC_1_1
#define SVC_1_3 SVC_1_1
#define SVC_2_3 SVC_2_1

#elif defined (__ICCARM__)      /* IAR Compiler */

#define __NO_RETURN __noreturn

#define RET_osEvent        "=r"(ret.status), "=r"(ret.value), "=r"(ret.def)
#define RET_osCallback     "=r"(ret.fp), "=r"(ret.arg)

#define osEvent_type       osEvent
#define osEvent_ret_status ret
#define osEvent_ret_value  ret
#define osEvent_ret_msg    ret
#define osEvent_ret_mail   ret

#define osCallback_type    uint64_t
#define osCallback_ret     ((uint64_t)ret.fp | ((uint64_t)ret.arg)<<32)

#define SVC_Setup(f)                                                           \
  __asm(                                                                         \
    "mov r12,%0\n"                                                             \
    :: "r"(&f): "r12"                                                          \
  );

#define SVC_Ret3()                                                             \
  __asm(                                                                         \
    "ldr r0,[sp,#0]\n"                                                         \
    "ldr r1,[sp,#4]\n"                                                         \
    "ldr r2,[sp,#8]\n"                                                         \
  );

#define SVC_0_1(f,t,...)                                                       \
t f (void);                                                                    \
_Pragma("swi_number=0") __swi t _##f (void);                                   \
static inline t __##f (void) {                                                 \
  SVC_Setup(f);                                                                \
  return _##f();                                                               \
}

#define SVC_1_1(f,t,t1,...)                                                    \
t f (t1 a1);                                                                   \
_Pragma("swi_number=0") __swi t _##f (t1 a1);                                  \
static inline t __##f (t1 a1) {                                                \
  SVC_Setup(f);                                                                \
  return _##f(a1);                                                             \
}

#define SVC_2_1(f,t,t1,t2,...)                                                 \
t f (t1 a1, t2 a2);                                                            \
_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2);                           \
static inline t __##f (t1 a1, t2 a2) {                                         \
  SVC_Setup(f);                                                                \
  return _##f(a1,a2);                                                          \
}

#define SVC_3_1(f,t,t1,t2,t3,...)                                              \
t f (t1 a1, t2 a2, t3 a3);                                                     \
_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2, t3 a3);                    \
static inline t __##f (t1 a1, t2 a2, t3 a3) {                                  \
  SVC_Setup(f);                                                                \
  return _##f(a1,a2,a3);                                                       \
}

#define SVC_4_1(f,t,t1,t2,t3,t4,...)                                           \
t f (t1 a1, t2 a2, t3 a3, t4 a4);                                              \
_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2, t3 a3, t4 a4);             \
static inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) {                           \
  SVC_Setup(f);                                                                \
  return _##f(a1,a2,a3,a4);                                                    \
}

#define SVC_1_2(f,t,t1,rr)                                                     \
uint64_t f (t1 a1);                                                            \
_Pragma("swi_number=0") __swi uint64_t _##f (t1 a1);                           \
static inline t __##f (t1 a1) {                                                \
  t ret;                                                                       \
  SVC_Setup(f);                                                                \
  _##f(a1);                                                                    \
  __asm("" : rr : :);                                                            \
  return ret;                                                                  \
}

#define SVC_1_3(f,t,t1,rr)                                                     \
t f (t1 a1);                                                                   \
void f##_ (t1 a1) {                                                            \
  f(a1);                                                                       \
  SVC_Ret3();                                                                  \
}                                                                              \
_Pragma("swi_number=0") __swi void _##f (t1 a1);                               \
static inline t __##f (t1 a1) {                                                \
  t ret;                                                                       \
  SVC_Setup(f##_);                                                             \
  _##f(a1);                                                                    \
  __asm("" : rr : :);                                                            \
  return ret;                                                                  \
}

#define SVC_2_3(f,t,t1,t2,rr)                                                  \
t f (t1 a1, t2 a2);                                                            \
void f##_ (t1 a1, t2 a2) {                                                     \
  f(a1,a2);                                                                    \
  SVC_Ret3();                                                                  \
}                                                                              \
_Pragma("swi_number=0") __swi void _##f (t1 a1, t2 a2);                        \
static inline t __##f (t1 a1, t2 a2) {                                         \
  t ret;                                                                       \
  SVC_Setup(f##_);                                                             \
  _##f(a1,a2);                                                                 \
  __asm("" : rr : :);                                                            \
  return ret;                                                                  \
}

#endif


// Callback structure
typedef struct {
  void *fp;             // Function pointer
  void *arg;            // Function argument
} osCallback;


// OS Section definitions
#ifdef OS_SECTIONS_LINK_INFO
extern const uint32_t  os_section_id$$Base;
extern const uint32_t  os_section_id$$Limit;
#endif

// OS Stack Memory for Threads definitions
extern       uint64_t  os_stack_mem[];
extern const uint32_t  os_stack_sz;

// OS Timers external resources
extern const osThreadDef_t   os_thread_def_osTimerThread;
extern       osThreadId      osThreadId_osTimerThread;
extern const osMessageQDef_t os_messageQ_def_osTimerMessageQ;
extern       osMessageQId    osMessageQId_osTimerMessageQ;

extern U32 IRQNestLevel; /* Indicates whether inside an ISR, and the depth of nesting.  0 = not in ISR. */


// ==== Helper Functions ====

/// Convert timeout in millisec to system ticks
static uint32_t rt_ms2tick (uint32_t millisec) {
  uint32_t tick;

  if (millisec == osWaitForever) return 0xFFFF; // Indefinite timeout
  if (millisec > 4000000) return 0xFFFE;        // Max ticks supported

  tick = ((1000 * millisec) + os_clockrate - 1)  / os_clockrate;
  if (tick > 0xFFFE) return 0xFFFE;

  return tick;
}

/// Convert Thread ID to TCB pointer
static P_TCB rt_tid2ptcb (osThreadId thread_id) {
  P_TCB ptcb;

  if (thread_id == NULL) return NULL;

  if ((uint32_t)thread_id & 3) return NULL;

#ifdef OS_SECTIONS_LINK_INFO
  if ((os_section_id$$Base != 0) && (os_section_id$$Limit != 0)) {
    if (thread_id  < (osThreadId)os_section_id$$Base)  return NULL;
    if (thread_id >= (osThreadId)os_section_id$$Limit) return NULL;
  }
#endif

  ptcb = thread_id;

  if (ptcb->cb_type != TCB) return NULL;

  return ptcb;
}

/// Convert ID pointer to Object pointer
static void *rt_id2obj (void *id) {

  if ((uint32_t)id & 3) return NULL;

#ifdef OS_SECTIONS_LINK_INFO
  if ((os_section_id$$Base != 0) && (os_section_id$$Limit != 0)) {
    if (id  < (void *)os_section_id$$Base)  return NULL;
    if (id >= (void *)os_section_id$$Limit) return NULL;
  }
#endif

  return id;
}

// === Helper functions for system call interface ===

static __inline char __get_mode(void) {
    return (char)(__get_CPSR() & 0x1f);
}

static __inline char __exceptional_mode(void) {
    switch(__get_mode()) {
        case MODE_USR:
        case MODE_SYS:
            return 0;
        case MODE_SVC:
            if (IRQNestLevel == 0)
                return 0; /* handling a regular service call */
            else
                return 1; /* handling an ISR in SVC mode */
        default:
            return 1;
    }
}

// ==== Kernel Control ====

uint8_t os_initialized;                         // Kernel Initialized flag
uint8_t os_running;                             // Kernel Running flag

// Kernel Control Service Calls declarations
SVC_0_1(svcKernelInitialize, osStatus, RET_osStatus)
SVC_0_1(svcKernelStart,      osStatus, RET_osStatus)
SVC_0_1(svcKernelRunning,    int32_t,  RET_int32_t)

static void  sysThreadError   (osStatus status);
osThreadId   svcThreadCreate  (const osThreadDef_t *thread_def, void *argument);
osMessageQId svcMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id);

// Kernel Control Service Calls

/// Initialize the RTOS Kernel for creating objects
osStatus svcKernelInitialize (void) {
  int ret;

  if (!os_initialized) {

    // Init Thread Stack Memory (must be 8-byte aligned)
    if ((uint32_t)os_stack_mem & 7) return osErrorNoMemory;
    ret = rt_init_mem(os_stack_mem, os_stack_sz);
    if (ret != 0) return osErrorNoMemory;

    rt_sys_init();                              // RTX System Initialization
  }

  os_tsk.run->prio = 255;                       // Highest priority

  if (!os_initialized) {
    // Create OS Timers resources (Message Queue & Thread)
    osMessageQId_osTimerMessageQ = svcMessageCreate (&os_messageQ_def_osTimerMessageQ, NULL);
    osThreadId_osTimerThread = svcThreadCreate(&os_thread_def_osTimerThread, NULL);
  }

  sysThreadError(osOK);

  os_initialized = 1;

  return osOK;
}

/// Start the RTOS Kernel
osStatus svcKernelStart (void) {

  if (os_running) return osOK;

  rt_tsk_prio(0, 0);                            // Lowest priority
  __set_PSP(os_tsk.run->tsk_stack + 8*4);       // New context
  os_tsk.run = NULL;                            // Force context switch

  rt_sys_start();

  os_running = 1;

  return osOK;
}

/// Check if the RTOS kernel is already started
int32_t svcKernelRunning(void) {
  return os_running;
}

// Kernel Control Public API

/// Initialize the RTOS Kernel for creating objects
osStatus osKernelInitialize (void) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  if (__get_mode() != MODE_USR) {
    return   svcKernelInitialize();
  } else {
    return __svcKernelInitialize();
  }
}

/// Start the RTOS Kernel
osStatus osKernelStart (void) {
  char mode = __get_mode();

  switch(mode) {
    case MODE_USR:
      if (os_flags & 1) return osErrorOS;  // Privileged Thread mode requested from Unprivileged
      break;
    case MODE_SYS:
      if (!(os_flags & 1)) {
        __set_CPS_USR();
      }
      break;
    default:
      return osErrorISR;                   // Not allowed in ISR
  }
  return __svcKernelStart();
}

/// Check if the RTOS kernel is already started
int32_t osKernelRunning(void) {
  if(__get_mode() != MODE_USR) {
    return os_running;
  } else {
    return __svcKernelRunning();
  }
}


// ==== Thread Management ====

/// Set Thread Error (for Create functions which return IDs)
static void sysThreadError (osStatus status) {
  // To Do
}

__NO_RETURN void osThreadExit (void);

// Thread Service Calls declarations
SVC_2_1(svcThreadCreate,      osThreadId, const osThreadDef_t *, void *,     RET_pointer)
SVC_0_1(svcThreadGetId,       osThreadId,                                    RET_pointer)
SVC_1_1(svcThreadTerminate,   osStatus,         osThreadId,                  RET_osStatus)
SVC_0_1(svcThreadYield,       osStatus,                                      RET_osStatus)
SVC_2_1(svcThreadSetPriority, osStatus,         osThreadId,      osPriority, RET_osStatus)
SVC_1_1(svcThreadGetPriority, osPriority,       osThreadId,                  RET_osPriority)

// Thread Service Calls

/// Create a thread and add it to Active Threads and set it to state READY
osThreadId svcThreadCreate (const osThreadDef_t *thread_def, void *argument) {
  P_TCB  ptcb;
  OS_TID tsk;
  void  *stk;

  if ((thread_def == NULL) ||
      (thread_def->pthread == NULL) ||
      (thread_def->tpriority < osPriorityIdle) ||
      (thread_def->tpriority > osPriorityRealtime)) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  if (thread_def->stacksize != 0) {             // Custom stack size
    stk = rt_alloc_mem(                         // Allocate stack
      os_stack_mem,
      thread_def->stacksize
    );
    if (stk == NULL) {
      sysThreadError(osErrorNoMemory);          // Out of memory
      return NULL;
    }
  } else {                                      // Default stack size
    stk = NULL;
  }

  tsk = rt_tsk_create(                          // Create task
    (FUNCP)thread_def->pthread,                 // Task function pointer
    (thread_def->tpriority-osPriorityIdle+1) |  // Task priority
    (thread_def->stacksize << 8),               // Task stack size in bytes
    stk,                                        // Pointer to task's stack
    argument                                    // Argument to the task
  );

  if (tsk == 0) {                               // Invalid task ID
    if (stk != NULL) {
      rt_free_mem(os_stack_mem, stk);           // Free allocated stack
    }
    sysThreadError(osErrorNoMemory);            // Create task failed (Out of memory)
    return NULL;
  }

  ptcb = (P_TCB)os_active_TCB[tsk - 1];         // TCB pointer

  *((uint32_t *)ptcb->tsk_stack + 13) = (uint32_t)osThreadExit;

  return ptcb;
}

/// Return the thread ID of the current running thread
osThreadId svcThreadGetId (void) {
  OS_TID tsk;

  tsk = rt_tsk_self();
  if (tsk == 0) return NULL;
  return (P_TCB)os_active_TCB[tsk - 1];
}

/// Terminate execution of a thread and remove it from ActiveThreads
osStatus svcThreadTerminate (osThreadId thread_id) {
  OS_RESULT res;
  P_TCB     ptcb;
  void     *stk;

  ptcb = rt_tid2ptcb(thread_id);                // Get TCB pointer
  if (ptcb == NULL) return osErrorParameter;

  stk = ptcb->priv_stack ? ptcb->stack : NULL;  // Private stack

  res = rt_tsk_delete(ptcb->task_id);           // Delete task

  if (res == OS_R_NOK) return osErrorResource;  // Delete task failed

  if (stk != NULL) {
    rt_free_mem(os_stack_mem, stk);             // Free private stack
  }

  return osOK;
}

/// Pass control to next thread that is in state READY
osStatus svcThreadYield (void) {
  rt_tsk_pass();                                // Pass control to next task
  return osOK;
}

/// Change priority of an active thread
osStatus svcThreadSetPriority (osThreadId thread_id, osPriority priority) {
  OS_RESULT res;
  P_TCB     ptcb;

  ptcb = rt_tid2ptcb(thread_id);                // Get TCB pointer
  if (ptcb == NULL) return osErrorParameter;

  if ((priority < osPriorityIdle) || (priority > osPriorityRealtime)) {
    return osErrorValue;
  }

  res = rt_tsk_prio(                            // Change task priority
    ptcb->task_id,                              // Task ID
    priority - osPriorityIdle + 1               // New task priority
  );

  if (res == OS_R_NOK) return osErrorResource;  // Change task priority failed

  return osOK;
}

/// Get current priority of an active thread
osPriority svcThreadGetPriority (osThreadId thread_id) {
  P_TCB ptcb;

  ptcb = rt_tid2ptcb(thread_id);                // Get TCB pointer
  if (ptcb == NULL) return osPriorityError;

  return (osPriority)(ptcb->prio - 1 + osPriorityIdle);
}


// Thread Public API

/// Create a thread and add it to Active Threads and set it to state READY
osThreadId osThreadCreate (const osThreadDef_t *thread_def, void *argument) {
  if (__exceptional_mode()) return NULL;           // Not allowed in ISR
  if ((__get_mode() != MODE_USR) && (os_running == 0)) {
    // Privileged and not running
    return   svcThreadCreate(thread_def, argument);
  } else {
    return __svcThreadCreate(thread_def, argument);
  }
}

/// Return the thread ID of the current running thread
osThreadId osThreadGetId (void) {
  if (__exceptional_mode()) return NULL;           // Not allowed in ISR
  return __svcThreadGetId();
}

/// Terminate execution of a thread and remove it from ActiveThreads
osStatus osThreadTerminate (osThreadId thread_id) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcThreadTerminate(thread_id);
}

/// Pass control to next thread that is in state READY
osStatus osThreadYield (void) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcThreadYield();
}

/// Change priority of an active thread
osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcThreadSetPriority(thread_id, priority);
}

/// Get current priority of an active thread
osPriority osThreadGetPriority (osThreadId thread_id) {
  if (__exceptional_mode()) return osPriorityError;// Not allowed in ISR
  return __svcThreadGetPriority(thread_id);
}

/// INTERNAL - Not Public
/// Auto Terminate Thread on exit (used implicitly when thread exists)
__NO_RETURN void osThreadExit (void) {
  __svcThreadTerminate(__svcThreadGetId());
  for (;;);                                     // Should never come here
}

#ifdef __MBED_CMSIS_RTOS_CA9
/// Get current thread state
uint8_t osThreadGetState (osThreadId thread_id) {
  P_TCB ptcb;

  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR

  ptcb = rt_tid2ptcb(thread_id);                // Get TCB pointer
  if (ptcb == NULL) return osErrorParameter;

  return ptcb->state;
}
#endif

// ==== Generic Wait Functions ====

// Generic Wait Service Calls declarations
SVC_1_1(svcDelay,           osStatus, uint32_t, RET_osStatus)
#if osFeature_Wait != 0
SVC_1_3(svcWait,  os_InRegs osEvent,  uint32_t, RET_osEvent)
#endif

// Generic Wait Service Calls

/// Wait for Timeout (Time Delay)
osStatus svcDelay (uint32_t millisec) {
  if (millisec == 0) return osOK;
  rt_dly_wait(rt_ms2tick(millisec));
  return osEventTimeout;
}

/// Wait for Signal, Message, Mail, or Timeout
#if osFeature_Wait != 0
os_InRegs osEvent_type svcWait (uint32_t millisec) {
  osEvent ret;

  if (millisec == 0) {
    ret.status = osOK;
#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
    osEvent_ret_status;
    return;
#else
    return osEvent_ret_status;
#endif
  }

  /* To Do: osEventSignal, osEventMessage, osEventMail */
  rt_dly_wait(rt_ms2tick(millisec));
  ret.status = osEventTimeout;

#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
  osEvent_ret_status;
  return;
#else
  return osEvent_ret_status;
#endif
}
#endif


// Generic Wait API

/// Wait for Timeout (Time Delay)
osStatus osDelay (uint32_t millisec) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcDelay(millisec);
}

/// Wait for Signal, Message, Mail, or Timeout
os_InRegs osEvent osWait (uint32_t millisec) {
  osEvent ret;

#if osFeature_Wait == 0
  ret.status = osErrorOS;
  return ret;
#else
  if (__exceptional_mode()) {                      // Not allowed in ISR
    ret.status = osErrorISR;
    return ret;
  }
  return __svcWait(millisec);
#endif
}


// ==== Timer Management ====

// Timer definitions
#define osTimerInvalid  0
#define osTimerStopped  1
#define osTimerRunning  2

// Timer structures

typedef struct os_timer_cb_ {                   // Timer Control Block
  struct os_timer_cb_ *next;                    // Pointer to next active Timer
  uint8_t             state;                    // Timer State
  uint8_t              type;                    // Timer Type (Periodic/One-shot)
  uint16_t         reserved;                    // Reserved
  uint16_t             tcnt;                    // Timer Delay Count
  uint16_t             icnt;                    // Timer Initial Count
  void                 *arg;                    // Timer Function Argument
  const osTimerDef_t *timer;                    // Pointer to Timer definition
} os_timer_cb;

// Timer variables
os_timer_cb *os_timer_head;                     // Pointer to first active Timer


// Timer Helper Functions

// Insert Timer into the list sorted by time
static void rt_timer_insert (os_timer_cb *pt, uint32_t tcnt) {
  os_timer_cb *p, *prev;

  prev = NULL;
  p = os_timer_head;
  while (p != NULL) {
    if (tcnt < p->tcnt) break;
    tcnt -= p->tcnt;
    prev = p;
    p = p->next;
  }
  pt->next = p;
  pt->tcnt = (uint16_t)tcnt;
  if (p != NULL) {
    p->tcnt -= pt->tcnt;
  }
  if (prev != NULL) {
    prev->next = pt;
  } else {
    os_timer_head = pt;
  }
}

// Remove Timer from the list
static int rt_timer_remove (os_timer_cb *pt) {
  os_timer_cb *p, *prev;

  prev = NULL;
  p = os_timer_head;
  while (p != NULL) {
    if (p == pt) break;
    prev = p;
    p = p->next;
  }
  if (p == NULL) return -1;
  if (prev != NULL) {
    prev->next = pt->next;
  } else {
    os_timer_head = pt->next;
  }
  if (pt->next != NULL) {
    pt->next->tcnt += pt->tcnt;
  }

  return 0;
}


// Timer Service Calls declarations
SVC_3_1(svcTimerCreate,           osTimerId,  const osTimerDef_t *, os_timer_type, void *, RET_pointer)
SVC_2_1(svcTimerStart,            osStatus,         osTimerId,      uint32_t,              RET_osStatus)
SVC_1_1(svcTimerStop,             osStatus,         osTimerId,                             RET_osStatus)
SVC_1_1(svcTimerDelete,           osStatus,         osTimerId,                             RET_osStatus)
SVC_1_2(svcTimerCall,   os_InRegs osCallback,       osTimerId,                             RET_osCallback)

// Timer Management Service Calls

/// Create timer
osTimerId svcTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument) {
  os_timer_cb *pt;

  if ((timer_def == NULL) || (timer_def->ptimer == NULL)) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  pt = timer_def->timer;
  if (pt == NULL) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  if ((type != osTimerOnce) && (type != osTimerPeriodic)) {
    sysThreadError(osErrorValue);
    return NULL;
  }

  if (osThreadId_osTimerThread == NULL) {
    sysThreadError(osErrorResource);
    return NULL;
  }

  if (pt->state != osTimerInvalid){
    sysThreadError(osErrorResource);
    return NULL;
  }

  pt->state = osTimerStopped;
  pt->type  =  (uint8_t)type;
  pt->arg   = argument;
  pt->timer = timer_def;

  return (osTimerId)pt;
}

/// Start or restart timer
osStatus svcTimerStart (osTimerId timer_id, uint32_t millisec) {
  os_timer_cb *pt;
  uint32_t     tcnt;

  pt = rt_id2obj(timer_id);
  if (pt == NULL) return osErrorParameter;

  tcnt = rt_ms2tick(millisec);
  if (tcnt == 0) return osErrorValue;

  switch (pt->state) {
    case osTimerRunning:
      if (rt_timer_remove(pt) != 0) {
        return osErrorResource;
      }
      break;
    case osTimerStopped:
      pt->state = osTimerRunning;
      pt->icnt  = (uint16_t)tcnt;
      break;
    default:
      return osErrorResource;
  }

  rt_timer_insert(pt, tcnt);

  return osOK;
}

/// Stop timer
osStatus svcTimerStop (osTimerId timer_id) {
  os_timer_cb *pt;

  pt = rt_id2obj(timer_id);
  if (pt == NULL) return osErrorParameter;

  if (pt->state != osTimerRunning) return osErrorResource;

  pt->state = osTimerStopped;

  if (rt_timer_remove(pt) != 0) {
    return osErrorResource;
  }

  return osOK;
}

/// Delete timer
osStatus svcTimerDelete (osTimerId timer_id) {
  os_timer_cb *pt;

  pt = rt_id2obj(timer_id);
  if (pt == NULL) return osErrorParameter;

  switch (pt->state) {
    case osTimerRunning:
      rt_timer_remove(pt);
      break;
    case osTimerStopped:
      break;
    default:
      return osErrorResource;
  }

  pt->state = osTimerInvalid;

  return osOK;
}

/// Get timer callback parameters
os_InRegs osCallback_type svcTimerCall (osTimerId timer_id) {
  os_timer_cb *pt;
  osCallback   ret;

  pt = rt_id2obj(timer_id);
  if (pt == NULL) {
    ret.fp  = NULL;
    ret.arg = NULL;
#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
    osCallback_ret;
    return;
#else
    return osCallback_ret;
#endif
  }

  ret.fp  = (void *)pt->timer->ptimer;
  ret.arg = pt->arg;

#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
  osCallback_ret;
  return;
#else
  return osCallback_ret;
#endif
}

static __INLINE osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec);

/// Timer Tick (called each SysTick)
void sysTimerTick (void) {
  os_timer_cb *pt, *p;

  p = os_timer_head;
  if (p == NULL) return;

  p->tcnt--;
  while ((p != NULL) && (p->tcnt == 0)) {
    pt = p;
    p = p->next;
    os_timer_head = p;
    isrMessagePut(osMessageQId_osTimerMessageQ, (uint32_t)pt, 0);
    if (pt->type == osTimerPeriodic) {
      rt_timer_insert(pt, pt->icnt);
    } else {
      pt->state = osTimerStopped;
    }
  }
}


// Timer Management Public API

/// Create timer
osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument) {
  if (__exceptional_mode()) return NULL;           // Not allowed in ISR
  if ((__get_mode() != MODE_USR) && (os_running == 0)) {
    // Privileged and not running
    return   svcTimerCreate(timer_def, type, argument);
  } else {
    return __svcTimerCreate(timer_def, type, argument);
  }
}

/// Start or restart timer
osStatus osTimerStart (osTimerId timer_id, uint32_t millisec) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcTimerStart(timer_id, millisec);
}

/// Stop timer
osStatus osTimerStop (osTimerId timer_id) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcTimerStop(timer_id);
}

/// Delete timer
osStatus osTimerDelete (osTimerId timer_id) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcTimerDelete(timer_id);
}

/// INTERNAL - Not Public
/// Get timer callback parameters (used by OS Timer Thread)
os_InRegs osCallback osTimerCall (osTimerId timer_id) {
  return __svcTimerCall(timer_id);
}


// Timer Thread
__NO_RETURN void osTimerThread (void const *argument) {
  osCallback cb;
  osEvent    evt;

  for (;;) {
    evt = osMessageGet(osMessageQId_osTimerMessageQ, osWaitForever);
    if (evt.status == osEventMessage) {
      cb = osTimerCall(evt.value.p);
      if (cb.fp != NULL) {
        (*(os_ptimer)cb.fp)(cb.arg);
      }
    }
  }
}


// ==== Signal Management ====

// Signal Service Calls declarations
SVC_2_1(svcSignalSet,             int32_t, osThreadId, int32_t,  RET_int32_t)
SVC_2_1(svcSignalClear,           int32_t, osThreadId, int32_t,  RET_int32_t)
SVC_1_1(svcSignalGet,             int32_t, osThreadId,           RET_int32_t)
SVC_2_3(svcSignalWait,  os_InRegs osEvent, int32_t,    uint32_t, RET_osEvent)

// Signal Service Calls

/// Set the specified Signal Flags of an active thread
int32_t svcSignalSet (osThreadId thread_id, int32_t signals) {
  P_TCB   ptcb;
  int32_t sig;

  ptcb = rt_tid2ptcb(thread_id);                // Get TCB pointer
  if (ptcb == NULL) return 0x80000000;

  if (signals & (0xFFFFFFFF << osFeature_Signals)) return 0x80000000;

  sig = ptcb->events;                           // Previous signal flags

  rt_evt_set(signals, ptcb->task_id);           // Set event flags

  return sig;
}

/// Clear the specified Signal Flags of an active thread
int32_t svcSignalClear (osThreadId thread_id, int32_t signals) {
  P_TCB   ptcb;
  int32_t sig;

  ptcb = rt_tid2ptcb(thread_id);                // Get TCB pointer
  if (ptcb == NULL) return 0x80000000;

  if (signals & (0xFFFFFFFF << osFeature_Signals)) return 0x80000000;

  sig = ptcb->events;                           // Previous signal flags

  rt_evt_clr(signals, ptcb->task_id);           // Clear event flags

  return sig;
}

/// Get Signal Flags status of an active thread
int32_t svcSignalGet (osThreadId thread_id) {
  P_TCB ptcb;

  ptcb = rt_tid2ptcb(thread_id);                // Get TCB pointer
  if (ptcb == NULL) return 0x80000000;

  return ptcb->events;                          // Return event flags
}

/// Wait for one or more Signal Flags to become signaled for the current RUNNING thread
os_InRegs osEvent_type svcSignalWait (int32_t signals, uint32_t millisec) {
  OS_RESULT res;
  osEvent   ret;

  if (signals & (0xFFFFFFFF << osFeature_Signals)) {
    ret.status = osErrorValue;
#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
    osEvent_ret_status;
    return;
#else
    return osEvent_ret_status;
#endif
  }

  if (signals != 0) {                           // Wait for all specified signals
    res = rt_evt_wait(signals, rt_ms2tick(millisec), __TRUE);
  } else {                                      // Wait for any signal
    res = rt_evt_wait(0xFFFF,  rt_ms2tick(millisec), __FALSE);
  }

  if (res == OS_R_EVT) {
    ret.status = osEventSignal;
    ret.value.signals = signals ? signals : os_tsk.run->waits;
  } else {
    ret.status = millisec ? osEventTimeout : osOK;
    ret.value.signals = 0;
  }

#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
  osEvent_ret_value;
  return;
#else
  return osEvent_ret_value;
#endif
}


// Signal ISR Calls

/// Set the specified Signal Flags of an active thread
static __INLINE int32_t isrSignalSet (osThreadId thread_id, int32_t signals) {
  P_TCB   ptcb;
  int32_t sig;

  ptcb = rt_tid2ptcb(thread_id);                // Get TCB pointer
  if (ptcb == NULL) return 0x80000000;

  if (signals & (0xFFFFFFFF << osFeature_Signals)) return 0x80000000;

  sig = ptcb->events;                           // Previous signal flags

  isr_evt_set(signals, ptcb->task_id);          // Set event flags

  return sig;
}


// Signal Public API

/// Set the specified Signal Flags of an active thread
int32_t osSignalSet (osThreadId thread_id, int32_t signals) {
  if (__exceptional_mode()) {                      // in ISR
    return   isrSignalSet(thread_id, signals);
  } else {                                      // in Thread
    return __svcSignalSet(thread_id, signals);
  }
}

/// Clear the specified Signal Flags of an active thread
int32_t osSignalClear (osThreadId thread_id, int32_t signals) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcSignalClear(thread_id, signals);
}

/// Get Signal Flags status of an active thread
int32_t osSignalGet (osThreadId thread_id) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcSignalGet(thread_id);
}

/// Wait for one or more Signal Flags to become signaled for the current RUNNING thread
os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec) {
  osEvent ret;

  if (__exceptional_mode()) {                      // Not allowed in ISR
    ret.status = osErrorISR;
    return ret;
  }
  return __svcSignalWait(signals, millisec);
}


// ==== Mutex Management ====

// Mutex Service Calls declarations
SVC_1_1(svcMutexCreate,  osMutexId, const osMutexDef_t *,           RET_pointer)
SVC_2_1(svcMutexWait,    osStatus,        osMutexId,      uint32_t, RET_osStatus)
SVC_1_1(svcMutexRelease, osStatus,        osMutexId,                RET_osStatus)
SVC_1_1(svcMutexDelete,  osStatus,        osMutexId,                RET_osStatus)

// Mutex Service Calls

/// Create and Initialize a Mutex object
osMutexId svcMutexCreate (const osMutexDef_t *mutex_def) {
  OS_ID mut;

  if (mutex_def == NULL) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  mut = mutex_def->mutex;
  if (mut == NULL) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  if (((P_MUCB)mut)->cb_type != 0) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  rt_mut_init(mut);                             // Initialize Mutex

  return mut;
}

/// Wait until a Mutex becomes available
osStatus svcMutexWait (osMutexId mutex_id, uint32_t millisec) {
  OS_ID     mut;
  OS_RESULT res;

  mut = rt_id2obj(mutex_id);
  if (mut == NULL) return osErrorParameter;

  if (((P_MUCB)mut)->cb_type != MUCB) return osErrorParameter;

  res = rt_mut_wait(mut, rt_ms2tick(millisec)); // Wait for Mutex

  if (res == OS_R_TMO) {
    return (millisec ? osErrorTimeoutResource : osErrorResource);
  }

  return osOK;
}

/// Release a Mutex that was obtained with osMutexWait
osStatus svcMutexRelease (osMutexId mutex_id) {
  OS_ID     mut;
  OS_RESULT res;

  mut = rt_id2obj(mutex_id);
  if (mut == NULL) return osErrorParameter;

  if (((P_MUCB)mut)->cb_type != MUCB) return osErrorParameter;

  res = rt_mut_release(mut);                    // Release Mutex

  if (res == OS_R_NOK) return osErrorResource;  // Thread not owner or Zero Counter

  return osOK;
}

/// Delete a Mutex that was created by osMutexCreate
osStatus svcMutexDelete (osMutexId mutex_id) {
  OS_ID mut;

  mut = rt_id2obj(mutex_id);
  if (mut == NULL) return osErrorParameter;

  if (((P_MUCB)mut)->cb_type != MUCB) return osErrorParameter;

  rt_mut_delete(mut);                           // Release Mutex

  return osOK;
}


// Mutex Public API

/// Create and Initialize a Mutex object
osMutexId osMutexCreate (const osMutexDef_t *mutex_def) {
  if (__exceptional_mode()) return NULL;           // Not allowed in ISR
  if ((__get_mode() != MODE_USR) && (os_running == 0)) {
    // Privileged and not running
    return    svcMutexCreate(mutex_def);
  } else {
    return __svcMutexCreate(mutex_def);
  }
}

/// Wait until a Mutex becomes available
osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcMutexWait(mutex_id, millisec);
}

/// Release a Mutex that was obtained with osMutexWait
osStatus osMutexRelease (osMutexId mutex_id) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcMutexRelease(mutex_id);
}

/// Delete a Mutex that was created by osMutexCreate
osStatus osMutexDelete (osMutexId mutex_id) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcMutexDelete(mutex_id);
}


// ==== Semaphore Management ====

// Semaphore Service Calls declarations
SVC_2_1(svcSemaphoreCreate,  osSemaphoreId, const osSemaphoreDef_t *,  int32_t, RET_pointer)
SVC_2_1(svcSemaphoreWait,    int32_t,             osSemaphoreId,      uint32_t, RET_int32_t)
SVC_1_1(svcSemaphoreRelease, osStatus,            osSemaphoreId,                RET_osStatus)
SVC_1_1(svcSemaphoreDelete,  osStatus,            osSemaphoreId,                RET_osStatus)

// Semaphore Service Calls

/// Create and Initialize a Semaphore object
osSemaphoreId svcSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count) {
  OS_ID sem;

  if (semaphore_def == NULL) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  sem = semaphore_def->semaphore;
  if (sem == NULL) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  if (((P_SCB)sem)->cb_type != 0) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  if (count > osFeature_Semaphore) {
    sysThreadError(osErrorValue);
    return NULL;
  }

  rt_sem_init(sem, count);                      // Initialize Semaphore

  return sem;
}

/// Wait until a Semaphore becomes available
int32_t svcSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec) {
  OS_ID     sem;
  OS_RESULT res;

  sem = rt_id2obj(semaphore_id);
  if (sem == NULL) return -1;

  if (((P_SCB)sem)->cb_type != SCB) return -1;

  res = rt_sem_wait(sem, rt_ms2tick(millisec)); // Wait for Semaphore

  if (res == OS_R_TMO) return 0;                // Timeout

  return (((P_SCB)sem)->tokens + 1);
}

/// Release a Semaphore
osStatus svcSemaphoreRelease (osSemaphoreId semaphore_id) {
  OS_ID sem;

  sem = rt_id2obj(semaphore_id);
  if (sem == NULL) return osErrorParameter;

  if (((P_SCB)sem)->cb_type != SCB) return osErrorParameter;

  if (((P_SCB)sem)->tokens == osFeature_Semaphore) return osErrorResource;

  rt_sem_send(sem);                             // Release Semaphore

  return osOK;
}

/// Delete a Semaphore that was created by osSemaphoreCreate
osStatus svcSemaphoreDelete (osSemaphoreId semaphore_id) {
  OS_ID sem;

  sem = rt_id2obj(semaphore_id);
  if (sem == NULL) return osErrorParameter;

  if (((P_SCB)sem)->cb_type != SCB) return osErrorParameter;

  rt_sem_delete(sem);                           // Delete Semaphore

  return osOK;
}


// Semaphore ISR Calls

/// Release a Semaphore
static __INLINE osStatus isrSemaphoreRelease (osSemaphoreId semaphore_id) {
  OS_ID sem;

  sem = rt_id2obj(semaphore_id);
  if (sem == NULL) return osErrorParameter;

  if (((P_SCB)sem)->cb_type != SCB) return osErrorParameter;

  if (((P_SCB)sem)->tokens == osFeature_Semaphore) return osErrorResource;

  isr_sem_send(sem);                            // Release Semaphore

  return osOK;
}


// Semaphore Public API

/// Create and Initialize a Semaphore object
osSemaphoreId osSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count) {
  if (__exceptional_mode()) return NULL;           // Not allowed in ISR
  if ((__get_mode() != MODE_USR) && (os_running == 0)) {
    // Privileged and not running
    return   svcSemaphoreCreate(semaphore_def, count);
  } else {
    return __svcSemaphoreCreate(semaphore_def, count);
  }
}

/// Wait until a Semaphore becomes available
int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec) {
  if (__exceptional_mode()) return -1;             // Not allowed in ISR
  return __svcSemaphoreWait(semaphore_id, millisec);
}

/// Release a Semaphore
osStatus osSemaphoreRelease (osSemaphoreId semaphore_id) {
  if (__exceptional_mode()) {                      // in ISR
    return   isrSemaphoreRelease(semaphore_id);
  } else {                                      // in Thread
    return __svcSemaphoreRelease(semaphore_id);
  }
}

/// Delete a Semaphore that was created by osSemaphoreCreate
osStatus osSemaphoreDelete (osSemaphoreId semaphore_id) {
  if (__exceptional_mode()) return osErrorISR;     // Not allowed in ISR
  return __svcSemaphoreDelete(semaphore_id);
}


// ==== Memory Management Functions ====

// Memory Management Helper Functions

// Clear Memory Box (Zero init)
static void rt_clr_box (void *box_mem, void *box) {
  uint32_t *p, n;

  if (box) {
    p = box;
    for (n = ((P_BM)box_mem)->blk_size; n; n -= 4) {
      *p++ = 0;
    }
  }
}

// Memory Management Service Calls declarations
SVC_1_1(svcPoolCreate, osPoolId, const osPoolDef_t *,           RET_pointer)
SVC_2_1(sysPoolAlloc,  void *,         osPoolId,      uint32_t, RET_pointer)
SVC_2_1(sysPoolFree,   osStatus,       osPoolId,      void *,   RET_osStatus)

// Memory Management Service & ISR Calls

/// Create and Initialize memory pool
osPoolId svcPoolCreate (const osPoolDef_t *pool_def) {
  uint32_t blk_sz;

  if ((pool_def == NULL) ||
      (pool_def->pool_sz == 0) ||
      (pool_def->item_sz == 0) ||
      (pool_def->pool == NULL)) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  blk_sz = (pool_def->item_sz + 3) & ~3;

  _init_box(pool_def->pool, sizeof(struct OS_BM) + pool_def->pool_sz * blk_sz, blk_sz);

  return pool_def->pool;
}

/// Allocate a memory block from a memory pool
void *sysPoolAlloc (osPoolId pool_id, uint32_t clr) {
  void *ptr;

  if (pool_id == NULL) return NULL;

  ptr = rt_alloc_box(pool_id);
  if (clr) {
    rt_clr_box(pool_id, ptr);
  }

  return ptr;
}

/// Return an allocated memory block back to a specific memory pool
osStatus sysPoolFree (osPoolId pool_id, void *block) {
  int32_t res;

  if (pool_id == NULL) return osErrorParameter;

  res = rt_free_box(pool_id, block);
  if (res != 0) return osErrorValue;

  return osOK;
}


// Memory Management Public API

/// Create and Initialize memory pool
osPoolId osPoolCreate (const osPoolDef_t *pool_def) {
  if (__exceptional_mode()) return NULL;           // Not allowed in ISR
  if ((__get_mode() != MODE_USR) && (os_running == 0)) {
    // Privileged and not running
    return   svcPoolCreate(pool_def);
  } else {
    return __svcPoolCreate(pool_def);
  }
}

/// Allocate a memory block from a memory pool
void *osPoolAlloc (osPoolId pool_id) {
  if (__get_mode() != MODE_USR) {               // in ISR or Privileged
    return   sysPoolAlloc(pool_id, 0);
  } else {                                      // in Thread
    return __sysPoolAlloc(pool_id, 0);
  }
}

/// Allocate a memory block from a memory pool and set memory block to zero
void *osPoolCAlloc (osPoolId pool_id) {
  if (__get_mode() != MODE_USR) {               // in ISR or Privileged
    return   sysPoolAlloc(pool_id, 1);
  } else {                                      // in Thread
    return __sysPoolAlloc(pool_id, 1);
  }
}

/// Return an allocated memory block back to a specific memory pool
osStatus osPoolFree (osPoolId pool_id, void *block) {
  if (__get_mode() != MODE_USR) {               // in ISR or Privileged
    return   sysPoolFree(pool_id, block);
  } else {                                      // in Thread
    return __sysPoolFree(pool_id, block);
  }
}


// ==== Message Queue Management Functions ====

// Message Queue Management Service Calls declarations
SVC_2_1(svcMessageCreate,        osMessageQId, const osMessageQDef_t *, osThreadId,           RET_pointer)
SVC_3_1(svcMessagePut,           osStatus,           osMessageQId,      uint32_t,   uint32_t, RET_osStatus)
SVC_2_3(svcMessageGet, os_InRegs osEvent,            osMessageQId,      uint32_t,             RET_osEvent)

// Message Queue Service Calls

/// Create and Initialize Message Queue
osMessageQId svcMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id) {

  if ((queue_def == NULL) ||
      (queue_def->queue_sz == 0) ||
      (queue_def->pool == NULL)) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  if (((P_MCB)queue_def->pool)->cb_type != 0) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  rt_mbx_init(queue_def->pool, 4*(queue_def->queue_sz + 4));

  return queue_def->pool;
}

/// Put a Message to a Queue
osStatus svcMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) {
  OS_RESULT res;

  if (queue_id == NULL) return osErrorParameter;

  if (((P_MCB)queue_id)->cb_type != MCB) return osErrorParameter;

  res = rt_mbx_send(queue_id, (void *)info, rt_ms2tick(millisec));

  if (res == OS_R_TMO) {
    return (millisec ? osErrorTimeoutResource : osErrorResource);
  }

  return osOK;
}

/// Get a Message or Wait for a Message from a Queue
os_InRegs osEvent_type svcMessageGet (osMessageQId queue_id, uint32_t millisec) {
  OS_RESULT res;
  osEvent   ret;

  if (queue_id == NULL) {
    ret.status = osErrorParameter;
#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
    osEvent_ret_status;
    return;
#else
    return osEvent_ret_status;
#endif
  }

  if (((P_MCB)queue_id)->cb_type != MCB) {
    ret.status = osErrorParameter;
#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
    osEvent_ret_status;
    return;
#else
    return osEvent_ret_status;
#endif
  }

  res = rt_mbx_wait(queue_id, &ret.value.p, rt_ms2tick(millisec));

  if (res == OS_R_TMO) {
    ret.status = millisec ? osEventTimeout : osOK;
#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
    osEvent_ret_value;
    return;
#else
    return osEvent_ret_value;
#endif
  }

  ret.status = osEventMessage;

#if defined (__GNUC__) && defined (__ARM_PCS_VFP)
  osEvent_ret_value;
  return;
#else
  return osEvent_ret_value;
#endif
}


// Message Queue ISR Calls

/// Put a Message to a Queue
static __INLINE osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) {

  if ((queue_id == NULL) || (millisec != 0)) {
    return osErrorParameter;
  }

  if (((P_MCB)queue_id)->cb_type != MCB) return osErrorParameter;

  if (rt_mbx_check(queue_id) == 0) {            // Check if Queue is full
    return osErrorResource;
  }

  isr_mbx_send(queue_id, (void *)info);

  return osOK;
}

/// Get a Message or Wait for a Message from a Queue
static __INLINE os_InRegs osEvent isrMessageGet (osMessageQId queue_id, uint32_t millisec) {
  OS_RESULT res;
  osEvent   ret;

  if ((queue_id == NULL) || (millisec != 0)) {
    ret.status = osErrorParameter;
    return ret;
  }

  if (((P_MCB)queue_id)->cb_type != MCB) {
    ret.status = osErrorParameter;
    return ret;
  }

  res = isr_mbx_receive(queue_id, &ret.value.p);

  if (res != OS_R_MBX) {
    ret.status = osOK;
    return ret;
  }

  ret.status = osEventMessage;

  return ret;
}


// Message Queue Management Public API

/// Create and Initialize Message Queue
osMessageQId osMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id) {
  if (__exceptional_mode()) return NULL;           // Not allowed in ISR
  if ((__get_mode() != MODE_USR) && (os_running == 0)) {
    // Privileged and not running
    return   svcMessageCreate(queue_def, thread_id);
  } else {
    return __svcMessageCreate(queue_def, thread_id);
  }
}

/// Put a Message to a Queue
osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) {
  if (__exceptional_mode()) {                      // in ISR
    return   isrMessagePut(queue_id, info, millisec);
  } else {                                      // in Thread
    return __svcMessagePut(queue_id, info, millisec);
  }
}

/// Get a Message or Wait for a Message from a Queue
os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec) {
  if (__exceptional_mode()) {                      // in ISR
    return   isrMessageGet(queue_id, millisec);
  } else {                                      // in Thread
    return __svcMessageGet(queue_id, millisec);
  }
}


// ==== Mail Queue Management Functions ====

// Mail Queue Management Service Calls declarations
SVC_2_1(svcMailCreate, osMailQId, const osMailQDef_t *, osThreadId,                   RET_pointer)
SVC_4_1(sysMailAlloc,  void *,          osMailQId,      uint32_t, uint32_t, uint32_t, RET_pointer)
SVC_3_1(sysMailFree,   osStatus,        osMailQId,      void *,   uint32_t,           RET_osStatus)

// Mail Queue Management Service & ISR Calls

/// Create and Initialize mail queue
osMailQId svcMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id) {
  uint32_t blk_sz;
  P_MCB    pmcb;
  void    *pool;

  if ((queue_def == NULL) ||
      (queue_def->queue_sz == 0) ||
      (queue_def->item_sz  == 0) ||
      (queue_def->pool == NULL)) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  pmcb = *(((void **)queue_def->pool) + 0);
  pool = *(((void **)queue_def->pool) + 1);

  if ((pool == NULL) || (pmcb == NULL) || (pmcb->cb_type != 0)) {
    sysThreadError(osErrorParameter);
    return NULL;
  }

  blk_sz = (queue_def->item_sz + 3) & ~3;

  _init_box(pool, sizeof(struct OS_BM) + queue_def->queue_sz * blk_sz, blk_sz);

  rt_mbx_init(pmcb, 4*(queue_def->queue_sz + 4));


  return queue_def->pool;
}

/// Allocate a memory block from a mail
void *sysMailAlloc (osMailQId queue_id, uint32_t millisec, uint32_t isr, uint32_t clr) {
  P_MCB pmcb;
  void *pool;
  void *mem;

  if (queue_id == NULL) return NULL;

  pmcb = *(((void **)queue_id) + 0);
  pool = *(((void **)queue_id) + 1);

  if ((pool == NULL) || (pmcb == NULL)) return NULL;

  if (isr && (millisec != 0)) return NULL;

  mem = rt_alloc_box(pool);
  if (clr) {
    rt_clr_box(pool, mem);
  }

  if ((mem == NULL) && (millisec != 0)) {
    // Put Task to sleep when Memory not available
    if (pmcb->p_lnk != NULL) {
      rt_put_prio((P_XCB)pmcb, os_tsk.run);
    } else {
      pmcb->p_lnk = os_tsk.run;
      os_tsk.run->p_lnk = NULL;
      os_tsk.run->p_rlnk = (P_TCB)pmcb;
      // Task is waiting to allocate a message
      pmcb->state = 3;
    }
    rt_block(rt_ms2tick(millisec), WAIT_MBX);
  }

  return mem;
}

/// Free a memory block from a mail
osStatus sysMailFree (osMailQId queue_id, void *mail, uint32_t isr) {
  P_MCB   pmcb;
  P_TCB   ptcb;
  void   *pool;
  void   *mem;
  int32_t res;

  if (queue_id == NULL) return osErrorParameter;

  pmcb = *(((void **)queue_id) + 0);
  pool = *(((void **)queue_id) + 1);

  if ((pmcb == NULL) || (pool == NULL)) return osErrorParameter;

  res = rt_free_box(pool, mail);

  if (res != 0) return osErrorValue;

  if (pmcb->state == 3) {
    // Task is waiting to allocate a message
    if (isr) {
      rt_psq_enq (pmcb, (U32)pool);
      rt_psh_req ();
    } else {
      mem = rt_alloc_box(pool);
      if (mem != NULL) {
        ptcb = rt_get_first((P_XCB)pmcb);
        if (pmcb->p_lnk == NULL) {
          pmcb->state = 0;
        }
        rt_ret_val(ptcb, (U32)mem);
        rt_rmv_dly(ptcb);
        rt_dispatch(ptcb);
      }
    }
  }

  return osOK;
}


// Mail Queue Management Public API

/// Create and Initialize mail queue
osMailQId osMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id) {
  if (__exceptional_mode()) return NULL;           // Not allowed in ISR
  if ((__get_mode() != MODE_USR) && (os_running == 0)) {
    // Privileged and not running
    return   svcMailCreate(queue_def, thread_id);
  } else {
    return __svcMailCreate(queue_def, thread_id);
  }
}

/// Allocate a memory block from a mail
void *osMailAlloc (osMailQId queue_id, uint32_t millisec) {
  if (__exceptional_mode()) {                      // in ISR
    return   sysMailAlloc(queue_id, millisec, 1, 0);
  } else {                                      // in Thread
    return __sysMailAlloc(queue_id, millisec, 0, 0);
  }
}

/// Allocate a memory block from a mail and set memory block to zero
void *osMailCAlloc (osMailQId queue_id, uint32_t millisec) {
  if (__exceptional_mode()) {                      // in ISR
    return   sysMailAlloc(queue_id, millisec, 1, 1);
  } else {                                      // in Thread
    return __sysMailAlloc(queue_id, millisec, 0, 1);
  }
}

/// Free a memory block from a mail
osStatus osMailFree (osMailQId queue_id, void *mail) {
  if (__exceptional_mode()) {                      // in ISR
    return   sysMailFree(queue_id, mail, 1);
  } else {                                      // in Thread
    return __sysMailFree(queue_id, mail, 0);
  }
}

/// Put a mail to a queue
osStatus osMailPut (osMailQId queue_id, void *mail) {
  if (queue_id == NULL) return osErrorParameter;
  if (mail == NULL)     return osErrorValue;
  return osMessagePut(*((void **)queue_id), (uint32_t)mail, 0);
}

#ifdef __CC_ARM
#pragma push
#pragma Ospace
#endif // __arm__
/// Get a mail from a queue
os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec) {
  osEvent ret;

  if (queue_id == NULL) {
    ret.status = osErrorParameter;
    return ret;
  }

  ret = osMessageGet(*((void **)queue_id), millisec);
  if (ret.status == osEventMessage) ret.status = osEventMail;

  return ret;
}
#ifdef __CC_ARM
#pragma pop
#endif // __arm__